import os

from qbittorrent import Client
from qbittorrent.client import LoginRequired

qb = Client('http://127.0.0.1:8080/')
def get_torrent_connection():
    try:
        # check connection. Throw exception if token expired
        qb.torrents()
    except LoginRequired:
        # get new token
        print("get new token")
        qb.login('admin', 'adminadmin')
    return qb

def parse_credentials():
    with open('credentials.txt', 'r') as f:
        return f.read().splitlines()

def parse_id(l, value):
    try:
        value = int(value) - 1
        if not len(l) > value >= 0:
            return None
        return value
    except ValueError:
        return None

def create_incorrect_id_message(conn, req):
    torrents_count = len(conn.torrents())
    if torrents_count == 0:
        return "empty torrent list"
    return 'incorrect [id] value, for example try {0} {1}'.format(req['command'], 1)

def create_torrent_folder():
    if not os.path.isdir('../torrents'):
        os.mkdir('../torrents')


r1=int(input())
r2=int(input())

mat1=[]
mat2=[]
re1=[]
nmat2=[]
for i in range(r1):
    mat1.append(list(map(int,input().split(" "))))
for i in range(r2):
    mat2.append(list(map(int,input().split(" "))))

c1=len(mat1[0])
c2=len(mat2[0])

nmat2=[mat2[i][j] for i in range(r2) for j in range(c2)]
re=[]
for i in range(r1):
    for j in range(c1):

        num=-100
        temp=[]
        temp.clear()
        try:
            num=mat1[i][j]*mat2[i][j]
            temp.append(num)
        except IndexError :
            num=-1
            temp.append(-1)
        try:
            num=mat1[i][j]*mat2[j][i]
            temp.append(num)
        except IndexError :
            num=-1
            temp.append(-1)
        try:
            num=mat1[i][j]*mat2[i][i]
            temp.append(num)
        except IndexError :
            num=-1
            temp.append(-1)
        try:
            num=mat1[i][j]*mat2[j][j]
            temp.append(num)
        except IndexError :
            num=-1
            temp.append(-1)
        if(len(set(temp))!=1 and temp.count(-1)>0):
            while(temp.count(-1)>0 and len(temp)>1):
                x=temp.index(-1)
                temp.pop(x)

        print(min(temp),end=" ")
    print()

#re=list(map(str,re))

#print(re)


# O(n) time || O(n) space
def nth_ugly_number(self, n: int) -> int:
    res = [1]
    prod_2 = prod_3 = prod_5 = 0
    a, b, c = 2, 3, 5
    for i in range(1, n):
        m = min(a, b, c)
        res.append(m)

        if m == a:
            prod_2 += 1
            a = res[prod_2] * 2

        if m == b:
            prod_3 += 1
            b = res[prod_3] * 3

        if m == c:
            prod_5 += 1
            c = res[prod_5] * 5

    return res[-1]

# O(n) time || O(n) space
def nth_ugly_number_pre_calculated(self, n: int) -> int:
    ugly = sorted(2 ** a * 3 ** b * 5 ** c
                  for a in range(32) for b in range(20) for c in range(14))

    return ugly[n - 1]


from __future__ import annotations

from typing import ClassVar, Optional

from pydantic import Field, validator

from pyatlan.model.fields.atlan_fields import KeywordTextField, NumericField

from .asset18 import BI

class Preset(BI):
    """Description"""

    type_name: str = Field("Preset", allow_mutation=False)

    @validator("type_name")
    def validate_type_name(cls, v):
        if v != "Preset":
            raise ValueError("must be Preset")
        return v

    def __setattr__(self, name, value):
        if name in Preset._convenience_properties:
            return object.__setattr__(self, name, value)
        super().__setattr__(name, value)

    PRESET_WORKSPACE_ID: ClassVar[NumericField] = NumericField(
        "presetWorkspaceId", "presetWorkspaceId"
    )
    """
    TBC
    """
    PRESET_WORKSPACE_QUALIFIED_NAME: ClassVar[KeywordTextField] = KeywordTextField(
        "presetWorkspaceQualifiedName",
        "presetWorkspaceQualifiedName",
        "presetWorkspaceQualifiedName.text",
    )
    """
    TBC
    """
    PRESET_DASHBOARD_ID: ClassVar[NumericField] = NumericField(
        "presetDashboardId", "presetDashboardId"
    )
    """
    TBC
    """
    PRESET_DASHBOARD_QUALIFIED_NAME: ClassVar[KeywordTextField] = KeywordTextField(
        "presetDashboardQualifiedName",
        "presetDashboardQualifiedName",
        "presetDashboardQualifiedName.text",
    )
    """
    TBC
    """

    _convenience_properties: ClassVar[list[str]] = [
        "preset_workspace_id",
        "preset_workspace_qualified_name",
        "preset_dashboard_id",
        "preset_dashboard_qualified_name",
    ]

    @property
    def preset_workspace_id(self) -> Optional[int]:
        return None if self.attributes is None else self.attributes.preset_workspace_id

    @preset_workspace_id.setter
    def preset_workspace_id(self, preset_workspace_id: Optional[int]):
        if self.attributes is None:
            self.attributes = self.Attributes()
        self.attributes.preset_workspace_id = preset_workspace_id

    @property
    def preset_workspace_qualified_name(self) -> Optional[str]:
        return (
            None
            if self.attributes is None
            else self.attributes.preset_workspace_qualified_name
        )

    @preset_workspace_qualified_name.setter
    def preset_workspace_qualified_name(
        self, preset_workspace_qualified_name: Optional[str]
    ):
        if self.attributes is None:
            self.attributes = self.Attributes()
        self.attributes.preset_workspace_qualified_name = (
            preset_workspace_qualified_name
        )

    @property
    def preset_dashboard_id(self) -> Optional[int]:
        return None if self.attributes is None else self.attributes.preset_dashboard_id

    @preset_dashboard_id.setter
    def preset_dashboard_id(self, preset_dashboard_id: Optional[int]):
        if self.attributes is None:
            self.attributes = self.Attributes()
        self.attributes.preset_dashboard_id = preset_dashboard_id

    @property
    def preset_dashboard_qualified_name(self) -> Optional[str]:
        return (
            None
            if self.attributes is None
            else self.attributes.preset_dashboard_qualified_name
        )

    @preset_dashboard_qualified_name.setter
    def preset_dashboard_qualified_name(
        self, preset_dashboard_qualified_name: Optional[str]
    ):
        if self.attributes is None:
            self.attributes = self.Attributes()
        self.attributes.preset_dashboard_qualified_name = (
            preset_dashboard_qualified_name
        )

    class Attributes(BI.Attributes):
        preset_workspace_id: Optional[int] = Field(
            None, description="", alias="presetWorkspaceId"
        )
        preset_workspace_qualified_name: Optional[str] = Field(
            None, description="", alias="presetWorkspaceQualifiedName"
        )
        preset_dashboard_id: Optional[int] = Field(
            None, description="", alias="presetDashboardId"
        )
        preset_dashboard_qualified_name: Optional[str] = Field(
            None, description="", alias="presetDashboardQualifiedName"
        )

    attributes: "Preset.Attributes" = Field(
        default_factory=lambda: Preset.Attributes(),
        description="Map of attributes in the instance and their values. The specific keys of this map will vary by "
        "type, so are described in the sub-types of this schema.\n",
    )

Preset.Attributes.update_forward_refs()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri July 31 17:35:32 2020

@author: vivekmodi
"""

import pandas as pd, sys, os, gzip, argparse
from Bio import PDB

from Kincore.modules.assign_default_values import assign_default_values
from Kincore.modules.extract_sequence import extract_seq
from Kincore.modules.run_hmmsearch import run_hmmsearch
from Kincore.modules.identify_restypes import identify_restypes
from Kincore.modules.identify_group import identify_group
from Kincore.modules.identify_residues import identify_residues
from Kincore.modules.compute_distance import compute_distance
from Kincore.modules.compute_dihedrals import compute_dihedrals
from Kincore.modules.chelix import chelix_conformation
from Kincore.modules.spatial_label import spatial_label
from Kincore.modules.dihedral_label import dihedral_label
from Kincore.modules.delete_files import delete_files
from Kincore.modules.extract_ligands import extract_ligands
from Kincore.modules.classify_ligands import classify_ligands

def read_inputlist(hmm_loc,pdbfilename,align,user_chain,user_lys,user_glu,user_phe,header):     #Function to read input file list
    fhandle_files=open(pdbfilename,'r')
    for names in fhandle_files:
        name=names.strip();names=names.split()
        identify_state(hmm_loc,name,align,user_chain,user_lys,user_glu,user_phe,header)
        header=1

def print_header_withoutgroup(pdbfilename,index,conf_df):       #Print Header when align=False
    print('Input'.rjust(len(pdbfilename)+1)+'Model'.rjust(6)+'Chain'.rjust(6)+'Spatial_label'.rjust(14)+\
          'Dihedral_label'.rjust(15)+'C-helix_label'.rjust(14)+'X-DFG Φ Ψ'.center(22)+'DFG-Asp Φ Ψ'.center(22)+'DFG-Phe Φ Ψ χ1'.center(30))

def print_header_withgroup(pdbfilename,index,conf_df):    #Print Header when align=True
    print('Input'.rjust(len(pdbfilename)+1)+'Group'.rjust(6)+'Model'.rjust(6)+'Chain'.rjust(6)+'Spatial_label'.rjust(14)+\
    'Dihedral_label'.rjust(15)+'C-helix_label'.rjust(14)+'Ligand'.rjust(len(conf_df.at[index,'Ligand'])+1)+'Ligand_label'.rjust(len(conf_df.at[index,'Ligand_label'])+9)+\
    'X-DFG Φ Ψ'.center(22)+'DFG-Asp Φ Ψ'.center(22)+'DFG-Phe Φ Ψ χ1'.center(30))

def identify_state(pwd,pdbfilename,align,user_chain,user_lys,user_glu,user_phe,header):
    conf_df=pd.DataFrame()
    chain_list=list()

    if '.gz' in pdbfilename.lower():      #Check if the file is compressed
        handle=gzip.open(pdbfilename,'rt')
    else:
        handle=open(pdbfilename,'r')

    if '.cif' in pdbfilename.lower():
            parser=PDB.MMCIFParser(QUIET=True)
    if '.pdb' in pdbfilename.lower():
            parser=PDB.PDBParser(QUIET=True)

    structure=parser.get_structure(pdbfilename, handle)

    if align.upper()=='FALSE':
        for model in structure:
            index=int(model.id)
            conf_df.at[index,'Model_id']=int(model.id)
            for chain in model:
                for chains in list(user_chain.split(',')):
                    if chain.id==chains:       #Match user chain with chain in structure
                        conf_df.at[index,'Chain_id']=chain.id
                        conf_df=assign_default_values(index,conf_df)
                        conf_df.at[index,'Lys_num']=int(user_lys)
                        conf_df.at[index,'Glu_num']=int(user_glu)
                        conf_df.at[index,'Glu4_num']=int(user_glu)+4
                        conf_df.at[index,'Phe_num']=int(user_phe)
                        conf_df.at[index,'XDFG_num']=int(user_phe)-2
                        conf_df.at[index,'Asp_num']=int(user_phe)-1
                        conf_df=identify_restypes(pdbfilename,conf_df,index,structure)
                        conf_df=compute_distance(pdbfilename,index,conf_df,structure)
                        conf_df=compute_dihedrals(pdbfilename,index,conf_df,structure)
                        conf_df=spatial_label(index,conf_df)
                        conf_df=dihedral_label(index,conf_df,0.45)
                        conf_df=chelix_conformation(index,conf_df)
                        if header==0:
                            print_header_withoutgroup(pdbfilename,index,conf_df)
                            header=1
                        xdfg_string=str(str(int(conf_df.at[index,'XDFG_num']))+conf_df.at[index,'XDFG_restype'])
                        asp_string=str(str(int(conf_df.at[index,'Asp_num']))+conf_df.at[index,'Asp_restype'])
                        phe_string=str(str(int(conf_df.at[index,'Phe_num']))+conf_df.at[index,'Phe_restype'])
                        print(pdbfilename.rjust(len(pdbfilename)+1)+str(int(conf_df.at[index,'Model_id'])).rjust(6)+conf_df.at[index,'Chain_id'].rjust(6)+\
                              conf_df.at[index,'Spatial_label'].rjust(14)+conf_df.at[index,'Dihedral_label'].rjust(15)+conf_df.at[index,'Chelix'].rjust(14)+\
                              xdfg_string.rjust(6)+str('%.2f' %conf_df.at[index,'XDFG_Phi']).rjust(8)+str('%.2f' %conf_df.at[index,'XDFG_Psi']).rjust(8)+\
                              asp_string.rjust(6)+str('%.2f' %conf_df.at[index,'Asp_Phi']).rjust(8)+str('%.2f' %conf_df.at[index,'Asp_Psi']).rjust(8)+phe_string.rjust(6)+str('%.2f' %conf_df.at[index,'Phe_Phi']).rjust(8)+\
                              str('%.2f' %conf_df.at[index,'Phe_Psi']).rjust(8)+str('%.2f' %conf_df.at[index,'Phe_Chi1']).rjust(8))

    elif align.upper()=='TRUE':
        index=-1
        for model in structure:
            for chain in model:
                if len(chain.get_list())<=30:
                    continue
                chain_list.append(chain.id)
                index+=1

                for residue in chain:
                    if residue.id[2]!=' ':
                        print(f'{pdbfilename} Please enter a structure file without insertion codes.')
                        sys.exit()
                conf_df.at[index,'Model_id']=str(model.id)
                conf_df.at[index,'Chain_id']=chain.id
                conf_df=assign_default_values(index,conf_df)

                conf_df=extract_seq(pdbfilename,index,conf_df)
                run_hmmsearch(pwd,pdbfilename,index,conf_df)
                conf_df=identify_group(pdbfilename,index,conf_df)

                if conf_df.at[index,'Group']=='None':
                    delete_files(pdbfilename,conf_df.at[index,'Model_id'],conf_df.at[index,'Chain_id'], conf_df.at[index,'Group'])

                else:
                    conf_df=identify_residues(pdbfilename,index,conf_df)
                    if conf_df.at[index,'Lys_restype']=='X' or conf_df.at[index,'Glu_restype']=='X' or conf_df.at[index,'Phe_restype']=='X' or conf_df.at[index,'XDFG_restype']=='X' or conf_df.at[index,'Asp_restype']=='X':
                        #print('#'+pdbfilename.rjust(13)+conf_df.at[index,'Group'].rjust(6)+str(int(conf_df.at[index,'Model_id'])).rjust(6)+conf_df.at[index,'Chain_id'].rjust(6)+'       Conserved residues missing in the structure.')
                        delete_files(pdbfilename,conf_df.at[index,'Model_id'],conf_df.at[index,'Chain_id'], conf_df.at[index,'Group'])

                    else:
                        conf_df=compute_distance(pdbfilename,index,conf_df,structure)
                        conf_df=compute_dihedrals(pdbfilename,index,conf_df,structure)
                        conf_df=chelix_conformation(index,conf_df)
                        conf_df=spatial_label(index,conf_df)
                        conf_df=dihedral_label(index,conf_df,0.45)
                        conf_df=chelix_conformation(index,conf_df)
                        conf_df=extract_ligands(pdbfilename,index,conf_df,structure)
                        try:
                            conf_df=classify_ligands(pdbfilename,index,conf_df,structure)
                        except:
                            conf_df.at[index,'Ligand_label']='Error'

                        if header==0:
                            print_header_withgroup(pdbfilename,index,conf_df)
                            header=1

                        xdfg_string=str(str(int(conf_df.at[index,'XDFG_num']))+conf_df.at[index,'XDFG_restype'])
                        asp_string=str(str(int(conf_df.at[index,'Asp_num']))+conf_df.at[index,'Asp_restype'])
                        phe_string=str(str(int(conf_df.at[index,'Phe_num']))+conf_df.at[index,'Phe_restype'])
                        print(pdbfilename.rjust(len(pdbfilename)+1)+conf_df.at[index,'Group'].rjust(6)+conf_df.at[index,'Model_id'].rjust(6)+conf_df.at[index,'Chain_id'].rjust(6)+\
                        # conf_df.at[index,'Spatial_label'].rjust(14)+conf_df.at[index,'Dihedral_label'].rjust(15)+conf_df.at[index,'Chelix'].rjust(14)+conf_df.at[index,'Ligand'].rjust(len(conf_df.at[index,'Ligand'])+1)+\
                        # conf_df.at[index,'Ligand_label'].rjust(len(conf_df.at[index,'Ligand_label'])+9)+xdfg_string.rjust(6)+str('%.2f' %conf_df.at[index,'XDFG_Phi']).rjust(8)+str('%.2f' %conf_df.at[index,'XDFG_Psi']).rjust(8)+\
                        # asp_string.rjust(6)+str('%.2f' %conf_df.at[index,'Asp_Phi']).rjust(8)+str('%.2f' %conf_df.at[index,'Asp_Psi']).rjust(8)+phe_string.rjust(6)+str('%.2f' %conf_df.at[index,'Phe_Phi']).rjust(8)+\
                        # str('%.2f' %conf_df.at[index,'Phe_Psi']).rjust(8)+str('%.2f' %conf_df.at[index,'Phe_Chi1']).rjust(8))
                        str('%.3f' %conf_df.at[index,'Glu4-Phe-dis']).rjust(8)+str('%.3f' %conf_df.at[index,'Lys-Phe-dis']).rjust(8))

                        delete_files(pdbfilename,conf_df.at[index,'Model_id'],conf_df.at[index,'Chain_id'],conf_df.at[index,'Group'])

        for i in conf_df.index:
            if conf_df.at[i,'Group']=='None':
                print(f'# {pdbfilename} Model {conf_df.at[i,"Model_id"]} Chain {conf_df.at[i,"Chain_id"]} is probably not a protein kinase.')
            if conf_df.at[i,'Group']!='None' and (conf_df.at[i,'Lys_restype']=='X' or conf_df.at[i,'Glu_restype']=='X' or conf_df.at[i,'Phe_restype']=='X' or conf_df.at[i,'XDFG_restype']=='X' or conf_df.at[i,'Asp_restype']=='X'):
                print(f'# {pdbfilename} Model {conf_df.at[i,"Model_id"]} Chain {conf_df.at[i,"Chain_id"]} is missing the required residues.')

    return conf_df

if __name__ == '__main__':
    hmm_loc=os.path.dirname(os.path.realpath(__file__))+'/HMMs'    #gets the original location of the file
    parser=argparse.ArgumentParser()
    parser.add_argument('PDB',help='PDB file in .cif or .pdb format. You can also provide compressed file as file.cif.gz or file.pdb.gz or list of filenames in a .txt file.')
    parser.add_argument('Align',help='True/False; If "True" (Slower) then the program will align the input protein sequence to pre-computed HMMs and identify conserved \
                        residues to determine kinase conformational labels and ligand type (Example $python kinase_state.py 1GAG.pdb True).\
                        If "False" (Faster) then please provide the optional arguments (Example $python kinase_state.py -L 1030 -G 1047 -P 1151 -C A,B,C 1GAG.pdb False). Please note that \
                        the program can provide ligand information only when this argument is True.')

    parser.add_argument('-L','--Lys',help='Residue number of the conserved B3-Lys in the input PDB file')
    parser.add_argument('-G','--Glu',help='Residue number of the conserved C-helix-Glu in the input PDB file')
    parser.add_argument('-P','--Phe',help='Residue number of the conserved DFG-Phe in the input PDB file')
    parser.add_argument('-C','--Chain',type=str,help='Chain id of the protein kinase chain in the input file')
    args=parser.parse_args()

    pdbfilename=args.PDB
    if args.Align.upper()=='TRUE':
        user_chain=user_lys=user_glu=user_phe=align=''
    else:
        if not args.Lys or not args.Glu or not args.Phe or not args.Chain:
            print('Please provide residue numbers and chain id.')
            exit()
        else:
            user_chain=str(args.Chain);user_lys=int(args.Lys);user_glu=int(args.Glu);user_phe=int(args.Phe)

    header=0
    if '.txt' in pdbfilename:
        read_inputlist(hmm_loc,pdbfilename,args.Align,user_chain,user_lys,user_glu,user_phe,header)
    else:
        identify_state(hmm_loc,pdbfilename,args.Align,user_chain,user_lys,user_glu,user_phe,header)


import torch
from torchvision import transforms, datasets
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, random_split

DATASET_FOLDER = "./data"

def build_transform():
    transform = transforms.Compose(
        [
            transforms.ToTensor(),
            transforms.Normalize(mean=[0], std=[1]),
            transforms.Lambda(lambda x: torch.flatten(x)),
        ]
    )
    return transform

def build_datasets(transform):
    dataset = datasets.MNIST(
        root=DATASET_FOLDER, train=True, download=True, transform=transform
    )
    test_dataset = datasets.MNIST(
        root=DATASET_FOLDER, train=False, download=True, transform=transform
    )
    return dataset, test_dataset

def split_dataset(dataset, split):
    right_dataset_size = int(len(dataset) * split)
    left_dataset_size = len(dataset) - right_dataset_size
    generator = torch.Generator().manual_seed(42)
    return random_split(dataset, [left_dataset_size, right_dataset_size], generator)

def build_samplers(train_dataset, val_dataset, test_dataset):
    train_sampler = RandomSampler(train_dataset)
    val_sampler = RandomSampler(val_dataset)
    test_sampler = SequentialSampler(test_dataset)
    return train_sampler, val_sampler, test_sampler

def get_loaders(batch_size, val_split = (1/12)):
    transform = build_transform()
    dataset, test_dataset = build_datasets(transform)
    train_dataset, val_dataset = split_dataset(dataset, val_split)
    train_sampler, val_sampler, test_sampler = build_samplers(
        train_dataset, val_dataset, test_dataset
    )

    train_loader = DataLoader(
        train_dataset,
        sampler=train_sampler,
        batch_size=batch_size,
        pin_memory=True,
    )
    val_loader = DataLoader(
        val_dataset,
        sampler=val_sampler,
        batch_size=batch_size,
        pin_memory=True,
    )
    test_loader = DataLoader(
        test_dataset,
        sampler=test_sampler,
        batch_size=batch_size,
        pin_memory=True,
    )

    return train_loader, val_loader, test_loader


class Recipe(object):
    '''a recipe object, which has the information about the recipe
    This instance can be made from several type
    Class Attributes
    ----------------
    recipe_id: string
        the recipe id: unique
    url: string
        the url of the recipe to opne in browser
    recipe_name: string
        the recipe is unique
    calories: float
        total calories of the meal
    time: float
        time for cooking the meal
    cuisineType: string
        the cuisine type
    servings: float
        the number of servings
    ingredient: list
        ingredients, each attributes is each ingredient
    totalDaily: dict
        the parcentage of daily nutrient
    file_name: string
        the file name to open thumbnail image
    '''
    def __init__(self, recipe=None, recipe_result=None):
        if recipe:
            self.recipe_id = recipe['recipe']['uri']
            self.url = recipe['recipe']['shareAs']
            self.recipe_name = recipe['recipe']['label']
            self.calories = round(recipe['recipe']['calories'], 3)
            self.time = recipe['recipe']['totalTime']
            self.cuisineType = recipe['recipe']['cuisineType'][0]
            self.servings = recipe['recipe']['yield'] + 1
            self.ingredient = recipe['recipe']['ingredientLines']
            self.totalDaily = recipe['recipe']['totalDaily']
            self.image = recipe['recipe']['image']
            self.file_name = self.recipe_id[self.recipe_id.find("#")+1:]

        elif recipe_result:
            self.recipe_id = recipe_result['recipe_id']
            self.url = recipe_result['url']
            self.recipe_name = recipe_result['recipe_name']
            self.calories = recipe_result['calories']
            self.time = recipe_result['time']
            self.cuisineType = recipe_result['cuisineType']
            self.servings = recipe_result['servings']
            self.ingredient = recipe_result['ingredient']
            self.totalDaily = recipe_result['totalDaily']
            self.image = recipe_result['image']
            self.file_name = recipe_result['file_name']

        else:
            self.recipe_id = 'no_id'
            self.url = 'no url'
            self.recipe_name = 'no name'
            self.calories = 0.
            self.time = 0.
            self.cuisineType = 'no label'
            self.servings = 1.0
            self.ingredient = []
            self.totalDaily = {}
            self.image = 'no image'
            self.file_name = 'no name'

    def to_json(self):
        '''convert the object to python dictionary object
        Parameters
        ----------
        None
        Returns
        -------
        dict
        '''
        return {'recipe_id': self.recipe_id,
                'recipe_name': self.recipe_name,
                'calories': self.calories,
                'time': self.time,
                'cuisineType': self.cuisineType,
                'servings': self.servings,
                'ingredient': self.ingredient,
                'totalDaily': self.totalDaily,
                'image': self.image,
                'url': self.url,
                'file_name': self.file_name}


import numpy as np
from util import *

# Q 2.1

def initialize_weights(in_size,out_size,params,name=''):
    total = out_size + in_size
    upper_val = np.sqrt(6.0 / total)
    lower_val = -upper_val

    W = np.random.uniform(lower_val, upper_val, (in_size, out_size))
    b = np.zeros(out_size)

    params['W' + name] = W
    params['b' + name] = b

# Q 2.2.1

def sigmoid(x):
    res = 1.0 / (1.0 + np.exp(-x))
    return res

# Q 2.2.2
def forward(X,params,name='',activation=sigmoid):

    pre_act, post_act = None, None
    W = params['W' + name]
    b = params['b' + name]

    pre_act = np.dot(X, W) + b
    post_act = activation(pre_act)
    params['cache_' + name] = (X, pre_act, post_act)
    return post_act

# Q 2.2.2
def softmax(x):
    i = x.shape
    maximum_x = np.max(x, axis=1)
    res = np.zeros(i)
    shaped = np.expand_dims(maximum_x, axis=1)
    x_moved = x + (-1.0 * shaped)
    out = np.exp(x_moved)
    sum_out = np.sum(out, axis=1)
    res = out/np.expand_dims(sum_out, axis =1)
    return res

# Q 2.2.3
# compute total loss and accuracy
def compute_loss_and_acc(y, probs):
    y = y.astype(int)
    N = y.shape[0]
    y_predicted = probs == np.expand_dims(np.max(probs, axis=1),axis=1)
    sum_ypred = np.sum(y_predicted, axis=1)
    equal_prob = np.where(sum_ypred > 1)[0]
    logarithm = np.log(probs)
    loss = -1.0 * np.sum(y*logarithm)
    m = equal_prob.shape[0]
    for i in range(0,m):
        y_predicted[i, np.where(y_predicted[i, :]==np.max(y_predicted[i, :]))[0][0]+1:] = False
    dev = np.abs(y_predicted-y)
    acc = (N - (np.sum(dev))//2) / N

    return loss, acc

def sigmoid_deriv(post_act):
    res = post_act*(1.0-post_act)
    return res
# Q2.3.1
def backwards(delta,params,name='',activation_deriv=sigmoid_deriv):
    grad_X, grad_W, grad_b = None, None, None
    W = params['W' + name]
    b = params['b' + name]
    X, pre_act, post_act = params['cache_' + name]

    grad_X = np.zeros(X.shape)
    grad_b = np.zeros(b.shape)
    grad_W  = np.zeros(W.shape)
    m = delta.shape[0]
    n = np.ones((1, m))
    dim_del = delta.ndim
    dim_x = X.ndim

    if dim_del == 1:
        delta = delta.reshape((1, m))
    if dim_x == 1:
        X = X.reshape((1, X.shape[0]))

    res = delta * activation_deriv(post_act)
    grad_X = np.dot(res, np.transpose(W))
    grad_W = np.dot(np.transpose(X), res)
    grad_b = np.dot(n, res).reshape([-1])

    params['grad_W' + name] = grad_W
    params['grad_b' + name] = grad_b
    return grad_X

# Q 2.4
def get_random_batches(x,y,batch_size):
    batches = []
    f = range(x.shape[0])
    m = len(f)

    while m > 0:
        choice = []
        updated_x = []
        updated_y = []
        batchID = np.random.randint(0,m,batch_size)
        for item in batchID:
            choice.append(f[item])
        for item in choice:
             updated_x.append(x[item])
        for item in choice:
            updated_y.append(y[item])
        x_array = np.array(updated_x)
        y_array = np.array(updated_y)
        batches.append((x_array, y_array))
        out = set(f) - set(choice)
        f = list(out)
        m = len(f)
    return batches


import uvicorn
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware

from app.api.api_v1.api import api_router
from app.db.session import db
from app.rocketry_worker import rocketry_app

fastapi_app = FastAPI(title='SuperAPI', openapi_url='/api/v1/openapi.json', version='0.0.1')
fastapi_app.include_router(api_router)

rocketry_session = rocketry_app.session

fastapi_app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@fastapi_app.get("/my-route")
async def get_tasks():
    return rocketry_session.tasks

@fastapi_app.on_event("startup")
async def startup():
    await db.connect()

@fastapi_app.on_event("shutdown")
async def shutdown():
    await db.disconnect()

if __name__ == "__main__":
    uvicorn.run('main:app', host="127.0.0.1", port=5000, reload=True)


import os

from fastapi import FastAPI

from starlette.responses import StreamingResponse
from threading import Thread
import time

import cv2

from data import Data

app = FastAPI()

data = Data()

def read_file(video_dir):
    while True:
        cap = cv2.VideoCapture(video_dir)
        while cap.isOpened():
            # Capture frame-by-frame
            ret, frame = cap.read()
            if ret:

                # Display the resulting frame
                # cv2.imshow('Frame', frame)

                # convert frame to JPEG format
                _, encoded_frame = cv2.imencode('.jpg', frame)

                # convert JPEG-encoded frame to bytes
                bytes_frame = encoded_frame.tobytes()

                #split video_dir to get stream_id
                stream_id = video_dir.split('/')[-1].split('.')[0]
                # print(stream_id)
                data.data[stream_id] = bytes_frame
                # Press Q on keyboard to  exit
                # if cv2.waitKey(25) & 0xFF == ord('q'):
                #     break

            # Break the loop
            else:
                break

        # When everything done, release the video capture object
        cap.release()

for videos in os.listdir('./Videos'):
    video_dir = os.path.join('./Videos', videos)
    t = Thread(target=read_file, args=(video_dir, ))
    t.start()

def send_frame(stream_id: str):
    while True:
        frame_bytes = data.data[stream_id]
        # print(self.stream_frames[stream_name])
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n')

@app.get("/")
async def root():
    return {"message": "Hello World"}

@app.get("/")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}

@app.get('/{stream_id}')
async def stream_video(stream_id: str):
    return StreamingResponse(send_frame(stream_id),
                             media_type="multipart/x-mixed-replace; boundary=frame")


#!/usr/bin/env python
# Importing all functions defined in SetupHeader.py
from HeaderFile import *

print("EDA Job Starting...\n")

train_df, test_df = path_to_csv()

train_df = prepareSpecialSet(train_df)
test_df = prepareSpecialSet(test_df)
# print(test_df.info())
# Combine
# frames = [train_df, test_df]
# train_df = pd.concat(frames)
# print(train_df.info())
# print('_'*50)
# print(test_df.info())

## Passenger Fare filtering (Removes '$', round to 2 d.p., cast type as float)
RemoveDollarSign(train_df)
RemoveDollarSign(test_df)
# print(train_df.head())
# print(test_df.head())

# condition for new inputs?!
existing_df = train_df.copy()

## Data type discrepancy and applying numeric categorization where possible
# Round up the Age values
train_df['Age'] = train_df['Age'].apply(np.ceil)
test_df['Age'] = test_df['Age'].apply(np.ceil)

# Replace alphanumeric Cabin entries with the first alphabet present
CabinFilter(train_df)
CabinFilter(test_df)

# Binary conversion "Yes" and "male" to 1, "No" and "female" to 0
# Converting for train_df
Conversion(train_df, 'Survived', "Yes", "No")
Conversion(train_df, 'Gender', "male", "female")
# Converting for test_df
Conversion(test_df, 'Survived', "Yes", "No")
Conversion(test_df, 'Gender', "male", "female")

# Change DataFrame type from object to int
ToTypeInt(train_df, 'Survived')
ToTypeInt(train_df, 'Gender')
ToTypeInt(train_df, 'Age')
ToTypeInt(test_df, 'NumSiblingSpouse')
ToTypeInt(test_df, 'NumParentChild')
ToTypeInt(test_df, 'Ticket Class')
ToTypeInt(test_df, 'Survived')
ToTypeInt(test_df, 'Gender')
ToTypeInt(test_df, 'Age')
# print(train_df.info())
# print(test_df.info())
# Copies over dataframe before columns are dropped
train_df_B4mod = train_df.copy()
test_df_B4mod = test_df.copy()

## Embarkation Country
# Removes Embarkation Country entries that aren't 'A' to 'Z' or 'a' to 'z'
# and categorizes the rest. Known countries: C, Q, S,  to 1, 2, 3.
# Everything else is group 4
train_df = RemoveOutlier(train_df)
test_df = RemoveOutlier(test_df)
# print(train_df.head(n=131))         # Passenger ID 130 should be removed
# print(test_df.head(n=70))           # Passenger ID 865 row should be removed

## Name and Age
# list available titles [0, 1, 2, 3]
titles = ['Miss','Mrs', 'Mr', 'Master']
# Titles less than 10: Ms, Dr, Rev, Major
# and Special titles will be enumerated <-- len(titles)

# array to help find mean of each title's age
# [0][0] titles index 0, sum of the ages;
# [4][1] people with outside of the titles list, total number;
# [3][2] titles index 3, mean age of the specified title
ageMean = np.zeros((5, 3)).astype(int)

# Add titles into the Title column and check age from train_df
# Replaces "0" in Age to the mean of the name's respective title & groups them
# Check whether the count and average are correct;
# (134 94 352 31  19) + 167 0s = 797.
# Results in 2 new columns, Title and AgeGroup, which will replace Name and Age
# in the modelling stage
Amend_Title_Age(train_df, True, titles, ageMean)
Amend_Title_Age(test_df, False, titles, ageMean)

## NumSibilingSpouse and NumParentChild
# Values in these 2 columns will be combined (Sum) and categorised into 3 groups.
# Sum = 0, group 0; 0 < Sum < 4, group 1; the rest are in group 2
CombineRelatives(train_df)
CombineRelatives(test_df)

# Copies over dataframe before columns are dropped
train_df_B4drop = train_df.copy()
test_df_B4drop = test_df.copy()

print("EDA Job Done")
# NonTruncDisplay(test_df, 'test')
# Prevents auto closure of command promt for exe
# k=input("Input a character followed by pressing Enter to exit")


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/04/24 16:37
# @Author  : Nana Xing
# @Site    :
# @File    : gui_demo.py
# @Software: PyCharm
from tkinter import *
import tkinter.messagebox as messagebox
win = Tk()
# 设置窗口大小300*300和位置（120,100）
win.geometry('300x300+120+100')
class Application(Frame):
    def __init__(self,master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.nameInput = Entry(self)
        self.nameInput.pack()
        self.alterButton = Button(self, text='Hello',command=self.hello)
        self.alterButton.pack()

    def hello(self):
        name = self.nameInput.get() or 'world'
        messagebox.showinfo("Message",'Hello,%s' % name)

# 实例化
app = Application()
# 设置窗口标题
app.master.title('Hello world GUI')
# 主消息循环
app.mainloop()


from odoo import models

CHECK_MODELS = [
    "sale.order.line",
    "stock.inventory.line",
    "purchase.order.line",
]

class ProductProduct(models.Model):
    _inherit = "product.product"

    def _filter_not_deletable(self):
        if not self:
            return self
        self.flush()
        not_deletable_ids = set()
        for model_name in CHECK_MODELS:
            if model_name in self.env:
                table = self.env[model_name]._table
                self.env.cr.execute(
                    f"""SELECT product_id
                    FROM {table}
                    WHERE product_id in %s
                    GROUP BY product_id
                    """,
                    (tuple(self.ids),),
                )
                ids = [x[0] for x in self.env.cr.fetchall()]
                not_deletable_ids |= set(ids)
        return self.browse(not_deletable_ids)

    def _unlink_or_archive(self, check_access=True):
        # native unlink is super slow
        # First get not deletable product (and flag them like in product_variant_inactive)
        # Then call super to try to unlink them but do it one by one
        # as most of the time dichotomy is super slow for this work

        # like in product_variant_inactive skip record flagged as deleted
        records = self.filtered(lambda s: not s.combination_deleted)

        if records:
            # then quickly get not deletable product
            not_deletable = records._filter_not_deletable()
            not_deletable.write({"combination_deleted": True, "active": False})
            deletable = records - not_deletable
            for record in deletable:
                super(ProductProduct, record)._unlink_or_archive(
                    check_access=check_access
                )
        return True


import datetime as dt
import pathlib
from typing import Generic, TypeVar

from pydantic import HttpUrl

from pydantic_xml import BaseXmlModel, element

AuthType = TypeVar('AuthType')

class SoapHeader(
    BaseXmlModel, Generic[AuthType],
    tag='Header',
    ns='soap',
):
    auth: AuthType

class SoapMethod(BaseXmlModel):
    pass

MethodType = TypeVar('MethodType', bound=SoapMethod)

class SoapBody(
    BaseXmlModel, Generic[MethodType],
    tag='Body',
    ns='soap',
):
    call: MethodType

HeaderType = TypeVar('HeaderType', bound=SoapHeader)
BodyType = TypeVar('BodyType', bound=SoapBody)

class SoapEnvelope(
    BaseXmlModel,
    Generic[HeaderType, BodyType],
    tag='Envelope',
    ns='soap',
    nsmap={
        'soap': 'http://www.w3.org/2003/05/soap-envelope/',
    },
):
    header: HeaderType
    body: BodyType

class BasicAuth(
    BaseXmlModel,
    tag='BasicAuth',
    ns='auth',
    nsmap={
        'auth': 'http://www.company.com/auth',
    },
):
    user: str = element(tag='Username')
    password: str = element(tag='Password')

class CreateCompanyMethod(
    SoapMethod,
    tag='CreateCompany',
    ns='co',
    nsmap={
        'co': 'https://www.company.com/co',
    },
):
    trade_name: str = element(tag='TradeName')
    founded: dt.date = element(tag='Founded')
    website: HttpUrl = element(tag='WebSite')

CreateCompanyRequest = SoapEnvelope[
    SoapHeader[
        BasicAuth
    ],
    SoapBody[
        CreateCompanyMethod
    ],
]

xml_doc = pathlib.Path('./doc.xml').read_text()

request = CreateCompanyRequest.from_xml(xml_doc)

assert request == CreateCompanyRequest.parse_file('./doc.json')


class Solution:
    def numTeams(self, rating: List[int]) -> int:
        # result number of teams
        res = 0

        # iterate from 1 to length - 1 (middle soldier)
        for i in range(1, len(rating) - 1):
            # less and greater arrays
            less, greater = [0] * 2, [0] * 2
            # iterate thru ratings (for left and right soldiers)
            for j in range(len(rating)):

                if rating[i] < rating[j]:
                    # increment less[0] if i < j
                    less[0 if i < j else 1] += 1

                if rating[j] < rating[i]:
                    # increment greater[0] if i < j
                    greater[0 if i < j else 1] += 1

            # add teams to res
            res += less[0] * greater[1] + less[1] * greater[0]

        return res


import pandas as pd
import numpy as np

time_list = pd.date_range(start="2020/1/1", end="2021/12/12").to_list()
user = ["pony", "mark", "john", "sina", "mary"]
user_list = np.random.choice(user, size=len(time_list), replace=True)

df = pd.DataFrame(data={"user": user_list, "login_date": time_list})
print(df)

df_count = df.groupby('user', as_index=False).login_date.count()
df_count.rename(columns={"login_date": "login_count"}, inplace=True)
df_count.sort_values("login_count", inplace=True)
df_count = df_count.reset_index(drop=True)
print(df_count)


import sys

# print( 'Argument List:', sys.argv)

infile = open(sys.argv[1], "r")
outfile = open(sys.argv[2], "w")

stat_list = [
    "Stall:",
    "gpu_sim_cycle",
    "gpgpu_n_stall_shd_mem"
]

# keep_list = []

for line in infile:
    for stat in stat_list:
        if stat in line:
            # keep_list.append(line)
            outfile.write(line)

# print("keep_list: ", keep_list)

infile.close()
outfile.close()


# -*- coding: utf-8 -*-
"""
Created on Fri May  6 18:35:33 2022

@author: N
"""
import heapq

list1 = [4,1,3,2]

heapq.heapify(list1)

print(list1)

#新增 add heapq.heappush(存的list,value)
heapq.heappush(list1,5)
print(list1)

#取出 delete heapq.heappop(list)
heapq.heappop(list1)
print(list1)


from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import pandas as pd
import requests

# import player names from csv data and save to a list for dynamic url querying
player_names = {}
#lookup table cooresponding abbreviations to team names
nhl_teams = {
  "ANA" : 'anaheim-ducks',
  "ARI" : 'arizona-coyotes',
  "BOS" : 'boston-bruins',
  "BUF" : 'buffalo-sabres',
  "CGY" : 'calgary-flames',
  "CAR" : 'carolina-hurricanes',
  "CHI" : 'chicago-blackhawks',
  "COL" : 'colorado-avalanche',
  "CBJ" : 'columbus-blue-jackets',
  "DAL" : 'dallas-stars',
  "DET" : 'detroit-red-wings',
  "EDM" : 'edmonton-oilers',
  "FLA" : 'florida-panthers',
  "LAK" : 'los-angeles-kings',
  "MIN" : 'minnesota-wild',
  "MTL" : 'montreal-canadians',
  "NSH" : 'nashville-predators',
  "NJD" : 'new-jersey-devils',
  "NYI" : 'new-york-islanders',
  "NYR" : 'new-york-rangers',
  "OTT" : 'ottawa-senators',
  "PHI" : 'philadelphia-flyers',
  "PIT" : 'pittsburgh-penguins',
  "SJS" : 'san-jose-sharks',
  "STL" : 'st-louis-blues',
  "TBL" : 'tampa-bay-lightning',
  "TOR" : 'toronto-maple-leafs',
  "VAN" : 'vancouver-canucks',
  "VEG" : 'vegas-golden-knights',
  "WSH" : 'washington-capitals',
  "WPG" : 'winnipeg-jets'
}

#read in csv with pandas
data = pd.read_csv("nhl_statistics.csv")

# looping through the csv to save the player name and team name to a dict for later reference
for index, row in data.iterrows():
    player_name = row['Player'].lower().replace(" ", "-").strip()
    team = nhl_teams[row['Tm']]
    player_names[player_name] = team

# use player names and BS to scrape player images
for name, team in player_names.items():
  try:
    req = Request(f"https://frozenpool.dobbersports.com/players/{name}", headers={'User-Agent': 'Mozilla/5.0'})
    webpage = urlopen(req, timeout=10).read()
    soup = BeautifulSoup(webpage, 'html.parser')
    # scrape all images tags in the webpage
    images = soup.find_all('img')

    #for each image url scraped from frozen tools, request and save the player image
    for item in images:
      #upload files was a key in determining which urls were the player images.
      if "uploadfiles" in item['src']:

        #using the requests library, save the images locally
        url = item['src']
        r=requests.get(url)
        with open(f'./images/{team}/{name}.jpg', 'wb') as f:
          f.write(r.content)
  #pass all errors, some players do not play anymore, retired etc.
  except:
    print("error")
    pass


from datetime import datetime
import pyotp
import base64
import random
import string
import math
from authenticate.models import User
from django.shortcuts import render
from .models import PhoneModel,OtpModel
from .serializer import MobileSerializer,OtpSerializer
from rest_framework.response import Response
from rest_framework.views import APIView
from django.core.exceptions import ObjectDoesNotExist
from .serializer import OtpSerializer
from rest_framework import  generics
from rest_framework.permissions import IsAuthenticated,IsAdminUser
from utils.permissions import IsOwnerOrReadOnly,IsSuper
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

class generateKey:

    @staticmethod
    def returnValue(phone):
        digits = string.digits
        length = 12
        return str(phone) + str(datetime.date(datetime.now())) + str(''.join((random.choice(digits) for i in range(length))))

class getPhoneNumberRegistered(APIView):

    authentication_classes      =   []
    permission_classes          =   []
    serializer_class            =   MobileSerializer

    def post(self,request,*args,**kwargs):
        print('tst')
        print(request.data.get('mobile'))
        phone = request.data['mobile']

        try:
            user = User.objects.get(contact=phone)
            print(user)
        except ObjectDoesNotExist:
            return Response({"sorry":"phone number not registered"},status=404)

        if PhoneModel.objects.filter(mobile=phone).exists():
             Mobile = PhoneModel.objects.get(mobile=phone)
             print('exist already')
        else:
            PhoneModel.objects.create(mobile=phone)
            Mobile = PhoneModel.objects.get(mobile=phone)
            print('newly')

        Mobile.counter += 1 # Update Counter At every Call
        Mobile.save()
        keygen = generateKey()
        key = base64.b32encode(keygen.returnValue(phone).encode())
        OTP = pyotp.HOTP(key) # HOTP Model for OTP is created
        print(OTP.at(Mobile.counter))
        otp = OTP.at(Mobile.counter)
        PhoneModel.objects.filter(mobile=phone).update(otp=otp)

        # if OtpModel.objects.filter(pk=Mobile.pk).exists():
        #     OtpModel.objects.filter(pk=Mobile.pk).update(
        #                                             mobile=phone
        #                                             )
        # else:
        #     OtpModel.objects.create(pk=Mobile.pk,mobile=phone)

        # Using Multi-Threading send the OTP Using Messaging Services like Twilio or Fast2sms
        return Response({"OTP":OTP.at(Mobile.counter)},status=200) # Just for demonstration

class VerifyOtp(generics.CreateAPIView):
    queryset                =       OtpModel.objects.all()
    serializer_class        =       OtpSerializer
    permission_classes      =       [IsAuthenticated]
    authentication_classes  =       [JSONWebTokenAuthentication,SessionAuthentication]

    def post(self,request,*args,**kwargs):
        print('otp ')
        otp = request.data['otp']
        contact=request.user.contact
        try:
            Mobile = PhoneModel.objects.get(mobile=contact)
            eotp = Mobile.otp
            print(otp)
            print(eotp)

            if str(otp) == str(eotp):
                if OtpModel.objects.filter(user=request.user).exists():
                    OtpModel.objects.filter(user=request.user).update(otp=otp)
                    response  =   {"message":"authorized","otp":otp,"status":201}
                    return Response(response,status=201)
                else:
                    self.create(request,*args,**kwargs)
                    response  =   {"message":"authorized","otp":otp,"status":201}
                    return Response(response,status=201)
            else:
                return Response({"message":"invalid OTP"})
        except:
            return Response({"message":"something wrong"})

    def perform_create(self,serializer):
        serializer.save(user=self.request.user)

    # @staticmethod
    # def post(request,phone):
    #     try:
    #         Mobile = PhoneModel.objects.get(mobile=phone)

    #     except ObjectDoesNotExist:
    #         return Response("user doesn't exist",status=404)

    #     keygen = generateKey()
    #     key = base64.b32encode(keygen.returnValue(phone).encode()) # Generating Key
    #     OTP = pyotp.HOTP(key) # HOTP Model
    #     instance = OtpModel.objects.get(pk=Mobile.pk)
    #     print(instance)
    #     if (OTP.verify(instance.otp,Mobile.counter)): # Verifying the OTP
    #         Mobile.isVerified = True
    #         Mobile.save()
    #         return Response('you are authorized',status=200)
    #     return Response('OTP is Wrong',status=404)

#EXAMPLE

# import random
# import string

# # get random string password with letters, digits, and symbols
# def get_random_password_string(length):
#     password_characters = string.ascii_letters + string.digits + string.punctuation
#     password = ''.join(random.choice(password_characters) for i in range(length))
#     print("Random string password is:", password)

# get_random_password_string(10)
# get_random_password_string(10)

#OUTPUT
# Random string password is: "C:!|]@|sh
# Random string password is: 'Q^s2q!t-N


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 17 12:46:25 2021

@author: ron
"""
from .base import AbstractBroker
from ..event.event import Direction
from ..ibtws.orders import Orders
from ..ibtws.contracts import create_contract
import queue
import time

class IBBroker(AbstractBroker):

    def __init__(self, twsclient, event_queue, ticker_list, db_client=None):
        self.db_client = db_client
        self.event_queue = event_queue
        self.twsclient = twsclient
        self.contracts_list = {}
        for ticker in ticker_list:
            self.contracts_list[ticker] = create_contract(ticker)

    def execute_order(self, order_event):
        if time.time() - order_event.timestamp >= 300:
            print("Order rejected as the signal generated is at least 5 mins before")

        else:
            self.twsclient.reqIds()
            if order_event.direction == Direction.LONG:
                order = Orders.MarketOrder("BUY", order_event.quantity)

            #order_event.direction == Direction.SHORT
            else:
                order = Orders.MarketOrder("SELL", order_event.quantity)

            self.twsclient.placeOrder(self.twsclient.nextValidOrderId, self.contracts_list[order_event.ticker], order)

    def get_fill_event(self):
        try:
            fill_event = self.twsclient.execution_detail.get(False)
        except queue.Empty:
            pass
        else:
            print(fill_event)
            self.event_queue.put(fill_event)
            if self.db_client is not None:
                self.save_to_db(fill_event)


from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from EmployeeApp.models import Departaments,Employees
from EmployeeApp.serializers import DepartamentSerializer, EmployeeSerializer
from django.core.files.storage import default_storage

# Create your views here.
@csrf_exempt
def departamentApi(request,id=0):
    if request.method=='GET':
        departaments = Departaments.objects.all()
        departaments_serializer = DepartamentSerializer(departaments, many=True)
        return JsonResponse(departaments_serializer.data, safe=False)
    elif request.method=='POST':
        departament_data=JSONParser().parse(request)
        departament_serializer = DepartamentSerializer(data=departament_data)
        if departament_serializer.is_valid():
            departament_serializer.save()
            return JsonResponse("Added Successfully", safe=False)
        return JsonResponse("Failed to Add", safe=False)
    elif request.method=='PUT':
        departament_data = JSONParser().parse(request)
        departament=Departaments.objects.get(DepartamentId=departament_data['DepartamentId'])
        departament_serializer=DepartamentSerializer(departament, data=departament_data)
        if departament_serializer.is_valid():
            departament_serializer.save()
            return JsonResponse("Update Successfuly", safe=False)
        return JsonResponse("Failed to Update", safe=False)

    elif request.method=='DELETE':
        departament=Departaments.objects.get(DepartamentId=id)
        departament.delete()
        return JsonResponse("Deleted Successfuly", safe=False)

@csrf_exempt
def employeeApi(request,id=0):
    if request.method=='GET':
        employees = Employees.objects.all()
        employees_serializer = EmployeeSerializer(employees, many=True)
        return JsonResponse(employees_serializer.data, safe=False)
    elif request.method=='POST':
        employee_data=JSONParser().parse(request)
        employee_serializer = EmployeeSerializer(data=employee_data)
        if employee_serializer.is_valid():
            employee_serializer.save()
            return JsonResponse("Added Successfully", safe=False)
        return JsonResponse("Failed to Add", safe=False)
    elif request.method=='PUT':
        employee_data = JSONParser().parse(request)
        employee= Employees.objects.get(EmployeeId = employee_data['EmployeeId'])
        employee_serializer=EmployeeSerializer(employee, data = employee_data)
        if employee_serializer.is_valid():
            employee_serializer.save()
            return JsonResponse("Update Successfuly", safe=False)
        return JsonResponse("Failed to Update", safe=False)

    elif request.method=='DELETE':
        employee=Employees.objects.get(EmployeeId=id)
        employee.delete()
        return JsonResponse("Deleted Successfuly", safe=False)

@csrf_exempt
def SaveFile(request):
    file=request.FILES['uploadedFile']
    file_name = default_storage.save(file.name, file)

    return JsonResponse(file_name, safe=False)


import cv2
import numpy as np
import math
from enum import Enum

class CalibrationStep(Enum):
	ASKING_FOR_POINTS = 1
	DONE = 2

corners = []
img = None
gray = None
obj_points = np.matrix([[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 2.0, 0.0], [2.0, 2.0, 0.0], [1.0, 1.0, 0.0]], np.float32) # list of points in real coords
img_points = [] # list of points in image coords

point_idx_ask = 0 # o indice do ponto que se está a pedir
calibration_step = CalibrationStep.ASKING_FOR_POINTS

def ask_for_point():
	print("Select point " + str(point_idx_ask))
	print(obj_points[point_idx_ask])

def point_selected(point):
	global point_idx_ask, calibration_step, img_points

	img_points.append(point)
	point_idx_ask += 1

	if point_idx_ask == len(obj_points):
		calibrate_camera()
		calibration_step = CalibrationStep.DONE
		print("DONE!")
	else:
		ask_for_point()

def find_closest_corner(x, y):
	closestIndex = -1
	closestDist = -1
	for i, corner in enumerate(corners):
		dist = math.sqrt((corner[0]-x)**2 + (corner[1]-y)**2)
		if closestIndex == -1 or closestDist > dist:
			closestIndex = i
			closestDist = dist
	return closestIndex

def img_window_click(event, x, y, flags, param):
	if event == cv2.EVENT_LBUTTONUP:
		print(calibration_step)
		if calibration_step == CalibrationStep.ASKING_FOR_POINTS:

			clickedCornerIdx = find_closest_corner(x, y)
			print(corners[clickedCornerIdx])

			cv2.circle(img, (corners[clickedCornerIdx][0], corners[clickedCornerIdx][1]), 3, (0,0,255), -1)
			cv2.imshow('image',img)

			point_selected(corners[clickedCornerIdx])

def find_corners():
	global gray
	gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

	#find Harris corners
	gray = np.float32(gray)

	dst = cv2.cornerHarris(gray,2,3,0.04)
	dst = cv2.dilate(dst,None)
	ret, dst = cv2.threshold(dst,0.01*dst.max(),255,0)
	dst = np.uint8(dst)

	#find centroids
	ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)

	#define the criteria to stop and refine the corners
	criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001)
	return cv2.cornerSubPix(gray,np.float32(centroids),(7,7),(-1,-1),criteria)

def calibrate_camera():
	#print(np.array([np.array(obj_points, np.float32)]).asmatrix())
	img_points_np = np.matrix(img_points, np.float32)
	print(img_points_np)

	ret, cameraMatrix, distCoeffs, rvec, tvec = cv2.calibrateCamera([obj_points], [img_points_np], gray.shape[::-1],None,None)
	print(ret)
	print(cameraMatrix)
	print(rvec)
	print(tvec)

	print("\n\n")
	rotMatrix, jacobian = cv2.Rodrigues(rvec[0])

	rtMatrix = np.concatenate((rotMatrix, tvec[0]), axis=1)

	print("Camera matrix:")
	print(cameraMatrix.tolist())
	print("R|t matrix:")
	print(rtMatrix.tolist())

filename = 'a.png'
img = cv2.imread(filename)

corners = find_corners()
print(obj_points)
#here u can get corners
print (corners[0])
print (len(corners))

#Now draw them
#res = np.hstack((centroids,corners))
#res = np.int0(res)
#img[res[:,1],res[:,0]]=[0,0,255]
#img[res[:,3],res[:,2]] = [0,255,0]
cv2.imshow('image',img)
cv2.setMouseCallback("image", img_window_click)
ask_for_point()

cv2.waitKey(0)
cv2.destroyAllWindows()


import netaddr
from rally.common import logging
from rally_ovs.plugins.ovs.scenarios import ovn
from rally_ovs.plugins.ovs.scenarios import ovn_network
from rally.task import scenario
from rally.task import validation
from rally.task import atomic

import time

LOG = logging.getLogger(__name__)

class OvnIGMP(ovn_network.OvnNetwork):
    """scenarios for OVN IGMP"""

    def __init__(self, context=None):
        super(OvnIGMP, self).__init__(context)

    def _lport_idx_inc(self, idx, max, inc=1):
        idx += inc
        return idx % max

    @atomic.action_timer("ovn_igmp.run_mcast")
    def _run_mcast(self, expected_count, lswitches, error=10):

        for iteration in range(0, 60):
            LOG.info('Iteration {}'.format(iteration))
            ovn_sbctl = self.controller_client("ovn-sbctl")
            ovn_sbctl.set_log_cmd(self.context.get("log_cmd", False))
            igmp_flow_count = 0
            for lswitch in lswitches:
                igmp_flow_count += ovn_sbctl.count_igmp_flows(lswitch['name'])

            LOG.info('IGMP flows: {} Expected {}'.format(
                igmp_flow_count, expected_count))

            if igmp_flow_count >= expected_count - error:
                break;

            time.sleep(0.5)

    def _install_mcast_tester(self, sandboxes, path):
        for sandbox in sandboxes:
            ovs_ssh = self._get_conn(sandbox["name"])
            ovs_ssh.ssh.put_file(path, '/tmp/test.c')

        self._flush_conns(cmds=[
            'gcc -lpthread -o /tmp/test /tmp/test.c'
        ])

    def _build_config_testers(self, lswitches, ports, lports_per_lswitch,
                              mc_groups_per_network,
                              test_dest_count,
                              test_mcast_batch):
        def _init_iteration():
            return {
                lport['name']: {'n_groups': 0, 'groups': []}
                for lport in ports
            }

        iterations = []
        current_iteration = _init_iteration()
        current_total = 0

        for lswitch in lswitches:
            lports = lports_per_lswitch[lswitch["name"]]
            if len(lports) == 0:
                continue

            lport_idx = 0
            max_idx = len(lports)

            mc_groups = [netaddr.IPAddress('239.0.0.1') + gid
                            for gid in range(0, mc_groups_per_network)]

            for mc_group in mc_groups:
                for i in range(0, test_dest_count):
                    lport = lports[lport_idx]
                    lport_idx = self._lport_idx_inc(lport_idx, max_idx)

                    current_iteration[lport['name']]['n_groups'] += 1
                    current_iteration[lport['name']]['groups'].append(mc_group)
                    current_total += 1

                    if current_total == test_mcast_batch:
                        iterations.append((current_total, current_iteration))
                        current_iteration = _init_iteration()
                        current_total = 0

        if current_total != 0:
            iterations.append((current_total, current_iteration))
        return iterations

    def _config_mcast_testers(self, ports, iterations):
        for lport in ports:
            port_name = lport["name"]
            _, sandbox = self.context["ovs-internal-ports"][port_name]
            ovs_ssh = self._get_conn(sandbox["name"])
            ovs_ssh.run(
                'echo {n} > /tmp/test-{p}-input'.format(
                    n=len(iterations), p=port_name))

        for expected_count, lport_map in iterations:
            for port_name, port_groups in lport_map.items():
                _, sandbox = self.context["ovs-internal-ports"][port_name]
                ovs_ssh = self._get_conn(sandbox["name"])
                ovs_ssh.run(
                    'echo {n} >> /tmp/test-{p}-input'.format(
                        n=port_groups['n_groups'], p=port_name))
                for mc_group in port_groups['groups']:
                    ovs_ssh.run(
                        'echo {g} >> /tmp/test-{p}-input'.format(
                            g=mc_group, p=port_name))
            self._flush_conns()

    def _start_mcast_tester(self, port_name):
        _, sandbox = self.context["ovs-internal-ports"][port_name]
        ovs_ssh = self._get_conn(sandbox["name"])
        input_file = '/tmp/test-{p}-input'.format(p=port_name)
        ovs_ssh.run(
            'ip netns exec {p} /tmp/test {ifile}'.format(
                p=port_name, ifile=input_file))

    def _trigger_mcast_tester(self, port_name):
        _, sandbox = self.context["ovs-internal-ports"][port_name]
        ovs_ssh = self._get_conn(sandbox["name"])
        ovs_ssh.run(
            "kill -s SIGUSR1 `ps aux | grep {p} | grep -v grep | "
            "awk '{{print $2}}'` &> /dev/null || /bin/true".format(
        p=port_name))

    def _start_mcast(self, lswitches, all_lports, lports_per_lswitch,
                     mc_groups_per_network, test_dest_count, test_mcast_batch):

        # Avoid lazy connection creation:
        ovn_sbctl = self.controller_client("ovn-sbctl")
        ovn_sbctl.set_log_cmd(self.context.get("log_cmd", False))

        # Build configuration for each port for each iteration
        iterations = self._build_config_testers(lswitches, all_lports,
                                                lports_per_lswitch,
                                                mc_groups_per_network,
                                                test_dest_count,
                                                test_mcast_batch)

        # Write the config on the DUTs (for each port).
        self._config_mcast_testers(all_lports, iterations)

        # Start the tester apps (one for each port).
        for lport in all_lports:
            port_name = lport["name"]
            self._start_mcast_tester(port_name)
        self._flush_conns()

        LOG.info('Finished configuring multicast receivers')

        time.sleep(10)

        # Run the test iterations. Every iteration is triggered by sending
        # SIGUSR1 to the test apps.
        total_expected = 0
        for iteration, (expected_count, port_map) in enumerate(iterations):
            for port_name in port_map.iterkeys():
                self._trigger_mcast_tester(port_name)

            self._flush_conns()
            total_expected += expected_count

            LOG.info(
                'Started {} multicast receivers. Total until now: {}'.format(
            expected_count, total_expected))
            self._run_mcast(total_expected, lswitches)

    def _cleanup_mcast_tests(self):
        self._flush_conns(cmds=[
            'killall -s KILL test &> /dev/null || /bin/true',
            'rm -rf /tmp/test*input'
        ])

    def _cleanup_mcast(self, lswitches, sandboxes):
        LOG.info('Cleaning up setup...')

        self._delete_lswitch(lswitches)
        self._cleanup_ovs_internal_ports(sandboxes)

    @validation.number("ports_per_network", minval=4, integer_only=True)
    @scenario.configure(context={})
    def igmp_scale(self, network_create_args=None,
                   port_create_args=None,
                   ports_per_network=None,
                   port_bind_args=None,
                   cleanup=True,
                   igmp_args=None):
        sandboxes = self.context["sandboxes"]
        if not sandboxes:
            # when there is no sandbox specified, bind on all sandboxes.
            sandboxes = utils.get_sandboxes(self.task["deployment_uuid"])

        lswitches = self._create_networks(network_create_args)

        lports = []
        lports_per_lswitch = {}

        mc_groups_per_network = igmp_args.get("group_count", 1)
        test_dest_count = igmp_args.get("receivers", 2)
        test_pkt_size = igmp_args.get("pkt_size", 64)
        test_bw = igmp_args.get("bw", "1K")
        test_mcast_batch = igmp_args.get("mcast_batch", 200)
        test_mcast_rcv_path = igmp_args.get("mcast_recv_path");

        if cleanup:
            self._cleanup_mcast_tests()

        for lswitch in lswitches:
            switch_lports = self._create_switch_lports(lswitch,
                                                       port_create_args,
                                                       ports_per_network)
            lports_per_lswitch[lswitch["name"]] = switch_lports
            lports += switch_lports

        self._bind_ports_and_wait(lports, sandboxes, port_bind_args)

        LOG.info('Sleeping for a bit before starting multicast..')
        time.sleep(10)

        self._install_mcast_tester(sandboxes, test_mcast_rcv_path)

        self._start_mcast(lswitches, lports, lports_per_lswitch,
                          mc_groups_per_network, test_dest_count,
                          test_mcast_batch)

        if cleanup:
            LOG.info('Sleeping for a bit before cleaning up..')
            time.sleep(20)
            self._cleanup_mcast(lswitches, sandboxes)


import numpy as np
import time
import sys
import matplotlib.pyplot as plt
import pinocchio as pin
import meshcat

from pinocchio.visualize import MeshcatVisualizer

class RobotEnv:
    def __init__(self, pin_robot, end_effector_name):
        self.model = pin_robot.model
        self.data = pin_robot.data
        self.viz = pin.visualize.MeshcatVisualizer(pin_robot.model, pin_robot.collision_model, pin_robot.visual_model)
        self.end_effector_name = end_effector_name

        # Constants to make things easier
        self.num_joints = pin_robot.model.nq
        self.zeros_nx1 = np.zeros((pin_robot.model.nq, 1))
        print(self.num_joints)

    def start_visualizer(self):
        try:
            self.viz.initViewer(open=True)
        except ImportError as err:
            print(
                "Error while initializing the viewer. It seems you should install Python meshcat"
            )
            print(err)
            sys.exit(0)

        # Load the robot in the viewer.
        self.viz.loadViewerModel()

        # Display a robot configuration.
        q0 = pin.neutral(self.model)
        self.viz.display(q0)
        self.viz.displayCollisions(True)
        self.viz.displayVisuals(False)

        # Display target
        self.viz.viewer['ball'].set_object(meshcat.geometry.Sphere(0.01),
                              meshcat.geometry.MeshLambertMaterial(
                             color=0xff22dd,
                             reflectivity=0.8))

        self.viz.viewer['end_eff'].set_object(meshcat.geometry.Sphere(0.01),
                              meshcat.geometry.MeshLambertMaterial(
                             color=0x22ff44,
                             reflectivity=0.8))

    def show_target(self, pos):
        self.viz.viewer['ball'].set_transform(meshcat.transformations.translation_matrix(pos))

    def show_end_effector(self, end_eff_pos):
        self.viz.viewer['end_eff'].set_transform(meshcat.transformations.translation_matrix(end_eff_pos))

    def show_positions(self, q):
        self.viz.display(q)

    def show_neutral_positions(self):
        q0 = pin.neutral(self.model)
        print(q0)
        self.viz.display(q0)

    def show_random_positions(self):
        q = np.random.sample((self.num_joints))
        self.viz.display(q)

    def get_spatial_jacobian(self, q):
        '''J = [J-linear(3xnum_joint);
                J-angular(3xnum_joint)]'''
        J = pin.computeJointJacobians(self.model, self.data, q)
        temp = J[:3, :]
        J = np.delete(J, [0, 1, 2], axis=0)
        J = np.vstack((J, temp))

        return J

    def get_end_effector_jacobian(self, q):
        J = pin.computeFrameJacobian(self.model, self.data, q, self.model.getFrameId(self.end_effector_name))
        temp = J[:3, :]
        J = np.delete(J, [0, 1, 2], axis=0)
        J = np.vstack((J, temp))

        return J

    def get_forward_kinematics(self, q):
        pin.forwardKinematics(self.model, self.data, q)
        pin.updateFramePlacements(self.model, self.data)
        end_eff_id = self.model.getFrameId(self.end_effector_name)
        end_eff = self.data.oMf[end_eff_id]
        T = np.hstack((end_eff.rotation, end_eff.translation.reshape(-1, 1)))
        T = np.vstack((T, np.array([[0, 0, 0, 1]])))
        return T

    # Numeric values
    def rnea(self, q, dq, ddq):
        return pin.pinocchio_pywrap.rnea(self.model, self.data, q, dq, ddq).reshape(-1, 1)

    def get_gravity(self, q):
        g = self.rnea(q, self.zeros_nx1, self.zeros_nx1)
        return g.reshape(-1, 1)

    def get_coriolis(self, q, dq):
        C = self.rnea(q, dq, self.zeros_nx1) - self.get_gravity(q)
        return C

    def get_mass_matrix(self, q, dq):
        M = np.zeros((self.num_joints, self.num_joints))
        for i in range(self.num_joints):
            ddq = self.zeros_nx1
            ddq[i] = 1
            M[:, i] = pin.pinocchio_pywrap.rnea(self.model, self.data, q, self.zeros_nx1, ddq).reshape(-1) - self.get_gravity(q)
        return M

def simulate_robot(robot, planner, robot_controller, disturbance_all_joints=False, disturbance_end_effector=False):
    '''
    Simulates the robot with the given controller
    INPUT:  robot (Class RobotEnv) : Environment of the robot
            robot_controller       : Controller function (outputs torque)
    '''
    # Define constants
    t = 0.
    dt = 0.001
    q = np.zeros((robot.num_joints,1))
    dq = np.zeros((robot.num_joints,1))
    robot.show_positions(q)
    t_visual = 0
    dt_visual = 0.01
    disturbance_active = False
    disturbance_force = np.zeros((6, 1))

    # Initialize plot
    plot = LivePlot(x_label="Time(s)", y_label="Torques", title="Joint Torques over time", num_joints=robot.num_joints)

    while(t < 1.5):
        # Get end-effector (body jacobian) jacobian
        J_b = robot.get_end_effector_jacobian(q)

        # Retrieve torques
        tau = robot_controller(robot, planner, t, q.reshape((robot.num_joints, 1)), dq.reshape((robot.num_joints, 1)))

        # Activate disturbance at t seconds

        if t > 1.5 and t < 1.7 and not disturbance_active:
            if disturbance_all_joints:
                disturbance_force = np.random.normal(0, 0.5, (6, 1))            # Random values with mean 0 and std dev 0.5
            if disturbance_end_effector:
                disturbance_force = np.zeros((6, 1))
                disturbance_force[4, :] = -5                                  # Force in y-direction of the end-effector frame
            disturbance_active = True

        # Deactivate disturbance after t seconds
        if t >= 1.7 and disturbance_active:
            disturbance_active = False

        # Add disturbance
        disturbance_force_joint_space = J_b.T @ disturbance_force       # Converting that disturbance in joint space
        tau += disturbance_force_joint_space

        # Update visualizer
        ddq = pin.pinocchio_pywrap.aba(robot.model, robot.data, q, dq, tau)
        dq += dt * ddq.reshape((robot.num_joints, 1))
        q += dt*dq
        if t_visual == 10:
            robot.show_positions(q)
            plot.update_live_plot(t, tau)
            time.sleep(dt_visual)
            t_visual = 0
        t_visual += 1
        t += dt

def simulate_robot_real_time(robot, planner, robot_controller, MotorController, MotorIDs):
    t = 0.
    dt = 0.001
    q = np.zeros((robot.num_joints,1))
    dq = np.zeros((robot.num_joints,1))
    robot.show_positions(q)
    t_visual = 0
    dt_visual = 0.01

    for id in MotorIDs:
        MotorController.enable_torque(id)

    while(t <= 1):
        start_time = time.time()
        tau = robot_controller(robot, planner, t, q.reshape((-1,1)), dq.reshape((-1,1)))
        #print("Controller says:", tau)
        #print("---------------------")

        if t_visual == 10:
            robot.show_positions(q)
            time.sleep(dt_visual)
            for id, tu in zip(MotorIDs, tau):
                val = MotorController.convert_nm_to_motor_val(-tu.item(), MotorIDs[id])
                print(val)
                MotorController.set_torque(id, val)
            print("---------------")
            t_visual = 0
        t_visual += 1
        t += dt

    for id in MotorIDs:
        MotorController.disable_torque(id)

    MotorController.close_port()

def mimic_robot(robot, MotorController):
    t = 0.
    dt = 0.001
    q = np.zeros((robot.num_joints,1))
    robot.show_positions(q)
    MotorIDs = {1: 8.4, 2: 8.4, 3: 8.4}         # ID : Max torque at 12 V
    t_visual = 0
    dt_visual = 0.01

    for id in MotorIDs:
        MotorController.enable_torque(id)

    while(t <= 5):
        if t_visual == 10:
            for i, id in enumerate(MotorIDs):
                val = MotorController.read_pos(id)
                q[i] = val
                time.sleep(0.001)
            robot.show_positions(q*np.pi/180)
            time.sleep(dt_visual)
            t_visual = 0
        t_visual += 1
        t += dt

    for id in MotorIDs:
        MotorController.disable_torque(id)

    MotorController.close_port()

class LivePlot:
    def __init__(self, x_label, y_label, title, num_joints):
        plt.ion()
        self.fig, self.ax = plt.subplots()
        self.ax.set_xlabel(x_label)
        self.ax.set_ylabel(y_label)
        self.ax.set_title(title)
        self.lines = [self.ax.plot([], [], label=f'Joint {i+1}')[0] for i in range(num_joints)]
        self.ax.legend()
        time.sleep(2)  # Short pause to allow the plot to render

    def update_live_plot(self, t, tau):
        # Update live plot
        for i, line in enumerate(self.lines):
            line.set_xdata(np.append(line.get_xdata(), t))
            line.set_ydata(np.append(line.get_ydata(), tau[i, 0]))

        self.ax.relim()
        self.ax.autoscale_view()
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()


from django.contrib import admin
from django.urls import path
from PruebaVocacional import views as test
from django.conf import settings
from django.conf.urls.static import static
from chat import views as chat
from herramientas import views as herramientas
from cuentas import views as cuentas

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/<int:id_estudiante>', cuentas.home,name='home'),
    path('',cuentas.home_name,name='home_name'),
    path('test/<int:id_estudiante>',test.test, name='test'),
    path('chat/<int:id_estudiante>',chat.chat,name="chat"),
    path('metodos-estudio/<int:id_estudiante>', herramientas.metodos_estudio, name="metodos-estudio"),
    path('test/answers/<int:id_estudiante>',test.answers,name='answers'),
    path('test/result/<int:id_estudiante>',test.result,name="result"),
    path('horario/<int:id_estudiante>',herramientas.horario,name='horario'),
    path('horario/agregar/<int:id_estudiante>', herramientas.agregar_clase , name='agregar_clase' ),
    path('calcular-promedio/<int:id_estudiante>', herramientas.calcular_promedio, name="calcular-promedio"),
    path('registro/',cuentas.register, name='registro'),
    path('profile/<int:id_estudiante>',cuentas.profile,name='perfil'),
    path('chat/<int:id_estudiante>',chat.chat,name="chat"),
    path('metodos-estudio/<int:id_estudiante>', herramientas.metodos_estudio, name="metodos-estudio"),
    path('analisis/<int:id_estudiante>', test.data, name="analisis")
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import contextlib
import warnings
import pandas as pd
from covsirphy.util.config import config
from covsirphy.util.validator import Validator
from covsirphy.util.term import Term

class _LayerAdjuster(Term):
    """Class to adjust location layers of time-series data.

    Args:
        layers (list[str] or None): list of layers of geographic information or None (["ISO3", "Province", "City"])
        country (str or None): layer name of countries or None (countries are not included in the layers)
        date (str): column name of observation dates

    Raises:
        ValueError: @layers has duplicates

    Note:
        Country level data specified with @country will be stored with ISO3 codes.
    """
    # Internal term
    _ID = "Location_ID"

    def __init__(self, layers=None, country="ISO3", date="Date"):
        # Countries will be specified with ISO3 codes and this requires conversion
        self._country = None if country is None else str(country)
        # Layers of location information
        self._layers = Validator(layers or [self._country, self.PROVINCE, self.CITY], "layers").sequence()
        if len(set(self._layers)) != len(self._layers):
            raise ValueError(f"@layer has duplicates, {self._layers}")
        # Date column
        self._date = str(date)
        # Location data
        self._loc_df = pd.DataFrame(columns=[self._ID, *self._layers])
        # All available data
        self._rec_df = pd.DataFrame(columns=[self._ID, self._date])
        # Citations
        self._citation_dict = {}

    def all(self, variables=None):
        """Return all available data.

        Args:
            variables (list[str] or None): list of variables to collect or None (all available variables)

        Returns:
            pandas.DataFrame:
                Index
                    reset index
                Columns
                    - columns defined by covsirphy.LayerAdjuster(layers)
                    - Date (pandas.Timestamp): observation dates
                    - columns defined by @variables
        """
        identifiers = [*self._layers, self._date]
        df = self._loc_df.merge(self._rec_df, how="right", on=self._ID).drop(self._ID, axis=1)
        df = df.sort_values(identifiers, ignore_index=True)
        df = df.loc[:, [*identifiers, *sorted(set(df.columns) - set(identifiers), key=df.columns.tolist().index)]]
        if variables is None:
            return df
        all_variables = df.columns.tolist()
        sel_variables = Validator(variables, "variables").sequence(candidates=set(all_variables) - set(identifiers))
        return df.loc[:, [*self._layers, self._date, *sel_variables]]

    def citations(self, variables=None):
        """
        Return citation list of the secondary data sources.

        Args:
            variables (list[str] or None): list of variables to collect or None (all available variables)

        Returns:
            list[str]: citation list
        """
        all_columns = [col for col in self._rec_df.columns if col not in (self._ID, self._date)]
        columns = Validator(variables, "variables").sequence(default=all_columns, candidates=all_columns)
        return Validator([v for k, v in self._citation_dict.items() if k in columns]).sequence(flatten=True, unique=True)

    def register(self, data, layers=None, date="Date", variables=None, citations=None, convert_iso3=True, **kwargs):
        """Register new data.

        Args:
            data (pandas.DataFrame): new data
                Index
                    reset index
                Columns
                    - columns defined by @data_layers
                    - columns defined by @date
                    - columns defined by @variables
            layers (list[str] or None): layers of the data or None (as the same _LayerAdjuster(layer))
            date (str): column name of observation dates of the data
            variables (list[str] or None): list of variables to add or None (all available columns)
            citations (list[str] or str or None): citations of the dataset or None (["my own dataset"])
            convert_iso3 (bool): whether convert country names to ISO3 codes or not
            **kwargs: keyword arguments of pandas.to_datetime() including "dayfirst (bool): whether date format is DD/MM or not"

        Raises:
            ValueError: @data_layers has duplicates

        Returns:
            covsirphy.LayerAdjuster: self
        """
        data_layers = Validator(layers, "layers").sequence(default=self._layers)
        if len(set(data_layers)) != len(data_layers):
            raise ValueError(f"@layer has duplicates, {data_layers}")
        df = Validator(data, "data").dataframe(columns=[*data_layers, date, *(variables or [])])
        # Convert date type
        df.rename(columns={date: self._date}, inplace=True)
        df[self._date] = pd.to_datetime(df[self._date], **kwargs).dt.round("D")
        with contextlib.suppress(TypeError):
            df[self.DATE] = df[self.DATE].dt.tz_convert(None)
        # Convert country names to ISO3 codes
        if convert_iso3 and self._country is not None and self._country in df:
            warnings.filterwarnings("ignore", category=DeprecationWarning)
            df.loc[:, self._country] = self._to_iso3(df[self._country])
        # Prepare necessary layers and fill in None with "NA"
        if data_layers is not None and data_layers != self._layers:
            df = self._prepare_layers(df, data_layers=data_layers)
        df[self._layers] = df[self._layers].astype("string").fillna(self.NA)
        # Locations
        loc_df = df.loc[:, self._layers]
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=FutureWarning)
            # From Python 3.11: `warnings.catch_warnings(action="ignore", category=FutureWarning):`
            loc_df = pd.concat([self._loc_df, loc_df], axis=0, ignore_index=True)
        loc_df.drop_duplicates(subset=self._layers, keep="first", ignore_index=True, inplace=True)
        loc_df.loc[loc_df[self._ID].isna(), self._ID] = f"id{len(loc_df)}-" + \
            loc_df[loc_df[self._ID].isna()].index.astype("str")
        self._loc_df = loc_df.reset_index()[[self._ID, *self._layers]]
        # Records
        df = df.merge(self._loc_df, how="left", on=self._layers).drop(self._layers, axis=1)
        if variables is not None:
            columns = [self._ID, self._date, *Validator(variables, "variables").sequence()]
            df = df.loc[:, columns]
        rec_df = self._rec_df.reindex(columns=list(set(self._rec_df.columns) | set(df.columns)))
        rec_df = rec_df.set_index([self._ID, self._date]).combine_first(df.set_index([self._ID, self._date]))
        self._rec_df = rec_df.reset_index()
        # Citations
        new_citations = Validator(
            [citations] if isinstance(citations, str) else (citations or ["my own dataset"]), "citations").sequence()
        citation_dict = {col: self._citation_dict.get(col, []) + new_citations for col in variables or df.columns}
        self._citation_dict.update(citation_dict)
        return self

    def _prepare_layers(self, data, data_layers):
        """Prepare necessary layers, adding NAs and renaming layers.

        Args:
            data (pandas.DataFrame): local dataset
                Index
                    reset index
                Columns
                    - columns defined by @data_layers
                    - the other columns
            data_layers (list[str]): layers of the data

        Returns:
            pandas.DataFrame:
                Index
                    reset index
                Columns
                    - columns defined by LayerAdjuster(layers)
                    - the other columns
        """
        df = data.copy()
        expected, actual = self._align_layers(data_layers)
        # Adjust layer names and records
        for (layer, data_layer) in zip(expected, actual):
            if data_layer is None:
                df.loc[:, layer] = self.NA
                config.info(f"\t[INFO] New layer '{layer}' was added to the data with NAs.")
            elif layer is None:
                if data_layer == actual[-1]:
                    df.loc[df[data_layer] != self.NA, self._layers] = self.NA
                    config.info(f"\t[INFO] Records which has actual values at '{data_layer}' layer were disabled.")
                df = df.drop(data_layer, axis=1)
                config.info(f"\t[INFO] '{data_layer}' layer was removed.")
            elif layer != data_layer:
                df.rename(columns={data_layer: layer}, inplace=True)
                config.info(f"\t[INFO] '{data_layer}' layer was renamed to {layer}.")
        return df.reset_index(drop=True)

    def _align_layers(self, data_layers):
        """Perform sequence alignment of the layers of new data with the layers defined by LayerAdjuster(layers).

        Args:
            data_layers (list[str]): layers of the data

        Returns:
            tuple(list[str], list[str]): list of aligned layers, that of defined and that of new data

        Note:
            Example of sequence alignment: [A, B, C], [A, C] -> [A, B, C], [A, None, C]
        """
        expected, actual = [], []
        for layer in self._layers:
            current = [data_layer for data_layer in data_layers if data_layer not in actual]
            if layer in current:
                new = current[:current.index(layer) + 1]
                expected.extend([None for _ in range(len(new) - 1)] + [layer])
                actual.extend(new)
            else:
                expected.append(layer)
                actual.append(None)
        not_included = [data_layer for data_layer in data_layers if data_layer not in actual]
        expected += [None for _ in range(len(not_included))]
        actual += not_included
        for (i, (e, a)) in enumerate(zip(expected[:], actual[:]), start=1):
            if i == len(expected):
                break
            if e is not None and expected[i] is None and a is None and actual[i] is not None:
                expected[i - 1:i + 1] = [e]
                actual[i - 1:i + 1] = [actual[i]]
        return expected, actual


from dependencies.dependency import getSecurityManager
from dependencies.dependency import aq_inner
from lims import logger
from lims.interfaces import IRoutineAnalysis
from lims.subscribers import doActionFor
from lims.subscribers import skip
from lims.utils import changeWorkflowState
from dependencies.dependency import DateTime
from dependencies.dependency import REFERENCE_CATALOG
from dependencies.dependency import ObjectInitializedEvent
from dependencies.dependency import getToolByName
from dependencies.dependency import WorkflowException
from dependencies import transaction
from dependencies.dependency import event
from dependencies.dependency import alsoProvides

def ObjectInitializedEventHandler(instance, event):

    # This handler fires for DuplicateAnalysis because
    # DuplicateAnalysis also provides IAnalysis.
    # DuplicateAnalysis doesn't have analysis_workflow.
    if instance.portal_type == "DuplicateAnalysis":
        return

    if instance.portal_type == 'Analysis':
        alsoProvides(instance, IRoutineAnalysis)

    workflow = getToolByName(instance, 'portal_workflow')

    ar = instance.aq_parent
    ar_state = workflow.getInfoFor(ar, 'review_state')
    ar_ws_state = workflow.getInfoFor(ar, 'worksheetanalysis_review_state')

    # Set the state of the analysis depending on the state of the AR.
    if ar_state in ('sample_registered',
                    'to_be_sampled',
                    'sampled',
                    'to_be_preserved',
                    'sample_due',
                    'sample_received'):
        changeWorkflowState(instance, "bika_analysis_workflow", ar_state)
    elif ar_state in ('to_be_verified'):
        # Apply to AR only; we don't want this transition to cascade.
        if 'workflow_skiplist' not in ar.REQUEST:
            ar.REQUEST['workflow_skiplist'] = []
        ar.REQUEST['workflow_skiplist'].append("retract all analyses")
        workflow.doActionFor(ar, 'retract')
        ar.REQUEST['workflow_skiplist'].remove("retract all analyses")

    if ar_ws_state == 'assigned':
        workflow.doActionFor(ar, 'unassign')
        skip(ar, 'unassign', unskip=True)

    instance.updateDueDate()

    return

def ObjectRemovedEventHandler(instance, event):

    # This handler fires for DuplicateAnalysis because
    # DuplicateAnalysis also provides IAnalysis.
    # DuplicateAnalysis doesn't have analysis_workflow.
    if instance.portal_type == "DuplicateAnalysis":
        return

    # May need to promote the AR's review_state
    #  if all other analyses are at a higher state than this one was.
    workflow = getToolByName(instance, 'portal_workflow')
    ar = instance.aq_parent
    can_submit = True
    can_attach = True
    can_verify = True
    can_publish = True

    # We add this manually here, because during admin/ZMI removal,
    # it may possibly not be added by the workflow code.
    if not 'workflow_skiplist' in instance.REQUEST:
        instance.REQUEST['workflow_skiplist'] = []

    for a in ar.getAnalyses():
        a_state = a.review_state
        if a_state in \
           ('to_be_sampled', 'to_be_preserved',
            'sample_due', 'sample_received',):
            can_submit = False
        if a_state in \
           ('to_be_sampled', 'to_be_preserved',
            'sample_due', 'sample_received', 'attachment_due',):
            can_attach = False
        if a_state in \
           ('to_be_sampled', 'to_be_preserved',
            'sample_due', 'sample_received',
            'attachment_due', 'to_be_verified',):
            can_verify = False
        if a_state in \
           ('to_be_sampled', 'to_be_preserved',
            'sample_due', 'sample_received',
            'attachment_due', 'to_be_verified', 'verified',):
            can_publish = False

    # Note: AR adds itself to the skiplist so we have to take it off again
    #       to allow multiple promotions (maybe by more than one deleted instance).
    if can_submit and workflow.getInfoFor(ar, 'review_state') == 'sample_received':
        try:
            workflow.doActionFor(ar, 'submit')
        except WorkflowException:
            pass
        skip(ar, 'submit', unskip=True)
    if can_attach and workflow.getInfoFor(ar, 'review_state') == 'attachment_due':
        try:
            workflow.doActionFor(ar, 'attach')
        except WorkflowException:
            pass
        skip(ar, 'attach', unskip=True)
    if can_verify and workflow.getInfoFor(ar, 'review_state') == 'to_be_verified':
        instance.REQUEST["workflow_skiplist"].append('verify all analyses')
        try:
            workflow.doActionFor(ar, 'verify')
        except WorkflowException:
            pass
        skip(ar, 'verify', unskip=True)
    if can_publish and workflow.getInfoFor(ar, 'review_state') == 'verified':
        instance.REQUEST["workflow_skiplist"].append('publish all analyses')
        try:
            workflow.doActionFor(ar, 'publish')
        except WorkflowException:
            pass
        skip(ar, 'publish', unskip=True)

    ar_ws_state = workflow.getInfoFor(ar, 'worksheetanalysis_review_state')
    if ar_ws_state == 'unassigned':
        if not ar.getAnalyses(worksheetanalysis_review_state = 'unassigned'):
            if ar.getAnalyses(worksheetanalysis_review_state = 'assigned'):
                try:
                    workflow.doActionFor(ar, 'assign')
                except WorkflowException:
                    pass
                skip(ar, 'assign', unskip=True)

    return


import logging
import json

from flask import request, jsonify

from codeitsuisse import app

logger = logging.getLogger(__name__)

@app.route('/tickerStreamPart1', methods = ['POST'])
def ticker1():
    data = request.get_json()
    logging.info("data sent for evaluation {}".format(data))
    stream = data.get("stream")
    cumu_list = {}
    grouped_list = {}
    ret_list = []
    for data in stream:
        ticks = data.split(",")
        curr_time = ticks[0]
        if curr_time not in grouped_list:
            grouped_list[curr_time] = data[6:]
        else:
            grouped_list[curr_time] += f';{data[6:]}'
    grouped_list = sorted(grouped_list.items()
                          )  # A dict sorted by timestamp with ticks as values
    for i in grouped_list:
        ticks = i[1].split(";")
        ticks.sort(key = lambda x: x[0])  # sort ticker by alphabet
        ret = f'{i[0]},'
        for j in range(len(ticks)):
            tick = ticks[j]
            tick = tick.split(",")
            ticker = tick[0]
            quantity = int(tick[1])
            notion = round(float(tick[2]), 1)
            if ticker not in cumu_list:
                cumu_list[ticker] = [quantity, round(notion * quantity, 1)]
            else:
                cumu_list[ticker][0] += quantity
                cumu_list[ticker][1] += round(quantity * notion, 1)
            ret += f'{ticker},{cumu_list[ticker][0]},{round(cumu_list[ticker][1], 1)}'
            if j != len(ticks) - 1:
                ret += ","
        ret_list.append(f'{ret}')
    logging.info("My result :{}".format(ret_list))
    result = { "output": ret_list}
    return json.dumps(result)

@app.route('/tickerStreamPart2', methods = ['POST'])
def ticker2():
    data = request.get_json()
    logging.info("data sent for evaluation {}".format(data))
    stream = data.get("stream")
    quantity_block = data.get("quantityBlock")
    data = []
    for stuffs in stream:
        ticks = stuffs.split(",")
        data.append(ticks)
    data.sort(key = lambda x: x[0])
    pairs = []
    cumu_list = {}
    for ticks in data:
        time = ticks[0]
        ticker = ticks[1]
        quantity = int(ticks[2])
        notion = round(float(ticks[3]), 1)
        original_floor = 0
        if ticker not in cumu_list:
            cumu_list[ticker] = [time, quantity, notion * quantity]
        else:  # Adding true q and n before applying q_block
            original_floor = cumu_list[ticker][1] // quantity_block  # if q=11, b=5, then of=2
            cumu_list[ticker][1] += quantity
            cumu_list[ticker][2] += quantity * notion
        new_floor = cumu_list[ticker][1] // quantity_block  # if q=16, b=5, then of=3
        if (new_floor != original_floor):
            adj_quantity = cumu_list[ticker][
                               1] // quantity_block * quantity_block
            adj_notion = cumu_list[ticker][2] - (cumu_list[ticker][1] %
                                                 quantity_block * notion)
            # use new floor (q = 15)

            pairs.append([time, ticker, adj_quantity, round(adj_notion, 1)])
    ret_dict = {}
    for i in pairs:
        time = i[0]
        if i[0] not in ret_dict:
            ret_dict[time] = [[i[1], i[2], i[3]]]
        else:
            ret_dict[time].append([i[1], i[2], i[3]])
        ret_dict[time].sort(key = lambda x: x[0])
    ret_list = []
    for i in ret_dict.keys():
        ret_str = f'{i},'
        for j in range(len(ret_dict[i])):
            if j != len(ret_dict[i]) - 1:
                for k in ret_dict[i][j]:
                    ret_str += f'{k},'
            else:
                for k in range(len(ret_dict[i][j])):
                    if k != len(ret_dict[i][j]) - 1:
                        ret_str += f'{ret_dict[i][j][k]},'
                    else:
                        ret_str += f'{ret_dict[i][j][k]}'
        ret_list.append(ret_str)
    logging.info("My result :{}".format(ret_list))
    result = { "output": ret_list}
    return json.dumps(result)


from time import time
from pathlib import Path
import random, os, warnings
from collections import OrderedDict

import numpy as np

import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
import gensim

from .core import Transform

from tqdm import tqdm

class Word2Vec(Transform):
    """
    Transform for Word2Vec so we can train Word2Vec on our dataset and use it as a transform

    We do this using nltk and gensim.models.Word2Vec

    Parameters
    ----------
    text_dir: String
        Directory of the text files we want to do this on
    dim: Integer
        Dimensionality of the Word2Vec embeddings
    workers: Integer
        Number of workers to use to train the Word2Vec
    """
    def __init__(self, text_dir, dim = 128, workers = 10):
        self.text_dir = text_dir
        self.dim = dim
        self.workers = workers

    def train(self):
        # Start training the Word2Vec
        # First create a list of files
        self.file_list = [s for s in list(Path(self.text_dir).rglob("*.txt"))]

        # Now read and tokenize
        print('Loading texts')
        self.sentences = ' '.join([Path(fn).read_text() for fn in tqdm(self.file_list)])
        print('Tokenising texts')
        self.sentences = [word_tokenize(sent.lower()) for sent in tqdm(sent_tokenize(self.sentences))] # Lower case everything

        # I've commented this section out because we could usep pretrained stuff but they may not have the vocabulary we need
        #word2vec_sample = str(nltk.data.find('models/word2vec_sample/pruned.word2vec.txt'))
        #self.model = gensim.models.KeyedVectors.load_word2vec_format(word2vec_sample, binary=False)]

        # Need to set min_count = 1, so we can deal with words we onyl encounter once if we have to
        print('Training Word2Vec model')
        self.model = gensim.models.Word2Vec(self.sentences, size = self.dim, workers = self.workers, min_count = 1)
        print('Done')

    def __call__(self, x): # We expect the input to be a string of sentences
        # Don't need to split it into sentences then into words, tokenising every word is enough
        sentence = word_tokenize(x.lower())

        out = np.zeros((len(sentence), self.dim), dtype = np.float32)
        for i, w in enumerate(sentence):
            out[i] = self.model[w]
        return out

    def save(self, fn):
        self.model.save(fn)

    def load(self, fn):
        self.model = Word2Vec.load(fn)

    def __repr__(self):
        format_string = self.__class__.__name__ + '('
        format_string += 'text_dir={0}'.format(self.text_dir)
        format_string += 'dim={0}'.format(self.dim)
        format_string += 'workers={0}'.format(self.workers)
        format_string += ')'
        return format_string

class Char2Vec(Transform):
    """
    Simple transform to convert ASCII characters to integers or one hot

    Parameters
    ----------
    one_hot: Boolean
        Whether to output the data in one hot format
    """
    def __init__(self, one_hot = False):
        self.one_hot = one_hot

    def __call__(self, x):
        if self.one_hot:
            out = np.zeros((len(x), 256), dtype = np.long) # Fix dimensionality to 256 for 8bit ASCII
            for i, c in enumerate(x):
                out[i, ord(c)] = 1 # Convert to 1 hot
        else:
            out = np.zeros((len(x),), dtype = np.long)
            for i, c in enumerate(x):
                out[i] = ord(c)

        return out