"""empty message

Revision ID: b22e5138a938
Revises: e6210176f55c
Create Date: 2020-10-29 13:52:55.784625

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'b22e5138a938'
down_revision = 'e6210176f55c'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('objectkind',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(length=64), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('validation',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(length=64), nullable=True),
    sa.Column('status', sa.Integer(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('deploymentvalidation',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(length=256), nullable=True),
    sa.Column('token_id', sa.Integer(), nullable=True),
    sa.Column('namespace_id', sa.Integer(), nullable=True),
    sa.Column('objectkind_id', sa.Integer(), nullable=True),
    sa.Column('validation_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['namespace_id'], ['namespace.id'], ),
    sa.ForeignKeyConstraint(['objectkind_id'], ['objectkind.id'], ),
    sa.ForeignKeyConstraint(['token_id'], ['token.id'], ),
    sa.ForeignKeyConstraint(['validation_id'], ['validation.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('deploymentvalidation')
    op.drop_table('validation')
    op.drop_table('objectkind')
    # ### end Alembic commands ###


#!\usr\bin\python3
import sys

#split region into subregion of N bins

input=sys.argv[1]
output=sys.argv[2]
bins=sys.argv[3] #size of subregions

fi=open(input,"r")
fo=open(output,"w")

#fi=open("/home/sadouni/mount/sacapus/silencer_project/silencer_pipeline_output_first_part/pgk/test.bed","r")
#fo=open("/home/sadouni/mount/sacapus/silencer_project/silencer_pipeline_output_first_part/pgk/test_output.bed","a")

def make_bins(bins,fi,fo):
    first_lines=fi.readlines()
    lines = first_lines[1:] #Remove the header
    fo.write("#chr\tstart\tend\tregion_type\tregion_id\tsubregion_id\n") #write new header
    for line in lines: # by line
        elem=line.split("\n")[0].split("\t") #separate the tabulated element
        start=int(elem[1]) # assign start end and region
        end=int(elem[2])
        region=elem[4]
        i=1 #subregion ID
        while start < end : #to dont have greater start than end
            fo.write(('%s\t%i\t') %(elem[0],start)) #write the first start
            start = start + int(bins) #add N bins
            subregion=region+"_"+str(i) #create subregion ID
            if start > end: # to don't have bigger regions than original
                start=end
            i=i+1
            fo.write(('%i\t%s\t%s\t%s\n') %(start,elem[3],elem[4],subregion)) #write new start which is end coordinates of subregion

make_bins(bins,fi,fo)

print("--------------\nDONE\n--------------")
fi.close()
fo.close()


from bs4 import BeautifulSoup
import requests, openpyxl

excel = openpyxl.Workbook()
sheet = excel.active
sheet.title = 'F1 Drivers 2022'
sheet.append(['Given Name', 'Family Name', 'Permanent Number', 'Nationality'])

try:
    source = requests.get('http://ergast.com/api/f1/2022/drivers')
    source.raise_for_status()

    soup = BeautifulSoup(source.text, 'xml')
    print(soup)

    givenNames = soup.find_all('GivenName')
    familyNames = soup.find_all('FamilyName')
    permanentNumbers = soup.find_all('PermanentNumber')
    nationalities = soup.find_all('Nationality')

    for givenName in givenNames:
        print(givenName.get_text())
        sheet.append({'Given Name': givenName.get_text()})

except Exception as e:
    print(e)

excel.save('IMDB Movie Ratings.xlsx')


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

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('skills', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='skill',
            name='alias',
            field=models.CharField(default=b'', max_length=200),
        ),
    ]


# 시퀀스 필터링

my_list = [1, 4, -5, 10, -7, 2, 3, -1]

# 가장 간단한 방범: list comprehension
bigger_then_zero = [n for n in my_list if 0 < n]
print(bigger_then_zero)
smaller_then_zero = [n for n in my_list if n < 0]
print(smaller_then_zero)

# 결과로 생성되는 리스트가 너무 크면 메모리나 시간 측면에서 한번에 리스트로 반환받기가 부담스러울 수가 있다.
# 그럴땐 list comprehensions 대신 Generator expressions을 쓰자.
bigger_generator = (n for n in my_list if 0 < n)
print(bigger_generator)
for item in bigger_generator:
    print(item)

print()

smaller_generator = (n for n in my_list if n < 0)
print(smaller_generator)
for item in smaller_generator:
    print(item)

print()

# 필터링 도중에 예외 처리를 해야 한다거나 복잡한 내용이 들어갈 땐
# 필터링 로직을 구현한 함수를 만들고 filter()를 쓰자
value_list = ['1', '2', '-3', '-', '4', 'N/A', '5']

def is_int(value):
    try:
        _ = int(value)
        return True
    except ValueError:
        return False

int_value = filter(is_int, value_list)
print(int_value)
int_value_list = list(int_value)
print(int_value_list)

print()

# list comprehension의 데이터 변형 기능 1: 조건에 맞는 값만 골라 변형하기
my_list_2 = [1, 4, -5, 10, -7, 2, 3, -1]
import math

square_root_list = [math.sqrt(n) for n in my_list_2 if 0 < n]
print(square_root_list)

# list comprehension의 데이터 변형 기능 2: 조건에 맞지 않는 값은 치환하여 변형하기
clip_neg = [n if 0 < n else 0 for n in my_list_2]
print(clip_neg)
clip_pos = [n if n < 0 else 0 for n in my_list_2]
print(clip_pos)

print()
print('compress')
addresses = [
    '5412 N CLARK',
    '5148 N CLARK',
    '5800 E 58TH',  # bigger than 5
    '2122 N CLARK'

    '5645 N RAVENSWOOD',
    '1060 W ADDISON',  # bigger than 5
    '4801 N BROADWAY',  # bigger than 5
    '1039 W GRANVILLE',
]
counts = [0, 3, 10, 4,
          1, 7, 6, 1]

from itertools import compress

bigger_than_5 = [5 < n for n in counts]
print(bigger_than_5)
bigger_than_5_compress = compress(addresses, bigger_than_5)
print(bigger_than_5_compress)
bigger_than_5_compress_list = list(bigger_than_5_compress)
print(bigger_than_5_compress_list)


import gmsh
import argparse
import math

parser = argparse.ArgumentParser(description="Input arguments")
parser.add_argument("input", metavar="input", type=str,
                    help="Path to mesh")
parser.add_argument("output", metavar="output", type=str,
                    help="Output path")
parser.add_argument("length", metavar="length", type=float,
                    help="Characteristic length mesh")
parser.add_argument("angle", metavar="angle", type=float,
                    help="""Angle at which new surface is defined in degrees.
                    If geometry is smooth, use 180, else use 45.""")

args = parser.parse_args()

gmsh.initialize()
gmsh.clear()

gmsh.option.setNumber("General.NumThreads", 4)

gmsh.merge(args.input)

angle = args.angle * math.pi / 180
gmsh.model.mesh.createTopology()
gmsh.model.mesh.classifySurfaces(angle, True, True)
gmsh.model.mesh.createGeometry()

gmsh.model.mesh.set_size(gmsh.model.getEntities(0), args.length)
gmsh.model.mesh.generate(2)
gmsh.model.mesh.optimize("Netgen")

gmsh.write(args.output)

gmsh.clear()


import cv2 as cv
import numpy as np
import time

# 이미지 불러오기
path = "C:/Users/DELL/PycharmProjects/Object-detection/image/test_shelf_resized.jpg"
img = cv.imread(path, cv.IMREAD_COLOR)
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # shape : (600, 900)
ret,thresh4 = cv.threshold(img_gray,127,255,cv.THRESH_TOZERO) # 책장 프레임 검출

# Sobel 함수와 Harris Corner Detection 사용해서 thresh4(책장) 코너점 검출하기 (구현코드 --- 더 미세하게 조정할 수 있음)

img_sobel_x = cv.Sobel(thresh4, cv.CV_32F, 1, 0)
img_sobel_y = cv.Sobel(thresh4, cv.CV_32F, 0, 1)

IxIx = img_sobel_x * img_sobel_x
IyIy = img_sobel_y * img_sobel_y
IxIy = img_sobel_x * img_sobel_y

height, width = img.shape[:2]

window_size = 5
offset = int(window_size/2)

r = np.zeros(thresh4.shape)

start = time.process_time()
for y in range(offset, height-offset):
    for x in range(offset, width-offset):
        window_IxIx = IxIx[y-offset:y+offset+1, x-offset:x+offset+1]
        window_IyIy = IyIy[y-offset:y+offset+1, x-offset:x+offset+1]
        window_IxIy = IxIy[y-offset:y+offset+1, x-offset:x+offset+1]

        Mxx = window_IxIx.sum()
        Myy = window_IyIy.sum()
        Mxy = window_IxIy.sum()

        det = Mxx*Myy - Mxy*Mxy
        trace = Mxx + Myy

        r[y,x] = det - 0.04 * (trace ** 2)

cv.normalize(r,r,0.0,1.0,cv.NORM_MINMAX)

for y in range(offset, height-offset):
    for x in range(offset, width-offset):
        if r[y, x] > 0.4:
            img.itemset((y, x, 0), 0)
            img.itemset((y, x, 1), 0)
            img.itemset((y, x, 2), 255)

end = time.process_time()
print(end-start)

cv.imshow("original", img)
cv.waitKey(0)

# images_combiend 파일 저장하기
path = "C:/Users/DELL/PycharmProjects/Object-detection/image/images_thresh4_Point.jpg"
cv.imwrite(path, img)

# *** load image *** #
path = "C:/Object-detection/image/test_shelf_resized.jpg"
img_color = cv.imread(path, cv.IMREAD_COLOR)
img_gray = cv.cvtColor(img_color, cv.COLOR_BGR2GRAY) # shape : (600, 900)

# ***make binary image *** #
ret,thresh1 = cv.threshold(img_gray,127,255,cv.THRESH_BINARY)
ret,thresh2 = cv.threshold(img_gray,127,255,cv.THRESH_BINARY_INV) # to detect book
ret,thresh3 = cv.threshold(img_gray,127,255,cv.THRESH_TOZERO_INV)
ret,thresh4 = cv.threshold(img_gray,127,255,cv.THRESH_TOZERO) # to detect bookshelf
thresh2_array = np.float32(thresh2)
thresh4_array = np.float32(thresh4)
# thresh_bookshelf = cv.add(thresh2_array + thresh4_array)  # *** is it work better? ***

# *** detect corner *** #
thresh2_corner = cv.cornerHarris(thresh2_array, 5, 3, 0.04)
thresh2_corner = cv.dilate(thresh2_corner,None) # not important
img_color[thresh2_corner>0.5*thresh2_corner.max()]=[0,0,255] # Threshold : it may vary to the image.

# *** save image *** #
path = "C:/Object-detection/image/images_thresh4_Point_func.jpg"
cv.imwrite(path, img_color)

# *** show image *** #
cv.imshow('detect corner',img_color)
if cv.waitKey(0) & 0xff == 27:
    cv.destroyAllWindows()

cv.destroyAllWindows()

# # cv2의 Corner Harris 함수 사용 (전처리 없이)
# path = "C:/Users/DELL/PycharmProjects/Object-detection/image/test_shelf_resized.jpg"
# img = cv.imread(path, cv.IMREAD_COLOR)
#
# img_gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
# img_gray = np.float32(img_gray)
#
# # print(img_dup)
# # print(img_dup.shape) # (600, 900, 3)
# dst = cv.cornerHarris(img_gray, 5, 3, 0.04)
# # print(dst)
# print(dst.shape) # (600, 900) # 고정시킨 사진 size
# print(dst.max())
# #result is dilated for marking the corners, not important
# dst = cv.dilate(dst,None)
#
# # Threshold for an optimal value, it may vary depending on the image.
# img[dst>0.1*dst.max()]=[0,0,255] # Red Dot
#
# cv.imshow('dst',img)
#
# if cv.waitKey(0) & 0xff == 27:
#     cv.destroyAllWindows()
#
# # corner point 찍힌 사진 저장하기
# path = "C:/Users/DELL/PycharmProjects/Object-detection/image/images_origin_Point_func.jpg"
# cv.imwrite(path, img)


#=======================================================================================================================
# This file traines a Convolutional neural network (CNN) and a Multi layer perceptron (MLP) neural network
# using training features generated in script 02
# Model weights will be saved in weights/ folder
# @ Shaikat Galib / smg478@mst.edu / 25/04/2019
#=======================================================================================================================
from __future__ import print_function, division
import sys
import numpy as np
import pandas as pd
from keras.models import Model
np.random.seed(203)
from keras.utils import to_categorical
from keras.optimizers import Adam
from keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint
from sklearn.metrics import f1_score
from sklearn.externals import joblib
from keras.layers import concatenate
from sklearn.preprocessing import RobustScaler
from keras.layers import Input, Dense, Dropout, Conv1D, Flatten, BatchNormalization, GlobalMaxPool1D
import os
#=======================================================================================================================
# bash train.sh /data/training/ /data/trainingAnswers.csv

########################################################################################################################
expt_name = 'ANN_CNN'
train_folder = '/data/training/'
train_answr = '/data/trainingAnswers.csv'
wdata_dir = '/wdata/'
if len(sys.argv) > 1:
    train_folder = sys.argv[1]
    train_answr = sys.argv[2]
########################################################################################################################

df_train = pd.read_csv(wdata_dir + 'train_feature_bin_30_slice.csv')
#=======================================================================================================================
# Make weight directories
weight_dir ='weights/' + expt_name + '/'
if not os.path.exists(weight_dir):
    os.makedirs(weight_dir)

#=======================================================================================================================
target = df_train.iloc[:, -1]
y= to_categorical(target, num_classes=len(np.unique(target)))
x_trn = df_train.iloc[:,1:-1]

# scale train ==========================================================================================================
X = x_trn.values
where_are_NaNs = np.isnan(X)
where_are_infs = np.isinf(X)
X[where_are_NaNs] = 0
X[where_are_infs] = 0

scaler = RobustScaler()
scaler.fit(X)
# scaler_filename = "scaler.save"
# joblib.dump(scaler, scaler_filename)

scaled_train_X = scaler.transform(X)
X = scaled_train_X
X = X.reshape(len(df_train), len(X[0]), 1)

#========================================================================================================================

def init_model():
    inp = Input(shape=(len(X[0]), 1))

    a = Conv1D(64, 5, activation="relu", kernel_initializer="uniform", )(inp)
    a = BatchNormalization()(a)
    a = Conv1D(64, 5, activation="relu", kernel_initializer="uniform", )(a)
    a = BatchNormalization()(a)
    max_pool = GlobalMaxPool1D()(a)

    b = Flatten()(inp)
    ab = concatenate([ max_pool, b])

    a = Dense(128, activation="relu", kernel_initializer="uniform")(ab)
    a = Dropout(0.5)(a)
    a = Dense(128, activation="relu", kernel_initializer="uniform")(a)

    output = Dense(7, activation="softmax", kernel_initializer="uniform")(a)
    model = Model(inp, output)

    return model

#======================================================================================================================
num_folds = 5
for i in range (7):
    _ids = df_train.index[df_train['152'] == i].tolist()
    all_length = len(_ids)
    fold_len = int(all_length / num_folds)

    init_idx = 0
    for j in range (num_folds):

        _train_idx = _ids[init_idx: init_idx + fold_len]
        init_idx = init_idx + fold_len
        df_train.loc[_train_idx, 'fold'] = j
df_train = df_train.fillna(0)

#=======================================================================================================================
oof = np.zeros(shape = (len(df_train), 7))

for fold_ in range(num_folds):
    trn_idx = df_train.index[df_train['fold'] != fold_].tolist()
    val_idx = df_train.index[df_train['fold'] == fold_].tolist()

    X_train, X_test = X[trn_idx], X[val_idx]
    y_train, y_test = y[trn_idx], y[val_idx]

    #===================================================================================================================
    callbacks = [EarlyStopping(monitor='val_acc',
                               patience=100,
                               verbose=2,
                               min_delta=1e-4,
                               mode='max'),
                 ReduceLROnPlateau(monitor='val_acc',
                                   factor=0.1,
                                   patience=50,
                                   cooldown=2,
                                   verbose=1,
                                   min_delta=1e-4,
                                   mode='max'),
                 ModelCheckpoint(monitor='val_acc',
                                 filepath=weight_dir + 'model_{}.hdf5'.format(fold_),
                                 save_best_only=True,
                                 save_weights_only=False,
                                 mode='max'),
                 #TensorBoard(log_dir="logs/" + expt_name + '/'),
                 #SWA(weight_dir + 'model_swa_{}.hdf5'.format(fold_), 15)
                 ]

    # model training ===================================================================================================
    model = init_model()
    model.compile(loss="categorical_crossentropy", optimizer=Adam(lr=0.001), metrics=["accuracy"])
    # https://github.com/umbertogriffo/focal-loss-keras
    #model.compile(loss = [categorical_focal_loss(alpha=.25, gamma=0)], optimizer=Adam(lr=0.001), metrics=["accuracy"])

    epochs = 30
    model.fit(X_train, y_train,
              validation_data=(X_test, y_test),
              epochs=epochs,
              batch_size=128,
              shuffle=True,
              verbose = 2,
              callbacks=callbacks)

    #===================================================================================================================
    model.load_weights(weight_dir + 'model_{}.hdf5'.format(fold_))
    pred_valid = model.predict(X_test)
    f1_err = f1_score(np.argmax(y_test, axis=1), np.argmax(pred_valid, axis=1), average='macro')
    print('F1 score on validation set:', f1_err)

print('training complete.')


with open('input.txt') as file:
    line = file.readline().strip().split()
    y_vals = line[-1].split('..')
    y_vals[0] = y_vals[0].split('=')[1]
    y_vals = [int(y_vals[0]), int(y_vals[1])]
    x_vals = line[-2].split(',')
    x_vals = x_vals[0].split('..')
    x_vals[0] = x_vals[0].split('=')[1]
    x_vals = [int(x_vals[0]), int(x_vals[1])]
    x_vals.sort()
    y_vals.sort()
    y_max = -1 * y_vals[0]
    y_min = y_vals[0]
    x_max = x_vals[1]
    x_min = 0

    num_angles = 0
    for x_init in range(x_max + 1):
        for y_init in range(y_min, y_max):
            pos = [0,0]
            x_vel = x_init
            y_vel = y_init
            while True:
                pos[0] += x_vel
                pos[1] += y_vel
                if x_vel > 0:
                    x_vel -= 1
                y_vel -= 1
                if pos[0] > x_vals[1] or pos[1] < y_vals[0]:
                    break
                elif pos[0] >= x_vals[0] and pos[1] <= y_vals[1]:
                    num_angles += 1
                    break
    print(num_angles)


import random

class Hero:
    def __init__(self, name, health=100):
        self.name = name
        self.health = health
        self.starting_health = health
        self.current_health = health
        self.abilities = list() # list of abilities and weapons
        self.armors = list()
        self.deaths = 0
        self.kills = 0

    def add_weapon(self, weapon):
        self.abilities.append(weapon)

    def add_ability(self, ability):
        self.abilities.append(ability)

    def add_armor(self, armor):
        self.armors.append(armor)

    def attack(self):
        ''' adds all abilities together to attack '''
        totalDamage = 0
        for ability in self.abilities:
            totalDamage += ability.attack()
        return totalDamage

    def take_damage(self, damage):
        self.health -= damage - self.defend()

    def defend(self):
        ''' Runs block method on each armor to calculate totalDefense '''
        totalDefense = 0
        for armor in self.armors:
            totalDefense += armor.block()

        if self.health <= 0:
            self.deaths += 1
            totalDefense = 0
        return totalDefense

    def is_alive(self):
        if self.health > 0:
            return True
        else:
            return False

    def add_kill(self, num_kills):
        self.kills += num_kills

    def fight(self, opponent):

        while self.is_alive() and opponent.is_alive():

            heroAttack = self.attack()
            opponent.take_damage(heroAttack)

            opponentAttack = opponent.attack()
            self.take_damage(opponentAttack)

            if self.is_alive() == False:
                print("{} died".format(self.name))
                opponent.add_kill(1)
                self.deaths += 1
            if opponent.is_alive() == False:
                print("{} died".format(opponent.name))
                self.add_kill(1)
                opponent.deaths += 1

class Ability:

    def __init__(self, name, attack_strength):
        self.name = name
        self.attack_strength = attack_strength

    def attack(self):
        randomAttackValue = random.randint(0, int(self.attack_strength))
        return randomAttackValue

    def update_attack(self, new_attack_strength):
        newAttackStrengthValue = self.randrange(attack_strength, new_attack_strength)
        return newAttackStrengthValue

class Weapon(Ability):

    def attack(self):
        randomAttackValue = random.randrange(int(self.attack_strength) // 2, int(self.attack_strength))
        return randomAttackValue

class Team:

    def __init__(self, name):
        self.name = name
        self.heroes = list()

    def healthCheck(self):
        total = 0
        for hero in self.heroes:
            total += hero.current_health
        return total

    def add_hero(self, Hero):
        self.heroes.append(Hero)

    def remove_hero(self, name):
        for hero in self.heroes:
            if hero.name == name:
                indexOfHero = self.heroes.index(hero)
                del self.heroes[indexOfHero]
                return
        ''' did not find hero so give an error value '''
        return 0

    def view_all_heroes(self):
        ''' Prints all heroes to the console '''
        for hero in self.heroes:
            print(hero.name)

    def attack(self, other_team):

        randomElement = random.SystemRandom()

        ''' randomly select a living hero from each '''
        selfRandomHero = randomElement.choice(self.heroes)
        other_team_random_hero = randomElement.choice(other_team.heroes)

        ''' Fight until one or both teams have no surviving heroes '''
        while other_team_random_hero.current_health > 0:
            selfRandomHero.fight(other_team_random_hero)
            other_team_random_hero.current_health -= 1

    # def attack(self, other_team):
    #      while self.healthCheck() and other_team.healthCheck():
    #         self.heroes[random.randint(0, len(self.heroes)-1)].fight(other_team.heroes[random.randint(0, len(other_team.heroes)-1)])

    def revive_heroes(self, health=100):
        ''' Resets all heroes health to their original starting value.'''
        for hero in self.heroes:
            hero.health = health

    def stats(self):
        ''' Prints Kills/Deaths ratio for each hero'''
        # for hero in self.heroes:
        #     kdr = hero.kills / hero.deaths
        #     print("{}'s K/D: {}".format(hero.name, kdr))

        for hero in self.heroes:
            if(hero.deaths > 0):
                print("{}: {}".format(self.name, (hero.kills/hero.deaths)))
            else:
                print("{}: {}".format(self.name, hero.kills))

    def still_alive(self):
        for hero in self.heroes:
            if hero.current_health > 0:
                return True
        return False

class Armor:

    def __init__(self, name, max_block):
        self.name = name
        self.max_block = max_block

    def block(self):
        randomValue = random.randrange(0, int(self.max_block))
        return randomValue

class Arena:
    def __init__(self):
        self.team_one = None
        self.team_two = None

    def create_ability(self):
        '''
        This method will allow a user to create an ability.

        Prompt the user for the necessary information to create a new ability object.

        return the new ability object.
        '''
        abilityName = input("\nAbility name: ")
        abilityDamage = input("How much damage attack will the ability {} have? (e.g 30): ".format(abilityName))

        return Ability(abilityName, abilityDamage)

    def create_weapon(self):
        '''
        This method will allow a user to create a weapon.

        Prompt the user for the necessary information to create a new weapon object.

        return the new weapon object.
        '''
        newAbilityName = input("\nOk! Let's create a weapon. What weapon do you want? (e.g shotgun): ")
        newAbilityStrength = input("How much damage do you want your {} to cause? (e.g 25): ".format(newAbilityName))

        return Weapon(newAbilityName, newAbilityStrength)

    def create_armor(self):
        '''
        This method will allow a user to create a piece of armor.

        Prompt the user for the necessary information to create a new armor object.

        return the new armor object.
        '''
        armorName = input("\nArmor type for hero (say something like medium light armor): ")
        armorStrength = input("Armor strength (say something like 25): ")

        return Armor(armorName, armorStrength)

    def create_hero(self):
        '''
        This method should allow a user to create a hero.

        User should be able to specify if they want armors, weapons, and abilites. Call the methods you made above and use the return values to build your hero.

        return the new hero object
        '''
        heroName = input("\nHero name: ")
        return Hero(heroName)

    def build_team_one(self):
        '''
        This method should allow a user to create team one.
        Prompt the user for the number of Heroes on team one and
        call self.create_hero() for every hero that the user wants to add to team one.

        Add the created hero to team one.
        '''
        teamOneName = input("Let's create the 1st team. What do you want to call them?: ")
        numberOfHeroes = int(input("How many heroes do you want to have in Team {}? (Say an integer like 2): ".format(teamOneName)))

        self.team_one = Team(teamOneName)

        while numberOfHeroes > 0:
            # subtract num of heroes so while loop can end
            numberOfHeroes -= 1
            self.team_one.heroes.append(self.create_hero())
        for hero in self.team_one.heroes:
            hero.armors.append(self.create_armor())
            hero.abilities.append(self.create_ability())
            hero.abilities.append(self.create_weapon())

    def build_team_two(self):
        '''
        This method should allow a user to create team two.
        Prompt the user for the number of Heroes on team two and
        call self.create_hero() for every hero that the user wants to add to team two.

        Add the created hero to team two.
        '''
        teamTwoName = input("\nNow, Let's create the 2nd team. What do you want to call them?: ")
        numberOfHeroes = int(input("How many heroes do you want to have in Team {}? (Say an integer like 2): ".format(teamTwoName)))

        self.team_two = Team(teamTwoName)

        while numberOfHeroes > 0:
            numberOfHeroes -= 1
            self.team_two.heroes.append(self.create_hero())
        for hero in self.team_two.heroes:
            hero.armors.append(self.create_armor())
            hero.abilities.append(self.create_ability())
            hero.abilities.append(self.create_weapon())

    def alive_heroes(self):
        '''
        Creates a list of heroes who have health > 0
        '''
        alive_list = []
        #find out if team one has heroes alive
        for hero in self.heroes:
            if hero.is_alive():
                alive_list.append(hero)
        return alive_list

    def team_battle(self):
        '''
        This method should battle the teams together.
        Call the attack method that exists in your team objects to do that battle functionality.
        '''
        self.team_one.attack(self.team_two)

    def show_stats(self):
        '''
        This method should print out battle statistics
        including each team's average kill/death ratio.

        Required Stats:
        Declare winning team
        Show both teams average kill/death ratio.
        Show surviving heroes.
        '''
        print("STATS:")

        # show surviving heroes
        if self.team_one.healthCheck() < 1:
            print(self.team_two.name + " Wins")
            print("Surviving Heroes:")
            for x in self.team_two.heroes:
                if x.current_health > 0:
                    print(x.name)
        elif self.team_two.healthCheck() < 1:
            print(self.team_one.name + " Wins")
            print("Surviving Heroes:")
            for x in self.team_one.heroes:
                if x.current_health > 0:
                    print(x.name)
        print("Team KDR:")
        self.team_one.stats()
        self.team_two.stats()

if __name__ == "__main__":
    game_is_running = True

    # Instantiate Game Arena
    arena = Arena()

    # Build Teams
    arena.build_team_one()
    arena.build_team_two()

    while game_is_running:
        arena.team_battle()
        arena.show_stats()
        play_again = input("Play Again? Y or N: ")

        # Check for Player Input
        if play_again.lower() == "n":
            game_is_running = False
        elif play_again.lower() == "y":
            # Revive heroes to play again
            arena.team_one.revive_heroes()
            arena.team_two.revive_heroes()

''' *** Shout out to Ramon & Sean for helping me with this project *** '''


# Programmers 탐욕법(Greedy) 4. 구명보트

# 시간복잡도: O(NlogN)
from collections import deque

def solution(people, limit):
    answer = 0
    queue = deque(sorted(people))
    while queue:
        heavy = queue[-1]
        light = queue[0]
        if len(queue) == 1:
            answer += 1
            break
        if heavy + light <= limit:
            queue.pop()
            queue.popleft()
        else:
            queue.pop()
        answer += 1

    return answer

'''
1. 사람들을 몸무게순으로 정렬한다.
2. 구명보트는 최대 2명만 탈 수 있기 때문에 가장 마지막에 있는 무거운 사람을 먼저 태우고 가능하다면 가장 처음에 있는 가벼운 사람을 같이 태운다.
3. 2번을 반복하는데 가장 마지막과 가장 처음이 같은 사람, 즉 남은 사람이 1명이라면 보트 하나에 태운다.
'''


import os
import os.path
import random
import sys
import logging
import time
import tornado.websocket
import tornado.web
import tornado.ioloop
from datetime import date, datetime
from perspective import Table, PerspectiveManager, PerspectiveTornadoHandler

class StaticHandler(tornado.web.StaticFileHandler):

    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "x-requested-with")
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')

class MainHandler(tornado.web.RequestHandler):

    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "x-requested-with")
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')

    def get(self):
        self.write("Access the dashboard at: ")

def make_app():
    TABLE = None
    VIEW = None
    CHANGELOG_TABLE = None
    CHANGELOG_VIEW = None

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

    def write_changelog(port_id, row):
        CHANGELOG_TABLE.update(row)

    with open(os.path.join(here, "superstore.arrow"), "rb") as arrow:
        TABLE = Table(arrow.read(), index="Row ID")
        VIEW = TABLE.view()

        CHANGELOG_TABLE = Table(TABLE.schema())
        CHANGELOG_VIEW = CHANGELOG_TABLE.view()

        VIEW.on_update(write_changelog, mode="row")

    MANAGER = PerspectiveManager()
    MANAGER.host_table("data_source", TABLE)
    MANAGER.host_view("data_view", VIEW)
    MANAGER.host_table("changelog_table", CHANGELOG_TABLE)
    MANAGER.host_view("changelog_view", CHANGELOG_VIEW)

    return tornado.web.Application([
        (r"/", MainHandler),
        # create a websocket endpoint that the client Javascript can access
        (r"/static/(.*)", StaticHandler, {"path": os.path.join(here, "static")}),
        (r"/ws", PerspectiveTornadoHandler, {"manager": MANAGER, "check_origin": True})
    ])

if __name__ == "__main__":
    app = make_app()
    port = int(os.environ.get("PORT", 5000))
    app.listen(port)
    logging.critical("Listening on Port {0}".format(port))
    loop = tornado.ioloop.IOLoop.current()
    loop.start()


# -*- coding: utf-8 -*-
"""
Created on Mon Sep  7 19:21:21 2020

@author: joamat
"""

import pandas as pd
import json
import requests
import functions.videos as videos

def callAPI(key, channelId, order):
    return requests.get('https://www.googleapis.com/youtube/v3/search',
                        params={
                                'key': key,
                                'part': 'id,snippet',
                                'channelId': channelId,
                                'maxResults': 6,
                                'order': order
                                })

def dataFrameToCSV(df):
    df.to_csv(r'./data/videos_id.csv', encoding='utf-8-sig')
    print('The table "videos_id.csv" is saved.')

def videosDataFrame(key, channelId, order):
    print('Downloading videos Id...')
    response = callAPI(key, channelId, order)
    json = response.json()
    snippet = []
    for value in json['items']:
        if 'videoId' in value['id'].keys():
            statistics = videos.statistics(key, value['id']['videoId'])
            snippet.append({**value['id'], **value['snippet'], **statistics})
            print(value['id'])

    df = pd.DataFrame(snippet)
    return df

def dropColumns(df):
    dropCol = ['kind', 'thumbnails', 'liveBroadcastContent', 'channelTitle']

    for col in dropCol:
        df = df.drop(col, 1)
    return df

def dropRows(df):
    df = df.dropna(subset=['videoId'])
    return df


from flask import Flask, render_template, request
from textblob import TextBlob

app = Flask(__name__)

@app.route('/', methods = ['GET', 'POST'])
def index():

    if(request.method == 'GET'):
        return render_template('sentiment.html')
    else:
        text = request.form.get('text')
        polarity = TextBlob(text).polarity
        subjectivity = TextBlob(text).subjectivity
        return render_template('result.html', polarity=polarity,subjectivity=subjectivity)

if __name__ == "__main__":
    app.run(debug=True)


import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
from sklearn.metrics import mean_squared_error

np.random.seed(0)
linear_dataset = range(1000000, 2000001)
normal_dataset = np.random.normal(0, 1, 1000000)

dataset = {index: value for index, value in enumerate(sorted(normal_dataset))}
X = np.array([[value] for value in dataset.values()])
y = np.array(list(dataset.keys()))

model = linear_model.LinearRegression()

model.fit(X, y)

y_pred = model.predict(X)

print(mean_squared_error(y, y_pred))
print("min error: {}".format(min(y_pred-y)))
print("max error: {}".format(max(y_pred-y)))

plt.scatter(X, y,  color='black')
plt.plot(X, y_pred, color='blue', linewidth=3)

plt.xticks(())
plt.yticks(())

plt.show()


from piece_generator import piece_distributor, wagon

wagon = wagon()

class Player:
    def __init__(self, name,piece=[]):
        self.name = name
        self.piece = piece

    def player():
        piece_player = piece_distributor()
        player1 = Player("Jogador 1",piece_player[0])

        player2 = Player("Jogador 2",piece_player[1])

        player3 = Player("Jogador 3",piece_player[2])

        player4 = Player("Jogador 4",piece_player[3])

        return player1,player2,player3,player4,piece_player

def show_piece(piece):
    for x in piece:
        if x in wagon.values():
            print(f"[{x}] É uma carroça")
        else:
            print(f"[{x}] Não é carroça")


import os
import json
import argparse
import shutil
import yaml
import copy
from datetime import datetime

import ehr_ml.timeline
import ehr_ml.ontology
import ehr_ml.index
import ehr_ml.labeler
import ehr_ml.clmbr
from ehr_ml.clmbr import Trainer
from ehr_ml.clmbr import PatientTimelineDataset
from ehr_ml.clmbr.dataset import DataLoader

import numpy as np
import pandas as pd

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

from sklearn.model_selection import ParameterGrid
from sklearn.metrics import roc_auc_score
#from torch.utils.data import DataLoader, Dataset
from prediction_utils.pytorch_utils.metrics import StandardEvaluator

parser = argparse.ArgumentParser()

parser.add_argument(
    '--pt_model_path',
    type=str,
    default='/local-scratch/nigam/projects/jlemmon/cl-clmbr/experiments/main/artifacts/models/clmbr/pretrained/models',
    help='Base path for the pretrained model.'
)

parser.add_argument(
    '--model_path',
    type=str,
    default='/local-scratch/nigam/projects/jlemmon/cl-clmbr/experiments/main/artifacts/models/clmbr/contrastive_learn/models',
    help='Base path for the trained end-to-end model.'
)

parser.add_argument(
    '--ft_model_path',
    type=str,
    default='/local-scratch/nigam/projects/jlemmon/cl-clmbr/experiments/main/artifacts/models/clmbr/contrastive_learn/models/gru_sz_800_do_0.1_cd_0_dd_0_lr_0.001_l2_0.01/best',
    help='Base path for the best finetuned model.'
)

parser.add_argument(
    '--cl_rep_best_path',
    type=str,
    default='/local-scratch/nigam/projects/jlemmon/cl-clmbr/experiments/main/artifacts/models/clmbr/cl_rep/models/best',
    help='Base path for the best contrastively trained model.'
)

parser.add_argument(
    '--cl_rep_model_path',
    type=str,
    default='/local-scratch/nigam/projects/jlemmon/cl-clmbr/experiments/main/artifacts/models/clmbr/cl_rep/models',
    help='Base path for the trained CL rep model.'
)

parser.add_argument(
    '--ocp_best_path',
    type=str,
    default='/local-scratch/nigam/projects/jlemmon/cl-clmbr/experiments/main/artifacts/models/clmbr/ocp/models/best',
    help='Base path for the best contrastively trained OCP model.'
)

parser.add_argument(
    '--ocp_model_path',
    type=str,
    default='/local-scratch/nigam/projects/jlemmon/cl-clmbr/experiments/main/artifacts/models/clmbr/ocp/models',
    help='Base path for the trained OCP model.'
)

parser.add_argument(
    '--probe_path',
    type=str,
    default='/local-scratch/nigam/projects/jlemmon/cl-clmbr/experiments/main/artifacts/models/probes/models',
    help='Base path for the trained probe model.'
)

parser.add_argument(
    '--results_path',
    type=str,
    default='/local-scratch/nigam/projects/jlemmon/cl-clmbr/experiments/main/artifacts/results',
    help='Base path for the results.'
)

parser.add_argument(
    '--extract_path',
    type=str,
    default='/local-scratch/nigam/projects/jlemmon/cl-clmbr/experiments/main/data/extracts/20210723',
    help='Base path for the extracted database.'
)

parser.add_argument(
    '--cohort_fpath',
    type=str,
    default="/local-scratch/nigam/projects/jlemmon/cl-clmbr/experiments/main/data/cohort",
    help='Base path for cohort file'
)

parser.add_argument(
    '--hparams_fpath',
    type=str,
    default="/local-scratch/nigam/projects/jlemmon/cl-clmbr/experiments/main/hyperparams",
    help='Base path for hyperparameter files'
)

parser.add_argument(
    '--labelled_fpath',
    type=str,
    default="/local-scratch/nigam/projects/jlemmon/cl-clmbr/experiments/main/data/labelled_data",
    help='Base path for labelled data directory'
)

parser.add_argument(
    '--cohort_dtype',
    type=str,
    default='parquet',
    help='Data type for cohort file.'
)

parser.add_argument(
    "--seed",
    type = int,
    default = 44,
    help = "seed for deterministic training"
)

parser.add_argument(
    '--batch_size',
    type=int,
    default=512,
    help='Size of training batch.'
)

parser.add_argument(
    '--epochs',
    type=int,
    default=20,
    help='Number of training epochs.'
)

parser.add_argument(
    '--n_boot',
    type=int,
    default=1000,
    help='Number of bootstrap iterations.'
)

parser.add_argument(
    '--n_jobs',
    type=int,
    default=8,
    help='Number of bootstrap jobs.'
)

parser.add_argument(
    '--early_stop',
    type=int,
    default=5,
    help='Number of training epochs before early stop is triggered.'
)

parser.add_argument(
    '--size',
    type=int,
    default=800,
    help='Size of embedding vector.'
)

parser.add_argument(
    '--dropout',
    type=float,
    default=0.1,
    help='Dropout proportion for training.'
)

parser.add_argument(
    '--pooler',
    type=str,
    default='cls',
    help='Pooler type to retrieve embedding.'
)

parser.add_argument(
    '--temp',
    type=float,
    default=0.05,
    help='Temperature value for the similarity scoring calculation'
)

parser.add_argument(
    '--lr',
    type=float,
    default=0.001,
    help='Learning rate for pretrained model.'
)

parser.add_argument(
	'--cl_lr',
	type=float,
	default=3e-5,
	help='Learning rate for constrastive learning finetuning.'
)

parser.add_argument(
    '--encoder',
    type=str,
    default='gru',
    help='Underlying neural network architecture for CLMBR. [gru|transformer|lstm]'
)

parser.add_argument(
    '--device',
    type=str,
    default='cuda:0',
    help='Device to run torch model on.'
)

parser.add_argument(
	'--patience',
	type=int,
	default=5,
	help='Number of epochs to wait before triggering early stopping.'
)

class LinearProbe(nn.Module):
	def __init__(self, clmbr_model, size, device='cuda:0', is_ocp=False):
		super().__init__()
		self.clmbr_model = clmbr_model
		self.config = clmbr_model.config
		self.is_ocp = is_ocp

		self.dense = nn.Linear(size,1)
		self.activation = nn.Sigmoid()

		self.device = torch.device(device)

	def forward(self, batch):
		if self.is_ocp:
			features = self.clmbr_model.timeline_model(batch['rnn'])[0].to(self.device)
		else:
			features = self.clmbr_model.timeline_model(batch['rnn']).to(self.device)

		label_indices, label_values = batch['label']

		flat_features = features.view((-1, features.shape[-1]))
		target_features = F.embedding(label_indices, flat_features).to(args.device)

		preds = self.activation(self.dense(target_features))

		return preds, label_values.to(torch.float32)

	def freeze_clmbr(self):
		self.clmbr_model.freeze()

	def unfreeze_clmbr(self):
		self.clmbr_model.unfreeze()

class EarlyStopping():
	def __init__(self, patience):
		self.patience = patience
		self.early_stop = False
		self.best_loss = 9999999
		self.counter = 0
	def __call__(self, loss):
		if self.best_loss > loss:
			self.counter = 0
			self.best_loss = loss
		else:
			self.counter += 1
			if self.counter == self.patience:
				self.early_stop = True
		return self.early_stop

def load_datasets(args, task, clmbr_hp, clmbr_model_path):
	"""
	Load datasets from split csv files.
	"""
	data_path = f'{args.labelled_fpath}/{task}/pretrained/{args.encoder}_sz_{clmbr_hp["size"]}_do_{clmbr_hp["dropout"]}_cd_{clmbr_hp["code_dropout"]}_dd_{clmbr_hp["day_dropout"]}_lr_{clmbr_hp["lr"]}_l2_{clmbr_hp["l2"]}'

	train_pids = pd.read_csv(f'{data_path}/ehr_ml_patient_ids_train.csv')
	val_pids = pd.read_csv(f'{data_path}/ehr_ml_patient_ids_val.csv')
	test_pids = pd.read_csv(f'{data_path}/ehr_ml_patient_ids_test.csv')

	train_days = pd.read_csv(f'{data_path}/day_indices_train.csv')
	val_days = pd.read_csv(f'{data_path}/day_indices_val.csv')
	test_days = pd.read_csv(f'{data_path}/day_indices_test.csv')

	train_labels = pd.read_csv(f'{data_path}/labels_train.csv')
	val_labels = pd.read_csv(f'{data_path}/labels_val.csv')
	test_labels = pd.read_csv(f'{data_path}/labels_test.csv')

	train_data = (train_labels.to_numpy().flatten(),train_pids.to_numpy().flatten(),train_days.to_numpy().flatten())
	val_data = (val_labels.to_numpy().flatten(),val_pids.to_numpy().flatten(),val_days.to_numpy().flatten())
	test_data = (test_labels.to_numpy().flatten(),test_pids.to_numpy().flatten(),test_days.to_numpy().flatten())

	train_dataset = PatientTimelineDataset(args.extract_path + '/extract.db',
											 args.extract_path + '/ontology.db',
											 f'{clmbr_model_path}/info.json',
											 train_data,
											 val_data )

	test_dataset = PatientTimelineDataset(args.extract_path + '/extract.db',
										 args.extract_path + '/ontology.db',
										 f'{clmbr_model_path}/info.json',
										 train_data,
										 test_data )

	return train_dataset, test_dataset

def train_probe(args, model, dataset, save_path):
	"""
	Train linear classification probe on frozen CLMBR model.
	At each epoch save model if validation loss was improved.
	"""
	model.train()
	model.freeze_clmbr()
	optimizer = optim.Adam([p for n, p in model.named_parameters() if p.requires_grad], lr=args.lr)

	criterion = nn.BCELoss()

	early_stop = EarlyStopping(args.patience)

	best_model = None
	best_val_loss = 9999999
	best_val_preds = []
	best_val_lbls = []
	best_val_ids = []

	for e in range(args.epochs):
		val_preds = []
		val_lbls = []
		val_ids = []
		print(f'epoch {e+1}/{args.epochs}')
		epoch_train_loss = 0.0
		epoch_val_loss = 0.0
		# Iterate through training data loader
		with DataLoader(dataset, model.config['num_first'], is_val=False, batch_size=model.config["batch_size"], device=args.device) as train_loader:
			for batch in train_loader:

				optimizer.zero_grad()
				logits, labels = model(batch)
				loss = criterion(logits, labels.unsqueeze(-1))

				loss.backward()
				optimizer.step()
				epoch_train_loss += loss.item()

		# Iterate through validation data loader
		with torch.no_grad():
			with DataLoader(dataset, 9262, is_val=True, batch_size=model.config["batch_size"], device=args.device) as val_loader:
				for batch in val_loader:
					logits, labels = model(batch)
					loss = criterion(logits, labels.unsqueeze(-1))
					epoch_val_loss += loss.item()
					val_preds.extend(logits.cpu().numpy().flatten())
					val_lbls.extend(labels.cpu().numpy().flatten())
					val_ids.extend(batch['pid'])
				# val_losses.append(epoch_val_loss)

		#print epoch losses
		print('epoch train loss:', epoch_train_loss)
		print('epoch val loss:', epoch_val_loss)

		# save model if validation loss is improved
		if epoch_val_loss < best_val_loss:
			print('Saving best model...')
			best_val_loss = epoch_val_loss
			best_model = copy.deepcopy(model)
			torch.save(best_model, f'{save_path}/best_model.pth')

			# flatten prediction and label arrays
			best_val_preds = val_preds
			best_val_lbls = val_lbls
			best_val_ids = val_ids

		# Trigger early stopping if model hasn't improved for awhile
		if early_stop(epoch_val_loss):
			print(f'Early stopping at epoch {e}')
			break
	return best_model, best_val_preds, best_val_lbls, best_val_ids

def evaluate_probe(args, model, dataset):
	model.eval()

	criterion = nn.BCELoss()

	preds = []
	lbls = []
	ids = []
	with torch.no_grad():
		with DataLoader(dataset, model.config['num_first'], is_val=True, batch_size=model.config['batch_size'], seed=args.seed, device=args.device) as eval_loader:
			for batch in eval_loader:
				if (len(batch['pid']) != len(batch['label'][0])):
					batch['pid'] = batch['pid'][:len(batch['label'][0])] #temp fix
				logits, labels = model(batch)
				loss = criterion(logits, labels.unsqueeze(-1))
				# losses.append(loss.item())
				preds.extend(logits.cpu().numpy().flatten())
				lbls.extend(labels.cpu().numpy().flatten())
				ids.extend(batch['pid'])
	return preds, lbls, ids

def calc_metrics(args, df):
	evaluator = StandardEvaluator()
	eval_ci_df, eval_df = evaluator.bootstrap_evaluate(
		df,
		n_boot = args.n_boot,
		n_jobs = args.n_jobs,
		strata_vars_eval = ['phase'],
		strata_vars_boot = ['labels'],
		patient_id_var='person_id',
		return_result_df = True
	)
	eval_ci_df['model'] = 'probe'
	return eval_ci_df

if __name__ == '__main__':
	args = parser.parse_args()

	torch.manual_seed(args.seed)
	tasks = ['hospital_mortality','LOS_7','readmission_30','icu_admission','aki1_label','aki2_label','hg_label','np_500_label','np_1000_label']

	# load best CLMBR model parameter grid
	bl_hp = list(
		ParameterGrid(
			yaml.load(
				open(
					f"{os.path.join(args.hparams_fpath,args.encoder)}-do-best.yml",
					'r'
				),
				Loader=yaml.FullLoader
			)
		)
	)[0]

	rd_hp = list(
		ParameterGrid(
			yaml.load(
				open(
					f"{os.path.join(args.ft_model_path + '_' + 'rand_day','hyperparams')}.yml",
					'r'
				),
				Loader=yaml.FullLoader
			)
		)
	)[0]

	dp_hp = list(
		ParameterGrid(
			yaml.load(
				open(
					f"{os.path.join(args.ft_model_path + '_' + 'diff_pat','hyperparams')}.yml",
					'r'
				),
				Loader=yaml.FullLoader
			)
		)
	)[0]

	mr_hp = list(
		ParameterGrid(
			yaml.load(
				open(
					f"{os.path.join(args.ft_model_path,'hyperparams')}.yml",
					'r'
				),
				Loader=yaml.FullLoader
			)
		)
	)[0]

	cl_rep_hp = list(
		ParameterGrid(
			yaml.load(
				open(
					f"{os.path.join(args.cl_rep_best_path,'hyperparams')}.yml",
					'r'
				),
				Loader=yaml.FullLoader
			)
		)
	)[0]

	ocp_hp = list(
		ParameterGrid(
			yaml.load(
				open(
					f"{os.path.join(args.ocp_best_path,'hyperparams')}.yml",
					'r'
				),
				Loader=yaml.FullLoader
			)
		)
	)[0]

	# Iterate through tasks
	for task in tasks:
		print(f'Task {task}')

		# Iterate through (singular) CLMBR hyperparam settings

# 		print('Training BL CLMBR probe with params: ', bl_hp)

# # 		# Path where CLMBR model is saved
		bl_model_str = f'{args.encoder}_sz_{bl_hp["size"]}_do_{bl_hp["dropout"]}_cd_{bl_hp["code_dropout"]}_dd_{bl_hp["day_dropout"]}_lr_{bl_hp["lr"]}_l2_{bl_hp["l2"]}'
		clmbr_model_path = f'{args.pt_model_path}/{bl_model_str}'
# # 		print(clmbr_model_path)

# # 		# Load  datasets
		train_dataset, test_dataset = load_datasets(args, task, bl_hp, clmbr_model_path)

# # 		# Path where CLMBR probe will be saved
# 		probe_save_path = f'{args.probe_path}/{task}/baseline/{bl_model_str}'
# 		os.makedirs(f"{probe_save_path}",exist_ok=True)

# 		result_save_path = f'{args.results_path}/{task}/probes/baseline/{bl_model_str}'
# 		os.makedirs(f"{result_save_path}",exist_ok=True)

# 		# Load CLMBR model and attach linear probe
# 		clmbr_model = ehr_ml.clmbr.CLMBR.from_pretrained(clmbr_model_path, args.device).to(args.device)
# 		clmbr_model.freeze()

# 		probe_model = LinearProbe(clmbr_model, bl_hp['size'])

# 		probe_model.to(args.device)

# 		print('Training probe...')
# 		# Train probe and evaluate on validation
# 		probe_model, val_preds, val_labels, val_ids = train_probe(args, probe_model, train_dataset, probe_save_path)

# 		val_df = pd.DataFrame({'CLMBR':'BL', 'model':'linear', 'task':task, 'phase':'val', 'person_id':val_ids, 'pred_probs':val_preds, 'labels':val_labels})
# 		val_df.to_csv(f'{result_save_path}/val_preds.csv',index=False)

# 		print('Testing probe...')
# 		test_preds, test_labels, test_ids = evaluate_probe(args, probe_model, test_dataset)

# 		test_df = pd.DataFrame({'CLMBR':'BL', 'model':'linear', 'task':task, 'phase':'test', 'person_id':test_ids, 'pred_probs':test_preds, 'labels':test_labels})
# 		test_df.to_csv(f'{result_save_path}/test_preds.csv',index=False)
# 		df_preds = pd.concat((val_df,test_df))
# 		df_preds['CLMBR'] = df_preds['CLMBR'].astype(str)
# 		df_preds['model'] = df_preds['model'].astype(str)
# 		df_preds['task'] = df_preds['task'].astype(str)
# 		df_preds['phase'] = df_preds['phase'].astype(str)

# 		df_eval = calc_metrics(args, df_preds)
# 		df_eval['CLMBR'] = 'BL'
# 		df_eval['task'] = task
# 		df_eval.to_csv(f'{result_save_path}/eval.csv',index=False)

# 		for cl_hp in [mr_hp]:#[dp_hp, rd_hp, mr_hp]:
# 			print('Training CL-CLMBR probe with params: ', cl_hp)
# 			cl_model_str = f'bs_{cl_hp["batch_size"]}_lr_{cl_hp["lr"]}_temp_{cl_hp["temp"]}_pool_{cl_hp["pool"]}'
# 			cl_model_path = f"{args.ft_model_path}_{cl_hp['pool']}"
# 			# Create probe and result directories
# 			probe_save_path = f'{args.probe_path}/{task}/contrastive_learn/{bl_model_str}/{cl_model_str}'

# 			os.makedirs(f"{probe_save_path}",exist_ok=True)

# 			result_save_path = f'{args.results_path}/{task}/probes/contrastive_learn/{bl_model_str}/{cl_model_str}'

# 			os.makedirs(f"{result_save_path}",exist_ok=True)

# 			# load cl clmbr model
# 			cl_model = ehr_ml.clmbr.CLMBR.from_pretrained(clmbr_model_path, args.device).to(args.device)
# 			cl_model.freeze()

# 			# Get probe model
# 			cl_probe_model = LinearProbe(cl_model, bl_hp['size'])

# 			cl_probe_model.to(args.device)

# 			# Train probe and get best model by validation score
# 			cl_probe_model, val_preds, val_labels, val_ids = train_probe(args, cl_probe_model, train_dataset,  probe_save_path)
# 			cl_str = 'CL-'
# 			if cl_hp['pool'] == 'mean_rep':
# 				cl_str += 'MR'
# 			elif cl_hp['pool'] == 'rand_day':
# 				cl_str += 'RD'
# 			elif cl_hp['pool'] == 'diff_pat':
# 				cl_str += 'DP'
# 			val_df = pd.DataFrame({'CLMBR':cl_str, 'model':'linear','task':task, 'phase':'val', 'person_id':val_ids, 'pred_probs':val_preds, 'labels':val_labels})
# 			val_df.to_csv(f'{result_save_path}/val_preds.csv',index=False)

# 			# Run probe on test set
# 			print('Testing probe...')

# 			test_preds, test_labels, test_ids = evaluate_probe(args, cl_probe_model, test_dataset)
# 			test_df = pd.DataFrame({'CLMBR':cl_str, 'model':'linear', 'task':task, 'phase':'test', 'person_id':test_ids, 'pred_probs':test_preds, 'labels':test_labels})
# 			test_df.to_csv(f'{result_save_path}/test_preds.csv',index=False)

# 			# create pred prob df and bootstrap metrics
# 			df_preds = pd.concat((val_df,test_df))
# 			df_eval = calc_metrics(args, df_preds)
# 			df_eval['CLMBR'] = cl_str
# 			df_eval['task'] = task
# 			print(df_eval)
# 			df_eval.to_csv(f'{result_save_path}/eval.csv',index=False)

# 		print('Training CL Representation probe with params: ', cl_rep_hp)

# 		# Path where CLMBR model is saved
# 		cl_model_str = f'gru_sz_800_do_0.1_cd_0_dd_0_lr_0.01_l2_0.1_bs_1000_lr_3e-5_temp_0.01_pool_rand_day'
# 		clmbr_model_path = f'{args.cl_rep_best_path}'
# 		print(clmbr_model_path)

# 		# Path where CLMBR probe will be saved
# 		probe_save_path = f'{args.probe_path}/{task}/cl_rep/{cl_model_str}'
# 		os.makedirs(f"{probe_save_path}",exist_ok=True)

# 		result_save_path = f'{args.results_path}/{task}/probes/cl_rep/{cl_model_str}'
# 		os.makedirs(f"{result_save_path}",exist_ok=True)

# 		# Load CLMBR model and attach linear probe
# 		clmbr_model = ehr_ml.clmbr.CLMBR.from_pretrained(clmbr_model_path, args.device).to(args.device)
# 		clmbr_model.freeze()

# 		probe_model = LinearProbe(clmbr_model, bl_hp['size'])

# 		probe_model.to(args.device)

# 		print('Training probe...')
# 		# Train probe and evaluate on validation
# 		probe_model, val_preds, val_labels, val_ids = train_probe(args, probe_model, train_dataset, probe_save_path)

# 		val_df = pd.DataFrame({'CLMBR':'CL_REP', 'model':'linear', 'task':task, 'phase':'val', 'person_id':val_ids, 'pred_probs':val_preds, 'labels':val_labels})
# 		val_df.to_csv(f'{result_save_path}/val_preds.csv',index=False)

# 		print('Testing probe...')
# 		test_preds, test_labels, test_ids = evaluate_probe(args, probe_model, test_dataset)

# 		test_df = pd.DataFrame({'CLMBR':'CL_REP', 'model':'linear', 'task':task, 'phase':'test', 'person_id':test_ids, 'pred_probs':test_preds, 'labels':test_labels})
# 		test_df.to_csv(f'{result_save_path}/test_preds.csv',index=False)
# 		df_preds = pd.concat((val_df,test_df))
# 		df_preds['CLMBR'] = df_preds['CLMBR'].astype(str)
# 		df_preds['model'] = df_preds['model'].astype(str)
# 		df_preds['task'] = df_preds['task'].astype(str)
# 		df_preds['phase'] = df_preds['phase'].astype(str)

# 		df_eval = calc_metrics(args, df_preds)
# 		df_eval['CLMBR'] = 'CL_REP'
# 		df_eval['task'] = task
# 		df_eval.to_csv(f'{result_save_path}/eval.csv',index=False)

		print('Training OCP probe with params: ', ocp_hp)

		# Path where CLMBR model is saved
		cl_model_str = f'gru_sz_800_do_0.1_l2_0.1_lr_5e-5_pool_ocp'
		clmbr_model_path = f'{args.ocp_best_path}'
		print(clmbr_model_path)

		# Path where CLMBR probe will be saved
		probe_save_path = f'{args.probe_path}/{task}/ocp/{cl_model_str}'
		os.makedirs(f"{probe_save_path}",exist_ok=True)

		result_save_path = f'{args.results_path}/{task}/probes/ocp/{cl_model_str}'
		os.makedirs(f"{result_save_path}",exist_ok=True)

		# Load CLMBR model and attach linear probe
		clmbr_model = ehr_ml.clmbr.CLMBR.from_pretrained(clmbr_model_path, args.device).to(args.device)
		clmbr_model.freeze()

		probe_model = LinearProbe(clmbr_model, bl_hp['size'], is_ocp=True)

		probe_model.to(args.device)

		print('Training probe...')
		# Train probe and evaluate on validation
		probe_model, val_preds, val_labels, val_ids = train_probe(args, probe_model, train_dataset, probe_save_path)

		val_df = pd.DataFrame({'CLMBR':'OCP', 'model':'linear', 'task':task, 'phase':'val', 'person_id':val_ids, 'pred_probs':val_preds, 'labels':val_labels})
		val_df.to_csv(f'{result_save_path}/val_preds.csv',index=False)

		print('Testing probe...')
		test_preds, test_labels, test_ids = evaluate_probe(args, probe_model, test_dataset)

		test_df = pd.DataFrame({'CLMBR':'OCP', 'model':'linear', 'task':task, 'phase':'test', 'person_id':test_ids, 'pred_probs':test_preds, 'labels':test_labels})
		test_df.to_csv(f'{result_save_path}/test_preds.csv',index=False)
		df_preds = pd.concat((val_df,test_df))
		df_preds['CLMBR'] = df_preds['CLMBR'].astype(str)
		df_preds['model'] = df_preds['model'].astype(str)
		df_preds['task'] = df_preds['task'].astype(str)
		df_preds['phase'] = df_preds['phase'].astype(str)

		df_eval = calc_metrics(args, df_preds)
		df_eval['CLMBR'] = 'OCP'
		df_eval['task'] = task
		df_eval.to_csv(f'{result_save_path}/eval.csv',index=False)


def solution(enroll, referral, seller, amount):
    answer = []
    relationship = {e : r for e, r in zip(enroll, referral)}
    money = {e : 0 for e in enroll}

    for s, a in zip(seller, amount):
        profit = a * 100
        while s != '-':
            money[s] += profit - int(profit * 0.1)
            s = relationship[s]
            profit = int(profit * 0.1)
            if profit == 0:
                break

    for e in enroll:
        answer.append(money[e])

    return answer

이경훈_77486_다단계 칫솔 판매.py