import os
import argparse
from encoder import DataEncoder
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
# import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms

from loss import FocalLoss
from retinanet import RetinaNet
from datagen import CoCoDataset
import time
from torch.autograd import Variable
from utils import format_time
import lbtoolbox as lb
from signal import SIGINT, SIGTERM

parser = argparse.ArgumentParser(description='PyTorch RetinaNet Training')
parser.add_argument('--lr', default=0.0005, type=float, help='learning rate')
parser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint')
parser.add_argument('--batch_size', default=2, type=int, help='the training batch size')
args = parser.parse_args()

# assert torch.cuda.is_available(), 'Error: CUDA not found!'
best_loss = float('inf')  # best test loss
start_epoch = 0  # start from epoch 0 or last epoch

# Data
print('==> Preparing data..')
transform = transforms.Compose([
    transforms.ToTensor(),
    # transforms.Normalize((0.485,0.456,0.406), (0.229,0.224,0.225))
])

trainset = CoCoDataset(root='./data/hologram',
                       json_file='./data/annotations/annotations_train.json',
                       train=True, transform=transform, input_size=1024)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size,
                                          shuffle=True, num_workers=1, collate_fn=trainset.collate_fn)

testset = CoCoDataset(root='./data/hologram',
                      json_file='./data/annotations/annotations_val.json',
                      train=False, transform=transform, input_size=1024)
testloader = torch.utils.data.DataLoader(testset, batch_size=args.batch_size,
                                         shuffle=False, num_workers=1, collate_fn=testset.collate_fn)

# Model
net = RetinaNet()
# net.load_state_dict(torch.load('./model/net.pth'))

# args.resume = 1
if args.resume:
    print('==> Resuming from checkpoint..')
    checkpoint = torch.load('./checkpoint/ckpt_interrupted.pth')
    net.load_state_dict(checkpoint['net'])
    best_loss = checkpoint['loss']
    start_epoch = checkpoint['epoch']
if torch.cuda.is_available():
    net = torch.nn.DataParallel(net, device_ids=range(torch.cuda.device_count()))
    net.cuda()

criterion = FocalLoss()
# optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=1e-4)
optimizer = optim.Adam(net.parameters(),lr=args.lr)

# Training
def train(epoch):
    print('\nEpoch: %d' % epoch)
    print('==================================================================')
    net.train()
    iter_p_epoch = int(len(trainloader)/ args.batch_size)
    # net.module.freeze_bn()
    train_loss = 0

    with lb.Uninterrupt(sigs=[SIGINT, SIGTERM], verbose=True) as u:

        for batch_idx, (inputs, loc_targets, cls_targets) in enumerate(trainloader):
            print('Iter: %4d / %d ' % (batch_idx+1, iter_p_epoch))
            t1 = time.time()
            if torch.cuda.is_available():
                inputs = Variable(inputs.cuda())
                loc_targets = Variable(loc_targets.cuda())
                cls_targets = Variable(cls_targets.cuda())
            else:
                inputs = Variable(inputs)
                loc_targets = Variable(loc_targets)
                cls_targets = Variable(cls_targets)
            optimizer.zero_grad()
            loc_preds, cls_preds = net(inputs)
            loss = criterion(loc_preds, loc_targets, cls_preds, cls_targets)
            loss.backward()
            optimizer.step()

            train_loss += loss.data.item()
            t2 = time.time()
            time_elp = t2-t1
            total_time = time_elp*iter_p_epoch
            time_pass = (batch_idx+1)*time_elp
            print('train_loss: %.3f | avg_loss: %.3f' % (loss.data.item(), train_loss/(batch_idx+1)))
            print('Time : %s / %s' % (format_time(time_pass), format_time(total_time)))
            print('\n')

            if u.interrupted:
                print("Interrupted on request!")
                break

    print('Saving..')
    state = {
        'net': net.state_dict(),
        'loss': train_loss,
        'epoch': epoch,
    }
    if not os.path.isdir('checkpoint'):
        os.mkdir('checkpoint')
    torch.save(state, './checkpoint/ckpt_interrupted.pth')
    print('\nSavd')

# Test
def test(epoch):
    print('\nTest==================================================================')
    net.eval()
    test_loss = 0
    for batch_idx, (inputs, loc_targets, cls_targets) in enumerate(testloader):
        print('Batch: %3d/%3d' % (batch_idx, int(len(testloader)/args.batch_size)))
        if torch.cuda.is_available():
            inputs = Variable(inputs.cuda(), volatile=True)
            loc_targets = Variable(loc_targets.cuda())
            cls_targets = Variable(cls_targets.cuda())
        else:
            inputs = Variable(inputs, volatile=True)
            loc_targets = Variable(loc_targets)
            cls_targets = Variable(cls_targets)

        loc_preds, cls_preds = net(inputs)
        loss = criterion(loc_preds, loc_targets, cls_preds, cls_targets)
        test_loss += loss.item()
        print('test_loss: %.3f | avg_loss: %.3f' % (loss.item(), test_loss/(batch_idx+1)))

    # Save checkpoint
    global best_loss
    test_loss /= len(testloader)
    if test_loss < best_loss:
        print('Saving..')
        state = {
            'net': net.state_dict(),
            'loss': test_loss,
            'epoch': epoch,
        }
        if not os.path.isdir('checkpoint'):
            os.mkdir('checkpoint')
        torch.save(state, './checkpoint/ckpt.pth')
        best_loss = test_loss
        print('\nSavd')

def visualization():
    import numpy as np
    from PIL import Image,ImageDraw
    print('visulization\n')
    net.eval()
    test_loss = 0
    for batch_idx, (inputs, loc_targets, cls_targets) in enumerate(trainloader):
        # inputs = Variable(inputs.cuda(), volatile=True)
        # loc_targets = Variable(loc_targets.cuda())
        # cls_targets = Variable(cls_targets.cuda())
        print('Batch: %3d/%3d' % (batch_idx+1, int(len(testloader)/args.batch_size)))
        inputs = Variable(inputs,volatile=True)
        loc_targets = Variable(loc_targets)
        cls_targets = Variable(cls_targets)
        # loc_preds, cls_preds = net(inputs)
        cls_preds = torch.rand([loc_targets.shape[1],256], dtype=torch.float)
        encoder = DataEncoder()
        boxes, labels = encoder.decode(loc_targets.squeeze(), cls_preds, (1024, 1024))
        images = inputs.numpy()[0].transpose(1, 2, 0)
        images = images*255
        image = Image.fromarray(images.astype(np.uint8))
        draw = ImageDraw.Draw(image)
        for bbox in boxes.numpy():
            x,y,x_,y_ = bbox
            draw.rectangle([int(x), int(y), int(x_), int(y_)], width=2, outline='yellow')
        image.show()
        break

for epoch in range(start_epoch, start_epoch+15):
    # visualization()
    train(epoch)
    # test(epoch)


# -*- coding: utf-8 -*-
# Copyright 2018 Elitumdevelop S.A, Ing. Mario Rangel
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).

from odoo import api, fields, models, _
from datetime import date, datetime
from odoo.exceptions import UserError, ValidationError

class TypeDocument(models.Model):
    _name = 'eliterp.type.document'
    _description = 'Tipos de documento'

    @api.multi
    def name_get(self):
        res = []
        for data in self:
            res.append((data.id, "%s [%s]" % (data.name, data.code)))
        return res

    name = fields.Char('Nombre', required=True)
    code = fields.Char('Código', size=2, required=True)
    tax_support_ids = fields.Many2many('eliterp.tax.support',
                                       'relation_type_document_tax_support_ids',
                                       'type_document_id',
                                       'tax_support_id',
                                       string='Sustentos tributarios')
    have_authorization = fields.Boolean('Tiene autorización?', default=False,
                                        help='Marcar si el Tipo de documento tiene Autorización del SRI')
    _sql_constraints = [
        ('code_unique', 'unique (code)', 'El Código del Tipo de documento debe ser único.')
    ]

class TaxSupport(models.Model):
    _name = 'eliterp.tax.support'
    _description = 'Sustento tributario'
    _order = "code asc"

    @api.multi
    def name_get(self):
        res = []
        for data in self:
            res.append((data.id, "%s [%s]" % (data.name, data.code)))
        return res

    name = fields.Char('Nombre', required=True)
    code = fields.Char('Código', size=2, required=True)

    _sql_constraints = [
        ('code_unique', 'unique (code)', 'El Código del Sustento tributario debe ser único.')
    ]

class SriAuthorization(models.Model):
    _name = 'eliterp.sri.authorization'
    _description = 'Autorizaciones del SRI'

    @api.multi
    def set_not_active(self):
        """
        Desactivamos
        """
        self.active = False

    @api.multi
    def name_get(self):
        res = []
        for data in self:
            res.append((data.id, "Documento %s [%s]" % (data.type_document.code, data.authorization)))
        return res

    @api.model
    @api.returns('self', lambda value: value.id)
    def create(self, values):
        result = self.search([
            ('company_id', '=', values['company_id']),
            ('type_document', '=', values['type_document']),
            ('establishment', '=', values['establishment']),
            ('emission_point', '=', values['emission_point']),
            ('active', '=', True)
        ])
        if result:
            MESSAGE = 'Ya existe una Autorización activa para %s-%s.' % (
                values['establishment'], values['emission_point'])
            raise UserError(_(MESSAGE))
        partner_id = self.env.user.company_id.partner_id.id
        if values['company_id'] == partner_id:
            authorization = values['authorization']
            number_next = values['initial_number']
            new_sequence = self.env['ir.sequence'].sudo().create({
                'name': "Secuencia de autorización " + authorization,
                'number_next': number_next,
                'code': authorization,
                'prefix': values['establishment'] + "-" + values['emission_point'] + "-",
                'padding': 9
            })
            values.update({'sequence_id': new_sequence.id})
        return super(SriAuthorization, self).create(values)

    @api.one
    @api.depends('expiration_date')
    def _get_status(self):
        """
        Confirmamos si la Autorización del SRI está vencida
        :return: self
        """
        if not self.expiration_date:
            return
        self.active = date.today() < datetime.strptime(self.expiration_date, '%Y-%m-%d').date()

    @api.multi
    def unlink(self):
        """
        Al borrar Autorización verificar no existan documentos asociados
        """
        invoices = self.env['account.invoice']
        res = invoices.search([('sri_authorization_id', '=', self.id)])
        if res:
            raise ValidationError("Está Autorización está relacionada a un documento.")
        return super(SriAuthorization, self).unlink()

    def _get_company(self):
        return self.env.user.company_id

    def is_valid_number(self, number):
        """
        Verificar si el número de la secuencia es válido
        :param number:
        :return: boolean
        """
        if self.initial_number <= number <= self.final_number:
            return True
        return False

    establishment = fields.Char('No. Establecimiento', size=3, default='001', required=True)
    emission_point = fields.Char('Punto emisión', size=3, default='001', required=True)
    initial_number = fields.Integer('No. inicial', default=1, required=True)
    final_number = fields.Integer('No. final', required=True)
    authorization = fields.Char('No. Autorización', required=True)
    type_document = fields.Many2one('eliterp.type.document', 'Tipo de documento',
                                    domain=[('have_authorization', '=', True)], required=True)
    code = fields.Char(related='type_document.code', string='Código de documento')
    expiration_date = fields.Date('Fecha de expiración', required=True)
    active = fields.Boolean('Activo?', compute='_get_status', store=True)
    company_id = fields.Many2one('res.company', string='Compañía', required=True, default=_get_company)
    sequence_id = fields.Many2one('ir.sequence', 'Secuencia')
    is_electronic = fields.Boolean('Es electrónica?', default=False)  # TODO

    _sql_constraints = [(
        'sri_authorization_unique',
        'CHECK(1=1)',
        'Ya existe una Autorización activa del SRI para estos parámetros.'
    )]

class WayPay(models.Model):
    _name = 'eliterp.way.pay'
    _description = 'Forma de pago'
    _order = "code asc"

    @api.multi
    def name_get(self):
        res = []
        for data in self:
            res.append((data.id, "%s [%s]" % (data.name, data.code)))
        return res

    name = fields.Char('Nombre', required=True)
    code = fields.Char('Código', size=2, required=True)

    _sql_constraints = [
        ('code_unique', 'unique (code)', 'El Código de Forma de pago debe ser único.')
    ]

class ResCompany(models.Model):
    _inherit = 'res.company'

    authorization_ids = fields.One2many(
        'eliterp.sri.authorization',
        'company_id',
        string='Autorizaciones del SRI'
    )

    @api.multi
    def _get_authorisation(self, type_document):
        """
        Obtenemos la autorización del SRI por código de documento
        :param type_document:
        """
        map_type = {
            'out_refund': '04',
            'retention_in_invoice': '07',
            'out_invoice': '18',
        }
        code = map_type[type_document]
        for authorisation in self.authorization_ids:
            if authorisation.active and authorisation.code == code:
                return authorisation
        return False

class AccountInvoice(models.Model):
    _inherit = 'account.invoice'

    ISSUANCE_DOCUMENTS = ['out_invoice', 'out_refund']  # Factura de venta, Nota de crédito en venta...

    @api.onchange('journal_id', 'sri_authorization_id')
    def _onchange_journal_id(self):
        """
        Obtener la el número de la secuencia del documento
        :return: self
        """
        super(AccountInvoice, self)._onchange_journal_id()
        if self.journal_id and self.type in self.ISSUANCE_DOCUMENTS:
            authorisation = self.env.user.company_id._get_authorisation(self.type)
            if authorisation:
                if self.type == 'out_invoice':
                    self.sri_authorization_id = authorisation.id
                elif self.type == 'out_refund':
                    self.sri_authorization_id = authorisation.id
                self.authorization = not self.sri_authorization_id.is_electronic and self.sri_authorization_id.authorization
                number = '{0}'.format(str(self.sri_authorization_id.sequence_id.number_next_actual).zfill(9))
                self.reference = number
        else:
            self.sri_authorization_id = False

    @api.one
    @api.depends('sri_authorization_id', 'reference')
    def _compute_invoice_number(self):
        """
        Calcular el número de documento
        :return: self
        """
        if self.reference:
            self.invoice_number = '{0}-{1}-{2}'.format(
                self.sri_authorization_id.establishment if self.sri_authorization_id else self.establishment,
                self.sri_authorization_id.emission_point if self.sri_authorization_id else self.emission_point,
                self.reference
            )
        else:
            self.invoice_number = False

    @api.onchange('reference')
    def _onchange_reference(self):
        """
        Validar número para rango de Autorización
        """
        if self.reference:
            self.reference = self.reference.zfill(9)
            if not self.sri_authorization_id.is_valid_number(
                    int(self.reference)) and self.type in self.ISSUANCE_DOCUMENTS:
                return {
                    'value': {
                        'reference': ''
                    },
                    'warning': {
                        'title': 'Error',
                        'message': 'Número no coincide con la autorización ingresada.'
                    }
                }

    @api.constrains('authorization')
    def _check_authorization(self):
        """
        Verificar la longitud de la autorización
        10: Documento físico
        35: Documento electrónico, online
        49: Documento electrónico, offline
        """
        if self.type not in ['in_invoice']:
            return
        if self.authorization and len(self.authorization) not in [10, 35, 49]:
            raise ValidationError('Debe ingresar 10, 35 o 49 dígitos según el documento.')

    def _default_way_pay(self):
        """
        Obtenemos forma de pago por defecto 20
        """
        return self.env['eliterp.way.pay'].search([('code', '=', '20')])[0].id

    def _default_tax_support(self):
        """
        Obtenemos sustento tributario por defecto
        """
        type = self._context.get('type')
        if type in ['in_invoice', 'in_refund']:
            return self.env['eliterp.tax.support'].search([])[0].id

    way_pay_id = fields.Many2one('eliterp.way.pay', string='Forma de pago',
                                 default=lambda self: self._default_way_pay())
    sri_authorization_id = fields.Many2one('eliterp.sri.authorization', string='Autorización del SRI', copy=False,
                                           readonly=True,
                                           states={'draft': [('readonly', False)]})
    authorization = fields.Char('No. Autorización', readonly=True,
                                states={'draft': [('readonly', False)]})
    invoice_number = fields.Char('No. Factura', compute='_compute_invoice_number', store=True, readonly=True,
                                 copy=False)
    tax_support_id = fields.Many2one('eliterp.tax.support', string='Sustento tributario',
                                     default=lambda self: self._default_tax_support())
    # Campos para documentos no emitidos por Companía
    establishment = fields.Char('No. Establecimiento', size=3, default='001', readonly=True,
                                states={'draft': [('readonly', False)]})
    emission_point = fields.Char('Punto emisión', size=3, default='001', readonly=True,
                                 states={'draft': [('readonly', False)]})

    _sql_constraints = [(
        'invoice_unique', 'CHECK(1=1)',
        'El No. Factura es único por autorización y empresa.'
    )]

class TributaryCredit(models.Model):
    _name = 'eliterp.tributary.credit'

    _description = 'Crédito tributario'

    @api.depends('name')
    def _compute_year(self):
        """
        Obtenemos el año
        """
        for record in self:
            record.year = record.name.period_id.year_accounting

    name = fields.Many2one('eliterp.lines.account.period', string='Período', domain=[('active', '=', True
                                                                                )])
    month = fields.Integer('Mes', related='name.code', readonly=True, store=True)
    year = fields.Integer('Año contable', compute='_compute_year', store=True)
    amount_iva = fields.Float("Valor IVA", required=True)
    amount_rent = fields.Float("Valor retención", required=True)

    _sql_constraints = [(
        'tributary_credit_unique', 'unique (name)',
        'Ya se registró crédito tributario correspondiente a este período.'
    )]


# -*- coding: utf-8 -*-

import os, time, json ,sys
from pymongo import MongoClient
import re
import logging
import datetime
#
logger = logging.getLogger('sourceDns.webdns.views')

reload(sys)
sys.setdefaultencoding("utf-8")

connection = MongoClient("localhost", 27017)
mydb = connection.Spider  # new a database
comment = mydb.Comment  # new a table
clencomment = mydb.CleanComment
statistics = mydb.Statistics  # new a table

def searchComment(searchkey, sorekey, pageindex, pagesize,lastesttime,isneg):
    logger.info(type(lastesttime))
    logger.info(type(isneg))
    logger.info(lastesttime)
    logger.info(isneg)

    if type(searchkey) == type(None):
        searchkey = ''

    if type(sorekey) == type(None):
        sorekey = 'date'

    if type(pagesize) == type(None):
        pagesize = 10
    else:
        if type(pagesize) == type(u'0'):
           pagesize = int(pagesize, 10)

    if type(pageindex) == type(None):
        pageindex = 1
    else:
       if type(pageindex) == type(u'0'):
          pageindex = int(pageindex,10)

    if type(pageindex) != type(0):
        return 'pageindex type wrong'

    if type(pagesize) != type(0):
        return 'pagesize type wrong'

    skipnumber = pagesize * pageindex

    logger.info(skipnumber)

    daysl = 0
    dbs = []

    if lastesttime == '1':
       daysl = -3
    elif lastesttime == '2':
       daysl = -7
    elif lastesttime == '3':
       daysl = -30
    else:
       searchDic = {}
       if searchkey != '':
         if isneg == '0':
            searchDic['body'] = re.compile(searchkey)
         else:
            searchDic['forsearch'] = re.compile(searchkey)

       if isneg == '0':
         dbs = comment.find(searchDic).sort([('date', -1)]).limit(pagesize).skip(skipnumber)
       elif isneg == '1':
         dbs = clencomment.find(searchDic).sort([('date', -1)]).limit(pagesize).skip(skipnumber)
       elif isneg == '2':
         isneg = True
         searchDic['isneg'] = isneg
         dbs = clencomment.find(searchDic).sort([('date', -1)]).limit(pagesize).skip(skipnumber)
       elif isneg == '3':
         isneg = False
         searchDic['isneg'] = isneg
         dbs = clencomment.find(searchDic).sort([('date', -1)]).limit(pagesize).skip(skipnumber)
       else:
         return 'isneg can not be None'

       logger.info(searchDic)

    if daysl != 0:
       now_time = datetime.datetime.now()
       now_time_string = now_time.strftime('%Y-%m-%d')
       yes_time = now_time + datetime.timedelta(days=daysl)
       yes_time_nyr = yes_time.strftime('%Y-%m-%d')

       searchDic = {}
       if searchkey != '':
           if isneg == '0':
               searchDic['body'] = re.compile(searchkey)
           else:
               searchDic['forsearch'] = re.compile(searchkey)

       if isneg == '0':
         searchDic['date'] = {"$gte": yes_time_nyr, "$lt": now_time_string}
         dbs = comment.find(searchDic).sort([('date', -1)]).limit(pagesize).skip(skipnumber)
       elif isneg == '1' or isneg == '0':
         searchDic['date'] = {"$gte": yes_time_nyr, "$lt": now_time_string}
         dbs = clencomment.find(searchDic).sort([('date', -1)]).limit(pagesize).skip(skipnumber)
       elif isneg == '2':
         isneg = True
         searchDic['isneg'] = isneg
         searchDic['date'] = {"$gte": yes_time_nyr, "$lt": now_time_string}
         dbs = clencomment.find(searchDic).sort([('date', -1)]).limit(pagesize).skip(skipnumber)
       elif isneg == '3':
         isneg = False
         searchDic['isneg'] = isneg
         searchDic['date'] = {"$gte": yes_time_nyr, "$lt": now_time_string}
         dbs = clencomment.find(searchDic).sort([('date', -1)]).limit(pagesize).skip(skipnumber)
       else:
         return 'isneg can not be None'

       logger.info(searchDic)
          #dbs = clencomment.find({'isneg':isneg,'forsearch': re.compile(searchkey),"date": {"$gte": yes_time_nyr, "$lt": now_time_string}}).sort([('date',-1)]).limit(pagesize).skip(skipnumber)

    list = []
    for item in dbs:
        dic = {}
        dic['evaluateId'] = item.get('userReviewId')
        dic['content'] = item.get('body')
        dic['time'] = item.get('date')
        dic['userName'] = item.get('name')
        dic['score'] = item.get('rating')
        dic['title'] = item.get('title')
        dic['isneg'] = item.get('isneg')
        logger.info(dic['title'])
        dic['scondtime'] = item.get('time')

        list.append(dic)

    resultDic = {}
    resultDic['resultData'] = list
    resultDic['code'] = '0000'
    liststring = json.dumps(resultDic)

    return liststring

def createKeyWordList():
    dbs = statistics.find({})
    list = []
    for db in dbs:
        list = db['statistic']

    resultDic = {}
    resultDic['resultData'] = list
    resultDic['code'] = '0000'

    resultString = json.dumps(resultDic)

    return resultString

def getcommentbaseinfo():
    allcomment = comment.find({})
    cleancomment = clencomment.find({})

    allcount = allcomment.count()
    clencount = clencomment.count()

    negcomment = clencomment.find({'isneg':True})
    negcountn = negcomment.count()

    poscountn = clencount - negcountn

    now_time = datetime.datetime.now()
    now_time_string = now_time.strftime('%Y-%m-%d')
    yes_time = now_time + datetime.timedelta(days=-30)
    yes_time_nyr = yes_time.strftime('%Y-%m-%d')

    dbs = clencomment.find({"date": {"$gte": yes_time_nyr, "$lt": now_time_string}})

    returnList = []

    timedic = {}
    for item in dbs:
        time = item.get('date')
        timeitem = timedic.get(time)
        if type(timeitem) == type(None):
            timeitem = {}
            timedic[time] = timeitem
            isneg = item.get('isneg')
            if isneg:
                timeitem['negcount'] = 1
            else:
                timeitem['poscount'] = 1
        else:
            isneg = item.get('isneg')
            if isneg:
                negcount = timeitem.get('negcount')
                if type(negcount) == type(None):
                    negcount = 1
                else:
                    negcount = negcount + 1
                timeitem['negcount'] = negcount
            else:
                poscount = timeitem.get('poscount')
                if type(poscount) == type(None):
                    poscount = 1
                else:
                    poscount = poscount + 1
                timeitem['poscount'] = poscount

    keys = timedic.keys()
    logger.info(keys)
    logger.info(timedic)
    for key in keys:
        countItem = timedic.get(key)
        poscount = countItem.get('poscount')
        negcount = countItem.get('negcount')

        if type(poscount) == type(None):
            poscount = 0

        if type(negcount) == type(None):
            negcount = 0

        itemDic = {}
        itemDic['date'] = key
        itemDic['goodEvt'] = poscount
        itemDic['badEvt'] = negcount

        returnList.append(itemDic)

    returnList.sort(key=lambda k: (k.get('date', 0)), reverse=False)

    returnDic = {}
    returnDic['total'] = allcount
    returnDic['valid'] = clencount
    returnDic['goodEvt'] = poscountn
    returnDic['badEvt'] = negcountn
    returnDic['EvtList'] = returnList

    resultDic = {}
    resultDic['resultData'] = returnDic
    resultDic['code'] = '0000'

    resultString = json.dumps(resultDic)

    return resultString


import torch
import torch.nn as nn

import math

class GRUCell(nn.Module):
    """
    An implementation of GRUCell.

    """
    def __init__(self, input_size, hidden_size, bias=True):
        super(GRUCell, self).__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.bias = bias
        self.x2h = nn.Linear(input_size, 3 * hidden_size, bias=bias)
        self.h2h = nn.Linear(hidden_size, 3 * hidden_size, bias=bias)
        self.reset_parameters()

    def reset_parameters(self):
        std = 1.0 / math.sqrt(self.hidden_size)
        for w in self.parameters():
            w.data.uniform_(-std, std)

    def forward(self, x, hidden):

        gate_x = self.x2h(x)
        gate_h = self.h2h(hidden)

        i_r, i_i, i_n = gate_x.chunk(3, 2)
        h_r, h_i, h_n = gate_h.chunk(3, 2)

        resetgate = torch.sigmoid(i_r + h_r)
        inputgate = torch.sigmoid(i_i + h_i)
        newgate = torch.tanh(i_n + resetgate * h_n)

        hy = (1 - inputgate) * newgate + inputgate * hidden
        return hy

class GRU(nn.Module):
    def __init__(self, input_dim, hidden_dim, bias=True):
        super(GRU, self).__init__()

        self.hidden_dim = hidden_dim
        self.gru_cell = GRUCell(input_dim, hidden_dim, bias)

    def forward(self, x, hn=None, masks=None):
        if hn is None:
            hn = torch.zeros(1, x.size(1), self.hidden_dim).to(device=x.device)

        outs = []
        for seq in range(x.size(0)):
            hn = self.gru_cell(x[seq].unsqueeze(0), hn)
            outs.append(hn)

            if not masks is None:
                hn *= masks[seq].view(-1, 1)

        return torch.cat(outs), hn


from django.shortcuts import render,reverse
from django.http import HttpResponse,HttpResponseRedirect
from .models import Comment,Goods,ShoppingCart,Order
from django.contrib.auth.decorators import login_required
from .forms import CommentForm,GoodsForm,ShoppingCartForm,OrderForm
from django.db import connection
import json
# Create your views here.

def index(request):
    new_goodss = Goods.objects.order_by("-pubDate")[:3]
    hot_goodss = Goods.objects.order_by("-goodssales")[:3]
    # print(new_goodss)
    # return HttpResponse("Hello , world. You're at the Store index.")
    context = {'new_goodss':new_goodss,'hot_goodss':hot_goodss}
    return render(request,'store/index.html',context)

def search(request):
    q = request.GET.get('q')
    error_msg = ''

    if not q:
        goods_type = '请输入关键词'
        return render(request, 'store/shop.html', {'goods_type': goods_type})

    goodss = Goods.objects.filter(goodsName__icontains=q)
    goods_type = '搜索结果'
    context = {'goodss':goodss,'goods_type':goods_type}
    return render(request, 'store/shop.html', context)

def shop(request,type_id):
    if type_id:
        goodss = Goods.objects.filter(goodsType=type_id).order_by('pubDate')
        GOODS_TYPE = {
            '1':'书籍',
            '2':'手机',
            '3':'电脑',
            '4':'衣服',
            '5':'其他',
        }
        goods_type = GOODS_TYPE[type_id]
    else:
        goodss = Goods.objects.order_by('pubDate')
        goods_type = '全部'

    print(goodss)
    context = {'goodss':goodss,'goods_type':goods_type}
    return render(request,'store/shop.html',context)

@login_required
def add_goods(request):
    if request.method != "POST":
        form = GoodsForm()
    else:
        form = GoodsForm(request.POST,files=request.FILES)
        if form.is_valid():
            new_goods = form.save(commit=False)
            new_goods.owner = request.user
            new_goods.goodssales = 0
            new_goods.save()
            return HttpResponseRedirect(reverse('store:mysale'))

    context = {'form':form}
    return render(request,'store/addgoods.html',context)

@login_required
def mysale(request,goods_id):
    try:
        goods = Goods.objects.get(id=goods_id)
        goods.delete()
    except:
        pass
    goodss = Goods.objects.filter(owner=request.user).order_by('pubDate')
    goods_nones = Goods.objects.filter(owner=request.user,goodsNum=0,goodsSelected=0).order_by('pubDate')
    context = {'goodss':goodss,'goods_nones':goods_nones}
    return render(request,'store/mysale.html', context)

def details(request,goods_id):
    goods = Goods.objects.get(id=goods_id)
    comments =  goods.comment_set.order_by('pubDate')
    if request.method != "POST":
        form1 = CommentForm()
        form2 = ShoppingCartForm()
    else:
        form = CommentForm(request.POST)
        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.owner = request.user
            new_comment.goods = goods
            new_comment.save()
            return HttpResponseRedirect(reverse('store:details',args=[goods_id]))
    context = {'goods':goods,'comments':comments,'form1':form1,'form2':form2}
    return render(request,'store/details.html', context)

@login_required
def addCheck(request):
    error_list = {'status':True,'errors':None}
    form = ShoppingCartForm(data=request.POST)
    # print(request.POST['id'])
    goods = Goods.objects.get(id=request.POST['id'])
    number = request.POST['number']
    # print(number)
    # print(goods.goodsNum)
    if form.is_valid():
        added_goodss = ShoppingCart.objects.filter(owner = request.user)
        for added_goods in added_goodss:
            if goods == added_goods.goods:
                added_goods.number += int(number)
                added_goods.subtotal += float(number) * goods.goodsPrice
                goods.goodsNum -= int(number)
                goods.goodsSelected += int(number)
                goods.save()
                added_goods.save()
                error_list['status'] = True
                return HttpResponse(json.dumps(error_list))
        new_goods = form.save(commit=False)
        new_goods.owner = request.user
        new_goods.subtotal = float(number) * goods.goodsPrice
        new_goods.goods = goods
        goods.goodsNum -= int(number)
        goods.goodsSelected += int(number)
        goods.save()
        new_goods.save()
        error_list['status']=True
        return HttpResponse(json.dumps(error_list))
    else:
        error_list['status']=False
        # 将错误信息转换为json格式
        error_list['errors']= form.errors.as_json()
        # 将返回到前台的数据转换为json
        return HttpResponse(json.dumps(error_list))

@login_required
def shoppingcart(request,cart_id):
    try:
        cart = ShoppingCart.objects.get(id=cart_id)
        number = cart.number
        goods = cart.goods
        goods.goodsNum += number
        goods.goodsSelected -= number
        goods.save()
        cart.delete()
    except:
        pass
    form = OrderForm()
    goodss = ShoppingCart.objects.filter(owner=request.user).order_by('id')
    context = {'goodss':goodss,'form':form}
    return render(request,'store/shoppingcart.html', context)

@login_required
def orderCheck(request):
    error_list = {'status':True,'errors':None}
    goodss = request.POST['content']
    # print(goodss)
    content = goodss.split(',')
    content = list(set(content))
    ids = []
    for entry in content:
        tlist = entry.split("*")
        ids.append(tlist[0])
    form = OrderForm(request.POST)
    if form.is_valid():

        new_order = form.save(commit=False)
        new_order.owner = request.user
        new_order.total = float(request.POST['total'])
        new_order.content = request.POST['content']
        new_order.save()

        for goods_id in ids:
            goods = Goods.objects.get(id=int(goods_id))
            carts = goods.shoppingcart_set.filter(owner=request.user)
            for cart in carts:
                number = cart.number
                cart.delete()
                goods.goodssales += number
                goods.goodsSelected -= number
                # print(goods.goodssales)
                # print(goods.goodsSelected)
                goods.save()

        error_list['status']=True
        return HttpResponse(json.dumps(error_list))
    else:
        error_list['status']=False
        # 将错误信息转换为json格式
        error_list['errors']= form.errors.as_json()
        # 将返回到前台的数据转换为json
        return HttpResponse(json.dumps(error_list))

@login_required
def purchased(request,order_id):
    if request.method == "POST":
        tar_order = Order.objects.get(id=order_id)
        tar_content = tar_order.content
        tar_goods = Goods.objects.get(id=request.POST["gid"])
        tconlist = tar_content.split(",")
        for i in range(len(tconlist)):
            tconitemlist = tconlist[i].split("*")
            if tconitemlist[0] == request.POST["gid"]:
                tconlist.pop(i)
                tar_num = int(tconitemlist[1])
                break
        editcontent =  ",".join(tconlist)
        tar_order.total -= tar_goods.goodsPrice * tar_num
        tar_order.content = editcontent
        if tar_order.total == 0.0:
            tar_order.delete()
        else:
            tar_order.save()
        return HttpResponseRedirect(reverse('store:purchased'))
    else:
        orders = Order.objects.filter(owner=request.user).order_by('-id')
        con_orders = []
        for order in orders:
            dic_order = {}
            dic_order["name"] = order.name
            dic_order["telephone"] = order.telephone
            dic_order["address"] = order.address
            dic_order["total"] = order.total
            dic_order["id"] = order.id
            goodss = []
            order_content = order.content
            order_content_list = order_content.split(",")
            for entry in order_content_list:
                tlist = entry.split("*")
                goods_content = {}
                goods = Goods.objects.get(id = int(tlist[0]))
                goods_content["goods"] = goods
                goods_content["num"] = int(tlist[1])
                subtotal = goods.goodsPrice * int(tlist[1])
                goods_content["subtotal"] = subtotal
                goodss.append(goods_content)
            dic_order["goodss"] = goodss
            # print(dic_order)
            con_orders.append(dic_order)
        # print(con_orders)
        context = {'con_orders':con_orders}
        return render(request,'store/purchased.html', context)


import cv2
cap = cv2.VideoCapture(0)
print ("Input even for Color livefeed")
print ("Input odd for Grayscale livefeed")
a = int(raw_input())

while True:
    ret = False
    while ret == False:
        ret,frame = cap.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    if a % 2 == 0:
        frame = cv2.flip(frame,flipCode=1)
        cv2.imshow("frame",frame)
        cv2.waitKey(1)
    else:
        gray = cv2.flip(gray,flipCode=1)
        cv2.imshow("frame",gray)
        cv2.waitKey(1)
cap.release()
cv2.destroyAllWindows()


import requests
import json
from pprint import pprint

url = "https://icanhazdadjoke.com/"

payload = {}
headers = {
  'Accept': 'application/json'
}

response = requests.request("GET", url, headers=headers, data = payload)

print("Here is your dad approved joke:")

responseJson = response.json()

pprint(response.text.encode('utf8'))


import re
import requests

def error(bot, update, error):
    full_text = str(error.__context__.object)
    pattern = r'(\"update_id\":(\d+),)'
    result = re.findall(pattern, full_text)
    url = f'https://api.telegram.org/bot{bot.token}/getUpdates'
    data = {'offset': str(int(result[1][1]) + 1), 'limit': '1'}
    tmp = requests.post(url, data=data)


#    Copyright 2016 Mirantis, Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import pytest

from mos_tests.functions import common
from mos_tests.functions import network_checks

@pytest.fixture
def instances(os_conn, security_group, keypair, network):
    instances = []
    zone = os_conn.nova.availability_zones.find(zoneName="nova")
    compute_host = zone.hosts.keys()[0]
    for i in range(2):
        instance = os_conn.create_server(
            name='server%02d' % i,
            availability_zone='{}:{}'.format(zone.zoneName, compute_host),
            key_name=keypair.name,
            nics=[{'net-id': network['network']['id']}],
            security_groups=[security_group.id],
            wait_for_active=False,
            wait_for_avaliable=False)
        instances.append(instance)
    common.wait(lambda: all(os_conn.is_server_active(x) for x in instances),
                timeout_seconds=2 * 60,
                waiting_for='instances to became to active status')
    common.wait(lambda: all(os_conn.is_server_ssh_ready(x) for x in instances),
                timeout_seconds=2 * 60,
                waiting_for='instances to be ready for ssh')
    return instances

@pytest.mark.testrail_id('842496')
def test_evacuate(devops_env, env, os_conn, instances, keypair):
    """Evacuate instances from failed compute node

    Scenario:
        1. Create net01, net01__subnet:
            neutron net-create net01
            neutron subnet-create net01 192.168.1.0/24 --enable-dhcp \
            --name net01__subnet
        2. Boot instances vm1 and vm2 in net01 on a single compute node:
        3. Destroy a compute node where instances are scheduled
        4. Evacuate instances vm1 and vm2:
            nova evacuate vm1 && nova evacuate vm2
        5. Check that they are rescheduled onto another compute node and
            are in ACTIVE state:
        6. Check that pings between vm1 and vm2 are successful
    """
    compute_host = getattr(instances[0], 'OS-EXT-SRV-ATTR:hypervisor_hostname')
    compute_node = env.find_node_by_fqdn(compute_host)
    devops_node = devops_env.get_node_by_mac(compute_node.data['mac'])
    devops_node.destroy()

    def is_hypervisor_down():
        hypervisor = os_conn.nova.hypervisors.find(
            hypervisor_hostname=compute_host)
        return hypervisor.state == 'down'

    common.wait(
        is_hypervisor_down,
        timeout_seconds=5 * 60,
        waiting_for='hypervisor {0} to be in down state'.format(compute_host))

    for instance in instances:
        os_conn.nova.servers.evacuate(instance)

    def is_instances_migrate():
        for instance in os_conn.nova.servers.list():
            if instance not in instances:
                continue
            if instance.status == 'ERROR':
                raise Exception('Instance {0.name} is in ERROR status\n'
                                '{0.fault[message]}\n'
                                '{0.fault[details]}'.format(instance))
            if not os_conn.server_status_is(instance, 'ACTIVE'):
                return False
            if getattr(instance,
                       'OS-EXT-SRV-ATTR:hypervisor_hostname') == compute_host:
                return False
        return True

    common.wait(is_instances_migrate,
                timeout_seconds=5 * 60,
                waiting_for='instances to migrate to another compute')

    network_checks.check_vm_connectivity(env, os_conn, vm_keypair=keypair)


import pandas as pd
import streamlit as st
from CONST import WARN_INPUT_NOT_FOUND
from functions import *

df = pd.read_csv("./data/foodflix.csv", index_col=0)

st.set_page_config(
    page_title="Foodflix",
    page_icon="./assets/f.jpg",
    layout='wide',
    initial_sidebar_state='expanded'
)

# --------------- #
# Title component #
# --------------- #

st.title("Moteur de recommandation basé sur le contenu")

# ----------------- #
# Sidebar component #
# ----------------- #

st.sidebar.image("./assets/foodlix.png", output_format='PNG')

method = st.sidebar.radio("Sélection de la méthode : ", ("TF-IDF", "CountVectorizer"))

model, X = fit_model(df, method)

user_input = st.sidebar.text_input('Que recherchez vous?').lower().capitalize()
short = st.sidebar.checkbox("Affichage simplifié", value=True)

if user_input and not short:
    allergens_filter = st.sidebar.multiselect(
        'Filtre allergènes', get_list_of_unique_most(df["allergens"])
    )
# -------------- #
# Body component #
# -------------- #

if user_input:
    show_results = True
    empty = st.empty()
    if df["product_name"].to_string().find(user_input) == -1 or df["brands"].to_string().find(user_input) == -1:
        show_results = False

        with empty.beta_container():
            fuzzies = find_fuzzy(user_input, df["product_name"].to_list())

            choices = [fuzzy[0] for fuzzy in fuzzies]
            choices.insert(0, "")
            choices = list(set(choices))
            choices.sort()

            st.warning(WARN_INPUT_NOT_FOUND.format(user_input))
            radio = st.radio("", choices)

            if radio != "":
                user_input = radio
                show_results = True
                empty.empty()

    if show_results:
        found = find_closest(model, X, user_input, method)
        results = get_results(df, found, short)

        for _, el in enumerate(results):

            if short:
                st.subheader(f"{el[0]} - {el[1]}")
                st.markdown(f"*_Nutri-Score_* {el[2]}")
            else:
                st.header(el[0])
                st.subheader(f"Marque : {el[1]}")
                col1, col2 = st.beta_columns(2)
                with col1:
                    st.markdown(f"**_Nutri-Score {el[2]}_**")
                    st.markdown(f"**_Allergènes: {el[3]}_**")
                    for el1 in el[4].split(","):
                        st.text(f"- {el1.strip()}")
                with col2:
                    st.text("Valeurs énergétiques :")
                    st.dataframe(el[5])
            st.markdown("_______")


from flask import Flask, request, jsonify, Response, render_template
import json, os, requests, uuid, sqlite3, datetime, time
from google.cloud import translate
app = Flask(__name__)
#db initialization

@app.route('/')
def render_home():
    return render_template('home.html')
@app.route('/view')
def render_document():
    return render_template('document.html')
@app.route('/editor')
def render_input():
    return render_template('input.html')
@app.route('/log')
def render_versions():
    return render_template('versions.html')
@app.route('/previous')
def render_version():
    return render_template('version.html')

@app.route('/documents/<string:title>/<string:lang>', methods=['GET'])
def get_document(title, lang):
    print('you are trying to get : '+ title)
    conn = sqlite3.connect("res/documents.db")
    cur= conn.cursor()
    #getting content
    sql = "SELECT * FROM wiki WHERE title LIKE ? ORDER BY time DESC LIMIT 1"
    cur.execute(sql, ('%'+title+'%',))
    rows = cur.fetchall()
    articleArray=None
    langTitle=None
    for row in rows:

        articleArray=json.loads(row[3])
        langTitle = json.loads(row[0])[lang]
    conn.close()
    for i in range(len(articleArray)):
        if articleArray[i]["lang"]==lang:
            return jsonify({"title":langTitle, "result":articleArray[i]["text"]})

@app.route('/documents/<string:title>/<string:lang>/raw', methods=['GET'])
def get_raw_document(title, lang):
    print('get raw versions of : '+ title)
    conn = sqlite3.connect("res/documents.db")
    cur= conn.cursor()
    sql = "SELECT * FROM wiki WHERE title LIKE ? ORDER BY time DESC LIMIT 1"
    cur.execute(sql, ('%'+title+'%',))
    rows = cur.fetchall()
    langTitle = json.loads(rows[0][0])[lang]
    result=rows[0][2]
    print(result)
    return jsonify({"title": langTitle, "result":result})

@app.route('/documents/<string:title>', methods=['POST'])
def post_document(title):
    print('you are trying to post : '+ title)
    articlejson = request.get_json()['article']
    #
    langs=["ko","zh","es","en","hi","ar","pt","bn","ru","ja","pa","de"]
    cachejson = []
    print("now start making cache")
    for i in range(len(langs)):
        obj={"lang": langs[i]}
        objtext=""
        for j in range(len(articlejson)):
            objtext += gTranslate(articlejson[j]["text"], langs[i])
            objtext += " "
        obj["text"]=objtext
        cachejson.append(obj)
    cachestr=str(cachejson).replace("'",'"')
    #
    article=str(articlejson)
    article=article.replace("'",'"')
    print(article)
    conn = sqlite3.connect("res/documents.db")
    cur= conn.cursor()
    sql = "INSERT INTO wiki VALUES (?, ?, ?, ?)"
    now = int(time.time())
    translated_title = gTranslateTitle(title)
    cur.execute(sql, (translated_title, now, article, cachestr))
    conn.commit()
    conn.close()
    return 'success posting'

@app.route('/documents/<string:title>/versions', methods=['GET'])
def get_all_version(title):
    print('get every versions of : '+ title)
    conn = sqlite3.connect("res/documents.db")
    cur= conn.cursor()
    sql = "SELECT time FROM wiki WHERE title LIKE ?"
    cur.execute(sql, ('%'+title+'%',))
    rows = cur.fetchall()
    versions=[]
    for row in rows:
        versions.append(row[0])
    return Response(json.dumps(versions),  mimetype='application/json')

@app.route('/documents/<string:title>/versions/<int:version>', methods=['GET'])
def get_raw_version(title, version):
    print('get'+str(version)+ 'th versions of : '+ title)
    conn = sqlite3.connect("res/documents.db")
    cur= conn.cursor()
    sql = "SELECT article FROM wiki WHERE title LIKE ? AND time = ?"
    cur.execute(sql, ('%'+title+'%',version,))
    rows = cur.fetchall()
    result=rows[0][0]
    print(result)
    return jsonify({"result":result})
@app.route('/documents/<string:title>/versions/<int:version>/<string:lang>', methods=['GET'])
def get_rendered_version(title, version, lang):
    print('you are trying to get : '+ title)
    conn = sqlite3.connect("res/documents.db")
    cur= conn.cursor()
    sql = "SELECT * FROM wiki WHERE title LIKE ? AND time = ?"
    cur.execute(sql, ('%'+title+'%',version,))
    rows = cur.fetchall()
    articleArray=None
    langTitle=None
    for row in rows:
        print(row[0])
        articleArray=json.loads(row[2])
        langTitle = json.loads(row[0])[lang]
    print(articleArray)
    for i in range(len(articleArray)):
        if articleArray[i]['lang']==lang:
            articleArray[i] = articleArray[i]['text']
        else :
            articleArray[i] = gTranslate(articleArray[i]['text'], lang)
    result = ' '.join(articleArray)
    print(result)
    conn.close()
    return jsonify({"title":langTitle, "result":result})

def gTranslate(inText, lang):
    text =u'{}'.format(inText)
    translate_client = translate.Client().from_service_account_json('gcpkey.json')
    target = lang
    translation = translate_client.translate(
        text,
        target_language=target)
    return u'{}'.format(translation['translatedText'])

def gTranslateTitle(title):
    allLangTitle={}
    print('gtt')
    langs=['ko','zh','es','en','hi','ar','pt','bn','ru','ja','pa','de']
    for i in range(len(langs)):
        text =u'{}'.format(title)
        translate_client = translate.Client().from_service_account_json('gcpkey.json')
        target = langs[i]
        translation = translate_client.translate(
        text,
        target_language=target)
        allLangTitle[langs[i]] = u'{}'.format(translation['translatedText'])
    output = str(allLangTitle)
    print('allttt: '+output)
    output=output.replace("'",'"')
    return output

if __name__ == '__main__':
    app.debug=False
    app.run(host='0.0.0.0', port=80)


import argparse
import resource
from collections import deque
from estado import Estado

estado_objetivo = [0, 1, 2, 3, 4, 5, 6, 7, 8]
nodo_objetivo = Estado
estado_inicial = list()
tamanio_tablero = 0
lado_tablero = 0

profundidad_maxima_busqueda = 0
tamanio_maximo_frontera = 0

movimientos = list()
costs = set()

def bfs(estado_inicio):
    global tamanio_maximo_frontera, nodo_objetivo, profundidad_maxima_busqueda

    explorado, queue = set(), deque([Estado(estado_inicio, None, None, 0, 0, 0)])

    while queue:
        nodo = queue.popleft()
        explorado.add(nodo.map)

        if nodo.estado == estado_objetivo:
            nodo_objetivo = nodo
            return queue

        vecinos = expandir(nodo)

        for vecino in vecinos:
            if vecino.map not in explorado:
                queue.append(vecino)
                explorado.add(vecino.map)
                if vecino.profundidad > profundidad_maxima_busqueda:
                    profundidad_maxima_busqueda += 1

        if len(queue) > tamanio_maximo_frontera:
            tamanio_maximo_frontera = len(queue)

def expandir(nodo):
    vecinos = list()

    vecinos.append(Estado(movimiento(nodo.estado, 1), nodo, 1, nodo.profundidad + 1, nodo.costo + 1, 0))
    vecinos.append(Estado(movimiento(nodo.estado, 2), nodo, 2, nodo.profundidad + 1, nodo.costo + 1, 0))
    vecinos.append(Estado(movimiento(nodo.estado, 3), nodo, 3, nodo.profundidad + 1, nodo.costo + 1, 0))
    vecinos.append(Estado(movimiento(nodo.estado, 4), nodo, 4, nodo.profundidad + 1, nodo.costo + 1, 0))

    nodes = [vecino for vecino in vecinos if vecino.estado]

    return nodes

def movimiento(estado, posicion):
    nuevo_estado = estado[:]
    indice = nuevo_estado.index(0)

    if posicion == 1:  # Up
        if indice not in range(0, lado_tablero):
            temp = nuevo_estado[indice - lado_tablero]
            nuevo_estado[indice - lado_tablero] = nuevo_estado[indice]
            nuevo_estado[indice] = temp
            return nuevo_estado
        else:
            return None

    if posicion == 2:  # Down
        if indice not in range(tamanio_tablero - lado_tablero, tamanio_tablero):
            temp = nuevo_estado[indice + lado_tablero]
            nuevo_estado[indice + lado_tablero] = nuevo_estado[indice]
            nuevo_estado[indice] = temp
            return nuevo_estado
        else:
            return None

    if posicion == 3:  # Left
        if indice not in range(0, tamanio_tablero, lado_tablero):
            temp = nuevo_estado[indice - 1]
            nuevo_estado[indice - 1] = nuevo_estado[indice]
            nuevo_estado[indice] = temp
            return nuevo_estado
        else:
            return None

    if posicion == 4:  # Right
        if indice not in range(lado_tablero - 1, tamanio_tablero, lado_tablero):
            temp = nuevo_estado[indice + 1]
            nuevo_estado[indice + 1] = nuevo_estado[indice]
            nuevo_estado[indice] = temp
            return nuevo_estado
        else:
            return None

def retroceso():
    nodo_actual = nodo_objetivo

    while estado_inicial != nodo_actual.estado:
        if nodo_actual.movimiento == 1:
            movimiento = 'Up'
        elif nodo_actual.movimiento == 2:
            movimiento = 'Down'
        elif nodo_actual.movimiento == 3:
            movimiento = 'Left'
        else:
            movimiento = 'Right'

        movimientos.insert(0, movimiento)
        nodo_actual = nodo_actual.padre
    return movimientos

def exportar(frontera):
    global movimientos

    movimientos = retroceso()

    print("Camino al objetivo: " + str(movimientos))
    print("Costo del camino: " + str(len(movimientos)))

def leer(configuracion):
    global tamanio_tablero, lado_tablero

    datos = configuracion.split(",")

    for elemento in datos:
        estado_inicial.append(int(elemento))

    tamanio_tablero = len(estado_inicial)
    lado_tablero = int(tamanio_tablero ** 0.5)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('tablero')
    args = parser.parse_args()
    leer(args.tablero)
    frontera = bfs(estado_inicial)
    exportar(frontera)

if __name__ == '__main__':
    main()


from bokeh.layouts import column, widgetbox
from bokeh.plotting import figure, output_file, show, ColumnDataSource, curdoc
from bokeh.models import FuncTickFormatter, FixedTicker, layouts, CustomJS, HoverTool, DatetimeTickFormatter
from bokeh.client import push_session
from bokeh.models.widgets import Dropdown, Button, DataTable, TableColumn
import sys
import argparse
import threading
import socket
import time
import datetime as dt
import os
import re
sys.path.append("/Users/john/Development/CNMAT/CNMAT/libo")
import libo as o
import o_udpreceive as oudpr

lt = 3.5

lock = threading.Lock()

colors = ["red", "green", "blue", "yellow", "cyan", "magenta", "black"]
tools = 'pan,box_zoom,box_select,wheel_zoom,resize,hover,save,reset'
t = {} # typetags as bytes

for s in ['c', 'C', 'u', 'U', 'i', 'I', 'h', 'H', 'f', 'd', 's', 'S', 't']:
    t[s] = int(bytes(s, "utf-8")[0])

class MyPlot:
    q = []
    xkey = None
    ykeys = []
    keys = []
    winsize = 600
    p = None
    ds = None
    def __init__(self, title, winsize, xkey, ykeys):
        self.winsize = winsize
        self.xkey = xkey
        self.ykeys = ykeys
        self.keys = ykeys + [xkey]
        d = {}
        for k in self.keys:
            d[k] = []
        self.ds = ColumnDataSource(d)
        self.p = figure(plot_width = 1200, plot_height = 250, tools = tools, title = title)
        i = 0
        for k in ykeys:
            self.p.line(x = self.xkey, y = k, source = self.ds, color = colors[i % len(colors)],  line_width = lt)
            i = i + 1
        tf = DatetimeTickFormatter()
        tf.hours = ["%Y-%m-%d %H:%M:%S"]
        tf.days = ["%Y-%m-%d %H:%M:%S"]
        tf.months = ["%Y-%m-%d %H:%M:%S"]
        tf.years = ["%Y-%m-%d %H:%M:%S"]
        tf.minutes = ["%Y-%m-%d %H:%M:%S"]
        tf.seconds = ["%Y-%m-%d %H:%M:%S"]
        tf.milliseconds = ["%Y-%m-%d %H:%M:%S"]
        tf.microseconds = ["%Y-%m-%d %H:%M:%S"]
        self.p.xaxis.formatter = tf

    def get_plot(self):
        return self.p

    def append_data(self, bndl_u):
        global lock
        lock.acquire()
        #print("appending " + str(bndl_u))
        self.q.append(o.osc_bundle_u_copy_py(bndl_u))
        lock.release()

    def update(self):
        global lock
        lst = []
        lock.acquire()
        for bndl_u in self.q:
            lst.append(bndl_u)
            #print("append " + str(bndl_u) + " " + str(lst[len(lst) - 1]))
        self.q = []
        lock.release()
        msgdict = {}
        for k in self.keys:
            msgdict[k] = []
        have_error = False
        for i in range(0, len(lst)):#bndl_u in lst:
            bndl_u = lst[i]
            #print("i = " + str(i) + " " + str(bndl_u))
            if have_error == True:
                break
            for k in self.keys:
                if have_error == True:
                    break
                msgar_u = o.osc_bundle_u_lookupAddress(bndl_u, bytes(k, "utf-8"), 1)
                if o.osc_message_array_u_getLen(msgar_u) == 1:
                    msg = o.osc_message_array_u_get(msgar_u, 0)
                    address = str(o.osc_message_u_getAddress(msg), "utf-8")
                    mit = o.osc_message_iterator_u_getIterator(msg)
                    while o.osc_message_iterator_u_hasNext(mit):
                        a = o.osc_message_iterator_u_next(mit)
                        tt = int(o.osc_atom_u_getTypetag(a)[0])
                        if tt == t['c'] or tt == t['C'] or tt == t['u'] or tt == t['U'] or tt == t['i'] or tt == t['I'] or tt == t['h'] or tt == t['H']:
                            msgdict[address].append(o.osc_atom_u_getInt(a))
                        elif tt == t['f'] or tt == t['d']:
                            msgdict[address].append(o.osc_atom_u_getDouble(a))
                        elif tt == t['t']:
                            if o.osc_timetag_timetagToFloat(o.osc_atom_u_getTimetag(a)) < 2208988800:
                                msgdict[address].append(dt.datetime.strptime(str(o.osc_timetag_format(o.osc_timetag_floatToTimetag(2208988800)), "utf-8"), "%Y-%m-%dT%H:%M:%S.%fZ"))
                            else:
                                msgdict[address].append(dt.datetime.strptime(str(o.osc_timetag_format(o.osc_atom_u_getTimetag(a)), "utf-8"), "%Y-%m-%dT%H:%M:%S.%fZ"))
                        else:
                            error("unsupported type: " + str(tt))
                    o.osc_message_iterator_u_destroyIterator(mit)
                else:
                    have_error = True
            #o.osc_bundle_u_free(lst[i])
        if have_error == False:
            self.ds.stream(msgdict, self.winsize)

    def clear(self):
        for k in self.keys:
            self.ds.data[k] = []
        # for i in range(0, len(lst)):
        #     o.osc_bundle_u_free(lst[i])
        #     lst[i] = None

# UDP_IP = "127.0.0.1"
# reset_address = "/reset"
# q = []
# msgdict = {}
# t = {} # typetags as bytes

# independent_var = 'n'

# timedomain_numplots = 0
# timedomain_keys = []
# timedomain_ds = None#ColumnDataSource()#dict(/time = [], /foo = []))
# timedomain_tools = 'pan,box_zoom,box_select,wheel_zoom,resize,hover,save,reset'
# timedomain_plot = figure(plot_width = 1200, plot_height = 500, tools = timedomain_tools)

# timedomain_winsize = 0
# timedomain_updatedict = {}

# text_ds = ColumnDataSource(
#     dict(
#         x = [0],
#         y = [.95],
#         text = []
#     )
# )
# text_plot = figure(plot_width = 800, plot_height = 500, x_range = (0, 1), y_range = (0, 1))
# text_plot.axis.visible = False
# text_plot.grid.visible = False
# text_renderer = text_plot.text('x', 'y', 'text', source = text_ds)

# table_source = ColumnDataSource(data = {'addresses' : [], 'data' : []})
# table = DataTable(source = table_source, columns = [TableColumn(field = "addresses", title = "Address"), TableColumn(field = "data", title = "Data")], width = 800, height = 500)

# def process_osc():
#     global q, lock
#     lst = []
#     lock.acquire()
#     if len(q) == 0:
#         lock.release()
#         return
#     for bndl_u in q:
#         #osctodict(bndl_u)
#         lst.append(bndl_u)
#     q = []
#     lock.release()
#     osctodict(lst)

# def osctodict(bndl_u_lst):
#     global table, table_source, timedomain_ds, timedomain_plot, timedomain_numplots, timedomain_updatedict, timedomain_keys, timedomain_winsize, i
#     msgdict = {}
#     for k in timedomain_keys:
#         msgdict[k] = []
#     for bndl_u in bndl_u_lst:
#         rstmsgar_u = o.osc_bundle_u_lookupAddress(bndl_u, bytes(reset_address, "utf-8"), 1)
#         if o.osc_message_array_u_getLen(rstmsgar_u) == 1:
#             clear()
#             return
#         else:
#             for k in timedomain_keys:
#                 msgar_u = o.osc_bundle_u_lookupAddress(bndl_u, bytes(k, "utf-8"), 1)
#                 if o.osc_message_array_u_getLen(msgar_u) == 1:
#                     msg = o.osc_message_array_u_get(msgar_u, 0)
#                     address = str(o.osc_message_u_getAddress(msg), "utf-8")
#                     #data = []
#                     mit = o.osc_message_iterator_u_getIterator(msg)
#                     while o.osc_message_iterator_u_hasNext(mit):
#                         a = o.osc_message_iterator_u_next(mit)
#                         tt = int(o.osc_atom_u_getTypetag(a)[0])
#                         if tt == t['c'] or tt == t['C'] or tt == t['u'] or tt == t['U'] or tt == t['i'] or tt == t['I'] or tt == t['h'] or tt == t['H']:
#                             msgdict[address].append(o.osc_atom_u_getInt(a))
#                         elif tt == t['f'] or tt == t['d']:
#                             msgdict[address].append(o.osc_atom_u_getDouble(a))
#                         elif tt == t['t']:
#                             #data.append(o.osc_atom_u_getDouble(a))
#                             if o.osc_timetag_timetagToFloat(o.osc_atom_u_getTimetag(a)) < 2208988800:
#                                 msgdict[address].append(dt.datetime.strptime(str(o.osc_timetag_format(o.osc_timetag_floatToTimetag(2208988800)), "utf-8"), "%Y-%m-%dT%H:%M:%S.%fZ"))
#                             else:
#                                 msgdict[address].append(dt.datetime.strptime(str(o.osc_timetag_format(o.osc_atom_u_getTimetag(a)), "utf-8"), "%Y-%m-%dT%H:%M:%S.%fZ"))
#                         else:
#                             error("unsupported type: " + str(tt))
#                             o.osc_message_iterator_u_destroyIterator(mit)
#                         #if address in msgdict:
#                             #msgdict[address].append(data)
#                         #else:
#                         #msgdict[address].append(data)
#                         #timedomain_ds.data[address].append(data)
#                 else:
#                     print("bundle is missing address " + k + ", bailing.")
#                     return
#     table_source.data = dict(addresses = list(msgdict.keys()), data = list(msgdict.values()))
#     #timedomain_ds.trigger('data', timedomain_ds.data, timedomain_ds.data)
#     timedomain_ds.stream(msgdict, timedomain_winsize)

# networking

# def udp_receive(port):
#     global q, lock
#     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#     #sock.settimeout(3.0)
#     sock.bind((UDP_IP, port))
#     while True:
#         try:
#             data, addr = sock.recvfrom(16384)
#         except:
#             sock.close()
#             error("exception trying to read from socket")
#             return
#         bndl_s = o.osc_bundle_s_alloc_py(len(data), data)
#         bndl_u = o.osc_bundle_s_deserialize(o.osc_bundle_s_getLen(bndl_s), o.osc_bundle_s_swugged(bndl_s))
#         lock.acquire()
#         q.append(bndl_u)
#         lock.release()
#         # try:
#         #     q.put(bndl_s)
#         # except:
#         #     error("queue is full! dropping packet.")
#         #     o.osc_bundle_s_free(bndl_s)

# def spawn_thread(callback, args):
#     try:
#         th = threading.Thread(target = callback, args = args)
#         th.start()
#     except:
#         error("couldn't spawn thread")
#         sys.exit(1)

# setup
# def main(argv):
#     global port, filename, timedomain_ds, timedomain_plot, timedomain_numplots, timedomain_winsize, timedomain_keys, reset_address, button_clear, independent_var
#     parser = argparse.ArgumentParser()
#     parser.add_argument("-p", "--port", help = "port number to receive UDP data on", default = 9999)
#     parser.add_argument("-o", "--out", help = "filename", default = dt.datetime.fromtimestamp(time.time()).strftime('%Y%m%d-%H:%M:%S'))
#     group = parser.add_mutually_exclusive_group(required = True)
#     group.add_argument("-n", "--n", help = "OSC address of an integer or numeric independent variable")
#     group.add_argument("-t", "--t", help = "OSC address of an OSC timetag independent variable")
#     parser.add_argument("-y", "--y", help = "OSC address of the dependent variables", nargs = '+')
#     parser.add_argument("-w", "--windowsize", help = "Size of the scrolling window in samples", default = 600)
#     parser.add_argument("-r", "--reset", help = "OSC address that resets the plot", default = '/reset')
#     parser.add_argument("-u", "--updaterate", help = "update rate in milliseconds", default = 250)
#     args = parser.parse_args()
#     port = int(args.port)
#     filename = args.out
#     output_file(filename)
#     d = {}
#     if args.n != None:
#         d[args.n] = []
#         timedomain_keys.append(args.n)
#         independent_var = 'n'
#     else:
#         d[args.t] = []
#         timedomain_keys.append(args.t)
#         independent_var = 't'
#         tf = DatetimeTickFormatter()
#         tf.hours = ["%Y-%m-%d %H:%M:%S"]
#         tf.days = ["%Y-%m-%d %H:%M:%S"]
#         tf.months = ["%Y-%m-%d %H:%M:%S"]
#         tf.years = ["%Y-%m-%d %H:%M:%S"]
#         tf.minutes = ["%Y-%m-%d %H:%M:%S"]
#         tf.seconds = ["%Y-%m-%d %H:%M:%S"]
#         tf.milliseconds = ["%Y-%m-%d %H:%M:%S"]
#         tf.microseconds = ["%Y-%m-%d %H:%M:%S"]
#         timedomain_plot.xaxis.formatter = tf
#     for k in args.y:
#         timedomain_keys.append(k)
#         d[k] = []
#     timedomain_ds = ColumnDataSource(d)
#     reset_address = args.reset
#     colors = ["red", "green", "blue", "yellow", "cyan", "magenta", "black"]
#     i = 0
#     for k in args.y:
#         if independent_var == 'n':
#             timedomain_plot.line(x = args.n, y = k, source = timedomain_ds, color = colors[i % len(colors)])
#         else:
#             timedomain_plot.line(x = args.t, y = k, source = timedomain_ds, color = colors[i % len(colors)])
#         i = i + 1
#         timedomain_numplots = len(args.y)
#     timedomain_winsize = int(args.windowsize)
#     update_rate = args.updaterate
#     button_clear = Button(label = "Clear", button_type = "success")
#     button_clear.on_click(clear_handler);
#     for s in ['c', 'C', 'u', 'U', 'i', 'I', 'h', 'H', 'f', 'd', 's', 'S', 't']:
#         t[s] = int(bytes(s, "utf-8")[0])
#     spawn_thread(udp_receive, [port])

# if __name__ == "__main__":
#     main(sys.argv[1:])

addy_time = "/ecg/time"
addys_ecg_y = ["/ecg/raw", "/ecg/filtered", "/ecg/mwidiv10", "/ecg/f1", "/ecg/i1div10"]
addys_hr_y = ["/ecg/rr", "/ecg/rravg/1", "/ecg/rravg/2"]
ecgs = [MyPlot("Dancer 1", 1000, addy_time, addys_ecg_y), MyPlot("Dancer 2", 1000, addy_time, addys_ecg_y), MyPlot("Dancer 3", 1000, addy_time, addys_ecg_y)]
hrs = [MyPlot("", 6000, addy_time, addys_hr_y), MyPlot("", 6000, addy_time, addys_hr_y), MyPlot("", 6000, addy_time, addys_hr_y)]

def cb(p, bndl_u):
    p.append_data(bndl_u)

def cb1(bndl_u):
    global ecgs, hrs
    cb(ecgs[0], bndl_u)
    cb(hrs[0], bndl_u)

def cb2(bndl_u):
    global ecgs, hrs
    cb(ecgs[1], bndl_u)
    cb(hrs[1], bndl_u)

def cb3(bndl_u):
    global ecgs, hrs
    cb(ecgs[2], bndl_u)
    cb(hrs[2], bndl_u)

def update_plots():
    global ecgs, hrs
    for ecg in ecgs:
        ecg.update()
    for hr in hrs:
        hr.update()

oudpr1 = oudpr.oudpr()
oudpr2 = oudpr.oudpr()
oudpr3 = oudpr.oudpr()

oudpr1.listen(10000, cb1, (addys_ecg_y + addys_hr_y) + [addy_time])
oudpr2.listen(10001, cb2, (addys_ecg_y + addys_hr_y) + [addy_time])
oudpr3.listen(10002, cb3, (addys_ecg_y + addys_hr_y) + [addy_time])

button_clear = None
def clear():
    for ecg in ecgs:
        ecg.clear()
    for hr in hrs:
        hr.clear()

def clear_handler():#(attr, old, new):
    clear();

button_clear = Button(label = "Clear", button_type = "success")
button_clear.on_click(clear_handler);

session = push_session(curdoc())
curdoc().add_periodic_callback(update_plots, 250)
#curdoc().add_root(column(button_clear, timedomain_plot, table))
curdoc().add_root(column(button_clear, ecgs[0].p, hrs[0].p, ecgs[1].p, hrs[1].p, ecgs[2].p, hrs[2].p))
session.show()
session.loop_until_closed()

clear()


from django.shortcuts import render
from django.urls import reverse_lazy
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.views import LoginView, LogoutView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import (
    CreateView,
    DeleteView,
    DetailView,
    ListView,
    TemplateView,
    UpdateView,
)
# Create your views here.
from .models import (
    CustomerModel,
    ProductModel,
    OrderModel,
)
from .forms import *
from .decorators import *

@method_decorator(unauthenticated, name='dispatch')
class RegistrationView(SuccessMessageMixin, CreateView):
    form_class = CreateUserForm
    template_name = 'accounts/registration_form.html'
    success_url = reverse_lazy('login')
    success_message = "%(username)s was created"
    extra_context = {
        'title': 'Registration'
    }

    def get_context_data(self, **kwargs):
        kwargs = self.kwargs
        context = super().get_context_data(**kwargs)
        context.update(self.extra_context)
        return context

@method_decorator(unauthenticated, name='dispatch')
class LoginPageView(LoginView):
    template_name = 'accounts/login_form.html'
    success_url = reverse_lazy('home')
    extra_context = {
        'title': 'Login'
    }

    def get_context_data(self, **kwargs):
        kwargs = self.kwargs
        context = super().get_context_data(**kwargs)
        context.update(self.extra_context)
        return context

class LogoutUser(LoginRequiredMixin, LogoutView):

    template_name = 'accounts/logout.html'

@method_decorator(login_required(login_url='login'), name='dispatch')
@method_decorator(admin_only, name='dispatch')
class DashboardView(TemplateView):
    template_name = 'accounts/index.html'

    def get_context_data(self, **kwargs):
        kwargs = self.kwargs
        context = super().get_context_data(**kwargs)
        customers = CustomerModel.objects.all()
        orders = OrderModel.objects.all()
        total_order = orders.count()
        total_delivered = orders.filter(status="Delivered").count()
        total_pending = orders.filter(status="Pending").count()
        extra_context = {
            'customers': customers,
            'orders': orders,
            'total_order': total_order,
            'total_delivered': total_delivered,
            'total_pending': total_pending,
        }
        context.update(extra_context)

        return context

@method_decorator(login_required(login_url='login'), name='dispatch')
@method_decorator(allowed_group(allowed=['customer']), name='dispatch')
class UserPageView(TemplateView):
    template_name = 'accounts/user_page.html'

    def get_context_data(self, **kwargs):
        kwargs = self.kwargs
        context = super().get_context_data(**kwargs)
        orders = self.request.user.customermodel.ordermodel_set.all()
        total_orders = orders.count()
        total_delivered = orders.filter(status="Delivered").count()
        total_pending = orders.filter(status="Pending").count()
        extra_context = {
            'orders': orders,
            'total_orders': total_orders,
            'total_delivered': total_delivered,
            'total_pending': total_pending,
        }
        context.update(extra_context)
        return context

@method_decorator(login_required(login_url='login'), name='dispatch')
@method_decorator(allowed_group(allowed=['admin']), name='dispatch')
class CustomerView(DetailView):
    model = CustomerModel
    context_object_name = 'customer'
    template_name = 'accounts/customer.html'

    def get_context_data(self, **kwargs):
        kwargs = self.kwargs
        context = super().get_context_data(**kwargs)
        orders = context['customer'].ordermodel_set.all()
        total_order = orders.count()
        extra_context = {
            'orders': orders,
            'total_order': total_order,
        }
        context.update(extra_context)
        return context

@method_decorator(login_required(login_url='login'), name='dispatch')
@method_decorator(allowed_group(allowed=['admin']), name='dispatch')
class ProductListView(ListView):
    model = ProductModel
    context_object_name = 'product_list'
    template_name = 'accounts/product_list.html'
    ordering = ['name']

    def get_context_data(self, **kwargs):
        kwargs = self.kwargs
        context = super().get_context_data(**kwargs)
        return context

@method_decorator(login_required(login_url='login'), name='dispatch')
@method_decorator(allowed_group(allowed=['admin']), name='dispatch')
class CreateOrderView(CreateView):
    form_class = OrderForm
    template_name = 'accounts/order_form.html'
    extra_context = {
        'title': 'Create Order'
    }

    def get_context_data(self, **kwargs):
        kwargs = self.kwargs
        context = super().get_context_data(**kwargs)
        context.update(self.extra_context)
        return context

@method_decorator(login_required(login_url='login'), name='dispatch')
@method_decorator(allowed_group(allowed=['admin']), name='dispatch')
class UpdateOrderView(UpdateView):
    model = OrderModel
    template_name = 'accounts/order_form.html'
    fields = [
        'product',
        'status',
        'note',
    ]
    extra_context = {
        'title': 'Update Order'
    }

    def get_context_data(self, **kwargs):
        kwargs = self.kwargs
        context = super().get_context_data(**kwargs)
        extra_context = {
            'name': context['object'].customer.name,
        }
        context.update(self.extra_context)
        context.update(extra_context)
        return context

@method_decorator(login_required(login_url='login'), name='dispatch')
@method_decorator(allowed_group(allowed=['admin']), name='dispatch')
class DeleteOrderView(DeleteView):
    model = OrderModel
    template_name = 'accounts/order_delete_confirmation.html'
    success_url = reverse_lazy('home')
    context_object_name = 'order'

    def get_context_data(self, **kwargs):
        kwargs = self.kwargs
        context = super().get_context_data(**kwargs)
        extra_context = {
            'name': context['order'].product.name + " by " + context['order'].customer.name
        }
        context.update(extra_context)
        return context

@method_decorator(login_required(login_url='login'), name='dispatch')
@method_decorator(allowed_group(allowed=['customer']), name='dispatch')
class AccountSetting(UpdateView):
    form_class = CustomerForm
    model = CustomerModel
    template_name = 'accounts/account_setting.html'

    def get_context_data(self, **kwargs):
        kwargs = self.kwargs
        context = super().get_context_data(**kwargs)
        return context


#!/usr/bin/python

from sys import stdin
from itertools import product

# read in data from stdin
values = list(map(int, stdin.readlines()))

# there really isn't a faster way than O(n^2); any speed gain
# from a faster algorithm would be lost to the initial sort

# filter generated tuples of values that add up to 2020
foundTuples = filter(
        lambda t : (t[0] + t[1]) == 2020,
        product( values, values )
    )

# There will be two, since the pairs are found (A,B) and (B,A)
# so we only need one
print ( "tuple is " + str( foundTuples[0] ) )
print ( foundTuples[0][0] *  foundTuples[0][1] )


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2020 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

#
# This is a simple example of the SerializingProducer using protobuf.
#
# To regenerate Protobuf classes you must first install the protobuf
# compiler. Once installed you may call protoc directly or use make.
#
# See the protocol buffer docs for instructions on installing and using protoc.
# https://developers.google.com/protocol-buffers/docs/pythontutorial
#
# After installing protoc execute the following command from the examples
# directory to regenerate the user_pb2 module.
# `make`
#
import argparse

# Protobuf generated class; resides at ./user_pb2.py
import user_pb2
from confluent_kafka import DeserializingConsumer
from confluent_kafka.schema_registry.protobuf import ProtobufDeserializer
from confluent_kafka.serialization import StringDeserializer

def main(args):
    topic = args.topic

    protobuf_deserializer = ProtobufDeserializer(user_pb2.User)
    string_deserializer = StringDeserializer('utf_8')

    consumer_conf = {'bootstrap.servers': args.bootstrap_servers,
                     'key.deserializer': string_deserializer,
                     'value.deserializer': protobuf_deserializer,
                     'group.id': args.group,
                     'auto.offset.reset': "earliest"}

    consumer = DeserializingConsumer(consumer_conf)
    consumer.subscribe([topic])

    while True:
        try:
            # SIGINT can't be handled when polling, limit timeout to 1 second.
            msg = consumer.poll(1.0)
            if msg is None:
                continue

            user = msg.value()
            if user is not None:
                print("User record {}: name: {}\n"
                      "\tfavorite_number: {}\n"
                      "\tfavorite_color: {}\n"
                      .format(msg.key(), user.name,
                              user.favorite_color,
                              user.favorite_number))
        except KeyboardInterrupt:
            break

    consumer.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="DeserializingConsumer Example")
    parser.add_argument('-b', dest="bootstrap_servers", required=True,
                        help="Bootstrap broker(s) (host[:port])")
    parser.add_argument('-s', dest="schema_registry", required=True,
                        help="Schema Registry (http(s)://host[:port]")
    parser.add_argument('-t', dest="topic", default="example_serde_protobuf",
                        help="Topic name")
    parser.add_argument('-g', dest="group", default="example_serde_protobuf",
                        help="Consumer group")

    main(parser.parse_args())


from __future__ import division
import tkinter.font as tkFont
from tkinter import *
# import tkMessageBox
from PIL import Image, ImageTk
import tkinter.messagebox as messagebox
import os
import glob
import random
import os
#import cv2

classes=['0', '1', '2', '3', '4', '5', '6', '7', '8', '9','A','B','C','D','E','F','G','H','I','J'
    ,'K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
curClass="None"
colors=['red', 'blue', 'orange','purple', 'pink', 'cyan', 'green', 'black']
newSizeX=600
class MergeCheckZoom():
    def __init__(self, master,OriImg,zoomInfo,groundtruth,MainObj):
        # print(zoomInfo)
        self.curTag=""
        self.zoomInfo=zoomInfo
        # print("self.zoomInfo:",tuple(self.zoomInfo))
        self.MainObj=MainObj

        self.frameWidth=0
        self.frameHeight = 0
        self.OriImg=OriImg
        self.PILimg=""

        self.times=1.2
        self.BBoxListId=[]
        self.infoBoxList = []
        self.groundTruth=groundtruth
        self.RectedNum=0
        self.option ={}
        self.option["isloadImg"]=False
        self.initLoad()

        self.font = tkFont.Font(family='Helvetica', size=24)
        self.tkObj = master
        self.tkObj.title("LabelZoom")
        self.frame = Frame(self.tkObj)
        self.frame.pack(fill=BOTH, expand=1)  # pack表示在TK()窗口中的填充方式
        self.tkObj.resizable(width=False, height=False)

        #图片显示区域,并绑定一些事件
        self.ImgPanel = Canvas(self.frame, cursor='tcross')  # cursor表示鼠标在画布Canvas中的形状
        self.ImgPanel.bind("<Button-1>", self.mouseClick)  # 绑定鼠标左键(<Button-1>)事件
        self.ImgPanel.bind("<Motion>", self.mouseMove)  # 绑定鼠标移动事件(Motion>)
        self.ImgPanel.grid(row=1, column=0, rowspan=6,columnspan=2, sticky=W + N)

        # 矩形框的listbox和删除、清空按钮
        self.BBoxListLab = Label(self.frame, text='Bounding boxes:')
        self.BBoxListLab.grid(row=1, column=2, sticky=W + N)
        self.listbox = Listbox(self.frame, width=30, height=12)
        self.listbox.grid(row=2, column=2, sticky=N)
        self.Deletebtn = Button(self.frame, text='Delete', command=self.delBBox)
        self.Deletebtn.grid(row=3, column=2, sticky=W + E + N)
        self.Clearbtn = Button(self.frame, text='ClearAll', command=self.clearBBox)
        self.Clearbtn.grid(row=4, column=2, sticky=W + E + N)

        self.FreeModebtn = Button(self.frame, text='Change to Free Mode', command=self.gotoFreeRect)
        self.FreeModebtn.grid(row=5, column=2, sticky=W + E + N)

        self.groundTruthLab = Label(self.frame, text='Ground Truth:')
        self.groundTruthLab.grid(row=7, column=0, sticky=W + E)

        self.groundTruthShowLab = Label(self.frame,text=self.groundTruth)
        self.groundTruthShowLab.grid(row=7, column=1, sticky=W + E)
        # self.groundTruthLab.insert(0,self.groundTruth)

        self.confirmGTbtn = Button(self.frame,text="OK",command=self.ReturnMainObj)
        self.confirmGTbtn.grid(row=7, column=2, sticky=W + E)

        #最后一行的控制面板
        self.ctrPanel=Frame(self.frame)
        self.ctrPanel.grid(row=10, column=0, columnspan=10, sticky=W + E)

        self.positionLab = Label(self.ctrPanel, text="x: ,y: ")
        self.positionLab.pack(side=RIGHT, padx=5, pady=3)

        # print(MainObj.infoBoxList)
        self.loadImage()

    def loadImage(self):
        # print("self.zoomInfo:",self.zoomInfo)
        self.OriImg=self.OriImg.crop(self.zoomInfo)
        imgSize=self.OriImg.size
        # print("before:",imgSize[0],imgSize[1])

        self.times=newSizeX/imgSize[0]
        newSizeY=imgSize[1]*self.times
        self.OriImg=self.OriImg.resize((int(newSizeX),int(newSizeY)))
        imgSize = self.OriImg.size
        # print("after:", imgSize[0], imgSize[1])
        # img_open.thumbnail((200, 200))
        self.PILimg = ImageTk.PhotoImage(self.OriImg)

        self.frameWidth = max(self.PILimg.width(), 100)
        self.frameHeight = max(self.PILimg.height(), 100)+50
        self.ImgPanel.config(width=self.frameWidth, height=self.frameHeight)
        self.ImgPanel.create_image(0, 50, image=self.PILimg, anchor=NW)

        for ind in range(0, len(self.MainObj.infoBoxList)):
            line = self.MainObj.infoBoxList[ind].strip()
            info = line.split(":")[1]
            tag = line.split(":")[0]
            if tag=="plate" or tag=="car":
                continue
            x1, y1, x2, y2 = info.split(",")
            #plateX+(int(pos[0]))/self.times, plateY+(int(pos[1])-50)/self.times,
            # print(list(self.zoomInfo))
            x1, y1, x2, y2 = (int(float(x1))-self.zoomInfo[0]) * self.times,(int(float(y1))-self.zoomInfo[1]) * self.times+50,\
                             (int(float(x2)) - self.zoomInfo[0]) * self.times,(int(float(y2))-self.zoomInfo[1]) * self.times+50
            infoForListBox = '%s : (%d, %d) -> (%d, %d)' % (tag, int(x1), int(y1), int(x2), int(y2))
            infoForInfoBox = '%s:%d,%d,%d,%d' % (tag, x1, y1, x2, y2)
            self.listbox.insert(END, infoForListBox)
            self.listbox.itemconfig(len(self.BBoxListId), fg=colors[(len(self.BBoxListId)) % len(colors)])
            id = self.ImgPanel.create_rectangle(x1, y1, x2, y2, width=2,
                                                outline=colors[(len(self.BBoxListId)) % len(colors)])
            self.BBoxListId.append(id)
            self.infoBoxList.append(infoForInfoBox)

        self.option["isloadImg"] = True
        self.initLoad()

    def initLoad(self):
        self.option["isFreeRect"], self.option["isClicked"] = True, False
        self.option["lineXID"], self.option["lineYID"] = -1, -1
        self.option["pointX"], self.option["pointY"] = -1, -1
        self.option["RectW"], self.option["RectH"] = -1, -1
        self.option["RectId"] ,self.option["textId"] = -1,-1
        self.initTag()

    def mouseClick(self,event):
        if self.option["isloadImg"]:
            if self.option["isFreeRect"]:
                if not self.option["isClicked"]:
                    self.option["isClicked"]=True
                    self.option["pointX"]=event.x
                    self.option["pointY"] = event.y
                else:
                    self.option["isFreeRect"]=False
                    self.option["RectW"]=abs(event.x-self.option["pointX"])
                    self.option["RectH"] = abs(event.y-self.option["pointY"])
                    self.BBoxListId.append(self.option["RectId"])
                    if len(self.infoBoxList)==0:
                        textVal="plate"
                    self.option["RectId"]=-1
                    infoForListBox='%s : (%d, %d) -> (%d, %d)' % (self.curTag,self.option["pointX"], self.option["pointY"], event.x, event.y)
                    infoForInfoBox='%s:%d,%d,%d,%d' % (self.curTag,self.option["pointX"], self.option["pointY"], event.x, event.y)
                    self.infoBoxList.append(infoForInfoBox)
                    self.listbox.insert(END, infoForListBox)
                    self.listbox.itemconfig(len(self.BBoxListId) - 1,fg=colors[(len(self.BBoxListId) - 1) % len(colors)])

                    if len(self.groundTruth)>=len(self.BBoxListId)+1:
                        pass
                        # isOneOrI1=self.curTag=="1" or self.curTag=="I"
                        # isOneOrI2 = self.groundTruth[len(self.BBoxListId)]=="1" or self.groundTruth[len(self.BBoxListId)]=="I"
                        # # print("TagFree:",self.curTag,self.groundTruth[len(self.BBoxListId)])
                        # if isOneOrI1 ^ isOneOrI2:  #字符前后不同时为1或不同时为I,则自由画框
                        #     self.clearTempLine()
                        #     self.gotoFreeRect()
                    self.initTag()
            else:
                    self.BBoxListId.append(self.option["RectId"])
                    endX=event.x+self.option["RectW"]
                    endY = event.y + self.option["RectH"]
                    # print(self.option["RectW"],self.option["RectH"])

                    infoForListBox='%s : (%d, %d) -> (%d, %d)' % (self.curTag,event.x, event.y,endX,endY)
                    infoForInfoBox='%s:%d,%d,%d,%d' % (self.curTag,event.x, event.y,endX,endY)
                    self.listbox.insert(END, infoForListBox)
                    self.infoBoxList.append(infoForInfoBox)
                    self.listbox.itemconfig(len(self.BBoxListId) - 1,fg=colors[(len(self.BBoxListId) - 1) % len(colors)])
                    self.option["RectId"] = -1
                    if len(self.groundTruth)>=len(self.BBoxListId)+1:
                        pass
                        # isOneOrI1=self.curTag=="1" or self.curTag=="I"
                        # isOneOrI2 = self.groundTruth[len(self.BBoxListId)]=="1" or self.groundTruth[len(self.BBoxListId)]=="I"
                        # # print("TagNoFree:",self.curTag,self.groundTruth[len(self.BBoxListId)])
                        # if isOneOrI1 ^ isOneOrI2:  #字符前后不同时为1或不同时为I,则自由画框
                        #     self.clearTempLine()
                        #     self.gotoFreeRect()
                    self.initTag()
                    # if (len(self.BBoxListId)==3):
                    #     self.gotoFreeRect()

    def clearTempLine(self):
        if self.option["lineXID"] > 0:
            self.ImgPanel.delete(self.option["lineXID"])
        if self.option["lineYID"] > 0:
            self.ImgPanel.delete(self.option["lineYID"])
        if self.option["textId"] > 0:
            self.ImgPanel.delete(self.option["textId"])
        if self.option["RectId"] > 0:
            self.ImgPanel.delete(self.option["RectId"])

    def mouseMove(self,event):
        self.positionLab.config(text='x: %d, y: %d' % (event.x, event.y))
        if self.option["isloadImg"]:
            if self.option["lineXID"] > 0:
                self.ImgPanel.delete(self.option["lineXID"])
            if self.option["lineYID"] > 0:
                self.ImgPanel.delete(self.option["lineYID"])
            #自由画框
            if self.option["isFreeRect"]:
                self.option["lineXID"] = self.ImgPanel.create_line(event.x, 0, event.x, self.frameHeight, width=2,
                                                                   fill=colors[(len(self.BBoxListId) ) % len(colors)])
                self.option["lineYID"] = self.ImgPanel.create_line(0, event.y, self.frameWidth, event.y, width=2,
                                                                   fill=colors[(len(self.BBoxListId) ) % len(colors)])
                if self.option["isClicked"]:
                    if self.option["RectId"] > 0:
                        self.ImgPanel.delete(self.option["RectId"])
                    self.option["RectId"] = self.ImgPanel.create_rectangle(self.option['pointX'],
                                            self.option['pointY'], event.x, event.y, width=2, outline=colors[(len(self.BBoxListId) ) % len(colors)])
            #固定宽高画框
            else:
                endX=event.x+self.option['RectW']
                endY = event.y + self.option['RectH']
                # print(event.x,event.y,endX,endY)

                if self.option["RectId"] > 0:
                    self.ImgPanel.delete(self.option["RectId"])
                self.option["RectId"] = self.ImgPanel.create_rectangle(event.x, event.y,endX, endY, width=2, outline=colors[(len(self.BBoxListId) ) % len(colors)])
            # print("groundTruth:",self.groundTruth)
            if self.option["textId"] > 0:
                self.ImgPanel.delete(self.option["textId"])
            self.option["textId"]=self.ImgPanel.create_text(event.x + 20, event.y - 15, text=self.curTag, fill=colors[(len(self.BBoxListId) ) % len(colors)], font=self.font)

    def cancelBBox(self,event):
        print("cancelBBox")

    def ReturnMainObj(self):
        plateX=int(self.zoomInfo[0])
        plateY = int(self.zoomInfo[1])
        print(self.infoBoxList)
        for ind,val in enumerate(self.infoBoxList):
            tag=val.split(":")[0]
            info=val.split(":")[1]
            pos=info.split(",")
            # print(tag, "->", pos)
            # print(info,"--",self.times)
            infoForInfoBox = '%s:%f,%f,%f,%f' % (tag, int(plateX+(float(pos[0]))/self.times), plateY+(int(pos[1])-50)/self.times,
                                                 plateX+(int(pos[2])) / self.times, plateY+(int(pos[3])-50)/self.times)
            # print((float(pos[0]))/self.times,int((float(pos[0]))/self.times),"--",self.times)
            self.MainObj.infoBoxList.append(infoForInfoBox)
        # print(self.MainObj.infoBoxList)
        self.MainObj.refreshZoom()
        # self.tkObj.close()

    def gotoFreeRect(self,event=None):
        # print(len(self.BBoxListId))
        if not self.option["isFreeRect"]:
            if self.option["RectId"] > 0:
                self.ImgPanel.delete(self.option["RectId"])
            if self.option["textId"] > 0:
                self.ImgPanel.delete(self.option["textId"])
            self.initLoad()

    def initTag(self):
        if len(self.BBoxListId) < len(self.groundTruth):
            self.curTag = self.groundTruth[len(self.BBoxListId)]
        elif (len(self.groundTruth) > 0):
            self.curTag = self.groundTruth[-1]

    def delBBox(self):
        sel = self.listbox.curselection()
        if len(sel)==0:
            return
        # if len(sel) != 1:
        #     return
        idx = int(sel[0])

        print("idx:",idx)
        self.ImgPanel.delete(self.BBoxListId[idx])
        self.BBoxListId.pop(idx)
        self.infoBoxList.pop(idx)
        self.listbox.delete(idx)
        # print(self.infoBoxList)

    def clearBBox(self):

        # print("refreshZoom:", self.infoBoxList)
        for ind in range(2, len(self.MainObj.BBoxListId)):
            self.MainObj.ImgPanel.delete(self.MainObj.BBoxListId[ind])
        self.MainObj.listbox.delete(2, len(self.MainObj.BBoxListId))
        self.MainObj.BBoxListId = self.MainObj.BBoxListId[0:2]

        for ind,var in enumerate(self.BBoxListId):
            self.ImgPanel.delete(var)
        self.listbox.delete(0, len(self.BBoxListId))

        self.MainObj.infoBoxList=self.MainObj.infoBoxList[0:2]
        # print("self.MainObj.infoBoxList:",self.MainObj.infoBoxList)
        self.clearTempLine()
        self.initLoad()
        if (len(self.groundTruth)>0):
           self.curTag=self.groundTruth[0]
        self.infoBoxList=[]
        self.BBoxListId=[]

    def changeClass(self,classNum):
        print("changeClass:",classNum)


import re

from django import template

register = template.Library()

REPO_REGEXP = re.compile(r'https://github\.com/(?P<name>\w+)/(?P<repo>\S+)/?')
REPO_SCHEMA = 'https://github.com/{name}/{repo}/'
WEBSITE_REGEXP = re.compile(
    r'http://(?P<name>\w+)\.github\.(io|com)/(?P<repo>\S+)/?'
)
WEBSITE_SCHEMA = 'http://{name}.github.io/{repo}/'

@register.assignment_tag
def format_link_to_repository(link):
    """
    Use: {% format_link_to_repository event.url as repo_link %}
    Then: {{ repo_link|urlize|default_if_none:"—" }}
    """
    if not link:
        return link
    elif REPO_REGEXP.match(link):
        return link
    else:
        try:
            repository = WEBSITE_REGEXP.findall(link)[0]
            return REPO_SCHEMA.format(name=repository[0], repo=repository[-1])
        except IndexError:
            return link

@register.assignment_tag
def format_link_to_website(link):
    """
    Use: {% format_link_to_website event.url as website_link %}
    Then: {{ website_link|urlize|default_if_none:"—" }}
    """
    if not link:
        return link
    elif WEBSITE_REGEXP.match(link):
        return link
    else:
        try:
            site = REPO_REGEXP.findall(link)[0]
            return WEBSITE_SCHEMA.format(name=site[0], repo=site[-1])
        except IndexError:
            return link