# -*- coding: utf-8 -*-
from openerp.osv import osv, fields
from idvalidator import is_identification
from openerp.osv.fields import _column
from openerp.osv.orm import browse_null
from openerp.tools.translate import _
from openerp import netsvc, tools
import time
from openerp.osv.orm import browse_record

class inherit_pos_config(osv.Model):
    _name = "pos.config"
    _inherit = "pos.config"

    _columns = {
        "iface_printer_host": fields.char("Host para impresora fiscal"),
        "iface_printer_model": fields.char("Modelo de impresora fiscal")
    }

class inherit_res_partner(osv.Model):
    _name = "res.partner"
    _inherit = "res.partner"

    def _check_unique_ref(self, cr, uid, ids, context=None):
        partner = self.browse(cr, uid, ids, context=context)[0]
        if partner.customer:
            if partner.is_company and not partner.ref:
                return False
            elif partner.is_company and isinstance(partner.property_account_position, browse_null):
                return False
            elif partner.is_company and is_identification(partner.ref):
                return True
            elif partner.is_company is False:
                return True
        else:
            return True

    _constraints = [
        (osv.osv._check_recursion, 'You cannot create recursive Partner hierarchies.', ['parent_id']),
        (_check_unique_ref, u"Los datos fiscales no son valido revise RNC/Cédula y la posición fiscal", [u"Rnc/Cédula"]),
    ]

class inherit_sale_shop(osv.Model):
    _name = 'sale.shop'
    _inherit = 'sale.shop'

    _columns = {
        'fiscal_id': fields.many2one('account.journal', u'NCF Con valor fiscal', help=u"Facturas que Generan Crédito y Sustentan Costos y/o Gastos.", required=True),
        'final_id': fields.many2one('account.journal', u'NCF Consumidor final', help=u"Facturas para Consumidores Finales.", required=True),
        'especiales_id': fields.many2one('account.journal', u'NCF Regímenes Especiales', help=u"Regímenes Especiales de Tributación.", required=True),
        'gubernamentales_id': fields.many2one('account.journal', u'NCF Gubernamentales', help=u"Comprobantes Gubernamentales.", required=True),
        'notas_credito_id': fields.many2one('account.journal', u'NCF Notas de credito', help=u"Comprobantes Notas de credito.", required=True),
        'default_partner_id': fields.many2one('res.partner', u'Cliente de contado', help=u"Se asignara este cliente por defecto cuando "
                                                                                u"cuando se grabe la factura sin un cliente seleccionado.", required=True)
    }

class inherit_account_fiscal_position(osv.Model):
    _name = 'account.fiscal.position'
    _inherit = 'account.fiscal.position'

    def _get_fiscal_type(self, cursor, user_id, context=None):
        return (
            ("final", u"Facturas para Consumidores Finales"),
            ("fiscal", u"Facturas que Generan Crédito y Sustentan Costos y/o Gastos"),
            ("final_note", u"Nota de crédito a consumidor final"),
            ("fiscal_note", u"Nota de crédito con derecho a crédito fiscal"),
            ("special", u"Regímenes Especiales de Tributación"),
            ("gov", u"Comprobantes Gubernamentales"),
            ("informal", u"Proveedores Informales"),
            ("minor", u"Gastos Menores"),
        )

    _columns = {
        "fiscal_type": fields.selection(_get_fiscal_type, "Tipo de NCF")
    }

    def map_tax(self, cr, uid, fposition_id, taxes, context=None):
        result = set()
        if taxes and isinstance(taxes[0], int):
            fobj = self.browse(cr, uid, fposition_id)
            tax_obj = self.pool.get('account.fiscal.position.tax')

            for t in tax_obj.browse(cr, uid, taxes):
                ok = False
                for tax in fobj.tax_ids:
                    if tax.tax_src_id.id == t.id:
                        if tax.tax_dest_id:
                            result.add(tax.tax_dest_id.id)
                        ok=True
                if not ok:
                    result.add(t.id)
        else:
            if not taxes:
                return []
            if not fposition_id:
                return map(lambda x: x.id, taxes)
            for t in taxes:
                ok = False
                for tax in fposition_id.tax_ids:
                    if tax.tax_src_id.id == t.id:
                        if tax.tax_dest_id:
                            result.add(tax.tax_dest_id.id)
                        ok=True
                if not ok:
                    result.add(t.id)
        return list(result)

class pos_order(osv.Model):
    _inherit = "pos.order"

    _columns = {
        'state': fields.selection([('draft', 'New'),
                                   ('cancel', 'Cancelled'),
                                   ('paid', 'Paid'),
                                   ('done', 'Posted'),
                                   ('invoiced', 'Invoiced'),
                                   ('ipf', 'Impreso')],
                                  'Status', readonly=True),
        'refund': fields.char('Refund', size=64, select=True, readonly=True)

    }

    _defaults = {'refund': lambda *a: False}

    def create_from_ui(self, cr, uid, orders, context=None):
        order_ids = []
        lot_obj = self.pool.get('stock.production.lot')
        for tmp_order in orders:

            order = tmp_order['data']

            if order.get('lines'):
                for line in order['lines']:
                    l = line[2]
                    if l.get('prodlot_id'):
                        lot = {'name': l['prodlot_id'],
                               'product_id': l['product_id']}
                        lot_id = lot_obj.create(cr, uid, lot)
                        l.update({'prodlot_id': lot_id})
                        line[2] = l

            order_id = self.create(cr, uid, {
                'name': order['name'],
                'user_id': order['user_id'] or False,
                'session_id': order['pos_session_id'],
                'lines': order['lines'],
                'pos_reference':order['name'],
                'partner_id': order.get('partner_id')
            }, context)

            for payments in order['statement_ids']:
                payment = payments[2]
                self.add_payment(cr, uid, order_id, {
                    'amount': payment['amount'] or 0.0,
                    'payment_date': payment['name'],
                    'statement_id': payment['statement_id'],
                    'payment_name': payment.get('note', False),
                    'journal': payment['journal_id']
                }, context=context)

            if order['amount_return']:
                session = self.pool.get('pos.session').browse(cr, uid, order['pos_session_id'], context=context)
                cash_journal = session.cash_journal_id
                cash_statement = False
                if not cash_journal:
                    cash_journal_ids = filter(lambda st: st.journal_id.type == 'cash', session.statement_ids)
                    if not len(cash_journal_ids):
                        raise osv.except_osv( _('error!'),
                            _("No cash statement found for this session. Unable to record returned cash."))
                    cash_journal = cash_journal_ids[0].journal_id
                self.add_payment(cr, uid, order_id, {
                    'amount': -order['amount_return'],
                    'payment_date': time.strftime('%Y-%m-%d %H:%M:%S'),
                    'payment_name': _('return'),
                    'journal': cash_journal.id,
                }, context=context)

            order_ids.append(order_id)
            wf_service = netsvc.LocalService("workflow")
            wf_service.trg_validate(uid, 'pos.order', order_id, 'paid', cr)
        return order_ids

    def action_create_invoice(self, cr, uid, id, context=None):
        wf_service = netsvc.LocalService("workflow")
        inv_ref = self.pool.get('account.invoice')
        inv_line_ref = self.pool.get('account.invoice.line')
        product_obj = self.pool.get('product.product')

        inv_id = False
        order = self.pool.get('pos.order').browse(cr, uid, id, context=context)[0]
        partner_ref = order.partner_id.ref
        partner_name = order.partner_id.name

        shop = order.shop_id.id
        fiscal_type = order.partner_id.property_account_position.fiscal_type
        fiscal_position = order.partner_id.property_account_position.id or 2

        if fiscal_type == "gov" or fiscal_type == "special":
            fiscal_type = "fiscal"

        if not order.partner_id:
            raise osv.except_osv(_('Error!'), _('Debe de seleccionar un cliente!'))
        acc = order.partner_id.property_account_receivable.id
        invoice_type = "out_invoice"
        afecta = None
        if order.refund:
            invoice_type = "out_refund"
            afecta = context["afecta"] or None

        inv = {
            'name': order.name,
            'origin': order.name,
            'fiscal_position': fiscal_position,
            'account_id': acc,
            'journal_id': order.sale_journal.id or None,
            'type': invoice_type, #'out_invoice',
            'parent_id': afecta,
            'reference': order.name,
            'partner_id': order.partner_id.id,
            'comment': order.note or '',
            'currency_id': order.pricelist_id.currency_id.id, # considering partner's sale pricelist's currency
        }
        inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
        if not inv.get('account_id', None):
            inv['account_id'] = acc
        inv_id = inv_ref.create(cr, uid, inv, context=context)

        self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'}, context=context)

        for line in order.lines:
            if invoice_type == "out_refund":
                quantity = -line.qty
            else:
                quantity = line.qty
            inv_line = {
                'invoice_id': inv_id,
                'product_id': line.product_id.id,
                'quantity': quantity,
            }
            inv_name = product_obj.name_get(cr, uid, [line.product_id.id], context=context)[0][1]
            inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
                                                           line.product_id.id,
                                                           line.product_id.uom_id.id,
                                                           line.qty, partner_id = order.partner_id.id,
                                                           fposition_id=order.partner_id.property_account_position.id)['value'])
            if line.product_id.description_sale:
                inv_line['note'] = line.product_id.description_sale
            inv_line['price_unit'] = line.price_unit
            inv_line['discount'] = line.discount
            inv_line['name'] = inv_name
            inv_line['invoice_line_tax_id'] = [(6, 0, [x.id for x in line.product_id.taxes_id] )]
            inv_line_ref.create(cr, uid, inv_line, context=context)
        inv_ref.button_reset_taxes(cr, uid, [inv_id], context=context)
        wf_service.trg_validate(uid, 'pos.order', order.id, 'invoice', cr)
        wf_service.trg_validate(uid, 'account.invoice', inv_id, 'validate', cr)

        # Ejecuta el signal para generar la factura definitiva
        wf_service.trg_validate(uid, 'account.invoice', inv_id, 'invoice_open', cr)
        current_invoice = inv_ref.browse(cr, uid, inv_id)

        return [inv_id, current_invoice.number, partner_ref, fiscal_type, partner_name, shop, uid]

    def create_picking(self, cr, uid, ids, context=None):
        """Create a picking for each order and validate it."""
        picking_obj = self.pool.get('stock.picking')
        partner_obj = self.pool.get('res.partner')
        move_obj = self.pool.get('stock.move')

        for order in self.browse(cr, uid, ids, context=context):
            if not order.state=='draft':
                continue
            addr = order.partner_id and partner_obj.address_get(cr, uid, [order.partner_id.id], ['delivery']) or {}
            picking_id = picking_obj.create(cr, uid, {
                'origin': order.name,
                'partner_id': addr.get('delivery',False),
                'type': 'out',
                'company_id': order.company_id.id,
                'move_type': 'direct',
                'note': order.note or "",
                'invoice_state': 'none',
                'auto_picking': True,
            }, context=context)
            self.write(cr, uid, [order.id], {'picking_id': picking_id}, context=context)
            location_id = order.shop_id.warehouse_id.lot_stock_id.id
            output_id = order.shop_id.warehouse_id.lot_output_id.id

            for line in order.lines:
                if line.product_id and line.product_id.type == 'service':
                    continue
                if line.qty < 0:
                    location_id, output_id = output_id, location_id

                move_obj.create(cr, uid, {
                    'name': line.name,
                    'product_uom': line.product_id.uom_id.id,
                    'product_uos': line.product_id.uom_id.id,
                    'picking_id': picking_id,
                    'product_id': line.product_id.id,
                    'product_uos_qty': abs(line.qty),
                    'product_qty': abs(line.qty),
                    'tracking_id': False,
                    'state': 'draft',
                    'location_id': location_id,
                    'location_dest_id': output_id,
                    'prodlot_id': line.prodlot_id and line.prodlot_id.id or False,
                }, context=context)
                if line.qty < 0:
                    location_id, output_id = output_id, location_id

            wf_service = netsvc.LocalService("workflow")
            wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
            picking_obj.force_assign(cr, uid, [picking_id], context)
        return True

    def _get_journal_id(self, fiscal_type, shop_id, refund):

        if refund:
            return shop_id.notas_credito_id.id
        elif fiscal_type == "final" or fiscal_type is None:
            return shop_id.final_id.id
        elif fiscal_type == "fiscal":
            return shop_id.fiscal_id.id
        elif fiscal_type == "special":
            return shop_id.especiales_id.id
        elif fiscal_type == "gov":
            return shop_id.gubernamentales_id.id
        else:
            return False

    def create(self, cr, uid, values, context=None):
        if not values["lines"]:
            raise osv.except_osv( _('Error!'),
                                  _("No puede grabar un pedido sin productos"))

        session = self.pool.get("pos.session").browse(cr, uid, [values["session_id"]], context)[0]
        if not values["partner_id"]:
            values["partner_id"] = session.config_id.shop_id.default_partner_id.id

        partner = self.pool.get("res.partner").browse(cr, uid, [values["partner_id"]], context)[0]
        fiscal_type = partner.property_account_position.fiscal_type or "final"
        shop_id = session.config_id.shop_id
        refund = values.get("refund", False)

        new_order = super(pos_order, self).create(cr, uid, values, context=context)
        self.write(cr, uid, [new_order],
                   {"sale_journal": self._get_journal_id(fiscal_type, shop_id, refund), "refund": refund},
                   context=context)
        return new_order

    def refund(self, cr, uid, ids, context=None):
        """Create a copy of order  for refund order"""
        clone_list = []
        line_obj = self.pool.get('pos.order.line')

        for order in self.browse(cr, uid, ids, context=context):
            current_session_ids = self.pool.get('pos.session').search(cr, uid, [
                ('state', '!=', 'closed'),
                ('user_id', '=', uid)], context=context)
            if not current_session_ids:
                raise osv.except_osv(_('Error!'), _('To return product(s), you need to open a session that will be used to register the refund.'))

            name = None
            if order.amount_total >= 0:
                name = order.name

            clone_id = self.copy(cr, uid, order.id, {
                'name': name,
                'session_id': current_session_ids[0],
                'date_order': time.strftime('%Y-%m-%d %H:%M:%S'),
                'refund': name
            }, context=context)
            clone_list.append(clone_id)

        for clone in self.browse(cr, uid, clone_list, context=context):
            for order_line in clone.lines:
                line_obj.write(cr, uid, [order_line.id], {
                    'qty': -order_line.qty
                }, context=context)

        new_order = ','.join(map(str,clone_list))
        abs = {
            #'domain': "[('id', 'in', ["+new_order+"])]",
            'name': _('Return Products'),
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'pos.order',
            'res_id':clone_list[0],
            'view_id': False,
            'context':context,
            'type': 'ir.actions.act_window',
            'nodestroy': True,
            'target': 'current',
        }
        return abs

    def set_printed(self, cr, uid, oid, context=None):
        oid = self.write(cr, uid, oid, {"state":"ipf"}, context)
        return oid

    def print_on_ipf(self, cr, uid, name, context=None):
        context = context or {}
        inv_obj = self.pool.get("account.invoice")

        inv_id = inv_obj.search(cr, uid, [["origin", "=", name]])
        ord_id = self.search(cr, uid, [["name", "=", name]])

        inv = inv_obj.browse(cr, uid, inv_id, context)[0]
        ord = self.browse(cr, uid, ord_id, context)[0]
        cashier = self.perm_read(cr, uid, ord_id,  details=True)[0].get("write_uid", None)[1]

        fiscal_type = ord.partner_id.property_account_position.fiscal_type or "final"

        if fiscal_type == "gov" or fiscal_type == "special":
            fiscal_type = "fiscal"

        afecta = None
        if ord.refund:
            afecta = inv.parent_id.number
            if fiscal_type == "final":
                fiscal_type = "nota_final"
            else:
                fiscal_type = "nota_fiscal"

        data = {
            'branch': ord.shop_id.id,
            'brand': ord.session_id.config_id.iface_printer_model,
            'client': ord.partner_id.name,
            'fiscal_type': fiscal_type,
            'ncf': inv.number,
            "afecta": afecta,
            'oid[]': ord.id,
            'receipt[cashier]': cashier,
            'receipt[change]': ord.amount_return,
            #'receipt[client]': u'',
            # 'receipt[company][company_registry]': u'false',
            'receipt[company][contact_address]': ord.company_id.street+u" "+ord.company_id.street2+u" "+u" "+ord.company_id.city,
            'receipt[company][email]': ord.company_id.email,
            'receipt[company][name]': ord.company_id.name,
            'receipt[company][phone]': ord.company_id.phone,
            'receipt[company][vat]': ord.company_id.vat,
            'receipt[company][website]': ord.company_id.website,
            'receipt[currency][accuracy]': inv.currency_id.accuracy,
            'receipt[currency][id]': inv.currency_id.id,
            'receipt[currency][position]': inv.currency_id.position,
            'receipt[currency][rounding]': inv.currency_id.position,
            'receipt[currency][symbol]': inv.currency_id.symbol,
            'receipt[date][date]': inv.date_invoice,
            # 'receipt[date][day]': u'0',
            # 'receipt[date][hour]': u'10',
            # 'receipt[date][minute]': u'52',
            # 'receipt[date][month]': u'11',
            # 'receipt[date][year]': u'2013',
            'receipt[invoice_id]': inv.id,
            'receipt[name]': ord.pos_reference,

            # 'receipt[orderlines][0][discount]': u'0',
            # 'receipt[orderlines][0][price]': u'1',
            # 'receipt[orderlines][0][price_display]': u'1',
            # 'receipt[orderlines][0][price_with_tax]': u'1',
            # 'receipt[orderlines][0][price_without_tax]': u'1',
            # 'receipt[orderlines][0][product_description]': u'false',
            # 'receipt[orderlines][0][product_description_sale]': u'false',
            # 'receipt[orderlines][0][product_name]': u'Productos sin referencia',
            # 'receipt[orderlines][0][quantity]': u'1',
            # 'receipt[orderlines][0][tax]': u'0',
            # 'receipt[orderlines][0][unit_name]': u'Unidad(es)',

            # 'receipt[paymentlines][0][amount]': u'1',
            # 'receipt[paymentlines][0][journal]': u'Efectivo (DOP)',

            'receipt[shop][name]': ord.shop_id.name,
            'receipt[subtotal]': u'1',
            'receipt[total_discount]': u'0',
            'receipt[total_paid]': ord.amount_paid,
            'receipt[total_tax]': inv.amount_tax,
            'receipt[total_with_tax]': inv.amount_total,
            'receipt[total_without_tax]': inv.amount_untaxed,
            'rnc': ord.partner_id.ref,
            'uid': uid
        }
        import pprint
        pp = pprint.PrettyPrinter(indent=4)

        pp.pprint(data)

class pos_order_line(osv.Model):
    _inherit = "pos.order.line"
    _columns = {
        'prodlot_id': fields.many2one('stock.production.lot', 'Serial No'),
    }

class product_product(osv.Model):
    _inherit = "product.product"
    _columns = {
        'serial_required': fields.boolean('Serial Number required in POS', help="Serial No. required in Point of Sale.")
    }

class sale_order(osv.Model):
    _inherit = "sale.order"

    def create_sales_order(self, cr, uid, orderline, customer_id, context=None):
        if context is None:
            context = {}
        sale_pool = self.pool.get('sale.order')
        prod_pool = self.pool.get('product.product')
        sale_line_pool = self.pool.get('sale.order.line')
        sale_no = ''
        sale = {}
        if customer_id:
            customer_id = int(customer_id)
            sale = {'partner_id': customer_id, 'partner_invoice_id': customer_id, 'partner_shipping_id': customer_id}
            part = sale_pool.onchange_partner_id(cr, uid, [], customer_id)['value']
            fiscal_position = part.get('fiscal_position')
            sale.update(part)
            sale_id = sale_pool.create(cr, uid, sale)
            sale_no = sale_pool.browse(cr, uid, sale_id).name
            #create sale order line
            sale_line = {'order_id': sale_id}
            for line in orderline:
                prod_rec = prod_pool.browse(cr, uid, line['product_id'])
                sale_line.update({'name': prod_rec.name or False,
                                  'product_id': prod_rec.id,
                                  'product_uom_qty':line['qty']})
                prod = sale_line_pool.product_id_change(cr, uid, [], sale['pricelist_id'],
                                                        prod_rec.id, qty=line['qty'], partner_id=customer_id,
                                                        fiscal_position=fiscal_position)['value']
                sale_line.update(prod)
                taxes = map(lambda a: a.id, prod_rec.taxes_id)
                if sale_line.get('tax_id'):
                    sale_line.update({'tax_id': [(6, 0, sale_line.get('tax_id'))]})
                else:
                    sale_line.update({'tax_id': [(6, 0, taxes)]})
                sale_line_pool.create(cr, uid, sale_line)
        return sale_no

class inherit_pos_session(osv.Model):
    _inherit = "pos.session"

    def _confirm_orders(self, cr, uid, ids, context=None):
        wf_service = netsvc.LocalService("workflow")

        for session in self.browse(cr, uid, ids, context=context):
            #order_ids = [order.id for order in session.order_ids if order.state == 'invoiced']

            #move_id = self.pool.get('account.move').create(cr, uid, {'ref' : session.name, 'journal_id' : session.config_id.journal_id.id, }, context=context)
            #self.pool.get('pos.order')._create_account_move_line(cr, uid, order_ids, session, move_id, context=context)

            for order in session.order_ids:
                if order.state not in ('paid', 'invoiced'):
                    raise osv.except_osv(
                        _('Error!'),
                        _("You cannot confirm all orders of this session, because they have not the 'paid' status"))
                else:
                    invoice_ref = self.pool.get("account.invoice")
                    wf_service.trg_validate(uid, 'pos.order', order.id, 'done', cr)
                    invoice_ref.write(cr, uid, invoice_ref.search(cr, uid, [("reference", "=", order.name)]), {'state':'paid'}, context=context)

        return True

# class account_invoice(osv.Model):
#     _inherits = "account.invoice"

class inherit_pos_make_payment(osv.osv_memory):
    _inherit = 'pos.make.payment'
    _description = 'Point of Sale Payment'

    def check(self, cr, uid, ids, context=None):
        """Check the order:
        if the order is not paid: continue payment,
        if the order is paid print ticket.
        """
        context = context or {}
        order_obj = self.pool.get('pos.order')

        obj_partner = self.pool.get('res.partner')
        active_id = context and context.get('active_id', False)

        order = order_obj.browse(cr, uid, active_id, context=context)
        amount = order.amount_total - order.amount_paid
        data = self.read(cr, uid, ids, context=context)[0]

        if order.refund:
            inv_obj= self.pool.get('account.invoice')
            refund_inv_ids = inv_obj.search(cr, uid, [("name", "=", order.refund)])
            context["afecta"] = refund_inv_ids[0]

        data['journal'] = data['journal_id'][0]

        if amount != 0.0:
            order_obj.add_payment(cr, uid, active_id, data, context=context)

        if order_obj.test_paid(cr, uid, [active_id]):
            wf_service = netsvc.LocalService("workflow")
            wf_service.trg_validate(uid, 'pos.order', active_id, 'paid', cr)

            #eneldo
            self.pool.get('pos.order').action_create_invoice(cr, uid, [order.id], context=context)

            return {'type': 'ir.actions.act_window_close'}
         ##self.print_report(cr, uid, ids, context=context)

        return self.launch_payment(cr, uid, ids, context=context)

import logging

_logger = logging.getLogger(__name__)

class publisher_warranty_contract(osv.Model):
    _inherit = 'publisher_warranty.contract'

    def update_notification(self, cr, uid, ids, cron_mode=True,
                            context=None):

        _logger.info("NO More Spying Stuff")

        return True

# Fix bug update location_id when onchange_warehouse_id
class purchase_order(osv.Model):
    _inherit = "purchase.order"

    def onchange_warehouse_id(self, cr, uid, ids, warehouse_id):
        if not warehouse_id:
            return {}
        warehouse = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id)
        self.write(cr, uid, ids, {'location_id': warehouse.lot_input_id.id}) # eneldo add this line
        return {'value':{'location_id': warehouse.lot_input_id.id, 'dest_address_id': False}}


import json
import requests
import datetime
#
import cherrypy

#html request
import requests
from cherrypy.lib import static
import os
from jinja2 import Environment, FileSystemLoader
from figo import FigoSession
import json

session = FigoSession("ASHWLIkouP2O6_bgA2wWReRhletgWKHYjLqDaqb0LFfamim9RjexTo22ujRIP_cjLiRiSyQXyt2kM1eXU2XLFZQ0Hro15HikJQT_eNeT_9XQ")

localDir = os.path.dirname(__file__)
absDir = os.path.join(os.getcwd(), localDir)

env = Environment(loader=FileSystemLoader('html'))

percentage=-0.01

class Landing_Page(object):
    @cherrypy.expose
    def index(self):
        tmpl = env.get_template('index.html')
        return tmpl.render(name="Apple")

    @cherrypy.expose
    def portfolio(self):
        tmpl = env.get_template('portfolio.html')
        return tmpl.render()

    @cherrypy.expose
    def transactionHistory(self):
        headers = {'Accept': 'application/json'}
        # Rest call towards the "John Snow" mock account on DB
        url = "https://007investment.table.core.windows.net:443/Transaction?sv=2016-05-31&si=Transaction-15EEC51E092&tn=transaction&sig=G%2BAfHj8oMMxKdTwj93q4KiR7tmnIPJdKkjwyHYdggpM%3D"
        response = requests.get(url, headers=headers)
        trans_j = response.json()
        all_transactions= []

        #Make a list of all transactions with the fields below ('Timestamp' etc.)
        for value in trans_j['value']:
                price_paid_long =(float(value['Price'])*float(value['Amount']))
                price_paid ="{0:.2f}".format(price_paid_long)
                time_stamp=datetime.datetime.strptime(value['Timestamp'][0:16], "%Y-%m-%dT%H:%M")
                if value['CreatedDate'][19] is 'Z':
                    time_stamp_purch= datetime.datetime.strptime(value['CreatedDate'][0:16], "%Y-%m-%dT%H:%M").strftime("%d.%m.%Y %H:%M")
                else:
                    time_stamp_purch= datetime.datetime.strptime(value['CreatedDate'], "%m/%d/%Y %I:%M:%S %p").strftime("%d.%m.%Y %H:%M")
                amount ="{0:.2f}".format(float(value['Amount']))
                single_transaction = {'Timestamp': time_stamp ,'TimestampPurch':time_stamp_purch, 'StockId': value['StockId'].split(':')[1], 'StockPrice': value['Price'], 'Amount': amount, 'MoneySpent': price_paid}
                all_transactions.append(single_transaction)

        all_transactions = sorted(all_transactions, key=lambda k: k['Timestamp'], reverse=True)
        tmpl = env.get_template('transactionHistory.html')
        return tmpl.render(seq=all_transactions)

    @cherrypy.expose
    def newTransaction(self):

        companyName=''
        stockName=''
        stockPrice=0
        stockAmount=0
        stockPercentage=0
        transAmount=0
        booking_date=''

        # Print out a list of accounts including its balance
        #for account in session.accounts:
        #    print(account.name)
        #    print(account.balance)

        headers = {'Accept': 'application/json'}
        url = "https://007investment.table.core.windows.net:443/Stock?sv=2016-05-31&si=Stock-15EEC52A495&tn=stock&sig=PbqLEW4Mi0hoNBw5nflEDszu36wzJ%2Bw592%2Bih%2BIfMI0%3D"
        response = requests.get(url, headers=headers)
        print(response.text)
        stocks = response.json()

        # Print out the list of all transactions on a specific account
        for transaction in session.get_account("A1.1").transactions:

            i = -1
            for stock in stocks['value']:
                for name in stock['CompanyName'].split('\n'):
                    i = i+1
                    #print(name.split(' ')[0] + "   "+transaction.name.split(' ')[0])
                    if name.split(' ')[0] == transaction.name.split(' ')[0]:
                        companyName = name.split(' ')[0]
                        stockName = name
                        stockPrice=stocks['value'][i]['Price']
                        stockId = stocks['value'][i]['Exchange']
                        stockAmount=(transaction.amount*percentage)
                        stockPercentage=((transaction.amount*percentage)/stocks['value'][i]['Price'])
                        transAmount=-1*transaction.amount
                        booking_date=transaction.booking_date
                        print(str(transaction.amount)+" "+str(i))

        print(companyName+" / "+stockName+" / "+str(stockPrice)+" / "+str(stockPercentage))
        #Post Request
        url = "https://007investment.table.core.windows.net:443/Transaction?sv=2016-05-31&si=Transaction-15EEC51E092&tn=transaction&sig=G%2BAfHj8oMMxKdTwj93q4KiR7tmnIPJdKkjwyHYdggpM%3D"
        response = requests.get(url, headers=headers)
        trans_j = response.json()
        allRow =[]
        for value in trans_j['value']:
            allRow.append(int(value['RowKey']))
            print(value['RowKey'])
        rowKey= str(1+allRow.pop())
        time= (datetime.timedelta(hours=2)+datetime.datetime.utcnow())
        headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
        payload = {
            "PartitionKey": "10-2017",
            "RowKey": rowKey,
            "UserId": "1",
            "StockId": stockId,
            "Price": stockPrice,
            "Status": "confirmed",
            "Amount": stockPercentage,
            "CreatedDate": time.strftime("%m/%d/%Y %I:%M:%S %p")
                }

        r = requests.post("https://007investment.table.core.windows.net:443/Transaction?sv=2016-05-31&si=Transaction-15EEC51E092&tn=transaction&sig=G%2BAfHj8oMMxKdTwj93q4KiR7tmnIPJdKkjwyHYdggpM%3D", data=json.dumps(payload), headers=headers)
        #End Post Request
        tmpl = env.get_template('newTransaction.html')
        return tmpl.render(companyName=companyName,stockName=stockName,stockPrice=stockPrice,stockPercentage=round(stockPercentage,2),transAmount=transAmount,stockAmount=stockAmount,booking_date=time.strftime("%d.%m.%Y %H:%M"))

    @cherrypy.expose
    def myLink(self):
        headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}

        payload = {
            "PartitionKey": "10-2017",
            "RowKey": "48",
            "UserId": "1",
            "StockId": "1",
            "Price": 10.6,
            "Status": "pending",
            "Amount": 100
                }

        r = requests.post("https://007investment.table.core.windows.net:443/Transaction?sv=2016-05-31&si=Transaction-15EEC51E092&tn=transaction&sig=G%2BAfHj8oMMxKdTwj93q4KiR7tmnIPJdKkjwyHYdggpM%3D", data=json.dumps(payload), headers=headers)
        status = r.status_code
        header = r.headers
        text = r.text
        tmpl = env.get_template('post_success.html')
        return tmpl.render(status=status, header=header, text=text)

config = {
    'global': {
        'server.socket_host': '0.0.0.0',
        'server.socket_port': int(os.environ.get('PORT', 5000)),
    },
    '/assets': {
         'tools.staticdir.root': os.path.dirname(os.path.abspath(__file__)),
         'tools.staticdir.on': True,
         'tools.staticdir.dir': 'assets',
    }
}

cherrypy.quickstart(Landing_Page(), '/', config=config)

##json read


"""
Wrap the transaction created in the previous task in a function that will take the first and
last name as a kwarg. Based on the given name or surname, the function will decide which query
to use to search for a director and then delete him/her. The search query should be in the text
form ().
"""

# https://docs.python.org/3/library/argparse.html
# allows us to define input arguments and help
import argparse

from sqlalchemy.orm import sessionmaker
from sqlalchemy import text
from cinematic import Movies, Directors, engine

# define the argparser, with description
ARG_PARSER = argparse.ArgumentParser(
    description="Deletes directors from db"
)

# create 2 arguments name and surname
ARG_PARSER.add_argument('-n', '--name', dest='name', help='handles directors name')
ARG_PARSER.add_argument('-s', '--surname', dest='surname', help='handles directors surname')
# parse all arguments from input
ARGS = ARG_PARSER.parse_args()

def delete_director(**kwargs):
    """ Deletes director """
    if kwargs.get('name') is not None:  # 'name' in kwargs:
        query = text('SELECT * FROM directors WHERE name = :name')
    elif kwargs.get('surname') is not None:
        query = text('SELECT * FROM directors WHERE surname = :surname')
    else:
        print('No valid arguments parsed')
        return

    # important, use autocommit=True
    session = sessionmaker(bind=engine, autocommit=True)()

    with session.begin():
        # select first found director, remember value is tuple with one elem: tuple(elem,)
        director_id = session\
                    .query(Directors.director_id)\
                    .from_statement(query)\
                    .params(kwargs)\
                    .first()

        try:
            # return deleted movies amount
            print('movies:', session
                  .query(Movies)
                  .filter(Movies.director_id == director_id[0])
                  .delete())

            # return deleted director amount
            print('directors', session
                  .query(Directors)
                  .filter(Directors.director_id == director_id[0])
                  .delete())
        # if no director found, catch exception, return human readable message
        except TypeError:
            print(f'No director found for {kwargs}')

# call function with two arguments
delete_director(name=ARGS.name, surname=ARGS.surname)


import cv2
import numpy as np

#Inicializar los parametros del detector de arucos
parametros = cv2.aruco.DetectorParameters_create()

#Cargamos el diccionario de nuestro aruco
diccionario = cv2.aruco.Dictionary_get(cv2.aruco.DICT_5X5_100)

#Lectura de la camara#
cap = cv2.VideoCapture(0)
cap.set(3,1280)
cap.set(4,720)

while True:
	ret, frame = cap.read()
	gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
	#Detectamos los marcadores en la imagen
	esquinas,ids,candidatos_malos = cv2.aruco.detectMarkers(gray,diccionario,parameters=parametros)

	if np.all(ids!=None):
		aruco = cv2.aruco.drawDetectedMarkers(frame,esquinas)

		#Extraemos los puntos de las esquinas en coordenadas separadas
		c1 = (esquinas[0][0][0][0], esquinas[0][0][0][1])
		c2 = (esquinas[0][0][1][0], esquinas[0][0][1][1])
		c3 = (esquinas[0][0][2][0], esquinas[0][0][2][1])
		c4 = (esquinas[0][0][3][0], esquinas[0][0][3][1])

		copy = frame
		#Leemos la imagen que vamos a sobreponer
		imagen = cv2.imread("imagen.jpg")
		#Extraemos el tamaño de la imagen
		tamaño = imagen.shape
		#Organizamos las coordenadas del aruco en una matriz
		puntos_aruco = np.array([c1,c2,c3,c4])

		#Organizamos las coordenadas de la imagen en otra matriz
		puntos_imagen = np.array([
			[0,0],
			[tamaño[1] - 1, 0],
			[tamaño[1] - 1, tamaño[0] - 1],
			[0, tamaño[0] - 1]
			], dtype = float)

		#Realizamos la superposicion de la imagen (homografia)
		h,estado = cv2.findHomography(puntos_imagen, puntos_aruco)

		#Realizamos la transformacion de perspectiva
		perspectiva = cv2.warpPerspective(imagen, h, (copy.shape[1], copy.shape[0]))
		cv2.fillConvexPoly(copy, puntos_aruco.astype(int), 0, 16)
		copy = copy + perspectiva
		cv2.imshow("Realidad Virtual", copy)

	else:
		cv2.imshow("Realidad Virtual", frame)

	k = cv2.waitKey(1)
	if k == 27:
		break

cap.release()
cv2.destroyAllWindows()


from constants import pickle_path
from gensim import models, corpora
from util import *
import pickle

class Books(object):
    def __init__(self):
        self.book_name = ""
        self.dict = None #loaded dict should be attached here
        self.input_type = "" #url # text file
        self.input_link = None
        self.input_file_path = None
        self.steps = [self.preprocess,
                      self.baseline,
                      self.log_baseline,
                      self.topic_modelling,
                      ]
        self.bias = 0.000001
        self.num_topics = 26

    def fetch_data(self):
        """
        :return: returns a dict by chapters implemented by each book
        """
        return {}

    def get_dict(self):
        if self.dict:
            return self.dict
        f = open(pickle_path+self.book_name+".pickle","rb")
        self.dict = pickle.load(f)
        f.close()
        return self.dict

    def preprocess(self):
        output_dict = self.fetch_data()
        filtered_dict = dict()
        for k,v in output_dict.items():
            filtered_dict[k] = clean_data(v)
        chapter_labels=[k for k in sorted(output_dict.keys())]
        final_dict = dict()
        final_dict['raw_text'] = output_dict
        final_dict['filtered_text'] = filtered_dict
        final_dict['chapter_labels'] = chapter_labels
        self.dict =final_dict
        of = open(pickle_path+self.book_name+".pickle","wb")
        pickle.dump(final_dict, of)

    def baseline(self):
        if not self.dict:
            self.get_dict()
        filtered_text=dict()
        for k,v in self.dict['raw_text'].items():
            filtered_text[k] = clean_data(v)
        self.dict['filtered_text'] = filtered_text
        #bag of words by chapter
        bag_of_words = get_bag_of_words_by_chapter(self.dict['filtered_text'])
        self.dict["bag_of_words"] = bag_of_words
        total_counter = sum([v for v in bag_of_words.values()])
        DTM, unique_words = get_DTM_from_counter(total_counter,dicts=[bag_of_words], return_words=True)
        self.dict["DTM"] = DTM
        row_labels=["ch{}".format(k) for k in self.dict['chapter_labels']]
        headers = sorted(unique_words, key=unique_words.get)
        self.dict["unique_words"] = headers
        save_to_csv('{}_baseline_DTM.csv'.format(self.book_name),DTM, headers)
        execute_similatity_matrix(DTM,  type=self.book_name, label="baseline", col_row_labels=row_labels)
        of = open(pickle_path+self.book_name+".pickle","wb")
        pickle.dump(self.dict, of)

    def log_baseline(self):
        if not self.dict:
            self.get_dict()

        DTM = self.dict["DTM"]
        row_labels=["ch{}".format(k) for k in self.dict['chapter_labels']]
        headers = self.dict["unique_words"]
        DTM = np.array(DTM) + self.bias
        DTM = np.log(DTM)
        DTM[DTM<0] = 0.0
        save_to_csv('{}_baseline_log_DTM.csv'.format(self.book_name),DTM, headers)
        self.dict["Log_DTM"] = DTM
        execute_similatity_matrix(DTM,  type=self.book_name, label="baseline_log", col_row_labels=row_labels)
        of = open(pickle_path+self.book_name+".pickle","wb")
        pickle.dump(self.dict, of)

    def topic_modelling(self):
        if not self.dict:
            self.get_dict()
        texts = self.dict["filtered_text"]
        documents = [texts[k] for k in sorted(texts.keys())]
        all_tokens = []
        for tokens in documents:
            all_tokens.extend(tokens)
        all_tokens = Counter(all_tokens)
        unique_tokens = set(filter(lambda x: all_tokens[x] ==1,all_tokens))
        documents = [[word for word in doc if word not in unique_tokens] for doc in documents]
        # Create Dictionary.
        id2word = corpora.Dictionary(documents)
        # Creates the Bag of Word corpus.
        mm = [id2word.doc2bow(text) for text in documents]
        lda = models.ldamodel.LdaModel(corpus=mm, id2word=id2word, num_topics=self.num_topics, \
                               update_every=1, chunksize=10000, passes=1)
        lda_corpus = lda[mm]
        lda_DTM = [[0]*self.num_topics for i in range(len(texts))]
        for doc_num, doc in enumerate(lda_corpus):
            for topic in doc:
                topic_id,score=topic
                lda_DTM[doc_num][topic_id] = score
        topics = lda.print_topics()
        topic_names = ["Topic{}".format(topic[0]) for topic in topics]
        self.dict["topics"] = topics
        self.dict["topic_names"] = topic_names
        self.dict["LDA_DTM"] = lda_DTM
        row_labels=["ch{}".format(k) for k in self.dict['chapter_labels']]
        save_to_csv('{}_lda_DTM.csv'.format(self.book_name),lda_DTM, topic_names)
        execute_similatity_matrix(lda_DTM,  type=self.book_name, label="lda", col_row_labels=row_labels)
        of = open(pickle_path+self.book_name+".pickle","wb")
        pickle.dump(self.dict, of)


"""
Module contains classes for calculating metrics and logging them to tensorboard,
plus related util functions.
"""
import os
from collections import defaultdict

import numpy as np
import torch
from torch.utils.tensorboard.writer import SummaryWriter

from .general_utils import get_logger

class Evaluation:
    """
    Base class for calculating model metrics and logging them to tensorboard.
    """

    def __init__(self, log_folder: str):
        self.logger = get_logger(
            "evaluation", os.path.join(log_folder, "evaluation.txt")
        )
        self.train_results, self.val_results = [], []
        self.dev_results, self.test_results = [], []
        self._epoch_reset()

    def set_fold(self, _):
        """
        Prepare evaluation for new cv fold.
        """
        self.train_results.append(defaultdict(list))
        self.val_results.append(defaultdict(list))
        self.dev_results.append(defaultdict(list))
        self.test_results.append(defaultdict(list))

    def evaluate(self, predicted, labels):
        raise NotImplementedError("Override in custom evaluation class.")

    def log_evaluation(self, epoch, dataset: str, writer: SummaryWriter):
        """
        Calculates metrics from running totals. Saves and logs them to tensorboard.
        """
        raise NotImplementedError("Override in custom evaluation class.")

    def _get_results(self, dataset: str, index=-1):
        if dataset == "train":
            return self.train_results[index]
        elif dataset == "val":
            return self.val_results[index]
        elif dataset == "test":
            return self.test_results[index]
        elif dataset == "dev":
            return self.dev_results[index]
        else:
            raise ValueError(
                f"Incorrect `dataset` value, got {dataset}, accept: train, test, dev, val."
            )

    def _epoch_reset(self):
        raise NotImplementedError("Override in custom evaluation class.")

    def get_experiment_results(self, dataset: str):
        """
        Get mean and std of results.
        """
        results = self._get_results(dataset, index=slice(None))
        return aggregate_results(results)

def aggregate_results(results):
    "Averages over list of dictionaries with results."
    agg_results = {}
    for k in results[0].keys():
        val_list = [res[k] for res in results]
        # Take mean and standard deviation across runs.
        agg_results[k] = (
            np.mean(val_list, axis=0),
            np.std(val_list, axis=0),
        )

    return agg_results

class BinaryClassificationEvaluation(Evaluation):
    """
    Class for calculating binary classification metrics and logging them to tensorboard.

    Metrics: accuracy, precision, recall.
    """

    def evaluate(self, predicted, labels):
        """
        Calculates confusion matrix between predicted and true labels for single batch.
        Saves running totals.
        """
        pred_positives = predicted > 0.5
        label_positives = labels > 0.5

        self.tp += (pred_positives & label_positives).sum().item()
        self.tn += (~pred_positives & ~label_positives).sum().item()
        self.fp += (pred_positives & ~label_positives).sum().item()
        self.fn += (~pred_positives & label_positives).sum().item()

        self.total += len(labels)

    def log_evaluation(self, epoch, dataset: str, writer: SummaryWriter):
        # Calculate.
        accuracy = (self.tp + self.tn) / self.total
        recall = self.tp / (self.tp + self.fp) if (self.tp + self.fp) > 0 else 0
        precision = self.tp / (self.tp + self.fn)

        # Log.
        writer.add_scalar(f"{dataset} accuracy", accuracy, epoch)
        writer.add_scalar(f"{dataset} precision", recall, epoch)
        writer.add_scalar(f"{dataset} recall", precision, epoch)
        self.logger.debug(f"Epoch {epoch}: {dataset} accuracy = {accuracy}")
        self.logger.debug(f"Epoch {epoch}: {dataset} precision = {precision}")
        self.logger.debug(f"Epoch {epoch}: {dataset} recall = {recall}")

        # Save.
        results = self._get_results(dataset)
        results["accuracy"].append(accuracy)
        results["epoch"].append(epoch)
        results["recall"].append(recall)
        results["precision"].append(precision)

        # Reset.
        self._epoch_reset()

    def _epoch_reset(self):
        self.tp = 0
        self.tn = 0
        self.fp = 0
        self.fn = 0
        self.total = 0

class RegressionEvaluation(Evaluation):
    """
    Class for calculating regression metrics and logging them to tensorboard.

    Metrics: root mean square error, mean absolute error.
    """

    def evaluate(self, predicted, labels):
        """
        Calculates diff between predicted and true labels for single batch.
        Saves running totals.
        """
        self.error_squared += torch.sum((predicted - labels) ** 2).item()
        self.error_abs += torch.sum(torch.abs(predicted - labels)).item()
        self.total += len(labels)

    def log_evaluation(self, epoch, dataset: str, writer: SummaryWriter):
        # Calculate.
        rmse = (self.error_squared / self.total) ** 0.5
        mae = self.error_abs / self.total

        # Log.
        writer.add_scalar(f"{dataset} rmse", rmse, epoch)
        writer.add_scalar(f"{dataset} mae", mae, epoch)
        self.logger.debug(f"Epoch {epoch}: {dataset} rmse = {rmse}")
        self.logger.debug(f"Epoch {epoch}: {dataset} mae = {mae}")

        # Save.
        results = self._get_results(dataset)
        results["rmse"].append(rmse)
        results["mae"].append(mae)

        # Reset.
        self._epoch_reset()

    def _epoch_reset(self):
        self.error_squared = 0
        self.error_abs = 0
        self.total = 0


#!/bin/python

import math
import os
import random
import re
import sys

# Complete the matchingStrings function below.
def matchingStrings(strings, queries):
    n = len(strings)
    q = len(queries)
    arr = []
    for query in queries:
        cnt = 0
        for string in strings:
            if(query == string):
                cnt += 1
        arr.append(cnt)
    return arr

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    strings_count = int(raw_input())
    if(strings_count >= 1 and strings_count <= 1000):

        strings = []

        for _ in xrange(strings_count):
            strings_item = raw_input()
            strings.append(strings_item)

        queries_count = int(raw_input())
        if (queries_count >= 1 and queries_count <= 1000):

            queries = []

            for _ in xrange(queries_count):
                queries_item = raw_input()
                queries.append(queries_item)

            res = matchingStrings(strings, queries)

            fptr.write('\n'.join(map(str, res)))
            fptr.write('\n')

    fptr.close()


from tkinter import *

window=Tk()
window.title("Mile to Km Converter")

window.config(padx=20,pady=20)

def miles_to_km():
    miles=float(entry_miles.get())
    km=miles*1.609
    kilometer_result.config(text=str(km))

entry_miles=Entry(width=7)
entry_miles.grid(column=1,row=0)

my_label=Label(text="Miles")
my_label.grid(column=2,row=0)

my_label2=Label(text="is equal to")
my_label2.grid(column=0,row=1)

kilometer_result=Label(text="0")
kilometer_result.grid(column=1,row=1)

kilometer_label=Label(text="Km")
kilometer_label.grid(row=1,column=2)

calculate_button=Button(text="Calculate",command=miles_to_km)
calculate_button.grid(row=2,column=1)
print("hello")
print("hello world")

window.mainloop()


import mpl_toolkits.mplot3d.axes3d as axes3d
import numpy as np
import matplotlib.pyplot as plt
import h5py as h5

points = h5.File('od_master.h5')['data']['neutron_xyz']

Height = 172 #cm
Radius = 64 # cm

fig = plt.figure(figsize = (10,8))
ax = fig.add_subplot(1, 1, 1, projection='3d')

u = np.linspace(0, np.pi*2, 60)
t = np.linspace(0, Radius, 60)
z = np.linspace(-Height/2, Height/2, 2)

#Defining the parametric space for making the top and bottom circles
U, T = np.meshgrid(u, t)

#For top and bottom
X1 = T*np.cos(U)
Y1 = T*np.sin(U)
ZTop = Height/2*np.ones(X1.shape)
ZBottom = -Height/2*np.ones(X1.shape)

#Defining the parametric space for making the cylindrical column
z = np.linspace(-Height/2, Height/2, 2)
u, z = np.meshgrid(u, z)

x = Radius * np.cos(u)
y = Radius * np.sin(u)

#Column
ax.plot_surface(x, y, z, color='b', alpha = 0.3)
#Top & Bottom
ax.plot_surface(X1, Y1, ZTop, alpha=0.3, color='cyan', rstride=6, cstride=12)
ax.plot_surface(X1, Y1, ZBottom, alpha=0.7, color='green', rstride=6, cstride=12)
for point in points:
    ax.scatter(point[0], point[1], point[2], color = 'b')
plt.show()


#!/usr/bin/env python3

import time
from argparse import ArgumentParser

from alsa_midi import READ_PORT, Address, MidiBytesEvent, SequencerClient

def make_events():
    # 3 ticks per quarternote, swung
    return [
            # D-on
            MidiBytesEvent(b"\x90\x3e\x7f", tick=0),

            # D-off, E-on
            MidiBytesEvent(b"\x80\x3e\x00\x90\x40\x7f", tick=2),

            # E-off, F-on
            MidiBytesEvent(b"\x80\x40\x00\x90\x41\x7f", tick=3),

            # F-off, G-on
            MidiBytesEvent(b"\x80\x41\x00\x90\x43\x7f", tick=5),

            # G-off, E-on
            MidiBytesEvent(b"\x80\x43\x00\x90\x40\x7f", tick=6),

            # E-off, C-on
            MidiBytesEvent(b"\x80\x40\x00\x90\x3c\x7f", tick=9),

            # C-off, D-on
            MidiBytesEvent(b"\x80\x3c\x00\x90\x3e\x7f", tick=11),

            # D-off
            MidiBytesEvent(b"\x80\x3e\x00", tick=24),
    ]

def main():
    parser = ArgumentParser(description="Play the lick (by sending bytes)")
    parser.add_argument("--port", "-p", type=Address, action="append",
                        help="Connect to the specific port(s)")
    parser.add_argument("--bpm", type=float, default=120.0,
                        help="Tempo in beats per minute (default: 120)")

    args = parser.parse_args()

    client = SequencerClient("play_the_lick.py")
    port = client.create_port("output", READ_PORT)
    queue = client.create_queue()

    queue.set_tempo(int(60.0 * 1000000 / args.bpm), 3)

    if args.port:
        targets = args.port
    else:
        target = client.list_ports(output=True)[0]
        print(f"Playing on {target.client_id}:{target.port_id}"
              f" '{target.name}' of '{target.client_name}'")
        targets = [target]

    for target in targets:
        port.connect_to(target)

    queue.start()
    try:
        for event in make_events():
            client.event_output(event, port=port, queue=queue)
        client.drain_output()
    except KeyboardInterrupt:
        pass

    time.sleep(60.0 * 8 / args.bpm)

    client.close()

if __name__ == '__main__':
    main()


import itertools
import sys
import math
import scipy.special as sp
import numpy as np
import os
import imageio
import natsort

__author__ = 'Marcin Kucharski'

def get_param(filein):
    """
    Function gets data from input file.
    :param filein:
    Name of input file.
    :return:
    Array with data from file.
    """
    modee_freq = []
    a = []
    p = []
    l_ = []
    m = []
    f = open(filein, 'r')
    for lines in f:
        parts = lines.split()
        modee_freq.append(float(parts[0]))
        a.append(float(parts[1]))
        p.append(float(parts[2]))
        l_.append(float(parts[3]))  # degree
        m.append(float(parts[4]))  # order
    return modee_freq, a, p, l_, m

def combinations(n_teta, n_fi):
    """
    Function makes theta and fi combinations.
    :param n_teta:
    Number of theta parts.
    :param n_fi:
    Number of phi parts.
    :return:
    Array with combinations.
    """
    teta = np.linspace(0, math.pi, n_teta)
    fi = np.linspace(0, 2 * math.pi, n_fi)

    comb = list(itertools.product(fi, teta))
    return comb

def r_values(combine, t, delta_t, freq, a, p, l_, m, name):
    """
    Function calculates r values for time t.
    Writes results to .dat file, and calls function with gnuplot commands.
    After making .png images, converts them to gif animation and removes temporary files.
    :param combine:
    Array with combinations.
    :param t:
    Time
    :param delta_t:
    Time period.
    :param freq:
    Frequency from file.
    :param a:
    Amplitude from file.
    :param p:
    Phase from file.
    :param l_:
    Degree of Spherical harmonic.
    :param m:
    Azimuthal order of spherical harmonics.
    :param name:
    Name of the output gif.
    """
    r = []
    time = 0.0
    while time < t:
        f = open('%s.dat' % round(time, 2), 'w+')
        f.write("PHI    THETA   R\n")
        for element in combine:
            i = 0
            sum = 0.0
            while i < len(a):
                sum += (a[i] *
                        np.sqrt((2 * l_[i] + 1 *
                                 np.math.factorial(l_[i] - m[i])) /
                                (4 * np.pi * np.math.factorial(l_[i] + m[i]))) *
                        sp.lpmv(m[i], l_[i], np.cos(element[1])) *
                        np.cos(m[i] * element[0]) *
                        np.cos(2 * np.pi * freq[i] * time + p[i]))
                i += 1
            theta_zamiana = ((math.pi / 2) - float(element[1]))
            r = (1.0 + sum)
            f.write("{}     {}      {}\n".format(str(element[0]), theta_zamiana, r))
        f.close()
        gnuplot_template(time, time)
        os.system("%s.plt" % time)
        os.system("del /f %s.plt" % time)
        os.system("del /f %s.dat" % round(time, 2))
        time += delta_t
    to_gif(name)
    os.system("del /f *.png")

def gnuplot_template(filename, time):
    """
    Function creates gnuplot commands.
    :param filename:
    Name of the file with commands.
    :param time:
    A moment in animation.
    :return:
    File with commands.
    """
    f = open('%s.plt' % filename, 'w+')
    f.write('''set terminal pngcairo size 1600,1000 enhanced
set pm3d
set hidden3d
set palette rgb 23,28,3
set mapping spherical
set border linewidth 2
unset key
set mxtics
set xrange [-1.1:1.3]
set yrange [-1.1:1.3]
set zrange [-1.1:1.3]
set cbrange [0.95:1.1]
set mytics
set mztics
set mcbtics
set xtics font 'Helvetica,13' offset 0,-1,0
set ytics font 'Helvetica,13' offset 2,0,0
set ztics font 'Helvetica,13' offset 0,0,0
set cbtics font 'Helvetica,17'
set format x "%.1f"
set format y "%.1f"
set format z "%.1f"
set format cb "%.2f"
set xlabel '(X/R_{star})' font 'Helvetica,15' offset 0,-1
set ylabel '(Y/R_{star})' font 'Helvetica,15' offset 0,-1
set zlabel '(Z/R_{star})' font 'Helvetica,15' offset -4
set cblabel 'Radial Displacement (1+{/Symbol D}r/R_{star})' font 'Helvetica,15' offset 5''')
    f.write("\nset title 'Elapsed Time = %s d" % round(time, 2))
    f.write("""\nset title  font 'Helvetica,30' offset 0,0,-2
set view 65,45,1.1
set view equal xyz
set ticslevel 0.1""")
    f.write("\nset output '%s.png'" % round(time, 2))
    f.write("\nsplot '%s.dat' u 1:2:3:3 w p lt 7 ps 0.9 palette" % round(time, 2))
    f.close()

def to_gif(name):
    """
    Functon that converts .png files to gif.
    :param name:
    Name of the output file.
    :return:
    Animation in gif.
    """
    gif_name = '%s.gif' % name
    file_list = []
    filenames = sorted(filter(os.path.isfile, [x for x in os.listdir() if x.endswith(".png")]))
    # filenames = natsort.natsorted(filenames)  <--- Uncomment when the file name contains '10'
    for filename in filenames:
        file_list.append(imageio.imread(filename))
    duration = 0.05
    imageio.mimsave(gif_name, file_list, duration=duration)

def print_help():
    """Prints help for user"""
    print("Warning!\n Script syntax:\n app.py <filein.txt> <fileout> <T> <delta_t> <N_teta> <N_fi>")
    exit()

def main():
    print("***************************")
    print("****Spherical Harmonics****")
    print("***************************")
    if len(sys.argv) != 7:
        print_help()
    else:
        o = sys.argv[1]
        freq, a, p, l_, m = get_param(o)
        com = combinations(int(sys.argv[5]), int(sys.argv[6]))
        r_values(com, int(sys.argv[3]), float(sys.argv[4]), freq, a, p, l_, m, sys.argv[2])

if __name__ == '__main__':
    main()


from multiprocess import Pool
import numpy as np
from s3_create import upload_files_s3, get_key_secret, create_bucket, get_data_files, get_bucket

def get_process_number(category_list):
    if len(category_list)%30000 == 0:
        additional_process = 0
    else:
        additional_process = 1
    return int(np.floor(len(category_list)/30000) + additional_process)

def get_parallel_process_list(pool, number_of_processes, category_list):
    parallel_processes = []
    index = 0
    factor = 30000
    for i in range(1, number_of_processes+1):
        last_index = i*factor
        if len(category_list) - last_index < 30000:
            last_index = len(category_list)%30000
        parallel_processes.append(
            pool.apply_async(upload_files_s3, [category_list[index: last_index],
                                               'capstone-project-2187',
                                               s3_bucket])
        )
        index += last_index
    return parallel_processes

def finalize_processes(list_of_processes):
    for process in list_of_processes:
        process.get()

def execute_parallel_uploads(plant_files_list, animal_files_list, human_files_list):
    num_processes = get_process_number(plant_files_list) + get_process_number(animal_files_list) + get_process_number(human_files_list)
    print(num_processes)
    pool = Pool(processes= num_processes)

    plants = get_parallel_process_list(pool,
                                       get_process_number(plant_files_list),
                                       plant_files_list)

    animals = get_parallel_process_list(pool,
                                       get_process_number(animal_files_list),
                                       animal_files_list)

    humans = get_parallel_process_list(pool,
                                       get_process_number(human_files_list),
                                       human_files_list)

    pool.close()
    pool.join()

    finalize_processes(plants)
    finalize_processes(animals)
    finalize_processes(humans)

if __name__ == '__main__':

    KEY, SECRET = get_key_secret()

    main_directory = "../../capstone data"
    plant_files_list, animal_files_list, human_files_list = get_data_files(main_directory)

    s3_client = create_bucket('capstone-project-2187',
                              KEY,
                              SECRET,
                              'us-west-2')

    s3_resource = get_bucket('capstone-project-2187',
                                  KEY,
                                  SECRET,
                                  'us-west-2')

    s3_bucket = s3_resource.Bucket('capstone-project-2187')

    execute_parallel_uploads(plant_files_list,
                             animal_files_list,
                             human_files_list)


import pandas
import ast
import time # if required
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import CountVectorizer

movies = pandas.read_csv('tmbd_5000_movies.csv')    #Loading The CSV files
creditss = pandas.read_csv('tmbd_5000_credits.csv')

cv = CountVectorizer(max_features=5000, stop_words='english')

movies = movies.merge(creditss,on='title')

def convert(obj):
    L = []
    for i in ast.literal_eval(obj):
        L.append(i['name'])
    return L

def convert3(obj):
    L = []
    counter = 0
    for i in ast.literal_eval(obj):
        if counter != 3:
            L.append(i['name'])
            counter+=1
        else:
            break
    return L

def fetch_director(obj):
    L = []
    for i in ast.literal_eval(obj):
        if i['job'] == 'Director':
            L.append(i['name'])
            break
    return L

movies['genres'] = movies['genres'].apply(convert)
movies['keywords'] = movies['keywords'].apply(convert)
movies['cast'] = movies['cast'].apply(convert3)
movies['crew'] = movies['crew'].apply(fetch_director)
movies['tags'] = movies['genres'] + movies['cast'] + movies['crew']
movies['genres'] = movies['genres'].apply(lambda r: [i.replace(" ", "") for i in r])
movies['keywords'] = movies['keywords'].apply(lambda r: [i.replace(" ", "") for i in r])
movies['cast'] = movies['cast'].apply(lambda r: [i.replace(" ", "") for i in r])
movies['crew'] = movies['crew'].apply(lambda r: [i.replace(" ", "") for i in r])
movies['tags'] = movies['tags'].apply(lambda x: " ".join(x))

df = movies[['movie_id', 'title', 'tags']] #needed Data

vectors = cv.fit_transform(movies['tags']).toarray()

similarity = cosine_similarity(vectors)

print('Hi I am a Recommender System')
print('I can give you recommendations for any Hollywold movie.')
print('Ensure that you enter the correct spelling of the movie')
time.sleep(4)
movie_input = input('Enter the name of the movie for which you want Recommandations:- ').title()
print()
print(f'Here are few Recommendation for the movie:- {movie_input} ')
time.sleep(2)
print()

def recommend(movie):
    movie_index = df[df['title'] == movie].index[0]
    distances = similarity[movie_index]
    movie_list = sorted(list(enumerate(distances)), reverse=True, key=lambda x:x[1])

    for i in movie_list[1:6]:
        print(df.iloc[i[0]].title)

recommend(movie_input)


def remove_element(nums, val):
    #k: slow moving pointer, i: fast moving pointer
    k = 0
    for i in range(len(nums)):
        if (nums[i] != val):
            nums[k] = nums[i]
            k += 1
        #end if
    #end for

    return k  #new container size

item = 5
nums = [1, 2, 3, 4, 5, 6, 7]
print("input array:")
print(nums)
print("element to remove in place: {}".format(item))
k = remove_element(nums, item)
print("output array:")
print(nums[:k])


import time
import pandas as pd
import generator
import Data

def parent(i):
    return (i - 1) // 2

def left(i):
    return 2 * i + 1

def right(i):
    return 2 * i + 2

def to_xls_file(arr, file_name: str):
    df = pd.DataFrame(data = data_array(arr), columns = ['Date', 'Flight', 'Full Name', 'Place'])
    file_name = file_name + '.xlsx'
    writer = pd.ExcelWriter(file_name, engine ='xlsxwriter')
    df.to_excel(writer, 'flight_table1')
    writer.save()

def from_xlsx_file(file_name: str):
    xl = pd.ExcelFile(file_name)
    df = xl.parse('flight_table1')
    arr = []
    for i in range(len(df)):
        row = df.iloc[i]
        data = Data.Data(row[1].to_pydatetime(), int(row[2]), str(row[3]), int(row[4]))
        arr.append(data)
    return arr

def data_array(array):
    arr = []
    for i in range(len(array)):
        arr2 = []
        arr2.append(array[i].Date)
        arr2.append(array[i].Flight)
        arr2.append(array[i].FullName)
        arr2.append(array[i].Place)
        arr.append(arr2)
    return arr

def insertation_sort(data_file: str, text_file: str):
    f = open(text_file, 'a')
    arr = from_xlsx_file(data_file)
    start_time = time.time()
    for i in range(1, len(arr)):
        j = i
        temp = arr[j]
        while j > 0 and temp < arr[j - 1]:
            arr[j] = arr[j - 1]
            j = j - 1
        arr[j] = temp
    print(data_file + ' :')
    print("       %s seconds       " % (time.time() - start_time))
    note = data_file + ' time = ' + str(time.time() - start_time) + '  !! INSERT SORT !!' + '\n'
    f.write(note)
    f.close()
    note2 = data_file.rsplit(".", 1)[0] + '_insert_sorted'
    to_xls_file(arr, note2)

def heapify(heap, index, size):
    l = left(index)
    r = right(index)
    if (l < size and heap[l] > heap[index]):
        largest = l
    else:
        largest = index
    if (r < size and heap[r] > heap[largest]):
        largest = r
    if (largest != index):
        heap[largest], heap[index] = heap[index], heap[largest]
        heapify(heap, largest, size)

def heap_sort(data_file: str, text_file: str):
    f = open(text_file, 'a')
    array = from_xlsx_file(data_file)
    start_time = time.time()
    length = len(array)
    beginning = parent(length - 1)
    while beginning >= 0:
        heapify(array, index=beginning, size=length)
        beginning = beginning - 1
    for i in range(len(array) - 1, 0, -1):
        array[0], array[i] = array[i], array[0]
        heapify(array, index=0, size=i)
    print(data_file + ' :')
    print("       %s seconds       " % (time.time() - start_time))
    note = data_file + ' time = ' + str(time.time() - start_time) + '  !! HEAP SORT !!' + '\n'
    f.write(note)
    f.close()
    note2 = data_file.rsplit(".", 1)[0] + '_heap_sorted'
    to_xls_file(array, note2)

def bubble_sort(data_file: str, text_file: str):
    f = open(text_file, 'a')
    array = from_xlsx_file(data_file)
    start_time = time.time()
    for i in range(len(array) - 1):
        for j in range(len(array) - i - 1):
            if array[j] > array[j + 1]:
                buff = array[j]
                array[j] = array[j + 1]
                array[j + 1] = buff
    print(data_file + ' :')
    print("       %s seconds       " % (time.time() - start_time))
    note = data_file + ' time = ' + str(time.time() - start_time) + ' !! BUBBLE SORT !!' + '\n'
    f.write(note)
    f.close()
    note2 = data_file.rsplit(".", 1)[0] + '_bubblesort'
    to_xls_file(array, note2)

bubble_sort('flight_info_100.xlsx', 'times.txt')
insertation_sort('flight_info_100.xlsx', 'times.txt')
heap_sort('flight_info_100.xlsx', 'times.txt')

bubble_sort('flight_info_500.xlsx', 'times.txt')
insertation_sort('flight_info_500.xlsx', 'times.txt')
heap_sort('flight_info_500.xlsx', 'times.txt')

bubble_sort('flight_info_1000.xlsx', 'times.txt')
insertation_sort('flight_info_1000.xlsx', 'times.txt')
heap_sort('flight_info_1000.xlsx', 'times.txt')

bubble_sort('flight_info_2500.xlsx', 'times.txt')
insertation_sort('flight_info_2500.xlsx', 'times.txt')
heap_sort('flight_info_2500.xlsx', 'times.txt')

bubble_sort('flight_info_5000.xlsx', 'times.txt')
insertation_sort('flight_info_5000.xlsx', 'times.txt')
heap_sort('flight_info_5000.xlsx', 'times.txt')

bubble_sort('flight_info_7500.xlsx', 'times.txt')
insertation_sort('flight_info_7500.xlsx', 'times.txt')
heap_sort('flight_info_7500.xlsx', 'times.txt')

bubble_sort('flight_info_10000.xlsx', 'times.txt')
insertation_sort('flight_info_10000.xlsx', 'times.txt')
heap_sort('flight_info_10000.xlsx', 'times.txt')


# helper data preprocessor
from src.reader import fetch_data
# custom PCA transformer
from src.pca import PCA
# custom One-Versus-Rest SVM
from src.ovr import OVR
# custom One-Versus-One SVM
from src.ovo import OVO

# scientific computing library
import numpy as np

# matplotlib backtest for missing $DISPLAY
import matplotlib
matplotlib.use('Agg')
# visualization tools
import matplotlib.pyplot as plt
import seaborn as sns
# prettify plots
plt.rcParams['figure.figsize'] = [12.0, 9.0]
sns.set_palette(sns.color_palette("muted"))
_palette = sns.color_palette("muted")
sns.set_style("ticks")

M = 121
standard = True

data = fetch_data(ratio=0.8)

X_train, y_train = data['train']

D, N = X_train.shape

pca = PCA(n_comps=M, standard=standard)

W_train = pca.fit(X_train)

X_test, y_test = data['test']
I, K = X_test.shape

W_test = pca.transform(X_test)

params = {'gamma': 2e-4, 'kernel': 'linear'}

fine = 5

# validate OVR
C_ovr = np.logspace(-5, 10, fine)
accuracy_ovr = []
for c in C_ovr:
    ovr = OVR(C=c, **params)
    ovr.fit(W_train, y_train)
    accuracy_ovr.append(ovr.score(W_test, y_test) * 100)

argmax_ovr = np.argmax(np.array(accuracy_ovr))

plt.semilogx(C_ovr, accuracy_ovr, color=_palette[0])
plt.axvline(C_ovr[argmax_ovr], color=_palette[1], lw=2)
plt.title('Cross Validation of $\mathbf{C}$ for OVR-SVM')
plt.xlabel('$\mathbf{C}$')
plt.ylabel('Recognition Accuracy [%]')
plt.savefig('data/out/c_validation_ovr.pdf', format='pdf', dpi=300)

# validate OVO
C_ovo = np.logspace(-5, 5, fine)
accuracy_ovo = []
for c in C_ovo:
    ovo = OVO(C=c, **params)
    ovo.fit(W_train, y_train)
    accuracy_ovo.append(ovo.score(W_test, y_test) * 100)

argmax_ovo = np.argmax(np.array(accuracy_ovo))

plt.figure()

plt.semilogx(C_ovo, accuracy_ovo, color=_palette[0])
plt.axvline(C_ovo[argmax_ovo], color=_palette[1], lw=2)
plt.title('Cross Validation of $\mathbf{C}$ for OVO-SVM')
plt.xlabel('$\mathbf{C}$')
plt.ylabel('Recognition Accuracy [%]')
plt.savefig('data/out/c_validation_ovo.pdf', format='pdf', dpi=300)


def count_vowels(word):
    vowels = "aeiouAEIOU"
    count = 0
    for char in word:
        if char in vowels:
            count += 1
    return count

def filter_by_voyel(word_list, N):
    filtered_list = []
    for word in word_list:
        if count_vowels(word) >= N:
            filtered_list.append(word)
    return filtered_list

words = []
a=0
while True:
    word= str(input("Entrez une liste de chaîne de caractères : "))
    if word == "":
        break
    words.append(word)

N = int(input("Entrez un nombre N : "))

filtered_words = filter_by_voyel(words, N)
print("Mots avec au moins", N, "voyelle(s) :", filtered_words)


#Ejercicio 1 - Eliminar los elementos repetidos de una lista

lista = [1,2,3, "Lina", 2,1,2, "Lina",3]

print(lista)

conjunto = set(lista)

lista = list(conjunto)

print(lista)

#otra forma:

lista1 = [1,2,3, "Lina", 2,1,2, "Lina",3]

lista1 = list(set(lista1))

print(lista1)


#!/usr/bin/env python3

import sys
import os
from app import root_url
import unittest
from unittest.mock import MagicMock
from tempfile import TemporaryDirectory
import json
from wsgiref.validate import validator
from wsgiref.util import setup_testing_defaults
from io import BytesIO

sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from woof.resource import MetaResource
from woof.server import RESTServer, config

class WSGIMockServer:

    def __init__(self, application):
        self.application = validator(application)
        self.responce = ""
        self.environ = {}
        self.start_response = MagicMock()

    def assert_response_is(self, expected):
        if self.responce != expected:
            raise AssertionError('Expected response: {}\nActual response: {}'
                                 .format(expected, self.response))

    def _run_app(self, path, query_string='', body=''):
        if isinstance(body, str):
            body = body.encode('utf-8')

        self.environ['PATH_INFO'] = path
        self.environ['QUERY_STRING'] = query_string
        self.environ['CONTENT_LENGTH'] = str(len(body))
        self.environ['wsgi.input'] = BytesIO(body)
        self.start_response.reset_mock()
        iterator = self.application(self.environ, self.start_response)
        try:
            self.responce = b''.join(list(iterator))
        except:
            raise
        finally:
            iterator.close()
        return self.responce

    def __getattr__(self, name):
        if name in ('get', 'delete', 'post', 'put',
                    'options', 'head', 'trace', 'connect'):
            self.environ = {}
            setup_testing_defaults(self.environ)
            self.environ['REQUEST_METHOD'] = name.upper()
            return self._run_app
        raise AttributeError("'WSGIMockServer' object has no attribute '{}'"
                             .format(name))

class TestCrud(unittest.TestCase):

    def AssertJsonEqual(self, serialized, expected):
        self.assertEqual(json.loads(serialized.decode('utf-8')), expected)

    def AssertStatusEquals(self, status):
        try:
            self.assertEqual(self.server.start_response.call_args[0][0], status)
        except IndexError:
            self.fail("start_response method hasn't called with status")

    @classmethod
    def setUpClass(cls):
        cls.tmp_dir = TemporaryDirectory()
        with open('config.json', 'w') as conf_file:
            conf_file.write(
                '{'
                    '"database": {'
                        '"provider": "sqlite",'
                        '"database": "%s"'
                    '}'
                '}' % os.path.join(cls.tmp_dir.name, 'test.db'))

        MetaResource.initialize(config.database)
        MetaResource.create_tables()
        application = RESTServer(root_url)
        cls.server = WSGIMockServer(application)
        cls.saved_books = []

    def test_01_select_books(self):
        books = self.server.get('/api/books', '')
        self.assertEqual(books, b'[]')

    def test_02_create_book(self):
        book = dict(title='Martine to the cinema',
                    abstract='Martine go to the cinema with Chuck Noris')

        expected_book = dict(id=1, chapters=[])
        expected_book.update(book)

        created_book = self.server.post('/api/books', '', json.dumps(book))

        self.saved_books.append(expected_book)
        self.AssertJsonEqual(created_book, expected_book)

    def test_03_create_book(self):
        book = dict(title='The life of Martine',
                    abstract='Martine has a hetic life')

        expected_book = dict(id=2, chapters=[])
        expected_book.update(book)

        created_book = self.server.post('/api/books', '', json.dumps(book))

        self.saved_books.append(expected_book)
        self.AssertJsonEqual(created_book, expected_book)

    def test_04_select_books(self):
        books = self.server.get('/api/books', '')
        self.AssertJsonEqual(books, self.saved_books)

    def test_05_select_one_book(self):
        book = self.server.get('/api/books/1', '')
        self.AssertJsonEqual(book, self.saved_books[0])

    def test_06_select_not_existing_book(self):
        book = self.server.get('/api/books/342', '')
        self.AssertStatusEquals('404 Not Found')
        self.AssertJsonEqual(book, {'error': 'Resource not found'})

    def test_07_update_books(self):
        book = dict(title='Martine go to the cinema',
                    abstract='Martine go to the cinema with Chuck Noris')
        updated = self.server.put('/api/books/1', '', json.dumps(book))
        book.update(dict(id=1, chapters=[]))
        self.AssertJsonEqual(updated, book)

    def test_08_create_chapter(self):
        chapter = dict(number=1, title="First step")
        created = self.server.post('/api/books/1/chapters', '', json.dumps(chapter))
        chapter['book_id'] = 1
        self.AssertJsonEqual(created, chapter)

    def test_09_create_chapter(self):
        chapter = dict(number=1, title="Init")
        created = self.server.post('/api/books/2/chapters', '', json.dumps(chapter))
        chapter['book_id'] = 2
        self.AssertJsonEqual(created, chapter)

    def test_10_update_chapter(self):
        chapter = dict(number=1, title="Introduction")
        updated = self.server.put('/api/books/1/chapters/1', '', json.dumps(chapter))
        chapter['book_id'] = 1
        self.AssertJsonEqual(updated, chapter)

    def test_11_select_chapter(self):
        chapter = self.server.get('/api/books/1/chapters/1', '')
        expected = dict(book_id=1, number=1, title="Introduction")
        self.AssertJsonEqual(chapter, expected)

    def test_12_select_chapters(self):
        chapter = self.server.get('/api/books/1/chapters', '')
        expected = [{"book_id": 1, "number": 1, "title": "Introduction"}]
        self.AssertJsonEqual(chapter, expected)

    def test_13_select_chapters(self):
        chapter = self.server.get('/api/books/2/chapters', '')
        expected = [{"book_id": 2, "number": 1, "title": "Init"}]
        self.AssertJsonEqual(chapter, expected)

    def test_14_delete_chapter(self):
        chapter = self.server.delete('/api/books/1/chapters/1', '')
        self.AssertJsonEqual(chapter, '')

    def test_15_select_chapters(self):
        chapter = self.server.get('/api/books/1/chapters', '')
        expected = []
        self.AssertJsonEqual(chapter, expected)

    def test_16_select_chapters(self):
        chapter = self.server.get('/api/books/2/chapters', '')
        expected = [{"book_id": 2, "number": 1, "title": "Init"}]
        self.AssertJsonEqual(chapter, expected)

    @classmethod
    def tearDownClass(cls):
        cls.tmp_dir.cleanup()
        os.remove('config.json')


# See also:
# https://click.palletsprojects.com/en/7.x/setuptools/#setuptools-integration
# https://click.palletsprojects.com/en/7.x/arguments/

import sys
from typing import Tuple

import click
from click_default_group import DefaultGroup

from dotenv_linter.checker import DotenvFileChecker
from dotenv_linter.version import pkg_version

@click.group(
    cls=DefaultGroup,
    default='lint',
    default_if_no_args=True,
    invoke_without_command=True,
)
@click.option('--version', is_flag=True, default=False)
def cli(version):
    """
    Main entrypoint to the app.

    Runs ``lint`` command by default if nothing else is not specified.
    Runs ``--version`` subcommand if this option is provided.
    """
    if version:
        print(pkg_version)  # noqa: WPS421

@cli.command()
@click.argument(
    'files',
    nargs=-1,
    required=True,
    type=click.Path(exists=True, dir_okay=False),
)
def lint(files: Tuple[str, ...]):
    """Runs linting process for the given files."""
    checker = DotenvFileChecker(files)

    try:
        checker.run()
    except Exception as ex:
        print(ex, file=sys.stderr)  # noqa: WPS421
        checker.fail()


#!/usr/bin/env python3
#!coding=utf-8
#
import sys
print(sys.version)
########################
from selenium import webdriver
import time
import random
#from bs4 import BeautifulSoup
import re
print("-"*10,"import end","-"*10)
########
def requestitem(url, pattern):
    # 爬取特定url页面内容
    driver = webdriver.Chrome(executable_path='/Users/shzy/seleniumwebdriver/chromedriver')
    driver.get(url)
    sleeptime = random.randint(2,5)
    print('time--'+str(sleeptime))
    time.sleep(sleeptime)
    content = driver.page_source
    driver.close()
    ##############
    items = re.findall(pattern, content)
    ######## 爬取收藏夹名称
    pattern0 = r'PageHeader-title">(.*?)
'
    try:
        items2 = re.search(pattern0, content).group(1)
    except:
        items2 = str(random.randint(1,10))
    ############## 打印看效果
    for i1, item in enumerate(items):
        print(i1, item)
    return items, items2
    ###############

def requestPage(url, pattern):
    # 爬取特定url页面内容
    driver = webdriver.Chrome(executable_path='/Users/shzy/seleniumwebdriver/chromedriver')
    driver.get(url)
    sleeptime = random.randint(2,5)
    print('time--'+str(sleeptime))
    time.sleep(sleeptime)
    content = driver.page_source
    driver.close()
    ##############
    items = re.findall(pattern, content)
    ############## 打印看效果
    #for i1, item in enumerate(items):
    #    print(i1, item)
    return items
   #^^^^^^^END

########################
def craw_folder(urlx, allpage, outfile):
    ######## 爬取收藏夹内容
#    pattern = r'(.*?)'
    pattern = r'(.*?)'
    for i1 in range(allpage):
        urli = urlx+str(i1+1)
        # 爬取一页
        print(urli)
        itemi, foldernamei = requestitem(urli, pattern)
        ff = open(outfile, 'a')
        for ii, i11 in enumerate(itemi):
            print(str(i1+1)+'\t'+str(ii)+'\t'+i11[0]+'\t'+i11[1]+'\t'+foldernamei, file=ff)
        ff.close()
   #^^^^^^^END

def readinCollection(filepath):
    # 读入收藏夹名与url清单
    ff = open(filepath, 'r')
    namelst = []
    urllst = []
    for i1 in ff:
        i1 = i1.replace('\n', '')
        print(i1)
        namelst.append(i1.split(' ')[0])
        urllst.append(i1.split(' ')[1])
    ff.close()
    return namelst, urllst
   #^^^^^^^END

###############################################################################
######## 爬取收藏夹内容
#url_collections = 'https://www.zhihu.com/people/wahaha50/collections'
namelst, urllst = readinCollection('./收藏夹信息.txt')
######### 获取每个收藏夹的最大页数
pa = '<button type="button" class="Button PaginationButton Button--plain">(.*?)</button>'
pagelst = []
for ci in urllst:
    items = requestPage(ci, pa)
    allpage = [int(i) for i in items]
    try:
        maxpage = max(allpage)
    except:
        maxpage = 1
    pagelst.append(maxpage)
print(pagelst)
######## 具体爬取每个收藏夹
for ii, urli in enumerate(urllst):
    craw_folder(urli+'?page=', pagelst[ii], 'alllist.txt')


#Julio Alexis González Villa 220839961
#Natalie Xiomara Moreno Bautista  220839996

#----------------------------------Actividad 7_Detección de Colores------------------------------------

import serial
import numpy as np
import pickle

serialPort = serial.Serial(port = "COM3", baudrate=9600)
serialString = ""

color = ['Rojo','Naranja','Amarillo','Verde','Limon','Azul','Marino','Cielo','Rosa','Morado','Cafe','Negro','Gris','Blanco']

model = pickle.load(open('act_7_colores.sav','rb'))

N = 100
i = 0

while(i<N):
    if(serialPort.in_waiting > 0):
        serialString = serialPort.readline()
        # print(serialString.decode('Ascii'))

        data_in = serialString.decode('Ascii')
        data_in = data_in.split(sep=',')
        data_in.pop()

        if(len(data_in)==4):
            data = [float(j) for j in data_in]
            data_array = np.asanyarray(data)

            y = model.predict(data_array.reshape(-1, 4))
            #i = i + 1
            d = y[0]
            print('iteration:',i,', data=',data_in, ', color=', color[d])
            i = i + 1

serialPort.close()

Python/Actividad 7 - Detector de colores/Act_7_Deteccion.py


def fiboSequence(n):
    a = 0
    b = 1
    print(f'{a} {b} ',end='')
    for i in range(2,n):
        c = a+b
        print(c,end=' ')
        a = b
        b = c

def fibo(n):
    if n == 0 or n == 1:
        return n

    return fibo(n-1)+fibo(n-2)

def memoizedFibo(n):
    fiboTable = {}
    # If the value is present in the list, return the value.
    # No need to re-compute the value.
    if fiboTable[n]:
        return fiboTable[n]
    if n == 0 or n == 1:
        return n
    # Compute the value
    value = fiboSequence(n-1)+fiboSequence(n-2)
    # Store the value in the dictionary
    fiboTable[n] = value

# Dynamic Programming
fiboTable = {}

def dynamicFiboSequence(n):
    global fiboTable
    fiboTable[0] = 0
    fiboTable[1] = 1
    for iter in range(2,n):
        fiboTable[iter] = fiboTable[iter-1] + fiboTable[iter-2]

    return list(fiboTable.values())

def dynamicFiboValue(n):
    global fiboTable
    fiboTable[0] = 0
    fiboTable[1] = 1

    try:
        # Base case
        return fiboTable[n]
    except KeyError:
        fiboTable[n] = dynamicFiboValue(n-1)+dynamicFiboValue(n-2)

    return fiboTable[n]

print(dynamicFiboSequence(int(input('Enter number of elements to print: '))))

Python/Course/Programming & DSA using Python/25.py


from project.models import OperatorLog
import datetime
from django.db import models
from project.models import Project,ProjectInvestDataModel
from rest_framework.filters import OrderingFilter

def strformat(ouser,obj,otype,request):#对修改和删除的对象的具体返回格式
    #传入
    if otype=='1':#1是修改,原来是什么，现在是什么
        if isinstance(obj,Project):
            #getdata = request.data #待更新的集合
            #toupdatedata = [(i,obj.__getattribute__(i),getdata[i]) for i in getdata if getdata[i]!=obj.__getattribute__(i)]
            #项目编号和项目名称
            res = (obj.id,obj.name)
            stritem = "项目编号为{},项目名称为{};"
            return stritem.format(*res)

        elif isinstance(obj,ProjectInvestDataModel):
            afterdata = request.data
            beforedata = [obj.__getattribute__(i) for i in afterdata]
            strtest = "投资数据"+"{} "*len(afterdata)*2+"修改为" +"{} "*len(afterdata)
            result = strtest.format(*afterdata,*beforedata,*afterdata.values())
            return result

    elif otype=='0':#0是删除
        if isinstance(obj, Project):
            return "　项目申请　{}".format(repr(obj))
        elif isinstance(obj,ProjectInvestDataModel):
            return "　投资数据　{}".format(repr(obj))

def write_to_log(ouser,obj,otype,request):
    #obj对应的file,otype是operator的对应的操作type
    if isinstance(obj,models.Model):
        oobj = strformat(ouser,obj,otype,request)
    else:
        oobj=obj
    OperatorLog.objects.create(otime=datetime.datetime.now(), oman=ouser, oobj=oobj, otype=otype)


import copy
import itertools
import os
import sys
from builtins import str

import mobly.config_parser as mobly_config_parser

from acts import keys
from acts import utils

# An environment variable defining the base location for ACTS logs.
_ENV_ACTS_LOGPATH = 'ACTS_LOGPATH'
# An environment variable that enables test case failures to log stack traces.
_ENV_TEST_FAILURE_TRACEBACKS = 'ACTS_TEST_FAILURE_TRACEBACKS'
# An environment variable defining the test search paths for ACTS.
_ENV_ACTS_TESTPATHS = 'ACTS_TESTPATHS'
_PATH_SEPARATOR = ':'

class ActsConfigError(Exception):
    """Raised when there is a problem in test configuration file."""

def _validate_test_config(test_config):
    """Validates the raw configuration loaded from the config file.

    Making sure all the required fields exist.
    """
    for k in keys.Config.reserved_keys.value:
        # TODO(markdr): Remove this continue after merging this with the
        # validation done in Mobly's load_test_config_file.
        if (k == keys.Config.key_test_paths.value
                or k == keys.Config.key_log_path.value):
            continue

        if k not in test_config:
            raise ActsConfigError("Required key %s missing in test config." %
                                  k)

def _validate_testbed_name(name):
    """Validates the name of a test bed.

    Since test bed names are used as part of the test run id, it needs to meet
    certain requirements.

    Args:
        name: The test bed's name specified in config file.

    Raises:
        If the name does not meet any criteria, ActsConfigError is raised.
    """
    if not name:
        raise ActsConfigError("Test bed names can't be empty.")
    if not isinstance(name, str):
        raise ActsConfigError("Test bed names have to be string.")
    for l in name:
        if l not in utils.valid_filename_chars:
            raise ActsConfigError(
                "Char '%s' is not allowed in test bed names." % l)

def _update_file_paths(config, config_path):
    """ Checks if the path entries are valid.

    If the file path is invalid, assume it is a relative path and append
    that to the config file path.

    Args:
        config : the config object to verify.
        config_path : The path to the config file, which can be used to
                      generate absolute paths from relative paths in configs.

    Raises:
        If the file path is invalid, ActsConfigError is raised.
    """
    # Check the file_path_keys and update if it is a relative path.
    for file_path_key in keys.Config.file_path_keys.value:
        if file_path_key in config:
            config_file = config[file_path_key]
            if type(config_file) is str:
                if not os.path.isfile(config_file):
                    config_file = os.path.join(config_path, config_file)
                if not os.path.isfile(config_file):
                    raise ActsConfigError(
                        "Unable to load config %s from test "
                        "config file.", config_file)
                config[file_path_key] = config_file

def _validate_testbed_configs(testbed_configs, config_path):
    """Validates the testbed configurations.

    Args:
        testbed_configs: A list of testbed configuration json objects.
        config_path : The path to the config file, which can be used to
                      generate absolute paths from relative paths in configs.

    Raises:
        If any part of the configuration is invalid, ActsConfigError is raised.
    """
    # Cross checks testbed configs for resource conflicts.
    for name, config in testbed_configs.items():
        _update_file_paths(config, config_path)
        _validate_testbed_name(name)

def gen_term_signal_handler(test_runners):
    def termination_sig_handler(signal_num, frame):
        print('Received sigterm %s.' % signal_num)
        for t in test_runners:
            t.stop()
        sys.exit(1)

    return termination_sig_handler

def _parse_one_test_specifier(item):
    """Parse one test specifier from command line input.

    Args:
        item: A string that specifies a test class or test cases in one test
            class to run.

    Returns:
        A tuple of a string and a list of strings. The string is the test class
        name, the list of strings is a list of test case names. The list can be
        None.
    """
    tokens = item.split(':')
    if len(tokens) > 2:
        raise ActsConfigError("Syntax error in test specifier %s" % item)
    if len(tokens) == 1:
        # This should be considered a test class name
        test_cls_name = tokens[0]
        return test_cls_name, None
    elif len(tokens) == 2:
        # This should be considered a test class name followed by
        # a list of test case names.
        test_cls_name, test_case_names = tokens
        clean_names = [elem.strip() for elem in test_case_names.split(',')]
        return test_cls_name, clean_names

def parse_test_list(test_list):
    """Parse user provided test list into internal format for test_runner.

    Args:
        test_list: A list of test classes/cases.
    """
    result = []
    for elem in test_list:
        result.append(_parse_one_test_specifier(elem))
    return result

def load_test_config_file(test_config_path, tb_filters=None):
    """Processes the test configuration file provided by the user.

    Loads the configuration file into a json object, unpacks each testbed
    config into its own TestRunConfig object, and validate the configuration in
    the process.

    Args:
        test_config_path: Path to the test configuration file.
        tb_filters: A subset of test bed names to be pulled from the config
                    file. If None, then all test beds will be selected.

    Returns:
        A list of mobly.config_parser.TestRunConfig objects to be passed to
        test_runner.TestRunner.
    """
    configs = utils.load_config(test_config_path)

    testbeds = configs[keys.Config.key_testbed.value]
    if type(testbeds) is list:
        tb_dict = dict()
        for testbed in testbeds:
            tb_dict[testbed[keys.Config.key_testbed_name.value]] = testbed
        testbeds = tb_dict
    elif type(testbeds) is dict:
        # For compatibility, make sure the entry name is the same as
        # the testbed's "name" entry
        for name, testbed in testbeds.items():
            testbed[keys.Config.key_testbed_name.value] = name

    if tb_filters:
        tbs = {}
        for name in tb_filters:
            if name in testbeds:
                tbs[name] = testbeds[name]
            else:
                raise ActsConfigError(
                    'Expected testbed named "%s", but none was found. Check'
                    'if you have the correct testbed names.' % name)
        testbeds = tbs

    if (keys.Config.key_log_path.value not in configs
            and _ENV_ACTS_LOGPATH in os.environ):
        print('Using environment log path: %s' %
              (os.environ[_ENV_ACTS_LOGPATH]))
        configs[keys.Config.key_log_path.value] = os.environ[_ENV_ACTS_LOGPATH]
    if (keys.Config.key_test_paths.value not in configs
            and _ENV_ACTS_TESTPATHS in os.environ):
        print('Using environment test paths: %s' %
              (os.environ[_ENV_ACTS_TESTPATHS]))
        configs[keys.Config.key_test_paths.
                value] = os.environ[_ENV_ACTS_TESTPATHS].split(_PATH_SEPARATOR)
    if (keys.Config.key_test_failure_tracebacks not in configs
            and _ENV_TEST_FAILURE_TRACEBACKS in os.environ):
        configs[keys.Config.key_test_failure_tracebacks.
                value] = os.environ[_ENV_TEST_FAILURE_TRACEBACKS]

    # TODO: See if there is a better way to do this: b/29836695
    config_path, _ = os.path.split(utils.abs_path(test_config_path))
    configs[keys.Config.key_config_path.value] = config_path
    _validate_test_config(configs)
    _validate_testbed_configs(testbeds, config_path)
    # Unpack testbeds into separate json objects.
    configs.pop(keys.Config.key_testbed.value)
    test_run_configs = []

    for _, testbed in testbeds.items():
        test_run_config = mobly_config_parser.TestRunConfig()
        test_run_config.testbed_name = testbed[
            keys.Config.key_testbed_name.value]
        test_run_config.controller_configs = testbed
        test_run_config.controller_configs[
            keys.Config.key_test_paths.value] = configs.get(
                keys.Config.key_test_paths.value, None)
        test_run_config.log_path = configs.get(keys.Config.key_log_path.value,
                                               None)
        if test_run_config.log_path is not None:
            test_run_config.log_path = utils.abs_path(test_run_config.log_path)

        user_param_pairs = []
        for item in itertools.chain(configs.items(), testbed.items()):
            if item[0] not in keys.Config.reserved_keys.value:
                user_param_pairs.append(item)
        test_run_config.user_params = dict(user_param_pairs)

        test_run_configs.append(test_run_config)
    return test_run_configs

def parse_test_file(fpath):
    """Parses a test file that contains test specifiers.

    Args:
        fpath: A string that is the path to the test file to parse.

    Returns:
        A list of strings, each is a test specifier.
    """
    with open(fpath, 'r') as f:
        tf = []
        for line in f:
            line = line.strip()
            if not line:
                continue
            if len(tf) and (tf[-1].endswith(':') or tf[-1].endswith(',')):
                tf[-1] += line
            else:
                tf.append(line)
        return tf