# -*- coding: utf-8 -*-

"""
	Venom
"""

import threading

from resources.lib.modules import control
from resources.lib.modules import log_utils
from resources.lib.modules import trakt

# check on adding while loop here with xbmc.Monitor().abortRequested() vs. inside the service function
control.execute('RunPlugin(plugin://%s)' % control.get_plugin_url({'action': 'service'}))

traktCredentials = trakt.getTraktCredentialsInfo()

try:
	AddonVersion = control.addon('plugin.video.venom').getAddonInfo('version')
	RepoVersion = control.addon('repository.venom').getAddonInfo('version')
	log_utils.log('###################   Venom   ##################', log_utils.LOGNOTICE)
	log_utils.log('#####   CURRENT Venom VERSIONS REPORT   #####', log_utils.LOGNOTICE)
	log_utils.log('########   Venom PLUGIN VERSION: %s   ########' % str(AddonVersion), log_utils.LOGNOTICE)
	log_utils.log('#####   Venom REPOSITORY VERSION: %s   #######' % str(RepoVersion), log_utils.LOGNOTICE)
	log_utils.log('############################################', log_utils.LOGNOTICE)

except:
	log_utils.log('############################# Venom ############################', log_utils.LOGNOTICE)
	log_utils.log('################# CURRENT Venom VERSIONS REPORT ################', log_utils.LOGNOTICE)
	log_utils.log('# ERROR GETTING Venom VERSION - Missing Repo of failed Install #', log_utils.LOGNOTICE)
	log_utils.log('################################################################', log_utils.LOGNOTICE)

def syncTraktLibrary():
	control.execute('RunPlugin(plugin://%s)' % 'plugin.video.venom/?action=tvshowsToLibrarySilent&url=traktcollection')
	control.execute('RunPlugin(plugin://%s)' % 'plugin.video.venom/?action=moviesToLibrarySilent&url=traktcollection')

def syncTraktWatched():
	control.execute('RunPlugin(plugin://%s)' % 'plugin.video.venom/?action=cachesyncTVShows')
	control.execute('RunPlugin(plugin://%s)' % 'plugin.video.venom/?action=cachesyncMovies')
	# if control.setting('trakt.general.notifications') == 'true':
		# control.notification(title = 'default', message = 'Trakt Watched Status Sync Complete', icon='default', time=1, sound=False)

def check_for_addon_update():
	try:
		if control.setting('general.checkAddonUpdates') == 'false':
			return
		import re
		import requests
		repo_xml = requests.get('https://raw.githubusercontent.com/123Venom/zips/master/addons.xml')
		if not repo_xml.status_code == 200:
			log_utils.log('Could not connect to repo XML, status: %s' % repo_xml.status_code, log_utils.LOGNOTICE)
			return
		repo_version = re.findall(r'<addon id=\"plugin.video.venom\" version=\"(\d*.\d*.\d*)\"', repo_xml.text)[0]
		local_version = control.getVenomVersion()

		if control.check_version_numbers(local_version, repo_version):
			while control.condVisibility('Library.IsScanningVideo'):
				control.sleep(10000)
			log_utils.log('A newer version of Venom is available. Installed Version: v%s, Repo Version: v%s' % (local_version, repo_version), log_utils.LOGNOTICE)
			control.notification(title = 'default', message = control.lang(35523) % repo_version, icon = 'default', time=5000, sound=False)
	except:
		pass

if traktCredentials is True:
	syncTraktWatched()

if control.setting('autoTraktOnStart') == 'true':
	syncTraktLibrary()

if control.setting('general.checkAddonUpdates') == 'true':
	check_for_addon_update()

if int(control.setting('schedTraktTime')) > 0:
	log_utils.log('###############################################################', log_utils.LOGNOTICE)
	log_utils.log('#################### STARTING TRAKT SCHEDULING ################', log_utils.LOGNOTICE)
	log_utils.log('#################### SCHEDULED TIME FRAME '+ control.setting('schedTraktTime')  + ' HOURS ###############', log_utils.LOGNOTICE)
	timeout = 3600 * int(control.setting('schedTraktTime'))
	schedTrakt = threading.Timer(timeout, syncTraktLibrary)
	schedTrakt.start()


import scipy
import numpy as np

def _cdf_with_replacement(i,n,N):
    return (i/N)**n

def _compute_variance(N, cur_data, expected_max_cond_n, pdfs):
    """
    this computes the standard error of the max.
    this is what the std dev of the bootstrap estimates of the mean of the max converges to, as
    is stated in the last sentence of the summary on page 10 of
    http://www.stat.cmu.edu/~larry/=stat705/Lecture13.pdf
    """
    variance_of_max_cond_n = []
    for n in range(N):
        # for a given n, estimate variance with \sum(p(x) * (x-mu)^2), where mu is \sum(p(x) * x).
        cur_var = 0
        for i in range(N):
            cur_var += (cur_data[i] - expected_max_cond_n[n])**2 * pdfs[n][i]
        cur_var = np.sqrt(cur_var)
        variance_of_max_cond_n.append(cur_var)
    return variance_of_max_cond_n

# this implementation assumes sampling with replacement for computing the empirical cdf
def samplemax(validation_performance):
    validation_performance = list(validation_performance)
    validation_performance.sort()
    N = len(validation_performance)
    pdfs = []
    for n in range(1,N+1):
        # the CDF of the max
        F_Y_of_y = []
        for i in range(1,N+1):
            F_Y_of_y.append(_cdf_with_replacement(i,n,N))

        f_Y_of_y = []
        cur_cdf_val = 0
        for i in range(len(F_Y_of_y)):
            f_Y_of_y.append(F_Y_of_y[i] - cur_cdf_val)
            cur_cdf_val = F_Y_of_y[i]

        pdfs.append(f_Y_of_y)

    expected_max_cond_n = []
    for n in range(N):
        # for a given n, estimate expected value with \sum(x * p(x)), where p(x) is prob x is max.
        cur_expected = 0
        for i in range(N):
            cur_expected += validation_performance[i] * pdfs[n][i]
        expected_max_cond_n.append(cur_expected)

    var_of_max_cond_n = _compute_variance(N, validation_performance, expected_max_cond_n, pdfs)

    return {"mean":expected_max_cond_n, "var":var_of_max_cond_n, "max": np.max(validation_performance),
            "min":np.min(validation_performance)}

if __name__ == "__main__":
    example_valid_perf = np.random.uniform(0,1, 20)
    print(samplemax(example_valid_perf))


#!/usr/bin/env python2
import MDAnalysis
import numpy as np
from numpy.linalg import norm

u = MDAnalysis.Universe('../../ionized.psf', '../output-dcd/NPT-250-pf10ps.dcd')
#print(u)
#print(list(u.atoms[:100].residues))

sel_prot = u.select_atoms("protein and backbone")
sel_memb = u.select_atoms("segid L.* and prop z > 0.0")

dist = []
f = open("separation.dat","w")
for ts in u.trajectory:
    print("Frame: %5d, Time: %8.3f ps" % (ts.frame, u.trajectory.time))
    A = sel_prot.center_of_mass()
    B = sel_memb.center_of_mass()
    dummy = A - B
    dist.append((u.trajectory.time, norm(dummy)))
    f.write(str(ts.frame) + " " + str(norm(dummy)) + "\n")
f.close()
print(dist)


class Solution(object):
    def findMaximizedCapital(self, k, W, Profits, Capital):
        """
        :type k: int
        :type W: int
        :type Profits: List[int]
        :type Capital: List[int]
        :rtype: int
        """
        pairs = []
        for i in range(len(Profits)):
            pairs.append((Capital[i], -Profits[i]))
        pairs.sort()
        heap = []
        cap = W
        i = 0
        while k > 0:
            while i < len(pairs) and pairs[i][0] <= cap:
                heapq.heappush(heap, (pairs[i][1], pairs[i][0]))
                i += 1
            if len(heap) == 0:  break
            project = heapq.heappop(heap)
            cap -= project[0]
            k -= 1
        return cap


import random

selected = None
winplan = random.choice(['가위','바위','보'])
print('winplan = ',winplan)
while selected != winplan:
    selected = input('가위, 바위, 보 중에서 선택하세요 : ')

    if selected not in ['가위','바위', '보']:
        print('잘못된 값을 입력하였습니다.\n')
    elif selected == winplan:
        break
    else:
        print('패배하였습니다.\n')

print('승리하셨습니다.')


from dataclasses import dataclass, field
from typing import Optional
from ojp.extension_type import ExtensionType
from ojp.mobility_enum import MobilityEnum

__NAMESPACE__ = "http://datex2.eu/schema/2_0RC1/2_0"

@dataclass
class Mobility:
    mobility_type: Optional[MobilityEnum] = field(
        default=None,
        metadata={
            "name": "mobilityType",
            "type": "Element",
            "namespace": "http://datex2.eu/schema/2_0RC1/2_0",
            "required": True,
        }
    )
    mobility_extension: Optional[ExtensionType] = field(
        default=None,
        metadata={
            "name": "mobilityExtension",
            "type": "Element",
            "namespace": "http://datex2.eu/schema/2_0RC1/2_0",
        }
    )


"""
    监控模型、资料的程式，通常是排程执行，或者资料流入执行。
    云端服务常见 composer, cloud function 触发.py档案执行。
    以此次范例来说，可以用 serving server 去纪录资料笔数，
    当累积达一定再呼叫此 server 之API来计算。

    ---

    以公司来说，可能是呼叫 BQ API 来做运算。

    以云端服务来说，是 cloud function / Google App Engine / Composer 的替代。
"""
import numpy as np
import requests
from joblib import load, dump
from flask import Flask, request, jsonify
from module.db import get_json
from module.monitoring import notify, get_model_performance, get_monotoring_data
from module.monitoring import check_model_performance
from module.model_training import retrain
from module.model_evaluation import is_evaluation

# app
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False     # 解决json中文问题

# config
config = get_json('./data/config.json')
model_name = './models/2022-11-29-11_29_08_483980rf.joblib'
model = load(model_name)

@app.route('/monitoring/cancer/', methods=['GET'])
def monitoring_cancer():
    """
        提供一个 monitoring 的 API，serving server 会呼叫此API，进行效能、资料监控。

        1. serving server 呼叫此 API，
        2. 此 server 计算目前模型的效能，
        3. 若异常呼叫retraining，若正常则不做事情。
    """
    global model
    x, y = get_monotoring_data(config['db_name_monitoring'], config['db_query_monitoring'], config['table_name_monitoring'])
    print(x.shape, y.shape)
    acc = get_model_performance(model, x, y)
    is_monitor = check_model_performance(acc, config['monitoring_threshold'])

    if is_monitor:
        message = '\n模型效能不佳，呼叫重新训练 API'
        notify('line-notify', config['line-notify'], message)
        url = config['retraining_url']
        resp = requests.get(url)
        return jsonify({'state': f'模型效能异常: {acc}，以触发重新训练。'})
    else:
        message = '\n'
        notify('line-notify', config['line-notify'], message)
        return jsonify({'state': f'模型效能正常: {acc}，不须处理。'})

if __name__ == '__main__':
    app.run(debug=False, port=8002)


#Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-os
# (com idade) em um dicionário, se por acaso a CTPS for diferente de ZERO, o dicionário receberá
# também o ano de contratação e o salário. Calcule e acrescente, além da idade, com quantos anos a
# pessoa vai se aposentar.

import datetime
trab = {}
trab['nome'] = str(input('Nome: '))
ano = int(input('Ano de nascimento: '))
trab['idade'] = datetime.date.today().year - ano
trab['ctps'] = int(input('Carteira de Trabalho (0 não tem): '))
if trab['ctps']!= 0:
    trab['contratação'] = int(input('Ano de contratação: '))
    trab['salário'] = float(input('Salário: '))
    trab['aposentadoria'] = trab['contratação'] - ano + 35

for k, v in trab.items():
    print(f'{k} tem o valor {v}')


import torch.nn as nn
import torch.nn.functional as F
import torch
from unet_block import *

def weights_init_normal(m):
    classname = m.__class__.__name__
    if classname.find('Conv') != -1:
        torch.nn.init.normal_(m.weight.data, 0.0, 0.02)
    elif classname.find('BatchNorm2d') != -1:
        torch.nn.init.normal_(m.weight.data, 1.0, 0.02)
        torch.nn.init.constant_(m.bias.data, 0.0)

# build U-Net using blocks
class GeneratorUNet(nn.Module):
    def __init__(self, in_channels=3, out_channels=3):
        super(GeneratorUNet, self).__init__()

        self.downsample1 = UNetDown(in_channels, 64, normalize=False)
        self.downsample2 = UNetDown(64, 128)
        self.downsample3 = UNetDown(128, 256)
        self.downsample4 = UNetDown(256, 512)
        self.downsample5 = UNetDown(512, 512)
        self.downsample6 = UNetDown(512, 512)
        self.downsample7 = UNetDown(512, 512)
        self.downsample8 = UNetDown(512, 512, normalize=False)

        self.upsample1 = UNetUp(512, 512, dropout=0.5)
        self.upsample2 = UNetUp(1024, 512, dropout=0.5)
        self.upsample3 = UNetUp(1024, 512, dropout=0.5)
        self.upsample4 = UNetUp(1024, 512, dropout=0.5)
        self.upsample5 = UNetUp(1024, 256)
        self.upsample6 = UNetUp(512, 128)
        self.upsample7 = UNetUp(256, 64)

        self.final = nn.Sequential(
            nn.Upsample(scale_factor=2),
            # nn.UpsamplingBilinear2d(scale_factor=2),
            nn.ZeroPad2d((1, 0, 1, 0)),
            nn.Conv2d(128, out_channels, 4, padding=1),
            nn.Tanh()
        )

    def forward(self, x):
        down1 = self.downsample1(x)
        down2 = self.downsample2(down1)
        down3 = self.downsample3(down2)
        down4 = self.downsample4(down3)
        down5 = self.downsample5(down4)
        down6 = self.downsample6(down5)
        down7 = self.downsample7(down6)
        down8 = self.downsample8(down7)
        up1 = self.upsample1(down8, down7)
        up2 = self.upsample2(up1, down6)
        up3 = self.upsample3(up2, down5)
        up4 = self.upsample4(up3, down4)
        up5 = self.upsample5(up4, down3)
        up6 = self.upsample6(up5, down2)
        up7 = self.upsample7(up6, down1)

        return self.final(up7)

#Discriminator

class Discriminator(nn.Module):
    def __init__(self, in_channels=3):
        super(Discriminator, self).__init__()

        def discriminator_block(in_filters, out_filters, normalization=True):
            """Returns downsampling layers of each discriminator block"""
            layers = [nn.Conv2d(in_filters, out_filters, 4, stride=2, padding=1)]
            if normalization:
                layers.append(nn.InstanceNorm2d(out_filters))
            layers.append(nn.LeakyReLU(0.2, inplace=True))
            return layers

        self.model = nn.Sequential(
            *discriminator_block(in_channels*2, 64, normalization=False),
            *discriminator_block(64, 128),
            *discriminator_block(128, 256),
            *discriminator_block(256, 512),
            nn.ZeroPad2d((1, 0, 1, 0)),
            nn.Conv2d(512, 1, 4, padding=1, bias=False)
        )

    def forward(self, img_A, img_B):
        img_input = torch.cat((img_A, img_B), 1)
        return self.model(img_input)


# -*- coding: utf-8 -*-

if __name__ == '__main__':

    import argparse
    import os
    import unittest
    import sys

    import system_tests

    parser = argparse.ArgumentParser(description="The system test suite")

    parser.add_argument(
        "--config_file",
        type=str,
        nargs=1,
        help="Path to the suite's configuration file",
        default=['suite.conf']
    )
    parser.add_argument(
        "--verbose", "-v",
        action='count',
        help="verbosity level",
        default=1
    )
    parser.add_argument(
        "--debug",
        help="enable debugging output",
        action='store_true'
    )

    parser.add_argument(
        "dir",
        help="directory where the test are searched for (defaults to the config"
        "file's location)",
        default=None,
        type=str,
        nargs='?'
    )

    args = parser.parse_args()
    conf_file = args.config_file[0]
    discovery_root = os.path.dirname(conf_file if args.dir is None else args.dir)
    system_tests.set_debug_mode(args.debug)

    system_tests.configure_suite(conf_file)

    discovered_tests = unittest.TestLoader().discover(discovery_root)
    test_res = unittest.runner.TextTestRunner(verbosity=args.verbose)\
                              .run(discovered_tests)

    sys.exit(0 if len(test_res.failures) + len(test_res.errors) == 0 else 1)


import numpy as np

class HopfieldNet:

    # Hopfield (1982)
    # Simple implementation of an Hopfield Network

    def __init__(self, neurons=5):
        self.neurons = np.ones(neurons, dtype="int8") # {-1,1} states
        self.T = np.zeros((neurons, neurons)) # weights matrix
        self.U = np.zeros(neurons) # neurons thresholds
        self.I = np.identity(neurons) # identity matrix

    #set neuron value at given index
    # value must be {-1,1}
    def set_neuron(self, index, value):
        if value not in [1,-1]:
            raise RuntimeError(f'Invalid value for a neuron: {value}.')
        self.neurons[index] = value

    # set weights matrix from input
    # matrix must be symmetric
    def set_weights(self, matrix):
        matrix = np.array(matrix)
        if matrix.shape != self.T.shape:
            raise RuntimeError('Incompatible shape for weights matrix.')
        if not np.all(np.abs(matrix - matrix.T) < 1e-8):
            raise RuntimeError('Weights matrix is not symmetric.')
        self.T = matrix

    # stores binary patterns inside the network
    # overwrites previous matrix
    def store_sequences(self, sequences):
        tmp_matrix = np.zeros(self.T.shape)
        for s in sequences:
            s = np.array([s])
            tmp_matrix += np.outer(s, s) - self.I
        self.T = tmp_matrix / len(sequences)

    # update neurons states until stable point is reached
    # negative weights -> neurons diverge to opposite values
    # positive weights -> neurons converge to same values
    def update_state(self, verbose=False):
        cycle, stable = 1, False
        while not stable:
            print(f'update cycle: {cycle}') if verbose else None
            cycle, stable = cycle + 1, True
            for i in range(self.U.shape[0]):
                if np.dot(self.T[i,:], self.neurons) >= self.U[i]:
                    if self.neurons[i] < 0:
                        self.neurons[i] = 1
                        stable = False
                else:
                    if self.neurons[i] > 0:
                        self.neurons[i] = -1
                        stable = False

    # return current state of neurons
    def instantaneous_state(self):
        return self.neurons

    # global energy of the net
    def energy(self):
        inter = 0.5 * self.neurons[:,None] * self.T * self.neurons
        intra = self.U[:,None] * self.neurons
        return - inter.sum() - intra.sum()

    # test function to evaluate error rate
    # paper suggests no more than 0.15*nodes patterns
    def test(self, store_seq=20, tot_seq=2**20):
        n = self.neurons.shape[0]
        store = n
        tot = 2**n
        store = store_seq if store > store_seq else store
        tot = tot_seq if tot > tot_seq else tot

        seq = [[-1 if x == '0' else 1 for x in f'{i:0{n}b}'] for i in range(tot)]
        seq = np.array(seq)
        pat = [tuple(x) for x in seq[np.random.randint(0, tot, size=store)]]
        self.store_sequences(pat)

        E = []
        for s in seq:
            for idx, val in enumerate(s):
                self.set_neuron(idx, val)
            E.append(self.energy())

        seq = [(x,y) for x,y in zip(seq, E)]
        seq = sorted(seq, key=lambda t:t[1])

        res = []
        for i,(s,e) in enumerate(seq):
            if tuple(s) in pat:
                res.append(i)

        print(f'Higher energy pattern at position {max(res)} out of {tot}')

if __name__ == '__main__':

    hnet = HopfieldNet(10)
    hnet.test(store_seq=2)


from collections import deque

N = int(input())
queue = deque()
for _ in range(N):
    row = input().split()
    if len(row) > 1:
        q, name = row
        queue.append(name)
    else:
        q = int(row[0])
        if q == 2:
            print(queue[0])
        else:
            queue.popleft()


from src.domain.models.players import Player
from src.infrastructure.repository import PostgresPlayerRepository

def test_in_memory_repository(engine):
    """Test player repository using a in memory engine."""

    player1 = Player("1", "test")
    player2 = Player("2", "test")

    repo = PostgresPlayerRepository(engine)

    # adding player1 to repository
    repo.add(player1)
    fetched_player = repo.get_by_name(player1.name)
    assert len(fetched_player) == 1

    # adding player2 to repository
    repo.add(player2)
    fetched_player = repo.get_by_name(player2.name)
    assert len(fetched_player) == 2

    # retrieving player by its id
    fetched_player = repo.get_by_id(player1.id)
    assert fetched_player.id == player1.id


from django.db import models
from django import forms
from .models import models

FAIXA_SALARIAL_CHOICE = (
    (('faixa1', 'R$1.000')),
    (('faixa2','R$1.000 a R$2.000')),
    (('faixa3','R$2.000 a R$3.000')),
    (('faixa4','Acima de R$3.000')),
    )

NIVEL_ESCOLAR_CHOICE = (
    (('faixa5', 'Ensino fundamental')),
    (('faixa6', 'Ensino médio')),
    (('faixa7', 'Tecnólogo')),
    (('faixa8', 'Ensino Superior')),
    (('faixa9', 'Pós/MBA/Mestrado')),
    (('faixa10', 'Doutorado')),
    )

class vagaDeEmprego(models.Model):
    nameJob = models.CharField(max_length=200)
    cbFaixaSalarial = models.CharField(max_length=25, choices=FAIXA_SALARIAL_CHOICE)
    cbEscolaridade = models.CharField(max_length=25, choices=NIVEL_ESCOLAR_CHOICE)


"""def getsum(a,b):
    print("Sum:",a+b)

#getsum(34,56)

x=int(input("Enter vaue of X:"))
y=int(input("Enter value of Y:"))
getsum(x,y)"""

# -----------------------------------------

def getdata(id,name,sub):
    print("Student ID:",id)
    print("Student Name:",name)
    print("Student Subject:",sub)

#getdata(101,'Nirav','Python')

stid=input("Enter ID:")
stnm=input("Enter Name:")
stsub=input("Enter Subject:")

getdata(stid,stnm,stsub)


import pytest
import pytest_mock
import requests_mock
from mock import MagicMock
import os
from visualize_data import graphics, x_axis_coordinates, y_axis_coordinates
import numpy as np
import bokeh
import requests

mock = MagicMock()

xaxis = mock.__iter__.return_value = range(100)
yaxis = mock.__iter__.return_value = range(100)

my_graphics = graphics.line(
                            xaxis,
                            yaxis,
                            color = 'red',
                            legend_label = 'test_label'
                            )

def test_output_file_has_been_created():
    assert os.path.isfile('data.html')

def test_graphiccs_xaxis_label_must_be_date():
    assert graphics.xaxis.axis_label == 'Date'

def test_graphics_yaxis_label_must_be_price_usd():
    assert graphics.yaxis.axis_label == 'Price (in USD)'

def test_any_element_in_x_axis_coordinates_is_type_datetime64():
    assert type(x_axis_coordinates[0]) == np.datetime64
    assert type(x_axis_coordinates[5]) == np.datetime64
    assert type(x_axis_coordinates[13]) == np.datetime64
    assert type(x_axis_coordinates[25]) == np.datetime64

def test_any_element_in_x_axis_coordinates_is_type_date():
    assert type(y_axis_coordinates[0]) == float
    assert type(y_axis_coordinates[5]) == float
    assert type(y_axis_coordinates[13]) == float
    assert type(y_axis_coordinates[25]) == float

def test_type_generated_graphics_instance():
    assert type(my_graphics) == bokeh.models.renderers.GlyphRenderer

def test_legend_location():
    assert graphics.legend.location == 'top_left'

def test_correct_HTML_response(requests_mock):
    requests_mock.get("http://your/custom/file/path", text="data")
    response = requests.get("http://your/custom/file/path")

    assert response.text == "data"


from mana.feeder import NetworkFeeder
from mana.handler import DetectionHandler
from mana.method import load_methods_json

def on_spoofing_attack(device_id, spoofing_indicator, method, state):
    print("Spoofing attack detected on {} at {}!".format(device_id, state.update_time))
    print("Method: {}".format(method))
    print("Spoofing indicator value: {}".format(spoofing_indicator))
    print("Last parsed sentence: {}".format(state.last_nmea_sentence))

device_ids, method_classes, method_options = load_methods_json("methods.json")

handler = DetectionHandler(device_ids=device_ids, method_classes=method_classes,
                           method_options=method_options, on_spoofing_attack=on_spoofing_attack,
                           detection_threshold=0.1)
feeder = NetworkFeeder(handler)
feeder.run()


# -*- coding: utf-8 -*-
import importlib
import os

import sys

from gos.exceptions import GOSIOException

class Loader(object):
    @staticmethod
    def import_custom_python_file(file_path):
        if not os.path.exists(file_path):
            raise GOSIOException("Specified file does not exists")
        if os.path.isdir(file_path):
            raise GOSIOException("Specified path corresponds to a directory, not a file")
        module_path, file_name = os.path.split(file_path)
        if not file_name.endswith((".py", ".pyc")):
            raise GOSIOException("Specified path does not correspond to python file ")
        if module_path not in sys.path:
            sys.path.insert(0, module_path)
        module_name = file_name[:file_name.rfind(".")]
        module = importlib.import_module(module_name)
        objects = [getattr(module, attr_name) for attr_name in dir(module)]
        return file_name, module_path, objects


from Bayes_Optimization.bayes_optim import Bayesian_Opt
import numpy as np
import pandas as pd
from Plots_and_error.results import evaluate

def main_passenger_dummy():
    name_dataset = 'dummy'  # Which dataset is
    mode_dataset = 'diff'  # We obtain the dataset in acumulated version, we modeled his acum. temporal series without tendency and obtain the acum. prediction
    method_trend = 'polynomic'  # Which method of fitting the trend: polynomic, logistic, gompertz
    predict_intervals = False
    log_transform = True
    parameters_trend = 1
    data = pd.read_csv("AirPassengers.csv", parse_dates=['Month'], index_col='Month', header=0)
    print(data.shape[0])

    TEST_SIZE = 24

    data_train, data_test = data.iloc[:-TEST_SIZE], data.iloc[-TEST_SIZE:]
    x_train = np.array(range(data_train.shape[0]))
    x_test = np.array(range(data_train.shape[0], data.shape[0]))

    x_train_features = np.hstack((x_train.reshape(-1,1), np.array(list(range(12)) * 10).reshape(-1,1)))
    x_test_features = np.hstack((x_test.reshape(-1,1), np.array(list(range(12)) * 2).reshape(-1,1)))

    model = Bayesian_Opt(x_train_features,
                         data_train,
                         n_sample_subset=30,  # Need to be multiple of the season_length
                         model_choose='SARIMA',
                         predict_intervals=predict_intervals,
                         loss_function=0,  # This is the loss function for the obj function of bayesian optimization
                         log_transform=log_transform,
                         fit_trend_method=method_trend,
                         parameters_trend=parameters_trend,
                         mode_dataset=mode_dataset,
                         timesplitmethod=0,
                         percentage_validation=0.2,
                         overlap=0.3)
    param, eval = model.run(max_iter=30)
    # print(eval)
    print(param)  # They aren't the last param corresponding to the last iteration. They correspond to the best rsme.
    model.fit()
    prediction_train = model.predict(x_train_features)
    prediction_test = model.predict(x_test_features)
    store_data = dict()
    store_data['air'] = [x_train_features[:, 0], data_train, prediction_train,
                    x_test_features[:, 0], data_test, prediction_test]

    evaluate(store_data, name_dataset = name_dataset, mode_dataset = mode_dataset, metrics_print = True, train_predict_plot = False)


from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Count,Q
from django.shortcuts import render
from learning.models import (
    Problem,
    Tutorial,
    Score,
    Submission
)
from django.contrib.auth.models import User
from django.urls import reverse_lazy
from django.shortcuts import get_object_or_404
from django.views.generic import (
    DetailView,
    ListView,
    CreateView
)
from learning.forms import SubmissionForm

class MainPageView(LoginRequiredMixin,ListView):

    template_name = 'learning/main_page.html'

    def get_queryset(self):
        return Problem.objects.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'blog_nav': 'active',
            'tutorials': Tutorial.objects.all(),
            'current_user': Score.objects.filter(learner=self.request.user),
            'dashboard_learning_tab': 'active',
            'dashboard_Tuto_tab': 'active'
        })
        return context

class ProblemListView(LoginRequiredMixin,ListView):
    model = Problem
    context_object_name = 'problems'
    template_name = 'learning/problems_list.html'

    def get_queryset(self):

        current_user = self.request.user if self.request.user.is_authenticated else None
        return Problem.objects.annotate(
            solve_count=Count(
                'submissions__user',
                filter=Q(submissions__status='AC'),
                distinct=True
            ),
            is_solved=Count(
                'submissions__user',
                filter=Q(submissions__status='AC', submissions__user=current_user)
            )
        ).order_by('-solve_count')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'dashboard_learning_tab': 'active',
            'dashboard_Prob_tab': 'active',
            'current_user': Score.objects.filter(learner=self.request.user)
        })
        return context

class ProblemDetailView(LoginRequiredMixin,DetailView):
    model = Problem
    template_name = 'learning/problem_details.html'
    context_object_name = 'problem'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'dashboard_learning_tab': 'active',
            'dashboard_Prob_tab': 'active',
            'submission_form': SubmissionForm(),
            'testcases': self.get_object().testcases.filter(is_sample=True)
        })
        return context

class SubmissionCreateView(LoginRequiredMixin,CreateView):
    model = Submission
    form_class = SubmissionForm
    success_url = reverse_lazy('learning:submission-list')

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.problem = get_object_or_404(Problem, pk=self.kwargs.get('problem_id'))
        return super().form_valid(form)

class SubmissionListView(LoginRequiredMixin,ListView):
    model = Submission
    paginate_by = 10
    context_object_name = 'submissions'
    template_name = 'learning/submission_list.html'

    def get_queryset(self):
        return Submission.objects.filter(user = self.request.user).order_by('-created_at')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'dashboard_learning_tab': 'active',
            'dashboard_Sub_tab': 'active'
        })
        return context


import time
import numpy as np
from processcomputing.unidadFuncional import sinSegmentacion, conSegmentacion

def procesador(option, cantidadInstrucciones):
    fetch = 5
    accesoMemoria = np.random.randint(10, 20)
    ejecucion = np.random.randint(20, 45)
    Retroescritura = np.random.randint(2, 5)
    actualizacionProcesador = 10
    i = 0
    tiempoEjecucion = 0
    cola = []
    bloques = 5

    if option==1:
        sinSegmentacion(i,tiempoEjecucion,cola,bloques,fetch,accesoMemoria,ejecucion,Retroescritura,actualizacionProcesador,cantidadInstrucciones)
    elif option==2:
        conSegmentacion(i,tiempoEjecucion,cola,bloques,fetch,accesoMemoria,ejecucion,Retroescritura,actualizacionProcesador,cantidadInstrucciones)


#!/usr/bin/python

##----------------------------------------------------------------------------##
## \file  randNumGen.py                                                       ##
## \brief Random number generator                                             ##
##                                                                            ##
## $URL: https://trstwprsvnapv01.treasury.corp.ge.com/svn/Treasury/QUANTS%20GROUP/Branches/Dima/mdm0/Utils/Python/Maths/randNumGen.py $
## $Id: randNumGen.py 23399 2015-05-28 19:58:41Z 212361829 $                  ##
##----------------------------------------------------------------------------##

from numpy import random

class RandNumGen(object):
    def __init__(self, seed = 1):
        self._seed = None
        self.seed  = seed

    @property
    def seed(self):
        """
        :return: seed
        :rtype:  int
        """
        return self._seed

    @seed.setter
    def seed(self, seed):
        """
        :param  seed: New seed
        :type   seed: unsigned long
        :return: Nothing
        :rtype:  None
        """
        self._seed = seed
        random.seed(seed = seed)

    @staticmethod
    def uniformInt(low, high = None, size = None, replace = True):
        """
        Random integers from low to high
        If high is valid, then from [low, high). If high = None, from [0, low).
        :param low:     boundary of the interval to draw from
        :type  low:     int
        :param high:    boundary of the interval to draw from
        :type  high:    int
        :param size:    Output matrix shape
        :type  size:    int or tuple of ints
        :param replace: Drawing with replacement (True) or without (False)
        :type  replace: bool
        :rtype:
        """
        if size is None:
            size = 1

        if replace or (size == 1):
            return random.randint(low = low, high = high, size = size)

        if high is None:
            data = range(low)
        else:
            data = range(low, high)
        return random.choice(a = data, size = size, replace = False)


class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def print_list(self):
        if self.head is None:
            print('Empty linked list')
            return

        cur_node = self.head
        llstr = ''

        while cur_node:
            llstr += str(cur_node.data) + '-->'
            cur_node = cur_node.next
        print(llstr)

    def append(self, data):
        new_node = Node(data)

        if self.head is None:
            self.head = new_node
            return

        last_node = self.head
        while last_node.next:
            last_node = last_node.next
        last_node.next = last_node

    def prepend(self, data):
        new_node = Node(data)
        new_node.next = self.head
        self.head = new_node

    def insert_after_node(self, prev_node, data):
        if prev_node:
            print('Previous node does not exist.')
            return
        new_node = Node(data)
        new_node.next = prev_node.next
        prev_node.next = new_node

    def delete_node(self, key):
        cur_node = self.head

        if cur_node and cur_node.data == key:
            self.head = cur_node.next
            cur_node = None
            return

        prev = None
        while cur_node and cur_node.data != key:
            prev = cur_node
        if cur_node is None:
            return

        prev.next = cur_node.next
        cur_node = None

    def Iterative_count(self):
        cur_node = self.head
        count = 0
        while cur_node:
            count +=1
            cur_node = cur_node.next
        return count

Linked Lists/Singly Linked List/Length Iterative Implementation.py


def max_number(mass):
  num = 0
  for i in range(len(mass)):
    if abs(mass[i]) < abs(mass[num]):
      num = i
      min = mass[i]
  print('Mинимальный по модулю элемент: ',min)
  i = 0
  pos = -1
  while i < len(mass):
    if mass[i] < 0 and pos == -1:
      pos = i
    elif mass[i] < 0 and mass[i] > mass[pos]:
      pos= i
    i += 1
  print('Mаксимальный отрицательный элемент',mass[pos])
print('Введите длину массива: ',end='')
n = int(input())
array = []
for i in range(n):
  array.append(int(input()))
print(array)
b = max_number(array)
print(b)


from classes import NotFoundError
from operator import itemgetter

def get_library_to_sign_up(libraries):
  sort_libraries = sorted(libraries, key=lambda x: x.num_book_shippable * x.total_score / x.signup_time, reverse=True)
  return sort_libraries[0]

def get_library_to_signup(libraries, ordered_libraries):
  """
  Returns the most promising library to sign up at some point.
  If one library is still signing up, we return this library.
  """
  signing_up = [lib for lib in libraries if lib.signing_up]

  # If one of the library is already signing up, we return this library
  if len(signing_up) and signing_up[0].time_left_to_signup > 0:
    signing_up[0].signing_up = True
    return ordered_libraries + [signing_up[0]]

  not_signed_up = [lib for lib in libraries if not lib.signed_up()]
  if len(not_signed_up):
    library_to_sign_up = get_library_to_sign_up(not_signed_up)
    library_to_sign_up.signing_up = True
    return ordered_libraries + [library_to_sign_up]

  return ordered_libraries

def get_best_library(libraries, days_left):

    if len(libraries) == 0:
        raise NotFoundError("No more libraries")

    def score(library):
        return sum(
                map(itemgetter(1),
                    library.books_set_ordered_by_score[
                        :library.num_book_shippable * (days_left-library.signup_time)
                    ]),
                    0
                    )
    library_scores = {
            library.id: score(library) if library.signup_time < days_left else 0
            for library in libraries
    }
    libraries = sorted(libraries, key=lambda library: library_scores[library.id], reverse=True)
    best_library = libraries[0]

    if best_library.signup_time >= days_left:
        raise NotFoundError("No library to signup in the remaining time")

    return best_library, libraries[1:]


from django.forms import modelform_factory
from django.shortcuts import render, get_object_or_404, redirect

# Create your views here.
from personas.forms import PersonaForm
from personas.models import Persona

def detallePersona(request, id):
    # persona = Persona.objects.get(pk=id)
    persona = get_object_or_404(Persona, pk=id)
    return render(request, 'personas/detalle.html', {'persona': persona})

# PersonaForm = modelform_factory(Persona, exclude=[])

def nuevaPersona(request):
    if request.method == 'POST':
        formatPersona = PersonaForm(request.POST)
        if formatPersona.is_valid():
            formatPersona.save()
            return redirect('index')
    else:
        formatPersona = PersonaForm()
    return render(request, 'personas/nueva.html', {'formatPersona': formatPersona})

def editarPersona(request, id):
    persona = get_object_or_404(Persona, pk=id)
    if request.method == 'POST':
        formatPersona = PersonaForm(request.POST, instance=persona)
        if formatPersona.is_valid():
            formatPersona.save()
            return redirect('index')
    else:
        formatPersona = PersonaForm(instance=persona)
    return render(request, 'personas/editar.html', {'formatPersona': formatPersona})

def eliminarPersona(request, id):
    persona = get_object_or_404(Persona, pk=id)
    if persona:
        persona.delete()
    return redirect('index')


from Nodo import *

nodo1=Nodo("impostor")

nodo2=Nodo("rojo")
nodo1.siguiente=nodo2

nodo3=Nodo("morado")
nodo2.siguiente=nodo3

print(nodo1.dato)
nodoGuia=nodo1.getSiguiente()
while True:

    if nodoGuia.siguiente==None:
        print (nodoGuia.getDato())
        break
    else:
        print(nodoGuia.getDato())
        nodoGuia=nodoGuia.getSiguiente()


# -*- coding: utf-8 -*-
"""
Decision Sypport Systems
6.5.1 - 6.5.2

Kasper Kronborg Larsen
"""

import pandas as pd
import itertools
import time
import statsmodels.api as sm
import matplotlib.pyplot as plt

data = pd.read_csv('C:/Users/Kasper/Desktop/datasets/Hitters.csv')
data.head()

print("Number of null values:", data["Salary"].isnull().sum())

# Print the dimensions of the original Hitters data (322 rows x 20 columns)
print("Dimensions of original data:", data.shape)

# Drop any rows the contain missing values, along with the player names
data_drop = data.dropna().drop('Unnamed: 0', axis=1)

# Print the dimensions of the modified Hitters data (263 rows x 20 columns)
print("Dimensions of modified data:", data_drop.shape)

# One last check: should return 0
print("Number of null values:", data_drop["Salary"].isnull().sum())

dummies = pd.get_dummies(data_drop[['League', 'Division', 'NewLeague']])
y = data_drop.Salary

# Drop the column with the independent variable (Salary), and columns for which we created dummy variables
X_ = data_drop.drop(['Salary', 'League', 'Division', 'NewLeague'], axis=1).astype('float64')

# Define the feature set X.
X = pd.concat([X_, dummies[['League_N', 'Division_W', 'NewLeague_N']]], axis=1)

dummies = pd.get_dummies(data_drop[['League', 'Division', 'NewLeague']])
y = data_drop.Salary

# Drop the column with the independent variable (Salary), and columns for which we created dummy variables
X_ = data_drop.drop(['Salary', 'League', 'Division', 'NewLeague'], axis=1).astype('float64')

# Define the feature set X.
X = pd.concat([X_, dummies[['League_N', 'Division_W', 'NewLeague_N']]], axis=1)

def processSubset(feature_set):
    # Fit model on feature_set and calculate RSS
    model = sm.OLS(y,X[list(feature_set)])
    regr = model.fit()
    RSS = ((regr.predict(X[list(feature_set)]) - y) ** 2).sum()
    return {"model":regr, "RSS":RSS}

def getBest(k):

    tic = time.time()

    results = []

    for combo in itertools.combinations(X.columns, k):
        results.append(processSubset(combo))

    # Wrap everything up in a nice dataframe
    models = pd.DataFrame(results)

    # Choose the model with the highest RSS
    best_model = models.loc[models['RSS'].argmin()]

    toc = time.time()
    print("Processed", models.shape[0], "models on", k, "predictors in", (toc-tic), "seconds.")

    # Return the best model, along with some other useful information about the model
    return best_model

# Could take quite awhile to complete...

models_best = pd.DataFrame(columns=["RSS", "model"])

tic = time.time()
for i in range(1,8):
    models_best.loc[i] = getBest(i)

toc = time.time()
print("Total elapsed time:", (toc-tic), "seconds.")

models_best
print(models_best.loc[2, "model"].summary())

# Show the best 19-variable model (there's actually only one)
print(getBest(19)["model"].summary())

models_best.loc[2, "model"].rsquared

# Gets the second element from each row ('model') and pulls out its rsquared attribute
models_best.apply(lambda row: row[1].rsquared, axis=1)

plt.figure(figsize=(20,10))
plt.rcParams.update({'font.size': 18, 'lines.markersize': 10})

# Set up a 2x2 grid so we can look at 4 plots at once
plt.subplot(2, 2, 1)

# We will now plot a red dot to indicate the model with the largest adjusted R^2 statistic.
# The argmax() function can be used to identify the location of the maximum point of a vector
plt.plot(models_best["RSS"])
plt.xlabel('# Predictors')
plt.ylabel('RSS')

# We will now plot a red dot to indicate the model with the largest adjusted R^2 statistic.
# The argmax() function can be used to identify the location of the maximum point of a vector

rsquared_adj = models_best.apply(lambda row: row[1].rsquared_adj, axis=1)

plt.subplot(2, 2, 2)
plt.plot(rsquared_adj)
plt.plot(rsquared_adj.argmax(), rsquared_adj.max(), "or")
plt.xlabel('# Predictors')
plt.ylabel('adjusted rsquared')

# We'll do the same for AIC and BIC, this time looking for the models with the SMALLEST statistic
aic = models_best.apply(lambda row: row[1].aic, axis=1)

plt.subplot(2, 2, 3)
plt.plot(aic)
plt.plot(aic.argmin(), aic.min(), "or")
plt.xlabel('# Predictors')
plt.ylabel('AIC')

bic = models_best.apply(lambda row: row[1].bic, axis=1)

plt.subplot(2, 2, 4)
plt.plot(bic)
plt.plot(bic.argmin(), bic.min(), "or")
plt.xlabel('# Predictors')
plt.ylabel('BIC')

def forward(predictors):

    # Pull out predictors we still need to process
    remaining_predictors = [p for p in X.columns if p not in predictors]

    tic = time.time()

    results = []

    for p in remaining_predictors:
        results.append(processSubset(predictors+[p]))

    # Wrap everything up in a nice dataframe
    models = pd.DataFrame(results)

    # Choose the model with the highest RSS
    best_model = models.loc[models['RSS'].argmin()]

    toc = time.time()
    print("Processed ", models.shape[0], "models on", len(predictors)+1, "predictors in", (toc-tic), "seconds.")

    # Return the best model, along with some other useful information about the model
    return best_model

models_fwd = pd.DataFrame(columns=["RSS", "model"])

tic = time.time()
predictors = []

for i in range(1,len(X.columns)+1):
    models_fwd.loc[i] = forward(predictors)
    predictors = models_fwd.loc[i]["model"].model.exog_names

toc = time.time()
print("Total elapsed time:", (toc-tic), "seconds.")

print(models_fwd.loc[1, "model"].summary())
print(models_fwd.loc[2, "model"].summary())

print(models_best.loc[6, "model"].summary())
print(models_fwd.loc[6, "model"].summary())

def backward(predictors):

    tic = time.time()

    results = []

    for combo in itertools.combinations(predictors, len(predictors)-1):
        results.append(processSubset(combo))

    # Wrap everything up in a nice dataframe
    models = pd.DataFrame(results)

    # Choose the model with the highest RSS
    best_model = models.loc[models['RSS'].argmin()]

    toc = time.time()
    print("Processed ", models.shape[0], "models on", len(predictors)-1, "predictors in", (toc-tic), "seconds.")

    # Return the best model, along with some other useful information about the model
    return best_model

models_bwd = pd.DataFrame(columns=["RSS", "model"], index = range(1,len(X.columns)))

tic = time.time()
predictors = X.columns

while(len(predictors) > 1):
    models_bwd.loc[len(predictors)-1] = backward(predictors)
    predictors = models_bwd.loc[len(predictors)-1]["model"].model.exog_names

toc = time.time()
print("Total elapsed time:", (toc-tic), "seconds.")

print("------------")
print("Best Subset:")
print("------------")
print(models_best.loc[7, "model"].params)
print("-----------------")
print("Foward Selection:")
print("-----------------")
print(models_fwd.loc[7, "model"].params)
print("-------------------")
print("Backward Selection:")
print("-------------------")
print(models_bwd.loc[7, "model"].params)


import random
from typing import List, Tuple
import fitz  # install with 'pip install pymupdf'

from .NoteExtractor import NoteExtractorInterface

class PdfNotesExtractor(NoteExtractorInterface):
    def __init__(self, filePath):
        self.noteBody = fitz.open(filePath)

    def getRandomlyChosenNotes(self, numToReturn=3):
        """
        Returns a randomly selected number (based on the numToReturn arg) of
        notes/highlights from the collection of notes (self.noteBody)
        """
        allNotes = self._getAllHighlights()

        if len(allNotes) < numToReturn:
            return allNotes
        else:
            result = []
            for _ in range(numToReturn):
                note = random.choice(allNotes)
                result.append(note)
                allNotes.remove(note)

    def _getAllHighlights(self):
        highlights = []
        for page in self.noteBody:
            highlights += self._handle_page(page)

        return highlights

    def _handle_page(self, page):
        wordlist = page.getText("words")  # list of words on page
        wordlist.sort(key=lambda w: (w[3], w[0]))  # ascending y, then x

        highlights = []
        annot = page.firstAnnot
        while annot:
            # annot.type == 8 means its a highlight:
            # https://pymupdf.readthedocs.io/en/latest/vars.html#annotationtypes
            if annot.type[0] == 8:
                highlights.append(self._parse_highlight(annot, wordlist))
            annot = annot.next
        return highlights

    def _parse_highlight(self, annot, wordlist):
        points = annot.vertices
        # find how many quadrilaterals are in the doc
        quad_count = int(len(points) / 4)
        sentences = []
        for i in range(quad_count):
            # where the highlighted part is by intersecting
            # the rectangles
            r = fitz.Quad(points[i * 4 : i * 4 + 4]).rect
            words = [w for w in wordlist if fitz.Rect(w[:4]).intersects(r)]
            sentences.append(" ".join(w[4] for w in words))
        sentence = " ".join(sentences)
        return sentence


import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('lenna.png', 1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.figure()
plt.hist(gray.ravel(), 256)
# hist = cv2.calcHist([gray], [0], None, [256], [0, 256])
# plt.plot(hist)
plt.title("Grayscale Histogram")
plt.xlabel("Bins")
plt.ylabel("Number of Pixels")
plt.xlim([0, 270])
plt.ylim([0, 4000])
plt.show()


#total number of cured cases
fin=open("complete.csv","r")
dict={}
for lines in fin:
    report=lines.rstrip("\n").split(",")
    state=report[1]
    cured=int(report[6])
    if(state not in dict):
        dict[state]=cured
    else:
        dict[state]+=cured
print("Dic",dict)
# curedlist=[]
# for k,v in dict.items():
#     curedlist.append((v,k))
#     d=max(curedlist)
# print("Curedlist",curedlist)
# sortedlist=sorted(curedlist)
# print("Sorted List",sortedlist)
# print("highest cured rate",d)


class TreeNode:
    def __init__(self, name, designation):
        self.data = [name, designation]
        self.parent = None
        self.children = []

    def add_child(self, node):
        node.parent = self
        self.children.append(node)

    def print_tree(self, type, max_level):
        level = self.get_level()
        if level > max_level: return
        if level:
            print( "   "*level + "|__", end="" )

        if type == "both":
            print(self.data[0] + f" ({self.data[1]})")
        elif type == "name":
            print(self.data[0])
        elif type == "designation":
            print(f"({self.data[1]})")

        for child in self.children:
            child.print_tree(type, max_level)

    def get_level(self):
        level = 0
        parent = self.parent
        while parent:
            level += 1
            parent = parent.parent
        return level

def build_management_tree():
    # level 0
    ceo = TreeNode("Nilupul", "CEO")

    # level 1
    cto = TreeNode("Chinmay", "CTO")
    hr_head = TreeNode("Gels", "HR Head")

    ceo.add_child(cto)
    ceo.add_child(hr_head)

    # level 2
    infra_head = TreeNode("Vishwa", "Infrastructure Head")
    application_head = TreeNode("Aamir", "Application Head")
    recruitment_manager = TreeNode("Peter", "Recruitment Manager")
    policy_manager = TreeNode("Waqas", "Policy Manager")

    cto.add_child(infra_head)
    cto.add_child(application_head)
    hr_head.add_child(recruitment_manager)
    hr_head.add_child(policy_manager)

    # level 3
    cloud_manager = TreeNode("Dhaval", "Cloud Manager")
    app_manager = TreeNode("Abhijit" , "App Manager")

    infra_head.add_child(cloud_manager)
    infra_head.add_child(app_manager)

    return ceo

if __name__ == "__main__":
    root = build_management_tree()
    root.print_tree("both", 0)


from django.shortcuts import render, redirect
from django.contrib import messages
from models import User
from ..posts.models import *

def index(request):
    if 'logged_id' not in request.session:
        return render(request, 'users/index.html')
    else:
        return redirect('/users/' + str(request.session['logged_id']))

def login(request):
    if 'logged_id' not in request.session:
        return render(request, 'users/login.html')
    else:
        return redirect('/users/' + str(request.session['logged_id']))

def register(request):
    if 'logged_id' not in request.session:
        return render(request, 'users/register.html')
    else:
        return redirect('/users/' + str(request.session['logged_id']))

def process_login(request):
    if request.method == 'POST':
        errors = User.objects.log_validator(request)
        if len(errors):
            for error in errors:
                messages.error(request, error)
                return redirect('/login')
        else:
            return redirect('/users/' + str(request.session['logged_id']))

def process_register(request):
    if request.method == 'POST':
        errors = User.objects.reg_validator(request)
        if len(errors):
            for error in errors:
                messages.error(request, error)
            return redirect('/register')
        else:
            User.objects.reg_user(request)
            request.session['logged_id'] = User.objects.last().id
            return redirect ('/users/' + str(request.session['logged_id']))

def users(request, id):
    context = {
        'user': User.objects.get(id = id),
        'posts': Post.objects.filter(user_id = id),
        'comments': Comment.objects.all(),
    }
    return render(request, 'users/users.html', context)

def community(request):
    context = {
        'users': User.objects.all().order_by('handle')
    }
    return render(request, 'users/community.html', context)

def settings(request, id):
    context = {
        'user': User.objects.get(id = id)
    }
    return render(request, 'users/settings.html', context)

def update_email(request):
    if request.method == 'POST':
        errors = User.objects.update_email_validator(request)
        if len(errors):
            for error in errors:
                messages.error(request, error)
            return redirect('/users/' + str(request.session['logged_id']) + '/settings')
        else:
            User.objects.update_email(request)
            messages.success(request, 'Email successfully updated!')
            return redirect('/users/' + str(request.session['logged_id']) + '/settings')

def update_password(request):
    if request.method == 'POST':
        errors = User.objects.update_password_validator(request)
        if len(errors):
            for error in errors:
                messages.error(request, error)
            return redirect('/users/' + str(request.session['logged_id']) + '/settings')
        else:
            User.objects.update_password(request)
            messages.success(request, 'Password successfully updated!')
            return redirect('/users/' + str(request.session['logged_id']) + '/settings')

def logout(request):
    request.session.clear()
    return redirect('/')


from mylist import MyList

class MyListSub(MyList):
    calls = 0                                      # Shared by instances
    def __init__(self, start):
        self.adds = 0                              # Varies in each instance
        MyList.__init__(self, start)

    def __add__(self, other):
        print('add: ' + str(other))
        MyListSub.calls += 1                       # Class-wide counter
        self.adds += 1                             # Per-instance counts
        return MyList.__add__(self, other)

    def stats(self):
        return self.calls, self.adds               # All adds, my adds

if __name__ == '__main__':
    x = MyListSub('spam')
    y = MyListSub('foo')
    print(x[2])
    print(x[1:])
    print(x + ['eggs'])
    print(x + ['toast'])
    print(y + ['bar'])
    print(x.stats())


"""
問題URL:https://atcoder.jp/contests/dp/tasks/dp_a
"""

def DP_search(h):
    nodes = [0]
    nodes.append(abs(h[1] - h[0]))
    for i in range(2, len(h)):
        a = abs(h[i] - h[i-1]) + nodes[i-1]
        b = abs(h[i] - h[i-2]) + nodes[i-2]
        nodes.append(a if a < b else b)
    return nodes

def main():
    n = int(input())
    h = list(map(int, input().split()))
    nodes = DP_search(h)
    print(nodes[n-1])

if __name__ == '__main__':
    main()


n = int(input())
arr = list(map(int,input().split()))
arr.sort() # 가벼운 순으로 꺼내져야 하므로
result = []
# 매번 2개씩 꺼내야하는데, 황금1 / 짱돌1 or 짱돌2 이렇게 남아있는 경우 break
# 꺼내는 기준: 가장 가벼운 돌!!
# 황금과 짱돌이 같은 무게일때는,황금이 먼저 나온다

while 1:
    if type(arr[0]) == str: # 처음 꺼내는 돌이 짱돌이면, 바로 break
        break
    elif type(arr[0]) != str and type(arr[1]) == str: # 두번째만 짱돌이면, 첫 황금은 추가해줘!
        result += [arr[0]]
        break
    elif type(arr[0]) != str and type(arr[1]) != str: # 둘다 황금이면,
        result += arr[0:2]
        tmp = arr[1]
        arr = arr[2:]
        # arr.append(tmp) # 어라. 이렇게 하면 짱돌인지 알 수가 없잖아. 심지어 무게 같은 황금이 있을땐 더더욱
        arr.append(str(tmp * 2)) # 짱돌은 str넣어서 구별!
        arr.sort(key=lambda i: int(i)) # ㅅㅂ 이렇게 하면되는구나

print(len(result))


from pathlib import Path
import pandas as pd

def load_data(path = './data', datasets = ['seasons', 'constructors', 'drivers', 'races', 'circuits', 'lap_times', 'results', 'status']):
    data_dir = Path(path).absolute()
    d = {k: pd.read_csv((data_dir/k).with_suffix('.csv')) for k in datasets}
    r = races = d['races']
    r = r.merge(d['results'], on='raceId')
    r = r.merge(d['constructors'], on='constructorId')
    r = r.merge(d['status'], on='statusId')
    r = r.merge(d['drivers'], on='driverId')
    r.drop(columns=[])
    r = r[r.year > 2010]
    races = races[races.year > 2010]
    return r

data = load_data()


from __future__ import print_function

import os.path
import sys

from Bio._py3k import range

VERSIONS = ["4_1", "4_3", "4_4", "4_4c", "4_5", "4_6", "4_7", "4_8", "4_9a"]

def codeml(vers=None, verbose=False):
    from Bio.Phylo.PAML import codeml
    if vers is not None:
        versions = [vers]
    else:
        versions = VERSIONS
    tests = [("aa_model0", "aa_alignment.phylip", "species.tree"),
             ("aa_pairwise", "aa_alignment.phylip", "species.tree"),
             ("all_NSsites", "alignment.phylip", "species.tree"),
             ("branchsiteA", "alignment.phylip", "species.tree"),
             ("clademodelC", "alignment.phylip", "species.tree"),
             ("freeratio", "alignment.phylip", "species.tree"),
             ("ngene2_mgene02", "lysinYangSwanson2002.nuc", "lysin.trees"),
             ("ngene2_mgene34", "lysinYangSwanson2002.nuc", "lysin.trees"),
             ("pairwise", "alignment.phylip", "species.tree"),
             ("SE", "alignment.phylip", "species.tree"),
             ("m2a_rel", "alignment.phylip", "species.tree")]

    for test in tests:
        print(test[0])
        cml = codeml.Codeml()
        cml.working_dir = "temp"
        ctl_file = os.path.join("Control_files",
                                "codeml",
                                '.'.join([test[0], "ctl"]))
        alignment = os.path.join("Alignments", test[1])
        tree = os.path.join("Trees", test[2])
        cml.read_ctl_file(ctl_file)
        cml.alignment = alignment
        cml.tree = tree
        for version in versions:
            # M2a_rel (NSsites 22) was introduced in PAML 4.6
            if test[0] == "m2a_rel" and int(version.split("_")[1][0]) < 6:
                continue
            print("\t{0}".format(version.replace('_', '.')))
            if test[0] in ["ngene2_mgene02", "ngene2_mgene34"] and \
               version == "4_6":
                cml.tree = ".".join([cml.tree, "4.6"])
            out_file = '.'.join(['-'.join([test[0], version]), "out"])
            cml.out_file = os.path.join("Results", "codeml", test[0], out_file)
            bin = ''.join(["codeml", version])
            cml.run(command=bin, verbose=verbose)

def baseml(vers=None, verbose=False):
    from Bio.Phylo.PAML import baseml
    if vers is not None:
        versions = [vers]
    else:
        versions = VERSIONS
    tests = [("model", list(range(0, 9))), ("nhomo", [1, 3, 4]),
             ("nparK", list(range(1, 5))), ("alpha1rho1", None), ("SE", None)]
    alignment = os.path.join("Alignments", "alignment.phylip")
    tree = os.path.join("Trees", "species.tree")
    for test in tests:
        print(test[0])
        bml = baseml.Baseml()
        for version in versions:
            print("\t{0}".format(version.replace('_', '.')))
            if test[1] is not None:
                for n in test[1]:
                    if (version in ["4_3", "4_4", "4_4c", "4_5"] and
                            test[0] == "nparK" and n in [3, 4]):
                        continue
                    print("\t\tn = {0}".format(n))
                    ctl_file = (os.path.join("Control_files", "baseml",
                                "{0}{1}.ctl".format(test[0], n)))
                    bml.read_ctl_file(ctl_file)
                    bml.alignment = alignment
                    bml.tree = tree
                    out_file = "{0}{1}-{2}.out".format(test[0], n, version)
                    bml.out_file = (os.path.join("Results", "baseml", test[0],
                                    out_file))
                    bin = "baseml{0}".format(version)
                    bml.run(command=bin, verbose=verbose)
            else:
                if (version in ["4_3", "4_4", "4_4c", "4_5"] and
                        test[0] == "alpha1rho1"):
                    continue
                ctl_file = (os.path.join("Control_files", "baseml",
                            "{0}.ctl".format(test[0])))
                bml.read_ctl_file(ctl_file)
                bml.alignment = alignment
                bml.tree = tree
                out_file = "{0}-{1}.out".format(test[0], version)
                bml.out_file = (os.path.join("Results", "baseml", test[0],
                                out_file))
                bin = "baseml{0}".format(version)
                bml.run(command=bin, verbose=verbose)

def yn00(vers=None, verbose=False):
    from Bio.Phylo.PAML import yn00
    if vers is not None:
        versions = [vers]
    else:
        versions = VERSIONS
    tests = ["yn00", "yn00_long"]
    for test in tests:
        print(test[0])
        yn = yn00.Yn00()
        for version in versions:
            print("\t{0}".format(version.replace('_', '.')))
            ctl_file = (os.path.join("Control_files", "yn00",
                        "{0}.ctl".format(test)))
            yn.read_ctl_file(ctl_file)
            out_file = "{0}-{1}.out".format(test, version)
            yn.out_file = os.path.join("Results", 'yn00', out_file)
            bin = "yn00{0}".format(version)
            yn.run(command=bin, verbose=verbose)

def print_usage():
    versions = ", ".join(vers.replace("_", ".") for vers in VERSIONS)
    usage = """Usage: gen_results.py [-v] PROGRAM [VERSION]

Generate result files to be used in Bio.Phylo.PAML unit tests.

  -v         Use verbose output
  PROGRAM    codeml, baseml or yn00
  VERSION    %s

To use this, the PAML programs must be in your executable path and
they must be named programX_Y, where X and Y are the version numbers
(i.e. baseml4_5 or codeml4_4c). If VERSION is not specified, test
results will be generated for all versions listed above.
""" % (versions)
    sys.exit(usage)

if __name__ == "__main__":
    programs = ["codeml", "baseml", "yn00"]
    prog = None
    verbose = False
    vers = None
    if len(sys.argv) < 2:
        print_usage()
    for arg in sys.argv[1:]:
        if arg == "-v":
            verbose = True
        elif arg in programs:
            if prog is not None:
                print("Only one program at a time, please.")
                print_usage()
            prog = arg
        elif arg.replace(".", "_") in VERSIONS:
            if vers is not None:
                print("Only one version at a time, sorry.")
            vers = arg.replace(".", "_")
        else:
            print("Unrecognized argument")
            print_usage()
    if prog is None:
        print("No program specified")
        print_usage()
    if prog == "codeml":
        codeml(vers, verbose)
    elif prog == "baseml":
        baseml(vers, verbose)
    elif prog == "yn00":
        yn00(vers, verbose)


import logging

import pygsheets
from fastapi import APIRouter, Depends, Body, Security

from configs import settings
from core.authen import get_api_key
from models.base_model import CarInsuranceModel
from models.base_response import BaseResponseData, BaseErrorResponse
from utils import create_aliased_response

router = APIRouter()
GC_SHEET_SRV = None
telegram_logger = logging.getLogger("critical")

def get_gg_sheet_inst():
    global GC_SHEET_SRV
    if GC_SHEET_SRV:
        return GC_SHEET_SRV
    else:
        gc = pygsheets.authorize(service_file="insurance.json")
        sh = gc.open(settings.SHEET_NAME)
        GC_SHEET_SRV = sh[0]
        GC_SHEET_SRV.insert_rows(
            3,
            number=1,
            values=[
                "Tên",
                "SĐT",
                "Email",
                "Hãng xe",
                "Dòng xe",
                "Năm SX",
                "Tỉnh thành",
                "Ngày ĐK đầu tiên",
                "Ngày hiệu lực BH",
                "Xe Đk KD",
                "Thời gian tạo",
            ],
        )
        return GC_SHEET_SRV

@router.get(
    "/healthcheck",
    response_model=BaseResponseData,
    tags=["Wrapper API"],
)
async def health_check():
    """Add multiple task to task-pipeline"""
    return create_aliased_response(
        BaseResponseData(
            code=0,
            message="success",
            result={"health_check": "Oke"},
        )
    )

@router.post(
    "/car-insurance/new-insurance",
    response_model=BaseResponseData,
    tags=["Wrapper API"],
    dependencies=[Security(get_api_key)],
)
async def new_car_insurance(
    *,
    body: CarInsuranceModel = Body(
        ...,
    ),
    gg_sh=Depends(get_gg_sheet_inst)
):
    """Add multiple task to task-pipeline"""

    try:
        gg_sh.insert_rows(
            5,
            number=1,
            values=[
                body.name,
                body.phone,
                body.email or "#",
                body.car_brand,
                body.car_model,
                body.car_year,
                body.province,
                body.date_registry,
                body.date_insurance_atv,
                body.is_ecom,
                body.date_submit,
            ],
            inherit=True,
        )
        telegram_logger.info("New data insert", body.dict())
        return create_aliased_response(
            BaseResponseData(
                code=0,
                message="success",
                result={},
            )
        )
    except Exception as ex:
        telegram_logger.error("New data update error", body.dict())
        return (
            create_aliased_response(
                BaseErrorResponse(code=1, message="servce  error", detail=str(ex)),
            ),
            400,
        )


import copy
import logging
from bz2 import BZ2Compressor
from typing import Union, Iterable

import cv2
import gym
import numpy as np
# noinspection PyUnresolvedReferences
import pybullet_envs  # Needs to be imported to register PyBullet environments
from gym import Wrapper
from gym.spaces import Box
from gym.wrappers.atari_preprocessing import AtariPreprocessing

# noinspection PyUnresolvedReferences
import gym_memory_environments  # Needs to be imported to register our custom memory environments
from tools.ae_wrapper import AEWrapper
from tools.configurations import (EpisodeRunnerCfg, ReacherMemoryEnvAttributesCfg, AtariEnvAttributesCfg,
                                  ProcGenEnvAttributesCfg)

class EnvHandler:
    """This class creates and modifies OpenAI-Gym environments."""

    def __init__(self, config: EpisodeRunnerCfg):
        self.config = config

    def make_env(self, env_id: str, render: bool = False, record: str = None, record_force: bool = False):
        if env_id == "ReacherMemory-v0" or env_id == "ReacherMemoryDynamic-v0":
            assert isinstance(self.config.environment_attributes, ReacherMemoryEnvAttributesCfg), \
                "For the environment 'ReacherMemory-v0' one must provide the ReacherMemoryEnvAttributesCfg" \
                " (config.environment_attributes)"

            env = gym.make(
                env_id,
                observation_frames=self.config.environment_attributes.observation_frames,
                memory_frames=self.config.environment_attributes.memory_frames,
                action_frames=self.config.environment_attributes.action_frames)
        elif env_id.startswith("procgen"):
            logging.debug("initiating procgen with memory")

            assert isinstance(self.config.environment_attributes, ProcGenEnvAttributesCfg), \
                "For procgen environment one must provide the ProcGenEnvAttributesCfg" \
                " (config.environment_attributes)"
            env = ProcEnvHandler(env_id, render, self.config.environment_attributes)
        elif env_id == 'QbertHard-v0':
            logging.debug("wrapping QbertNoFrameskip-v4 in QbertGlitchlessWrapper")
            env = QbertGlitchlessWrapper(gym.make('QbertNoFrameskip-v4'))
        elif env_id == 'ReverseShaped-v0':
            env = gym.make('Reverse-v0')
            # these options are specific to reverse-v0 and aren't important enough to be part of the
            # global configuration file.
            env.env.last = 15
            env.env.min_length = 7
            logging.debug("creating env with min_length " + str(
                env.env.min_length) + " and also comparing results over the last " + str(env.env.last) + " runs.")

            logging.debug("wrapping env in ReverseWrapper")
            env = ReverseWrapper(env)
        else:
            env = gym.make(env_id)

        if self.config.use_autoencoder:
            logging.debug("wrapping env in AEWrapper")
            env = AEWrapper(env)
        else:
            if env.spec.id.endswith("NoFrameskip-v4"):
                logging.debug("wrapping env in AtariPreprocessing")

                assert isinstance(self.config.environment_attributes, AtariEnvAttributesCfg), \
                    "For atari environment one must provide the AtariEnvAttributesCfg" \
                    " (config.environment_attributes)"

                # terminal_on_life_loss behaves different than EpisodicLifeEnv
                # terminal_on_life_loss resets the env when the first life is loss so the next agent will start fresh
                # EpisodicLifeEnv does not reset the env, so the next agent will continue where the last one died.
                # env = AtariPreprocessing(env, screen_size=32, scale_obs=True, terminal_on_life_loss=False)
                # env = EpisodicLifeEnv(env)
                env = AtariPreprocessing(env,
                                         screen_size=self.config.environment_attributes.screen_size,
                                         scale_obs=self.config.environment_attributes.scale_obs,
                                         terminal_on_life_loss=self.config.environment_attributes.terminal_on_life_loss,
                                         grayscale_obs=self.config.environment_attributes.grayscale_obs)

        if str(env_id).startswith("BipedalWalker"):
            logging.debug("wrapping env in Box2DWalkerWrapper")
            # remove spurious warning "WARN: Box bound precision lowered by casting to float32" during creation
            gym.logger.MIN_LEVEL = gym.logger.ERROR
            env = Box2DWalkerWrapper(env)
            # gym.logger.MIN_LEVEL = level

        if self.config.novelty:
            if self.config.novelty.behavior_source in ['observation', 'action', 'state']:
                logging.debug("wrapping env in BehaviorWrapper")
                env = BehaviorWrapper(env, self.config.novelty.behavior_source,
                                      self.config.novelty.behavioral_interval,
                                      self.config.novelty.behavioral_max_length)

        if self.config.max_steps_per_run:
            logging.debug("wrapping env in MaxStepWrapper")
            env = MaxStepWrapper(env, max_steps=self.config.max_steps_per_run, penalty=self.config.max_steps_penalty)

        if record is not None:
            env = gym.wrappers.Monitor(env, record, force=record_force)

        return env

class ProcEnvHandler(gym.Env):
    """
    This Wrapper scales to observation to values between 0 and 1.
    Additionally it implements a seed method because for reasons unknown it not implemented upstream
    """

    def __init__(self, env_id: str, render: bool, conf: ProcGenEnvAttributesCfg):
        # todo: maybe add env specific configuration, but only after issue #20 has been implemented
        self.env_id = env_id
        self.render_mode = None
        self.conf = conf
        if render:
            self.render_mode = "rgb_array"
        super().__init__()
        self._env = self._make_inner_env(start_level=0)
        self.spec = copy.deepcopy(self._env.spec)  # deep copy to avoid references to inner gym
        self.action_space = self._env.action_space  # use reference, so action_space.seed() works as expected
        self.obs_dtype = np.float16
        self.input_high = 255
        self.current_level = 0
        assert self.input_high == self._env.observation_space.high.min(), "unexpected bounds for input space"
        assert self.input_high == self._env.observation_space.high.max(), "unexpected bounds for input space"
        assert 0 == self._env.observation_space.low.min(), "unexpected bounds for input space"
        assert 0 == self._env.observation_space.low.max(), "unexpected bounds for input space"
        self.observation_space = Box(low=0, high=1,
                                     shape=(self.conf.screen_size, self.conf.screen_size, 3),
                                     dtype=self.obs_dtype)

    def _make_inner_env(self, start_level):
        self.current_level = start_level
        env = gym.make(self.env_id,
                       distribution_mode=self.conf.distribution_mode,
                       use_monochrome_assets=self.conf.use_monochrome_assets,
                       restrict_themes=self.conf.restrict_themes,
                       use_backgrounds=self.conf.use_backgrounds,
                       num_levels=1,
                       start_level=self.current_level,
                       render_mode=self.render_mode
                       )
        return env

    def _transform_ob(self, ob):
        obs = cv2.resize(ob, (self.conf.screen_size, self.conf.screen_size), interpolation=cv2.INTER_AREA)
        return np.asarray(obs, dtype=self.obs_dtype) / 255.0

    def render(self, mode="human", **kwargs):
        frame = self._env.render(mode=self.render_mode, **kwargs)
        cv2.imshow("ProcGen Agent", frame)
        cv2.waitKey(1)

    def step(self, action):
        ob, rew, done, info = self._env.step(action)
        return self._transform_ob(ob), rew, done, info

    def reset(self):
        del self._env
        self._env = self._make_inner_env(start_level=self.current_level + 1)
        return self._transform_ob(self._env.reset())

    def seed(self, seed=0):
        # explicitly delete old env to avoid memory leak
        del self._env
        self._env = self._make_inner_env(start_level=seed)

class MaxStepWrapper(Wrapper):
    def __init__(self, env, max_steps, penalty):
        super().__init__(env)
        self.steps = 0
        self.max_steps = max_steps
        self.penalty = penalty

    def reset(self, **kwargs):
        self.steps = 0
        return super(MaxStepWrapper, self).reset(**kwargs)

    def step(self, action: Union[int, Iterable[int]]):
        self.steps += 1
        ob, rew, done, info = super(MaxStepWrapper, self).step(action)
        if self.steps > self.max_steps:
            logging.debug("step limit reached")
            done = True
            rew += self.penalty
        return ob, rew, done, info

class QbertGlitchlessWrapper(Wrapper):
    def step(self, action: Union[int, Iterable[int]]):
        ob, rew, done, info = super(QbertGlitchlessWrapper, self).step(action)
        if rew == 500 or rew == 525:
            logging.debug("remove reward to avoid luring enemy into abyss")
            rew = 0
        if rew == 300 or rew == 325:
            logging.debug("removed reward from fruit to avoid repetitive behavior")
            rew = 0
        return ob, rew, done, info

class BehaviorWrapper(Wrapper):
    def __init__(self, env, behavior_source, behavioral_interval, behavioral_max_length):
        super().__init__(env)
        self.behavior_source = behavior_source
        self.behavioral_interval = behavioral_interval
        self.behavioral_max_length = behavioral_max_length
        self._reset_compressor()

    def _reset_compressor(self):
        self.compressed_behavior = b''
        self.compressor = BZ2Compressor(2)
        self.step_count = 0
        self.aggregate = None

    def reset(self, **kwargs):
        return super(BehaviorWrapper, self).reset(**kwargs)

    def _aggregate2compressor(self):
        if self.aggregate is not None:
            data_bytes = np.array(self.aggregate).astype(np.float16).tobytes()
            self.compressed_behavior += self.compressor.compress(data_bytes)
            self.aggregate.fill(0)

    def _record(self, data):
        if self.behavioral_interval < 0:
            # in this case  the actual recording is handled by get_compressed_behavior
            self.aggregate = np.array(data)
            return

        if self.aggregate is None:
            self.aggregate = np.array(data, dtype=np.float32)
            self.aggregate.fill(0)

        if self.behavioral_interval > 0:
            self.aggregate += np.array(data) / self.behavioral_interval

        if self.step_count * self.behavioral_interval < self.behavioral_max_length:
            if self.step_count % self.behavioral_interval == 0:
                self._aggregate2compressor()

    def step(self, action: Union[int, Iterable[int]]):
        ob, rew, done, info = super(BehaviorWrapper, self).step(action)
        if self.behavior_source == "observation":
            self._record(ob)
        elif self.behavior_source == "action":
            self._record(action)
        elif self.behavior_source == "state":
            if hasattr(self.env.unwrapped, "model") and "PyMjModel" in str(type(self.env.unwrapped.model)):
                # since float16.max is only around 65500, we need to make it a little smaller
                data = np.array(self.env.unwrapped.sim.data.qpos.flat) * 10e-3
                self._record(data)
            elif self.env.spec.id.endswith("NoFrameskip-v4"):
                # this is an atari env
                # noinspection PyProtectedMember
                self._record(self.env.unwrapped._get_ram())
            else:
                raise RuntimeError('behavior_source=="state" is unsupported for this environment')
        return ob, rew, done, info

    def get_compressed_behavior(self):
        if self.behavioral_interval < 0:
            # special case, where just the last value is used as BC
            self._aggregate2compressor()
        data = self.compressed_behavior + self.compressor.flush()
        self._reset_compressor()
        return data

class Box2DWalkerWrapper(Wrapper):
    """ simple speedup for bad agents, because some agents just stand still indefinitely and waste simulation time"""

    def __init__(self, *narg, **kwargs):
        super(Box2DWalkerWrapper, self).__init__(*narg, **kwargs)
        self.consecutive_non_movement = 0

    def reset(self, **kwargs):
        self.consecutive_non_movement = 0
        return super(Box2DWalkerWrapper, self).reset(**kwargs)

    def step(self, action):
        ob, rew, done, info = super(Box2DWalkerWrapper, self).step(action)

        if ob[2] < 0.0001:
            self.consecutive_non_movement = self.consecutive_non_movement + 1
            if self.consecutive_non_movement > 50:
                done = True
                rew = rew - 100
        else:
            self.consecutive_non_movement = 0

        return ob, rew, done, info

class ReverseWrapper(Wrapper):
    """In reverse-v0 the readhead should be at a specific position when deciding which symbol to write next.
    This Wrapper adds a penalty when the head was in a wrong position, when a symbol was written"""

    def step(self, action):
        ob, rew, done, info = self.env.step(action)

        if done:
            if rew < 0:
                inp_act, out_act, pred = action
                dist = abs(len(self.unwrapped.target)
                           - self.unwrapped.read_head_position
                           - self.unwrapped.write_head_position)
                if dist > 0:
                    rew -= 1. * dist
                if self.unwrapped.MOVEMENTS[inp_act] != "left":
                    rew -= 1

        return ob, rew, done, info


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

class Solution(object):
    def countUnivalSubtrees(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        return self.helper(root)[0]

    def helper(self, node):
        if not node:    return (0, None, True)
        if not node.left and not node.right:    return (1, node.val, True)
        left = self.helper(node.left)
        right = self.helper(node.right)
        if left[2] and right[2] and                         \
            (left[1] == node.val or left[1] == None) and    \
            (right[1] == node.val or right[1] == None):
            return (left[0] + right[0] + 1, node.val, True)
        else:
            return (left[0] + right[0], node.val, False)


# import sys
# import pytesseract
# from difflib import SequenceMatcher as SQ

# try:
#     from PIL import Image
# except ImportError:
#     import Image

# raw_string = pytesseract.image_to_string("/Users/zeraphim/Desktop/aaa.png", lang="eng", config='--psm 7')  # eng or example_model

# print(raw_string)

import os

os.environ["GOOGLE_APPLICATION_CREDENTIALS"]= r"gvision_auth.json"

def detect_document(path):
    """Detects document features in an image."""
    from google.cloud import vision

    client = vision.ImageAnnotatorClient()

    with open(path, "rb") as image_file:
        content = image_file.read()

    image = vision.Image(content=content)

    response = client.document_text_detection(image=image)

    for page in response.full_text_annotation.pages:
        for block in page.blocks:
            print(f"\nBlock confidence: {block.confidence}\n")

            for paragraph in block.paragraphs:
                print("Paragraph confidence: {}".format(paragraph.confidence))

                for word in paragraph.words:
                    word_text = "".join([symbol.text for symbol in word.symbols])
                    print(
                        "Word text: {} (confidence: {})".format(
                            word_text, word.confidence
                        )
                    )

                    for symbol in word.symbols:
                        print(
                            "\tSymbol: {} (confidence: {})".format(
                                symbol.text, symbol.confidence
                            )
                        )

    if response.error.message:
        raise Exception(
            "{}\nFor more info on error messages, check: "
            "https://cloud.google.com/apis/design/errors".format(response.error.message)
        )

# def detect_document(path):
#     """Detects document features in an image."""
#     from google.cloud import vision

#     client = vision.ImageAnnotatorClient()

#     with open(path, "rb") as image_file:
#         content = image_file.read()

#     image = vision.Image(content=content)

#     response = client.document_text_detection(image=image)

#     for page in response.full_text_annotation.pages:
#         for block in page.blocks:
#             for paragraph in block.paragraphs:
#                 for word in paragraph.words:
#                     word_text = "".join([symbol.text for symbol in word.symbols])
#                     print(word_text, end=' ')
#     print()  # Print a newline at the end

img_path = "/Users/zeraphim/Desktop/MKR-Thesis/demo_images/s1.png"

detect_document(img_path)


# 무지의 먹방 라이브
# 회전판에 먹어야 할 N 개의 음식이 있다.
# 각 음식에는 1부터 N 까지 번호가 붙어있으며, 각 음식을 섭취하는데 일정 시간이 소요된다.
# 무지는 다음과 같은 방법으로 음식을 섭취한다.
#
# 무지는 1번 음식부터 먹기 시작하며, 회전판은 번호가 증가하는 순서대로 음식을 무지 앞으로 가져다 놓는다.
# 마지막 번호의 음식을 섭취한 후에는 회전판에 의해 다시 1번 음식이 무지 앞으로 온다.
# 무지는 음식 하나를 1초 동안 섭취한 후 남은 음식은 그대로 두고, 다음 음식을 섭취한다.
# 다음 음식이란, 아직 남은 음식 중 다음으로 섭취해야 할 가장 가까운 번호의 음식을 말한다.
# 회전판이 다음 음식을 무지 앞으로 가져오는데 걸리는 시간은 없다고 가정한다.
# 무지가 먹방을 시작한 지 K 초 후에 네트워크 장애로 인해 방송이 잠시 중단되었다.
# 무지는 네트워크 정상화 후 다시 방송을 이어갈 때, 몇 번 음식부터 섭취해야 하는지를 알고자 한다.
# 각 음식을 모두 먹는데 필요한 시간이 담겨있는 배열 food_times, 네트워크 장애가 발생한 시간 K 초가 매개변수로 주어질 때 몇 번 음식부터 다시 섭취하면 되는지 return 하도록 solution 함수를 완성하라.
#
# 제한사항
# food_times 는 각 음식을 모두 먹는데 필요한 시간이 음식의 번호 순서대로 들어있는 배열이다.
# k 는 방송이 중단된 시간을 나타낸다.
# 만약 더 섭취해야 할 음식이 없다면 -1을 반환하면 된다.
# 정확성 테스트 제한 사항
# food_times 의 길이는 1 이상 2,000 이하이다.
# food_times 의 원소는 1 이상 1,000 이하의 자연수이다.
# k는 1 이상 2,000,000 이하의 자연수이다.
# 효율성 테스트 제한 사항
# food_times 의 길이는 1 이상 200,000 이하이다.
# food_times 의 원소는 1 이상 100,000,000 이하의 자연수이다.
# k는 1 이상 2 x 10^13 이하의 자연수이다.

# 아이디어: 먹는데 시간이 가장 적게드는 음식 순으로 제거
# 우선순위 큐를 이용한다.
import heapq

def solution(food_times, k):
    # 더 섭취해야할 음식이 없으면 -1 리턴
    print(sum(food_times))
    if sum(food_times) <= k:
        return -1
    # 먹는데 시간이 적게드는 음식 순으로 빼야 함으로 우선순위 큐 사용
    q =[]
    for i in range(len(food_times)):
        #음식시간,음식번호 로 우선순위 큐에 삽입
        heapq.heappush(q,(food_times[i], i+1))
    sum_value = 0 # 먹기 위해 사용한 시간
    previous = 0    # 직전에 다 먹은 음식 시간
    length = len(food_times)        # 남은 음식의 개수

    while sum_value +((q[0][0] - previous)*length) <= k:
        now = heapq.heappop(q)[0]
        sum_value += (now - previous)*length
        length -= 1 #다먹은 음식 제외
        previous = now  # 이전 음식 시간 재설정
    # 남은 음식 중에서 몇 번째 음식인지 확인하여 출력
    result = sorted(q, key = lambda x:x[1]) #음식의 번호 기준으로 정렬
    return result[(k - sum_value) % length][1]

food_times = [3,1,2]
print(solution(food_times,5))


from datetime import datetime
from decimal import Decimal

import csv
import sys
import os

wd = os.getcwd()
sys.path.append(wd)

from cryptocoins.models.forex_pairs_history import ForexPairsHistory
from cryptocoins.utils import setup_logging

if len(sys.argv) < 3:
    raise ValueError('Usage: import file_name symbol')

file_path = sys.argv[1]
to_symbol = sys.argv[2]

logger = setup_logging()

if __name__ == "__main__":
    logger.info(f"IMPORTING FROM {file_path}, SYMBOL {to_symbol}")
    data = []
    with open(file_path, 'r') as csv_file:
        reader = csv.reader(csv_file)
        for i in range(5):
            next(reader)
        for row in reader:
            if len(row) < 2:
                continue
            if not row[1]:
                continue
            timestamp_epoc = datetime.strptime(row[0], '%d/%m/%y').timestamp()
            price_dollars = Decimal(row[1].replace(',', ''))
            model_params = {'from_symbol': 'USD',
                            'to_symbol': to_symbol,
                            'price': Decimal(1.0) / price_dollars,
                            'timestamp_epoc': timestamp_epoc}
            data.append(model_params)
    ForexPairsHistory.create_from_model_params(data)


import datetime

from aiogram import Router, Bot, F
from aiogram.filters import Command, Text
from aiogram.types import CallbackQuery, Message, ChatInviteLink, \
    InlineKeyboardButton

from aiogram.fsm.context import FSMContext
from aiogram.utils.deep_linking import create_start_link, decode_payload
from aiogram.utils.keyboard import InlineKeyboardBuilder

from config_data.conf import LOGGING_CONFIG, conf, tz
import logging.config

from keyboards.keyboards import start_kb, custom_kb
from lexicon.lexicon import LEXICON_RU
from services.db_func import create_user, check_user, get_channels, \
    get_user_subscribe_text, update_subscribe
from services.referal import add_referal_count

logging.config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger('bot_logger')
err_log = logging.getLogger('errors_logger')

router: Router = Router()

@router.message(Command(commands=["start"]))
async def process_start_command(message: Message, state: FSMContext, bot: Bot):
    await state.clear()
    referal = message.text[7:]
    new_user = create_user(message.from_user, referal)
    if new_user:
        reference = str(decode_payload(referal))
        if reference and reference != new_user.tg_id:
            add_referal_count(reference)
        await message.answer(LEXICON_RU['start_text'], reply_markup=start_kb)
    else:
        await message.answer(LEXICON_RU['start_text'], reply_markup=start_kb)

@router.callback_query(Text(text='demo'))
async def get_demo_info(callback: CallbackQuery, state: FSMContext, bot: Bot):
    text = LEXICON_RU['demo_text']
    await callback.message.answer(text, reply_markup=custom_kb(1, {'Получить пробный доступ': 'get_demo'}))
    await callback.message.delete()

@router.callback_query(Text(text='get_demo'))
async def get_demo(callback: CallbackQuery, state: FSMContext, bot: Bot):
    user = check_user(callback.from_user.id)
    if user.demo_used:
        await callback.message.answer('Вы уже использовали демо-доступ')
    else:
        user.set('demo_used', 1)
        channels = get_channels()
        for channel in channels:
            link: ChatInviteLink = await bot.create_chat_invite_link(
                chat_id=channel.channel_id,
                creates_join_request=False,
                expire_date=(datetime.datetime.now(tz=conf.tg_bot.TIMEZONE) + datetime.timedelta(hours=24)),
                member_limit=1)
            text = LEXICON_RU['get_demo'].format(channel.title)
            url_button_1 = InlineKeyboardButton(
                text=f'Перейти на {channel.title}',
                url=f'{link.invite_link}')
            kb_builder: InlineKeyboardBuilder = InlineKeyboardBuilder()
            kb_builder.row(url_button_1)
            keyboard = kb_builder.as_markup()
            await callback.message.answer(text, reply_markup=keyboard)
            await bot.unban_chat_member(chat_id=channel.channel_id,
                                        user_id=callback.from_user.id,
                                        only_if_banned=True)
            # user.set('demo_expire', link.expire_date)
            update_subscribe(user, channel.id, 1)

    await callback.message.delete()

@router.callback_query(Text(text='check_expire'))
async def check_expire(callback: CallbackQuery, state: FSMContext, bot: Bot):
    subscribes_text = get_user_subscribe_text(callback.from_user.id)
    await callback.message.answer(subscribes_text)

@router.callback_query(Text(text='support'))
async def support(callback: CallbackQuery, state: FSMContext, bot: Bot):
    text = LEXICON_RU['support_text']
    await callback.message.answer(text, reply_markup=start_kb)
    await callback.message.delete()


import os
import json
import numpy as np

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

from core.laserMarker import JCZLaserMarker, Pen, Hatch
from core.constants import JCZError

from ui.UiLaser import Ui_Laser

class RedLightThread(QThread):
    def __init__(self, laser, name="", showContour=True) -> None:
        super().__init__()
        self.name = name
        self.laser = laser
        self.showContour = showContour

        self._isRunning = False

    def start(self, priority=QThread.InheritPriority) -> None:
        self._isRunning = True
        super().start(priority)

    def quit(self) -> None:
        self._isRunning = False

    def run(self) -> None:
        while self._isRunning:
            self.laser.redLightMarkByEnt(self.name, self.showContour)
            self.msleep(1)

        self.quit()

class Window(Ui_Laser, QWidget):
    def __init__(self) -> None:
        super().__init__()
        self.setupUi(self)
        self.setWindowTitle("LaserDemo")

        QDir.setCurrent("./bin/")
        self.laser = JCZLaserMarker(os.path.abspath( "./MarkEzd.dll" ))
        self.laser.loadDLL()
        self.laser.sigError.connect(self.onError)

        self.isOpen = False
        self.startTimer(500)
        self.redThread = RedLightThread(self.laser)

        # bind signal
        self.bnOpen.clicked.connect(self.onOpen)
        self.bnSave.clicked.connect(self.onSave)
        self.bnInit.clicked.connect(self.onInit)
        self.bnClose.clicked.connect(self.onClose)
        self.bnSetting.clicked.connect(self.onDevConfig)

        self.bnMirrorMove.clicked.connect(self.onMirrorMove)

        self.bnEntMark.clicked.connect(self.onMark)
        self.bnEntRedLight.clicked.connect(self.onRedLight)
        self.bnEntChangeText.clicked.connect(self.onChangeText)
        self.bnEntMove.clicked.connect(self.onMove)
        self.bnEntMoveSet.clicked.connect(self.onMoveSet)
        self.bnEntGetHatch.clicked.connect(self.onGetHatch)
        self.bnEntSetHatch.clicked.connect(self.onSetHatch)
        self.bnEntSetPen.clicked.connect(self.onSetPen)
        self.bnEntGetPen.clicked.connect(self.onGetPen)

            # comboBox
        self.cbEnt.textActivated.connect(self.onCombo)

    def onError(self, methodName, e: JCZError):
        print("OnError:", [methodName, e.code, e.desc, e.solution])

    def onCombo(self, name):
        rect,z = self.laser.getEntSize(name)
        self.lbEntRect.setText(f"{rect}")

    def onOpen(self):
        if not self.isOpen: return
        file, _ = QFileDialog.getOpenFileName(filter="Ezd File (*.ezd)")
        if file:
            self.laser.loadEzdFile(file)

            n = self.laser.getEntityCount()
            for i in range(n):
                name = self.laser.getEntName(i)
                self.cbEnt.addItem(name)

    def onSave(self):
        self.laser.saveEzdFile(self.laser.ezdFile)

    def onInit(self):
        self.isOpen = self.laser.initial(False)

    def onClose(self):
        self.isOpen = False
        self.laser.close()

    def onDevConfig(self):
        self.laser.setDeviceConfig()

    def onMirrorMove(self):
        x, y = self.leMirrorX.text(), self.leMirrorY.text()
        self.laser.gotoPos(float(x), float(y))

    def onMark(self):
        name = self.cbEnt.currentText()
        self.laser.markEntity(name)

    def onRedLight(self):
        name = self.cbEnt.currentText()
        self.redThread.name = name
        if self.redThread.isRunning():
            self.redThread.quit()
        else:
            self.redThread.start()

    def onChangeText(self):
        name = self.cbEnt.currentText()
        newText = self.leEntText.text()
        self.laser.changeTextByName(name, newText)

    def onMove(self):
        name = self.cbEnt.currentText()
        x, y = self.leEntX.text(), self.leEntY.text()
        self.laser.moveEnt(name, float(x), float(y))

    def onMoveSet(self):
        name = self.cbEnt.currentText()
        x, y = self.leEntX.text(), self.leEntY.text()
        w, h = self.leEntW.text(), self.leEntH.text()
        self.laser.setSizeAndMove(name, float(x), float(y), float(w), float(h))

    def onGetHatch(self):
        name = self.cbEnt.currentText()
        hatch = self.laser.getHatchEntParam2(Hatch(name))
        self.tePara.setText(json.dumps(hatch.asDict(), indent=4))

    def onGetPen(self):
        name = self.cbEnt.currentText()
        n = self.laser.getPenNumberFromEnt(name)
        pen = self.laser.getPenParam(Pen(n))
        self.tePara.setText(json.dumps(pen.asDict(), indent=4))

    def onSetHatch(self):
        hatchDict = json.loads(self.tePara.toPlainText())
        self.laser.setHatchEntParam2(Hatch.fromDict(hatchDict))

    def onSetPen(self):
        penDict = json.loads(self.tePara.toPlainText())
        self.laser.setPenParam(Pen.fromDict(penDict))

    def timerEvent(self, e: 'QTimerEvent') -> None:
        if self.isOpen == False : return

        ## img
        s = self.gvPreview.sceneRect().size()
        img = self.laser.getPrevBitmap(s.width(), s.height())
        img = self.gvPreview.scene().addPixmap(img)
        img.setPos(-200, -200)

        ## pos
        x, y = self.laser.getCurCoor()
        self.lbPos.setText(f"({x},{y})")

        ## is marking
        v = self.laser.isMarking()
        self.lsMarking.setText(str(v))

        ## speed
        v = self.laser.getFlySpeed()
        self.lbSpeed.setText(f"{v}")

        ## ent count
        v = self.laser.getEntityCount()
        self.lbCount.setText(f"{v}")

        # ent Rect
        name = self.cbEnt.currentText()
        rect,z = self.laser.getEntSize(name)
        self.lbEntRect.setText(f"{rect}")

        # last markTime
        hour, min, sec, miliSec = self.laser.getLastMarkTime()
        self.lbMarkTime.setText(f"{hour}:{min}:{sec}.{miliSec}")

app = QApplication([])
win  = Window()
win.show()
app.exec()


from pymongo import MongoClient

from kobject import KObject

class KTimer(KObject):
    def __init__(self, name, char, onetime, start_time,
                 callback, duration, *args):
        KObject.__init__(self, _id=None)

        self.name = name
        self.args = args
        self.onetime = onetime
        self.callback = callback
        self.start_time = start_time
        self.duration = duration
        self.char = char
        self._id = self.state_save()

    def die(self):
        self.callback(self)

    def state_save(self):
        client = MongoClient('mongodb://192.168.0.107:27017/')
        db = client.kmud
        collection = db.timers

        timer = {'char': self.char._id,
                 'duration': self.duration,
                 'start': self.start_time,
                 'onetime': self.onetime,
                 'args': self.args}

        return collection.insert_one(timer).inserted_id


import random
from matplotlib import pyplot as plt
import numpy as np

def determine_if_mandelbrot(iterations, imaginary_number):
    z = imaginary_number
    iteration = 0
    while abs(z.real) < 2 and abs(z.imag) < 2 and iteration < iterations:
        z = z**2 + imaginary_number
        iteration += 1
    if iteration == iterations:
        boolean = 'T'
    else:
        boolean = 'F'
    return [imaginary_number, iteration, boolean]

realRange = [-2, 2]
imagRange = [-2, 2]
n = 800000
iterations = 1000

realGrid = np.arange(realRange[0], realRange[1], (realRange[1]-realRange[0])*1.0/n)
if len(realGrid) == n:
	realGrid = np.append(realGrid, realRange[1])
imagGrid = np.arange(imagRange[0], imagRange[1], (imagRange[1]-imagRange[0])*1.0/n)
if len(imagGrid) == n:
	imagGrid = np.append(imagGrid, imagRange[1])

realOrder = random.sample(np.arange(n), n)
imagOrder = random.sample(np.arange(n), n)

all_points = []
max = -2
for i in range(n):

	point = random.uniform(realGrid[realOrder[i]], realGrid[realOrder[i] + 1]) + 1j* random.uniform(imagGrid[imagOrder[i]], imagGrid[imagOrder[i]+1])
	all_points.append(determine_if_mandelbrot(iterations, point))

hit = 0
x = []
y = []
color = []

for result in all_points:
	if result[2] == 'T':
		hit += 1
	x.append(result[0].real)
	y.append(result[0].imag)
	color.append(result[1])

plt.scatter(x,y, s=1, c=color)
plt.ylim(-2,2)
plt.xlim(-2,2)
print(hit*1.0/n * 16.0)
plt.show()