import pickle
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim

import pandas as pd
import os
import heapq
import sys
import_path = os.path.split(os.path.realpath(__file__))[0] + '/..'
if import_path not in sys.path:
    sys.path.append(import_path)
import time
import random
from itertools import product
from sklearn.preprocessing import MinMaxScaler

from utils.train import Trainer, Plugin
from metrics.RootRelativeSquaredError import RRSE
from metrics.EmpiricalCorrelaionCoefficient import CORR
from metrics.MeanAbsoluteError import MAE
from metrics.MeanSquaredError import MSE
from itertools import product

def ensure_path(path):
    if not os.path.exists(path):
        os.makedirs(path)

def grid_search(*hyper_params):
    for hyper_param in product(*hyper_params):
        yield hyper_param

def get_name_from_params(params):
    params = [str(p) for p in params]
    f = '_'.join(params)
    return f

def get_with_pickle(fn):
    with open(fn, 'rb') as f:
        result = pickle.load(f)
    return result

def save_with_pickle(obj, fn):
    with open(fn, 'wb') as f:
        pickle.dump(obj, f)

class MTSDataset(torch.utils.data.Dataset):
    # data :numpy.array
    # data.shape = (N, feature)
    #mode in ['train', 'valid', 'test']
    def __init__(self, data, window, horizon, mm, mode='train'):
        N, _ = data.shape
        self.window = window
        self.horizon = horizon
        self.mode = mode

        self.nums = N - window - horizon + 1
        self.train_nums = int(self.nums*0.6)
        self.valid_nums = int(self.nums*0.2)

        self.data = torch.from_numpy(mm.fit_transform(data)).float()
        self.mm = mm

    def set_mode(self, mode):
        self.mode = mode

    def __getitem__(self, index):
        begin = None
        if self.mode == 'train':
            begin = 0
        elif self.mode == 'valid':
            begin = self.train_nums
        elif self.mode == 'test':
            begin = self.train_nums + self.valid_nums

        x = self.data[begin+index:begin+index+self.window, :]
        y = self.data[begin+index+self.window+self.horizon-1, :]
        return x, y

    def __len__(self):
        if self.mode == 'train':
            return self.train_nums
        elif self.mode == 'valid':
            return self.valid_nums
        elif self.mode == 'test':
            return self.nums - self.train_nums - self.valid_nums

def setup_seed(seed):
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    np.random.seed(seed)
    random.seed(seed)
    torch.backends.cudnn.deterministic = True

def get_electricity():
    current_file_name = os.path.realpath(__file__)
    current_file_path = os.path.split(current_file_name)[0]
    electricity_file_name = os.path.join(current_file_path, 'electricity/electricity.npy')
    return np.load(electricity_file_name)

def get_exchange_rate():
    current_file_name = os.path.realpath(__file__)
    current_file_path = os.path.split(current_file_name)[0]
    exchange_rate_file_name = os.path.join(current_file_path, 'exchange_rate/exchange_rate.npy')
    return np.load(exchange_rate_file_name)

def get_solar_energy():
    current_file_name = os.path.realpath(__file__)
    current_file_path = os.path.split(current_file_name)[0]
    solar_energy_file_name = os.path.join(current_file_path, 'solar-energy/solar_AL.npy')
    return np.load(solar_energy_file_name)

def get_traffic():
    current_file_name = os.path.realpath(__file__)
    current_file_path = os.path.split(current_file_name)[0]
    traffic_file_name1 = os.path.join(current_file_path, 'traffic/traffic1.npy')
    traffic_file_name2 = os.path.join(current_file_path, 'traffic/traffic2.npy')
    traffic1 =  np.load(traffic_file_name1)
    traffic2 = np.load(traffic_file_name2)
    traffic = np.concatenate([traffic1, traffic2], 0)
    return traffic

def get_dataset(dataset_name, window, horizon):
    dataset_dict = {
        'solar_energy':get_solar_energy,
        'traffic':get_traffic,
        'electricity':get_electricity,
        'exchange_rate':get_exchange_rate
    }
    get = dataset_dict[dataset_name]
    data = get()
    dataset = MTSDataset(data, window, horizon, MinMaxScaler())
    return dataset

class MTSTrainer(Trainer):
    def __init__(self, model, criterion, optimizer, dataset):
        super(MTSTrainer, self).__init__(model, criterion, optimizer, dataset)
        self.jump_out = False
        self.original_dataset = dataset
        self.dataset = None

    def run(self, epochs=1, batch_size=64, shuffle=True):
        for q in self.plugin_queues.values():
            heapq.heapify(q)
        self.dataset = torch.utils.data.DataLoader(self.original_dataset, batch_size=batch_size, shuffle=shuffle, pin_memory=True)
        for i in range(1, epochs + 1):
            self.train(batch_size, shuffle)
            self.call_plugins('epoch', i, i == epochs)
            if self.jump_out:
                break
        self.dataset = None

    def train(self, batch_size, shuffle=True):
        self.original_dataset.set_mode('train')
        super(MTSTrainer, self).train()

class MTSPlugin(Plugin):
    def __init__(self, file_path, limit=10):
        super(MTSPlugin, self).__init__([(1, 'epoch'), (1, 'iteration')])
        self.file_path = file_path
        self.iteration_nums = 0
        self.iteration_loss = 0
        self.limit = limit
        self.counter = 0
        self.validation_best_corr = -1
        self.validation_best_rse = 1
        self.mm = None
        #self.last_time = time.time()

    def register(self, trainer):
        self.trainer = trainer
        self.mm = trainer.original_dataset.mm
        self.trainer.stats['valid_RSE'] = []
        self.trainer.stats['valid_CORR'] = []
        self.trainer.stats['valid_MSE'] = []
        self.trainer.stats['valid_MAE'] = []

        self.trainer.stats['test_RSE'] = []
        self.trainer.stats['test_CORR'] = []
        self.trainer.stats['test_MSE'] = []
        self.trainer.stats['test_MAE'] = []

        self.trainer.stats['train_Loss'] = []

    def epoch(self, time, last_time):
        self.trainer.model.eval()
        stats = self.trainer.stats

        train_loss = self.iteration_loss/self.iteration_nums
        stats['train_Loss'].append(train_loss)
        self.iteration_nums = 0
        self.iteration_loss = 0

        valid_rrse = 0.0
        valid_corr = 0.0
        valid_mse = 0.0
        valid_mae = 0.0

        test_rrse = 0.0
        test_corr = 0.0
        test_mse = 0.0
        test_mae = 0.0

        #mse = nn.MSELoss()
        with torch.no_grad():
            self.trainer.original_dataset.set_mode('valid')
            dataloader = torch.utils.data.DataLoader(self.trainer.original_dataset, batch_size=64, shuffle=False, pin_memory=True)
            valid_pred = []
            valid_y = []
            for (X, Y) in dataloader:
                X = X.cuda()
                predY = self.trainer.model(X)
                valid_pred.append(predY)
                valid_y.append(Y)

            Y = torch.cat(valid_y, 0)
            predY = torch.cat(valid_pred, 0)

            predY = predY.detach().cpu().numpy()
            Y = Y.detach().cpu().numpy()
            predY = self.mm.inverse_transform(predY)
            Y = self.mm.inverse_transform(Y)

            rrse, corr = RRSE(Y, predY), CORR(Y, predY)
            valid_corr = float(corr)
            valid_rrse= float(rrse)
            valid_mse = float(MSE(Y, predY))
            valid_mae = float(MAE(Y, predY))

            self.trainer.original_dataset.set_mode('test')
            test_pred = []
            test_y = []
            for (X, Y) in dataloader:
                X = X.cuda()
                #Y = Y.cuda()
                predY = self.trainer.model(X)
                test_pred.append(predY)
                test_y.append(Y)

            Y = torch.cat(test_y, 0)
            predY = torch.cat(test_pred, 0)

            predY = predY.detach().cpu().numpy()
            Y = Y.detach().cpu().numpy()
            predY = self.mm.inverse_transform(predY)
            Y = self.mm.inverse_transform(Y)

            rrse, corr = RRSE(Y, predY), CORR(Y, predY)
            test_corr = float(corr)
            test_rrse = float(rrse)
            test_mse = float(MSE(Y, predY))
            test_mae = float(MAE(Y, predY))

        stats['valid_RSE'].append(valid_rrse)
        stats['valid_CORR'].append(valid_corr)
        stats['valid_MSE'].append(valid_mse)
        stats['valid_MAE'].append(valid_mae)
        stats['test_RSE'].append(test_rrse)
        stats['test_CORR'].append(test_corr)
        stats['test_MSE'].append(test_mse)
        stats['test_MAE'].append(test_mae)

        self.counter += 1
        if valid_corr - valid_rrse >= self.validation_best_corr - self.validation_best_rse:
            self.validation_best_corr = valid_corr
            self.validation_best_rse = valid_rrse
            self.counter = 0
            self.save_model()

        if self.counter >= self.limit:#提前结束需要保存数据
            self.trainer.jump_out = True
            self.save_stats()
        elif last_time:#如果是最后一次运行也需要保存数据
            self.save_stats()
        self.trainer.model.train()

        #print(f'epochs={time},train_mse={mse},valid_corr={valid_mean_corr},valid_rse={valid_mean_rrse},test_corr={test_mean_corr},test_rse={test_mean_rrse}')
        print(f'epochs={time}')
        print(f'train:loss={train_loss}')
        print(f'valid:mse={valid_mse},mae={valid_mae},rse={valid_rrse},corr={valid_corr}')
        print(f'test:mse={test_mse},mae={test_mae},rse={test_rrse},corr={test_corr}')

    def iteration(self, time, batch_input, batch_target, batch_output, loss):
        L = loss.item()
        #c = time.time()
        #print(f'{c-self.last_time}')
        #self.last_time = c
        self.iteration_loss += L
        self.iteration_nums += 1

    def save_model(self):
        model_file = self.file_path + '.model'
        #with open(model_file, 'wb') as f:
        #    pickle.dump(self.trainer.model.cpu(), f)
        #self.trainer.model.cuda()
        torch.save(self.trainer.model.state_dict(), model_file)

    # def load_model(self):
    #     model_file = self.file_path + '.model'
    #     return torch.load(model_file)

    def save_stats(self):
        stats_file = self.file_path + '.stats'
        with open(stats_file, 'wb') as f:
            pickle.dump(self.trainer.stats, f)

    # def load_stats(self):
    #     stats_file = self.file_path + '.stats'
    #     result = None
    #     with open(stats_file, 'rb') as f:
    #         result = pickle.load(f)
    #     return result

if __name__ == '__main__':
    electricity = get_electricity()
    print('electricity', electricity.shape)
    exchange_rate = get_exchange_rate()
    print('exchange_rate', exchange_rate.shape)
    solar_energy = get_solar_energy()
    print('solar_energy', solar_energy.shape)
    traffic = get_traffic()
    print('traffic', traffic.shape)


import tensorflow as tf
from tensorflow.examples.adding_an_op import cuda_op

class AddOneTest(tf.test.TestCase):

  def test(self):
    if tf.test.is_built_with_cuda():
      result = cuda_op.add_one([5, 4, 3, 2, 1])
      self.assertAllEqual(result, [6, 5, 4, 3, 2])

if __name__ == '__main__':
  tf.test.main()


#!/usr/bin/python3

def iterPower(base, exp):
    '''
    base: int or float.
    exp: int >= 0
    returns: int or float, base^exp
    '''
    _base = 1
    if exp > 0:
        for i in range(exp):
            _base = _base * base
    return _base

if __name__ == "__main__":
    print(iterPower(-2.29, 10))


import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from sklearn import cross_validation
import xgboost as xgb
from sklearn.metrics import roc_auc_score

training = pd.read_csv("../input/train.csv", index_col=0)
test = pd.read_csv("../input/test.csv", index_col=0)

print(training.shape)
print(test.shape)

# Replace -999999 in var3 column with most common value 2
# See https://www.kaggle.com/cast42/santander-customer-satisfaction/debugging-var3-999999
# for details
training = training.replace(-999999,np.nan)
training=training.replace(9999999999,np.nan)

X = training.iloc[:,:-1]
y = training.TARGET

X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, stratify=y, test_size=0.3)

# xgboost parameter tuning with p = 75
# recipe: https://www.kaggle.com/c/bnp-paribas-cardif-claims-management/forums/t/19083/best-practices-for-parameter-tuning-on-models/108783#post108783

ratio = float(np.sum(y == 1)) / np.sum(y==0)
# Initial parameters for the parameter exploration
# clf = xgb.XGBClassifier(missing=9999999999,
#                 max_depth = 10,
#                 n_estimators=1000,
#                 learning_rate=0.1,
#                 nthread=4,
#                 subsample=1.0,
#                 colsample_bytree=0.5,
#                 min_child_weight = 5,
#                 scale_pos_weight = ratio,
#                 seed=4242)

# gives : validation_1-auc:0.845644
# max_depth=8 -> validation_1-auc:0.846341
# max_depth=6 -> validation_1-auc:0.845738
# max_depth=7 -> validation_1-auc:0.846504
# subsample=0.8 -> validation_1-auc:0.844440
# subsample=0.9 -> validation_1-auc:0.844746
# subsample=1.0,  min_child_weight=8 -> validation_1-auc:0.843393
# min_child_weight=3 -> validation_1-auc:0.848534
# min_child_weight=1 -> validation_1-auc:0.846311
# min_child_weight=4 -> validation_1-auc:0.847994
# min_child_weight=2 -> validation_1-auc:0.847934
# min_child_weight=3, colsample_bytree=0.3 -> validation_1-auc:0.847498
# colsample_bytree=0.7 -> validation_1-auc:0.846984
# colsample_bytree=0.6 -> validation_1-auc:0.847856
# colsample_bytree=0.5, learning_rate=0.05 -> validation_1-auc:0.847347
# max_depth=8 -> validation_1-auc:0.847352
# learning_rate = 0.07 -> validation_1-auc:0.847432
# learning_rate = 0.2 -> validation_1-auc:0.846444
# learning_rate = 0.15 -> validation_1-auc:0.846889
# learning_rate = 0.09 -> validation_1-auc:0.846680
# learning_rate = 0.1 -> validation_1-auc:0.847432
# max_depth=7 -> validation_1-auc:0.848534
# learning_rate = 0.05 -> validation_1-auc:0.847347
#

X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, stratify=y, test_size=0.3)

xgbooster = xgb.XGBClassifier(missing=np.nan,
                max_depth = 5,
                n_estimators=1000,
                learning_rate=0.1,
                nthread=4,
                subsample=1.0,
                colsample_bytree=0.5,
                min_child_weight = 3,
                scale_pos_weight = ratio,
                reg_alpha=0.03,
                seed=234)
scorestrain=[]
scorescv=[]
iterations=[]

for i in range(1000,len(X_train),3000) :
    print(i)
    xgbooster.fit(X_train[:i], y_train[:i], early_stopping_rounds=50, eval_metric="auc",
    eval_set=[(X_test, y_test)])
    scorestrain.append(roc_auc_score(y_train[:i], xgbooster.predict_proba(X_train[:i], ntree_limit=xgbooster.best_iteration)[:,1]))
    scorescv.append(roc_auc_score(y_test,xgbooster.predict_proba(X_test,ntree_limit=xgbooster.best_iteration)[:,1]))
    iterations.append(i)

"""

    print(pd.Series(X_testpred[:,1]).describe())

submission = pd.DataFrame({"ID":test.index, "TARGET":y_pred[:,1]})
submission.to_csv("submission.csv", index=False)

"""

import matplotlib.pyplot as plt

plt.figure(figsize=(15,10))
plt.plot(iterations,scorestrain,'r')
plt.plot(iterations,scorescv, 'b')
plt.ylim(0.8,0.9)
plt.xlim(1000,55000)
plt.xlabel('# training examples')
plt.ylabel('AUC')
plt.legend(['Training Set','CV set'],loc='lower right')


"""
On the first line, you will receive a string of numbers separated by space. On the second line,
you'll receive a target number. Your task is to find all pairs of numbers whose sum equals the target number.
For each found pair print "{number} + {number} = {target_number}".
Then, save only the unique pairs. Note: (1, 2) and (2, 1) are unique.
Also, you should keep track of how many iterations you've done.
At the end print all the iterations done in format: "Iterations done: {total_number_of_iterations}".
On the following lines, print the unique pairs in the format: "(first_number, second_number)".
The order in which we print the result does not matter.

Example:
Input
1 5 4 2 2 3 1 3 2
4

Output
1 + 3 = 4
1 + 3 = 4
2 + 2 = 4
2 + 2 = 4
2 + 2 = 4
3 + 1 = 4
1 + 3 = 4
Iterations done: 36
(3, 1)
(1, 3)
(2, 2)
"""

numbers = [int(x) for x in input().split()]
target = int(input())

iterations = 0
unique_pairs = set()

for idx1 in range(len(numbers)):
    for idx2 in range(idx1 + 1, len(numbers)):
        iterations += 1
        p1 = numbers[idx1]
        p2 = numbers[idx2]
        if p1 + p2 == target:
            print(f'{p1} + {p2} = {target}')
            unique_pairs.add(f'{p1} + {p2}')

print(f'Iterations done: {iterations}')
[print(f'({x})') for x in unique_pairs]


import sys
input = sys.stdin.readline

def do():
  def find(x):
    if (x == root[x]):
      return x
    root[x] = find(root[x])
    return root[x]

  N = int(input())
  root = list(i for i in range(N + 1))
  M = int(input())
  lst = list(list(map(int, input().split())) for i in range(M))
  lst.sort(key = lambda x : x[2])

  res = 0
  i = 0
  for a, b, c in lst:
    x, y = find(a), find(b)
    if (x != y):
      res += c
      i += 1
      if (x < y):
        root[x] = y
      else:
        root[y] = x
    if (i == N - 1):
      break

  print(res)

do()

그래프 이론/1922_네트워크 연결.py


# capitalize(word)
# Parameters
# word - A single word as a JavaScript String
# Return Value
# The original word, but with its first character uppercased and the rest of its characters lowercased.

# Examples
# capitalize('a') // -> "A"
# capitalize('link') // -> "Link"
# capitalize('tO') // -> "To"
# capitalize('ThE') // -> "The"
# capitalize('pAsT') // -> "Past"

# define a function that takes a string (word)
# define a variable for the output
# loop through the word
# if it is the first word capitalize and add
# otherwise add the letter

def capitalize(word) :
    output = None
    i = 0
    length = len(word)
    while i < length :
        if output is None :
            output = word[i].upper()
        else :
            output = output + word[i].lower()
        i = i + 1
    return output

print(capitalize('a'))
print(capitalize('link'))
print(capitalize('tO'))
print(capitalize('ThE'))
print(capitalize('pAsT'))


import re
import tekore as tk
import pathlib
import pickle
import argparse
import inquirer

def get_config():
    conf_path  = pathlib.Path.home().joinpath('.spotify.cnf')
    return tk.config_from_file(conf_path.as_posix())

def get_user_token():
    config = get_config()
    token_path = pathlib.Path.home().joinpath('.spotify.token.pkl')

    if not token_path.exists():
        user_token = tk.prompt_for_user_token( *config, scope=tk.scope.every)
        with open(token_path.as_posix(), 'wb') as f:
            pickle.dump({'refresh': user_token.refresh_token}, f)
    else:
        with open(token_path.as_posix(), 'rb') as f:
            d = pickle.load(f)
            refresh_token = d['refresh']
        refresher = tk.RefreshingCredentials(*config)
        user_token = refresher.refresh_user_token(refresh_token)
    return user_token

def play_top_k_tracks(spotify, k=10):
    tracks = spotify.current_user_top_tracks(limit=k).items
    spotify.playback_start_tracks([t.id for t in tracks])

def init():
    conf = get_config()
    app_token = tk.request_client_token(*conf[:2])
    spotify = tk.Spotify(app_token)
    spotify.token = get_user_token()
    return spotify

def albums(spotify, args):
    format_str = "%s - %s"
    def artists_str(artists):
        st = "%-30s" % ("; ".join([a.name for a in artists])[:30])
        return st

    albums = [a.album for a in spotify.saved_albums(limit=20).items]
    questions = [
      inquirer.List('choosen',
                    message="What album do you want to hear?",
                    choices=[format_str % (artists_str(a.artists), a.name) for a in albums],
                ),
    ]
    answers     = inquirer.prompt(questions)
    context_uri = next( (a.uri for a in albums if format_str % (artists_str(a.artists), a.name) == answers['choosen']) )
    spotify.playback_start_context(context_uri)

def playlists(spotify, args):
    playlists = spotify.followed_playlists(limit=50).items
    questions = [
            inquirer.List('choosen',
                message="What playlist do you want to hear?",
                choices=[p.name for p in playlists]
                ),
        ]
    answers = inquirer.prompt(questions)
    context_uri = next( (p.uri for p in playlists if p.name == answers['choosen']) )
    spotify.playback_start_context(context_uri)

def status(spotify, args):
    pb = spotify.playback()
    print("%-15s" % "Playing:", pb.item.name, " by ", "; ".join([a.name for a in pb.item.artists]))
    print("%-15s" % "On device:", pb.device.name)

def next_track(spotify, args):
    spotify.playback_next()

def previous_track(spotify, args):
    spotify.playback_previous()

def analyze(spotify, args):
    playlist = spotify.followed_playlists(limit=1).items[0]
    track = spotify.playlist_items(playlist.id, limit=1).items[0].track
    name = f'"{track.name}" from {playlist.name}'
    if track.episode:
        print(f'Cannot analyse episodes!\nGot {name}.')
    elif track.track and track.is_local:
        print(f'Cannot analyse local tracks!\nGot {name}.')
    else:
        print(f'Analysing {name}...\n')
        analysis = spotify.track_audio_features(track.id)
        print(repr(analysis))

def play(spotify, args):
    spotify.playback_resume()

def pause(spotify, args):
    spotify.playback_pause()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()
    # Play pause
    p = subparsers.add_parser('play')
    p.set_defaults(func=play)

    p = subparsers.add_parser('pause')
    p.set_defaults(func=pause)

    p = subparsers.add_parser('next')
    p.set_defaults(func=next_track)

    p = subparsers.add_parser('previous')
    p.set_defaults(func=previous_track)

    p = subparsers.add_parser('analyze')
    p.set_defaults(func=analyze)

    p = subparsers.add_parser('albums')
    p.set_defaults(func=albums)

    p = subparsers.add_parser('playlists')
    p.set_defaults(func=playlists)

    p = subparsers.add_parser('status')
    p.set_defaults(func=status)

    spotify = init()

    args = parser.parse_args()
    args.func(spotify, args)


# This file contains the Edition class
# as well as a function 'prettify' for prettifying the XML of the edition

from __future__ import annotations

from itertools import chain

from lxml.etree import _Element
from typing import Optional, Sequence
import re

from ..xml import BaseElement
from ..constants import (
    XMLNS
)
from ..utils import default_str, flatlist

from .element import EpiDocElement
from .ab import Ab
from .token import Token
from .expan import Expan
from .textpart import TextPart

from .epidoc_types import (
    SpaceUnit,
    TokenCarrier,
    AtomicTokenType,
    SubatomicTagType,
    CompoundTokenType,
    ContainerType
)

def prettify(
    spaceunit:SpaceUnit,
    number:int,
    edition:Edition
) -> Edition:

    """

 elements generally set xml:space="preserve".
    Accordingly, built-in pretty-printers
    do not prettify the text.
    This function prettifies the edition text in particular such that
    <lb> tags start new lines.

    Arguments:

    spaceunit -- sets the kind of unit, whether a tab or a space,
    to be used for indenting lines.

    number -- sets the number of spaceunit for each indentation.
    """

    newlinetags = ['div', 'ab', 'lb']

    def _get_multiplier(element:BaseElement) -> int:
        if element.tag.name in chain(
            AtomicTokenType.values(),
            CompoundTokenType.values(),
            SubatomicTagType.values()
        ):
            return element.depth
        elif element.tag.name in ContainerType.values():
            return element.depth + 1
        raise ValueError("Cannot find multiplier for this element.")

    def _get_prevs(elements:Sequence[BaseElement]) -> Sequence[BaseElement]:
        prevs:list[BaseElement] = []
        for element in elements:
            if element.previous_sibling is not None:
                prevs += [element.previous_sibling]

        return prevs

    def get_parents_for_first_children(elements:Sequence[BaseElement]) -> Sequence[BaseElement]:
        """
        Returns parent elements for all first children
        """

        parents:list[BaseElement] = []
        for element in elements:
            if element.previous_sibling is None: # Explain why only gives parents if previous sibling is None
                if element.parent is not None:
                    parents.append(element.parent)

        return parents

    def prettify_lb(lb:BaseElement) -> None:
        first_parent = lb.get_first_parent_by_name(['ab', 'div'])
        if first_parent is None:
            return

        lb.tail = ''.join([
            default_str(lb.tail),
            "\n",
            (spaceunit.value * number) * (first_parent.depth + 1)
        ])

    def prettify_prev(element:BaseElement) -> None:
        element.tail = ''.join([
            default_str(element.tail),
            "\n",
            (spaceunit.value * number) * element.depth
        ])

    def prettify_first_child(element:BaseElement) -> None:
        element.text = ''.join([
            default_str(element.text).strip(),
            "\n",
            spaceunit.value * number * (element.depth + 1)
        ])

    def prettify_parent_of_lb(element:BaseElement) -> None:
        first_parent = element.get_first_parent_by_name(['ab', 'div'])
        if first_parent is None:
            return

        element.text = ''.join([
            default_str(element.text).strip(),
            "\n",
            (spaceunit.value * number) * (first_parent.depth + 1)
        ])

    def prettify_closing_tags(elements:Sequence[BaseElement]) -> None:
        for element in elements:
            if element.children == []:
                continue
            lastchild = element.children[-1]
            lastchild.tail = ''.join([
                default_str(lastchild.tail).strip(),
                "\n",
                (spaceunit.value * number) * (_get_multiplier(element) - 1)
            ])

    # Do the pretty printing
    for tag in newlinetags:
        desc_elems = edition.get_desc_elems_by_name(elem_names=[tag])

        if tag == 'ab':
            for ab in desc_elems:
                prettify_first_child(ab)

        prevs = _get_prevs(desc_elems)

        for prev in prevs:
            if tag == 'lb':
                prettify_lb(prev)
            else:
                prettify_prev(prev)

        parents = get_parents_for_first_children(desc_elems)

        for parent in parents:
            if tag == 'lb':
                prettify_parent_of_lb(parent)
            else:
                prettify_first_child(parent)

        prettify_closing_tags(edition.get_desc_elems_by_name(['ab', 'div']))

    return edition

class Edition(EpiDocElement):

    """
    Provides services for
 elements.
    """

    def __init__(self, e:Optional[_Element | EpiDocElement | BaseElement]=None):
        if type(e) not in [_Element, EpiDocElement, BaseElement] and e is not None:
            raise TypeError('e should be _Element or Element type, or None.')

        if type(e) is _Element:
            self._e = e
        elif type(e) is EpiDocElement:
            self._e = e.e
        elif type(e) is BaseElement:
            self._e = e.e

        if self.tag.name != 'div':
            raise TypeError('Element should be of type
.')

        if self.get_attrib('type') != 'edition':
            raise TypeError('Element type attribute should be "edition".')

    @property
    def abs(self) -> list[Ab]:
        """
        Returns all the <ab> elements in an edition
        as a |list| of |Ab|.
        """

        return [Ab(element._e)
            for element in self.get_desc_elems_by_name(['ab'])]

    @property
    def compound_tokens(self) -> list[EpiDocElement]:
        compound_tokens = []

        for ab in self.abs:
            compound_tokens += ab.compound_tokens

        return compound_tokens

    def convert_words_to_names(self) -> Edition:
        for ab in self.abs:
            ab.convert_words_to_names()

        return self

    @property
    def divs(self) -> list[BaseElement]:
        return self.get_desc_elems_by_name(['div'])

    @property
    def edition_text(self) -> str:
        return self.text_desc

    @property
    def expans(self) -> list[Expan]:
        return flatlist([ab.expans for ab in self.abs])

    @property
    def gaps(self) -> list[EpiDocElement]:
        gaps = []
        for ab in self.abs:
            gaps += ab.gaps

        return gaps

    @property
    def lang(self):
        return self.get_attrib('lang', XMLNS)

    def prettify(self, spaceunit:SpaceUnit, number:int) -> None:
        prettify(spaceunit=spaceunit, number=number, edition=self)

    def space_tokens(self) -> None:

        """
        Separates tokens by spaces, as long as they should be separated by spaces
        and the following token is not among the tokens that should be separated
        from previous by a space
        """

        for elem in self.space_separated:
            elem.append_space()

    @property
    def formatted_text(self) -> str:
        _text = re.sub(r'\n\s+', '\n', self.text_desc)
        return re.sub(r'(\S)·(\S)', r'\1 · \2', _text)

    def set_ids(self) -> None:
        for ab in self.abs:
            ab.set_ids()

    @property
    def space_separated(self) -> list[EpiDocElement]:
        """
        :return: |Element|s that should be separated by spaces
        """
        return flatlist([ab.space_separated for ab in self.abs])

    @property
    def no_space(self) -> list[EpiDocElement]:
        """
        :return: |Element|s that should not be separated by spaces.
        """
        return flatlist([ab.no_space for ab in self.abs])

    @property
    def subtype(self) -> Optional[str]:
        return self.get_attrib('subtype')

    @property
    def supplied(self) -> Sequence[BaseElement]:
        return [elem for elem in self.desc_elems
            if elem.local_name == 'supplied']

    @property
    def textparts(self) -> list[TextPart]:
        return [TextPart(part) for part in self.get_div_descendants('textpart')]

    def tokenize(self) -> Optional[Edition]:
        for ab in self.abs:
            ab.tokenize()

        return self

    @property
    def tokens(self) -> list[Token]:
        words = []

        for ab in self.abs:
            words += ab.tokens

        return words

    @property
    def token_g_dividers(self) -> list[EpiDocElement]:
        dividers = []
        for ab in self.abs:
            dividers += ab.g_dividers

        return dividers

    @property
    def tokens_list_str(self) -> list[str]:
        return flatlist([ab.tokens_list_str for ab in self.abs])

    @property
    def tokens_str(self) -> str:
        return ' '.join(self.tokens_list_str)

    @property
    def w_tokens(self) -> list[Token]:
        return flatlist([ab.w_tokens for ab in self.abs])


import ipywidgets as widgets
from IPython.display import display

class RadioButtonsWithOutput:
    """RadioButtonsWithOutput: A widget that displays a group of radio buttons and an output widget that displays a message when a button is selected."""

    def __init__(self, label, options, message):
        self.radio_buttons = widgets.RadioButtons(
            description=label, options=options
        )
        self.output = widgets.Output()
        self.value = None

        def update_output(change):
            with self.output:
                self.output.clear_output()
                print(message.format(change["new"]))
                self.value = change["new"]

        self.radio_buttons.observe(update_output, names="value")
        display(widgets.VBox([self.radio_buttons, self.output]))


dict_s = {"black": "0",
          "brown": "1",
          "red": "2",
          "orange": "3",
          "yellow": "4",
          "green": "5",
          "blue": "6",
          "violet": "7",
          "grey": "8",
          "white": "9",
          }
r = ""
for x in range(3):
    s = input()
    if x == 2:
        converter = str(10 ** int(dict_s.get(s)))
        r += converter[1:]

    else:
        r += (dict_s.get(s))
print(int(r))


import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
from solver import *
from tkinter import *
from tkinter import messagebox

board = None
def clearBoard():
  global board
  board = [
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0]]
  screen.fill((255,255,255))
  drawGrid()
  drawButtons()
  pygame.display.update()

pygame.font.init()
myFont = pygame.font.SysFont(None, 65)
pygame.display.set_caption("Sudoku Solver")
(width, height) = (700, 503)
screen = pygame.display.set_mode((width, height))
background_colour = (255,255,255)
screen.fill(background_colour)
resetButton = None
solveButton = None
#sets up a window with a white background and a title

x = 0
y = 0
actualx = 0
actualy = 0

def drawGrid():
    pygame.draw.rect(screen, (0,0,0), (1, 1, 500 ,500), 4)
    for i in range(8):
        if (i+1) % 3 == 0 and i != 0:
            thick = 3
        else:
            thick = 1
        gridInterval = ((i+1)/9)*501
        pygame.draw.line(screen, (0,0,0), (0, gridInterval), (501, gridInterval), thick)
        pygame.draw.line(screen, (0, 0, 0), (gridInterval, 0), (gridInterval, 501), thick)
        #draws a square and 8 lines across and down, changing thickness to make the board

def getSelected(pos):
    global x
    global y
    global actualx
    global actualy
    global board
    if pos <= (501, 501):
        x = int(((pos[0]-1) // 55.5556))
        y = int(((pos[1]-1) // 55.5556))
        actualx = ((x/9)*500)+1
        actualy = ((y/9)*500)+1
    elif resetButton.collidepoint(pos):
        clearBoard()
        pygame.display.update()
    elif solveButton.collidepoint(pos):
        valid = validateBoard(board)
        if all(valid):
          solve(board)
          drawNumbers(board)
          pygame.display.update()
        else:
          if valid[0] == False:
            Tk().wm_withdraw()
            messagebox.showinfo('Error','The Sudoku entered does not have enough numbers (Minimum is 17).')
          if valid[1] == False:
            Tk().wm_withdraw()
            messagebox.showinfo('Error','The Sudoku entered violates Sudoku Rules.')

    #calculates which box or button the mouse has clicked on and where to draw the blue outline

def drawSelectedCell(pos):
    global x
    global y
    getSelected(pos)
    screen.fill((255,255,255))
    drawGrid()
    drawButtons()
    drawNumbers(board)
    pygame.draw.rect(screen, (0, 85, 255), (actualx, actualy, 55.5556, 55.5556), 3)
    pygame.display.update()
    #wipes the screen and draws the grid and new blue box

def drawNumbers(board):
    screen.fill((255,255,255))
    drawGrid()
    drawButtons()
    pygame.draw.rect(screen, (0, 85, 255), (actualx, actualy, 55.5556, 55.5556), 3)
    for i in range(9):
        for j in range(9):
            if board[i][j] != 0:
              text = myFont.render(str(board[i][j]), False, (0,0,0))
              screen.blit(text, ((j/9*500) + 17, (i/9*500) + 8))
    pygame.display.update()
    #draws numbers from left to right, top to bottom after clearing the image and drawing the grid and cursor

def drawButtons():
    global resetButton
    global solveButton
    buttonBackground = pygame.image.load(r'C:\Users\brett\OneDrive\Pictures\Sudoku\buttonBackground.png')
    buttonBackground = pygame.transform.scale(buttonBackground, (126, 48))
    resetButton = screen.blit(buttonBackground, (545, 145))
    solveButton = screen.blit(buttonBackground, (545, 310))
    text = myFont.render("Reset", False, (0,0,0))
    screen.blit(text, (550, 150))
    text = myFont.render("Solve", False, (0,0,0))
    screen.blit(text, (550, 315))
    #draws the buttons and button text

def validateBoard(board):
    count = 0
    for i in range(9):
        count = count + board[i].count(0)
    sudokuRules = True
    for i in range(9):
      for j in range(9):
        if board[i][j] != 0 and valid(board, board[i][j], (i,j)) == False:
            sudokuRules = False
    conditions = [count <= 64, sudokuRules]
    return conditions
    #checks the board can be solved

clearBoard()
drawGrid()
drawButtons()
pygame.display.update()
pygame.display.flip()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
          running = False
        if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_1:
                    board[y][x] = 1
                    drawNumbers(board)
                if event.key == pygame.K_2:
                    board[y][x] = 2
                    drawNumbers(board)
                if event.key == pygame.K_3:
                    board[y][x] = 3
                    drawNumbers(board)
                if event.key == pygame.K_4:
                    board[y][x] = 4
                    drawNumbers(board)
                if event.key == pygame.K_5:
                    board[y][x] = 5
                    drawNumbers(board)
                if event.key == pygame.K_6:
                    board[y][x] = 6
                    drawNumbers(board)
                if event.key == pygame.K_7:
                    board[y][x] = 7
                    drawNumbers(board)
                if event.key == pygame.K_8:
                    board[y][x] = 8
                    drawNumbers(board)
                if event.key == pygame.K_9:
                    board[y][x] = 9
                    drawNumbers(board)
                if event.key == pygame.K_DELETE or event.key == pygame.K_BACKSPACE:
                    board[y][x] = 0
                    drawNumbers(board)
                if pos:
                  if event.key == pygame.K_UP:
                    if y > 0:
                      y = y - 1
                      pos = (pos[0], (y * 55.5556)+5)
                      drawSelectedCell(pos)
                  if event.key == pygame.K_DOWN:
                    if y < 8:
                      y = y + 1
                      pos = (pos[0], (y * 55.5556)+5)
                      drawSelectedCell(pos)
                  if event.key == pygame.K_LEFT:
                    if x > 0:
                      x = x - 1
                      pos = ((x * 55.5556)+5, pos[1])
                      drawSelectedCell(pos)
                  if event.key == pygame.K_RIGHT:
                    if x < 8:
                      x = x + 1
                      pos = ((x * 55.5556)+5, pos[1])
                      drawSelectedCell(pos)

        if event.type == pygame.MOUSEBUTTONDOWN:
          pos = pygame.mouse.get_pos()
          drawSelectedCell(pos)
          #main loop: checks for any input

pygame.quit()


#coding: utf-8

import requests
import sys
import re

url = 'http://hashtoolkit.com/reverse-hash/?hash='
try:
	hasH = sys.argv[1]
except:
	print ("\nComando: hash.py HASH")
	sys.exit()

http = requests.get(url+hasH)
content = http.content
descrypt = re.findall("(.*)", content)
print ("\nHash Identificada: "+descrypt[0][0])
print ("Senha Descryptada: "+descrypt[0][1])


import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

import dash
from dash import dcc
from dash.dependencies import Input, Output
import os
import dash_bootstrap_components as dbc

global df, title, x_buy, x_sell, y_buy, y_sell
# inizialization variables
x_buy, x_sell, y_buy, y_sell = [],[],[],[]
last_save=0
last_cancel=0
value = 'BTCEUR'
title = value
df = pd.read_csv('./DATA/{}.csv'.format(value))
df.start = pd.to_datetime(df.start)
df = df.sort_values('start')
df.index = df.start
fig = px.line(x=df.index, y=df['close']
    ).add_traces(
    px.line(x=df.index, y=df['close']
    )
        .update_traces(marker_color="rgba(0,0,0,0)").data
)
fig.layout.height = 400

tab1_content = dbc.Card(
    dbc.CardBody(
        [
            dash.dcc.Graph(id="graph_1", figure=fig, ),
        ]
    ),
    className="mt-3",
)

tab2_content = dbc.Card(
    dbc.CardBody(
        [
            dash.dcc.Graph(id="graph_2", figure=fig),
        ]
    ),
    className="mt-3",
)

tabs = dbc.Tabs(
    [
        dbc.Tab(tab1_content, label="Buy "),
        dbc.Tab(tab2_content, label="Sell"),

    ]
)

# Build App

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP], suppress_callback_exceptions=True)
app.layout = dash.html.Div([
    dbc.Row([
        dbc.Row(dbc.Card(dash.html.H1('FastTradingLabel'),color='danger')),
        dbc.Col([

            dbc.Row( [
        dbc.Row(dash.html.H6('FTL is a tool to quickly label cryptocurrency data,'
                             ' choose the exchange and click on the chart to the right'
                             'the market entry and exit points you consider appropriate')),
        dbc.Row(dash.html.H4('Select exchange')),
        dbc.Row(
                            dcc.Dropdown(
                                options=list({'label':x[:-4],'value':x} for x in os.listdir('DATA')), id='select_cripto',

                            )
                    ),

        dbc.Row( id='n_operation_buy'),
        dbc.Row( id='n_operation_sell'),
        dbc.Button('Cancel', n_clicks=0,id='cancel'),
        dbc.Button('Save', n_clicks=0,id='save'),
    ],
    className="d-grid gap-2 col-6 mx-auto",),
            dbc.Row(),
            dbc.Row( id='saved'),
        ],align="end"),
        dbc.Col(tabs,id='tab', width=8)
    ]),
    dbc.Row(dash.html.Div(id="where"))
])

@app.callback(
    Output("where", "children"),
    Output("n_operation_buy", "children"),
    Output("n_operation_sell", "children"),
    Input("graph_1", "clickData"),
    Input("graph_2", "clickData"),
    Input("save", 'n_clicks'),
    Input("cancel", 'n_clicks')
)
def click(clickData1,clickData2,save,cancel):
    global x_buy, x_sell, y_buy, y_sell, last_cancel, last_save

    if cancel == last_cancel and save == last_save:
        if clickData1:
            x_buy.append(clickData1['points'][0]['x'])
            y_buy.append(clickData1['points'][0]['y'])

        if clickData2:
            x_sell.append(clickData2['points'][0]['x'])
            y_sell.append(clickData2['points'][0]['y'])

    if cancel > last_cancel:
        last_cancel += 1

        if x_buy != []:
            x_buy.pop()
        if x_sell != []:
            x_sell.pop()
        if y_buy != []:
            y_buy.pop()
        if y_sell != []:
            y_sell.pop()

    if save > last_save:

        last_save += 1
        df['BUY']=0
        df['SELL'] = 0
        df['BUY'].loc[list(set(x_buy))] = 1
        df['SELL'].loc[list(set(x_sell))] = 1
        if not os.path.exists('./LABELED_DATA'):
            os.mkdir('./LABELED_DATA')
        df.to_csv('./LABELED_DATA/{}.csv'.format(title), index=False)
        x_buy, x_sell, y_buy, y_sell = [], [], [], []

    trace = go.Candlestick(x=df.start,
                           open=df.open,
                           high=df.high,
                           low=df.low,
                           close=df.close)
    data = [trace]
    data.append(go.Scatter(x=x_buy, y=y_buy,
                               mode='markers',
                               name='buy',
                               marker_size=20,
                               marker_symbol="triangle-up",
                               marker_color="green"))
    data.append(go.Scatter(x=x_sell, y=y_sell,
                               mode='markers',
                               name='buy',
                               marker_size=20,
                               marker_symbol="triangle-down",
                               marker_color="red"))
    layout = {'title':title,'xaxis': {'rangeslider': {'visible': False}}}
    figure = {'data': data, 'layout': layout}

    return dash.dcc.Graph(figure=figure), dash.html.H4('Number of buy: {}'.format(str(len(set(x_buy))))),\
           dash.html.H4('Number of sell: {}\n'.format(str(len(set(x_sell)))))

@app.callback(
    (Output("tab", "children")),
    Input("select_cripto", 'value')
)
def drop(value):
    global df, title, x_buy, x_sell, y_buy, y_sell

    x_buy, x_sell, y_buy, y_sell = [], [], [], []
    ###### FIGURE TAB
    if not value:
        value = 'BTCEUR'
    else:
        value = value[:-4]
    title = value
    df = pd.read_csv('./DATA/{}.csv'.format(value))
    df.start = pd.to_datetime(df.start)
    df = df.sort_values('start')
    df.index = df.start
    fig = px.line(x=df.index, y=df['close']
                  ).add_traces(
        px.line(x=df.index, y=df['close']
                )
            .update_traces(marker_color="rgba(0,0,0,0)").data
    )
    fig.layout.height = 400
    tab1_content = dbc.Card(
        dbc.CardBody(
            [
                dash.dcc.Graph(id="graph_1", figure=fig),
            ]
        ),
        className="mt-3",
    )

    tab2_content = dbc.Card(
        dbc.CardBody(
            [
                dash.dcc.Graph(id="graph_2", figure=fig),
            ]
        ),
        className="mt-3",
    )

    tabs = dbc.Tabs(
        [
            dbc.Tab(tab1_content, label="Buy "),
            dbc.Tab(tab2_content, label="Sell"),

        ]
    )
    return tabs

# Run app and display result inline in the notebook
app.run_server()


import math

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

from stampe import prPurple, prYellow, prRed

def isSpotifyTrackUrl(url):
    return "open.spotify.com/track" in url

def getAudioFeatures(url):
    spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(
        client_id='client_id',
        client_secret='client_secret'
    ))

    return spotify.audio_features(url.split('/')[-1].split('?')[0]), spotify.track(url)["explicit"]

def normalizeCos1To100Int(value):
    return int((math.cos(value) + 1) / 2 * 100)

def trackAudioFeaturesToQueryEvidence(trackAudioFeatures, explicit):
    return {
        "trackIsexplicit": 1 if explicit else 0,
        "danceability": normalizeCos1To100Int(trackAudioFeatures[0]["danceability"]),
        "energy": normalizeCos1To100Int(trackAudioFeatures[0]["energy"]),
        "key": normalizeCos1To100Int(trackAudioFeatures[0]["key"]),
        "loudness": normalizeCos1To100Int(trackAudioFeatures[0]["loudness"]),
        "speechiness": normalizeCos1To100Int(trackAudioFeatures[0]["speechiness"]),
        "acousticness": normalizeCos1To100Int(trackAudioFeatures[0]["acousticness"]),
        "instrumentalness": normalizeCos1To100Int(trackAudioFeatures[0]["instrumentalness"]),
        "valence": normalizeCos1To100Int(trackAudioFeatures[0]["valence"]),
        "tempo": normalizeCos1To100Int(trackAudioFeatures[0]["tempo"]),
    }

def queryOutput(data, differentialColumn, evidence):
    querySong = data.query(
        show_progress=False,
        variables=[differentialColumn],
        evidence=evidence
    )
    prRed("\nProbability for given url:")
    print(querySong)

def outputExplain():
    print(
        "+-----------------------------------+---------------------------+\n",
        "|           feature name            |    feature probability    |\n",
        "+===================================+===========================+\n",
        "|  feature name(0 (not liked song)) | probability feature (val) |\n",
        "+-----------------------------------+---------------------------+\n",
        "|   feature name(1 (liked song))    | probability feature (val) |\n",
        "+-----------------------------------+---------------------------+",
    )
    prPurple(
        "Probability value fluctuates between 0 (impossible event) to 1 (certain event)\n"
    )

def querySystem(data, differentialColumn):
    prYellow(
        "Welcome to my system, with this tool you can, taken a song, playlist or album spotify link, predict if the user the data are generated on would like it or not.\n"
    )

    outputExplain()

    while True:
        prYellow(
            "Input a spotify url for a prediction? - (Typing 'n' close program)"
        )
        result = str(input())
        if "N" == result or result == "n":
            exit(0)
        else:
            if isSpotifyTrackUrl(result):
                trackAudioFeatures, explicit = getAudioFeatures(result)
                if trackAudioFeatures:
                    evidence = trackAudioFeaturesToQueryEvidence(
                        trackAudioFeatures, explicit)
                    queryOutput(data, differentialColumn, evidence)
                else:
                    print(
                        "Couldn't retreive audio features for the given song from spotify api")
            else:
                print("Url in input is not a valid spotify track url")


from django.db import models
from django.utils import timezone
from jsonfield import JSONField
import requests, json

class Image(models.Model):
	title = models.CharField(max_length=70)
	url = models.CharField(max_length=2083)
	related_images = JSONField()
	created_date = models.DateTimeField(default=timezone.now())

	def publish(self):
		if not self.url.startswith("http"):
			self.url = "http://" + self.url
		imagga_url = "http://api.imagga.com/v1/tagging"
		querystring = {'url': self.url, 'version': '2'}
		headers = {
			'accept': "application/json",
			'authorization': "Basic YWNjXzQ0ODZkZjA5ODg5YTczYzplOTFlMzllNzA4ZGVjYjQxNjk5YTY2MTdhNThiZWM3OA=="
		}
		r = requests.request('GET', imagga_url, headers=headers, params=querystring)
		data = r.json()['results'][0]['tags']
		tag_len = len(data)
		tags = []
		for i in range(0, tag_len - 1):
			tags.append(data[i]['tag'])
		count = 0
		related_images = []
		r2 = requests.request('get', "http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" + ' '.join(tags))
		data2 = r2.json()['responseData']['results'];
		while count < 50 and len(tags):
			r2 = requests.request('get', "http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" + ' '.join(tags))
			data2 = r2.json()['responseData']['results'];
			related_len = len(data2)
			tags.pop()
			for i in range(0, related_len - 1):
				if (count >= 50):
					i = related_len
				else:
					related_image = {'url': data2[i]['url'], 'thumbnail': data2[i]['tbUrl']}
					contains_image = False
					for j in range(0, len(related_images)- 1):
						if related_images[j] == related_image:
							contains_image = True
					if not contains_image:
						related_images.append(related_image)
						count += 1
		self.related_images = json.dumps(related_images)
		self.save()

	def __str__(self):
		return self.title


import re
from utils import is_shad

def add_shad_to_note_text(note_chunk):
    note_text = ''
    note_options = re.split("(;)", note_chunk)
    for note_option in note_options:
        if note_option != ';':
            if note_option[-1] == '>':
                note_text += f"{note_option[:-1]}།>"
            else:
                note_text += f"{note_option}།"
        else:
            note_text += ';'

    return note_text

def resolve_missing_punct_note_text(collated_text):
    reformated_collated_text = ""

    chunks = re.split('(\(\d+\) <.+?>)', collated_text)

    for chunk_walker,chunk in enumerate(chunks):
        try:
            next_chunk = chunks[chunk_walker+1]
        except:
            next_chunk = ''
        if re.search('\(\d+\) <.+?>', chunk):
            if next_chunk and is_shad(next_chunk[0]):
                reformated_collated_text += '།'
                updated_note_text = add_shad_to_note_text(chunk)
                reformated_collated_text += updated_note_text
                chunks[chunk_walker+1] = next_chunk[1:]
            else:
                reformated_collated_text += chunk
        else:
            reformated_collated_text += chunk
    return reformated_collated_text

if __name__ == "__main__":

    collated_text = 'ནཱ་མ་བྲྀཏྟི(3) <«སྡེ་»བྲིཏྟ;«སྣར་»བྲིཏྟི>། བོད་སྐད་དུ། རྒྱུ་ནི་ཡོད་པ་མ་ཡིན(4) <«སྡེ་»«སྣར་»ཡིན་ནོ>། ཅིའི་ཕྱིར་ཞེ་ན། '
    expected_text = 'ནཱ་མ་བྲྀཏྟི།(3) <«སྡེ་»བྲིཏྟ།;«སྣར་»བྲིཏྟི།> བོད་སྐད་དུ། རྒྱུ་ནི་ཡོད་པ་མ་ཡིན།(4) <«སྡེ་»«སྣར་»ཡིན་ནོ།> ཅིའི་ཕྱིར་ཞེ་ན། '

    actual_text = resolve_missing_punct_note_text(collated_text)
    print(actual_text)
    assert actual_text == expected_text


# -*- coding: utf-8 -*-
"""
Created on Mon Aug 12 20:28:28 2019

@author: brand
"""

import torch
import torch.nn as nn
from model1 import predictor

model = predictor(17, 11)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

checkpoint = torch.load('/ModelState.pt')

model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
epoch = checkpoint['epoch']

for p in model.parameters():
    print(p.data)


import os
import shutil

from tensorflow.core.config import flags
from tensorflow.core.protobuf import fingerprint_pb2
from tensorflow.core.protobuf import saved_model_pb2
from tensorflow.python.eager import def_function
from tensorflow.python.eager import test
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_spec
from tensorflow.python.lib.io import file_io
from tensorflow.python.saved_model import fingerprinting
from tensorflow.python.saved_model import fingerprinting_utils
from tensorflow.python.saved_model import save
from tensorflow.python.saved_model.pywrap_saved_model import constants
from tensorflow.python.saved_model.pywrap_saved_model import fingerprinting as fingerprinting_pywrap
from tensorflow.python.trackable import autotrackable

class FingerprintingTest(test.TestCase):

  def _create_saved_model(self):
    root = autotrackable.AutoTrackable()
    save_dir = os.path.join(self.get_temp_dir(), "saved_model")
    save.save(root, save_dir)
    self.addCleanup(shutil.rmtree, save_dir)
    return save_dir

  def _create_model_with_function(self):
    root = autotrackable.AutoTrackable()
    root.f = def_function.function(lambda x: 2. * x)
    return root

  def _create_model_with_input_signature(self):
    root = autotrackable.AutoTrackable()
    root.f = def_function.function(
        lambda x: 2. * x,
        input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)])
    return root

  def _create_model_with_data(self):
    root = autotrackable.AutoTrackable()
    root.x = constant_op.constant(1.0, dtype=dtypes.float32)
    root.f = def_function.function(
        lambda x: root.x * x,
        input_signature=[tensor_spec.TensorSpec(None, dtypes.float32)])
    return root

  def _read_fingerprint(self, filename):
    fingerprint_def = fingerprint_pb2.FingerprintDef()
    with file_io.FileIO(filename, "rb") as f:
      fingerprint_def.ParseFromString(f.read())
    return fingerprint_def

  def setUp(self):
    super().setUp()
    flags.config().saved_model_fingerprinting.reset(True)

  def test_basic_module(self):
    save_dir = self._create_saved_model()
    files = file_io.list_directory_v2(save_dir)

    self.assertLen(files, 4)
    self.assertIn(constants.FINGERPRINT_FILENAME, files)

    fingerprint_def = self._read_fingerprint(
        file_io.join(save_dir, constants.FINGERPRINT_FILENAME))

    # We cannot check this value due to non-determinism in saving.
    self.assertGreater(fingerprint_def.saved_model_checksum, 0)
    self.assertEqual(fingerprint_def.graph_def_program_hash,
                     14830488309055091319)
    self.assertEqual(fingerprint_def.signature_def_hash, 12089566276354592893)
    self.assertEqual(fingerprint_def.saved_object_graph_hash, 0)
    # TODO(b/242348400): The checkpoint hash is non-deterministic, so we cannot
    # check its value here.
    self.assertGreater(fingerprint_def.checkpoint_hash, 0)

  def test_model_saved_with_different_signature_options(self):
    model = self._create_model_with_function()
    # Save the model with signatures specified in SaveOptions.
    sig_dir = os.path.join(self.get_temp_dir(), "saved_model")
    save.save(
        model,
        sig_dir,
        signatures=model.f.get_concrete_function(
            tensor_spec.TensorSpec(None, dtypes.float32)))
    # Save the model without signatures.
    no_sig_dir = os.path.join(self.get_temp_dir(), "saved_model2")
    save.save(model, no_sig_dir)
    # Save the model with an input signature specified.
    input_sig_dir = os.path.join(self.get_temp_dir(), "saved_model3")
    save.save(self._create_model_with_input_signature(), input_sig_dir)

    fingerprint_sig = self._read_fingerprint(
        file_io.join(sig_dir, constants.FINGERPRINT_FILENAME))
    fingerprint_no_sig = self._read_fingerprint(
        file_io.join(no_sig_dir, constants.FINGERPRINT_FILENAME))
    fingerprint_input_sig = self._read_fingerprint(
        file_io.join(input_sig_dir, constants.FINGERPRINT_FILENAME))

    # Check that the model saved with different options has different
    # SignatureDef hashes.
    self.assertNotEqual(fingerprint_sig.signature_def_hash,
                        fingerprint_no_sig.signature_def_hash)
    # Check that the model saved with the same concrete function has the same
    # regularized hashes.
    self.assertEqual(fingerprint_sig.graph_def_program_hash,
                     fingerprint_input_sig.graph_def_program_hash)
    self.assertEqual(fingerprint_sig.signature_def_hash,
                     fingerprint_input_sig.signature_def_hash)

  def test_read_fingerprint_api(self):
    save_dir = self._create_saved_model()
    fingerprint = fingerprinting.read_fingerprint(save_dir)

    fingerprint_def = self._read_fingerprint(
        file_io.join(save_dir, constants.FINGERPRINT_FILENAME))

    self.assertEqual(fingerprint, fingerprint_def)

  def test_read_fingerprint_file_not_found(self):
    with self.assertRaisesRegex(FileNotFoundError,
                                "SavedModel Fingerprint Error"):
      fingerprinting.read_fingerprint("foo")

  def test_write_fingerprint(self):
    save_dir = os.path.join(self.get_temp_dir(), "model_and_fingerprint")
    save.save_and_return_nodes(
        self._create_model_with_data(), save_dir,
        experimental_skip_checkpoint=True)  # checkpoint data won't be loaded

    fingerprint_def = fingerprinting.read_fingerprint(save_dir)

    # We cannot check this value due to non-determinism in serialization.
    self.assertGreater(fingerprint_def.saved_model_checksum, 0)
    self.assertEqual(fingerprint_def.graph_def_program_hash,
                     8947653168630125217)
    self.assertEqual(fingerprint_def.signature_def_hash, 15354238402988963670)
    self.assertEqual(fingerprint_def.checkpoint_hash, 0)

  def test_valid_singleprint(self):
    save_dir = os.path.join(self.get_temp_dir(), "singleprint_model")
    save.save(self._create_model_with_data(), save_dir)
    fingerprint = fingerprinting.read_fingerprint(save_dir)
    singleprint = fingerprint.singleprint()

    # checkpoint_hash is non-deterministic and not included
    self.assertRegex(singleprint,
                     "/".join(["8947653168630125217",  # graph_def_program_hash
                               "15354238402988963670",  # signature_def_hash
                               "1613952301283913051"  # saved_object_graph_hash
                               ]))

  def test_invalid_singleprint(self):
    fingerprint = fingerprinting.Fingerprint()
    with self.assertRaisesRegex(ValueError,
                                "Encounted invalid fingerprint values"):
      fingerprint.singleprint()

  def test_valid_from_proto(self):
    save_dir = os.path.join(self.get_temp_dir(), "from_proto_model")
    save.save(self._create_model_with_data(), save_dir)
    fingerprint_def = fingerprint_pb2.FingerprintDef().FromString(
        fingerprinting_pywrap.ReadSavedModelFingerprint(save_dir))
    fingerprint = fingerprinting.Fingerprint.from_proto(fingerprint_def)
    self.assertEqual(fingerprint, fingerprint_def)

  def test_invalid_from_proto(self):
    save_dir = os.path.join(self.get_temp_dir(), "from_proto_model")
    save.save(self._create_model_with_data(), save_dir)
    wrong_def = saved_model_pb2.SavedModel(
        saved_model_schema_version=1)
    with self.assertRaisesRegex(ValueError,
                                "Given proto could not be deserialized as"):
      fingerprinting.Fingerprint.from_proto(wrong_def)

  def test_fingerprint_to_proto(self):
    save_dir = os.path.join(self.get_temp_dir(), "from_proto_model")
    save.save(self._create_model_with_data(), save_dir)
    fingerprint = fingerprinting.read_fingerprint(save_dir)
    fingerprint_def = fingerprinting_utils.to_proto(fingerprint)
    self.assertEqual(fingerprint, fingerprint_def)

if __name__ == "__main__":
  test.main()


import os
import time
from datetime import datetime

import numpy as np
import tensorflow as tf

from DLAPP.Resnet import parse_args, read_cifar, resnet_cifar

tf.logging.set_verbosity(tf.logging.INFO)

def train(model_conf):
    """train resnet"""
    images, labels = read_cifar.cifar_input(model_conf.dataset,
                                            model_conf.data_path,
                                            model_conf.batch_size,
                                            evaluation=False,
                                            do_augmentation=True)
    model = resnet_cifar.ResNet(model_conf, images, labels)
    model.build_graph()

    y = tf.argmax(model.labels, 1)
    y_ = tf.argmax(model.predictions, 1)
    acc = tf.reduce_mean(tf.to_float(tf.equal(y, y_)))

    tf.scalar_summary('accuracy', acc)
    summary_op = tf.merge_all_summaries()

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

    sess = tf.Session()
    with sess.as_default():
        sess.run(tf.initialize_all_variables())
        summary_writer = tf.train.SummaryWriter(model_conf.train_dir, sess.graph)
        tf.summary.FileWriter
        # Start the queue runners.
        tf.train.start_queue_runners(sess=sess)

        for step in xrange(model_conf.num_step):
            start_time = time.time()
            [loss_value, acc_value, _, lr_value] = sess.run([model.loss, acc, model.train_op, model.lrn_rate])
            duration = time.time() - start_time

            assert not np.isnan(loss_value), 'Model diverged with loss = NaN'

            if step%10 == 0:
                format_str = ('%s: step %d, loss = %.5f, acc = %.5f, lr = %.5f (%.3f examples/sec; %.3f '
                              'sec/batch)')
                print(format_str % (datetime.now(), step, loss_value, acc_value, lr_value,
                                    model_conf.batch_size/duration, duration))

            if step%100 == 0:
                summary_str = sess.run(summary_op)
                summary_writer.add_summary(summary_str, step)

            if step % 10000 == 0 or step + 1 == model_conf.num_step:
                checkpoint_path = os.path.join(model_conf.model_path, 'model.ckpt')
                saver.save(sess, checkpoint_path, step)

def evaluate(model_conf):
    images, labels = read_cifar.cifar_input(model_conf.dataset,
                                            model_conf.data_path,
                                            model_conf.batch_size,
                                            evaluation=True,
                                            do_augmentation=False)
    model = resnet_cifar.ResNet(model_conf, images, labels)
    model.build_graph()

    saver = tf.train.Saver()
    sess = tf.Session()
    tf.train.start_queue_runners(sess)

    try:
        ckpt_state = tf.train.get_checkpoint_state(model_conf.model_path)
    except tf.errors.OutOfRangeError as e:
        tf.logging.error('Can not restore checkpoint %s', e)
        return

    if not (ckpt_state and ckpt_state.model_checkpoint_path):
        tf.logging.info('No model to eval yet at %s', model_conf.model_path)
        return

    tf.logging.info('Loading checkpoint %s', ckpt_state.model_checkpoint_path)
    saver.restore(sess, ckpt_state.model_checkpoint_path)

    total_prediction, correct_prediction = 0, 0
    best_precision = 0.0
    for _ in xrange(model_conf.eval_batch_count):
        (loss, y, y_) = sess.run([model.loss, model.labels, model.predictions])

        y = np.argmax(y, 1)
        y_ = np.argmax(y_, 1)
        correct_prediction += np.sum(y == y_)
        total_prediction += y_.shape[0]

    precision = 1.0 * correct_prediction / total_prediction
    best_precision = max(precision, best_precision)

    tf.logging.info('loss: %.3f, precision: %.3f, best precision: %.3f\n' %
                    (loss, precision, best_precision))

def main(_):
    model_conf = parse_args.ModelConf()
    if model_conf.mode == 'train':
        train(model_conf)
    elif model_conf.mode == 'eval':
        evaluate(model_conf)

if __name__ == '__main__':
    tf.app.run()


"""
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

Example 1:
    Input: nums = [2,7,11,15], target = 9
    Output: [0,1]
    Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:
    Input: nums = [3,2,4], target = 6
    Output: [1,2]

Example 3:
    Input: nums = [3,3], target = 6
    Output: [0,1]

Constraints:
    2 <= nums.length <= 10^4
    -10^9 <= nums[i] <= 10^9
    -10^9 <= target <= 10^9
    Only one valid answer exists.
"""

def two_sum_HashTable(nums_list, target):
    memo = dict() # 해쉬 테이블 이용. dict 선언. memo = {} 동일
    result = False # 결과 저장 변수 선언

    # 메모리 저장
    for idx, data in enumerate(nums_list):
        memo[data] = True  # 딕셔너리의 키(key) 저장이 핵심. 값(value)는 임의로 True로 저장한다.
    # print(memo)

    # 딕셔너리를 for 문을 돌리면 딕셔너리의 키(key) 값이 할당.
    for key in nums_list:
        search_key = target - key
        if search_key in memo:  # 해시 테이블에서 key 값 조사.
            result = True   # 문제 조건 달성. return 으로 종료.
            return result

    return result

# 정수형 배열 입력 받기
nums = list(map(int, input().split()))

# 타겟 입력 받기
target = int(input())

# 결과 출력
result = two_sum_HashTable(nums, target)
print("결과는 : {}".format(result))


import pickle
import numpy as np
from scipy.io import loadmat
import matplotlib.pyplot as plt

from configs.config import Config
from utils.plot_utils import PlotUtils
from forward_model.model import MethodOfMomentModel
from inverse_model.solve import InverseProblemSolver

def get_grid_permittivity(grid_positions):

    center_x = 0.4
    center_y = 0.4
    radius = 0.15
    epsilon_r = 1.1

    m = Config.doi["forward_grids"]
    scatterer = np.ones((m, m), dtype=float)

    # circle
    scatterer[(grid_positions[0] - center_x) ** 2 + (grid_positions[1] - center_y) ** 2 <= radius ** 2] = epsilon_r

    # square
    # mask = ((grid_positions[0] <= center_x + radius) & (grid_positions[0] >= center_x - radius) &
    #         (grid_positions[1] <= center_y + radius) & (grid_positions[1] >= center_y - radius))
    # scatterer[mask] = epsilon_r

    fig, (ax1, ax2) = plt.subplots(ncols=2)

    original = ax1.imshow(np.real(scatterer), cmap=plt.cm.hot, extent=PlotUtils.get_doi_extent())
    fig.colorbar(original, ax=ax1, fraction=0.046, pad=0.04)
    ax1.title.set_text("Scatterer: real")

    reconstructed_real = ax2.imshow(np.imag(scatterer), cmap=plt.cm.hot, extent=PlotUtils.get_doi_extent())
    fig.colorbar(reconstructed_real, ax=ax2, fraction=0.046, pad=0.04)
    ax2.title.set_text("Scatterer: imaginary")

    return scatterer

def solve_many(A, data, prior):
    values = np.linspace(0, 1e3, 20)
    fig1, axes1 = plt.subplots(nrows=4, ncols=5)
    fig2, axes2 = plt.subplots(nrows=4, ncols=5)

    real_rec = []
    imag_rec =  []
    for value in values:
        params = {"alpha": value}
        chi_real, chi_imag = InverseProblemSolver.solve(A, data, prior, params)
        real_rec.append(chi_real)
        imag_rec.append(chi_imag)

    fig1.subplots_adjust(hspace=0.2)
    fig1.suptitle('Reconstructions for real part')

    for ax, rec, in zip(axes1.flatten(), real_rec):
        ax.imshow(rec, cmap=plt.cm.hot, extent=PlotUtils.get_doi_extent())

    fig2.subplots_adjust(hspace=0.2)
    fig2.suptitle('Reconstructions for imaginary part')

    for ax, rec, in zip(axes2.flatten(), imag_rec):
        ax.imshow(rec, cmap=plt.cm.hot, extent=PlotUtils.get_doi_extent())

def plot_results(scatterer, chi_real, chi_imag):

    fig, (ax1, ax2, ax3) = plt.subplots(ncols=3)

    original = ax1.imshow(scatterer, cmap=plt.cm.hot)
    fig.colorbar(original, ax=ax1, fraction=0.046, pad=0.04)
    ax1.title.set_text("Original scatterer")

    reconstructed_real = ax2.imshow(chi_real, cmap=plt.cm.hot, extent=PlotUtils.get_doi_extent())
    fig.colorbar(reconstructed_real, ax=ax2, fraction=0.046, pad=0.04)
    ax2.title.set_text("Real Reconstruction")

    reconstructed_imag = ax3.imshow(chi_imag, cmap=plt.cm.hot, extent=PlotUtils.get_doi_extent())
    fig.colorbar(reconstructed_imag, ax=ax3, fraction=0.046, pad=0.04)
    ax3.title.set_text("Imaginary Reconstruction")

if __name__ == '__main__':

    """" Solve the Forward Problem """
    # Instantiate forward model
    forward = MethodOfMomentModel()

    """" Generate / Read the scatterer """
    scatterer = get_grid_permittivity(forward.grid_positions)

    # Generate forward data for scatterer
    direct_field, direct_power, total_field, total_power = forward.generate_forward_data(scatterer)

    """" Solve the Inverse Problem """

    model_type = "prytov_complex"
    prior = "qs2D_complex"
    params = {"alpha": 10}

    A = InverseProblemSolver.get_inverse_model(model_type)
    data = InverseProblemSolver.get_measurement_data(model_type, direct_power, total_power)

    chi_real, chi_imag = InverseProblemSolver.solve(A, data, prior, params)
    plot_results(scatterer, chi_real, chi_imag)

    # solve_many(A, data, prior)


import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import tkinter as tk
from tkinter import ttk
import csv

class Grapher(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        tk.Tk.iconbitmap(self)
        tk.Tk.wm_title(self, "ComMeN grapher")

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in [StartPage]:
            frame = F(container)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):
    def __init__(self, parent):
        self.comp_data = {}
        self.time_data = []
        self.node_vars = {}

        tk.Frame.__init__(self, parent)

        tk.Label(self, text="Data file:").grid(row=0, column=0)

        filename = tk.Entry(self)
        filename.grid(row=0, column=1)
        filename.insert(0, 'Experiments/0/0.csv')

        data_button = ttk.Button(self, text="Load data", command=lambda: self.load_data(filename.get()))
        data_button.grid(row=0, column=2)

        self.data_message = tk.StringVar()
        tk.Label(self, textvariable=self.data_message).grid(row=1, column=1)
        self.data_message.set("")

        f = Figure(figsize=(5, 5), dpi=100)
        self.subplot = f.add_subplot(111)
        self.compartment_variable = tk.StringVar(self)

        self.canvas = FigureCanvasTkAgg(f, self)
        # self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
        self.canvas.get_tk_widget().grid(row=2, rowspan=20, columnspan=3)
        self.canvas.show()

        self.compartment_menu = tk.OptionMenu(self, self.compartment_variable, "")
        self.compartment_menu.config(width=20)
        self.compartment_menu.grid(row=23, column=1)

        plot_button = ttk.Button(self, text="Plot", command=lambda: self.update_graph())
        plot_button.grid(row=24, column=1)

        self.pack()

    def load_data(self, filename):
        try:
            csv_file = open(filename, 'r')
            self.data_message.set("Data loaded")
        except IOError:
            self.data_message.set("File {0} not found".format(filename))
            return
        self.subplot.clear()
        self.canvas.show()
        self.comp_data = {}
        self.time_data = []
        csv_reader = csv.DictReader(csv_file)
        compartments = sorted(list(csv_reader.fieldnames))
        compartments.remove('node_id')
        compartments.remove('timestep')

        self.compartment_menu['menu'].delete(0, 'end')
        for choice in compartments:
            self.compartment_menu['menu'].add_command(label=choice, command=tk._setit(self.compartment_variable, choice))

        for c in compartments:
            self.comp_data[c] = {}

        current_time = -1.0
        for row in csv_reader:
            if float(row['timestep']) != current_time:
                self.time_data.append(float(row['timestep']))
                current_time = float(row['timestep'])
            for c in compartments:
                node_data = self.comp_data[c]
                if row['node_id'] not in node_data:
                    node_data[row['node_id']] = []
                node_data[row['node_id']].append(row[c])

        self.pack()

        nodes = self.comp_data.values()[0].keys()
        nodes = sorted(nodes)
        row = 2
        for n in nodes:
            self.node_vars[n] = tk.IntVar()
            tk.Checkbutton(self, text=n, variable=self.node_vars[n]).grid(row=row, column=3)
            row += 1

    def update_graph(self,):
        self.data_message.set("")
        self.subplot.clear()
        if not self.compartment_variable.get():
            return
        compartment_chosen_data = self.comp_data[self.compartment_variable.get()]
        nodes = [n for n in self.node_vars if self.node_vars[n].get() == 1]

        if not nodes:
            nodes = self.node_vars.keys()

        for key in nodes:
            self.subplot.plot(self.time_data, compartment_chosen_data[key], label=key)
        self.canvas.show()

if __name__ == '__main__':
    app = Grapher()
    app.mainloop()


#
# Required by Cython to build Hiredis extensions
#
import os
import sys
from distutils.core import setup
from distutils.extension import Extension
from distutils.errors import (CCompilerError, DistutilsExecError,
                              DistutilsPlatformError)
try:
    from Cython.Distutils import build_ext
    cython_message = None
except ImportError:
    from distutils.command.build_ext import build_ext
    cython_message = 'Cannot build C extensions, Cython is not installed.'

try:
    import numpy
    include_dirs = [numpy.get_include()]
except ImportError:
    include_dirs = []

ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError)
if sys.platform == 'win32' and sys.version_info > (2, 6):
   # 2.6's distutils.msvc9compiler can raise an IOError when failing to
   # find the compiler
   ext_errors += (IOError,)

class BuildFailed(Exception):

    def __init__(self, msg=None):
        if not msg:
            msg = str(sys.exc_info()[1])
        self.msg = msg

class tolerant_build_ext(build_ext):
    # This class allows C extension building to fail. From SQLAlchemy

    def run(self):
        if cython_message:
            raise BuildFailed(cython_message)
        try:
            build_ext.run(self)
        except DistutilsPlatformError:
            raise BuildFailed()

    def build_extension(self, ext):
        if cython_message:
            raise BuildFailed(cython_message)
        try:
            build_ext.build_extension(self, ext)
        except ext_errors:
            raise BuildFailed()
        except ValueError:
            # this can happen on Windows 64 bit, see Python issue 7511
            if "'path'" in str(sys.exc_info()[1]): # works with both py 2/3
                raise BuildFailed()
            raise

################################################################################
##    EXTENSIONS

ext_modules  = Extension('stdnet.lib.hr', ['lib/src/hr.pyx',
                                           'lib/hiredis/hiredis.c',
                                           'lib/hiredis/sds.c',
                                           'lib/src/reader.c'])

base_path = os.path.split(os.path.abspath(__file__))[0]
include_dirs.append(os.path.join(base_path,'hiredis'))
include_dirs.append(os.path.join(base_path,'src'))

libparams = {
             'ext_modules': [ext_modules],
             'cmdclass': {'build_ext' : tolerant_build_ext},
             'include_dirs': include_dirs
             }


'''This script contains all variables for the
exact diagonalization code'''

import gc
import os
import shutil
import threading
import numpy as np
import concurrent.futures

cutoff = 0 # Landau level index cutoff
Q = 4 # Dirac magnetic Monopole charge
StrengthTol = 1e-8
NCPU = os.cpu_count() # Number of CPUs in the current computer
pFactor = 4 # Parallization Factor; Basis States are divided into
# pFactor * NCPU groups

kinConst = 1e+4 # Strength of the kinetic part
intConst = 4e+4 # Strength of the interacting part

l_max = Q - 0.5 + cutoff # Maximum Landau level for the given Magnetic
# field and "cutoff"

TotalSPStates = int((4*cutoff + 2) * Q + 2 * cutoff \
    * (cutoff + 1)) # Total number of single particle states

NParticles = 4 # Total number of electrons in the system
nEigvals = 20

LargestNumber = 2**TotalSPStates

lock = threading.Lock()

def Bset(Q,cutoff,m):
    # Set of quantum numbers if magentic
    # field and cutoff is specified for a given m
    levels = []
    if ((Q*2) % 2) < 1e-8:
#         M = max(int(abs(m)+0.5),)
        for i in range(-cutoff,cutoff+1):
            l = Q + np.abs(i) - 1/2
            if ((np.abs(m)*2) % 2) > 0.999:
                if np.abs(m) <= np.abs(l):
                    levels.append(i)
    else:
        for i in range(-cutoff,cutoff+1):
            l = Q + np.abs(i) - 1/2
            if ((np.abs(m)*2) % 2) < 1e-8:
                if np.abs(m) <= np.abs(l):
                    levels.append(i)
    return levels


import logging
import threading
#import sys
#import sys
#class Unbuffered(object):
#   def __init__(self, stream):
#       self.stream = stream
#   def write(self, data):
#       self.stream.write(data)
#       self.stream.flush()
#   def writelines(self, datas):
#       self.stream.writelines(datas)
#       self.stream.flush()
#   def __getattr__(self, attr):
#       return getattr(self.stream, attr)

#sys.stdout = Unbuffered(sys.stdout)
#print 'Hello'
class deploy_logger:
    def __init__(self,level):
        self._error_list = []

    def log_error(self,msg:str, thread:str, traceback_text:str):
        err = {}
        err['message'] = msg
        err['thread'] = thread
        err['traceback'] = traceback_text
        self._error_list.append(err)

    def get_error_count(self)->int:
        return len(self._error_list)

    def get_error_log(self)->list:
        return self._error_list

    def log(self, object_name:str, msg:str):
        if object_name is None or object_name == '':
            log_msg = msg
        else:
            log_msg = object_name + ': ' + msg
        #print(log_msg, flush=True)
        #print(log_msg)
        #sys.stdout.write(log_msg)
        #sys.stdout.flush()
        # acquire the lock
        lock = threading.Lock()
        lock.acquire()
        # report message
        print(log_msg, flush=True)
        # release the lock
        lock.release()

    def highlight(self, msg:str):
        print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
        print(msg)
        print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!', flush=True)

    def show_all_errors(self):
        error_count = self.get_error_count()
        if error_count > 0:
            self.log('','!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
            self.log('','!!!               Processing Errors                   !!!')
            self.log('','!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
            err_list = self.get_error_log()
            for err in err_list:
                self.log('','####################')
                if err['thread'] is not None and err['thread'] != '':
                    self.log('','### Error Object ###')
                    self.log('',err['thread'])
                self.log('',err['message'])
                self.log('',err['traceback'])
                self.log('','####################')
            self.log('','!!!!!!!!!!!!!!!!!!!!!!!!! end !!!!!!!!!!!!!!!!!!!!!!!!!!!')


from Alien import Alien
from Score import Score

class Alien_Fleet:
    fleet = []
    land = False
    score = Score()

    def __init__(self, fleetX, fleetY):
        posX = 15
        posY = 46
        for i in range(fleetX):
            for j in range(fleetY):
                if j == 0:
                    self.fleet.append(Alien(posX, posY, 3, (255,0,0)))
                elif j == 1 or j == 2:
                    self.fleet.append(Alien(posX, posY, 2, (255,255,0)))
                else:
                    self.fleet.append(Alien(posX, posY, 1, (255,255,255)))
                posY += 62
            posX += 45
            posY = 46

    def draw(self, screen):
        for i in self.fleet:
            i.draw(screen)

    def update(self):
        for i in self.fleet:
            if i.destroyed == True:
                self.fleet.remove(i)
                self.score.plus(i.score)
            if i.land == True:
                self.land = True
            i.update()


#!/usr/bin/env python

"""Setup script for MailManagerPythonInterface."""

import setuptools

from mailmanager import __project__, __version__

import os
if os.path.exists('README.md'):
    README = open('README.md').read()
else:
    README = ""  # a placeholder, readme is generated on release
CHANGES = open('CHANGELOG.md').read()

setuptools.setup(
    name=__project__,
    version=__version__,

    description="Mail Manager Python Interface is a Python 3 package template.",
    url='https://github.com/KyleChamberlin/mail-manager-python-interface',
    author='Kyle Chamberlin',
    author_email='KyleChamberlin@project20million.org',

    packages=setuptools.find_packages(),

    entry_points={'console_scripts': []},

    long_description=(README + '\n' + CHANGES),
    license='MIT',
    classifiers=[
        'Development Status :: 1 - Planning',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3.4',
    ],

    install_requires=open('requirements.txt').readlines(),
)


# Do not use packages that are not in standard distribution of python
import numpy as np
np.random.seed(1024)
from ._base_network import _baseNetwork

class TwoLayerNet(_baseNetwork):
    def __init__(self, input_size=28 * 28, num_classes=10, hidden_size=128):
        super().__init__(input_size, num_classes)

        self.hidden_size = hidden_size
        self._weight_init()

    def _weight_init(self):
        '''
        initialize weights of the network
        :return: None; self.weights is filled based on method
        - W1: The weight matrix of the first layer of shape (num_features, hidden_size)
        - b1: The bias term of the first layer of shape (hidden_size,)
        - W2: The weight matrix of the second layer of shape (hidden_size, num_classes)
        - b2: The bias term of the second layer of shape (num_classes,)
        '''

        # initialize weights
        self.weights['b1'] = np.zeros(self.hidden_size)
        self.weights['b2'] = np.zeros(self.num_classes)
        np.random.seed(1024)
        self.weights['W1'] = 0.001 * np.random.randn(self.input_size, self.hidden_size)
        np.random.seed(1024)
        self.weights['W2'] = 0.001 * np.random.randn(self.hidden_size, self.num_classes)

        # initialize gradients to zeros
        self.gradients['W1'] = np.zeros((self.input_size, self.hidden_size))
        self.gradients['b1'] = np.zeros(self.hidden_size)
        self.gradients['W2'] = np.zeros((self.hidden_size, self.num_classes))
        self.gradients['b2'] = np.zeros(self.num_classes)

    def forward(self, X, y, mode='train'):

        loss = None
        accuracy = None
        #############################################################################
        # TODO:                                                                     #
        #    1) Implement the forward process:                                      #
        #        1) Call sigmoid function between the two layers for non-linearity  #
        #        2) The output of the second layer should be passed to softmax      #
        #        function before computing the cross entropy loss                   #
        #    2) Compute Cross-Entropy Loss and batch accuracy based on network      #
        #       outputs                                                             #
        #############################################################################
        C = self.num_classes
        D = self.input_size
        H = self.hidden_size
        N = X.shape[0]

        X = np.concatenate((X, np.ones((N, 1))), axis = -1)                             #(N, D + 1)
        w1 = np.concatenate((self.weights['W1'], self.weights['b1'].reshape(1, H)))     #(D+1, H)
        w2 = np.concatenate((self.weights['W2'], self.weights['b2'].reshape(1, C)))     #(H + 1, C)

        z1 = X @ w1                     #(N, H)
        s1 = super().sigmoid(z1)        #(N, H)
        a1 = np.concatenate((s1, np.ones((N, 1))), axis = -1) #(N, H+1)

        z2 = a1 @ w2                #(N, C)
        s2 = super().softmax(z2)    #(N, C)

        loss = super().cross_entropy_loss(s2, y)
        accuracy = super().compute_accuracy(s2, y)

        if mode != 'train': return loss, accuracy
        #############################################################################
        #                              END OF YOUR CODE                             #
        #############################################################################

        #############################################################################
        # TODO:                                                                     #
        #    1) Implement the backward process:                                     #
        #        1) Compute gradients of each weight and bias by chain rule         #
        #        2) Store the gradients in self.gradients                           #
        #    HINT: You will need to compute gradients backwards, i.e, compute       #
        #          gradients of W2 and b2 first, then compute it for W1 and b1      #
        #          You may also want to implement the analytical derivative of      #
        #          the sigmoid function in self.sigmoid_dev first                   #
        #############################################################################

        #W2

        dL_dz2 = (s2 - np.eye(C)[y]).transpose()[:, np.newaxis, :]      #(N, C)->  #(C, N) ->  #(C, 1, N)

        dz_dw2 = a1.transpose()[np.newaxis, :, :]                       #(N, H+1) -> (H+1, N) -> (1, H+1, N)

        dL_dw2 = np.mean((dL_dz2 * dz_dw2), axis = -1).transpose()      #(C, H+1, N) -> (C, H+1) -> (H+1, C)

        self.gradients['W2'], self.gradients['b2'] = dL_dw2[:H, :], dL_dw2[H, :].reshape(C,)

        #W1

        dL_da1 = w2[:H, :] @ dL_dz2.reshape((C, N))        #(H, C) X (C, N) = (H, N)

        da_dz1 = self.sigmoid_dev(z1).transpose()          #(N, H) ->(H, N)

        dL_dz1 = (dL_da1 * da_dz1) [np.newaxis, :, :]      #(H,N) -> (1, H, N)

        X = X.transpose()[:, np.newaxis, :]                #(D+1, 1, N)

        dL_dw1 = np.mean(X * dL_dz1, axis = -1)            #(D+1, H, N) -> (D+1, N)

        self.gradients["W1"], self.gradients['b1'] = dL_dw1[:D, :], dL_dw1[D, :].reshape(H,)

        #############################################################################
        #                              END OF YOUR CODE                             #
        #############################################################################

        return loss, accuracy


"""changed column name

Revision ID: d117cba5172d
Revises: 07cc036446ac
Create Date: 2021-12-21 13:01:29.513999

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'd117cba5172d'
down_revision = '07cc036446ac'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('Broup', sa.Column('is_left', sa.Boolean(), nullable=True))
    op.drop_column('Broup', 'left')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('Broup', sa.Column('left', sa.BOOLEAN(), autoincrement=False, nullable=True))
    op.drop_column('Broup', 'is_left')
    # ### end Alembic commands ###


from datetime import datetime, timedelta
import redis
import numpy as np
import pandas as pd
import time
import pickle
import threading
from model_ import model_run_and_forecast, model_preprocessing
from tensorflow.keras.models import load_model
from sklearn.base import clone
from silence_tensorflow import silence_tensorflow
silence_tensorflow()
np.seterr(all="ignore")

def time_update_thread():

    with open("./model/scaler.pickle", 'rb') as p:
        SCALER = pickle.load(p)

    SCALER.clip = False
    INITIAL_DATA = pd.read_csv("./data/initial_data.csv")
    PREDICT_MODEL = load_model("./model/model.h5")
    PREDICT_TIME = 3*24
    rd = redis.StrictRedis(host="localhost", port=6379, db=1)

    # initial model
    initial_x = model_preprocessing(INITIAL_DATA, SCALER)
    predict_result, s_data = model_run_and_forecast(
        PREDICT_MODEL, initial_x, PREDICT_TIME)

    with open("./result/predict_result.pickle", "wb") as r:
        pickle.dump([predict_result, s_data], r, pickle.HIGHEST_PROTOCOL)

    # initial redis
    for i in range(1, (PREDICT_TIME + 1)):
        rd.set(i, 0)

    # time, result update per hour

    while True:
        # time update
        print("Time Update")
        time.sleep(3600)

        new_time_set = {PREDICT_TIME: 0}
        for index in range(1, PREDICT_TIME + 1):
            if index == 1:
                time_index1 = rd.get(index).decode("utf-8")
            else:
                new_time_set[index-1] = rd.get(index).decode("utf-8")

        for key, values in new_time_set.items():
            rd.set(key, int(values))

        # predict data update
        update_data = predict_result[0] + SCALER.transform([[time_index1]])
        test_predict = np.append(initial_x, update_data)[1:]

        # reset data, update result
        initial_x = test_predict
        predict_result, s_data = model_run_and_forecast(
            PREDICT_MODEL, initial_x, PREDICT_TIME)

        with open("./result/predict_result.pickle", "wb") as r:
            pickle.dump([predict_result, s_data], r, pickle.HIGHEST_PROTOCOL)


# ---------------------- PROBLEM 47 (RANDOM) ----------------------------------#
# n computing, a hash table (hash map) is a data structure that implements an
# associative array abstract data type, a structure that can map keys to values.
# A hash table uses a hash function to compute an index, also called a hash code,
# into an array of buckets or slots, from which the desired value can be found.

class HashTable:
	def __init__(self, size=4):
		self.keyMap = [None] * size

# ----------------METHOD 01---------------------#
	# COMPLEXITY = AVERAGE/BEST TIME: O(1), WORST TIME: O(n), SPACE: O(1)
	def hash(self, key):
		total, WEIRD_PRIME = 0, 31
		for i in range(min(len(key), 100)):
			char = key[i]
			value = ord(char) - 96
			total = (total * WEIRD_PRIME + value) % len(self.keyMap)
		return total
# ----------------METHOD 01---------------------#

# ----------------METHOD 02---------------------#
	# COMPLEXITY = TIME: O(1), SPACE: O(1)
	def set(self, key, value):
		hashed_key = self.hash(key)
		if self.keyMap[hashed_key] is None:
			self.keyMap[hashed_key] = []
		self.keyMap[hashed_key].append([key,value])

		return self.keyMap[hashed_key]
# ----------------METHOD 02---------------------#

# ----------------METHOD 03---------------------#
	# COMPLEXITY = TIME: O(1), SPACE: O(1)
	def get(self, key):
		hashed_key = self.hash(key)
		idx = self.keyMap[hashed_key]
		if idx is not None:
			for pair in idx:
				if key == pair[0]: return pair[1]
		return None
# ----------------METHOD 03---------------------#

# ----------------METHOD 04---------------------#
	# COMPLEXITY = TIME: O(n^2), SPACE: O(1)
	def keys(self):
		keyArr = []
		pair_list = self.keyMap
		for lst in pair_list:
			if lst:
				for key in lst:
					if key[0] not in keyArr: keyArr.append(key[0])
		return keyArr
# ----------------METHOD 04---------------------#

# ----------------METHOD 05---------------------#
	# COMPLEXITY = TIME: O(n^2), SPACE: O(1)
	def values(self):
		valArr = []
		pair_list = self.keyMap
		for lst in pair_list:
			if lst:
				for val in lst:
					if val[1] not in valArr: valArr.append(val[1])
		return valArr
# ----------------METHOD 05---------------------#

hashNo = HashTable()
print(hashNo.set('red', '#FF0000')) 	 # [['red', '#FF0000']]
print(hashNo.set('red', '#FF0000')) 	 # [['red', '#FF0000'], ['red', '#FF0000']]
print(hashNo.set('white', '#FFFFFF')) # [['red', '#FF0000'], ['red', '#FF0000'], ['white', '#FFFFFF']]
print(hashNo.get('red')) 			 # #red
print(hashNo.get('meme')) 			 # None
print('******')
print(hashNo.keys()) 				 # ['red', 'white']
print(hashNo.values()) 				 # ['#FF0000', '#FFFFFF']


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the twoPluses function below.
def twoPluses(grid):
    rows = len(grid)
    cols = len(grid[0])
    #
    bigPlus = {}
    # scan the grid to find the largest "+" possible centered on each cell
    for i in range(rows):
        for j in range(cols):
            bigPlus[cellName(i, j)] = plusCells(i,j,grid)
    best = 0
    for iCell in bigPlus.keys():
        iPlus = bigPlus[iCell]
        for jCell in bigPlus.keys():
            if iCell == jCell: continue
            jPlus = bigPlus[jCell]
            while (overlapping(iPlus, jPlus)):
                if len(iPlus) > len(jPlus):
                    iPlus = trimPlus(iPlus)
                else:
                    jPlus = trimPlus(jPlus)
            product = len(iPlus) * len(jPlus)
            if product > best: best = product
            iPlus = bigPlus[iCell]
    return best

def overlapping(plus: list, other: list):
    # empty cells cannot overlap
    if len(plus) == 0 or len(other) == 0: return False
    # first element is the "center" cell of the plus
    # centers are the same - we're checking a plus against itself
    if plus[0] == other[0]: return False
    # now for the main check
    return len(set(plus) & set(other)) > 0

def trimPlus(plus: list):
    # plus will be a list of cells, including the center-cell
    # take the length, subtract 1, divide-by 4 --> the length of each side
    # the sides will be ordered: center-cell, above, below, left, right
    sideLength = math.floor((len(plus) - 1) / 4)
    # if nothing left to remove but the center itself!
    if sideLength == 0: return []
    # remove the last cell from each side
    center = plus[0]
    above = plus[1: sideLength]
    below = plus[sideLength + 1 : sideLength * 2]
    left = plus[sideLength * 2 + 1 : sideLength * 3]
    right = plus[sideLength * 3 + 1: sideLength * 4]
    # and reassemble the lists for the newly trimmed "+"
    return [center, *above, *below, *left, *right]

def cellName(i: int, j: int):
    return f'{i}+{j}'

def plusCells(i: int, j: int, grid):
    bigG = 'G'
    rows = len(grid)
    cols = len(grid[0])
    # store the 4 legs in these
    above = []
    below = []
    left = []
    right = []

    # cells on edges - can not have any legs
    if i == 0 or i == rows - 1 or j == 0 or j == cols - 1: return [cellName(i, j)]

    # above
    for y in range(1,i + 1):
        if grid[i - y][j] != bigG: break
        above.append(cellName(i-y,j))
    # below
    for y in range(i + 1, rows):
        if grid[y][j] != bigG: break
        below.append(cellName(y,j))
    # to-the left
    for x in range(1, j + 1):
        if grid[i][j - x] != bigG: break
        left.append(cellName(i,j-x))
    # to-the right
    for x in range(j + 1, cols):
        if grid[i][x] != bigG: break
        right.append(cellName(i, x))
    # trim all down to the max-common length
    sideLength = min(len(above), len(below), len(left), len(right))
    above = above[:sideLength]
    below = below[:sideLength]
    left = left[:sideLength]
    right = right[:sideLength]
    # combine in this order to store the plus
    return [cellName(i, j), *above, *below, *left, *right]

if __name__ == '__main__':
    try:
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    except KeyError:
        fptr = sys.stdout

    nm = input().split()

    n = int(nm[0])

    m = int(nm[1])

    grid = []

    for _ in range(n):
        grid_item = input()
        grid.append(grid_item)

    result = twoPluses(grid)

    fptr.write(str(result) + '\n')

    fptr.close()