fin=open("C:/Users/Andu/Desktop/aoc/22.txt", "r")
d=[[],[]]
def part1():
    di=0
    for l in fin.read().splitlines():
        if "Player" not in l and l!='':
            d[di].append(int(l))
        elif "Player 2" in l:
            di=1
    while len(d[0])!=0 and len(d[1])!=0:
        if d[0][0]>d[1][0]:
            d[0].append(d[0][0])
            d[0].append(d[1][0])
        else:
            d[1].append(d[1][0])
            d[1].append(d[0][0])
        d[0].pop(0)
        d[1].pop(0)
    if len(d[0])==0:
        di=1
    else:
        di=0
    s=0
    for i in range(1, len(d[di])+1):
        s=s+d[di][-i]*i
    return s

def part2():
    def read():
        di=0
        global d
        for l in fin.read().splitlines():
            if "Player" not in l and l!='':
                d[di].append(int(l))
            elif "Player 2" in l:
                di=1
        return d
    a=read()
    d=a

    def recurs(d1, d2):
        l=[]
        while len(d1)!=0 and len(d2)!=0:
            a=d1[0]
            b=d2[0]
            if (d1, d2) in l:
                return 1, d1
            l.append((d1,d2))
            d1.pop(0)
            d2.pop(0)
            if a<=len(d1) and b<=len(d2):
                if 1==recurs(d1[:a],d2[:b])[0]:
                    d1.append(a)
                    d1.append(b)
                else:
                    d2.append(b)
                    d2.append(a)
            else:
                if a>b:
                    d1.append(a)
                    d1.append(b)
                else:
                    d2.append(b)
                    d2.append(a)
        if len(d1)==0:
            return 2, d2
        else:
            return 1, d1
    s=0
    a=recurs(d[0],d[1])[1]
    for i in range(1, len(a)+1):
        s=s+a[-i]*i
    return s
print(part2())
fin.close()


import os
from aws_cdk import core, aws_dynamodb as dynamodb, aws_iam as iam
from cdk_chalice import Chalice

class WsCpmGuildathonStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        self.connections_table = dynamodb.Table(self, f"WSPlaygroundConnections",
                                             partition_key=dynamodb.Attribute(
                                                 name="connection_id",
                                                 type=dynamodb.AttributeType.STRING),
                                                 billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
                                                 removal_policy=core.RemovalPolicy.DESTROY)

        self.records_table = dynamodb.Table(self, f"WSPlaygroundRecords",
                                             partition_key=dynamodb.Attribute(
                                             name="id",
                                             type=dynamodb.AttributeType.STRING),
                                             billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
                                             removal_policy=core.RemovalPolicy.DESTROY)

        core.CfnOutput(self, id="ConnectionsTableName", value=self.connections_table.table_name)
        core.CfnOutput(self, id="RecordsTableName", value=self.records_table.table_name)

        self.service_role = self._create_service_role()

        chalice_dir = os.path.join(os.path.dirname(__file__), os.pardir, "ws")
        chalice_config = self._create_chalice_stage_config()

        self.chalice = Chalice(self, id, source_dir=chalice_dir, stage_config=chalice_config)

    def _create_chalice_stage_config(self):
        chalice_stage_config = {
            'api_gateway_stage': 'v1',
            'lambda_functions': {
                'api_handler': {
                    'manage_iam_role': False,
                    'iam_role_arn': self.service_role.role_arn,
                    'environment_variables': {
                        'RECORDS_TABLE_NAME': self.records_table.table_name,
                        'CONNECTIONS_TABLE_NAME': self.connections_table.table_name,
                    },
                    'lambda_memory_size': 128,
                    'lambda_timeout': 10
                }
            }
        }
        return chalice_stage_config

    def _create_service_role(self):
       role = iam.Role(self, "WSServiceRole",
                       assumed_by=iam.ServicePrincipal("lambda.amazonaws.com"), inline_policies={
                "AccountsServicePolicy": iam.PolicyDocument(
                    statements=[
                        iam.PolicyStatement(
                            actions=[
                                "logs:CreateLogGroup",
                                "logs:CreateLogStream",
                                "logs:PutLogEvents",
                                "logs:DescribeLogGroups",
                            ],
                            resources=["arn:aws:logs:*:*:*"],
                            effect=iam.Effect.ALLOW),
                        iam.PolicyStatement(
                            actions=[
                                "ssm:Describe*",
                                "ssm:Get*",
                                "ssm:List*"
                            ],
                            resources=["arn:aws:ssm:*"],
                            effect=iam.Effect.ALLOW)
                    ])
            })
       return role


import torch
import torch.nn as nn
import torch.nn.functional as F

from speakerlab.models.campplus.layers import DenseLayer

class CosineClassifier(nn.Module):
    def __init__(
        self,
        input_dim,
        num_blocks=0,
        inter_dim=512,
        out_neurons=1000,
    ):

        super().__init__()
        self.blocks = nn.ModuleList()

        for index in range(num_blocks):
            self.blocks.append(
                DenseLayer(input_dim, inter_dim, config_str='batchnorm')
            )
            input_dim = inter_dim

        self.weight = nn.Parameter(
            torch.FloatTensor(out_neurons, input_dim)
        )
        nn.init.xavier_uniform_(self.weight)

    def forward(self, x):
        # x: [B, dim]
        for layer in self.blocks:
            x = layer(x)

        # normalized
        x = F.linear(F.normalize(x), F.normalize(self.weight))
        return x

class LinearClassifier(nn.Module):
    def __init__(
        self,
        input_dim,
        num_blocks=0,
        inter_dim=512,
        out_neurons=1000,
    ):

        super().__init__()
        self.blocks = nn.ModuleList()

        self.nonlinear = nn.ReLU(inplace=True)
        for index in range(num_blocks):
            self.blocks.append(
                DenseLayer(input_dim, inter_dim, bias=True)
            )
            input_dim = inter_dim

        self.linear = nn.Linear(input_dim, out_neurons, bias=True)

    def forward(self, x):
        # x: [B, dim]
        x = self.nonlinear(x)
        for layer in self.blocks:
            x = layer(x)
        x = self.linear(x)
        return x


import turtle
from turtle import *

def tree(branchLen,leonardo):
    if branchLen > 5:
        leonardo.forward(branchLen)
        leonardo.width(leonardo.width()-1)
        leonardo.right(20)
        tree(branchLen-15,leonardo)
        leonardo.left(40)
        tree(branchLen-15,leonardo)
        leonardo.right(20)
        leonardo.backward(branchLen)
        leonardo.width(leonardo.width()+1)

def main():
    leonardo = turtle.Turtle()
    myWin = turtle.Screen()
    leonardo.width(7)
    leonardo.left(90)
    leonardo.up()
    leonardo.backward(100)
    leonardo.down()
    leonardo.color("green")
    tree(75,leonardo)
    turtle.clearscreen()
    level = 3
    size = 200
    penup()
    goto(-size / 2.0, size / 2.0)
    pendown()
    # For positioning turtle
    hilbert(level, 90, size/(2**level-1))
    done()
    myWin.exitonclick()

def hilbert(level, angle, step):

    # Input Parameters are numeric
    # Return Value: None
    if level == 0:
        return

    right(angle)
    hilbert(level-1, -angle, step)

    forward(step)
    left(angle)
    hilbert(level-1, angle, step)

    forward(step)
    hilbert(level-1, angle, step)

    left(angle)
    forward(step)
    hilbert(level-1, -angle, step)
    right(angle)

main()


import yaml
import logging
import logging.config
from pathlib import Path

from .saving import log_path

LOG_LEVEL = logging.INFO

def setup_logging(run_config, log_config="logging.yml") -> None:
    """
    Setup ``logging.config``

    Parameters
    ----------
    run_config : str
        Path to configuration file for run

    log_config : str
        Path to configuration file for logging
    """
    log_config = Path(log_config)

    if not log_config.exists():
        log_folder = log_path(run_config)
        log_file_debug = log_folder / "debug.log"
        log_file_info = log_folder / "info.log"
        log_file_warning = log_folder / "warning.log"
        log_file_error = log_folder / "error.log"
        log_file_critical = log_folder / "critical.log"

        # Create separate log handlers for each log file
        handler_debug = logging.FileHandler(filename=str(log_file_debug))
        handler_info = logging.FileHandler(filename=str(log_file_info))
        handler_warning = logging.FileHandler(filename=str(log_file_warning))
        handler_error = logging.FileHandler(filename=str(log_file_error))
        handler_critical = logging.FileHandler(filename=str(log_file_critical))

        # Set log levels for each handler
        handler_debug.setLevel(logging.DEBUG)
        handler_info.setLevel(logging.INFO)
        handler_warning.setLevel(logging.WARNING)
        handler_error.setLevel(logging.ERROR)
        handler_critical.setLevel(logging.CRITICAL)

        # Create formatters (if needed)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        handler_debug.setFormatter(formatter)
        handler_info.setFormatter(formatter)
        handler_warning.setFormatter(formatter)
        handler_error.setFormatter(formatter)
        handler_critical.setFormatter(formatter)

        # Get the root logger
        logger = logging.getLogger()

        # Add the handlers to the root logger
        logger.addHandler(handler_debug)
        logger.addHandler(handler_info)
        logger.addHandler(handler_warning)
        logger.addHandler(handler_error)
        logger.addHandler(handler_critical)

        logger.setLevel(LOG_LEVEL)

        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.DEBUG)  # Set the level for console output
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)

        # Log a warning message to the console
        logger.warning(f'"{log_config}" not found. Using basicConfig with custom log files.')
        return

    with open(log_config, "rt") as f:
        config = yaml.safe_load(f.read())

    # modify logging paths based on run config
    run_path = log_path(run_config)
    for _, handler in config["handlers"].items():
        if "filename" in handler:
            handler["filename"] = str(run_path / handler["filename"])

    logging.config.dictConfig(config)

def setup_logger(name):
    log = logging.getLogger(f'funmap.{name}')
    log.setLevel(LOG_LEVEL)
    return log


import pandas as pd
import re,dateparser,time,sqlite3,os
import numpy as np
from datetime import datetime
from consolidate_data import consolidate_data
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def main():

    #Delete the old sheet
    if 'Results  FIFA.xlsx' in os.listdir():
        os.remove('Results  FIFA.xlsx')

    #Download the new sheet
    browser = openBrowser(headless=False)
    browser.get('https://docs.google.com/spreadsheets/d/1DzPBoZzRx1JraO48IaiRsTCML75XXLFMj0ZItfaI8-A/edit#gid=1509390892')
    browser.find_element_by_id('docs-file-menu').click()
    time.sleep(2)
    [x for x in browser.find_elements_by_tag_name('span') if '다운로드' in x.text][0].click()
    time.sleep(2)
    [x for x in browser.find_elements_by_tag_name('span') if 'xlsx' in x.text][0].click()

    #Wait until sheet downloaded
    while not 'Results  FIFA.xlsx' in os.listdir():
        time.sleep(5)
    browser.close()

    Excel = pd.ExcelFile(r'Results  FIFA.xlsx')

    master = pd.DataFrame()

    for sheet_num in range(len(Excel.sheet_names)):
        df = pd.read_excel(Excel,sheet_num,header=None)
        fixtures_date = Excel.sheet_names[sheet_num]

        for i in df.index.values:

            row = df.loc[i]

            #Set the current competition if necessary
            try:
                compheader = re.findall('[0-9]+:[0-9]+ - [0-9]+:[0-9]+',row[1])
                if compheader:
                    compheader = compheader[0]
                    comp = row[1].replace(compheader,'').strip()
                    fixtures_start = re.findall('[0-9]+:[0-9]+',row[1])[0]
                    fixtures_start = fixtures_date + ' ' + fixtures_start
                    timestamp = time.mktime(datetime.timetuple(datetime.strptime(fixtures_start,'%Y.%m.%d %H:%M')))
                    timestamp = np.int64(timestamp)

                    gamescounted = 0
            except:
                continue

            #if type(row[4]) == float:
                #if np.isnan(row[4]): continue

            try:
                if 'channel' in row[4]:

                    hometeam = re.findall('\(.*\)',row[1])[0].strip('()').replace('С','C')
                    awayteam = re.findall('\(.*\)',row[3])[0].strip('()').replace('С','C')

                    try:
                        #Discard any 1st half data in case it accidentally gets parsed
                        score = row[2].split('(')[0]
                        hscore,ascore = re.findall('[0-9]+',score)[:2]
                    except:
                        hscore = ascore = np.nan

                    #a bit of a hacky solution to try and get more accurate game times
                    gamescounted += 1
                    if gamescounted %2 == 0:
                        timestamp += 60*15

                    gameID = str(timestamp)+hometeam+awayteam

                    gamedic= {
                    'DATE':[datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M')],
                    'TIMESTAMP':[timestamp],
                    'COMPETITION':[comp],
                    'HOME':[hometeam],
                    'AWAY':[awayteam],
                    'VENUE':[np.nan],
                    'HOME SCORE':[hscore],
                    'AWAY SCORE':[ascore],
                    'TOTAL':[hscore+ascore],
                    'GAME ID':[gameID],
                    'STAGE':['Group Stage']
                               }

                    #This turns the new game data into a pandas dataframe
                    new_game = pd.DataFrame(gamedic)
                    #This adds the new dataframe to the complete list of games
                    master = pd.concat([master,new_game],ignore_index=True,sort=False)
            except:
                continue

    master.drop_duplicates(subset='GAME ID',inplace=True,keep='last')

    master = consolidate_data(master)

    master.to_pickle('master.pkl')
    conn = connect_to_database('master.db')
    master.to_sql('MATCHES',conn,index=False)
    conn.commit()
    conn.close()

    #Group by competitions for saving separately
    for comp in master.groupby('COMPETITION'):
        d = pd.DataFrame(comp[1])
        d.to_pickle(comp[0])
        conn = connect_to_database(comp[0])
        d.to_sql('MATCHES',conn,index=False)
        conn.commit()
        conn.close()

def connect_to_database(path):
    try:
        open(path,'w').close()
    except:
        pass

    conn = sqlite3.connect(path)

    return conn

def openBrowser(headless=True):
    prefs = {"download.default_directory" : r"C:\Users\GerardArmstrong\Documents\GitHub\efootballresults\Cyberleagues"}
    chrome_options = Options()
    chrome_options.add_experimental_option("prefs",prefs)
    if headless == True:
        chrome_options.add_argument("--headless")
        chrome_options.add_argument("--window-size=1920x1080")
        print('Browser opening in headless mode')

    #Starts a new instance of Chrome using Selenium webdriver
    if not 'browser' in locals():
        browser = webdriver.Chrome(chrome_options=chrome_options,executable_path='C:\\Users\\GerardArmstrong\\Documents\\Python Scripts\\Compiler\\chromedriver.exe')

    return browser

if __name__ == '__main__':
    main()


# 특정색 추출 (BGR 정보에서 추출)
import numpy as np
import cv2
def tracking():
    cap = cv2.VideoCapture(0)
    while True:
        ret, frame = cap.read()
        blue_result, green_result, red_result = cv2.split(frame)
        zeros = np.zeros((frame.shape[0], frame.shape[1]), dtype='uint8')
        blue_result = cv2.merge([blue_result, zeros, zeros])
        green_result = cv2.merge([zeros, green_result, zeros])
        red_result = cv2.merge([zeros, zeros, red_result])
        cv2.imshow("original", frame)
        cv2.imshow("blue", blue_result)
        cv2.imshow("red", red_result)
        cv2.imshow("green", green_result)
        key = cv2.waitKey(1) & 0xFF
        if key == 27:
            break
    cv2. destroyAllWindows()
tracking()


#!/usr/bin/python3
"""
位置参数:
在参数名之前使用一个星号，就是让函数接受任意多的位置参数
python把参数收集到一个元组中，作为变量args。
显式声明的参数之外如果没有位置参数，这个参数就作为一个空元组
"""
def multiply(*args):
    total = 1;
    for arg in args:
        total *= arg
    return total
print("2 * 3 * 4 * 5 * 6 = ", multiply(2, 3, 4, 5, 6))
"""
关键字参数:
python在参数名之前使用两个星号来支持任意多的关键字参数
kwargs是一个正常的python字典类型，包含参数名和值。
如果没有更多的关键字参数，kwargs就是一个空字典
"""
def accept(**kwargs):
    for keyword, value in kwargs.items():
        print("%s => %r" % (keyword, value))
accept(foo = 'bar', spam = 'eggs')
"""
混合参数类型
任意的位置参数和关键字参数可以和其他标准的参数声明一起使用。
混合使用时要加些小心，因为python中他们的次序是重要的。
参数归为4类，不是所有的类别都需要。他们必须按下面的次序定义。不用的可以跳过
1. 必须的参数
2. 可选参数
3. 过量的位置参数
4. 过量的关键字参数
def complex_function(a, b = None, *c, **d)
这个次序是必须的，因为*args和**kwargs只接受那些没有放进来的其他任何参数。
没有这个次序，当你调用一个带有位置参数的函数，python不知道哪个值是已声明参数想要的，
也不知道哪个被作为过量参数对待。
也要注意的是，当函数能接受许多必须的参数和可选的参数，那它只要定义一个过量的参数类型即可。
"""
def add(a, b, c):
    return a + b + c
print("add(1, 2, 3) = ", add(1, 2, 3))
print("add(a = 4, b = 5, c = 6) = ", add(a = 4, b = 5, c = 6))
args = (2, 3)
print("add(1, *args) = ", add(1, *args))
kwargs = {'b' : 8, 'c' : 9}
print("add(a = 7, **kwargs) = ", add(a = 7, **kwargs))

"""
默认参数很有用，但使用不当，也会掉坑里，默认参数有个最大的坑，演示如下:
先定义一个函数，传入一个list, 添加一个END再返回
"""
def add_end(L=[]):
    L.append('END')
    return L
#当你正常调用时，结果似乎不错:
print(add_end([1, 2, 3]))
print(add_end(['x', 'y', 'z']))
#当你使用默认参数调用时，一开始结果也是对的:
print(add_end())
#但是，再次调用add_end()时，结果就不对了
print(add_end())
print(add_end())
#很多初学者很疑惑，默认参数是[]，但是函数似乎每次都'记住了'了上次添加了'END'后的list
#原因解释如下: python函数在定义的时候，默认参数L的值就被计算出来了，[]，因为默认参数L也是一个变量，它指向对象[]，每次调用该函数，如果改变了L的内容，则下次调用时，默认参数的内容就变了，不再是函数定义的[]了
#定义默认参数要牢记一点: 默认参数必须指向不变对象
#要修改上面的例子，我们可以用None这个不变对象来实现:
def add_end_1(L1=None):
    if L1 is None:
        L1 = []
    L1.append('END')
    return L1
print(add_end_1())
print(add_end_1())
#为什么要设计str、None这样的不变对象呢？因为不变对象一旦创建，对象内部的数据就不能修改，这样就减少了由于修改数据导致的错误。此外，由于对象不变，多任务环境下同时读取对象不需要加锁，同时读一点问题都没有。我们在编写程序时，如果可以设计一个不变对象，那就尽量设计成不变对象。
def cacl(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
print(cacl(1, 2))
print(cacl(1, 3, 5, 7, 9))
#python允许你在list或tuple前面加一个*号，把list或tuple的元素变成可变参数传进去
print(cacl(*range(10)))

#关键字参数
#可变参数允许你传入0个或任意个参数，这些可变参数在函数调用时自动组装为一个tuple。而关键字参数允许你传入0个或任意个含参数名的参数，这些关键字参数在函数内部自动组装成一个dict
def person(name, age, **kw):
    print('name: ', name, 'age: ', age, 'other: ', kw)
person('Michael', 30)
person('Bob', 35, city='Beijing')
person('Adam', 45, gender='M', job='Engineer')
#关键字参数有什么用呢？它可以扩展函数的功能。比如，在person函数里，我们保证能接收到name和age这两个参数，但是， 如果调用者愿意提供更多的参数，我们也能收到，试想你正在做一个用户注册的功能，除了用户名和年龄是必填项外，其他都是可选项，利用关键字参数来定义这个函数就能满足注册的需求。
#**extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw函数，kw将获得一个dict，注意kw获得的dict是extra的一份拷贝，对kw的改动不会影响到函数外的extra
extra = {'city':'Beijing', 'job':'Enjineer'}
person('Jack', 24, **extra)
#如果要限制关键字参数的名字，就可以用命名关键字参数。例如，只接收city和job作为关键字参数。
def person1(name, age, *, city, job):
    print(name, age, city, job)
#和关键字参数**kw不同，命名关键字参数需要一个特殊分隔符*， *后面的参数被视为命名关键字参数。
person1('Jack', 24, city='Beijing', job='Engineer')
#如果函数定义中已经有了一个可变参数，后面跟着的命名关键字参数就不再需要一个特殊分隔符*了
def person2(name, age, *arg, city, job):
    print(name, age, *arg, city, job)
person2('Jack', 24, [1, 2], city='Beijing', job='Engineer')

#命名关键字参数可以有缺省值，从而简化调用
def person3(name, age, *arg, city='Beijing', job):
    print(name, age, *arg, city, job)
#由于命名关键字参数city具有默认值，调用时，可不传入city参数
person3('Jack', 24, [1, 2], job='Engineer')

"""
参数组合
在python中定义函数，可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数。这5种参数都可以组合使用。
但是请注意，参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数
"""
def f1(a, b, c=0, *args, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
f1(1, 2)
f1(1, 2, c=3)
f1(1, 2, 3, 'a', 'b')
f1(1, 2, 3, 'a', 'b', x=99)
f2(1, 2, d=99, ext=None)
#最神奇的是通过一个tuple和dict，你也可以调用上述函数：
args = (1, 2, 3, 4)
kw = {'d': 99, 'x': '#'}
f1(*args, **kw)
args = (1, 2, 3)
kw = {'d': 88, 'x': '#'}
f2(*args, **kw)


#!/usr/bin/python
# coding=utf-8
import datetime
import re
from collections import OrderedDict
import sys
import xlsxwriter
import os

dic_cpu_temp = OrderedDict ()
dic_cpu_temp_total = OrderedDict ()
dic_power_cap = OrderedDict ()
dic_power_current = OrderedDict ()
dic_sprdbat_temp_monitor = OrderedDict ()
dic_cpu_cluster = OrderedDict ()
dic_cpu_freq_total = OrderedDict ()
dic_backlight_level = OrderedDict ()
dic_board_temp_level = OrderedDict ()

cpu_temp = 'cpu\d* temp:\d*' ;  # for cpux temp
dic_power_cap["power_cap"] = []
dic_power_current["power_current"] = []
dic_sprdbat_temp_monitor["chg_cur"] = []
dic_backlight_level["backlight_level"] = []
dic_board_temp_level["board_temp"] = []

DEBUG = 1

class debug_leakage:
	def __init__(self,obj):
		self.obj = obj
		if(DEBUG == 1):
			if(type(self.obj) is list):
				for x in self.obj:
					print(x)

			if(type(self.obj) is OrderedDict):
				for x in  self.obj:
					print(x)
					print(self.obj[x])

class deal_data_to_chart(object):
	def __init__(self,result_book):
		self.result_book = result_book

	def cpu_filter(self,dic_cpu,dic_cpu_total,parttern):
		for key in dic_cpu_total:
			cpu_n = ''.join ( re.findall ( "cpu\d*", dic_cpu_total[key] ) )
			if (cpu_n in dic_cpu.keys ()):
				cpu_value = ''.join ( re.findall ( parttern+"\d*", dic_cpu_total[key] ) ).replace ( parttern, "" )
				target_key = ''.join ( re.findall ( "\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{3}", key ) )
				dic_cpu[cpu_n].append ( {target_key: cpu_value} )

	def make_chart(self,dic_data,dic_chart):
		sheet1 = self.result_book.add_worksheet ( dic_chart["sheet_name"])
		list_colum_line = [chr ( i ).upper () + '2' for i in range ( 97, 123 )]
		list_colum_color = ['red', 'yellow', 'green', 'blue', 'black']
		i = 0
		x_scale = 1
		chart_col = self.result_book.add_chart ({'type':'line', 'substyle':'stacked'})
		for x in dic_data:
			list_colums_key = []
			list_colums_value = []
			if((len (dic_data[x])+1)//14!=0):
				x_scale =(len (dic_data[x])+1)//14
				if(x_scale >3):
					x_scale = 3
			print ( len (dic_data[x]) )
			print(x_scale)
			for y in dic_data[x]:
				list_colums_key.append ( ''.join ( list ( y.keys () ) ) )
				list_colums_value.append ( float ( ''.join ( list ( y.values () ) ) ) )
			sheet1.write ( list_colum_line[i * 2].replace ( "2", "1" ), x )
			sheet1.write_column ( list_colum_line[i * 2], list_colums_key )
			sheet1.write_column ( list_colum_line[i * 2 + 1], list_colums_value )
			index_culom_categories = list_colum_line[i * 2].replace ( '2', '' )
			sheet1.set_column ( index_culom_categories + ':' + index_culom_categories, 20 ) # set culom width
			index_culom_values = list_colum_line[i * 2 + 1].replace ( '2', '' )
			chart_col.add_series ( {
				'name': '='+dic_chart["sheet_name"]+'!$' + index_culom_categories + '$1',
				'categories': '='+dic_chart["sheet_name"]+'!$' + index_culom_categories + '$2:$' + index_culom_categories + "$" + str (
					len ( list_colums_key ) + 1 ),
				'values': '='+dic_chart["sheet_name"]+'!$' + index_culom_values + '$2:$' + index_culom_values + "$" + str (
					len ( list_colums_value ) + 1 ),
				'line': {'color': list_colum_color[i]},
			} )
			i = i + 1
		chart_col.set_title ( {'name': dic_chart["title"]} )
		chart_col.set_x_axis ( {'name':dic_chart["x_axis"]} )
		chart_col.set_y_axis ( {'name': dic_chart["y_axis"]} )
		#chart_col.set_style ( 1 )
		sheet1.insert_chart ( list_colum_line[(i) * 2 + 1], chart_col,{'x_offset':0, 'y_offset': 0,'x_scale': x_scale, 'y_scale': 1})

class read_log():

	def read_kernel_log(self,filepath):
		with open ( filepath, "rt", encoding="UTF-8", errors='ignore' ) as kernel_file:
			while True:
				content = kernel_file.readline () ;
				if not content:
					break ;

				# for power last
				if (content.find ( "sprdbat: vbat:" ) != -1):
					if (content.find ( "cap:" ) != -1):
						power_cap_value = ''.join ( re.findall ( "cap:\d*", content ) ).replace ( "cap:", "" )
						power_cap_key = ''.join ( re.findall ( "\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d*", content ) )
						dic_power_cap["power_cap"].append ( {power_cap_key: power_cap_value} )
					if (content.find ( "current:" ) != -1):
						power_current_value = ''.join ( re.findall ( "current:-?\d*", content ) ).replace ( "current:",
																											"" )
						power_current_key = ''.join ( re.findall ( "\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d*", content ) )
						dic_power_current["power_current"].append ( {power_current_key: power_current_value} )
					continue

				# for list_sprdbat_temp_monitor
				if (content.find ( "sprdbat_temp_monitor" ) != -1 and content.find ( "chg_cur=" ) != -1):
					chag_cur_value = ''.join ( re.findall ( "chg_cur=\d*", content ) ).replace ( "chg_cur=", "" )
					chag_cur_key = ''.join ( re.findall ( "\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d*", content ) )
					dic_sprdbat_temp_monitor["chg_cur"].append ( {chag_cur_key: chag_cur_value} )
					continue

				# for cpu temp
				if (re.findall ( cpu_temp, content )):
					cpu_temp_value = ''.join ( re.findall ( "cpu\d* temp:\d*", content ) )
					dic_cpu_temp_total[content] = cpu_temp_value
					cpu_temp_x = ''.join ( re.findall ( 'cpu\d*', ''.join ( re.findall ( cpu_temp, content ) ) ) )
					dic_cpu_temp[cpu_temp_x] = []

					# for cpu freq
					if (content.find ( "online" ) != -1 and content.find ( "target_freq" ) != -1):
						cpu_freq_value = ''.join ( re.findall ( "cpu\d* temp:\d* target_freq:\d*", content ) )
						dic_cpu_freq_total[content] = cpu_freq_value
						cpu_freq_x = ''.join ( re.findall ( 'cpu\d*', cpu_freq_value ) )
						dic_cpu_cluster[cpu_freq_x] = []
					continue

				# for backlight
				if (content.find ( "set max_brightness to" ) != -1 and content.find ( "backlight:" ) != -1):
					backlight_level_value = ''.join ( re.findall ( "set max_brightness to \d*", content ) ).replace (
						"set max_brightness to", "" )
					backlight_level_key = ''.join ( re.findall ( "\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d*", content ) )
					dic_backlight_level["backlight_level"].append ( {backlight_level_key: backlight_level_value} )
					continue
		kernel_file.close ()

	def read_main_log(self,main_log_path):
		with open ( main_log_path, "r", encoding="UTF-8", errors='ignore' ) as main_file:
			while True:
				content = main_file.readline ()
				if not content:
					break
				if (re.findall ( "ThermalCvtGovernor: board \w* average temp", content ) or \
					content.find("ThermalCvtGovernor: board-thmzone average temp") != -1):
					if(re.findall ( "\d{3}-\d{2} \d{2}:\d{2}:\d{2}.\d*", content )):
						board_temp_key = ''.join ( re.findall ( "\d{3}-\d{2} \d{2}:\d{2}:\d{2}.\d*", content))
					elif(re.findall ( "\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d*", content )):
						board_temp_key = ''.join ( re.findall ( "\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d*", content ) )
					board_temp_value = ''.join ( re.findall ( "average temp: \d*", content ) ).replace (
						"average temp: ", "" )
					dic_board_temp_level["board_temp"].append ( {board_temp_key: board_temp_value} )
		main_file.close ()

class deal_result():
	def __init__(self, result_path):
		self.result_path = result_path
	def write_chart(self):
		result_book = xlsxwriter.Workbook ( result_path )
		deal_data_to_chart_obj = deal_data_to_chart ( result_book )

		dic_power_cap_chart = {"sheet_name": "power_cap", "title": "Power Cap change curve", "x_axis": "Time",
							   "y_axis": "Power"}
		dic_power_current_chart = {"sheet_name": "power_current", "title": "Power Current change curve",
								   "x_axis": "Time", "y_axis": "Power"}
		dic_chg_curr_chart = {"sheet_name": "chg_cur", "title": "Charge Current change curve", "x_axis": "Time",
							  "y_axis": "Power"}
		dic_backlight_level_chart = {"sheet_name": "backlight_level", "title": "Backlight level change curve",
									 "x_axis": "Time", "y_axis": "level"}
		dic_cpu_freq_chart = {"sheet_name": "cpu_freq", "title": "CPU freq change curve", "x_axis": "Time",
							  "y_axis": "KHZ"}
		deal_data_to_chart_obj.cpu_filter ( dic_cpu_cluster, dic_cpu_freq_total, "target_freq:" )
		dic_cpu_temp_chart = {"sheet_name": "cpu_temp", "title": "CPU temp change curve", "x_axis": "Time",
							  "y_axis": "Temp"}
		deal_data_to_chart_obj.cpu_filter ( dic_cpu_temp, dic_cpu_temp_total, "temp:" )
		dic_board_temp_chart = {"sheet_name": "board_temp", "title": "Board temp change curve", "x_axis": "Time",
								"y_axis": "Temp"}

		list_chart = [dic_power_cap_chart, dic_power_current_chart, dic_chg_curr_chart, dic_backlight_level_chart,
					  dic_cpu_freq_chart, dic_cpu_temp_chart, dic_board_temp_chart]
		list_data = [dic_power_cap, dic_power_current, dic_sprdbat_temp_monitor, dic_backlight_level, dic_cpu_cluster,
					 dic_cpu_temp, dic_board_temp_level]
		for dic_chart, dic_data in zip ( list_chart, list_data ):
			deal_data_to_chart_obj.make_chart ( dic_data, dic_chart )

		result_book.close ()

if __name__ == '__main__':
	try:
		kernel_log_path = sys.argv[1]
	except Exception:
		print("please input coorect kernel log path")
		exit()
	try:
		main_log_path = sys.argv[2]
	except Exception:
		print("please input coorect main log path")
		exit()

	file_dir = os.getcwd()
	result_path = file_dir+"\\result.xlsx"

	read_log_obj = read_log()
	read_log_obj.read_kernel_log(kernel_log_path)
	read_log_obj.read_main_log(main_log_path)

	deal_result(result_path).write_chart()


from datetime import date
import toga
import toga.style.pack
from toga.style.pack import Pack
from .record import Record
from requests import Session
from pathlib import Path
from .login_win import LoginWindow, try_login
from mycqu.mycqu import access_mycqu
from mycqu.exam import Exam
import sys

session: Session
app: toga.App
cache_path: Path
data_path: Path
record: Record

# Rely on `sys.getandroidapilevel`, which only exists on Android; see
# https://github.com/beeware/Python-Android-support/issues/8
if hasattr(sys, 'getandroidapilevel'):
    current_platform = 'android'
else:
    current_platform = sys.platform

class MainApp(toga.App):
    week = ['一', '二', '三', '四', '五', '六', '日']

    def set_exam_list(self, _=None):
        print(f"set_exam_list of {record.user_info.code}")
        exams = Exam.fetch(record.user_info.code)
        # access_mycqu(session)
        self.exam_list.data.clear()
        today = date.today()
        for exam in exams:
            if exam.date < today:
                continue
            self.exam_list.data.append(
                icon=toga.Icon("resources/cqutimetable.png"),
                title=f"{exam.course.name} 考试 位于 {exam.room} 座号{exam.seat_num}",
                subtitle=f'{exam.date.strftime("%Y-%m-%d")} 第 {exam.week} 周周{self.week[exam.weekday]} '
                f'{exam.start_time.strftime("%H:%M")} ~ {exam.end_time.strftime("%H:%M")}'
            )

    def refresh_after_login(self):
        self.main_window.title = f"考表 - {record.user_info.name} {record.user_info.code}"
        self.set_exam_list()

    def login_callback(self, success):
        if success:
            self.refresh_after_login()

    def login_window(self):
        login = LoginWindow(self.main_window, self.login_callback)
        self.windows.add(login)
        login.show()

    def startup(self):
        global app, cache_path, data_path, record, session
        app = self

        cache_path = self.paths.cache
        data_path = self.paths.data
        record = Record.read()
        session = record.session

        main_window = toga.MainWindow(title="考表")
        self.commands.add(toga.Command(lambda _: self.login_window(), "登录"))
        if current_platform == "android":
            from .android import cal
            self.commands.add(toga.Command(cal.cal_command, "日历"))

        self.exam_list = toga.DetailedList(
            on_refresh=self.set_exam_list, style=Pack(flex=1))

        exam_list_box = toga.Box(style=Pack(
            flex=1, direction="column", padding=10))
        exam_list_box.add(self.exam_list)

        main_window.content = exam_list_box
        self.main_window = main_window
        self.main_window.show()

        if record.username and record.password:
            try_login(main_window, record.username,
                      record.password, self.login_fallback)
        else:
            self.login_window()

    def login_fallback(self, status: bool):
        if status:
            self.refresh_after_login()
        else:
            self.main_window.info_dialog("登录失败", "请重新登录")
            self.login_window()

def main():
    return MainApp()


"""Test swig-style wrapped pointers

Created on Oct 2, 2014 by David Gobbi
"""

import sys
from vtkmodules.vtkCommonCore import (
    vtkInformation,
    vtkIntArray,
    vtkObject,
)
from vtkmodules.test import Testing

class TestSwigPointer(Testing.vtkTest):
    def testVoidPointer(self):
        a = vtkIntArray()
        a.SetNumberOfTuples(1)
        a.SetValue(0, 1)
        b = vtkIntArray()
        b.SetNumberOfTuples(1)
        b.SetValue(0, 2)
        ptr = a.GetVoidPointer(0)
        # check the format _0123456789abcdef_p_void
        self.assertEqual(ptr[0:1], "_")
        self.assertEqual(ptr[-7:], "_p_void")
        address = int(ptr[1:-7], 16)
        # check that we can use the pointer
        b.SetVoidArray(ptr, 1, 1)
        self.assertEqual(b.GetValue(0), 1)
        a.SetValue(0, 10)
        self.assertEqual(b.GetValue(0), 10)

    def testObjectPointer(self):
        a = vtkInformation()
        ptr = a.__this__
        # check the format _0123456789abcdef_p_vtkInformation
        self.assertEqual(ptr[0:1], "_")
        self.assertEqual(ptr[-17:], "_p_vtkInformation")
        address = int(ptr[1:-17], 16)
        # create a VTK object from the swig pointer
        b = vtkObject(ptr)
        self.assertEqual(b.GetClassName(), a.GetClassName())
        self.assertEqual(a.__this__, b.__this__)
        self.assertEqual(a, b)

if __name__ == "__main__":
    Testing.main([(TestSwigPointer, 'test')])


"""
Introduction running and visualising the MPE environments using random actions.
"""

import jax
from jaxmarl import make
from jaxmarl.environments.mpe import MPEVisualizer

# Parameters + random keys
max_steps = 25
key = jax.random.PRNGKey(0)
key, key_r, key_a = jax.random.split(key, 3)

# Instantiate environment
env = make('MPE_simple_reference_v3')
obs, state = env.reset(key_r)
print('list of agents in environment', env.agents)

# Sample random actions
key_a = jax.random.split(key_a, env.num_agents)
actions = {agent: env.action_space(agent).sample(key_a[i]) for i, agent in enumerate(env.agents)}
print('example action dict', actions)

state_seq = []
for _ in range(max_steps):
    state_seq.append(state)
    # Iterate random keys and sample actions
    key, key_s, key_a = jax.random.split(key, 3)
    key_a = jax.random.split(key_a, env.num_agents)
    actions = {agent: env.action_space(agent).sample(key_a[i]) for i, agent in enumerate(env.agents)}

    # Step environment
    obs, state, rewards, dones, infos = env.step(key_s, state, actions)

viz = MPEVisualizer(env, state_seq)
viz.animate(view=True)


class Solution:
    def numTilePossibilities(self, tiles: str) -> int:
        res = set()

        def dfs(prefix, tiles):
            if prefix in res:
                return
            res.add(prefix)
            for i, t in enumerate(tiles):
                dfs(prefix + t, tiles[:i] + tiles[i + 1 :])

        dfs("", tiles)
        return len(res) - 1


from email.mime import image
import pygame
import random

pygame.init()
#bắt đầu
start = 0
start2 =0
start_1=0
check_1=0
check_2= 0
check_3=0
check_4=0
game_over = 0
game_over_2 = 0
pipe_frequency = 2000
last_pipe = pygame.time.get_ticks() - pipe_frequency
last_pipe_2 = pygame.time.get_ticks() - pipe_frequency
p_pass = 0
p_pass_2 = 0
score = 0
score2 = 0
#màn hình
width = 1200
height = 900
displaysurf = pygame.display.set_mode((width,height))
font = pygame.font.SysFont('Bauhaus 93', 60)
#set up tên cửa sổ
pygame.display.set_caption('Flappy Bird')
#background + sàn
floor = pygame.image.load('img/ground.png')
floor = pygame.transform.scale(floor,(width+70,168))
floor_1 = pygame.transform.scale(floor,(width//2+70,168))
floor_move =0
floor_move_2=width//2
background = pygame.image.load('img/bg.png')
background = pygame.transform.scale(background,(width,height))
botton_load = pygame.image.load('img/restart.png')
botton_1 = pygame.image.load('img/1player.png')
botton_1 = pygame.transform.scale(botton_1,(160,100))
botton_2 = pygame.image.load('img/2player.png')
botton_2 = pygame.transform.scale(botton_2,(160,100))
#âm thanh
bird_wing = pygame.mixer.Sound('sound/sfx_wing.wav')
# bird_die = pygame.mixer.Sound('sound/sfx_die.wav')
bird_point = pygame.mixer.Sound('sound/sfx_point.wav')
# bird_swooshing = pygame.mixer.Sound('sound/sfx_swooshing.wav')
bird_hit = pygame.mixer.Sound('sound/sfx_hit.wav')
#Chim
class Bird(pygame.sprite.Sprite) :
    def __init__(self,x,y):
        super(Bird, self).__init__()
        self.imgs = []
        self.count = 0
        self.index = 0
        self.v=0
        for i in range(1,4):
            self.imgs.append(pygame.image.load(f'img/bird{i}.png'))
        self.image = self.imgs[0]
        self.rect = self.image.get_rect()
        self.rect.center = (x,y)
    #chuyển động chim
    def update(self):
        #rơi
        if start == 1:
            self.v += 0.7
            if self.rect.bottom < height-132:
                self.rect.y += int(self.v)
            if self.v == 8:
                self.v = 8
        #bay
        if game_over == 0:
            if pygame.key.get_pressed()[pygame.K_SPACE]==1:
                bird_wing.play()
                self.v = 0
                self.v -= 10
            self.count += 1
            if self.index == len(self.imgs):
                self.index = 0
            self.image = self.imgs[self.index]
            self.image  = pygame.transform.rotate(self.image,self.v*-1)
            if self.count > 11:
                self.index += 1
                self.count = 0
        else:
            self.image  = pygame.transform.rotate(self.imgs[0],-90)
class Bird_2(pygame.sprite.Sprite) :
    def __init__(self,x,y):
        super(Bird_2, self).__init__()
        self.imgs = []
        self.count = 0
        self.index = 0
        self.v=0
        for i in range(1,4):
            self.imgs.append(pygame.transform.scale(pygame.image.load(f'img/bird_{i}.png'),(51,36)))
        self.image = self.imgs[0]
        self.rect = self.image.get_rect()
        self.rect.center = (x,y)
    #chuyển động chim
    def update(self):
        #rơi
        if start2 == 1:
            self.v += 0.7
            if self.rect.bottom < height-132:
                self.rect.y += int(self.v)
            if self.v == 8:
                self.v = 8
        #bay
        if game_over_2 == 0:
            if pygame.mouse.get_pressed()[2]==1:
                bird_wing.play()
                self.v = 0
                self.v -= 10
            self.count += 1
            if self.index == len(self.imgs):
                self.index = 0
            self.image = self.imgs[self.index]
            self.image  = pygame.transform.rotate(self.image,self.v*-1)
            if self.count > 11:
                self.index += 1
                self.count = 0
        else:
            self.image  = pygame.transform.rotate(self.imgs[0],-90)
#ống nước
class Pipe(pygame.sprite.Sprite):
    def __init__(self, x,y,pos):
        super(Pipe,self).__init__()
        self.image = pygame.image.load('img/pipe.png')
        self.rect = self.image.get_rect()
        if pos == -1:
            self.rect.topleft = (x,y+100)
        if pos == 1:
            self.image = pygame.transform.flip(self.image,False,True)
            self.rect.bottomleft = (x,y-100)
    def update(self):
        self.rect.x -=4
        if self.rect.right < 0:
            self.kill()
class Pipe2(pygame.sprite.Sprite):
    def __init__(self, x,y,pos):
        super(Pipe2,self).__init__()
        self.image = pygame.image.load('img/pipe.png')
        self.rect = self.image.get_rect()
        if pos == -1:
            self.rect.topleft = (x,y+100)
        if pos == 1:
            self.image = pygame.transform.flip(self.image,False,True)
            self.rect.bottomleft = (x,y-100)
    def update(self):
        self.rect.x -=4
        if self.rect.right < width//2+90:
            self.kill()
#nút
class Botton:
    def __init__(self, x, y, image):
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.topleft = (x,y)
        self.x = x
        self.y = y
    def draw(self):
        displaysurf.blit(self.image,(self.x,self.y))
    def check(self):
        action = 0
        pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(pos):
            if pygame.mouse.get_pressed()[0] == 1:
                action = 1
        return action
bird = Bird(100,int(height/2))
bird_group = pygame.sprite.Group()
pipe_group = pygame.sprite.Group()
bird_group.add(bird)
botton = Botton(int(width/2)-60,int(height/2),botton_load)
bird1 = Bird_2(width//2+100,int(height/2))
bird_group_2 = pygame.sprite.Group()
bird_group_2.add(bird1)
pipe_group_2 = pygame.sprite.Group()
floor_2 = pygame.transform.scale(floor,(20,168))
#vẽ chữ
def draw_text(text,font,color,x,y):
    img = font.render(text,True, color)
    displaysurf.blit(img,(x,y))
botton1 = Botton(int(width/2)-260,int(height/2)-200,botton_1)
botton2 = Botton(int(width/2)+100,int(height/2)-200,botton_2)
seperate = pygame.image.load('img/ngancach.png')
seperate = pygame.transform.scale(seperate,(10,height))
floor_3 = pygame.image.load('img/aa.png')
floor_3 = pygame.transform.scale(floor_3,(20,168))
clock = pygame.time.Clock()

run =1
while run:
    clock.tick(60)
    displaysurf.blit(background,(0,0))
    if start == 0:
        displaysurf.blit(pygame.transform.scale(background,(width,height)) ,(0,0))
        botton1.draw()
        botton2.draw()
        if botton1.check() and start == 0 and game_over == 0:
            start_1 = 0
            start = 1
            check_1=0
            check_3=0
        if botton2.check() and start == 0 and game_over == 0 and start2 ==0 and game_over_2 == 0:
            start_1 = 1
            start = 1
            start2 = 1
            check_2=0
            check_1=0
            check_3 = 0
            check_4=0
    if start_1 == 0:
        background = pygame.transform.scale(background,(width,height))
        if start == 1 and game_over ==0  :
            if check_3 == 0:
                displaysurf.blit(pygame.transform.scale(pygame.image.load('img/bird1.png'),(51,36)),(100,height//2))
            if pygame.key.get_pressed()[pygame.K_SPACE]==1:
                check_3 = 1
            if check_3:
                bird_group.draw(displaysurf)
                bird_group.update()
                pipe_group.draw(displaysurf)
        #kiem tra va cham
        if check_3:
            if pygame.sprite.groupcollide(bird_group,pipe_group,False,False) or bird.rect.top < 0:
                if game_over== 0:
                    bird_hit.play()
                game_over = 1
            if bird.rect.bottom >=height-132:
                if game_over == 0:
                    bird_hit.play()
                game_over = 1
            displaysurf.blit(floor,(floor_move,height -132))
            #di chuyển ống + sàn
            if game_over == 0 and start == 1:
                pipe_now = pygame.time.get_ticks()
                if pipe_now - last_pipe > pipe_frequency and start ==1:
                    pipe_h = random.randint(-200,200)
                    top_pipe = Pipe(width,int(height/2)+pipe_h,1)
                    bottom_pipe = Pipe(width,int(height/2)+pipe_h-30,-1)
                    pipe_group.add(bottom_pipe)
                    pipe_group.add(top_pipe)
                    last_pipe = pipe_now
                if floor_move <= -40:
                    floor_move = 0
                floor_move -=4
                pipe_group.update()
            #điểm
            if len(pipe_group) > 0:
                if bird_group.sprites()[0].rect.left > pipe_group.sprites()[0].rect.left and  bird_group.sprites()[0].rect.right < pipe_group.sprites()[0].rect.right and p_pass == 0:
                    p_pass = 1
                if p_pass == 1 and bird_group.sprites()[0].rect.left > pipe_group.sprites()[0].rect.right:
                    bird_point.play()
                    score += 1
                    p_pass = 0
            if start ==1:
                draw_text(str(score),font,(255,255,255,255),int(width/2),0)
            #restart
            if game_over == 1 and start ==1:
                botton.draw()
                if botton.check():
                    start = 0
                    pipe_group.empty()
                    bird.rect.x = 100
                    bird.rect.y = int(height / 2)
                    score = 0
                    game_over = 0
                    bird.v=0
    else:
        #player 1
        displaysurf.blit(background,(0,0))
        if start == 1:
            if check_1 == 0:
                displaysurf.blit(pygame.transform.scale(pygame.image.load('img/bird1.png'),(51,36)),(100,height//2))
            if pygame.key.get_pressed()[pygame.K_SPACE]==1:
                check_1 = 1
            if check_1:
                check_4 = 1
                bird_group.draw(displaysurf)
                bird_group.update()
                pipe_group.draw(displaysurf)
            #kiem tra va cham
        if check_1:
            if pygame.sprite.groupcollide(bird_group,pipe_group,False,False) or bird.rect.top < 0:
                if game_over == 0:
                    bird_hit.play()
                game_over = 1
            if bird.rect.bottom >=height-132:
                if game_over == 0:
                    bird_hit.play()
                game_over = 1
            displaysurf.blit(floor_1,(floor_move,height -132))
            #di chuyển ống + sàn
            if game_over == 0 and start == 1:
                pipe_now = pygame.time.get_ticks()
                if pipe_now - last_pipe > pipe_frequency and start ==1:
                    pipe_h = random.randint(-200,200)
                    top_pipe = Pipe(width//2,int(height/2)+pipe_h,1)
                    bottom_pipe = Pipe(width//2,int(height/2)+pipe_h-20,-1)
                    pipe_group.add(bottom_pipe)
                    pipe_group.add(top_pipe)
                    last_pipe = pipe_now
                if floor_move <= -40:
                    floor_move = 0
                floor_move -=4
                pipe_group.update()
            if game_over == 1:
                displaysurf.blit(floor,(floor_move,height -132))
            #điểm
            if len(pipe_group) > 0:
                if bird_group.sprites()[0].rect.left > pipe_group.sprites()[0].rect.left and  bird_group.sprites()[0].rect.right < pipe_group.sprites()[0].rect.right and p_pass == 0:
                    p_pass = 1
                if p_pass == 1 and bird_group.sprites()[0].rect.left > pipe_group.sprites()[0].rect.right:
                    bird_point.play()
                    score += 1
                    p_pass = 0
            if start ==1:
                draw_text(str(score),font,(255,255,255,255),int(width/4),0)
        #player2
        displaysurf.blit(background,(width//2,0))
        if start2 == 1:
            if check_2 == 0 :
                displaysurf.blit(pygame.transform.scale(pygame.image.load('img/bird_1.png'),(51,36)),(width//2+100,height//2))
            if  pygame.mouse.get_pressed()[2]==1:
                check_2=1
            if check_2==1:
                bird_group_2.draw(displaysurf)
                bird_group_2.update()
                pipe_group_2.draw(displaysurf)
            #kiem tra va cham
                if pygame.sprite.groupcollide(bird_group_2,pipe_group_2,False,False) or bird1.rect.top < 0:
                    if game_over_2 == 0:
                        bird_hit.play()
                    game_over_2 = 1
                if bird1.rect.bottom >=height-132:
                    if game_over_2 == 0:
                        bird_hit.play()
                    game_over_2 = 1
                displaysurf.blit(floor_1,(floor_move_2,height-132))
                #di chuyển ống + sàn
                if game_over_2 == 0 and start2 == 1:
                    pipe_now_1 = pygame.time.get_ticks()
                    if pipe_now_1 - last_pipe_2 > pipe_frequency and start2 ==1:
                        pipe_h = random.randint(-200,200)
                        top_pipe = Pipe2(width,int(height/2)+pipe_h,1)
                        bottom_pipe = Pipe2(width,int(height/2)+pipe_h-20,-1)
                        pipe_group_2.add(bottom_pipe)
                        pipe_group_2.add(top_pipe)
                        last_pipe_2 = pipe_now_1
                    if floor_move_2 <= width//2-20:
                        floor_move_2 = width//2
                    floor_move_2 -=4
                    pipe_group_2.update()
                #điểm
                if len(pipe_group_2):
                    if bird_group_2.sprites()[0].rect.left > pipe_group_2.sprites()[0].rect.left and  bird_group_2.sprites()[0].rect.right < pipe_group_2.sprites()[0].rect.right and p_pass_2 == 0:
                        p_pass_2 = 1
                    if p_pass_2 == 1 and bird_group_2.sprites()[0].rect.left > pipe_group_2.sprites()[0].rect.right:
                        bird_point.play()
                        score2 += 1
                        p_pass_2 = 0
                if start2 ==1:
                    draw_text(str(score2),font,(255,255,255,255),int(width*3/4),0)
            if check_1 and check_2:
                displaysurf.blit(floor_2,(width//2-20,height-132))
            if check_4 == 0 and check_2 ==1:
                displaysurf.blit(floor_3,(width//2-20,height-132))
            displaysurf.blit(seperate,(width//2,0))
            #restart
            if game_over == 1 and start ==1 and game_over_2==1 and start2==1:
                displaysurf.blit(pygame.transform.scale(background,(width,height)),(0,0))
                botton.draw()
                if botton.check():
                    start = 0
                    start2=0
                    pipe_group.empty()
                    pipe_group_2.empty()
                    bird.rect.x = 100
                    bird.rect.y = int(height / 2)
                    bird1.rect.x = width//2+100
                    bird1.rect.y = int(height / 2)
                    bird1.v=0
                    bird.v = 0
                    score = 0
                    score2 = 0
                    game_over = 0
                    game_over_2 = 0
                    background = pygame.transform.scale(background,(width//2,height))
    if start == 0:
        displaysurf.blit(pygame.transform.scale(background,(width,height)) ,(0,0))
        botton1.draw()
        botton2.draw()
        if botton1.check() and start == 0 and game_over == 0:
            start_1 = 0
            start = 1
            check_1=0
        if botton2.check() and start == 0 and game_over == 0 and start2 ==0 and game_over_2 == 0:
            start_1 = 1
            start = 1
            start2 = 1
            check_2=0
            check_1=0
            check_3 = 0
            check_4 = 0
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = 0
    pygame.display.update()

pygame.quit()


"""
Day23 : Implement a function that takes two integers as input and returns their greatest common divisor (GCD).
"""

#Program

def gcd(a, b):

	if (a == 0):
		return b
	if (b == 0):
		return a

	if (a == b):
		return a

	if (a > b):
		return gcd(a-b, b)
	return gcd(a, b-a)

a = 98
b = 56
if(gcd(a, b)):
	print('GCD of', a, 'and', b, 'is', gcd(a, b))
else:
	print('not found')


import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
from sklearn.feature_selection import RFE
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
import pandas as pd
import sys
import matplotlib.pyplot as plt

def main():
    df = pd.read_csv("austin_weather.csv")
    df = df.drop('Date', axis=1)

    indexes = list()
    for iter,row in df.iterrows():
        for c in df.columns:
            if row[c] == '-' :
                if iter not in indexes: indexes.append(iter)
    df.drop(df.index[indexes], inplace=True)

    predictions_df = df[['Events']]
    predictions_df['Events'] = np.where(df['Events'].str.contains('Rain'), 1,  0)
    samples_df = df.drop(['Events','PrecipitationSumInches'], axis=1)

    print(samples_df)
    print(predictions_df['Events'].value_counts())

    data_vars=samples_df.columns.values.tolist()
    data_final_vars = list()

    logreg = LogisticRegression(max_iter=10000)
    rfe = RFE(logreg, n_features_to_select=9)
    rfe = rfe.fit(samples_df, predictions_df.values.ravel())
    print(rfe.support_)
    print(rfe.ranking_)

    for idx,val in enumerate(rfe.support_):
        if val: data_final_vars.append(data_vars[idx])

    print(samples_df.columns.values)
    print(data_final_vars)

    final_samples_df = samples_df[data_final_vars]
    print(final_samples_df)

    X_train, X_test, y_train, y_test = train_test_split(final_samples_df, predictions_df, test_size=0.2)
    print(f'Полная выборка: {len(samples_df)}\nТренировочная: {len(X_train)}')

    model = LogisticRegression(max_iter=10000)
    model.fit(X_train, y_train)

    np.set_printoptions(threshold=sys.maxsize)
    y_pred = model.predict(X_test)

    print('Accuracy of logistic regression classifier on test set: {:.2f}'.format(model.score(X_test, y_test)))
    #print("MSE:", mean_squared_error(y_test, y_pred))
    #print("r2_score = %s" % r2_score(y_test, y_pred))

    logit_roc_auc = roc_auc_score(y_test, model.predict(X_test))
    fpr, tpr, thresholds = roc_curve(y_test, model.predict_proba(X_test)[:,1])
    plt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc)
    plt.plot([0, 1], [0, 1],'r--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver operating characteristic')
    plt.legend(loc="lower right")
    plt.show()

if __name__ == "__main__":
    main()


import networkx as nx
import csv
from itertools import combinations

# all networks
n = {}
with open('data/srep00196-s3.csv') as f:
    reader = csv.reader(f)
    for r in reader:
        # discard comments
        if r[0].startswith('#'):
            continue
        cuisine = r[0]

        # a different network per cuisine
        if cuisine not in n:
            n[cuisine] = nx.Graph()

        # connect all combinations of two ingredients, repeats sum weight
        for pair in combinations(r[1:], 2):
            e = n[cuisine].get_edge_data(*pair)
            if e:
                w = e['weight'] + 1
            else:
                w = 1
            n[cuisine].add_edge(*pair, weight=w)

# write out a pickle per cuisine
for cuisine in n:
    nx.gpickle.write_gpickle(n[cuisine], 'data/omni_%s.pickle' % cuisine)


class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        # 考虑nums[i],i > k
        # 在nums[i - k:i]中,所有比nums[i]小的数都将不起作用,可以弹出
        # 此时nums[i]是最小的,放在队列最左侧
        def clearStack(i):  # 将deque中小于nums[i]的弹出
            # 如果i - k是当前最大值,则需要弹出
            # 否则,无需理会
            # 那么,会不会有i < j,nums[stack[i]] > nums[stack[j]],stack[i]先被弹出,而stack[j]无法被弹出的情况呢?
            # 假设stack[j] < stack[i],由于nums[stack[i]] > nums[stack[j]]
            # 在扫描stack[0]的时候,先扫描到i,j没有被扫描到
            # 但是由于nums[stack[i]] > nums[stack[j]],在stack[i]被插入的时候,stack[j]已经被弹出了
            if stack and stack[0] == i - k:
                stack.pop(0)
            while stack and nums[i] > nums[stack[-1]]:
                stack.pop()
            #print(stack)

        stack = []  # 存放nums的下标,按照nums[i]从大到小排序
        n = len(nums)
        ans = []
        for i in range(n):
            clearStack(i)
            stack.append(i)
            #print(stack)
            if i >= k - 1:
                ans.append(nums[stack[0]])
        return ans


import json
import random
import logging
from utils import utils

class UfMentionLabelLoader:
    def __init__(self, mention_file, extra_label_file, yield_id=False):
        self.mention_file = mention_file
        self.extra_label_file = extra_label_file
        self.yield_id = yield_id

    def __iter__(self):
        return self.mention_label_gen()

    def mention_label_gen(self):
        fm = open(self.mention_file, encoding='utf-8')
        fl = open(self.extra_label_file, encoding='utf-8') if self.extra_label_file is not None else None
        cur_label_obj = None
        for i, line_m in enumerate(fm):
            mention = json.loads(line_m)
            if self.extra_label_file is None:
                if self.yield_id:
                    yield i, mention, None
                else:
                    yield mention, None
            else:
                if (cur_label_obj is None or cur_label_obj['id'] < i) and fl is not None:
                    try:
                        line_l = next(fl)
                        cur_label_obj = json.loads(line_l)
                    except StopIteration:
                        fl.close()
                        fl = None
                r_label_obj = None
                if cur_label_obj['id'] == i:
                    r_label_obj = cur_label_obj
                else:
                    assert cur_label_obj['id'] > i
                if self.yield_id:
                    yield i, mention, r_label_obj
                else:
                    yield mention, r_label_obj
        fm.close()
        if fl is not None:
            fl.close()

class SimpleUFBertBatchLoader:
    def __init__(self, tokenizer, mention_files, label_files, max_seq_len, batch_size, yield_id=False, loop=True):
        self.tokenizer = tokenizer
        self.mention_files = mention_files
        self.label_files = label_files
        self.file_idx = 0
        self.max_seq_len = max_seq_len
        self.batch_size = batch_size
        self.yield_id = yield_id
        self.loop = loop

    def __iter__(self):
        return self.next_batch()

    def next_batch(self):
        ml_loader = iter(UfMentionLabelLoader(
            self.mention_files[self.file_idx], self.label_files[self.file_idx], yield_id=self.yield_id))

        batch = list()
        while True:
            try:
                mid = None
                if self.yield_id:
                    mid, mention, lobj = next(ml_loader)
                else:
                    mention, lobj = next(ml_loader)
                # print(lobj)
                # exit()
                tok_id_seq = uf_mention_to_sm_bert_sample(self.tokenizer, mention, self.max_seq_len)
                if tok_id_seq is not None:
                    if self.yield_id:
                        sample = mid, tok_id_seq, mention['y_str'], mention, lobj
                    else:
                        sample = tok_id_seq, mention['y_str'], lobj
                    batch.append(sample)
                    if len(batch) >= self.batch_size:
                        yield batch
                        batch = list()
            except StopIteration:
                self.file_idx = (self.file_idx + 1) % len(self.mention_files)
                if self.file_idx == 0 and not self.loop:
                    break
                ml_loader = iter(UfMentionLabelLoader(self.mention_files[self.file_idx], None, yield_id=self.yield_id))

class SampleBatchLoader:
    def __init__(self, samples, batch_size, n_iter, shuffle=False, n_steps=-1):
        self.samples = samples
        self.batch_size = batch_size
        self.n_iter = n_iter
        self.shuffle = shuffle
        self.n_samples = len(self.samples)
        self.n_batches = (self.n_samples + batch_size - 1) // batch_size
        self.n_steps = n_iter * self.n_batches
        if n_steps > 0:
            self.n_steps = n_steps

    def batch_at(self, batch_idx):
        batch_idx = batch_idx % self.n_batches
        batch_beg, batch_end = batch_idx * self.batch_size, min((batch_idx + 1) * self.batch_size, self.n_samples)
        return self.samples[batch_beg:batch_end]

    def __iter__(self):
        return self.batch_iter()

    def batch_iter(self):
        for step in range(self.n_steps):
            batch_idx = step % self.n_batches
            batch_beg, batch_end = batch_idx * self.batch_size, min((batch_idx + 1) * self.batch_size, self.n_samples)
            batch = self.samples[batch_beg:batch_end]
            if batch_beg == self.n_samples and self.shuffle:
                random.shuffle(self.samples)
            yield batch

def get_bert_sep_token_seq(ltokens, rtokens, mstr_tokens, second_seg_tokens, max_seq_len, discard_too_long):
    seq_len = len(ltokens) + len(rtokens) + len(mstr_tokens) + len(second_seg_tokens) + 3
    if seq_len > max_seq_len:
        if discard_too_long:
            return None
        l_ex = seq_len - max_seq_len
        rtokens = rtokens[:max(0, len(rtokens) - l_ex)]
        l_ex = len(ltokens) + len(rtokens) + len(mstr_tokens) + len(second_seg_tokens) + 3 - max_seq_len
        if l_ex > 0:
            ltokens = ltokens[min(l_ex, len(ltokens) - 1):]
        l_ex = len(ltokens) + len(rtokens) + len(mstr_tokens) + len(second_seg_tokens) + 3 - max_seq_len
        if l_ex > 0:
            mstr_tokens = []
            second_seg_tokens = second_seg_tokens[:100]
    assert len(ltokens) + len(rtokens) + len(mstr_tokens) + len(second_seg_tokens) + 3 <= max_seq_len
    token_seq = ['[CLS]'] + ltokens + mstr_tokens + rtokens + ['[SEP]'] + second_seg_tokens + ['[SEP]']
    return token_seq

def uf_mention_to_sm_bert_sample(tokenizer, mention, max_seq_len, discard_too_long=True):
    lcxt, rcxt = ' '.join(mention['left_context_token']), ' '.join(mention['right_context_token'])
    mstr = mention['mention_span']

    ltokens, rtokens = tokenizer.tokenize(lcxt), tokenizer.tokenize(rcxt)
    mstr_tokens = tokenizer.tokenize(mstr)
    token_seq = get_bert_sep_token_seq(ltokens, rtokens, mstr_tokens, mstr_tokens, max_seq_len, discard_too_long)
    token_id_seq = tokenizer.convert_tokens_to_ids(token_seq)
    return token_id_seq

def bert_sm_samples_from_json_data(
        tokenizer, type_id_dict, json_data_file, max_seq_len=128, n_sample_limit=-1):
    samples = list()
    f = open(json_data_file, encoding='utf-8')
    for i, line in enumerate(f):
        x = json.loads(line)
        token_id_seq = uf_mention_to_sm_bert_sample(tokenizer, x, max_seq_len, discard_too_long=False)

        type_ids = [type_id_dict[t] for t in x['y_str']]
        samples.append((i, token_id_seq, type_ids))
        if n_sample_limit > 0 and len(samples) > n_sample_limit:
            break
    f.close()
    return samples

class LabelReader:
    def __init__(self, label_file):
        self.f = open(label_file, encoding='utf-8')
        self.cur_label_obj = None

    def labels_for(self, mention_id):
        if self.f is None:
            return None

        while True:
            if self.cur_label_obj is not None:
                cur_id = self.cur_label_obj['id']
                if cur_id == mention_id:
                    return self.cur_label_obj
                if cur_id > mention_id:
                    return None
            try:
                line = next(self.f)
                self.cur_label_obj = json.loads(line)
            except StopIteration:
                self.f.close()
                self.f = None
                return None

def get_labels_with_weights(
        type_id_dict, orignal_labels, ex_labels, ex_label_is_tids, weight_for_original, weight_for_mlm):
    if weight_for_mlm < 0:
        weight_for_mlm = 1.0

    tids = [type_id_dict.get(t, -1) for t in orignal_labels]
    tids = [tid for tid in tids if tid > -1]
    type_weights = [weight_for_original for _ in tids]

    if ex_labels is None:
        return tids, type_weights

    for i, label in enumerate(ex_labels):
        tid = label if ex_label_is_tids else type_id_dict[label]
        if tid not in tids:
            tids.append(tid)
            type_weights.append(weight_for_mlm)

    return tids, type_weights

class UfDataBatchLoader:
    def __init__(self, tokenizer, type_vocab, type_id_dict, mention_files, extra_label_files,
                 batch_size, max_seq_len, max_n_ex_types, ex_tids=False, weight_for_original_labels=1,
                 weight_for_mlm=1):
        self.mention_files = mention_files
        self.extra_label_files = extra_label_files
        self.f = None
        self.file_idx = 0
        self.n_files = len(self.mention_files)
        self.tokenizer = tokenizer
        self.type_vocab = type_vocab
        self.type_id_dict = type_id_dict
        self.batch_size = batch_size
        self.max_seq_len = max_seq_len
        self.ex_label_reader = None
        if extra_label_files is not None:
            self.ex_label_reader = LabelReader(extra_label_files[0])
            # print('use labels {}'.format(self.extra_label_files[0]))
            logging.info('use labels {}'.format(self.extra_label_files[0]))
        self.mention_id = 0
        self.max_n_ex_types = max_n_ex_types
        self.ex_tids = ex_tids
        self.is_first_file = True
        self.weight_for_original_labels = weight_for_original_labels
        self.weight_for_mlm = weight_for_mlm

    def next_batch(self):
        if self.f is None:
            self.f = open(self.mention_files[self.file_idx], encoding='utf-8')
            # print('use {}'.format(self.mention_files[self.file_idx]))
            logging.info('use {}'.format(self.mention_files[self.file_idx]))

        batch = list()
        while len(batch) < self.batch_size:
            try:
                line = next(self.f)
                x = json.loads(line)
                ex_labels = None
                if self.ex_label_reader is not None:
                    ex_label_obj = self.ex_label_reader.labels_for(self.mention_id)
                    if ex_label_obj is not None:
                        # ex_labels = ex_label_obj['types']
                        ex_labels = ex_label_obj['tids'] if self.ex_tids else ex_label_obj['types']
                        n_tmp = min(len(ex_labels), self.max_n_ex_types)
                        ex_labels = ex_labels[:n_tmp]

                    # print(x)
                    # print(ex_label_obj)
                sample = None
                if ex_labels is not None or self.ex_label_reader is None:
                    token_id_seq = uf_mention_to_sm_bert_sample(self.tokenizer, x, self.max_seq_len)
                    if token_id_seq is not None:
                        tids, weights = get_labels_with_weights(
                            self.type_id_dict, x['y_str'], ex_labels, self.ex_tids,
                            weight_for_original=self.weight_for_original_labels,
                            weight_for_mlm=self.weight_for_mlm)
                        sample = (-1, token_id_seq, tids, weights)
                if sample is not None:
                    batch.append(sample)
                self.mention_id += 1
            except StopIteration:
                self.f.close()
                self.is_first_file = False
                self.file_idx = (self.file_idx + 1) % self.n_files
                self.f = open(self.mention_files[self.file_idx], encoding='utf-8')
                # print('use {}'.format(self.mention_files[self.file_idx]))
                logging.info('use {}'.format(self.mention_files[self.file_idx]))
                self.mention_id = 0
                if self.extra_label_files is not None:
                    self.ex_label_reader = LabelReader(self.extra_label_files[self.file_idx])
                    # print('use labels {}'.format(self.extra_label_files[self.file_idx]))
                    logging.info('use labels {}'.format(self.extra_label_files[self.file_idx]))
        return batch

class MyMentionLabelLoader:
    def __init__(self, mention_file, label_file):
        self.mention_file = mention_file
        self.label_file = label_file

    def __iter__(self):
        return self.mention_label_gen()

    def mention_label_gen(self):
        fm = open(self.mention_file, encoding='utf-8')
        fl = open(self.label_file, encoding='utf-8')
        cur_label_obj = None
        for i, line_m in enumerate(fm):
            mention = json.loads(line_m)
            mention_id = mention['id']
            if (cur_label_obj is None or cur_label_obj['id'] < mention_id) and fl is not None:
                try:
                    line_l = next(fl)
                    cur_label_obj = json.loads(line_l)
                except StopIteration:
                    fl.close()
                    fl = None
                    break
            if cur_label_obj['id'] == mention_id:
                yield mention, cur_label_obj
            else:
                if cur_label_obj['id'] < mention_id:
                    print(i, mention)
                    print(cur_label_obj)
                    print()
                assert cur_label_obj['id'] > mention_id
                yield mention, None
        fm.close()
        if fl is not None:
            fl.close()

def bert_sm_seq_from_my_mention(tokenizer, mention, max_seq_len):
    text = mention['text']
    bp, ep = mention['span']
    mstr = text[bp:ep]
    tokens = ['[CLS]'] + tokenizer.tokenize(text) + ['[SEP]'] + tokenizer.tokenize(mstr) + ['[SEP]']
    if len(tokens) > max_seq_len:
        return None
    token_id_seq = tokenizer.convert_tokens_to_ids(tokens)
    return token_id_seq

class MyMentionTypeDataBatchLoader:
    def __init__(self, tokenizer, type_vocab, type_id_dict, mention_file, type_file, batch_size,
                 max_n_types, max_seq_len, ex_tids=False, use_weighted_loss=False, weight_for_mlm=1):
        self.mention_file = mention_file
        self.type_file = type_file
        self.type_vocab = type_vocab
        self.mention_file = mention_file
        self.label_file = type_file
        self.ml_loader = iter(MyMentionLabelLoader(mention_file, type_file))
        self.tokenizer = tokenizer
        self.type_id_dict = type_id_dict
        self.batch_size = batch_size
        self.max_n_types = max_n_types
        self.max_seq_len = max_seq_len
        self.rr_state = 0
        self.ex_tids = ex_tids
        self.person_type_id = self.type_id_dict['person']
        self.use_weighted_loss = use_weighted_loss
        self.weight_for_mlm = weight_for_mlm if weight_for_mlm > 0 else 1.0

    def next_batch(self):
        batch = list()
        # for i, (mention, lobj) in enumerate(self.ml_loader):
        while len(batch) < self.batch_size:
            try:
                mention, lobj = next(self.ml_loader)
                if lobj is None:
                    continue

                type_labels = lobj['tids'] if self.ex_tids else lobj['types']
                if len(type_labels) > self.max_n_types:
                    type_labels = type_labels[:self.max_n_types]
                if type_labels is None:
                    continue

                pbeg, pend = mention['span']
                mstr = mention['text'][pbeg:pend]
                if mstr.lower() in utils.person_pronouns and 'person' not in type_labels:
                    if self.ex_tids:
                        type_labels.append(self.person_type_id)
                    else:
                        type_labels.append('person')

                if not self.ex_tids:
                    type_labels = [self.type_id_dict[t] for t in type_labels]

                token_id_seq = bert_sm_seq_from_my_mention(self.tokenizer, mention, self.max_seq_len)
                if token_id_seq is not None:
                    if self.use_weighted_loss:
                        weights = [self.weight_for_mlm for i in range(len(type_labels))]
                        # print(self.tokenizer.convert_ids_to_tokens(token_id_seq))
                        # print([self.type_vocab[tid] for tid in type_labels])
                        # print(weights)
                        # exit()
                        batch.append((mention['id'], token_id_seq, type_labels, weights))
                    else:
                        batch.append((mention['id'], token_id_seq, type_labels))
                # if sample is not None:
                #     batch.append(sample)
            except StopIteration:
                self.ml_loader = iter(MyMentionLabelLoader(self.mention_file, self.type_file))
        return batch


from pygame import *
from pygame.locals import *

import os
os.chdir('C:/Users/Asus/FinalProjectSirJude')

from permainan import * #importing game progress
from tkinter import *
from ALLFUNC import *
from SCREEN2_PLAYING import *
from characterplat import *

from pygame import mixer

def inventorys():
    pygame.init()

    mixer.init()
    mixer.music.load('campfire.mp3')
    mixer.music.set_volume(1)
    mixer.music.play(-1)

    screen_width = 1300
    screen_height = 650

    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption('Poopyz.World')
    screen.fill((74,98,110))
    pygame.display.flip
    #define game variables
    tile_size = 80

    white = (255, 255, 255)
    green = (0, 255, 0)
    blue = (0, 0, 128)
    black = (16,16,16)

    illuminablank_img = pygame.image.load('illuminablank.png')
    illuminablank_img_rect = illuminablank_img.get_rect()
    illuminablank_img_rect.x = 1300-145
    illuminablank_img_rect.y = 650-20

    creepoopblank_img = pygame.image.load('creepblank.png')
    creepoopblank_img_rect = creepoopblank_img.get_rect()

    class World():
        def __init__(self, data):
            self.tile_list = []

            #load images
            bingkai_img = pygame.image.load('bingkai.png')
            bingkai1_img = pygame.image.load('bingkai1.png')
            creepooper_level_img = pygame.image.load('creepooperinvent.png')
            illuminashiet_level_img = pygame.image.load('illuminavent.png')
            row_count = 0
            for row in data:
                col_count = 0
                for tile in row:
                    if tile == 1:
                        img = pygame.transform.scale(bingkai_img, (tile_size, tile_size))
                        img_rect = img.get_rect()
                        img_rect.x = col_count * tile_size
                        img_rect.y = row_count * tile_size
                        tile = (img, img_rect,2)
                        self.tile_list.append(tile)
                    if tile == 2:
                        img = pygame.transform.scale(bingkai1_img, (tile_size, tile_size))
                        img_rect = img.get_rect()
                        img_rect.x = col_count * tile_size
                        img_rect.y = row_count * tile_size
                        tile = (img, img_rect,2)
                        self.tile_list.append(tile)
                    if tile == 3:
                        img = pygame.transform.scale(bingkai_img, (20,tile_size))
                        img_rect = img.get_rect()
                        img_rect.x = col_count * tile_size
                        img_rect.y = row_count * tile_size
                        tile = (img, img_rect,2)
                        self.tile_list.append(tile)
                    if tile == 928:
                        img = pygame.transform.scale(creepooper_level_img, (tile_size,tile_size))
                        img_rect = img.get_rect()
                        img_rect.x = col_count * tile_size
                        img_rect.y = row_count * tile_size
                        tile = (img, img_rect,2)
                        self.tile_list.append(tile)
                    if tile == 929:
                        img = pygame.transform.scale(illuminashiet_level_img, (tile_size,tile_size))
                        illuminashiet_rect = img.get_rect()
                        illuminashiet_rect.x = col_count * tile_size
                        illuminashiet_rect.y = row_count * tile_size
                        tile = (img, illuminashiet_rect,2)
                        self.tile_list.append(tile)
                    col_count += 1
                row_count += 1

        def draw(self):
            for tile in self.tile_list:
                screen.blit(tile[0], tile[1])

    world_data = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 0],
    [0, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 0],
    [0, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 0]
    ]

    if creepooper_level > 0 :
        world_data[5][1] = 928
        img = pygame.transform.scale(illuminablank_img, (tile_size,tile_size))
        creepooper_img1_rect = img.get_rect()
        creepooper_img1_rect.x = 1*tile_size
        creepooper_img1_rect.y = 5*tile_size

    if illuminashiet_level > 0 :
        world_data[5][2] = 929
        illuminablank_img1_rect = img.get_rect()
        illuminablank_img1_rect.x = 2*tile_size
        illuminablank_img1_rect.y = 5*tile_size

    world = World(world_data)
    run = True

    illu = inventory(illuminablank_img)
    creepoop = inventory(creepoopblank_img)

    while run :
        screen.fill((74,98,110))
        world.draw()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        if creepoop.muncul == True and illu.muncul == False :
            creepoop.tulisan(42,black,creepooper_level,round(creepooper_level*0.02,2),round(creepooper_level*0.04,2),"Creepooper")
            creepoop.countdowns += 5
            pygame.draw.rect(screen,(255,0,0),creepooper_img1_rect,2)

        if creepoop.muncul == False  and creepoop.baba <= 105:
            creepoop.baba += 3

        if illu.muncul == True and creepoop.muncul == False:
            illu.tulisan(42,black,illuminashiet_level,illuminashiet_level*0.01,illuminashiet_level*0.02,"Illuminashiet")
            illu.countdowns += 5
            pygame.draw.rect(screen,(255,0,0),illuminablank_img1_rect,2)

        if illu.muncul == False and illu.baba <= 105 :
            illu.baba += 5

        if event.type == pygame.MOUSEBUTTONDOWN:
            if creepooper_img1_rect.collidepoint(event.pos) and creepoop.muncul == False  :
                creepoop.muncul = True
                creepoop.baba = 0
                illu.muncul = False

            elif creepooper_img1_rect.collidepoint(event.pos) and creepoop.muncul == True and creepoop.countdowns > 100:
                creepoop.countdowns = 0
                creepoop.muncul = False

            if illuminablank_img1_rect.collidepoint(event.pos) and illu.muncul == False  :
                illu.baba = 0
                illu.muncul = True
                creepoop.muncul = False

            elif illuminablank_img1_rect.collidepoint(event.pos) and illu.muncul == True and illu.countdowns > 100:
                illu.countdowns = 0
                illu.muncul = False

        pygame.display.update()

        world.draw()

    pygame.quit()

inventorys()


import gettext as _gettext
import locale

from solaar import NAME as _NAME

#
#
#

def _find_locale_path(lc_domain):
    import os.path as _path
    import sys as _sys
    prefix_share = _path.normpath(_path.join(_path.realpath(_sys.path[0]), '..'))
    src_share = _path.normpath(_path.join(_path.realpath(_sys.path[0]), '..', 'share'))
    del _sys

    from glob import glob as _glob

    for location in prefix_share, src_share:
        mo_files = _glob(_path.join(location, 'locale', '*', 'LC_MESSAGES', lc_domain + '.mo'))
        if mo_files:
            return _path.join(location, 'locale')

    # del _path

try:
    locale.setlocale(locale.LC_ALL, '')
except Exception:
    pass

language, encoding = locale.getlocale()
del locale

_LOCALE_DOMAIN = _NAME.lower()
path = _find_locale_path(_LOCALE_DOMAIN)

_gettext.bindtextdomain(_LOCALE_DOMAIN, path)
_gettext.textdomain(_LOCALE_DOMAIN)
_gettext.install(_LOCALE_DOMAIN)

_ = _gettext.gettext
ngettext = _gettext.ngettext


import cv2
import numpy as np
import os

def get_special_label_image(image, id=1):
    image = image[:, :, 0]
    def f(x):
        if x==id:
            return 1
        return 0
    shape = image.shape
    image = list(np.array(image).flatten())
    image = list(map(f, image))
    image = np.array(image).reshape(shape)
    image = np.uint8(image)
    return image

def build_folder(path):
    if os.path.exists(path) == False:
        os.mkdir(path)

def build_new_label_only_road():
    old_label_path = "../image/labels"
    new_label_path = "../image/new_labels"

    build_folder(new_label_path)

    labels = [f for f in os.listdir(old_label_path) if f.endswith("png")]

    class_no = 17

    for i in range(len(labels)):
        old_label_image_path = old_label_path+"/"+labels[i]
        old_image = cv2.imread(old_label_image_path)
        new_image = get_special_label_image(old_image, class_no)
        # 虽然我们已经处理成了一维图片，但写成jpg的时候又会搞成3通道
        #print(new_image.shape)
        new_label_image_path = new_label_path+"/"+labels[i]
        cv2.imwrite(new_label_image_path, new_image)
        if i%10==0:
            print("已完成{}/{}".format(i, len(labels)))

def test_new_label_image():
    new_label_image_folder = "../image/new_labels"
    image_path = new_label_image_folder+"/"+"0001TP_006690.png"
    image = cv2.imread(image_path)
    print(image.shape)
    cv2.imshow("1", image)
    cv2.waitKey()

def rename_new_label_image():
    '''
    之前没发现image的名字没有_p，但是label名字多了个_p写到dataloader才发现，去吧new_label重命名一下，去掉_p
    :return:
    '''
    new_label_path = "../image/new_labels"
    labels = os.listdir(new_label_path)
    print(len(labels))
    for i in range(len(labels)):
        src = new_label_path+"/"+labels[i]
        dst = new_label_path+"/"+labels[i][:-6]+".png"
        os.rename(src, dst)
        if i%10==0:
            print("已完成{}/{}".format(i, len(labels)))

if __name__ == '__main__':
    # build_new_label_only_road()
    test_new_label_image()
    # rename_new_label_image()


import sys

sys.setrecursionlimit(10 ** 9)
input1 = sys.stdin.readline

# 차례대로 정점의 수 , 간선의 수 , 시작 정점.
n, m, r = map(int, input1().split())
graph = [[] for _ in range(n + 1)]
for _ in range(m):
    a, b = map(int, input1().split())
    graph[a].append(b)
    graph[b].append(a)

visited = [0] * (n + 1)
cnt = 1

# result = [r] # 메모리오류

def dfs(start):
    global cnt
    visited[start] = cnt
    graph[start].sort()
    for i in graph[start]:
        if visited[i] == 0:
            cnt += 1
            dfs(i)

dfs(r)
for i in range(1, n + 1):
    print(visited[i])
    # if i in result: 메모리 초과
    #     print(result.index(i) + 1)
    # else:
    #     print(0)


"""Partially learned gradient descent scheme for ellipses."""

import os
import sys
import adler
#adler.util.gpu.setup_one_gpu()

from adler.tensorflow import prelu, cosine_decay, reference_unet, psnr

import tensorflow as tf
import numpy as np
import odl
import odl.contrib.tensorflow

def random_ellipse(interior=False):
    if interior:
        x_0 = np.random.rand() - 0.5
        y_0 = np.random.rand() - 0.5
    else:
        x_0 = 2 * np.random.rand() - 1.0
        y_0 = 2 * np.random.rand() - 1.0

    magnitude = np.random.choice([-1, 1]) * (0.1 + np.random.exponential(0.2))

    return (magnitude,
            np.random.exponential() * 0.2, np.random.exponential() * 0.2,
            x_0, y_0,
            np.random.rand() * 2 * np.pi)

def random_phantom(spc, n_ellipse=50, interior=False):
    n = np.random.poisson(n_ellipse)
    ellipses = [random_ellipse(interior=interior) for _ in range(n)]
    return odl.phantom.ellipsoid_phantom(spc, ellipses)

def make_difference(space):
    minp = (np.random.rand(2) - 0.5) - 0.05
    maxp = minp + 0.1 + 0.1 * (np.random.rand(2) - 0.5)
    scale = 0.5 * space.domain.extent
    magnitude = 0.1
    return magnitude * odl.phantom.cuboid(space, scale * minp, scale * maxp)

power = float(sys.argv[1])
const_val = 10 ** power
print('Running with const_val={}'.format(const_val))

np.random.seed(0)
name = os.path.splitext(os.path.basename(__file__))[0] + '/' + str(const_val)
sess = tf.InteractiveSession()

# Create ODL data structures
size = 128
space = odl.uniform_discr([-64, -64], [64, 64], [size, size],
                          dtype='float32')

geometry = odl.tomo.parallel_beam_geometry(space, num_angles=30)
operator = odl.tomo.RayTransform(space, geometry)

# Ensure operator has fixed operator norm for scale invariance
opnorm = odl.power_method_opnorm(operator)
operator = (1 / opnorm) * operator

# Create tensorflow layer from odl operator
odl_op_layer = odl.contrib.tensorflow.as_tensorflow_layer(operator,
                                                          'RayTransform')
odl_op_layer_adjoint = odl.contrib.tensorflow.as_tensorflow_layer(operator.adjoint,
                                                                  'RayTransformAdjoint')

# User selected paramters
n_data = 5
n_iter = 10
n_primal = 5
n_dual = 5

def generate_data(validation=False):
    """Generate a set of random data."""
    n_generate = 1 if validation else n_data

    y_arr1 = np.empty((n_generate, operator.range.shape[0], operator.range.shape[1], 1), dtype='float32')
    x_true_arr1 = np.empty((n_generate, space.shape[0], space.shape[1], 1), dtype='float32')
    y_arr2 = np.empty((n_generate, operator.range.shape[0], operator.range.shape[1], 1), dtype='float32')
    x_true_arr2 = np.empty((n_generate, space.shape[0], space.shape[1], 1), dtype='float32')

    for i in range(n_generate):
        if validation:
            phantom1 = odl.phantom.shepp_logan(space, True)
        else:
            phantom1 = random_phantom(space)

        phantom2 = phantom1 + make_difference(space)

        data1 = operator(phantom1)
        noisy_data1 = data1 + odl.phantom.white_noise(operator.range) * np.mean(np.abs(data1)) * 0.05
        data2 = operator(phantom2)
        noisy_data2 = data2 + odl.phantom.white_noise(operator.range) * np.mean(np.abs(data2)) * 0.05

        x_true_arr1[i, ..., 0] = phantom1
        y_arr1[i, ..., 0] = noisy_data1
        x_true_arr2[i, ..., 0] = phantom2
        y_arr2[i, ..., 0] = noisy_data2

    return y_arr1, x_true_arr1, y_arr2, x_true_arr2

with tf.name_scope('placeholders'):
    x_true1 = tf.placeholder(tf.float32, shape=[None, size, size, 1], name="x_true1")
    y_rt1 = tf.placeholder(tf.float32, shape=[None, operator.range.shape[0], operator.range.shape[1], 1], name="y_rt1")

    x_true2 = tf.placeholder(tf.float32, shape=[None, size, size, 1], name="x_true2")
    y_rt2 = tf.placeholder(tf.float32, shape=[None, operator.range.shape[0], operator.range.shape[1], 1], name="y_rt2")

    is_training = tf.placeholder(tf.bool, shape=(), name='is_training')
    const = tf.placeholder(tf.float32, shape=(), name='const')

def apply_conv(x, filters=32):
    return tf.layers.conv2d(x, filters=filters, kernel_size=3, padding='SAME',
                            kernel_initializer=tf.contrib.layers.xavier_initializer())

def learned_primal_dual(data, reuse):
    with tf.variable_scope('learned_primal_dual', reuse=reuse):
        with tf.name_scope('initial_values'):
            primal = tf.concat([tf.zeros_like(x_true1)] * n_primal, axis=-1)
            dual = tf.concat([tf.zeros_like(data)] * n_dual, axis=-1)

        for i in range(n_iter):
            with tf.variable_scope('dual_iterate_{}'.format(i)):
                evalop = odl_op_layer(primal[..., 1:2])
                update = tf.concat([dual, evalop, data], axis=-1)

                update = prelu(apply_conv(update), name='prelu_1')
                update = prelu(apply_conv(update), name='prelu_2')
                update = apply_conv(update, filters=n_dual)
                dual = dual + update

            with tf.variable_scope('primal_iterate_{}'.format(i)):
                evalop = odl_op_layer_adjoint(dual[..., 0:1])
                update = tf.concat([primal, evalop], axis=-1)

                update = prelu(apply_conv(update), name='prelu_1')
                update = prelu(apply_conv(update), name='prelu_2')
                update = apply_conv(update, filters=n_primal)
                primal = primal + update

        return primal[..., 0:1]

with tf.name_scope('tomography'):
    recon1 = learned_primal_dual(y_rt1, reuse=False)
    recon2 = learned_primal_dual(y_rt2, reuse=True)

with tf.name_scope('edge_detect'):
    recons = tf.concat([recon1, recon2], axis=-1)
    difference_update = reference_unet(recons, 1,
                                 ndim=2,
                                 features=64,
                                 keep_prob=1.0,
                                 use_batch_norm=False,
                                 activation='relu',
                                 is_training=is_training,
                                 name='edge_result')

    difference_result = (recon1 - recon2) + difference_update

with tf.name_scope('loss'):
    loss_tomography = (tf.reduce_mean((recon1 - x_true1) ** 2) +
                       tf.reduce_mean((recon2 - x_true2) ** 2))

    loss_difference = tf.reduce_mean((difference_result - (x_true1 - x_true2)) ** 2)

    loss = loss_tomography + const * loss_difference

with tf.name_scope('optimizer'):
    # Learning rate
    global_step = tf.Variable(0, trainable=False)
    maximum_steps = 100001
    starter_learning_rate = 3e-4
    learning_rate = cosine_decay(starter_learning_rate,
                                 global_step,
                                 maximum_steps,
                                 name='learning_rate')

    update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
    with tf.control_dependencies(update_ops):
        opt_func = tf.train.AdamOptimizer(learning_rate=learning_rate,
                                          beta2=0.99)

        tvars = tf.trainable_variables()
        grads, _ = tf.clip_by_global_norm(tf.gradients(loss, tvars), 1)
        optimizer = opt_func.apply_gradients(zip(grads, tvars),
                                             global_step=global_step)

# Summaries
# tensorboard --logdir=...

with tf.name_scope('summaries'):
    tf.summary.scalar('loss', loss)
    tf.summary.scalar('loss_tomography', loss_tomography)
    tf.summary.scalar('loss_difference', loss_difference)
    tf.summary.scalar('psnr1', psnr(recon1, x_true1))
    tf.summary.scalar('psnr2', psnr(recon2, x_true2))

    tf.summary.image('recon1', recon1)
    tf.summary.image('recon2', recon2)
    tf.summary.image('x_true1', x_true1)
    tf.summary.image('x_true2', x_true2)
    tf.summary.image('difference', difference_result)
    tf.summary.image('difference_true', (x_true1 - x_true2))

    merged_summary = tf.summary.merge_all()
    test_summary_writer, train_summary_writer = adler.tensorflow.util.summary_writers(name, cleanup=True)

# Initialize all TF variables
sess.run(tf.global_variables_initializer())

# Add op to save and restore
saver = tf.train.Saver()

# Generate validation data
y_arr_validate1, x_true_arr_validate1, y_arr_validate2, x_true_arr_validate2 = generate_data(validation=True)

if 0:
    saver.restore(sess,
                  adler.tensorflow.util.default_checkpoint_path(name))

# Train the network
for i in range(0, maximum_steps):
    if i%10 == 0:
        y_arr1, x_true_arr1, y_arr2, x_true_arr2 = generate_data()

    _, merged_summary_result_train, global_step_result = sess.run([optimizer, merged_summary, global_step],
                              feed_dict={x_true1: x_true_arr1,
                                         y_rt1: y_arr1,
                                         x_true2: x_true_arr2,
                                         y_rt2: y_arr2,
                                         is_training: True,
                                         const: const_val})

    if i>0 and i%10 == 0:
        loss_result, merged_summary_result, global_step_result = sess.run([loss, merged_summary, global_step],
                              feed_dict={x_true1: x_true_arr_validate1,
                                         y_rt1: y_arr_validate1,
                                         x_true2: x_true_arr_validate2,
                                         y_rt2: y_arr_validate2,
                                         is_training: False,
                                         const: const_val})

        train_summary_writer.add_summary(merged_summary_result_train, global_step_result)
        test_summary_writer.add_summary(merged_summary_result, global_step_result)

        print('iter={}, loss={}'.format(global_step_result, loss_result))

    if i>0 and i%1000 == 0:
        saver.save(sess,
                   adler.tensorflow.util.default_checkpoint_path(name))


# import the necessary packages
import numpy as np
import argparse
import cv2
import math
import re
from morse_converter import convertMorseToText
from time_estimator import *

def light_decoder(raw_light_sequence) -> list:
    # the longer light pulse is called dah
    dah = max(raw_light_sequence)

    decoded_morse = []
    for i in raw_light_sequence:
        if dah - 2 < i < dah + 2:
            decoded_morse.append('-')
        elif 0 < i < dah // 2:
            decoded_morse.append('.')
        else:
            decoded_morse.append(' ')
    return decoded_morse

def main():
    cap = cv2.VideoCapture(0)
    # adjust streaming params, more can be found here:
    # https://stackoverflow.com/questions/11420748/setting-camera-parameters-in-opencv-python

    cap.set(3,1280) # Width of the frames in the video stream
    cap.set(4,1024) # Height of the frames in the video stream
    cap.set(15, -8.0) # reduce exposure to limit noise light
    light_sequence = [0]
    pulse_instance = 0

    while True:
        _, frame = cap.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # apply blurring effect to reduce high frequency noise
        blurred = cv2.GaussianBlur(gray, (11, 11), 0)

        # apply threshold to convert images to binary
        thresh = cv2.threshold(blurred, 240, 255, cv2.THRESH_BINARY)[1]

        # apply erosions and dilations to reduce sparse spots
        thresh = cv2.erode(thresh, None, iterations=2)
        thresh = cv2.dilate(thresh, None, iterations=4)

        # find the curve of object's boundary
        cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        cnts = cnts[0] if len(cnts) == 2 else cnts[1]

        # create filter conditions for the object's shape and size
        min_area = 100
        total_light_area = 0

        for c in cnts:
            perimeter = cv2.arcLength(c, True)
            area = cv2.contourArea(c)
            circularity = 4*math.pi*(area/(perimeter*perimeter))

            if area > min_area and 0.6 < circularity < 1.2:
                cv2.drawContours(frame, [c], -1, (128,255,0), 2)
                total_light_area += area

        # log the light pulses as positive int and dark periods as 0s
        if total_light_area > 0:
            light_sequence[-1] = light_sequence[-1] + 1
        else:
            light_sequence.append(0)

        # translate signal into text
        decoded = light_decoder(light_sequence)
        clean_morse = convertMorseToText(morse_cleaner(decoded))

        # annotate predicted texts on video stream
        cv2.putText(frame, "Message: " + clean_morse, (10, 470),
                        cv2.FONT_HERSHEY_DUPLEX, 0.7, (52, 152, 219), 2)

        cv2.imshow("Frame", frame)

        key = cv2.waitKey(1)
        if key == 27:
            break

if __name__ == '__main__':
    main()