import cv2
import numpy as np
import pyautogui
import time

def find_grid_location(image):
    # Define the lower and upper bounds for the blue color
    lower_blue = np.array([56, 142, 245])
    upper_blue = np.array([103, 198, 255])

    # Create a binary mask for the blue color
    mask = cv2.inRange(image, lower_blue, upper_blue)

    # Find contours in the binary mask
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Filter out erroneous contours based on shape and area compared to the median contour
    valid_contours = []

    if len(contours) > 0:
        # Calculate the median contour
        median_contour = sorted(contours, key=cv2.contourArea)[-10]

        for contour in contours:
            # Calculate the absolute difference in area and shape between the current contour and the median contour
            area_difference = abs(cv2.contourArea(contour) - cv2.contourArea(median_contour))
            shape_difference = cv2.matchShapes(median_contour, contour, cv2.CONTOURS_MATCH_I2, 0)

            # Adjust these thresholds based on your specific case
            if area_difference < 20 or shape_difference < 1:
                valid_contours.append(contour)

    # Sort valid contours by their x-coordinate
    valid_contours.sort(key=lambda c: cv2.boundingRect(c)[0])

    # Group contours into columns based on their x-coordinate
    grouped_contours_x = group_contours(valid_contours, 'x', 5)

    # Sort valid contours by their y-coordinate
    valid_contours.sort(key=lambda c: cv2.boundingRect(c)[1])

    # Group contours into rows based on their y-coordinate
    grouped_contours_y = group_contours(valid_contours, 'y', 5)

    # Get the center locations of valid contours in each column and row
    x_centers = [(int)(sum(cv2.boundingRect(contour)[0] + cv2.boundingRect(contour)[2] / 2 for contour in group)) // len(group) for group in grouped_contours_x]
    y_centers = [(int)(sum(cv2.boundingRect(contour)[1] + cv2.boundingRect(contour)[3] / 2 for contour in group)) // len(group) for group in grouped_contours_y]

    return x_centers, y_centers

def group_contours(contours, axis, threshold):
    # Group contours into columns or rows based on their x or y coordinate
    grouped_contours = []
    current_group = [contours[0]]

    for i in range(1, len(contours)):
        current_val = cv2.boundingRect(contours[i])[0] if axis == 'x' else cv2.boundingRect(contours[i])[1]
        prev_val = cv2.boundingRect(contours[i - 1])[0] if axis == 'x' else cv2.boundingRect(contours[i - 1])[1]

        if abs(current_val - prev_val) < threshold:
            current_group.append(contours[i])
        else:
            grouped_contours.append(current_group)
            current_group = [contours[i]]

    grouped_contours.append(current_group)
    return grouped_contours

def read_board(x_centers, y_centers, image):
    color_grid = []

    line_len = (int) ((y_centers[-1] - y_centers[0]) / (len(y_centers) - 1) / 5)

    for y in y_centers:
        row = []

        for x in x_centers:
            # Calculate the coordinates for the line above and below the center pixel
            y_top = int(y - line_len)
            y_bottom = int(y + line_len)

            # Extract colors along the vertical line
            colors = image[y_top:y_bottom, x]

            avg_color = np.min(colors, axis=0)

            # Determine the color category
            category = get_color_category(avg_color)

            # Append the category to the row
            row.append(category)

        # Append the row to the color grid
        color_grid.append(row)

    return color_grid

def get_color_category(color):
    # Define color ranges for categories
    cover_range = ((90, 180, 240), (150, 240, 255))
    blank_range = ((240, 240, 240), (255, 255, 255))
    empty_range = ((20, 20, 20), (60, 60, 90))
    one_range = ((10, 140, 170), (40, 190, 230))
    two_range = ((70, 90, 0), (140, 180, 40))
    three_range = ((120, 10, 50), (220, 70, 130))
    four_range = ((11, 40, 110), (40, 90, 180))
    five_range = ((90, 5, 5), (180, 50, 40))
    six_range = ((0, 91, 90), (10, 120, 109))

    # Check the color against predefined ranges
    if is_in_range(color, cover_range):
        return 'c'
    elif is_in_range(color, blank_range):
        return "b"
    elif is_in_range(color, empty_range):
        return "e"
    elif is_in_range(color, one_range):
        return 1
    elif is_in_range(color, two_range):
        return 2
    elif is_in_range(color, three_range):
        return 3
    elif is_in_range(color, four_range):
        return 4
    elif is_in_range(color, five_range):
        return 5
    elif is_in_range(color, six_range):
        return 6
    else:
        # return "?"
        raise Exception(f"Unknown square {color}")

def is_in_range(color, color_range):
    # Check if the color is in the specified range
    return all(color_range[0] <= color) and all(color <= color_range[1])

def start_ai(x_grid, y_grid, board_state):
    cols = len(x_grid)
    rows = len(y_grid)

    # Modify the board state to show mines and free squares
    simple_check(rows, cols, board_state)

    to_click = False
    for row in board_state:
        if "s" in row:
            to_click = True
            break

    if not to_click:
        advanced_check(rows, cols, board_state)

    clicked = False

    # Display the free spaces and the mines
    for row in range(rows):
        for col in range(cols):
            if board_state[row][col] == "s":
                # The square is not a mine
                pyautogui.click(x_grid[col], y_grid[row])
                clicked = True

            elif board_state[row][col] == "m":  # The square is a mine
                # The square is a mine
                pass

    if not clicked:
        raise Exception("Help me Step Bro! I'm stuck!")

class InvalidBoardState(Exception):
    pass

def simple_check(rows, cols, board_state):
    changed = False  # Record if any values in the array were changed
    for row in range(rows):
        for col in range(cols):
            # If it's a numbers square check it for relevant info
            if isinstance(board_state[row][col], int):
                pot_mine_num = 0  # The number of mine or unknowns around the square
                mine_num = 0  # The number of mine around the square

                # Check the squares around the square to find the above two values
                for i in range(-1, 2):
                    for j in range(-1, 2):
                        if (0 <= row + i < rows and 0 <= col + j < cols):
                            if board_state[row + i][col + j] == "c":  # Unknown square found
                                pot_mine_num += 1
                            elif board_state[row + i][col + j] == "m":  # Mine found
                                mine_num += 1
                                pot_mine_num += 1

                if pot_mine_num < board_state[row][col] or mine_num > board_state[row][col]:
                    raise InvalidBoardState(board_state)

                # Check if the square's value is the same as the total potential mines or the total known mines
                if pot_mine_num == board_state[row][col] or mine_num == board_state[row][col]:
                    # Find all unknown squares around the square and change them accordingly
                    for i in range(-1, 2):
                        for j in range(-1, 2):
                            if (
                                0 <= row + i < rows and 0 <= col + j < cols
                                and board_state[row + i][col + j] == 'c'
                            ):
                                if pot_mine_num == board_state[row][col]:  # The square is a mine
                                    board_state[row + i][col + j] = "m"
                                else:  # the square is not a mine
                                    board_state[row + i][col + j] = "s"
                                changed = True  # Record that the board state changed
    if changed:  # If the board state changed run this check again
        return simple_check(rows, cols, board_state)
    return board_state

def advanced_check(rows, cols, board_state):
    for row in range(rows):
        for col in range(cols):
            if board_state[row][col] == "c":
                m_board = [row[:] for row in board_state]

                m_board[row][col] = "m"
                try:
                    simple_check(rows, cols, m_board)
                except InvalidBoardState:
                    board_state[row][col] = "s"
                    continue

                s_board = [row[:] for row in board_state]
                s_board[row][col] = "s"
                try:
                    simple_check(rows, cols, s_board)
                except InvalidBoardState:
                    board_state[row][col] = "m"
                    continue

    simple_check(rows, cols, board_state)

def main():
    # Capture the screen using pyautogui
    screen = np.array(pyautogui.screenshot())

    # Find the grid location
    x_grid, y_grid = find_grid_location(screen)
    mid_x, mid_y = (int)(len(x_grid)/2), (int)(len(y_grid)/2)
    board = read_board(x_grid, y_grid, screen)

    # Click window to ensure it is focused
    pyautogui.click(x_grid[mid_x], y_grid[mid_y])
    time.sleep(0.01)

    if board[mid_y][mid_x] == "c":
        pyautogui.click()
    elif board[mid_y][mid_x] == "e":
        clicked = False
        for row in range(len(y_grid)):
            for col in range(len(x_grid)):
                if board[row][col] == "b":
                      pyautogui.click(x_grid[col], y_grid[row])
                      pyautogui.click(x_grid[col], y_grid[row])
                      clicked = True

        if not clicked:
            pyautogui.click(x_grid[(int)(len(x_grid)/4)], y_grid[mid_y])

    while True:
        pyautogui.moveTo((x_grid[-1] - x_grid[-2]) + x_grid[-1] , y_grid[0])
        screen = np.array(pyautogui.screenshot())

        board = read_board(x_grid, y_grid, screen)

        start_ai(x_grid, y_grid, board)
        time.sleep(0.1)

if __name__ == "__main__":
    main()


from django.urls import path
from . import views

urlpatterns = [
    path("home",views.index , name = "index"),
    path("signup" ,views.signup, name = "signup"),
    path("" ,views.loginx ,name = "loginx"),
    path("add", views.add , name = "add"),
    path("remove",views.remove , name = "remove"),
    path("about" ,views.about , name = "about"),
    path("logout" , views.logoutx , name = 'logout')
]


# Author: Dionne Bang
# Date: 12/7/22
# Description: Server side of a simple client-server multiplayer tic-tac-toe ascii game.
# Citation for following program:
# Date retrieved: 12/5/22
# Source code based on: Kurose and Ross, Computer Networking: A Top-Down Approach, 7th Edition,Pearson, Chapter 2.7

from socket import *
import pickle

serverPort = 56565

# The server creates a socket and binds to ‘localhost’ and port xxxx
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('localhost', serverPort))

# The server then listens for a connection
serverSocket.listen(1)

print('Waiting for message...')
connectionSocket, addr = serverSocket.accept()

# When connected, the server calls recv to receive game invite
invite = connectionSocket.recv(1024).decode()

# The server prints invite, then prompts for answer
print(invite)
reply = input('>')
connectionSocket.send(reply.encode())

while reply.lower() != 'y':
    # if server doesn't want to play
    if reply.lower() == 'n':
        print('Okay, bye!')
        connectionSocket.close()
        break

    # if server types something other than y/n
    elif reply.lower() != 'y' and reply.lower() != 'n':
        reply = input('Invalid answer! Type \'Y\' or \'N\': ')
        connectionSocket.send(reply.encode())

if reply.lower() == 'y':
    # if server wants to play
    print('Let\'s play!')
    print('Waiting for first move...')

    while True:
        # receive board from client
        game = connectionSocket.recv(1024)
        updatedGame = pickle.loads(game)
        updatedGame.print_board()

        # close if game over
        if updatedGame.get_game_state() == 'GAME OVER':
            print(updatedGame.get_game_result())
            print(updatedGame.get_game_state())
            connectionSocket.close()
            break

        # play if game ongoing
        # server makes move
        myMove = input('Your move: ')
        updatedGame.make_move(myMove)

        while updatedGame.get_move_validity() == False:
            myMove = input('Your move: ')
            updatedGame.make_move(myMove)

        # send client updated game
        sendGame = pickle.dumps(updatedGame)
        connectionSocket.send(sendGame)

        # close if game over
        if updatedGame.get_game_state() == 'GAME OVER':
            print(updatedGame.get_game_state())
            connectionSocket.close()
            break

        print('Their move.')


import unittest
import datetime
from typing import Optional
from decimal import Decimal
from money import Money

from test.utils.capture_exception import capture_exception
from src.domain.transactions.buy_item import BuyItem
from src.domain.transactions.sell_item import SellItem
from src.domain.trading.buy_sell_pair import BuySellPair
from src.domain.currency import Currency
from src.domain.quotation.buy_sell_pair_pln_quotator import BuySellPairPLNQuotator
from src.domain.errors import NoQuotesAvailableError

class QuotesProviderStub:
    usd_table = {
        datetime.date(2000, 12, 20): 3.0,
        datetime.date(2000, 12, 21): 3.0,
        datetime.date(2000, 12, 22): 3.0,
        # datetime.date(2000, 12, 23): 3.0, # saturday
        # datetime.date(2000, 12, 24): 3.0, # sunday
        datetime.date(2000, 12, 25): 3.0,
        datetime.date(2000, 12, 26): 4.0,
        datetime.date(2000, 12, 27): 4.0,
    }

    def get_average_pln_for_day(self, currency: Currency, date: datetime.date) -> Optional[Decimal]:
        if currency != Currency("USD"):
            return None
        if date not in QuotesProviderStub.usd_table:
            return None
        return Decimal(QuotesProviderStub.usd_table[date])

class TaxableItemQuotatorTest(unittest.TestCase):
    def test_quotation_unsupported_currency_raises_error(self):
        # given
        quotator = BuySellPairPLNQuotator(QuotesProviderStub())
        buy_sell_pair = BuySellPair(
            buy=BuyItem(
                asset_name="PHYS",
                amount=100,
                paid=Money("1000", "SGD"),
                commission=Money("1", "SGD"),
                date=datetime.date(2000, 12, 26),
                transaction_id=0,
            ),
            sell=SellItem(
                asset_name="PHYS",
                amount=100,
                received=Money("1000", "SGD"),
                commission=Money("1", "SGD"),
                date=datetime.date(2000, 12, 27),
                transaction_id=0,
            ),
            amount_sold=100,
        )

        # when
        expected_error = capture_exception(quotator.quote, buy_sell_pair)

        # then
        self.assertIsInstance(expected_error, NoQuotesAvailableError)

    def test_quotation_before_available_quotes_raises_error(self):
        # given
        quotator = BuySellPairPLNQuotator(QuotesProviderStub())
        before_available = datetime.date(2000, 12, 20)
        buy_sell_pair = BuySellPair(
            buy=BuyItem(
                asset_name="PHYS",
                amount=100,
                paid=Money("1000", "USD"),
                commission=Money("1", "USD"),
                date=before_available,
                transaction_id=0,
            ),
            sell=SellItem(
                asset_name="PHYS",
                amount=100,
                received=Money("1000", "USD"),
                commission=Money("1", "USD"),
                date=datetime.date(2000, 12, 27),
                transaction_id=0,
            ),
            amount_sold=100,
        )

        # when
        expected_error = capture_exception(quotator.quote, buy_sell_pair)

        # then
        self.assertIsInstance(expected_error, NoQuotesAvailableError)

    def test_quotation_after_available_quotes_raises_error(self):
        # given
        quotator = BuySellPairPLNQuotator(QuotesProviderStub())
        after_available = datetime.date(2001, 1, 5)
        buy_sell_pair = BuySellPair(
            buy=BuyItem(
                asset_name="PHYS",
                amount=100,
                paid=Money("1000", "USD"),
                commission=Money("1", "USD"),
                date=datetime.date(2000, 12, 26),
                transaction_id=0,
            ),
            sell=SellItem(
                asset_name="PHYS",
                amount=100,
                received=Money("1000", "USD"),
                commission=Money("1", "USD"),
                date=after_available,
                transaction_id=0,
            ),
            amount_sold=100,
        )

        # when
        expected_error = capture_exception(quotator.quote, buy_sell_pair)

        # then
        self.assertIsInstance(expected_error, NoQuotesAvailableError)

    def test_same_amounts_different_quotes(self):
        # given
        quotator = BuySellPairPLNQuotator(QuotesProviderStub())
        buy_sell_pair = BuySellPair(
            BuyItem(
                asset_name="PHYS",
                amount=100,
                paid=Money("1000", "USD"),
                commission=Money("1", "USD"),
                date=datetime.date(2000, 12, 26),
                transaction_id=1,
            ),
            SellItem(
                asset_name="PHYS",
                amount=100,
                received=Money("1000", "USD"),
                commission=Money("1", "USD"),
                autoconversions=[],
                date=datetime.date(2000, 12, 27),
                transaction_id=2,
            ),
            amount_sold=100,
        )

        # when
        item = quotator.quote(buy_sell_pair)

        # then
        self.assertEqual(item.buy_pln_quotation_date, datetime.date(2000, 12, 25))
        self.assertEqual(item.buy_paid_pln, Decimal(3000))  # 1000 * 3 USD/PLN
        self.assertEqual(item.buy_commission_pln, Decimal(3))  # 1 * 3 USD/PLN

        self.assertEqual(item.sell_pln_quotation_date, datetime.date(2000, 12, 26))
        self.assertEqual(item.sell_received_pln, Decimal(4000))  # 1000 * 4 USD/PLN
        self.assertEqual(item.sell_commission_pln, Decimal(4))  # 1 * 4 USD/PLN

    def test_different_amounts_same_quotes(self):
        # given
        quotator = BuySellPairPLNQuotator(QuotesProviderStub())
        buy_sell_pair = BuySellPair(
            buy=BuyItem(
                asset_name="PHYS",
                amount=100,
                paid=Money("1000", "USD"),
                commission=Money("1", "USD"),
                date=datetime.date(2000, 12, 21),
                transaction_id=0,
            ),
            sell=SellItem(
                asset_name="PHYS",
                amount=10,
                received=Money("100", "USD"),
                commission=Money("2", "USD"),
                date=datetime.date(2000, 12, 23),
                transaction_id=0,
            ),
            amount_sold=10,
        )

        # when
        item = quotator.quote(buy_sell_pair)

        # then
        self.assertEqual(item.buy_pln_quotation_date, datetime.date(2000, 12, 20))
        self.assertEqual(item.buy_paid_pln, Decimal(3000))  # 1000 * 3 USD/PLN
        self.assertEqual(item.buy_commission_pln, Decimal(3))  # 1 * 3 USD/PLN

        self.assertEqual(item.sell_pln_quotation_date, datetime.date(2000, 12, 22))
        self.assertEqual(item.sell_received_pln, Decimal(300))  # 100 * 3 USD/PLN
        self.assertEqual(item.sell_commission_pln, Decimal(6))  # 2 * 3 USD/PLN


import logging
import os
from tracemalloc import start
import requests
import shutil
from bs4 import BeautifulSoup
import re

logger = logging.getLogger(__name__)
ch = logging.StreamHandler()
ch.setFormatter(logging.Formatter("%(name)s - %(levelname)s - %(message)s"))
logger.addHandler(ch)
logger.setLevel(logging.DEBUG)

ID_PAYS=66

class Syride :

    def __init__(self, minDistance, maxDistance, minPlafond, spotId, maxTraceToGet, startAtPage, outputDir):
        self.minDistance = minDistance
        self.maxDistance = maxDistance
        self.minPlafond = minPlafond
        self.spotId = spotId
        self.maxTraceToGet = maxTraceToGet
        self.startAtPage = startAtPage
        self.outputDir = outputDir

    def getFlights(self):
        logger.debug(f"start getting flights for spot ID {self.spotId}")
        flights = getFlightsList(self.spotId, self.minPlafond, self.minDistance, self.maxDistance, self.maxTraceToGet, self.startAtPage)
        logger.debug(f"nbre de vols trouvés : {len(flights)}")

        if os.path.exists(self.outputDir):
            shutil.rmtree(self.outputDir, ignore_errors=True)
        os.mkdir(self.outputDir)

        for flight in flights:
            logger.debug(f"get key for {flight['piloteName']}, number {flight['flightNumber']}")
            key = getFlightKey(flight['flightNumber'])
            flight['key'] = key
            flight['flightIgcUrl'] = f"https://www.syride.com/scripts/downloadIGC.php?idSession={flight['flightNumber']}&key={flight['key']}"
            saveFlight(flight, self.outputDir)

def getFlightsList(spotId, minPlafond, minDistance, maxDistance, maxTraceToGet, startAtPage):
    flights = []
    page_number = startAtPage
    need_exit = False
    while True :
        flightsListUrl = getFlightsListUrl(spotId, page_number)

        page = requests.get(flightsListUrl)
        logger.debug(f"request for page {page_number} : {page.status_code}")
        soup = BeautifulSoup(page.content, "html.parser")
        table = soup.find("table")

        for row in table.find_all("tr", class_="lineDiv"):
            cols = row.find_all("td")
            piloteName = cols[0].find("a", href=True)['href'].replace("/fr/pilotes/","")
            distance = cols[2].text.replace("Kilomètres","")
            plafond = cols[3].text.replace("mètres","")
            date = cols[5].text.replace("\t","").replace("\n"," ").strip()
            flightNumber = re.search(r'showFlight\(\'[^\']+\',(\d+),\);', cols[6].get('onclick')).group(1)
            if int(distance) >= minDistance and int(distance) <= maxDistance and int(plafond) >= minPlafond:
                logger.debug(f"{piloteName}, {date}, plaf : {plafond}, distance : {distance}")
                flights.append({"flightNumber" : flightNumber, "piloteName": piloteName, "distance": distance, "date": date})
                if len(flights) == maxTraceToGet :
                    need_exit = True
                    break
            else :
                if int(distance) < minDistance :
                    logger.debug("Out of criteria, exit loop before next page")
                    need_exit = True
        if need_exit :
            break
        else:
            page_number = page_number + 1
    return flights

def saveFlight(flight, path):
    fileName = f"{flight['piloteName'].lower()}-{flight['date']}.igc".replace(" ","-").replace("/","-")
    with open(f"{path}/{fileName}", "w") as file:
        igc = requests.get(f"https://www.syride.com/scripts/downloadIGC.php?idSession={flight['flightNumber']}&key={flight['key']}")
        file.write(igc.text)
        file.close()

def getFlightKey(flightNumber) :
    url = f"https://www.syride.com/ficheVol.php?l=fr&idSession={flightNumber}&idActivite=undefined&maxHeight=369"
    page = requests.get(url)
    flightKey = re.search(r'idSession=(\d+)&key=(\d+)', page.text).group(2)
    return flightKey

def getFlightsListUrl(spot_id, page_number) :
    return f"https://www.syride.com/scripts/ajx_vols.php?l=fr&idPays={ID_PAYS}&idSpot={spot_id}&page={page_number}&order=distance&tri=DESC"


# -*- coding:UTF-8 -*-

import unittest

from testscripts.Login.test_login import Login
from action.driver import *
from util.log_print import *
from util.myunit import StartEnd
from test_data.testdata import testDataInfo

class Logout(Login):
    url='/'
    logout_data=testDataInfo('Logout')['Logout']
    logout_type=logout_data['logout_el'][1]['type']
    logout_value=logout_data['logout_el'][2]['value']
    checkinfo_type=logout_data['check_info'][1]['type']
    checkinfo_value=logout_data['check_info'][2]['value']

    def logout(self):
        el=self.find_element_(self.logout_type,self.logout_value)
        self.click_(el)

    def check_logout(self):
        el=self.find_element_(self.checkinfo_type,self.checkinfo_value)
        text=self.text_(el)
        return text

class TestLoginOut(StartEnd):
    logger=get_log('test logout')
    data=testDataInfo('Logout')['Logout']
    def test_logout(self):
        self.logger.info("Start test logout")
        driver=browser()
        newspage=Logout(driver)
        newspage.open_browser_()
        newspage.login_page()
        try:
            newspage.logout()
            newspage.accept_()
            text=newspage.check_logout()
            self.assertEqual(text,self.data['assertvalue'][2]['value'])
        except Exception as msg:
            self.logger.error(msg)
            newspage.quit_browser_()
        finally:
            self.logger.info("test logout is end")
            newspage.quit_browser_()

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


import math
import random

random.seed(0) #设置随机数种子

def rand(a, b):
    return (b - a) * random.random() + a #生成从[a,b)的随机数

def make_matrix(m, n, fill=0.0):#创造一个指定大小的矩阵
    mat = []
    for i in range(m):
        mat.append([fill] * n)
    return mat

def sigmoid(x): #设定激活函数为sigmoid哈数
    return 1.0 / (1.0 + math.exp(-x))

def sigmoid_derivative(x):#sigmoid激活函数的导数
    return x * (1 - x)

class BPNeuralNetwork:
    def __init__(self):

        self.input_n = 0
        self.hidden_n = 0
        self.output_n = 0
        #三个列表维护输入层，隐含层和输出层神经元，列表中的元素代表对应神经元当前的输出值.
        self.input_cells = []
        self.hidden_cells = []
        self.output_cells = []
        #使用两个二维列表以邻接矩阵的形式维护输入层与隐含层
        self.input_weights = []
        self.output_weights = []
        #隐含层与输出层之间的连接权值， 通过同样的形式保存矫正矩阵.
        self.input_correction = []
        self.output_correction = []

    def setup(self, ni, nh, no):
        self.input_n = ni + 1
        self.hidden_n = nh
        self.output_n = no

        # init cells
        self.input_cells = [1.0] * self.input_n #初始化输入层，长度为input_n的列表
        self.hidden_cells = [1.0] * self.hidden_n #初始化隐藏层，长度为hidden_n的列表
        self.output_cells = [1.0] * self.output_n #初始化输出层，长度为output_n的列表
        # init weights
        self.input_weights = make_matrix(self.input_n, self.hidden_n)#输入的权重为，n个输入层给n个隐藏层的2维列表权重
        self.output_weights = make_matrix(self.hidden_n, self.output_n) # 输出的权重为，n个隐藏层给n个输出层的2维列表权重
        # random activate，随机给出初始输入权重
        for i in range(self.input_n):
            for h in range(self.hidden_n):
                self.input_weights[i][h] = rand(-0.2, 0.2)
        for h in range(self.hidden_n):#随机给出初始输出权重
            for o in range(self.output_n):
                self.output_weights[h][o] = rand(-2.0, 2.0)
        # init correction matrix，初始化输入矫正权重和输出矫正权重
        self.input_correction = make_matrix(self.input_n, self.hidden_n)
        self.output_correction = make_matrix(self.hidden_n, self.output_n)
        print(self.input_weights)
        print(self.output_weights)
        print(self.input_correction)
        print(self.output_correction)

    def predict(self, inputs):
        # activate input layer
        for i in range(self.input_n - 1):
            self.input_cells[i] = inputs[i]
        # activate hidden layer
        for j in range(self.hidden_n):
            total = 0.0
            for i in range(self.input_n):
                total += self.input_cells[i] * self.input_weights[i][j]
            self.hidden_cells[j] = sigmoid(total)
        # activate output layer
        for k in range(self.output_n):
            total = 0.0
            for j in range(self.hidden_n):
                total += self.hidden_cells[j] * self.output_weights[j][k]
            self.output_cells[k] = sigmoid(total)
        return self.output_cells[:]

    def back_propagate(self, case, label, learn, correct):
        # feed forward
        self.predict(case)
        # get output layer error
        output_deltas = [0.0] * self.output_n
        for o in range(self.output_n):
            error = label[o] - self.output_cells[o]
            output_deltas[o] = sigmoid_derivative(self.output_cells[o]) * error
        # get hidden layer error
        hidden_deltas = [0.0] * self.hidden_n
        for h in range(self.hidden_n):
            error = 0.0
            for o in range(self.output_n):
                error += output_deltas[o] * self.output_weights[h][o]
            hidden_deltas[h] = sigmoid_derivative(self.hidden_cells[h]) * error
        # update output weights
        for h in range(self.hidden_n):
            for o in range(self.output_n):
                change = output_deltas[o] * self.hidden_cells[h]
                self.output_weights[h][o] += learn * change + correct * self.output_correction[h][o]
                self.output_correction[h][o] = change
        # update input weights
        for i in range(self.input_n):
            for h in range(self.hidden_n):
                change = hidden_deltas[h] * self.input_cells[i]
                self.input_weights[i][h] += learn * change + correct * self.input_correction[i][h]
                self.input_correction[i][h] = change
        # get global error
        error = 0.0
        for o in range(len(label)):
            error += 0.5 * (label[o] - self.output_cells[o]) ** 2
        return error

    def train(self, cases, labels, limit=10000, learn=0.05, correct=0.1):
        for j in range(limit):
            error = 0.0
            for i in range(len(cases)):
                label = labels[i]
                case = cases[i]
                error += self.back_propagate(case, label, learn, correct)

    def test(self):
        cases = [
            [0, 0],
            [0, 1],
            [1, 0],
            [1, 1],
        ]
        labels = [[0], [1], [1], [0]]
        self.setup(2, 5, 1)
        self.train(cases, labels, 10000, 0.05, 0.1)
        for case in cases:
            print(self.predict(case))

if __name__ == '__main__':
    nn = BPNeuralNetwork()
    nn.test()


from flask import g

from homewerk import models as m
from sqlalchemy import or_
from homewerk.services import Singleton
from homewerk.constants import SubmitStatus, NotificationScopes
from homewerk.utils import save_b64_file
from homewerk.services.notification import NotificationService

noti_service = NotificationService.get_instance()

class SubmitService(Singleton):
    def get_submits(self, data):
        query = m.Submit.query

        id = data.get('id')
        if id:
            query = query.filter(m.Submit.id == id)

        assignment_id = data.get('assignment_id')
        if assignment_id:
            query = query.filter(m.Submit.assignment_id == assignment_id)

        user_id = data.get('user_id')
        if not data.get('user_id'):
            user_id = g.user.id
        if user_id:
            query = query.filter(m.Submit.user_id == user_id)

        status = data.get('status')
        if status:
            query = query.filter(m.Submit.status == status)

        return query.all()

    def update_submit(self, data):
        id = data.get('id')
        if not id:
            return

        submit = m.Submit.query.filter(m.Submit.id == id).first()
        status = data.get('status')
        if status:
            submit.status = status

        result = data.get('score')
        if result:
            submit.result = result
            submit.status = SubmitStatus.GRADED

        comment = data.get('comment')
        if comment:
            submit.comment = comment

        work_id = data.get('work_id')
        if work_id:
            file_data = data.get('file')
            if file_data:
                file_path = save_b64_file(file_data, work_id)
                work = m.Work.query.get(work_id)
                work.result_path = file_path

        m.db.session.commit()
        if result:
            noti_service.grade_assignment_notification(submit)
        return submit

    def add_submit(self, data):
        submit = m.Submit()
        submit.status = 'submitted'
        user_id = data.get('user_id')
        if not user_id:
            return
        submit.user_id = user_id
        assignment_id = data.get('assignment_id')
        if not assignment_id:
            return
        submit.assignment_id = assignment_id
        m.db.session.add(submit)
        m.db.session.commit()

        noti_service.submit_assignment_notification(submit)
        assignment = m.Assignment.query.filter(m.Assignment.id == assignment_id).first()
        noti_service.subcribe_notification(user_id=user_id,
                                           scope=NotificationScopes.ASSIGNMENT,
                                           scope_id=assignment_id)

        return submit


# Class corresponding to a DeclarationSequence node in the abstract syntax tree.
from Declaration import Declaration
from Error import printSyntaxError
from Scanner import Scanner
from Token import Token

class DeclarationSequence:
    def __init__(self):
        #initialize all posisble children of Declaration Sequence node
        self._decl = None
        self._declSeq = None

    # Parse this DeclarationSequence statement according to the BNF production.
    def parseDeclarationSequence(self, tokens: Scanner):
        self._decl = Declaration()
        self._decl.parseDeclaration(tokens)
        # check if next token is an INT keyword; this indicates we are in second alternative of prod. rule
        if tokens.getToken() == Token.INT.value:
            self._declSeq = DeclarationSequence()
            self._declSeq.parseDeclarationSequence(tokens)

    # Print this DeclarationSequence statement according to the BNF production.
    def printDeclarationSequence(self,tabLevel):
        self._decl.printDeclaration(tabLevel)
        if self._declSeq:
            self._declSeq.printDeclarationSequence(tabLevel)

    # Execute this Declaration Sequence statement.
    def execDeclarationSequence(self):
        self._decl.execDeclaration()
        if self._declSeq:
            self._declSeq.execDeclarationSequence()


# Create constants for the longitude and latitude boundaries of the regions
MAX_LAT = 49.189787
MIN_LAT = 24.660845
P1_LONG = -67.444574
P3_LONG = -87.518395
P5_LONG = -101.998892
P7_LONG = -115.236428
P9_LONG = -125.242264

# Function that computes and returns the happiness score for each tweet and its corresponding region, date, and time
def compute_tweets(tweetFile, keywordFile):
    try:
        t = open(tweetFile, "r", encoding="utf-8")
        tweets = t.readlines()
        k = open(keywordFile, "r", encoding="utf-8")
        keywords = k.readlines()

        # Create and initialize empty lists, dictionaries, and tuples to store values that will be used later
        region_scores = {'Eastern': 0, 'Central': 0, 'Mountain': 0, 'Pacific': 0}
        tweet_count = {'Eastern': 0, 'Central': 0, 'Mountain': 0, 'Pacific': 0}
        keyword_count = {'Eastern': 0, 'Central': 0, 'Mountain': 0, 'Pacific': 0}
        lines_list = []
        keywords_dict = {}
        result = []

        # Store keywords into a dictionary named keywords_dict
        for line in keywords:
            line = line.split(',')
            line[1] = line[1].replace('\n', '')
            keywords_dict[line[0]] = line[1]

        # Split each line in tweets by whitespace and store the values in a list, lines. Then store lines into lines_list
        for line in tweets:
            line = line.lower()
            lines = []
            line = line.split()
            for item in line:
                lines.append(item)
            lines_list.append(lines)

        # Remove the value, date, and time from each list from the tweet file.
        for item in lines_list:
            item.pop(2)
            item.pop(2)
            item.pop(2)
            # Find the region in which the tweet was sent and remove punctuation from the beginning and end of words.
            latitude = item[0].replace('[', '')
            latitude = latitude.replace(',', '')
            longitude = item[1].replace(']', '')
            # Remove all punctuation in the tweets
            for index, char in enumerate(item):
                if char[0] in ',.?!@#$%-()\'\"':
                    item[index] = char.replace(char[0], '')
                if char[-1] in ',.?!@#$%-()\'\"':
                    item[index] = char.replace(char[-1], '')
            # Call function find_region to determine which timezone the tweet belongs in
            timezone = find_region(float(latitude), float(longitude))
            # Check if a tweet is from one of the given timezones and increment the score by such; if not, it is not added to the score.
            if timezone != "":
                tweet_count[timezone] += 1
                # Call function calculate_score to find the happiness score of the tweet
                score = calculate_score(item, keywords_dict)
                if score is not None:
                    region_scores[timezone] += score
                    keyword_count[timezone] += 1

        # Create a tuple storing the average happiness value, the number of keyword tweets and the total number of tweets.
        for place in tweet_count:
            if keyword_count[place] != 0:
                average = region_scores[place] / keyword_count[place]
            else:
                average = 0
            regions = (average, keyword_count[place], tweet_count[place])
            result.append(regions)

        return result

    # Raise exception if file does not exist and return an empty list
    except IOError:
        return []

# Function that finds the region where the tweet was sent
def find_region(latitude, longitude):
    if MIN_LAT <= latitude <= MAX_LAT:  # If the tweet is not within the longitude boundaries, nothing is returned
        # If the tweet is within the longitude boundaries, eastern, central, mountain or nothing will be returned depending on where it falls within the latitude boundaries
        if P1_LONG >= longitude >= P3_LONG:
            return "Eastern"
        elif P3_LONG >= longitude >= P5_LONG:
            return "Central"
        elif P5_LONG >= longitude >= P7_LONG:
            return "Mountain"
        elif P7_LONG >= longitude >= P9_LONG:
            return "Pacific"
        else:
            return ""
    else:
        return ""

# Function that calculates and returns the happiness score in each tweet
def calculate_score(tweet, keywords):
    sentiment_value = 0
    num_keywords = 0
    for word in tweet:
        for key, value in keywords.items():
            if word == key:
                num_keywords += 1
                sentiment_value += int(value)
    if num_keywords != 0:
        happiness_score = sentiment_value / num_keywords
        return happiness_score


"""
FastAPI application module
"""

import inspect
import os
import sys

from fastapi import APIRouter, FastAPI

from .base import API
from .factory import Factory

from ..app import Application

# API instance
app = FastAPI()

# Global API instance
INSTANCE = None

def get():
    """
    Returns global API instance.

    Returns:
        API instance
    """

    return INSTANCE

def apirouters():
    """
    Lists available APIRouters.

    Returns:
        {router name: router}
    """

    # Get handle to api module
    api = sys.modules[".".join(__name__.split(".")[:-1])]

    available = {}
    for name, rclass in inspect.getmembers(api, inspect.ismodule):
        if hasattr(rclass, "router") and isinstance(rclass.router, APIRouter):
            available[name.lower()] = rclass.router

    return available

@app.on_event("startup")
def start():
    """
    FastAPI startup event. Loads API instance.
    """

    # pylint: disable=W0603
    global INSTANCE

    # Load YAML settings
    config = Application.read(os.getenv("CONFIG"))

    # Instantiate API instance
    api = os.getenv("API_CLASS")
    INSTANCE = Factory.create(config, api) if api else API(config)

    # Get all known routers
    routers = apirouters()

    # Conditionally add routes based on configuration
    for name, router in routers.items():
        if name in config:
            app.include_router(router)

    # Special case for embeddings clusters
    if "cluster" in config and "embeddings" not in config:
        app.include_router(routers["embeddings"])

    # Special case to add similarity instance for embeddings
    if "embeddings" in config and "similarity" not in config:
        app.include_router(routers["similarity"])

    # Execute extensions if present
    extensions = os.getenv("EXTENSIONS")
    if extensions:
        for extension in extensions.split(","):
            # Create instance and execute extension
            extension = Factory.get(extension.strip())()
            extension(app)


#!/usr/bin/env python
"""
Train My Brain
github.com/irlrobot/train_my_brain
"""
from __future__ import print_function
import json
from play_new_game import play_new_game
from handle_answer_request import handle_answer_request
from alexa_responses import play_end_message, speech

def lambda_handler(event, _context):
    """main function for AWS Lambda"""
    print('=====lambda handler started...')
    print(json.dumps(event))

    if event['session']['new']:
        on_session_started({'requestId': event['request']['requestId']},
                           event['session'])
        # this will trigger if a one shot is used
        if event['request']['type'] == "IntentRequest":
            return on_launch(event['request'], event['session'])

    if event['request']['type'] == "LaunchRequest":
        return on_launch(event['request'], event['session'])
    if event['request']['type'] == "IntentRequest":
        return on_intent(event['request'], event['session'])
    if event['request']['type'] == "SessionEndedRequest":
        return on_session_ended(event['request'], event['session'])

def on_session_started(session_started_request, session):
    """when starting a new session"""
    print("=====on_session_started requestId:  " +
          session_started_request['requestId'] + ", sessionId=" +
          session['sessionId'])

def on_launch(event_request, session):
    """when customer launches the skill via modal"""
    print("=====on_launch requestId:  " + event_request['requestId'] +
          ", sessionId=" + session['sessionId'])
    return play_new_game(False)

def on_intent(event_request, session):
    """when customer launches the skill via modal"""
    print("=====on_intent requestId:  " + event_request['requestId'] +
          ", sessionId=" + session['sessionId'])

    intent = event_request['intent']
    intent_name = event_request['intent']['name']
    print("=====intent is: " + intent_name)

    if intent_name == "AnswerIntent":
        print("=====AnswerIntent fired...")
        if 'attributes' in session:
            if 'questions' in session['attributes']:
                return handle_answer_request(intent, session)

        # we probably got here because user said something other than
        # yes or no after asking if they wanted to play the game again
        print("=====no attributes ending game")
        return play_end_message()
    if intent_name == "GameIntent":
        print("=====GameIntent fired...")
        # if there's a session and we're in a game treat this as an answer
        # unfortunately it will be wrong but it's better than starting over
        if 'attributes' in session:
            if session['attributes']['game_status'] == "in_progress":
                return handle_answer_request(intent, session)
        return play_new_game(False)
    if intent_name in ("AMAZON.StartOverIntent", "AMAZON.YesIntent"):
        print("=====StartOverIntent or YesIntent fired...")
        return play_new_game(True)
    if intent_name == "AMAZON.NoIntent":
        print("=====NoIntent fired...")
        # if there's a session and we're in a game treat this as a wrong answer
        if 'attributes' in session:
            if session['attributes']['game_status'] == "in_progress":
                return handle_answer_request(intent, session)
        # otherwise end the game
        return play_end_message()
    if intent_name in ("AMAZON.StopIntent", "AMAZON.CancelIntent"):
        print("=====StopIntent or CancelIntent fired")
        return play_end_message()
    if intent_name == 'AMAZON.HelpIntent':
        print("=====HelpIntent...")
        tts = "During the game I'll give you 6 random brain teasers and only 8 "\
            "seconds to anser each one... To make your mind muscles stronger, I "\
            "won't repeat any of the questions, so try to remember all the "\
            "details... You can say 'Start Over' if you'd like a new game, "\
            "or make your guess for the last question..."
        return speech(tts, session['attributes'], False, None)

def on_session_ended(event_request, session):
    """when the user ends the session intentionally or timeout"""
    print("=====on_session_ended requestId=" + event_request['requestId'] +
          ", sessionId=" + session['sessionId'])
    return play_end_message()


class Ordering:
    """A class to specify specific column ordering of the query result."""

    _field_name: str
    _value: str

    @classmethod
    def ASC(cls, field_name: str) -> "Ordering":
        """Specify column ordering of the query result in ascending order.

        Args:
            field_name: The column name.

        Returns:
            Ordering: The column order object.
        """
        obj = cls()
        obj._field_name = field_name
        obj._value = "ASC"
        return obj

    @classmethod
    def DESC(cls, field_name: str) -> "Ordering":
        """Specify column ordering of the query result in descending order.

        Args:
            field_name: The column name.

        Returns:
            Ordering: The column order object.
        """
        obj = cls()
        obj._field_name = field_name
        obj._value = "DESC"
        return obj

    def _copy(self) -> "Ordering":
        obj = Ordering()
        obj._field_name = self._field_name
        obj._value = self._value
        return obj

class InvalidQuery(Exception):
    """Invalid query operation"""


# CS 61A Fall 2014
# Name: xin heng

def two_equal(a, b, c):
    """Return whether exactly two of the arguments are equal and the
    third is not.

    >>> two_equal(1, 2, 3)
    False
    >>> two_equal(1, 2, 1)
    True
    >>> two_equal(1, 1, 1)
    False
    >>> result = two_equal(5, -1, -1) # return, don't print
    >>> result
    True

    """
    l = [a,b,c]
    if len(set(l)) == 2:
        return True
    else:
        return False

def same_hailstone(a, b):
    """Return whether a and b are both members of the same hailstone
    sequence.

    >>> same_hailstone(10, 16) # 10, 5, 16, 8, 4, 2, 1
    True
    >>> same_hailstone(16, 10) # order doesn't matter
    True
    >>> result = same_hailstone(3, 19) # return, don't print
    >>> result
    False

    """
    "*** YOUR CODE HERE ***"

def near_golden(perimeter):
    """Return the integer height of a near-golden rectangle with PERIMETER.

    >>> near_golden(42) # 8 x 13 rectangle has perimeter 42
    8
    >>> near_golden(68) # 13 x 21 rectangle has perimeter 68
    13
    >>> result = near_golden(100) # return, don't print
    >>> result
    19

    """
    smallest = perimeter
    for w in range(1, perimeter//2):
        h = perimeter//2 - w
        dif = abs(h/w - (w/h-1) )
        if dif < smallest:
            smallest = dif
            h_best = h
    return h_best


from .Sha256NmcAuxPowChain import Sha256NmcAuxPowChain
from . import SCRIPT_TYPE_UNKNOWN
from ..deserialize import opcodes, match_decoded

NAME_NEW         = opcodes.OP_1
NAME_FIRSTUPDATE = opcodes.OP_2
NAME_UPDATE      = opcodes.OP_3

SCRIPT_TYPE_NAME_NEW = 7
SCRIPT_TYPE_NAME_FIRSTUPDATE = 8
SCRIPT_TYPE_NAME_UPDATE = 9

NAME_NEW_TEMPLATE = [NAME_NEW, opcodes.OP_PUSHDATA4, opcodes.OP_2DROP]
NAME_FIRSTUPDATE_TEMPLATE = [NAME_FIRSTUPDATE, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_2DROP, opcodes.OP_2DROP]
NAME_UPDATE_TEMPLATE = [NAME_UPDATE, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_2DROP, opcodes.OP_DROP]

class Namecoin(Sha256NmcAuxPowChain):
    """
    Namecoin represents name operations in transaction output scripts.
    """
    def __init__(chain, **kwargs):
        chain.name = 'Namecoin'
        chain.code3 = 'NMC'
        chain.address_version = '\x34'
        chain.magic = '\xf9\xbe\xb4\xfe'
        Sha256NmcAuxPowChain.__init__(chain, **kwargs)

    _drops = (opcodes.OP_NOP, opcodes.OP_DROP, opcodes.OP_2DROP)

    def parse_decoded_txout_script(chain, decoded):
        start = 0
        pushed = 0
        start = 0

        if match_decoded(decoded[0:len(NAME_NEW_TEMPLATE)], NAME_NEW_TEMPLATE):
            start = len(NAME_NEW_TEMPLATE)
            data = []
            script_type = SCRIPT_TYPE_NAME_NEW
        elif match_decoded(decoded[0:len(NAME_FIRSTUPDATE_TEMPLATE)], NAME_FIRSTUPDATE_TEMPLATE):
            start = len(NAME_FIRSTUPDATE_TEMPLATE)
            name = decoded[1][1]
            newtx_hash = decoded[2][1]
            value = decoded[3][1]
            data = [name, value, newtx_hash]
            script_type = SCRIPT_TYPE_NAME_FIRSTUPDATE
        elif match_decoded(decoded[0:len(NAME_UPDATE_TEMPLATE)], NAME_UPDATE_TEMPLATE):
            start = len(NAME_UPDATE_TEMPLATE)
            name = decoded[1][1]
            value = decoded[2][1]
            data = [name, value]
            script_type = SCRIPT_TYPE_NAME_UPDATE

        script_type2, data2 = Sha256NmcAuxPowChain.parse_decoded_txout_script(chain, decoded[start:])

        if start > 0:
            fullData = [[script_type2, data2]] + data
            return script_type, fullData
        else:
            return script_type2, data2

    datadir_conf_file_name = "namecoin.conf"
    datadir_rpcport = 8336


from sqlalchemy.sql import text
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String

engine = create_engine('sqlite:///college.db', echo=True)
meta = MetaData()

students = Table(
    'students', meta,
    Column('id', Integer, primary_key=True),
    Column('name', String),
    Column('lastname', String),
)

conn = engine.connect()

s = text("select students.name, students.lastname from students where students.name between :x and :y")
result = conn.execute(s, x='A', y='L').fetchall()

for row in result:
    print(row)


import requests
import tok
import exchange

token = tok.token

URL = 'https://api.telegram.org/bot' + token + '/'

global recent_update_id
last_update_id = 0

def get_updates():
    url = URL + 'getupdates'
    response = requests.get(url)
    return response.json()

def get_message():
  data = get_updates()

  last_object = data['result'][-1]
  current_update_id = last_object['update_id']

  global last_update_id
  if last_update_id != current_update_id:
    chat_id = last_object['message']['chat']['id']
    message_text = last_object['message']['text']

    message  ={'chat_id': chat_id, 'text': message_text}

    last_update_id = current_update_id
    return message
  else:
    return None

def send_message(chat_id, text = 'Wait a second, please'):
  url = URL + 'sendmessage?chat_id={}&text={}'.format(chat_id, text)
  requests.get(url)

def main():

  while True:
    answer  = get_message()
    if answer != None:
      chat_id = answer['chat_id']
      text = answer['text']

      if '/btc_usd' in text:
        send_message(chat_id, exchange.get_btc_usd())
      elif '/btc_eur' in text:
        send_message(chat_id, exchange.get_btc_eur())
    else:
      continue

if __name__ == '__main__':
    main()


#!/usr/bin/python3
"""hbtn header module"""
import urllib.request
import urllib.parse
import sys

if __name__ == "__main__":
    url = sys.argv[1]
    mail = {'email': sys.argv[2]}
    # encode the data in the standard
    data = urllib.parse.urlencode(mail).encode('ascii')
    # pass the encoded data to the request object
    req = urllib.request.Request(url, data)
    with urllib.request.urlopen(req) as response:
        print(response.read().decode('utf-8'))


arr = [1,2, 2, 2, 7,2,3,8,7,2]
arr.sort()
dups = []
for i in range(len(arr)):
    if arr[i - 1] == arr[i] and arr[i-1] not in dups:
        dups.append(arr[i])

print(len(dups))

number = input("Enter a number: ")
arr = []
while(number > 0):
    remainder = number % 10
    number -= remainder
    arr.append(remainder)
    number /= 10
print(arr)


import logging
from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler,MessageHandler,filters
from subprocess import STDOUT, check_output
import asyncio

logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.INFO
)
logger = logging.getLogger(__name__)

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("A python bot to be hacked,for example send \"print(1)\" to me")

async def help(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("A python bot to be hacked,for example send \"print(1)\" to me")

async def hack(cmd):
    try:
        result=check_output(["runasuser.exe","jail","jail","RestrictShutdown.exe",
        # absolute path is needed I dont know why
        r"C:\Users\54930\AppData\Local\Programs\Python\Python310\python.exe", "-c", cmd], stderr=STDOUT, timeout=5).decode("gbk")
    except Exception as e:
        result=str(e)

    return result

async def do_eval(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.message.from_user
    logger.info("%s %s %s: %s",user.first_name ,user.last_name,user.username, update.message.text)
    result = await hack(update.message.text)
    try:
        message=await context.bot.send_message(chat_id=update.effective_chat.id, text=result)
    except Exception as e:
        message=await context.bot.send_message(chat_id=update.effective_chat.id, text=str(e))

async def do_eval_group(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if "@catcatworm_bot" in update.message.parse_entities("mention").values():
        user = update.message.from_user
        logger.info("%s %s %s: %s",user.first_name ,user.last_name,user.username, update.message.text)
        result=await hack(update.message.text.replace("@catcatworm_bot",""))
        try:
            if len(result)>300:
                result=result[-300:]
            message=await context.bot.send_message(chat_id=update.effective_chat.id, text=result)
            await asyncio.sleep(10)
            await message.delete()
        except Exception as e:
            result=str(e)
            if len(result)>300:
                result=result[-300:]
            message=await context.bot.send_message(chat_id=update.effective_chat.id, text=result)
            await asyncio.sleep(10)
            await message.delete()

if __name__ == "__main__":
    token=""
    if token=="":
        token=input("please input your token:")
    application = ApplicationBuilder().token(token).build()
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("help", help))
    msg_handler = MessageHandler(filters.ChatType.PRIVATE, do_eval)
    grp_handler = MessageHandler(filters.ChatType.GROUPS & filters.Entity("mention"), do_eval_group)
    application.add_handler(msg_handler)
    application.add_handler(grp_handler)
    application.run_polling()


import time
import import_alarms

UserVoiceInput = "set an alarm for one two ten"#placeholder voice-interpreted text
UserVoiceInput = UserVoiceInput.lower()
VoiceArray = UserVoiceInput.split(" ")

hourList = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']

minuteMono = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
minutePrefix =['twenty','thirty','fourty','fifty']
minuteSuffix =['one', 'two', 'three', 'four', 'five', "six", "seven", "eight", "nine"]

finalHour=0
finalMinute=0

AMorPM = "PM" ###DEFAULT PLEASE CHANGE###

hour_detected = False

for word in range(0, len(VoiceArray)):
    print (VoiceArray[word])
    if VoiceArray[word] == 'AM':#
        AMorPM ="AM"#
    if VoiceArray[word] == 'PM':#The voice detection will likely not read these as AM or PM and as such they should be updated.
        AMorPM ="PM" #
    if hour_detected == False:
        for i in range (0, len(hourList)):
            if VoiceArray[word] == hourList[i]:
                hour_detected = True
                finalHour = i+1
    else:
        for i in range (0, len(minutePrefix)):
            if VoiceArray[word] == minutePrefix[i]:
                finalMinute+= 10*((i+2))
        for i in range (0, len(minuteSuffix)):
            if VoiceArray[word] == minuteSuffix[i]:
                finalMinute += i+1
        for i in range (0, len(minuteMono)):
            if VoiceArray[word] == minuteMono[i]:
                finalMinute = i + 10

alarm= [finalHour, finalMinute, AMorPM]

import_alarms.alarms_list.append(alarm)

write_data = open('import_alarms.py', 'w')
write_data.write("alarms_list=" + str(import_alarms.alarms_list))
write_data.close()

##CHECK ALARM##
for i in (0, len(import_alarms.alarms_list)-1):
    for x in (0, len(import_alarms.alarms_list[i])):
        if import_alarms.alarms_list[i][2] == 'AM':
            if int(time.strftime("%H"))==import_alarms.alarms_list[i][0] and int(time.strftime("%M"))==import_alarms.alarms_list[i][1]:
                print("alarm is sounding")
        else:
            if int(time.strftime("%H")) - 12 ==import_alarms.alarms_list[i][0] and int(time.strftime("%M"))==import_alarms.alarms_list[i][1]:
                print("alarm is sounding")


"""New Migration

Revision ID: d18be0fb8ef4
Revises: 1a469a37607f
Create Date: 2023-07-03 20:24:50.355260

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'd18be0fb8ef4'
down_revision = '1a469a37607f'
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index('ix_phone_contacts_id', table_name='phone_contacts')
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_index('ix_phone_contacts_id', 'phone_contacts', ['id'], unique=False)
    # ### end Alembic commands ###


import json
import jieba
import pandas as pd

filter_map = ['。','，','、','；','：','（','）','(',')','.','-',' ','\u3000','—','副','任','其间','成员','兼','中国','国家','工作','司','省','和','专业','学习','系','在','十九']

def output(arr):
    with open("frequency.json","w") as f:
        json.dump(arr,f)

# JSON.stringfy add \ and " to json, while python didn't accept them
def wash(input):
    output = input.strip('" ').replace('\\','').replace("null,",'')
    return output

if __name__ == "__main__":
    with open("exps.json","r",encoding="utf8") as f:
        data = json.loads(wash(f.read()))
    print(len(data))
    seg_list = []
    for row in data:
        seg_list.extend(jieba.cut(row))
    seg_list = list(filter(lambda x: x not in filter_map, seg_list))
    seg_list = list(map(lambda x: {'text':x,'value':1}, seg_list))
    dfSg = pd.DataFrame(seg_list)
    dfWord = dfSg.groupby('text')['value'].sum()
    dfWord.sort_values(inplace=True,ascending=False)
    result = dfWord.iloc[0:50].to_dict()
    result = list(map(lambda k: {'text':k, 'value':result[k]}, result))
    print(result)
    output(result)


import pathlib
from setuptools import setup, find_packages

package_name = 'UniFuncNet'

def get_package_version():
    import os
    from sys import platform
    if platform.startswith('win'):
        SPLITTER = '\\'
    else:
        SPLITTER = '/'

    dir_name = os.path.dirname(os.path.abspath(__file__))
    init_path = f'{dir_name}{SPLITTER}{package_name.lower()}{SPLITTER}__init__.py'
    package_version = None
    with open(init_path) as file:
        for line in file:
            if '__version__' in line:
                package_version = line.replace('__version__', '')
                package_version = package_version.strip('\n')
                package_version = package_version.strip()
                package_version = package_version.strip('=')
                package_version = package_version.strip()
                package_version = package_version.strip('"')
                package_version = package_version.strip('"')
    return package_version

# The directory containing this file
HERE = pathlib.Path(__file__).parent

# The text of the README file
README = (HERE / "README.md").read_text(encoding='utf-8')

long_description = 'UniFuncNet is network annotation tool that integrates multiple biological databases into one composite output.'

setup(
    name=package_name,
    version=get_package_version(),
    author="Pedro Queirós",
    author_email="pdqueiros@gmail.com",
    description="Biological network annotation tool.",
    long_description=long_description,
    long_description_content_type='text/markdown',
    url="https://github.com/PedroMTQ/UniFuncNet",
    project_urls={
        "Bug Tracker": "https://github.com/PedroMTQ/UniFuncNet/issues",
    },
    packages=find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    license="MIT",
    install_requires=['requests', 'beautifulsoup4', 'lxml'],
    entry_points={
        "console_scripts": [
            "unifuncnet=unifuncnet.__main__:main",
        ],
    },
)


'''Day 21 of python

'''
#default arguments for a function
'''def average(a=1,b=2):
    print((a+b)/2)

average()

'''

#arbitary arguments

def average(*numbers):
    sum=0
    for i in numbers:
        sum = sum + i
    return sum/len(numbers)

c= average(1,2,4,5)

print(c)


# 문제 설명
# 행렬의 덧셈은 행과 열의 크기가 같은 두 행렬의 같은 행, 같은 열의 값을 서로 더한 결과가 됩니다.
# 2개의 행렬 arr1과 arr2를 입력받아, 행렬 덧셈의 결과를 반환하는 함수, solution을 완성해주세요.

# 제한 조건
# 행렬 arr1, arr2의 행과 열의 길이는 500을 넘지 않습니다.
# 입출력 예
# arr1	arr2	return
# [[1,2],[2,3]]	[[3,4],[5,6]]	[[4,6],[7,9]]
# [[1],[2]]	[[3],[4]]

arr1 = [[3,4,5],[5,6,7]]
arr2 = [[4,5,6],[7,8,9]]

# print(arr1[0][1]+arr1[0][1])   # 4+4 = 8
print(arr1[0][1])   # 4 //0번째 행에서 1번째열

def solution(arr1,arr2) :
    answer = [[]for x in range(len(arr2))]  # 세로크기
    for i in range(len(arr1)) :         #가로크기
        for j in range(len(arr1[i])) :
            answer[i].append(arr1[i][j] + arr2[i][j])
    return answer

print(solution(arr1,arr2))

# 다른 사람 풀이

def sumMatrix(A,B):
    answer = [[c + d for c, d in zip(a, b)] for a, b in zip(A,B)]
    return answer

# 아래는 테스트로 출력해 보기 위한 코드입니다.
print(sumMatrix([[1,2], [2,3]], [[3,4],[5,6]]))

프로그래머스/간단한문제/행렬의덧셈.py


import random
from tqdm import tqdm
import numpy as np
from glob import glob
import csv
import copy
import argparse
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import Config

parser = argparse.ArgumentParser()
parser.add_argument('--dataset', type=str, default='gcc430')
parser.add_argument('--loop_time', type=int, default=100)
args = parser.parse_args()
print(args)

loop_time = args.loop_time
tested_compiler = args.dataset
dis_base_url = './distances/' + tested_compiler + '/'
res_csv = './results/' + tested_compiler + '.csv'

compiler = Config.datasets[tested_compiler]
topn = compiler.n
names = compiler.names
missing_tc = compiler.missing_tc
bug_num = compiler.bug_num
COUNT = compiler.COUNT - len(missing_tc)
rev_url = compiler.rev_url

name2id = {}
id2name = {}
with open(names, 'r') as f:
    for index, line in enumerate(f):
        name = line.strip().split('/')[-1].split('.')[0]
        name2id[name] = index
        id2name[index] = name

def FPF(distance_matrix):
    tag = np.zeros(COUNT + len(missing_tc))
    # missing tc start
    tc_ids = []
    start = random.randint(0, COUNT - 1)
    while True:
        if id2name[start] not in missing_tc:
            tc_ids = [start]
            break
        else:
            start = random.randint(0, COUNT - 1)
    # # origin start
    # start = random.randint(0, COUNT - 1)
    # tc_ids = [start]
    tag[start] = 1
    dis = copy.deepcopy(distance_matrix[start])
    while len(tc_ids) < COUNT:
        choice = np.argmax(dis)
        if tag[choice] == 1:
            remain_candidate = [i for i, x in enumerate(dis) if tag[i] == 0 and id2name[i] not in missing_tc]
            # random.shuffle(remain_candidate)
            tc_ids.extend(remain_candidate)
            break

        if id2name[int(choice)] in missing_tc:
            dis[choice] = 0
            tag[choice] = 1
            continue
        mask = distance_matrix[choice] < dis
        dis[mask] = copy.deepcopy(distance_matrix[choice][mask])
        tc_ids.append(choice)
        dis[choice] = 0
        tag[choice] = 1
    return tc_ids

def random_tc():
    tc_ids = list(range(0, COUNT + len(missing_tc)))
    for i in missing_tc:
        tc_ids.remove(name2id[i])
    random.shuffle(tc_ids)
    return tc_ids

def get_bug_map():
    file_list = glob(rev_url)
    bug_map = {}
    for file in file_list:
        with open(file, 'r') as f:
            contents = f.read()
            if '#' in contents:
                contents = contents.split('#')[2]
            name = file.split('/')[-1].split('.')[0]
            if name in name2id.keys():
                bug_map[name] = contents
            # bug_map[file.split('/')[-1].split('.')[0]] = f.read()
    return bug_map

def form_trigger(tc_ids, bug_map):
    bug_list = []
    nums_list = []
    flag = False
    for index, tc_id in enumerate(tc_ids):
        if flag:
            return nums_list
        tc_name = id2name[tc_id]
        bug_id = bug_map[tc_name]
        if bug_id not in bug_list:
            nums_list.append(index + 1)
            if len(set(bug_list)) == bug_num:
                # print("All bugs revealed    ====>   {}".format(index))
                flag = True
        bug_list.append(bug_id)
    return nums_list

def triggered_bugs(tc_ids, bug_map):
    bug_list = []
    num = 0
    bug_id = 0
    nums_list = []
    exist = []
    flag = False
    for index, tc_id in enumerate(tc_ids):
        if flag:
            bug_list.append((id2name[tc_id], bug_id))
            exist.append(bug_id)
            nums_list.append(num)
            continue
        # try:
        tc_name = id2name[tc_id]
        bug_id = bug_map[tc_name]
        if bug_id not in exist:
            bug_list.append((id2name[tc_id], bug_id))
            num = num + 1
            if num == bug_num:
                # print("All bugs revealed    ====>   {}".format(index))
                flag = True
        bug_list.append((id2name[tc_id], bug_id))
        exist.append(bug_id)
        nums_list.append(num)
        # except:
        #     print(tc_id)
    # print(bug_list)
    return np.array(nums_list)
    # return bug_list, np.array(nums_list)

def max_min_normalize(x):
    min_mask = x < 0.0001
    x[min_mask] = 0
    x = (x - np.min(x)) / (np.max(x) - np.min(x))
    return x

def plus(x, y):
    x = max_min_normalize(x)
    y = max_min_normalize(y)

    m1 = np.mean(x)
    m2 = np.mean(y)
    r = x + (y * (m1 / m2))
    return r

def write_result_table(reses, names):
    path = res_csv
    bugs = ['']
    for b in range(1, bug_num + 1):
        bugs.append(str(b))
    with open(path, 'w') as f:
        csv_write = csv.writer(f)
        csv_write.writerow(['APP.', 'Bug number'])
        csv_write.writerow(bugs)
        for i, name in zip(reses, names):
            t = [name]
            for j in range(0, len(i)):
                t.append(i[j] / loop_time)
            csv_write.writerow(t)

if __name__ == '__main__':
    bug_map = get_bug_map()
    # print(bug_map)

    program_dis = np.load(dis_base_url + 'program.npy')
    opt_dis = np.load(dis_base_url + 'opt.npy')
    coverage_dis = np.load(dis_base_url + 'coverage.npy')

    tamer_dis = np.load(dis_base_url + 'tamer.npy')

    total_dis = plus(plus(program_dis, coverage_dis), opt_dis)

    ablation1_dis = plus(program_dis, coverage_dis)
    ablation2_dis = plus(coverage_dis, opt_dis)
    ablation3_dis = plus(program_dis, opt_dis)

    total_num = np.zeros(COUNT)
    total_tc_num = np.zeros(bug_num)

    ab_num1 = np.zeros(COUNT)
    ab_num2 = np.zeros(COUNT)
    ab_num3 = np.zeros(COUNT)

    tc_ab_num1 = np.zeros(bug_num)
    tc_ab_num2 = np.zeros(bug_num)
    tc_ab_num3 = np.zeros(bug_num)

    tamer_num = np.zeros(COUNT)
    tamer_tc = np.zeros(bug_num)

    transformer_num = np.zeros(COUNT)
    transformer_tc = np.zeros(bug_num)

    for i in tqdm(range(0, loop_time)):
        total_num = total_num + triggered_bugs(FPF(total_dis), bug_map)
        total_tc_num = total_tc_num + form_trigger(FPF(total_dis), bug_map)

        ab_num1 = ab_num1 + triggered_bugs(FPF(ablation1_dis), bug_map)
        tc_ab_num1 = tc_ab_num1 + form_trigger(FPF(ablation1_dis), bug_map)

        ab_num2 = ab_num2 + triggered_bugs(FPF(ablation2_dis), bug_map)
        tc_ab_num2 = tc_ab_num2 + form_trigger(FPF(ablation2_dis), bug_map)

        ab_num3 = ab_num3 + triggered_bugs(FPF(ablation3_dis), bug_map)
        tc_ab_num3 = tc_ab_num3 + form_trigger(FPF(ablation3_dis), bug_map)

        tamer_num = tamer_num + triggered_bugs(FPF(tamer_dis), bug_map)
        tamer_tc = tamer_tc + form_trigger(FPF(tamer_dis), bug_map)

        rad = random_tc()
        transformer_num = transformer_num + triggered_bugs(rad, bug_map)
        transformer_tc = transformer_tc + form_trigger(rad, bug_map)

    # write wasted effort result into csv file
    improve1 = ((tamer_tc - total_tc_num) / tamer_tc) * 100
    improve2 = ((transformer_tc - total_tc_num) / transformer_tc) * 100
    reses = [tc_ab_num1, tc_ab_num2, tc_ab_num3, tamer_tc, transformer_tc, total_tc_num, improve1, improve2]
    names = ['$D3_{noO}$', '$D3_{noP}$', '$D3_{noC}$', '$Tamer$', '$Transformer$',
             '$D3$', '\\Uparrow $Im_{Tamer}(\%)$', '\\Uparrow $Im_{Transformer}(\%)$']
    write_result_table(reses, names)

    # calculate theoretical best RAUC
    theoretical_best = np.zeros(COUNT)
    if topn < bug_num:
        theoretical_best = list(range(1, topn))
    else:
        theoretical_best = list(range(1, bug_num + 1))
        for i in range(bug_num + 1, topn + 1):
            theoretical_best.append(bug_num)
    best_auc = np.trapz(theoretical_best)
    theoretical_best = np.array(theoretical_best) * loop_time

    # discovery curve & R-AUC value
    label_font = {'family': 'Times New Roman',
                  'weight': 'normal',
                  'size': 18,
                  }
    legend_font = {'family': 'Times New Roman',
                   'weight': 'normal',
                   'size': 20,
                   }
    plt.figure(figsize=(14, 9))
    ax = plt.gca()
    y_major_locator = MultipleLocator(1)
    ax.yaxis.set_major_locator(y_major_locator)
    plt.yticks(fontproperties='Times New Roman', fontsize=20)  # 设置大小及加粗
    plt.xticks(fontproperties='Times New Roman', fontsize=20)
    plt.xlabel('Number of test failures', label_font)
    plt.ylabel('Number of unique bugs', label_font)
    plt.tick_params(labelsize=18)
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    [label.set_fontname('Times New Roman') for label in labels]
    plt.grid(b=True, axis='y', linestyle='--', color='gray', alpha=0.6)  # 只显示x轴网格线

    lists = [total_num[:topn], tamer_num[:topn], transformer_num[:topn]]
    types = ['D3', 'Tamer', 'Transformer']
    line_style = ['-', '--', ':', '-.']
    markers = ['*', 's', '^', '*']
    colors = ['#FA7F6F', '#8ECFC9', '#82B0D2', '#82B0D2']

    for num, t, s, m, c in zip(lists, types, line_style, markers, colors):
        num = num / loop_time
        num = num[:topn]
        auc = np.trapz(num)
        rauc = auc / best_auc
        rauc = str(rauc * 100)[0:5] + '%'
        num = np.insert(num, 0, 0)
        plt.plot(num, label=t + ' ' + '(APFD: ' + rauc + ')', ls=s, color=c, lw=2.8)
        print(t + ': ' + '(APFD: ' + rauc + ')')
        plt.legend(prop=legend_font)
    plt.show()


import logging
import json

from handlers.base import BaseHandler

from get_sql import get_course_list
from ParseGameObject import Parser

class EvaluateHandler(BaseHandler):  # 继承base.py中的类BaseHandler
    def post(self):
        data = self.request.body.decode('utf-8')
        print(data)
        g_data = json.loads(data)
        table_id = g_data["table_id"]
        course_id = g_data["course_id"]
        logging.info("课程id：%s, 课程表名：%s" % (course_id, table_id))
        if not (table_id and course_id):
            self.return_data = {"code": 400, "msg": "错误的课程信息", "data": ""}
            self.write(self.return_data)

        report = Parser()
        course_content = get_course_list(table_id)
        if course_content:
            get_report, msg = report.ParseGame(course_content, course_id)
            print(get_report)
            if get_report:
                logging.info(get_report)
                self.return_data["data"] = get_report
            else:
                self.return_data["code"] = 400
                self.return_data["msg"] = f"{msg}, 请联系管理员"
            self.write(self.return_data)
        else:
            self.return_data = {"code": 400, "msg": "错误的课程信息", "data": ""}
            self.write(self.return_data)


import praw
import psycopg2
import re

conn = psycopg2.connect("dbname=nick user=nick")
cur = conn.cursor()
conn.set_client_encoding('UTF8')

file = open("comments.csv","w+")

cur.execute('SELECT subreddit, body FROM comments')
r = re.compile(r"\s+")

num = 0
delimeter = " ////////######## "

while(num < 300,000):
	num += 1
	line = cur.fetchone()
	subreddit = line[0]
	comment = line[1]
	comment = r.sub(" ", comment)
	file.write(str(num) + delimeter + subreddit + delimeter + comment + "\n")

file.close()
cur.close()
conn.close()


from django.shortcuts import get_object_or_404, render
from django.utils import timezone
from .models import Post
from .forms import PostForm, NamuForm
from django.shortcuts import redirect
import csv
from django.http import HttpResponse
from .resources import PostResource
import requests
from bs4 import BeautifulSoup
import pandas as pd
from tablib import Dataset

#views에 있는 함수는 다음의 둘중 하나를 한다. 요청된 페이지를 담고 있는 HttpResponse객체를 반환하거나, Http404같은 예외를 발생시키거나
#그래서 return render(request, '특정html파일', optional=context)이라고 반환하는것, 즉 특정html모양으로 그려라(render)
#def 함수이름(request): return HttpResponse("
hello world
") 기본 모양
#꿀팁 : 헷갈리니까 함수명 자체를 _view라고 붙여라

def post_list(request):
    querry_set = Post.objects.all()                                         #1)qs(쿼리셋) = Post.objecs.all()이라고 ORM 명령어를 이용해서 DB에서 가져온 Post 클래스로 만든 데이터를 리스트 형태로 qs라는 변수에 저장함
    querry_set = querry_set.filter(published_date__lte=timezone.now())     #2)앞에서 가져온 리스트에 필터를 걸어서 현재 시각 이전에 작성된 것만 리스트를 추림
    querry_set = querry_set.order_by('-published_date')                    #3)마지막으로 정렬방식을 개시일을 기준으로 최신순으로 오름차순 정렬한 것을 qs라는 변수에 넣어줌

                         #models에서 만든 Post 클래스를 불러오고 해당 클래스가 만든 모든 객체중에 필터를 걸고 정렬
                                                           #위의 qs(쿼리셋)는 이거를 쪼갠거  Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request = request, template_name = 'blog/post_list.html', context = {'post_list' : querry_set,})

#***context의 목적*****
#여기서 request를 넣고, html주소를 넣고 마지막으로 post_list는 앞에서 정의한 쿼리셋이다 라고 딕셔너리를 만들었음
#이 딕셔너리 혹은 context를 활용해서 blog/post_list.html에서 for루프로 render(화면에 띄워줄)하려는 목적으로, 이제 좀 감이 잡힘
#중요!!!! : {key:value}로 딕셔너리 형태로 만든걸 context라고 함. html에서도 사용한바 있음. 즉 {{ request.user }}에서 문맥에 따라 내용이 바뀜
#그래서 위의 함수에서 {'post_list' : qs,}라고 써놓고, blog/post_list.html에서 {{ post_list }}라고 context를 넣어준것.
#정확하게는 그 이후에 {{ for post in post_list }}라고 넣어줌.즉 포스트 리스트가 list type이므로 for문으로 하나씩 꺼내준 것.
#이걸 왜 아무도 안 가르쳐줌...

def post_detail(request, pk):
    try:
        post = Post.objects.get(pk=pk)    #ORM으로 pk를 get했음.,,,, 보통 함수의 괄호 안에 aa=bb라고 쓰는건 해당 함수에서 쓰는 타입을 정하는거(commit=false)처럼
    except Post.DoesNotExist:
        raise Http404                 # 위의 내용을 단축해서 쓰면 post = get_object_or_404(Post, pk=pk) ==> 다이내믹 url
    return render(request = request, template_name= 'blog/post_detail.html',context= {'post' : post,})

#여기서 id로 바꾸고 템플릿에서도 id로 바꿔서 돌려봐도 동일하게 작동함
#위에서 post 변수에 Post.objects.get(pk=pk)라고 정의 했으므로
#밑의 context에서 'post'를 템플릿에 {{ post }}로 띄울때 각 페이지의 고유 포스트를 띄울 수 있게 된다!!!!
#즉, detali 템플릿에 가면 {% url "post_detail" post.pk %}이라고 써있다. 여기서 장고가 자동으로 만든 pk라는 고유값(id같은것)으로 불러온다는 의미
#id는 파이썬이 만든거고 pk는 장고가 만든건데 그냥 pk써라라고 스택오버플로우에서 알랴줌 https://stackoverflow.com/questions/2165865/django-queries-id-vs-pk
#장고걸스 중 "pk = post.pk이란 무엇일까요? pk는 "데이터베이스의 각 레코드를 식별"하는 기본키(Prmiary Key)의 줄임말 입니다.
#Post 모델에서 기본키를 지정하지 않았기 때문에 장고는 pk라는 필드를 추가해 새로운 블로그 게시물이 추가될 때마다 그 값이 1,2,3 등으로 증가하게 됩니다.
#Post 객체의 다른 필드 (제목, 작성자 등)에 액세스하는 것과 같은 방식으로 post.pk를 작성하여 기본 키에 액세스합니다
#post.pk를 써서 기본키에 접근할 수 있고 같은 방법으로 Post객체내 다른 필드(title, author)에도 접근할 수 있습니다!""

#render는 django.shortcuts 패키지에 있는 함수로서 첫번째 파라미터로 request를, 그리고 두번째 파라미터로 템플릿을,
#세번째로 context를 받는다. 말 그대로 문맥에 맞게 보여주겠다는 뜻.... 이걸 왜 아무도 안 가르쳐주지??

def post_new(request):
    if request.method == "POST":
        my_form = PostForm(request.POST)
        if my_form.is_valid():
            print(my_form.cleaned_data)
            post = my_form.save(commit=False)       # DB에 바로 저장은 하지 않고 post변수에만 저장한 후에, post를 나중에 저장
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        my_form = PostForm()                             #request의 method가 POST가 아니면 my_form에 빈PostForm을 넣어라, 즉 비워라
    return render(request = request, template_name= 'blog/post_edit.html', context = {'my_form': my_form})

#{'앞의 form은 html에 있는 값':뒤에 my_form은 변수 } 다이내믹하게 보여주려고

#r여기서 save는 post.objects.create와 동일함.

def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)         #수정하는 기능이니까 처음부터 특정글의 정보인 pk가 필요함/이른바 다이내믹 url이라서 get_object_or_404
    if request.method == "POST":
        my_form = PostForm(request.POST, instance=post)
# instance=post를 넣으면 기존 instace를 업데이트하고, 저걸 안 쓰면 새로 instance를 하나 만든다 그래서 post_new에는 없다
        if my_form.is_valid():
            post = my_form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        my_form = PostForm(instance=post)
    return render(request = request, template_name= 'blog/post_edit.html', context={'my_form' : my_form,}) #다이내믹!!!

def post_remove(request, pk):
    post = get_object_or_404(Post, pk=pk)   #다이내믹 url
    post.delete()                           #if request.method == "POST":를 쓰고 싶은데 안 지워짐. post.delete() 하는건 GET리퀘스트라고 하네? 다음 기회에....
    return redirect('post_list')

def export_posts_excel(request):
    post_resource = PostResource()
    dataset = post_resource.export()
    response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel')
    response.write(u'\ufeff'.encode('utf8'))
    response['Content-Disposition'] = 'attachment; filename="posts_all.xls"'
    return response

def post_import(request):
    if request.method == 'POST':
        post_resource = PostResource()
        dataset = Dataset()
        new_posts = request.FILES['myfile']
        imported_data = dataset.load(new_posts.read())
        result = post_resource.import_data(dataset, dry_run=True)  # Test the data import

        if not result.has_errors():
            post_resource.import_data(dataset, dry_run=False)  # Actually import now

    return render(request, 'blog/post_import.html')

#NamuForm은 장고의 models.Form 클래스를 상속받은 클래스이므로 장고 Form클래스가 받는 인수인 request.GET을 받아서 부모클래스의 특성대로 인스턴스를 만들어
#search라는 인스턴스를 생성함

def namu_search_view(request):
    search = NamuForm(request.GET)
    if search.is_valid():
            url = 'https://www.namu.wiki/w/' + str(search.cleaned_data.get('search'))
            res = requests.get(url)
            soup = BeautifulSoup(res.content, 'html.parser')
            wikiLinkInt = soup.select('.wiki-link-internal')
            search = []
            for link in wikiLinkInt:
                thTitle = link.get('title')
                thRef = 'http://namu.wiki' + link.get('href') #주소가 특수문자로 나오는데 한글로 하면 오류남
                hyperlink = '' + thTitle + ''
                search.append( hyperlink )
    return render(request = request, template_name= 'blog/namu_search.html', context= { 'search' : search })

#requests모듈로 스크래핑을 하면서 parameter를 넣어서 GET메소드로 보내보고
#params = {'param1': 'value1', 'param2': 'value'} res = requests.get(URL, params=params)
#res.url명령어를 넣어보면 https://www.tistory.com/?param1=value1&param2=value 검색어를 url주소에 넣어서 같이 보내는것
#https://dgkim5360.tistory.com/entry/python-requests 이 사이트에서 설명해줌
#이제 되냐....???
#search = myNamuLink라고 해야됨!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

'''
cfe에서는 view에 있는 함수들을 아래와 같이 통일함. 깔끔해짐
def 함수이름_view(request, id(필요할경우))
    변수명 = 함수 or 쿼리셋
    context = {
        "html에서 쓸 이름" : 변수명
    }
#return render(request, "이동할주소.html", context)
'''


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import cluster
from sklearn.cluster import KMeans
from sklearn.metrics import confusion_matrix

f1_score = []
r = []
for i in range(0,500,50):
    #乱数の作成
    np.random.seed(0)
    array1 = np.random.normal(0,1,(10000,3))
    array2 = np.random.normal(0,1,(10000,3))
    array3 = np.random.normal(0,24,(1,3))
    array4 = np.random.normal(0,24,(i,3))
    array2[:i] = array2[:i] + array4
    array2[i:501] = array2[i:501] + array3
    experiment = array2
    #実験群をデータフレーム化
    target = pd.DataFrame(np.zeros(10000))
    target[:500] = 1
    target[501:] = 0
    df_experiment = pd.DataFrame(experiment)
    df_experiment["target"] = target

    #e = cluster.KMeans(n_clusters=2,random_state=0)
    #e.fit(experiment)

    np.random.seed(1)
    array1_1 = np.random.normal(0,1,(10000,3))
    array2_1 = np.random.normal(0,1,(10000,3))
    array3_1 = np.random.normal(0,24,(1,3))
    array4_1 = np.random.normal(0,24,(i,3))
    array2_1[:i] = array2_1[:i] + array4_1
    array2_1[i:501] = array2_1[i:501] + array3_1
    experiment_1 = array2_1
    #実験群をデータフレーム化
    target_1 = pd.DataFrame(np.zeros(10000))
    target_1[:500] = 1
    target_1[501:] = 0
    df_experiment_1 = pd.DataFrame(experiment_1)
    df_experiment_1["target"] = target_1
    X2 = df_experiment_1
    y2 = df_experiment_1["target"]

    pre = KMeans(n_clusters=2,random_state=0).fit_predict(df_experiment_1)
    predict = []
    for j in pre:
        predict.append(j)
    matrix = confusion_matrix(df_experiment_1["target"].values.tolist(), predict)
    print(matrix)

    #Fスコア計算
    TP = matrix[1,1]
    FP = matrix[0,1]
    FN = matrix[1,0]
    P = TP + FN
    precision = TP / (TP + FP)
    recall = TP / P
    F1 = 2 / (1 / precision + 1 / recall)
    print(F1)
    f1_score.append(F1)
    r.append(i)

plt.scatter(r,f1_score)
plt.show()


import pyautogui
from pyautogui import keyboard

# mouse 控制
LIST_RECORDER = []

AAA = []

def abc(xxx):
    a = keyboard.KeyboardEvent('down', 28, 'enter')
    if xxx.event_type == 'down' and xxx.name == a.name:
        x, y = pyautogui.position()
        LIST_RECORDER.append((x, y))
        AAA.append(1)
        print("你按下了enter键")
        print(f"已经记录坐标位置:  {x}, {y}")
        alert(text=f'已经记录坐标位置:  {x}, {y}', title='ding', button='OK')
try:
    while True:
        keyboard.hook(abc)
        keyboard.wait()
except KeyboardInterrupt:
    for n, i in enumerate(LIST_RECORDER):
        x, y = i
        pyautogui.click(x=x, y=y)
        time.sleep(AAA[n])
    alert(text=f'您已完成全部设定课程, Nice!', title='ding', button='OK')


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

# N을 K로 나누었을 때, 나누어 떨어지면 실행

# 나누어 떨어지지 않으면 -1

# result는 연산을 하는 총 횟수
result = 0

while True:
    # n이 k로 나누어 떨어지지 않을 때, 가장 가까운 k로 나누어 떨어지는 수가 무엇인지 찾고자 할 때 사용
    # n이 k로 나누어 떨어지는 수가 될 때까지 빼기
    target = (n // k) * k
    result += (n - target)
    n = target
    # n이 k보다 작을 때 (더 이상 나눌 수 없을 때) 반복문 탈출
    if n < k:
        break
    # k로 나누기
    result += 1
    n //= k

result += (n - 1)
print(result)


import discord

from discord.ext import commands
from typing import Any, Dict, List, Optional

from .enums import Source

__all__: tuple = (
    'Track',
    'Playlist'
)

class Track:
    """
    Represents an obsidian song track.

    Parameters
    ----------
    id: str
        The base 64 track ID.
    info: Dict[str, Any]
        The raw JSON payload returned by Obsidian,
        containing information about this track.
    ctx: Optional[:class:`commands.Context`]
        An optional context to use for this track.
        By default, if this is provided, :attr:`Track.requester` will be the author of the context.
    kwargs
        Extra keyword arguments to pass into the constructor.
    """

    __slots__: tuple = (
        '_id',
        '_ctx',
        '_requester',
        '_title',
        '_author',
        '_uri',
        '_identifier',
        '_length',
        '_position',
        '_is_stream',
        '_is_seekable',
        '_source',
        '_thumbnail'
    )

    def __init__(self, *, id: str, info: Dict[str, Any], ctx: Optional[commands.Context] = None, **kwargs) -> None:
        self._ctx: Optional[commands.Context] = ctx
        self._requester: Optional[discord.Member] = kwargs.get('requester') or (ctx.author if ctx else None)

        self._id: str = id
        self._uri: str = info['uri']
        self._title: str = info['title']
        self._author: str = info['author']
        self._length: int = info['length']
        self._position: int = info['position']
        self._is_stream: bool = info['is_stream']
        self._identifier: str = info['identifier']
        self._is_seekable: bool = info['is_seekable']
        self._source: Source = Source(info['source_name'])
        self._thumbnail: Optional[str] = info.get('thumbnail')

    def __repr__(self) -> str:
        return f'<Track title={self._title!r} uri={self._uri!r} source={self.source!r} length={self._length}>'

    @property
    def id(self) -> str:
        """
        str: The Base64 Track ID, can be used to rebuild track objects.

        See Also
        --------
        :meth:`.Node.decode_track`
        """
        return self._id

    @property
    def ctx(self) -> Optional[commands.Context]:
        """
        Optional[:class:`~discord.ext.commands.Context`]: The :class:`~discord.ext.commands.Context`
        that invoked the track. Could be `None` .
        """
        return self._ctx

    @property
    def title(self) -> str:
        """
        str: The track title.
        """
        return self._title

    @property
    def author(self) -> str:
        """
        str: The author of the track.
        """
        return self._author

    @property
    def uri(self) -> str:
        """
        str: The track's URI.
        """
        return self._uri

    @property
    def identifier(self) -> str:
        """
        str: The tracks identifier.
        """
        return self._identifier

    @property
    def length(self) -> int:
        """
        int: The duration of the track in milliseconds.
        """
        return self._length

    @property
    def position(self) -> int:
        """
        int: The current position of the track in milliseconds.
        """
        return self._position

    @property
    def stream(self) -> bool:
        """
        bool: Whether the track is a stream or not.
        """
        return self._is_stream

    @property
    def seekable(self) -> bool:
        """
        bool: If you are able to seek the track's position or not.
        """
        return self._is_seekable

    @property
    def source(self) -> Source:
        """
        :class:`Source`: Return an |enum_link| indicates the type of the :class:`.Source` .
        """
        return self._source

    @property
    def thumbnail(self) -> str:
        """
        str: Return the image URL of the track's thumbnail, could be an empty :class:`str` depending on the :class:`.Source` .
        """
        if self.source is Source.YOUTUBE:
            return f'https://img.youtube.com/vi/{self.identifier}/hqdefault.jpg'

        if self._thumbnail:
            return self._thumbnail

        return ''

    @property
    def requester(self) -> Optional[discord.Member]:
        """
        Optional[:class:`discord.Member`]: The :class:`discord.Member` that requested the track.
        """
        return self._requester

    @ctx.setter
    def ctx(self, ctx: commands.Context) -> None:
        """
        A utility `function` for changing the :attr:`ctx`.
        """
        self._ctx = ctx

    @requester.setter
    def requester(self, requester: discord.Member) -> None:
        """
        A utility `function` for changing the :attr:`requester`.
        """
        self._requester = requester

class Playlist:
    """
    Represents a playlist of tracks.
    """

    def __init__(
            self,
            *,
            info: Dict[str, Any],
            tracks: List[Dict[str, Any]],
            ctx: Optional[commands.Context] = None,
            cls: type = Track,
            **kwargs
    ) -> None:
        self._ctx: Optional[commands.Context] = ctx
        self._requester: Optional[discord.Member] = kwargs.get('requester') or (ctx.author if ctx else None)

        self._name: str = info['name']
        self._tracks: List[Dict[str, Any]] = tracks
        self._selected_track: int = info.get('selected_track', 0)

        self._uri: Optional[str] = info.get('uri')

        self.__track_cls: type = cls
        self.__constructed_tracks: Optional[List[Track]] = None
        self.__kwargs = kwargs

    @property
    def __track_kwargs(self) -> Dict[str, Any]:
        return {
            **self.__kwargs,
            'requester': self._requester
        }

    @property
    def count(self) -> int:
        """
        int: Return the total amount of tracks in the playlist.
        """
        return len(self._tracks)

    @property
    def tracks(self) -> List[Track]:
        """
        List[Track]: Return a `list` of :class:`Track` s.
        """
        if self.__constructed_tracks is not None:
            return self.__constructed_tracks

        self.__constructed_tracks = res = [
            self.__track_cls(id=track['track'], info=track['info'], ctx=self.ctx, **self.__track_kwargs)
            for track in self._tracks
        ]
        return res

    @property
    def ctx(self) -> Optional[commands.Context]:
        """
        Optional[:class:`~discord.ext.commands.Context`]: The :class:`~discord.ext.commands.Context`
        that invoked the playlist. Could be `None` .
        """
        return self._ctx

    @property
    def name(self) -> str:
        """
        str: The name of the playlist.
        """
        return self._name

    @property
    def selected_track(self) -> Optional[Track]:
        """
        The selected track returned by Obsidian, could be `None` .
        """
        try:
            return self.tracks[self._selected_track]
        except IndexError:
            return self.tracks[0]

    @property
    def uri(self) -> Optional[str]:
        """
        str: The playlist's URI.
        """
        return self._uri

    @property
    def source(self) -> Source:
        """
        :class:`.Source`: Return an |enum_link| indicates the type of the :class:`.Source` .
        """
        try:
            return self.tracks[0].source
        except (IndexError, KeyError):
            return Source.YOUTUBE

    @property
    def requester(self) -> Optional[discord.Member]:
        """
        Optional[:class:`discord.Member`]: The :class:`discord.Member` that requested the playlist.
        """
        return self._requester

    @requester.setter
    def requester(self, requester: discord.Member) -> None:
        """
        A utility `function` for changing the :attr:`requester`.
        """
        self._requester = requester

    @ctx.setter
    def ctx(self, ctx: commands.Context) -> None:
        """
        A utility `function` for changing the :attr:`ctx`.
        """
        self._ctx = ctx

    def __iter__(self) -> iter:
        return iter(self._tracks)

    def __len__(self) -> int:
        return self.count

    def __repr__(self) -> str:
        return f'<Playlist name={self._name!r} selected_track={self.selected_track} count={len(self._tracks)}>'


from flask import jsonify, request

from app import app
from app import controller

@app.route("/")
def index():
    return "
Hello to Jobs Finder!
"

@app.route("/add_skill/", methods=["POST"])
def add_skill():
    try:
        skill_name = request.json.get('name')
        return controller.add_skill_control(skill_name.lower())

    except Exception as ex:
        return jsonify("skill name argument don't exists")

@app.route("/add_job/", methods=["POST"])
def add_job():
    try:
        title = request.json.get('title')
        skill_id = request.json.get('skill_id')
        return controller.add_job_control(title.lower(), skill_id)

    except Exception as ex:
        return jsonify("jobs arguments missing")

@app.route("/add_candidate/", methods=["POST"])
def add_candidate():
    try:
        title = request.json.get('title')
        skills_ids = request.json.get('skills_ids')
        return controller.add_candidate_control(title.lower(), skills_ids)
    except Exception as ex:
        return jsonify("candidate arguments missing")

@app.route("/candidate_finder/", methods=["POST"])
def candidate_finder():
    try:
        job_id = request.json.get('job_id')
        return controller.candidate_finder_control(job_id)
    except Exception as ex:
        return jsonify("candidate arguments missing")


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def generateTrees(self, n: int) -> List[Optional[TreeNode]]:
        if n == 0:
            return []
        return self.helper(1, n)

    def helper(self, start, end):
        if start > end:
            return [None]
        allTrees = []
        for i in range(start, end + 1):
            leftTrees = self.helper(start, i - 1)
            rightTrees = self.helper(i + 1, end)
            for l in leftTrees:
                for r in rightTrees:
                    currTree = TreeNode(i)
                    currTree.left = l
                    currTree.right = r
                    allTrees.append(currTree)
        return allTrees