"""
Created 18th June 2019
"""
from urllib.parse import urlsplit, parse_qs

class LogLineProcessor:
    """
    Class for applying log processing on a line by line basis.
    Cleansing of PID data is applied here. Specific keys can
    be passed to further processor classes if additional
    processing is required.
    """

    def __init__(self):
        self.processors = {}
        self.processor_keys = []

        self.pid_references = self.make_sensitive_substitutions()
        self.setprocessor_keys()

    @staticmethod
    def make_sensitive_substitutions():
        """
        List of substitution references - where patient identifiable data
        should be stripped from Operation Logs. Substitution is case
        insensitive.
        """
        # Force all keys to lower - they are compared against key.lower()
        return set(
            x.lower()
            for x in [
                "nhsNumber",
                "successorNhsNumber",
                "motherNhsNumber",
                "babyNhsNumber",
                # The following lines are output in Demographics Trace Logging
                "queryLine",
                "givenName",
                "familyName",
                # The following lines are output in CPIS Logging.
                "authIdentityNo",
                "laCode",
                "laName",
                "cpoType",
            ]
        )

    def setprocessor_keys(self):
        """
        List of keys which are subject to additional processing
        """
        self._add_processor("url", self.url_key_handler)
        self._add_processor("requestUrl", self.url_key_handler)

    def _add_processor(self, key, handler):
        """
        Add a processor and corresponding handler instance
        to the log processor.
        """
        lower_key = key.lower()
        self.processor_keys.append(lower_key)
        self.processors[lower_key] = handler

    # pylint: disable=broad-except
    # We really do want to catch a general exception in process().
    # There is scope for failures in the log key handlers which
    # would cause critical application errors. Since all logging
    # may pass through this method, validating all input edge cases
    # is difficult. It's safer to catch the general exception and
    # carry on as normal.
    def process(self, key, log_line):
        """
        Determine if we should process this type of key.
        If so, pass processing to the appropriate handler.
        """
        audit_row_required = False
        if not key:
            return audit_row_required

        lower = key.lower()

        if lower in self.pid_references:
            audit_row_required = True

        elif lower in self.processor_keys:
            try:
                audit_row_required = self.processors[lower](log_line)
            except Exception:
                pass

        return audit_row_required

    def url_key_handler(self, url):
        """
        Handler for url key types. Remove PID which
        has been passed as a URL parameter
        """
        query = urlsplit(url.lower())[3]
        params = parse_qs(query)

        return len(set(params.keys()) & self.pid_references) > 0

def check_for_param_dictionary(param_dict):
    """
    If key is 'parameters' and value is a dict, check the keys within the dict
    for any which need to be in audit.
    """
    if isinstance(param_dict, dict):
        for param_key in param_dict:
            audit = LogLineProcessor().process(param_key, param_dict[param_key])
            if audit:
                return True

    return False


import vcf
import numpy as np

def get_all_gt(records: vcf.Reader) -> list:
    """
    Receiving all genotype values from vcf.Reader records
    :param records: vcf.Reader records
    :return: list with all genotype values
    """
    all_gt_values = list()

    for row in records:
        samples = row.samples
        for sample in samples:
            gt_value = sample.data.GT
            if gt_value not in all_gt_values:
                all_gt_values.append(gt_value)

    return all_gt_values

def get_vaf_dict(records: vcf.Reader, correct_haploid_gt_values: set) -> dict:
    """
    Receiving cp_alleles_gt_vaf dictionary in the format below where
    sample.data.AD1 / sum(sample.data.AD) is a VAF for each sample):
        { chr_pos: alleles (for correct haploid genotype values):
            gt_value: [sample.data.AD1 / sum(sample.data.AD), ..., sample.data.ADn / sum(sample.data.AD)]
        }
        example:
        { 'Pf_M76611 33': 'T,A': '0/0': [[1.0, 0.0], ..., [1.0, 0.0]] }
        { 'Pf_M76611 33': 'T,A': '0|1': [[0.9166666666666666, 0.08333333333333333]] }
    :param records: vcf.Reader
    :param correct_haploid_gt_values: set with the correct haploid genotype values
    :return: cp_alleles_gt_vaf dictionary
    """
    cp_alleles_gt_vaf = dict()

    for row in records:
        chr_pos = f'{row.CHROM} {row.POS}'
        alleles = ','.join([str(x) for x in row.alleles])
        if chr_pos not in cp_alleles_gt_vaf:
            cp_alleles_gt_vaf[chr_pos] = dict()

        samples = row.samples

        for sample in samples:
            ad_values = sample.data.AD
            # don't use the sample.data.DP as sum of AD is not equal to DP
            # -> it means that DP contains information by all reads (not only informative as in AD)
            dp_value = sum(ad_values)
            gt_value = sample.data.GT.replace('0|0', '0/0').replace('0|1', '0/1').replace(
                '1|1', '1/1').replace('0/.', './.')

            if gt_value in correct_haploid_gt_values and dp_value > 0:
                if alleles not in cp_alleles_gt_vaf[chr_pos]:
                    cp_alleles_gt_vaf[chr_pos][alleles] = dict()

                if gt_value not in cp_alleles_gt_vaf[chr_pos][alleles]:
                    cp_alleles_gt_vaf[chr_pos][alleles][gt_value] = list()

                cp_alleles_gt_vaf[chr_pos][alleles][gt_value].append([x / dp_value for x in ad_values])

    return cp_alleles_gt_vaf

def write_output(cp_alleles: dict, outp_file: str) -> None:
    """
    Receiving mean VAF for each sample set for genotype and writing in the output file
    :param cp_alleles: cp_alleles dictionary in the format below where
    sample.data.AD1 / sum(sample.data.AD) is a VAF for each sample):
        { chr_pos: alleles (for correct haploid genotype values):
            gt_value: [sample.data.AD1 / sum(sample.data.AD), ..., sample.data.ADn / sum(sample.data.AD)]
        }
    :param outp_file: output filepath
    :return: None
    """
    outp_data = ''
    for chr_pos, alleles_gt_vaf in cp_alleles.items():
        for alleles, gt_vaf in alleles_gt_vaf.items():
            for gt, vaf in gt_vaf.items():
                mx = np.matrix(vaf)
                sum_array = np.array(mx.sum(axis=0))[0]
                vaf_lst = [x / mx.shape[0] for x in sum_array]

                data_vaf = ','.join([str(x) for x in vaf_lst])
                outp_data += f"{chr_pos} {alleles} {data_vaf}\n"

    with open(outp_file, 'w+') as f:
        f.write(outp_data)

if __name__ == "__main__":
    vcf_path = './vcf_vaf_data/Pf_M76611.pf7.200_samples.vcf'

    all_gt_values = get_all_gt(records=vcf.Reader(open(vcf_path, 'r')))
    print(f"All genotype values list for the input records: {all_gt_values}")

    cp_alleles_dict = get_vaf_dict(
        records=vcf.Reader(open(vcf_path, 'r')),
        correct_haploid_gt_values={'0/0', '0|0', '0/1', '0|1', '1/1', '1|1', './.', '0/.'}
    )
    write_output(cp_alleles=cp_alleles_dict, outp_file='./vcf_vaf_data/outp_vaf.txt')


'''
    Check for 4 repeating numbers in an NxN matrix
    row-wise, column-wise or diagonally
    Return true if found, else false
'''

def checkio(matrix):
    vector = []
    cols = list(zip(*matrix))
    rows = matrix
    for m in matrix:
        vector += m
    uniques = set(vector)
    diagonalsnw, diagonalsne = diagonal_coord(matrix)

    for num in uniques:
        for col in cols:
            for i, x in enumerate(cols[:-3]):
                if all([x == num for x in col[i:i+4]]):

                    return True
        for row in rows:
            for i, x in enumerate(rows[:-3]):
                if all([x == num for x in row[i:i+4]]):
                    return True
        for diag in diagonalsnw:
            if all( [matrix[x][y] == num for x,y in diag]):
                return True
        for diag in diagonalsne:
            if all( [matrix[x][y] == num for x,y in diag]):
                return True
    return False

def diagonal_coord(m):
    diagonalsnw = []
    diagonalsne = []
    n = len(m)
    for i in range(n-3):
        for j in range(n-3):
            diagonalsnw.append([(i,j), (i+1,j+1), (i+2,j+2), (i+3,j+3)])
            diagonalsne.append([(i,(n-1)-j), (i+1,(n-1)-(j+1)), (i+2,(n-1) - (j+2)), (i+3,(n-1)-(j+3))])

    return diagonalsnw, diagonalsne

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert checkio([
        [1, 2, 1, 1],
        [1, 1, 4, 1],
        [1, 3, 1, 6],
        [1, 7, 2, 5]
    ]) == True, "Vertical"
    assert checkio([
        [7, 1, 4, 1],
        [1, 2, 5, 2],
        [3, 4, 1, 3],
        [1, 1, 8, 1]
    ]) == False, "Nothing here"
    assert checkio([
        [2, 1, 1, 6, 1],
        [1, 3, 2, 1, 1],
        [4, 1, 1, 3, 1],
        [5, 5, 5, 5, 5],
        [1, 1, 3, 1, 1]
    ]) == True, "Long Horizontal"
    assert checkio([
        [7, 1, 1, 8, 1, 1],
        [1, 1, 7, 3, 1, 5],
        [2, 3, 1, 2, 5, 1],
        [1, 1, 1, 5, 1, 4],
        [4, 6, 5, 1, 3, 1],
        [1, 1, 9, 1, 2, 1]
    ]) == True, "Diagonal"


import requests
from bs4 import BeautifulSoup
import time

# 爬取美女壁纸

url = 'https://pic.netbian.com/4kmeinv/'
resp = requests.get(url)
resp.encoding = 'gbk'
tags = BeautifulSoup(resp.text, 'html.parser')
imgs = tags.find('ul', class_='clearfix').find_all('img')
for img in imgs:
    imgUrl = url[0:-9] + img.get('src')
    # print(imgUrl)
    imgDown = requests.get(imgUrl)
    imgDown.encoding = 'gbk'
    with open('file/' + img.get('alt') + '.jpg', mode='wb') as file:
        file.write(imgDown.content)
    print('下载完成：', img.get('alt'))
    # time.sleep(1)


"""
bid_frame.py represents the abstract frame for different types of auctions.
"""

__author__ = "Max Chan, Nick Chua"

# Library import
from tkinter import *
from datetime import datetime
from abc import ABC

# File import
from Controller.bid_controller import BidController
from View.abstract_frames import AbstractFrame
from popups import *
from api_constants import *

class BidFrame(AbstractFrame, ABC):
    """
    Not meant to be initiated. Only inherited by frames for different types of auctions.
    """

    def __init__(self, parent, controller):
        AbstractFrame.__init__(self, parent, controller)
        self.cont = BidController()
        self.text_welcome = StringVar()

    def load_base_ui(self):
        frame_base_ui = Frame(self)
        self.label_welcome = Label(self, textvariable=self.text_welcome)
        self.label_welcome.grid(row=0, column=2)

        self.button_back = Button(
            frame_base_ui,
            text="Back",
            command=lambda: self.controller.show_frame("BidSetupFrame"),
        )
        self.button_back.grid(row=1, column=4, padx=20)

        frame_base_ui.grid(row=0, column=0)

    def setup_request_form(self, bid_type):
        """Create labels and entries for the auction information form.

        This method is separated to declutter from the constructor.
        """
        self.disclaimer_label = \
            Label(self, text="DISCLAIMER:\nBy submitting a bid, you consent to signing a contract\n"
                             "between you and a prospecting tutor.")
        self.disclaimer_label.place(x=500, y=200)

        _, lessonEntry = self.grid_input_cluster("lessonName", "Lesson: ", (1, 0))

        self.grid_input_cluster(
            "minsPerSession", "Preferred minutes per session: ", (2, 0)
        )
        self.grid_input_cluster("numSessions", "Number of sessions: ", (3, 0))
        self.grid_input_cluster("sessionRate", "Rate per session: ", (4, 0))
        self.grid_input_cluster("tutorCompetency", "Tutor competency", (5, 0))
        self.grid_input_cluster("contractDuration", "Contract Duration", (6, 0))

        self.button_new_request = Button(
            self, text="Create Auction", command=lambda: self.cont.new_bid(
                bid_type,
                self.controller.user.get_id(),
                str(datetime.utcnow().isoformat() + "Z"),
                self.get_lesson(lessonEntry.get())["id"],
                {
                    "minutes_per_session": self.entries["minsPerSession"].get(),
                    "sessions_per_week": self.entries["numSessions"].get(),
                    "preferred_hourly_rate": self.entries["sessionRate"].get(),
                    "tutor_competency": self.entries["tutorCompetency"].get(),
                    "contract_duration": self.entries["contractDuration"].get(),
                }
            )
        )
        self.button_new_request.grid(pady=10)

        self.create_lesson_list(lessonEntry)

    def create_lesson_list(self, lessonEntry):
        """Create and set up listbox filled with lesson names."""

        def update_list(given_list):
            """Update listbox based on items in given_list."""
            lesson_list.delete(0, END)
            for item in given_list:
                lesson_list.insert(END, item)

        def fillout_box(event):
            """Fill in the lesson entry box based on item selected in
            listbox
            """
            lessonEntry.delete(0, END)
            lessonEntry.insert(0, lesson_list.get(ANCHOR))

        def check_list(event):
            """Update listbox based on input in the lesson entry box."""
            user_input = lessonEntry.get()

            if user_input == "":
                # Reset to the beginning
                data = lesson_names
            else:
                data = []
                for item in lesson_names:
                    if user_input.lower() in item.lower():
                        data.append(item)
            update_list(data)

        # Loading list of existing lessons
        lessons_data = requests.get(
            url=subject_url, headers={"Authorization": my_api_key}
        ).json()

        lesson_names = []
        for lesson in lessons_data:
            lesson_names.append(lesson["description"])

        # Creating Listbox
        lesson_list = Listbox(self, height=5, width=50)
        lesson_list.grid(row=1, column=2, rowspan=3)
        # Instantiate every lesson name
        update_list(lesson_names)

        # Fill in the Lesson Entry based on selected item in Listbox
        lesson_list.bind("<<ListboxSelect>>", fillout_box)
        # Update Listbox based on user input
        lessonEntry.bind("<KeyRelease>", check_list)

    def get_lesson(self, lesson_name):
        """ Calls the controller to get the lesson from the API given a lesson name"""
        return BidController.get_lesson(self, lesson_name)

    def is_positive_integer(self, key, value):
        """Assess whether given value is a positive numerical integer."""
        if not value.isdigit():
            PopupError(key + " must be a number.")
            raise Exception()
        elif not int(value) > 0:
            PopupError(key + " must be positive.")
            raise Exception()


#!/usr/bin/env python3

"""Get the minimum distance ** 2 among the given points.
>>> main("testcases/test_100000_1")
0
>>> main("testcases/test_10000_1")
144
>>> main("testcases/test_1000_1")
200
>>> main("testcases/test_uniform")
3969
"""

import math
import fileinput
from collections import defaultdict, deque

def load_points(input_file=None):
    """Read points from stdin and parse them to a list.

    input_file:
        The input file as a file object.
        Example usage:
            load_points('example.txt')
            load_points()  # Reads from stdin
    """
    # Not using with statement for python2 compatibility
    infile = fileinput.input(input_file)
    n_points = int(infile.readline())
    points = [int(x)+int(y)*1j for x, y in map(str.split, infile)]
    infile.close()
    assert len(points) == n_points
    return points

def mindist(points):
    """Get the minimum distance for the given points.

    points:
        list of points as a complex int.
        they should be sorted by x coordinate.
    """
    # 1. Getting the dimensions and upper bound
    xmin, xmax = points[0].real, points[-1].real
    ymin, ymax = points[0].imag, points[0].imag
    for p in points:
        if p.imag < ymin:
            ymin = p.imag
        elif p.imag > ymax:
            ymax = p.imag
    # We equally divide the bounding rectangle into k*k parts, where k*k<n.
    # According to the pigeonhole principle, there exists two points inside
    # one rectangle. The distance between those two points is no more than
    # math.hypot(width, height) / k.
    upper_bound = (math.hypot(xmax-xmin, ymax-ymin) /
                   math.floor(math.sqrt(len(points)-1)))

    # Workaround when minimum distance is zero or one.
    min_ = min(abs(points[i+1]-points[i]) for i in range(len(points)-1))
    if min_ in [0, 1]:
        return min_
    upper_bound = min(upper_bound, min_)

    # 2. Getting the minimum distance.
    # The minimum distance so far:
    min_ = upper_bound
    upper_bound_int = math.ceil(upper_bound)
    start = 0
    # Grouping of the points (in the queue) with similar y coordinates.
    group = [int(p.imag * 2 // upper_bound_int) for p in points]
    i_by_group = defaultdict(deque)
    # Pass the points through a queue.
    # The queue (points[start:stop]) can be represented as
    # merely two indices (start and stop).
    # Every iteration adds the last p into the queue.
    for stop, p in enumerate(points):
        # Points too left are popped out of the queue.
        while points[start].real <= p.real - min_:
            i = i_by_group[group[start]].popleft()
            assert start == i, (start, i)
            start += 1
        # Update minimum distance for the points inside the queue:
        # If two points have a difference > upper_bound_int,
        # Their group index has a difference of > 2.
        for check_group in range(group[stop]-2, group[stop]+3):
            for i in i_by_group[check_group]:
                min_ = min(min_, abs(p-points[i]))
        # Assign current point to group
        i_by_group[group[stop]].append(stop)
    return min_

def main(input_file=None):
    ps = load_points(input_file)
    ps.sort(key=lambda p: p.real)
    print(round(mindist(ps) ** 2))

if __name__ == '__main__':
    main()


import scrapy
import time

limit = False
infty = 1000000

class Player(scrapy.Item):
    name = scrapy.Field()
    team = scrapy.Field()
    passport = scrapy.Field()
    birth_date = scrapy.Field()
    height = scrapy.Field()
    position = scrapy.Field()

class NewSpider(scrapy.Spider):
    name = 'players'

    def start_requests(self):
        try:
            with open("links.csv") as f:
                start_urls = [url.strip() for url in f.readlines()][1:]
        except:
            start_urls = []
        counter = infty
        if limit:
            counter = 100
        Start = time.time()
        for url in start_urls:
            if counter > 0:
                yield scrapy.Request(url=url, callback=self.parse)
                counter = counter - 1
        End =time.time()
        Total = End-Start
        print('Crawling time:', Total)
    def parse(self, response):
        p = Player()
        p['name'] = response.css('title::text').get()
        p['team'] = response.css('div.col-xl-6.col-lg-6.col-md-6.col-sm-12.mycol').css('li::text').get().replace('-', '').replace('  ', '')
        data = response.css('div.col-6.numer').css('span::text').getall()
        p['passport'] = data[0]
        p['birth_date'] = data[1]
        p['height'] = data[2]
        p['position'] = data[3]

        yield p


import numpy as np
import pyaudio
import wave
#define params manually here
from audio_utils import *
from Audio import *
from debugger import *

def get_zero_string(n):
    """Returns left padded number with zeros for file search

    Args:
        n (int): document number you want to query
    Returns:
        string: value in a left padded zero string. 1 -> 001, 10 -> 010 -> 100, 100 -> 100
    """
    zero_str = ''

    if n < 10:
        zero_str =  "00" + str(n)
    elif n < 100:
        zero_str =  "0" + str(n)
    elif n < 1000:
        zero_str = str(n)

    return zero_str

def load_data_file(n=1,audio_n_offset=0,file_stem="data_rec",sample_rate = 44100,label_rate = 1,
data_label_path="/Users/zachyamaoka/Documents/de3_audio/data_label/",
data_wav_path="/Users/zachyamaoka/Dropbox/de3_audio_data/data_wav_5/"): #only works up to 10 rn

    label_num = get_zero_string(n+audio_n_offset)
    audio_num = get_zero_string(n+audio_n_offset)

    label_file_path = data_label_path+file_stem+label_num+".txt"
    audio_file_path = data_wav_path+file_stem+audio_num+".wav"

    #First load labels from the audio file
    label = np.loadtxt(label_file_path)
    num_labels = label.shape[0]
    # if len(label.shape) < 2: #theta
    # label.reshape(num_labels,1)

    #load audio file
    chunk = 1024
    player = AudioPlayer(chunk)
    player.load_wav_audio(audio_file_path)
    raw_data = player.get_all_data()

    #regardless clip of first 2 seconds if data #b/c small not meaningful start at the begging
    if label_rate == 100: #old recs
        start_clip = sample_rate * 2 #seconds
    else:
        start_clip = 0
    data = raw_data[start_clip:-1]
    num_sample = data.shape[0]

    # find start and end
    start = 0
    for i in np.arange(num_sample):
        if data[i,0] != 0:
            start = i
            break;
    #print("num labels, ", num_labels)
    label_time = (num_labels-1) * (1/label_rate) #so you get better use out of your last label
    #print("Label Time: ", label_time)
    num_sample_labeled = label_time * sample_rate
    end = int(start + num_sample_labeled)
    data = data[start:end,:]

    len_data = data.shape[0]
    print("Song time: ", len_data/sample_rate)
    #find end based on num of samples

    return [data,label,[sample_rate,label_rate]] #list of data

def listen_2_data(all_data, window_chunk=1024, audio_rate=44100, label_rate=100):
    data = all_data[0]
    label = all_data[1]
    if len(label.shape) == 1: #just theta
        label = label.reshape(label.shape[0],1)

    curr_frame = 0
    last_frame = data.shape[0] - 1
    last_ind = -1
    Viz = Debugger()
    room_width = 5
    room_length = room_width

    player = AudioPlayer(window_chunk)
    count = 0

    while True:

        clip = data[curr_frame:curr_frame+window_chunk,:]
        parsed_audio = encode(clip)

        curr_frame += window_chunk
        if curr_frame > last_frame:
            break

        ind = sample2labelId(curr_frame,audio_rate,label_rate)

        count += 1
        if count % 50 == 0:
        # if ind != last_ind: #only go further if he has moved, may get lag if label rate 2 high
            last_ind = ind
            pos = label[ind,:]
            if len(pos) == 3: #xyz
                r = np.sqrt(pos[0]**2 + pos[1]**2)
                theta = np.cos(pos[0]/r)
                Viz.draw_sound_in_room(pos[0], pos[1])
            else: #theta
                Viz.draw_heading(pos[0])

        player.play_this(parsed_audio)

def sample2labelId(n, sample_rate,label_rate): #get label which correlates with sample
    timestamp = n/sample_rate
    #Used to be -1 but that does not give the correct behavour
    #With audio samples you want to floor(). Any samples should correspond to the last label, not the nearest... do not round()
    label_num = int(timestamp*label_rate) #so you can index correctly in list
    return label_num

#Make function to playback music and vizualize

def show_data(data, labels):
    pass

if __name__ == '__main__':
    # data = load_data_file(n=0,label_rate = 10,file_stem="real_rec_",
    # data_label_path="/Users/zachyamaoka/Documents/de3_audio/data_real_label/",
    # data_wav_path="/Users/zachyamaoka/Dropbox/de3_audio_data/data_real_wav/")
    #
    # listen_2_data(data,label_rate = 10)

    data = load_data_file(n=1,label_rate = 100,file_stem="data_rec",
    data_label_path="/Users/zachyamaoka/Documents/de3_audio/data_label/",
    data_wav_path="/Users/zachyamaoka/Dropbox/de3_audio_data/data_wav_5/")

    listen_2_data(data,label_rate = 100)

    print("Data Params")
    print("Audio Stero Vector: ", data[0].shape, " Sample Rate: ", data[2][0])
    print("Position Label: ", data[1].shape, " Label Rate: ", data[2][1])

    '''
    ind = sample2labelId(0, 44100, 1) #will be some small error, but no more then 1 label so its ok....
    # assert ind == 0
    print(ind)
    ind = sample2labelId(data[0].shape[0], 44100, 1) #will be some small error, but no more then 1 label so its ok....
    print(ind)
    '''


import sys

n, m = map(int, sys.stdin.readline().split())

board = []
for _ in range(n) :
    row = list(sys.stdin.readline().rstrip())
    board.append(row)

row_len_list = []
col_len_list = []

for r in board :
    if r.count('#') > 0 :
        row_len_list.append(r.count('#'))

# 상하좌우 각각의 길이에서, 최대측정 길이보다 1씩 작은 부분이 있다.
# 그 부분이 상에 있다면 UP, 하에 있다면 DOWN, 좌에 있다면 LEFT, 우에 있다면 RIGHT 이다
for i in range(m) :
    cnt = 0
    for j in range(n) :
        if board[j][i] == '#' :
            cnt += 1
    if cnt > 0 :
        col_len_list.append(cnt)

if row_len_list[0] > row_len_list[-1] :
    print("DOWN")

if row_len_list[0] < row_len_list[-1] :
    print("UP")

if col_len_list[0] > col_len_list[-1] :
    print("RIGHT")

if col_len_list[0] < col_len_list[-1] :
    print("LEFT")


#external
from coordination.runtime import FeaturesProvider as Provider
from coordination.runtime import Scope
from coordination.wire import Entity
# internal
import coordinators
import entities

class FeaturesProvider(Provider):

    @Provider.feature('GUI.Qt')
    def Qt(self):
        from PyQt4 import QtCore, QtGui
        self.provide(QtCore=QtCore, QtGui=QtGui)

    @Provider.feature('GUI.Gtk')
    def Gtk(self):
        import pygtk
        pygtk.require('2.0')
        import gtk
        import gobject
        self.provide(gtk=gtk)

def main():
    Entity.scope = Scope()
    provider = Entity.provider = FeaturesProvider()

    scheduler = entities.Scheduler()

    reactor = entities.Reactor()

    statusbar = entities.StatusBar()

    editor = entities.SourceEditor()

    if False:
        coorditators = [
            coordinators.Coordinator_StatusBar_EditorPosition_QtWidget(
                statusbar.EditorPosition, statusbar.QtWidget),
            coordinators.Coordinator_SourceEditor_Position_StatusBar_EditorPosition(
                editor.Position, statusbar.EditorPosition),
            coordinators.Coordinator_SourceEditor_QtWidget_Position(
                editor.QtWidget, editor.Position),
            coordinators.Coordinator_Reactor_Qt_Scheduler_Queue(
                reactor.Qt, scheduler.Queue),
            coordinators.Coordinator_Scheduler_Queue(
                scheduler.Queue),
            ]

        mainWin = provider.QtGui.QMainWindow()
        mainWin.setStatusBar(statusbar.QtWidget.widget)
        mainWin.setCentralWidget(editor.QtWidget.widget)
        mainWin.show()

        for coordinator in coorditators:
            coordinator.create()

        reactor.Qt.run()

    else:
        coorditators = [
            coordinators.Coordinator_StatusBar_EditorPosition_GtkWidget(
                statusbar.EditorPosition, statusbar.GtkWidget),
            coordinators.Coordinator_SourceEditor_Position_StatusBar_EditorPosition(
                editor.Position, statusbar.EditorPosition),
            coordinators.Coordinator_SourceEditor_GtkWidget_Position(
                editor.GtkWidget, editor.Position),
            coordinators.Coordinator_Reactor_Gtk_Scheduler_Queue(
                reactor.Gtk, scheduler.Queue),
            coordinators.Coordinator_Scheduler_Queue(
                scheduler.Queue),
            ]

        mainWin = provider.gtk.Window()
        layout = provider.gtk.VBox(False, 0)
        layout.pack_start(editor.GtkWidget.widget, True, True, 0)
        layout.pack_start(statusbar.GtkWidget.widget, False, True, 0)
        layout.show()
        mainWin.add(layout)
        mainWin.show()

        for coordinator in coorditators:
            coordinator.create()

        reactor.Gtk.run()


"""
Pre-Processing
1. The JSON file is processed to extract raw data and store it.
2. Raw data is converted to a data frame and processed to filter non-English characters.
3. Messages containing SHIB and DODGE are kept.
"""

# Libraries
from tqdm import tqdm
import json
import argparse
import pandas as pd

# Creates and returns data frame with attributes: text, date, time
def create_dataframe(text, date, time):
    df = pd.DataFrame(list(zip(text, date, time)), columns =['Text', 'Date','Time'])
    return df

# Saves data frame to CSV
def save_dataframe(df):
    df.to_csv('data/telegram_processed_data.csv',index=False)

# Pandas Functionality Extender: Filters English Character
def english_char_filter(x):
    return x.encode('ascii',errors='ignore').decode()

# Pandas Functionality Extender: Lowercase String
def lowercase_string(x):
    return x.lower()

# Filters English characters and keeps messages with substrings dodge or shib
# Returns filtered dataframe
def process_dataframe(df):
    df['Text'] = df['Text'].apply(english_char_filter)
    df['Text'] = df['Text'].apply(lowercase_string)
    df = df[df['Text'].str.contains("doge|shib")==True]
    df = df.reset_index(drop=True)
    return df

# Extract raw data from JSON file and returns list of attributes: text, date, time
def processing_main(data):
    string_list, date_list, time_list  = [],[],[]

    # Pre-processing text data
    for i in tqdm(data['messages']):
        if isinstance(i['text'], list):
            temp_str=''
            for j in i['text']:
                if not isinstance(j,str):
                    temp_str+=j['text']
                else:
                    temp_str+=j
            string_list.append(temp_str)

        else:
            string_list.append(i['text'])

    # Pre-processing Date data
    for i in tqdm(data['messages']):
        date,time = i['date'].split('T')
        date_list.append(date)
        time_list.append(time)

    return string_list, date_list, time_list

# Main Driver
def main():

    # Input Filename: 'data/result.json'

    parser = argparse.ArgumentParser()
    parser.add_argument("input")
    args = parser.parse_args()

    file_data = open(args.input)
    json_data = json.load(file_data)
    text, date, time = processing_main(json_data)
    df = create_dataframe(text, date, time)
    df = process_dataframe(df)
    save_dataframe(df)

if __name__ == "__main__":
    main()


#!/usr/bin/python3
'''This module contains one class, HBNBCommand'''

import cmd
import sys
import models
import json
from models.engine.file_storage import FileStorage
from models.amenity import Amenity
from models.base_model import BaseModel
from models.city import City
from models.place import Place
from models.review import Review
from models.state import State
from models.user import User

class HBNBCommand(cmd.Cmd):
    """HBNBCommand is a command line
    interpreter for the HBNB project
    """
    prompt = '(hbnb) '
    file = None
    __allowed_classes = ('BaseModel', 'User', 'Amenity',
                         'State', 'Place', 'City', 'Review')

    @staticmethod
    def allowed_classes():
        '''The classes we allow eval() to evaluate upon reload'''
        return HBNBCommand.__allowed_classes

    def from_json_string(json_string):
        '''convert json string of obj dicts into list of same'''
        if json_string is None or json_string == "":
            return []
        else:
            return json.loads(json_string)

    def do_quit(self, arg):
        """quit the command line
        """
        self.close()
        return True

    def do_EOF(self, arg):
        """exits with a newline
        """
        print()
        self.close()
        return True

    def close(self):
        """closes a file before it's finished execut
        """
        if self.file:
            self.file.close()
            self.file = None

    def emptyline(self):
        '''Do nothing if empty newline'''
        pass

    def do_create(self, arg):
        """create new instance of object and serialize
        """
        if not arg:
            print("** class name missing **")
        elif arg not in HBNBCommand.allowed_classes():
            print("** class doesn't exist **")
        else:
            args = arg.split()
            obj = eval(str(args[0]) + '()')
            if not isinstance(obj, BaseModel):
                return
            obj.save()
            print(obj.id)

    def do_show(self, line):
        """print the json string of an object
        """
        args = line.split()
        if not args or len(args) == 0:
            print("** class name missing **")
            return
        elif args[0] not in HBNBCommand.allowed_classes():
            print("** class doesn't exist **")
            return
        elif len(args) == 1:
            print("** instance id missing **")
            return
        l_class, l_id = args[0], args[1]
        instance_found = False
        for (key, value) in models.storage.all().items():
            if key == l_class + '.' + l_id:
                instance_found = True
                print(value)
        if not instance_found:
            print("** no instance found **")

    def do_all(self, line):
        """ method that prints all instances"""
        args = line.split()
        if len(args) == 0:  # user types 'all' with no arguments
            list_objects = [str(obj) for (key, obj) in
                            models.storage.all().items()]
            print(list_objects)
        elif line not in HBNBCommand.allowed_classes():  # user types bad Cname
            print("** class doesn't exist **")
        else:  # user types 'all [allowed classname]'
            list_objects = [str(obj) for (key, obj) in
                            models.storage.all().items() if
                            key.split('.')[0] == args[0]]
            print(list_objects)

    def do_destroy(self, line):
        """ method that deletes class individual instance """
        args = line.split()
        if len(args) == 0:
            print("** class name missing **")
            return
        if len(args) == 1:
            print("** instance id missing **")
            return
        if args[0] not in HBNBCommand.allowed_classes():
            print("** class doesn't exist **")
            return
        deletable_key = 0
        l_name, l_id = args[0], args[1]
        for (key, value) in models.storage.all().items():
            if key == l_name + "." + l_id:
                deletable_key = key
        if deletable_key == 0:
            print("** no instance found **")
        else:
            del models.storage.all()[deletable_key]
            models.storage.save()

    def do_update(self, line):
        '''update attributes of an instance'''
        args = line.split()
        if len(args) == 0:
            print("** class name missing **")
        elif args[0] not in HBNBCommand.allowed_classes():
            print("** class doesn't exist **")
        elif len(args) == 1:
            print("** instance id missing **")
        elif len(args) == 2:
            print("** attribute name missing **")
        elif len(args) == 3:
            print("** value missing **")
        else:
            classname, obj_id = args[0], args[1]
            instance_found = False
            for (key, value) in models.storage.all().items():
                if key == classname + '.' + obj_id:
                    instance_found = True
            if not instance_found:
                print("** no instance found **")
            att, val = args[2], args[3].strip('\"')
            models.storage.all()[classname + '.' + obj_id].__dict__[att] = val
            models.storage.all()[classname + '.' + obj_id].save()

if __name__ == "__main__":
    HBNBCommand().cmdloop()


# -*- coding: utf-8 -*-

from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
from datetime import datetime

class AflowzSchoolPolling(models.Model):
    _name = 'aflowz.school.polling'
    _description = 'Aflowz School Polling'
    _inherit = ['mail.thread']

    name = fields.Char(required=True, track_visibility='onchange')
    date = fields.Date(required=True, default=datetime.now(), track_visibility='onchange')
    option_ids = fields.Many2many('aflowz.school.option', required=True, track_visibility='onchange')
    description = fields.Text(track_visibility='onchange')
    voter_type = fields.Selection([
        ('student', 'Student'),
        ('teacher', 'Teacher'),
        ('all', 'Student & Teacher')],
        default="all",
        required=True,
        track_visibility='onchange'
    )
    polling_line_ids = fields.One2many('aflowz.school.polling.line', 'polling_id')
    polling_result_ids = fields.One2many('aflowz.school.polling.result', 'polling_id')
    state = fields.Selection([
        ('draft', 'Draft'),
        ('open', 'Open'),
        ('done', 'Done')],
        default="draft",
        track_visibility='onchange'
    )
    participant_count = fields.Integer(compute="_compute_participant_count")
    participant_count_string = fields.Char(compute="_compute_participant_count")
    open_vote_date = fields.Datetime(track_visibility='onchange')
    finish_vote_date = fields.Datetime(track_visibility='onchange')

    def _compute_participant_count(self):
        for rec in self:
            pol_line = len(rec.polling_line_ids)
            rec.participant_count = pol_line
            rec.participant_count_string = "%s %s" % (pol_line, "Participants")

    def action_graph(self):
        return {
            'name': _('Voting Graph'),
            'view_type': 'form',
            'view_mode': 'graph',
            'res_model': 'aflowz.school.polling.line',
            'type': 'ir.actions.act_window',
            'domain': [('polling_id', '=', self.id)],
        }

    def action_open(self):
        for rec in self:
            rec.state = 'open'
            rec.open_vote_date = datetime.now()

    def action_done(self):
        for rec in self:
            rec.state = 'done'
            rec.finish_vote_date = datetime.now()

    def action_set_to_draft(self):
        for rec in self:
            rec.state = 'draft'

    @api.constrains('option_ids', 'polling_line_ids')
    def _constrains_polling_result(self):
        for rec in self:
            option_list_id = rec.option_ids.ids
            result_option_id = [opt.option_id.id for opt in rec.polling_result_ids]
            polling_line_ids = set([opt_l.option_id.id for opt_l in rec.polling_line_ids])

            for opt_l in option_list_id:
                if opt_l not in result_option_id:
                    rec.polling_result_ids = [(0, 0, {
                        'option_id': opt_l
                    })]

            for r_opt in rec.polling_result_ids:
                for pl in polling_line_ids:
                    if pl not in option_list_id:
                        raise ValidationError(_("You can't remove an option when someone already vote for it!"))

                if not r_opt.option_id.id in option_list_id:
                    rec.polling_result_ids = [(2, r_opt.id)]

            for opt_l in option_list_id:
                percentage = 0
                if rec.polling_line_ids:
                    percentage = round(len(rec.polling_line_ids.filtered(lambda pl: pl.option_id.id == opt_l)) / len(rec.polling_line_ids) * 100, 2)

                for res_opt in rec.polling_result_ids:
                    if opt_l == res_opt.option_id.id:
                        res_opt.polling_percentage = percentage
                        res_opt.polling_percentage_string = "%s (%s/%s)" % (str(percentage) + "%", len(rec.polling_line_ids.filtered(lambda pl: pl.option_id.id == opt_l)) or 0, len(rec.polling_line_ids) or 0)

class AflowzSchoolPollingLine(models.Model):
    _name = 'aflowz.school.polling.line'
    _sql_constraints = [('unique_voter', 'unique(polling_id, voter_id)', 'There are duplicate voter on the same polling')]

    voter_type = fields.Selection([
        ('student', 'Student'),
        ('teacher', 'Teacher'),
        ('all', 'Student & Teacher')],
        default="all",
        required=True
    )
    polling_id = fields.Many2one('aflowz.school.polling', required=True)
    voter_id = fields.Many2one('aflowz.school.citizen', required=True)
    option_ids = fields.Many2many('aflowz.school.option')
    option_id = fields.Many2one('aflowz.school.option', required=True)

    @api.onchange('voter_type')
    def onchange_voter_type(self):
        """
        :param self:
        :return: [domain]
        """
        for record in self:
            if record.voter_type:
                ctz_type = ['student', 'teacher']
                if record.voter_type == 'student':
                    ctz_type = ['student']
                elif record.voter_type == 'teacher':
                    ctz_type = ['teacher']

                return {'domain': {'voter_id': [('citizen_type', 'in', ctz_type)]}}

class AflowzSchoolOption(models.Model):
    _name = 'aflowz.school.option'

    name = fields.Char()

class AflowzSchoolOption(models.Model):
    _name = 'aflowz.school.polling.result'

    polling_id = fields.Many2one('aflowz.school.polling')
    option_id = fields.Many2one('aflowz.school.option')
    polling_percentage = fields.Float()
    polling_percentage_string = fields.Char()


import torch
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt

train_data = np.load("E:\\quant_research\\train the rank of ten points\\RNN_point\\data\\train_data_10num.npy")
train_aim = np.load("E:\\quant_research\\train the rank of ten points\\RNN_point\\data\\train_label_10num.npy")
train_data = train_data.reshape(train_data.shape[0],10,1)
train_data = train_data.swapaxes(0, 1)
train_data = torch.from_numpy(train_data).type(torch.FloatTensor)
train_aim = torch.from_numpy(train_aim).type(torch.FloatTensor)

test_data = np.load("E:\\quant_research\\train the rank of ten points\\RNN_point\\data\\test_data_10num.npy")
test_aim = np.load("E:\\quant_research\\train the rank of ten points\\RNN_point\\data\\test_label_10num.npy")
test_data = test_data.reshape(test_data.shape[0],10,1)
test_data = test_data.swapaxes(0, 1)
test_data = torch.from_numpy(test_data).type(torch.FloatTensor)
test_aim = torch.from_numpy(test_aim).type(torch.FloatTensor)

class Encoder(nn.Module):

    def __init__(self, input_size, hidden_size, batch_size, bidirectional=True):
        super(Encoder, self).__init__()
        self.hidden_size = hidden_size
        self.input_size = input_size
        self.batch_size = batch_size
        self.bidirectional = bidirectional

        self.lstm = nn.LSTM(input_size, hidden_size, batch_first=False, bidirectional=bidirectional)

    def forward(self, inputs, hidden):
        output, hidden = self.lstm(inputs, hidden)
        return output, hidden

    def init_hidden(self):
        return (torch.zeros(1 + int(self.bidirectional), self.batch_size, self.hidden_size),
                torch.zeros(1 + int(self.bidirectional), self.batch_size, self.hidden_size))   #(num_layers * num_directions, batch, hidden_size)

class AttentionDecoder(nn.Module):

    def __init__(self, hidden_size, output_size, batch_size, vocab_size,seq_len):
        super(AttentionDecoder, self).__init__()
        self.hidden_size = hidden_size
        self.output_size = output_size
        self.batch_size = batch_size
        self.seq_len = seq_len
        self.vocab_size = vocab_size

        self.attn = nn.Linear(hidden_size + output_size + vocab_size, 1)
        self.lstm = nn.LSTM(hidden_size + vocab_size, output_size)
        self.final = nn.Linear(output_size, vocab_size)

    def init_hidden(self):
        return (torch.zeros(1, self.batch_size, self.output_size),
                torch.zeros(1, self.batch_size, self.output_size))

    def forward(self, decoder_hidden, encoder_outputs, input):
        seq = 0
        weights= []
        i = 0
        output = torch.zeros(self.batch_size, self.vocab_size)
        for i in range(len(encoder_outputs)):
            weights.append(self.attn(torch.cat((decoder_hidden[0][:].squeeze(0),encoder_outputs[i],output), dim=1)))

        normalized_weight = F.softmax(torch.cat(weights, 1), 1)
        normalized_weights = normalized_weight

        attn_applied = torch.bmm(normalized_weight.unsqueeze(1),
                                 encoder_outputs.transpose(0,1))
        input_lstm = torch.cat((attn_applied.transpose(0,1)[0], output),
                               dim=1)  # if we are using embedding, use embedding of input here instead

        output_, hidden = self.lstm(input_lstm.unsqueeze(0), decoder_hidden)

        output = self.final(output_[0]) #output 为（vocab_size, output_size）
        #output = self.final2(output)

        # hidden0 = hidden[0].transpose(0, 1).reshape(batch_size, 1, -1).transpose(0, 1)
        # hidden1 = hidden[1].transpose(0, 1).reshape(batch_size, 1, -1).transpose(0, 1)
        # decoder_hidden = (hidden0, hidden1)
        # decoder_hiddens = decoder_hidden

        out = F.softmax(output,1)

        return out

seq_len = 10
input_size = 1
hidden_size = 2
batch_size = train_data.shape[1]
bidirectional = True
output_size = hidden_size * (1 + bidirectional)
vocal_size = 10

input = []
for i in range(10):
    m = np.ones((10000,10))*i
    input.append(m)
input = np.array(input)
input = torch.from_numpy(input).type(torch.FloatTensor)

class pointer_atten(nn.Module):
    def __init__(self):
        super(pointer_atten, self).__init__()
        self.layer1 = Encoder(input_size = input_size,
                              hidden_size = hidden_size,
                              batch_size = batch_size,
                              bidirectional=True)
        self.layer2 = AttentionDecoder(
            hidden_size = hidden_size * (1 + bidirectional),
            output_size = output_size,
            batch_size = batch_size,
            vocab_size = vocal_size,
            seq_len = 1
        )

    def forward(self,x):
        output, hidden = self.layer1.forward(x, self.layer1.init_hidden())
        hidden0 = hidden[0].transpose(0, 1).reshape(batch_size, 1, -1).transpose(0, 1)
        hidden1 = hidden[1].transpose(0, 1).reshape(batch_size, 1, -1).transpose(0, 1)
        decoder_hidden = (hidden0, hidden1)
        encoder_outputs = output
        last_output = self.layer2.forward(decoder_hidden, output, input)

        return last_output

Net = pointer_atten()

learning_rate = 0.05
Loss = nn.MSELoss(reduction='mean')
optimizer = torch.optim.Adam(Net.parameters(), lr=learning_rate)

###########################################
# train
###########################################
loss_list = []
True_list = []
num_epochs = 10000
epoch = 10000
batch = train_aim.detach().numpy().size

Net.load_state_dict(torch.load('E:\\quant_research\\train the rank of ten points\\RNN_point\\net_10num\\net720.pkl'))

for epoch in range(1000):
    train_data = Variable(train_data,requires_grad=True)
    train_aim = Variable(train_aim,requires_grad=True)

    # Forward pass
    outputs = Net(train_data)
    loss = Loss(outputs, train_aim)
    loss_list.append(loss)

    # Backward and optimize
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if (epoch) % 10 == 0:
        print ('Epoch [{}/{}], Loss: {:.4f}'
               .format(epoch+1,num_epochs,loss.item()))

        is_not = outputs.detach().numpy() - train_aim.detach().numpy()
        is_not = np.where(is_not < -0.1, 10, is_not)
        is_not = np.where(is_not < 0.1, 1, 0)
        T_pre = np.nansum(is_not)
        True_rate = T_pre / batch
        True_list.append(True_rate)
        print('accuracy of prediction in training data:', True_rate)

    if epoch % 10 ==0:
        torch.save(Net.state_dict(), 'E:\\quant_research\\train the rank of ten points\\\RNN_point\\net_10num\\net{}.pkl'.format(epoch))

loss_array = np.array(loss_list)
true_array = np.array(True_list)
np.save('E:\\quant_research\\train the rank of ten points\\\RNN_point\\loss',loss_array)
np.save('E:\\quant_research\\train the rank of ten points\\\RNN_point\\true',true_array)

loss_array = np.load('E:\\quant_research\\train the rank of ten points\\\RNN_point\\loss.npy',allow_pickle=True)
true_array = np.load('E:\\quant_research\\train the rank of ten points\\\RNN_point\\true.npy')

outputs = Net(train_data)
loss = Loss(outputs, train_aim)
label = np.argmax(outputs.detach().numpy(),axis = 1)
label_aim = np.argmax(train_aim.detach().numpy(),axis = 1)
True_rate = np.sum(label == label_aim) / 10000
print('loss in testing data:%.5f，accuracy of prediction in testing data:%.5f'%(loss,True_rate))

outputs = Net(test_data)
loss = Loss(outputs, test_aim)
label = np.argmax(outputs.detach().numpy(),axis = 1)
label_aim = np.argmax(test_aim.detach().numpy(),axis = 1)
True_rate = np.sum(label == label_aim) / 10000
print('loss in training data:%.5f，accuracy of prediction in training data:%.5f'%(loss,True_rate))


import tkinter as tk
from tkinter import simpledialog

ROOT = tk.Tk()
ROOT.withdraw()

def is_even(a):
    return a % 2 == 0

def simple_gui_input(text='값을 입력하세요'):
    user_input = simpledialog.askstring(title='6. 짝수의 합 구하기', prompt=text)
    try:
        return int(user_input)
    except ValueError:
        print('유효한 값을 입력하세요.')

def main():
    # a = int(input("숫자를 입력하세요."))
    start_nb = simple_gui_input('시작점을 입력하세요.')
    end_nb = simple_gui_input('끝점을 입력하세요.')
    evens = [x for x in range(start_nb, end_nb+1) if is_even(x)]
    sum_even = sum(evens)

    print(f"{start_nb}-{end_nb}까지 숫자 중 짝수의 합은 {sum_even}입니다.")

if __name__ == "__main__":
    main()


from base import Screen
import curses
from math import sin, cos, pi
from time import sleep, strftime
from datetime import datetime
from threading import Lock, Thread

class TimeClock(Screen):
    name = '时钟'
    used_pairs = (
        (curses.COLOR_BLACK, curses.COLOR_WHITE),
        (curses.COLOR_YELLOW, -1),
        (curses.COLOR_RED, -1),
        (curses.COLOR_GREEN, -1)
    )
    styles = None
    clock_str = '''
          ***********
      ****    XII    ****
    **  XI            I  **
   *                       *
  * X                    II *
 *                           *
 *                           *
** IX          *         III **
 *                           *
 *                           *
  * VIII                 IV *
   *                       *
    **  VII           V  **
      ****     VI    ****
          ***********
'''
    # version 0
    # r'''
          # ***********
      # ****    XII    ****
    # **  XI           I   **
   # *               /       *
  # *  X         |  /     II  *
 # *             | /           *
 # *             |/            *
# **  IX         *        III  **
 # *              \            *
 # *               \           *
  # * VIII          \     IV  *
   # *               \       *
    # **  VII         \ V  **
      # ****     VI    ****
          # ***********
    # '''
    clock_height = 15
    clock_width = 31
    clock_radio = 15
    clock_hour_rate = 0.4
    clock_min_rate = 0.55
    clock_sec_rate = 0.65
    '''convert_table = [
        (pi/2, '|'), (pi/3, '/'), (pi/6, '-'), (0, '-'),
        (pi/6*11, '-'), (pi/3*5, '\\'), (pi/2*3, '|'),
        (pi/3*4, '/'), (pi/6*7, '-'), (pi, '-'),
        (pi/6*5, '-'), (pi/3*2, '\\')
    ]'''

    end = False
    pad = None
    thread = None

    def __init__(self, scr):
        # if TimeClock.styles is None:
            # curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)
            # curses.init_pair(4, curses.COLOR_YELLOW, -1)
            # curses.init_pair(5, curses.COLOR_RED, -1)
            # curses.init_pair(6, curses.COLOR_GREEN, -1)
            # TimeClock.styles = [
                # curses.color_pair(3), curses.color_pair(4),
                # curses.color_pair(5), curses.color_pair(6)
            # ]
        Screen.__init__(self, scr)
        self.lock = Lock()
        self.alloc_space()
        self.draw_clock()

    def alloc_space(self):
        if self.maxx < 33 or self.maxy < 23:
            self.clock_scr = None
            self.time_scr = self.scr.subwin(1,
                self.maxx, (self.maxy - 1) // 2, 0)
            self.mode = 1
            return
        self.mode = 0
        width = TimeClock.clock_width
        height = TimeClock.clock_height
        clock_x = (self.maxx - width) // 2
        if self.maxy > 30:
            clock_y = (self.maxy - height - 6) // 2
            time_y = clock_y + height + 3
        else:
            clock_y = 3
            time_y = clock_y + height + 2
        self.clock_scr = self.scr.derwin(height, width, clock_y, clock_x)
        self.time_scr = self.scr.derwin(1, self.maxx, time_y, 0)
        # mode:
        # 0: clock painted
        # 1: no clock painting

    def get_clock_pad(self):
        pad = curses.newpad(
            TimeClock.clock_height,
            TimeClock.clock_width)
        border_style, char_style = TimeClock.styles[0:2]
        x = y = 0
        for ch in TimeClock.clock_str[1:-1]:
            if ch == '\n' or ch == '\r':
                x = 0
                y += 1
                continue
            if ch == '*':
                pad.addch(y, x, '■', border_style)
            elif ch != ' ':
                pad.addch(y, x, ch, char_style)
            x += 1
        return pad

    def draw_clock(self):
        if self.end or self.mode == 1:
            return

        # load time
        now = datetime.now()
        hour, minute, second = now.hour, now.minute, now.second
        del now

        # self.clock_scr.erase()
        min_style, hour_style, sec_style = TimeClock.styles[1:]
        '''x = y = 0
        for ch in TimeClock.clock_str[1:-1]:
            if ch == '\n' or ch == '\r':
                x = 0
                y += 1
                continue
            if ch == '*':
                self.clock_scr.addch(y, x, '■', border_style)
            elif ch != ' ':
                self.clock_scr.addch(y, x, ch, char_style)
            x += 1'''
        if self.pad is None:
            self.pad = self.get_clock_pad()
        endy = TimeClock.clock_height - 1
        endx = TimeClock.clock_width - 1
        self.pad.overwrite(self.clock_scr, 0, 0, 0, 0, endy, endx)

        # draw clock hands
        self.draw_hand(second / 5,
            TimeClock.clock_sec_rate, sec_style)
        self.draw_hand(minute / 5 + second / 300,
            TimeClock.clock_min_rate, min_style)
        self.draw_hand(hour + minute / 60,
            TimeClock.clock_hour_rate, hour_style)

        # end drawing
        self.clock_scr.refresh()

    def draw_hand(self, time, rate, style):
        # for style, see 'version 0' comment
        rd = TimeClock.clock_radio
        start_y = rd // 2
        start_x = rd
        # rad, ch = self.__convert_table[time % 12]
        time %= 12
        block = (15 - time) % 12
        rad = block * pi / 6
        if 1.8 <= time <= 4.2 or 7.8 <= time <= 10.2:
            ch = '-'
        elif 2.5 <= block <= 3.5 or 8.5 <= block <= 9.5:
            ch = '|'
        elif 0 <= block <= 3 or 6 <= block <= 9:
            ch = '/'
        else:
            ch = '\\'
        sin_rad = sin(rad)
        cos_rad = cos(rad)
        end_y = int(-sin_rad * rd / 2 * rate) + start_y
        end_x = int(cos_rad * rd * rate) + start_x
        if end_x == start_x:
            if end_y > start_y:
                for y in range(start_y + 1, end_y + 1):
                    self.clock_scr.addch(y, end_x, ch, style)
            else:
                for y in range(start_y - 1, end_y - 1, -1):
                    self.clock_scr.addch(y, end_x, ch, style)
            return
        if end_y == start_y:
            if end_x > start_x:
                for x in range(start_x + 1, end_x + 1):
                    self.clock_scr.addch(end_y, x, ch, style)
            else:
                for x in range(start_x - 1, end_x - 1, -1):
                    self.clock_scr.addch(end_y, x, ch, style)
            return
        if 1.5 <= time <= 4.5 or 7.5 <= time <= 10.5:
            tan = (end_y - start_y) / (end_x - start_x)
            if end_x > start_x:
                for x in range(start_x + 1, end_x + 1):
                    y = tan * (x - start_x) + start_y
                    self.clock_scr.addch(round(y), x, ch, style)
            else:
                for x in range(start_x - 1, end_x - 1, -1):
                    y = tan * (x - start_x) + start_y
                    self.clock_scr.addch(round(y), x, ch, style)
        else:
            tan = (end_x - start_x) / (end_y - start_y)
            if end_y > start_y:
                for y in range(start_y + 1, end_y + 1):
                    x = tan * (y - start_y) + start_x
                    self.clock_scr.addch(y, round(x), ch, style)
            else:
                for y in range(start_y - 1, end_y - 1, -1):
                    x = tan * (y - start_y) + start_x
                    self.clock_scr.addch(y, round(x), ch, style)

    def draw_time(self):
        if self.end:
            return
        msg = strftime('%a %b %d %Y %H:%M:%S %Z')
        x = (self.maxx - len(msg)) // 2
        self.time_scr.erase()
        self.time_scr.addstr(0, x, msg)
        self.time_scr.refresh()

    def on_load(self):
        self.draw_time()
        self.draw_clock()
        self.thread = Thread(target=self.target)
        self.thread.start()

    def target(self):
        while not self.end:
            for i in range(8):
                sleep(0.1)
                if self.end:
                    return
            self.lock.acquire()
            self.draw_time()
            self.draw_clock()
            self.lock.release()

    def on_unload(self):
        self.lock.acquire()
        self.end = True
        self.scr.erase()
        self.scr.refresh()
        self.lock.release()
        if self.thread is not None:
            self.thread.join()
            self.thread = None

    def on_resize(self):
        self.lock.acquire()
        Screen.on_resize(self)
        self.alloc_space()
        self.scr.erase()
        self.scr.refresh()
        self.draw_clock()
        self.draw_time()
        self.lock.release()

export = TimeClock


import tkinter as tk
import sys

class Menu():
    def __init__(self,master):

        self.master=master
        self.master.geometry("330x350")
        self.master.title("Blackjack")

        self.titleLabel=self.Label(self,text="Blackjack",bg='green',font=("Arial",12),width=25,height=2)
        self.titleLabel.place(x=50, y=0)

        self.playBtn=tk.Button(self,text="1. Play the Game",font=("Arial",12),width=25,height=2,command=play(root))
        self.playBtn.place(x=50, y=70)

        self.displayBtn=tk.Button(self,text="2. Display Availabel Founds",font=("Arial",12),width=25,height=2)
        self.displayBtn.place(x=50, y=125)

        self.resetBtn=tk.Button(self,text="3. Reset Funds to Zero",font=("Arial",12),width=25,height=2)
        self.resetBtn.place(x=50, y=180)

        self.quitBtn=tk.Button(self,text="4. Quit",font=("Arial",12),width=25,height=2)
        self.quitBtn.place(x=50, y=235)

    def playPage(self):
        root2=Toplevel(self.master)
        myPlay=PlayPage(root2)

class PlayPage():
    def __init__(self,master):
        self.master=master
        self.master.geometry("330x350")
        self.master.title("Blackjack")

def main():
    root=tk.Tk()
    myMenu=Menu(root)
    root.mainloop()

if __name__ == "__main__":
    main()


from GenericTree import *

def isIdentical(tree1, tree2):
    if (tree1 or tree2) is None:
        return None
    q1 = queue.Queue()
    q1.put(tree1)
    q2 = queue.Queue()
    q2.put(tree2)
    if tree1.data != tree2.data:
        return False

    while (not(q1.empty())) and (not(q2.empty())):
        node1 = q1.get()
        node2 = q2.get()
        l1 = []
        l2 = []
        for i in node1.children:
            l1.append(i.data)
        for i in node2.children:
            l2.append(i.data)
        if l2 != l1:
            return False
    return True
root2 = list(map(int,input().split()))
root2 = inputLevelWise(root2)
print(isIdentical(root,root2))


# Creator: Alexander Ryan
# Task allocated by TradeWeb - Mike Byrne

# Tasks:
# System to cache sovereign bonds consiting of a 4 part string
# Add and cancel orders
# Queries:
#   Search for Bond ID
#   Return all Bond IDs above a specified quantity (buy and sell)
#   Total quantity of orders
#   Difference between buy and sell
# Run and compile code
# Tests required

import re

def _trade(trade, cache_ids, cached_trades):
    if not re.fullmatch("ID([0-9])+ Bond[A-Z] '*[BS]'* [1-9][0-9]*", trade):  # Check matched format
        return "Incorrect trade format", True, cached_trades  # Due to wrong input
    trade_id = trade.split(" ")[0]
    if trade_id in cache_ids:
        return "Order ID already present!", True, cached_trades  # Due to wrong input
    cached_trades.append(trade)
    return f"Order cached: {trade}", False, cached_trades  # Success! End trading loop and return to start

def _cancel(cancel_id, cache_ids, cached_trades):
    if not re.fullmatch("ID[0-9]+", cancel_id):  # Check matched format
        return "\nIncorrect cancel format", True, cached_trades  # Due to wrong input
    if cancel_id not in cache_ids:
        return "\nTrade not cached", True, cached_trades  # Due to wrong input
    cached_trades = [order_id for order_id in cached_trades if cancel_id not in order_id]
    return "\nCache canceled", False, cached_trades  # Success! End canceling loop and return to start

def total_q(_input, directions):
    if _input in ("B", "S"):
        return f"{directions.count(_input)}"  # return the number of buy or sell trades
    elif _input == "ALL":
        return f"{len(directions)}"
    else:  # Fail if not B, S, or All
        return "Incorrect input"

def diff_q(directions):
    bought = directions.count("B")  # counts only the buy trades
    sold = len(directions) - bought  # finds sale trades
    return f"Number of trades Bought: {bought} and Sold: {sold}\n"

def quantity_q(quantity, quantities):
    if not re.fullmatch("[1-9][0-9]*", quantity):
        return "Incorrect quantity", True  # Due to wrong format or invalid number
    else:
        # count being the number of trades with a higher quantity value
        count = len([quant for quant in quantities
                     if quantity.isnumeric() and int(quant) > int(quantity)])
        return count, False  # Success, end quantity query loop

def bond_q(bond, bond_ids):
    if not re.fullmatch("Bond[A-Z]+", bond):  # Check format matched
        return "Incorrect format\n", True  # Due to wrong input
    elif bond not in bond_ids:  # Success due to either bond being found or not
        return "False", False
    else:
        return "True", False

def _query(query, queries, bond_ids, quantities, directions):
    if query not in queries:
        return "\nIncorrect query", True
    if query == "bond":  # Bond section
        bonding = True  # Keeping bond query running until success
        while bonding:
            bond = input("Input a Bond_ID in the form 'BondA': ")
            prin, bonding = bond_q(bond, bond_ids)
            print(prin)
            # bonding = bon
        return "", True
    elif query == "quantity":  # Quantity section
        quantifying = True  # Keeping bond query running until success
        while quantifying:
            quantity = input("Input a quantity higher than 0: ")
            prin, quantifying = quantity_q(quantity, quantities)
            print(prin)
            # quantifying = quan
        return "", True
    elif query == "total":  # Total section, enforce upper to normalise
        total = input("Input a direction either All or B or S: ").upper()
        print(total_q(total, directions))
        return "", True

    elif query == "diff":  # Difference section
        print(diff_q(directions))
        return "", True
    else:  # Exit queries
        return "", False

def cacher():
    cached_trades = []  # Store all information
    while True:
        cache_ids = [cache.split(" ")[0] for cache in cached_trades]  # Divide info. into different lists
        bond_ids = [cache.split(" ")[1] for cache in cached_trades]
        directions = [cache.split(" ")[2] for cache in cached_trades]
        quantities = [cache.split(" ")[3] for cache in cached_trades]

        process = input("Would you like to trade, cancel, query or exit: ").lower()  # Normalise with lower
        processes = ("trade", "cancel", "query", "exit")
        if process in processes:  # Make sure only a few options are available

            if process == "trade":  # Adding section
                trading = True  # Sets up an individual while loops to keep trading running until success
                while trading:
                    trade = input("Insert a trade, in the form - ID1 BondD B 10000: ").replace("'", "")  # Clean input
                    prin, trading, cached_trades = _trade(trade, cache_ids, cached_trades)
                    print(prin)
                    # trading = trad

            elif process == "cancel":  # Cancel section
                canceling = True  # Sets up an individual while loops to keep canceling running until success
                while canceling:
                    if len(cached_trades) == 0:
                        print("No trades cached to cancel")
                        canceling = False
                    else:
                        cancel_id = input(f"Please select an Order_ID from the following: "
                                          f"\n {cached_trades} \n In the form 'ID1: ")
                        prin, canceling, cached_trades = _cancel(cancel_id, cache_ids, cached_trades)
                        print(prin)
                        # canceling = can
            elif process == "query":  # Query section
                querying = True  # Keeping the section running until success or exit chosen
                while querying:
                    if len(cached_trades) == 0:  # Check if any trades present before moving on
                        print("No trades cached to query")
                        querying = False  # End while loop
                    else:  # Trades are present
                        query = input(f"\tSearch if a Bond ID is cached - with 'bond'"
                                      f"\n\tBond IDs above a specified quantity (buy and sell)  - with 'quantity'"
                                      f"\n\tTotal number of cached trades - with 'total'"
                                      f"\n\tDifference between buy and sell trades - with 'diff'"
                                      f"\n\tOr Exit - with exit"
                                      f"\nChoose a query from above: ").lower()  # Normalise with lower
                        queries = ('bond', 'quantity', 'total', 'diff', "exit")
                        prin, querying = _query(query, queries, bond_ids, quantities, directions)
                        print(prin)
                        # querying = que
            else:  # Exit program
                break
        else:  # Wrong Input
            print("Wrong input.")
        print(f"\nCurrent Cache:  {cached_trades}\n")  # Show current cached trades

if __name__ == '__main__':
    cacher()


import pygame
from pygame.sprite import Sprite

class Alien(Sprite):
    """a single alien class"""

    def __init__(self, ai_settings, screen):
        """init alien set"""
        super(Alien, self).__init__()
        self.screen = screen
        self.ai_settings = ai_settings

        #load alien image, set it as rect
        self.image = pygame.image.load('images/alien.bmp')
        self.rect = self.image.get_rect()

        #every alien first formed at (0,0)
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

        #storge the right position of alien
        self.x = float(self.rect.x)

    def blitme(self):
        """paint alien at pointed position"""
        self.screen.blit(self.image, self.rect)


from aws_cdk import core
from aws_cdk import aws_apigateway

class APIDeploymentStack(core.NestedStack):
    def __init__(
        self,
        scope,
        *,
        rest_api_id,
        root_resource_id,
        methods=None,
        parameters=None,
        timeout=None
    ):
        super().__init__(
            scope,
            "DeployStack",
            parameters=parameters,
            timeout=timeout,
        )

        deployment = aws_apigateway.Deployment(
            self,
            "Deployment",
            api=aws_apigateway.LambdaRestApi.from_rest_api_attributes(
                self,
                "RestAPI",
                rest_api_id=rest_api_id,
                root_resource_id=root_resource_id,
            ),
        )

        if methods is not None:
            for method in methods:
                deployment.node.add_dependency(method)

        self.deploy(deployment)

class APIProdDeploymentStack(APIDeploymentStack):
    def deploy(self, deployment: aws_apigateway.Deployment) -> aws_apigateway.Stage:
        return aws_apigateway.Stage(
            self,
            "ProdStage",
            deployment=deployment,
            stage_name="prod",
            tracing_enabled=True,
            metrics_enabled=True,
        )

class APIDevDeploymentStack(APIDeploymentStack):
    def deploy(self, deployment: aws_apigateway.Deployment) -> aws_apigateway.Stage:
        return aws_apigateway.Stage(
            self,
            "DevStage",
            deployment=deployment,
            stage_name="dev",
            tracing_enabled=False,
            metrics_enabled=False,
        )


import spotipy
import sys
import pandas as pd
import numpy as np
from spotipy.oauth2 import SpotifyClientCredentials
from get_data import get_audio_features, get_songs, get_playlist_ID, preprocess_data
from model import separate_features, split_data, kNN_model, rf_model, logreg_model, mlp_model
import argparse
import spotipy.util as util
import os
from json.decoder import JSONDecodeError
import collections

def main(userID):
    client_credentials_manager = SpotifyClientCredentials()
    sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

    #Setup Spotify Authentication Protocol
    scope = 'playlist-read-private'
    username = userID
    try:
    	token = util.prompt_for_user_token(username, scope)
    except(AttributeError, JSONDecodeError):
    	os.remove(f".cache-{username}")
    	token = util.prompt_for_user_token(username, scope)
    if token:
    	sp = spotipy.Spotify(auth=token)
    	sp.trace = False

	#Get Consolidated Dataset for selected like and disliked songs
    like, dislike, analyze = get_playlist_ID(userID, sp)
    like_final = pd.DataFrame()
    dislike_final = pd.DataFrame()

    for pair in like:
    	playlist = pair[0]
    	userID = pair[1]
    	like_ids, like_songs = get_songs(userID, playlist, sp)
    	like_audio_features = get_audio_features(like_ids, like_songs, sp)
    	like_final = pd.concat([like_final, like_audio_features], ignore_index = True)

    for pair in dislike:
    	playlist = pair[0]
    	userID = pair[1]
    	dislike_ids, dislike_songs = get_songs(userID, playlist, sp)
    	dislike_audio_features = get_audio_features(dislike_ids, dislike_songs, sp)
    	dislike_final = pd.concat([dislike_final, dislike_audio_features], ignore_index = True)

    #Preprocess data to get a "target" column
    complete_data = preprocess_data(like_final, dislike_final)

    #Seperate features into features and labels dataset
    X, y = separate_features(complete_data)

    #Split data into training and test dataset
    X_train, X_test, y_train, y_test = split_data(X, y)

    #Reshape dimensions of labels (y)
    y_train = np.ravel(y_train)
    y_test = np.ravel(y_test)

    print(len(like_final))
    print(len(dislike_final))
    print(X_train.shape)
    print(X_test.shape)

    rf_model(X_train, X_test, y_train, y_test)
    #kNN_model(X_train, X_test, y_train, y_test)
    #logreg_model(X_train, X_test, y_train, y_test)
    #mlp_model(X_train, X_test, y_train, y_test)

if __name__ == '__main__':
    print('Starting... \n\n')
    parser = argparse.ArgumentParser(description='description')
    parser.add_argument('--username', help='username')
    parser.add_argument('--playlist', help='username')
    args = parser.parse_args()
    main('12165262567')


#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
4.11    同时迭代多个序列
Created on 2016年9月2日
@author: wang
'''

xpts = [1, 5, 4, 2, 10, 7]
ypts = [101, 78, 37, 15, 62, 99]
for x, y in zip(xpts, ypts):
    print(x, y)

a = [1, 2, 3]
b = ['w', 'y', 'z', 'x']
for x, y in zip(a, b):
    print(x, y)

from itertools import zip_longest
for i in zip_longest(a, b):
    print(i)
for i in zip_longest(a, b, fillvalue=0):
    print(i)

a = [1, 2, 3]
b = ['w', 'y', 'z']
c = [7, 8, 9]
for i in zip(a, b, c):
    print(i)


#!/bin/env python

import time
from datetime import datetime

import numpy as np
import pandas as pd
from sportsipy.nfl.boxscore import Boxscore, Boxscores

from definitions import (
    AGG_DROP_COLS,
    AGG_MERGE_ON,
    AGG_RENAME_AWAY,
    AGG_RENAME_HOME,
    AWAY_STATS,
    AWAY_STATS_DROP,
    ELO_DATA_URL,
    ELO_DROP_COLS,
    ELO_TEAMS,
    HOME_STATS,
    HOME_STATS_DROP,
    STD_TEAMS,
)
from utils.logger import log
from utils.utils import read_write_data

def main():
    start_date = "2022-09-08"
    start_date_dt = datetime.strptime(start_date, "%Y-%m-%d")
    end_date = "2023-01-11"
    end_date_dt = datetime.strptime(end_date, "%Y-%m-%d")
    current_week = 18
    collect_data(start_date_dt, end_date_dt, current_week)

def collect_data(start_date: datetime, end_date: datetime, current_week: int) -> None:
    # Get start year from start date
    start_year = int(start_date.year)
    # Get end year from end date
    if end_date.year == start_date.year + 1:
        end_year = int(end_date.year - 1)
    else:
        end_year = int(end_date.year)
    # Create list of weeks to scrape
    weeks = list(range(1, current_week + 1))
    for year in range(start_year, end_year + 1):
        log.info(f"Collecting game data for {year}...")
        # Get and save season's game data
        season_games_name = f"{year}_season_games"
        season_games_df = read_write_data(season_games_name, get_season_data, year, current_week)
        # Get and save season's schedule
        schedule_name = f"{year}_schedule"
        schedule_df = read_write_data(schedule_name, get_schedule, year)
        # Get and save aggregate game data
        agg_games_name = f"{year}_agg_games"
        agg_games_df = read_write_data(
            agg_games_name,
            agg_weekly_data,
            schedule_df,
            season_games_df,
            current_week,
            weeks,
        )
        # Get and save ELO ratings
        elo_name = f"{year}_elo"
        elo_df = read_write_data(elo_name, get_elo, start_date, end_date)
        # Get and save combined data
        combined_data_name = f"{year}_combined_data"
        combined_data_df = read_write_data(combined_data_name, combine_data, agg_games_df, elo_df)
        # Get and save completed games
        comp_games_name = f"{year}_comp_games"
        _ = read_write_data(comp_games_name, parse_completed_games, combined_data_df)
        # Get and save games to predict
        pred_games_name = f"{year}_{current_week}_pred_games"
        _ = read_write_data(pred_games_name, parse_games_to_predict, combined_data_df, current_week)

def get_season_data(year: int, current_week: int) -> pd.DataFrame:
    season_games_df = pd.DataFrame()
    # Step through each week of current season
    for week in range(1, current_week + 1):
        log.info(f"Scraping Week {week} game data...")
        # Get and save week's game data
        week_games_name = f"{year}_{week}"
        week_games_df = read_write_data(week_games_name, get_game_data_by_week, year, week)
        # Concatenate week's game data into season
        season_games_df = pd.concat([season_games_df, week_games_df])
    return season_games_df

def get_game_data_by_week(year: int, week: int) -> pd.DataFrame:
    date_string = f"{week}-{year}"
    week_scores = Boxscores(week, year)
    time.sleep(3)
    week_games_df = pd.DataFrame()
    for game in range(len(week_scores.games[date_string])):
        game_str = week_scores.games[date_string][game]["boxscore"]
        game_stats = Boxscore(game_str)
        time.sleep(3)
        game_df = pd.DataFrame(week_scores.games[date_string][game], index=[0])
        away_team_df, home_team_df = parse_game_data(game_df, game_stats)
        away_team_df["week"] = week
        home_team_df["week"] = week
        away_team_df["year"] = year
        home_team_df["year"] = year
        week_games_df = pd.concat([week_games_df, away_team_df], ignore_index=True)
        week_games_df = pd.concat([week_games_df, home_team_df], ignore_index=True)
    return week_games_df

def parse_game_data(
    game_df: pd.DataFrame, game_stats: Boxscore
) -> tuple[pd.DataFrame, pd.DataFrame]:
    try:
        away_team_df = game_df[["away_name", "away_abbr", "away_score"]].rename(
            columns={
                "away_name": "team_name",
                "away_abbr": "team_abbr",
                "away_score": "score",
            }
        )
        home_team_df = game_df[["home_name", "home_abbr", "home_score"]].rename(
            columns={
                "home_name": "team_name",
                "home_abbr": "team_abbr",
                "home_score": "score",
            }
        )
        try:
            if game_df.loc[0, "away_score"] > game_df.loc[0, "home_score"]:
                away_team_df = pd.merge(
                    away_team_df,
                    pd.DataFrame({"game_won": [1], "game_lost": [0]}),
                    left_index=True,
                    right_index=True,
                )
                home_team_df = pd.merge(
                    home_team_df,
                    pd.DataFrame({"game_won": [0], "game_lost": [1]}),
                    left_index=True,
                    right_index=True,
                )
            elif game_df.loc[0, "away_score"] < game_df.loc[0, "home_score"]:
                away_team_df = pd.merge(
                    away_team_df,
                    pd.DataFrame({"game_won": [0], "game_lost": [1]}),
                    left_index=True,
                    right_index=True,
                )
                home_team_df = pd.merge(
                    home_team_df,
                    pd.DataFrame({"game_won": [1], "game_lost": [0]}),
                    left_index=True,
                    right_index=True,
                )
            else:
                away_team_df = pd.merge(
                    away_team_df,
                    pd.DataFrame({"game_won": [0], "game_lost": [0]}),
                    left_index=True,
                    right_index=True,
                )
                home_team_df = pd.merge(
                    home_team_df,
                    pd.DataFrame({"game_won": [0], "game_lost": [0]}),
                    left_index=True,
                    right_index=True,
                )
        except TypeError:
            away_team_df = pd.merge(
                away_team_df,
                pd.DataFrame({"game_won": [np.nan], "game_lost": [np.nan]}),
                left_index=True,
                right_index=True,
            )
            home_team_df = pd.merge(
                home_team_df,
                pd.DataFrame({"game_won": [np.nan], "game_lost": [np.nan]}),
                left_index=True,
                right_index=True,
            )
        away_stats_df = (
            game_stats.dataframe[AWAY_STATS]
            .reset_index()
            .drop(columns="index")
            .rename(columns=AWAY_STATS_DROP)
        )
        home_stats_df = (
            game_stats.dataframe[HOME_STATS]
            .reset_index()
            .drop(columns="index")
            .rename(columns=HOME_STATS_DROP)
        )
        away_team_df = pd.merge(away_team_df, away_stats_df, left_index=True, right_index=True)
        home_team_df = pd.merge(home_team_df, home_stats_df, left_index=True, right_index=True)
        try:
            away_team_df["time_of_possession"] = (
                int(away_team_df["time_of_possession"].loc[0][0:2]) * 60
            ) + int(away_team_df["time_of_possession"].loc[0][3:5])
            home_team_df["time_of_possession"] = (
                int(home_team_df["time_of_possession"].loc[0][0:2]) * 60
            ) + int(home_team_df["time_of_possession"].loc[0][3:5])
        except TypeError:
            away_team_df["time_of_possession"] = np.nan
            home_team_df["time_of_possession"] = np.nan
    except TypeError:
        away_team_df = pd.DataFrame()
        home_team_df = pd.DataFrame()
    return away_team_df, home_team_df

def get_schedule(year: int) -> pd.DataFrame:
    weeks = list(range(1, 19))
    schedule_df = pd.DataFrame()
    log.info(f"Getting {year} schedule...")
    for week in weeks:
        log.info(f"Week {week}...")
        date_string = f"{week}-{year}"
        week_scores = Boxscores(week, year)
        time.sleep(3)
        week_games_df = pd.DataFrame()
        for game in range(len(week_scores.games[date_string])):
            game_df = pd.DataFrame(week_scores.games[date_string][game], index=[0])[
                [
                    "away_name",
                    "away_abbr",
                    "home_name",
                    "home_abbr",
                    "winning_name",
                    "winning_abbr",
                ]
            ]
            game_df["week"] = week
            week_games_df = pd.concat([week_games_df, game_df])
        schedule_df = pd.concat([schedule_df, week_games_df]).reset_index(drop=True)
    return schedule_df

def agg_weekly_data(
    schedule_df: pd.DataFrame, season_games_df: pd.DataFrame, current_week: int, weeks: list
) -> pd.DataFrame:
    schedule_df = schedule_df[schedule_df.week < current_week + 1]
    agg_games_df = pd.DataFrame()
    for week in weeks:
        games_df = schedule_df[schedule_df.week == week]
        agg_weekly_df = (
            season_games_df[season_games_df.week < week]
            .drop(columns=["score", "week", "year", "game_won", "game_lost"])
            .groupby(by=["team_name", "team_abbr"])
            .mean()
            .reset_index()
        )
        win_loss_df = (
            season_games_df[season_games_df.week < week][
                ["team_name", "team_abbr", "game_won", "game_lost"]
            ]
            .groupby(by=["team_name", "team_abbr"])
            .sum()
            .reset_index()
        )
        win_loss_df["win_perc"] = win_loss_df["game_won"].div(
            win_loss_df["game_won"] + win_loss_df["game_lost"]
        )
        win_loss_df.loc[~np.isfinite(win_loss_df["win_perc"]), "win_perc"] = 0
        win_loss_df = win_loss_df.drop(columns=["game_won", "game_lost"])
        agg_weekly_df["fourth_down_perc"] = agg_weekly_df["fourth_down_conversions"].div(
            agg_weekly_df["fourth_down_attempts"]
        )
        agg_weekly_df.loc[~np.isfinite(agg_weekly_df["fourth_down_perc"]), "fourth_down_perc"] = 0
        agg_weekly_df["fourth_down_perc"] = agg_weekly_df["fourth_down_perc"].fillna(0)
        agg_weekly_df["third_down_perc"] = agg_weekly_df["third_down_conversions"].div(
            agg_weekly_df["third_down_attempts"]
        )
        agg_weekly_df.loc[~np.isfinite(agg_weekly_df["third_down_perc"]), "third_down_perc"] = 0
        agg_weekly_df["third_down_perc"] = agg_weekly_df["third_down_perc"].fillna(0)
        agg_weekly_df = agg_weekly_df.drop(
            columns=[
                "fourth_down_attempts",
                "fourth_down_conversions",
                "third_down_attempts",
                "third_down_conversions",
            ]
        )
        agg_weekly_df = pd.merge(
            win_loss_df,
            agg_weekly_df,
            left_on=["team_name", "team_abbr"],
            right_on=["team_name", "team_abbr"],
        )
        away_df = (
            pd.merge(
                games_df,
                agg_weekly_df,
                how="inner",
                left_on=["away_name", "away_abbr"],
                right_on=["team_name", "team_abbr"],
            )
            .drop(columns=["team_name", "team_abbr"])
            .rename(columns=AGG_RENAME_AWAY)
        )
        home_df = (
            pd.merge(
                games_df,
                agg_weekly_df,
                how="inner",
                left_on=["home_name", "home_abbr"],
                right_on=["team_name", "team_abbr"],
            )
            .drop(columns=["team_name", "team_abbr"])
            .rename(columns=AGG_RENAME_HOME)
        )
        agg_weekly_df = pd.merge(away_df, home_df, left_on=AGG_MERGE_ON, right_on=AGG_MERGE_ON)
        agg_weekly_df["win_perc_dif"] = (
            agg_weekly_df["away_win_perc"] - agg_weekly_df["home_win_perc"]
        )
        agg_weekly_df["first_downs_dif"] = (
            agg_weekly_df["away_first_downs"] - agg_weekly_df["home_first_downs"]
        )
        agg_weekly_df["fumbles_dif"] = agg_weekly_df["away_fumbles"] - agg_weekly_df["home_fumbles"]
        agg_weekly_df["interceptions_dif"] = (
            agg_weekly_df["away_interceptions"] - agg_weekly_df["home_interceptions"]
        )
        agg_weekly_df["net_pass_yards_dif"] = (
            agg_weekly_df["away_net_pass_yards"] - agg_weekly_df["home_net_pass_yards"]
        )
        agg_weekly_df["pass_attempts_dif"] = (
            agg_weekly_df["away_pass_attempts"] - agg_weekly_df["home_pass_attempts"]
        )
        agg_weekly_df["pass_completions_dif"] = (
            agg_weekly_df["away_pass_completions"] - agg_weekly_df["home_pass_completions"]
        )
        agg_weekly_df["pass_touchdowns_dif"] = (
            agg_weekly_df["away_pass_touchdowns"] - agg_weekly_df["home_pass_touchdowns"]
        )
        agg_weekly_df["pass_yards_dif"] = (
            agg_weekly_df["away_pass_yards"] - agg_weekly_df["home_pass_yards"]
        )
        agg_weekly_df["penalties_dif"] = (
            agg_weekly_df["away_penalties"] - agg_weekly_df["home_penalties"]
        )
        agg_weekly_df["points_dif"] = agg_weekly_df["away_points"] - agg_weekly_df["home_points"]
        agg_weekly_df["rush_attempts_dif"] = (
            agg_weekly_df["away_rush_attempts"] - agg_weekly_df["home_rush_attempts"]
        )
        agg_weekly_df["rush_touchdowns_dif"] = (
            agg_weekly_df["away_rush_touchdowns"] - agg_weekly_df["home_rush_touchdowns"]
        )
        agg_weekly_df["rush_yards_dif"] = (
            agg_weekly_df["away_rush_yards"] - agg_weekly_df["home_rush_yards"]
        )
        agg_weekly_df["time_of_possession_dif"] = (
            agg_weekly_df["away_time_of_possession"] - agg_weekly_df["home_time_of_possession"]
        )
        agg_weekly_df["times_sacked_dif"] = (
            agg_weekly_df["away_times_sacked"] - agg_weekly_df["home_times_sacked"]
        )
        agg_weekly_df["total_yards_dif"] = (
            agg_weekly_df["away_total_yards"] - agg_weekly_df["home_total_yards"]
        )
        agg_weekly_df["turnovers_dif"] = (
            agg_weekly_df["away_turnovers"] - agg_weekly_df["home_turnovers"]
        )
        agg_weekly_df["yards_from_penalties_dif"] = (
            agg_weekly_df["away_yards_from_penalties"] - agg_weekly_df["home_yards_from_penalties"]
        )
        agg_weekly_df["yards_lost_from_sacks_dif"] = (
            agg_weekly_df["away_yards_lost_from_sacks"]
            - agg_weekly_df["home_yards_lost_from_sacks"]
        )
        agg_weekly_df["fourth_down_perc_dif"] = (
            agg_weekly_df["away_fourth_down_perc"] - agg_weekly_df["home_fourth_down_perc"]
        )
        agg_weekly_df["third_down_perc_dif"] = (
            agg_weekly_df["away_third_down_perc"] - agg_weekly_df["home_third_down_perc"]
        )
        agg_weekly_df = agg_weekly_df.drop(columns=AGG_DROP_COLS)
        if agg_weekly_df["winning_name"].isna().values.any():
            if agg_weekly_df["winning_name"].isna().sum() == agg_weekly_df.shape[0]:
                agg_weekly_df["result"] = np.nan
                log.info(f"Week {week} games have not finished yet.")
            else:
                agg_weekly_df.loc[agg_weekly_df["winning_name"].isna(), "result"] = 0
                agg_weekly_df["result"] = agg_weekly_df["result"].astype("float")
        else:
            agg_weekly_df["result"] = agg_weekly_df["winning_name"] == agg_weekly_df["away_name"]
            agg_weekly_df["result"] = agg_weekly_df["result"].astype("float")
        agg_weekly_df = agg_weekly_df.drop(columns=["winning_name", "winning_abbr"])
        agg_games_df = pd.concat([agg_games_df, agg_weekly_df])
    agg_games_df = agg_games_df.reset_index(drop=True)
    return agg_games_df

def get_elo(start_date: datetime, end_date: datetime) -> pd.DataFrame:
    elo_df = pd.read_csv(ELO_DATA_URL)
    # elo_df = pd.read_csv("./utils/nfl_elo.csv")
    elo_df = elo_df.drop(columns=ELO_DROP_COLS)
    elo_df["date"] = pd.to_datetime(elo_df["date"])
    mask = (elo_df["date"] >= start_date) & (elo_df["date"] <= end_date)
    elo_df = elo_df.loc[mask]
    elo_df["team1"] = elo_df["team1"].replace(ELO_TEAMS, STD_TEAMS)
    elo_df["team2"] = elo_df["team2"].replace(ELO_TEAMS, STD_TEAMS)
    return elo_df

def combine_data(agg_games_df: pd.DataFrame, elo_df: pd.DataFrame) -> pd.DataFrame:
    agg_games_df = pd.merge(
        agg_games_df,
        elo_df,
        how="inner",
        left_on=["home_abbr", "away_abbr"],
        right_on=["team1", "team2"],
    ).drop(columns=["date", "team1", "team2"])
    agg_games_df["elo_dif"] = agg_games_df["elo2_pre"] - agg_games_df["elo1_pre"]
    agg_games_df["qb_dif"] = agg_games_df["qb2_value_pre"] - agg_games_df["qb1_value_pre"]
    agg_games_df = agg_games_df.drop(
        columns=["elo1_pre", "elo2_pre", "qb1_value_pre", "qb2_value_pre"]
    )
    return agg_games_df

def parse_completed_games(combined_data_df: pd.DataFrame) -> pd.DataFrame:
    comp_games_df = combined_data_df[combined_data_df["result"].notna()]
    return comp_games_df

def parse_games_to_predict(combined_data_df: pd.DataFrame, current_week: int) -> pd.DataFrame:
    pred_games_df = pd.DataFrame(combined_data_df[combined_data_df["week"] == current_week])
    return pred_games_df

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
"""
Created on Wed Jun 21 11:23:57 2023

@author: athar
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

path = r"C:\Users\athar\OneDrive\Desktop\Machine learning\Projects\SimpleLinearRegressionDataset\HtWt.csv"

df = pd.read_csv(path)

X = df['Height']
y = df['Weight']

#explore the dataset
plt.scatter(X, y, color='blue')
plt.xlabel('Height')
plt.ylabel('Weight')
plt.show()

#data preprocessing
X = np.asanyarray(X).reshape(-1, 1)
y = np.asanyarray(y)

#splitting the dataset
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=42)

#training
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train,y_train)

slope = regressor.coef_
intercept = regressor.intercept_

#visualizing the model
equation = slope*X_test + intercept

plt.scatter(X_test, y_test, color = 'blue')
plt.plot(X_test, equation,color = 'green')
plt.show()

#evaluating the model
from sklearn.metrics import mean_squared_error, r2_score
mse = mean_squared_error(y_test, equation)
r_squared = r2_score(y_test, equation)
print('Mean_Squared_Error :' ,mse)
print('r_square_value :',r_squared)


def appendAndDelete(s, t, k):
    # Write your code here
    ls = len(s)
    lt = len(t)
    i = 0
    while i < ls and i < lt and s[i] == t[i]:
        i += 1
    if k >= ls + lt:
        return 'Yes'
    elif k >= ls + lt - 2*i and (k - ls - lt + 2*i) % 2 == 0:
        return 'Yes'
    else :
        return 'No'


'''Последовательность Фибоначчи определяется рекурсивным правилом:

Fn = Fn−1 + Fn−2, где F1 = 1 и F2 = 1.
Таким образом, первые 12 членов последовательности равны:

F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
Двенадцатый член F12 - первый член последовательности, который содержит три цифры.

Каков порядковый номер первого члена последовательности Фибоначчи, содержащего 1000 цифр?
'''

import math
from time import time

# число цифр
nn = 1000

# Последовательность Фибоначчи
def fibo(n):
    a, b = 0, 1
    for __ in range(n): a, b = b, a + b
    return a

def find_long_m(n):
    k = 1
    f_k = 0
    while f_k < n:
        fibo_k = fibo(k)
        f_k = len(str(fibo_k))
        k += 1
    return [k, fibo_k]

t1 = time()
answ = find_long_m(nn)[0]
print("порядковый номер первого члена последовательности Фибоначчи, содержащего ", nn, " цифр равоно ", answ)
t2 = time()
print("время выполнения", t2 - t1)


class Merge:
    '''
     Merge Sort
      - It is a divide and conquer algorithm
      - Divide the input array in two halves, and we keep having recursively until they become too small that cannot be broken further
      - merge halves by sorting them
      Time O(N logN) space O(n)
      merge sort is out place algorithm
      merge sort is stable
      when to use merge sort?
      - when you need stable sort
      - when average expected time in O(N logN)
      when to avoid stable sort?
      - when space is a concern
    '''

    @staticmethod
    def merge(left, right):
        result = []
        i, j = 0, 0
        while i < len(left) and j < len(right):
            if left[i] < right[j]:
                result.append(left[i])
                i += 1
            else:
                result.append(right[j])
                j += 1
        result += left[i:]
        result += right[j:]
        return result

    @staticmethod
    def merge_sort(array):
        if len(array) <= 1:
            return array
        mid = int(len(array)/2)
        left = Merge.merge_sort(array[:mid])
        right = Merge.merge_sort(array[mid:])
        return Merge.merge(left, right)

numbers = [8, 1, 6, 2, 7, 4]

if __name__ == "__main__":
    print(Merge.merge_sort(numbers))

24 - Sorting Algorithms/Sorting Algorithms Techniques/05. Merge Sort.py


import sys
import os
import ctypes

from pdt_uac import *
from pdt_bin_buf import *
from pdt_win_calls import *
from pdt_patch import *

############## first, get admin rights #############
if not is_admin():
    get_admin()
    #leave commented for now
    #useful for debugging
    sys.exit()

############### init stuff ###########################
if len(sys.argv) != 2:
    proc_id = int(input("input pid: ").strip())
else:
    proc_id = int(sys.argv[1].strip())

print("opening proc {}...".format(proc_id))

proc_handle = OP(PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION, False, proc_id)

if proc_handle == 0:
        print("no proc!")
        print(ctypes.WinError(ctypes.get_last_error()))
        #sys.exit()

################# some patches #######################
god = patch(0x008655F0, bin_buf('90 90 90 90 90'), bin_buf('A3 543C1C01'))
instakill = patch(0x00807A24, bin_buf('29C0'), bin_buf('29F0'))
#hunger 011C4C78
#wall 00A78D77
#xcoord 011C3BAC
#ycoord 011C3BB0
#map 0122B6D8
#wall: 07; floor: 21
######################################################
cmd = ""
while cmd == "" or cmd[0] != "exit":
    cmd = input(">>>>>")
    if cmd == "":
        continue

    cmd = cmd.strip().split()

    if cmd[0] == "damage":
        instakill.toggle(proc_handle)
    if cmd[0] == "god":
        god.toggle(proc_handle)
    if cmd[0] == "pos":
        get_xy(proc_handle)
    if cmd[0] == "modmap":
        if len(cmd) == 4:
            mod_map(proc_handle, int(cmd[1], 10), int(cmd[2], 10), bin_buf(cmd[3]))
        else:
            print("not enough args for modmap")
    if cmd[0] == "dig":
        digger_patch(proc_handle)

CH(proc_handle)


import numpy as np

# ### K-Nearest Neighbors implementacja ###
# W celu klasyfikacji obliczana jest odległość czyli podobieństwo od obiektu który chcemy
# sklasyfikować do obiektów z zestawu testowego.
# Podobieństwo może być wyliczne w różny sposób w przypadku tej implementacji
# będzie to odległość euklidesowa.
class KNN:
    def __init__(self, k) -> None:
        self.k = k

    # Metoda statyczna wyliczająca odlekłość euklidesową pomiędzy dwoma wektorami.
    @staticmethod
    def euclidean(v1, v2):
        vector1 = np.array(v1)
        vector2 = np.array(v2)
        distance = 0
        for i in range(len(vector1) - 1):
            distance += (vector1[i] - vector2[i]) ** 2
        return np.sqrt(distance)

    # Prosta ocena naczego algorytmu,
    # weryfikacja w ilu przypadkach algorytm poprawnie zaklasyfikował obiekt.
    @staticmethod
    def evaluate(y, y_pred):
        correct = 0
        best = len(y)
        for i in range(len(y)):
            if y[i] == y_pred[i]:
                correct += 1
        return correct / best

    def predict(self, train_set, test_object):
        # Oblicz odległość euklidesową między obiektem do klasyfikacji,
        # a każdą obiektem testowym i zapisz ją do tablicy distances.
        distances = []
        for i in range(len(train_set)):
            distance = self.euclidean(train_set.iloc[i][:-1], test_object)
            distances.append((train_set.iloc[i], distance))
        # Posortuj uzyskane dystansy od najkrótszego do najdłuższego
        distances.sort(key=lambda x: x[1])

        # Z posortowanych dystansów weź k najkrótszych odległości.
        # Czyli k początkowych elementów tablicy.
        neighbors = []
        for i in range(self.k):
            neighbors.append(distances[i][0])

        classes = {}
        # Sprawdź jakiej klasy są k najblisi sąsiedzi.
        for i in range(len(neighbors)):
            # Pobierz klasę dla sąsiada.
            response = neighbors[i][-1]
            # Jeżeli wcześniej już był sąsiad takiej klasy zwiększa wartość dla tej klasy o 1.
            if response in classes:
                classes[response] += 1
            # Jeżeli jest to klasa która wcześniej nie występowała dodaj ją do obiektu classes.
            else:
                classes[response] = 1

        # Po posortowaniu wartości zapisanych w classes, wiemy która klasa występowała najczęściej wśród
        # sąsiadów i do takiej klasy klasyfikujemy nasz obiekt.
        return sorted(classes.items(), key=lambda x: x[1], reverse=True)[0][0]