#!/usr/bin/env python
# coding:utf-8
import tempfile

import os
import pytest

import meshroom.core
from meshroom.core import desc, registerNodeType, unregisterNodeType
from meshroom.core.exception import NodeUpgradeError
from meshroom.core.graph import Graph, loadGraph
from meshroom.core.node import CompatibilityNode, CompatibilityIssue, Node

class SampleNodeV1(desc.Node):
    """ Version 1 Sample Node """
    inputs = [
        desc.File(name='input', label='Input', description='', value='', uid=[0],),
        desc.StringParam(name='paramA', label='ParamA', description='', value='', uid=[])  # No impact on UID
    ]
    outputs = [
        desc.File(name='output', label='Output', description='', value=desc.Node.internalFolder, uid=[])
    ]

class SampleNodeV2(desc.Node):
    """ Changes from V1:
        * 'input' has been renamed to 'in'
    """
    inputs = [
        desc.File(name='in', label='Input', description='', value='', uid=[0],),
        desc.StringParam(name='paramA', label='ParamA', description='', value='', uid=[])  # No impact on UID
    ]
    outputs = [
        desc.File(name='output', label='Output', description='', value=desc.Node.internalFolder, uid=[])
    ]

def test_unknown_node_type():
    """
    Test compatibility behavior for unknown node type.
    """
    registerNodeType(SampleNodeV1)
    g = Graph('')
    n = g.addNewNode("SampleNodeV1", input="/dev/null", paramA="foo")
    graphFile = os.path.join(tempfile.mkdtemp(), "test_unknown_node_type.mg")
    g.save(graphFile)
    internalFolder = n.internalFolder
    nodeName = n.name
    unregisterNodeType(SampleNodeV1)

    # reload file
    g = loadGraph(graphFile)
    os.remove(graphFile)

    assert len(g.nodes) == 1
    n = g.node(nodeName)
    # SampleNodeV1 is now an unknown type
    # check node instance type and compatibility issue type
    assert isinstance(n, CompatibilityNode)
    assert n.issue == CompatibilityIssue.UnknownNodeType
    # check if attributes are properly restored
    assert len(n.attributes) == 3
    assert n.input.isInput
    assert n.output.isOutput
    # check if internal folder
    assert n.internalFolder == internalFolder

    # upgrade can't be perform on unknown node types
    assert not n.canUpgrade
    with pytest.raises(NodeUpgradeError):
        g.upgradeNode(nodeName)

def test_description_conflict():
    """
    Test compatibility behavior for conflicting node descriptions.
    """
    registerNodeType(SampleNodeV1)

    g = Graph('')
    n = g.addNewNode("SampleNodeV1")
    graphFile = os.path.join(tempfile.mkdtemp(), "test_description_conflict.mg")
    g.save(graphFile)
    internalFolder = n.internalFolder
    nodeName = n.name

    # replace SampleNodeV1 by SampleNodeV2
    # 'SampleNodeV1' is still registered but implementation has changed
    meshroom.core.nodesDesc[SampleNodeV1.__name__] = SampleNodeV2

    # reload file
    g = loadGraph(graphFile)
    os.remove(graphFile)

    assert len(g.nodes) == 1
    n = g.node(nodeName)
    # Node description clashes between what has been saved
    assert isinstance(n, CompatibilityNode)
    assert n.issue == CompatibilityIssue.DescriptionConflict
    assert len(n.attributes) == 3
    assert hasattr(n, "input")
    assert not hasattr(n, "in")
    assert n.internalFolder == internalFolder

    # perform upgrade
    g.upgradeNode(nodeName)
    n = g.node(nodeName)

    assert isinstance(n, Node)
    assert not hasattr(n, "input")
    assert hasattr(n, "in")
    # check uid has changed (not the same set of attributes)
    assert n.internalFolder != internalFolder
    unregisterNodeType(SampleNodeV1)

def test_upgradeAllNodes():
    registerNodeType(SampleNodeV1)
    registerNodeType(SampleNodeV2)

    g = Graph('')
    n1 = g.addNewNode("SampleNodeV1")
    n2 = g.addNewNode("SampleNodeV2")
    n1Name = n1.name
    n2Name = n2.name
    graphFile = os.path.join(tempfile.mkdtemp(), "test_description_conflict.mg")
    g.save(graphFile)

    # make SampleNodeV2 an unknown type
    unregisterNodeType(SampleNodeV2)
    # replace SampleNodeV1 by SampleNodeV2
    meshroom.core.nodesDesc[SampleNodeV1.__name__] = SampleNodeV2

    # reload file
    g = loadGraph(graphFile)
    os.remove(graphFile)

    # both nodes are CompatibilityNodes
    assert len(g.compatibilityNodes) == 2
    assert g.node(n1Name).canUpgrade      # description conflict
    assert not g.node(n2Name).canUpgrade  # unknown type

    # upgrade all upgradable nodes
    g.upgradeAllNodes()

    # only the node with an unknown type has not been upgraded
    assert len(g.compatibilityNodes) == 1
    assert n2Name in g.compatibilityNodes.keys()

    unregisterNodeType(SampleNodeV1)


"""
Given a set of parameters, simulates two rounds of PCR with a binomial
selection in between them.
"""

import random
import argparse
import time
import multiprocessing as mp

import numpy as np

MUTATOR = {
    '0': ['1', '2', '3'],
    '1': ['0', '2', '3'],
    '2': ['0', '1', '3'],
    '3': ['0', '1', '2']
}

def pcr_simulator(population, polymerase_error, pcr_efficiency, nbp, cycles):

    population_size = sum(population.values())
    start = time.time()

    range_bp = range(0, nbp)

    # pre draw large sample from binomial distribution for how many
    # mutations a sequence gets after PCR amplification
    # this step to save on some computational efficiency

    num_mutation_draws = 10000000
    num_mutations = np.random.binomial(
        nbp,
        polymerase_error,
        num_mutation_draws
    )
    num_mutations_counter = 0

    for cycle in range(0, cycles):

        population_t = population.items()
        pcr_sampling = np.random.binomial(
            [i[1] for i in population_t], pcr_efficiency)
        population_t = [
            [i[0], i[1], j] for i, j in zip(population_t, pcr_sampling)]

        for seq, count, pcr_sample in population_t:

            if pcr_sample > num_mutation_draws:
                num_mutation_draws = pcr_sample
                num_mutations = np.random.binomial(
                    nbp,
                    polymerase_error,
                    pcr_sample
                )
                num_mutations_counter = 0
            if (num_mutations_counter+pcr_sample) > num_mutation_draws:
                np.random.shuffle(num_mutations)
                num_mutations_counter = 0

            # sample how many mutations occur on the sequences chosen for
            # PCR amplification

            mutations_nn = num_mutations[
                num_mutations_counter:(num_mutations_counter+pcr_sample)]
            num_mutations_counter += pcr_sample

            # increment the current popluation by number of sequences
            # that do not get mutated
            population[seq] += np.count_nonzero(mutations_nn == 0)

            # randomly select base pair locations for mutation

            mutations_nn = mutations_nn[mutations_nn != 0]
            mutations_select = [
                random.sample(range_bp, i) for i in mutations_nn]

            for i in range(0, len(mutations_nn)):
                for mm in mutations_select[i]:
                    seq_new = seq[0:mm] + random.sample(
                        MUTATOR[seq[mm]], 1)[0] + seq[(mm+1):]
                if seq_new in population:
                    population[seq_new] += 1
                else:
                    population[seq_new] = 1
        # print 'Cycle: ' + str(cycle+1) + ' - ' + str(time.time() - start), str(sum(population.values()))

    return population, sum(population.values())

def simulation(x, args):
    population = {'0'*args.nbp: args.initpop}

    # REPLI-g simulation

    population, population_size = pcr_simulator(
        population=population,
        polymerase_error=args.polymerase_error_replig,
        pcr_efficiency=args.pcr_efficiency_replig,
        nbp=args.nbp,
        cycles=args.cycles_replig
    )

    # sample from the REPLI-g preduct for TruSeq PCR

    for seq, count in population.items():
        population[seq] = np.random.binomial(count, args.replig_sampling)
    for seq, count in population.items():
        if count == 0:
            population.pop(seq, None)

    population_size = sum(population.values())

    # TruSeq simulation

    population, population_size = pcr_simulator(
        population=population,
        polymerase_error=args.polymerase_error_truseq,
        pcr_efficiency=args.pcr_efficiency_truseq,
        nbp=args.nbp,
        cycles=args.cycles_truseq
    )

    # format the output data

    data = []
    for i in range(0, args.nbp):
        n_wt = 0
        n_mut_1 = 0
        n_mut_2 = 0
        n_mut_3 = 0
        for seq, count in population.items():
            if seq[i] == '0':
                n_wt += count
            elif seq[i] == '1':
                n_mut_1 += count
            elif seq[i] == '2':
                n_mut_2 += count
            elif seq[i] == '3':
                n_mut_3 += count
        total = n_wt + n_mut_1 + n_mut_2 + n_mut_3
        data += [n_mut_1, n_mut_2, n_mut_3]

    data = map(lambda x: str(x), data)
    print('Done with iteration: {}'.format(x))

    return str(total), data

def main(args):

    if args.p > 1:
        pool = mp.Pool(processes=args.p)
        results = [pool.apply_async(
            simulation, args=(x, args,)) for x in range(0, args.n)]
        results = [p.get() for p in results]
    else:
        results = [simulation(1, args)]

    totals = [i[0] for i in results]
    data = [i[1] for i in results]
    fout = open(args.prefix + '.csv', 'w')
    fout.write(','.join(map(lambda x: str(x), range(1, args.n+1))) + '\n')
    fout.write(','.join(totals) + '\n')
    for i in range(0, len(data[0])):
        fout.write(
            ','.join(map(lambda x: x[i], data)) + '\n'
        )
    fout.close()

parser = argparse.ArgumentParser()
parser.add_argument(
    '--initpop',
    type=int,
    required=True
)
parser.add_argument(
    '--polymerase_error_truseq',
    type=float,
    required=True
)
parser.add_argument(
    '--polymerase_error_replig',
    type=float,
    required=True
)
parser.add_argument(
    '--cycles_truseq',
    type=int,
    required=True
)
parser.add_argument(
    '--cycles_replig',
    type=int,
    required=True
)
parser.add_argument(
    '--pcr_efficiency_truseq',
    type=float,
    required=True
)
parser.add_argument(
    '--pcr_efficiency_replig',
    type=float,
    required=True
)
parser.add_argument(
    '--replig_sampling',
    type=float,
    required=True
)
parser.add_argument(
    '--nbp',
    type=int,
    required=False,
    default=3172
)
parser.add_argument(
    '--n',
    type=int,
    required=False,
    default=1,
    help='Number replicates.'
)
parser.add_argument(
    '--p',
    type=int,
    required=False,
    default=1,
    help='Number cores.'
)
parser.add_argument(
    '--prefix',
    type=str,
    required=True,
    help='Output prefix'
)
args = parser.parse_args()

main(args)


from django.db.models.enums import TextChoices
from django.db.models.fields import TextField
from django.db.models.query import QuerySet
from django.forms.models import inlineformset_factory, modelform_factory
from django.forms.widgets import CheckboxSelectMultiple, RadioSelect, SelectMultiple, TextInput, Textarea
from django.shortcuts import render, get_object_or_404

from ComunicOral.forms import ComunicOralForm
from ressonancia.models import Ressonancia
from tipodevoz.forms import TipoVozForm
from .models import AtaqueVocalCad, AvaliacaoAD, ComunicOralidade, ComunicOral, LoudnessCad, PitchCad, RessonanciaCad, TipoVozCad, AtaqueVocalCad, PitchCad, ModulacaoCad, QualidadeemisCad
from avaliacaoAD.forms import AtaqueVocalCadForm, AvaliacaoAD, AvaliacaoADForm, ComunicOralidadeForm, PitchCadForm, RessonanciaCadForm, TipodeVozCadForm, AtaqueVocalCadForm, PitchCadForm, ModulacaoCadForm, QualidadeemisCadForm

def avaliacaoad(request):
    if request.method == 'GET':
        avaliacaoads = AvaliacaoAD.objects.all()
        #comunicoralidades = ComunicOralidade.objects.all()
        form = AvaliacaoADForm()
        formoralidade_factory = inlineformset_factory(AvaliacaoAD, ComunicOralidade, form=ComunicOralidadeForm, extra=9, can_delete=False, widgets={"ComunicOral": TextInput(), "resp_oralidade": RadioSelect()}, fields=('ComunicOral','resp_oralidade',), labels={'ComunicOral' : 'Pergunta','resp_oralidade': 'Resposta'})
        #formoralidade_factory = inlineformset_factory(AvaliacaoAD, ComunicOralidade, form=ComunicOralidadeForm, extra=9, can_delete=False)
        #formoralidade_factory = modelform_factory(AvaliacaoAD, ComunicOralidade, form=ComunicOralidadeForm)

        formtipodevozcad_factory = inlineformset_factory(AvaliacaoAD, TipoVozCad, form=TipodeVozCadForm, extra=11, can_delete=False)
        formressoanacia_factory = inlineformset_factory(AvaliacaoAD, RessonanciaCad, form=RessonanciaCadForm, extra=4, can_delete=False)
        formataquevocal_factory = inlineformset_factory(AvaliacaoAD, AtaqueVocalCad, form=AtaqueVocalCadForm, extra=3, can_delete=False)
        formpitch_factory = inlineformset_factory(AvaliacaoAD, PitchCad, form=PitchCadForm, extra=3, can_delete=False)
        formloudness_factory = inlineformset_factory(AvaliacaoAD, LoudnessCad, form=PitchCadForm, extra=3, can_delete=False)
        formmodulacao_factory = inlineformset_factory(AvaliacaoAD, ModulacaoCad, form=PitchCadForm, extra=3, can_delete=False)
        formqualidadeemis_factory = inlineformset_factory(AvaliacaoAD, QualidadeemisCad, form=QualidadeemisCadForm, extra=4, can_delete=False)

        formoralidade = formoralidade_factory()
        formtipodevozcad = formtipodevozcad_factory()
        formressonanciacad = formressoanacia_factory()
        formataquevocalcad = formataquevocal_factory()
        formpitchcad = formpitch_factory()
        formloudnesscad = formloudness_factory()
        formmodulacaocad = formmodulacao_factory()
        formqualidadeemis  = formqualidadeemis_factory()

        context = {
            'avaliacaoads': avaliacaoads,
            'form': form,
            'formoralidade': formoralidade,
            'formtipodevozcad' : formtipodevozcad,
            'formressonanciacad' : formressonanciacad,
            'formataquevocalcad' : formataquevocalcad,
            'formpitchcad' : formpitchcad,
            'formloudnesscad' : formloudnesscad,
            'formmodulacaocad' : formmodulacaocad,
            'formqualidadeemis' : formqualidadeemis,
        }
        return render(request, 'avaliacaoad.html', context=context)
    elif request.method == 'POST':
        form = AvaliacaoADForm(request.POST)
        #formoralidade_factory = inlineformset_factory(AvaliacaoAD, ComunicOralidade, form=ComunicOralidadeForm, can_delete=False, widgets={"ComunicOral": Textarea(), "resp_oralidade": RadioSelect()})
        #formoralidade_factory = modelform_factory(AvaliacaoAD, ComunicOralidade, form=ComunicOralidadeForm)
        formoralidade_factory = inlineformset_factory(AvaliacaoAD, ComunicOralidade, form=ComunicOralidadeForm, can_delete=False)
        formtipodevozcad_factory = inlineformset_factory(AvaliacaoAD, TipoVozCad, form=TipodeVozCadForm, can_delete=False)
        formressoanacia_factory = inlineformset_factory(AvaliacaoAD, RessonanciaCad, form=RessonanciaCad, can_delete=False)
        formataquevocal_factory = inlineformset_factory(AvaliacaoAD, RessonanciaCad, form=AtaqueVocalCad, can_delete=False)
        formpitch_factory = inlineformset_factory(AvaliacaoAD, PitchCad, form=PitchCadForm, extra=3, can_delete=False)
        formloudness_factory = inlineformset_factory(AvaliacaoAD, LoudnessCad, form=PitchCadForm, extra=3, can_delete=False)
        formmodulacao_factory = inlineformset_factory(AvaliacaoAD, ModulacaoCad, form=PitchCadForm, extra=3)
        formqualidadeemis_factory = inlineformset_factory(AvaliacaoAD, QualidadeemisCad, form=QualidadeemisCadForm, extra=4, can_delete=False)

        formoralidade = formoralidade_factory(request.POST)
        formtipodevozcad = formtipodevozcad_factory(request.POST)
        formressonanciacad = formressoanacia_factory(request.POST)
        formataquevocalcad = formataquevocal_factory(request.POST)
        formpitchcad = formpitch_factory(request.POST)
        formloudnesscad = formloudness_factory(request.POST)
        formmodulacaocad = formmodulacao_factory(request.POST)
        formqualidadeemiscad = formqualidadeemis_factory(request.POST)

        if form.is_valid() and formoralidade.is_valid() and formtipodevozcad.is_valid() and formressonanciacad.is_valid() and formataquevocalcad.is_valid() and formpitchcad.is_valid and formloudnesscad.is_valid and formmodulacaocad.is_valid and formqualidadeemiscad.is_valid:
            avaliacao = form.save()
            formoralidade.instance = avaliacao
            formtipodevozcad.instance = avaliacao
            formressonanciacad.instance = avaliacao
            formataquevocalcad.instance = avaliacao
            formpitchcad.instance = avaliacao
            formloudnesscad.instance = avaliacao
            formoralidade.save()
            formtipodevozcad.save()
            formressonanciacad.save()
            formataquevocalcad.save()
            formpitchcad.save()
            formloudnesscad.save()
            formmodulacaocad.save()
            formqualidadeemiscad.save()

            form = AvaliacaoADForm()
            formoralidade = ComunicOralidadeForm()
            formtipodevozcad = TipodeVozCadForm()
            formressonanciacad = RessonanciaCadForm()
            formataquevocalcad = AtaqueVocalCadForm()
            formpitchcad = PitchCadForm()
            formloudnesscad = LoudnessCad()
            formmodulacaocad = ModulacaoCad()
            formqualidadeemis = QualidadeemisCad()

        context = {
            'form' : form,
            'formoralidade' : formoralidade,
            'formtipodevozcad': formtipodevozcad,
            'formressonanciacad': formressonanciacad,
            'formataquevocalcad' : formataquevocalcad,
            'formpitchcad': formpitchcad,
            'formloudnesscad' : formloudnesscad,
            'formmodulacaocad': formmodulacaocad,
            'formqualidadeemis': formqualidadeemis,

        }

        return render(request, 'avaliacaoad.html', context=context)

"""def avaliacaoad(request):
    if request.method == 'GET':
        avaliacaoads = AvaliacaoAD.objects.all()
        form = AvaliacaoADForm()
        formoralidade_factory = modelform_factory(ComunicOralidade, ComunicOralidadeForm,fields=('ComunicOral', 'resp_oralidade'),localized_fields='__all__')
        formoralidade = formoralidade_factory()
        #for ft in formoralidade:
        #    print(ft)
        context = {
            'form': form,
            'formoralidade': formoralidade,

        }
        return render(request, 'avaliacaoad.html', context=context)
    elif request.method == 'POST':
        form = AvaliacaoADForm(request.POST)
        formoralidade_factory = modelform_factory(ComunicOralidade, ComunicOralidadeForm,fields=('ComunicOral', 'resp_oralidade'),localized_fields='__all__')
        formoralidade = formoralidade_factory(request.POST)
        if form.is_valid() and formoralidade.is_valid():
            avaliacao = form.save()
            formoralidade.instance = avaliacao
            formoralidade.save()
            form = AvaliacaoADForm()
            formoralidade = ComunicOralidadeForm()

        context = {
            'form' : form,
            'formoralidade' : formoralidade,

        }
        return render(request, 'avaliacaoad.html', context=context)
"""


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

from odoo import models, fields, api, _
from odoo.osv import expression
from odoo.addons.phd_inventory.models.inherit_stock_picking import PICKING_TYPE_OUTGOING_CODE
from odoo import tools
from datetime import datetime
from dateutil import relativedelta
import operator as op
from odoo.tools import float_is_zero
import logging

_logger = logging.getLogger(__name__)

NUM_OF_MONTH_IN_YEAR = 12

class StockProductionLot(models.Model):
    _inherit = 'stock.production.lot'

    lot_name_for_delivery = fields.Char(store=True)
    ###################################
    # FIELDS
    ###################################

    ###################################
    # GENERAL FUNCTIONS
    ###################################
    lot_qty_on_location = fields.Float(string='Quantity', compute='_compute_lot_qty_on_location')

    def _compute_lot_qty_on_location(self):
        move_id = self._context.get('move_id')
        move_id = self.env['stock.move'].browse(move_id)
        location = move_id.location_id
        for record in self:
            quants = record.quant_ids.filtered(
                lambda q: q.location_id.usage in ['internal', 'transit'] and q.location_id == location)
            if quants:
                record.lot_qty_on_location = sum(quants.mapped('quantity'))
            else:
                record.lot_qty_on_location = record.product_qty

    @api.model
    def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None):
        picking_id = self._context.get('active_picking_id')
        picking_id = self.env['stock.picking'].browse(picking_id)
        picking_type_code = picking_id.picking_type_id.code

        if picking_id and picking_type_code == PICKING_TYPE_OUTGOING_CODE:
            product_id = self._context.get('default_product_id')
            partner_id = picking_id.partner_id

            args = list(args or [])
            if not self._rec_name:
                _logger.warning("Cannot execute name_search, no _rec_name defined on %s", self._name)
            elif not (name == '' and operator == 'ilike'):
                args += [(self._rec_name, operator, name)]
            lot_ids = self._search(args, limit=100, access_rights_uid=name_get_uid, order='use_date ASC')
            lot_ids = self.browse(lot_ids).with_user(name_get_uid)

            is_check_previous_shipment_date = self.get_is_check_previous_shipment_date(partner_id)
            expire_date_of_previous_shipment = is_check_previous_shipment_date \
                                               and self.get_expire_date_of_previous_shipment(product_id, partner_id.id)
            if expire_date_of_previous_shipment:
                # Filter all lots which use date >= expire date of previous shipment
                lot_ids = lot_ids.filtered(
                    lambda rec: rec.use_date and rec.use_date >= expire_date_of_previous_shipment)

            # Get shelf-life require of partner, if it not set then get from parent company
            required_shelf_life = self.get_required_shelf_life(partner_id)
            if required_shelf_life:
                # filter lots which use_date - now >= shelf-life require
                lot_ids = lot_ids.filtered(
                    lambda rec: self.get_number_of_month_between_date(rec.use_date,
                                                                      datetime.now()) >= required_shelf_life)
            lot_ids = lot_ids.recommend_lot_ids()
            names = tools.lazy(lambda: dict(lot_ids.recommend_lot_name_get()))
            return [(rid, tools.lazy(op.getitem, names, rid)) for rid in lot_ids.ids]
        else:
            res = super(StockProductionLot, self)._name_search(name=name, args=args, operator=operator, limit=100,
                                                               name_get_uid=name_get_uid)
        return res

    def recommend_lot_name_get(self):
        res = []
        for record in self:
            res.append((record.id, record.lot_name_for_delivery))
        return res

    def recommend_lot_ids(self):
        lot_ids = []
        # res = []
        move_id = self._context.get('move_id')
        move_id = self.env['stock.move'].browse(move_id)
        location = move_id.location_id

        for record in self:
            use_date = fields.Date.to_date(record.use_date) if record.use_date else 'Not set'
            quants = record.quant_ids.filtered(
                lambda q: q.location_id.usage in ['internal', 'transit'] and q.location_id == location)
            lot_product_qty = sum(quants.mapped('quantity'))

            record.lot_name_for_delivery = '%s Qty: %s Expiration: %s' % (record.name, lot_product_qty, use_date)
            if not float_is_zero(lot_product_qty, precision_digits=0):
                # res.append((record.id, name))
                lot_ids.append(record.id)
        return self.browse(lot_ids)

    ###################################
    # HELPER FUNCTIONS
    ###################################

    def get_number_of_month_between_date(self, date_start, date_end):
        relative = relativedelta.relativedelta(date_start, date_end)

        number_of_month = relative.years * NUM_OF_MONTH_IN_YEAR + relative.months

        return number_of_month

    def get_required_shelf_life(self, partner_obj):
        """
        Get parent required shelf life
        :param partner_obj:
        :type partner_obj: object
        :return:
        :rtype:
        """
        required_shelf_life = partner_obj.month_of_shelf_life_require
        partner = partner_obj
        while partner.parent_id and not required_shelf_life:
            partner = partner.parent_id
            required_shelf_life = partner.month_of_shelf_life_require

        return required_shelf_life

    def get_is_check_previous_shipment_date(self, partner_obj):
        """
        Get parent is check previous shipment date
        :param partner_obj:
        :type partner_obj: object
        :return:
        :rtype:
        """
        is_check_previous_shipment_date = partner_obj.check_previous_shipment_date
        partner = partner_obj
        while partner.parent_id and not is_check_previous_shipment_date:
            partner = partner.parent_id
            is_check_previous_shipment_date = partner.check_previous_shipment_date

        return is_check_previous_shipment_date

    def get_expire_date_of_previous_shipment(self, product_id, partner_id):
        """
        Get previous shipment expiration date of product for specific vendor
        :param product_id:
        :type product_id: int
        :param partner_id:
        :type partner_id: int
        :return:
        :rtype: datetime
        """
        sql_query = """
                       SELECT stock_production_lot.use_date AS previous_move_expire_date
                       FROM stock_move
                       JOIN stock_move_line on stock_move.id = stock_move_line.move_id
                                       AND stock_move.product_id = %s
                                       AND stock_move.picking_id IS NOT NULL
                                       AND stock_move.state = %s
                       JOIN stock_production_lot ON stock_move_line.lot_id = stock_production_lot.id
                       JOIN stock_picking ON stock_picking.id = stock_move.picking_id
                                        AND stock_picking.partner_id = %s
                       ORDER BY stock_move.date DESC,
                                stock_production_lot.use_date DESC
                       LIMIT 1;
                   """
        sql_params = [product_id, 'done', partner_id]
        self.env.cr.execute(sql_query, sql_params)
        result = self.env.cr.dictfetchall()
        use_date = result[0].get('previous_move_expire_date') if result else None
        return use_date


from playsound import playsound
import pygame
from tkinter import *
from tkinter.messagebox import askyesno
import logging
import psutil
from time import sleep
from datetime import datetime

BATTERY_THRESHOLD = 99

logger = logging.getLogger(__name__)

logging.basicConfig(level=logging.INFO,
                format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S',
                handlers=[logging.FileHandler('battery_life.log', mode='a'),
                            logging.StreamHandler()])
#Tkinter interface
root = Tk()
root.title("Battery level warning")
root.geometry("400x200")
# Create text widget and specify size.
T = Text(root, height = 5, width = 52)

# Pygame music
pygame.mixer.init()
pygame.mixer.music.load(r'C:\Users\HP\Python_For_Spyder\mini_projects\battery_warning\Tornado_Siren.mp3')

# Battery Stats
battery = psutil.sensors_battery()
START_BATTERY_PERCENT = battery.percent
START_TIME = datetime.now()

logger.info(f"Program started with battery percent {battery.percent}")

def low_batter_sound_stop():
    pygame.mixer.music.stop()
    # quiting the program
    print("quiting")
    quit()

def low_batter_sound_start():
    global START_TIME
    backup_time=(datetime.now()-START_TIME).total_seconds()/3600
    Fact=f"The battery has run for {backup_time} hours"
    logger.info(f"The battery has run for {backup_time} hours")
    T.pack()
    T.insert(END, Fact)
    pygame.mixer.music.play(loops=9)
    my_button = Button(root,text='Exit',command=low_batter_sound_stop,width='20')
    my_button.pack(pady=20)

while(1):
    sleep(5)
    if START_BATTERY_PERCENT > battery.percent:
        START_BATTERY_PERCENT=battery.percent
        logger.info(f"{battery.percent}")
    if START_BATTERY_PERCENT<=BATTERY_THRESHOLD:
        root.after(1,low_batter_sound_start)
        root.mainloop()


import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class UnderdogSpider(CrawlSpider):
    name = 'underdog'
    allowed_domains = ['www.copunderdog.com']
    # start_urls = ['http://copunderdog.com/']
    url = 'https://www.copunderdog.com/product-category/sneakers/'
    user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36"

    def start_requests(self):
        yield scrapy.Request(
            url=self.url,
            # wait_time=3,
            # callback=self.parse_item,
            headers={'User-Agent':self.user_agent})

    rules=(
        Rule(LinkExtractor(restrict_xpaths="//div[@class='product-header']/a"),callback='parse_item', follow=True, process_request='get_user_agent'),
        Rule(LinkExtractor(restrict_xpaths="//ul[@class='page-numbers']/li[position()=last()]/a"), process_request='get_user_agent')
    )

    def get_user_agent(self, request, spider):
        request.headers['User-Agent'] = self.user_agent
        return request

    def parse_item(self, response):
        # driver = response.meta['driver']

        # html = driver.page_source
        # response_obj = Selector(text=html)

        name = response.xpath("//h1/text()").get()
        rupee = response.xpath("//bdi/span/text()").get()
        price =response.xpath("//bdi/text()").get()
        sizes = response.xpath("//li[contains(@class,'variable-item button-variable-item')]/div/span/text()").getall()
        sku = response.xpath("//span[@class='sku']/text()").get()
        categories = response.xpath("//span[@class='posted_in']/a/text()").getall()
        description = response.xpath("//div[@class='woocommerce-Tabs-panel woocommerce-Tabs-panel--description panel entry-content wc-tab']/div/p/text()").getall()
        images = response.xpath("//div[@class='woocommerce-product-gallery__image woocommerce-main-image']/a/@href").getall()

        yield {
            "Item_url": response.url,
            "Name": name,
            "Price":rupee+price[1:],
            "Sizes_Available": ','.join(sizes),
            "SKU":sku,
            "Categories":','.join(categories),
            "Description":",".join(description),
            "All_image_URLs":''.join(images),
        }


import sys
import rosbag

import matplotlib.pyplot as plt

args = sys.argv

if len(args) < 2:
  print("Please insert RosVive data file")
  sys.exit(0)

bag = rosbag.Bag(args[1], "r")

hdurations = dict()
vdurations = dict()

for topic, msg, t in bag.read_messages(topics=["/loc/vive/light"]):
  if topic == "/loc/vive/light":
    if not msg.lighthouse in hdurations:
      hdurations[msg.lighthouse] = dict()
    if not msg.lighthouse in vdurations:
      vdurations[msg.lighthouse] = dict()
    for sample in msg.samples:
      if msg.axis == 0:
        if not sample.sensor in hdurations[msg.lighthouse]:
          hdurations[msg.lighthouse][sample.sensor] = list()
        hdurations[msg.lighthouse][sample.sensor].append(sample.length)
      elif msg.axis == 1:
        if not sample.sensor in vdurations[msg.lighthouse]:
          vdurations[msg.lighthouse][sample.sensor] = list()
        vdurations[msg.lighthouse][sample.sensor].append(sample.length)

lh_1 = hdurations.keys()[0]
# lh_2 = durations.keys()[1]
# fig, axs = plt.subplots(4,2)
fig, axs = plt.subplots(2,1)
axs[0].plot(hdurations[lh_1][6])
axs[0].set_title("HOR")
axs[1].plot(vdurations[lh_1][6])
axs[1].set_title("VER")

# axs[0,0].plot(durations[lh_1][2])
# axs[0,0].set_title("3")
# axs[1,0].plot(durations[lh_1][7])
# axs[1,0].set_title("4")
# axs[2,0].plot(durations[lh_1][12])
# axs[2,0].set_title("7")
# axs[3,0].plot(durations[lh_1][21])
# axs[3,0].set_title("21")
# axs[0,1].plot(durations[lh_2][2])
# axs[0,1].set_title("3")
# axs[1,1].plot(durations[lh_2][7])
# axs[1,1].set_title("4")
# axs[2,1].plot(durations[lh_2][12])
# axs[2,1].set_title("7")
# axs[3,1].plot(durations[lh_2][21])
# axs[3,1].set_title("21")
plt.show()


import unittest
from typing import Set, Tuple, Union

from isla.derivation_tree import DerivationTree
from fuzzingbook.Parser import EarleyParser

from evogfuzz.execution_handler import (
    SingleExecutionHandler,
    BatchExecutionHandler,
)
from evogfuzz.input import Input
from evogfuzz.oracle import OracleResult
from evogfuzz.report import MultipleFailureReport

from evogfuzz_formalizations.calculator import grammar_alhazen as grammar

def program(test_input: str):
    if test_input == "sin(1)":
        pass
    elif test_input == "sqrt(-900)":
        raise NotImplementedError("Failure_1")
    elif test_input == "cos(10)":
        raise AssertionError("Failure_2")

def oracle(test_input: str) -> Union[Tuple[OracleResult, Exception], OracleResult]:
    try:
        program(str(test_input))
    except Exception as exp:
        return OracleResult.BUG, exp
    else:
        return OracleResult.NO_BUG

def batch_oracle(test_inputs: Set[Input]):
    result = list()
    for inp in test_inputs:
        try:
            program(str(inp))
        except Exception as exp:
            result.append((OracleResult.BUG, exp))
        else:
            result.append((OracleResult.NO_BUG, None))

    return result

class TestExecutionHandler(unittest.TestCase):
    def setUp(self) -> None:
        inputs = {"sqrt(-900)", "cos(10)", "sin(1)"}

        self.test_inputs = set()
        for inp in inputs:
            self.test_inputs.add(
                Input(
                    DerivationTree.from_parse_tree(
                        next(EarleyParser(grammar).parse(inp))
                    )
                )
            )

    def test_execution_handler(self):
        handler = SingleExecutionHandler(oracle=oracle)
        report = MultipleFailureReport()

        handler.label(self.test_inputs, report)
        print(report)
        for inp in self.test_inputs:
            print(inp, inp.oracle)

    def test_batch_execution_handler(self):
        handler = BatchExecutionHandler(oracle=batch_oracle)
        report = MultipleFailureReport()

        handler.label(self.test_inputs, report)
        print(report)
        for inp in self.test_inputs:
            print(inp, inp.oracle)

if __name__ == "__main__":
    unittest.main()


import numpy as np
import math
import heapq
from util import read_bed_for_snp, read_phenotype, get_num_SNPs
from statistics.standard_stats import get_genotype_dist, chi_squared_test, allelic_test_nd, allelic_test
from tqdm import tqdm

function_dict = {
	chi_squared_test: "Chi squared test",
	allelic_test: "Allelic test",
	allelic_test_nd: "Allelic test"
}

def chi_squared_test_sensitivity(genotype_dist):

	"""
	Paper says, "If we have no knowledge of either the cases or the controls,
	we get the sensitivity result presented in Corollary 3.5. On the other
	hand, when the controls are known, we can use Theorem 3.4 to reduce the
	sensitivity assigned to each set of SNPs grouped by the maximum number of
	controls among the three genotypes."
	"""

	# This will result in the same sensitivity for all SNPS
	# if (
	# 	genotype_dist['r0'] >= genotype_dist['r2'] and
	# 	genotype_dist['s0'] >= genotype_dist['s2']
	# 	):
	#	# Corollary 3.5
	# 	m = max(genotype_dist['R'], genotype_dist['S'])
	# else:
	#	# Theorem 3.4
	#	m = max(genotype_dist['s0'], genotype_dist['s1'], genotype_dist['s2'])

	# This will result in different sensivity for different SNPs
	m = max(genotype_dist['s0'], genotype_dist['s1'], genotype_dist['s2'])

	sensitivity = (
			genotype_dist['N']**2/(genotype_dist['R']*genotype_dist['S'])
			)*(
			1 - 1/(m + 1)
			)

	return sensitivity

def allelic_test_sensitivity(genotype_dist):
	N = genotype_dist['N']
	R = genotype_dist['R']
	S = genotype_dist['S']

	v1 = (8* N**2 * S)/(R*(2*S+3)*(2*S+1))
	v2 = (4* N**2 * ((2*R**2-1)*(2*S-1) - 1))/(R*S*(2*R+1)*(2*R-1)*(2*S+1))
	v3 = (8* N**2 * R)/(S*(2*R+3)*(2*R+1))
	v4 = (4* N**2 * ((2*S**2-1)*(2*R-1) - 1))/(R*S*(2*S+1)*(2*S-1)*(2*R+1))

	sensitivity = max(v1, v2, v3, v4)
	return sensitivity

def top_SNPs_laplace(
	data_dir,
	genotype_file_name,
	phenotype_file_name,
	statistic_function,
	sensitivity_function,
	M,
	epsilon,
	num_SNPs = None
):
	# print("num_SNPs", num_SNPs)
	print(f"Running the Laplace algorithm to calculate top {M} SNPs by the {function_dict[statistic_function]}")
	if num_SNPs is None:
		num_SNPs = get_num_SNPs(data_dir, genotype_file_name)

	M_SNPs_heap = []

	phenotype_list = read_phenotype(data_dir, phenotype_file_name)
	print(f"Calculating statistics for {num_SNPs} SNPs")
	for idx_SNP in tqdm(range(num_SNPs)):
		genotype_list = read_bed_for_snp(data_dir, genotype_file_name, idx_SNP)
		genotype_dist = get_genotype_dist(genotype_list, phenotype_list)

		value = statistic_function(genotype_dist)
		sensitivity = sensitivity_function(genotype_dist)

		scale = 4*M*sensitivity/epsilon
		perturbed_statistic_value = value + np.random.laplace(0, scale)

		if len(M_SNPs_heap) < M:
			heapq.heappush(M_SNPs_heap, (perturbed_statistic_value, idx_SNP))
		else:
			if perturbed_statistic_value > M_SNPs_heap[0][0]:
				heapq.heapreplace(M_SNPs_heap, ((perturbed_statistic_value, idx_SNP)))

	M_SNPs = []
	print(f"Picking {M} SNPs")
	for _ in tqdm(range(M)):
		perturbed_value, idx = heapq.heappop(M_SNPs_heap)
		genotype_list = read_bed_for_snp(data_dir, genotype_file_name, idx)
		genotype_dist = get_genotype_dist(genotype_list, phenotype_list)

		value = statistic_function(genotype_dist)
		sensitivity = sensitivity_function(genotype_dist)
		scale = 2*M*sensitivity/epsilon
		laplace_noise = np.random.laplace(0, scale)
		# print(laplace_noise)
		perturbed_value = value + laplace_noise
		M_SNPs.append((perturbed_value, idx))

	return M_SNPs

def top_SNPs_exponential(
	data_dir,
	genotype_file_name,
	phenotype_file_name,
	statistic_function,
	sensitivity_function,
	M,
	epsilon,
	num_SNPs = None
):
	print(f"Running the Exponential algorithm to calculate top {M} SNPs by the {function_dict[statistic_function]}")
	if num_SNPs is None:
		num_SNPs = get_num_SNPs(data_dir, genotype_file_name)

	error_count = 0
	while error_count < 2:
		try:
			w_SNPs = np.zeros(num_SNPs)
			w_sum = 0
			phenotype_list = read_phenotype(data_dir, phenotype_file_name)
			print(f"Calculating statistics for {num_SNPs} SNPs")
			for idx_SNP in tqdm(range(num_SNPs)):
				genotype_list = read_bed_for_snp(data_dir, genotype_file_name, idx_SNP)
				genotype_dist = get_genotype_dist(genotype_list, phenotype_list)

				value = statistic_function(genotype_dist)
				sensitivity = sensitivity_function(genotype_dist)

				w = np.exp((epsilon*value)/(4*M*sensitivity))
				w_sum += w
				w_SNPs[idx_SNP] = w
			w_SNPs /= w_sum

			M_SNPs = []
			print(f"Picking {M} SNPs")
			for _ in tqdm(range(M)):
				idx_SNP = np.random.choice(np.arange(num_SNPs), p = w_SNPs)
				genotype_list = read_bed_for_snp(data_dir, genotype_file_name, idx_SNP)
				genotype_dist = get_genotype_dist(genotype_list, phenotype_list)

				value = statistic_function(genotype_dist)
				sensitivity = sensitivity_function(genotype_dist)
				scale = 2*M*sensitivity/epsilon
				laplace_noise = np.random.laplace(0, scale)
				perturbed_value = value + laplace_noise
				M_SNPs.append((perturbed_value, idx_SNP))

				w_SNPs *= w_sum
				w_sum -= w_SNPs[idx_SNP]
				w_SNPs[idx_SNP] = 0
				w_SNPs /= w_sum

			return M_SNPs
		except Exception as e:
			error_count += 1
			print(f"Encountered error - {e}")
			if error_count < 2:
				print("Recalculating w_dp and trying again")
			else:
				print("Encountered errors twice, returning empty list")
			continue
	return []

def get_neighbour_distance(genotype_dist, w, Y):
	N = genotype_dist['N']
	R = genotype_dist['R']
	S = genotype_dist['S']
	r0 = genotype_dist['r0']
	r1 = genotype_dist['r1']
	r2 = genotype_dist['r2']
	s0 = genotype_dist['s0']
	s1 = genotype_dist['s1']
	s2 = genotype_dist['s2']

	min_eps = 1e-10
	def get_P():
		P = set()
		m_vals = [1, 2, 0.5]

		for m in m_vals:
			alpha = 2*N*R*S*m - R*S*w*m - 2*N*S*S - R*S*w
			beta = N*R*S*w*(1+m)
			gamma = 2*N*R*R*m + R*S*w*m + R*S*w - 2*N*R*S + min_eps
			alpha /= gamma
			beta /= gamma

			A = 2*N*(S-alpha*R)**2 + R*S*w*(1+alpha)**2
			B = 4*N*beta*R*(alpha*R-S) - 2*R*S*w*(N - beta)*(1 + alpha)
			C = 2*N*beta*beta*R*R - R*S*w*beta*(2*N - beta)

			disc = B*B - 4*A*C
			if disc >= 0:
				x = (-B + np.sqrt(disc))/(2*A)
				y = alpha*x + beta
				if not (np.isnan(x) or math.isinf(x)):
					if x>=0 and x<=2*R and y>=0 and y<=2*S:
						P.add((x, y))

				x = (-B - np.sqrt(disc))/(2*A)
				y = alpha*x + beta
				if not (np.isnan(x) or math.isinf(x)):
					if x>=0 and x<=2*R and y>=0 and y<=2*S:
						P.add((x, y))
		return P

	def get_y_for_x(x):
		A = 2*N*R*R + R*S*w
		B = 2*R*S*w*x - 2*N*R*S*w - 4*N*R*S*x
		C = 2*N*S*S*x*x + R*S*w*x*x - 2*N*R*S*w*x

		d = B*B - 4*A*C

		if d >= 0:
			y1 = (-B + np.sqrt(d)) / (2*A)
			y2 = (-B - np.sqrt(d)) / (2*A)
			return y1, y2
		return None, None

	def get_x_for_y(y):
		A = 2*N*S*S + R*S*w
		B = 2*R*S*w*y - 2*N*R*S*w - 4*N*R*S*y
		C = 2*N*S*S*y*y + R*S*w*y*y - 2*N*R*S*w*y

		d = B*B - 4*A*C

		if d >= 0:
			x1 = (-B + np.sqrt(d)) / (2*A)
			x2 = (-B - np.sqrt(d)) / (2*A)
			return x1, x2
		return None, None

	def get_Q():
		Q = set()
		x_vals = [
			2*(genotype_dist['r0'] + genotype_dist['r2']) + genotype_dist['r1'],
			2*genotype_dist['r0'] + genotype_dist['r1'],
			genotype_dist['r1'],
			0,
			2*R
		]
		y_vals = [
			2*(genotype_dist['s0'] + genotype_dist['s2']) + genotype_dist['s1'],
			2*genotype_dist['s0'] + genotype_dist['s1'],
			genotype_dist['s1'],
			0,
			2*S
		]

		for x in x_vals:
			y1, y2 = get_y_for_x(x)
			if (y1 is not None and y1 >= 0 and y1 <= 2*S and not (np.isnan(y1) or math.isinf(y1))):
				Q.add((x, y1))
			if (y2 is not None and y2 >= 0 and y2 <= 2*S and not (np.isnan(y2) or math.isinf(y2))):
				Q.add((x, y2))

		for y in y_vals:
			x1, x2 = get_x_for_y(y)
			if (x1 is not None and x1 >= 0 and x1 <= 2*R and not (np.isnan(x1) or math.isinf(x1))):
				Q.add((x1, y))
			if (x2 is not None and x2 >= 0 and x2 <= 2*R and not (np.isnan(x2) or math.isinf(x2))):
				Q.add((x2, y))

		return Q

	def g1_x(x):
		if (x <= 2*R - r1 and
			x >= 2*r0 + r1
		):
			return (x-2*r0-r1)/2
		elif (x >= r1 and
			x <= 2*r0+r1
		):
			return (2*r0+r1-x)/2
		elif (x <= 2*R and x >= 2*R - r1):
			return r2+x-2*(r0+r2)-r1
		else:
			return r0+r1-x

	def g2_y(y):
		if (y <= 2*S - s1 and
			y >= 2*s0 + s1
		):
			return (y-2*s0-s1)/2
		elif (y >= s1 and
			y <= 2*s0+s1
		):
			return (2*s0+s1-y)/2
		elif (y <= 2*S and y >= 2*S - s1):
			return s2+y-2*(s0+s2)-s1
		else:
			return s0+s1-y

	def g_xy(x, y):
		return g1_x(x) + g2_y(y)

	def beta1_x(x):
		if (r1 == 0 and
			(x-2*r0-r1)%2 == 1
		):
			return np.ceil(g1_x(x))+1
		else:
			return np.ceil(g1_x(x))

	def beta2_y(y):
		if (s1 == 0 and
			(y-2*s0-s1)%2 == 1
		):
			return np.ceil(g2_y(y))+1
		else:
			return np.ceil(g2_y(y))

	def get_limits_for_Ui(i):
		if r1>0:
			if i == 0 or i == 1:
				return (2*r0+r1, 2*(r0+r2)+r1)
			elif i == 2 or i == 3:
				return (r1, 2*r0+r1)
			elif i == 4 or i == 5:
				return (2*(r0+r2)+r1, 2*R)
			elif i == 6 or i == 7:
				return (0, r1)
			else:
				print(f"i_max not set correctly, received i = {i}")
				return (None, None)
		else:
			if i == 0 or i == 1:
				return (2*r0, 2*R)
			elif i == 2 or i == 3:
				return (0, 2*r0)
			else:
				print(f"i_max not set correctly, received i = {i}")
				return (None, None)

	def get_limits_for_Uprimej(j, alpha, beta):
		if alpha == 0:
				alpha += min_eps

		if s1>0:
			if j == 0 or j == 1:
				l1 = (2*s0+s1-beta)/alpha
				l2 = (2*(s0+s2)+s1-beta)/alpha
			elif j == 2 or j == 3:
				l1 = (s1-beta)/alpha
				l2 = (2*s0+s1-beta)/alpha
			elif j == 4 or j == 5:
				l1 = (2*(s0+s2)+s1-beta)/alpha
				l2 = (2*S-beta)/alpha
			elif j == 6 or j == 7:
				l1 = (-beta)/alpha
				l2 = (s1-beta)/alpha
			else:
				print(f"j_max not set correctly, received j = {j}")
				return (None, None)

			l_min = min(l1, l2)
			l_max = max(l1, l2)
			return l_min, l_max
		else:
			if j == 0 or j == 1:
				l1 = (2*s0-beta)/alpha
				l2 = (2*S-beta)/alpha
			elif j == 2 or j == 3:
				l1 = -beta/alpha
				l2 = (2*s0-beta)/alpha
			else:
				print(f"j_max not set correctly, received j = {j}")
				return (None, None)

			l_min = min(l1, l2)
			l_max = max(l1, l2)
			return l_min, l_max

	def get_alpha_beta(i, j, delta):
		if r1>0:
			vi_list = [1/2, 1/2 ,-1/2, -1/2, 1, 1, -1, -1]
			di_list = [-r0-r1/2, -r0-r1/2+1/2, r0+r1/2, r0+r1/2+1/2, r2-2*(r0+r2)-r1, r2-2*(r0+r2)-r1, r0+r1, r0+r1]
		else:
			vi_list = [1/2, 1/2, -1/2, -1/2]
			di_list = [-r0, -r0+3/2, r0, r0+3/2]

		if s1>0:
			vj_list = [1/2, 1/2 ,-1/2, -1/2, 1, 1, -1, -1]
			dj_list = [-s0-s1/2, -s0-s1/2+1/2, s0+s1/2, s0+s1/2+1/2, s2-2*(s0+s2)-s1, s2-2*(s0+s2)-s1, s0+s1, s0+s1]
		else:
			vj_list = [1/2, 1/2, -1/2, -1/2]
			dj_list = [-s0, -s0+3/2, s0, s0+3/2]

		vi = vi_list[i]
		di = di_list[i]
		vj = vj_list[j]
		dj = dj_list[j]

		if vj == 0:
			vj += min_eps

		alpha = -vi/vj
		beta = (delta - di - dj)/vj

		return alpha, beta

	def get_limits_i_j(i, j, delta):
		alpha, beta = get_alpha_beta(i, j, delta)

		l1, l2 = get_limits_for_Ui(i)
		l3, l4 = get_limits_for_Uprimej(j, alpha, beta)

		if l1 is None or l2 is None or l3 is None or l4 is None:
			return None, None

		if l2<l3 or l4<l1:
			return None, None

		if l3>l1:
			l1 = l3
		if l4<l2:
			l2 = l4

		return l1, l2

	def get_limits_Y(alpha, beta):
		A = 2*N*(S-alpha*R)**2 + R*S*w*(1+alpha)**2
		B = 4*N*beta*R*(alpha*R-S) - 2*R*S*w*(N - beta)*(1 + alpha)
		C = 2*N*beta*beta*R*R - R*S*w*beta*(2*N - beta)

		d = B*B - 4*A*C
		if d >= 0:
			l1 = (-B - np.sqrt(d))/(2*A)
			l2 = (-B + np.sqrt(d))/(2*A)
			return l1, l2
		return None, None

	def get_r_s(i, j, delta):
		l1, l2 = get_limits_i_j(i, j, delta)
		alpha, beta = get_alpha_beta(i, j, delta)
		l3, l4 = get_limits_Y(alpha, beta)

		if l1 is None or l2 is None or l3 is None or l4 is None:
			return None, None
		if l2<l3 or l4<l1:
			return None, None
		r = max(l1, l3)
		s = min(l2, l4)
		return r, s

	def check_delta(delta):
		if r1>0:
			ci_vals = [-2*r0-r1, -2*r0-r1+1, -2*r0-r1, -2*r0-r1+1, 0, 1, 0, 1]
			i_max = 8
		else:
			ci_vals = [-2*r0, -2*r0+1, -2*r0, -2*r0+1]
			i_max = 4

		if s1>0:
			cj_vals = [-2*s0-s1, -2*s0-s1+1, -2*s0-s1, -2*s0-s1+1, 0, 1, 0, 1]
			j_max = 8
		else:
			cj_vals = [-2*s0, -2*s0+1, -2*s0, -2*s0+1]
			j_max = 4

		for i in range(i_max):
			for j in range(j_max):
				alpha, beta = get_alpha_beta(i, j, delta)
				r, s = get_r_s(i, j, delta)

				if r is None:
					continue

				r = np.ceil(r)

				for k in range(5):
					t = r+k
					x = t
					y = alpha*t + beta

					ci = x+ci_vals[i]
					cj = y+cj_vals[j]

					if ci%2==0 and cj%2==0:
						return True
		return False

	try:
		P = get_P()
		Q = get_Q()

		PQ = P.union(Q)
		g_hat = None
		for x, y in PQ:
			g_val = np.ceil(g_xy(x, y))
			if g_hat is None or g_hat > g_val:
				g_hat = g_val

		if Y < w:
			return g_hat

		for i in range(6):
			delta = g_hat+i
			if check_delta(delta):
				return delta
		return -5 # returning random negative value
	except Exception as e:
		return -5 # returning random negative value

def dp_allelic_test_nd(genotype_dist, epsilon):
	""" Alternative formulation for the allelic test. Gives the same value.
	"""
	x = 2*genotype_dist['r0']+genotype_dist['r1']
	y = 2*genotype_dist['s0']+genotype_dist['s1']

	x_dp = x + np.random.laplace(2/epsilon)
	y_dp = y + np.random.laplace(2/epsilon)

	value = 2*genotype_dist['N']*(x_dp*genotype_dist['S']-y_dp*genotype_dist['R'])**2
	d = genotype_dist['R']*genotype_dist['S']*(x_dp+y_dp)*(2*genotype_dist['N']-x_dp-y_dp)

	if d == 0:
		return 0
	else:
		return value/d

def top_SNPs_neighbour_distance(
	data_dir,
	genotype_file_name,
	phenotype_file_name,
	statistic_function,
	sensitivity_function,
	neighbour_distance_function,
	M,
	epsilon,
	num_SNPs = None
):
	print(f"Running the Neighbour distance algorithm to calculate top {M} SNPs by the {function_dict[statistic_function]}")
	if num_SNPs is None:
		num_SNPs = get_num_SNPs(data_dir, genotype_file_name)

	epsilon1 = epsilon*0.3
	epsilon2 = epsilon*0.7

	M_SNPs_heap = []
	phenotype_list = read_phenotype(data_dir, phenotype_file_name)
	print(f"Calculating w_dp by iterating over {num_SNPs} SNPs")
	for idx_SNP in tqdm(range(num_SNPs)):
		genotype_list = read_bed_for_snp(data_dir, genotype_file_name, idx_SNP)
		genotype_dist = get_genotype_dist(genotype_list, phenotype_list)

		value = statistic_function(genotype_dist)

		if len(M_SNPs_heap) < M+1:
			heapq.heappush(M_SNPs_heap, (value, idx_SNP))
		else:
			if value > M_SNPs_heap[0][0]:
				heapq.heapreplace(M_SNPs_heap, (value, idx_SNP))

	w = (M_SNPs_heap[0][0] + M_SNPs_heap[1][0])/2
	s = sensitivity_function(genotype_dist) # using the last genotype_dist from the loop since N, R, S would be same for all distributions

	error_count = 0
	while error_count < 2:
		try:
			w_dp = w + np.random.laplace(s/epsilon1) # should we multiply with scale by M?
			# print(w, w_dp)

			w_SNPs = np.zeros(num_SNPs)
			w_sum = 0
			print(f"Calculating neighbour distance for {num_SNPs} SNPs")
			for idx_SNP in tqdm(range(num_SNPs)):
				genotype_list = read_bed_for_snp(data_dir, genotype_file_name, idx_SNP)
				genotype_dist = get_genotype_dist(genotype_list, phenotype_list)

				value = statistic_function(genotype_dist)
				neighbour_distance = neighbour_distance_function(genotype_dist, w_dp, value)

				if value > w_dp:
					w = np.exp((epsilon2*neighbour_distance)/(4*M)) # 4 instead of 2 if adding noise later
				else:
					w = np.exp((epsilon2*(1-neighbour_distance))/(4*M))
				# if w>w_max:
				# 	w_max=w
				# if neighbour_distance>nd_max:
				# 	nd_max=neighbour_distance
				w_sum += w
				w_SNPs[idx_SNP] = w
			w_SNPs /= w_sum

			# print('w_sum starting ', w_sum)
			# print('w_max starting ', w_max)
			# print('nd_max starting ', nd_max)

			# print("Sum ", np.linalg.norm(w_SNPs))
			M_SNPs = []
			print(f"Picking {M} SNPs")
			for _ in tqdm(range(M)):
				idx_SNP = np.random.choice(np.arange(num_SNPs), p = w_SNPs)
				# M_SNPs.append(idx_SNP)

				genotype_list = read_bed_for_snp(data_dir, genotype_file_name, idx_SNP)
				genotype_dist = get_genotype_dist(genotype_list, phenotype_list)
				perturbed_value = dp_allelic_test_nd(genotype_dist, epsilon2/2)
				M_SNPs.append((perturbed_value, idx_SNP))

				w_SNPs *= w_sum
				w_sum -= w_SNPs[idx_SNP]
				w_SNPs[idx_SNP] = 0
				# w_sum = np.sum(w_SNPs)
				w_SNPs /= w_sum
			return M_SNPs
		except Exception as e:
			error_count += 1
			print(f"Encountered error - {e}")
			if error_count < 2:
				print("Recalculating w_dp and trying again")
			else:
				print("Encountered errors twice, returning empty list")
			continue

	return []


'''
Settings, customisation and tweaks.
'''
import os
from os import path
import subprocess
import json

# Colour codes for built-in qtile bar, default custom gruvbox color_scheme
#
#
THEME = 'gruvbox/gruvbox-dark'

default_theme = {
    "background": "#282828",
    "inactive_group": "#928374",
    "focus": "#fb4934",
    "urgent": "#689d6a",
    "selected": "#8ec07c",
    "foreground": "#ebdbb2",
    "active_group": "#d65d0e"
}

def load_theme(theme=''):
    qtile_path = path.join(path.expanduser('~'), ".config", "qtile")

    if not theme:
        return default_theme

    theme_file = path.join(qtile_path, "misc/themes/", f'{theme}.json')

    if not path.isfile(theme_file):
        #        message = f'"{theme}" does not exist, using default theme'
        #        run('notify-send "Qtile theme config" "%s"' %message, with_output=False)
        return default_theme

    with open(theme_file) as f:
        return json.load(f)

COLOR_SCHEME = load_theme(THEME)

# Modifier keys
ALT = "mod1"    # Left Alt
MOD = "mod4"    # Windows/Super
R_ALT = "mod3"  # Right Alt

# Directions
DIRECTIONS = ("Left", "Down", "Up", "Right")

# Keyboard Layouts
K_LAYOUTS = ['us', 'es', 'us dvp']

# Programs
TERMINAL = "alacritty"

# UI Config vars
FONT = 'Hurmit Nerd Font'
FOREGROUND = COLOR_SCHEME['foreground']
ALERT = COLOR_SCHEME['focus']
FONTSIZE = 15
PADDING = 2

# Keep all of the UI consistent
FONT_PARAMS = {
    'font': FONT,
    'fontsize': FONTSIZE,
    'foreground': FOREGROUND,
}

# Location of my script files (must have a trailing slash!)
SCRIPT_DIR = os.path.expanduser('~/.config/qtile/misc/')
ACME_SCRIPT_DIR = os.path.expanduser('~/Personal/acme-corp/scripts/')

# Whether or not the primary monitor should spawn a systray
# NOTE :: When embedding qtile inside of another desktop environment (such
#         as mate) this should be `False` as the DE systray and qtile's
#         end up fighting each other and both loose...!
WITH_SYS_TRAY = True


from sys import argv

from O365 import Account
from O365 import FileSystemTokenBackend

def main(client_id: str, client_secret: str):
    """
    認証を行う

    """
    credentials = (client_id, client_secret)
    token_backend = \
        FileSystemTokenBackend(
            token_path='.',
            token_filename='token.json'
        )
    account = Account(credentials, token_backend=token_backend)
    if account.authenticate(scopes=['basic', 'message_all']):
        print('Authenticated!')

if __name__ == '__main__':
    if len(argv) != 3:
        raise ValueError('insufficent params')

    client_id = argv[1]
    client_secret = argv[2]

    main(client_id, client_secret)


import rethinkdb as r

# Connect, defaults are 'localhost', 28015, and the 'test' db.
conn = r.connect(host='localhost', port=28015, db='CheeseRealtime')

# Start a changefeed
cheese_cursor = r.table('Cheese').changes().run(conn)
for cheese in cheese_cursor:
    print(cheese)


"""
Dans cette exemple vous pourrez voir comment :
-Creation de labels (champs de texte)
-Creation de champs de saisie de texte
-Creation de liste deroulante
-Conenxion d'evenement et mise a jour de texte
-exemple d'utilisation des layouts pour gerer le placemenet

"""

import sys

from PyQt5.QtCore import QCoreApplication, Qt
from PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit,
                             QTextEdit, QGridLayout, QApplication, QPushButton, QHBoxLayout, QVBoxLayout, QComboBox)

class Example(QWidget):
    """"Creation de la classe qui va gerer la fenetre
    creation des methodes evenements"""
    def __init__(self):
        #constructeur
        super().__init__()
        self.initUI()

    def initUI(self):
        #creation des labels
        nom = QLabel('Nom')
        prenom = QLabel('Prenom')
        commentaire = QLabel('Commentaire')
        #creation des champs d'entree de texte
        nomEdit = QLineEdit()
        prenomEdit = QLineEdit()
        #creation d'un champ d'entree multiligne
        commentaireEdit = QTextEdit()
        #creation des boutons
        okButton = QPushButton("OK")
        quitButton = QPushButton("Quitter")

        #creation d'un layout horizontal
        hbox = QHBoxLayout()
        hbox.addStretch(1)
        #ajout des widget dans le layout
        hbox.addWidget(okButton)
        hbox.addWidget(quitButton)

        #connexion du l'action de fermeture de la fenetre
        quitButton.clicked.connect(QCoreApplication.instance().quit)

        #creation d'un layout verticale
        vbox = QVBoxLayout()
        vbox.addStretch(1)

        #creation d'une grid layout
        grid = QGridLayout()
        grid.setSpacing(10)

        #Postionnement des differents elements dans le grid layout
        grid.addWidget(nom, 1, 0)
        grid.addWidget(nomEdit, 1, 1)

        grid.addWidget(prenom, 2, 0)
        grid.addWidget(prenomEdit, 2, 1)

        grid.addWidget(commentaire, 3, 0)
        grid.addWidget(commentaireEdit, 3, 1, 5, 1)

        #Creation de la liste deroulante
        combo = QComboBox(self)
        #On ajoute les differents elements pour la liste deroulante
        combo.addItem("Stylo")
        combo.addItem("Feutre")
        combo.addItem("Craie")
        combo.addItem("Chocolat")
        combo.addItem("Panda")
        #ajout de la liste deroulante dans la grid layout
        grid.addWidget(combo, 8, 0)
        #creation du label qui sera mise a jour lors de la selection de la liste deroulante
        self.label = QLabel("Stylo", self)
        #ajout du label dans la grille
        grid.addWidget(self.label, 8,1)
        #On connecte la mise a jour du texte a la selection de la liste
        combo.activated[str].connect(self.onActivated)

        #On ajoute la grid layout et le layout horizontal dans le layout vertical
        vbox.addLayout(grid)
        vbox.addLayout(hbox)
        #on met en place le layout
        self.setLayout(vbox)
        #mise a jour des fenetres
        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('PC2')
        self.show()

    def onActivated(self, text):
        #methode qui fera la mise a jour du label a la selection dans la liste
        self.label.setText(text)
        self.label.adjustSize()
        print(text)

    def keyPressEvent(self, e):
        #methode qui surcharge l'appuie d'une touche du clavier
        if e.key() == Qt.Key_Escape:
            #on ferme la fenetre lors de l'appuie du bouton Esc
            self.close()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


from nio.properties import Property, BoolProperty

from .mongodb_base import MongoDBBase

class MongoDBRemove(MongoDBBase):

    """ A block for running `remove` against a mongodb.

    Properties:
        condition (expression): A dictionary form of a remove expression. This
        is an expression property that can evaluate to a dictionary or be a
        parseable JSON string

    """
    condition = Property(
        title='Condition',
        default="{'id': {'$gt': 0}}")
    only_one = BoolProperty(
        title='Maximum One Deletion',
        default=False)

    def execute_query(self, collection, signal):
        condition = self.evaluate_expression(self.condition, signal)
        self.logger.debug("Deleting on condition {}".format(condition))

        res = collection.remove(condition, multi=(not self.only_one()))
        return [{'deleted': res.get('n', 0)}]


#!/usr/bin/env python3

import numpy as np
import matplotlib.pyplot as plt

class Tally:

    def __init__( self, DataDirectory, ID ):

        self.DataDirectory = DataDirectory
        self.ID            = ID

        return

    def GetData( self ):

        Root = self.DataDirectory + self.ID + '/' + self.ID \
                 + '.plt_StandingAccretionShock_Relativis_Tally_'

        self.Mass   = np.loadtxt( Root + 'BaryonicMass.dat', skiprows = 1 )
        self.Energy = np.loadtxt( Root + 'Energy.dat', skiprows = 1 )

    def PlotData( self ):

        self.GetData()

        fig, axs = plt.subplots( 2, 1 )

        axs[0].plot( self.Mass  [:,0], self.Mass  [:,4] )
        axs[1].plot( self.Energy[:,0], self.Energy[:,4] )

        axs[0].set_ylabel( 'Change [Msun]' )
        axs[1].set_ylabel( 'Change [B]' )

        plt.show()

if __name__ == '__main__':

    DataDirectory \
      = '/Users/dunhamsj/Research/Data/AccretionShockParameterStudy/'

    ID = 'GR2D_M1.4_Mdot0.3_Rs180_PA0.004_nX320x064_smooth'

    T = Tally( DataDirectory, ID )

    T.PlotData()

    import os
    os.system( 'rm -rf __pycache__ ' )


""" Módulo de testes para o @applled com fins de aprendizado """

import gdshortener

from pyrogram.errors import YouBlockedUser
from userge import userge, Message
from userge.utils.exceptions import StopConversation

@userge.on_cmd("bitly", about={
    'header': "Encurte qualquer URL usando o bit.ly",
    'como usar': "{tr}bitly [link ou resposta]"}, allow_via_bot=False)
async def bitly(msg: Message):
    url = msg.input_or_reply_str
    if not url:
        await msg.err("Obrigatório uma URL aqui.")
        return
    try:
        async with userge.conversation("Sl_BitlyBot") as conv:
            await conv.send_message("/start")
            await conv.get_response(mark_read=True)
            await conv.send_message(url)
            shorten_url = (
                await conv.get_response(mark_read=True)
            ).text.split('\n', maxsplit=1)[-1]
            await msg.edit(f"Prontinho: {shorten_url}", disable_web_page_preview=True)
    except YouBlockedUser:
        await msg.edit("Desbloqueie o **@Sl_BitlyBot** para encurtar a URL")
    except StopConversation:
        await msg.err("O Bot está morto...")

@userge.on_cmd("isgd", about={
    'header': "Encurte qualquer URL usando o is.gd",
    'como usar': "{tr}isgd [link ou resposta]"})
async def is_gd(msg: Message):
    url = msg.input_or_reply_str
    if not url:
        await msg.err("Obrigatório uma URL aqui.")
        return
    s = gdshortener.ISGDShortener()
    try:
        s_url, stats = s.shorten(url, log_stat=True)
    except Exception as er:
        await msg.err(str(er))
    else:
        await msg.edit(
            f"**URL Encurtada:**\n`{s_url}`\n\n**Stats:** `{stats}`",
            disable_web_page_preview=True
        )

@userge.on_cmd("statsisgd", about={
    'header': "Reverta uma URL is.gd na original URl.",
    'como usar': "{tr}statsisgd [link ou resposta]"})
async def stats_is_gd(msg: Message):
    url = msg.input_or_reply_str
    if not url:
        await msg.err("Precisa de uma URL para verificar.")
        return
    s = gdshortener.ISGDShortener()
    try:
        original_url = s.lookup(url)
    except Exception as er:
        await msg.err(str(er))
    else:
        await msg.edit(
            f"**URL:** `{original_url}`",
            disable_web_page_preview=True
        )


import torch
import tqdm

class Trainer:
    def __init__(self, model, model_type, optimizer, criterion, scheduler, data_loader, device):
        self._model = model
        self._optimizer = optimizer
        self._criterion = criterion
        self._scheduler = scheduler
        self._data_loader = data_loader
        self._model_type = model_type
        self._device = device

    def make_train_step(self):
        # Builds function that performs a step in the train loop
        def train_step(train_batch):
            # Sets model to TRAIN mode
            self._model.train()

            # Zero the gradients
            self._optimizer.zero_grad()

            # Makes predictions and compute loss
            if self._model_type == 'pairwise':
                batch_score_pos = self._model(
                    query_emb = train_batch[ 'query_emb'].to(self._device),
                    entity_emb = train_batch[ 'ent_emb_pos'].to(self._device),
                    neighbors = train_batch['pos_ent_neighbors']
                )

                batch_score_neg = self._model(
                    query_emb=train_batch['query_emb'].to(self._device),
                    entity_emb=train_batch['ent_emb_neg'].to(self._device),
                    neighbors=train_batch['neg_ent_neighbors']
                )

                batch_loss = self._criterion(
                    batch_score_pos.tanh(),
                    batch_score_neg.tanh(),
                    torch.ones(batch_score_pos.size()).to(self._device)
                )

            elif self._model_type == 'pointwise':
                batch_score = self._model(
                    query_emb=train_batch['query_emb'].to(self._device),
                    entity_emb=train_batch['ent_emb'].to(self._device),
                )

                batch_loss = self._criterion(batch_score, torch.unsqueeze(train_batch['label'], dim=1).to(self._device))
            else:
                raise ValueError('Model type must be `pairwise` or `pointwise`.')

            # Computes gradients
            batch_loss.backward()

            # Updates parameters
            self._optimizer.step()
            self._scheduler.step()

            # Returns the loss
            return batch_loss.item()

        # Returns the function that will be called inside the train loop
        return train_step

    def train(self):
        train_step = self.make_train_step()
        epoch_loss = 0
        num_batch = len(self._data_loader)

        for _, batch in tqdm.tqdm(enumerate(self._data_loader), total=num_batch):
            batch_loss = train_step(batch)
            epoch_loss += batch_loss

        return epoch_loss


# --- hussein kaplan --- حسين قبلان
# استدعاء المكتبات المطلوبة
import itertools
from instagrapi import Client
import json
import os
import sys

print(sys.argv[1])
username = sys.argv[1]

def read_file(path_file, object_hook=None):

    with open(path_file, 'r', encoding='utf8') as json_file:
        return json.load(json_file, object_hook=object_hook)

if __name__ == '__main__':
    IG_CREDENTIAL_PATH = "credential.json"
    import os
    cl = None
    if os.path.exists(IG_CREDENTIAL_PATH):
        cl = Client(read_file(IG_CREDENTIAL_PATH))

user_id = cl.user_id_from_username(username)
followers = cl.user_following(user_id)
for item in followers:
    print(item)
    print("--------------------------------")
    chickstory = cl.user_stories(item)
    if chickstory != []:
        stories = cl.user_stories_gql(item)
        for itemttt in stories:
            ab = itertools.chain([itemttt.pk])
            cl.story_seen(list(ab))

مشاهدة ستوريات انستقرام/stories.py


# python3
import itertools

#number of rooms and corridors connecting the rooms respectively.
n, m = map(int, input().split())
edges = [ list(map(int, input().split())) for i in range(m) ]

adj = [[] for _ in range(n)]
clauses = []
position = range(1,n+1)

for i, j in edges:
    adj[i-1].append(j-1)
    adj[j-1].append(i-1)

def var_num(i, j):
    return n * i + j

def exactly_one_of(literals):
    clauses.append([l for l in literals])
    for pair in itertools.combinations(literals, 2):
        clauses.append([-l for l in pair])
# each node can only appear once in the path and
# every position in the path can only have one node

for i in range(n):
    exactly_one_of([var_num(i,j) for j in position])

for j in position:
    exactly_one_of([var_num(i, j) for i in range(n)])

for j in position[:-1]:
    for i, nodes in enumerate(adj):
        clauses.append([-var_num(i, j)] + [var_num(n, j+1) for n in nodes])

print(len(clauses), n * n)
for c in clauses:
    c.append(0)
    print(' '.join(map(str, c)))

Coursera_Data_Structures_and_Algorithms_Specialization/5. Advanced Algorithms and Complexity/week3/cleaning_apartment.py


import logging

from pytezos.sandbox.node import SandboxedNodeTestCase
from pytezos.sandbox.parameters import sandbox_addresses
from pytezos.rpc.errors import RpcError

logging.basicConfig(level=logging.DEBUG)

class TransactionCounterTestCase(SandboxedNodeTestCase):

    def test_1_send_multiple_transactions_non_batched(self) -> None:
        client = self.client
        # Only one manager operation per manager per block allowed
        with self.assertRaises(RpcError):
            for _ in range(3):
                client.transaction(destination=sandbox_addresses['bootstrap3'], amount=42) \
                    .autofill(gas_reserve=100000) \
                    .sign() \
                    .inject(min_confirmations=0)

        pending_operations = client.shell.mempool.pending_operations()
        self.assertEqual(1, len(pending_operations['applied']))


#!/usr/bin/env python3

import pika
import logging
from constants import END, CLOSE, OK, OUT_JOINER_EXCHANGE
from rabbitmq_queue import RabbitMQQueue
from watchdog import heartbeatprocess

JOINED_QUEUE = 'joined_hands'
HANDS_EXCHANGE = 'hands'
TERMINATOR_EXCHANGE = 'hands_filter_terminator'
HANDS = ['R', 'L', 'U']

class DifferentHandsFilter:
    def __init__(self):
        self.acked = set()
        self.in_queue = RabbitMQQueue(exchange=OUT_JOINER_EXCHANGE, exchange_type='direct',
                                      consumer=True, queue_name=JOINED_QUEUE,
                                      routing_keys=['filter'])
        self.out_queue = RabbitMQQueue(exchange=HANDS_EXCHANGE, exchange_type='direct')
        self.terminator_queue = RabbitMQQueue(exchange=TERMINATOR_EXCHANGE)

    def run(self, _):
        self.in_queue.consume(self.filter)

    def filter(self, ch, method, properties, body):
        logging.info('Received %r' % body)
        data = body.decode().split(',')
        id = data[0]

        if data[1] == END:
            self.terminator_queue.publish(body)
            logging.info('Sent %r' % body)
            ch.basic_ack(delivery_tag=method.delivery_tag)
            return

        if data[1] == CLOSE:
            if not id in self.acked:
                body = ','.join([data[0], OK])
                self.terminator_queue.publish(body)
                self.acked.add(id)
            else:
                self.in_queue.publish(body)
            logging.info('Sent %s' % body)
            ch.basic_ack(delivery_tag=method.delivery_tag)
            return

        winner_hand = data[4]
        loser_hand = data[8]
        if winner_hand in HANDS and loser_hand != winner_hand:
            body = ','.join([id, '1'])
            self.out_queue.publish(body, winner_hand)
            logging.info('Sent %s to %s accumulator' % (body, winner_hand))
        ch.basic_ack(delivery_tag=method.delivery_tag)

if __name__ == '__main__':
    logging.basicConfig(format='%(asctime)s %(message)s',
                        level=logging.ERROR)

    hb = heartbeatprocess.HeartbeatProcess.setup(DifferentHandsFilter)
    hb.run()


from django.db.models import Avg
from rest_framework import serializers

from timetable.serializers import LectureTimeSerializer
import re

from everytime.exceptions import FieldError
from lecture.models import Course, LectureEvaluation, ExamInfo, Point, Lecture

class CourseForEvalSerializer(serializers.ModelSerializer):
    semester = serializers.SerializerMethodField()
    sem_options = serializers.SerializerMethodField()

    class Meta:
        model = Course
        fields = (
            'id',
            'title',
            'instructor',
            'semester',
            'sem_options',
        )

    def get_semester(self, course):
        semester = ""
        sem = self.context['sem']
        if sem is not None:
            for i in range(len(sem)-1):
                num = re.findall(r'\d+', sem[i])
                semester += (num[0]+"-"+num[1]+", ")

            num = re.findall(r'\d+', sem[len(sem)-1])
            semester += (num[0]+"-"+num[1])

        return semester

    def get_sem_options(self, course):
        return self.context['sem']

class EvalListSerializer(serializers.ModelSerializer):
    course = serializers.SerializerMethodField(read_only=True)
    course_id = serializers.SerializerMethodField()
    semester = serializers.SerializerMethodField(read_only=True)
    is_mine = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = LectureEvaluation
        fields = (
            'id',
            'course_id',
            'course',
            'rating',
            'semester',
            'content',
            'is_mine',
            'num_of_likes'
        )

    def get_course_id(self, obj):
        return obj.course.id

    def get_course(self, obj):
        return obj.course.title + " : " + obj.course.instructor

    def get_semester(self, obj):
        sem = obj.semester.name
        return sem[2:] + " 수강자"

    def get_is_mine(self, obj):
        if obj.writer == self.context['user']:
            return True
        return False

class EvalCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = LectureEvaluation
        exclude = ['course', 'like_users', 'num_of_likes', 'reporting_users']

    def validate(self, data):
        content = data.get('content')
        if content is None or len(content) < 20:
            raise FieldError("좀 더 성의있는 내용 작성을 부탁드립니다 :)")

        return data

    def create(self, validated_data):
        eval = LectureEvaluation.objects.create(**validated_data)
        return eval

class CourseSearchSerializer(serializers.ModelSerializer):
    rating = serializers.SerializerMethodField()

    class Meta:
        model = Course
        fields = (
            'id',
            'title',
            'instructor',
            'rating'
        )

    def get_rating(self, course):
        evals = LectureEvaluation.objects.filter(course=course)

        if not evals.exists():
            return 0

        avg_rating = round(evals.aggregate(Avg('rating')).get('rating__avg'), 1)
        return avg_rating

class MyCourseSerializer(serializers.ModelSerializer):
    is_evaluated = serializers.SerializerMethodField()

    class Meta:
        model = Course
        fields = (
            'id',
            'title',
            'instructor',
            'is_evaluated',
        )

    def get_is_evaluated(self, course):
        if course.lectureevaluation_set.exists():
            return True
        else:
            return False

class ExamInfoCreateSerializer(serializers.ModelSerializer):
    types = serializers.ListSerializer(required=False, child=serializers.ChoiceField(choices=ExamInfo.EXAM_TYPE_CHOICES), allow_empty=False)
    examples = serializers.ListSerializer(child=serializers.CharField(max_length=255), allow_empty=False)

    class Meta:
        model = ExamInfo
        exclude = ['course', 'readable_users', 'num_of_likes', 'like_users', 'reporting_users']

    def validate(self, data):
        strategy = data.get('strategy')
        if len(strategy) < 20:
            raise FieldError("시험 전략에 대해 좀 더 성의있는 작성을 부탁드립니다 :)")

        examples = ""
        ex_input = data.get('examples') # validation 통과해야해서 무조건 존재하긴 함 (빈 list도 불가)
        # element를 \t로 나눠서 쭉 이어붙이기
        for i in range(len(ex_input)-1):
            examples += ex_input[i]
            examples += '\t'
        examples += ex_input[len(ex_input)-1]
        data['examples'] = examples

        return data

    def create(self, validated_data):
        info = ExamInfo.objects.create(**validated_data)
        return info

class ExamInfoListSerializer(serializers.ModelSerializer):
    is_readable = serializers.SerializerMethodField()
    exam = serializers.SerializerMethodField()
    semester = serializers.SerializerMethodField()
    strategy = serializers.SerializerMethodField()
    is_mine = serializers.SerializerMethodField()
    types = serializers.SerializerMethodField()
    examples = serializers.SerializerMethodField()

    class Meta:
        model = ExamInfo
        fields = (
            'id',
            'is_readable',
            'exam',
            'semester',
            'strategy',
            'types',
            'examples',
            'is_mine',
            'num_of_likes',
        )

    def get_is_readable(self, obj):
        if self.context['user'] in obj.readable_users.all():
            return True
        else:
            return False

    def get_exam(self, obj):
        return dict(ExamInfo.EXAM_CHOICES)[obj.exam]

    def get_semester(self, obj):
        sem = obj.semester.name
        return sem[2:] + " 수강자"

    def get_strategy(self, obj):
        if self.context['user'] in obj.readable_users.all():
            return obj.strategy
        else:
            return None

    def get_is_mine(self, obj):
        if obj.writer == self.context['user']:
            return True
        return False

    def get_types(self, obj):
        if self.context['user'] not in obj.readable_users.all():
            return None

        if not obj.types.exists():
            return None

        return ', '.join(list(obj.types.values_list('type',flat=True)))

    def get_examples(self, obj):
        if self.context['user'] in obj.readable_users.all():
            return obj.examples.split('\t')
        else:
            return None

class PointSerializer(serializers.ModelSerializer):
    created_at = serializers.SerializerMethodField()

    class Meta:
        model = Point
        fields = (
            'id',
            'point',
            'reason',
            'created_at',
        )

    def get_created_at(self, obj):
        return str(obj.created_at)

class LectureSearchSerializer(serializers.ModelSerializer):
    lecture_time = serializers.SerializerMethodField()
    course = serializers.SerializerMethodField()

    class Meta:
        model = Lecture
        fields = '__all__'

    def get_lecture_time(self, lecture):
        lecture_time_set = lecture.lecturetime_set.all()
        return LectureTimeSerializer(lecture_time_set, many=True).data

    def get_course(self, lecture):
        avg_rating = lecture.avg_rating if lecture.avg_rating else 0
        avg_rating = round(avg_rating, 1)
        return {
            'title': lecture.course.title,
            'instructor': lecture.course.instructor,
            'rating': avg_rating
        }


from rest_framework import serializers
from .models import BasicUser,Address
from shop.models import Wishlist,Cart
from dj_rest_auth.registration.serializers import RegisterSerializer

#from userManager.serializers import BasicUserSerializer,AddressSerializer

class BasicUserSerializer(serializers.ModelSerializer):
	class Meta:
		model = BasicUser
		fields = [
			'id',
			'user',
			'phone',
			'photo',
			'created',
		]

class AddressSerializer(serializers.ModelSerializer):
	class Meta:
		model = Address
		fields = [
			'id',
			'user',
			'line_1',
			'line_2',
			'city',
			'state',
			'country',
			'pincode',
			'created',
		]

	def create(self,validated_data):
		address = Address.objects.create(**validated_data)
		user = self.context.get('user')
		address.user = user
		address.save()
		return address

class CustomRegisterSerializer(RegisterSerializer):
	def custom_signup(self, request, user):
		basic_user = BasicUser(user=user)
		basic_user.save()
		wish_list = Wishlist(user=basic_user)
		wish_list.save()
		cart = Cart(user=basic_user)
		cart.save()


from os   import listdir
from os   import path
from lxml import etree

from gutenbergpy.parse.cachefields      import Fields
from gutenbergpy.parse.book             import Book
from gutenbergpy.parse.parseitem        import ParseItem
from gutenbergpy.parse.parseitemfile    import ParseItemFiles
from gutenbergpy.parse.parseitemtitles  import ParseItemTitles
from gutenbergpy.parse.rdfparseresults  import RDFParseResults
from gutenbergpy.gutenbergcachesettings import GutenbergCacheSettings
from gutenbergpy.utils                  import Utils

##
# The rdf parser
# noinspection PyClassHasNoInit
class RdfParser:
    ##
    # The main funciton, this actually parses the rdf files from the downloaded cache
    @staticmethod
    def do():
        result = RDFParseResults()

        result.field_sets = Fields.FIELD_COUNT * [None]
        result.field_sets[Fields.TITLE]     = ParseItemTitles(xpath=['//dcterms:title/text()','//dcterms:alternative/text()'])
        result.field_sets[Fields.SUBJECT]   = ParseItem(xpath =['//dcterms:subject/rdf:Description/rdf:value/text()'])
        result.field_sets[Fields.TYPE]      = ParseItem(xpath =['//dcterms:type/rdf:Description/rdf:value/text()'])
        result.field_sets[Fields.LANGUAGE]  = ParseItem(xpath =['//dcterms:language/rdf:Description/rdf:value/text()'])
        result.field_sets[Fields.AUTHOR]    = ParseItem(xpath =['//dcterms:creator/pgterms:agent/pgterms:alias/text()','//dcterms:creator/pgterms:agent/pgterms:name/text()'])
        result.field_sets[Fields.BOOKSHELF] = ParseItem(xpath =['//pgterms:bookshelf/rdf:Description/rdf:value/text()'])
        result.field_sets[Fields.FILES]     = ParseItemFiles(xpath =['//dcterms:hasFormat'])
        result.field_sets[Fields.PUBLISHER] = ParseItem(xpath =['//dcterms:publisher/text()'])
        result.field_sets[Fields.RIGHTS]    = ParseItem( xpath =['//dcterms:rights/text()'])

        dirs  =  [d for d in listdir(GutenbergCacheSettings.CACHE_RDF_UNPACK_DIRECTORY) if not d.startswith("DELETE")]
        total = len(dirs)

        for idx, dir in enumerate(dirs):
            processing_str = "Processing progress: %d / %d" % (idx,total)
            Utils.update_progress_bar(processing_str,idx,total)
            file_path = path.join(GutenbergCacheSettings.CACHE_RDF_UNPACK_DIRECTORY,dir,'pg%s.rdf'%(dir))
            doc = etree.parse(file_path,etree.ETCompatXMLParser())

            res = Fields.FIELD_COUNT * [-1]
            for idx_field, pt in enumerate(result.field_sets):
                if not pt.needs_book_id():
                    res[idx_field] = pt.do(doc)
                else:
                    res[idx_field] = pt.do(doc,idx+1)

            gutenberg_book_id = int(dir)

            date_issued_x   = doc.xpath('//dcterms:issued/text()', namespaces=GutenbergCacheSettings.NS)
            num_downloads_x = doc.xpath('//pgterms:downloads/text()',namespaces=GutenbergCacheSettings.NS)

            date_issued       = '1000-10-10' if not date_issued_x or date_issued_x[0] =='None' else str(date_issued_x[0])
            num_downloads     =  -1 if not num_downloads_x else int(num_downloads_x[0])
            publisher_id      =  -1 if not res[Fields.PUBLISHER] else res[Fields.PUBLISHER][0]
            rights_id         =  -1 if not res[Fields.RIGHTS]    else res[Fields.RIGHTS][0]
            language_id       =  -1 if not res[Fields.LANGUAGE] else res[Fields.LANGUAGE][0]
            bookshelf_id      =  -1 if not res[Fields.BOOKSHELF] else res[Fields.BOOKSHELF][0]
            type_id           =  -1 if not  res[Fields.TYPE]    else  res[Fields.TYPE][0]

            newbook = Book(publisher_id, rights_id, language_id, bookshelf_id,
                           gutenberg_book_id, date_issued, num_downloads, res[Fields.TITLE],
                           res[Fields.SUBJECT], type_id, res[Fields.AUTHOR], res[Fields.FILES])

            result.books.append(newbook)

        return result


import cv2

cam = cv2.VideoCapture(0)
cam_buffer = []
index = 0
MAX_BUFFER_SIZE = 7

try:
    while True:

         ret, frame = cam.read()

         if not ret:
            print("bad")
            break;

         if len(cam_buffer) < MAX_BUFFER_SIZE:
            cam_buffer.append(frame)
            index = index+1
         else:
            cam_buffer[index] = frame
            index = index+1

         index = index % MAX_BUFFER_SIZE

except KeyboardInterrupt:
    pass

print("closed camera")
cam.release()

for i in range(0,MAX_BUFFER_SIZE):
    while True:
         cv2.imshow('frame {}'.format(i), cam_buffer[i])

         k = cv2.waitKey(1)
         if k%256 == 27:
             cv2.destroyAllWindows()
             break;


import datetime
import pandas as pd
import math
import numpy as np

def haversine(coord1, coord2):
    """
    Haversine distance in meters for two (lat, lon) coordinates
    """
    lat1, lon1 = coord1
    lat2, lon2 = coord2
    radius = 6371000 # mean earth radius in meters (GRS 80-Ellipsoid)
    dlat = math.radians(lat2-lat1)
    dlon = math.radians(lon2-lon1)
    a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
        * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    d = radius * c
    return d/1000

r = lambda f,p: f - f % p # For rounding decimals

def mark_point(dir,imeifile,tau,static_dist,bigtau,speed_trip):

    """
    Marks Start and Stop point of the points

    """

    df = pd.read_csv(dir + "Data\\" + imeifile, converters={'Latitude': str,'Longitude':str})
    df['Latitude'] = [r(pd.to_numeric(df['Latitude'][i]),0.0000001) for i in range(0,len(df))]
    df['Longitude'] = [r(pd.to_numeric(df['Longitude'][i]),0.0000001) for i in range(0,len(df))]
    df['Date Time'] = df['Date Time'].apply(lambda x : datetime.datetime.strptime(x,'%Y%m%d %H:%M:%S'))
    df = df.sort_values(by = ['Date Time']).reset_index(drop=True)
    df['TripID'] = 0
    df['SegmentID'] = 0
    df['Remove'] = "Static Points" #Removing pints which are stationary i.e due to GPS inaccuracy
    df['Dist'] = 1
    df['Timediff'] = 1
    dfi = pd.DataFrame()
    #Calculate distnace of those points
    df['Dist'][1:len(df)] = [haversine((df['Latitude'][x-1],df['Longitude'][x-1]),(df['Latitude'][x],df['Longitude'][x])) for x in df['Dist'][1:].index.tolist()]
    df['Remove']= np.where(df['Dist'] > static_dist,"0","Static Points")
    # Calculate Static points until they are moving i.e distnace > static_dist
    while any(df['Remove'][i] == "Static Points" for i in range(1,len(df))):
            dfi = dfi.append(df[df['Remove'] != "0"]).reset_index(drop=True)
            df = df[df['Remove'] == "0"].reset_index(drop=True)
            df['Dist'] = 1
            df['Dist'][1:len(df)] = [haversine((df['Latitude'][x-1],df['Longitude'][x-1]),(df['Latitude'][x],df['Longitude'][x])) for x in df['Dist'][1:].index.tolist()]
            df['Remove']= np.where(df['Dist'] < static_dist,"Static Points","0")

    if len(dfi) > 1:
        dfi = dfi.sort_values(by = ['Date Time']).reset_index(drop=True)
        dfi['Dist'] = 1
        dfi['Timediff'] = 0
        dfi['Dist'][1:len(dfi)] = [haversine((dfi['Latitude'][x-1],dfi['Longitude'][x-1]),(dfi['Latitude'][x],dfi['Longitude'][x])) for x in dfi['Dist'][1:].index.tolist()]
        dfi['Timediff'][1:len(dfi)] = [(dfi['Date Time'][i] - dfi['Date Time'][i-1]).total_seconds()/3600 for i in range(1,len(dfi))]
        dfi['Remove'] = np.where((dfi.Dist == 0) & (dfi.Timediff == 0),"Duplicate Points","Static Points")

    #Mark them with differet trip label of data
    if len(df) > 1:
      df['Timediff'] = 0
      df['Timediff'][1:len(df)] = [(df['Date Time'][i] - df['Date Time'][i-1]).total_seconds()/3600 for i in range(1,len(df))]
      for i in range(0,len(df)):
          if df.Timediff[i] > bigtau:
              df.TripID[i] = 1
              continue
          else:
              if df.Timediff[i] > tau:
                  if haversine((df['Latitude'][i],df['Longitude'][i]),(df['Latitude'][i-1],df['Longitude'][i-1])) / df.Timediff[i] < speed_trip:
                     df.TripID[i] = 1

      df['TripID'][0:(len(df)-1)] = [np.sum(df['TripID'][0:(i+1)]) for i in range(0,len(df)-1)]
      df['TripID'][len(df)-1] = df['TripID'][len(df)-1] + df['TripID'][len(df)-2]

    dfi = dfi.append(df).reset_index(drop=True)
    df = dfi[["VendorID","IMEI","VehicleNumber","Date Time","Latitude","Latitude_Direction","Longitude","Longitude_Direction","Speed","TripID","SegmentID","Remove","PacketType","PacketStatus","GPSFix","Heading","SatelliteNumber","Altitude","PDOP","Operator","Ignition","MainPowerStatus","EmergencyStatus","TamperAlert","GSMSignal","MCC","MNC","LAC","CellID","DigitalInput","DigitalOutput","FrameNumber"]]

    return df
    #df.to_csv(dir + "\" +"Mark_Point\" + "Label_" + imeifile[0:15]+ ".csv",date_format='%Y-%m-%d %H:%M:%S')

'''
      mark = 0
      i = 1
      j = 0
      while i < len(df):
          if i == len(df) - 1:
              if ((df['Date Time'].loc[i] - df['Date Time'].loc[i - 1]).total_seconds()) / 3600 > tau:
                   df['TripID'].loc[j:i] = mark
                   df['TripID'].loc[i] = -1
              else:
                  df['TripID'].loc[j:len(df)] = mark
              break

          if ((df['Date Time'].loc[i] - df['Date Time'].loc[i - 1]).total_seconds()) / 3600 > tau:
                if i == j + 1:
                    df['TripID'].loc[j] = -1
                    j = i
                    i = i + 1
                else:
                    df['TripID'].loc[j:i] = mark
                    df['TripID'].loc[i] = -1
                    j = i
                    i = i + 1
                    mark = mark + 1
          else:
                i = i + 1
'''

Driver behaviour analytics/Python_script/IMEI Cleaning/Mark_Point.py


import requests
import json
import sys

#Charles
exec(open("osuAuth.py").read())
headers = {
    'Authorization': 'Bearer ' + get_token()["access_token"]
}

userId = sys.argv[1]
theUser = requests.get('https://osu.ppy.sh/api/v2/users/' + userId, headers=headers)
user = json.loads(theUser.text)
userN = user['id']

scores = json.loads(requests.get('https://osu.ppy.sh/api/v2/users/' + str(userN) + '/scores/best?limit=100', headers=headers).text)

spinners = 0
mapspinners = 0
for i in range(len(scores)):
        mapspinners = scores[i]["beatmap"]["count_spinners"]
        if "SO" in scores[i]["mods"]:
            mapspinners = 0
        spinners += mapspinners

print("there are "+str(spinners)+" spinners in this person's top 100")


from django.test import TestCase
from django.urls import reverse
from .models import MenuModel

class MenuTestCase(TestCase):
    def setUp(self):
        self.menu = MenuModel.objects.create(name='Menu', named_url='menu', parent=None)

    def test_menu_view(self):
        url = reverse('menu', args=['menu'])
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'menu.html')
        self.assertIn('tree', response.context)

    def test_menu_hierarchy(self):
        child_menu = MenuModel.objects.create(name='Child Menu', named_url='child-menu', parent=self.menu)
        url = reverse('menu', args=['menu'])
        response = self.client.get(url)

        self.assertContains(response, self.menu.name)
        self.assertContains(response, child_menu.name)
        self.assertContains(response, '<ul class="children">')


import copy
import pickle
import shutil
from pathlib import Path
from typing import Any, Optional, Union

from ..utilities import Strings

class Object(object):
    supported_extensions = [".pkl"]
    type = "object"
    default_extension = ".pkl"
    supported_object_type = None

    def __init__(self,
                 data: Any = None,
                 path: Union[None, Path, str] = None,
                 name: Optional[str] = None):

        self._data = data

        if type(path) == str and path != "":
            self._path = Path(path)
        elif isinstance(path, Path):
            self._path = path
        else:
            self._path = None

        if name is None or name == "":
            if self._path is not None:
                name = self._path.name
            else:
                name = Strings().random_string(16)
        self._name = name

    def __repr__(self):
        return self.to_repr()

    def __str__(self):
        return self.to_str()

    def _lazy_load(self):
        pass

    def to_repr(self) -> str:
        return "<Type: {}>".format(self.type)

    def to_str(self) -> str:
        return "<Type: {}>".format(self.type)

    def to_dict(self) -> dict:
        return {}

    @property
    def data(self) -> Any:
        if self._data is None and self._path is not None:
            self._lazy_load()
        return self._data

    @property
    def name(self) -> str:
        return self._name

    @property
    def path(self) -> Optional[Path]:
        return self._path

    @property
    def extension(self) -> str:
        if isinstance(self._path, Path):
            return self._path.suffix
        return ""

    def save(self,
             path: Path,
             encoding: Optional[str] = 'utf-8',
             indent: Optional[int] = None) -> bool:

        if self.path is not None:
            shutil.copy(self.path, path)
            return True

        if self._data is None:
            path.touch()
            return True

        try:
            with path.open(mode='wb') as file:
                pickle.dump(self._data, file)
        except TypeError:
            path.write_text("Can't pickle this object")
        except AttributeError:
            path.write_text("Can't pickle this object")

        return True

    def clear(self):
        self._data = None

    def copy(self, path: Path) -> bool:
        if self.path is None:
            return self.save(path)
        else:
            shutil.copy(self.path, path)

        return True

    def rename(self, name: str):
        self._name = name

    def get_file_name(self, base_path: Optional[Path] = None) -> Path:
        path = Path(self._name)
        if path.suffix == "":
            path = path.parent.joinpath(self.name + self.default_extension)
        if path.suffix not in self.supported_extensions:
            path = path.parent.joinpath(path.name + self.default_extension)
        if base_path is not None:
            path = base_path.joinpath(path.name)

        return path

    @classmethod
    def load(cls, path: Path, name: Optional[str] = None) -> "Object":
        return cls(path=path, name=cls._get_name(path, name))

    @classmethod
    def is_supported_file(cls, path: Path) -> bool:
        if path.suffix in cls.supported_extensions:
            return True

        return False

    @classmethod
    def is_supported_object(cls, _object: Any) -> bool:
        if cls.supported_object_type is None:
            return False
        if isinstance(_object, cls.supported_object_type):
            return True
        return False

    @classmethod
    def _get_name(cls, path: Path, name: Optional[str] = None) -> str:
        if name is not None:
            return name

        return path.name

    def get(self, data_format: Optional[str] = None) -> Optional[object]:
        return self.data