#!/usr/bin/env python
# encoding: utf-8
import argparse
from zstacklib import *

start_time = datetime.now()
# set default value
file_root = "files/consoleproxy"
pip_url = 'https://pypi.python.org/simple/'
proxy = ""
sproxy = ""
chroot_env = 'false'
zstack_repo = 'false'
post_url = ""
pkg_consoleproxy = ""
virtualenv_version = "12.1.1"
remote_user = "root"
remote_pass = None
remote_port = None

# get parameter from shell
parser = argparse.ArgumentParser(description='Deploy consoleproxy to management node')
parser.add_argument('-i', type=str, help="""specify inventory host file
                        default=/etc/ansible/hosts""")
parser.add_argument('--private-key', type=str, help='use this file to authenticate the connection')
parser.add_argument('-e', type=str, help='set additional variables as key=value or YAML/JSON')

args = parser.parse_args()
argument_dict = eval(args.e)
locals().update(argument_dict)
# update the variable from shell arguments
virtenv_path = "%s/virtualenv/consoleproxy/" % zstack_root
consoleproxy_root = "%s/console/package" % zstack_root
host_post_info = HostPostInfo()
# create log
logger_dir = "/var/log/zstack/"
create_log(logger_dir)
host_post_info.host = host
host_post_info.host_inventory = args.i

host_post_info.post_url = post_url
host_post_info.transport = 'local'

# include zstacklib.py
(distro, distro_version, distro_release) = get_remote_host_info(host_post_info)
zstacklib_args = ZstackLibArgs()
zstacklib_args.distro = distro
zstacklib_args.distro_release = distro_release
zstacklib_args.distro_version = distro_version
zstacklib_args.zstack_repo = zstack_repo
zstacklib_args.yum_server = yum_server
zstacklib_args.zstack_root = zstack_root
zstacklib_args.host_post_info = host_post_info
zstacklib_args.pip_url = pip_url
zstacklib_args.trusted_host = trusted_host
zstacklib = ZstackLib(zstacklib_args)

# name: judge this process is init install or upgrade
if file_dir_exist("path=" + consoleproxy_root, host_post_info):
    init_install = False
else:
    init_install = True
    # name: create root directories
    command = 'mkdir -p %s %s' % (consoleproxy_root, virtenv_path)
    run_remote_command(command, host_post_info)

run_remote_command("rm -rf %s/*" % consoleproxy_root, host_post_info)

# name: copy zstacklib
copy_arg = CopyArg()
copy_arg.src = "files/zstacklib/%s" % pkg_zstacklib
copy_arg.dest = "%s/%s" % (consoleproxy_root, pkg_zstacklib)
copy_zstacklib = copy(copy_arg, host_post_info)
# name: copy consoleproxy
copy_arg = CopyArg()
copy_arg.src = "%s/%s" % (file_root, pkg_consoleproxy)
copy_arg.dest = "%s/%s" % (consoleproxy_root, pkg_consoleproxy)
copy_consoleproxy = copy(copy_arg, host_post_info)
# only for os using init.d not systemd  -- by diwen
# copy_arg = CopyArg()
# copy_arg.src = "%s/zstack-consoleproxy" % file_root
# copy_arg.dest = "/etc/init.d/"
# copy_arg.args = "mode=755"
# copy(copy_arg, host_post_info)

# name: install virtualenv
virtual_env_status = check_and_install_virtual_env(virtualenv_version, trusted_host, pip_url, host_post_info)
if virtual_env_status is False:
    command = "rm -rf %s && rm -rf %s" % (virtenv_path, consoleproxy_root)
    run_remote_command(command, host_post_info)
    sys.exit(1)

# name: make sure virtualenv has been setup
command = "[ -f %s/bin/python ] || virtualenv %s " % (virtenv_path, virtenv_path)
run_remote_command(command, host_post_info)

# name: install zstacklib
if copy_zstacklib != "changed:False":
    agent_install_arg = AgentInstallArg(trusted_host, pip_url, virtenv_path, init_install)
    agent_install_arg.agent_name = "zstacklib"
    agent_install_arg.agent_root = consoleproxy_root
    agent_install_arg.pkg_name = pkg_zstacklib
    agent_install(agent_install_arg, host_post_info)

# name: install consoleproxy
if copy_consoleproxy != "changed:False":
    agent_install_arg = AgentInstallArg(trusted_host, pip_url, virtenv_path, init_install)
    agent_install_arg.agent_name = "consoleproxy"
    agent_install_arg.agent_root = consoleproxy_root
    agent_install_arg.pkg_name = pkg_consoleproxy
    agent_install(agent_install_arg, host_post_info)

# name: restart consoleproxy
if chroot_env == 'false':
    if distro == "RedHat" or distro == "CentOS":
        command = "systemctl stop zstack-consoleproxy && systemctl start zstack-consoleproxy"
    elif distro == "Debian" or distro == "Ubuntu":
        command = "systemctl stop zstack-consoleproxy && systemctl start zstack-consoleproxy"  #  by diwen
    run_remote_command(command, host_post_info)

host_post_info.start_time = start_time
handle_ansible_info("SUCC: Deploy consoleproxy agent successful", host_post_info, "INFO")

sys.exit(0)


import pandas as pd
import numpy as np
import folium

interim_data_path = 'data/interim/'

data_df = pd.read_csv(interim_data_path + 'DataSampleLabeled.csv')
poi_df = pd.read_csv(interim_data_path + 'POIlistCleaned.csv')
poi_df.set_index('POIID', inplace=True)

#remove errenous entries (lon/lat do not match Canada locations)
data_df = data_df[data_df['ClosestDistance'] < 3000]

#Calcuate the average and standard deviation of distrance for each POI
poi_stats = data_df.groupby('ClosestPOI').agg({'ClosestDistance':['mean', 'std']})

print(poi_stats)
print('\n')

#create dataframe for plotting
#the max ClosesetDistance is used as the radium to ensure all locations are
#covered

poi_plot = data_df.groupby('ClosestPOI').agg({'ClosestDistance':['max','count']})
poi_plot.columns = poi_plot.columns.get_level_values(1)

#merge with POIlistCleaned
poi_plot = poi_plot.merge(poi_df, left_index = True, right_on = 'POIID')
print('\n')

# Plot with Folium
m = folium.Map(location=[55, -100], width=1000, height=500,zoom_start=3)

for i, data in poi_plot.iterrows():
    folium.Circle(location=[data['Latitude'],data['Longitude']],
    radius=data['max']*1000, popup = str(i), color='#3186cc', fill=True,
    fill_color='#3186cc').add_to(m)

viz_out_path = 'submission/visualization/'
m.save(viz_out_path + 'POICoverPlot.html')

# Calculate densign
poi_density = poi_plot[['max','count']].copy()

poi_density.columns = ['radius','count']

poi_density['density'] = np.divide(poi_density['count'],
np.power(poi_density['radius'],2)*np.pi)

print(poi_density)


import subprocess
import os
import sys
import cv2
import numpy as np

my_env = os.environ
def bash(command):
    p = subprocess.Popen(command, env=my_env, shell=True)
    pd = p.pid
    p.wait()
    # process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    # output, error = process.communicate()
    # return output,error
opt = {
    'Model' : None,
    'images' : [],
}

transform = 'BtoA'
alpha = 10 # High means low impact of adverserial
lbda = 1 # High means high impact of adverserial
niter = 1000

ntrain = 2

# if(sys.argv[1].split('.') != 'png'):
opt['Model'] = sys.argv[1]
opt['seq_len'] = int(sys.argv[2])
opt['Dataset'] = sys.argv[3] + '/latest_net_G_val/images/output'
start_img = int(sys.argv[4])
gap = int(sys.argv[5])

# else:
#     opt['images'].append(sys.argv[1])

for i in range(ntrain):
    # 'data_mode/' +
    name  = opt['Dataset'] + '/img_' + str(start_img + i*gap) + '.png'
    print(name)
    opt['images'].append(name)

name = opt['Model']
continue_tr = 0
if opt['Model'] is not None:
    continue_tr = 1
    if(name.split('_')[-1] != 'normal'):
        bash('cp -r checkpoints/' + name + ' checkpoints/' + name + '_normal' )
        bash('mv checkpoints/' + name + ' checkpoints/' + name + '_mmodal' )
        opt['Model'] = name + '_mmodal' #something
    else:
        nm2 = name.split('_')
        name = '_'.join(nm2[:-1])
        bash('cp -r checkpoints/' + name + '_normal' + ' checkpoints/' + name + '_mmodal' )
        opt['Model'] = name + '_mmodal'

# for i in range(2,len(sys.argv)-1):
#     opt['images'].append(sys.argv[i])

bash("rm train_chain/train/*")
bash("rm train_chain/val/*")

# for img in opt['images']:
#     name = img.split('/')[-1]
#     bash('cp ' + img + ' train_chain/train/' + name)

name_1 = opt['images'][0].split('/')[-1]
for i in range(1, len(opt['images'])):
    name_2 = opt['images'][i].split('/')[-1]

    # Move ahead.
    im_A = cv2.imread(opt['images'][i-1])#, cv2.CV_LOAD_IMAGE_COLOR)
    im_B = cv2.imread(opt['images'][i])#, cv2.CV_LOAD_IMAGE_COLOR)
    im_AB = np.concatenate([im_A, im_B], 1)
    path_AB = 'train_chain/train/' + name_1.split('.')[0] + '_' + name_2
    cv2.imwrite(path_AB, im_AB)
    name_1 = name_2

img = opt['images'][0]
name = img.split('/')[-1]

# bash('cp ' + img + ' train_chain/val/' + name)

im = cv2.imread(img)#, cv2.CV_LOAD_IMAGE_COLOR)
im_B = np.zeros(np.shape(im))
im_AB = np.concatenate([im, im_B], 1)
path_AB = 'train_chain/val/' + name.split('.')[0] + '_' + 'black.png'
cv2.imwrite(path_AB, im_AB)
name_1 = name_2

bash('mkdir results_chain/' + opt['Model'])
bash('cp ' + img + ' results_chain/' + opt['Model'] + '/' + name.split('.')[0] + '_' + 'black_' + str(start_img) + '.png')

cmd = 'DATA_ROOT=./train_chain  name={0} lambda={1} alpha={2} which_direction={3} continue_train={4} niter={5} th train.lua'.format(\
    opt['Model'],lbda,alpha,transform, continue_tr, niter)

print(cmd)
print('# -------- Training ---------------')

bash(cmd)

# CUDA_VISIBLE_DEVICES=3
cmd = ' DATA_ROOT=./train_chain  name={0} lambda={1} alpha={2} which_direction=AtoB th test.lua'.format(opt['Model'],lbda,alpha)

ctc_img = cv2.imread('results_chain/' + opt['Model'] + '/' + name.split('.')[0] + '_' + 'black_' +str(start_img) + '.png')
prefix = '/'.join(opt['images'][0].split('/')[:-2])
ctc_gt = cv2.imread(prefix + '/target/' + 'img_' + str(gap) + '.png')
print(prefix + '/target/' + 'img_' + str(gap) + '.png')
ctc_cg = cv2.imread(prefix + '/output/' + 'img_' + str(gap) + '.png')
ctc_rgb = cv2.imread(prefix + '/input/' + 'img_' + str(gap) + '.png')

for i in range(opt['seq_len']):
    bash(cmd)
    bash('cp results/' + opt['Model'] + '/latest_net_G_val/images/output/'  + name.split('.')[0] + '_' + 'black.png' + ' ' + 'results_chain/' + opt['Model'] + '/' + name.split('.')[0] + '_' + 'black_' + str(i+1) + '.png')
    img = 'results/' + opt['Model'] + '/latest_net_G_val/images/output/' + \
        name.split('.')[0] + '_' + 'black.png'

    print(img)
    im = cv2.imread(img)#, cv2.CV_LOAD_IMAGE_COLOR)
    im_B = np.zeros(np.shape(im))
    im_AB = np.concatenate([im, im_B], 1)
    ctc_img = np.concatenate([ctc_img, im], 1)
    ig = cv2.imread(prefix + '/target/' + 'img_' + str(start_img + i*gap+gap) + '.png')
    ctc_gt = np.concatenate([ctc_gt, ig], 1)
    ig = cv2.imread(prefix + '/output/' + 'img_' + str(start_img + i*gap+gap) + '.png')
    ctc_cg = np.concatenate([ctc_cg, ig], 1)
    ig = cv2.imread(prefix + '/input/' + 'img_' + str(start_img + i*gap+gap) + '.png')
    ctc_rgb = np.concatenate([ctc_rgb, ig], 1)

    path_AB = 'train_chain/val/' + name.split('.')[0] + '_' + 'black.png'
    cv2.imwrite(path_AB, im_AB)

ctc_img = np.concatenate([ctc_img, ctc_rgb], 0)
ctc_img = np.concatenate([ctc_img, ctc_gt], 0)
ctc_img = np.concatenate([ctc_img, ctc_cg], 0)

cv2.imwrite('results_chain/' + opt['Model'] + '/' + name.split('.')[0] + '_strip.png', ctc_img)

print('# -------- Testing ---------------')

# Ending


"""
Code for self-training with weak supervision.
Author: Giannis Karamanolakis (gkaraman@cs.columbia.edu)
"""

import argparse
import json
import logging
import os
import random
import joblib
import numpy as np
import multiprocessing as mp
from functools import partial
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.linear_model import LogisticRegression
from Tokenizer import Tokenizer

class LogRegTrainer:
    # Trainer Class
    # has to implement: __init__, train, evaluate, save, load
    def __init__(self, args, logger=None):
        self.args = args
        self.logger = logger
        self.tokenizer_method = args.tokenizer_method
        self.remove_stopwords = True
        self.vocab_path = os.path.join(args.experiment_folder, "preprocessed/")
        self.tokenizer = None
        self.seed = args.seed
        self.tokenizer_obj = Tokenizer(language='english',
                                       tokenizer_method=self.tokenizer_method,
                                       remove_stopwords=self.remove_stopwords,
                                       ngram_range=(1, 1),
                                       min_freq=1,
                                       max_freq_perc=1.0)
        self.tokenizer = self.tokenizer_obj.tokenizer
        self.vectorizer = TfidfVectorizer(sublinear_tf=True, min_df=5, max_df=0.9, norm='l2',
                                          ngram_range=(1, 2), analyzer='word', tokenizer=identity_fn,
                                          preprocessor=identity_fn,
                                          token_pattern=None)
        self.model = LogisticRegression(random_state=self.seed, max_iter=int(1e6))
        self.finetune = self.train_pseudo

    def preprocess(self, texts, preprocessed_texts=None):
        """
        Pre-processes a list of texts into lists of tokenized texts
        :param texts: input list of texts
        :param preprocessed_texts: already pre-processed list of texts
        :return: tokenized texts
        """
        if preprocessed_texts is not None:
            return preprocessed_texts
        self.logger.info("tokenizing {} documents".format(len(texts)))
        with mp.Pool(processes=mp.cpu_count()) as pool:
            tokenized_texts = pool.map(partial(self.tokenizer), texts)
        return tokenized_texts

    def train(self, train_texts, train_labels, dev_texts=None, dev_labels=None, eval_fn=None,
              preprocessed_train_texts=None, preprocessed_dev_texts=None):
        logger = self.logger
        tokenized_texts = self.preprocess(train_texts, preprocessed_train_texts)
        logger.info("Fitting vectorizer on {} texts".format(len(train_texts)))
        features = self.vectorizer.fit_transform(tokenized_texts).toarray()
        logger.info("Training logistic regression: {}".format(features.shape))
        self.model.fit(features, train_labels)
        logger.info("logreg weights: {} ({})".format(self.model.coef_.shape[1] * self.model.coef_.shape[0],
                                                     self.model.coef_.shape))
        res = {}
        return res

    def train_pseudo(self, train_texts, train_labels, train_weights=None, dev_texts=None, dev_labels=None, eval_fn=None,
                     preprocessed_train_texts=None, preprocessed_dev_texts=None):
        logger = self.logger
        tokenized_texts = self.preprocess(train_texts, preprocessed_train_texts)
        logger.info("Fitting vectorizer on {} texts".format(len(train_texts)))
        features = self.vectorizer.fit_transform(tokenized_texts).toarray()
        train_labels = np.array(train_labels)
        if train_labels.ndim == 2:
            train_labels = np.argmax(train_labels, axis=-1)
        if train_weights is not None:
            train_weights = np.array(train_weights)
            logger.info("Training logistic regression: {}\nFirst Weights:{}".format(features.shape, train_weights[:10]))
        else:
            logger.info("Training logistic regression: {}\nFirst Weights: None".format(features.shape))
        self.model.fit(features, train_labels, sample_weight=train_weights)
        logger.info("logreg weights: {} ({})".format(self.model.coef_.shape[1] * self.model.coef_.shape[0],
                                                     self.model.coef_.shape))
        res = {}
        return res

    def predict(self, texts, preprocessed_texts=None, prefix=""):
        logger = self.logger
        tokenized_texts = self.preprocess(texts, preprocessed_texts)
        features = self.vectorizer.transform(tokenized_texts).toarray()
        logger.info("predicting labels: {}".format(features.shape))
        preds = self.model.predict(features)
        soft_proba = self.model.predict_proba(features)
        res = {
            'preds': preds,
            'proba': soft_proba,
            'features': features
        }
        return res

    def save(self, savefolder):
        self.logger.info("saving student at {}".format(savefolder))
        joblib.dump(self.tokenizer_obj, os.path.join(savefolder, 'tokenizer_obj.pkl'))
        joblib.dump(self.vectorizer, os.path.join(savefolder, 'vectorizer.pkl'))
        joblib.dump(self.model, os.path.join(savefolder, 'logreg.pkl'))

    def load(self, savefolder):
        self.logger.info("loading student from {}".format(savefolder))
        self.tokenizer_obj = joblib.load(os.path.join(savefolder, 'tokenizer_obj.pkl'))
        self.tokenizer = self.tokenizer_obj.tokenizer
        self.vectorizer = joblib.load(os.path.join(savefolder, 'vectorizer.pkl'))
        self.model = joblib.load(os.path.join(savefolder, 'logreg.pkl'))

def identity_fn(doc):
    return doc


from datetime import date
atual = date.today().year
totmaior = 0
totmenor = 0
for pess in range(1, 5):
    n = int(input('Em que a {}ª pessoa nasceu? '.format(pess)))
    idade = atual - n
    if idade >=18:
        totmaior += 1
    else:
        totmenor += 1
print('\n{} de maior.'.format(totmaior))
print('{} de menor.'.format(totmenor))


import itertools

def solution(orders, course):

    answer = []
    for element in course:
        dictionary = dict()
        for j in range(len(orders)):
            combinations = itertools.combinations(orders[j], element)
            for combination in combinations:
                sort_combination = list(combination)
                sort_combination.sort()
                combination = "".join(sort_combination)
                if combination not in dictionary:
                    dictionary[combination] = 0
                else:
                    dictionary[combination] +=1
        max_value = 0
        for key, value in dictionary.items():
            max_value = max(value, max_value)
        if max_value < 1:
            continue
        for key, value in dictionary.items():
            if max_value == value:
                answer.append(key)

    return sorted(answer)

def main():
    print(solution(["ABCFG", "AC", "CDE", "ACDE", "BCFG", "ACDEH"],	[2,3,4]	))

if __name__ == "__main__":
    main()


import numpy as np
import os
# Set TensorFlow logging level to 3 before loading tensorflow to suppress warnings
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf

from anonymizer.utils import Box

# Discard depreciation warnings from Tensorflow
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

class Detector:
    def __init__(self, kind, weights_path):
        self.kind = kind

        self.detection_graph = tf.Graph()
        with self.detection_graph.as_default():
            od_graph_def = tf.compat.v1.GraphDef()
            with tf.io.gfile.GFile(weights_path, 'rb') as fid:
                serialized_graph = fid.read()
                od_graph_def.ParseFromString(serialized_graph)
                tf.import_graph_def(od_graph_def, name='')

        conf = tf.compat.v1.ConfigProto()
        self.session = tf.compat.v1.Session(graph=self.detection_graph, config=conf)

    def _convert_boxes(self, num_boxes, scores, boxes, image_height, image_width, detection_threshold):
        assert detection_threshold >= 0.001, 'Threshold can not be too close to "0".'

        result_boxes = []
        for i in range(int(num_boxes)):
            score = float(scores[i])
            if score < detection_threshold:
                continue

            y_min, x_min, y_max, x_max = map(float, boxes[i].tolist())
            box = Box(y_min=y_min * image_height, x_min=x_min * image_width,
                      y_max=y_max * image_height, x_max=x_max * image_width,
                      score=score, kind=self.kind)
            result_boxes.append(box)
        return result_boxes

    def detect(self, image, detection_threshold):
        image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
        num_detections = self.detection_graph.get_tensor_by_name('num_detections:0')
        detection_scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
        detection_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')

        image_height, image_width, channels = image.shape
        assert channels == 3, 'Invalid number of channels: {}. ' \
                              'Only images with three color channels are supported.'.format(channels)

        np_images = np.array([image])
        num_boxes, scores, boxes = self.session.run(
            [num_detections, detection_scores, detection_boxes],
            feed_dict={image_tensor: np_images})

        converted_boxes = self._convert_boxes(num_boxes=num_boxes[0], scores=scores[0], boxes=boxes[0],
                                              image_height=image_height, image_width=image_width,
                                              detection_threshold=detection_threshold)
        return converted_boxes


#Paquete Numpy

import numpy

lista = [2, 4, 6, 8, 10, 12]

#vector = numpy.array(lista)

print("Lista original: ",lista)

vector+1
vector*2
lista*2
vector+vector2
vector*vector2

type(vector[1])
type(vector)


import numpy as np
import pandas as pd
import json

import time

from flask import jsonify
from markupsafe import escape

from os.path import dirname, abspath
import sys

SCRIPT_DIR = dirname(abspath(__file__))
sys.path.append(dirname(SCRIPT_DIR))

import utils.simple_utils.simple_tools as su_tools

#getting raid id to look for
def info_about_raid_id_m(
        id,
        st_db_raid_table,
        st_db_boss_table,
        st_db_loot_table,
        st_db_item_table
):
    #start timer
    s_t = time.perf_counter()

    raid_id = int(escape(id))

    #read table w/ raid info
    main_df = pd.read_parquet(
        st_db_raid_table
    )

    #looking for the specific raid id
    main_df = su_tools.find_one_row_in_DataFrame(
        main_df,
        object_to_search_for = raid_id,
        item_column = "raid_id"
    )

    #check is there such raid
    main_df_type = main_df.__class__.__name__
    if main_df_type == "NoneType" :
        return jsonify("There is no such raid")

    dict_to_send = {
        "data" :{
            "id" : int(main_df["raid_id"]),
            "name" : main_df["raid_name"],
            "raid_capacity" : int(main_df["raid_capacity"]),
            "bosses" : []
        }
    }

    #delete columns that wont use in main_df
    main_df.pop("raid_name")
    main_df.pop("raid_capacity")

    #reading table w/ bosses info
    df_for_bosses = pd.read_parquet(
        st_db_boss_table,
        columns=[
            "boss_id",
            "raid_id",
            "boss_name",
            #"npc_wowhead_id"
        ]
    )

    #add bosses of our raid
    main_df = pd.DataFrame.merge(
        main_df.to_frame().T,
        df_for_bosses,
        on="raid_id")

    main_df.pop("raid_id")

    #reading table w/ dropp info
    df_for_drop = pd.read_parquet(
        st_db_loot_table
    )
    #read items info
    df_items = pd.read_parquet(
        st_db_item_table
    )

    #for every boss get its loot
    for row in main_df["boss_id"]:
        series_row = main_df[main_df.loc[:, "boss_id"] == row]

        #writing info about boss and its loot into the dict
        add_part = {
            "id" : int(series_row.iloc[0].at["boss_id"]),
            "name" : series_row.iloc[0].at["boss_name"],
            #"npc_wowhead_id" : series_row.iloc[0].at["npc_wowhead_id"],
            "loot": []
        }

        #delete columns that wont use in df_for_cycle
        series_row.pop("boss_name")
        #series_row.pop("npc_wowhead_id")

        #getting loot_drop of sertain boss
        df_for_cycle = pd.merge(
            series_row,
            df_for_drop,
            on="boss_id"
        )

        #delete column that we dont need in df_for_cycle anymore
        df_for_cycle.pop("boss_id")

        #getting info about items for loot
        df_for_cycle = pd.merge(
            df_for_cycle,
            df_items,
            on="item_id"
        )

        df_for_cycle.rename(
            {
                "item_id": "id",
                "item_name": "name"
            },
            axis="columns",
            inplace=True
        )

        #renaming elements according to docs
        su_tools.extend_list_by_dict_from_df(
            df_for_cycle,
            add_part["loot"]
        )

        #writing boss's data into the main dict
        dict_to_send["data"]["bosses"].append(add_part)

    #end timer
    e_t = time.perf_counter()
    print(f"Time of {info_about_raid_id_m.__name__}={e_t-s_t}")

    return json.dumps(dict_to_send, indent=2)


import numpy as np
import cv2
import sys

cap = cv2.VideoCapture(0)
cascPath = sys.argv[1]

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)

while(True):

    ret, frame = cap.read() # capture frames
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Detect faces in the image
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30),
        flags = cv2.cv.CV_HAAR_SCALE_IMAGE
    )

    #print "Found {0} faces!".format(len(faces))

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # Display the resulting frame
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'): # Press q to scape of imaging
        break

cap.release()
cv2.destroyAllWindows()


import numpy as np

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

from body_model import SMPL_JOINTS
from geometry.camera import invert_camera, compose_cameras
from geometry.rotation import batch_rodrigues
from util.logger import Logger
from util.tensor import detach_all

J_BODY = len(SMPL_JOINTS) - 1  # no root

class Params(nn.Module):
    def __init__(self, batch_size):
        super().__init__()
        self.batch_size = batch_size
        self.param_names = set()

    def set_param(self, name, val, requires_grad=False):
        print("SETTING PARAM", name, val.shape)
        with torch.no_grad():
            setattr(
                self, name, nn.Parameter(val.contiguous(), requires_grad=requires_grad)
            )
        self.param_names.add(name)

    def get_param(self, name):
        if name not in self.param_names:
            raise ValueError(f"{name} not stored as opt param")
        return getattr(self, name)

    def load_dict(self, param_dict):
        for name, val in param_dict.items():
            self.set_param(name, val, requires_grad=False)

    def get_dict(self):
        return {name: self.get_param_item(name) for name in self.param_names}

    def get_vars(self, names=None):
        if names is None:
            names = self.param_names
        return {name: self.get_param(name) for name in names}

    def get_param_item(self, name):
        with torch.no_grad():
            param = self.get_param(name)
            return param.detach()

    def _set_param_grad(self, name, val: bool):
        if name not in self.param_names:
            raise ValueError(f"{name} not stored as param")
        param = getattr(self, name)
        assert isinstance(param, torch.Tensor)
        param.requires_grad = val

    def set_require_grads(self, names):
        """
        set parameters in names to True, set all others to False
        """
        for name in self.param_names:
            self._set_param_grad(name, False)

        for name in names:
            self._set_param_grad(name, True)

        Logger.log("Set parameter grads:")
        Logger.log(
            {name: getattr(self, name).requires_grad for name in self.param_names}
        )

class CameraParams(Params):
    """
    Parameter container with cameras
    """

    def set_cameras(
        self, cam_data, opt_scale=True, opt_cams=False, opt_focal=False, **kwargs
    ):
        self.opt_scale = opt_scale
        self.opt_cams = opt_cams
        self.opt_focal = opt_focal

        # (T, 3, 3), (T, 3)
        cam_R, cam_t = cam_data["cam_R"], cam_data["cam_t"]
        intrins = cam_data["intrins"]  # (T, 4)

        T = cam_R.shape[0]
        device = cam_R.device

        # assume focal length and center are same for all timesteps
        self.cam_center = intrins[:, 2:]  # (T, 2)
        cam_f = intrins[:, :2]  # (T, 2)
        if self.opt_focal:
            self.set_param("cam_f", cam_f)
        else:
            self.cam_f = cam_f

        self._cam_R = cam_R  # (T, 3, 3)
        self._cam_t = cam_t  # (T, 3)

        world_scale = torch.ones(1, 1, device=device)
        if self.opt_scale:
            if "world_scale" in kwargs:
                world_scale = kwargs["world_scale"]
            self.set_param("world_scale", world_scale)
        else:
            self.world_scale = world_scale

        if self.opt_cams:
            init_delta_R = torch.zeros(T, 3, device=device)
            init_delta_t = torch.zeros(T, 3, device=device)
            if "delta_cam_R" in kwargs:
                print("setting delta_cam_R from kwargs")
                init_delta_R = kwargs["delta_cam_R"]
            if "delta_cam_t" in kwargs:
                print("setting delta_cam_t from kwargs")
                init_delta_t = kwargs["delta_cam_t"]

            self.set_param("delta_cam_R", init_delta_R)
            self.set_param("delta_cam_t", init_delta_t)

    @property
    def intrins(self):  # (4,)
        return torch.cat([self.cam_f[0], self.cam_center[0]], dim=-1).detach().cpu()

    def get_extrinsics(self):
        """
        returns (T, 3, 3), (T, 3)
        """
        cam_R, cam_t = self._cam_R, self._cam_t
        if self.opt_cams:
            dR = batch_rodrigues(self.delta_cam_R)
            cam_R = torch.matmul(cam_R, dR)
            cam_t = cam_t + self.delta_cam_t
        return cam_R, cam_t * self.world_scale

    def get_intrinsics(self):
        """
        returns (T, 4)
        """
        return torch.cat([self.cam_f, self.cam_center], axis=-1)

    def get_cameras(self, idcs=None):
        """
        returns cam_R (B, T, 3, 3) cam_t (B, T, 3), cam_f (T, 2), cam_center (T, 2)
        """
        if idcs is None:
            idcs = np.arange(self._cam_R.shape[0])

        cam_R, cam_t = self.get_extrinsics()
        cam_R, cam_t = cam_R[None, idcs], cam_t[None, idcs]
        cam_f, cam_center = self.cam_f[idcs], self.cam_center[idcs]

        B = self.batch_size
        cam_R = cam_R.repeat(B, 1, 1, 1)
        cam_t = cam_t.repeat(B, 1, 1)
        return cam_R, cam_t, cam_f, cam_center


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

from unittest import TestCase
from util.tester import UtilTester

# https://realpython.com/blog/python/testing-third-party-apis-with-mocks/

class TestAPIIntegration(TestCase):

    def setUp(self):
        # create a tester passing the unittest self
        self.tester = UtilTester(self)

    def test_api_integration(self):
        # DO LOGIN
        self.tester.auth_login("miguel@admin.com", "miguel")

        f_table_name = "addresses_1930"

        ##################################################
        # create a layer
        ##################################################
        layer = {
            'type': 'Layer',
            'properties': {'layer_id': -1, 'f_table_name': f_table_name, 'name': 'Addresses in 1930',
                           'description': '', 'source_description': '',
                           'reference': [], 'keyword': []}
        }
        layer = self.tester.api_layer_create(layer)

        ##################################################
        # create the feature_table for the layer above
        ##################################################
        feature_table = {
            'type': 'FeatureTable',
            'f_table_name': f_table_name,
            'properties': {'start_date': 'timestamp without time zone', 'end_date': 'timestamp without time zone',
                           'address': 'text'},
            'geometry': {
                'crs': {'type': 'name', 'properties': {'name': 'EPSG:4326'}},
                'type': 'MULTIPOINT'
            }
        }

        self.tester.api_feature_table_create(feature_table)

        ##################################################
        # create the time columns for the layer above
        ##################################################
        temporal_columns = {
            'properties': {'f_table_name': f_table_name, 'start_date': '1900-01-01', 'end_date': '1920-12-31',
                           'end_date_column_name': 'end_date', 'start_date_column_name': 'start_date',
                           'start_date_mask_id': 1001, 'end_date_mask_id': 1001},
            'type': 'TemporalColumns'
        }

        self.tester.api_temporal_columns_create(temporal_columns)

        ##################################################
        # update the layer
        ##################################################
        layer["properties"]["name"] = "Some addresses"
        layer["properties"]["description"] = "Addresses"
        layer["properties"]["reference"] = [1050, 1052]
        layer["properties"]["keyword"] = [1001, 1041]
        self.tester.api_layer_update(layer)

        ##################################################
        # check if the layer, feature table and the temporal columns were modified
        ##################################################
        expected_layer = {'type': 'FeatureCollection', 'features': [layer]}
        self.tester.api_layer(expected_at_least=expected_layer, f_table_name=f_table_name)

        feature_table["properties"]["id"] = "integer"
        feature_table["properties"]["geom"] = "geometry"
        feature_table["properties"]["version"] = "integer"
        feature_table["properties"]["changeset_id"] = "integer"
        expected_feature_table = {'type': 'FeatureCollection', 'features': [feature_table]}
        self.tester.api_feature_table(expected_feature_table, f_table_name=f_table_name)

        expected_temporal_columns = {'type': 'FeatureCollection', 'features': [temporal_columns]}
        self.tester.api_temporal_columns(expected_temporal_columns, f_table_name=f_table_name)

        ##################################################
        # delete the layer
        ##################################################
        # get the id of layer to SEARCH AND REMOVE it
        layer_id = layer["properties"]["layer_id"]

        # REMOVE THE layer AFTER THE TESTS
        self.tester.api_layer_delete(layer_id)

        # it is not possible to find the layer that just deleted
        expected = {'type': 'FeatureCollection', 'features': []}
        self.tester.api_layer(expected, layer_id=layer_id)

        # DO LOGOUT AFTER THE TESTS
        self.tester.auth_logout()

# Putting the unittest main() function here is not necessary,
# because this file will be called by run_tests.py


# coding: utf-8

# In[289]:

# In[13]:

import random
import pandas as pd
import numpy as np
import numpy.random as nr
from numpy import *

# In[27]:

#データセット①
x1 = 500 #
y1 = 1000 #データ幅の指定
zz = 3000 #出力データ個数(固定)
r1 = 0 #出力データの小数点指定(整数は０)

# In[28]:

#出力モデル
a = np.random.uniform(x1, y1, zz)
a = np.round(a, r1)
a

# In[29]:

#データセット②
x2 = 10000
y2 = 30000 #データ幅の指定
r2 = 0 #出力データの小数点指定(整数は０)

# In[30]:

b = np.random.uniform(x2, y2, zz)
b = np.round(b, r2)
b

# In[31]:

#データセット③
x3 = 1000
y3 = 2000 #データ幅の指定
r3 = 0 #出力データの小数点指定(整数は０)

# In[32]:

c = np.random.uniform(x3, y3, zz)
c = np.round(c, r3)
c

# In[33]:

#データセット④
x4 = 0
y4 = 1 #データ幅の指定
r4 = 0 #出力データの小数点指定(整数は０)

# In[34]:

d = np.random.uniform(x4, y4, zz)
d = np.round(d, r4)
d

# In[35]:

#時間設定
#開始時間,freqで時間幅を設定
#リファレンス http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
dt = pd.date_range('2014-11-01 10:00', periods=zz, freq='2H30T17S')
dt

# In[36]:

#データセット⑤
wl = np.array(["パン","牛乳","お肉","お水","砂糖","お茶","野菜","菓子","果物","お米"])
wd = random.choice(wl, zz)
wd

# In[37]:

#index
index = np.arange(0,zz,1)
index

# In[40]:

#それぞれを統合
#各カラムの名前を設定
df = pd.DataFrame(
{'品物' : wd,
 '値段' : a,
 '販売数' : b})
df

# In[41]:

#CSVで出力
df.to_csv('output.csv', index=False)

# In[ ]:

# In[ ]:


import os
import re
import math

scriptPath = os.path.dirname(os.path.abspath(__file__))
inputPath = scriptPath + '/input.txt'

def findStep(offset):
  return 0 if offset == 0 else int(math.copysign(1, offset))

vents = {}
intersections = 0

with open(inputPath) as file:
  lines = file.read().splitlines()

for line in lines:
  x1, y1, x2, y2 = list(map(int, (re.findall('\d+', line))))

  xOffset = x2 - x1
  xStep = findStep(xOffset)

  yOffset = y2 - y1
  yStep = findStep(yOffset)

  distance = max(abs(xOffset), abs(yOffset))

  x = x1
  y = y1
  for _ in range(distance + 1):
    key = "{0},{1}".format(x, y)

    vents[key] = vents[key] + 1 if key in vents else 1

    if vents[key] == 2:
      intersections += 1

    x += xStep
    y += yStep

print(str(intersections) + ' vents intersect.')


import logging
import re
from superdesk.services import BaseService
from superdesk import get_resource_service
from superdesk.errors import SuperdeskApiError
from superdesk.publish.formatters import get_all_formatters
from superdesk.utils import get_random_string
from superdesk.validation import ValidationError
from io import BytesIO
from zipfile import ZipFile
from flask import current_app as app
from flask_babel import _

logger = logging.getLogger(__name__)

class ExportService(BaseService):
    def create(self, docs, **kwargs):
        doc = docs[0]
        formatter = self._validate_and_get_formatter(doc)

        validate = doc.get("validate", False)
        archive_service = get_resource_service("archive")

        unsuccessful_exports = 0
        try:
            in_memory_zip = BytesIO()
            with ZipFile(in_memory_zip, "a") as zip:
                for item_id in doc.get("item_ids"):
                    item = archive_service.find_one(req=None, _id=item_id)
                    if item:
                        try:
                            if validate:
                                self._validate_for_publish(item)

                            contents = formatter.export(item)
                            # Remove invalid filename chars (for windows OS) and create the filename
                            filename = (
                                re.sub(r'[\\/*?:"<>|]', "", item.get("slugline", ""))
                                + "_"
                                + str(item.get("unique_id"))
                                + ".txt"
                            )
                            zip.writestr(filename, contents.encode("UTF-8"))
                        except ValidationError:
                            unsuccessful_exports += 1
                    else:
                        unsuccessful_exports += 1

            url = None
            # Store the zip file on media_storage
            # only if at least one item is formatted successfully
            if unsuccessful_exports < len(doc.get("item_ids")):
                zip_id = app.media.put(
                    in_memory_zip.getvalue(),
                    filename="export_{}.zip".format(get_random_string()),
                    content_type="application/zip",
                    folder="temp",
                )
                url = app.media.url_for_download(zip_id, "application/zip")

            doc["url"] = url
            doc["failures"] = unsuccessful_exports
            return [len(docs)]
        except Exception as ex:
            raise SuperdeskApiError.badRequestError(
                _("Error creating export zip file. Try again please."), exception=ex
            )

    def _validate_for_publish(self, doc):
        """Validates the given story for publish action"""
        validate_item = {"act": "publish", "type": doc["type"], "validate": doc}
        validation_errors = get_resource_service("validate").validate(validate_item)
        if validation_errors:
            raise ValidationError(validation_errors)

    def _validate_and_get_formatter(self, doc):
        """Validates incoming request and gets the formatter to be used"""
        if doc.get("item_ids") == 0:
            raise SuperdeskApiError.badRequestError(_("No items to export."))

        formatter_name = doc.get("format_type")
        formatter = next((f for f in get_all_formatters() if type(f).__name__ == formatter_name), None)
        if not formatter:
            raise SuperdeskApiError.badRequestError(_("Formatter not found for requested format type."))

        return formatter


import numpy as np

def simulation(data, params, verbose=False):
    """
    Cema-Neige snow model

    Input:
    1. Data - pandas dataframe with correspondent timeseries:
        'Temp'- mean daily temperature (Celsium degrees)
        'Prec'- mean daily precipitation (mm/day)
    2. Params - list of model parameters:
        'CTG' - dimensionless weighting coefficient of
        the snow pack thermal state
                [0, 1]
        'Kf'  - day-degree rate of melting (mm/(day*celsius degree))
                [1, 10]
        'TT'  - temperature which separates rain and snow fraction
        of precipitation (optional)
                [-1.5, 2.5]
    Output:
    Total amount of liquid and melting precipitation daily timeseries
    (for coupling with hydrological model)
    """

    if len(params) == 3:
        CTG, Kf, TT = params
    elif len(params) == 2:
        CTG, Kf = params
        TT = -0.2
        print("TT parameter not set. Setting to default value of %s" % TT)

    # reading the data
    Temp = data['Temp']
    Prec = data['Prec']
    FraqSolidPrecip = np.where(Temp < TT, 1, 0)

    # initialization
    # constants
    # melting temperature
    Tmelt = 0
    # Threshold for solid precip
    # function for Mean Annual Solid Precipitation

    def MeanAnnualSolidPrecip(data):
        annual_vals = [data.Prec[
            data.Prec.index.year == i][data.Temp < TT].sum()
                       for i in np.unique(data.index.year)]
        return np.mean(annual_vals)

    MASP = MeanAnnualSolidPrecip(data)
    Gthreshold = 0.9*MASP
    MinSpeed = 0.1

    # model states
    G = 0
    eTG = 0
    PliqAndMelt = 0

    # ouput of snow model
    SNOWPACK = []
    PliqAndMelt = np.zeros(len(Temp))

    for t in range(len(Temp)):
        # solid and liquid precipitation accounting
        # liquid precipitation
        Pliq = (1 - FraqSolidPrecip[t]) * Prec[t]
        # solid precipitation
        Psol = FraqSolidPrecip[t] * Prec[t]
        # Snow pack volume before melt
        G = G + Psol
        # Snow pack thermal state before melt
        eTG = CTG * eTG + (1 - CTG) * Temp[t]
        # control eTG
        if eTG > 0:
            eTG = 0
        # potential melt
        if (int(eTG) == 0) & (Temp[t] > Tmelt):
            PotMelt = Kf * (Temp[t] - Tmelt)
            if PotMelt > G:
                PotMelt = G
        else:
            PotMelt = 0
        # ratio of snow pack cover (Gratio)
        if G < Gthreshold:
            Gratio = G/Gthreshold
        else:
            Gratio = 1
        # actual melt
        Melt = ((1 - MinSpeed) * Gratio + MinSpeed) * PotMelt
        # snow pack volume update
        G = G - Melt
        # Gratio update
        if G < Gthreshold:
            Gratio = G/Gthreshold
        else:
            Gratio = 1

        # Water volume to pass to the hydrological model
        PliqAndMelt[t] = Pliq + Melt
        SNOWPACK.append(G)

    if verbose:
        return PliqAndMelt, SNOWPACK
    else:
        return PliqAndMelt

def bounds():
    """
    'CTG' - dimensionless weighting coefficient of the snow pack thermal state
            [0, 1]
    'Kf'  - day-degree rate of melting (mm/(day*celsius degree))
            [1, 10]
    'TT'  - temperature which separates rain and
    snow fraction of precipitation (optional)
            [-1.5, 2.5]
    """
    bnds = ((0, 1), (1, 10), (-1.5, 2.5))
    return bnds


import sys
import math

file = open("treeout.txt", "w")
tree = {}

def split_csv_line(x):
	x = x.split(',')
	if x[-1][-1] == '\n': x[-1] = x[-1][:-1]
	return x

def calculate_entropy(idx, features, data):
	vals = set(data[features[idx]])
	entropy = 0
	for val in vals:
		idxes = [outcome for i, outcome in enumerate(data[features[-1]]) if data[features[idx]][i]==val]
		outcomes = list(set(idxes))
		bad = outcomes[0]
		good = outcomes[1] if len(outcomes)>1 else 0
		if idx!=len(features)-1:
			temp_e = (idxes.count(bad)/len(idxes))*math.log(idxes.count(bad)/len(idxes),2) if idxes.count(bad) != 0 else 0
			temp_e += (idxes.count(good)/len(idxes))*math.log(idxes.count(good)/len(idxes),2) if idxes.count(good) != 0 else 0
		else:
			temp_e = math.log(len(idxes)/len(data[features[-1]]), 2)
		entropy -= (len(idxes)/len(data[features[-1]]))*(temp_e)
	return entropy

def entropy_gain(past, curr):
	return past-curr

def make_new_split(features, idx, type, data):
	idxes = [i for i in range(len(data[idx])) if data[idx][i]==type]

	new_features = [feature for feature in features if feature!=idx]
	new_data = {}
	for feature in features:
		if feature!=idx: new_data[feature] = [data[feature][i] for i in idxes]
	return new_features, new_data

def write_to_file(val):
	val = str(val+'\n')
	file.write(val)

def make_ideal_tree(n, branch, curr, features, data):
	dE = [calculate_entropy(i, features, data) for i in range(len(features)-1)]
	next = features[dE.index(min(dE))] if max(dE)!=0.0 else ''
	if next!='' and min(dE)!=0.0:
		if n!=0:
			write_to_file(''.join('\t' for i in range(n))+'* '+curr)
			branch[curr] = {next:{}}
			branch = branch[curr]
			curr = next
			n+=1
		else:
			curr = next
		write_to_file(''.join('\t' for i in range(n))+'* '+next)
		branch[curr] = {feature:{} for feature in set(data[next])}
	elif next!='':
		write_to_file(''.join('\t' for i in range(n))+'* '+curr)
		write_to_file(''.join('\t' for i in range(n+1))+'* '+next+'?')
		branch[curr] = {next:{feature:'' for feature in data[next]}}
		for val in set(data[next]):
			write_to_file(''.join('\t' for i in range(n+2))+'* '+val+' --> '+data[features[-1]][data[next].index(val)])
			branch[curr][next][val] = data[features[-1]][data[next].index(val)]
	else:
		write_to_file(''.join('\t' for i in range(n))+'* '+curr+' --> '+data[features[-1]][0])
		branch[curr] = data[features[-1]][0]
	if min(dE) == 0.0: return
	vals = set(data[next])
	for val in vals:
		new_features, new_data = make_new_split(features, next, val, data)
		make_ideal_tree(n+1, branch[curr], val, new_features, new_data)

f = open(sys.argv[1], "r")
features = split_csv_line(f.readline())
attrs = {feature:[] for feature in features}
for line in f:
	x = split_csv_line(line)
	for i, feature in enumerate(features): attrs[feature].append(x[i])
make_ideal_tree(0, tree, '', features, attrs)
print(tree)


"""
ID: warreng1
LANG: PYTHON3
TASK: friday
"""

file = open('friday.in', 'r')
file2 = open('friday.out', 'w')

currentyear = 1900
months = {"January" : 31, "Febuary" : 28, "March" : 31, "April" : 30, \
          "May" : 31, "June" : 30, "July" : 31, "August" : 31, \
          "September" : 30, "October" : 31, "November" : 30, "December" : 31}
days = {"Monday" : 0, "Tuesday" : 0, "Wenesday" : 0, "Thursday" : 0,\
        "Friday" : 0, "Saturday" : 0, "Sunday" : 0}

for x in file:
    x = x.rstrip('\n')
    number = int(x)
monthdays = 0
day = 13
leapyear = False
yearafter = False
applyamount = 0
for x in range(number):
    if currentyear % 100 == 0:
        if currentyear % 400 == 0:
            months['Febuary'] = 29
            leapyear = True
    elif currentyear % 4 == 0:
        months['Febuary'] = 29
        leapyear = True
    for z in range(12):
        y = z+1
        day += monthdays
        day1 = day % 7
        if yearafter == True:
            day1 += 1
            day1 = day1 % 7
        if day1 == 1:
            days['Monday'] += 1
        elif day1 == 2:
            days['Tuesday'] += 1
        elif day1 == 3:
            days['Wenesday'] += 1
        elif day1 == 4:
            days['Thursday'] += 1
        elif day1 == 5:
            days['Friday'] += 1
        elif day1 == 6:
            days['Saturday'] += 1
        elif day1 == 0:
            days['Sunday'] += 1
        if y == 1:
            monthdays = months['January']
        elif y == 2:
            monthdays = months['Febuary']
        elif y == 3:
            monthdays = months['March']
        elif y == 4:
            monthdays = months['April']
        elif y == 5:
            monthdays = months['May']
        elif y == 6:
            monthdays = months['June']
        elif y == 7:
            monthdays = months['July']
        elif y == 8:
            monthdays = months['August']
        elif y == 9:
            monthdays = months['September']
        elif y == 10:
            monthdays = months['October']
        elif y == 11:
            monthdays = months['November']
        elif y == 12:
            monthdays = months['December']
    months['Febuary'] = 28
    currentyear += 1
print(days['Saturday'], days['Sunday'], days['Monday'], days['Tuesday'],\
      days['Wenesday'], days['Thursday'], days['Friday'], file=file2)
file2.close()


class Player():
    def __init__(self):
        self.name='ABCD'
        self.jersy_number=120
        self.position='Goalkeeper'

player1 = Player()
player1.name = "Ronaldo"
player1.jersy_number = 9
player1.position = "Striker"
print("Name of the Player:", player1.name)
print("Jersey Number of player:", player1.jersy_number)
print("Position of player:", player1.position)
print("===========================")
player2 = Player()
player2.name = "Neuer"
player2.jersy_number = 1
player2.position = "Goal Keeper"
print("Name of the player:", player2.name)
print("Jersey Number of player:", player2.jersy_number)
print("Position of player:", player2.position)


import tkinter as tk
import OptionMenuChain

class tt():
    def __init__(self):

        omc_dict = {'Asia': {'East':['Japan', 'China', 'Korea'], 'South':['Malaysia']},
                    'Europe': {'West':['Germany', 'France', 'Switzerland'], 'East':['Poland', 'Russia']},
                    'Africa': {'Good':[], 'Bad':[]},
                    'America': {}}
        omc_label = ['Continent', 'Region', 'Country']

        self.root = tk.Tk()

        self.app1 = OptionMenuChain.OptionMenuChain(self.root, omc_dict, omc_label, text='Country Selection 1', font='Verdana 10 bold')
        self.app2 = OptionMenuChain.OptionMenuChain(self.root, omc_dict, omc_label, text='Country Selection 2', font='Verdana 10 bold')

        self.b = tk.Button(self.root, text="OK", command=self.callback)
        self.b.pack()

        self.root.mainloop()

    def callback(self):
        print('here')
        omc_dict = {'Asia2': {'East2':['Japan', 'China', 'Korea'], 'South':['Malaysia']},
                    'Europe2': {'West2':['Germany', 'France', 'Switzerland'], 'East':['Poland', 'Russia']},
                    'Africa2': {'Good2':[], 'Bad':[]},
                    'America2': {},
                    ' ': {}}
        self.app1.change_chain_dict(omc_dict)
        xx = self.app1.get()
        print(xx)

if __name__ == '__main__':
    tt()


class Errors:
    def fruits(self,name):
        if not type(name) is str:
            raise TypeError
        else:
            print(f"{name} is a fruit ")

if __name__ == "__main__":
    e=Errors()
    e.fruits(12.4)


# Write a program which takes an array of n integers,
# where A[i] denotes the maximum you can advance from index 1,
# and retums whether it is possible to advance to the last index
# starting from the beginning of the array.
# Hint: Analyze each location, starting from the beginning.

def can_reach_end(A):

    if len(A) == 1:
        return True
    count, index = 1, -2
    while A[index] < count:
        count, index = count + 1, index - 1
        if count == len(A):
            return False
    return can_reach_end((A[:index+1]))


'''
    __file__ = 10tkpy.view.py
    __author__ = 'kyle roux'
    __date__ = '04-16-13'
    __pkg__ = '10tkpy'
'''
from Tkinter import *
import random
import sys

DIES = ('   One', '   Two', ' Three', '  Four', '   Five', '    Six',)
DIEMAP = {'   One': 1, '   Two': 2, ' Three': 3, '  Four': 4, '   Five': 5, '    Six': 6}

class LabelDemo(Frame):
    def __init__(self):
        ''' set up the window widget '''
        Frame.__init__(self)
        self.master.title('10 Tk Py')
        self.grid()
        self._label = Label(self, text="Hello World!")
        self._label.grid()

class DiceRollWidget(Frame):
    """ use DiceRollWidget to keep track of dice rolls """
    global DIES
    global DIEMAP
    _dies = DIES
    _diemap = DIEMAP

    def __init__(self):
        """ set up inital setting and windows """
        Frame.__init__(self)
        self.heldDice = [][:]
        self.heldNumber = 0
        self.dieNum = 6
        self.roll()
        self.master.title('TZP Softwares "10Tk Py"')
        self.grid()
        self.topLabel = Label(self, text="Your Roll:\n\n", font="Sans 18")
        self.topLabel.grid(row=0, column=0)
        self.set_buttons()
        self.rollButton = Button(self, text="Roll Dice", font="Sans 11", command=self.roll)
        self.rollButton.grid(row=50, column=2)
        self.reset_held()
        self.resetButton = Button(self, text="Reset", command=self.reset_held)
        self.resetButton.grid(row=100, column=2)
        self.quitButton = Button(self, text="Quit", command=sys.exit)
        self.quitButton.grid(row=100, column=0)

    def reset_roll_label(self):
        """ update the roll label """
        try:
            self.rollLabel.configure(text=self.make_roll_label_text())
        except AttributeError:
            self.rollLabel = Label(self, text=self.make_roll_label_text(), font="Times 16")
        self.rollLabel.grid(row=1, column=0, columnspan=3)

    def make_roll_label_text(self):
        """ return a string of the current roll """
        return ', '.join(map(str, self.dice))

    def set_buttons(self):
        """ seprate function to set up numbered buttons """
        self.oneHoldButton = Button(self, text="Not Held", font="Times 14", command=self.hold_one)
        self.oneHoldButton.grid(row=2, column=2)
        self.twoHoldButton = Button(self, text="Not Held", font="Times 14", command=self.hold_two)
        self.twoHoldButton.grid(row=3, column=2)
        self.threeHoldButton = Button(self, text="Not Held", font="Times 14", command=self.hold_three)
        self.threeHoldButton.grid(row=4, column=2)
        self.fourHoldButton = Button(self, text="Not Held", font="Times 14", command=self.hold_four)
        self.fourHoldButton.grid(row=5, column=2)
        self.fiveHoldButton = Button(self, text="Not Held", font="Times 14", command=self.hold_five)
        self.fiveHoldButton.grid(row=6, column=2)
        self.sixHoldButton = Button(self, text="Not Held", font="Times 14", command=self.hold_six)
        self.sixHoldButton.grid(row=7, column=2)

    def inc_held(self, number, num=1):
        """ increment the heldNumber number """
        if str(number) in self.heldDice:
            pass
        else:
            self.heldNumber += num
        self._reset_held_label()

    def hold_one(self):
        """ check if button says held or not held and switch """
        if self.oneHoldButton['text'] == "Not Held":
            self.oneHoldButton.configure(text="   Held   ")
            self.inc_held('one')
            self.heldDice.append('one')
        else:
            self.heldNumber -= 1
            self._reset_held_label()
            self.heldDice.remove('one')
            self.oneHoldButton.configure(text="Not Held")

    def hold_two(self):
        """ same as last function and next function """
        if self.twoHoldButton['text'] == "Not Held":
            self.twoHoldButton.configure(text="   Held   ")
            self.inc_held('two')
            self.heldDice.append('two')
        else:
            self.heldNumber -= 1
            self._reset_held_label()
            self.heldDice.remove('two')
            self.twoHoldButton.configure(text="Not Held")

    def hold_three(self):
        """ same as last function and next function """
        if self.threeHoldButton['text'] == "Not Held":
            self.threeHoldButton.configure(text="   Held   ")
            self.inc_held('three')
            self.heldDice.append('three')
        else:
            self.heldNumber -= 1
            self._reset_held_label()
            self.heldDice.remove('three')
            self.threeHoldButton.configure(text="Not Held")

    def hold_four(self):
        """ same as last function and next function """
        if self.fourHoldButton['text'] == 'Not Held':
            self.fourHoldButton.configure(text="   Held   ")
            self.inc_held('four')
            self.heldDice.append('four')
        else:
            self.heldNumber -= 1
            self._reset_held_label()
            self.heldDice.remove('four')
            self.fourHoldButton.configure(text="Not Held")

    def hold_five(self):
        """ same as last function and next function """
        if self.fiveHoldButton["text"] == "Not Held":
            self.fiveHoldButton.configure(text="   Held   ")
            self.inc_held('five')
            self.heldDice.append('five')
        else:
            self.heldNumber -= 1
            self._reset_held_label()
            self.heldDice.remove('five')
            self.fiveHoldButton.configure(text="Not Held")

    def hold_six(self):
        """ same as last function and next function """
        if self.sixHoldButton['text'] == 'Not Held':
            self.sixHoldButton.configure(text="   Held   ")
            self.inc_held('six')
            self.heldDice.append('six')
        else:
            self.heldNumber -= 1
            self._reset_held_label()
            self.heldDice.remove('six')
            self.sixHoldButton.configure(text="Not Held")

    def _reset_held_num(self):
        """ reset held number to 0 and reset held list """
        self.heldNumber = 0
        self.heldDice = [][:]

    def _reset_held_label(self):
        """ refresh heldLabel on screen """
        self.diceHeldLabel = Label(self, text="Dice Held: "  + str(self.heldNumber), font="Sans 11")
        self.diceHeldLabel.grid(row=50, column=0)

    def reset_held(self):
        """ reset all held stats """
        self.set_buttons()
        self._reset_held_num()
        self._reset_held_label()
        self.roll()

    def roll(self, num=None):   # define for custom die implementations
        global DIES
        if num is None:
            num = self.dieNum
        self.dice = [][:]       # copy an empty list
        self.dice = [0] * num   # make an empty list of n size
        for i in range(len(self.dice)):
            self.dice[i] = random.choice(DIES)
        self._reset_dice()

    def _reset_one(self):
        try:
            self.oneLabel.configure(text="1: \t" + self.dice[0] + ' (' + str(DiceRollWidget._diemap[self.dice[0]]) + ')')
        except AttributeError:
            self.oneLabel = Label(self, text="1: \t" + self.dice[0] + ' (' + str(DiceRollWidget._diemap[self.dice[0]]) + ')')
        self.oneLabel.grid(row=2, column=0)

    def _reset_two(self):
        try:
            self.twoLabel.configure(text="2: \t" + self.dice[1] + ' (' + str(DiceRollWidget._diemap[self.dice[1]]) + ')')
        except AttributeError:
            self.twoLabel = Label(self, text="2: \t" + self.dice[1] + ' (' + str(DiceRollWidget._diemap[self.dice[1]]) + ')')
        self.twoLabel.grid(row=3, column=0)

    def _reset_three(self):
        try:
            self.threeLabel.configure(text="3: \t" + self.dice[2] + ' (' + str(DiceRollWidget._diemap[self.dice[2]]) + ')')
        except AttributeError:
            self.threeLabel = Label(self, text="3: \t" + self.dice[2] + ' (' + str(DiceRollWidget._diemap[self.dice[2]]) + ')')
        self.threeLabel.grid(row=4, column=0)

    def _reset_four(self):
        try:
            self.fourLabel.configure(text="4: \t" + self.dice[3] + ' (' + str(DiceRollWidget._diemap[self.dice[3]]) + ')')
        except AttributeError:
            self.fourLabel = Label(self, text="4: \t" + self.dice[3] + ' (' + str(DiceRollWidget._diemap[self.dice[3]]) + ')')
        self.fourLabel.grid(row=5, column=0)

    def _reset_five(self):
        try:
            self.fiveLabel.configure(text="5: \t" + self.dice[4] + ' (' + str(DiceRollWidget._diemap[self.dice[4]]) + ')')
        except AttributeError:
            self.fiveLabel = Label(self, text="5: \t" + self.dice[4] + ' (' + str(DiceRollWidget._diemap[self.dice[4]]) + ')')
        self.fiveLabel.grid(row=6, column=0)

    def _reset_six(self):
        try:
            self.sixLabel.configure(text="6: \t" + self.dice[5] + ' (' + str(DiceRollWidget._diemap[self.dice[5]]) + ')')
        except AttributeError:
            self.sixLabel = Label(self, text="6: \t" + self.dice[5] + ' (' + str(DiceRollWidget._diemap[self.dice[5]]) + ')')
        self.sixLabel.grid(row=7, column=0)

    def _reset_dice(self):
        if 'one' in self.heldDice:
            pass
        else:
            self._reset_one()
        if 'two' in self.heldDice:
            pass
        else:
            self._reset_two()
        if 'three' in self.heldDice:
            pass
        else:
            self._reset_three()
        if 'four' in self.heldDice:
            pass
        else:
            self._reset_four()
        if 'five' in self.heldDice:
            pass
        else:
            self._reset_five()
        if 'six' in self.heldDice:
            pass
        else:
            self._reset_six()
        self.reset_roll_label()

def main():
    DiceRollWidget().mainloop()

if __name__ == "__main__":
    main()


from __future__ import unicode_literals
import json
import pygame

import pyglet
from pygame import mixer, event, init

import youtube_dl

class MyLogger(object):
    def debug(self, msg):
        pass
    def warning(self, msg):
        pass
    def error(self, msg):
        print(msg)

def my_hook(d):
    if d['status'] == 'finished':
        print('Done downloading, now converting ...')

ydl_opts = {
    'outtmpl': 'C:\\Users\\ADMIN\\Desktop\\c4t\\Sesson2\\Sesson12\\finalhack\\%(title)s.%(ext)s',
    'default_search': 'ytsearch5',
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
    'logger': MyLogger(),
    'progress_hooks': [my_hook],
}
from youtube_dl import YoutubeDL

ydl = YoutubeDL(ydl_opts)

print("Welcome to music app!")

while True:
    with open('C:\\Users\\ADMIN\\Desktop\\c4t\\Sesson2\\Sesson12\\finalhack\\database.json') as json_files:
        current_database = json.load(json_files)
    def songlist():
        if len(current_database) == 0:
            print("You don't have any song!")
        else:
            for i in range(len(current_database)):
                print(f"{i+1}. {current_database[i]['title']}")

    print("""Pick one of these options:
    1. Show all songs
    2. Show details of a song
    3. Play a song
    4. Search and download songs
    5. Exit:""")
    while True:
        selection = int(input(">>>"))
        if selection in [1,2,3,4,5]:
            break
        else:
            print('Invalid Command !!')

    if selection == 1 :
        songlist()

    elif selection == 2:
        songlist()
        song = int(input("Enter the number of the song you want to see detail: "))
        while True:
            if song in range(1, len(current_database)+1):
                break
            else:
                print("Invalid song!")
        for k, v in current_database[song-1].items():
            print(f'{k}: {v}')

    elif selection == 3:

        songlist()
        song = int(input("Which song do you want to hear? >>> "))

        mixer.init()
        mixer.music.load(f"""{current_database[song-1]['title']}.mp3""".encode('utf8'))

        mixer.music.play()

        while True:
            choose = input("Play/ Pause/ Stop ? >> ")
            if choose.upper() == "PLAY":
                mixer.music.unpause()
            elif choose.upper() == "PAUSE":
                mixer.music.pause()
            elif choose.upper() == "STOP":
                mixer.music.stop()
                break

    elif selection == 4:
        keyword = input('Enter the name of the song you want to search >>> ')
        search_result = ydl.extract_info(keyword, False)
        for i in range(5):
            print(f"""{i+1}. {search_result['entries'][i]["title"]}""")

        ask = input("Which song do you want to choose? (Enter a number or enter n to out the download!) ")
        while True:
            if ask.isdigit():
                if int(ask) in [1,2,3,4,5]:
                    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                        ydl.download([search_result['entries'][int(ask) - 1]['webpage_url']])
                    print("Your song have been downloaded")
                    new_data = {
                        'title': search_result['entries'][int(ask)-1]['title'],
                        'creator': search_result['entries'][int(ask)-1]['creator'],
                        'artist': search_result['entries'][int(ask)-1]['artist'],
                        'track': search_result['entries'][int(ask)-1]['track']
                    }
                    data = []
                    data.extend(current_database)
                    data.append(new_data)

                    with open('C:\\Users\\ADMIN\\Desktop\\c4t\\Sesson2\\Sesson12\\finalhack\\database.json', 'w') as outfile:
                        json.dump(data, outfile)
                    break
                else:
                    print("Invalid number! Enter the number again!")
            elif str(ask).upper() == "N":
                break
            else:
                print("")
                print("Invalid command !!!")

    elif selection == 5:
        print('See you later!!!')
        break


import argparse
import xarray as xr
from .grid import make_grid_SG

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Append grid-box corners to file')
    parser.add_argument('filein')
    parser.add_argument(
        '--sg_params', metavar='P', type=float, nargs=3,
        default=[1.0, 170.0, -90.0],
        help='input grid stretching parameters (stretch-factor, target longitude, target latitude)')
    args = parser.parse_args()

    ds = xr.open_dataset(args.filein)

    csgrid, csgrid_list = make_grid_SG(
        ds.dims['Ydim'],
        stretch_factor=args.sg_params[0],
        target_lon=args.sg_params[1],
        target_lat=args.sg_params[2]
    )

    ds = ds.assign_coords(
        {'corner_lons': xr.DataArray(
            csgrid['lon_b'],
            dims=['nf', 'YCdim', 'XCdim']),
         'corner_lats': xr.DataArray(
             csgrid['lat_b'],
             dims=['nf', 'YCdim', 'XCdim'])})
    ds.load()
    ds.close()
    ds.to_netcdf(args.filein)

    print(ds)


import sys
sys.path.append('../../tsakhloev/validator')
from lib import *

sys.path.append('../')
from validator.lib import *

from dataset_structure_common import dataset

def dataset_common_insert(dataset, host_id,room_type, bedrooms, country, cleaning_fee, calendar_updated, extra_people):
	conditions = [room_type_validator(room_type),bedrooms_validator(bedrooms),host_id_validator(host_id),country_validator(country),
	cleaning_fee_validator(cleaning_fee),calendar_updated_validator(calendar_updated), extra_people_validator(extra_people)]
	if all(conditions):
		dataset.update({
		    host_id:
			   {
			   "room_type":room_type,
	           "bedrooms":bedrooms,
	           "country":country,
	           "cleaning-fee": cleaning_fee,
               "calendar-updated": calendar_updated,
               "extra-people": extra_people
	            }})

dataset_common_insert(dataset,"9465817","Private room","1","United States","$35.00","yesterday", "$25.00")

print(dataset)


"""Швидке сортування"""
def sort(list):
    """Сортування алгоритмом Insertion"""
    for i in range(len(list)):
        j = i
        while (list[j] < list[j-1] and j > 0):
            """Замінити елементи з індексом j и j-1 місцями"""
            temp = list[j]
            list[j] = list[j-1]
            list[j-1] = temp
            j -= 1
    return sorted(list)

"""Пошук елементу за значенням"""
def indexOf(element, list):
    """Перебір елементів списку"""
    for i in range(len(list)):
        el = list[i]
        if (el == element):
            """Повернення індекса елементу"""
            return i
    """Якщо не знайшли, повернути -1"""
    return -1

"""5 мінімальних елементів"""
def getMinFive(list):
    """Сортування"""
    sorted = sort(list)
    fiveMin = []
    """Записуєм та повертаємо 5 мінімальних елементів"""
    for i in range(0, 5):
        fiveMin.append(sorted[i])
    return fiveMin

"""5 максимальних елементів"""
def getMaxFive(list):
    """Сортування"""
    sorted = sort(list)
    fiveMax = []
    """Записуєм та повертаємо 5 максимальних елементів"""
    for i in range(len(sorted) - 5, len(sorted)):
        fiveMax.append(sorted[i])
    return fiveMax

"""Середне арифметичне"""
def getAvg(list):
    avg = 0
    for i in range(len(list)):
        """Додаємо всі елементи"""
        avg += list[i]
    """Ділимо суму на кількість елементів та повертаємо"""
    avg /= len(list)
    return avg

"""Знаходження унікальних елементів"""
def getUnique(list):
    unique = []
    """Перебір елементів списку"""
    for i in range(len(list)):
        el = list[i]
        """Якщо поточний елемент не записували, то записуємо"""
        if not el in unique:
            unique.append(el)
    return unique

"""Знаходження кількості повторень"""
def getNotUniqueCount(list):
    unique = getUnique(list)
    uniqueLen = len(unique)
    listLen = len(list)
    """Віднімаємо кілкість унікальних елементів від усіх"""
    return listLen - uniqueLen

"""Функція для зсуву списку"""
def shiftList(list):
    length = len(list)
    shifted = [list[length - 1]]
    for i in range(length - 1):
        shifted.append(list[i])
    return shifted

"""Функція знаходження найменшого спільного дільника двох чисел"""
def getLeastComMult(a, b):
    i = min(a, b)
    while True:
        if i%a == 0 and i%b == 0:
            return i
        i += 1


# 统计文件中行数，非空行数，以及空格间隔的token数

# -*- coding: UTF-8 -*-
import json

def count_file(file):
    line_count = 0
    non_empty_line_count = 0
    token_count = 0

    with open(file, 'r') as f:
        while True:
            # 读取每行
            line = f.readline()
            if not line:
                break

            line_count += 1
            line_len = len(line)
            line_token_count = 0

            # 实现统计单行token数
            blank = False
            for char in line:
                if char in [' ', '\t', '\b']:
                    blank = True
                else:
                    if blank:
                        line_token_count += 1
                    blank = False

            token_count += line_token_count
            if line_token_count > 0:
                non_empty_line_count += 1

    return {
        'file': file,
        'line_count': line_count,
        'line_token_count': token_count,
        'non_empty_line_count': non_empty_line_count
    }

if __name__ == '__main__':
    ret = count_file('count_file.py')
    print('行数：', ret['line_count'])
    print('非空行：', ret['non_empty_line_count'])
    print('非空词数：', ret['line_token_count'])
    with open('/tmp/count.json', 'w') as f:
        f.write(json.dumps(ret, indent=2, ensure_ascii=False))


#!/usr/bin/python

#
#  Proyecto X
#  main.py
#
#  Creado el 17/08/2019
#  Mariano Andres Di Maggio <mariano.dim@gmail.com>
#
from src import lexerOriginal
from src.parser import Parser

__author__ = 'Mariano Andres Di Maggio'

import os
import sys
from builtins import print
from src.lexer import Lexer

def main():
    content = ""  # Esta variable mandendra el contenido del archivo de entrada leido
    path = os.getcwd()

    print('|-|-|-|-|-|-|-|-|-|-|-|-|-|-  Starting Compilador  |-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|- \n')
    print("Leyendo archivo...")

    # Verifico que el usuario haya ingresado el nombre del archivo como parametro
    try:
        fileName = sys.argv[1]
    except:
        print("[ERROR] Se esperaba el nombre de archivo, como parametro para iniciar procesamiento, por ejemplo: 'demo.x'")
        return

    # Chequeo si la extension del archivo es correcta
    if fileName[len(fileName) - 2:len(fileName)] != ".x":
        print("[ERROR] Extension de archivo no reconocida, asegurese que la extension del archivo sea '.x'")
        return

    # Abre el archivo de entrada (en modo lectura) y lo graba en la variable 'content'
    try:
        with open(path + "/" + fileName, "r") as sourceCodeFile:
            content = sourceCodeFile.read()
        print(content)
    except:
        print('[ERROR] No se puede encontrar el archivo "' + fileName + '"')

    # --------------------------------------
    #  LEXER
    # --------------------------------------
    print('\n|-|-|-|-|-|-|-|-|-|-|-|-|-|-  LEXER  |-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|- \n')

    # Crea una instancia nueva de la clase lexer
    # lex = lexerOriginal.Lexer(content)
    # tokens = lex.tokenize
    # print(tokens)
    lexer = Lexer().get_lexer()
    tokens = lexer.lex(content)

    # for token in tokens:
    #     print(token)

    # --------------------------------------
    #  PARSER
    # --------------------------------------
    print('\n|-|-|-|-|-|-|-|-|-|-|-|-|-|-  PARSER  -|-|-|-|-|-|-|-|-|-|-|-|-|-|-|- \n')

    # Crea una instancia nueva de la clase Parser y le pasa los Tokens generados como parametro
    # parse = parser.Parser(tokens)

    # source_ast = parse.parse()

    # print(source_ast)

    pg = Parser()
    pg.parse()
    parser = pg.get_parser()
    parser.parse(tokens).eval()

# Llamada a la funcion de arranque
main()


import pandas as pd
import matplotlib
import seaborn
from sklearn import svm

matplotlib.use('Agg')

if __name__ == "__main__":
    data = pd.read_csv(\
        './datasets/_f6284c13db83a3074c2b987f714f24f5_svm-data.csv',
        names=['target', 'A', 'B'])

    S = svm.SVC(C=100000, random_state=241, kernel='linear')
    svm_model = S.fit(data[['A', 'B']], data['target'])
#    f = open('./svm_result.txt', 'wt')
#    res = ''
#    tmp = svm_model.support_
#    tmp.sort()
#    for i in tmp:
#        res = res + str(i+1) + ','
#    res = res.strip('\n')
#    f.write(res)
#    f.close()
    with open('./svm_result.txt', 'w') as res_f:
        res = ''
        for i in svm_model.support_:
            res = res + str(i+1) + ','
        res = res.strip(',')
        res_f.write(res)

    plt = seaborn.regplot(data['A'], data['B'])
    plt.figure.savefig('./svm.png')


import logging
import serial
from Adafruit_IO import Client

logging.basicConfig(
    format=' %(levelname)s - %(asctime)s - %(message)s ', level=logging.INFO)

ser = serial.Serial('/dev/ttyUSB0')

def getPm25():
    data = []
    for index in range(0, 10):
        datum = ser.read()
        data.append(datum)
        pmtwofive = int.from_bytes(
            b''.join(data[2:4]), byteorder='little') / 10
        logging.info("PM 2.5:\t %s", pmtwofive)
    return pmtwofive

def getPm10():
    data = []
    for index in range(0, 10):
        datum = ser.read()
        data.append(datum)

        pmten = int.from_bytes(b''.join(data[4:6]), byteorder='little') / 10
        logging.info("PM 10:\t %s", pmten)

    return pmten


import logging
import time
from pathlib import Path
from typing import Iterable, Set, Tuple, Dict, Sequence

import numpy as np

from quant.datamodel import TypedSpan, get_dataset_files, DatasetType, read_annotation, read_text, collect_categories
from quant.model import SpanNERModel
from quant.utils import invert

class Solution:

    model_path = Path('onnx/main.pkl')
    exclude_filenames = {
        '165459_text', '176167_text', '178485_text', '192238_text',
        '193267_text', '193946_text', '194112_text', '2021',
        '202294_text', '2031', '209438_text', '209731_text', '546860_text'
    }

    @classmethod
    def predict(cls, texts: Sequence[str]) -> Iterable[Set[Tuple[TypedSpan]]]:
        model = SpanNERModel.load(cls.model_path)
        return model.predict(list(texts))

    @classmethod
    def evaluate(cls):
        text_files, annotation_files = get_dataset_files(Path('data'), DatasetType.TEST, exclude_filenames=cls.exclude_filenames)
        test_categories = collect_categories(annotation_files)

        ground_truth = list(map(read_annotation, annotation_files))
        texts = list(map(read_text, text_files))

        model = SpanNERModel.load(cls.model_path)
        model_predictions = list(model.predict(texts))

        print(f'Computing metrics for {test_categories} ({len(test_categories)}/{len(model.category_mapping) - 1})')

        n_categories = len(test_categories)
        category_id_mapping = dict(enumerate(test_categories))
        category_mapping = invert(category_id_mapping)

        def group_by_category(entities: Set[TypedSpan]) -> Dict[str, Set[Tuple[int, int]]]:
            groups = {cat: set() for cat in test_categories}
            for entity in entities:
                groups[entity.type].add((entity.start, entity.end))
            return groups

        true_positives = np.zeros(n_categories, dtype=int)
        false_positives = np.zeros(n_categories, dtype=int)
        false_negatives = np.zeros(n_categories, dtype=int)

        for true_entities, predicted_entities in zip(ground_truth, model_predictions):
            true_groups = group_by_category(true_entities)
            predicted_groups = group_by_category(predicted_entities)

            for category in test_categories:
                category_id = category_mapping[category]
                true_set = true_groups[category]
                predicted_set = predicted_groups[category]

                true_positives[category_id] += len(true_set.intersection(predicted_set))
                false_positives[category_id] += len(predicted_set.difference(true_set))
                false_negatives[category_id] += len(true_set.difference(predicted_set))

        category_f1 = true_positives / (true_positives + (false_positives + false_negatives) / 2)
        for category_id, f1 in enumerate(category_f1):
            category = category_id_mapping[category_id]
            print(f'{category}: {f1 * 100:.2f}%')

        f1_macro = category_f1.mean()
        print(f'macro F1: {f1_macro * 100:.2f}%')

        return f1_macro

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    start_time = time.time()
    Solution.evaluate()
    end_time = time.time()

    print(f'Test time: {end_time - start_time:.4f}s')


import discord
from discord.ext import commands
import random
import json
import asyncio
import sys

client = commands.Bot(command_prefix='!')
client.remove_command("help")

@client.event
async def on_ready():
    data = read_json("sings")
    client.sings_channel = data["SingsChannels"]
    await client.change_presence(status=discord.Status.idle)
    print("Bot Ready")

@client.event
async def on_message(message):
    member = message.author
    if message.author.bot:
        return
    msg = message.content
    if client.user.id != message.author.id:
        if any(word in msg for word in singtrigger):
            if message.channel.id in client.sings_channel:
                async with message.channel.typing():
                    await asyncio.sleep(2)
                responses = ["Lyric Response 1",
                             "Lyric Response 2",]
                await message.channel.send(f'{random.choice(responses)}')
            else:
                return

    await client.process_commands(message)

@client.command()
async def help(ctx):
    embed = discord.Embed(title="BOT COMMANDS", description="Here is my Commands", color=(2621184))
    embed.add_field(name="STANDARD COMMANDS", value="!help - This Message\n!ping - Checks my Ping\n!say - Make me say things\n!esay - Make me say things in a embed", inline=False)
    embed.add_field(name="CONFIG", value="!singtrue - Have me sing songs randomly in your current channel\n!singfalse - Make me no longer sing in your text channel", inline=False)
    embed.add_field(name="SOURCE CODE", value="https://github.com/BoomerangRosalina/DiscordSingsBot.py", inline=False)
    await ctx.send(embed=embed)

@client.command()
async def ping(ctx):
    await ctx.send(f'Pong! My Latency is {round(client.latency * 1000)}ms')

@client.command()
async def say(ctx, *, question: commands.clean_content):
    await ctx.send(f'{question}')
    await ctx.message.delete()

@client.command()
async def esay(ctx, *, question):
    embed = discord.Embed(description=f'{question}', color=(2621184))
    await ctx.send(embed=embed)
    await ctx.message.delete()

@client.command()
@commands.has_permissions(manage_guild=True)
async def singtrue(ctx):
    client.sings_channel.append(ctx.channel.id)
    data = read_json("sings")
    data["SingsChannels"].append(ctx.channel.id)
    write_json(data, "sings")
    await ctx.send("I will now randomly sing in this channel")

@singtrue.error
async def singtrue_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send('YOU REQUIRE THE MANAGE_GUILD PERMISSION TO USE THIS COMMAND')
    else:
        raise error

@client.command()
@commands.has_permissions(manage_guild=True)
async def singfalse(ctx):
    client.sings_channel.remove(ctx.channel.id)
    data = read_json("sings")
    data["SingsChannels"].remove(ctx.channel.id)
    write_json(data, "sings")
    await ctx.send("I will no longer randomly sing in this channel")

@singfalse.error
async def singfalse_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send('YOU REQUIRE THE MANAGE_GUILD PERMISSION TO USE THIS COMMAND')
    else:
        raise error

def read_json(filename):
    with open(f"./sings.json", "r") as file:
        data = json.load(file)
    return data

def write_json(data, filename):
    with open(f"./sings.json", "w") as file:
        json.dump(data, file, indent=4)

if "__main__" == __name__:
    with open("singtrigger.txt", "r") as f:
        singtrigger = f.read().splitlines()

singtrigger = ["I", "night"]

client.run("INSERTBOTTOKENHERE")


def breakRec(game, n):

    maxs = game[0]
    mins = game[0]
    hig = 0
    low = 0

    for i in range(1, n):
        if game[i] > maxs:
            maxs = game[i]
            hig = hig + 1

    for i in range(1, n):
        if game[i] < mins:
            mins = game[i]
            low = low + 1

    print('%d %d' % (hig, low))

game = []

n = int(input())
game = list(map(int, input().split()))

breakRec(game, n)

hacker_rank/easy/15. Breaking the Records.py


import numpy as np
import matplotlib.pyplot as plt
import Tools.general
from copy import deepcopy
from random import sample

class hyperParameters:
    def __init__(self):
        self.mean = np.array([])
        self.cov  = np.array([])
        self.lik  = np.array([])

def randperm(k):
    # return a random permutation of range(k)
    z = range(k)
    y = []
    ii = 0
    while z and ii < 2*k:
        n = sample(z,1)[0]
        y.append(n)
        z.remove(n)
        ii += 1
    return y

def plotter(xs,ym,ys2,x,y,axisvals=None,file=None):
    xss  = np.reshape(xs,(xs.shape[0],))
    ymm  = np.reshape(ym,(ym.shape[0],))
    ys22 = np.reshape(ys2,(ys2.shape[0],))
    plt.plot(xs, ym, 'g-', x, y, 'r+', linewidth = 3.0, markersize = 10.0)
    plt.fill_between(xss,ymm + 2.*np.sqrt(ys22), ymm - 2.*np.sqrt(ys22), facecolor=[0.,1.0,0.0,0.8],linewidths=0.0)
    plt.grid()
    if axisvals:
        plt.axis(axisvals)
    plt.xlabel('input x')
    plt.ylabel('output y')

    if file and isinstance(file,str):
        plt.savefig(file)
    plt.show()

def FITCplotter(u,xs,ym,ys2,x,y,axisvals=None,file=None):
    xss  = np.reshape(xs,(xs.shape[0],))
    ymm  = np.reshape(ym,(ym.shape[0],))
    ys22 = np.reshape(ys2,(ys2.shape[0],))
    plt.plot(xs, ym, 'g-', x, y, 'r+', linewidth = 3.0, markersize = 10.0)
    plt.fill_between(xss,ymm + 2.*np.sqrt(ys22), ymm - 2.*np.sqrt(ys22), facecolor=[0.,1.0,0.0,0.8],linewidths=0.0)
    plt.grid()
    if axisvals:
        plt.axis(axisvals)
    plt.xlabel('input x')
    plt.ylabel('output y')
    plt.plot(u,np.ones_like(u),'kx',markersize=12)
    if file and isinstance(file,str):
        plt.savefig(file)
    plt.show()

def convert_to_array(hyp):
    y = np.concatenate((np.concatenate((hyp.mean, hyp.cov),axis=0),hyp.lik),axis=0)
    return y

def convert_to_class(x,hyp):
    y = deepcopy(hyp)
    Lm = len(hyp.mean)
    Lc = len(hyp.cov)
    y.mean = x[:Lm]
    y.cov  = x[Lm:(Lm+Lc)]
    y.lik  = x[(Lm+Lc):]
    return y

def unique(x):
    # First flatten x
    y = [item for sublist in x for item in sublist]
    if isinstance(x,np.ndarray):
        n,D = x.shape
        assert(D == 1)
        y = np.array( list(set(x[:,0])) )
        y = np.reshape(y, (len(y),1))
    else:
        y = list(set(y))
    return y

def flatten(l, ltypes=(list, tuple)):
    ltype = type(l)
    l = list(l)
    i = 0
    while i < len(l):
        while isinstance(l[i], ltypes):
            if not l[i]:
                l.pop(i)
                i -= 1
                break
            else:
                l[i:i + 1] = l[i]
        i += 1
    return ltype(l)

def checkParameters(func,hyp,D):
    valt = flatten(Tools.general.feval(func))
    val = 0
    if isinstance(valt,list):
        for v in valt:
            if isinstance(v,str):
                val += eval(v)
            else:
                val += v
    else:
        val = valt
    res = (val == len(hyp))
    return res


#shubham chandra, problem 5
#Using your solution to Problem 3 and information provided in Problem 4,
#crack the following Caesar Cipher encrypted message.

#What is the key and what is the message?

#mpwtpgp jzf nly lyo jzf lcp slwqhlj espcp
#Write out your approach and any assumptions you made as a comment at the top of the file.

phrase = "mpwtpgp jzf nly lyo jzf lcp slwqhlj espcp"

#To solve, we test all possible ranges for the key between 0 and 26 adjustments. (below)

#take in previous functions from problem 3
import string

possible_letters = string.ascii_lowercase

og_key = {} #the original letter mappings created below

count = 0
for i in range(len(possible_letters)):
    count +=1
    og_key[possible_letters[i]] = count

print(og_key)

#create the new cipher key with numbers as the key
def key_adjustment(key):
    new_key = {}
    for letter in og_key:
        shifted_position = (og_key[letter] - key - 1) % 26 + 1
        new_key[letter] = possible_letters[shifted_position - 1]
    return new_key

def caesar_encrypt(key, message):
    # Use the adjusted key to encrypt the message directly
    new_key = key_adjustment(key)
    ciphered_message = ""
    for letter in message:
        if letter == " ":
            ciphered_message += " "
        elif letter.lower() in new_key:
            if letter.isupper():
                ciphered_message += new_key[letter.lower()].upper()
            else:
                ciphered_message += new_key[letter]
        else:
            ciphered_message += letter
    return ciphered_message

#print(caesar_encrypt(2,"hello   world!")) #we confirm this works

#now we decrypt, using the original function but reversing the shift

def caesar_decrypt(key, encrypted):
    return caesar_encrypt(26 - key, encrypted)

#print(caesar_decrypt(2, "fcjjm   umpjb!")) #we confirm this works

#We test all possible ranges for the key between 0 and 26 adjustments.

for i in range (0,26):
    print(caesar_decrypt(i,phrase))
    print(i)

#We find that 15 is the one that creates a readable text

print(caesar_decrypt(15,phrase))


import copy
import logging

from .preprocess import Preprocess

LOG = logging.getLogger(__name__)

class MinSize(Preprocess):
    """Convert annotations below a size to crowd annotations."""

    def __init__(self, min_side=1.0):
        self.min_side = min_side

    def __call__(self, image, anns, meta):
        anns = copy.deepcopy(anns)
        for ann in anns:
            if ann['bbox'][2] > self.min_side \
               and ann['bbox'][3] > self.min_side:
                continue
            ann['iscrowd'] = True

        return image, anns, meta


# -*- coding: utf-8 -*-
#Pregnant women1 with COVID-19, United States, January 22, 2020 - October 25, 2021
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MaxNLocator

#import csv file
df  = pd.read_csv("cases_of_covid19_among_pregnant_women_by_week_of_diagnosis_download.csv")
df1 = pd.read_csv("pregnancy_data_download.csv")
df2 = pd.read_csv("Covid-Vaccine-among-prengnant.csv")
#graph1 ********
dateDiag = df.iloc[2:92,0]
numCase  = df.iloc[2:92,1]

fig,axes = plt.subplots(1,1)

plt.bar(dateDiag, numCase)
plt.xticks(rotation=45)
axes.xaxis.set_major_locator(MaxNLocator(23))
plt.xlabel('week of Diagnosis')
plt.ylabel('Number of cases')
plt.title('Cases of COVID-19 among Pregnant Women by Week of Diagnosis*')
plt.savefig('by Week of Diagnosis.png', dpi=300, bbox_inches='tight')
plt.show()
#*****************************************
age        = df1.iloc[5:14,0]
numAgeCase = df1.iloc[5:14,1]

plt.bar(age, numAgeCase)
plt.xticks(rotation=45)
plt.xlabel('Age Group')
plt.ylabel('Number of Cases')
plt.title('Pregnant women with COVID-19 by age, United States')
plt.savefig('Pregnant women by age.png', dpi=300, bbox_inches='tight')
plt.show()
#***************************************
Race    = df1.iloc[16:21,0]
numRace = df1.iloc[16:21,1]

plt.bar(Race, numRace)
plt.xticks(rotation=45)
plt.xlabel('Race / Ethnicity')
plt.ylabel('Number of Cases')
plt.title('Pregnant women with COVID-19 by race/ethnicity, United States')
plt.savefig('By raceEthnicity', dpi=300, bbox_inches='tight')
plt.show()
#**************************************
Hospital = df1.iloc[30:33,0]
numHos   = df1.iloc[30:33,1]

plt.bar(Hospital, numHos)
plt.xlabel('Hospitalization Status')
plt.ylabel('Number of Cases')
plt.title('Pregnant women with COVID-19 by Hospitalization Status, United States')
plt.savefig('Hospitalization Status.png', dpi=300, bbox_inches='tight')
plt.show()
#***************************Vaccine in prengnancy 14 Dec 2020 - 30 Oct 2021
prior = [[0]]*34
priorAndDuring = [[0]]*34
During = [[0]]*34
dateVaccine = [[0]]*34
CDCVaccineData1 = df2.iloc[0:102]
n = 0
a = 0
b = 0
for i in range(0,102,3):
    prior[n]       = (CDCVaccineData1.iloc[i,4])
    dateVaccine[n] = CDCVaccineData1.iloc[i,0]
    n = n+1
for i in range(1,102,3):
    priorAndDuring[a] = CDCVaccineData1.iloc[i,4]
    a = a+1
for i in range(2,102,3):
    During[b] = CDCVaccineData1.iloc[i,4]
    b = b+1

prior1 = np.array(prior)
priorAndDuring1 = np.array(priorAndDuring)
During1 = np.array(During)

plt.bar(dateVaccine, prior1)
plt.bar(dateVaccine, priorAndDuring1, bottom = prior1)
plt.bar(dateVaccine, During1, bottom = prior1 + priorAndDuring1)
plt.xticks(rotation=45, fontsize = 7)
plt.xlabel('Date')
plt.ylabel('Vaccination Coverage(%)')
plt.title('Percent of Pregnant People Aged 18-49 Years \n Fully Vaccinated Covid-19,United States')
plt.legend(['Prior to Pregnancy','Prior to and During Pregnancy','During Pregnancy'])
plt.savefig('FullyVaccinatedCovid-19.png', dpi=300, bbox_inches='tight')
plt.show()
#************************************


import numpy as np  # linear algebra library
nrInputs = 300
# sigmoid function
def nonlin(x, deriv=False):
    if (deriv == True):
        return x * (1 - x)
    return 1 / (1 + (np.exp(-x)))

training = [[] for i in range(nrInputs)]
answers = [[] for i in range(nrInputs)]
with open("training.txt") as f:
    line = f.readline()
    cnt = 0
    while line and cnt < nrInputs:
        if not line.startswith(("Image", "\n", " ", "#")):
            # print(line.replace(" ", "").replace("\n", ""))
            temp = []
            for y in range(0, 20):
                for c in line.replace("\n", "").split(" "):
                    # print("Line {}: {}".format(cnt, line.strip()))
                    temp.append(int(c)/31)
                line = f.readline()
                # print("Line {}: {}".format(cnt, line.strip()))
            # print(len(temp))
            training[cnt] = temp
            cnt += 1
        line = f.readline()
with open("training-facit.txt") as f:
    line = f.readline()
    cnt = 0
    while line and cnt < nrInputs:
        if not line.startswith(("\n", " ", "#")):
            app = [0 for x in range(0, 4)]
            val = line.split(" ")[1]
            #print("Line {}: {}".format(cnt, line.strip()))
            #print("c is: " + c)
            print(val)
            app[int(val)-1] = 1
            answers[cnt] = app
            cnt += 1
        line = f.readline()
print(answers)
print(len(answers))
print(len(training))

# input dataset
# Each row is a single "training example"
# Each column corresponds to one of our input nodes
X = np.array(training)
# old values
# np.array([[0, 0, 1, 1],
#           [0, 1, 1, 0],
#           [1, 0, 1, 0],
#           [1, 1, 1, 0]])
print("shape of X: " + str(X.shape))
# output dataset
y = np.array(answers)  # = np.array([[0, 0, 1, 1]]).T

print("shape of y: " + str(y.shape))
# seed random numbers to make calculation
# deterministic (just a good practice)
np.random.seed(55)

# initialize weights randomly with mean 0
syn0 = 2*np.random.random((400, 4))-1
print("first syn0: " + str(syn0))
for iter in range(10000):

    # forward propagation
    l0 = X
    l1 = nonlin(np.dot(l0, syn0))
    #print("l1: " + str(l1))

    # how much did we miss?
    l1_error = y - l1
    #print("l1_error: " + str(l1_error))
    # multiply how much we missed by the
    # slope of the sigmoid at the values in l1
    l1_delta = l1_error * nonlin(l1, True)
    #print("l1_delta:" + str(l1_delta))
    # update weights
    syn0 += np.dot(l0.T, l1_delta)
    #print("syn0: " + str(syn0[0]))
print("Output After Training:")
#print("syn0: " + str(syn0))

for i, guess in enumerate(l1):
    print(guess)
    print(max(guess))
    print(np.log(guess))
    if str(np.log(guess).argmax(axis=0)+1) is not "1":
        print("guess " +
              str(np.unravel_index(np.argmax(np.log(guess), axis=None),
                                   np.log(guess).shape)[0]+1) + " : " + str(y[i]))
    print()


import click
from achilles.model import AchillesModel
from achilles.utils import get_dataset_dim

@click.option(
    "--gpu",
    "-g",
    metavar="",
    default=None,
    required=False,
    show_default=True,
    help="SET CUDA_VISIBLE_DEVICES to train model on specific" " GPU (e.g. 0 or 0,1)",
)
@click.option(
    "--gpus",
    metavar="",
    default=1,
    required=False,
    show_default=True,
    help="Build the model for distributed training across multiple GPUs",
)
@click.option(
    "--threads",
    "-t",
    metavar="",
    default=2,
    required=False,
    show_default=True,
    help="Feed batches into training function using multiple processes",
)
@click.option(
    "--batch_size",
    "-b",
    metavar="",
    default=200,
    required=False,
    show_default=True,
    help="Batch size for training, major determinant of RAM used on GPU",
)
@click.option(
    "--epochs",
    "-e",
    metavar="",
    default=100,
    required=False,
    show_default=True,
    help="Number of epochs to train model for",
)
@click.option(
    "--loss_function",
    "--loss",
    metavar="",
    default="binary_crossentropy",
    required=False,
    show_default=True,
    help="Compile model with loss function for training",
)
@click.option(
    "--optimizer",
    metavar="",
    default="adam",
    required=False,
    show_default=True,
    help="Compile model with optimizer for training",
)
@click.option(
    "--recurrent_dropout",
    metavar="",
    default=0.2,
    required=False,
    show_default=True,
    help="Internal dropout applied to LSTM layers",
)
@click.option(
    "--dropout",
    metavar="",
    default=0.2,
    required=False,
    show_default=True,
    help="Dropout applied to LSTM layers",
)
@click.option(
    "--bidirectional",
    metavar="",
    is_flag=True,
    required=False,
    show_default=True,
    help="Bidirectional LSTM",
)
@click.option(
    "--units",
    metavar="",
    default=200,
    required=False,
    show_default=True,
    help="Number of units per LSTMs",
)
@click.option(
    "--channels",
    metavar="",
    default=256,
    required=False,
    show_default=True,
    help="Number channels per Residual Block",
)
@click.option(
    "--lstm",
    metavar="",
    default=1,
    required=False,
    show_default=True,
    help="Number of stacked LSTMs connected to Residual Blocks",
)
@click.option(
    "--residual_block",
    metavar="",
    default=1,
    required=False,
    show_default=True,
    help="Number of stacked ResidualBlocks in initial layers",
)
@click.option(
    "--activation",
    "-a",
    metavar="",
    default="softmax",
    required=False,
    show_default=True,
    help="Activation function applied to final fully connected " "classification layer",
)
@click.option(
    "--verbose",
    "-v",
    metavar="",
    is_flag=True,
    required=False,
    show_default=True,
    help="Show training progress output and model architecture in Keras",
)
@click.option(
    "--load",
    "-l",
    metavar="",
    default="",
    required=False,
    show_default=True,
    help="Trained model weights from Keras, HDF5 to"
    " continue training, or re-train model",
)
@click.option(
    "--outdir",
    "-o",
    metavar="",
    default="training_model",
    required=True,
    show_default=True,
    help="Output directory",
)
@click.option(
    "--run_id",
    "-i",
    metavar="",
    default="model",
    required=True,
    show_default=True,
    help="Training run ID",
)
@click.option(
    "--file",
    "-f",
    metavar="",
    default=None,
    required=True,
    show_default=True,
    help="Input training / validation HDF5 dataset",
)
@click.command()
def train(
    file,
    run_id,
    outdir,
    load,
    verbose,
    activation,
    residual_block,
    lstm,
    channels,
    units,
    bidirectional,
    dropout,
    optimizer,
    loss_function,
    epochs,
    batch_size,
    threads,
    gpus,
    gpu,
):
    """Train neural network classifiers in Achilles"""

    achilles = AchillesModel(data_file=file)

    window_size = get_dataset_dim(file)[2]  # 4D tensors

    if load:
        achilles.load_model(load)
    else:
        achilles.build(
            window_size=window_size,
            activation=activation,
            gpus=gpus,
            nb_residual_block=residual_block,
            nb_channels=channels,
            nb_rnn=lstm,
            rnn_units=units,
            dropout=dropout,
            bidirectional=bidirectional,
        )

        # Compile model with loss function and optimizer
        achilles.compile(optimizer=optimizer, loss=loss_function)

    achilles.train(
        epochs=epochs,
        batch_size=batch_size,
        workers=threads,
        run_id=run_id,
        outdir=outdir,
        verbose=verbose,
        gpu=gpu,
    )