import validators
from .logger import setup_logging

class ConnectedObject:
    '''
    '''

    def __init__(self, host='0.0.0.0', port=4242):
        '''
        '''
        setup_logging()
        self._host = None
        self._port = None

    @property
    def host(self):
        return self._host

    @host.setter
    def host(self, value):
        '''
        '''
        error_msg = (f'Invalid host "{value}". Value should be a '
                     f'domain, valid IPv4 address, or valid IPv6 address.')
        is_domain = validators.domain(value)
        is_ipv4 = validators.ip_address.ipv4(value)
        is_ipv6 = validators.ip_address.ipv6(value)
        if is_domain or is_ipv4 or is_ipv6:
            self._host = value
            return
        raise ValueError(error_msg)

    @property
    def port(self):
        return self._port

    @port.setter
    def port(self, value):
        '''
        '''
        error_msg = (f'Invalid port number "{value}". Value should be an '
                     f'integer between 1025 and 65535 (included).')
        try:
            value = int(value)
        except ValueError:
            raise ValueError(error_msg)
        if 1024 < int(value) < 65536:
            self._port = int(value)
            return
        raise ValueError(error_msg)


from PyQt4 import QtGui
from datetime import datetime

class FiberPropertiesWindow(QtGui.QDialog):

    def __init__(self, fibers, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self._fibers = fibers
        self.setWindowTitle(self.tr("Fiber Properties"))

        self.nameInput = QtGui.QLineEdit()
        self.authorInput = QtGui.QLineEdit()
        self.crdateLabel = QtGui.QLabel()
        self.tstampLabel = QtGui.QLabel()
        self.descriptionInput = QtGui.QPlainTextEdit()

        formLayout = QtGui.QFormLayout()
        formLayout.addRow(QtGui.QLabel(self.tr("Name")),
                          self.nameInput)
        formLayout.addRow(QtGui.QLabel(self.tr("Author")),
                          self.authorInput)
        formLayout.addRow(QtGui.QLabel(self.tr("Created")),
                          self.crdateLabel)
        formLayout.addRow(QtGui.QLabel(self.tr("Modified")),
                          self.tstampLabel)
        formLayout.addRow(QtGui.QLabel(self.tr("Description")),
                          self.descriptionInput)

        buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok |
                                           QtGui.QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        layout = QtGui.QVBoxLayout()
        layout.addLayout(formLayout)
        layout.addWidget(buttonBox)
        self.setLayout(layout)

    def exec_(self):
        self.nameInput.setText(self._fibers["name"])
        self.authorInput.setText(self._fibers["author"])
        self.crdateLabel.setText(datetime.fromtimestamp(
            self._fibers["crdate"]).strftime('%Y-%m-%d %H:%M:%S'))
        self.tstampLabel.setText(datetime.fromtimestamp(
            self._fibers["tstamp"]).strftime('%Y-%m-%d %H:%M:%S'))
        self.descriptionInput.setPlainText(self._fibers["description"])
        super().exec_()

    def accept(self):
        if self._fibers["name"] != self.nameInput.text():
            self._fibers["name"] = self.nameInput.text()
            self.parent().setDirty(True)
        if self._fibers["author"] != self.authorInput.text():
            self._fibers["author"] = self.authorInput.text()
            self.parent().setDirty(True)
        if self._fibers["description"] != self.descriptionInput.toPlainText():
            self._fibers["description"] = self.descriptionInput.toPlainText()
            self.parent().setDirty(True)
        super().accept()


import collections
import math
import copy

import pyexcel_ods3
import pyexcel_xls

from openglider.glider.cell import DiagonalRib
from openglider.utils.table import Table

class GliderSpreadsheet(object):
    """
    Tabular representation of a glider for easy manipulation
    """
    def __init__(self, glider2d):
        self.glider2d = glider2d
        self.sheets = collections.OrderedDict([
            ("Geometry", Table()),
            ("Cell Elements", Table()),
            ("Rib Elements", Table()),
            ("Airfoils", Table()),
            ("Balloonings", Table()),
            ("Parametric", Table()),
            ("Lines", Table()),
            ("Data", Table())
        ])

    @classmethod
    def read_ods(cls, filepath):
        data = pyexcel_ods3.get_data(filepath)
        return cls.from_dict(data)

    @classmethod
    def read_xls(cls, filepath):
        data =pyexcel_xls.get_data(filepath)
        return cls.from_dict(data)

    @classmethod
    def from_dict(cls, dct):
        # unpack sheets:
        pass

    def update(self):
        self.set_geometry()
        self.set_cell_parts()
        self.set_rib_parts()
        #self.set_lines()
        #self.set_airfoils()
        #self.set_balloonings()
        #self.set_parametric()
        #self.set_data()

    def set_geometry(self):
        header = ["Ribs", "Chord", "Le x (m)", "Le y (m)", "Arc", "AOA", "Z-rotation", "Y-rotation", "profile-merge", "ballooning-merge"]
        geometry = [header]
        shape = self.glider2d.shape.get_half_shape()
        arc_angles_rad = self.glider2d.arc.get_cell_angles(self.glider2d.shape.rib_x_values) + [0]
        arc_angles = [0] + [angle*180/math.pi for angle in arc_angles_rad]

        aoa_int = self.glider2d.aoa.interpolation(num=100)
        profile_int = self.glider2d.profile_merge_curve.interpolation(num=100)
        ballooning_int = self.glider2d.ballooning_merge_curve.interpolation(num=100)

        for rib_no, x in enumerate(self.glider2d.shape.rib_x_values):
            chord = shape.chords[rib_no]
            front = shape.front[rib_no]
            x = front[0]
            y = -front[1]
            arc_diff = arc_angles[rib_no+1] - arc_angles[rib_no]

            row = [rib_no+1,
                   float(chord),
                   float(x),
                   float(y),
                   float(arc_diff),
                   float(aoa_int(x)*180/math.pi),
                   0,
                   0,
                   float(profile_int(x)),
                   float(ballooning_int(x))]

            geometry.append(row)

        self.sheets["Geometry"] = geometry

    @staticmethod
    def _get_columns(name, row_num, col_num):
        lst = [["" for i in range(row_num+1)] for j in range(col_num)]
        lst[0][0] = name
        return lst

    def set_cell_parts(self):

        row_num = self.glider2d.shape.half_cell_num
        elems = self.glider2d.elements

        columns = [["Cell No."] + [i+1 for i in range(row_num)]]

        # cuts
        # group by type
        cut_types = {}
        for cut in elems["cuts"]:
            cut_type = cut["type"]
            cut_types.setdefault(cut_type, [[]]*row_num)
            for cell_no in cut["cells"]:
                cut_types[cut_type][cell_no].append(copy.copy(cut))

        for cut_type, cells in cut_types.items():
            while any(len(cell) for cell in cells):
                columns_cut = self._get_columns(cut_type, row_num, 2)

                def find_next(x_last=None, cell_start=0):
                    for i, cuts in enumerate(cells[cell_start:]):
                        for cut in cuts:
                            if cut["left"] == x_last or x_last is None:
                                cuts.remove(cut)
                                return cell_start+i, cut

                res = find_next()

                while res:
                    cell_no, cut = res
                    columns_cut[0][cell_no+1] = cut["left"]
                    columns_cut[1][cell_no+1] = cut["right"]

                    res = find_next(cut["right"], cell_no+1)

                columns += columns_cut

        # Diagonals
        for diagonal in elems["diagonals"]:
            diagonal = copy.copy(diagonal)
            cols = self._get_columns("QR", row_num, 6)

            cells = diagonal.pop("cells")
            _diagonal = DiagonalRib(**diagonal)

            for cell_no in cells:
                # center_left, center_right, width_left, width_right, height_left, height_right

                cols[0][cell_no+1] = _diagonal.center_left
                cols[1][cell_no+1] = _diagonal.center_right
                cols[2][cell_no+1] = _diagonal.width_left
                cols[3][cell_no+1] = _diagonal.width_right
                cols[4][cell_no+1] = _diagonal.left_front[1]
                cols[5][cell_no+1] = _diagonal.right_front[1]

            columns += cols

        # Straps
        for strap in elems["straps"]:
            cols = self._get_columns("VEKTLAENGE", row_num, 2)
            for cell_no in strap["cells"]:
                cols[0][cell_no+1] = strap["left"]
                cols[0][cell_no+1] = strap["right"]

        # Material
        max_parts = max([len(c) for c in elems["materials"]])
        cols = [["MATERIAL"] + ["" for i in range(row_num)] for j in range(max_parts)]

        for cell_no, cell in enumerate(elems["materials"]):
            for part_no, part in enumerate(cell):
                cols[part_no][cell_no+1] = part

        columns += cols

        self.sheets["Cell Elements"] = list(zip(*columns))

    def set_rib_parts(self):

        row_num = self.glider2d.shape.half_cell_num + 1
        elems = self.glider2d.elements
        columns = [["Rib No."] + [i+1 for i in range(row_num)]]

        # holes
        for hole in elems["holes"]:
            hole_cols = self._get_columns("HOLE", row_num, 2)
            for rib_no in hole["ribs"]:
                hole_cols[0][rib_no+1] = hole["pos"]
                hole_cols[1][rib_no+1] = hole["size"]

            columns += hole_cols

        # attachment points
        per_rib = [self.glider2d.lineset.get_upper_nodes(rib_no) for rib_no in range(self.glider2d.shape.half_rib_num)]
        max_points = max([len(p) for p in per_rib])
        header = ["AHP", "", ""] * max_points
        attachment_points = [header]

        for rib_no, nodes in enumerate(per_rib):
            nodes.sort(key=lambda node: node.rib_pos)
            row = ["", "", ""] * max_points
            for node_no, node in enumerate(nodes):
                row[node_no*3] = node.name
                row[node_no*3+1] = node.rib_pos
                row[node_no*3+2] = node.force
            attachment_points.append(row)

        columns += list(zip(*attachment_points))

        # rigidfoils
        rigidfoils = elems.get("rigidfoils", [])
        rigidfoils.sort(key=lambda r: r["start"])
        for rigidfoil in rigidfoils:
            rigid_cols = self._get_columns("RIGIDFOIL", row_num, 3)
            for rib_no in rigidfoil["ribs"]:
                rigid_cols[0][rib_no+1] = rigidfoil["start"]
                rigid_cols[1][rib_no+1] = rigidfoil["end"]
                rigid_cols[2][rib_no+1] = rigidfoil["distance"]

            columns += rigid_cols

        self.sheets["Rib Elements"] = list(zip(*columns))

    def set_lines(self):
        table = self.glider2d.lineset.get_table()
        self.sheets["Lines"] = table

    def set_airfoils(self):
        table = Table()
        for airfoil in self.glider2d.profiles:
            x = [p[0] for p in airfoil]
            y = [p[1] for p in airfoil]

            x.insert(0, airfoil.name)
            y.insert(0, "")

            table.add_columns(x, y)

        self.sheets["Airfoils"] = table

    def set_balloonings(self):
        table = Table()
        for ballooning in self.glider2d.balloonings:
            upper = ballooning.controlpoints[0]
            lower = ballooning.controlpoints[1]

            x = [p[0] for p in upper+lower]
            y = [p[1] for p in upper+lower]

            x.insert(0, ballooning.name or "ballooning")
            y.insert(0, "")

            table.add_columns(x, y)

        self.sheets["Balloonings"] = table

    def _transpose_columns(self, data, name):
        x = [p[0] for p in data]
        y = [p[1] for p in data]
        x.insert(0, name)
        y.insert(0, "")

        return x, y

    def set_parametric(self):
        table = Table()

        table.add_columns(*self._transpose_columns(self.glider2d.arc.curve, "Arc"))
        table.add_columns(*self._transpose_columns(self.glider2d.shape.front_curve, "Front"))
        table.add_columns(*self._transpose_columns(self.glider2d.shape.back_curve, "Back"))
        table.add_columns(*self._transpose_columns(self.glider2d.shape.rib_distribution, "Dist"))
        table.add_columns(*self._transpose_columns(self.glider2d.aoa, "AOA"))
        table.add_columns(*self._transpose_columns(self.glider2d.profile_merge_curve, "Profile_merge"))
        table.add_columns(*self._transpose_columns(self.glider2d.ballooning_merge_curve, "Ballooning_merge"))

        self.sheets["Parametric"] = table

    def set_data(self):
        data = {
            "SPEED": self.glider2d.speed,
            "GLIDE": self.glider2d.glide,
            "CELLS": self.glider2d.shape.cell_num
        }

        self.sheets["Data"] = data.items()

    def write_ods(self, filepath):
        pyexcel_ods3.save_data(filepath, self.sheets)


import io
import os
import random
from unittest.mock import patch, MagicMock

import pytest

from peek import __file__ as package_root
from peek.es_api_spec.kspec_js import JsSpecParser, JsSpecEvaluator, build_js_specs

package_root = os.path.dirname(package_root)
kibana_dir = os.path.join(package_root, 'specs', 'kibana-7.8.1')

@pytest.mark.skipif(not os.path.exists(kibana_dir), reason='Kibana directory not available')
def test_parse_specs():
    spec_parser = JsSpecParser(kibana_dir)
    spec_parser.parse()

@pytest.mark.skipif(not os.path.exists(kibana_dir), reason='Kibana directory not available')
def test_eval_specs():
    spec_parser = JsSpecParser(kibana_dir)
    nodes = spec_parser.parse()
    spec_evaluator = JsSpecEvaluator()
    specs = spec_evaluator.visit(nodes)
    assert 'GLOBAL' in specs
    assert 'search' in specs
    assert 'put_mapping' in specs

def test_build_js_spec_will_respect_cache_config():
    kibana_dir = 'kibana_dir'
    mock_parser = MagicMock()
    mock_parser_cls = MagicMock(name='JsSpecParser', return_value=mock_parser)
    mock_evaluator = MagicMock(name='JsSpecEvaluator', return_value=MagicMock())
    cache_io = io.StringIO("source")
    use_cache_file = random.choice((True, False))
    cache_file_exists = random.choice((True, False))
    with patch('os.path.exists', MagicMock(return_value=cache_file_exists)), patch(
        'builtins.open', MagicMock(return_value=cache_io)
    ), patch('peek.es_api_spec.kspec_js.JsSpecParser', mock_parser_cls), patch(
        'peek.es_api_spec.kspec_js.JsSpecEvaluator', mock_evaluator
    ):
        build_js_specs(kibana_dir, use_cache_file)

        if not use_cache_file:
            mock_parser_cls.assert_called_with(kibana_dir, source=None)
            mock_parser.parse.assert_called_once()
            mock_parser.save.assert_not_called()
        else:
            if cache_file_exists:
                mock_parser_cls.assert_called_with(kibana_dir, source='source')
                mock_parser.save.assert_not_called()
            else:
                mock_parser_cls.assert_called_with(kibana_dir, source=None)
                mock_parser.save.assert_called()

def test_parser_will_not_read_spec_files_when_source_is_provided():
    kibana_dir = None  # intentionally have it as None so if used will trip
    spec_parser = JsSpecParser(kibana_dir, source='let x = 42')
    nodes = spec_parser.parse()
    assert len(nodes) == 1


from email import header
from django.shortcuts import render, redirect
from django.views.generic import View
from django.core.exceptions import ObjectDoesNotExist
from django.contrib import messages
import requests
import math
import random
from django.conf import settings
from payments.models import OrderAddress
from . forms import checkoutForm
from afrogulio.models import Cart

key = settings.SWAHILIES_SECRET_KEY
url = "https://swahiliesapi.invict.site/Api"
headers = {'User-Agent': 'Mozilla/5.0'}

# Create your views here.
class CheckoutView(View):
    def get(self, *args, **kwargs):
        cart = Cart.objects.get(user=self.request.user, ordered=False)
        form = checkoutForm()
        context={
           'form':form,
           'cart':cart
        }
        return render(self.request, 'payments/checkout.html', context)
    def post(self,*args, **kwargs):
        print(self.request.POST)
        form = checkoutForm(self.request.POST or None)
        try:
            cart = Cart.objects.get(user=self.request.user, ordered=False)
            if form.is_valid():
                address = form.cleaned_data.get('address')
                second_address = form.cleaned_data.get('second_address')
                country = form.cleaned_data.get('country')
                zip_code = form.cleaned_data.get('zip_code')
                phone = form.cleaned_data.get('phone')
                email = form.cleaned_data.get('email')
                payment = form.cleaned_data.get('payment')
                order_id = ''+str(math.floor(1000000 + random.random()*9000000)),
                order = OrderAddress(
                    user= self.request.user,
                    address= address,
                    second_address= second_address,
                    country=country,
                    zip_code=zip_code,
                    phone= phone,
                    email= email,
                    order_id = order_id

                )
                order.save()
                # cart.ordered = True
                # cart.order = order
                # cart.save()
                # send_mail(
                #     'New Order has been placed',
                #     f"Please visit your admin panel site to see order",
                #     'ummasoft@gmail.com',['isayaelib@gmail.com'], fail_silently=False
                # )
                if payment == 'S':
                     return redirect('process', order_id=order_id)
                elif payment == 'C':
                    return redirect('payment', payment_option='cash')
                else:
                    messages.warning(self.request, "Ivalid payment method")
            messages.info(self.request, "Failed checkout")
            return redirect('checkout')

        except ObjectDoesNotExist:
            messages.error(self.request, "You do not have an active order..")
            return redirect('cart')

def swahilies(request, payment_option):

    return render(request, 'payments/swahilies.html')

def process_payment(request, order_id):
    cart = Cart.objects.get(user=request.user, ordered=False)
    payload = {
        "api":170, "code":101,"data":{
        "api_key":key,
        "order_id": order_id,
        "amount":cart.get_line_total,
        "username":"Afrogulio",
        "phone_number":"0783262616",
        "is_live":False,
        # "cancel_url": "afrogulio.co.tz/canceled"
        }}
    response = requests.post(url,  headers=headers, json=payload)
    # print(response.json())
    response =response.json()
    # print(response['code'])
    return redirect(response['payment_url'])

def reconcilliation(request):
    payload = {"api":170, "code":103,"data":{
        "api_key":key
        }
    }
    response = requests.post(url, headers=headers, json=payload)
    print(response.json())
    response =response.json()
    print(response['code'])


import datetime
class Task():

    def __init__(self, task, priority, deadline=0):
        self.task = task
        self.priority = priority
        self.deadline = deadline
        self.date = datetime.datetime.now()
        self.id = int(self.get_id()) +1

    def get_id(self):
        with open('../homework 4/id_counter', 'w') as id_file:
            return id_file.read().strip()

    def update_id(self):
        with open('../homework 4/id_counter', 'w') as id_file:
            id_file.write(self.id)
if __name__ == '__main__':
    t1 = Task(1,1)
    t2 = Task(2,2)
    print(Task.ID)


# -*- encoding: utf-8 -*-

from odoo import api, models
import logging

_logger = logging.getLogger(__name__)
class ReporteCompras(models.AbstractModel):
    _name = 'report.l10n_gt_extra.reporte_compras'

    def lineas(self, datos):
        totales = {}

        totales['num_facturas'] = 0
        totales['compra'] = {'exento': 0, 'neto': 0, 'iva': 0, 'total': 0}
        totales['servicio'] = {'exento': 0, 'neto': 0, 'iva': 0, 'total': 0}
        totales['importacion'] = {'exento': 0, 'neto': 0, 'iva': 0, 'total': 0}
        totales['combustible'] = {'exento': 0, 'neto': 0, 'iva': 0, 'total': 0}
        totales['compras'] = {'bienes': 0}
        totales['total'] = 0
        totales['resumen'] = {'exento': 0, 'neto': 0, 'iva': 0, 'total': 0}
        totales['pequenio_contribuyente'] = 0

        journal_ids = [x for x in datos['diarios_id']]
        facturas = self.env['account.invoice'].search([
            ('state', 'in', ['open', 'paid', 'in_payment']),
            ('journal_id', 'in', journal_ids),
            ('date', '<=', datos['fecha_hasta']),
            ('date', '>=', datos['fecha_desde']),
        ], order='date_invoice, reference')

        lineas = []
        for f in facturas:
            totales['num_facturas'] += 1

            tipo_cambio = 1
            if f.currency_id.id != f.company_id.currency_id.id:
                total = 0
                for l in f.move_id.line_ids:
                    if l.account_id.id == f.account_id.id:
                        total += l.credit - l.debit
                tipo_cambio = abs(total / f.amount_total)

            tipo = 'FACT'
            if f.type != 'in_invoice':
                tipo = 'NC'
            if f.partner_id.pequenio_contribuyente:
                tipo += ' PEQ'

            linea = {
                'estado': f.state,
                'tipo': tipo,
                'fecha': f.date_invoice,
                #'serie': f.journal_id.code,
                'serie': f.provider_invoice_serial or '',
                # 'numero': f.reference or '',
                #'numero': f.move_name or '',
                'numero': f.provider_invoice_number or '',
                'proveedor': f.partner_id,
                'compra': 0,
                'compra_exento': 0,
                'servicio': 0,
                'servicio_exento': 0,
                'combustible': 0,
                'combustible_exento': 0,
                'importacion': 0,
                'importacion_exento': 0,
                'importacion_iva': 0,
                'compra_iva': 0,
                'servicio_iva': 0,
                'combustible_iva': 0,
                'base': 0,
                'iva': 0,
                'total': 0
            }
            is_compra = False
            is_service = False
            is_mix = False
            is_import = False
            is_gas = False
            flag_gas = False

            for linea_factura in f.invoice_line_ids:
                precio = (linea_factura.price_unit *
                          (1-(linea_factura.discount or 0.0)/100.0)) * tipo_cambio
                if tipo == 'NC':
                    precio = precio * -1

                tipo_linea = f.tipo_gasto

                if linea_factura.invoice_line_tax_ids:
                    for tax in linea_factura.invoice_line_tax_ids:
                        if tax.sat_tax_type == 'gas':
                            if is_compra or is_service:
                                is_mix = True
                                flag_gas = True
                            else:
                                is_gas = True
                                flag_gas = True
                    if flag_gas:
                        flag_gas = False

                if f.tipo_gasto == 'mixto':

                    if linea_factura.product_id.type == 'product' or linea_factura.product_id.type == 'consu':
                        tipo_linea = 'compra'
                    if linea_factura.product_id.type == 'service':
                        tipo_linea = 'servicio'
                    if is_gas:
                        tipo_linea = 'combustible'

                if f.tipo_gasto == 'combustible':
                    tipo_linea = 'combustible'

                r = linea_factura.invoice_line_tax_ids.compute_all(
                    precio, currency=f.currency_id, quantity=linea_factura.quantity, product=linea_factura.product_id, partner=f.partner_id)

                linea['base'] += r['base']
                totales[tipo_linea]['total'] += r['base']
                #totales[tipo_linea]['total'] += precio * linea_factura.quantity

                if len(linea_factura.invoice_line_tax_ids) > 0:
                    linea[tipo_linea] += r['base']
                    if tipo_linea == 'compra':
                        totales['compras']['bienes'] += r['base']
                    totales[tipo_linea]['neto'] += r['base']
                    totales['resumen']['neto'] += r['base']
                    for i in r['taxes']:
                        if i['id'] == datos['impuesto_id'][0]:
                            linea['iva'] += i['amount']
                            linea[tipo_linea+'_iva'] += i['amount']
                            totales[tipo_linea]['iva'] += i['amount']
                            totales['resumen']['iva'] += r['base']
                            totales[tipo_linea]['total'] += i['amount']
                        elif i['amount'] > 0:

                            if tipo_linea == 'combustible':
                                linea['compra_exento'] += i['amount']
                                totales[tipo_linea]['exento'] += i['amount']
                                totales[tipo_linea]['total'] += i['amount']
                            else:
                                linea[tipo_linea+'_exento'] += i['amount']
                                totales[tipo_linea]['exento'] += i['amount']
                                totales[tipo_linea]['total'] += i['amount']
                            totales['resumen']['exento'] += i['amount']

                else:
                    linea[tipo_linea+'_exento'] += r['base']
                    totales[tipo_linea]['exento'] += r['base']
                    totales['resumen']['exento'] += r['base']
                    totales[tipo_linea]['total'] += r['base']

                linea['total'] += precio * linea_factura.quantity

                totales['total'] += precio * linea_factura.quantity

            if f.partner_id.pequenio_contribuyente:
                totales['pequenio_contribuyente'] += linea['base']

            lineas.append(linea)

        return {'lineas': lineas, 'totales': totales}

    @api.model
    def _get_report_values(self, docids, data=None):
        return self.get_report_values(docids, data)

    @api.model
    def get_report_values(self, docids, data=None):
        model = self.env.context.get('active_model')
        docs = self.env[model].browse(self.env.context.get('active_ids', []))

        diario = self.env['account.journal'].browse(data['form']['diarios_id'][0])

        return {
            'doc_ids': self.ids,
            'doc_model': model,
            'data': data['form'],
            'docs': docs,
            'lineas': self.lineas,
            'direccion': diario.direccion and diario.direccion.street,
        }


from ReText import settings
import re

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor, QFont, QSyntaxHighlighter, QTextCharFormat

reHtmlTags     = re.compile('<[^<>@]*>')
reHtmlSymbols  = re.compile(r'&#?\w+;')
reHtmlStrings  = re.compile('"[^"<]*"(?=[^<]*>)')
reHtmlComments = re.compile('<!--[^<>]*-->')
reAsterisks    = re.compile(r'(?<!\*)\*[^ \*][^\*]*\*')
reUnderline    = re.compile(r'(?<!_|\w)_[^_]+_(?!\w)')
reDblAsterisks = re.compile(r'(?<!\*)\*\*((?!\*\*).)*\*\*')
reDblUnderline = re.compile(r'(?<!_|\w)__[^_]+__(?!\w)')
reTrpAsterisks = re.compile(r'\*{3,3}[^\*]+\*{3,3}')
reTrpUnderline = re.compile('___[^_]+___')
reMkdHeaders   = re.compile('^#.+')
reMkdLinksImgs = re.compile(r'(?<=\[)[^\[\]]*(?=\])')
reMkdLinkRefs  = re.compile(r'(?<=\]\()[^\(\)]*(?=\))')
reBlockQuotes  = re.compile('^ *>.+')
reReSTDirects  = re.compile(r'\.\. [a-z]+::')
reReSTRoles    = re.compile(':[a-z]+:')
reTextileHdrs  = re.compile(r'^h[1-6][()<>=]*\.\s.+')
reTextileQuot  = re.compile(r'^bq\.\s.+')
reWords        = re.compile('[^_\\W]+', flags=re.UNICODE)
reSpacesOnEnd  = re.compile(r'\s+$', flags=re.UNICODE)

defaultColorScheme = {
	'htmlTags': Qt.darkMagenta,
	'htmlSymbols': Qt.darkCyan,
	'htmlStrings': Qt.darkYellow,
	'htmlComments': Qt.gray,
	'markdownLinks': Qt.blue,
	'blockquotes': Qt.darkGray,
	'restDirectives': Qt.darkMagenta,
	'restRoles': Qt.darkRed,
	'whitespaceOnEnd': QColor(0xf0, 0xf0, 0xd2)
}
colorScheme = {}

def updateColorScheme(settings=settings):
	settings.beginGroup('ColorScheme')
	for key in defaultColorScheme:
		if settings.contains(key):
			colorScheme[key] = settings.value(key, type=QColor)
		else:
			colorScheme[key] = defaultColorScheme[key]
	settings.endGroup()

updateColorScheme()

class ReTextHighlighter(QSyntaxHighlighter):
	dictionary = None
	docType = None

	def highlightBlock(self, text):
		patterns = (
			# regex,         color,            font style,    italic, underline
			(reHtmlTags,     'htmlTags',       QFont.Bold),                     # 0
			(reHtmlSymbols,  'htmlSymbols',    QFont.Bold),                     # 1
			(reHtmlStrings,  'htmlStrings',    QFont.Bold),                     # 2
			(reHtmlComments, 'htmlComments',   QFont.Normal),                   # 3
			(reAsterisks,    None,             QFont.Normal,  True),            # 4
			(reUnderline,    None,             QFont.Normal,  True),            # 5
			(reDblAsterisks, None,             QFont.Bold),                     # 6
			(reDblUnderline, None,             QFont.Bold),                     # 7
			(reTrpAsterisks, None,             QFont.Bold,    True),            # 8
			(reTrpUnderline, None,             QFont.Bold,    True),            # 9
			(reMkdHeaders,   None,             QFont.Black),                    # 10
			(reMkdLinksImgs, 'markdownLinks',  QFont.Normal),                   # 11
			(reMkdLinkRefs,  None,             QFont.Normal,  True,   True),    # 12
			(reBlockQuotes,  'blockquotes',    QFont.Normal),                   # 13
			(reReSTDirects,  'restDirectives', QFont.Bold),                     # 14
			(reReSTRoles,    'restRoles',      QFont.Bold),                     # 15
			(reTextileHdrs,  None,             QFont.Black),                    # 16
			(reTextileQuot,  'blockquotes',    QFont.Normal),                   # 17
			(reAsterisks,    None,             QFont.Bold),                     # 18
			(reDblUnderline, None,             QFont.Normal,  True),            # 19
		)
		patternsDict = {
			'Markdown': (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13),
			'reStructuredText': (4, 6, 14, 15),
			'Textile': (0, 5, 6, 16, 17, 18, 19),
			'html': (0, 1, 2, 3)
		}
		# Syntax highlighter
		if self.docType in patternsDict:
			for number in patternsDict[self.docType]:
				pattern = patterns[number]
				charFormat = QTextCharFormat()
				charFormat.setFontWeight(pattern[2])
				if pattern[1] != None:
					charFormat.setForeground(colorScheme[pattern[1]])
				if len(pattern) >= 4:
					charFormat.setFontItalic(pattern[3])
				if len(pattern) >= 5:
					charFormat.setFontUnderline(pattern[4])
				for match in pattern[0].finditer(text):
					self.setFormat(match.start(), match.end() - match.start(), charFormat)
		for match in reSpacesOnEnd.finditer(text):
			charFormat = QTextCharFormat()
			charFormat.setBackground(colorScheme['whitespaceOnEnd'])
			self.setFormat(match.start(), match.end() - match.start(), charFormat)
		# Spell checker
		if self.dictionary:
			charFormat = QTextCharFormat()
			charFormat.setUnderlineColor(Qt.red)
			charFormat.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)
			for match in reWords.finditer(text):
				finalFormat = QTextCharFormat()
				finalFormat.merge(charFormat)
				finalFormat.merge(self.format(match.start()))
				if not self.dictionary.check(match.group(0)):
					self.setFormat(match.start(), match.end() - match.start(), finalFormat)


import csv

from django.conf import settings
from django.core.management.base import BaseCommand

from reviews.models import Comment, Review
from users.models import User

class Command(BaseCommand):
    def handle(self, *args, **options) -> None:
        print('Importing data from:', settings.DATA_IMPORT_LOCATION)

        with open(
            f'{settings.DATA_IMPORT_LOCATION}/comments.csv',
            'r',
            encoding='utf-8-sig',
        ) as csv_file:
            csv_file = csv.reader(csv_file)
            next(csv_file)

            for counter, line in enumerate(csv_file):
                id = line[0]
                review = Review.objects.get(id=line[1])
                text = line[2]
                author = User.objects.get(id=line[3])
                pub_date = line[4]

                if not Comment.objects.filter(
                    review=review,
                    text=text,
                    author=author,
                    pub_date=pub_date,
                ).exists():
                    obj = Comment()
                    obj.id = id
                    obj.review = review
                    obj.text = text
                    obj.author = author
                    obj.pub_date = pub_date
                    obj.save()

                    print(obj)

            print(f'Import complete, imported {counter} products')


#!/usr/bin/env python3

import os
import os.path
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

email = ''
password = ''
to = '@kindle.com'
group = 5

def send_email(s, i, paths):
    msg = MIMEMultipart()
    msg['Subject'] = 'Kindle docs ' + str(i)
    print(msg['Subject'])
    msg['From'] = email
    msg['To'] = to

    for path in paths:
        msg.attach(new_attachment(path))

    msg = msg.as_string()
    s.sendmail(email, to, msg)
    print()

def new_attachment(path):
    with open(path, 'rb') as book:
        attachment = MIMEBase('application', 'x-mobipocket-ebook')
        attachment.set_payload(book.read())
        fname = filename(path)
        print('  ', fname)
        attachment.add_header('Content-Disposition', 'attachment', filename=fname)
        encoders.encode_base64(attachment)
    return attachment

def filename(path):
    basename = os.path.basename(path)
    name, ext = os.path.splitext(basename)
    title, author = name.rsplit('-', 1)
    return title.strip() + ext

def main():
    s = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    s.login(email, password)

    paths = []
    for root, dirs, files in os.walk('books'):
        for file in files:
            paths.append(os.path.join(root, file))

    i = 1
    for start in range(0, len(paths), group):
        send_email(s, i, paths[start:start+group])
        i += 1

    s.quit()

if __name__ == '__main__':
    main()


import json
from pytils.translit import slugify

from django.core.management.base import BaseCommand

from my import models

def load_json():
    with open('./delivery/data/data.txt', encoding='utf-8') as f:
        data = json.loads(f.read())
    return data

class Command(BaseCommand):
    help = 'load data from old site'

    def handle(self, *args, **options):
        data = load_json()
        for item in data:
            cat = models.Categories.objects.create(name=item['cat'], slug=slugify(item['cat']))
            for menu in item['menu']:
                sc = models.SubCategories.objects.filter(name=menu['subcategory'].replace('  ', ' ')).first()
                if menu['subcategory']=='гр.':
                    menu['subcategory'] =None
                else:
                    menu['subcategory'] = sc or\
                                        models.SubCategories.objects.create(
                                                                        name=menu['subcategory'].replace('  ',' '),
                                                                        slug=slugify(menu['subcategory']))

                if menu['image']:
                    image =  f"media/old/{menu['image']}"
                else:
                    image = None
                m = models.Products(
                    name=menu['name'],
                    slug=slugify(menu['name']+menu['subcategory'].__str__()),
                    category=cat,
                    description=menu['description'],
                    price=menu['price'],
                    image=image,
                    subcategory = menu['subcategory']
                )
                m.save()


import streamlit as st
from langchain.callbacks.base import BaseCallbackHandler
from langchain.chains import RetrievalQAWithSourcesChain
from langchain.chains import RetrievalQA
from langchain.chains import ConversationalRetrievalChain,LLMChain, RetrievalQA

import os
from dotenv import load_dotenv
import qdrant_client

load_dotenv()

openai_api_type = os.getenv("OPENAI_API_TYPE")
openai_api_key = os.getenv("OPENAI_API_KEY")
openai_api_base = os.getenv("OPENAI_API_BASE")
openai_api_version = os.getenv("OPENAI_API_VERSION")
deployment_name = os.getenv("OPENAI_COMPLETION_DEPLOYMENT_NAME")
completion_model = os.getenv("OPENAI_COMPLETION_MODEL")
embedding_name = os.getenv("OPENAI_EMBEDDING_DEPLOYMENT_NAME")
qdrant_url = os.getenv("QDRANT_URL")
qdrant_collection = os.getenv("QDRANT_COLLECTION")

st.set_page_config(page_title="Movie expert AI", page_icon="ðŸ“º")

def settings():

    # Vectorstore
    from langchain.vectorstores import Qdrant
    from langchain.embeddings import OpenAIEmbeddings
    embeddings_model = OpenAIEmbeddings(
        deployment=embedding_name,
        chunk_size=1
    )

    client = qdrant_client.QdrantClient(
        qdrant_url
    )

    vector_store = Qdrant(
        client=client, collection_name=qdrant_collection,
        embeddings=embeddings_model,
    )

    # LLM
    from langchain.llms import AzureOpenAI
    from langchain.chat_models import AzureChatOpenAI
    llm = AzureChatOpenAI(
        openai_api_type = openai_api_type,
        openai_api_version = openai_api_version,
        openai_api_base = openai_api_base,
        openai_api_key = openai_api_key,
        deployment_name = deployment_name,
        model_name=completion_model
    )

    retriever = vector_store.as_retriever(search_type="mmr")

    return retriever, llm

class StreamHandler(BaseCallbackHandler):
    def __init__(self, container, initial_text=""):
        self.container = container
        self.text = initial_text

    def on_llm_new_token(self, token: str, **kwargs) -> None:
        self.text += token
        self.container.info(self.text)

class PrintRetrievalHandler(BaseCallbackHandler):
    def __init__(self, container):
        self.container = container.expander("Context Retrieval")

    def on_retriever_start(self, query: str, **kwargs):
        self.container.write(f"**Question:** {query}")

    def on_retriever_end(self, documents, **kwargs):
        # self.container.write(documents)
        for idx, doc in enumerate(documents):
            source = doc.metadata["source"]
            self.container.write(f"**Results from {source}**")
            self.container.text(doc.page_content)

st.sidebar.image("movieagent.jpg")
st.header("`Movie AI Agent`")
st.info("`I am an AI that can answer questions about all the movies you told me earlier.`")

# Make retriever and llm
if 'retriever' not in st.session_state:
    st.session_state['retriever'], st.session_state['llm'] = settings()
retriever = st.session_state.retriever
llm = st.session_state.llm

# User input
question = st.text_input("`Ask a question:`")

if question:
    qa_sources_chain = RetrievalQAWithSourcesChain.from_chain_type(llm, retriever=retriever)
    retrieval_streamer_cb = PrintRetrievalHandler(st.container())
    answer = st.empty()
    stream_handler = StreamHandler(answer, initial_text="`Answer:`\n\n")
    result = qa_sources_chain({"question": question},callbacks=[retrieval_streamer_cb, stream_handler])
    print(result)
    answer.info('`Answer:`\n\n' + result['answer'])
    st.info('`Sources:`\n\n' + result['sources'])


#encoding=utf8
import nltk,json
from tool import ner_stanford,cut_stanford

def get_stanfrod_ner_nodes(parent):
    date = ''
    org = ''
    loc = ''
    for node in parent:
        if type(node) is nltk.Tree:
            if node.label() == 'DATE':
                date = date+' '+''.join([i[0] for i in node])
            elif node.label() == 'ORGANIZATIONL':
                org = org+' '+''.join([i[0] for i in node])
            elif node.label() == 'LOCATION':
                loc = loc+' '+''.join([i[0] for i in node])

    if len(date) > 0 or len(org) > 0 or len(loc) > 0:
        return {'date':date,'org':org,'loc':loc}
    else:
        return {}

def grammer_parse(raw_sentence=None,file_object=None):
    if len(raw_sentence.strip()) < 2:
        return False
    grammer_dict = {
        'stanford_ner_drop':r"""
        DATE:{<DATE>+<MISC>?<DATE>*}
        {<DATE>+}
        {<TIME>+}
        ORGANIZATIONL:{<ORGANIZATION>+}
        LOCATION:{<LOCATION|STATE_OR_PROVINCE|CITY|COUNTRY>+}
        """
    }

    stanford_ner_drop_rp = nltk.RegexpParser(grammer_dict['stanford_ner_drop'])
    try:
        stanford_ner_drop_result = stanford_ner_drop_rp.parse(ner_stanford(raw_sentence))
        # 通过stanfordnlp的ner之后，再通过nltk的parse进行构建语法树
    except:
        print('the error sentence is {}'.format(raw_sentence))
    # 如果try里面的语句没有问题，就执行else语句
    else:
        stanford_keep_drop_dict = get_stanfrod_ner_nodes(stanford_ner_drop_result)
        if len(stanford_keep_drop_dict) > 0:
            file_object.write(json.dumps(stanford_keep_drop_dict,skipkeys=False,
            ensure_ascii=False,
            check_circular=True,
            allow_nan=True,
            cls=None,
            indent=4,
            separators=None,
            default=None,
            sort_keys=False
            ))

分词、词性标注以及命名实体识别/命名实体识别/rules.py


from django.shortcuts import render
from itertools import chain
from author.models import Author
from .models import Book
from django.contrib.auth.decorators import login_required
from operator import attrgetter

@login_required(login_url='login')
def searchBooks(request):
    query = request.GET.get('query')
    if not query:
        return showBooks(request)
    by_id = None
    try:
        by_id = Book.objects.all().filter(id=int(query))
    except:
        print('no int')
    by_name = Book.objects.all().filter(name__icontains=query)
    by_description = Book.objects.all().filter(description__icontains=query)
    by_author_name = Book.objects.all().filter(authors__name__icontains=query)
    by_author_surname = Book.objects.all().filter(authors__surname__icontains=query)
    if by_id:
        result_list = list(chain(by_id, by_name, by_description, by_author_name, by_author_surname))
    else:
        result_list = list(chain(by_name, by_description, by_author_name, by_author_surname))
    book_author_zip = zip(result_list, get_authors(result_list))
    return render(request, 'book/book.html', {'book_author_zip': book_author_zip})

@login_required(login_url='login')
def showBooks(request):
    books_query = Book.objects.order_by('id')
    book_author_zip = zip(books_query, get_authors(books_query))
    return render(request, 'book/book.html', {'book_author_zip': book_author_zip})

def get_authors(books):
    authors_list = []
    if type(books) == Book:
        print(True)
        book = books
        print(book.authors)
        if list(book.authors.all()):
            for author in book.authors.all():
                authors_list.append(author)
        else:
            authors_list.append(None)
    else:
        for book in books:
            temp = []
            if list(book.authors.all()):
                for author in book.authors.all():
                    temp.append(author)
                authors_list.append(temp)
            else:
                authors_list.append(None)
    return authors_list

def showOrderedBooks(request, pk):
    books_query = Book.objects.order_by(pk)
    book_author_zip = zip(books_query, get_authors(books_query))
    return render(request, 'book/book.html', {'book_author_zip': book_author_zip})

def showSpecificBook(request, id):
    book_obj = Book.objects.get(id=id)
    return render(request, 'book/specificBook.html', {'book': book_obj, 'authors': get_authors(book_obj)})

@login_required(login_url='login')
def createBook(request):
    if request.user.role != 1:
        text = 'You have no permission to view this page'
        return render(request, 'authentication/denied.html', {'text': text})
    if request.method == 'POST':
        name = request.POST.get('name')
        description = request.POST.get('description')
        count = request.POST.get('count')
        Book.create(name=name, description=description, count=count)
    return render(request, 'book/create_book.html')


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

import pandas as pd
import numpy as np
import re
import config
import logging

logger = logging.getLogger('QQ')

def changeFace(ans):
	ans = str(ans)
	val = re.sub("Face Amount: ", ' ', ans)
	val = re.sub(",", ' ', val)
	val = str(re.sub(" ", '', val))
	index = (val.find('$'))
	if(index != -1):
		val = val[1:]

	#val = int(val)
	return (val)

def changeWt(ans):
	ans = str(ans)
	val = re.sub("#", 'lb', ans)
	val = re.sub("lbs", 'lb', val)
	val = re.sub("Pounds", 'lb', val)
	val = re.sub("pounds", 'lb', val)
	val = str(re.sub(" ", '', val))
	if(re.search('KG|Kg|kg', val, re.I | re.U)):
		x = re.findall(r'\d+', ans)
		val = str(int(int(x[0]) * 2.2)) + 'lb'
	#val = int(val)
	return (val)

def changeHeight(ans):
	ans = str(ans)
	val = re.sub("Feet", '.', ans)
	val = str(re.sub(" ", '', val))
	if(re.search('inches|Inches', val, re.I | re.U) or val=='nan'):
		val = re.sub("Inches", '', val)
		return (val)
	else:
		val = re.sub("Inches", '', val)
		val = re.sub("Inch", '', val)
		val = val + '0'
		return (val)

def changePT(ans):
	ans = str(ans)
	val = re.sub("Product Type", '', ans)
	val = re.sub(":", '', val)
	val = str(re.sub(" ", '', val))
	return (val)

def emailfirst(doc):
	if(type(doc) == str):
		mails = doc.split(";")
		return str(mails[0])
	else:
		doc = ""
		return doc
def human_format(num):
    num = float('{:.3g}'.format(num))
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num /= 1000.0
    return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), ['', 'K', 'M', 'B', 'T'][magnitude])

def standardize_famnt(doc):
	if(doc.isdigit()):
		number = int(doc)
		num = human_format(number)
		return(num)
	else:
		return(doc)

def preprocess_main(file):

	logger.info(">> Start - Preprocessing. Standardize Face amount, Weight... etc")
	logger.debug("Opening -" + config.regex_processed_csv)
	df = pd.read_csv(config.regex_processed_csv, encoding='UTF-8')
	df = df.drop(columns=['Year_of_Birth'])
	of = pd.read_csv(file, encoding='UTF-8')
	of['recepientemail'] = of['recepientemail'].apply(emailfirst)
	df['recepientemail'] = of['recepientemail'].values

	logger.info("Standardize Weight")
	df['Weight'] = df['Weight'].apply(changeWt)

	logger.info("Standardize Height")
	df['Height'] = df['Height'].apply(changeHeight)

	logger.info("Standardize Face amount")
	df['Face Amount'] = df['Face Amount'].apply(changeFace)

	logger.info("Standardize Product Type")
	df['Product Type'] = df['Product Type'].apply(changePT)
	df['Face Amount'] = df['Face Amount'].apply(standardize_famnt)
	# print(df['Face Amount'])

	#print(df)
	df.to_csv(config.preprocessed_csv, index=False, encoding="utf-8")
	logger.info("<< End - Preprocess")

preprocess_main(config.raw_data_csv)


from sqlalchemy import between

from nanohttp import context, HTTPBadRequest

class FilteringMixin:
    @classmethod
    def filter_by_request(cls, query=None):
        # noinspection PyUnresolvedReferences
        query = query or cls.query

        # noinspection PyUnresolvedReferences
        for c in cls.iter_dict_columns():
            # noinspection PyUnresolvedReferences
            json_name = cls.get_dict_key(c)
            if json_name in context.query:
                value = context.query[json_name]
                query = cls._filter_by_column_value(query, c, value)

        return query

    @classmethod
    def _filter_by_column_value(cls, query, column, value):
        import_value = getattr(cls, 'import_value')
        if not isinstance(value, str):
            raise HTTPBadRequest()

        if value.startswith('^') or value.startswith('!^'):
            value = value.split(',')
            not_ = value[0].startswith('!^')
            first_item = value[0][2 if not_ else 1:]
            items = [first_item] + value[1:]
            items = [i for i in items if i.strip()]
            if not len(items):
                raise HTTPBadRequest('Invalid query string: %s' % value)
            expression = column.in_([import_value(column, j) for j in items])
            if not_:
                expression = ~expression

        elif value.startswith('~'):
            values = value[1:].split(',')
            start, end = [import_value(column, v) for v in values]
            expression = between(column, start, end)

        elif value == 'null':
            expression = column.is_(None)
        elif value == '!null':
            expression = column.isnot(None)
        elif value.startswith('!'):
            expression = column != import_value(column, value[1:])
        elif value.startswith('>='):
            expression = column >= import_value(column, value[2:])
        elif value.startswith('>'):
            expression = column > import_value(column, value[1:])
        elif value.startswith('<='):
            expression = column <= import_value(column, value[2:])
        elif value.startswith('<'):
            expression = column < import_value(column, value[1:])
        elif value.startswith('%~'):
            expression = column.ilike('%%%s%%' % import_value(column, value[2:]))
        elif value.startswith('%'):
            expression = column.like('%%%s%%' % import_value(column, value[1:]))
        else:
            expression = column == import_value(column, value)

        return query.filter(expression)


"""manosBackend URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin

#Por ver
from rest_framework import routers
from apps.apiREST.views import *
router = routers.DefaultRouter()
router.register(r'^userDOC',UserViewSet)
router.register(r'^workerDOC',WorkerViewSet)
router.register(r'^addressDOC',AddressViewSet)
router.register(r'^commentDOC',CommentViewSet)
router.register(r'^categoryDOC',CategoryViewSet)
router.register(r'^subcategoryDOC',SubcategoryViewSet)
router.register(r'^jobrequestDOC',JobRequestViewSet)
router.register(r'^photoDOC',PhotoViewSet)
router.register(r'^jobapplicationDOC',JobApplicationViewSet)

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('apps.apiREST.urls')),
	url(r'^',include(router.urls)),
]


from helper import *
from data import game_data

if __name__ == "__main__":
    """
    Prints battleship info and rules
    Instantiates two player objects. If is_computer=True, that player will act as a computer
    Plays battleship between the two players with ships in data.json
    """
    print_battleship_info()

    player = Player(name=input(f"Your name: "), is_computer=False)
    computer = Player(name="Computer", is_computer=True)
    data = game_data

    play_battleship(player, computer, data)


import calendar
from datetime import datetime as dt
from datetime import timedelta as td

"""
Python utility library for payroll calendars - weekly, biweekly, semimonthly
and monthly

https://payroll.unca.edu/sites/default/files/2016%20Payroll%20Calendar.pdf`
"""

def add_one_month(t):
    """Return a `datetime.date` or `datetime.datetime` (as given) that is
    one month earlier.

    Note that the resultant day of the month might change if the following
    month has fewer days:

        >>> add_one_month(datetime.date(2010, 1, 31))
        datetime.date(2010, 2, 28)
    """
    one_day = td(days=1)
    one_month_later = t + one_day
    while one_month_later.month == t.month:  # advance to start of next month
        one_month_later += one_day
    target_month = one_month_later.month
    while one_month_later.day < t.day:  # advance to appropriate day
        one_month_later += one_day
        if one_month_later.month != target_month:  # gone too far
            one_month_later -= one_day
            break
    return one_month_later

def next_sunday(date):
    if date.weekday() == 6:
        next_sunday = date
    else:
        day = date
        while day < date + td(days=7):
            day = day + td(days=1)

            if day.weekday()== 6:
                break
        next_sunday = day
    return next_sunday

def previous_monday(date):
    if date.weekday() == 0:
        return date
    else:
        day = date
        while day > date - td(days=7):
            day = day - td(days=1)

            if day.weekday()== 0:
                break
        previous_monday = day
    return previous_monday

def current_week(date):
    period_start = previous_monday(date)
    period_end = next_sunday(date)
    return period_start, period_end

def current_month(date):
    period_start = dt(year=date.year,
                      month=date.month,
                      day=1)

    period_end = add_one_month(dt(year=date.year, month=date.month, day=1)) - td(days=1)
    return period_start, period_end

def last_monday_previous_year(date):
    jan1 = dt(year=date.year, month=1, day=1)
    mon = jan1
    while mon.weekday() != 0:

        mon = mon - td(days=1)
    return mon

def first_biweek_of_year(date):
    return last_monday_previous_year(dt.now()), \
        last_monday_previous_year(dt.now()) + td(days=13)

def next_biweek(start, end):
    return start + td(14), end + td(14)

def next_week(start, end):
    return start + td(7), end + td(7)

def next_month(start, end):
    if start.month != end.month:
        print('start and end month are different')
    if start.month < 12:
        return (dt(year=start.year, month=start.month + 1, day=start.day),
                dt(year=end.year, month=end.month + 1, day=calendar.monthrange(end.year, end.month + 1)[1]))
    else:
        return (dt(year=start.year + 1, month=1, day=start.day),
                dt(year=end.year + 1, month=1, day=calendar.monthrange(end.year, 1)[1]))

def next_semimonth(start, end):
    if end.day == 15:

        if end.month < 12:
            return (dt(year=start.year, month=start.month, day=16),
                    dt(year=end.year, month=end.month + 1 if end.month < 12 else 1, day=1) -
                    td(days=1))
        else:
            if end.day < 16:
                return (dt(year=end.year, month=end.month, day=16),
                        dt(year=end.year, month=end.month, day=calendar.monthrange(end.year, end.month)[1]))
    else:
        if end.month < 12:
            return (dt(year=start.year, month=start.month + 1, day=1),
                    dt(year=end.year, month=end.month + 1, day=15))
        else:
            return (dt(year=start.year + 1, month=1, day=1),
                    dt(year=start.year + 1, month=1, day=15))

def current_semimonth(date):
    if date.day < 16:
        return (dt(year=date.year, month=date.month, day=1),
                dt(year=date.year, month=date.month, day=15))
    else:
        return (dt(year=date.year, month=date.month, day=16),
                dt(year=date.year, month=date.month, day=calendar.monthrange(date.year, date.month)[1]))

def current_biweek(date):
    start, end = first_biweek_of_year(date)
    if date >= start and date <= end + td(days=1):
        return start, end

    else:
        while date >= start and date >= end + td(days=1):
            start, end = next_biweek(start, end)

    return start, end

# todo: write unittest for weeks_between_dates


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Marvin with a simple menu to start up with.
Marvin doesnt do anything, just presents a menu with some choices.
You should add functinoality to Marvin.

"""

def meImagex():
    """
    Store my ascii image in a separat variabel as a raw string
    """
    return r"""
          ,     ,
         (\____/)
          (_oo_)
            (O)
          __||__    \)
       []/______\[] /
       / \______/ \/
      /    /__\
     (\   /____\
    """
def meImageBIG():
    """
    store
    """
    return r"""
              ____               ____
             /,,,,\_____________/,,,,\
            |,(  )/,,,,,,,,,,,,,\(  ),|
             \__,,,,___,,,,,___,,,,__/
               /,,,/(')\,,,/(')\,,,\
              |,,,,___ _____ ___,,,,|
              |,,,/   \\o_o//   \,,,|
              |,,|       |       |,,|
              |,,|   \__/|\__/   |,,|
               \,,\     \_/     /,,/
                \__\___________/__/
  ________________/,,,,,,,,,,,,,\________________
 / \,,,,,,,,,,,,,,,,___________,,,,,,,,,,,,,,,,/ \
(   ),,,,,,,,,,,,,,/           \,,,,,,,,,,,,,,(   )
 \_/____________,,/             \,,____________\_/
               /,/    *SWEET*    \,\
              |,|                 |,|
              |,|     *DREAMS*    |,|
              |,|                 |'|
              |,|        O        |,|
               \,\               /,/
               /,,\_____________/,,\
              /,,,,,,,,,,,,,,,,,,,,,\
             /,,,,,,,,_______,,,,,,,,\
            /,,,,,,,,/       \,,,,,,,,\
           /,,,,,,, /         \,,,,,,,,\
          /_____,,,/           \,,,_____\
         //     \,/             \,/     \\
         \\_____//               \\_____//                              """
def meImage():
    """
    store
    """
    return r"""
              ____               ____
             /,,,,\_____________/,,,,\
            |,(  )/,,,,,,,,,,,,,\(  ),|
             \__,,,,___,,,,,___,,,,__/
               /,,,/(')\,,,/(')\,,,\
              |,,,,___ _____ ___,,,,|
              |,,,/   \\o_o//   \,,,|
              |,,|       |       |,,|
              |,,|   \__/|\__/   |,,|
               \,,\     \_/     /,,/
                \__\___________/__/
                             """
def menu():
    """
    Display the menu with the options that Marvin can do.
    """
    print(chr(27) + "[2J" + chr(27) + "[;H")
    print(meImage())
    print("Hi, I'm Bjorn. Been there done that. \nWhat can U do you for mee?")
    print("1) Present yourself to Björn.")
    print("2) Inform Bjorn of your age.")
    print("3) Your wheight on the moon.")
    print("4) Minutes to hours.")
    print("5) Convert from C to F.")
    print("6) Repeat something a number of times")
    print("7) Ten random numbers in a range .. . .")
    print("8) Sum and avargae when you quit")
    print("9) Points to grades 'learning curve'")
    print("10) Circle area from radius  ")
    print("11) a triangle long leg  hypotenuse")
    print("12) compare two numbers in a logrow ")
    print("13) Guess the number ")
    print("14) Talk2Marvin ")
    print("15) Randomize ")
    print("16) Find quotas ")
    print("17) myInventory")
#    print("17) Some dialogue")
    print("q) Quit.")

def myNameIs():
    """
    Read the users name and say hello to Marvin.
    """
    name = input("What is your name? ")
    print("\nMarvin says:\n")
    print("Hello %s - your awesomeness!" % name)
    print("What can I do you for?!")

#from datetime import datetime
def myAgeIs():
    """
    Read user bd
    """

    age = input("Pls enter your age: ")
    try:
        age = int(age)
    except ValueError:
        print("Try to enter a number please")
    #    main()
      #  quit()
    print("Your age is more than: " +  str(age * 365 * 24 * 3600) +  " secs")

def myMoonWeight():
    '''moon weight
    '''
    moonWeight = int(input("Pls enter weight: "))
    print("Yout weight on the moon are: " + str(moonWeight * 0.166) + " kg or moonKg")

def myMinutes2Hours():
    '''
    time conversion
    '''

    mins2Hours = int(input("Pls enter minutes: "))
    print("Is is: " + str(int(mins2Hours / 60)) + " hours and " + str(int(mins2Hours % 60)) + " minutes")

def myDegC2F():
    """
    Convert Deg C to deg F
    """
    degC = int(input("Pls enter your agedeg C convert to deg F: "))
    print(str(degC) + "C...Converts to: " + str(degC * 9 / 5 + 32) + " deg F")

def myWordBoost():
    """
    repeat as wanted
    """
    nums = int(input("repete this many times: "))
    st = input("what to repete? ")
    i = 0
    while i < nums:
        i += 1
        print(st)

def myRandGen():
    """
    Generate 10 random in range
    """
    import random
    minn = float(input("Random from "))
    maxx = float(input("random too  "))
    randy = ''
    i = 0
    while i < 10:
        y = float(random.uniform(minn, maxx))
        randy = ', \n' + str(y) + randy
        i += 1
        #print("check01")

   # print(randy)
    randy2 = randy[1:]
    print(randy2)
#    print("check02")
#    print("check03")
#
def mySumAvg():
    """
    -----
    """

    summa = 0
    count = 0
    x = 0
    while x != 'done':
        x = float(x)
        summa = summa + x
        count += 1
        x = input("feed me:!! with a number. END is 'done': ")
    count -= 1

    print("The sum of " + str(count) + ' numbers is: ' + str(summa) + ' and the avg is ' + str(summa / count))

def myP2G():
    """
    convert points to a grade
    """

    try:
        points = input('Enter points: ')
        points = float(points)
        if points > 1.0:
            print('To many points')
        elif points >= 0.9:
            print('Grade: A')
        elif points >= 0.8:
            print('Grade: B')
        elif points >= 0.7:
            print('Grade: C')
        elif points >= 0.6:
            print('Grade: D')
        elif points < 0.6:
            print('Grade: F')
    except ValueError:
        print('Bad score')

def myCircleArea():
    """ circle area """
    import math
    radius = float(input("set radius "))
    area = radius**2 * math.pi
    print("The area of a cirkle with radius: " + str(radius) + " is " + str(area))
def myPyt():
    """ hptnusa """
    import math
    leg1 = float(input("Leg1: "))
    leg2 = float(input("Leg2: "))
    hy = math.sqrt(leg1**2 + leg2**2)
    print("Hyppe: " + str(hy))

def mySameSame():
    """ ss """
    first = input("First: ")

    while first != "done":
        after = input("Next: ")
        if after < first:
            print("Is less ")
            x = after
            after = first
            first = x
           # print(after, '  ' , first)
        elif after > first:
            print("Is more ")
            x = after
            after = first
            first = x
            #print(after, '  ' , first)
        else:
            print(" same--same ")

def guessNumber():
    """ guess a number in a range """
    # This is a guess the number game.
    import random

    guessesTaken = 0

    print('Hello! What is your name?')
    myName = input()

    number = random.randint(1, 100)
    print('Well, ' + myName + ', I am thinking of a number between 1 and 100.')

    while guessesTaken < 6:
        print('Take a guess.') # There are four spaces in front of print.
        guess = input()
        guess = int(guess)

        guessesTaken = guessesTaken + 1

        if guess < number:
            print('Your guess is too low.') # There are eight spaces in front of print.

        if guess > number:
            print('Your guess is too high.')

        if guess == number:
            break

    if guess == number:
        guessesTaken = str(guessesTaken)
        print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')

    if guess != number:
        number = str(number)
        print('Nope. The number I was thinking of was ' + number)

def myDate():
    """ Date feeling ??? """
#    import time
    import datetime
    import random

    moods = ["happy", "sad", "depressed",
             "angry", "annoyed", "bored",
             "confused", "excited", "lonely", "undefined"]
#   smilies = [":)", ":(", ":D",
#              ":/", ":|", ":'(",
#              ":O", ":@", ":P", ":3"]
    #smiley = random.choice(smilies)

    yy = datetime.datetime.now()
    stre = str(yy)
    temp01 = stre.split('.')
    temp01 = str(temp01[0])
    timeDate = temp01.split(' ')

    lines = [line.rstrip('\n') for line in open('filen.txt')]

    mood = random.choice(moods)
    xxx = moods.index(mood)
    yyy = len(mood)

    flyt = round((3.1416 * xxx / yyy), 3)

    print(lines[0] +  ' '  + timeDate[0] +  lines[1]\
          + ' '  +  timeDate[1] + lines[2]\
         + ' ' + mood  + lines[3] + ' ' + \
        str(xxx + 1) + ' '  + lines[4] +\
        ' ' + str(flyt))

def myHoppsan():
    """ kaos """
    import random

    snurr = input("Give me a word to randomize!  ")
#    lengt = len(snurr)
    print("Starting with:   ", snurr)
    snurr = ''.join(random.sample(snurr, len(snurr)))
    print("Retards to       ", str(snurr))

def myQuotas():
    """ Some Quotas """
    import random
#    inputFile = open('quotes.txt', 'r+')
    data = [line.strip() for line in open("quotes.txt", 'r')]
    tester = input(" YES, do you have a good question??  ")
    if "citat" or "quota" or "mos" or "bjvi13" in tester:
        aa = random.randint(0, len(data))
        #print(aa)
        print("Enjoy ", aa, ": ", data[aa])
#    elif "quota" in tester:
#        aa = random.randint(0, len(data))
#        print("Citat num ", aa, ": ", data[aa])

    else:
        print("NOPE!")

    """
def myInventory():
    """ """Discuss inventory with marvin """ """

    # the name of the file
    filename = "test.txt"

    print("Commands")
    command = input("choose from: inv,  inv pick flower, inv drop flower  ")
    with open(filename) as filehandle:
        line = filehandle.readline()  #1
        line = line.rstrip('\n') #1B

    if command == 'inv':
            print("items in invertory: ", line)

    if command == 'write':
        # write line into file
        print("Command taken: ", command)

        with open("test.txt", "w") as fhand:
            print("Start-------------")
            for i in range(0, 4, 1):
                writed = str(i) + "  Thisaaa is a test."
                print("---  ", writed)
                fhand.write(writed)

    """

def myDia():
    """ some small talk """
   # data = [line.strip() for line in open("xtraquotes.txt", 'r')]
    #data2 =
#    data = data.split('#')
    fhand = open("xtraquotes.txt", 'r')
    print(fhand)
    count = 0
    for line in fhand:
        line = line.rstrip()
#        if not line.startswith('#'):
#            #ALL LINESprint(line)
#  #      print(line)
        count += 1

    print("Line count: ", count)

    print("test\nav\nCR\n")

    #data2 =

   # print(data)
    hello = ['Hej själv! ', 'Trevligt att du bryr dig om mig. ',
             'Det var länge sedan någon var trevlig mot mig. ',
             'Halloj, det ser ut att bli mulet idag. ']
#    with open('hi.txt', 'r') as content_file:
#        content = content_file.read()

#    lines = [line.strip('\n') for line in open('hi.txt')]
    i = 0
    while i < len(hello):
        print(hello[i])
        i += 1

    print("Hello")
def myInventory(guestName):
    """ Discuss inventory with marvin """

#    status = False

    # the name of the file
    filename = "test.txt"

    #print("Commands")
    command = input("choose from these commands: \n inv,  inv drop flower, inv pick flower,  add X, drop X ")

##def myReadOne(filename)
    line = myReadOneLine(filename)
# returns the read line somewhat cleaned

#------------------------------------------------
# make a list of inventory
    items_as_list = line.split(",") #2

    #***errata = mySanityCheck(items_as_list)
    #print("errata before action: ", errata)
    # add item to the list

    ipfx = command.split()
    if ipfx[0] == 'add':
    #    print("adder")
        items_as_list.append(ipfx[1])
        myWriter(items_as_list, filename)
        print('I added ' + ipfx[1] + ' for U ' + guestName)
        print(mySanityCheck(items_as_list))
        myInventory(guestName)

    if  ipfx[0] == 'drop':
        #***sss = items_as_list
        eee = [i for i, j in enumerate(items_as_list) if j == ipfx[1]]
        if len(eee) > 0:
            items_as_list.remove(ipfx[1])
        myWriter(items_as_list, filename)
        print('I dropped ' +  ipfx[1] + ' ' + guestName)
        print(mySanityCheck(items_as_list))
        myInventory(guestName)

    if command == 'inv':
        print("All items in invertory: ", line)
        print("Thnx4Checking  " + guestName)
        myInventory(guestName)

    if command == 'inv pick flower':
        ipf = command.split()
        #print(ipf)
        items_as_list.append('flower')
        myWriter(items_as_list, filename)
        print('I ' + ipf[1] + 'ed ' +  ipf[2] + ' ' + guestName)
        print(mySanityCheck(items_as_list))
        myInventory(guestName)

    if command == 'inv drop flower':
        ipf = command.split()
        #print(ipf)
        #***sss = items_as_list
        eee = [i for i, j in enumerate(items_as_list) if j == ipf[2]]
        if len(eee) > 0:
            items_as_list.remove(ipf[2])
        myWriter(items_as_list, filename)
        print('I ' + ipf[1] + 'ped ' +  ipf[2] + ' ' + guestName)
        print(mySanityCheck(items_as_list))
        myInventory(guestName)

# the updated items list (items_as_list)
#is braught into a string (list_as_str)
# and written to filenamne
#***    list_as_str = myWriter(items_as_list, filename)

def myReadOneLine(filename):
    """ rad one line from file and strip and split """
    with open(filename) as filehandle:
        line = filehandle.readline()  #1
        line = line.rstrip('\n') #1B
# split the line into a list on the comma ","
#    items_as_list = line.split(",") #2
    return line

def myWriter(items_as_list, filename):
    """
    takes items as a list
    (items_as_list) and brings the items
    inte a comma separateds string
    which is written into a file (filename)
    returns the comma separated string
    """
    # join the list into a string with a comma ","" between every item
    #
    list_as_str = ",".join(items_as_list) #3
    # show what the string looks like after join
    print("Inventory:  ", list_as_str)
    # write the line to the file
    with open(filename, "w") as filehandle:
        filehandle.write(list_as_str)
    return list_as_str

def mySanityCheck(items_as_list):
    """ check the number of items in backpack """
        # How many??
    numOfItemsInList = len(items_as_list)
        #RANK!
    if numOfItemsInList == 4:
        errata = "Hi there NOW you are on maximun  " \
                    " pls do not add more items \n You have " \
                    + str(numOfItemsInList) + " items in inventory"
    #    print("Hi there you are already on maximun pls do not att more items")
    elif numOfItemsInList == 5:
        errata = "UR naughty pls remove something you have " + str(numOfItemsInList) + " in inventory"
    #    print("UR naughty pls remove something")
    elif numOfItemsInList >= 6:
        errata = "NOW UR really bad with " \
                + str(numOfItemsInList) + " in inventory"
    #    print("UR naughty pls remove something")
    else:
        errata = "You are good with " + str(numOfItemsInList) + " in inventory"

    return errata
def myGuestCheckin():
    """ Say hello to guest """
    name = input("PLS give me your name: ")
    return name


from PIL import Image

class getPixelsInImage():

    def __init__(self, image):
        self.image = image

    def getPixelsHealth(self):
        im = Image.open(self.image)
        red = 0

        for pixel in im.getdata():
            if pixel == (219, 79, 79):
                red += 1

        if red > 0:
            return red
        else:
            return 0

    def getPixelsMana(self):
        im = Image.open(self.image)
        blue = 0

        for pixel in im.getdata():
            if pixel == (83, 80, 218):
                blue += 1

        if blue > 0:
            return blue
        else:
            return 0


from urllib.request import urlopen
import requests
from bs4 import BeautifulSoup
import urllib.request

class Sandro:
    def get_info(self, page_url):
        response = requests.get(page_url)
        html = response.text
        soup = BeautifulSoup(html, 'html.parser')
        name = soup.select_one("#title").text
        #price = soup.select_one("span.price-sales").text.strip()
        images = soup.select("img", attrs={"class": "productthumbnail lazyload loaded"})

        return {'name': name, 'images': images}

    def save_images(self, info):
        img_list =[]
        for img in info['images']:
            if "data-hires" in img.attrs:
                img_url = img["data-hires"]
                img_list.append(img_url)
            else:
                pass

        for index, url in enumerate(img_list):
            with urlopen(url) as f:
                with open(f"{info['name']}_{str(index)}.jpg", 'wb') as h:
                    img = f.read()
                    h.write(img)

class DIOR:
    def get_info(self, page_url):
        response = requests.get(page_url)
        html = response.text
        soup = BeautifulSoup(html, 'html.parser')
        name = soup.select_one('span.multiline-text.Titles_title__PAVsd').text
        images = soup.select('img')
        reference = soup.select_one('p.Titles_ref__7LPN1').text.split(':')[1].strip()

        return {'name': name, 'images': images, 'reference': reference}

    def save_images(self, info):
        img_list =[]
        for img in info['images']:
            if info['reference'] in img['src']:
                try:
                    img_list.append(img['src'])
                except:
                    pass

        for index, url in enumerate(img_list):
            with urlopen(url) as f:
                with open(f"{info['name']}_{str(index)}.jpg", 'wb') as h:
                    img = f.read()
                    h.write(img)

class CELINE:
    def get_info(self, page_url):
        response = requests.get(page_url)
        html = response.text
        soup = BeautifulSoup(html, 'html.parser')

        name = soup.select_one('span.o-product__title-truncate.f-body--em').text
        images = soup.find_all('button','m-thumb-carousel__img')
        reference = soup.select_one('span.product-id.d-none').text

        return {'name': name, 'images': images, 'reference': reference}

    def save_images(self, info):
        n = 1
        for img in info['images']:
            imgUrl = img.find('img')['data-src-zoom']
            urllib.request.urlretrieve(imgUrl, info['name'] + str(n)+'.jpg')
            n += 1

        # for index, url in enumerate(img_list):
        #     with urlopen(url) as f:
        #         with open(f"./results/{info['name']}_{str(index)}.jpg", 'wb') as h:
        #             img = f.read()
        #             h.write(img)


#!/usr/bin/env python
'Explore project results'

##   Copyright (C) 2010 University of Texas at Austin
##
##   This program is free software; you can redistribute it and/or modify
##   it under the terms of the GNU General Public License as published by
##   the Free Software Foundation; either version 2 of the License, or
##   (at your option) any later version.
##
##   This program is distributed in the hope that it will be useful,
##   but WITHOUT ANY WARRANTY; without even the implied warranty of
##   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##   GNU General Public License for more details.
##
##   You should have received a copy of the GNU General Public License
##   along with this program; if not, write to the Free Software
##   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
import sys

try:
    import wx
except:
    sys.stderr.write('Please install wx!\n\n')
    sys.exit(1)

from signal import *
import os, commands

class TestFrame(wx.Frame):
    def __init__(self):
        cwd = os.getcwd()
        proj = os.path.join(
            os.path.basename(os.path.dirname(os.path.dirname(cwd))),
            os.path.basename(os.path.dirname(cwd)),
            os.path.basename(cwd))
        wx.Frame.__init__(self,None,-1,proj)
        self.pid = 0

        signal(SIGINT,self.handler)

        sizer = wx.BoxSizer(wx.VERTICAL)

        panel = wx.Panel(self,-1)
        buttons = self.set_buttons(panel)
        panel.SetSizer(buttons)
        buttons.Fit(self)

        sizer.Add(panel,0,wx.ALL|wx.EXPAND,5)

        self.results = commands.getoutput("scons -s results").split()
        c = self.results[-1:][0]
        if (c < 'A' or c > 'z'):
            self.results.pop() # remove scons junk

        self.flip = {}

        panel = wx.Panel(self,-1)
        rsizer = wx.FlexGridSizer(rows=len(self.results),cols=2,vgap=5)

        for fig in self.results:
            self.flip[fig] = False

            title = self.get_title(fig)
            if title:
                title = '%s [%s]' % (fig,title)
            else:
                title = fig
            cb = wx.CheckBox(panel,-1,title)
            cb.Bind(wx.EVT_CHECKBOX, self.set_flip)
            rsizer.Add(cb,0,0)

            b = wx.Button(panel,-1,'show')
            self.Bind(wx.EVT_BUTTON,self.show(fig),b)
            rsizer.Add(b,0,0)

        panel.SetSizer(rsizer)
        rsizer.Fit(self)

        sizer.Add(panel,0,wx.ALL|wx.EXPAND,15)

        self.SetSizer(sizer)
        sizer.Fit(self)

    def set_flip(self, event):
        sender = event.GetEventObject()
        fig = sender.GetLabel()
        self.flip[fig] = sender.GetValue()

    def set_buttons(self,panel):
        bsizer = wx.BoxSizer(wx.HORIZONTAL)

        bcycl = wx.Button(panel,-1,'Cycle')
        bcycl.SetBackgroundColour('light yellow')
        self.Bind(wx.EVT_BUTTON,self.showall,bcycl)
        bsizer.Add(bcycl,0,wx.ALL,5)

        bflip = wx.Button(panel,-1,'Flip')
        bflip.SetBackgroundColour('light green')
        self.Bind(wx.EVT_BUTTON,self.flipit,bflip)
        bsizer.Add(bflip,0,wx.ALL,5)

        bquit = wx.Button(panel,-1,'Quit')
        bquit.SetBackgroundColour('pink')
        self.Bind(wx.EVT_BUTTON,self.quit,bquit)
        bsizer.Add(bquit,0,wx.ALL,5)

        return bsizer

    def quit(self,event):
        sys.exit(0)

    def handler(self,signum,frame):
        sys.stdout.write("\n%s: aborting...\n" % sys.argv[0])
        if self.pid:
            os.kill(self.pid,SIGINT)
        sys.exit(1)

    def showall(self,event):
        self.pid = os.fork()
        if not self.pid:
            for fig in self.results:
                os.system ("pscons %s.view" % fig)
        sys.exit()

    def flipit(self,event):
        figs = map(lambda x: 'Fig/%s.vpl' % x,
                   filter(lambda y: self.flip[y],self.results))
        if figs:
            self.pid = os.fork()
            if not self.pid:
                command = "sfpen %s" % ' '.join(figs)
                sys.stderr.write(command+'\n')
                os.system (command)
                sys.exit()

    def show(self,fig):
        def showfig(event):
            os.system("pscons %s.view" % fig)
        return showfig

    def get_title(self,fig):
        vpl = os.path.join('Fig',fig+'.vpl')
        if not os.path.isfile(vpl):
            return None
        txt = os.path.join('Fig',fig+'.txt')
        os.system('sfpldb < %s > %s' % (vpl,txt))
        titles = []
        try:
            plot = open(txt,'r')
            for line in plot:
                if line[0] != '[':
                    continue
                line2 = plot.next()
                if line2[:5] != 'title':
                    continue
                while line2:
                    line2 = plot.next()
                    if line2[0] == 'G':
                        title = plot.next()
                        titles.append(title.rstrip())
                        break
            title = ','.join(titles)
        except:
            title = None

        plot.close()
        os.unlink(txt)
        return title

if __name__=='__main__':
    app = wx.App()
    frame = TestFrame()
    frame.Show()

    app.MainLoop()


'''
Created on 12 de abr de 2017

@author: Thiago
'''
from analytics import minhash_util
from math import sqrt

def check(dirToScreens):
    import os
    from os import path
    files = []
    for f in os.listdir(dirToScreens):
        if f.endswith(".csv"):
            files.append(f)
    return files

def classifica(att1,att2,gabarito,rev=False):
    for resp in gabarito:
        resposta = resp
        if (rev):
            resposta = [resp[1],resp[0]]

        if (att1 == resposta[0]) and (att2 == resposta[1]):
            return 'TM'
    return 'FM'

def corrigeLinha(att1,dt1,att2,dt2,gabarito):
    if dt1 == 'ncvoters' or dt2 == 'ncvoters':
        if dt1 == 'ncvoters':
            return classifica(h1,h2,gabarito),False
        else:
            return classifica(h1,h2,gabarito,rev=True),True

    if dt1 == 'medicare' or dt2 == 'medicare':
        if dt1 == 'medicare':
            return classifica(h1,h2,gabarito),False
        else:
            return classifica(h1,h2,gabarito,rev=True),True

def buscaTrueNonMatch(file1,data_length1,dt1,file2,data_length2,dt2,espelho_gabartio,gabarito,inv_flag):
    a = set()
    for g in gabarito:
        tupla = tuple(g)
        if inv_flag:
            tupla = (g[1],g[0])

        a.add(tupla)
    z = a - espelho_gabarito

    r = []
    if len(z) != 0:
        for e in z:
            tnm = [p1['filename'],data_length1,dt1,e[0],p2['filename'],data_length2,dt2,e[1],0,'TNM']
            r.append(tnm)

    return r

if __name__ == '__main__':
    profile_dir = 'data/profile/plano_bigram/'
    outfile_prefix =  'data/profile/resumo_'

    filenames = check(profile_dir)
    first = True
    dt_set = set()

    for fname in filenames:
        dt_set.add(minhash_util.getDataType(fname))

    outfiles = {}
    headers = {}
    for element in dt_set:
        file = outfile_prefix + str(element) +'_plano_bigram.csv'
        outfiles[element] =  open(file,'w')
        headers[element] = True

    for fname in filenames:
        dt = minhash_util.getDataType(fname)
        outfile = outfiles[dt]

        file = profile_dir + fname
        with open(file) as infile:
            header = infile.readline()
            data = infile.readline()
            if headers[dt]:
                headers[dt] = False
                outfile.write(header)
            else:
#                 print(data)
                outfile.write(data)

    print("Done profile")
    profile_dir = 'data/profile/'
    filenames = check(profile_dir)

    profiles = []
    for fname in filenames:
        file = profile_dir + fname
#        p = minhash_util.readProfile2Dict(file)
        pp = minhash_util.readFullProfile2Dict(file)
        for p in pp:
            profiles.append(p)

    from util import config

    #####debug
    count_debug = 0

    result = []
    result_enchaced = []

    for p1 in profiles:
        dt1 = minhash_util.getDataType(p1['filename'])
        hs1 = config.getHeaders(dt1)
        data_length1 = p1['filename'].split('_')[3].split('.')[0]
#         print(p1['filename'])

        for p2 in profiles:
            dt2 = minhash_util.getDataType(p2['filename'])
            if dt1 != dt2:
                hs2 = config.getHeaders(dt2)
                data_length2 = p2['filename'].split('_')[3].split('.')[0]
                #gabarito
                gabarito = minhash_util.getGoldStandard(dt1,dt2)
                espelho_gabarito = set()

                for h1 in hs1[1:]:
                    for h2 in hs2[1:]:
                        u1 = float(p1['min_num_bigram_'+str(h1)])
                        u2 = float(p1['max_num_bigram_'+str(h1)])
#                         unique_vals_column_
                        w1 = float(p2['min_num_bigram_'+str(h2)])
                        w2 = float(p2['max_num_bigram_'+str(h2)])
                        #     min_num_1_
                        #     max_num_1_
                        u = (u1,u2)
                        w = (w1,w2)
                        u_inter_w = minhash_util.intercetion(u, w)

                        d = (minhash_util.vector_lenght(u) + minhash_util.vector_lenght(w))
                        if u_inter_w == 0:
                            sim_dl = 0
                        else:
                            if d == 0:
                                #alterado 1/
                                sim_dl = u_inter_w
                            else:
                                sim_dl = (2*u_inter_w)/d

                        if ( minhash_util.vector_lenght(u) == 0 ) or (minhash_util.vector_lenght(w) == 0):
                            if (minhash_util.vector_lenght(u) == minhash_util.vector_lenght(w) ):
                                cos_sim = 1
                            else:
                                cos_sim = u_inter_w / sqrt(minhash_util.vector_lenght(u) + minhash_util.vector_lenght(w))
                        else:
                            cos_sim = u_inter_w / sqrt(minhash_util.vector_lenght(u) * minhash_util.vector_lenght(w))

                        classificacao,inv_boolean = corrigeLinha(h1,dt1,h2,dt2, gabarito)
                        if sim_dl > 0:
                            #debug

                            if classificacao == 'TM':
                                espelho_gabarito.add( (h1,h2) )
                            rl = [p1['filename'],data_length1,dt1,h1,p2['filename'],data_length2,dt2,h2,sim_dl,classificacao]
                            result.append(rl)

                            ####debug
                            ######## enhaced
                            max_sim = max([sim_dl,cos_sim])
                            min_sim = min([sim_dl,cos_sim])

                            if (1 - min_sim/max_sim < 0.6):
                                count_debug += 1
                                erl = [p1['filename'],data_length1,dt1,h1,p2['filename'],data_length2,dt2,h2,((sim_dl+cos_sim)/2),classificacao]
                                result_enchaced.append(erl)
#                                 print("-----------")
#                                 print(h1,u)
#                                 print(h2,w)
#                                 print("sim_dl : " , sim_dl)
#                                 print("sim_cos : ", cos_sim)

                    #adiciona o True Non Match
                    tnm_list = buscaTrueNonMatch(p1['filename'],data_length1,dt1, p2['filename'],data_length2,dt2,
                                                 espelho_gabarito, gabarito , inv_boolean)

                #  adiciona os tnm ao resultado
                for tnm in tnm_list:
                    result.append(tnm)
                    result_enchaced.append(tnm)

    hs = ['file_1','data_length1','data_type_1','attribut_1','file_2','data_length2','data_type_2','attribut_2','sim_dl','classificacao']
    ofile = profile_dir + 'analytic.txt'
    config.write(ofile, hs, result)

    eofile = profile_dir + 'enchaced-analytic.txt'
    config.write(eofile, hs, result_enchaced)
    print("Done", count_debug)
#     print(result)


#!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
# All Functions created by ApTr13 for obtaining the results of a Swiss Tournamnet

import psycopg2
from contextlib import contextmanager

def connect():
    """Connect to the PostgreSQL database.  Returns a database connection."""
    try:
        return psycopg2.connect("dbname=tournament")
    except:
        print("Oops.... Connection Failed :(")

"""***
TRIED IMPLEMENTING THIS CURSOR FUNCTION AS SUGGESTED BY PROJECT REVIEWER...
BUT IT PRODUCED MANY ERRORS...
WILL SURELY WORKOUT function decorators & contextlib IN NEAR FUTURE..
THANKS... :D
***
@contextmanager
def get_cursor():
    DB = connect()
    a = DB.cursor()
    try:
        yield a
    except:
        print "Error connecting to Cursor in psql...."
    else:
        DB.commit()
    finally:
        a.close()
        DB.close()
"""

def deleteMatches():
    """Remove all the match records from the database."""
    DB = connect()
    a = DB.cursor()
    a.execute("DELETE FROM Matches")
    DB.commit()
    DB.close()

def deletePlayers():
    """Remove all the player records from the database."""
    DB = connect()
    a = DB.cursor()
    a.execute("DELETE FROM Players")
    DB.commit()
    DB.close()

def countPlayers():
    """Returns the number of players currently registered."""
    DB = connect()
    a = DB.cursor()
    a.execute("SELECT count(*) as num FROM Players")
    count = a.fetchall()
    DB.close()
    return count[0][0]

def registerPlayer(name):
    """Adds a player to the tournament database.

    The database assigns a unique serial id number for the player.  (This
    should be handled by your SQL database schema, not in your Python code.)

    Args:
      name: the player's full name (need not be unique).
    """
    DB = connect()
    a = DB.cursor()
    a.execute("INSERT INTO Players (Name) VALUES (%s)",(name,))
    DB.commit()
    DB.close()

def playerStandings():
    """Returns a list of the players and their win records, sorted by wins.

    The first entry in the list should be the player in first place, or a player
    tied for first place if there is currently a tie.

    Returns:
      A list of tuples, each of which contains (id, name, wins, matches):
        id: the player's unique id (assigned by the database)
        name: the player's full name (as registered)
        wins: the number of matches the player has won
        matches: the number of matches the player has played
    """
    """
        THIS QUERY WORKS ON VIEWS. TWO VIEWS *Wins* & *Loses*
        COMBINED TO GET RESULTS IN THE VIEW *Standings*
    """
    DB = connect()
    a = DB.cursor()
    a.execute("SELECT * FROM Standings")
    b = a.fetchall()
    DB.close()
    return b

def reportMatch(winner, loser):
    """Records the outcome of a single match between two players.

    Args:
      winner:  the id number of the player who won
      loser:  the id number of the player who lost
    """
    DB = connect()
    a = DB.cursor()
    a.execute("INSERT INTO Matches (WinID, LoseID) VALUES (%s,%s)",(winner, loser,))
    DB.commit()
    DB.close()

def swissPairings():
    """Returns a list of pairs of players for the next round of a match.

    Assuming that there are an even number of players registered, each player
    appears exactly once in the pairings.  Each player is paired with another
    player with an equal or nearly-equal win record, that is, a player adjacent
    to him or her in the standings.

    Returns:
      A list of tuples, each of which contains (id1, name1, id2, name2)
        id1: the first player's unique id
        name1: the first player's name
        id2: the second player's unique id
        name2: the second player's name
    """
    """
        FIRST A TEMPORARY VIEW *Swiss* IS CREATED, FROM WHICH
        THE GIVEN SELECT QUERY FILTERS THE PAIRINGS

        The Temporary view is created so that Serial number (Sr) can be used
        for the conditions in WHERE clause to create tuples with two ids &
        two names of players at nearly-equally position in table.
    """
    DB = connect()
    a = DB.cursor()
    a.execute("SELECT a.Id, a.Name, b.Id, b.Name FROM Swiss as a, Swiss as b WHERE b.Sr = a.Sr + 1 AND a.Sr%2 = 1 ")
    b = a.fetchall()
    DB.close()
    return b


""" https://leetcode.com/problems/minimum-speed-to-arrive-on-time/ """
from typing import List
from math import ceil

class Solution:
    def minSpeedOnTime(self, dist: List[int], hour: float) -> int:
        if len(dist) - 1 >= hour:
            return -1

        def find_time(speed: int) -> float:
            return sum(ceil(dist[i] / speed) for i in range(len(dist) - 1)) + dist[-1] / speed

        hi, lo = 1e7, 1
        while lo < hi:
            cur = int(lo + (hi - lo) / 2)
            ft = find_time(cur)
            if ft > hour:
                lo = cur + 1
            elif ft < hour:
                hi = cur
            else:
                return cur

        return cur if find_time(cur) <= hour else cur + 1

if __name__ == '__main__':
    tests = (
        ([1, 3, 2], 6),
        ([1, 3, 2], 2.7),
        ([1, 3, 2], 2.4),
        ([2, 1, 5, 4, 4, 3, 2, 9, 2, 10], 75.12),
        ([1, 1], 1.0),
    )
    for dist, time in tests:
        print(Solution().minSpeedOnTime(dist, time))


# type: ignore
import setuptools

# read description from README.md
with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()

data_files = []

setuptools.setup(
    name="zxlive",
    version="0.1",
    author="Aleks Kissinger",
    author_email="aleks0@gmail.com",
    description="An interactive tool for the ZX calculus",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/Quantomatic/zxlive",
    project_urls={
        "Bug Tracker": "https://github.com/Quantomatic/zxlive/issues",
    },
    license="Apache2",
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: Apache Software License",
        "Operating System :: OS Independent",
    ],
    packages=["zxlive"],
    package_data={'': ['*.svg']},
    data_files=data_files,
    install_requires=["PySide2>=5.14", "pyzx>=0.7.3"],
    python_requires=">=3.7",
    entry_points={'console_scripts': 'zxlive=zxlive.app:main'},
)


import harris
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

infile1 = '../Images/opencv-feature-matching-image.jpg'
infile2 = '../Images/opencv-feature-matching-template.jpg'
im1 = np.array(Image.open(infile1).convert('L'))
im2 = np.array(Image.open(infile2).convert('L'))

wid = 5
harrisim = harris.compute_harris_response(im1,5)
filtered_coords1 = harris.get_harris_points(harrisim,wid+1)
d1 = harris.get_descriptors(im1,filtered_coords1,wid)

harrisim = harris.compute_harris_response(im2,5)
filtered_coords2 = harris.get_harris_points(harrisim,wid+1)
d2 = harris.get_descriptors(im2,filtered_coords2,wid)

##print ('starting matching')
##matches = harris.match_twosided(d1,d2,threshold=0.5)
##plt.figure()
##plt.gray()
##harris.plot_matches(im1,im2,filtered_coords1,filtered_coords2,matches)
##plt.show()

##Testing with maximumPixelDistance
print ('starting matching')
matches = harris.match_twosided(d1,d2,threshold=0.1, maximumPixelDistance=5)
plt.figure()
plt.gray()
harris.plot_matches(im1,im2,filtered_coords1,filtered_coords2,matches)
plt.show()