from pathlib import Path
import iprPy
import shutil
import pypandoc
import inspect

def main():

    buildcalculations()
    copynotebooks()

def buildcalculations():
    """Builds doc/source pages for all calculation styles implemented in iprPy"""

    # Find root iprPy directory
    rootdir = Path(inspect.getfile(iprPy)).parent

    # Specify path to Python code for the iprPy.calculations submodule
    pypath = Path(rootdir, 'calculation')
    if not pypath.exists():
        raise ValueError(pypath.as_posix())

    # Specify relative path to doc/source folder for calculations
    docpath = Path(rootdir, '..', 'doc', 'source', 'calculation')

    # Remove existing doc source
    if docpath.is_dir():
        cleantree(docpath)

    # Loop over all implemented calculation styles
    for name in iprPy.calculationmanager.loaded_style_names:
        print(name, flush=True)
        calc = iprPy.load_calculation(name)

        pydir = Path(pypath, name)
        docdir = Path(docpath, name)
        docdir.mkdir(parents=True)

        # Verify calculation is a submodule
        if pydir.is_dir():

            # Create index.rst
            with open(Path(docdir, 'index.rst'), 'w', encoding='UTF-8', newline='\n') as f:
                f.write(calc_index(calc))

            # Create doc.rst
            with open(Path(docdir, 'doc.rst'), 'w', encoding='UTF-8', newline='\n') as f:
                f.write(calc_doc(calc))

            # Create template.rst
            with open(Path(docdir, 'template.rst'), 'w', encoding='UTF-8', newline='\n') as f:
                f.write(calc_template(calc))

            # Create function.rst
            with open(Path(docdir, 'function.rst'), 'w', encoding='UTF-8', newline='\n') as f:
                f.write(calc_function(calc))

            # Create class.rst
            with open(Path(docdir, 'class.rst'), 'w', encoding='UTF-8', newline='\n') as f:
                f.write(calc_class(calc))

def calc_index(calc):
    """Generates the index.rst content for a calculation style"""

    content = '\n'.join([
        calc.calc_style,
        '=' * len(calc.calc_style),
        '',
        '.. toctree::',
        '    :maxdepth: 1',
        '',
        '    doc',
        '    template',
        '    function',
        '    class',
    ])
    return content

def calc_function(calc):
    """Generates the function.rst content for a calculation style"""

    content = '\n'.join([
        Path(inspect.getfile(calc.calc)).name,
        '=' * len(Path(inspect.getfile(calc.calc)).name),
        '',
        'Calculation functions',
        '---------------------',
        f'.. automodule:: {calc.calc.__module__}',
        '    :members:',
        '    :undoc-members:',
        '    :show-inheritance:',
    ])

    return content

def calc_class(calc):
    """Generates the class.rst content for a calculation style"""

    content = '\n'.join([
        calc.__module__.split('.')[-1],
        '=' * len(calc.__module__.split('.')[-1]),
        '',
        'Calculation class',
        '-----------------',
        f'.. automodule:: {calc.__module__}',
        '    :members:',
        '    :undoc-members:',
        '    :show-inheritance:',
    ])

    return content

def calc_doc(calc):
    content = (pypandoc.convert_text(calc.maindoc, 'rst', format='md', encoding='UTF-8') + '\n' +
               pypandoc.convert_text(calc.theorydoc, 'rst', format='md', encoding='UTF-8'))

    return content

def calc_template(calc):
    return pypandoc.convert_text(calc.templatedoc, 'rst', format='md', encoding='UTF-8')

def copynotebooks():

    # Find root iprPy directory
    rootdir = Path(inspect.getfile(iprPy)).parent

    # Specify path to Jupyter Notebooks
    pypath = Path(rootdir, '..', 'notebook')

    # Specify relative path to doc/source folder for database
    docpath = Path(rootdir, '..', 'doc', 'source', 'notebook')

    # Remove existing doc source
    if docpath.is_dir():
        cleantree(docpath)

    for oldpath in pypath.glob('*/* - Methodology and code.ipynb'):
        oldname = oldpath.name
        newname = oldname.replace(' - Methodology and code', '').replace(' ', '_')
        #newname = oldname.replace(' ', '_')
        print(newname)
        newpath = Path(docpath, newname)
        shutil.copy(oldpath, newpath)

def cleantree(path):
    """Removes content in the existing directory."""

    # Try rmtree up to 10 times
    for i in range(10):
        if path.is_dir():
            try:
                shutil.rmtree(path)
            except:
                pass
            else:
                break
    path.mkdir(parents=True)

if __name__ == '__main__':
    main()


a = input().split()

n = int(a[0])
k = int(a[1])

masVal = [[0]*n for i in range(k)]

for i in range(k):
    a = input().split()
    for j in range(n):
        masVal[i][j] = int(a[j])

correctCol = list(range(0, n, 1))
ansTrue = 0

while (len(masVal) != 0 and not(ansTrue)):
    singleNum = -1
    singleNumCol = -1

    for i in range(len(masVal)):
        coun = 0
        for j in correctCol:
            if (masVal[i][j] != -1):
                coun+=1
                singleNum = masVal[i][j]
                singleNumCol = j
        if (coun == 1):
            coun = -1
            break

    #print(singleNumCol)
    if (coun == -1):
        i = 0
        while (i < len(masVal)):
            if (masVal[i][singleNumCol] == singleNum):
                del masVal[i]
                i-=1
            elif (1 - masVal[i][singleNumCol] == singleNum):
                singleFalse = 1
                for j in correctCol:
                    if (masVal[i][j] != -1 and j != singleNumCol):
                        singleFalse = 0
                if (singleFalse):
                    ansTrue = 1
            i += 1
        correctCol.remove(singleNumCol)

    if (coun != -1):
        break

if (ansTrue):
    print("YES")
else:
    print("NO")

#print(*masVal)
#print()
#print(*correctCol)


class Text:
    def __init__(self):
        self.textmenu = ['Главное меню:',
                         'Сохранить заметки',
                         'Загрузить заметки',
                         'Добавить заметку',
                         'Вывести краткий список заметок',
                         'Вывести заметки на дату',
                         'Вывести подробную информацию по заметке',
                         'Редактировать заметку',
                         'Удалить заметку',
                         'Выход']
        self.input_message = 'Выберите пункт меню: '
        self.find_note_by_date = '\nВывод списка заметок по дате: '
        self.find_note_by_id = '\nВывод подробной информации заметки по id: '
        self.show_note_info = '\nПодробная информация по заметке:\n'
        self.input_date = '\nВведите дату в формате [dd-mm-yyyy]: '
        self.input_note = ['\nВведите заголовок заметки: ',
                           'Введите тело заметки: ']
        self.input_uid = '\nВведите id заметки: '
        self.exit_message = '\n!!!До свидания!!!'
        self.empty_notes_list = 'Список заметок пуст'
        self.show_notes_list_short = '\n!!!Полный список заметок!!!'
        self.show_notes_list = '\n!!!Список заметок!!!'
        self.add_note = '\n!!!Добавление заметки!!!'
        self.remove_note = '\n!!!Удаление заметки!!!'
        self.edit_note = '\n!!!Редактирование заметки!!!'
        self.input_uid_digit_error = '\nВведенное значение не является числом'
        self.add_note_successful = '\nЗаметка успешно добавлена'
        self.remove_note_successful = '\nЗаметка успешно удалена'
        self.edit_note_successful = '\nЗаметка успешно изменена'
        self.notes_save_successful = '\nЗаметки успешно сохранены'

    def input_uid_find_error(self, uid: int) -> str:
        return f'\nЗаметка с id = {(uid)} не найдена. Проверьте id заметки и повторите действие'

    def input_menu_error(self) -> str:
        return f'Введено недопустимое значение: выберите пункт от 1 до {len(self.textmenu)-1}'


import json

from sklearn.model_selection import train_test_split

def save_data(data_dir: str, data_type: str, xs: list, ys: list):
    with open(data_dir.format(data_type), 'w', encoding="utf-8") as fsw:
        for ind, x_data_line in enumerate(xs):
            y_data_line = ys[ind]
            fsw.write(f"{''.join(x_data_line)}\t{''.join(y_data_line)}\n")

            if len(list(x_data_line)) != len(list(y_data_line)):
                print(x_data_line)

def save_json_data(data_dir: str, data_type: str, lines: list):
    with open(data_dir.format(data_type), 'w', encoding="utf-8") as fsw:
        for ind, json_line in enumerate(lines):
            fsw.write(json_line.strip() + "\n")

train_file_path = r"Z:/research/data/biendata/ccks2019_el/ccks2019_el/train.json"

data_dir = r"D:\data\biendata\ccks2019_el\ccks_train_data\{}.json"

inds = []
lines = []

with open(train_file_path, 'r', encoding='utf-8') as all_trains:
    for line_ind, json_line in enumerate(all_trains):
        inds.append(line_ind)
        lines.append(json_line)

inds_train, inds_o, lines_train, lines_o = train_test_split(inds, lines, test_size=0.3)

inds_val, inds_test, lines_val, lines_test = train_test_split(inds_o, lines_o, test_size=0.5)

# save_data(data_dir, "train", x_train, y_train)
# save_data(data_dir, "validate", x_val, y_val)
# save_data(data_dir, "test", x_test, y_test)

save_json_data(data_dir, "train", lines_train)
save_json_data(data_dir, "validate", lines_val)
save_json_data(data_dir, "test", lines_test)


from woeman import brick, Brick

@brick
class KenLM(Brick):
    """KenLM language model estimator"""

    mosesDir = None  #: path containing bin/lmplz

    def __init__(self, corpus):
        """
        :param corpus: tokenized training corpus
        """
        Brick.__init__(self)

    def output(self, languageModel):
        """
        :param languageModel: binarized KenLM
        """
        pass

    def configure(self, ngramOrder=5, prune="0 0 1", otherOptions=None):
        """
        :param ngramOrder:   n-gram order
        :param prune:        "0 0 1" means prune singleton trigrams and above
        :param otherOptions: additional lmplz options dict (e.g. 'discount_fallback' for small corpora)
        """
        if otherOptions is None:
            otherOptions = {}

        extraOptions = ''
        for key in otherOptions:
            if key == 'discount_fallback':
                extraOptions += ' --discount_fallback'
            else:
                raise ValueError('KenLM: unsupported extraOptions key "%s"' % key)

        self.extraOptions = extraOptions
        del otherOptions  # avoid adding these to the object below.
        # (note: the local extraOptions will also redundantly be copied to self.extraOptions again)
        Brick.configure(self, locals())


import pathlib
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras import backend
from functions import *
###############
#signal2 --> data1 predictions / lo
#signal --> data2 predictions / lo2
#signal1 --> data3 predictions / lo3
###############

#encode outlier year
lo = np.zeros((270,3))
lo[0:22,0] = 1
lo[22:210,1] = 1
lo[210:240,2] = 1
lo[240:270,1] = 1

lo2 = np.zeros((270,3))
lo2[38:60,0] = 1
lo2[18:30,0] = 1
lo2[208:230,2] = 1
lo2[60:208,1] = 1
lo2[230:270,1] = 1

lo3 = np.zeros((266,3))
lo3[190:226,0] = 1
lo3[0:38,1] = 1
lo3[65:190,1] = 1
lo3[226:245,1] = 1
lo3[245:266,2] = 1
lo3[38:65,2] = 1

#simple binar classifcation model
def build_model_outlier(input_shape):
    model = keras.Sequential([
            layers.Dense(4, activation='relu', input_shape=(input_shape)),
            layers.Dense(4, activation='relu'),
            layers.Dense(3, activation='softmax')
        ])

    optimizer = tf.keras.optimizers.Adam()

    model.compile(loss='mse',
                  optimizer=optimizer,
                  metrics=['mae', 'mse'])

    return model

tf.keras.backend.clear_session()

outlier_predictor = build_model_outlier((10,))

outlier_predictor.fit(signal2,
                  lo,
                  epochs=1000,
                  batch_size=32,
                  validation_split=0.2,
                  verbose=1,
                  shuffle=False,
                  callbacks=[reduce_lr, early_stop])

outlier_predictor.fit(signal,
                  lo2,
                  epochs=1000,
                  batch_size=32,
                  validation_split=0.2,
                  verbose=1,
                  shuffle=False,
                  callbacks=[reduce_lr, early_stop])

outlier_predictor.fit(signal1,
                  lo3,
                  epochs=1000,
                  batch_size=32,
                  validation_split=0.2,
                  verbose=1,
                  shuffle=False,
                  callbacks=[reduce_lr, early_stop])

#test predictions

predictions_alpha = outlier_predictor.predict(signal1)
predictions_beta = outlier_predictor.predict(signal2)
predictions_gamma = outlier_predictor.predict(signal)

predict_data3 = plt.figure()
plt.plot(predictions_alpha[:,1])
plt.plot(lo3[:,1])
plt.plot(labels3)

predict_data1 = plt.figure()
plt.plot(predictions_beta[:,0])
plt.plot(lo[:,0])
plt.plot(labels1)

predict_data2 = plt.figure()
plt.plot(predictions_gamma[:,0])
plt.plot(lo2[:,0])
plt.plot(labels2)


number_of_people = int(input())
number_of_nights = int(input())
transport_cards_number = int(input())
museum_tickets_number = int(input())

nights = number_of_nights * 20
transport_cards = transport_cards_number * 1.60
museum_tickets = museum_tickets_number * 6
total_price_per_person = nights + transport_cards + museum_tickets
total_group_price = total_price_per_person * number_of_people
other_costs = total_group_price * 0.25 + total_group_price
print(f"{other_costs:.2f}")


from __future__ import absolute_import
from st2tests.base import CleanDbTestCase
from st2common.models.db.pack import PackDB
from st2common.models.db.action import ActionDB
from st2common.persistence.pack import Pack
from st2common.persistence.action import Action

class UIDMixinTestCase(CleanDbTestCase):
    def test_get_uid(self):
        pack_1_db = PackDB(ref="test_pack")
        pack_2_db = PackDB(ref="examples")

        self.assertEqual(pack_1_db.get_uid(), "pack:test_pack")
        self.assertEqual(pack_2_db.get_uid(), "pack:examples")

        action_1_db = ActionDB(
            pack="examples", name="my_action", ref="examples.my_action"
        )
        action_2_db = ActionDB(pack="core", name="local", ref="core.local")
        self.assertEqual(action_1_db.get_uid(), "action:examples:my_action")
        self.assertEqual(action_2_db.get_uid(), "action:core:local")

    def test_uid_is_populated_on_save(self):
        pack_1_db = PackDB(
            ref="test_pack",
            name="test",
            description="foo",
            version="1.0.0",
            author="dev",
            email="test@example.com",
        )
        pack_1_db = Pack.add_or_update(pack_1_db)
        pack_1_db.reload()

        self.assertEqual(pack_1_db.uid, "pack:test_pack")

        action_1_db = ActionDB(
            name="local",
            pack="core",
            ref="core.local",
            entry_point="",
            runner_type={"name": "local-shell-cmd"},
        )
        action_1_db = Action.add_or_update(action_1_db)
        action_1_db.reload()

        self.assertEqual(action_1_db.uid, "action:core:local")


from PIL import ImageGrab
from paddleocr import PaddleOCR
import re
from pydirectinput import press
import logging
from win32gui import FindWindow, GetWindowRect
from configparser import ConfigParser
from time import sleep, time
import logging
from pyautogui import getAllTitles
from os.path import exists
from warnings import filterwarnings
if __name__ != "__main__":
    from NSRPAutoMeth.constants import QUESTION_ANSWERS
    from NSRPAutoMeth.game_controller import GameController

class NSRPAutoMeth:
    """
    Class contains the main bot loop and manages the bots state.

    Methods
    -------
    start()
        Starts the main loop of the bot
    __setup()
        Sets up the bot
    __tick()
        Manages the bot state, called every set interval
    __getText()
        Takes screenshot of screen and returns text detected
    __getProductionPercent(imageText: str)
        Returns production time found in given text
    __getQuestion(imageText: str)
        Returns question found in given text
    """
    __consecutiveFailedTicks = 0
    __cooking = False

    def __getText(self) -> str:

        """Finds text within left half of screen

        Returns
        -------
        str
            The text found within left half of window
        """
        if self.use_game_window[0] == "t": # if using game window to take screenshot
            # get window size
            window_handle = FindWindow(None, self.window_name)
            window_rect   = GetWindowRect(window_handle)
            # screenshot left half of screen
            logging.debug("Window rect: " + str(window_rect))
            img = ImageGrab.grab(bbox=(window_rect[0], window_rect[1], window_rect[2] / 3, window_rect[3]))
        else: # screenshot and crop to left half
            img = ImageGrab.grab(bbox=(0, self.resolution_y/5, self.resolution_x / 3, self.resolution_y))
        # save image
        img.save("last-screenshot.png")
        return " ".join(re.findall(r"'(.*?)'", str(self.__ocr.ocr('last-screenshot.png', cls=True))))

    def __getProductionPercent(self, text: str) -> str:
        """Returns production time of found in given text

        Parameters
        ----------
        text : str
            The text to find production percentage in

        Returns
        -------
        str
            The production percentage found within given text
        """
        productionPercent = re.search(r"\d+(?=%)", text)
        if productionPercent is None:
            return None
        return productionPercent.group(0)

    def __getQuestion(self, text: str) -> str:
        """Finds question in given text

        Parameters
        ----------
        text : str
            The text to find question in

        Returns
        -------
        str
            The key to  a question found within text, if one is found
        """
        for question in QUESTION_ANSWERS:
            if question in text:
                return question

    def __answerQuestion(self, question: str, text: str) -> None:
        """Finds question's answer, then presses corresponding number

        Parameters
        ----------
        text : str
            The text to find answer in
        question : str
            The question to answer
        """
        answer = QUESTION_ANSWERS[question]
        try:
            answerIndex = text.index(answer)
        except ValueError:
            logging.warning(
                "Answer not found in text after question was found")
            return
        number = text[answerIndex - 3]
        press(number)*3
        logging.info(f'Answered Question: "{question}"')

    def __check_for_information(self, text) -> bool:
        """Checks for question or production percentage within left half of screen"""
        flag = False
        question = self.__getQuestion(text)
        if question is not None:
            self.__answerQuestion(question, text)
            flag = True
        if "production:" in text: # production percent
            productionPercent = self.__getProductionPercent(text)
            if productionPercent == None:
                logging.warning("Production percent failed, 'production:' found but no percent")
            else:
                logging.info(f"Production: {productionPercent}%")
                flag = True
        return flag

    def __tick(self) -> None:
        """ Runs every tick managing the bots state"""
        if not self.__cooking:
            self.game_controller.startCook()
            self.__cooking = True
            logging.info("Started cook")
            return
        text = self.__getText()
        found_info = self.__check_for_information(text)
        # log if tick found info question or production percentage
        if found_info:
            self.__consecutiveFailedTicks = 0
        else:
            logging.warning("No question or production percent detected")
            logging.debug("Detected Text: " + text)
            self.__consecutiveFailedTicks += 1
        # if over five failed ticks then restart
        if self.__consecutiveFailedTicks > 5:
            logging.warning("Restarting cook, 5 failed ticks")
            self.__cooking = False
            self.__consecutiveFailedTicks = 0
            self.game_controller.moveBackToFront()

    def __setup(self):
        """ Sets up the bots logging and loads the settings config file """
        # clear current log setup
        for handler in logging.root.handlers[:]:
            logging.root.removeHandler(handler)
        logging.basicConfig(
            filename="log.txt",
            level=logging.NOTSET,
            format="%(asctime)s:%(levelname)s:%(message)s")
        logging.getLogger().addHandler(logging.StreamHandler()) # print log to console
        parser = ConfigParser()
        if not exists("settings.ini"):
            logging.error("settings.ini not found")
            exit()
        parser.read('settings.ini')
        self.tick_interval: int = int(parser.get('Basic', 'tick_interval'))
        self.countdown = int(parser.get('Basic', 'countdown'))
        self.window_name = parser.get('Setup', 'window_name')
        self.game_controller = GameController(parser)
        self.window_exist_check = parser.get('Debug', 'window_exist_check')
        self.use_game_window = parser.get('Debug', 'use_game_window')
        self.resolution_x, self.resolution_y = parser.get('Debug', 'resolution').split("x")
        self.resolution_y = int(self.resolution_y.split(" ")[0])
        self.resolution_x = int(self.resolution_x)
        clear_log = parser.get('Debug', 'clear_log')
        if clear_log[0] == "t":
            open("log.txt", "w").close() # clear log.txt
        logging.root.setLevel(
            getattr(logging, parser.get('Debug', 'log_level').split(" ")[0].upper(), None))
        filterwarnings(action='ignore', category=DeprecationWarning, message='`np.bool8` is a deprecated alias for `np.bool_')
        logging.debug("Setup complete")

    def start(self):
        """
            Starts the bot
        """
        print("Setting up...")
        self.__ocr = PaddleOCR(use_angle_cls=True, lang='en', show_log=False)
        self.__setup()
        # check if game window is open
        if self.window_exist_check[0] == "t"  and self.window_name not in getAllTitles():
            logging.error("Game window not found, check settings.ini or disable check")
            exit()
        # countdown to start from 10
        for i in range(self.countdown, 0, -1):
            logging.info("Starting in: " + str(i))
            sleep(1)
        # main loop
        while True:
            self.__tick()
            curr_time = time()
            sleep(self.tick_interval - (time() - curr_time))


from django.contrib import auth
from rest_framework import viewsets, mixins, response, status

from . import serializers

class SessionViewSet(viewsets.GenericViewSet,
                     mixins.CreateModelMixin):
    def get_serializer_class(self):
        serializer_class = None

        if self.action == 'list':
            serializer_class = serializers.UserSerializer
        else:
            serializer_class = serializers.SessionSerializer

        return serializer_class

    def list(self, request, *args, **kwargs):
        if request.user.is_anonymous:
            return response.Response(status=status.HTTP_404_NOT_FOUND)
        else:
            serializer = self.get_serializer(request.user)
            return response.Response(serializer.data)


prime_numbers = []
number_id = 1
for i in range(1547341, 1547410):
    n = i
    divs = [1, i]
    k = 2
    while k * k <= n:
        if n % k == 0:
            divs.append(k)
            k_ch = n // k
            if k_ch != k:
                divs.append(k_ch)
        k += 1
    if len(divs) == 2:
        print(number_id, i)
        number_id += 1


import json
from typing import (
    Dict,
    Iterator,
    Union,
    List,
    Any,
    Tuple
)
from urllib.parse import urlencode
from hedra.core.engines.types.common.base_action import BaseAction
from hedra.core.engines.types.common.constants import NEW_LINE
from hedra.core.engines.types.common.hooks import Hooks
from hedra.core.engines.types.common import URL
from hedra.core.engines.types.common.encoder import Encoder
from hedra.core.engines.types.common.types import RequestTypes
from hedra.core.engines.types.http2.streams.stream_settings import Settings

class HTTP2Action(BaseAction):

    __slots__ = (
        'action_id',
        'method',
        'type',
        'url',
        'protocols',
        '_headers',
        '_data',
        'encoded_data',
        'encoded_headers',
        'is_stream',
        'ssl_context',
        'hpack_encoder',
        '_remote_settings',
        'event',
        'action_args',
        '_header_items',
        'mutations'
    )

    def __init__(
        self,
        name: str,
        url: str,
        method: str = 'GET',
        headers: Dict[str, str] = {},
        data: Union[str, dict, Iterator, bytes, None] = None,
        user: str=None,
        tags: List[Dict[str, str]] = []
    ) -> None:
        super(HTTP2Action, self).__init__(
            name,
            user,
            tags
        )

        self.method = method.upper()
        self.type = RequestTypes.HTTP2

        address_family, protocol = self.protocols[self.type]
        self.url = URL(url, family=address_family, protocol=protocol)

        self._headers = headers
        self._header_items: List[Tuple[str, str]] = list(headers.items())
        self._data = data

        self.encoded_data = None
        self.encoded_headers = None
        self.is_stream = False
        self.ssl_context = None
        self.hpack_encoder = Encoder()
        self._remote_settings = Settings(
            client=False
        )

        self.hooks: Hooks[HTTP2Action] = Hooks()
        self.action_args: Dict[str, Any] = {}

    @property
    def size(self):
        if self.encoded_data:
            return len(self.encoded_data)

        else:
            return 0

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, value):
        self._data = value
        self.encoded_data = None

    @property
    def headers(self):
        return self._headers

    @headers.setter
    def headers(self, value: Dict[str, str]):
        self._headers = value
        self._header_items = list(value.items())
        self.encoded_headers = None

    def setup(self):

        if self.encoded_data is None:
            self._setup_data()

        if self.encoded_headers is None:
            self._setup_headers()

    def _setup_data(self):
        if self._data:
            if isinstance(self._data, Iterator):
                chunks = []
                for chunk in self._data:
                    chunk_size = hex(len(chunk)).replace("0x", "") + NEW_LINE
                    encoded_chunk = chunk_size.encode() + chunk + NEW_LINE.encode()
                    self.size += len(encoded_chunk)
                    chunks.append(encoded_chunk)

                self.is_stream = True
                self.encoded_data = chunks

            else:

                if isinstance(self._data, dict):
                    self.encoded_data = json.dumps(
                        self._data
                    ).encode()

                elif isinstance(self._data, tuple):
                    self.encoded_data = urlencode(
                        self._data
                    ).encode()

                elif isinstance(self._data, str):
                    self.encoded_data = self._data.encode()

    def _setup_headers(self) -> Union[bytes, Dict[str, str]]:

        encoded_headers = [
            (b":method", self.method),
            (b":authority", self.url.authority),
            (b":scheme", self.url.scheme),
            (b":path", self.url.path),
        ]

        encoded_headers.extend([
            (
                k.lower(),
                v
            )
            for k, v in self._header_items
            if k.lower()
            not in (
                b"host",
                b"transfer-encoding",
            )
        ])

        encoded_headers = self.hpack_encoder.encode(encoded_headers)
        self.encoded_headers = [
            encoded_headers[i:i+self._remote_settings.max_frame_size]
            for i in range(
                0, len(encoded_headers), self._remote_settings.max_frame_size
            )
        ]


#!/usr/bin/env python

# import the necessary packages
import rospy
from sensor_msgs.msg import Image, CameraInfo
import cv2, cv_bridge
from collections import deque
import numpy as np
import argparse
import math
import time
import os
from std_msgs.msg import String

class Movement:

    #the range of colors that will be processed
    color_lower = (150, 45, 150)
    color_upper = (170, 250, 255)

    buffer_size = 2048

    minimum_contour_radius = 10

    blur_strength = 11

    def __init__(self):
        self.bridge = cv_bridge.CvBridge()
        #cv2.namedWindow("window",1)
        self.image_sub = rospy.Subscriber('camera/rgb/image_raw', Image,
            self.image_callback)

        self.pts = deque(maxlen=self.buffer_size)
        #adds global variable to save the last frame allowing for compaison
        self.last_circle = None

    def convert_and_preprocess(self, image_msg):
        """
        Convert a ROS image messge to OpenCV format and HSV color.
        """
        frame = self.bridge.imgmsg_to_cv2(image_msg, desired_encoding= 'bgr8')
        #blurred = cv2.GaussianBlur(frame, (11, 11), 0)
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        return frame, hsv

    def mask_and_despeckle(self, hsv_image):
        """
        construct a mask for the color "green", then perform
        a median blur to get rid of small speckles
        """
        mask = cv2.inRange(hsv_image, self.color_lower, self.color_upper)
        mask = cv2.medianBlur(mask, self.blur_strength)
        return mask

    #returns a list of circles
    #filters out small areas
    def filter_by_radius(self, contours):
        return [contour for contour in contours if contour[1] > self.minimum_contour_radius]

    def location(self, place_pixels):
        #takes a integer representing the number of pixels
        #returns place on screen by placement of x pixels
        if place_pixels < 200:
            #return place_pixels
            return "The correct shell is on the right."
        if 200 < place_pixels < 420:
            #return place_pixels
            return "The correct shell is in the middle."
        if place_pixels > 420:
            #return place_pixels
            return "The correct shell is on the left"

    def decompose_circle(self, circle):
        #takes a circle
        #returns a tuple of x, y, radius
        return circle[0][0], circle[0][1], circle[1]

    def Distance_Between(self, circle1, circle2):
        #finds the distance between two circles
        #returns the distance
        cir1 = self.decompose_circle(circle1)
        cir2 = self.decompose_circle(circle2)
        squared = (cir1[0] - cir2[0])**2 + (cir1[1] - cir2[1])**2
        return squared**.5

    def match_circles(self, last, new_circles):
        #finds the closest circle off of the last frame captured
        ((last_x, last_y), last_radius) = last

        def distance_to(new_circle):
            ((new_x, new_y), new_radius) = new_circle
            return (new_x - last_x)**2 + (new_y - last_y)**2

        new_circles.sort(key=distance_to)
        return new_circles[0]

    def image_callback(self, msg):
        img, hsv = self.convert_and_preprocess(msg)
        mask = self.mask_and_despeckle(hsv)
        cv2.imshow("mask", mask)

        # find contours in the mask
        contours = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
            cv2.CHAIN_APPROX_SIMPLE)[-2]

        new_circles = [cv2.minEnclosingCircle(contour) for contour in contours]

        new_circles = self.filter_by_radius(new_circles)

        if self.last_circle == None:
            if new_circles:
                self.last_circle = new_circles[0]
            else:
                return
        else:
            if new_circles:
                potential = self.match_circles(self.last_circle, new_circles)
                dist = self.Distance_Between(potential, self.last_circle)
                if dist < 100:
                    self.last_circle = potential

        ((x,y), radius) = self.last_circle
        center = int(x), int(y)
        cv2.circle(img, center, int(radius),
            (0, 255, 255), 2)
        cv2.circle(img, center, 5, (0, 0, 255), -1)

        cv2.imshow("circles", img)
        key = cv2.waitKey(1)

rospy.init_node('movement')
movement = Movement()
rospy.spin()


import numpy as np
from src.agents.action_value_learners.tabular_AV_learners.tabular_AV import TabularAV

class MonteCarlo(TabularAV):
    REQUIRES_FINITE_STATE_SPACE = True

    def should_update(self, done: bool) -> bool:
        return done

    # To be called only when self._memory has > self._batch_size items
    def update(self):
        states, actions, rewards, next_states, dones = self._memory.sample(sample_all=True,
                                                                           as_torch=False)
        assert int(dones[-1]) == 1, dones
        assert not np.any(dones[:-2]), dones
        T = len(rewards)
        returns = np.zeros(T)
        returns[-1] = rewards[-1]
        # sets rewards[-2], rewards[-3], ...., rewards[1], rewards[0]
        for t in range(T - 2, -1, -1):
            returns[t] = rewards[t] + (self._gamma * returns[t + 1])
        # for a,b,c in zip(rewards, returns,actions):
        #     print("|", a,b,c)
        assert len(returns) == len(rewards), (returns, rewards)
        # First visit
        seen = []

        for t in range(T):
            state = self.get_hashable_state(states[t])
            action = (actions[t])
            if True:  # (state, action) not in seen
                seen.append((state, action))
                ret = (returns[t])
                # print(f"{state:1.0f}, {action:1.0f}, " + f"{ret:2.2f}".zfill(5))
                n = self._Q_count[state][action]
                self._Q_count[state][action] += 1
                prev = float(self._Q[state][action])
                self._Q[state][action] += (ret - prev) / (n + 1)


# Authors: Fangyu Wu (fwu10@illinois.edu)
# Date: Dec 30th, 2016
# Script to extract displacements, velocities, and accelerations from panoramic videos

import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
plt.style.use("seaborn-white")
import matplotlib
matplotlib.rc("font", family="FreeSans")
import sys
from sklearn.cluster import KMeans, DBSCAN
from scipy.spatial import ConvexHull
from scipy.signal import convolve2d
from scipy.io import savemat
from tools import *
from copy import deepcopy

# Initialize the templates using background subtraction
# and Delaunay triangulation.
def init_templates(init_frame, background, THRESH):
    init_frame = match_histogram(init_frame, background)
    background_ = background.astype(np.float)
    init_frame_ = init_frame.astype(np.float)
    foreground = background_ - init_frame_
    foreground = np.sqrt(np.sum(foreground**2,2)).astype(np.uint8)
    ret, foreground_ = cv2.threshold(foreground,48,255,cv2.THRESH_BINARY)

    # Use DBSCAN for image segmentation
    dim = background.shape
    r = dim[1]/(2*np.pi)
    R = r + dim[0]
    dbscan_mask = foreground > THRESH
    dbscan_frame = np.column_stack(np.where(dbscan_mask))
    for num, pixel in enumerate(dbscan_frame):
        xr = pixel[1]
        yr = pixel[0]
        dbscan_frame[num, 0:2] = rec2ann(xr, yr, r, R, dim)
    dbscan = DBSCAN(eps=2.5, min_samples=15)
    dbscan.fit(dbscan_frame)
    labels = dbscan.labels_
    labels_unique = np.unique(labels)

    hulls = []
    clusters = []
    boxes = []
    for label in labels_unique:
        if label != -1:
            mask = labels==label
            cluster = dbscan_frame[mask]
            center = find_center(cluster)
            if len(cluster) > 500:
                for idx, point in enumerate(cluster):
                    xa = point[0]
                    ya = point[1]
                    cluster[idx, 0:2] = ann2rec(xa, ya, r, R, dim)
                if max(cluster[:,0]) - min(cluster[:,0]) > 1920:
                    for idx, point in enumerate(cluster):
                        if cluster[idx, 0] < 1920:
                            cluster[idx, 0] += 3840
                # Find convex hull of each cluster
                #hull = ConvexHull(cluster)
                #hull = [[x+100, y] for x, y in zip(cluster[hull.vertices,0],
                #                                cluster[hull.vertices,1])]
                # Find concave hull of each cluster
                hull = ConcaveHull(cluster)
                pad_hull = []
                for edge in hull:
                    pad_hull.append([[edge[0][0]+100, edge[0][1]],
                                     [edge[1][0]+100, edge[1][1]]])
                box = find_box(cluster)
                boxes.append(box)
                clusters.append(cluster)
                hulls.append(pad_hull)

    for hull in hulls:
        vertices = np.asarray([edge[0] for edge in hull])
        if np.max(vertices[:,0]) > 3940:
            duplicate = []
            for edge in hull:
                duplicate.append([[edge[0][0]-3840, edge[0][1]],
                                  [edge[1][0]-3840, edge[1][1]]])
            hulls.append(duplicate)

    hulls = np.asarray(hulls)
    roi = np.hstack((init_frame[:, -100:], init_frame, init_frame[:, 0:100]))
    frame_coord = np.asarray([(x, y) for x in range(4040) for y in range(80)])
    mask = np.zeros((80, 4040))
    for hull in hulls:
        mask_ = np.transpose(in_hull(frame_coord, hull).reshape(4040, 80))
        mask = np.logical_or(mask, mask_)
    roi[np.logical_not(mask)] = 0
    for box in boxes:
        cv2.rectangle(roi,(box[0]+100,box[1]),(box[2]+100,box[3]),(255,0,0))
    cv2.imwrite(SRC+"ROI.png", roi)
    cv2.imshow("ROI.png", roi)
    cv2.waitKey(0)
    templates = []
    for box in boxes:
        template = roi[box[1]:box[3],box[0]+100:box[2]+100]
        templates.append(template)
        #cv2.imshow("Template", template)
        #cv2.waitKey(1000)
    return templates, boxes

# Track the templates from the previous frame in the next frame
# and return the updated templates.
def track_templates(frame, templates, boxes, radius):
    padded_frame_bgr = np.hstack((frame[:,-100:], frame, frame[:,:100]))
    padded_frame = cv2.cvtColor(padded_frame_bgr, cv2.COLOR_BGR2GRAY)
    for idx in range(len(boxes)):
        boxes[idx][0] += 100
        boxes[idx][2] += 100
    templates_ = []
    boxes_ = []
    for template, box in zip(templates, boxes):
        template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
        neighbor = padded_frame[int(box[1]-radius[1]):int(box[3]+radius[1]),
                                int(box[0]-radius[0]):int(box[2]+radius[0])]

        box_ = []
        matches = cv2.matchTemplate(neighbor, template, cv2.TM_CCOEFF)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(matches)
        x = max_loc[0]
        y = max_loc[1]
        peak_locs_ = np.asarray([[x-1,y-1],[x  ,y-1],[x+1,y-1],
                                 [x-1,y  ],[x  ,y  ],[x+1,y  ],
                                 [x-1,y+1],[x  ,y+1],[x+1,y+1]])
        peak_vals = []
        peak_locs = []
        for loc in peak_locs_:
            try:
                peak_vals.append(matches[loc[1],loc[0]])
                peak_locs.append(loc)
            except:
                continue
        peak_locs = np.asarray(peak_locs)
        peak_vals = np.asarray(peak_vals)
        peak_vals += abs(np.min(peak_vals))
        peak_vals /= (np.std(peak_vals)+1)
        peak_vals **= 1
        best_loc = np.average(peak_locs,axis=0,weights=peak_vals)

        if False:
            fig = plt.figure()
            ax1 = fig.add_subplot(2,2,1)
            ax1.imshow(neighbor, cmap="gray")
            ax2 = fig.add_subplot(2,2,2)
            ax2.imshow(template, cmap="gray")
            ax3 = fig.add_subplot(2,2,3)
            ax3.imshow(matches, interpolation="nearest", cmap="plasma")
            ax3.plot(peak_locs[:,0], peak_locs[:,1], '+')
            ax3.plot(best_loc[0], best_loc[1], '*')
            ax4 = fig.add_subplot(2,2,4)
            ax4.imshow(matches, interpolation="nearest", cmap="plasma")
            plt.show()

        base = best_loc
        #base = [x, y]
        if base[0]+box[0]-radius[0] >= 100:
            base[0] = base[0]+box[0]-radius[0]
        else:
            base[0] = 4039-(base[0]+box[0]-radius[0])
        base[1] = base[1]+box[1]-radius[1]
        box_.append(base[0]-100)
        box_.append(base[1])
        box_.append(base[0]+(box[2]-box[0])-100)
        box_.append(base[1]+(box[3]-box[1]))
        boxes_.append(box_)
        template_ = padded_frame_bgr[int(box_[1]):int(box_[3]),
                                     int(box_[0]):int(box_[2])]
        templates_.append(template_)
    return templates_, boxes_

# Parse the command line argument
SRC = sys.argv[1]
THRESH = int(sys.argv[2])

init_frame = cv2.imread(SRC+"init_frame.png")
background = cv2.imread(SRC+"background.png")
templates, boxes = init_templates(init_frame, background, THRESH)

tracks = []
cap = cv2.VideoCapture(SRC+"subtracted_video.avi")
idx = 0
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
while (idx<frame_count):
    idx += 1
    tracks.append(boxes)
    ret, frame = cap.read()
    templates_, boxes = track_templates(frame, templates, deepcopy(boxes), [10,2])
    padded_frame = np.hstack((frame[:,-100:], frame, frame[:,:100]))
    for box in boxes:
        cv2.rectangle(padded_frame, (int(box[0]+100), int(box[1])),
                      (int(box[2]+100), int(box[3])), (255,0,0), 1)
    cv2.line(padded_frame, (100, 0), (100, 80), (255,0,0), 1)
    cv2.line(padded_frame, (3940, 0), (3940, 80), (0,0,255), 1)
    padded_frame = np.vstack((padded_frame[:,:1010],    padded_frame[:,1010:2020],
                              padded_frame[:,2020:3030],padded_frame[:,3030:4040]))
    cv2.putText(padded_frame, str(idx), (10,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255))
    cv2.imshow("Tracking", padded_frame)
    #cv2.imshow("Video",frame)
    k = cv2.waitKey(1) & 0xff
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()
np.save(SRC+"tracks.npy", tracks)
#savemat("tracks.mat", mdict={"tracks": tracks})


def permute(nums):
    def backtrack(first=0):
        # 所有数都填完了
        if first == n:
            res.append(nums[:])

        for i in range(first, n):
            # 动态数组维护
            nums[first], nums[i] = nums[i], nums[first]
            # 继续递归下一个数
            backtrack(first+1)
            # 回退，撤销操作
            nums[first], nums[i] = nums[i], nums[first]

    n = len(nums)  # n 判断条件
    res = []   # output
    backtrack()
    return res

from typing import List

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        def dfs(nums, size, depth, path, used, res):
            if depth == size:
                res.append(path[:])
                return

            for i in range(size):
                if not used[i]:
                    used[i] = True
                    path.append(nums[i])

                    dfs(nums, size, depth + 1, path, used, res)

                    # 回退，撤销操作
                    used[i] = False
                    path.pop()

        size = len(nums)
        if len(nums) == 0:
            return []

        used = [False for _ in range(size)]
        res = []
        dfs(nums, size, 0, [], used, res)
        return res

if __name__ == '__main__':
    nums = [1, 2, 3]
    solution = Solution()
    res = solution.permute(nums)
    print(res)


#-*- coding:utf-8 -*

import tensorflow as tf
from LSTM_captcha.config import *

def computational_graph_lstm(x, y, batch_size = batch_size):

    #weights and biases of appropriate shape to accomplish above task
    out_weights = tf.Variable(tf.random_normal([num_units,n_classes]), name = 'out_weight')
    out_bias = tf.Variable(tf.random_normal([n_classes]),name = 'out_bias')

    #构建网络
    lstm_layer = [tf.nn.rnn_cell.LSTMCell(num_units, state_is_tuple=True) for _ in range(layer_num)]    #创建两层的lstm
    mlstm_cell = tf.nn.rnn_cell.MultiRNNCell(lstm_layer, state_is_tuple = True)   #将lstm连接在一起

    init_state = mlstm_cell.zero_state(batch_size, tf.float32)  #cell的初始状态

    outputs = list()    #每个cell的输出
    state = init_state
    with tf.variable_scope('RNN'):
        for timestep in range(time_steps):
            if timestep > 0:
                tf.get_variable_scope().reuse_variables()
            (cell_output, state) = mlstm_cell(x[:, timestep, :], state) # 这里的state保存了每一层 LSTM 的状态
            outputs.append(cell_output)
    # h_state = outputs[-1] #取最后一个cell输出

    #计算输出层的第一个元素
    prediction_1 = tf.nn.softmax(tf.matmul(outputs[-4],out_weights)+out_bias)    #获取最后time-step的输出，使用全连接, 得到第一个验证码输出结果
    #计算输出层的第二个元素
    prediction_2 = tf.nn.softmax(tf.matmul(outputs[-3],out_weights)+out_bias)   #输出第二个验证码预测结果
    #计算输出层的第三个元素
    prediction_3 = tf.nn.softmax(tf.matmul(outputs[-2],out_weights)+out_bias)   #输出第三个验证码预测结果
    #计算输出层的第四个元素
    prediction_4 = tf.nn.softmax(tf.matmul(outputs[-1],out_weights)+out_bias)   #输出第四个验证码预测结果,size:[batch,num_class]
    #输出连接
    prediction_all = tf.concat([prediction_1, prediction_2, prediction_3, prediction_4],1)  # 4 * [batch, num_class] => [batch, 4 * num_class]
    prediction_all = tf.reshape(prediction_all,[batch_size, captcha_num, n_classes],name ='prediction_merge') # [4, batch, num_class] => [batch, 4, num_class]

    #loss_function
    loss = -tf.reduce_mean(y * tf.log(prediction_all),name = 'loss')
    # loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction_all,labels=y))
    #optimization
    opt = tf.train.AdamOptimizer(learning_rate=learning_rate, name = 'opt').minimize(loss)
    #model evaluation
    pre_arg = tf.argmax(prediction_all,2,name = 'predict')
    y_arg = tf.argmax(y,2)
    correct_prediction = tf.equal(pre_arg, y_arg)
    accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32),name = 'accuracy')

    return opt, loss, accuracy, pre_arg, y_arg


from datetime import timedelta
from django.utils import timezone
from django.conf import settings
from rest_framework.authentication import TokenAuthentication
from rest_framework.exceptions import AuthenticationFailed
# from rest_framework.authtoken.models import Token

class ExpiringTokenAuthentication(TokenAuthentication):
    expired = False
    def expires_in(self, token):
        time_elapsed = timezone.now() - token.created
        # cualquier de las 2 formas
        #left_time = timedelta(seconds=settings.TOKEN_EXPIRED_AFTER_SECONDS - time_elapsed.total_seconds())
        left_time = timedelta(seconds=settings.TOKEN_EXPIRED_AFTER_SECONDS) - time_elapsed
        return left_time

    def is_token_expired(self, token):
        return self.expires_in(token) < timedelta(seconds=0)

    def token_expire_handler(self, token):
        is_expire = self.is_token_expired(token)
        if is_expire:
            expired = True
            user = token.user
            token.delete()
            # se pueden borrar las sesiones
            token = self.get_model().objects.create(user=user)
        return is_expire, token

    def authenticate_credentials(self, key):
        mesaage, token, user = None, None, None
        try:
            #token = Token.objects.get(key=key) esta clase tiene implentado
            # una func que devueleve el modelo sino esta definido devuelve el model Token
            token = self.get_model().objects.select_related('user').get(key=key)
            user = token.user
        except self.get_model().DoesNotExist:
            #raise AuthenticationFailed('Token invalido')
            mesaage = "Token invalido"
        if token is not None:
            if not token.user.is_active:
                #raise AuthenticationFailed('Usuario invalido o eliminado')
                mesaage = 'Usuario invalido o eliminado'
            is_expired = self.token_expire_handler(token)
            if is_expired:
                #raise AuthenticationFailed('Su token ha expirado')
                mesaage = "Su token ha expirado"
        return (user, token, mesaage, self.expired)


import requests
from bs4 import BeautifulSoup
import re
import dbMysql as db
i=0
while i <= 100:
    i = i + 1
    url = 'http://www.hao6v.net/dy/index_%d.html' % i

    res = requests.get(url)
    res.encoding = 'gb2312'
    suop = BeautifulSoup(res.text, 'lxml')
    movice_list = suop.find_all("a", target="_blank")

    for item in movice_list:
        movice = item.attrs['href']

        url = re.compile(r'^http://www.hao6v.net/dy/(\d{4}-\d{1,2}-\d{1,2})/.*.html$')
        if not re.search(url, movice):
            continue
        else:
            movice_name = item.text
            # print(movice, movice_name)
            res2 = requests.get(movice)
            res2.encoding = 'gb2312'
            suop2 = BeautifulSoup(res2.text, 'lxml')
            movice_list2 = suop2.find_all('a')
            for i in movice_list2:
                mv = i.attrs['href']
                magnet = re.compile(r'^magnet:.*.$')
                if not re.search(magnet, mv):
                    continue
                else:
                    i = i.text
                    db.add_image(mv, i)
                    print(i)


"""
Install library
    $ pip install python-dotenv
    $ pip install python-telegram-bot

Run the script
    $ python telegram_bot.py

To get chat-id
https://api.telegram.org/bot1<token>/sendMessage?chat_id=@channelName&text=123
"""
from telegram.ext import Updater, InlineQueryHandler, CommandHandler,  MessageHandler, Filters
from telegram.ext.dispatcher import run_async
import requests
import re
import os
from dotenv import load_dotenv

load_dotenv()

API_KEY = os.getenv('API_KEY')

def get_url():
    contents = requests.get('https://random.dog/woof.json').json()
    url = contents['url']
    return url

def get_image_url():
    allowed_extension = ['jpg','jpeg','png']
    file_extension = ''
    while file_extension not in allowed_extension:
        url = get_url()
        file_extension = re.search("([^.]*)$",url).group(1).lower()
    return url

# @run_async
def bop(update, context):
    url = get_image_url()
    chat_id = update.message.chat_id
    context.bot.send_photo(chat_id=chat_id, photo=url)

def start(update, context):
    s = "Welcome I Am The Binance new coin Chat Bot! Your life has now changed forever."
    update.message.reply_text(s)
    context.bot.sendMessage(chat_id='@BinanceNewCoin', text='Some content')

def repeater(update, context):
    # if context.user_data[echo]:
    #     update.message.reply_text(update.message.text)
    update.message.reply_text(update.message.text)

def echo(update, context):
    command = context.args[0].lower()
    if("on" == command):
        context.user_data[echo] = True
        update.message.reply_text("Repeater Started")
    elif("off" == command):
        context.user_data[echo] = False
        update.message.reply_text("Repeater Stopped")

def main():
    updater = Updater(API_KEY, use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('bop',bop))
    dp.add_handler(CommandHandler('start', start))
    dp.add_handler(CommandHandler('echo', echo))
    dp.add_handler(MessageHandler(Filters.text, repeater))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()


from models.bp_layer import bp_layer
from models.net import net

import time
import wandb
import numpy as np
import torch
from torch import nn

class bp_net(net):
    def __init__(self, depth, in_dim, hid_dim, out_dim, activation_function, loss_function, algorithm, device):
        self.device = device
        self.depth = depth
        self.layers = self.init_layers(in_dim, hid_dim, out_dim, activation_function)
        self.loss_function = loss_function
        self.MSELoss = nn.MSELoss(reduction="sum")
        self.algorithm = algorithm

    def init_layers(self, in_dim, hid_dim, out_dim, activation_function):
        layers = [None] * self.depth
        dims = [in_dim] + [hid_dim] * (self.depth - 1) + [out_dim]
        for d in range(self.depth - 1):
            layers[d] = bp_layer(dims[d], dims[d + 1], activation_function, self.device)
        layers[-1] = bp_layer(dims[-2], dims[-1], "linear", self.device)
        return layers

    def train(self, train_loader, valid_loader, epochs, lr, log):
        for e in range(epochs):
            start_time = time.time()

            # train forward
            for x, y in train_loader:
                x, y = x.to(self.device), y.to(self.device)
                self.update_weights(x, y, lr)

            end_time = time.time()
            print(f"epochs {e}: {end_time - start_time:.2f}")

            # predict
            with torch.no_grad():
                train_loss, train_acc = self.test(train_loader)
                valid_loss, valid_acc = self.test(valid_loader)
                if log:
                    log_dict = {"train loss": train_loss,
                                "valid loss": valid_loss}
                    if train_acc is not None:
                        log_dict["train accuracy"] = train_acc
                    if valid_acc is not None:
                        log_dict["valid accuracy"] = valid_acc
                    log_dict["time"] = end_time - start_time

                    wandb.log(log_dict)
                else:
                    print(f"\ttrain loss     : {train_loss}")
                    print(f"\tvalid loss     : {valid_loss}")
                    if train_acc is not None:
                        print(f"\ttrain acc      : {train_acc}")
                    if valid_acc is not None:
                        print(f"\tvalid acc      : {valid_acc}")

    def update_weights(self, x, y, lr):
        y_pred = self.forward(x).requires_grad_()
        y_pred.retain_grad()
        loss = self.loss_function(y_pred, y)
        batch_size = len(y)
        self.zero_grad()
        loss.backward()
        g = y_pred.grad
        grad = [None] * self.depth
        with torch.no_grad():
            for d in reversed(range(self.depth)):
                g = g * self.layers[d].activation_derivative(self.layers[d].linear_activation)
                grad[d] = g.T @ self.layers[d - 1].linear_activation if d >= 1 else g.T @ x
                if self.algorithm == "BP":
                    g = g @ self.layers[d].weight
                elif self.algorithm == "FA":
                    g = g @ self.layers[d].fixed_weight
        for d in range(self.depth):
            self.layers[d].weight = (self.layers[d].weight - (lr / batch_size)
                                     * grad[d]).detach().requires_grad_()

    def zero_grad(self):
        for d in range(self.depth):
            if self.layers[d].weight.grad is not None:
                self.layers[d].weight.grad.zero_()

    def forward(self, x, update=True):
        y = x
        for d in range(self.depth):
            y = self.layers[d].forward(y, update=update)
        return y


from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

def margin(obj):
    obj.line(30,30,580,30)#top
    obj.line(30,30,30,758)#left
    obj.line(30,758,580,758)#bottom
    obj.line(580,758,580,30)#right

def para_1(obj,img,fonts):
    obj.setFont("Courier-Bold",20)
    obj.drawString(230,720,"Story Time")
    obj.drawString(150,690,"(Turtle and Rabbit Story)")
    obj.rect(60, 550, 100, 100, stroke=1, fill=0)
    obj.drawImage(img, 65, 555, width=90, height=90)
    obj.setFont("Times-Roman",20)
    obj.drawString(170,630,"Once upon a time there was a Rabbit and Turtle" )
    obj.drawString(170,590,"Then they planned to go for a race , so they ")
    obj.drawString(172,550,"organized race.")

def para_2(obj,img_2,fonts):
    obj.rect(435, 425, 100, 100, stroke=1, fill=0)
    obj.drawImage(img_2, 440, 430, width=90, height=90)
    obj.setFont("Times-Roman",20)
    obj.drawString(65,510,"Both of them started the race from starting")
    obj.drawString(65,472,"point , The rabbit ran faster than turtle in ")
    obj.drawString(65,437,"race and the turtle puts full efforts in race. ")

def para_3(obj,img_3,fonts):
    obj.rect(65,295 , 100, 100, stroke=1, fill=0)
    obj.drawImage(img_3, 70, 300, width=90, height=90)
    obj.setFont("Times-Roman",20)
    obj.drawString(176,380,"After a while in a race the rabbit thinks in a way ")
    obj.drawString(176,343,"that turtle is not a competitor to rabbit and takes ")
    obj.drawString(176,308,"rest under the tree , on that time turtle crossed.")

def para_4(obj,img_3,fonts):
    obj.rect(435, 150, 100, 100, stroke=1, fill=0)
    obj.drawImage(img_4, 440, 155, width=90, height=90)
    obj.setFont("Times-Roman",20)
    obj.drawString(65,230,"The turtle puts consistent efforts in a race")
    obj.drawString(65,195,"and at the same time the rabbit comes to  ")
    obj.drawString(65,158,"know that turtle in end line and turtle wins. ")

def moral(obj,img_climax,fonts):
    obj.setFont("Times-Roman-Bold",30)
    obj.rect(236, 620, 124, 124, stroke=1, fill=0)
    obj.drawImage(img_climax, 243, 627, width=110, height=110)
    obj.drawString(50,580,"The moral of the story is that the rabbit")
    obj.drawString(50,530,"thinks in a way like the turtle is not faster")
    obj.drawString(50,480,"than rabbit and it felt lethargic because of")
    obj.drawString(48,430,"that it takes rest in between the race , so that")
    obj.drawString(50,380,"the rabbit loss a race but due to the ")
    obj.drawString(50,330,"consistent effort of turtleit pays for it and")
    obj.drawString(50,280,"the rabbit had learned his lesson...!!")
    obj.setFont("Helvetica-Bold",30)
    obj.drawString(90,210,"'''Slow Steady Wins The Race'''")
if __name__ == "__main__":
    obj = canvas.Canvas("exp_pdf.pdf",pagesize=letter)
    fonts = obj.getAvailableFonts()
    img = "start.jfif"
    img_2 = "started.jfif"
    img_3 = "turtle_crosses_rabbit.jfif"
    img_4 = "turtle_win.jfif"
    img_climax = "Quote.jfif"
    print("PDF Created")
    margin(obj)
    para_1(obj,img,fonts)
    para_2(obj,img_2,fonts)
    para_3(obj,img_3,fonts)
    para_4(obj,img_4,fonts)
    obj.showPage()
    margin(obj)
    moral(obj,img_climax,fonts)
    obj.save()


from flask import Flask, render_template, request
import shapely
from shapely.geometry import Point
import pandas as pd
import matplotlib.pyplot as plt
import os
import folium
import geopandas as gpd
import random

app = Flask(__name__)

@app.route('/', methods=['GET'])
def homepage():
     return render_template("home.html")

@app.route('/Scelta1', methods=['GET'])
def Scelta1():
     df = pd.read_excel('GdL_GV_2021.xlsx')
     df_giudizio = df.groupby("giudizio")[["localita"]].count().reset_index()
     giudizio = list(df_giudizio["giudizio"])
     numero = list(df_giudizio["localita"])
     return render_template("scelta1.html", numero=numero, prova = df_giudizio.to_html())

@app.route('/Scelta2', methods=['GET'])
def Scelta2():
    df = pd.read_excel('GdL_GV_2021.xlsx')

    giudizi = df['giudizio'].value_counts(normalize=True) * 100

    return render_template('scelta2.html', giudizi=giudizi)

@app.route('/Scelta3', methods=['GET'])
def Scelta3():
    df = pd.read_excel('GdL_GV_2021.xlsx')
    tipo_inquinamento_counts = df['giudizio'].value_counts(normalize=True) * 100

    plt.figure(figsize=(6, 4))
    plt.pie(tipo_inquinamento_counts, labels=tipo_inquinamento_counts.index, autopct='%1.1f%%')
    plt.title('Percentuale dei Tipi di Inquinamento')

    dir = "static/images"
    file_name = "graf3.png"
    save_path = os.path.join(dir, file_name)
    plt.savefig(save_path, dpi=150)

    plt.show()

    return render_template('scelta3.html')

@app.route('/Scelta4', methods=['GET'])
def Scelta4():
    df = pd.read_excel('GdL_GV_2021.xlsx')

    localita_con_spiaggia = df[df['localita'].str.lower().str.contains('spiaggia', na=False, case=False)]['giudizio']

    localita_con_spiaggia = localita_con_spiaggia.drop_duplicates()

    return render_template("scelta4.html", localita_con_spiaggia=localita_con_spiaggia)

@app.route('/Scelta5', methods=['GET'])
def Scelta5():
    df = pd.read_excel('GdL_GV_2021.xlsx')
    gdf = gpd.GeoDataFrame(df.drop(['longitude', 'latitude'], axis=1),
          crs='EPSG:4326',
          geometry=df.apply(lambda row: shapely.geometry.Point((row.longitude, row.latitude)), axis=1))

    mappa = folium.Map(location=[45.706, 9.742], zoom_start=8)

    for idx, row in gdf.iterrows():
        folium.Marker([row['geometry'].y, row['geometry'].x], tooltip=row['localita']).add_to(mappa)

    mappa_html = mappa.get_root().render()

    return render_template("scelta5.html", mappa_html=mappa_html, gdf=gdf)

@app.route('/Scelta6', methods=['GET'])
def scelta6():
    df = pd.read_excel('GdL_GV_2021.xlsx')
    num_punti = 10
    punti = []

    for _ in range(num_punti):
        latitude = random.uniform(45.0, 46.0)
        longitude = random.uniform(9.0, 10.0)
        giudizio = random.choice(['Entro i Limiti', 'Inquinato', 'Fortemente Inquinato'])
        punti.append({'Latitude': latitude, 'Longitude': longitude, 'Giudizio': giudizio})

    mappa = folium.Map(location=[45.4, 9.2], zoom_start=8)

    for punto in punti:
        folium.Marker(
            location=[punto['Latitude'], punto['Longitude']],
            popup='Giudizio: ' + punto['Giudizio']
        ).add_to(mappa)
    mappa.save('templates/mappa.html')

    return render_template('mappa.html')

@app.route('/Scelta7', methods=['GET', 'POST'])
def Scelta7():
    if request.method == 'POST':
        nome_regione = request.form['nome_regione']

        punti_monitorati = pd.DataFrame({
            'Latitude': [45.7, 45.71, 45.72],
            'Longitude': [9.2, 9.21, 9.22],
            'Giudizio': ['Entro i Limiti', 'Inquinato', 'Fortemente Inquinato']
        })

        mappa = folium.Map(location=[45.7, 9.2], zoom_start=10)

        for _, punto in punti_monitorati.iterrows():
            folium.Marker(
                location=[punto['Latitude'], punto['Longitude']],
                popup='Giudizio: ' + punto['Giudizio']
            ).add_to(mappa)

        mappa.save('templates/mappa_regionale.html')

        return render_template('mappa_regionale.html')

    return render_template('scelta7.html')

@app.route('/Scelta8', methods=['GET', 'POST'])
def Scelta8():
    if request.method == 'POST':
        nome_lago = request.form['nome_lago']

        punti_monitorati2 = pd.DataFrame({
            'Latitude': [45.57, 45.96, 46.01],
            'Longitude': [10, 8.65, 9.25],
            'Giudizio': ['Entro i Limiti', 'Inquinato', 'Fortemente Inquinato']
        })

        mappa = folium.Map(location=[45.7, 9.2], zoom_start=10)

        for _, punto in punti_monitorati2.iterrows():
            folium.Marker(
                location=[punto['Latitude'], punto['Longitude']],
                popup='Giudizio: ' + punto['Giudizio']
            ).add_to(mappa)

        mappa.save('templates/mappa_lago.html')

        return render_template('mappa_lago.html')

    return render_template('scelta8.html')

@app.route('/Scelta9', methods=['GET'])
def Scelta9():
     return render_template("home.html")

if __name__ == '__main__':
  app.run(host='0.0.0.0', port=3245, debug=True)


from fuzzconfig import FuzzConfig
import nonrouting
import nets
import pytrellis
import re
import fuzzloops

jobs = [
    {
        "cfg": FuzzConfig(job="PIOL", family="ECP5", device="LFE5U-45F", ncl="empty.ncl",
                          tiles=["MIB_R59C0:PICL0", "MIB_R60C0:PICL1", "MIB_R61C0:PICL2"]),
        "side": "L",
        "pins": [("M4", "A"), ("N5", "B"), ("N4", "C"), ("P5", "D")]
    },

    {
        "cfg": FuzzConfig(job="PIOR", family="ECP5", device="LFE5U-45F", ncl="empty.ncl",
                          tiles=["MIB_R35C90:PICR0", "MIB_R36C90:PICR1", "MIB_R37C90:PICR2"]),
        "side": "R",
        "pins": [("L20", "A"), ("M20", "B"), ("L19", "C"), ("M19", "D")]
    },

]

def main():
    pytrellis.load_database("../../../database")
    for job in jobs:
        cfg = job["cfg"]
        side = job["side"]
        pins = job["pins"]
        cfg.setup()
        empty_bitfile = cfg.build_design(cfg.ncl, {})
        cfg.ncl = "pio.v"

        def per_pin(pin):
            loc, pio = pin

            def get_substs(iomode, extracfg=None):
                if iomode == "NONE":
                    iodir, type = "NONE", ""
                else:
                    iodir, type = iomode.split("_", 1)
                substs = {
                    "dir": iodir,
                    "io_type": type,
                    "loc": loc,
                    "extra_attrs": "",
                    "cfg_vio": "3.3"
                }
                if extracfg is not None:
                    substs["extra_attrs"] = '(* {}="{}" *)'.format(extracfg[0], extracfg[1])
                if side == "B":
                    substs["cfg_vio"] = get_cfg_vccio(type)
                return substs

            modes = ["NONE"]

            nonrouting.fuzz_enum_setting(cfg, "PIO{}.TERMINATION_1V8".format(pio), ["OFF", "50", "75", "150"],
                                         lambda x: get_substs(iomode="BIDIR_SSTL18_I", extracfg=("TERMINATION", x)),
                                         empty_bitfile, False)

            nonrouting.fuzz_enum_setting(cfg, "PIO{}.TERMINATION_1V5".format(pio), ["OFF", "50", "75", "150"],
                                         lambda x: get_substs(iomode="BIDIR_SSTL15_I", extracfg=("TERMINATION", x)),
                                         empty_bitfile, False)

            nonrouting.fuzz_enum_setting(cfg, "PIO{}.TERMINATION_1V35".format(pio), ["OFF", "50", "75", "150"],
                                         lambda x: get_substs(iomode="BIDIR_SSTL135_I", extracfg=("TERMINATION", x)),
                                         empty_bitfile, False)

            nonrouting.fuzz_enum_setting(cfg, "PIO{}.DIFFRESISTOR".format(pio), ["OFF", "100"],
                                         lambda x: get_substs(iomode="INPUT_LVDS", extracfg=("DIFFRESISTOR", x)),
                                         empty_bitfile, False)

        fuzzloops.parallel_foreach(pins, per_pin)

if __name__ == "__main__":
    main()


bookreaders = []
n = int(input())
for i in range(n):
    name = input()
    bookcount = int(input())
    u25 = int(input())
    list1 = [name , bookcount,u25]
    bookreaders.append(list1)
print(bookreaders)
intelligentreaders = [reader[0] for reader in bookreaders if reader[1]>200]
print(intelligentreaders)
youngreaders = [reader[0] for reader in bookreaders if reader[2] ==1]
print(youngreaders)


import asyncio
import os
import pathlib
import socket
import tempfile
import time
import unittest
import sys

from uvloop import _testbase as tb

SSL_HANDSHAKE_TIMEOUT = 15.0

class _TestUnix:
    def test_create_unix_server_1(self):
        CNT = 0           # number of clients that were successful
        TOTAL_CNT = 100   # total number of clients that test will create
        TIMEOUT = 5.0     # timeout for this test

        async def handle_client(reader, writer):
            nonlocal CNT

            data = await reader.readexactly(4)
            self.assertEqual(data, b'AAAA')
            writer.write(b'OK')

            data = await reader.readexactly(4)
            self.assertEqual(data, b'BBBB')
            writer.write(b'SPAM')

            await writer.drain()
            writer.close()
            await self.wait_closed(writer)

            CNT += 1

        async def test_client(addr):
            sock = socket.socket(socket.AF_UNIX)
            with sock:
                sock.setblocking(False)
                await self.loop.sock_connect(sock, addr)

                await self.loop.sock_sendall(sock, b'AAAA')

                buf = b''
                while len(buf) != 2:
                    buf += await self.loop.sock_recv(sock, 1)
                self.assertEqual(buf, b'OK')

                await self.loop.sock_sendall(sock, b'BBBB')

                buf = b''
                while len(buf) != 4:
                    buf += await self.loop.sock_recv(sock, 1)
                self.assertEqual(buf, b'SPAM')

        async def start_server():
            nonlocal CNT
            CNT = 0

            with tempfile.TemporaryDirectory() as td:
                sock_name = os.path.join(td, 'sock')
                srv = await asyncio.start_unix_server(
                    handle_client,
                    sock_name)

                try:
                    srv_socks = srv.sockets
                    self.assertTrue(srv_socks)
                    self.assertTrue(srv.is_serving())

                    tasks = []
                    for _ in range(TOTAL_CNT):
                        tasks.append(test_client(sock_name))

                    await asyncio.wait_for(asyncio.gather(*tasks), TIMEOUT)

                finally:
                    self.loop.call_soon(srv.close)
                    await srv.wait_closed()

                    if (
                        self.implementation == 'asyncio'
                        and sys.version_info[:3] >= (3, 12, 0)
                    ):
                        # asyncio regression in 3.12 -- wait_closed()
                        # doesn't wait for `close()` to actually complete.
                        # https://github.com/python/cpython/issues/79033
                        await asyncio.sleep(1)

                    # Check that the server cleaned-up proxy-sockets
                    for srv_sock in srv_socks:
                        self.assertEqual(srv_sock.fileno(), -1)

                    self.assertFalse(srv.is_serving())

                # asyncio doesn't cleanup the sock file
                self.assertTrue(os.path.exists(sock_name))

        async def start_server_sock(start_server):
            nonlocal CNT
            CNT = 0

            with tempfile.TemporaryDirectory() as td:
                sock_name = os.path.join(td, 'sock')
                sock = socket.socket(socket.AF_UNIX)
                sock.bind(sock_name)

                srv = await start_server(sock)

                try:
                    srv_socks = srv.sockets
                    self.assertTrue(srv_socks)
                    self.assertTrue(srv.is_serving())

                    tasks = []
                    for _ in range(TOTAL_CNT):
                        tasks.append(test_client(sock_name))

                    await asyncio.wait_for(asyncio.gather(*tasks), TIMEOUT)

                finally:
                    self.loop.call_soon(srv.close)
                    await srv.wait_closed()

                    if (
                        self.implementation == 'asyncio'
                        and sys.version_info[:3] >= (3, 12, 0)
                    ):
                        # asyncio regression in 3.12 -- wait_closed()
                        # doesn't wait for `close()` to actually complete.
                        # https://github.com/python/cpython/issues/79033
                        await asyncio.sleep(1)

                    # Check that the server cleaned-up proxy-sockets
                    for srv_sock in srv_socks:
                        self.assertEqual(srv_sock.fileno(), -1)

                    self.assertFalse(srv.is_serving())

                # asyncio doesn't cleanup the sock file
                self.assertTrue(os.path.exists(sock_name))

        with self.subTest(func='start_unix_server(host, port)'):
            self.loop.run_until_complete(start_server())
            self.assertEqual(CNT, TOTAL_CNT)

        with self.subTest(func='start_unix_server(sock)'):
            self.loop.run_until_complete(start_server_sock(
                lambda sock: asyncio.start_unix_server(
                    handle_client,
                    None,
                    sock=sock)))
            self.assertEqual(CNT, TOTAL_CNT)

        with self.subTest(func='start_server(sock)'):
            self.loop.run_until_complete(start_server_sock(
                lambda sock: asyncio.start_server(
                    handle_client,
                    None, None,
                    sock=sock)))
            self.assertEqual(CNT, TOTAL_CNT)

    def test_create_unix_server_2(self):
        with tempfile.TemporaryDirectory() as td:
            sock_name = os.path.join(td, 'sock')
            with open(sock_name, 'wt') as f:
                f.write('x')

            with self.assertRaisesRegex(
                    OSError, "Address '{}' is already in use".format(
                        sock_name)):

                self.loop.run_until_complete(
                    self.loop.create_unix_server(object, sock_name))

    def test_create_unix_server_3(self):
        with self.assertRaisesRegex(
                ValueError, 'ssl_handshake_timeout is only meaningful'):
            self.loop.run_until_complete(
                self.loop.create_unix_server(
                    lambda: None, path='/tmp/a',
                    ssl_handshake_timeout=SSL_HANDSHAKE_TIMEOUT))

    def test_create_unix_server_existing_path_sock(self):
        with self.unix_sock_name() as path:
            sock = socket.socket(socket.AF_UNIX)
            with sock:
                sock.bind(path)
                sock.listen(1)

            # Check that no error is raised -- `path` is removed.
            coro = self.loop.create_unix_server(lambda: None, path)
            srv = self.loop.run_until_complete(coro)
            srv.close()
            self.loop.run_until_complete(srv.wait_closed())

    def test_create_unix_connection_open_unix_con_addr(self):
        async def client(addr):
            reader, writer = await asyncio.open_unix_connection(addr)

            writer.write(b'AAAA')
            self.assertEqual(await reader.readexactly(2), b'OK')

            writer.write(b'BBBB')
            self.assertEqual(await reader.readexactly(4), b'SPAM')

            writer.close()
            await self.wait_closed(writer)

        self._test_create_unix_connection_1(client)

    def test_create_unix_connection_open_unix_con_sock(self):
        async def client(addr):
            sock = socket.socket(socket.AF_UNIX)
            sock.connect(addr)
            reader, writer = await asyncio.open_unix_connection(sock=sock)

            writer.write(b'AAAA')
            self.assertEqual(await reader.readexactly(2), b'OK')

            writer.write(b'BBBB')
            self.assertEqual(await reader.readexactly(4), b'SPAM')

            writer.close()
            await self.wait_closed(writer)

        self._test_create_unix_connection_1(client)

    def test_create_unix_connection_open_con_sock(self):
        async def client(addr):
            sock = socket.socket(socket.AF_UNIX)
            sock.connect(addr)
            reader, writer = await asyncio.open_connection(sock=sock)

            writer.write(b'AAAA')
            self.assertEqual(await reader.readexactly(2), b'OK')

            writer.write(b'BBBB')
            self.assertEqual(await reader.readexactly(4), b'SPAM')

            writer.close()
            await self.wait_closed(writer)

        self._test_create_unix_connection_1(client)

    def _test_create_unix_connection_1(self, client):
        CNT = 0
        TOTAL_CNT = 100

        def server(sock):
            data = sock.recv_all(4)
            self.assertEqual(data, b'AAAA')
            sock.send(b'OK')

            data = sock.recv_all(4)
            self.assertEqual(data, b'BBBB')
            sock.send(b'SPAM')

        async def client_wrapper(addr):
            await client(addr)
            nonlocal CNT
            CNT += 1

        def run(coro):
            nonlocal CNT
            CNT = 0

            with self.unix_server(server,
                                  max_clients=TOTAL_CNT,
                                  backlog=TOTAL_CNT) as srv:
                tasks = []
                for _ in range(TOTAL_CNT):
                    tasks.append(coro(srv.addr))

                self.loop.run_until_complete(asyncio.gather(*tasks))

                # Give time for all transports to close.
                self.loop.run_until_complete(asyncio.sleep(0.1))

            self.assertEqual(CNT, TOTAL_CNT)

        run(client_wrapper)

    def test_create_unix_connection_2(self):
        with tempfile.NamedTemporaryFile() as tmp:
            path = tmp.name

        async def client():
            reader, writer = await asyncio.open_unix_connection(path)
            writer.close()
            await self.wait_closed(writer)

        async def runner():
            with self.assertRaises(FileNotFoundError):
                await client()

        self.loop.run_until_complete(runner())

    def test_create_unix_connection_3(self):
        CNT = 0
        TOTAL_CNT = 100

        def server(sock):
            data = sock.recv_all(4)
            self.assertEqual(data, b'AAAA')
            sock.close()

        async def client(addr):
            reader, writer = await asyncio.open_unix_connection(addr)

            sock = writer._transport.get_extra_info('socket')
            self.assertEqual(sock.family, socket.AF_UNIX)

            writer.write(b'AAAA')

            with self.assertRaises(asyncio.IncompleteReadError):
                await reader.readexactly(10)

            writer.close()
            await self.wait_closed(writer)

            nonlocal CNT
            CNT += 1

        def run(coro):
            nonlocal CNT
            CNT = 0

            with self.unix_server(server,
                                  max_clients=TOTAL_CNT,
                                  backlog=TOTAL_CNT) as srv:
                tasks = []
                for _ in range(TOTAL_CNT):
                    tasks.append(coro(srv.addr))

                self.loop.run_until_complete(asyncio.gather(*tasks))

            self.assertEqual(CNT, TOTAL_CNT)

        run(client)

    def test_create_unix_connection_4(self):
        sock = socket.socket(socket.AF_UNIX)
        sock.close()

        async def client():
            reader, writer = await asyncio.open_unix_connection(sock=sock)
            writer.close()
            await self.wait_closed(writer)

        async def runner():
            with self.assertRaisesRegex(OSError, 'Bad file'):
                await client()

        self.loop.run_until_complete(runner())

    def test_create_unix_connection_5(self):
        s1, s2 = socket.socketpair(socket.AF_UNIX)

        excs = []

        class Proto(asyncio.Protocol):
            def connection_lost(self, exc):
                excs.append(exc)

        proto = Proto()

        async def client():
            t, _ = await self.loop.create_unix_connection(
                lambda: proto,
                None,
                sock=s2)

            t.write(b'AAAAA')
            s1.close()
            t.write(b'AAAAA')
            await asyncio.sleep(0.1)

        self.loop.run_until_complete(client())

        self.assertEqual(len(excs), 1)
        self.assertIn(excs[0].__class__,
                      (BrokenPipeError, ConnectionResetError))

    def test_create_unix_connection_6(self):
        with self.assertRaisesRegex(
                ValueError, 'ssl_handshake_timeout is only meaningful'):
            self.loop.run_until_complete(
                self.loop.create_unix_connection(
                    lambda: None, path='/tmp/a',
                    ssl_handshake_timeout=SSL_HANDSHAKE_TIMEOUT))

class Test_UV_Unix(_TestUnix, tb.UVTestCase):

    @unittest.skipUnless(hasattr(os, 'fspath'), 'no os.fspath()')
    def test_create_unix_connection_pathlib(self):
        async def run(addr):
            t, _ = await self.loop.create_unix_connection(
                asyncio.Protocol, addr)
            t.close()

        with self.unix_server(lambda sock: time.sleep(0.01)) as srv:
            addr = pathlib.Path(srv.addr)
            self.loop.run_until_complete(run(addr))

    @unittest.skipUnless(hasattr(os, 'fspath'), 'no os.fspath()')
    def test_create_unix_server_pathlib(self):
        with self.unix_sock_name() as srv_path:
            srv_path = pathlib.Path(srv_path)
            srv = self.loop.run_until_complete(
                self.loop.create_unix_server(asyncio.Protocol, srv_path))
            srv.close()
            self.loop.run_until_complete(srv.wait_closed())

    def test_transport_fromsock_get_extra_info(self):
        # This tests is only for uvloop.  asyncio should pass it
        # too in Python 3.6.

        async def test(sock):
            t, _ = await self.loop.create_unix_connection(
                asyncio.Protocol,
                sock=sock)

            sock = t.get_extra_info('socket')
            self.assertIs(t.get_extra_info('socket'), sock)

            with self.assertRaisesRegex(RuntimeError, 'is used by transport'):
                self.loop.add_writer(sock.fileno(), lambda: None)
            with self.assertRaisesRegex(RuntimeError, 'is used by transport'):
                self.loop.remove_writer(sock.fileno())

            t.close()

        s1, s2 = socket.socketpair(socket.AF_UNIX)
        with s1, s2:
            self.loop.run_until_complete(test(s1))

    def test_create_unix_server_path_dgram(self):
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
        with sock:
            coro = self.loop.create_unix_server(lambda: None,
                                                sock=sock)
            with self.assertRaisesRegex(ValueError,
                                        'A UNIX Domain Stream.*was expected'):
                self.loop.run_until_complete(coro)

    @unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'),
                         'no socket.SOCK_NONBLOCK (linux only)')
    def test_create_unix_server_path_stream_bittype(self):
        sock = socket.socket(
            socket.AF_UNIX, socket.SOCK_STREAM | socket.SOCK_NONBLOCK)
        with tempfile.NamedTemporaryFile() as file:
            fn = file.name
        try:
            with sock:
                sock.bind(fn)
                coro = self.loop.create_unix_server(lambda: None, path=None,
                                                    sock=sock)
                srv = self.loop.run_until_complete(coro)
                srv.close()
                self.loop.run_until_complete(srv.wait_closed())
        finally:
            os.unlink(fn)

    @unittest.skipUnless(sys.platform.startswith('linux'), 'requires epoll')
    def test_epollhup(self):
        SIZE = 50
        eof = False
        done = False
        recvd = b''

        class Proto(asyncio.BaseProtocol):
            def connection_made(self, tr):
                tr.write(b'hello')
                self.data = bytearray(SIZE)
                self.buf = memoryview(self.data)

            def get_buffer(self, sizehint):
                return self.buf

            def buffer_updated(self, nbytes):
                nonlocal recvd
                recvd += self.buf[:nbytes]

            def eof_received(self):
                nonlocal eof
                eof = True

            def connection_lost(self, exc):
                nonlocal done
                done = exc

        async def test():
            with tempfile.TemporaryDirectory() as td:
                sock_name = os.path.join(td, 'sock')
                srv = await self.loop.create_unix_server(Proto, sock_name)

                s = socket.socket(socket.AF_UNIX)
                with s:
                    s.setblocking(False)
                    await self.loop.sock_connect(s, sock_name)
                    d = await self.loop.sock_recv(s, 100)
                    self.assertEqual(d, b'hello')

                    # IMPORTANT: overflow recv buffer and close immediately
                    await self.loop.sock_sendall(s, b'a' * (SIZE + 1))

                srv.close()
                await srv.wait_closed()

        self.loop.run_until_complete(test())
        self.assertTrue(eof)
        self.assertIsNone(done)
        self.assertEqual(recvd, b'a' * (SIZE + 1))

class Test_AIO_Unix(_TestUnix, tb.AIOTestCase):
    pass

class _TestSSL(tb.SSLTestCase):

    ONLYCERT = tb._cert_fullname(__file__, 'ssl_cert.pem')
    ONLYKEY = tb._cert_fullname(__file__, 'ssl_key.pem')

    def test_create_unix_server_ssl_1(self):
        CNT = 0           # number of clients that were successful
        TOTAL_CNT = 25    # total number of clients that test will create
        TIMEOUT = 10.0    # timeout for this test

        A_DATA = b'A' * 1024 * 1024
        B_DATA = b'B' * 1024 * 1024

        sslctx = self._create_server_ssl_context(self.ONLYCERT, self.ONLYKEY)
        client_sslctx = self._create_client_ssl_context()

        clients = []

        async def handle_client(reader, writer):
            nonlocal CNT

            data = await reader.readexactly(len(A_DATA))
            self.assertEqual(data, A_DATA)
            writer.write(b'OK')

            data = await reader.readexactly(len(B_DATA))
            self.assertEqual(data, B_DATA)
            writer.writelines([b'SP', bytearray(b'A'), memoryview(b'M')])

            await writer.drain()
            writer.close()

            CNT += 1

        async def test_client(addr):
            fut = asyncio.Future(loop=self.loop)

            def prog(sock):
                try:
                    sock.starttls(client_sslctx)

                    sock.connect(addr)
                    sock.send(A_DATA)

                    data = sock.recv_all(2)
                    self.assertEqual(data, b'OK')

                    sock.send(B_DATA)
                    data = sock.recv_all(4)
                    self.assertEqual(data, b'SPAM')

                    sock.close()

                except Exception as ex:
                    self.loop.call_soon_threadsafe(
                        lambda ex=ex:
                            (fut.cancelled() or fut.set_exception(ex)))
                else:
                    self.loop.call_soon_threadsafe(
                        lambda: (fut.cancelled() or fut.set_result(None)))

            client = self.unix_client(prog)
            client.start()
            clients.append(client)

            await fut

        async def start_server():
            extras = dict(ssl_handshake_timeout=SSL_HANDSHAKE_TIMEOUT)

            with tempfile.TemporaryDirectory() as td:
                sock_name = os.path.join(td, 'sock')

                srv = await asyncio.start_unix_server(
                    handle_client,
                    sock_name,
                    ssl=sslctx,
                    **extras)

                try:
                    tasks = []
                    for _ in range(TOTAL_CNT):
                        tasks.append(test_client(sock_name))

                    await asyncio.wait_for(asyncio.gather(*tasks), TIMEOUT)

                finally:
                    self.loop.call_soon(srv.close)
                    await srv.wait_closed()

        try:
            with self._silence_eof_received_warning():
                self.loop.run_until_complete(start_server())
        except asyncio.TimeoutError:
            if os.environ.get('TRAVIS_OS_NAME') == 'osx':
                # XXX: figure out why this fails on macOS on Travis
                raise unittest.SkipTest('unexplained error on Travis macOS')
            else:
                raise

        self.assertEqual(CNT, TOTAL_CNT)

        for client in clients:
            client.stop()

    def test_create_unix_connection_ssl_1(self):
        CNT = 0
        TOTAL_CNT = 25

        A_DATA = b'A' * 1024 * 1024
        B_DATA = b'B' * 1024 * 1024

        sslctx = self._create_server_ssl_context(self.ONLYCERT, self.ONLYKEY)
        client_sslctx = self._create_client_ssl_context()

        def server(sock):
            sock.starttls(sslctx, server_side=True)

            data = sock.recv_all(len(A_DATA))
            self.assertEqual(data, A_DATA)
            sock.send(b'OK')

            data = sock.recv_all(len(B_DATA))
            self.assertEqual(data, B_DATA)
            sock.send(b'SPAM')

            sock.close()

        async def client(addr):
            extras = dict(ssl_handshake_timeout=SSL_HANDSHAKE_TIMEOUT)

            reader, writer = await asyncio.open_unix_connection(
                addr,
                ssl=client_sslctx,
                server_hostname='',
                **extras)

            writer.write(A_DATA)
            self.assertEqual(await reader.readexactly(2), b'OK')

            writer.write(B_DATA)
            self.assertEqual(await reader.readexactly(4), b'SPAM')

            nonlocal CNT
            CNT += 1

            writer.close()
            await self.wait_closed(writer)

        def run(coro):
            nonlocal CNT
            CNT = 0

            with self.unix_server(server,
                                  max_clients=TOTAL_CNT,
                                  backlog=TOTAL_CNT) as srv:
                tasks = []
                for _ in range(TOTAL_CNT):
                    tasks.append(coro(srv.addr))

                self.loop.run_until_complete(asyncio.gather(*tasks))

            self.assertEqual(CNT, TOTAL_CNT)

        with self._silence_eof_received_warning():
            run(client)

class Test_UV_UnixSSL(_TestSSL, tb.UVTestCase):
    pass

class Test_AIO_UnixSSL(_TestSSL, tb.AIOTestCase):
    pass


import unittest
from unittest.mock import patch, Mock

import sys
sys.modules['gb'] = Mock()
from LODStrategy import LODBounceBot
from random import seed
from random import uniform
from random import randint
from Test.Data.AMDTestData import happyPath
from Globals import Globals as gb
from freezegun import freeze_time
import datetime
import pytz

@freeze_time("2022-03-31 6:31:34")
class TestLODSadBot(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        requestID = 1
        ib = Mock()
        ib.reqRealTimeBars = Mock(return_value = 1)

        cls.bot = LODBounceBot.LODBounceBot(ib, "MRK")

        cls.bot.setup()

        testBars = []

        for bar in happyPath:
            testBars.extend(cls.generateBars(*bar))

        for bar in testBars:
            cls.bot.on_realtime_update(requestID, None, bar[0], bar[1], bar[2], bar[3], None, None, None)

    def test_open_order(self):
        self.assertFalse(self.bot.executionTracker.isLongOrderSent(), "Not executed")

    def test_done(self):
        self.assertTrue(self.bot.done, "Bot is not done")

    @classmethod
    def generateBars(self, _open, high, low, _close):
        seed(1)
        newStart = _open
        returnList = []

        highIndex = randint(1, 12)
        highLow = randint(1, 12)

        for i in range(12):
            newHigh = uniform(newStart, high)
            newClose = uniform(newStart, newHigh)
            newLow = uniform(low, newClose)

            if i == highIndex:
                newHigh = high

            if i == highLow:
                newLow = low

            if i == 11:
                returnList.append((newStart, newHigh, newLow, _close))
            else:
                returnList.append((newStart, newHigh, newLow, newClose))
            newStart = newClose

        return returnList
if __name__ == '__main__':
    unittest.main()


from PySide6.QtGui import Qt
from PySide6.QtWidgets import QMainWindow, QPushButton, QWidget, QGridLayout, QCheckBox, QHBoxLayout

from Selector import Selector
from src.Copy import calc

class MedToExcel(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self.data_line = False
        self.comma = False

        self.layout = QGridLayout(self)

        self.model_selector = Selector("Model")
        self.mpc_selector = Selector(".MPC")

        self.layout.addWidget(self.model_selector, 1, 0)
        self.layout.addWidget(self.mpc_selector, 2, 0)

        self.check_data_line = QCheckBox("Receive data on the same line?")
        self.check_data_line.stateChanged.connect(self.get_data_line)
        self.button_copy_data = QPushButton("Copy data")
        self.button_copy_data.clicked.connect(self.get_copy_data)
        self.check_comma = QCheckBox("Use Comma?")
        self.check_comma.stateChanged.connect(self.get_comma)

        self.layout.addWidget(self.check_data_line, 1, 1)
        self.layout.addWidget(self.button_copy_data, 3, 0)
        self.layout.addWidget(self.check_comma, 2, 1)

        # self.button.clicked.connect(self.button_clicked)

    def get_copy_data(self):
        model_file = open(self.model_selector.file_path)
        mpc_file = open(self.mpc_selector.file_path)
        calc(mpc_file, model_file, self.check_data_line.isChecked(), self.check_comma.isChecked())

    def get_data_line(self, state):
        if state == Qt.CheckState.Checked:
            self.data_line = True
        else:
            self.data_line = False

    def get_comma(self, state):
        if state == Qt.CheckState.Checked:
            self.comma = True
        else:
            self.comma = False