from Rotor import Rotor
from Enigma import Enigma
from Plugboard import Plugboard

rotors = ["EKMFLGDQVZNTOWYHXUSPAIBRCJ", "AJDKSIRUXBLHWTMCQGZNPYFVOE", "BDFHJLCPRTXVZNYEIWGAKMUSQO",
          "ESOVPZJAYQUIRHXLNFTGKDCMWB", "VZBRGITYUPSDNHLXAWMJQOFECK"]

def string_to_dict(letters_dict):
    """
    create dictionary from string.
    :param letters_dict: string.
    :return: dictionary.
    """
    _dict = dict()

    for key, value in enumerate(letters_dict):
        _dict[key] = value

    return _dict

def letter_to_index(letter):
    """
    Translate index to char, where 0 equal A and 25 equal Z.
    :param letter: int
    :return: the char equivalent value.
    """
    if isinstance(letter, str) is not False:
        return ord(letter) - ord('A')

class Task5:
    # Declare all the object we need.
    group_offset = ''
    encrypted_massage_key = ''
    massage_key = ''
    only_message = ''
    plug_board = {'Z': 'U', 'H': 'L', 'C': 'Q', 'W': 'M', 'O': 'A', 'P': 'Y', 'E': 'B', 'T': 'R', 'D': 'N', 'V': 'I'}

    rotorA = None
    rotorB = None
    rotorC = None

    plugboard = Plugboard(plug_board)

    def __init__(self): pass

    def get_message(self, message=None):
        """
        Get message.
        :param message: string.
        :return: the message.
        """
        if message is None:
            message = raw_input("Enter massage: ")

        for letter in message:
            if letter.isalpha() is not True:
                message = message.replace(letter, "")
            elif letter.islower():
                message = message.replace(letter, letter.upper())
        return message

    def extract_data(self, message):
        """
        Isolate only the relevant parts from the message.
        :param message: string.
        :return: decrypt / encrypt message.
        """
        message = ''.join(message)

        self.group_offset = message[:3]
        self.encrypted_massage_key = message[3:6]
        self.only_message = message[11:]

    def get_massage_key(self):
        """
        Get the offset by decrypt the mesage.
        :return: decrypted offset.
        """
        self.rotorA = Rotor(string_to_dict(rotors[3]), 4, letter_to_index(self.group_offset[2]), letter_to_index('X'))
        self.rotorB = Rotor(string_to_dict(rotors[4]), 5, letter_to_index(self.group_offset[1]), letter_to_index('I'))
        self.rotorC = Rotor(string_to_dict(rotors[1]), 2, letter_to_index(self.group_offset[0]), letter_to_index('S'))

        _enigma = Enigma(self.rotorA, self.rotorB, self.rotorC, self.plugboard)

        # The real offset.
        self.massage_key = _enigma.decrypt(message=self.encrypted_massage_key)

    def decrypt_message(self):
        """
        Decrypt the message itself.
        :return: decrypted message.
        """

        self.rotorA = Rotor(string_to_dict(rotors[3]), 4, letter_to_index(self.massage_key[2]), letter_to_index('X'))
        self.rotorB = Rotor(string_to_dict(rotors[4]), 5, letter_to_index(self.massage_key[1]), letter_to_index('I'))
        self.rotorC = Rotor(string_to_dict(rotors[1]), 2, letter_to_index(self.massage_key[0]), letter_to_index('S'))

        enigma = Enigma(self.rotorA, self.rotorB, self.rotorC, self.plugboard)

        # The decrypted message.
        return enigma.decrypt(message=self.only_message, show=True)

    def run(self, message):
        """
        Run the task.
        :param message: string.
        :return: the decrypted message.
        """
        self.extract_data(self.get_message(message))
        self.get_massage_key()
        self.decrypt_message()


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

from setuptools import setup, find_packages
from thumbor_padding_filter import __version__

tests_require = [
    'mock',
    'nose',
    'coverage',
    'yanc',
    'colorama',
    'preggy',
    'ipdb',
    'coveralls',
    'numpy',
]

setup(
    name='thumbor_padding',
    version=__version__,
    description='Padding filter for thumbor.',
    long_description='''
Padding filter for thumbor.
''',
    keywords='thumbor filter',
    author='Derek Lucas',
    author_email='derek.lucas@arcivr.com',
    url='https://github.com/arcivr/thumbor-padding',
    license='MIT',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: MacOS',
        'Operating System :: POSIX',
        'Operating System :: Unix',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.7',
    ],
    packages=find_packages(),
    include_package_data=True
)


a={1:500,2:300,3:400}
# print(a.get(1))
b={4:700,5:700,7:300}
c={8:200,9:234}

dict={}
for key in a:
    dict[key]=a[key]
for key in b:
    dict[key]=b[key]
for key in c:
    dict[key]=c[key]
print(dict)

# Q.2
# n=int(input('enter the no. of elements do you want in your dict:\n'))
# dict={}
# i=0
# while i<n:
#     key=input('enter the desired key:')
#     value=input('enter the desired value:')
#     dict[key]=value
#     i+=1
# print(dict)

# a={"1":["a","b"],"2":["c","d"]}
# for i in a["1"]:
#     for j in a["2"]:
#         print(i+j)

# from operator import le

# from itertools import count

# d=[{'a':100},{'b':200},{'c':300},{'e':200}]

# a=list(d.values())
# b=list(d.keys())

# dict={}
# for i in b:
#     for j in a:
#         dict[j]=i
# print(dict)

# Q.2

# dict={}
# i=0
# l=len(d)
# while i<l-1:
#     j=i+1
#     while j<l:
#         for item_1 in d[i]:
#             for item_2 in d[j]:
#                 if d[i][item_1]!=d[j][item_2]:
#                     dict[item_1]=d[i][item_1]
#                 else:
#                     pass
#         j+=1
#     i+=1
# print(dict)

# dict_1={'a':100,'b':200,'c':700}
# count_1=0
# for key in dict_1:
#     count_1+=1
#     # print(key,' ',value,' ',count_1)
#     print(key,end=' ')
#     print(dict_1[key],end=' ')
#     print(count_1)

# a={'1':['a','b'],'2':['c','d']}
# list_values=list(a.values())
# for i in list_values[0]:
#     for j in list_values[1]:
#         print(i,end='')
#         print(j)

a={'s   001':['M','S'],'s    002':['M','s','e'],'s003':['M','S']}
dict={}
for key in a:
    k=''
    for l in key:
        # print(l)
        if l==' ':
            pass
        else:
            k+=l
    dict[k]=a[key]
print(dict)


import bisect

def grade(score, breakpoints=[60,70,80,90], grades='FDCBA'):
	i = bisect.bisect(breakpoints, score)
	return grades[i]

# print [grade(score) for score in [0,99,32,80,100]]

def insertion_point(l, insert):
	left = bisect.bisect_left(l,insert)
	right = bisect.bisect_right(l,insert)
	print(l[left], l[right])

l1 = range(10)
l2 = [1,2,5,6] # sorted
l3 = [5,6,2,7] # unsorted
insertion_point(l1,4)
# (4, 5)
insertion_point(l2,4)
# (2, 2)
insertion_point(l3,4)
# (7, 7)


import os
import random
import shutil

import numpy as np
import pandas as pd
from sklearn.utils.class_weight import compute_class_weight

from app.datasets.DatasetConfig import DatasetConfig
from app.datasets.dataset_utility import label2vec, pos_count, DataSequence, get_class_weights_multibinary

class DataSet:
    train = []
    dev = []
    test = []

    def __init__(self, dsconfig):
        """
        :param dsconfig:
        :type dsconfig: DatasetConfig
        """
        self.dsconfig = dsconfig

        self.train_csv = os.path.join(dsconfig.output_dir, "train.csv")
        self.dev_csv = os.path.join(dsconfig.output_dir, "dev.csv")
        self.test_csv = os.path.join(dsconfig.output_dir, "test.csv")

        if dsconfig.use_default_split:  # split train/dev/test
            datasets = ["train", "dev", "test"]
            for d in datasets:
                shutil.copy(f"{self.DSConfig.data_entry_dir}/{d}.csv", self.conf.output_dir)

        if self.dsconfig.force_resplit or not os.path.isfile(self.train_csv) or not os.path.isfile(
                self.dev_csv) or not os.path.isfile(self.test_csv):
            self.split_dataset()
        else:
            self.reload_dataset()

        output_fields = ["Image Index", "Patient ID", "Finding Labels"]
        self.train[output_fields].to_csv(self.train_csv, index=False)
        self.dev[output_fields].to_csv(self.dev_csv, index=False)
        self.test[output_fields].to_csv(self.test_csv, index=False)
        self.print_summary()

    def img_count(self, subdataset="all"):
        return_dict = {"train": len(self.train), "dev": len(self.dev),
                       "test": len(self.test),
                       "all": len(self.train) + len(self.dev) + len(self.test)}
        return return_dict[subdataset.lower()]

    def img_pos_count(self, subdataset="train"):
        return_dict = {"train": pos_count(self.train, self.dsconfig.class_names),
                       "dev": pos_count(self.dev, self.dsconfig.class_names),
                       "test": pos_count(self.test, self.dsconfig.class_names)}
        return return_dict[subdataset.lower()]

    def pat_count(self, subdataset="all"):
        return_dict = {"train": len(list(self.train["Patient ID"].unique())),
                       "dev": len(list(self.dev["Patient ID"].unique())),
                       "test": len(list(self.test["Patient ID"].unique())),
                       "all": len(list(self.train["Patient ID"].unique())) + len(
                           list(self.dev["Patient ID"].unique())) + len(list(self.test["Patient ID"].unique()))}
        return return_dict[subdataset.lower()]

    def print_summary(self):
        print("Total patients = {} ".format(self.pat_count(subdataset="all")), end="")
        print('in train/dev/test ', end="")
        print("{}/".format(self.pat_count(subdataset="train")), end="")
        print("{}/".format(self.pat_count(subdataset="dev")), end="")
        print("{}".format(self.pat_count(subdataset="test")))
        print("Total images = {} ".format(self.img_count(subdataset="all")), end="")
        print("in train/dev/test ", end="")
        print("{}/".format(self.img_count(subdataset="train")), end="")
        print("{}/".format(self.img_count(subdataset="dev")), end="")
        print("{}".format(self.img_count(subdataset="test")))

    def reload_dataset(self):
        print(f"Reloading splitted datasets from {self.train_csv}")
        self.train = pd.read_csv(self.train_csv)
        print(f"Reloading splitted datasets from {self.dev_csv}")
        self.dev = pd.read_csv(self.dev_csv)
        print(f"Reloading splitted datasets from {self.test_csv}")
        self.test = pd.read_csv(self.test_csv)
        self.train["One_Hot_Labels"] = self.train["Finding Labels"].apply(
            lambda x: label2vec(x, self.dsconfig.class_names))
        self.dev["One_Hot_Labels"] = self.dev["Finding Labels"].apply(lambda x: label2vec(x, self.dsconfig.class_names))
        self.test["One_Hot_Labels"] = self.test["Finding Labels"].apply(
            lambda x: label2vec(x, self.dsconfig.class_names))

    def split_dataset(self):
        print(f"Splitting dataset for {self.dsconfig.class_mode}")
        os.makedirs(self.dsconfig.output_dir, exist_ok=True)
        e = pd.read_csv(self.dsconfig.data_entry)

        # one hot encode
        e["One_Hot_Labels"] = e["Finding Labels"].apply(lambda x: label2vec(x, self.dsconfig.class_names))

        # shuffle and split
        pid = list(e["Patient ID"].unique())
        total_patients = len(pid)
        train_patient_count = int(total_patients * self.dsconfig.train_ratio / 100)
        dev_patient_count = int(total_patients * self.dsconfig.dev_ratio / 100)

        random.seed(self.dsconfig.random_state)
        random.shuffle(pid)

        self.train = e[e["Patient ID"].isin(pid[:train_patient_count])]
        self.dev = e[e["Patient ID"].isin(pid[train_patient_count:train_patient_count + dev_patient_count])]
        self.test = e[e["Patient ID"].isin(pid[train_patient_count + dev_patient_count:])]

    def class_weights(self):
        print(f"** {self.dsconfig.class_mode} class_weights **")
        if self.dsconfig.class_mode == 'multiclass':
            class_id = range(len(self.dsconfig.class_names))
            concat_labels = [lbl for sublist in self.train["Finding Labels"].tolist() for lbl in sublist.split("|")]
            concat_labels = [lbl for lbl in concat_labels if lbl != "No Finding"]
            class_weight_sk = compute_class_weight('balanced', self.dsconfig.class_names, concat_labels)
            class_weight = dict(zip(class_id, class_weight_sk))
            for c, w in class_weight.items():
                print(f"  {c+1} [{self.dsconfig.class_names[c]}]: {w}")
        elif self.dsconfig.class_mode == 'multibinary':
            class_weight = get_class_weights_multibinary(
                self.img_count(subdataset="train"),
                self.img_pos_count(subdataset="train"),
                multiply=self.dsconfig.positive_weights_multiply,
                use_class_balancing=self.dsconfig.use_class_balancing)
            for c, w in class_weight.items():
                print(f" {c}: ", end="")
                for wk, wv in w.items():
                    print(f"{wk}: {np.round(wv,2)} ", end="")
                print("")

        return class_weight

    def train_generator(self, verbosity=0):
        batch = self.train.sample(frac=1)  # shuffle
        return DataSequence(batch, image_config=self.dsconfig.ImageConfig, set_name='train',
                            dilation=self.dsconfig.dataset_dilation, verbosity=verbosity)

    def dev_generator(self, verbosity=0):
        batch = self.dev.sample(frac=1)  # shuffle
        return DataSequence(batch, image_config=self.dsconfig.ImageConfig, set_name='dev', dilation=1,
                            verbosity=verbosity)

class DataSetTest:
    def __init__(self, dsconfig):
        """

        :param dsconfig:
        :type dsconfig: DatasetConfig
        """
        self.dsconfig = dsconfig
        test_set = os.path.join(dsconfig.output_dir, "test.csv")
        self.test = pd.read_csv(test_set)

        # one hot encode
        self.test["One_Hot_Labels"] = self.test["Finding Labels"].apply(
            lambda x: label2vec(x, self.dsconfig.class_names))
        pid = list(self.test["Patient ID"].unique())
        self.test_patient_count = len(pid)
        self.test_count = len(self.test)

        print(f"Total patients for test = {self.test_patient_count}")
        print(f"Total images for test = {self.test_count}")

    def test_generator(self, verbosity=0):
        return DataSequence(self.test, image_config=self.dsconfig.ImageConfig, set_name='test', dilation=1,
                            verbosity=verbosity)


# -*- coding: utf-8 -*-
import logging
import maya.cmds as mc
from miraLibs.pipeLibs import pipeFile
from miraLibs.pipeLibs.pipeMaya import get_model_name, publish
from miraLibs.mayaLibs import open_file, quit_maya, export_abc, Xgen, export_selected, save_as
from miraLibs.pyLibs import json_operation

def main(file_name, local):
    logger = logging.getLogger("Hair publish")
    if not local:
        open_file.open_file(file_name)
    # get paths
    context = pipeFile.PathDetails.parse_path(file_name)
    hair_cache_path = context.abc_cache_path
    hair_path = context.hair_path
    delta_path = context.delta_path
    asset_name = context.asset_name
    # import reference
    publish.reference_opt()
    # copy image
    publish.copy_image_and_video(context)
    logger.info("Copy image done.")
    # export SCULP group to abc
    model_name = get_model_name.get_model_name("hair")
    export_abc.export_abc(1, 1, hair_cache_path, model_name)
    logger.info("Export abc done.")
    # export xgen file
    collection_node = str("%s_collection" % asset_name)
    xgen = Xgen.Xgen()
    xgen.export_palette(collection_node, hair_path)
    xgen.create_delta(collection_node, delta_path)
    logger.info("Export .xgen file done.")
    # export shd
    export_shd(context)
    logger.info("Export shader done.")
    save_as.save_as(context.publish_path)
    if not local:
        quit_maya.quit_maya()

def get_descriptions():
    import xgenm as xgen
    collections = xgen.palettes()
    needed_collection = collections[0]
    descriptions = xgen.descriptions(needed_collection)
    return descriptions

def get_all_hair_sg_nodes():
    hair_sg_nodes = list()
    connection_dict = dict()
    descriptions = get_descriptions()
    if not descriptions:
        return
    for description in descriptions:
        shapes = mc.listRelatives(description, s=1)
        if not shapes:
            continue
        shape = shapes[0]
        sg_nodes = mc.listConnections(shape, s=0, d=1, type="shadingEngine")
        if not sg_nodes:
            continue
        sg_node = sg_nodes[0]
        hair_sg_nodes.append(sg_node)
        connection_dict[description] = sg_node
    return hair_sg_nodes, connection_dict

def export_shd(context):
    sg_nodes, connection_dict = get_all_hair_sg_nodes()
    if not sg_nodes:
        return
    mc.select(sg_nodes, r=1, ne=1)
    export_selected.export_selected(context.shd_path)
    json_operation.set_json_data(context.connection_path, connection_dict)


from class_mdia import Media

class Actor(Media):
    def __init__(self, dast, name, k, ims, ul, du, ca, n, ag, last, jens, character):
        super().__init__(dast, name, k, ims, ul, du, ca)
        name_actor = n
        age = ag
        last_name = last
        jensiat = jens
        shakhsiat = character # bad , good , npc

    def show_actor(self):
        print("name : ", self.name_actor, "lastname : ", self.last_name, "age : ", self.age, "jensiat : ", self.jensiat, "naghsh to film : ", self.shakhsiat)


import requests
import time

def send_request():
    response = requests.get('https://dummyjson.com/products/1')
    print(response.json())

if __name__ == '__main__':
    print('starting requests')
    while True:
        send_request()
        time.sleep(3)


import clue.Cards as Cards
from clue.Exceptions import ImpossibleError

# Player class
class Player:
	def __init__(self, name, numCards):
		self.name = name
		# number of cards this player holds
		self.numCards = numCards
		# Set of cards this player is known to have
		self.hasCards = set()
		# Set of cards this player is known NOT to have
		self.notHasCards = set()
		# list of triple as about
		self.asked = []
		# list of triples of which one has been shown to someone
		self.shown = []

	def hasCard(self, card):
		self.hasCards.add(card)
		if len(self.hasCards) > self.numCards:
			raise ImpossibleError(
				"%s has only %s cards but has shwon %r" %
				(self.name, self.numCards, self.hasCards))

	def ask(self, triple):
		self.asked.append(triple)

	def show(self, triple):
		if set(triple.all_cards).issubset(self.notHasCards):
			raise ImpossibleError(
				"%s showed me one of %s, but earlier decline to show all those."
				% (self.name, triple))

		self.shown.append(triple)

	def noshow(self, triple):
		has = self.hasCards.intersection(triple.all_cards)
		if has:
			raise ImpossibleError(
				"%s declined for %s, but we know they have %s"
				% (self.name, triple.all_cards, has))

		self.notHasCards.update(triple.all_cards)

	def check(self):
		impossible = self.hasCards.intersection(self.notHasCards)
		if impossible:
			raise ImpossibleError(
				"%s is known to have and known to not have %s"
				% (self.name, impossible))

	def snapshot(self):
		s = self.__class__(self.name, self.numCards)
		s.hasCards = self.hasCards.copy()
		s.notHasCards = self.notHasCards.copy()
		s.asked = self.asked.copy()
		s.shown = self.shown.copy()
		return s

	def __repr__(self):
		return "%s(%r, %r)" % (self.__class__.__name__, self.name, self.numCards)

class Me(Player):
	def __init__(self, myCards):
		myCards = set(myCards)
		super().__init__("Me", len(myCards))
		self.hasCards.update(myCards)
		self.notHasCards = set(Cards.DECK).difference(self.hasCards)

	def snapshot(self):
		s = self.__class__(self.hasCards)
		s.asked = self.asked.copy()
		s.shown = self.shown.copy()
		return s

	def __repr__(self):
		return "%s(%r)" % (self.__class__.__name__, sorted(self.hasCards))


import os,random
import string
t=input('Nhập tên thư mục: ')
path='C:\\'
os.chdir(path)
os.mkdir(t)
file_name = input("Nhập tên file dữ liệu: ")
n=int(input("Nhập dung lượng 1MB-1024MB của thư mục: "))
for i in range(n):
    path1 = path + t
    os.chdir(path1)
    file=open(file_name + " lần thứ "+ str(i+1) + '.txt','w+')
    file.seek(1024*1000-1)
    file.write("random.choice(string.ascii_lowercase)")
if file.seek(0):
    os.remove(file)
file.close()


from collections import ChainMap
import traceback
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta
from time import monotonic
import re
from uuid import uuid4
import logging
from server.utils import get_randomization, safe_strptime, timer, config, warn_set
from server.query import Query
from server.db_conn import db_connection
from common.utils import boolinize

LOGGER = logging.getLogger('Monitor')

class Monitor:
    '''Used for scheduling and monitoring execution of Queries'''

    def __init__(self, username):
        self.username = username
        self.queries = dict()
        self.db_conn = db_connection()
        self.DEFAULT_DATE = datetime(1970,1,1)
        self.MIN_INTERVAL = int(config['min_query_interval'])
        self.queries_run_counter = 0
        self._create_eta_dict()
        self.warnings = warn_set()

    def _create_eta_dict(self):
        '''create mapping {eta_parameter: tuple(regex_pattern, parsing_function)}'''
        dow = {'monday': 0,'tuesday': 1,'wednesday': 2,'thursday': 3,'friday': 4,'saturday': 5,'sunday': 6}
        dowj = '|'.join(dow.keys())
        dt = r"([0-2]?[0-9]|3[0-1])/([0-1]?[0-2]|0?[0-9])/[0-9]{4}"
        t = r"([0-1]?[0-9]|2[0-4])(:[0-5][0-9])?"
        self.eta_re = dict(
            dow       = (re.compile(f'^({dowj})$'),          lambda d: dow[d]                                                                       ),
            time_span = (re.compile(f'^{t}-{t}$'),           lambda d: tuple(tuple(int(c) for c in (t+':00').split(':')[:2]) for t in d.split('-')) ),
            dt_span   = (re.compile(f'^{dt}-{dt}$'),         lambda d: self._create_dt_span(d)                                                      ),
            dow_span  = (re.compile(f'^({dowj})-({dowj})$'), lambda d: tuple(dow[t] for t in d.split('-'))                                          ),
            dt        = (re.compile(f'^{dt}$'),              lambda d: tuple(int(c) for c in d.split('/'))                                          ),
        )

    def _create_dt_span(self, d:str) -> tuple:
        return tuple(datetime(**{k:int(v) for k,v in zip(['day', 'month', 'year'], t.split('/'))}) for t in d.split('-'))

    def _res_msg(self, base:str='', w_prefix:str=' with warnings: '):
        w = f"{w_prefix}{', '.join(self.warnings)}" if self.warnings else ''
        self.warnings.clear()
        return base + w

    async def add_query(self, d:dict) -> tuple[bool, str]:
        d, is_valid = await self._validate_query(d)
        if not is_valid: return False, self._res_msg('Query validation failed', 'with errors: ')
        cookies, d['cookies_filename'] = await self.db_conn.setdefault_cookie_file(username=self.username, filename=d['cookies_filename'])
        d['query'] = Query(url=d['url'], sequence=d['sequence'], cookies=cookies, min_matches=d['min_matches'], mode=d['mode'])
        self.queries[d['uid']] = d
        LOGGER.debug(f'[{self.username}] added Query: {self.queries[d["uid"]]}')
        return True, self._res_msg('Query added successfully')

    @timer
    async def _validate_query(self, d:dict) -> tuple[dict, bool]:
        '''return validated Query - remove unwanted data, check if required paramerters were provided,
           ensure parameters types and set defaults if missing '''

        # Preclude any unexpected parameters
        vd = dict()

        # Validate required parameters
        vd['url'] = await self._valpar(d, 'url',         exp_inst=str,   d_val=None)
        if not vd['url']:
            self.warnings.add('Query missing required parameter: url')
            return vd, False
        vd['sequence'] = await self._valpar(d, 'sequence',    exp_inst=str,   d_val=None)
        if not vd['sequence']:
            self.warnings.add('Query missing required parameter: sequence')
            return vd, False
        vd['interval'] = await self._valpar(d, 'interval',    exp_inst=int,   v_func=self._parse_interval, i=d.get('interval'))
        if not vd['interval']:
            self.warnings.add('Query missing required parameter: interval')
            return vd, False

        # Verify unique alias
        vd['uid'] = await self._valpar(d, 'uid', exp_inst=str, d_func=self._create_uid)
        vd['alias'] = await self._valpar(d, 'alias', exp_inst=str, d_val=d['url'])
        if vd['alias'] in {v['alias'] for k,v in self.queries.items() if k!=vd['uid']}:
            self.warnings.add(f"Query not added due to duplicate alias: {vd['alias']}")
            return vd, False

        # Parse ETA
        vd['eta'] = await self._parse_eta(d.get('eta'))
        vd['cooldown'] = await self._parse_cooldown(d.get('cooldown', '0'), vd['interval'])

        vd['target_url'] = d.get('target_url')

        # Setdefault other parameters
        vd['randomize'] =           await self._valpar(d, 'randomize',             exp_inst=int,               d_val=0                                   )
        vd['mode'] =                await self._valpar(d, 'mode',                  exp_inst=str,               d_val='exists'                            )
        vd['cycles_limit'] =        await self._valpar(d, 'cycles_limit',          exp_inst=int,               d_val=0                                   )
        vd['is_recurring'] =        await self._valpar(d, 'is_recurring',          exp_inst=boolinize,         d_val=False                               )
        vd['alert_sound'] =         await self._valpar(d, 'alert_sound',           exp_inst=str,               d_val=config['default_sound']             )
        vd['min_matches'] =         await self._valpar(d, 'min_matches',           exp_inst=int,               d_val=1, v_func=self._validate_min_matches)
        vd['cycles'] =              await self._valpar(d, 'cycles',                exp_inst=int,               d_val=0                                   )
        vd['last_run'] =            await self._valpar(d, 'last_run',              exp_inst=safe_strptime,     d_val=self.DEFAULT_DATE                   )
        vd['found'] =               await self._valpar(d, 'found',                 exp_inst=boolinize,         d_val=False                               )
        vd['last_match_datetime'] = await self._valpar(d, 'last_match_datetime',   exp_inst=safe_strptime,     d_val=self.DEFAULT_DATE                   )
        vd['is_new'] =              await self._valpar(d, 'is_new',                exp_inst=boolinize,         d_val=False                               )
        vd['status'] =              await self._valpar(d, 'status',                exp_inst=int,               d_val=-1                                  )
        vd['cookies_filename'] =    await self._valpar(d, 'cookies_filename',      exp_inst=str,               d_val=None,
                                                                                d_func=self.db_conn.create_cookies_filename,
                                                                                filename=vd['alias'], username=self.username                           )
        return vd, True

    async def _valpar(self, d, k, exp_inst:type=str, d_val=None, d_func=None, v_func=None, **kwargs):
        '''return validated Query parameter'''
        old = d.get(k)
        try:
            new_value = exp_inst(d[k]) if not v_func else await v_func(d[k])
            if exp_inst == str and not new_value.strip(): raise ValueError
        except (KeyError, TypeError, ValueError):
            try:
                new_value = await d_func(**kwargs) if d_func else d_val
                LOGGER.debug(f"[{self.username}] replaced invalid parameter '{k}' {old} --> {new_value}")
            except (TypeError, ValueError, AttributeError):
                LOGGER.debug(f"[{self.username}] failed to validate parameter: {k}")
                return d_val
        return new_value

    async def _parse_interval(self, i:str) -> int:
        res = await self._parse_time(str(i))
        if res < self.MIN_INTERVAL:
            res = self.MIN_INTERVAL
            self.warnings.add(f'interval too low (min:{self.MIN_INTERVAL})')
        return res

    async def _parse_cooldown(self, c:str, i:int):
        c = await self._parse_time(str(c))
        return max(c, i)

    async def _parse_time(self, t:str) -> int:
        '''returns number of minutes from time-like string'''
        if t.endswith('h'):
            res = float(t[:-1])*60
        elif t.endswith('d'):
            res = float(t[:-1])*60*24
        else:
            res = float(t)
        return int(res)

    async def _create_uid(self) -> str:
        return str(uuid4())

    async def _validate_min_matches(self, min_matches:str):
        return max(int(min_matches), 1)

    async def _parse_eta(self, eta) -> dict:
        '''create eta dict from string'''
        w = list()
        eta = eta.get('raw', '') if isinstance(eta, dict) else eta
        d = {'dow':[], 'dt':[], 'dow_span':[], 'dt_span':[], 'time_span':[], 'raw': eta or ''}
        if not eta or not isinstance(eta, str): return d
        for p in eta.lower().split(','):
            for k, v in self.eta_re.items():
                if v[0].search(p):
                    try:
                        d[k].append(v[1](p))
                    except (TypeError, IndexError, KeyError, AttributeError):
                        LOGGER.debug(f"[{self.username}] Invalid value for eta parser {k}: {p}")
                        w.append(p)
                    break
            else:
                LOGGER.debug(f"[{self.username}] ETA rule not found for {p}")
                w.append(p)
        w = f"invalid ETA rules: {', '.join(w)}" if w else ''
        self.warnings.add(w)
        return d

    async def edit_query(self, d:dict) -> bool:
        '''update existing query with new parameters (with validation)'''
        try:
            uid = d['uid']
            if uid not in self.queries.keys(): return False, 'Query does not exist'
            d = {**self.queries[uid], **d}
            d, s = await self._validate_query(d)
            if not s: return False, self._res_msg('Query edit failed', ' with errors: ')
            await self.close_session(uid)
            self.queries[uid].update(d)
            cookies, self.queries[uid]['cookies_filename'] = await self.db_conn.setdefault_cookie_file(
                                                                username=self.username,
                                                                filename=self.queries[uid]['cookies_filename'])
            self.queries[uid]['query'] = Query(url=self.queries[uid]['url'],
                                                sequence=self.queries[uid]['sequence'],
                                                cookies=cookies,
                                                min_matches=self.queries[uid]['min_matches'],
                                                mode=self.queries[uid]['mode'])
            res, msg = True, self._res_msg('Query edited successfully')
        except Exception as e:
            LOGGER.error(traceback.format_exc())
            res, msg = False, e.__class__.__name__
        return res, msg

    async def restore_query(self, d:dict) -> tuple[bool, str]:
        d, s = await self._validate_query(d)
        if not s: return False, self._res_msg('Query restore failed', ' with errors: ')
        cookies, d['cookies_filename'] = await self.db_conn.setdefault_cookie_file(username=self.username, filename=d['cookies_filename'])
        d['query'] = Query(url=d['url'], sequence=d['sequence'], cookies=cookies, min_matches=d['min_matches'], mode=d['mode'])
        self.queries[d['uid']] = d
        return True, self._res_msg(f'Query restored: {d["alias"]}')

    async def scan(self) -> tuple[dict, str]:
        '''Uses ThreadPoolExecutor to perform a run of scheduled queries and return results'''
        start_all = monotonic()
        self.queries_run_counter = 0
        with ThreadPoolExecutor() as executor:
            _res = executor.map(self._scan_one, self.queries.values())
        self.queries = dict(ChainMap(*reversed(list(_res))))  # merge list of dicts into a single dict, retaining order
        if self.queries_run_counter>1:
            LOGGER.info(f"[{self.username}] scanned {self.queries_run_counter} queries in {(monotonic()-start_all)*1000:.0f}ms")
        return self.queries, self._res_msg('Scanned Queries')

    def _scan_one(self, q) -> dict:
        '''Runs a request for 1 query if conditions are met. Returns dict[uid:query_params]'''
        if self._should_run(q):
            start = monotonic()
            prev_found = q['found']
            q['found'], q['status'] = q['query'].run()
            q['last_match_datetime'] = self._get_last_match_datetime(prev_found, q['found'], q['last_match_datetime'], q['is_recurring'])
            q['last_run'] = datetime.now()
            if q['status'] in {0, 1}:
                q['cycles']+=1
            q['is_new'] = True
            self.queries_run_counter+=1
            LOGGER.info(f"[{self.username}] ran query: {q['alias']} in {1000*(monotonic()-start):.0f}ms Found: {q['found']}, Status: {q['status']}")
        else:
            q['is_new'] = False
        return {q['uid']:q}

    def _should_run(self, q:dict):
        if q['status'] in {-1, 2} and q['cycles_limit']>=0:
            res = True
        else:
            eta_c = self._eta_condition(q['eta'])
            res = eta_c and (not q['found'] or q['is_recurring']) and \
                (q['cycles'] < q['cycles_limit'] if q['cycles_limit'] != 0 else True) and \
                q['last_run'] + timedelta(minutes=q['cooldown'] if q['found'] \
                else (q['interval']+get_randomization(q['interval'], q['randomize']))) <= datetime.now()
        return res

    def _get_last_match_datetime(self, prev_found, found, last_match_datetime, recurring):
            if found or (recurring and not prev_found):
                return datetime.now()
            else:
                return last_match_datetime

    def _eta_condition(self, eta:dict, n:datetime=None) -> bool:
        dow, time_span, dt, dt_span, dow_span = [True]*5
        n = n or datetime.now()

        for d in eta['dow']:
            dow = n.weekday() == d
            if dow: break
        if not dow: return False

        for d in eta['time_span']:
            time_span = d[0] <= (n.hour, n.minute) <= d[1]
            if time_span: break
        if not time_span: return False

        for d in eta['dt_span']:
            dt_span = d[0] <= n <= d[1]+timedelta(days=1)
            if dt_span: break
        if not dt_span: return False

        for d in eta['dow_span']:
            dow_span = d[0] <= n.weekday() <= d[1]
            if dow_span: break
        if not dow_span: return False

        for d in eta['dt']:
            dt = d == (n.day, n.month, n.year)
            if dt: break
        if not dt: return False

        return True

    async def clean_queries(self):
        new_queries = dict()
        removed_queries = set()
        for k, v in self.queries.items():
            if not v['found'] or v['is_recurring']:
                new_queries[k] = v
            else:
                await self.close_session(k)
                removed_queries.add(v['alias'])
        self.queries = new_queries
        msg = f"[{self.username}] removed queries: {', '.join(removed_queries)}"
        LOGGER.info(msg)
        return True, msg

    async def delete_query(self, uid) -> tuple[bool, str]:
        try:
            alias = self.queries[uid]['alias']
            del self.queries[uid]
            LOGGER.info(f"[{self.username}] deleted query '{alias}'")
            return True, f"Query {alias} was removed"
        except KeyError:
            return False, f"Query with uid: {uid} does not exist"

    async def close_session(self, uid) -> tuple[bool, str]:
        try:
            await self.queries[uid]['query'].close_session()
            return True, f"Session closed for Query: {self.queries[uid]['alias']}"
        except KeyError:
            return False, f"Query with uid: {uid} does not exist"

    async def save(self) -> tuple[bool, str]:
        try:
            await self.db_conn.save_dashboard(self.username, self.queries)
            saved_cookies = await self.db_conn.save_cookies(self.username, self.queries)
            LOGGER.info(f"[{self.username}] saved cookies: {', '.join(saved_cookies)}")
            return True, 'Saved user data'
        except Exception as e:
            LOGGER.error(traceback.format_exc())
            return False, 'Failed saving Dashboard with Error: {e}'

    async def get_sound_file(self, sound):
        try:
            f, fname = await self.db_conn.load_notification_file(self.username, sound)
        except Exception as e:
            LOGGER.error(f"[{self.username}] Exception occurred while loading the sound file: {sound}. Exception: {e}")
            f, fname = None, 'err'
        return f, fname

    async def populate(self) -> tuple[bool, str]:
        '''Populate Monitor of the user with queries from the db'''
        queries = await self.db_conn.get_dashboard_data(self.username)
        aliases = list()
        for q in queries.values():
            res, msg = await self.restore_query(q)
            if res: aliases.append(q['alias'])
            else: LOGGER.warning(f"[{self.username}] Query restore failed: {msg}")
        added_q = self.queries
        exp_len = len(queries.values())
        msg = f"[{self.username}] restored {len(added_q)}/{exp_len} Queries: {', '.join(aliases)}"
        if len(added_q)==exp_len:
            LOGGER.info(msg)
            return True, f"Restored all {len(added_q)} queries"
        else:
            LOGGER.warning(msg)
            return False, f"Restored only {len(added_q)}/{exp_len} Queries"

    async def reload_cookies(self, cookies) -> tuple[bool, str]:
        '''Update existing files with new data'''
        try:
            await self.db_conn.reload_cookies(self.username, cookies)
            return True, f'Cookies reloaded'
        except Exception as e:
            LOGGER.error(traceback.format_exc())
            return False, f"Error occurred: {e}"


print("Hello and welcome to the Factorial Factory!")
print("""Prepare to be amazed as we take any number you give us and give to you,
it's Fantastic Factorial""")

factor = int(input("Please enter any number you wish: "))

def factorial(num):
    sum = 1
    while num >= 1:
        sum = sum * num
        num = num - 1
    return sum

number = factorial(factor)
print(number)


# test_spiderfoot_module_loading.py
import os
import unittest

from sflib import SpiderFoot

class TestSpiderFootModuleLoading(unittest.TestCase):
    """
    Test SpiderFoot module loading
    """

    default_options = {
        '_debug': False,  # Debug
        '__logging': True,  # Logging in general
        '__outputfilter': None,  # Event types to filter from modules' output
        '_useragent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0',  # User-Agent to use for HTTP requests
        '_dnsserver': '',  # Override the default resolver
        '_fetchtimeout': 5,  # number of seconds before giving up on a fetch
        '_internettlds': 'https://publicsuffix.org/list/effective_tld_names.dat',
        '_internettlds_cache': 72,
        '_genericusers': "abuse,admin,billing,compliance,devnull,dns,ftp,hostmaster,inoc,ispfeedback,ispsupport,list-request,list,maildaemon,marketing,noc,no-reply,noreply,null,peering,peering-notify,peering-request,phish,phishing,postmaster,privacy,registrar,registry,root,routing-registry,rr,sales,security,spam,support,sysadmin,tech,undisclosed-recipients,unsubscribe,usenet,uucp,webmaster,www",
        '__version__': '3.3',
        '__database': 'spiderfoot.test.db',  # note: test database file
        '__modules__': None,  # List of modules. Will be set after start-up.
        '_socks1type': '',
        '_socks2addr': '',
        '_socks3port': '',
        '_socks4user': '',
        '_socks5pwd': '',
        '_torctlport': 9051,
        '__logstdout': False
    }

    def test_module_loading(self):
        sf = SpiderFoot(self.default_options)

        # Go through each module in the modules directory with a .py extension
        sfModules = dict()
        mod_dir = sf.myPath() + '/modules/'
        for filename in os.listdir(mod_dir):
            if filename.startswith("sfp_") and filename.endswith(".py"):
                # Skip the module template and debugging modules
                if filename == "sfp_template.py" or filename == 'sfp_stor_print.py':
                    continue
                modName = filename.split('.')[0]

                # Load and instantiate the module
                sfModules[modName] = dict()
                mod = __import__('modules.' + modName, globals(), locals(), [modName])
                sfModules[modName]['object'] = getattr(mod, modName)()
                sfModules[modName]['name'] = sfModules[modName]['object'].meta['name']
                sfModules[modName]['cats'] = sfModules[modName]['object'].meta.get('categories', list())
                sfModules[modName]['group'] = sfModules[modName]['object'].meta.get('useCases', list())
                sfModules[modName]['labels'] = sfModules[modName]['object'].meta.get('flags', list())
                sfModules[modName]['descr'] = sfModules[modName]['object'].meta['summary']
                sfModules[modName]['provides'] = sfModules[modName]['object'].producedEvents()
                sfModules[modName]['consumes'] = sfModules[modName]['object'].watchedEvents()
                sfModules[modName]['meta'] = sfModules[modName]['object'].meta
                if hasattr(sfModules[modName]['object'], 'opts'):
                    sfModules[modName]['opts'] = sfModules[modName]['object'].opts
                if hasattr(sfModules[modName]['object'], 'optdescs'):
                    sfModules[modName]['optdescs'] = sfModules[modName]['object'].optdescs

        self.assertTrue(len(sfModules.keys()))

        valid_use_cases = ["Footprint", "Passive", "Investigate"]
        valid_categories = ["Content Analysis", "Crawling and Scanning", "DNS",
                            "Leaks, Dumps and Breaches", "Passive DNS",
                            "Public Registries", "Real World", "Reputation Systems",
                            "Search Engines", "Secondary Networks", "Social Media"]

        for module in sfModules:
            m = sfModules[module]

            self.assertTrue(m.get('object'))
            self.assertTrue(m.get('name'))
            self.assertTrue(m.get('meta'))
            self.assertIsInstance(m.get('cats'), list)
            # self.assertTrue(m.get('group'))
            self.assertIsInstance(m.get('labels'), list)
            self.assertTrue(m.get('descr'))
            # self.assertTrue(m.get('provides'))
            self.assertIsInstance(m.get('provides'), list)
            self.assertTrue(m.get('consumes'))
            self.assertIsInstance(m.get('consumes'), list)
            self.assertIsInstance(m.get('meta'), dict)

            # skip debugging and output modules
            if module in ["sfp__stor_db", "sfp__stor_stdout"]:
                continue

            for cat in m.get('group', list()):
                self.assertIn(cat, valid_use_cases)

            for cat in m.get('cats', list()):
                self.assertIn(cat, valid_categories)

            self.assertTrue(m.get('name'))
            self.assertTrue(m.get('descr'))

            # check len(options) == len(option descriptions)
            if m.get('opts'):
                self.assertEqual("%s opts: %s" % (module, len(m.get('opts').keys())), "%s opts: %s" % (module, len(m.get('optdescs').keys())))


import warnings
import itertools
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import statsmodels.api as sm
import matplotlib
import pmdarima as pm
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.stattools import acf, adfuller
from statsmodels.tools.sm_exceptions import ConvergenceWarning
from scipy.fftpack import fft, fftfreq
from scipy.signal import argrelextrema
from sklearn.metrics import mean_absolute_error as mae
from sklearn.metrics import mean_squared_error

warnings.simplefilter('ignore', ConvergenceWarning)

class Sarima:
    def __init__(self, df, alpha=0.05):
        if isinstance(df, str):
          self.df = pd.read_csv(df)
        else:
          self.df = df.copy()
        self.col_names = list(df.keys())
        self.index_name = df.index.name
        self.start = None
        self.alpha = alpha
        self.season = self._find_season(self.df)
        self._prep_sarima()
        self.pdq = self.find_pdq(self.df, self.season)
        self.model = self.init_sarima()
        self.prediction = None
        self.conf_int = None

    def _adf_test(self,timeseries):
        #Perform Dickey-Fuller test:
        dftest = adfuller(timeseries, autolag='AIC')
        dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])
        for key,value in dftest[4].items():
           dfoutput['Critical Value (%s)'%key] = value
        return dfoutput['p-value']

    def _find_season(self,d):
        r = acf(d)[1:-1]
        res = argrelextrema(np.abs(r), np.greater)
        try:
            return argrelextrema(np.abs(r), np.greater)[0][0]
        except:
            return 0

    def _prep_sarima(self):
        #res = df.copy()
        #on suppose que df est déjà une copie
        p = self._adf_test(self.df)
        if p > self.alpha:
            self.df = self.df - self.df.shift(1)
            self.df = self.df.dropna()
            #clean(self.df) si jamais on a des NULL

        trend_diff = pm.arima.ndiffs(self.df,alpha=self.alpha)
        if self.season > 0:
            #self.df = self.df - self.df.shift(self.season)
            self.df = self.df - self.df.shift(trend_diff)
            self.df = self.df.dropna()
            #clean(df) si jamais on a des NULL

    def find_pdq(self,df,season):
        p = range(0, 2)
        d = range(0, 2)
        q = range(0, 2)
        if season < 2:
            season = 2
        pdq = list(itertools.product(p, d, q))
        seasonal_pdq = [(x[0], x[1], x[2], season) for x in list(itertools.product(p, d, q))]
        res = []
        for param in pdq:
          for param_seasonal in seasonal_pdq:
            try:
              mod = sm.tsa.statespace.SARIMAX(df,order=param, seasonal_order=param_seasonal, enforce_stationarity=False, enforce_invertibility=False)
              results = mod.fit(disp=False)
              res.append((param, param_seasonal, results.aic))
            except Exception as e:
              #print(e)
              pass
        try:
            res = min(res, key = lambda t: t[2]) #min sur results.aic
        except:
            res = [(0,0,0),(0,0,0,0),0]
        return res # (tuple[3],tuple[4],float)

    def init_sarima(self):
        mod = sm.tsa.statespace.SARIMAX(self.df,order=self.pdq[0], seasonal_order=self.pdq[1], enforce_stationarity=False,\
                                enforce_invertibility=False)
        res = mod.fit(disp=False)
        return res

    def predict(self,start,end,dynamic=False,alpha=0.05):
        self.alpha = alpha
        self.prediction = self.model.get_prediction(start=start, end=end, dynamic=dynamic)
        self.start=start
        self.conf_int = self.prediction.conf_int(alpha=self.alpha)
        return self.prediction,self.conf_int

    def mse(self,data=None,square_root=False):
        y_forecasted = self.prediction.predicted_mean
        y_forecasted = y_forecasted.to_frame(name=self.col_names[0])
        n = None
        if data is None:
            ref = self.df[self.start:]
        else:
            ref = data
            n = len(data)
        if n:
            if square_root:
                return np.sqrt(((y_forecasted[:n] - ref) ** 2)).mean()
            return ((y_forecasted[:n] - ref) ** 2).mean()
        else:
            if square_root:
                return np.sqrt(((y_forecasted - ref) ** 2)).mean()
            return ((y_forecasted - ref) ** 2).mean()

    def mape(self,data=None):
        if self.prediction == None:
            return None
        y_forecasted = self.prediction.predicted_mean
        y_forecasted = y_forecasted.to_frame(name=self.col_names[0])
        n = None
        if data is None:
            ref = self.df[self.start:]
        else:
            ref = data
            n = len(data)
        if n:
            return np.mean(np.abs((ref[self.col_names[0]] - y_forecasted[self.col_names[0]][:n])/y_forecasted[self.col_names[0]][:n]))*100
        return np.mean(np.abs((ref[self.col_names[0]] - y_forecasted[self.col_names[0]])/y_forecasted[self.col_names[0]]))*100

    def rmse(self,data=None):
        if self.prediction == None:
            return None
        y_forecasted = self.prediction.predicted_mean
        y_forecasted = y_forecasted.to_frame(name=self.col_names[0])
        n = None
        if data is None:
            ref = self.df[self.start:]
        else:
            ref = data
            n = len(data)
        if n:
            return mean_squared_error(ref[self.col_names[0]], y_forecasted[self.col_names[0]][:n], squared=False)
        return mean_squared_error(ref[self.col_names[0]], y_forecasted[self.col_names[0]], squared=False)

    def mae(self,data=None):
        if self.prediction == None:
            return None
        y_forecasted = self.prediction.predicted_mean
        y_forecasted = y_forecasted.to_frame(name=self.col_names[0])
        n = None
        if data is None:
            ref = self.df[self.start:]
        else:
            ref = data
            n = len(data)
        if n:
            return mae(ref[self.col_names[0]], y_forecasted[self.col_names[0]][:n])
        return mae(ref[self.col_names[0]], y_forecasted[self.col_names[0]])


import collections

def solution(maps):
    answer = 0
    dx = [0, 0, 1, -1]
    dy = [1, -1, 0, 0]

    def BFS(start):
        q = collections.deque([(start)])
        while q:
            y, x = q.popleft()
            for s in range(4):
                newX = x + dx[s]
                newY = y + dy[s]
                if(newX < 0 or newX >= len(maps[0]) or newY < 0 or newY >= len(maps)):
                    continue
                if(maps[newY][newX] == 0):
                    continue
                if(maps[newY][newX] == 1):
                    maps[newY][newX] = maps[y][x] + 1
                    q.append((newY, newX))
        if(maps[len(maps) - 1][len(maps[0]) - 1] == 1):
            return -1
        else:
            return maps[len(maps) - 1][len(maps[0]) - 1]

    answer = BFS((0,0))

    return answer

프로그래머스/lv2/1844. 게임 맵 최단거리/게임 맵 최단거리.py

게임 맵 최단거리.py


import unittest

from src.game_entities.character import Character
from src.game_entities.movable import DamageKind
from tests.random_data_library import (
    random_character_entity,
    random_shield,
    random_equipment,
    random_foe_entity,
    random_weapon,
)
from tests.tools import minimal_setup_for_game

class TestCharacter(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        minimal_setup_for_game()

    def test_init_character(self):
        name = "character_test"
        pos = (3, 2)
        sprite = "imgs/characs/jist.png"
        hp = 10
        defense = 4
        res = 3
        strength = 2
        classes = ["innkeeper"]
        equipments = []
        strategy = "STATIC"
        lvl = 3
        skills = []
        alterations = []
        race = "human"
        gold = 500
        interaction = {
            "dialog": [
                "Hurry up ! Leave the village from the west, and enter the necropolis.",
                "The clock is ticking... The ogre's bones must be returned to their "
                "original place.",
            ],
            "join_team": False,
        }
        character_test = Character(
            name,
            pos,
            sprite,
            hp,
            defense,
            res,
            strength,
            classes,
            equipments,
            strategy,
            lvl,
            skills,
            alterations,
            race,
            gold,
            interaction,
        )
        self.assertEqual(equipments, character_test.equipments)
        self.assertEqual(classes, character_test.classes)
        self.assertEqual(race, character_test.race)
        self.assertEqual(gold, character_test.gold)
        self.assertFalse(character_test.join_team)
        self.assertEqual(int, type(character_test.constitution))

    def test_talk_to_character(self):
        interaction = {
            "dialog": [
                "Hurry up ! Leave the village from the west, and enter the necropolis.",
                "The clock is ticking... The ogre's bones must be returned to their "
                "original place.",
            ],
            "join_team": False,
        }
        actor = random_character_entity()
        character_test = random_character_entity(interaction=interaction)
        entries = character_test.talk(actor)
        self.assertEqual(2, len(entries))

    def test_talk_to_recruitable_character(self):
        interaction = {
            "dialog": [
                "Hurry up ! Leave the village from the west, and enter the necropolis.",
                "The clock is ticking... The ogre's bones must be returned to their "
                "original place.",
            ],
            "join_team": True,
        }
        actor = random_character_entity()
        character_test = random_character_entity(interaction=interaction)
        character_test.talk(actor)
        self.assertTrue(character_test.join_team)

    def test_lvl_up(self):
        character_test = random_character_entity(lvl=3)
        hp_before = character_test.hit_points_max
        character_test.lvl_up()
        self.assertEqual(4, character_test.lvl)
        self.assertNotEqual(hp_before, character_test.hit_points_max)

    def test_parried(self):
        parry_rate = 100
        equipments = [random_shield(parry_rate=parry_rate)]
        character_test = random_character_entity(equipments=equipments)
        self.assertTrue(character_test.parried())

        parry_rate = 0
        equipments = [random_shield(parry_rate=parry_rate)]
        character_test.equipments = equipments
        self.assertFalse(character_test.parried())

    def test_attacked_while_having_equipments(self):
        defense = 2
        res = 3
        equipments = [random_equipment(defense=defense, res=res)]
        character_test = random_character_entity(equipments=equipments)

        # Physical attack
        damage = character_test.defense + 5
        character_test.attacked(random_foe_entity(), damage, DamageKind.PHYSICAL, [])
        self.assertEqual(character_test.hit_points_max - 3, character_test.hit_points)

        character_test.healed()

        # Mental attack
        damage = character_test.resistance + 5
        character_test.attacked(random_foe_entity(), damage, DamageKind.SPIRITUAL, [])
        self.assertEqual(character_test.hit_points_max - 2, character_test.hit_points)

    def test_attack_with_weapon(self):
        weapon = random_weapon(strong_against=[])
        equipments = [weapon]
        character_test = random_character_entity(equipments=equipments)

        self.assertEqual(
            character_test.strength + weapon.attack,
            character_test.attack(random_foe_entity()),
        )


class AlphaBetaNode(object):
    # Class constructor.
    #
    # PARAM [board.Board] brd: the board state
    # PARAM [int]         col: column where last token was added
    # PARAM [int]         evaluation: The likely hood of either player winning.
    #
    # Note: Evaluation is from 0-1; 1 meaning AI will win and 0 meaning the other player will win
    def __init__(self, board, col, evaluation):
        # Board used in node
        self.board = board
        # column where last token was added
        self.col = col
        # evaluation value given by the alphaBetaAgent evaluation function
        self.evaluation = evaluation


import numpy as np
from numpy import ndarray
import csv
#from datetime import datetime
from claseEmpleado import Empleado
from empleadoPlanta import EmpleadoPlanta
from empleadoContratado import EmpleadoContratado
from empleadoExterno import EmpleadoExterno

class ManejadorEmpleados:
    __arregloEmpleados = ndarray
    __dimension = int
    __indice = int

    def __init__(self, dimension, indice = 0):
        self.__arregloEmpleados=np.empty(dimension,dtype=Empleado)
        self.__dimension = dimension
        self.__indice = indice

    def cargarEmpleados(self):
        self.cargarPlanta()
        self.cargarContratados()
        EmpleadoContratado.setValorHora(5000)
        self.cargarExternos()
        print("Empleados cargados.")

    def cargarPlanta(self):
        archivo = open('planta.csv')
        reader = csv.reader(archivo, delimiter = ';')
        cabecera = True
        for fila in reader:
            if cabecera:
                cabecera = False
            else:
                instancia = EmpleadoPlanta(str(fila[0]), str(fila[1]), str(fila[2]), str(fila[3]), float(fila[4]), int(fila[5]))
                self.__arregloEmpleados[self.__indice] = instancia
                self.__indice = self.__indice + 1
        archivo.close
        return

    def cargarContratados(self):
        archivo = open('contratados.csv')
        reader = csv.reader(archivo, delimiter = ';')
        cabecera = True
        for fila in reader:
            if cabecera:
                cabecera = False
            else:
                instancia = EmpleadoContratado(str(fila[0]), str(fila[1]), str(fila[2]), str(fila[3]), str(fila[4]), str(fila[5]), int(fila[6]))
                self.__arregloEmpleados[self.__indice] = instancia
                self.__indice = self.__indice + 1
        archivo.close
        return

    def cargarExternos(self):
        archivo = open('externos.csv')
        reader = csv.reader(archivo, delimiter = ';')
        cabecera = True
        for fila in reader:
            if cabecera:
                cabecera = False
            else:
                instancia = EmpleadoExterno(str(fila[0]), str(fila[1]), str(fila[2]), str(fila[3]), str(fila[4]), str(fila[5]), str(fila[6]), float(fila[7]), float(fila[8]), float(fila[9]))
                self.__arregloEmpleados[self.__indice] = instancia
                self.__indice = self.__indice + 1
        archivo.close
        return

    def mostrarCarga(self): #esta feo hecho, pero la idea es solo que muestre con el print arriba sin iterarlo, sé que estoy utilizando for demás
        print("\n")
        print("EMPLEADO DE PLANTA:")
        for emp in self.__arregloEmpleados:
            if isinstance(emp, EmpleadoPlanta):
                print(emp)

        print("\n")
        print("EMPLEADO CONTRATADO:")
        for emp in self.__arregloEmpleados:
            if isinstance(emp, EmpleadoContratado):
                print (emp)

        print("\n")
        print("EMPLEADO EXTERNO:")
        for emp in self.__arregloEmpleados:
            if isinstance(emp, EmpleadoExterno):
                print(emp)

    def buscarEmpleado(self, dni):
        indice = True
        i = 0
        while i < len(self.__arregloEmpleados) and indice:
            if self.__arregloEmpleados[i].getDNI() == dni:
                indice = False
                print("Lo encontramos! {}" .format(self.__arregloEmpleados[i].getDNI()))
            else:
                i = i + 1
        return i

    def registrarHoras(self, pos):
        #print("{}" .format(pos))
        if isinstance(self.__arregloEmpleados[pos], EmpleadoContratado):
            horas = int(input("Ingrese la cantidad de horas trabajadas: "))
            print("Horas trabajadas antes del registro: {}" .format(self.__arregloEmpleados[pos].getCantHTrabajadas()))
            self.__arregloEmpleados[pos].modificarHoras(horas)
            print("Horas trabajadas despues del registro: {}" .format(self.__arregloEmpleados[pos].getCantHTrabajadas()))
        else:
            print("El empleado no es contratado, por lo tanto no se puede realizar su registro de horas trabajadas.")

    def buscarTarea(self, tarea):
        indice = True
        i = 0
        while i < len(self.__arregloEmpleados) and indice:
            opcion = isinstance (self.__arregloEmpleados[i], EmpleadoExterno)
            if opcion:
                if self.__arregloEmpleados[i].getTarea() == tarea:
                    indice = False
                    print("Lo encontramos! {}" .format(self.__arregloEmpleados[i].getDNI()))
            else:
                i = i + 1
        return i

    def mostrarMonto(self, pos):
        fechaActual = str(input("Ingrese la fecha actual (formato: xx/xx/xxxx): "))
        if fechaActual > self.__arregloEmpleados[pos].getFechaFinalizacion():
            print("El monto a pagar por la tarea: {}, es: ${}" .format(self.__arregloEmpleados[pos].getTarea(), self.__arregloEmpleados[pos].getCostoObra()))
        else:
            print("Aun la tarea no finalizó.")

    def listarAyuda(self):
        print("LISTADO DE PERSONAS QUE LES CORRESPONDE LA AYUDA.")
        for emp in self.__arregloEmpleados:
            #print("SUELDO: {}" .format(emp.getSueldo()))
            if emp.getSueldo() < 150000:
                print("Nombre: {},  direccion: {}, DNI: {}" .format(emp.getNombre(), emp.getDireccion(), emp.getDNI()))

    def listarEmpleados(self):
        print("EMPLEADOS:")
        for emp in self.__arregloEmpleados:
            print("Nombre: {},  telefono: {}, sueldo: ${}" .format(emp.getNombre(), emp.getTelefono(), emp.getSueldo()))


import sys

sys.path.append("./EyesBot")
import ccxt
import ta
import pandas as pd
import numpy as np
from utilities.spot_ftx import SpotFtx
from utilities.custom_indicators import VMC, SuperTrend
from datetime import datetime
import time
import json

f = open(
    "./EyesBot/secret.json",
)
secret = json.load(f)
f.close()

timeframe = "1h"
account_to_select = "VMC"

params_coin = {
    "BTC/USD": {
        "wallet_exposure": 0.2,
        "wtChannelLen": 15,
        "wtAverageLen": 5,
        "wtMALen": 20,
        "rsiMFIperiod": 20,
        "rsiMFIMultiplier": 20,
        "rsiMFIPosY": 400
    },
    "SOL/USD": {
        "wallet_exposure": 0.2,
        "wtChannelLen": 15,
        "wtAverageLen": 5,
        "wtMALen": 25,
        "rsiMFIperiod": 20,
        "rsiMFIMultiplier": 20,
        "rsiMFIPosY": 400
    },
    "ETH/USD": {
        "wallet_exposure": 0.2,
        "wtChannelLen": 15,
        "wtAverageLen": 5,
        "wtMALen": 5,
        "rsiMFIperiod": 20,
        "rsiMFIMultiplier": 20,
        "rsiMFIPosY": 400
    },
    "APE/USD": {
        "wallet_exposure": 0.2,
        "wtChannelLen": 15,
        "wtAverageLen": 5,
        "wtMALen": 20,
        "rsiMFIperiod": 20,
        "rsiMFIMultiplier": 20,
        "rsiMFIPosY": 400
    },
    "AVAX/USD": {
        "wallet_exposure": 0.1,
        "wtChannelLen": 15,
        "wtAverageLen": 5,
        "wtMALen": 15,
        "rsiMFIperiod": 20,
        "rsiMFIMultiplier": 20,
        "rsiMFIPosY": 400
    },
    "ATOM/USD": {
        "wallet_exposure": 0.1,
        "wtChannelLen": 15,
        "wtAverageLen": 5,
        "wtMALen": 20,
        "rsiMFIperiod": 20,
        "rsiMFIMultiplier": 20,
        "rsiMFIPosY": 400
    },
}

if sum(d["wallet_exposure"] for d in params_coin.values() if d) > 1:
    raise ValueError("Wallet exposure must be less or equal than 1")

ftx = SpotFtx(
    apiKey=secret[account_to_select]["apiKey"],
    secret=secret[account_to_select]["secret"],
    subAccountName=secret[account_to_select]["subAccountName"],
)

now = datetime.now()
current_time = now.strftime("%d/%m/%Y %H:%M:%S")
print("Execution Time :", current_time)

open_orders = ftx.get_open_order()

for order in open_orders:
    order = order["info"]
    if float(order["filledSize"]) > 0:
        print(
            f"Order on {order['market']} is partially fill, create {order['side']} Market of {order['remainingSize']} {order['market']} order to complete it"
        )
        ftx.cancel_all_open_order(order["market"])
        ftx.place_market_order(order["market"], order["side"], order["remainingSize"])

df_list = {}
for pair in params_coin:
    params = params_coin[pair]
    ftx.cancel_all_open_order(pair)
    df = ftx.get_last_historical(pair, timeframe, 1000)
    # -- Populate indicators --
    def chop(high, low, close, window=14):
        tr1 = pd.DataFrame(high - low).rename(columns={0: 'tr1'})
        tr2 = pd.DataFrame(abs(high - close.shift(1))
                       ).rename(columns={0: 'tr2'})
        tr3 = pd.DataFrame(abs(low - close.shift(1))
                       ).rename(columns={0: 'tr3'})
        frames = [tr1, tr2, tr3]
        tr = pd.concat(frames, axis=1, join='inner').dropna().max(axis=1)
        atr = tr.rolling(1).mean()
        highh = high.rolling(window).max()
        lowl = low.rolling(window).min()
        chop_serie = 100 * np.log10((atr.rolling(window).sum()) /
                          (highh - lowl)) / np.log10(window)
        return pd.Series(chop_serie, name="CHOP")

    svmc = VMC(
        df["self"],
        df["open"],
        df["high"],
        df["low"],
        df["close"],
        params["wtChannelLen"],
        params["wtAverageLen"],
        params["wtMALen"],
        params["rsiMFIperiod"],
        params["rsiMFIMultiplier"],
        params["rsiMFIPosY"]
    )

    df['HLC3'] = (df['high'] +df['close'] + df['low'])/3
    vmc = VMC(high =df['high'],low = df['low'],close=df['HLC3'],open=df['open'])
    df['VMC_WAVE1'] = svmc.wave_1()
    df['VMC_WAVE2'] = svmc.wave_2()
    vmc = VMC(high =df['high'],low = df['low'],close=df['close'],open=df['open'])
    df['MONEY_FLOW'] = svmc.money_flow()
    df['EMA50'] = ta.trend.ema_indicator(close = df['close'], window = 50)
    df['EMA200'] = ta.trend.ema_indicator(close = df['close'], window = 200)
    df["CHOP"] = chop(df['high'],df['low'],df['close'],window=14)
    df['ema1'] = ta.trend.ema_indicator(close = df['close'], window = 5) # Moyenne exponentielle 1
    df_list[pair] = df

coin_balance = ftx.get_all_balance()
coin_in_usd = ftx.get_all_balance_in_usd()
usd_balance = coin_balance["USD"]
del coin_balance["USD"]
del coin_in_usd["USD"]
total_balance = usd_balance + sum(coin_in_usd.values())
available_wallet_pct = 1

positions = []
for coin in coin_in_usd:
    if coin_balance[coin] > float(ftx.get_min_order_amount(coin + "/USD")):
        positions.append(coin + "/USD")
        available_wallet_pct -= params_coin[coin + "/USD"]["wallet_exposure"]

pair_to_check = list(set(params_coin.keys()) - set(positions))
#Achat
for pair in pair_to_check:
    # iloc -2 to get the last completely close candle
    row = df_list[pair].iloc[-2]
    previousRow = df_list[pair].iloc[-3]
    if row['EMA50'] > row ['EMA200'] and row ['close'] > row['EMA50']  and row['MONEY_FLOW'] >  0 and row['VMC_WAVE1'] < 0 and row['VMC_WAVE2'] < 0 and row['VMC_WAVE1'] > row['VMC_WAVE2'] and previousRow['VMC_WAVE1'] < previousRow['VMC_WAVE2'] and row['CHOP'] <50: #ligne choix achat
        buy_limit_price = float(ftx.convert_price_to_precision(pair, row["ema1"]))
        buy_quantity_in_usd = usd_balance * (
            params_coin[pair]["wallet_exposure"] / available_wallet_pct
        )
        buy_quantity = float(
            ftx.convert_amount_to_precision(pair, buy_quantity_in_usd / buy_limit_price)
        )
        exchange_buy_quantity = buy_quantity * buy_limit_price
        print(
            f"Place Buy Limit Order: {buy_quantity} {pair[:-4]} at the price of {buy_limit_price}$ ~{round(exchange_buy_quantity, 2)}$"
        )
        ftx.place_limit_order(pair, "buy", buy_quantity, buy_limit_price)
#Vente
for pair in positions:
    row = df_list[pair].iloc[-2]
    if row["EMA50"] < row["EMA200"] and row['CHOP'] >50:
        sell_limit_price = float(ftx.convert_price_to_precision(pair, row["ema"]))
        sell_quantity = float(
            ftx.convert_amount_to_precision(pair, coin_balance[pair[:-4]])
        )
        exchange_sell_quantity = sell_quantity * sell_limit_price
        print(
            f"Place Sell Limit Order: {sell_quantity} {pair[:-4]} at the price of {sell_limit_price}$ ~{round(exchange_sell_quantity, 2)}$"
        )
        ftx.place_limit_order(pair, "sell", sell_quantity, sell_limit_price)

new_coin_in_usd = ftx.get_all_balance_in_usd()
new_coin_in_usd = {x: y for x, y in new_coin_in_usd.items() if y != 0}
for coin in new_coin_in_usd:
    new_coin_in_usd[coin] = str(round(new_coin_in_usd[coin], 2)) + " $"
print("My current balance in USD:", new_coin_in_usd)


for num in range(2, 36):
    factors = 0
    for divisor in range(2, num):
        if num % divisor == 0:
            factors += 1
    if factors == 0:
        print(num)

def combo_colors(c1, c2):
    primary_colors = ['red', 'blue', 'yellow']
    if (c1 == 'red' and c2 == 'blue') or (c1 == 'blue' and c2 == 'red'):
        return 'purple'
    elif (c1 == 'red' and c2 == 'yellow') or (c1 == 'yellow' and c2 == 'red'):
        return 'orange'
    elif (c1 == 'blue' and c2 == 'yellow') or (c1 == 'yellow' and c2 == 'blue'):
        return 'green'
c1 = 'red'
c2 = 'blue'
result = combo_colors(c1, c2)
print(f"{c1} and {c2}.")


#!/usr/bin/env python3

import os
import tempfile

from testsupport import (
    run,
    subtest,
    warn,
    test_root,
    run_project_executable,
    ensure_library,
)

def main() -> None:
    # Run the test program
    lib = ensure_library("liblockfreelinkedlist.so")
    extra_env = {"LD_LIBRARY_PATH": str(os.path.dirname(lib))}
    test_lockfreelinkedlist = test_root().joinpath("test_lockfreelinkedlist")

    if not test_lockfreelinkedlist.exists():
        run(["make", "-C", str(test_root()), str(test_lockfreelinkedlist)])

    with tempfile.TemporaryDirectory() as tmpdir:
        with subtest("Checking lock free linked list"):
            with open(f"{tmpdir}/stdout", "w+") as stdout:
                run_project_executable(
                    str(test_lockfreelinkedlist),
                    stdout=stdout,
                    extra_env=extra_env,
                )

if __name__ == "__main__":
    main()