# Practical 1 Tic-Tac-Toe Using Magic Square Method
# Importing the library
import random

# Some Data Structure Required during Execution
## Board Data structure for displaying the game
board=['-','-','-',
        '-','-','-',
        '-','-','-']
## Magic Square Data structure for playing in the game play Data structure
magic_square=[2,7,6,
            9,5,1,
            4,3,8]
## Game Play data structure for placing the moves on Board
gameplay=[0,0,0,
        0,0,0,
        0,0,0]

## Computer Move Index represented as arr[i]=i-1
computer_index=[1,2,3,4,5,6,7,8,9]

## To Store Computer Moves with respect to Magic Square
computer_moves=[]
## To Store Human moves with respect to Magic Square
human_moves=[]

# Utility Function Required by the program
# Function To Display any 1d array of length 9 in 3X3 form
def display_board(arr):
    print(str(arr[0]) + ' | ' + str(arr[1]) + ' | ' + str(arr[2]))
    print("---------")
    print(str(arr[3]) + ' | ' + str(arr[4]) + ' | ' + str(arr[5]))
    print("---------")
    print(str(arr[6]) + ' | ' + str(arr[7]) + ' | ' + str(arr[8]))

# Function to perform computer move
def computer_move_operation(move):
    """
    Exchange the exact values from magic square to
    gameplay and board(choice) at specified index-1
    append the corresponding magic_square value in computer move array
    display
    """
    print("Current Computer Move",move)
    gameplay[move-1]=magic_square[move-1]
    board[move-1]=computer_choice

    computer_moves.append(magic_square[move-1])

    display_board(board)

# Function to perform Human move
def human_move_operation(move):
    """
    Exchange the exact values from magic square to
    gameplay and board(choice) at specified index-1
    append the corresponding magic_square value in Human move array
    display
    """
    gameplay[move-1]=magic_square[move-1]
    board[move-1]=human_choice.upper()

    human_moves.append(magic_square[move-1])
    display_board(board)

# Function To check win Possiblity
def check_win(arr):
    """
    A Function for checking the winning possiblites using Magic Sqaure Concept
    It check for both the players if computer is playing then it checks for it
    like return 1-D Array with true and value which is to be marked with corresponding
    index and check the human wining for blocking the move.
    It also check for human wining it true return a 1-D array of True else return false.
    The function is divided into 3 part checking that are for Row, Column and Diagonal.
    """

    # Row
    for col in range(0,7,3):
        current_row=[gameplay[col],gameplay[col+1],gameplay[col+2]]

        com_elements=list(set(current_row) & set(arr))
        if len(com_elements) >=2:                               # For Wining the row should have atleast 2 elements from Move array
            x=15-sum(com_elements)
            # Special Checking for checking the win of own where difference should be zero and all the elements should be available in Move array
            if x == 0 and (current_row[0] in arr) and (current_row[1] in arr) and (current_row[2] in arr):
                return [True]
            # Return the Difference and check that value is not taken in the board
            if x <= 9 and gameplay[magic_square.index(x)]==0:
                return [True,x]

    # Column
    for row in range(3):
        current_col=[gameplay[row],gameplay[row+3],gameplay[row+6]]

        com_elements=list(set(current_col) & set(arr))
        if len(com_elements) >=2:                               # For Wining the column should have atleast 2 elements from Move array
            y=15-sum(com_elements)
            # Special Checking for checking the win of own where difference should be zero and all the elements should be available in Move array
            if y == 0 and (current_col[0] in arr) and (current_col[1] in arr) and (current_col[2] in arr):
                return [True]
            # Return the Difference and check that value is not taken in the board
            if y <= 9 and gameplay[magic_square.index(y)]==0:
                return [True,y]

    # Diagonal
    for diag in [0,2]:
        if diag == 0:
            current_diag=[gameplay[diag],gameplay[diag+4],gameplay[diag+8]]
        if diag == 2:
            current_diag=[gameplay[diag],gameplay[diag+2],gameplay[diag+4]]

        com_elements=list(set(current_diag) & set(arr))
        if len(com_elements) >= 2:                              # For Wining the diagonal should have atleast 2 elements from Move array
            z=15-sum(com_elements)
            # Special Checking for checking the win of own where difference should be zero and all the elements should be available in Move array
            if z == 0 and (current_diag[0] in arr) and (current_diag[1] in arr) and (current_diag[2] in arr):
                return [True]
            # Return the Difference and check that value is not taken in the board
            if z <= 9 and gameplay[magic_square.index(z)]==0:
                return [True,z]

    return [False]

def play_game(current_turn):
    """
    The Main Function Of the Program which Controls all the logic behind Wining, Blocking, Placing Moves For Computer.
    This Function Also Enlist Different Scenarios for both Computer and Human, like who to process with first turn and afterwords for each of it.

    The First Two condition Places the basic First Moves for both.
    The third conditon which is else part controls further steps in game and set the game in systematic manner.
    """
    if start_turn==1 and current_turn==0:
        current_computer_move=random.choice(computer_index)
        computer_move_operation(current_computer_move)

    elif start_turn==2 and current_turn==0:
        current_human_move=int(input(" Enter place the of Move from 1 to 9 : "))
        if current_human_move >=1 and current_human_move <= 9 and gameplay[current_human_move-1]==0:
            human_move_operation(current_human_move)
        else:
            print(" Enter Valid Input")
            play_game(current_turn)

    else:
        # When First Player is Computer
        if start_turn == 1:
            """
            When First Turn is Played by Computer/System
            First Condition Places the move randomly because its the second move for Computer.
            In Second Condion the Computer is trying to check some more scenerio's at particular turns of system
                - If it is itself wining then find the move with corresponding index and check for wining and exit the porgram.
                - If human is wing then block the move of his/her and check for wining and exit the porgram.
                - If nothing is Happening then place it randomly while checking the gameboard or gameplay and check for wining and exit the porgram.
            In Last else part where the turn is of human, it is asking the move and checking fot the wining, if it true then exit the game.
            """
            if current_turn == 2:
                current_computer_move=random.choice(computer_index)
                if gameplay[current_computer_move-1]==0 and (magic_square[current_computer_move-1] not in human_moves):
                    computer_move_operation(current_computer_move)
                else:
                    play_game(current_turn)

            elif current_turn in [4,6,8]:
                check_human_win=check_win(human_moves)
                check_computer_win=check_win(computer_moves)

                if check_computer_win[0] and gameplay[magic_square.index(check_computer_win[1])] == 0:
                    current_computer_move=magic_square.index(check_computer_win[1])
                    computer_move_operation(current_computer_move+1)
                    #print("Board from Computer win")
                    check_computer_win=check_win(computer_moves)
                    if check_computer_win[0] and len(check_computer_win) == 1:
                        print("Computer Has Won! Winnner")
                        exit()

                elif check_human_win[0] and gameplay[magic_square.index(check_human_win[1])] == 0:
                    current_computer_move=magic_square.index(check_human_win[1])
                    computer_move_operation(current_computer_move+1)
                    #print("Board From human wining")
                    check_computer_win=check_win(computer_moves)
                    if check_computer_win[0] and len(check_computer_win) == 1:
                        print("Computer Has Won! Winnner")
                        exit()

                else:
                    current_computer_move=random.choice(computer_index)
                    if gameplay[current_computer_move-1]==0 and (magic_square[current_computer_move-1] not in human_moves):
                        computer_move_operation(current_computer_move)
                        #print("Board from actual random turn")
                        check_computer_win=check_win(computer_moves)
                        if check_computer_win[0] and len(check_computer_win) == 1:
                            print("Computer Has Won! Winnner")
                            exit()
                    else:
                        play_game(current_turn)

            else:
                current_human_move=int(input("Enter place the of Move from 1 to 9 : "))
                if current_human_move >=1 and current_human_move <= 9 and gameplay[current_human_move-1] == 0:
                    check_human_win=check_win(human_moves)
                    human_move_operation(current_human_move)
                    if check_human_win[0] and (magic_square.index(check_human_win[1])+1) == current_human_move:
                        print("You Have Won the game")
                        exit()
                else:
                    print(" Enter Valid Input. Move already taken.")
                    play_game(current_turn)

        # When First Player is Human
        if start_turn == 2:
            """
            When First Turn is Played by Human/User, It places the Move according to input and checks for wining chances of him.
            First Condition Places the move according to the user because its the second move for him.
            In Second Condion the Computer is trying to check some more scenerio's at particular turns of system
                - First condition places the move randomly because its the second move for Computer.
                - In Second Subcondtions its checking different Scenerio's such as
                    - If it is itself wining then find the move with corresponding index and check for wining and exit the porgram.
                    - If human is wing then block the move of his/her and check for wining and exit the porgram.
                    - If nothing is Happening then place it randomly while checking the gameboard or gameplay and check for wining and exit the program.
            """
            if current_turn in [2,4,6,8]:
                current_human_move=int(input("Enter place the of Move from 1 to 9 : "))
                if current_human_move >=1 and current_human_move <= 9 and gameplay[current_human_move-1]==0:
                    check_human_win=check_win(human_moves)
                    human_move_operation(current_human_move)
                    #print(check_human_win)
                    if check_human_win[0] and (magic_square.index(check_human_win[1])+1) == current_human_move:
                        print("You have won the game")
                        exit()
                else:
                    print(" Enter Valid Input or Move already taken.")
                    play_game(current_turn)
            else:
                if current_turn == 1:
                    current_computer_move=random.choice(computer_index)
                    if gameplay[current_computer_move-1]==0:
                        computer_move_operation(current_computer_move)
                    else:
                        play_game(current_turn)

                elif current_turn in [3,5,7]:
                    check_human_win=check_win(human_moves)
                    check_computer_win=check_win(computer_moves)

                    if check_computer_win[0] and gameplay[magic_square.index(check_computer_win[1])]  == 0:
                        current_computer_move=magic_square.index(check_computer_win[1])
                        computer_move_operation(current_computer_move+1)
                        #print("Board from Computer win")
                        check_computer_win=check_win(computer_moves)
                        if check_computer_win[0] and len(check_computer_win) == 1:
                            print("Computer Has Won! Winnner")
                            exit()

                    elif check_human_win[0] and gameplay[magic_square.index(check_human_win[1])] == 0:
                        current_computer_move=magic_square.index(check_human_win[1])
                        computer_move_operation(current_computer_move+1)
                        #print("Board From human wining")
                        check_computer_win=check_win(computer_moves)
                        if check_computer_win[0] and len(check_computer_win) == 1:
                            print("Computer Has Won! Winnner")
                            exit()

                    else:
                        current_computer_move=random.choice(computer_index)
                        if gameplay[current_computer_move-1]==0 and (magic_square[current_computer_move-1] not in human_moves):
                            computer_move_operation(current_computer_move)
                            #print("Board from actual random turn")
                            check_computer_win=check_win(computer_moves)
                            if check_computer_win[0] and len(check_computer_win) == 1:
                                print("Computer Has Won! Winnner")
                                exit()
                        else:
                            play_game(current_turn)

# Introduction Part Containiing the Board and Magic Square Part
print()
print("Intial Board and corresponding Magic Square")
print()
display_board(board)
print()
print("#####################################################################")
print("Magic Square Concept Sum will be 15 for each row, column and diagonal")
print("#####################################################################")
print()
display_board(magic_square)
print()

# Main Program
human_choice=str(input(" Enter Your preference of symbol from 'X' or 'O': "))       # Variable for storing the Choice of Human
if human_choice=='X' or human_choice=='x':
    computer_choice='O'
else:
    computer_choice='X'
print(" So Computer will play using : ",computer_choice)                            # Variable for Storing the Choice of Computer

# Varibale which starts the game with any player at random
start_turn=random.randint(1,2)

# For Loop for looping the turns between Human and Computer
# also the loop reaches for a DRAW if no one wins
for i in range(10):
    if i==9:                                                                        # Condition if loop reaches to end then should DRAW the game
        print("No Winner This is Draw")
        break
    else:
        print("TURN : ",i+1)                                                        # Variable for Showing the Turn iteration between play
        if start_turn==1 and i==0:
            print("First Move is played by Computer")
            play_game(i)
        elif start_turn==2 and i==0:
            print("Play your First Move")
            play_game(i)
        else:
            play_game(i)

Artificial_Intelligence and Data_Science/Practical 1/Practical_1_TTT_Magic_Square.py


import re
from dataclasses import asdict, dataclass
from pathlib import Path

from nrlf.core.constants import DbPrefix
from nrlf.core.json_schema import DEFAULT_SYSTEM_VALUE
from nrlf.core.model import Contract, key

from .constants import GLOBAL, HTTP_SUBS, PATH_PATTERNS
from .errors import BadContractGroup, BadContractPath

def _substitute_http_from_system(system: str):
    for path_system, url_system in HTTP_SUBS.items():
        if path_system in system:
            return system.replace(path_system, url_system)
    return system

def _strip_http_from_system(system: str):
    for path_system, url_system in HTTP_SUBS.items():
        if url_system in system:
            return system.replace(url_system, path_system)
    return system

@dataclass
class ContractGroup:
    name: str
    system: str = DEFAULT_SYSTEM_VALUE
    value: str = DEFAULT_SYSTEM_VALUE

    def __post_init__(self):
        if (
            self.system == DEFAULT_SYSTEM_VALUE or self.value == DEFAULT_SYSTEM_VALUE
        ) and (self.system != self.value):
            raise BadContractGroup(
                f"system and value must both be equal to either be '{DEFAULT_SYSTEM_VALUE}' or "
                f"otherwise neither must be equal to '{DEFAULT_SYSTEM_VALUE}'"
            )

    @property
    def pk(self):
        return key(DbPrefix.Contract, self.system, self.value)

    @property
    def active_sk(self):
        return key(DbPrefix.Version, 0, self.name)

    def __hash__(self):
        return (self.system, self.value, self.name).__hash__()

    def dict(self):
        return asdict(self)

    @classmethod
    def from_contract(cls, contract: Contract) -> "ContractGroup":
        """
        Constructor method for building a ContractGroup a Contract object.
        """
        return cls(
            system=contract.system.__root__,
            value=contract.value.__root__,
            name=contract.name.__root__,
        )

    def to_active_contract(self, version: str, json_schema: dict) -> Contract:
        return Contract(
            pk=self.pk,
            sk=self.active_sk,
            version=version,
            json_schema=json_schema,
            **self.dict(),
        )

    @classmethod
    def from_path(cls, path: str) -> "ContractGroup":
        """
        Constructor method for building a ContractGroup from the filepath
        of a JSON Schema, which must conform to one of PATH_PATTERNS.
        """
        for regex in PATH_PATTERNS:
            match: re.Match = regex.match(str(path))
            if match:
                kwargs = match.groupdict()
                system = kwargs.get("system")
                if system:
                    kwargs["system"] = _substitute_http_from_system(system=system)
                return ContractGroup(**kwargs)

        raise BadContractPath(
            f"File path '{path}' not one of the expected formats: "
            + " or ".join(regex.pattern for regex in PATH_PATTERNS)
        )

    def to_path(self, base_dir: str) -> Path:
        """The compliment of the class method 'from_path'"""
        if self.system == DEFAULT_SYSTEM_VALUE and self.value == DEFAULT_SYSTEM_VALUE:
            base_path = (GLOBAL,)
        else:
            system = _strip_http_from_system(self.system)
            base_path = (system, self.value)
        return Path(base_dir).joinpath(*base_path, f"{self.name}.json")


from collections import deque

c = 11
b = 2

#코니의 위치 변화
#코니는 처음 위치에서 1초 후 1만큼, 매초마다 이전 이동거리 + 1만큼 움직입니다.
# 즉 증가하는 속도가 1초마다 1씩 증가한다는 소리.
# 속도 1, 2, 3, 4, 5, 6, 7, 8
#위치: 12, 14, 17, 21...

#브라운의 위치 변화는
# B-1, B+1, 2*B
# B = 2
# 1,   3,   4

# 모든 경우의 수를 다 나열해야겠구나.
# BFS 를 써야함.
# 잡았다! 라는 의미는 똑같은 시간에 똑같은 위치에 존재.
# 시간은 + 1
# 위치 코니도 브라운도 값이 자유자재로 바뀜
# 규칙적 -> 배열 , 자유자재 -> 딕셔너리.
# 각 시간마다 브라운이 갈 수 있는 위치를 저장하고싶음.

def catch_me(cony_loc, brown_loc):
    time = 0
    queue = deque()
    queue.append((brown_loc, 0))
    visited = [{} for _ in range(200001)]

    while cony_loc <= 200000:
        cony_loc += time # 시간만큼 +1, +2, +3 ...

        if time in visited[cony_loc]:
            return time

        for i in range(0, len(queue)):
            current_position, current_time = queue.popleft()

            new_time = current_time + 1
            new_position = current_position - 1
            if new_position >= 0 and new_time not in visited[new_position]:
                visited[new_position][new_time] = True
                queue.append((new_position, new_time))

            new_position = current_position + 1
            if new_position < 200001 and new_time not in visited[new_position]:
                visited[new_position][new_time] = True
                queue.append((new_position, new_time))

            new_position = current_position * 2
            if new_position < 200001 and new_time not in visited[new_position]:
                visited[new_position][new_time] = True
                queue.append((new_position, new_time))

        time += 1

    return -1

print(catch_me(c, b))  # 5가 나와야 합니다!


import json

from app.config import db, app

class User(db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    chatId = db.Column(db.BigInteger, nullable=False)
    sub_status = db.Column(db.Boolean, default=False)
    username = db.Column(db.String(64), default="N/A")
    quiz_current = db.Column(db.Integer, default=0)
    gpt_context = db.Column(db.JSON)

    def __repr__(self):
        return '<Account %r>' % self.chatId

    def __init__(self, chatId: int, username: str):
        with app.app_context():
            if User.query.filter_by(chatId = chatId).first():
                print("false")
            else:
                 self.chatId = chatId
                 self.username = username
                 db.session.add(self)
                 db.session.commit()

def theEconomistSub(chatId: int, key:int):
    with app.app_context():
        user = User.query.filter_by(chatId=chatId).first()
        if key == 1:
            user.sub_status = True
            db.session.commit()
        else:
            user.sub_status = False
            db.session.commit()

def quizCompleteCounter(chatId):
    with app.app_context():
        user = User.query.filter_by(chatId=chatId).first()
        user.quiz_current+=1
        db.session.commit()

def createUser(chatId, username):
    with app.app_context():
        if User.query.filter_by(chatId=chatId).first():
            pass
        else:
            User(chatId=chatId, username=username)

def getUsername(chatId: int):
    with app.app_context():
        user = User.query.filter_by(chatId=chatId).first()
    return user.username

def getUser(chatId: int):
    with app.app_context():
        user = User.query.filter_by(chatId=chatId).first()
    return user

def getSubStatus(chatId):
    with app.app_context():
        user = User.query.filter_by(chatId=chatId).first()
    return user.sub_status

def zeroingQuiz(chatId):
    with app.app_context():
        user = User.query.filter_by(chatId=chatId).first()
        user.quiz_current = 0
        db.session.commit()

def addContext(chatId, data):
    with app.app_context():
        user = User.query.filter_by(chatId=chatId).first()
        data = json.dumps(data)
        user.gpt_context = data
        db.session.commit()

def clearContext(chatId):
    with app.app_context():
        user = User.query.filter_by(chatId=chatId).first()
        user.gpt_context = None
        db.session.commit()

def getContext(chatId):
    with app.app_context():
        user = User.query.filter_by(chatId=chatId).first()
        if user.gpt_context != None:
            text = json.loads(user.gpt_context)
        else:
            text = []
        return text

# data = []
# data.append({"role": "user", "content": "{}".format("test")})
# data.append({"role": "assistant", "content": "{}".format("test")})
#
# # addContext(479516545, data)
#
# print(getContext(479516545))
# clearContext(479516545)
# with app.app_context():
#     user = User.query.filter_by(chatId=479516545).first()
#     user.economist_issue = '2023#12'
#     db.session.commit()

# def fetchAllUsers():
#     with app.app_context():
#         return User.query.filter(User.test == "asd").filter(User.chatId == 12).all()

#updateUser(chatId=10, test="asd")
# c = User(chatId=3, test="asd")
# with app.app_context():
#     db.session.commit()

# with app.app_context():
#     User.query.filter(User.chatId ==3).delete()
#     db.session.commit()

# with app.app_context():
# #     b = User.query.filter_by(chatId=13).first()
# #     b.updateUser(test="sad")
# #     db.session.commit()
#
# print(fetchAllUsers())


import pygame
import sys
import os
import time
import random

red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
white = (255, 255, 255)
black = (0, 0, 0)
pink = (150, 0, 150)
rich_black = (1, 22, 39)
red_crayola = (239, 45, 86)
princeton_orange = (237, 125, 58)
azure = (230, 250, 252)
mantis = (140, 216, 103)
emerald = (47, 191, 113)

class Button:
    def __init__(self, screen, font, color, x, y, width, height, text=""):
        self.screen = screen
        self.font = font
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self, outline=None):
        # Call this method to draw the button on the screen
        if outline:
            pygame.draw.rect(
                self.screen,
                outline,
                (self.x - 2, self.y - 2, self.width + 4, self.height + 4),
                0,
            )

        pygame.draw.rect(
            self.screen, self.color, (self.x, self.y, self.width, self.height), 0
        )

        if self.text != "":

            text = self.font.render(self.text, 1, (0, 0, 0))
            self.screen.blit(
                text,
                (
                    self.x + (self.width / 2 - text.get_width() / 2),
                    self.y + (self.height / 2 - text.get_height() / 2),
                ),
            )

    def isOver(self, pos):
        # Pos is the mouse position or a tuple of (x,y) coordinates
        if pos[0] > self.x and pos[0] < self.x + self.width:
            if pos[1] > self.y and pos[1] < self.y + self.height:
                return True

        return False

class SimonSays:
    def __init__(self, difficulty, screen, clock, font, w, h, fps):
        self.difficulty = difficulty
        self.screen = screen
        self.clock = clock
        self.font = font
        self.w, self.h = w, h
        self.fps = fps

        background_image = pygame.image.load(os.path.join("images", "GAMEBACK.jpeg"))
        self.backgroundResize = pygame.transform.scale(background_image, (1280, 720))

        game_image = pygame.image.load(os.path.join("images", "GAMEBACK.jpeg"))
        self.gameImageResize = pygame.transform.scale(game_image, (1280, 720))

        self.font = pygame.font.SysFont("comicsans", 25)

        if self.difficulty == "easy":
            grid_size = 3
            self.num_squares_to_click = 3
            self.time_to_see_square = 1000  # in ms

        if self.difficulty == "medium":
            grid_size = 4
            self.num_squares_to_click = 4
            self.time_to_see_square = 1000  # in ms

        if self.difficulty == "hard":
            grid_size = 5
            self.num_squares_to_click = 5
            self.time_to_see_square = 1000  # in ms

        size = 100
        startx, starty = 40, 40
        gap = 10

        xywh = []
        for i in range(grid_size):
            for j in range(grid_size):
                x = startx + i * size + i * gap
                y = starty + j * size + j * gap
                xywh.append([x, y, size, size])

        self.rects = []
        for x, y, w, h in xywh:
            self.rects.append(pygame.Rect(x, y, w, h))

    def draw_startwindow(self):
        self.screen.fill(white)

        self.screen.blit(self.backgroundResize, (1, 1))
        # x,y,width,height
        pygame.draw.rect(self.screen, (0, 0, 0), (58, 78, 650, 62))
        pygame.draw.rect(self.screen, (255, 255, 255), (60, 80, 640, 56))

        # The text
        instructionsText1 = self.font.render(
            "Welcome to Simon Says! You have to click the buttons in the ",
            True,
            (0, 0, 0),
        )
        instructionsText2 = self.font.render(
            "order they appear on the screen! Are you ready?", True, (0, 0, 0)
        )

        self.screen.blit(instructionsText1, (80, 90))

        self.screen.blit(instructionsText2, (80, 115))

    def minigame(self):
        # background
        self.screen.fill(white)
        self.screen.blit(self.gameImageResize, (0, 0))

        # draw rectangles
        for rect in self.rects:
            pygame.draw.rect(self.screen, red_crayola, rect)

        # show tiles
        pygame.display.update()
        pygame.time.wait(3000)

        # grey out 3 tiles
        grey_rects = random.sample(self.rects, self.num_squares_to_click)
        for rect in grey_rects:
            # draw grey rect
            pygame.draw.rect(self.screen, emerald, rect)
            pygame.display.update()
            pygame.time.wait(self.time_to_see_square)

            # undraw grey rect
            pygame.draw.rect(self.screen, red_crayola, rect)
            pygame.display.update()

        cur_square = 0
        while True:
            # exit the game if the user wants
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                # if user clicks on button to start game
                pos = pygame.mouse.get_pos()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    for rect in self.rects:
                        if rect.collidepoint(pos):
                            if rect == grey_rects[cur_square]:
                                cur_square += 1
                                pygame.draw.rect(self.screen, blue, rect)
                                pygame.display.update()
                                pygame.time.wait(200)
                                pygame.draw.rect(self.screen, red_crayola, rect)
                                pygame.display.update()
                                if cur_square >= len(grey_rects):
                                    return True
                            else:
                                pygame.draw.rect(self.screen, rich_black, rect)
                                pygame.display.update()
                                pygame.time.wait(500)
                                return False
            self.clock.tick(self.fps)

    def play_minigame(self):
        """Return True if minigame is won, else False"""
        startwindow = True

        # draw start window
        self.draw_startwindow()
        playbutton = Button(
            self.screen,
            self.font,
            (
                0,
                200,
                220,
            ),
            150,
            225,
            250,
            100,
            "Play game :D !",
        )
        playbutton.draw((0, 0, 0))
        pygame.display.update()

        while True:
            # exit the game if the user wants
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                # if user clicks on button to start game
                pos = pygame.mouse.get_pos()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if playbutton.isOver(pos):
                        return self.minigame()

            self.clock.tick(self.fps)

if __name__ == "__main__":
    # constants
    width = 1280
    height = 720
    fps = 60

    # initialize
    pygame.init()
    pygame.font.init()
    font = pygame.font.SysFont("timesnewroman", 20)
    screen = pygame.display.set_mode([width, height])
    pygame.display.set_caption("Simon Says")
    clock = pygame.time.Clock()

    # start game
    minigame = SimonSays("hard", screen, clock, font, width, height, fps)
    result = minigame.play_minigame()
    print(f"\n\nGame Result: {result}")


import os
import matplotlib.pyplot as plt

# Get the path of the directory where the program is located
dir_path = os.path.dirname(os.path.realpath(__file__))

# Prompt the user to enter the filename
filename = input("Enter the name of the file: ")
file_path = os.path.join(dir_path, filename)

# Check if the file exists
if not os.path.exists(file_path):
    print("Error: file not found.")
    exit()

# Read the contents of the file
with open(file_path, 'r') as file:
    lines = file.readlines()
    num_lines = len(lines)
    if num_lines == 0:
        print("Error: file is empty.")
        exit()

# Prompt the user to enter the starting and ending lines
start_line = int(input(f"Enter the starting line number (1 to {num_lines}): "))
end_line = int(input(f"Enter the ending line number ({start_line} to {num_lines}): "))

# Check if the line numbers are valid
if start_line < 1 or end_line > num_lines or start_line > end_line:
    print("Error: invalid line numbers.")
    exit()

# Extract the data from the selected lines
data = []
for i in range(start_line - 1, end_line):
    data.append(float(lines[i]))

# Plot the chart
plt.plot(data)
plt.xlabel('Sample number')
plt.ylabel('Value')
plt.title('Selected Data')
plt.show()


class Solution:
    def removeStones(self, stones: List[List[int]]) -> int:
        count = defaultdict(int)
        parent = defaultdict(tuple)
        for r  , c in stones:
            parent[(r , c)] = (r , c)
            count[(r , c)] = 1

        def find(child):
            while child != parent[child]:
                parent[child] = parent[parent[child]]
                child = parent[child]
            return child

        def union(x , y):
            rep_x = find(x)
            rep_y = find(y)
            if rep_x != rep_y:
                if count[rep_x] > count[rep_y]:
                    parent[rep_x] = rep_y
                    count[rep_y] += count[rep_x]
                else:
                    parent[rep_y] = rep_x
                    count[rep_x] += count[rep_y]

        for idx1 , (r1 , c1) in enumerate(stones):
            for idx2 , (r2 , c2) in enumerate(stones):
                if idx1 != idx2:
                    if r1 == r2 or c1 == c2:
                        union((r1 , c1) , (r2 , c2))

        ans = set()
        for row , col in stones:
            temp = find((row , col))
            ans.add(temp)

        return len(stones) - len(ans)


#Shengquan Ni 46564157 and Changchuan Shen 83371717
import socket
from general import *

def build_connection():
    '''
    build a connection of a specfic host with a specfic port
    then initialize ICS32 connectfour with the server
    '''
    s=socket.socket()
    host=input('host:')
    port=check_type((int,lambda x:x>=0 and x<=65535),hint='port:',errormessage='PORT must be integer and between 0 and 65535',sep=None)
    try:
        s.connect((host,port))
        playername=check_type((lambda x:x!='' and len(x.split())==1 and len(x.strip())==len(x)),hint='playername:',errormessage='Please re-enter your playername',sep=None)
        send_and_recv(s,'I32CFSP_HELLO '+playername)
        send_and_recv(s,'AI_GAME')
        return s
    except Exception as e:
        print(e)
        print('CONNECTION ERROR')
        s.close()
        return None

def send(s,message):
    '''send message to server'''
    s.send((message+'\r\n').encode())

def recv(s,recvcount=1):
    '''receive responses from server for 'recvcount' times'''
    result=''
    for i in range(recvcount):
        temp=s.recv(4096).decode()
        result+=temp
    return result

def send_and_recv(s,message,recvcount=1):
    '''send and recieve responses'''
    send(s,message)
    return recv(s,recvcount)

def translate(message):
    '''translate message to the format of 'DROP X' or 'POP X'
    '''
    message=message.split('\n')
    if message[0].find('DROP') or message[0].find('POP'):
        a,b=message[0].split()
        return a,int(b)
    else:
        return None,None


import os

from flask import Flask, render_template, request, jsonify, json
from werkzeug.utils import secure_filename
from Classifier import train, prediction

app = Flask(__name__)

# This is the train model

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

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

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

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

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

@app.route('/train', methods=['POST'])
def train_runner():
    # epoch and bach size
    call = ""
    try:
        train()
        call = "Successfull"
        return render_template('./base.html',call=call)

    except Exception as e:
        call = "Fail"
        print(e)
        return render_template('./base.html', call=e)
    #return redirect("home")

# this is for the model
@app.route('/process', methods=['POST'])
def train_prediction():
    print(request.files['file'])
    try:
        if request.method=="POST" and request.files['file']:
            f = request.files['file']
            filename = secure_filename(f.filename)
            print(filename)
            path = os.path.join(os.path.abspath(""), os.path.join("UPLOAD_FOLDER",filename))
            f.save(path)
            pred = prediction(path)
            cls = sorted(os.listdir('v_data/train'))
            result = []
            i = 1
            for name, percent in zip(cls, pred[0]):
                # print("trying...", i)
                result.append('["' + name + '",' + str(percent * 100) + ']')
                i=i+1
            # print(result)
        print("Result",result)
        return render_template('./home.html', result=result)
    except Exception as e:
        return str(e)

# This is the main method , in my view
if __name__ == '__main__':
    app.run(host='0.0.0.0')


#!/usr/bin/env python
# coding=utf-8

import redis
import MySQLdb

client =redis.Redis(host='127.0.0.1',port=6379,db=0)

# 连接数据库
db = MySQLdb.connect("m56o8yzw.586.dnstoo.com",
                      "xiyoulinux_f","xiyoulinux","xiyoulinux" )

# 设置name值
# 有效值 api_id, api_name, version
# 例如查找 name="yun" 的 api_id 和 version
# 数据库中存储 key:yun_id  value:api_id
#             key:yun_version  value:version
def setCheckName(api_id, api_name, version):
    key_id = str(api_name) + "_id"
    key_version = str(api_name) + "_version"
    client.hset(name="check_name", key=key_id, value=api_id)
    client.hset(name="check_name", key=key_version, value=version)
    return True

# 获取id，version对应的值
def getCheckName(api_name):
    key_id = str(api_name) + "_id"
    key_version = str(api_name) + "_version"
    value_id = client.hget(name="check_name",key=key_id)
    value_version = client.hget(name="check_name", key=key_version)
    return value_id,value_version

#设置check_url
#有效数据 api_id, version, url, type
def setCheckUrl(api_id, version, url, type):
    key_url = str(api_id) + "_" + str(version) + "_url"
    key_type = str(api_id) + "_" + str(version) + "_type"
    client.hset(name="check_url", key=key_url, value=url)
    client.hset(name="check_url", key=key_type, value=type)
    return True

#获取url，type值
def getCheckUrl(api_id, version):
    key_url = str(api_id) + "_" + str(version) + "_url"
    key_type = str(api_id) + "_" + str(version) + "_type"
    value_url = client.hget(name="check_url", key=key_url)
    value_type = client.hget(name="check_url", key=key_type)
    return value_url,value_type

#设置check_match
def setCheckMatch(api_id, version, match):
    key_match = str(api_id) + "_" + str(version) + "_match"
    client.hset(name="check_match", key=key_match, value=match)
    return True

# 获取 match值
def getCheckMatch(api_id, version):
    key_match = str(api_id) + "_" + str(version) + "_match"
    value_match = client.hget(name="check_match", key=key_match)
    return value_match

# 设置check_token的值
def setCheckToken(token, app_id, usr_id, time):
    key_appid =str(token) + "_appid"
    key_usrid = str(token) + "_usrid"
    key_time = str(token) + "_time"
    client.set(name=key_appid, value=app_id, ex=time)
    client.set(name=key_usrid, value=usr_id, ex=time)
    return True

# 获取check_token值
def getCheckToken(token):
    key_appid = str(token) + "_appid"
    key_usrid = str(token) + "_usrid"
    value_appid = client.get(name=key_appid)
    value_usrid = client.hget(name=key_usrid)
    return value_appid,value_usrid

# 获取数据库查询
def getTokenInfo(token):
    cursor = db.cursor()
    # 使用execute方法执行SQL语句

    sql_res = '''
                SELECT
                    oauth_sessions.client_id AS app_id,
                    oauth_sessions.owner_id AS user_id,
                    oauth_access_tokens.expire_time AS expire_time
                FROM
                   oauth_sessions
                INNER JOIN oauth_access_tokens ON oauth_access_tokens.session_id = oauth_sessions.id
                WHERE
                  oauth_access_tokens.id =
                # + str(token)
                '04078pEXPddAa2NzDe0yi5nIA0xl9KApb8YoIGdB' '''

    cursor.execute(sql_res)

    # 使用 fetchone() 方法获取一条数据
    data = cursor.fetchone()
    if data:
        setCheckToken()
        db.close()
        return data[0],data[1],data[2]
    else:
        return False


#!/usr/bin/env python
import math
import rospy
import tf

import geometry_msgs.msg
import turtlesim.srv

if __name__ == '__main__':
    rospy.init_node('tf_turtle')

    # The listener receives tf transformations over the wire
    # and buffers them for up to 10 seconds (by default).
    listener = tf.TransformListener()

    rospy.wait_for_service('spawn')
    spawner = rospy.ServiceProxy('spawn', turtlesim.srv.Spawn)
    spawner(4, 2, 0, 'turtle2')

    turtle_vel = rospy.Publisher('turtle2/cmd_vel',
                                 geometry_msgs.msg.Twist,
                                 queue_size=1)

    rate = rospy.Rate(10.0)
    timeout = rospy.Duration(1.0)
    listener.waitForTransform("/turtle2", "/turtle1", rospy.Time(0), timeout)
    rospy.sleep(5.0)
    while not rospy.is_shutdown():
        # We query the listener for a specific transformation,
        # from current frame 'turtle2' to frame 'turtle1' 5 seconds ago.
        try:
            now = rospy.Time.now()
            past = now - rospy.Duration(5.0)
            # The advanced API for lookupTransform() computes the transform
            # from frame 'turtle2' at time 'now' to frame 'turtle1' at time
            # 'past' using the help of a fixed frame 'world' that does not
            # change over time.
            # What happens is the following:
            # - In the past tf computes the transform from 'turtle1' to 'world'.
            # - In the world frame tf time travels from the past to now.
            # - At time now tf computes the transform from 'world' to 'turtle2'.
            listener.waitForTransformFull('/turtle2', now,
                                          '/turtle1', past,
                                          '/world',
                                          timeout)
            (trans, rot) = listener.lookupTransformFull('/turtle2', now,
                                                        '/turtle1', past,
                                                        '/world')
        except (tf.LookupException,
                tf.ConnectivityException,
                tf.ExtrapolationException):
            continue

        angular = 4*math.atan2(trans[1], trans[0])
        linear = 0.5*math.sqrt(trans[0]**2 + trans[1]**2)
        cmd = geometry_msgs.msg.Twist()
        cmd.linear.x = linear
        cmd.angular.z = angular
        turtle_vel.publish(cmd)

        rate.sleep()


import json
import os

# Library
os.system('wget -nc -O lib/browser-polyfill.js https://unpkg.com/webextension-polyfill@0.8.0/dist/browser-polyfill.js')

# Preprocess
os.system('wget -nc https://raw.githubusercontent.com/CanCLID/ToJyutping/74f8e9c/preprocess.py')
os.system("sed -i 's/src\/ToJyutping\/jyut6ping3.simple.dict.yaml/jyut6ping3.simple.dict.yaml/' preprocess.py")
os.system('python preprocess.py')

l = []

with open('jyut6ping3.simple.dict.yaml') as f:
    for line in f:
        k, v = line.rstrip('\n').split('\t')
        l.append((k, v))

# *.json.txt: See mozilla/addons-linter#1700
with open('background_scripts/dictionary.json.txt', 'w') as f:
    f.write(json.dumps(l, ensure_ascii=False).replace('], [', '],\n['))
    f.write('\n')  # Add line break at the end of file


content = None
with open(__file__.replace('.py', '.txt'), 'r') as handle:
    content = handle.readlines()

#content = """
#2-4,6-8
#2-3,4-5
#5-7,7-9
#2-8,3-7
#6-6,4-6
#2-6,4-8
#""".strip().split("\n")

total_part1 = 0
total_part2 = 0
for line in content:
    first, second = [[int(b) for b in a.split("-")] for a in line.split(",")]

    if first[0] <= second[0] and first[1] >= second[1]:
        total_part1 += 1

    elif second[0] <= first[0] and second[1] >= first[1]:
        total_part1 += 1

    if set(range(first[0], first[1]+1)).intersection(range(second[0], second[1]+1)):
        total_part2 += 1

print("Part1", total_part1)
print("Part2", total_part2)


# -*- coding: utf-8 -*-
import csv
import time
import logging
import requests
import argparse
from lxml import html
from datetime import datetime, timedelta
from os import mkdir
from os.path import isdir

class Crawler():
    def __init__(self, prefix="data"):
        """ Make directory if not exist when initialize """
        if not isdir(prefix):
            mkdir(prefix)
        self.prefix = prefix

    def _clean_row(self, row):
        """ Clean comma and spaces """
        for index, content in enumerate(row):
            row[index] = content.replace(',', '')
        return row

    def _record(self, stock_id, row):
        """ Save row to csv file """
        f = open('{}/{}.csv'.format(self.prefix, stock_id), 'a')
        import os
        s = os.stat('{}/{}.csv'.format(self.prefix, stock_id))
        if s.st_size == 0:
            f.write('date,amount,volume,open,high,low,close,diff,number\n')
        cw = csv.writer(f, lineterminator='\n')
        cw.writerow(row)
        f.close()

    def _get_tse_data(self, date_str):
        payload = {
            'download': '',
            'qdate': date_str,
            # 'selectType': 'ALL'
            'selectType': 'ALLBUT0999'
        }
        url = 'http://www.twse.com.tw/ch/trading/exchange/MI_INDEX/MI_INDEX.php'

        # Get html page and parse as tree
        page = requests.post(url, data=payload)

        if not page.ok:
            logging.error("Can not get TSE data at {}".format(date_str))
            return

        # Parse page
        tree = html.fromstring(page.text)

        for tr in tree.xpath('//table[2]/tbody/tr'):
            tds = tr.xpath('td/text()')
            # self.get_stocklist(tds)

            sign = tr.xpath('td/font/text()')
            sign = '-' if len(sign) == 1 and sign[0] == u'－' else ''

            # print(self.year.__str__() + self.month.__str__())
            date_str = '{0}-{1:02d}-{2:02d}'.format(self.year, self.month, self.day)
            row = self._clean_row([
                date_str,  # 日期
                tds[2][:-4],  # 成交股數
                tds[4],  # 成交金額
                tds[5],  # 開盤價
                tds[6],  # 最高價
                tds[7],  # 最低價
                tds[8],  # 收盤價
                sign + tds[9],  # 漲跌價差
                tds[3],  # 成交筆數
            ])

            self._record(tds[0].strip(), row)

    def _get_otc_data(self, date_str):
        ttime = str(int(time.time()*100))
        url = 'http://www.tpex.org.tw/web/stock/aftertrading/daily_close_quotes/stk_quote_result.php?l=zh-tw&d={}&_={}'.format(date_str, ttime)
        page = requests.get(url)

        if not page.ok:
            logging.error("Can not get OTC data at {}".format(date_str))
            return

        result = page.json()

        if result['reportDate'] != date_str:
            logging.error("Get error date OTC data at {}".format(date_str))
            return

        for table in [result['mmData'], result['aaData']]:
            for tr in table:
                date_str = '{0}-{1:02d}-{2:02d}'.format(self.year, self.month, self.day)
                row = self._clean_row([
                    date_str,
                    tr[8][:-4],  # 成交股數
                    tr[9],  # 成交金額
                    tr[4],  # 開盤價
                    tr[5],  # 最高價
                    tr[6],  # 最低價
                    tr[2],  # 收盤價
                    tr[3],  # 漲跌價差
                    tr[10]  # 成交筆數
                ])
                self._record(tr[0], row)

    def get_data(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

        date_str = '{0}/{1:02d}/{2:02d}'.format(year - 1911, month, day)
        print('Crawling {}'.format(date_str))
        self._get_tse_data(date_str)
        self._get_otc_data(date_str)

def main():
    parser = argparse.ArgumentParser(description='Crawl data at assigned day')
    parser.add_argument('day', type=int, nargs='*', help='assigned day (format: YYYY MM DD), default is today')
    parser.add_argument('-b', '--back', action='store_true', help='crawl back from assigned day until 2004/2/11')
    parser.add_argument('-c', '--check', action='store_true', help='crawl the assigned day')

    args = parser.parse_args()
    print(args)

    crawler = Crawler()
    end = datetime.today()

    try:
        if args.back:
            begin = datetime(args.day[0], args.day[1], args.day[2])
        elif args.check:
            begin = datetime(args.day[0], args.day[1], args.day[2])
            end = begin
        else:
            begin = datetime.today()
    except IndexError:
        parser.error('Date should be assigned with (YYYY MM DD) or none')
        return

    print('BEGIN: ' + begin.__str__())
    print('END  : ' + end.__str__())

    if args.back or args.check:        # otc first day is 2007/04/20 # tse first day is 2004/02/11
        max_error = 5
        error = 0

        while error < max_error and end >= begin:
            try:
                crawler.get_data(begin.year, begin.month, begin.day)
                error = 0
            except OSError:
                date_str = begin.strftime('%Y/%m/%d')
                # logging.error('Crawl raise error {}'.format(date_str))
                logging.error('Crawl raise error {} {} {}'.format(begin.year, begin.month, begin.day))
                error += 1
                continue
            finally:
                begin += timedelta(1)
    else:
        crawler.get_data(end.year, end.month, end.day)

def auto_crawl():
    with open('data/0050.csv', 'r') as f:
        last_line = f.readlines()[-1]
        last_day = last_line.split(',')[0]
        begin = datetime.strptime(last_day, '%Y-%m-%d')
        begin += timedelta(1)
    end = datetime.today()

    crawler = Crawler()

    max_error = 5
    error = 0

    print('BEGIN: ' + begin.__str__())
    print('END  : ' + end.__str__())

    while error < max_error and end >= begin:
        try:
            crawler.get_data(begin.year, begin.month, begin.day)
            error = 0
        except OSError:
            date_str = begin.strftime('%Y/%m/%d')
            # logging.error('Crawl raise error {}'.format(date_str))
            logging.error('Crawl raise error {} {} {}'.format(begin.year, begin.month, begin.day))
            error += 1
            continue
        finally:
            begin += timedelta(1)

if __name__ == '__main__':
    # main()
    auto_crawl()


from flask import Blueprint, render_template, request, redirect, url_for, flash
import csv

from flask_login.utils import login_required

from flight_app.models import db,Flight,Schedule

from flight_app.utils import format_datetime,is_invalid_date_of_first_flight, is_valid_flight_time,timedelta

flight = Blueprint("flight", __name__)

@flight.route("/flight/<int:flight_id>/add-passenger", methods=["GET", "POST"])
def add_passenger(flight_id):
    flight = Flight.query.get_or_404(flight_id)
    return render_template("book.html", flight=flight)

@flight.route("/upload-flight", methods=["GET", "POST"])
def upload_flight():
    pass

#     if request.method == "POST":
#         filename = request.form.get("file_name")
#         dir = "./static/flight_data/"
#         flight_csv_data = dir + filename

#         with open(flight_csv_data) as file:
#             flight_data = csv.reader(file)
#             for (
#                 code,
#                 origin,
#                 destination,
#                 capacity,
#                 departure_time,
#                 arrival_time,
#             ) in flight_data:
#                 flight = add_flight(
#                     code, origin, destination, capacity, departure_time, arrival_time
#                 )
#                 db.session.add(flight)
#         db.session.commit()

#         return render_template("index.html")

import os

@login_required
@flight.route("/register-new-flight", methods=["GET", "POST"])

def register_new_flight():
    if request.method == "POST":
        flight_code = request.form.get("flight_code").upper()
        flight_capacity = request.form.get("flight_capacity")
        flight_model = request.form.get("flight_model")
        category = request.form.get("flight_category")
        date_of_first_flight = format_datetime(request.form.get("first_flight_date"))

        # check to ensure that the flight does not already exist in the database
        flight = Flight.query.filter_by(code=flight_code).first()
        if flight:
            message = "Sorry, A flight with thesame code already exist."
            flash(message, "danger")
            return render_template('register_new_flight.html')

        # Add flight to database
        if is_invalid_date_of_first_flight(date_of_first_flight):
            message = "Sorry, The date of first flight must not be in the future."
            flash(message, "danger")
            return render_template('register_new_flight.html')
        flight = Flight(
        code=flight_code,
        capacity=flight_capacity,
        model=flight_model,
        category=category,
        date_of_first_flight=date_of_first_flight)
        db.session.add(flight)
        db.session.commit()

        message = f"Flight {flight_code} with a capacity of {flight_capacity} was added successfully!"
        flash(message, "success")
        return redirect(url_for('main.index'))
    return render_template("register_new_flight.html", title="Register Flight")

@flight.route("/flight/status/<int:flight_id>/<string:action>", methods=["GET", "POST"])
def change_status(flight_id, action):
    flight = Flight.query.get(flight_id)
    # get pilot

    if action == "enable":
        flight.enable()
        flash(f'Flight {flight.code} has been enabled. You can now schedule it for a route','success')
        return redirect(request.referrer)
    flight.disable()
    flash(f'Flight {flight.code} has been disabled','info')
    return redirect(request.referrer)

@flight.route("/schedule_flight/<int:flight_id>", methods=["GET", "POST"])
def schedule_flight(flight_id):

    """This function schedules an already registered flight by assigning it an origin, destination,
    capacity,departure datetime, arrival datetime. Once the flight is schedule, passengers are able to
    book the flight. It becomes unaviable for schedule once it is scheduled."""

    #check if the flight is available
    flight = Flight.query.get_or_404(flight_id)
    if flight.is_available == False:
        flash('Sorry, This flight is currently unavailable and cannot be scheduled!','danger')
        return redirect(request.referrer)
    return render_template('schedule_flight.html',flight = flight, title = 'Schedule Flight')

@flight.route("/process_flight/<int:flight_id>", methods=["GET", "POST"])
def process_flight_schedule(flight_id):
    """Process the received form"""

    if request.method == "POST":

        flight_origin = (request.form.get("flight_origin")).capitalize()
        flight_destination = (request.form.get("flight_destination")).capitalize()
        flight_departure_time = request.form.get("departure_time")
        flight_arrival_time = request.form.get("arrival_time")
        flight_capacity = int(request.form.get('flight_capacity'))

        # FORMAT FLIGHT DEPARTURE AND ARRIVAL TIME TO DB COMPATIBLE
        departure_time = format_datetime(flight_departure_time)
        arrival_time = format_datetime(flight_arrival_time)

        if not is_valid_flight_time(departure_time, arrival_time):
            flash('Please ensure the flight time is valid. It must be at least two hours from the current time.','danger')
            return redirect(request.referrer)
            # return redirect(request.referrer)
        flight = Flight.query.get_or_404(flight_id)

        schedule = flight.schedule_flight(flight_origin,flight_destination,flight_capacity,departure_time,arrival_time)

        # message = f"""flight_code: {code} from {flight_origin} to {flight_destination}\n
        # departure time: {departure_time},\n arrival time: {arrival_time},\nflight capacity: {flight_capacity} was
        # added successfully!"""
        message = f"Flight {schedule.flight.code} from {schedule.origin} to {schedule.destination} scheduled successfully!"
        flash(message,'success')
        return redirect(url_for('main.flight',flight_id = flight_id))
        # return render_template("schedule_flight.html")

@flight.route("/flight/delay/<int:schedule_id>", methods=["GET", "POST"])
def delay_flight(schedule_id):

    if request.method =="POST":
        #retrieve the delay amount from the form
        delay_amount = int(request.form.get('delay_amount'))
        #query the database with the schedule amount to get the schedule object

        schedule = Schedule.query.get_or_404(schedule_id)
        schedule.delay_flight(delay_amount)
        message = f"""Flight from {schedule.origin} to {schedule.destination}
        has been delay for {delay_amount} mins. The new arrival time is {schedule.arrival_time}"""
        flash(message,'success')
        return redirect(url_for('main.flight',flight_id = schedule.flight.id))
    return render_template('delay_flight.html',schedule_id = schedule_id)

        # get the flight origin,destination and code
        # flight_origin = request.form.get("flight_origin")
        # flight_destination = request.form.get("flight_destination")
        # flight_code = request.form.get("flight_code").upper()
        # delay_amount = int(request.form.get("delay_amount"))
        # # return f"
{(flight_code)}
"
        # # Query the database for the given flight
        # flight = Flight.query.filter_by(
        #     origin=flight_origin,
        #     destination=flight_destination,
        #     code=flight_code,
        # ).first()
        # if not flight:
        #     message = "No such flight exist. Please, ensure you enter the correct flight origin,destination and flight code!"
        #     return render_template("error.html", message=message)
        # else:
        #     # delay light by delay amount
        #     new_arrival_time = flight.delay_flight(delay_amount)
        #     flight.arrival_time = new_arrival_time
        #     db.session.commit()
        #     message = "Flight {} from {} to {} has been delayed by {}minutes. New Arrival Time is {}".format(
        #         flight.code,
        #         flight.origin,
        #         flight.destination,
        #         delay_amount,
        #         flight.arrival_time,
        #     )
        #     return render_template("success.html", message=message)
            # return f"
Original arival time:{flight.arrival_time},\n New Arrival Time: {flight.delay_flight(delay_amount)}\n Flight Duration: {((flight.arrival_time - flight.departure_time).total_seconds())//60}
"

    # else:
    #     return render_template("book-flight.html")

@flight.route("/flight/<int:flight_id>/delete", methods=["GET"])
def delete_flight(flight_id):

    flight = Flight.query.get_or_404(flight_id)
    if flight:
        #check if flight is disabled before deleting
        if flight.is_available == True:
            flash('sorry, you must first disable flight before you can delete','danger')
            return redirect(request.referrer)
        db.session.delete(flight)
        db.session.commit()
        message = f"Flight {flight.code} deleted successfully!"
        flash(message, "success")
        return redirect(request.referrer)
    flash('Error: Flight does not exist','danger')
    return render_template('index.html')

@flight.route("/flight/<int:flight_id>/edit", methods=["GET", "POST"])
def edit_flight(flight_id):
    if request.form == 'POST':

        # GET THE FORM REQUESTS
        flight_code = request.form.get("flight_code").upper()
        flight_capacity = request.form.get("flight_capacity")
        flight_model = request.form.get("flight_model")
        category = request.form.get("flight_category")
        date_of_first_flight = format_datetime(request.form.get("first_flight_date"))

        # QUERY THE DB AND REASSIGN THE VALUES IN THE DATABASE
        flight = Flight.query.get_or_404(flight_id)

        if not flight:
            flash('sorry, flight is invalid')
            return redirect(request.referrer)
        else:

           flight.code = flight_code
           flight.model = flight_model
           flight.category = category

           db.session.commit()
           return redirect('Flight Information successfully updated', 'success')
    flight = Flight.query.get_or_404(flight_id)
    return render_template('register_new_flight.html', flight=flight)

    # print("Request is a post request.")
    #     flight = Flight.query.get_or_404(flight_id)
    #     return f"This will process the edit function for flight {flight.code}"
    # flight = Flight.query.get_or_404(flight_id)
    # return render_template('register_new_flight.html',flight = flight)

@flight.route("/test", methods = ['GET','POST'])
def flight_test():
    input = request.form.getlist('checkbox')
    return f"
{input}
"


def compute_rho_avgsa(per, avg_periods, sctx, rctx, dctx, stddvs_avgsa, bgmpe,
                      corr_type):
    """
    """
    # Import libraries
    from openquake.hazardlib import imt, const, gsim
    from .modified_akkar_correlation_model import ModifiedAkkarCorrelationModel

    sum_numeratore = 0
    for i1 in avg_periods:
        rho = []
        if corr_type == 'baker_jayaram':
            rho = gsim.mgmpe.generic_gmpe_avgsa. \
                    BakerJayaramCorrelationModel([per, i1])(0, 1)
        if corr_type == 'akkar':
            rho = ModifiedAkkarCorrelationModel([per, i1])(0, 1)
        s = [const.StdDev.TOTAL]
        mean1, std1 = bgmpe().get_mean_and_stddevs(sctx, rctx, dctx,
                                                   imt.SA(i1), s)
        sum_numeratore = sum_numeratore + rho * std1[0]

    denominatore = len(avg_periods) * stddvs_avgsa
    rho_avgsa = sum_numeratore / denominatore
    return rho_avgsa


from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("https://python.org")
time.sleep(2)
driver.maximize_window()

time.sleep(2)

# 拖动窗口
#执行javaScript代码
JS = "window.scrollTo(10000,document.body.scrollHeight)"
driver.execute_script(JS)

time.sleep(2)
driver.quit()


# Author: Arsene Bwasisi
# Description: This programs displays several shapes that are seleceted
#              by the user. They include an hourlass, plumbbob, house.
#              Users will provide a character to use for the shape as well
#              the shapes height.

def line(height):
    '''
    This function will determine the height of the row_area line
    with the input provided by the user.
    '''
    line = '|'+'-'*9+'|\n' # line = |---------|
    print(line*height, end='')

def upward_arrow(character):
    '''
    This function will display the upwards arrow of the selected
    shape witt the provided character.
    '''
    # Defines the index, scalar to determine number of
    # characters and space to determine number of space.
    index = 0
    scalar = 1
    space = 5

    # Loopt through to print upward arrow by multiplying
    # space string with a space variable and character
    # argument with scalar variable.
    while index < 6:
        print(' '*space + character*scalar)
        scalar += 2 # index each variable.
        space -= 1
        index += 1

def downward_arrow(character):
    '''
    This function will display the downward arrow of the selected
    shape with the provided character.
    '''
    # Reverses the upward_arrow function.
    index = 6
    scalar = 11
    space = 0

    while index > 0:
        print(' '*space + character*scalar)
        scalar -= 2
        space += 1
        index -= 1

def main():

    # Stores user input in to variables
    shape = input("Enter shape to display:\n")
    if shape != 'hourglass' and shape != 'plumbbob' and shape != 'house':
        print('Not valid option.') # Prints message if input is invalid.
    else:
        character = input("Enter arrow character:\n")
        height = int(input("Enter row-area height:\n")) # wrap input into int.
        print()

    # Will check input of shape and display an image by calling
    # the line, upward, and downward function.
    if shape == 'hourglass':
        line(height)
        downward_arrow(character)
        upward_arrow(character)
        line(height)
    elif shape == 'plumbbob':
        upward_arrow(character)
        line(height)
        downward_arrow(character)
    elif shape == 'house':
        upward_arrow(character)
        line(height)

main()


import collections as col

# with open("Day 7/Testdata.txt",'r') as file:
# with open("Day 7/Testdata2.txt",'r') as file:
with open("Day 7/Indata.txt",'r') as file:
    rawData = file.read()

rawDataLines = rawData.splitlines()

# Cleanup the raw data into namedTuples
    # Example input:
    # bright white bags contain 1 shiny gold bag.
    # muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.
    # faded blue bags contain no other bags.

ChildTuple = col.namedtuple('ChildTuple', ['count', 'name'])

# Set up a dictionary with all mappings as namedTuples
bagDict = dict()
for rawDataLine in rawDataLines:
    name = ' '.join(rawDataLine.split(' ')[:2])
    if rawDataLine.endswith('no other bags.'):
        bagDict[name] = None
    else:
        childs = []
        for rawChild in ' '.join(rawDataLine.split(' ')[4:]).split(','):
            rawChild = rawChild.strip().split(' ')
            childCount = int(rawChild[0])
            childName = rawChild[1] + ' ' + rawChild[2]
            child = ChildTuple(childCount, childName)
            childs.append(child)
        bagDict[name] = childs

# Part 1 solution
# Recursively traverse each "bag tree" looking for Shiny Gold bag
def Traverse(bagName):
    """
    Recursive method that looks for shiny gold bags in a "bag tree"
    """
    # Base case: Check if the current bag contains any shiny gold bags
    if bagDict[bagName] == None:
        return False
    for bag in bagDict[bagName]:
        if bag.name == 'shiny gold':
            return True

    # Recursive case: Check if any of the contained bags in turn contain any shiny gold bags
    for bag in bagDict[bagName]:
        if Traverse(bag.name) == True:
            return True

    # Default case: This bag and none of its contained bags contain any shiny gold bags
    return False

count = 0
for bag in bagDict.keys():
    result = Traverse(bag)
    if result == True:
        count += 1

print('Number of bags eventually containing shiny gold bags: ' + str(count))

# Part 2 solution
# Recursively traverse the "shiny gold" bag tree and count all bags
def TraverseCount(bagName):
    """
    Recursive method that counts all bags in the "bag tree"
    """
    # Base case: Check if the current bag contains no other bags
    if bagDict[bagName] == None:
        return 1

    # Recursive case: Count all bags contained in this bag
    count = 0
    for bag in bagDict[bagName]:
        count += bag.count * TraverseCount(bag.name)

    # Return count of all contained bags including this bag
    return count + 1

# Count all bags contained in your shiny gold bag (yours included) and then subtract your bag
result = TraverseCount('shiny gold') - 1
print('Number of bags in your shiny gold bag: ' + str(result))


import numpy as np
from scipy.stats import norm
import random

standings = {
    "FANtasy": [9, 1, 1174],
    "Emily's Team": [7, 3, 1105],
    "Run CMC": [6, 4, 1186],
    "League is Rigged": [6, 4, 1181],
    "Adam's Team": [6, 4, 1113],
    "James's Team": [5, 5, 1157],
    "Eat Lobster!": [5, 5, 1114],
    "Daniel's Team": [3, 7, 940],
    "Kyle's Team": [2, 8, 1005],
    "Christian's Team": [1, 9, 1026],
}

historicalPoints = {
    "FANtasy": [108, 129, 136, 82, 132, 107, 146, 101, 134, 98],
    "Emily's Team": [166, 127, 107, 107, 104, 109, 134, 86, 80, 86],
    "Run CMC": [140, 106, 125, 134, 115, 118, 105, 105, 131, 107],
    "League is Rigged": [94, 148, 165, 137, 102, 98, 128, 117, 118, 75],
    "Adam's Team": [127, 124, 102, 104, 101, 120, 112, 117, 104, 101],
    "James's Team": [99, 150, 135, 101, 122, 105, 127, 83, 136, 100],
    "Eat Lobster!": [110, 120, 130, 142, 101, 90, 107, 79, 97, 139],
    "Daniel's Team": [75, 148, 110, 77, 74, 75, 130, 79, 75, 97],
    "Kyle's Team": [81, 121, 105, 121, 81, 114, 83, 125, 90, 84],
    "Christian's Team": [95, 92, 101, 112, 119, 87, 104, 119, 130, 67]
}

meanStd = {
    "FANtasy": [0, 0],
    "Emily's Team": [0, 0],
    "Run CMC": [0, 0],
    "League is Rigged": [0, 0],
    "Adam's Team": [0, 0],
    "James's Team": [0, 0],
    "Eat Lobster!": [0, 0],
    "Daniel's Team": [0, 0],
    "Kyle's Team": [0, 0],
    "Christian's Team": [0, 0],
}

for team, data in historicalPoints.items():
    s = np.std(data)
    m = np.mean(data)
    meanStd[team] = [m, s]

# Set game results
# -1 = simulate game based on past results
# -2 = simulate game based on provided odds for team1 (-2, .14 means 14% chance team one wins)
# 0 = force team one wins
# 1 = force team two wins
schedule = {
    11: [
        ["League is Rigged", "Run CMC", -2, .14],
        ["Eat Lobster!", "Kyle's Team", -2, .16],
        ["Daniel's Team", "Adam's Team", 1, 0],
        ["James's Team", "Christian's Team", -2, .54],
        ["Emily's Team", "FANtasy", -2, .78],
    ],
    12: [
        ["League is Rigged", "Adam's Team", -1, 0],
        ["Eat Lobster!", "Run CMC", -1, 0],
        ["Daniel's Team", "Christian's Team", -1, 0],
        ["James's Team", "FANtasy", -1, 0],
        ["Emily's Team", "Kyle's Team", -1, 0],
    ],
    13: [
        ["League is Rigged", "Christian's Team", -1, 0],
        ["Eat Lobster!", "Adam's Team", -1, 0],
        ["Run CMC", "Kyle's Team", -1, 0],
        ["Daniel's Team", "FANtasy", -1, 0],
        ["Emily's Team", "James's Team", -1, 0],
    ],
    14: [
        ["League is Rigged", "FANtasy", -1, 0],
        ["Eat Lobster!", "Christian's Team", -1, 0],
        ["Daniel's Team", "Emily's Team", -1, 0],
        ["James's Team", "Kyle's Team", -1, 0],
        ["Adam's Team", "Run CMC", -1, 0],
    ],
}

numSimulations = 20000
allSimilatedResults = []

for i in range(numSimulations):
    simulatedResults = {
        "FANtasy": [0, 0, 0],
        "Emily's Team": [0, 0, 0],
        "Run CMC": [0, 0, 0],
        "League is Rigged": [0, 0, 0],
        "Adam's Team": [0, 0, 0],
        "James's Team": [0, 0, 0],
        "Eat Lobster!": [0, 0, 0],
        "Daniel's Team": [0, 0, 0],
        "Kyle's Team": [0, 0, 0],
        "Christian's Team": [0, 0, 0],
    }

    for _, week in schedule.items():
        for matchup in week:
            team1 = matchup[0]
            team2 = matchup[1]
            forcewinner = matchup[2]

            simTeam1Score = np.random.normal(
                meanStd[team1][0], meanStd[team1][1])
            simTeam2Score = np.random.normal(
                meanStd[team2][0], meanStd[team2][1])

            # simulate game
            team1Won = 0
            team2Won = 0
            if forcewinner == -1:
                team1Won = 1 if simTeam1Score > simTeam2Score else 0
                team2Won = not team1Won
            elif forcewinner == -2:
                rndnum = random.uniform(0, 1)
                team1odds = matchup[3]
                team1Won = 1 if rndnum < team1odds else 0
                team2Won = not team1Won
            else:
                # use the forced game result
                team1Won = 1 if forcewinner == 0 else 0
                team2Won = not team1Won

            # update simulation matchup
            prev = simulatedResults[team1]
            new = [prev[0] + team1Won, prev[1] +
                   team2Won, prev[2] + simTeam1Score]
            simulatedResults[team1] = new

            prev = simulatedResults[team2]
            new = [prev[0] + team2Won, prev[1] +
                   team1Won, prev[2] + simTeam2Score]
            simulatedResults[team2] = new

    allSimilatedResults.append(simulatedResults)

finalStandings = {
    "FANtasy": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    "Emily's Team": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    "Run CMC": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    "League is Rigged": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    "Adam's Team": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    "James's Team": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    "Eat Lobster!": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    "Daniel's Team": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    "Kyle's Team": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    "Christian's Team": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}

for simulatedResult in allSimilatedResults:
    # [team, wins, points]
    unorderdTeams = []

    # add week 0 - 12 standings
    for team, data in standings.items():
        unorderdTeams.append(
            [team, data[0] + simulatedResult[team][0], data[2] + simulatedResult[team][2]])

    # see who wins the simulation by ordering by wins then points
    orderedTeams = sorted(unorderdTeams, key=lambda x: (-x[1], -x[2]))

    # update final standings
    for place in range(10):
        team = orderedTeams[place][0]
        finalStandings[team][place] += 1

print("{: <20}{: <8}{: <8}{: <8}{: <8}{: <8}{: <8}{: <8}{: <8}{: <8}{: <8}{: <12}".format(
    "Team", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "Playoffs"))

for team in finalStandings:
    # total place finishes
    tpf = finalStandings[team]
    print("{: <20}{: <8.2%}{: <8.2%}{: <8.2%}{: <8.2%}{: <8.2%}{: <8.2%}{: <8.2%}{: <8.2%}{: <8.2%}{: <8.2%}{: <12.2%}".format(
        team, tpf[0] / numSimulations, tpf[1] / numSimulations, tpf[2] / numSimulations, tpf[3] / numSimulations, tpf[4] / numSimulations, tpf[5] / numSimulations, tpf[6] / numSimulations, tpf[7] / numSimulations, tpf[8] / numSimulations, tpf[9] / numSimulations, (tpf[0] + tpf[1] + tpf[2] + tpf[3]) / numSimulations))


#!/usr/bin/env python
#coding: utf-8
import os
import json
import sys
PY3K = sys.version_info[0] == 3
if not PY3K:
    import urllib2
    from urllib import urlencode
else:
    import urllib.request as urllib2
    from urllib.parse import urlencode
    raw_input = input
    _map = map
    map = lambda *a, **k: list(_map(*a, **k))
import locale
LOCALE = locale.getdefaultlocale()

HOSTKEY = None # HOSTKEY_ANCHOR

CFARG = {
    'user_auth': ("cloudflare_email", "cloudflare_pass"),
    'zone_set': ("zone_name", "subdomains", "resolve_to"),
    'zone_delete': ("zone_name",),
    'zone_list': (),
    'zone_lookup': ("zone_name",),
    'add_subdomain':("zone_name", "subdomains", "resolve_to"),
    'delete_subdomain': ("zone_name", "subdomains"),
    'ssl_verfication': ("zone",),
    'host_key_regen': (),
}
CFHOST_FILE = ".cfhost"

I18N = {
    "zone_list": "显示所有接入的域名",
    "zone_set": "接入域名",
    "zone_lookup": "显示DNS记录",
    "zone_delete": "删除接入的域名",
    "host_key_regen": "重新生成host key",
    "user_auth": "登录",
    "add_subdomain": "添加/修改DNS记录",
    "delete_subdomain": "删除DNS记录",
    "logout": "退出当前帐号",
    "ssl_verfication": "开通SSL",
    "zone_name": "根域名",
    "resolve_to": "源站地址",
    "subdomains": "子域名",
    "cloudflare_email": "邮箱",
    "cloudflare_pass": "密码",
    "zone": "根域名",
    "subdomain": "子域名",
    "Zone": "根域名",
    "User": "用户",
    "Subdomain": "子域名",
    "Resolve to": "源站地址",
    "Content": "内容",
    "Login as %s": "%s 已登录",
    "vetting": "审批中",
    "validating": "等待验证",
    "ready": "已启用",
    "none": "未知",
    "Select your action:": "选择所需的操作，输入数字：",
    "Missing required arg \"%s\". (act:%s)": "缺少参数 \"%s\". (act:%s)",
    "Login failed, msg: %s": "登录失败: %s",
    "Success! Please set CNAME record of %s to %s": "设置成功! 请将%s的CNAME记录设置为%s",
    "Domain %s has been removed from partner": "域名%s已取消接入",
    "%s (act: %s)": "报错: %s (act: %s) ",
    "Please enter your Cloudflare partner hostkey (https://partners.cloudflare.com/api-management)> ":
        "请输入 Cloudflare hostkey (https://partners.cloudflare.com/api-management)> ",
    "SSL status: %s": "SSL状态: %s",
    "Please login first. (uri: %s)": "请先登录. (uri: %s)",
    "Please login first. (act: %s)": "请先登录. (act: %s)",
    "No zone found matching %s. Please use zone_set first.": "账户中不存在域名%s, 请先添加域名",
    "SSL for domain %s has already been activated.": "域名%s已开通SSL, 无需操作",
    "??? %s": "喵喵喵？ %s",
    "Please set CNAME record of %s to %s and run this option again after record become effective":
        "请将%s的CNAME记录设置为%s, 然后在解析生效后再运行一次\"开通SSL\"",
    "Please create a file with the following content and run this option again after record become effective:":
        "请新建文件使下列URL能访问到指定的内容，然后再运行一次\"开通SSL\":",
    "Can't delete root record": "不能删除根域名",
    "Record %s is deleted": "DNS记录%s已删除",
    "Record %s is not found in zone %s": "记录%s不存在于域名%s中",
    "If you want to activate SSL, please set CNAME record of %s to %s and " \
        "run this \"ssl_verfication\" after record become effective":
            "如果需要启用SSL, 请将%s的CNAME记录设置为%s, 然后在解析生效后运行一次\"开通SSL\"",
    "Zone %s not exists or is not under user %s": "域名%s不存在，或者不属于用户%s",
    "Host key has been changed to %s": "Hostkey已更新为 %s",
}

def i18n(s):
    _ = I18N[s] if LOCALE[1] and LOCALE[1].lower() in ("utf-8", "cp936") and s in I18N else s
    if LOCALE[1].lower() == "cp936" and not PY3K: # windows with simplified Chinese locale
        return _.decode('utf-8').encode('gb18030')
    return _

def log(fmt, arg = (), level = "INFO"):
    if PY3K:
        if not (isinstance(arg, list) or isinstance(arg, tuple)):
            arg = (arg, )
        arg = tuple([a.decode('ascii') if isinstance(a, bytes) else a for a in arg])
    print("%-4s - %s" % (level, i18n(fmt) % arg))

def catch_err(func):
    def _(instance, j, *arg):
        if j['result'] == 'error':
            log("%s (act: %s)", (j['msg'].encode('utf-8'), j['request']['act'].encode('utf-8')), "ERR")
            return
        return func(instance, j, *arg)
    return _

class CF(object):
    def __init__(self):
        self.user_email = None
        self.user_key = None
        self.user_api_key = None
        if os.path.exists(CFHOST_FILE):
            r = open(CFHOST_FILE).read()
            _ = r.split(",")
            if len(_) != 3:
                try:
                    os.remove(CFHOST_FILE)
                except:
                    pass
            else:
                _ = map(lambda x:x.strip(), _)
                self.user_email, self.user_key, self.user_api_key = _
                log("Login as %s", self.user_email)

    def _hostapi(self, act, extra={}):
        if not self.user_key and act not in ("user_auth", "host_key_regen"):
            log("Please login first. (act: %s)", act, "ERR")
            return
        payload = {
            "act": act,
            "host_key": HOSTKEY,
        }
        if act not in ("user_auth", "host_key_regen"):
            payload.update({"user_key": self.user_key})
        if extra:
            payload.update(extra)
        if act in CFARG:
            for k in CFARG[act]:
                if k not in payload:
                    log("Missing required arg \"%s\". (act:%s)", (k, act), "ERR")
                    return
        if PY3K:
            payload = urlencode(payload).encode('ascii')
        else:
            payload = urlencode(payload)
        req  = urllib2.Request("https://api.cloudflare.com/host-gw.html", payload)
        r = urllib2.urlopen(req).read()
        if PY3K and isinstance(r, bytes):
            r = r.decode('ascii')
        return json.loads(r)

    def _userapi(self, uri, method="GET", extra={}):
        if not self.user_api_key:
            log("Please login first. (uri: %s)", uri, "ERR")
            return
        headers = {
            'X-Auth-Email': self.user_email,
            'X-Auth-Key': self.user_api_key,
            'Content-Type': "application/json",
        }
        if extra:
            headers.update(extra)
        opener = urllib2.build_opener(urllib2.HTTPHandler)
        req  = urllib2.Request("https://api.cloudflare.com/client/v4%s" % uri)
        for k, v in headers.items():
            req.add_header(k, v)
        req.get_method = lambda: method
        r = opener.open(req).read()
        if PY3K and isinstance(r, bytes):
            r = r.decode('ascii')
        return json.loads(r)

        return json.loads(r.read())

    def user_auth(self, arg):
        ret = self._hostapi("user_auth", arg)
        if not ret:
            return False
        if 'response' not in ret or 'user_key' not in ret['response']:
            log("Login failed, msg: %s", ret['msg'].encode('utf-8'), "ERR")
            return False
        log("Login as %s", arg['cloudflare_email'])
        self.user_key = ret['response']['user_key']
        self.user_api_key = ret['response']['user_api_key']
        if not PY3K:
            self.user_email = arg['cloudflare_email']
            self.user_key = self.user_key.encode('utf-8')
            self.user_api_key = self.user_api_key.encode('utf-8')
        open(CFHOST_FILE, "w").write("%s,%s,%s" % (self.user_email, self.user_key, self.user_api_key))
        return True

    def logout(self, *arg):
        try:
            os.remove(CFHOST_FILE)
        except:
            pass
        os._exit(0)

    def ssl_verfication(self, arg):
        r = self._userapi("/zones?name=%s&match=all" % arg['zone'])
        if len(r['result']) < 1:
            log("No zone found matching %s. Please use zone_set first.", arg['zone'], "ERR")
            return
        zone_id = r['result'][0]['id']
        r = self._userapi("/zones/%s/ssl/verification?retry=true" % zone_id)
        if len(r['result']) < 1:
            log("??? %s", r, "ERR")
            return
        if r['result'][0]['certificate_status'] == "active":
            log("SSL for domain %s has already been activated.", arg['zone'])
            return True
        verification_info = r['result'][0]['verification_info']
        if 'record_name' in verification_info: # DNS verification
            log("Please set CNAME record of %s to %s and run this option again after record become effective", (
                verification_info['record_name'].encode('utf-8'), verification_info['record_target'].encode('utf-8')))
        else: # HTTP verification
            log("Please create a file with the following content and run this option again after record become effective:")
            print("%-90s%s" % (i18n("URL"), i18n("Content")))
            print("-" * 80)
            print("\n".join(map(lambda x: "%-90s%s" % (
                    x['verification_info']['http_url'],
                    x['verification_info']['http_body']),
                r['result'])))

    def add_subdomain(self, arg):
        r = self._hostapi("zone_lookup", {"zone_name": arg['zone_name']})
        if 'hosted_cnames' not in r['response'] or not r['response']['hosted_cnames']:
            log("No zone found matching %s. Please use zone_set first.", arg['zone_name'], "ERR")
            return
        hosted = r['response']['hosted_cnames']
        # concat a real subdomain
        if arg['subdomains'] == "@":
            subdomain = arg['zone_name']
        elif arg['subdomains'].lower().endswith(arg['zone_name'].lower()):
            subdomain = arg['subdomains']
        else:
            subdomain = "%s.%s" % (arg['subdomains'], arg['zone_name'])
        hosted[subdomain] = arg['resolve_to']
        # make the subdomain to @ to avoid it being changed
        arg['resolve_to'] = hosted[arg['zone_name']]
        arg['subdomains'] = "@,%s" % (",".join(["%s:%s" % (k, v) for k, v in hosted.items() if k != arg['zone_name']]))
        r = self._hostapi("zone_set", arg)
        self._zone_set(r, subdomain)

    def delete_subdomain(self, arg):
        if arg['subdomains'] == "@":
            log("Can't delete root record", (), "ERR")
            return
        r = self._hostapi("zone_lookup", {"zone_name": arg['zone_name']})
        if 'hosted_cnames' not in r['response'] or not r['response']['hosted_cnames']:
            log("No zone found matching %s. Please use zone_set first.", arg['zone_name'], "ERR")
            return
        hosted = r['response']['hosted_cnames']
        # concat a real subdomain
        if arg['subdomains'] == "@":
            subdomain = arg['zone_name']
        elif arg['subdomains'].lower().endswith(arg['zone_name'].lower()):
            subdomain = arg['subdomains']
        else:
            subdomain = "%s.%s" % (arg['subdomains'], arg['zone_name'])
        if subdomain not in hosted:
            log("Record %s is not found in zone %s", (subdomain, arg['zone_name']))
            return
        # make the subdomain to @ to avoid it being changed
        arg['resolve_to'] = hosted[arg['zone_name']]
        arg['subdomains'] = "@,%s" % (",".join(["%s:%s" % (k, v) for k, v in hosted.items() if k != arg['zone_name'] and k != subdomain]))
        r = self._hostapi("zone_set", arg)
        log("Record %s is deleted", subdomain)

    @catch_err
    def _zone_list(self, j):
        print("%-24s%-24s" % (i18n("Zone"), i18n("User")))
        print("-" * 80)
        for z in j['response']:
            print("%-24s%-24s" % (z['zone_name'], z['user_email']))

    @catch_err
    def _zone_set(self, j, resolve=None):
        if 'forward_tos' in j['response']:
            resolve = resolve if resolve else list(j['response']['forward_tos'].keys())[0]
            cname = j['response']['forward_tos'][resolve]
            log("Success! Please set CNAME record of %s to %s", (resolve.encode('utf-8'), cname.encode('utf-8')))

    @catch_err
    def _zone_delete(self, j):
        log("Domain %s has been removed from partner", j['request']['zone_name'].encode('utf-8'))

    @catch_err
    def _zone_lookup(self, j):
        if not j['response']['zone_exists']:
            log("Zone %s not exists or is not under user %s",
                (j['request']['zone_name'].encode('utf-8'), self.user_email))
            return
        log("SSL status: %s", (i18n(j['response']['ssl_status'].encode('utf-8').decode('ascii'))))
        print("%-32s%-24s%-32s" % (i18n("Subdomain"), i18n("Resolve to"), i18n("CNAME")))
        print("-" * 80)
        tos = j['response']['forward_tos']
        hosted = j['response']['hosted_cnames']
        if not tos or not hosted:
            return
        ssl_cname, ssl_resolve_to = None, None
        for z in tos.keys():
            if hosted[z].endswith("comodoca.com"):
                ssl_cname = z.encode('utf-8')
                ssl_resolve_to = hosted[z].encode('utf-8')
                continue
            print("%-32s%-32s%-32s" % (z, hosted[z], tos[z]))
        if ssl_cname and j['response']['ssl_status'] != "ready":
            print("")
            log("If you want to activate SSL, please set CNAME record of %s to %s and " \
                "run this \"ssl_verfication\" after record become effective", (ssl_cname, ssl_resolve_to))

    @catch_err
    def _host_key_regen(self, j):
        global HOSTKEY
        HOSTKEY = j['request']['host_key']['__host_key'].encode('utf-8')
        check_hostkey(force = True)
        log("Host key has been changed to %s", HOSTKEY)

    def __getattr__(self, act, handle=True):
        if act not in CFARG:
            raise AttributeError("'CF' object has no attribute '%s'" % act)
        return lambda k={}:getattr(self, "_%s" % act)(self._hostapi(act, k))

def check_hostkey(force = False):
    global HOSTKEY
    if HOSTKEY and len(HOSTKEY) == 32 and not force:
        return
    while not HOSTKEY or len(HOSTKEY) != 32:
        HOSTKEY = raw_input(i18n("Please enter your Cloudflare partner hostkey (https://partners.cloudflare.com/api-management)> ")).strip()
    import re
    with open(__file__, "rb") as f:
        script = f.read()
    if PY3K:
        HOSTKEY = HOSTKEY.encode('ascii')
    script = re.sub(b"HOSTKEY.+HOSTKEY_ANCHOR", b"HOSTKEY = \"%s\" # HOSTKEY_ANCHOR" % HOSTKEY, script, count = 1)
    with open(__file__, 'wb') as f:
        f.write(script)

def menu(act = None):
    if not act:
        acts = [k for k in sorted(CFARG.keys()) if k != "user_auth"] + ["logout"]
        print("=" * 32)
        print(i18n("Select your action:"))
        for i in range(len(acts)):
            print("%d. %s" % (i + 1, i18n(acts[i])))
        s = raw_input("> ").strip()
        if not s.isdigit() or int(s) not in range(1, len(acts) + 1):
            return None, None
        act = acts[int(s) - 1]
    arg = {}
    if act in CFARG:
        for k in CFARG[act]:
            while True:
                arg[k] = raw_input("%s > " % i18n(k))
                if arg[k]:
                    break
    return act, arg

if __name__ == '__main__':
    try:
        check_hostkey()
        cf = CF()
        while not cf.user_key:
            act, arg = menu(act = "user_auth")
            cf.user_auth(arg)
        while True:
            act, arg = menu()
            if not act:
                continue
            getattr(cf, act)(arg)
    except (KeyboardInterrupt, EOFError):
        os._exit(0)


# Name: Charmi Kadi
# Date: May. 18, 2021
# Class: ICS3U1-01
# Description: Program that reads in a file name from the user and tells them what kind of file it is

# User input
file = str(input("Enter the file name: "))

# String slicing
period = file.find(".")
extension = str(file[period+1:])

# if statement
if extension == "png":
   print( file, "is a png file.")
elif extension == "jpeg":
   print( file, "is a jpeg file.")
elif extension == "doc":
   print( file, "is a Word Document.")
elif extension == "gif":
   print( file, "is a GIF image file.")
elif extension == "pdf":
   print( file, "is a Portable Document Format file.")


import requests

# Set the API token and chat ID of your Telegram bot
api_token = 'your_api_token_here'
chat_id = 'your_chat_id_here'

# Set the path of the file you want to send
file_path = '/path/to/your/file.jpg'

# Construct the URL for the Telegram API endpoint
api_url = f'https://api.telegram.org/bot{api_token}/sendPhoto'

# Set the parameters of the POST request
params = {
    'chat_id': chat_id,
}

# Open the file in binary mode and attach it to the POST request
with open(file_path, 'rb') as file:
    response = requests.post(api_url, params=params, files={'photo': file})

# Check the status code of the response to make sure the file was sent successfully
if response.status_code == 200:
    print('File sent successfully.')
else:
    print('Error sending file:', response.content)


import mindspore.ops as ops
import mindspore
import mindspore.common.dtype as mstype
from mindspore.common.tensor import Tensor
from mindspore.ops import operations as P
from mindspore.ops import functional as F
from mindspore import nn
from mindspore.ops import _selected_ops
import numpy as np
from mindspore.ops import Fill
from mindspore.ops import composite as C

# import mindspore.numpy as np

def expand(self, x):
    fill = Fill()
    temp = fill((mindspore.float32, (1, x.shape(0)), 1))
    output = [x1.expand_as(temp) for x1 in x]

    return output

class _Loss(nn.Cell):
    """
    Base class for other losses.
    """

    def __init__(self, reduction='mean'):
        super(_Loss, self).__init__()
        if reduction is None:
            reduction = 'none'

        if reduction not in ('mean', 'sum', 'none'):
            raise ValueError(f"reduction method for {reduction.lower()} is not supported")

        self.average = True
        self.reduce = True
        if reduction == 'sum':
            self.average = False
        if reduction == 'none':
            self.reduce = False

        self.reduce_mean = _selected_ops.ReduceMean()
        self.reduce_sum = P.ReduceSum()
        self.mul = P.Mul()
        self.cast = P.Cast()

    def get_axis(self, x):
        shape = F.shape(x)
        length = F.tuple_len(shape)
        perm = F.make_range(0, length)
        return perm

    def get_loss(self, input, weights=1.0):
        """
        Computes the weighted loss
        Args:
            weights: Optional `Tensor` whose rank is either 0, or the same rank as inputs, and must be broadcastable to
                inputs (i.e., all dimensions must be either `1`, or the same as the corresponding inputs dimension).
        """
        input_dtype = input.dtype
        input = self.cast(input, mstype.float32)
        weights = self.cast(weights, mstype.float32)
        input = self.mul(weights, input)
        if self.reduce and self.average:
            input = self.reduce_mean(input, self.get_axis(input))
        if self.reduce and not self.average:
            input = self.reduce_sum(input, self.get_axis(input))
            # input = self.reduce_sum(input)
        input = self.cast(input, input_dtype)
        return input

    def construct(self, base, target):
        raise NotImplementedError

class TripletLoss(_Loss):

    def __init__(self, batch=32, perm=(1, 0), thres=None, min_value=None, max_value=None, margin=1.5, mutual_flag=False,
                 ):
        super(TripletLoss, self).__init__()
        if thres is None:
            thres = []
        if min_value == None:
            min_value = Tensor(0, mstype.float32)
        if max_value == None:
            max_value = Tensor(1, mstype.float32)
        self.min_value = min_value
        self.max_value = max_value
        self.batch = batch
        self.margin = margin
        self.maximum = ops.ArgMaxWithValue()
        self.minimum = ops.ArgMinWithValue()
        self.mutual = mutual_flag
        self.pow = ops.Pow()
        self.equal = ops.Equal()
        self.sqrt = ops.Sqrt()
        self.matrix_multiply = ops.MatMul()
        self.squeeze = ops.Squeeze(1)
        self.squeeze0 = ops.Squeeze(0)
        self.cumsum = ops.CumSum()
        self.transpose = ops.Transpose()
        self.perm = perm
        self.broadcastto = ops.BroadcastTo((self.batch, self.batch))
        self.mul = ops.Mul()
        self.not_equal = ops.NotEqual()
        self.thres = thres
        self.greater = ops.Greater()
        self.print = ops.Print()
        self.max = ops.Maximum()
        self.reducemesns = ops.ReduceMean()
        self.abs = ops.Abs()

    def construct(self, base, targets):
        # dist = self.broadcastto(self.squeeze(self.cumsum(self.pow(base, 2), 1)[:, -1:]))
        dist = self.broadcastto(self.reduce_sum(self.pow(base, 2), 1))
        dist = dist + self.transpose(dist, self.perm)
        xy = self.matrix_multiply(base, self.transpose(base, self.perm))
        dist = self.sqrt(self.abs(dist - 2 * (xy)) + 1e-4)
        mask = self.equal(self.broadcastto(targets), self.transpose(self.broadcastto(targets), self.perm))

        dist_ap = self.mul(dist, mask)
        temp = self.not_equal(dist_ap, dist)
        dist_an = self.mul(dist, temp) + mask * 10000000
        _, ap = self.maximum(dist_ap)
        _, an = self.minimum(dist_an)

        # loss = C.clip_by_value(self.max((ap - an + self.margin), 0), self.min_value, self.max_value)
        loss = self.max((ap - an + self.margin), 0)
        # loss = loss.sum()/len(loss)
        ret = self.reducemesns(loss, 0)
        # loss = self.squeeze0(ret[ret.shape[0] - 1:ret.shape[0]]) / self.batch

        return ret

class MGN_Loss(_Loss):

    def __init__(self, batch=64, thres=None, reduction='none'):
        super(MGN_Loss, self).__init__(reduction)

        if thres is None:
            thres = []
        self.scalar_summary = ops.ScalarSummary()
        self.cross_entropy_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
        self.TripletLoss = TripletLoss(batch=batch, margin=1.5, thres=thres)
        self.squeeze = ops.Squeeze(0)
        # self.metric = nn.Accuracy('classification')/root/miniconda3

    def construct(self, base, target):
        TriLoss = self.TripletLoss(base[0], target)
        TriLoss += self.TripletLoss(base[1], target)
        TriLoss += self.TripletLoss(base[2], target)
        crossloss = self.cross_entropy_loss(base[3], target)
        crossloss += self.cross_entropy_loss(base[4], target)
        crossloss += self.cross_entropy_loss(base[5], target)
        crossloss += self.cross_entropy_loss(base[6], target)
        crossloss += self.cross_entropy_loss(base[7], target)
        crossloss += self.cross_entropy_loss(base[8], target)
        crossloss += self.cross_entropy_loss(base[9], target)
        crossloss += self.cross_entropy_loss(base[10], target)
        crossloss = TriLoss / 3 + 2 * crossloss / 8
        # crossloss = crossloss / 8
        self.scalar_summary("TriLoss", TriLoss/3)
        # self.scalar_summary("crossloss", crossloss)

        loss_sum = crossloss

        return self.get_loss(loss_sum)

class PCBLoss_v2(_Loss):
    def __init__(self, reduction='none'):
        super(PCBLoss_v2, self).__init__(reduction)
        # self.abs = ops.Abs()
        # self.reduce_mean = ops.ReduceMean()
        '''
        两种损失函数的比较
        '''
        self.l = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
        # self.l = nn.SoftmaxCrossEntropyWithLogits(sparse=True)

    def construct(self, base, target):
        # print('输出')
        # print(base[0])
        # print('mubiao ')
        # print(target)
        y = self.l(base[3], target)
        y += self.l(base[4], target)
        y += self.l(base[5], target)
        # y += self.l(base[6], target)
        # y += self.l(base[7], target)
        # y += self.l(base[8], target)
        # y += self.l(base[9], target)
        # y += self.l(base[10], target)
        y = y / 5
        return self.get_loss(y)

if __name__ == '__main__':
    input = Tensor(np.array([[3, 4, 6, 10], [1, 6, 7, 9], [4, 3, 8, 7], [1, 3, 7, 9]]).astype(np.float32))
    target = Tensor([1, 1, 3, 4])
    loss = TripletLoss(batch=4, thres=Tensor(np.zeros((4, 4))))
    out = loss.construct(input, target)
    print(out)