#!/bin/python3

import datetime
import json
import threading
import time
import turtle
import sys

from urllib import request
from collections import namedtuple

class ISS():

    def __init__(self):
        self.is_instance = True
        self._astronauts_url = 'http://api.open-notify.org/astros.json'
        self._location_url = 'http://api.open-notify.org/iss-now.json'
        self._location_tuple = namedtuple(
            'Location', ['latitude', 'longitude'])
        self._location()

    def __enter__(self):
        return self

    def __exit__(self, exctype, excinst, exctb):
        self.is_instance = False

    def __repr__(self):
        return (f'{self.__class__.__name__}:\n\tTimestamp:{self._update_timestamp}\n\tLocation:{self.location}\n\tPeople: {self.people_in_space}')

    def _get_page(self, url):
        response = request.urlopen(url)
        result = json.loads(response.read())
        return result

    def _location(self):
        result = self._get_page(self._location_url)
        self.location = self._location_tuple(result['iss_position']['latitude'],
                                             result['iss_position']['longitude'])
        self._update_timestamp = result['timestamp']

    @property
    def people_in_space(self):
        result = self._get_page(self._astronauts_url)
        return [people['name'] for people in result['people']]

class Tracker(ISS):

    def __init__(self):
        super().__init__()
        self._bgpic = 'images/map.gif'
        self._shape = 'images/iss2.gif'

        self._screen = turtle.Screen()
        self._screen.title('Python ISS Tracker')
        self._screen.setup(width=720, height=360)
        self._screen.setworldcoordinates(-180, -90, 180, 90)
        self._screen.bgpic(self._bgpic)
        self._screen.register_shape(self._shape)
        self._screen.onscreenclick(self.update_turtle_location, btn=1)

        self._tracker = turtle.Turtle()
        self._tracker.shape(self._shape)
        self._tracker.setheading(90)

    def update_turtle_location(self, *args):
        self._location()
        self._tracker.penup()
        self._tracker.goto(float(self.location[0]), float(self.location[1]))
        # Debug
        print(self.__repr__())

if __name__ == '__main__':

    try:
        with Tracker() as iss:
            iss.update_turtle_location()
        turtle.mainloop()

    except KeyboardInterrupt:
        sys.exit(0)

# # http://open-notify.org/Open-Notify-API/
# url = 'http://api.open-notify.org/astros.json'
# response = urllib.request.urlopen(url)
# result = json.loads(response.read())

# print('People in Space: ', result['number'])

# people = result['people']

# for p in people:
#   print(p['name'], ' in ', p['craft'])

# url = 'http://api.open-notify.org/iss-now.json'
# response = urllib.request.urlopen(url)
# result = json.loads(response.read())

# location = result['iss_position']
# lat = float(location['latitude'])
# lon = float(location['longitude'])
# print('Latitude: ', lat)
# print('Longitude: ', lon)

# screen = turtle.Screen()
# screen.setup(720, 360)
# screen.setworldcoordinates(-180, -90, 180, 90)
# screen.bgpic('map.gif')

# screen = turtle.Screen()
# screen.setup(720, 360)
# screen.setworldcoordinates(-180, -90, 180, 90)
# # image source:
# # map.jpg: http://visibleearth.nasa.gov/view.php?id=57752 Credit: NASA
# screen.bgpic('map.gif')

# screen.register_shape('iss2.gif')
# iss = turtle.Turtle()
# iss.shape('iss2.gif')
# iss.setheading(90)

# iss.penup()
# iss.goto(lon, lat)

# # When Does ISS next pass over me?
# #london
# #lat = 51.5072
# #lon = 0.1275

# # Tokyo
# #lat = 35.689487
# #lon = 139.691706

# # Space Center, Houston
# lat = 29.5502
# lon = -95.097

# location = turtle.Turtle()
# location.penup()
# location.color('yellow')
# location.goto(lon, lat)
# location.dot(5)
# location.hideturtle()

# url = 'http://api.open-notify.org/iss-pass.json?lat=' + \
#     str(lat) + '&lon=' + str(lon)
# response = urllib.request.urlopen(url)
# result = json.loads(response.read())

# #print result
# over = result['response'][1]['risetime']
# location.write(time.ctime(over))


def parse(line):
    f = line.split(" ")
    return f if len(f) == 1 else (f[0], int(f[1]))

def parse_items(items_l):
    f = items_l.split(":")
    return [int(i) for i in f[1].split(",")]

def parse_operation_function(operation_l):
    f = operation_l.split("=")
    g = f[1].split(" ")

    if g[-1].isdigit():
        if g[-2] == '+':
            return lambda x: (x + int(g[-1])) // 3
        else:
            return lambda x: (x * int(g[-1])) // 3
    else:
        if g[-2] == '+':
            return lambda x: (x + x) // 3
        else:
            return lambda x: (x * x) // 3

def parse_test_function(test_cond, true_cond, false_cond):
    cond_num = int(test_cond.split(" ")[-1])
    true_cond_num = int(true_cond.split(" ")[-1])
    false_cond_num = int(false_cond.split(" ")[-1])
    return lambda x: true_cond_num if x % cond_num == 0 else false_cond_num

def exec():
    with open("input2.txt") as fp:
        lines = [l.strip() for l in fp if l.strip()]

    # Parse input
    items = []
    test = []
    op = []

    for start_line in range(0, len(lines), 6):
        items.append(parse_items(lines[start_line + 1]))
        op.append(parse_operation_function(lines[start_line + 2]))
        test.append(parse_test_function(lines[start_line + 3], lines[start_line + 4], lines[start_line + 5]))

    num_monkeys = len(items)

    # Process input
    items_processed = [0 for i in range(0, num_monkeys)]

    for rnd in range(0, 20):
        for m in range(0, num_monkeys):
            items_processed[m] = items_processed[m] + len(items[m])
            for i in items[m]:
                worry_lvl = op[m](i)
                dest_monkey = test[m](worry_lvl)
                items[dest_monkey].append(worry_lvl)
            items[m] = []

        # print(f'Round {rnd + 1}: {items}')

    print(items_processed)

    s = sorted(items_processed)

    print(s[-1] * s[-2])

if __name__ == '__main__':
    exec()


"""added san and is_my_move to Move

Revision ID: f39051a2ca9b
Revises: c9b0d072e5e4
Create Date: 2020-12-16 13:05:46.434429

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'f39051a2ca9b'
down_revision = 'c9b0d072e5e4'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('moves', schema=None) as batch_op:
        batch_op.add_column(sa.Column('is_my_move', sa.Boolean(), nullable=True))
        batch_op.add_column(sa.Column('san', sa.String(length=8), nullable=True))

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('moves', schema=None) as batch_op:
        batch_op.drop_column('san')
        batch_op.drop_column('is_my_move')

    # ### end Alembic commands ###


from selenium import webdriver
from datetime import datetime
import boto3
import os
import time

now = datetime.now()
folder_name = now.strftime("%Y%m%d")
image_name = "traffic_" + now.strftime("%Y%m%d") + "-" + now.strftime("%H-%M") + ".png"
Bucket_name = "googletrafficmap"
prefix = folder_name + "/"

#Get map snapshot
driver = webdriver.PhantomJS(service_log_path=os.path.devnull)
driver.set_window_size(1920, 1080) # set the window size that you need
driver.get('http://googletrafficmap.s3-website.ca-central-1.amazonaws.com')
# driver.save_screenshot(folder_name + "/" + image_name)
screenshotPNG = driver.get_screenshot_as_png() #Get screenshot in binary data

#Create low-client connection
client = boto3.client('s3')
#Uploading image to s3 bucket and creating folder structure at the same time
client.put_object(
    Bucket = Bucket_name,
    Body = screenshotPNG,
    Key = folder_name + "/" + image_name
)

time.sleep(60)
driver.close()
driver.quit()


#!/usr/bin/env python
import sys
import shutil
from typing import Optional, List, Tuple, Dict

import typer
from rich import print
from rich.columns import Columns
from rich.console import Console
from rich.traceback import install

# fmt: off
# Mapping from topics to colors
TOPICS = {
    "TIMR": "#9a9a99",
    "VOTE": "#67a0b2",
    "LEAD": "#d0b343",
    "TERM": "#70c43f",
    "LOG1": "#4878bc",
    "LOG2": "#398280",
    "CMIT": "#98719f",
    "PERS": "#d08341",
    "SNAP": "#FD971F",
    "DROP": "#ff615c",
    "CLNT": "#00813c",
    "TEST": "#fe2c79",
    "INFO": "#ffffff",
    "WARN": "#d08341",
    "ERRO": "#fe2626",
    "TRCE": "#fe2626",
}
# fmt: on

def list_topics(value: Optional[str]):
    if value is None:
        return value
    topics = value.split(",")
    for topic in topics:
        if topic not in TOPICS:
            raise typer.BadParameter(f"topic {topic} not recognized")
    return topics

def main(
    file: typer.FileText = typer.Argument(None, help="File to read, stdin otherwise"),
    colorize: bool = typer.Option(True, "--no-color"),
    n_columns: Optional[int] = typer.Option(None, "--columns", "-c"),
    ignore: Optional[str] = typer.Option(None, "--ignore", "-i", callback=list_topics),
    just: Optional[str] = typer.Option(None, "--just", "-j", callback=list_topics),
):
    topics = list(TOPICS)

    # We can take input from a stdin (pipes) or from a file
    input_ = file if file else sys.stdin
    # Print just some topics or exclude some topics (good for avoiding verbose ones)
    if just:
        topics = just
    if ignore:
        topics = [lvl for lvl in topics if lvl not in set(ignore)]

    topics = set(topics)
    console = Console()
    width = console.size.width

    panic = False
    for line in input_:
        try:
            time, topic, *msg = line.strip().split(" ")
            # To ignore some topics
            if topic not in topics:
                continue

            msg = " ".join(msg)

            # Debug calls from the test suite aren't associated with
            # any particular peer. Otherwise we can treat second column
            # as peer id
            if topic != "TEST":
                i = int(msg[1])

            # Colorize output by using rich syntax when needed
            if colorize and topic in TOPICS:
                color = TOPICS[topic]
                msg = f"[{color}]{msg}[/{color}]"

            # Single column printing. Always the case for debug stmts in tests
            if n_columns is None or topic == "TEST":
                print(time, msg)
            # Multi column printing, timing is dropped to maximize horizontal
            # space. Heavylifting is done through rich.column.Columns object
            else:
                cols = ["" for _ in range(n_columns)]
                msg = "" + msg
                cols[i] = msg
                col_width = int(width / n_columns)
                cols = Columns(cols, width=col_width - 1, equal=True, expand=True)
                print(cols)
        except:
            # Code from tests or panics does not follow format
            # so we print it as is
            if line.startswith("panic"):
                panic = True
            # Output from tests is usually important so add a
            # horizontal line with hashes to make it more obvious
            if not panic:
                print("#" * console.width)
            print(line, end="")

if __name__ == "__main__":
    typer.run(main)


# python3

class Node:
    def __init__(self, key=None, next=None):
        self.key = key
        self.next = next

class LinkedList:
    def __init__(self):
        self.head = None

    def insert(self, key):
        self.head = Node(key, self.head)

    def check(self):
        if not self.head:
            print()
        else:
            node = self.head

            while node:
                print(node.key, end=' ')
                node = node.next
            print()

    def delete(self, key):
        if self.head:
            if self.head.key == key:
                self.head = self.head.next
            else:
                node = self.head

                while node and node.next:
                    if node.next.key == key:
                        node.next = node.next.next
                        break
                    node = node.next

    def find(self, key):
        node = self.head

        while node:
            if node.key == key:
                return 'yes'
            node = node.next

        return 'no'

def polyhash(S, p, x):
    hash = 0
    for i in range(len(S)-1, -1, -1):
        hash = ((hash*x + ord(S[i])) % p)
    return hash

if __name__ == "__main__":
    m = int(input())
    n = int(input())
    queries = [input() for i in range(n)]

    hash_map = [LinkedList() for i in range(m)]

    for i in queries:
        q = i.split()

        if q[0] == 'add':
            index = polyhash(q[1], 1000000007, 263) % m
            if hash_map[index].find(q[1]) == 'no':
                hash_map[index].insert(q[1])
        elif q[0] == 'del':
            hash_map[polyhash(q[1], 1000000007, 263) % m].delete(q[1])
        elif q[0] == 'find':
            print(hash_map[polyhash(q[1], 1000000007, 263) % m].find(q[1]))
        else:
            hash_map[int(q[1])].check()


i = 1

f = 1.2

b = True

l = [1, 2, 3]

d = {'a': 1, 'b': 2}

s = {1, 2, 3}

t = (1, 2, 3)

def greeting():
    print('Hello world')

def func(something):
    return something

# Appending a function to a list
l.append(greeting)

# Adding a function to dictionary
d.update({'greeting': greeting})


# 对学生基本信息进行画像展示分析。包括性别、年级、班级、住址、班主任等形成学生画像标签。
# 对个体维度对学生学业情况进行描述性统计分析。
# 对成绩情况进行统计，并汇总各个科目历史考试成绩趋势，
# 明确学生当前学科成绩分布特点以及未来成绩趋势，为学业干预提供输入。
# 度量指标如原始分、得分率、标准分（Z以及T分）、全年级排名、全班排名、离均值等。
# 学生消费画像分析，通过对学生一卡通消费数据，分析学生消费情况；
# 支持消费分布数据统计分析；
# 如消费趋势对比，对消费进行预警，便于了解学生生活方式尤其是贫困生，并及时干预支持消费明细的查询。
# 学生考勤画像分析，如学生考勤数据统计：如缺勤、迟到、请假、到勤的比例和实际天数；

class Student:
    def __init__(self,name='', stuId=0,sex='', grade=0, cla=0, addr='', headTeacher='', scores=[]):
        self.stuId = stuId
        self.name = name
        self.sex = sex
        self.grade = grade
        self.cla = cla
        self.addr = addr
        self.headTeacher = headTeacher
        self.scores = scores

class Teacher:
    """
    1_teacher.csv:包含了近五年各班各学科的教师信息
    term:学期
    cla_id:班级ID
    cla_Name:班级名
    gra_Name:年级名
    sub_id:学科ID
    sub_Name:学科名
    bas_id:教师id
    bas_Name:教师名
    """
    def __init__(self,term, claID, claName, graName, subID, subName, basID, basName):
        self.term = term
        self.claID = claID
        self.claName = claName
        self.graName = graName
        self.subID = subID
        self.subName = subName
        self.basID = basID
        self.basName = basName

class Score:
    """
    mes_TestID,考试id
    exam_number,考试编码
    exam_numname,考试编码名称
    mes_sub_id,考试学科id
    mes_sub_name,考试学科名
    exam_term,考试学期
    exam_type,考试类型（对应考试类型表）
    exam_sdate,考试开始时间
    mes_StudentID,学生id
    mes_Score,考试成绩(-1为作弊，-2为缺考，-3为免考)
    mes_Z_Score,换算成Z-score
    mes_T_Score,换算成T-score
    mes_dengdi：换算成等第
    """
    def __init__(self,TestID, exam_number, exam_numname, sub_id,
       sub_name, exam_term, exam_type, exam_sdate, StudentID,
       score, Z_score, T_score, dengdi):
        self.TestID = TestID
        self.exam_number = exam_number
        self.exam_numname = exam_numname
        self.sub_id =sub_id
        self.sub_name = sub_name
        self.exam_term = exam_term
        self.exam_type = exam_type
        self.exam_sdate = exam_sdate
        self.studentID = StudentID
        self.score = score
        self.T_score = T_score
        self.Z_score = Z_score
        self.dengdi = dengdi

# 班级


from serpent.game_agent import GameAgent
from serpent.input_controller import KeyboardKey
import offshoot

class SerpentSuperHexagonGameAgent(GameAgent):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.frame_handlers["PLAY"] = self.handle_play

        self.frame_handler_setups["PLAY"] = self.setup_play

        self.analytics_client = None

        #Ccontext class setup
        plugin_path = offshoot.config["file_paths"]["plugins"]

        context_classifier_path = "datasets/context_classifier.model"

        from serpent.machine_learning.context_classification.context_classifiers.cnn_inception_v3_context_classifier import \
            CNNInceptionV3ContextClassifier
        context_classifier = CNNInceptionV3ContextClassifier(
            input_shape=(240, 384, 3))  # Replace with the shape (rows, cols, channels) of your captured context frames

        context_classifier.prepare_generators()
        context_classifier.load_classifier(context_classifier_path)

        self.machine_learning_models["context_classifier"] = context_classifier

    def setup_play(self):
        # self.input_controller.tap_key(KeyboardKey.KEY_SPACE)
        pass

    def handle_play(self, game_frame):
        # for i, game_frame in enumerate(self.game_frame_buffer.frames):
        #     self.visual_debugger.store_image_data(
        #         game_frame.frame,
        #         game_frame.frame.shape,
        #         str(i)
        #     )
        # self.input_controller.tap_key(KeyboardKey.KEY_RIGHT)
        context = self.machine_learning_models["context_classifier"].predict(game_frame.frame)
        print("Context:", context)


import socket
import time

from PyQt5.QtCore import QTimer, QThread
import queue
import logging
import pyaudio
import threading

logging.basicConfig(format="%(message)s", level=logging.INFO)

class AudioRec(QThread):
    def __init__(self, threadChat):
        super().__init__()
        self.threadChat = threadChat

        self.host_name = socket.gethostname()
        self.host_ip = socket.gethostbyname(self.host_name)
        # self.host_ip = '127.0.0.1'
        self.port = 9634
        self.socket_address = (self.host_ip, self.port)

        # a maxsize 100 will be ideal but lags with video at the moment
        # must send frames from server VideoGen and make sync in client
        # using audio and frame timestamps
        self.q = queue.Queue(maxsize=5)

        self.BUFF_SIZE = 65536
        self.audio_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.audio_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.BUFF_SIZE)
        self.audio_socket.bind(self.socket_address)
        self.p = pyaudio.PyAudio()
        self.CHUNK = 1024
        self.stream = self.p.open(format=self.p.get_format_from_width(2),
                                  channels=2,
                                  rate=44100,
                                  output=True,
                                  frames_per_buffer=self.CHUNK)

        self.timer = QTimer()
        self.timer.timeout.connect(self.play_audio)
        self.timer.start(1000 * 0.8 * self.CHUNK / 44100)

        t1 = threading.Thread(target=self.get_audio_data, args=())
        t1.start()
        print('Listening for audio...')

    def get_audio_data(self):
        while self.threadChat.nickname == "":
            # print('wait audio')
            # time.sleep(0.1)
            pass

        while True:
            try:
                self.frame, _ = self.audio_socket.recvfrom(self.BUFF_SIZE)
                self.q.put(self.frame)
            except BlockingIOError:
                pass
            except Exception as e:
                logging.error(e)

    def play_audio(self):
        if not self.q.empty():
            frame = self.q.get()
            self.stream.write(frame)


print("Mustafa kapasi")

# a = int(input("Enter your name:"))
# print(a)

# b =  [1 , 3, 4, 5]

# print(b)
# print(b[1])

# b[0] = 35
# print(b)

# c = (45 , 32, 43, 12)
# print(c)

# c[0] = 24
# print(c)

# calculating orders

print("Welcome to Our Restaurant")
a1 = 0
a2 = 0
b1 = 0
b2 = 0

print("Enter 1 for punjabi menu and 2 for gujarati menu : ")
ch = int(input())

if (ch==1) :
    print("Panner bhurji 100Rs\nPanner toofani 130Rs")
    print("Now enter 1 for panner bhurji and 2 for panner toofani : ")
    a = int(input())
    if(a==1) :
        a1 = a1 + 1
    elif (a==2) :
        a2 = a2 + 1
    else :
        print("enter number 1 or 2")

elif (ch==2) :
    print("Sev tameta 100Rs\nFlower bataka 140Rs")
    print("Now enter 1 for Sev tameta and 2 for flower bateka : ")
    b = int(input())
    if(b==1) :
        b1 = b1 + 1
    elif (b==2) :
        b2 = b2 + 1
    else :
        print("enter number 1 or 2")

else :
    print("enter number 1 or 2")


def merge_files(filenames, output_filename):
    with open(output_filename, 'a') as output_file:
        for filename in filenames:
            with open(filename, 'r') as input_file:
                output_file.write(input_file.read())
                output_file.write('\n')  # Add a new line between each file's content

# List to store input filenames
input_files = []

# Accept eight text file paths from the user
for i in range(1, 9):
    file_path = input(f"Enter path of text file {i}: ")
    input_files.append(file_path)

# Output filename
output_file = 'all.txt'

# Merge the files
merge_files(input_files, output_file)

print("Merging completed! The content of all the files has been appended into 'all.txt'.")


import numpy as np
from sklearn.metrics import f1_score
from sklearn.naive_bayes import BernoulliNB
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer

class NaiveBayes:
    """
    Naive Bayes implementation based on Multi-variate Bernoulli using python
    """
    def __init__(self):
        """
        self.class_probability --> Class probability of shape (output_label, ). It indicates the probability of alpha label appearing
                       without seeing the input data.
        self.phi --> Probability of alpha input feature given alpha output label. P(x|y_train). shape (output_label, input_feature)
        self.output_label --> Number of output class
        self.input_feature --> Number of input feature
        """
        self.class_probability = None
        self.phi = None
        self.output_label = None

    def fit(self, x_train, y_train):
        """
        Train the model
        :param x_train: Input training example of shape (number of training data, input feature)
        :param y_train: Output training example of shape (number of training data, )
        :return:
        """
        m = x_train.shape[0]  # Number of training example
        # Flatten the training set
        x_train = x_train.reshape(m, -1)
        input_features = x_train.shape[1]
        self.output_label = len(np.unique(y_train.reshape(-1)))
        # Initialize everything with zero
        self.class_probability = np.zeros(self.output_label)
        self.phi = np.zeros((self.output_label, input_features))
        # Calculate class probability and phi
        for label in range(self.output_label):
            # Extract the training data from an individual labels
            current_label_data = x_train[y_train == label]
            # Number of occurarances of this particular label in the training set
            current_label_occur = current_label_data.shape[0]
            # Class label of this training data
            self.class_probability[label] = (current_label_occur + 1) / (m + self.output_label)
            # Calculate phi for an individual label
            # How many times each of the input feature appeared for this label
            # One is added for laplace smoothing
            input_feature_occur = np.sum(current_label_data, axis=0) + 1
            # Fix the denominator according to the laplace smoothing
            curr_label_laplace_smoothing = current_label_occur + self.output_label
            # Calculate phi
            self.phi[label, :] = input_feature_occur / curr_label_laplace_smoothing

    def predict(self, x_test):
        """
        Make prediction
        :param x_test: data to predict of shape (number of prediction, input feature)
        :return:
        """
        # Number of prediction
        num_of_test = x_test.shape[0]
        # Probability of each of the class.
        # Initially each of the label will have zero probability
        probabilities = np.zeros((num_of_test, self.output_label))
        # Calculate for all test
        for test_index in range(num_of_test):
            # Count probabilities for each of the classes
            for label in range(self.output_label):
                # First get all the words present in this test example
                words_for_this_example = x_test[test_index] == 1
                # Get the calculated probabilities for this label and this ese words example
                words_probabilities = self.phi[label][words_for_this_example]
                # Multiply all these probability
                words_probability_multiply = np.prod(words_probabilities)
                # Multiply this with class_probability probabilities/class probabilities
                # to get the overall probability of this example
                probabilities[test_index, label] = words_probability_multiply * self.class_probability[label]
            # Normalize the probabilities
            probabilities[test_index] /= np.sum(probabilities[test_index])
        # return the maximum probability index
        return np.argmax(probabilities, axis=1)

    def get_f1_score(self, x_test, y_test):
        """
        Calculate the f1 score of our model
        :param x_test:
        :param y_test:
        :return:
        """
        return f1_score(y_test, self.predict(x_test))

if __name__ == '__main__':
    # Test our model with amazon cell review dataset.
    # Where model will predict if alpha review is positive or negetive
    # Read the dataset
    with open("amazon_cells_labelled.txt", "r") as file:
        # This will contain all the sentences
        sentences = []
        # This will contain all the output label(0, 1)
        labels = []
        for line in file.readlines():
            # The label and sentences are separated with alpha tab
            line_arr = line.strip().split("\t")
            # Remove stop words
            sentences.append(line_arr[0])
            labels.append(int(line_arr[1]))

    # Vectorize the training sentences
    vectorizer = CountVectorizer(analyzer="word", lowercase=True, stop_words="english", max_features=4500)
    data = vectorizer.fit_transform(sentences).toarray()

    # Split data
    x_train, x_test, y_train, y_test = train_test_split(data, np.array(labels))

    # Fit to our model
    naive_bayes = NaiveBayes()
    naive_bayes.fit(x_train, y_train)
    model_f1_score = naive_bayes.get_f1_score(x_test, y_test)
    print("F1 score of test set of our model is : ", str(model_f1_score))

    # Compare with scikit-learn model
    sci_naive_bayes = BernoulliNB()
    sci_naive_bayes.fit(x_train, y_train)
    sk_prediction = sci_naive_bayes.predict(x_test)
    print("F1 score of the test set of scikit learn model is : ", str(f1_score(y_test, sk_prediction)))


from numba import *
from numba import error

#@autojit
def func():
    if x:
        print("hello")
    else:
        print("world")

def compile_func1():
    try:
        jit(void())(func)
    except error.NumbaError as e:
        print("exception: %s" % e)

__doc__ = """
>>> compile_func1()
--------------------- Numba Encountered Errors or Warnings ---------------------
    if x:
-------^
Error 6:7: No global named 'x'
--------------------------------------------------------------------------------
exception: 6:7: No global named 'x'
"""

#@autojit
def func2():
    print(10[20])

def compile_func2():
    try:
        jit(void())(func2)
    except error.NumbaError as e:
        print("exception: %s" % e)

__doc__ += """>>> compile_func2()
--------------------- Numba Encountered Errors or Warnings ---------------------
    print(10[20])
----------^
Error 29:10: object of type int cannot be indexed
--------------------------------------------------------------------------------
exception: 29:10: object of type int cannot be indexed
"""

@autojit # this often messes up line numbers
def func_decorated():
    print(10[20])

def compile_func3():
    try:
        func_decorated()
    except error.NumbaError as e:
        print("exception: %s" % e)

__doc__ += """
>>> compile_func3()
--------------------- Numba Encountered Errors or Warnings ---------------------
    print(10[20])
----------^
Error 48:10: object of type int cannot be indexed
--------------------------------------------------------------------------------
exception: 48:10: object of type int cannot be indexed
"""

if __name__ == '__main__':
    import numba
    numba.testmod()


from tkinter import *

fenetre = Tk()

import debug as de
import sauvegarde as sauvegarde
import plateau as plateau
import pions as pions
import gestionnaire_evenements as g_evenements
import menu as menu
import gestionnaire_images as g_images
import ast

# -*- coding: utf-8 -*-
"""
Created on Mon Mar 13 18:48:54 2017

@author: Pierre Monrocq
"""

#Paramètres d'affichage
fenetre.title('Latroncules')
FENETRE_LARGEUR = "1000"
FENETRE_HAUTEUR = "580"
fenetre.geometry(FENETRE_LARGEUR+"x"+FENETRE_HAUTEUR)
fenetre.resizable(0, 0)
can = Canvas(fenetre,height=FENETRE_HAUTEUR,width=FENETRE_LARGEUR,bg="#d5d5d5")

#Menu
imgmenu = can.create_image(500,290,image=g_images.menu)
bm = Button(can, text="NOUVELLE PARTIE",fg="#f5f5f5",bg="#262625",highlightthickness = 0,bd=0,borderwidth=5,font = ('Helvetica',12))
bm2 = Button(can, text="CONTINUER PARTIE",fg="#f5f5f5",bg="#262625",highlightthickness = 0,bd=0,borderwidth=5,font = ('Helvetica',12))
bm4 = Button(can, text="QUITTER",fg="#f5f5f5",bg="#262625",highlightthickness = 0,bd=0,borderwidth=5,font = ('Helvetica',12))
bm3 = Button(can, text="AIDE",fg="#f5f5f5",bg="#262625",highlightthickness = 0,bd=0,borderwidth=5,font = ('Helvetica',12))

bm.configure(width=20,height=1,activebackground = "#b9b8b6", relief = FLAT, command= lambda: lancer_jeu(can))
bm2.configure(width=20,height=1,activebackground = "#b9b8b6", relief = FLAT, command= lambda: lancer_jeu(can,True),state=DISABLED)
bm3.configure(width=20,height=1,activebackground = "#b9b8b6", relief = FLAT,command= lambda: print("Merci de consulter le mode mode d’emploi, situé dans le dossier rapport."))
bm4.configure(width=20,height=1,activebackground = "#b9b8b6", relief = FLAT, command=fenetre.destroy)

bm.place(relx=0.5,rely=0.48,anchor=CENTER)
bm2.place(relx=0.5,rely=0.38,anchor=CENTER)
bm4.place(relx=0.5,rely=0.68,anchor=CENTER)
bm3.place(relx=0.5,rely=0.58,anchor=CENTER)
can.pack()

if(sauvegarde.fichier_existant() == True):#Si il y a déjà une partie enregistrée
    bm2.configure(state=NORMAL)
    can.pack()

def lancer_jeu(can,*continuer):
    """
    Lance le jeu et appel les autres fonctions

   :param can: Canvas Tkinter
   :type can: Objet Tkinter
   :param continuer: Si la condition continuer est vraie le jeu charge une partie existante (default false) (facultatif)
   :type continuer: Booléen
   """
    #Debut du calcul du temps d'execution
    deb = de.afficher_temps_execution_debut()

    #suppression du menu
    global bm,bm2,bm3,bm4,imgmenu
    bm2.configure(state=NORMAL)
    menu.supprimer_boutons_menu(bm,bm2,bm3,bm4)
    menu.supprimer_fond_menu(can,imgmenu)

    #Fonctions de création du plateau
    plateau.generer_plateaux(can,g_images.case_noire_iso,g_images.case_blanche_iso,g_images.case_noire_plat,g_images.case_blanche_plat)
    if(True in continuer):#Chargement d'une partie existante
        grille = ast.literal_eval(sauvegarde.charger_grille_partie())
        pions.tour = int(sauvegarde.charger_tour_partie())
        pions.afficher_pions_captures(can,grille,"C","c",g_images.cavalier_blanc_plat,g_images.cavalier_noir_plat)
    else:#sinon creation d'une nouvelle partie
        grille = pions.ajouter_pions_grille(8)
    pions.afficher_pions_plateau_plat(grille,can)
    pions.afficher_pions_plateau_iso(grille,can)
    g_evenements.afficher_tour(can,pions.tour,g_images.tourn,g_images.tourb)
    de.afficher_temps_execution_fin(deb, "Lancement en")

    #Boutons en jeu
    but = Button(can, text="CHANGER DE VUE", command= lambda: g_evenements.changement_vue(can),fg="#f5f5f5",bg="#8c8c8b",highlightthickness = 0,bd=0,borderwidth=5)
    but.configure(width = 14, activebackground = "#b9b8b6", relief = FLAT)
    but.place(relx=0.1,rely=0.05,anchor=CENTER)
    b2 = Button(can, text="NOUVELLE PARTIE",fg="#f5f5f5",bg="#8c8c8b",highlightthickness = 0,bd=0,borderwidth=5)
    b2.configure(width = 14, activebackground = "#b9b8b6", relief = FLAT,command=lambda: g_evenements.partie_termine(fenetre,can))
    b2.place(relx=0.9,rely=0.05,anchor=CENTER)

    #Evenements
    can.bind("<Button-1>",lambda event: pions.selectionner_pion(event,grille,can))
    can.bind("<Button-3>",lambda event: pions.deplacer_pion(event,fenetre,grille,can))
    fenetre.protocol("WM_DELETE_WINDOW",lambda: g_evenements.confirmer_quitter(fenetre,grille,pions.tour))

#Execution de la boucle principale Tkinter
fenetre.mainloop()


# pylint: disable=E0401
import js
import functools
from pyodide.ffi import create_once_callable, create_proxy
from enum import Enum
from typing import Callable, TypedDict, Sequence, MutableMapping, Union

State = MutableMapping[str, Union[str, int, dict, list, None]]
Actions = dict[str, Callable]

Attributes = dict[str, Union[str, int, tuple[str]]]

class VDom(TypedDict):
    node_name: str
    attributes: Attributes
    children: Sequence[Union[str, "VDom"]]

def p(
    node_name: str, attributes: Attributes, children: Sequence[Union[str, "VDom"]]
) -> VDom:
    if not isinstance(children, Sequence):
        return {
            "node_name": node_name,
            "attributes": attributes,
            "children": [children],
        }

    return {"node_name": node_name, "attributes": attributes, "children": children}

class App:
    def __init__(
        self,
        selector: str,
        state: State,
        view: Callable[[State, Actions], VDom],
        actions: Actions,
    ):
        def dispatch_action(action, state, data):
            action(state, data)
            self.resolve_node()

        self.view = view
        self.state = state
        self.actions = {
            name: functools.partial(dispatch_action, action)
            for name, action in actions.items()
        }
        self.skip_render = False
        self.new_node = None
        self.current_node = None
        self.dom_manager = DomManager(selector)
        self.resolve_node()

    def resolve_node(self):
        self.new_node = self.view(self.state, self.actions)
        self.schedule_render()

    def render(self, _):
        self.dom_manager.render(self.new_node)
        self.skip_render = False

    def schedule_render(self):
        if not self.skip_render:
            self.skip_render = True

        js.requestAnimationFrame(create_once_callable(self.render))

class DomManager:
    def __init__(self, selector: str) -> None:
        self.element = js.document.querySelector(selector)
        self.element.innerHTML = ""
        self.v_current_node = None

    class ChangeType(Enum):
        NONE = 1
        TYPE = 2
        TEXT = 3
        NODE = 4
        VALUE = 5
        ATTR = 6

    def render(self, v_new_node):
        if self.v_current_node:
            self.update_element(self.element, self.v_current_node, v_new_node)
        else:
            self.element.appendChild(self.create_element(v_new_node))

        self.v_current_node = v_new_node

    def create_element(self, v_node):
        if not self.is_v_node(v_node):
            return js.document.createTextNode(str(v_node))

        element = js.document.createElement(v_node["node_name"])
        self.set_attributes(element, v_node["attributes"])

        for child in v_node["children"]:
            element.appendChild(self.create_element(child))

        return element

    def set_attributes(self, element, attributes):
        for attr, value in attributes.items():
            if self.is_event_attr(attr):
                element.addEventListener(attr[2:].lower(), create_proxy(value))
            else:
                element.setAttribute(str(attr), value)

    def update_element(
        self, parent_node, v_current_node, v_new_node, current_node_index=0
    ):
        if not v_current_node:
            parent_node.appendChild(self.create_element(v_new_node))
            return

        current_node = (
            parent_node.childNodes[current_node_index]
            if len(parent_node.childNodes) > current_node_index
            else parent_node.childNodes[-1]
        )

        if not v_new_node:
            parent_node.removeChild(current_node)
            return

        change_type = self.change_type(v_current_node, v_new_node)

        if change_type in [
            self.ChangeType.TYPE,
            self.ChangeType.TEXT,
            self.ChangeType.NODE,
        ]:
            parent_node.replaceChild(self.create_element(v_new_node), current_node)

        if change_type == self.ChangeType.VALUE:
            current_node.value = v_new_node["attributes"].get("value")

        if change_type == self.ChangeType.ATTR:
            self.update_attributes(
                current_node, v_current_node["attributes"], v_new_node["attributes"]
            )

        if not self.is_v_node(v_current_node) or not self.is_v_node(v_new_node):
            return

        for i in range(
            max([len(v_current_node["children"]), len(v_new_node["children"])])
        ):
            v_current_node_child = (
                v_current_node["children"][i]
                if i < len(v_current_node["children"])
                else None
            )
            v_new_node_child = (
                v_new_node["children"][i] if i < len(v_new_node["children"]) else None
            )

            self.update_element(current_node, v_current_node_child, v_new_node_child, i)

    def update_attributes(self, target_node, current_attributes, new_attributes):
        for attr in list(set(current_attributes.keys()) - set(new_attributes)):
            if self.is_event_attr(str(attr)):
                continue
            target_node.removeAttribute(str(attr))

        for attr, value in new_attributes.items():
            if (
                self.is_event_attr(str(attr))
                or current_attributes.get(str(attr)) == value
            ):
                continue
            target_node.setAttribute(str(attr), value)

    def change_type(self, a, b):
        if a.__class__.__name__ != b.__class__.__name__:
            return self.ChangeType.TYPE

        if not self.is_v_node(a) and a != b:
            return self.ChangeType.TEXT

        if self.is_v_node(a) and self.is_v_node(b):
            if a["node_name"] != b["node_name"]:
                return self.ChangeType.NODE

            if a["attributes"].get("value") != b["attributes"].get("value"):
                return self.ChangeType.VALUE

            if a["attributes"] != b["attributes"]:
                return self.ChangeType.ATTR

        return self.ChangeType.NONE

    def is_v_node(self, node):
        return isinstance(node, dict)

    def is_event_attr(self, attr: str):
        return attr.startswith("on")


# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------
from datetime import datetime
import re
import importlib
import inspect
import logging
import os
import sys
import sphinx
import megengine

# -- Project information -----------------------------------------------------

project = 'MegEngine'
copyright = f'2020-{datetime.now().year}, The MegEngine Open Source Team'
author = 'The MegEngine Open Source Team'
version = megengine.__version__
release = version

# -- General configuration ---------------------------------------------------

extensions = [
    'nbsphinx',
    'recommonmark',
    'sphinx.ext.napoleon',
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.doctest',
    'sphinx.ext.extlinks',
    'sphinx.ext.intersphinx',
    'sphinx.ext.mathjax',
    'sphinx.ext.viewcode',
    'sphinx.ext.githubpages',
    'sphinx.ext.graphviz',
    'sphinxcontrib.mermaid',
    'sphinx_autodoc_typehints',
    'sphinx_copybutton'
]

source_suffix = {
    '.rst': 'restructuredtext',
    '.txt': 'markdown',
    '.md': 'markdown',
}

source_encoding = "utf-8"

master_doc = 'index'
templates_path = ['_templates']
exclude_patterns = [
    '_build',
    'build',
    'examples',
    '**/includes/**',
    '**.ipynb_checkpoints'
]

# -- Options for internationalization ----------------------------------------

language = 'zh_CN'

# By default, the document `functional/loss.rst` ends up in the `functional` text domain.
# With this option set to False, it is `functional/loss`.
gettext_compact = False

# -- Options for Extensions -------------------------------------------------

# Setting for sphinx.ext.autosummary to auto-generate single html pages
# Please makesure all api pages are stored in `/refenrece/api/` directory
autosummary_generate = True

# Setting for sphinx.ext.auotdoc
autodoc_default_options = {
    'member-order': 'bysource', # Need developer organize the source code
    'show-inheritance': True,  # But it can not refer the short module path
}
autoclass_content = 'class'
autodoc_typehints = 'description'
autodoc_docstring_signature = True
add_function_parentheses = False
add_module_names = False

# Setting for sphinx.ext.mathjax
# The path to the JavaScript file to include in the HTML files in order to load MathJax.
mathjax_path = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'

mathjax_config = {
    'extensions': ['tex2jax.js'],
    'jax': ['input/TeX', 'output/HTML-CSS'],
}

# Setting for sphinxcontrib-mermaid
mermaid_version = 'latest' # from CDN unpkg.com

# Setting for sphinx.ext.intersphinx
# Useful for refenrece other projects, eg. :py:class:`zipfile.ZipFile`
intersphinx_mapping = {
    'python': ('https://docs.python.org/3/', None),
    'numpy': ('https://numpy.org/doc/stable/', None),
}

# Setting for sphinx.ext.extlinks
# Can use the alias name as a new role, e.g. :issue:`123`
extlinks = {
    'src': ('https://github.com/MegEngine/MegEngine/blob/master/%s', ''),
    'docs': ('https://github.com/MegEngine/Documentation/blob/master/%s', ''),
    'issue': ('https://github.com/MegEngine/MegEngine/issues/%s', 'Issue #'),
    'pull': ('https://github.com/MegEngine/MegEngine/pull/%s', 'Pull Requset #'),
    'duref': ('http://docutils.sourceforge.net/docs/ref/rst/'
                      'restructuredtext.html#%s', ''),
}

# Setting for sphinx.ext.nbsphinx
# nbsphinx do not use requirejs (breaks bootstrap)
nbsphinx_requirejs_path = ""
logger = logging.getLogger(__name__)

try:
    import nbconvert
except ImportError:
    logger.warning("nbconvert not installed. Skipping notebooks.")
    exclude_patterns.append("**/*.ipynb")
else:
    try:
        nbconvert.utils.pandoc.get_pandoc_version()
    except nbconvert.utils.pandoc.PandocMissing:
        logger.warning("Pandoc not installed. Skipping notebooks.")
        exclude_patterns.append("**/*.ipynb")

# -- Options for HTML output -------------------------------------------------

html_theme = 'pydata_sphinx_theme'
html_theme_path = ['_themes']
html_theme_options = {
    'search_bar_text': '输入搜索文本...',
    'search_bar_position': 'navbar',
    'github_url': 'https://github.com/MegEngine/MegEngine',
    'external_links': [
        { 'name': '论坛', 'url': 'https://discuss.megengine.org.cn/'},
        { 'name': '官网', 'url': 'https://megengine.org.cn/'}
    ],
    'use_edit_page_button': False,
    'navigation_with_keys': False,
    'show_prev_next': False,
    'use_version_switch': True,
    'version_switch_json_url': '/doc/version.json',
    'version_switch_enable_locale': True,
    'version_switch_locates': ['zh', 'en']
}

html_sidebars = {
    '**': ['sidebar-search-bs.html', 'sidebar-nav-bs.html'],
    'index': ['sidebar-search-bs.html', 'homepage-sidebar.html']
}

html_static_path = ['_static']
html_logo = "logo.png"
html_favicon = "favicon.ico"
html_css_files = [
    'css/custom.css'
]
html_js_files = [
    'js/custom.js'
]

html_search_language = 'zh'


import sys
input = sys.stdin.readline

n, k = map(int, input().split())
data = list(map(int, input().split()))

ans = 0

start = 0
end = 20*n
while start <= end:

    # 그룹들의 최소가 mid인가?
    mid = (start + end) // 2

    my_sum = 0
    count = 0

    for i in range(n):
        my_sum += data[i]
        if my_sum >= mid:
            count += 1
            my_sum = 0

    if count >= k:
        start = mid + 1
        ans = mid
    else:
        end = mid - 1

print(ans)


# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from flask import Flask, request, jsonify, make_response, abort
import requests
from stations import stations

app = Flask(__name__)

name = [
    'station_train_code',
    'from_station_name',
    'to_station_name',
    'lishi',
    'start_time',
    'arrive_time',
    'swz_num',
    'tz_num',
    'zy_num',
    'ze_num',
    'gr_num',
    'rw_num',
    'yw_num',
    'rz_num',
    'yz_num',
    'wz_num',
    'qt_num']

@app.route('/zd')
def zd_tickets():
    tickets = []
    date = request.args.get('Date')
    from_station = request.args.get('from')
    to_station = request.args.get('to')
    if from_station in stations.keys() and to_station in stations.keys():
        from_station = stations[from_station]
        to_station = stations[to_station]
    else:
        abort(400)

    url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.\
        format(date, from_station, to_station)
    r = requests.get(url, verify=False)
    # if the url param 'date'was supplied incorrectly, 12306 would return -1 of int type.
    if r.json() == -1:
        abort(400)
    if 'datas' in r.json()['data']:
        contents = r.json()['data']['datas']

        # get out the information that we want in the contents dict.
        for content in contents:
            ticket = {key: content[key] for key in name}
            tickets.append(ticket)
    else:
        abort(404)

    return jsonify({'tickets': tickets})

@app.route('/hc')
def hc_tickets():
    tickets_1 = []
    tickets_2 = []
    date = request.args.get('Date')
    from_station = request.args.get('from')
    to_station = request.args.get('to')
    changed_station = request.args.get('change')
    if from_station in stations.keys() and to_station in stations.keys() and changed_station in stations.keys():
        from_station = stations[from_station]
        to_station = stations[to_station]
        changed_station = stations[changed_station]
    else:
        abort(400)

    url1 = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'. \
        format(date, from_station, changed_station)
    r1 = requests.get(url1, verify=False)

    if r1.json() == -1:
        abort(400)

    if 'datas' in r1.json()['data']:
        contents_1 = r1.json()['data']['datas']

        for content in contents_1:
            ticket = {key: content[key] for key in name}
            tickets_1.append(ticket)
    else:
        abort(404)

    for ticket in tickets_1:
        if int(ticket['lishi'][:2]) + int(ticket['start_time'][:2]) < 24:  # TODO
            url2 = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT' \
                   '&queryDate={}&from_station={}&to_station={}'. \
                format(date, changed_station, to_station)
            r2 = requests.get(url2, verify=False)

            if r2.json() == -1:
                abort(400)

            if 'datas' in r2.json()['data']:
                contents_2 = r2.json()['data']['datas']

                for content in contents_2:
                    ticket = {key: content[key] for key in name}
                    tickets_2.append(ticket)

                if tickets_2:
                    for x in tickets_1:
                        x['changed_ticket'] = [y for y in tickets_2 if
                                               1 < int(y['start_time'][:2]) - int(x['arrive_time'][:2]) < 3]
            else:
                abort(404)

        else:
            # if the first train arrived at next day, we add one day to the queryDate param.
            date2 = str(datetime.strptime(date, '%Y-%m-%d') + timedelta(days=1))[:10]

            # TODO: the following repeatedly codes should be moved to a helper method.
            url2 = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT' \
                   '&queryDate={}&from_station={}&to_station={}'. \
                format(date2, changed_station, to_station)
            r2 = requests.get(url2, verify=False)

            if r2.json() == -1:
                abort(400)

            if 'datas' in r2.json()['data']:
                contents_2 = r2.json()['data']['datas']

                for content in contents_2:
                    ticket = {key: content[key] for key in name}
                    tickets_2.append(ticket)

                if tickets_2:
                    for x in tickets_1:
                        x['changed_ticket'] = [y for y in tickets_2 if
                                           1 < int(y['start_time'][:2]) - int(x['arrive_time'][:2]) < 3]

    return jsonify({'tickets': tickets_1})

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

@app.errorhandler(400)
def bad_request(error):
    return make_response(jsonify({'error': 'Please check your query param format'}), 400)

if __name__ == '__main__':
    app.run(debug=True)


import math

def calculatein(main_list, dictionary, imm, non_imm):

    time_loss = 0

    for f, l in imm:
        fir = main_list.index(f)
        sec = main_list.index(l)
        order = [fir, sec]
        order.sort()
        sub_list = main_list[order[0]+1: order[1]+1]

        for i in range(0, len(sub_list)):
            sub_list[i] = dictionary[sub_list[i]]

        time_loss += sum(sub_list)

    for f, l in non_imm:
        fir = main_list.index(f)
        sec = main_list.index(l)

        order = [fir, sec]
        order.sort()

        sub_list = main_list[order[0]+1: order[1]+1]

        for i in range(0, len(sub_list)):
            sub_list[i] = dictionary[sub_list[i]]

        time_loss += 15-sum(sub_list)

    return time_loss

condition = input('enter condition(works, prerequired, imm, non_imm): ')
condition = condition.strip().split()

print(condition)

n_work = int(condition[0])
n_prereq = int(condition[1])
n_imm = int(condition[2])
n_non_imm = int(condition[3])

work_time = input('enter works required times: ')
work_time = work_time.strip().split()

print(work_time)

string = [str(i) for i in range(1, 16)]
print(string)

count = 0
work_dict = dict()

for time in work_time:
    work_dict[string[count]] = int(time)
    count += 1

print(work_dict)

prereq = []

for x in range(0, int(n_prereq)):
    pr = input('enter prerequirments: ')
    pr = pr.strip().split()
    prereq.append((pr[0], pr[1]))

print(prereq)

imm = []

for x in range(0, int(n_imm)):
    imd = input('enter immediate works: ')
    imd = imd.strip().split()
    imm.append((imd[0], imd[1]))

print(imm)

non_imm = []

for x in range(0, int(n_non_imm)):
    nimd = input('enter non-immediate: ')
    nimd = nimd.strip().split()
    non_imm.append((nimd[0], nimd[1]))

print(non_imm)

def sort_prereq(main_list, prereq):
    pass

def sort_imm(main_list, imm):
    pass

def sort_non_imm(main_list, non_imm):
    pass

with open('/tmp/all.list', 'a') as file:
    elements = [i for i in list(work_dict.keys())]
    print(elements)
    for x in elements:
        count = math.factorial(len(elements) - 1)
        print(count)

# یک راه پیدا کردم که شاید جواب بده.
# این که لیست های مطابق پیش نیاز ها رو جدا کنم و یکی که
# کمترین ضرر رو به بار میاره رو جدا کنم


from datetime import datetime, timezone
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
import logging
import os
import mongo_client
from typing import Optional, List, Union
import random

client = WebClient(token=os.environ.get("SLACK_TOKEN"))

good_words_collection = mongo_client.get_good_words_collection()

EMOJIS = os.environ.get("VALID_EMOJIS").split(' ')

def add_historical_goodwords():
    # Call the conversations.list method using the WebClient
    result = client.conversations_history(channel="C0441R6SKBN")
    conversation_history = result["messages"]
    for message in conversation_history:
        word = message['text']
        date_millis = float(message['ts'])
        user_id = message['user']
        temp_list = list(filter(lambda a: len(a) > 0, word.split(" ")))
        if len(temp_list) == 1:
            handle_word_sent(temp_list[0], date_millis, user_id, True)

def process_event(event: object):
    if event.get('text', False) and event.get('ts', False) and event.get('user', False):
        if event.get('thread_ts', False):
            print(f"Replies to posts not accepted.")
            return
        message = event['text']
        millis_time = float(event['ts'])
        user = event['user']
        channel = event['channel']
        temp_list = list(filter(lambda a: len(a) > 0, message.split(" ")))
        if len(temp_list) > 1 or channel != "C0441R6SKBN":
            print(f"invalid submission: {temp_list}")
        else:
            handle_word_sent(temp_list[0], millis_time, user)
    else:
        print(f"Event missing attribute ts or text: {event}")

def handle_word_sent(word: str, millis_time: float, user_id: str, historical: bool=False):
    prev_sent = find_word(word)
    if prev_sent is not None:
        if not historical:
            client.chat_postMessage(channel="C0441R6SKBN", text=f"{word} was previously sent on {datetime.fromtimestamp(prev_sent['date_millis']).strftime('%m/%d/%Y')}", thread_ts=str(millis_time))
        print(f"Thread Time: {datetime.fromtimestamp(prev_sent['date_millis']).strftime('%m/%d/%Y')}, Prev Sent Word: {word}")
    elif not historical:
        insert_new_word(word, millis_time, user_id)
        client.reactions_add(channel="C0441R6SKBN", name=random.choice(EMOJIS), timestamp=str(millis_time))
    else:
        insert_new_word(word, millis_time, user_id)

def insert_new_word(word: str, date_millis: float, user: str):
    word_lowercase = word.lower()
    document = {
        "word": word_lowercase,
        "date_millis": date_millis,
        "user_id": user
    }
    good_words_collection.insert_one(document)
    print(f"Successfully added word: \n {document['word']} \n millis: {document['date_millis']}")

def find_word(word: str):
    result = good_words_collection.find_one({"word": word.lower()})
    print(f"Found: {result}")
    return result


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.db import transaction
from django.template import loader
from django.core.exceptions import ValidationError
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from django.core.mail import send_mail, BadHeaderError
from django.contrib.auth.decorators import login_required
from .forms import UserForm, RegisterForm, UserProfileForm, ContactForm
from .models import UserProfile, Event

def index(request):
    template = loader.get_template("help/index.html")
    return HttpResponse(template.render(request=request))

@transaction.atomic
def register(request):
    registered = False
    if request.method == "POST":
        user_form = RegisterForm(data=request.POST)
        userprofile_form = UserProfileForm(data=request.POST)
        if user_form.is_valid() and userprofile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            phone = userprofile_form.cleaned_data.get("phone")
            userprofile = UserProfile.objects.filter(user_id=user.id)
            userprofile.update(phone=phone)
            registered = True
        else:
            messages.error(request, (
                'Veuillez corriger les erreurs ci-dessous.'))
    else:
        user_form = RegisterForm()
        userprofile_form = UserProfileForm()
    return render(
        request, "help/registration.html", {
            "user_form": user_form,
            "userprofile_form": userprofile_form,
            "registered": registered}
    )

def logout2(request):
    logout(request)
    return redirect(reverse("index"))

@login_required()
def update_event(request):
    if request.method == "POST":
        id = request.POST['event_id']
        event = Event.objects.filter(id=id)
        event.update(status="closed")

        return redirect(reverse('profile'))

    else:
        user_form = RegisterForm()
        userprofile_form = UserProfileForm()
    return render(request, "help/profile.html")

def contact(request):
    send = False
    email = []
    contact_form = ContactForm()
    if request.method == "POST":
        subject = "demande d'info"
        from_email = "needhelp_contact"
        email.append(request.POST['Email'])
        body = {
            'name': request.POST['Nom'],
            'email': request.POST['Email'],
            'phone': request.POST['Mobile'],
            'message': request.POST['Message'],
            }
        message = "\n".join(body.values())

        try:
            send_mail(
                subject,
                message,
                from_email,
                email
                )

        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        send = True
        # return redirect(reverse('contact'))
    else:
        contact_form = ContactForm()

    return render(
        request, "help/contact.html",
        {
            'contact_form': contact_form,
            'send': send
        })


import os
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms

class AnimeDataset(Dataset):

    def __init__(self, dataset_path, image_size):
        self.transform = transforms.Compose([
            transforms.Resize(image_size),
            transforms.CenterCrop(image_size),
            transforms.ToTensor(),
            transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
        ])
        self.paths = [os.path.join(dataset_path, name) for name in os.listdir(dataset_path)]

    def __getitem__(self, item):
        image = Image.open(self.paths[item])
        data = self.transform(image)
        return data

    def __len__(self):
        return len(self.paths)

class LossWriter:
    def __init__(self, save_path):
        self.save_path = save_path

    def add(self, loss, i):
        with open(self.save_path, mode="a") as f:
            term = str(i) + " " + str(loss) + "\n"
            f.write(term)
            f.close()

def recover_image(img):
    return (
            (img.numpy() *
             np.array([0.5, 0.5, 0.5]).reshape((1, 3, 1, 1)) +
             np.array([0.5, 0.5, 0.5]).reshape((1, 3, 1, 1))
             ).transpose(0, 2, 3, 1) * 255
    ).clip(0, 255).astype(np.uint8)


"""
   crown.py
   COMP9444, CSE, UNSW
"""

import torch
import torch.nn as nn
import matplotlib.pyplot as plt

# the data for this task has three columns: x y and class.
# the input of nn will be x and y, and the output will be a binary class.
class Full3Net(torch.nn.Module):
  # assume we have a linear nn here:
    def __init__(self, hid=3):
        super(Full3Net, self).__init__()
        # define the structure of the nn
        # define the first hidden layer: size of in feature is 2 and size of out feature is define by variable hid
        self.hidden1 = nn.Linear(2, hid)
        # define the second hidden layer: size of in feature is hid and size of out feature is hid
        self.hidden2 = nn.Linear(hid, hid)
        # define the third layer: the size of input is hid from layer 2, the size of output is 1
        self.hidden3 = nn.Linear(hid, 1)

    def forward(self, input):
        # assume we are having a linear nn.
        # calculate the linear sum of the weight with the input:
        sum1 = self.hidden1(input)
        # apply the activation function: tanh
        self.hid1 = torch.tanh(sum1)
        # calculate the linear sum of the weight with the first hidden layer output after activation
        sum2 = self.hidden2(self.hid1)
        # apply the activation function: tanh
        self.hid2 = torch.tanh(sum2)
        # compute the sum for the final layer
        out_sum = self.hidden3(self.hid2)
        # apply the activation function: sigmoid
        output = torch.sigmoid(out_sum)
        return output

class Full4Net(torch.nn.Module):
    def __init__(self, hid):
        super(Full4Net, self).__init__()

    def forward(self, input):
        self.hid1 = None
        self.hid2 = None
        self.hid3 = None
        return 0*input[:,0]

class DenseNet(torch.nn.Module):
    def __init__(self, num_hid):
        super(DenseNet, self).__init__()

    def forward(self, input):
        self.hid1 = None
        self.hid2 = None
        return 0*input[:,0]


from random import randint
# n = randint(0, 100)
n = 71
playing = True
count = 0
while playing:
    guess = int(input('Guess my number (0-100)? '))
    if guess > n:
        print('Too big')
    elif guess < n:
        print('Too small')
    else:
        print('bingo')
        break
    count += 1
    if count == 7:
        print('You lose')
        break


"""
Example of the FrequentistSurface plot.

Usage: surf_plot.py FILE
where FILE is a file containing Surface to be plotted. The surface is expected
to be found in the `/surface` directory of the FILE.
"""

import sys
import matplotlib.pyplot as plt

from cafplot import load
from cafplot.plot.surface import (
    plot_surface, plot_surface_best_fit, plot_surface_gauss_contour
)

root_file = load(sys.argv[1])
surface   = root_file.get_fsurface('surface')

f, ax = plt.subplots()

im = plot_surface(ax, surface)

plot_surface_best_fit(ax, surface, color = 'red', marker = '*')
plot_surface_gauss_contour(
    ax, surface, sigma = 1, color = 'red', label = r'1$\sigma$'
)

ax.set_xlabel(r'$\sin^2 \theta_{23}$')
ax.set_ylabel(r'$\Delta m^2_{32}$')

ax.legend()

f.colorbar(im)

plt.show()


A, B = map(int,input().split())
C = int(input())

hour = (B+C)//60 # 몫이므로 (30+20)//60= 0 이렇게 더함
min = (B+C)%60 # 나머지

if (B+C >= 60):
    if (A+hour >= 24): # 24시간 넘어갈 경우 24시간 빼줘서 0부터 시작하게 만들어줌
        A = A-24
    A = A + hour # 뺴준 값에다 다시 hour 더해주기
    print(A, min)

else: # B+C < 60
    if(A >= 24):
        A = A-24
    print(A, B+C)


import numpy as np
import os

from .image_extraction import extract_images_from_pdf
from .images import get_box
from PIL import Image
from flask import current_app

def reference_image(exam_id, page, dpi, widget_area_in=None, padding=0):
    """Returns a reference image for a specified area

    The reference image is a flattened image of the
    problem on the original PDF

    Parameters
    ----------
    exam_id : int
        The id of the exam to use
    page : int
        The page number to get the reference image for
    dpi : int
        The desired DPI of the image
    widget_area_in : numpy array
        The widget coordinates as numpy array
        If None, return the full page
    padding : float
        Extra padding to apply in inches

    Returns
    -------
    image_path : string
        Location of the image.
    """

    app_config = current_app.config
    data_directory = app_config["DATA_DIRECTORY"]
    generated_path = os.path.join(data_directory, f"{exam_id}_data", "blanks", f"{dpi}")

    if not os.path.exists(generated_path):
        _extract_reference_images(dpi, exam_id)

    image_path = os.path.join(generated_path, f"page{page:02d}.jpg")
    if not os.path.exists(image_path):
        _extract_reference_images(dpi, exam_id)

    blank_page = Image.open(image_path)
    blank_img_array = np.array(blank_page)

    if widget_area_in is not None:
        return get_box(blank_img_array, widget_area_in, padding=padding)
    else:
        return blank_img_array

def _extract_reference_images(dpi, exam_id):
    """Extract and save reference images for the specified exam

    Saves the images at:
        {data_directory}/{exam_id}_data/blanks/{dpi}/page{page}.jpg

    Parameters
    ----------
    dpi : int
        The desired DPI for the extracted images
    exam_id : int
        The id of the desired exam
    """
    data_directory = current_app.config["DATA_DIRECTORY"]
    output_directory = os.path.join(data_directory, f"{exam_id}_data")
    pdf_path = os.path.join(output_directory, "exam.pdf")

    pages = extract_images_from_pdf(pdf_path, dpi=dpi)

    for page, (image, _) in enumerate(pages, start=1):
        _save_image(image, page, dpi, output_directory)

def _save_image(image, page, dpi, output_directory):
    """Save an image at an appropriate location.

    Saves the images at:
        {output_directory}/blanks/{dpi}/page{page}.jpg

    Parameters
    ----------
    image : PIL Image
        Image data.
    page : int
        The corresponding page number, starting at 1.
    dpi : int
        The DPI of the image to save.
    output_directory : path
        The output directory of the exam the page is from.

    Returns
    -------
    image_path : string
        Location of the image.
    """

    submission_path = os.path.join(output_directory, "blanks", f"{dpi}")
    os.makedirs(submission_path, exist_ok=True)
    image_path = os.path.join(submission_path, f"page{page-1:02d}.jpg")
    image.save(image_path)
    return image_path


import shutil

import pytest
from repo2rocrate.snakemake import find_workflow, get_lang_version, make_crate

SNAKEMAKE_ID = "https://w3id.org/workflowhub/workflow-ro-crate#snakemake"

def test_find_workflow(tmpdir):
    root = tmpdir / "snakemake-repo"
    workflow_dir = root / "workflow"
    workflow_dir.mkdir(parents=True)
    with pytest.raises(RuntimeError):
        find_workflow(root)
    wf_path = workflow_dir / "Snakefile"
    wf_path.touch()
    assert find_workflow(root) == wf_path
    new_wf_path = root / "Snakefile"
    shutil.move(wf_path, new_wf_path)
    assert find_workflow(root) == new_wf_path

def test_get_lang_version(tmpdir):
    v = "0.1.0"
    wf_path = tmpdir / "Snakefile"
    for arg_part in f'("{v}")', f"( '{v}')":
        with open(wf_path, "wt") as f:
            f.write(f"# comment\nfrom x import y\nmin_version{arg_part}\n")
        assert get_lang_version(wf_path) == v

@pytest.mark.parametrize("defaults", [False, True])
def test_make_crate(data_dir, defaults):
    repo_name = "fair-crcc-send-data"
    root = data_dir / repo_name
    repo_url = f"https://github.com/crs4/{repo_name}"
    kwargs = {"repo_url": repo_url}
    if defaults:
        wf_path = root / "workflow" / "Snakefile"
        wf_name = repo_name
        wf_version = None
        lang_version = "6.5.0"
        license = None
        ci_workflow = "main.yml"
        diagram = "images/rulegraph.svg"
    else:
        wf_path = root / "pyproject.toml"
        wf_name = "spam/bar"
        wf_version = "0.9.0"
        lang_version = "99.9.9"
        license = "GPL-3.0"
        ci_workflow = "release-please.yml"
        diagram = "images/rulegraph.dot"
        kwargs.update(
            workflow=wf_path,
            wf_name=wf_name,
            wf_version=wf_version,
            lang_version=lang_version,
            license=license,
            ci_workflow=ci_workflow,
            diagram=diagram,
        )
    crate = make_crate(root, **kwargs)
    if license:
        assert crate.root_dataset["license"] == license
    # workflow
    workflow = crate.mainEntity
    assert workflow.id == str(wf_path.relative_to(root))
    assert workflow["name"] == crate.root_dataset["name"] == wf_name
    if wf_version:
        assert workflow["version"] == wf_version
    image = crate.get(diagram)
    assert image
    assert set(image.type) == {"File", "ImageObject"}
    assert workflow["image"] is image
    language = workflow["programmingLanguage"]
    assert language.id == SNAKEMAKE_ID
    assert language["version"] == lang_version
    assert workflow["url"] == crate.root_dataset["isBasedOn"] == repo_url
    # workflow testing metadata
    suite = crate.root_dataset["mentions"]
    assert suite
    if isinstance(suite, list):
        assert len(suite) == 1
        suite = suite[0]
    assert suite.type == "TestSuite"
    assert suite["mainEntity"] is workflow
    instance = suite["instance"]
    assert instance
    if isinstance(instance, list):
        assert len(instance) == 1
        instance = instance[0]
    assert instance.type == "TestInstance"
    assert instance["url"] == "https://api.github.com"
    assert instance["resource"] == f"repos/crs4/{repo_name}/actions/workflows/{ci_workflow}"
    # layout
    expected_data_entities = [
        ("LICENSE", "File", ""),
        ("README.md", "File", ""),
        ("config", "Dataset", "Configuration folder"),
        (".tests/integration", "Dataset", "Integration tests for the workflow"),
        ("workflow/rules", "Dataset", "Workflow rule modules"),
        ("workflow/schemas", "Dataset", "Validation files"),
        ("workflow/scripts", "Dataset", "Scripts folder"),
    ]
    for relpath, type_, desc in expected_data_entities:
        entity = crate.get(relpath)
        assert entity, f"{relpath} not listed in crate metadata"
        assert entity.type == type_
        if desc:
            assert entity["description"] == desc


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

import re
import logging as log
from time import sleep
from html import escape
import requests

class FloodException(Exception): pass

def send(config, post):
    # prepare config
    c = {'token': '', 'chat': '', 'maxlength': 1000, 'skip': [], 'censor': []}
    c.update(config)
    if not c['token'] or not c['chat']:
        raise Exception('[Telegram] missing parameter')

    # check key words
    if any((x in post['title']) for x in c['skip']):
        log.info('[Telegram] skip word hit')
        return
    if any((x in post['content']) for x in c['censor']):
        log.info('[Telegram] censor word hit')
        post['content'] = ''

    # fixes email addresses and links
    post['content'] = re.sub(r'([!-~]+\@[!-~]+)', ' \\1 ', post['content'])
    post['content'] = re.sub(r'(https?://[!-~]+)', '\\1 ', post['content'])

    # form message
    html = f'{escape(post["title"])}\n'
    html += f'{post["time"]} #{post["dept"]}\n'
    html += f'校内链接  VPN链接\n\n'
    html += f'{escape(post["content"])}'
    if len(html) > c['maxlength']: html = html[:c['maxlength']] + '...'
    log.debug(f'[Telegram] html: {html}')

    # call HTTP API
    while True:
        try:
            r = requests.post('https://api.telegram.org/bot'+c['token']+'/sendMessage', json={
                'chat_id': c['chat'],
                'text': html,
                'parse_mode': 'HTML',
                'disable_web_page_preview': True
            }, timeout=5)
            log.debug(f'[Telegram] response: {r.text}')
            if not r.json()['ok']:
                if r.json()['error_code'] == 429:
                    raise FloodException()
                else:
                    raise Exception(r.json()['error_code'])
            break
        except FloodException:
            log.warning('[Telegram] hit rate limit!')
            sleep(30)
        except requests.exceptions.RequestException as e:
            log.info('[Telegram] network error')
            log.info(repr(e))
            sleep(5)
        except Exception as e:
            log.error('[Telegram] unknown error')
            log.error(repr(e))
            sleep(60)


from __future__ import annotations

import copy
from dataclasses import dataclass
from enum import Enum
from typing import TYPE_CHECKING, Self

from randovania.bitpacking import bitpacking
from randovania.bitpacking.bitpacking import BitPackDecoder, BitPackEnum, BitPackValue
from randovania.bitpacking.type_enforcement import DataclassPostInitTypeCheck
from randovania.game_description import default_database
from randovania.game_description.db.dock import DockType, DockWeakness
from randovania.games.game import RandovaniaGame
from randovania.lib import enum_lib

if TYPE_CHECKING:
    from collections.abc import Iterator

    from randovania.game_description.db.dock import DockWeaknessDatabase

class DockRandoMode(BitPackEnum, Enum):
    long_name: str
    description: str

    VANILLA = "vanilla"
    DOCKS = "docks"
    WEAKNESSES = "weaknesses"

enum_lib.add_long_name(
    DockRandoMode,
    {
        DockRandoMode.VANILLA: "Vanilla",
        DockRandoMode.DOCKS: "Doors",
        DockRandoMode.WEAKNESSES: "Types",
    },
)

enum_lib.add_per_enum_field(
    DockRandoMode,
    "description",
    {
        DockRandoMode.VANILLA: "Original door locks",
        DockRandoMode.DOCKS: "Randomize the type of each door individually",
        DockRandoMode.WEAKNESSES: "Randomizes all doors by type, turning all of one type into another",
    },
)

@dataclass(frozen=True)
class DockTypeState(BitPackValue, DataclassPostInitTypeCheck):
    game: RandovaniaGame
    dock_type_name: str
    can_change_from: set[DockWeakness]
    can_change_to: set[DockWeakness]

    @staticmethod
    def _get_weakness_database(game: RandovaniaGame) -> DockWeaknessDatabase:
        return default_database.game_description_for(game).dock_weakness_database

    @property
    def weakness_database(self) -> DockWeaknessDatabase:
        return self._get_weakness_database(self.game)

    @property
    def dock_type(self) -> DockType:
        return self.weakness_database.find_type(self.dock_type_name)

    @property
    def can_shuffle(self) -> bool:
        return len(self.can_change_from) > 0

    @property
    def as_json(self) -> dict:
        return {
            "can_change_from": sorted(weakness.name for weakness in self.can_change_from),
            "can_change_to": sorted(weakness.name for weakness in self.can_change_to),
        }

    @classmethod
    def from_json(cls, value: dict, game: RandovaniaGame, dock_type_name: str) -> DockTypeState:
        weakness_database = cls._get_weakness_database(game)
        return cls(
            game=game,
            dock_type_name=dock_type_name,
            can_change_from={
                weakness_database.get_by_weakness(dock_type_name, weakness) for weakness in value["can_change_from"]
            },
            can_change_to={
                weakness_database.get_by_weakness(dock_type_name, weakness) for weakness in value["can_change_to"]
            },
        )

    def bit_pack_encode(self, metadata) -> Iterator[tuple[int, int]]:
        yield from bitpacking.pack_sorted_array_elements(
            sorted(self.can_change_from),
            sorted(self.possible_change_from),
        )
        yield from bitpacking.pack_sorted_array_elements(
            sorted(self.can_change_to),
            sorted(self.possible_change_to),
        )

    @classmethod
    def bit_pack_unpack(cls, decoder: BitPackDecoder, metadata) -> DockTypeState:
        reference: DockTypeState = metadata["reference"]
        ref_change_from = sorted(cls._possible_change_from(reference.game, reference.dock_type_name))
        ref_change_to = sorted(cls._possible_change_to(reference.game, reference.dock_type_name))

        return cls(
            game=reference.game,
            dock_type_name=reference.dock_type_name,
            can_change_from=set(bitpacking.decode_sorted_array_elements(decoder, ref_change_from)),
            can_change_to=set(bitpacking.decode_sorted_array_elements(decoder, ref_change_to)),
        )

    @staticmethod
    def _possible_change_from(game: RandovaniaGame, dock_type_name: str) -> Iterator[DockWeakness]:
        weakness_database = DockTypeState._get_weakness_database(game)
        yield from weakness_database.dock_rando_params[weakness_database.find_type(dock_type_name)].change_from

    @property
    def possible_change_from(self) -> Iterator[DockWeakness]:
        yield from self._possible_change_from(self.game, self.dock_type_name)

    @staticmethod
    def _possible_change_to(game: RandovaniaGame, dock_type_name: str) -> Iterator[DockWeakness]:
        weakness_database = DockTypeState._get_weakness_database(game)
        yield from weakness_database.dock_rando_params[weakness_database.find_type(dock_type_name)].change_to

    @property
    def possible_change_to(self) -> Iterator[DockWeakness]:
        yield from self._possible_change_to(self.game, self.dock_type_name)

@dataclass(frozen=True)
class DockRandoConfiguration(BitPackValue, DataclassPostInitTypeCheck):
    game: RandovaniaGame
    mode: DockRandoMode
    types_state: dict[DockType, DockTypeState]

    @staticmethod
    def _get_weakness_database(game: RandovaniaGame) -> DockWeaknessDatabase:
        return default_database.game_description_for(game).dock_weakness_database

    @property
    def weakness_database(self) -> DockWeaknessDatabase:
        return self._get_weakness_database(self.game)

    @property
    def as_json(self) -> dict:
        return {
            "mode": self.mode.value,
            "types_state": {
                dock_type.short_name: type_state.as_json for dock_type, type_state in self.types_state.items()
            },
        }

    @classmethod
    def from_json(cls, value: dict, game: RandovaniaGame) -> Self:
        weakness_database = cls._get_weakness_database(game)
        return cls(
            game=game,
            mode=DockRandoMode(value["mode"]),
            types_state={
                weakness_database.find_type(dock_type): DockTypeState.from_json(type_state, game, dock_type)
                for dock_type, type_state in value["types_state"].items()
            },
        )

    def bit_pack_encode(self, metadata) -> Iterator[tuple[int, int]]:
        reference: DockRandoConfiguration = metadata["reference"]

        yield from self.mode.bit_pack_encode(None)

        modified_types = sorted(
            dock_type
            for dock_type, type_state in self.types_state.items()
            if type_state != reference.types_state[dock_type]
        )
        yield from bitpacking.pack_sorted_array_elements(modified_types, sorted(self.weakness_database.dock_types))
        for dock_type in modified_types:
            yield from self.types_state[dock_type].bit_pack_encode({"reference": reference.types_state[dock_type]})

    @classmethod
    def bit_pack_unpack(cls, decoder: BitPackDecoder, metadata) -> Self:
        reference: DockRandoConfiguration = metadata["reference"]

        mode = DockRandoMode.bit_pack_unpack(decoder, None)

        modified_types = bitpacking.decode_sorted_array_elements(
            decoder, sorted(reference.weakness_database.dock_types)
        )
        types_state = copy.copy(reference.types_state)
        for dock_type in modified_types:
            types_state[dock_type] = DockTypeState.bit_pack_unpack(
                decoder, {"reference": reference.types_state[dock_type]}
            )

        return cls(
            game=reference.game,
            mode=mode,
            types_state=types_state,
        )

    def is_enabled(self) -> bool:
        return self.mode != DockRandoMode.VANILLA

    def can_shuffle(self, dock_type: DockType) -> bool:
        return dock_type in self.weakness_database.dock_rando_params and self.types_state[dock_type].can_shuffle

    def settings_incompatible_with_multiworld(self) -> list[str]:
        danger = []
        if self.mode == DockRandoMode.DOCKS:
            danger.append(f"{self.mode.long_name}: {self.mode.description}")
        return danger


# p161 미로찾기(그래프탐색)
def solve_maze(g, start, end):
    qu = []
    done = set()

    qu.append(start)
    done.add(start)

    while qu:
        p = qu.pop(0)
        v = p[-1]
        if v == end:
            return p
        for x in g[v]:
            if x not in done:
                qu.append(p + x)
                done.add(x)

    return '?'

maze = {
    'a': ['e'],
    'b': ['c', 'f'],
    'c': ['b', 'd'],
    'd': ['c'],
    'e': ['a', 'i'],
    'f': ['b', 'g', 'j'],
    'g': ['f', 'h'],
    'h': ['g', 'l'],
    'i': ['e', 'm'],
    'j': ['f', 'k', 'n'],
    'k': ['j', 'o'],
    'l': ['h', 'p'],
    'm': ['i', 'n'],
    'n': ['m', 'j'],
    'o': ['k'],
    'p': ['l']
}

print(solve_maze(maze, 'a', 'p'))

# p168 가짜 동전 찾기1
def weigh(a, b, c, d):
    fake = 14
    if a <= fake and fake <= b:
        return -1
    elif c >= fake and fake <= d:
        return 1
    return 0

def find_fakecoin(left, right):
    for i in range(left+1, right+1):
        result = weigh(left, left, i, i)
        if result == -1:
            return left
        elif result == 1:
            return i
    return '?'
n = 100
print(find_fakecoin(0, n-1))

# p178 가짜 동전 찾기2
def weigh(a, b, c, d):
    fake = 25
    if a <= fake and fake <= b:
        return -1
    elif c <= fake and fake <= d:
        return 1
    return 0

def find_fakecoin(left, right):
    if left == right:
        return left

    half = (right - left + 1) // 2
    g1_l = left
    g1_r = left + half - 1
    g2_l = left + half
    g2_r = g2_l + half - 1
    result = weigh(g1_l, g1_r, g2_l, g2_r)

    if result == -1:
        return find_fakecoin(g1_l, g1_r)
    elif result == 1:
        return find_fakecoin(g2_l, g2_r)
    else:
        return right
n = 100
print(find_fakecoin(0, n-1))

# p175 주식 최대수익1
def max_profit(prices):
    n = len(prices)
    max_profit = 0

    for i in range(0, n-1):
        for j in range(i+1, n):
            profit = prices[j] - prices[i]
            if profit > max_profit:
                max_profit = profit
    return max_profit
stock = [10300, 9600, 9800, 8200, 7800, 8300, 9500, 9800, 10200, 9500]
print(max_profit(stock))

# p177 주식 최대수익2
def max_profit(prices):
    n = len(prices)
    min_price = prices[0]
    max_profit = 0

    for i in range(1, n):
        profit = prices[i] - min_price
        if profit > max_profit:
            max_profit = profit
        if prices[i] < min_price:
            min_price = prices[i]
    return max_profit

stock = [10300, 9600, 9800, 8200, 7800, 8300, 9500, 9800, 10200, 9500]
print(max_profit(stock))


from flask import render_template, request, flash, jsonify
from appInitialize import app, db
from model.client import Client
from model.product import Product
from model.order import Order
import json

@app.route('/')
def index ():
    return render_template('layout.html')

#Consultar clientes
@app.route('/read/clients', methods=['GET'])
def readClients ():
    clients = Client.query.filter_by(state = 'activo').all()
    return render_template('read.html', id = False, records = clients, route = 'client')

@app.route('/api/read/clients', methods=['GET'])
def apiReadClients ():
    clients = Client.query.filter_by(state = 'activo').all()
    return jsonify([{'name': client.name, 'document': client.document, 'state': client.state, 'created_at': client.created_at} for client in clients])

#Consultar productos
@app.route('/read/products', methods=['GET'])
def readProducts ():
    products = Product.query.filter(Product.state != 'inactivo').all()
    return render_template('read.html', id = False, records = products, route = 'product')

@app.route('/api/read/products', methods=['GET'])
def apiReadProducts ():
    products = Product.query.filter(Product.state != 'inactivo').all()
    return jsonify([{'name': product.name, 'document': product.price, 'state': product.state, 'created_at': product.created_at} for product in products])

#Consultar ordenes
@app.route('/read/orders', methods=['GET', 'POST'])
def readOrders ():
    if request.method == 'POST':
        id = request.form['id']
        if id == "true":
            clientid = request.form['clientid']
            client = Client.query.filter_by(clientid = clientid, state = 'activo').all()
            if len(client) == 0:
                flash('Cliente no encontrado')
                return render_template('read.html', id = True, route = 'order')
            else:
                orders = Order.query.filter_by(clientid = clientid, state = 'pendiente').join(Client, Order.clientid == Client.clientid and Client.state == 'activo').join(Product, Order.clientid == Product.productid and Product.state != 'inactivo').all()
                return render_template('read.html', id = False, records = orders, route = 'order')
    return render_template('read.html', id = True, route = 'order')

@app.route('/api/read/orders', methods=['POST'])
def apiReadOrders ():
    if request.method == 'POST':
        data = json.loads(request.data)
        client = Client.query.filter_by(clientid = data['clientid'], state = 'activo').all()
        if len(client) == 0:
            return "Registro no encontrado", 402
        orders = Order.query.filter_by(clientid = data['clientid'], state = 'pendiente').join(Client, Order.clientid == Client.clientid and Client.state == 'activo').join(Product, Order.clientid == Product.productid and Product.state != 'inactivo').all()
        return jsonify([{'clientid': order.clientid, 'productid': order.productid, 'quantity': order.quantity, 'total': order.total, 'state': order.state, 'created_at': order.created_at} for order in orders])

#Consultar compras
@app.route('/read/purchases', methods=['GET', 'POST'])
def readPurchases ():
    if request.method == 'POST':
        id = request.form['id']
        if id == "true":
            clientid = request.form['clientid']
            client = Client.query.filter_by(clientid = clientid, state = 'activo').all()
            if len(client) == 0:
                flash('Cliente no encontrado')
                return render_template('read.html', id = True, route = 'purchase')
            else:
                orders = Order.query.filter_by(clientid = clientid, state = 'pagada').join(Client, Order.clientid == Client.clientid and Client.state == 'activo').join(Product, Order.clientid == Product.productid and Product.state != 'inactivo').all()
                return render_template('read.html', id = False, records = orders, route = 'purchase')
    return render_template('read.html', id = True, route = 'purchase')

@app.route('/api/read/purchases', methods=['POST'])
def apiReadPurchases ():
    if request.method == 'POST':
        data = json.loads(request.data)
        client = Client.query.filter_by(clientid = data['clientid'], state = 'activo').all()
        if len(client) == 0:
            return "Registro no encontrado", 402
        orders = Order.query.filter_by(clientid = data['clientid'], state = 'pagada').join(Client, Order.clientid == Client.clientid and Client.state == 'activo').join(Product, Order.clientid == Product.productid and Product.state != 'inactivo').all()
        return jsonify([{'clientid': order.clientid, 'productid': order.productid, 'quantity': order.quantity, 'total': order.total, 'state': order.state, 'created_at': order.created_at} for order in orders])

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


#Seting the Hyper Parameters
param_test1 = {
 'max_depth':[3,5,6,10],
 'min_child_weight':[3,5,10],
 'gamma':[0.0, 0.1, 0.2, 0.3, 0.4],
# 'reg_alpha':[1e-5, 1e-2, 0.1, 1, 10],
 'subsample':[i/100.0 for i in range(75,90,5)],
 'colsample_bytree':[i/100.0 for i in range(75,90,5)]
}

#Creating the classifier
model_xg = XGBClassifier(random_state=2)

grid_search = GridSearchCV(model_xg, param_grid=param_test1, cv=5, scoring='recall')
grid_search.fit(X_train, y_train)

grid_search.best_score_
grid_search.best_params_

y_pred = grid_search.predict(X_test)

# Verificaar os resultados obtidos
print(accuracy_score(y_test,y_pred))
print("\n")
print(confusion_matrix(y_test, y_pred))


import functools
from typing import (
    Any,
    Callable,
    TypeVar,
    cast,
)
import warnings

TFunc = TypeVar("TFunc", bound=Callable[..., Any])

def deprecate_method(func: TFunc, message: str = None) -> TFunc:
    @functools.wraps(func)
    def deprecated_func(*args: Any, **kwargs: Any) -> Any:
        warnings.warn(
            category=DeprecationWarning,
            message=(
                message
                or f"{func.__name__} is deprecated. "
                "A breaking change is expected in a future release."
            ),
            stacklevel=2,
        )
        func(*args, **kwargs)

    return cast(TFunc, deprecated_func)


from bs4 import BeautifulSoup
import requests,re,os
import textract
os.chdir("..")
DATA_DIR = "data/fiscal_pdf"
SAVE_DIR = "data/fiscal_txt"
pre_link="http://www.imf.org"
target_dir = "http://www.imf.org/external/np/g20/"
g8_link = "http://www.g8.utoronto.ca/summit/index.htm"

# Extract all IMF Staff Note from IMF website
html = requests.get(target_dir)
soup = BeautifulSoup(html.content, "lxml")
link_imf = soup.findAll("a",text=re.compile('IMF Staff Note to G-20'))

def extract_pdf(r,link,datdir,savedir):
    name = link.split("/")[-1].split(".")[0][:6]
    name_format = "20"+name[-2:]+name[:2]+name[2:4]
    name_pdf = name_format + ".pdf"
    name_txt = name_format + ".txt"
    save_dir = os.path.join(datdir,name_pdf)
    save_txt = os.path.join(savedir,name_txt)
    with open(save_dir, 'wb') as f:
        f.write(r.content)
    text = textract.process(save_dir)
    with open(save_txt, 'wb') as f:
        f.write(text)

for i in link_imf:
    if "pdf" in i["href"]:
        if "www" in i["href"]:
            r = requests.get(i["href"], stream=True)
            extract_pdf(r,i["href"],DATA_DIR,SAVE_DIR)
        else:
            link_temp=pre_link + i["href"]
            r = requests.get(link_temp,stream=True)
            extract_pdf(r,i["href"],DATA_DIR,SAVE_DIR)
    else:
        if "www" in i["href"]:
            r = requests.get(i["href"], stream=True)
        else:
            link_temp=pre_link + i["href"]
            r = requests.get(link_temp,stream=True)
        temp=BeautifulSoup(r.content, "lxml")
        link_temp=temp.find(text=re.compile("Read the"))
        link_temp=link_temp.parent.a["href"]
        if "external" in link_temp:
            link_temp=pre_link+link_temp
        else:
            link_temp=target_dir+link_temp
        r = requests.get(link_temp,stream=True)
        extract_pdf(r,link_temp,DATA_DIR,SAVE_DIR)