import argparse
from collections import defaultdict
import os
from pathlib import Path
import pandas as pd
import sqlalchemy
import glob

import csv

import io

import logging

parser = argparse.ArgumentParser()
dtypes: defaultdict = defaultdict(lambda: str)

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.WARNING)
loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict]
for logger in loggers:
    logger.setLevel(logging.WARNING)

def make_tablename(filename):
    return f"census_" + Path(filename).stem

def main():
    parser.add_argument("--path", type=str, required=True)

    args = parser.parse_args()
    print(args)
    engine = sqlalchemy.create_engine(
        "postgresql://postgres@localhost/postgres"
    )

    files = glob.glob(f'{args.path}/*.txt')

    for txtfile in files:
        connection = engine.raw_connection()
        cursor = connection.cursor()
        tablename = Path(txtfile).stem
        print(f'Dropping {tablename}')
        cursor.execute(f"DROP TABLE IF EXISTS IF EXISTS {make_tablename(tablename)}")

    for txtfile in files:
        tablename = Path(txtfile).stem
        print(f'Loading {txtfile} / {make_tablename(tablename)}')
        #file = open(f"{txtfile}", "rb")
        #file_bytes = file.read()
        #file.close()
        for chunk in pd.read_csv(
            #io.BytesIO(file_bytes),
            txtfile,
            delimiter="|",
            dtype=dtypes,
            on_bad_lines="skip",
            engine="python",
            quoting=csv.QUOTE_NONE,
            encoding="utf-8",
            chunksize=10000
        ):
            chunk.to_sql(name=make_tablename(tablename),
                        if_exists='append',
                         con=engine)

if __name__ in "__main__":
    main()


from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from santhob.preprocessing import ImageToArrayPreProcessor
from santhob.preprocessing import SimplePreprocessor
from santhob.datasets import SimpleDatasetLoader
from santhob.nn.cnn import ShallowNet
from keras.optimizers import SGD
from imutils import paths
import matplotlib.pyplot as plt
import numpy as np
import argparse
from tqdm import tqdm
import os

DATADIR = "/home/guru/Desktop/pyimagebook/chapter12/santhob/datasets"

CATEGORIES = ["dog", "cat","panda"]

for category in CATEGORIES:  # do dogs and cats
    path = os.path.join(DATADIR,category)  # create path to dogs and cats
    for img in os.listdir(path):  # iterate over each image per dogs and cats
        img_array = cv2.imread(os.path.join(path,img) ,cv2.IMREAD_GRAYSCALE)  # convert to array
        plt.imshow(img_array, cmap='gray')  # graph it
        plt.show()  # display!

        break  # we just want one for now so break
    break

#grab the list of images that we are describing

print("Images are loading...")
imagePaths = list(paths.list_images(args["dataset"]))
#imagepaths = list(paths.list_images(args['dataset']))

#initialize the image preprocessor

sp=SimplePreprocessor(32,32)
iap=ImageToArrayPreProcessor()

#load the dataset from disk and scale to range between [0,1]

sd1=SimpleDatasetLoader(preprocessors=[sp,iap])
(data,labels)=sd1.load(imagePaths,verbose=500)

data=data.astype("float") / 255.0

#partition the dataser to train and test dataset

(trainx,testx,trainy,testy)=train_test_split(data,labels,test_size=0.25,random_state=42)

#convert the labels from integer to vectors

trainy=LabelBinarizer().fit_transform(trainy)
testy=LabelBinarizer().fit_transform(testy)

#initialize the model and optimizer

print("compiling the model")

opt=SGD(lr=0.001)
model=ShallowNet.build(width=32,height=32,depth=3,classes=3)
model.compile(loss="categorical_crossentropy",optimizer=opt,metrics=['accuracy'])

print("train the network")

H=model.fit(trainx,trainy,validation_data=(testx,testy),epochs=10,verbose=1)

#evaluate the model

print("evaluating the model....")
predictions=model.predict(testx)
print(classification_report(testy.argmax(axis=1),predictions.argmax(axis=1),target_names=["cat","dog","panda"]))

# plot the training loss and accuracy
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, 10), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, 10), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, 10), H.history["acc"], label="train_acc")
plt.plot(np.arange(0, 10), H.history["val_acc"], label="val_acc")
plt.title("Training Loss and Accuracy")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend()
plt.show()


# Треугольник тип
import sys
a = int(input("a = "))
b = int(input("b = "))
c = int(input("c = "))

if (a + b < c) or (a + c < b) or (c+ b < a):
	print("Такого треугольника не сущствует")
	sys.exit(0)

if (a == b == c):
	print("Треугольник равносторонний")
elif (a != b) and (a != c) and (c != b):
	print("Треугольник разносторонний")
else:
	print("Треугольник равнобедренный")


import pygame, pytmx, pyscroll
import mapscript
import transition
import ClassPG as PG
import valeurs
import Ennemis
import random
import fight

class Map:
    def __init__(self, name, walls, objecte, group, tmx_data, mapdata, mapobject, ennemis=[]):
        self.name = name
        self.walls = walls
        self.object = objecte
        self.group = group
        self.tmx_data = tmx_data
        self.map_data = mapdata
        self.mapobject = mapobject
        self.ennemis = ennemis

class Tuile(pygame.sprite.Sprite):
    def __init__(self, x, y, image, tile_size):
        super(Tuile, self).__init__()
        self.name = "tile"
        self.rect = pygame.Rect(x * tile_size, y * tile_size, tile_size, tile_size)
        self.image = image
        self.type = "tile"

class Mapmanager:
    def __init__(self, screen, player):
        self.mapobject = None
        self.maps = {}
        self.basemap = "Lobby"
        self.load_localtion()
        self.current_map = self.basemap
        self.screen = screen
        self.player = player

        self.loading = False  # Load from the file
        self.seecollision = False

        self.maps_dico = {}

        self.all_register()

        self.current_map = self.basemap

        self.changemap(self.basemap, "PlayerPos")

        self.Animation = transition.Animation(3)

        self.song = {}
        self.song['door'] = PG.son("../song/Ingame/door.mp3", "song")
        self.song['chest'] = PG.son("../song/Ingame/chest.mp3", "song")
        self.song['aie'] = PG.son("../song/Ingame/aie.mp3", "song")

        self.teleport_player("PlayerPos")

    def all_register(self):
        self.register_map("Lobby", mapscript.lobby(self))
        self.register_map("Grotte", mapscript.Grotte(self))
        self.register_map("Village", mapscript.Village(self))
        self.register_map("Maison", mapscript.Maison(self))
        self.register_map("Puit", mapscript.Puit(self))
        self.register_map("Foret", mapscript.Foret(self))
        self.register_map("Maison_Foret", mapscript.Maison_Foret(self))
        self.register_map("Plaine", mapscript.Plaine(self))
        self.register_map("MaisonPêcheur", mapscript.MaisonPêcheur(self))
        self.register_map("Plage", mapscript.Plage(self))
        self.register_map("MaisonPlage", mapscript.MaisonPlage(self))

        self.zoomIO(1.6*(self.screen.get_size()[0] / 1280))

    def reload_maps(self):
        self.register_map(self.current_map, self.maps_dico[self.current_map])
        self.zoomIO(1.6 * (self.screen.get_size()[0] / 1280))
        print('reload maps')

    def alltiles(self):
        self.alltiles_d = {}
        self.alltiles_d["Base"] = pytmx.util_pygame.load_pygame("../img/tile/alltiles.tmx", load_all_tiles=True)
        self.alltiles_d["Base2"] = pytmx.util_pygame.load_pygame("../img/tile/Base2Tiles.tmx", load_all_tiles=True)
        self.alltiles_d["Base3"] = pytmx.util_pygame.load_pygame("../img/tile/TX Props.tmx", load_all_tiles=True)

    def register_map(self, name, mapobject):
        self.current_map = name
        self.maps_dico[name] = mapobject
        tmx = pytmx.util_pygame.load_pygame(f"../img/tile/{name}.tmx", load_all_tiles=True)
        self.alltiles()
        mapdata = pyscroll.data.TiledMapData(tmx)
        map_layer = pyscroll.orthographic.BufferedRenderer(mapdata, self.screen.get_size())
        map_layer.zoom = 1.6 * (self.screen.get_size()[0] / 1280)
        self.walls = []
        objects_input = {}

        player_layer = tmx.layers
        liste = []
        for element in range(len(player_layer)):
            liste.append(player_layer[element].name)
            if player_layer[element].name == "PlayerCalque":
                u = element
        group = pyscroll.PyscrollGroup(map_layer=map_layer, default_layer=int(u))

        for obj in tmx.objects:  # Ajout des collsion dans des listes
            if obj.type == "Collision":
                self.walls.append(pygame.Rect(obj.x, obj.y, obj.width, obj.height))
                if self.seecollision: group.add(
                    PG.img("../img/menu/background.jpg", obj.x, obj.y, obj.width, obj.height, False))
            if obj.type != "Collision":
                objects_input[obj.id] = [obj, pygame.Rect(obj.x, obj.y, obj.width, obj.height), obj.type]
                if self.seecollision: group.add(
                    PG.img("../img/img.inv/case.png", obj.x, obj.y, obj.width, obj.height, False))

                # Créer un nombre aléatoire d'ennemis dans un emplacement aléatoire dans une zone donnée et les ajoutes dans le group de la map.
        ennemis = []
        for element in tmx.objects:
            if element.type == "Ennemi":
                for i in range(element.properties['nbennemis']):
                    id = int(random.choice(element.properties['Ennemis'].split(",")))
                    lvl = random.randint(int(element.properties['level'].split(",")[0]),
                                         int(element.properties['level'].split(",")[-1]))
                    x = int(random.randint(int(element.x), int(element.x + element.width)))
                    y = int(random.randint(int(element.y), int(element.y + element.height)))
                    a = Ennemis.Ennemy(id, lvl, x, y)
                    group.add(a)
                    ennemis.append(a)

        # groupe contenant le joueur et la map
        group.add(self.player)
        group.change_layer(self.player, u)

        self.maps[name] = Map(name, self.walls, objects_input, group, tmx, mapdata, mapobject, ennemis)
        mapobject.load()
        self.actionnb = mapobject.actionb

    def reloadmap(self):

        pygame.display.flip()

    def zoomIO(self, level):
        self.maps[self.current_map].zoom = level

    def save_all(self, name):
        self.maps[name].allmap.save_player_info()

    def save(self, name):
        """
        Il écrit la carte actuelle et le dictionnaire actionb dans un fichier

        :param name: Le nom du fichier de sauvegarde
        """
        print("savegarde de la map : ", name)
        w = open(valeurs.valeur.save_l + f"/save/{name}.txt", "w")
        w.write(self.current_map + "\n")

        for i in self.maps[self.current_map].mapobject.actionb.keys():
            w.write(str(i) + ": " + str(self.maps[self.current_map].mapobject.actionb[i]) + "\n")
        w.close()

    def load(self, name):
        try:
            w = open(valeurs.valeur.save_l + f"/save/{name}.txt", "r")
        except FileNotFoundError:
            open(valeurs.valeur.save_l + f"/save/{name}.txt", "w")
            w = open(valeurs.valeur.save_l + f"/save/{name}.txt", "r")
        liste = w.readlines()
        a = {}
        for i in liste:
            try:
                a[i.split(":")[0]] = eval(i.split(":")[1])
            except IndexError:
                pass

        if a != {}:
            return a
        else:
            return None

    def load_localtion(self):
        """ Fonction qui change la location du spawnpoint"""
        a = open(valeurs.valeur.save_l + "/save/sauvegarde.txt", "r")
        liste = a.readlines()
        try:
            self.basemap = liste[0].split(": ")[1].strip()
        except IndexError:
            self.basemap = "Lobby"
        return self.basemap

    def get_map(self):
        return self.maps[self.current_map]

    def get_group(self):
        return self.get_map().group

    def get_walls(self):
        return self.get_map().walls

    def get_objectinp(self, type, returntype="all"):
        """
        Fonction qui renvoie une liste qui renvoie les objet d'un certain type
        """
        l = []
        if returntype == "rect":
            for i in self.get_map().object.keys():
                if self.get_map().object[i][2] == type:
                    l.append(self.get_map().object[i][1])
        if returntype == "object":
            for i in self.get_map().object.keys():
                if self.get_map().object[i][2] == type:
                    l.append(self.get_map().object[i][0])
        if returntype == "all":
            for i in self.get_map().object.keys():
                if self.get_map().object[i][2] == type:
                    l.append(self.get_map().object[i])
        return l

    def get_allobject(self, returntype="all"):
        """
        Fonction qui renvoie tout les objects
        :param returntype:
        :return:
            returntype = rect : return pygame.Rect
            returntype = object : return object
            returntype = all : [object, pygame.Rect]
        """
        l = []
        if returntype == "rect":
            for i in self.get_map().object.keys():
                l.append(self.get_map().object[i][1])
        if returntype == "object":
            for i in self.get_map().object.keys():
                l.append(self.get_map().object[i][0])
        if returntype == "all":
            for i in self.get_map().object.keys():
                l.append(self.get_map().object[i])
        return l

    def get_object(self, id):
        return self.get_map().tmx_data.get_object_by_name(id)

    def teleport_player(self, name):
        point = self.get_object(name)
        self.player.rect.centerx, self.player.rect.centery = point.x, point.y
        self.player.save_old_location()

    def draw(self):
        self.get_group().draw(self.screen)
        self.get_group().center(self.player.rect.center)

    def updating(self):
        self.maps[self.current_map].group.update()
        self.collision()

        try:
            self.maps[self.current_map].mapobject.update()
        except KeyError:
            pass

    def collision(self):
        for i in self.get_group().sprites():
            if i.type == 'Joueur':
                if i.feet.collidelist(
                        self.get_walls()) > -1:  # si les pieds du joueurs entre en collision avec un objet
                    i.moveback()
                player = i
                self.maps[self.current_map].mapobject.collision(i)

        for i3 in self.maps[self.current_map].ennemis:
            if i3.rect.colliderect(player.rect):
                fightt = fight.fight(self.player, i3.id,i3.lvl)
                fightt.image(self.screen)
                self.player.allinputoff(False)
                if fightt.FightScreen() in ["Player", "Fuite"]:
                    self.maps[self.current_map].ennemis.remove(i3)
                    self.get_group().remove(i3)
                else:
                    self.changemap(self.load_localtion(), "PlayerPos")
                    self.player.hp = self.player.hpmax
                self.player.allinputoff(True)
                self.player.pressed[pygame.K_l] = False

    def checkcollision(self, x, y):
        for element in self.get_walls():
            if element.collidepoint((x, y)):
                return True

    def changemap(self, name, teleportpoint):
        """
        Change la map actuel
        :param name: str
        :param teleportpoint: str
        :return: Nothing
        """
        self.current_map = name
        self.mapobject = self.maps[name].mapobject
        self.teleport_player(teleportpoint)

    def remove_collision(self, obj):
        self.maps[self.current_map].walls.remove(pygame.Rect(obj.x, obj.y, obj.width, obj.height))

    """def remove_inputaction(self, obj):
        self.maps[self.current_map].object"""

    def add_collision_from_obj(self, obj):
        self.maps[self.current_map].walls.append(pygame.Rect(obj.x, obj.y, obj.width, obj.height))

    def add_collision_from_rect(self, rect):
        self.maps[self.current_map].walls.append(rect)

    def add_image_to_draw(self, file, x, y, w, h):
        img = PG.img(file, x, y, w, h, True)
        self.maps[self.current_map].group.add(img)

    def add_element_to_draw_obj(self, name: str, gid: int, x: int, y: int, layer: int):
        img = self.alltiles_d[name].get_tile_image_by_gid(gid + 1)
        self.maps[self.current_map].group.add(Tuile(x, y, img, 32), layer=layer)

    def add_class_to_draw_obj(self, object):
        self.maps[self.current_map].group

    def remove_element_to_draw_obj(self, x, y):
        try:
            for element in self.maps[self.current_map].group:
                if element.name == "tile":
                    if element.rect.x == x * 32 and element.rect.y == y * 32:
                        self.maps[self.current_map].group.remove(element)
        except AttributeError:
            pass

    def set_layer_visible(self, layer, Visible):
        """
        Met le layer en visible ou non
        :param layer: str
        :param Visible: bool
        :return: Nothing
        """
        self.maps[self.current_map].tmx_data.get_layer_by_name(layer).visible = Visible

    def get_layer_by_name(self, name):
        return self.get_map().tmx_data.get_layer_by_name(name)


import subprocess
import json

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from pandas import DataFrame, read_csv
from numpy import log
#from statistics import mean

from datetime import datetime
import time

from keras.models import Sequential, load_model
from keras.layers import LSTM, Dense, Dropout
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.normalization import BatchNormalization
from keras.callbacks import EarlyStopping, TensorBoard, ReduceLROnPlateau, CSVLogger

log_dir = "2-layer-32-32-LeakyReLU-update"

early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=0, mode='auto')
#logger = TensorBoard(log_dir='log/{}'.format(log_dir), write_graph=True, histogram_freq=1, batch_size=1)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=0.001)
csv_logger = CSVLogger('training-2-layer-32-32-LeakyReLU-update.csv')

previous_df = read_csv('memoryUsed9-final.csv')
previous_df.columns = ['timestamp', 'value']
previous_df.set_index('timestamp', inplace=True)
previous_df.dropna(inplace=True)
print(previous_df.head())
print(previous_df.shape)
previous_values = previous_df.values

last_input_value = previous_values[-2]
prev_value = previous_values[-1]

def difference_2(dataset, interval=1):
    print(dataset.ndim)
    print(dataset.shape)
    diff = np.ndarray(shape=(dataset.shape[0]-interval, dataset.shape[1]), dtype=float)
    for i in range(interval, len(dataset)):
        for j in range(dataset.shape[1]):
            diff[i-1][j] = dataset[i][j] - dataset[i - interval][j]
    return diff

diff_values = difference_2(previous_values)
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(diff_values)

min_val = scaler.data_min_
max_val = scaler.data_max_

def mean(nums):
    return sum(nums, 0.0) / len(nums)

def streaming():
    counter = 0
    total_instance = 0
    total_mem = list()
    mem_max = 0
    while(counter != 5):
        print("in streaming loop with counter and time in minutes", counter, datetime.now().minute%5)
        instance_stat = subprocess.check_output("cf curl v2/apps/3bbffff8-6834-4383-8140-cd223d9927ee/stats | jq 'with_entries(.value = .value.stats)'", shell=True)
        instance_stat_json = json.loads(instance_stat)
        mem_quota = list()
        instances = list()
        mem_usages = list()
        #mem = 0
        for instance in instance_stat_json:
            instances.append(int(instance))
            mem_usages.append(instance_stat_json[instance]['usage']['mem'])
            mem_quota.append(instance_stat_json[instance]['mem_quota'])
            #mem = mem + int(instance)*instance_stat_json[instance]['usage']['mem']
        total_mem.append(sum(mem_usages))
        total_instance = len(instances)
        mem_max = max(mem_quota)
        # Wait for 60 seconds
        time.sleep(60)
        counter = counter+1
        if datetime.now().minute % 5 == 0:
            break
    return mean(total_mem), total_instance

def difference(data, prev_val):
    return data-prev_value

def scale_dataset(data, min_val, max_val):
    return (data - min_val)/(max_val - min_val)

def inverse_scale(data, min_val, max_val):
    return data*(max_val - min_val) + min_val

def inverse_diff(data, last_val):
    return data + last_val

def predict(data):
    print("in prediction function with data", data)
    diff_data = difference(data)
    scaled_data = scale_dataset(diff_data)
    train_X = scaled_data.reshape(scaled_data.shape[0], 1, 1)
    yhat= model.predict(train_X, batch_size=1)
    yhat = yhat.reshape(yhat.shape[0], yhat.shape[2])
    yhat_inv = inverse_scale(yhat)
    yhat_final = inverse_diff(yhat_inv, last_value)
    return yhat_final

def scale_decision(memory, instance):
    print("scaling decision function with memory and instance", memory, instance)

def update(data):
    print("update model with next data", data)

#model = load_model('mem0_5-stack-2-32-LeakyReLU.h5')

flag=1
# date_time = datetime.now()
# year, month, day = date_time.year, date_time.month, date_time.day
# hour, minute = date_time.hour, date_time.minute
# rem = minute % 5
# sleep 5-rem
print("streaming starting from : ", datetime.now())
c=0
while(flag):
    print("in infinite loop with iteration: ", c)
    total_mem, instance_count =  streaming()
    predict(total_mem)
    scale_decision(total_mem, instance_count)
    update(total_mem)
    c = c+1

# history = model.fit(train_X, train_y, epochs=100, batch_size=1, validation_data=(test_X, test_y), verbose=2, shuffle=False, callbacks=[logger, reduce_lr, csv_logger])

# mem = subprocess.check_output("cf curl v2/apps/3bbffff8-6834-4383-8140-cd223d9927ee/stats | jq 'with_entries(.value = .value.stats.usage.mem)'", shell=True)
# json_mem = json.loads(mem)
# print(json_mem)
# instances = list()
# mem_usages = list()
# for instance in json_mem:
#     print(instance, json_mem[instance])
#     instances.append(int(instance))
#     mem_usages.append(json_mem[instance])

# print(instances)
# print(mem_usages)

# total_instance = len(instances)
# total_mem = sum(mem_usages)
# mem_per_instance = total_mem/total_instance

# print(total_instance)
# print(total_mem)
# print(mem_per_instance)

# instance_stat = subprocess.check_output("cf curl v2/apps/3bbffff8-6834-4383-8140-cd223d9927ee/stats | jq 'with_entries(.value = .value.stats)'", shell=True)
# instance_stat_json = json.loads(instance_stat)
# mem_quota = list()
# instances = list()
# mem_usages = list()
# for instance in instance_stat_json:
#     #print("instance", instance)
#     #print("content", json_mem[instance])
#     #print("memory quota", instance_stat_json[instance]['mem_quota'])
#     #print("memory usage of the instance", instance_stat_json[instance]['usage']['mem'])
#     instances.append(int(instance))
#     mem_usages.append(instance_stat_json[instance]['usage']['mem'])
#     mem_quota.append(instance_stat_json[instance]['mem_quota'])

# print("instances list", instances)
# print("memory quota list", mem_quota)
# print("memory usage of the instances", mem_usages)

# total_instance = len(instances)
# total_mem = sum(mem_usages)
# mem_per_instance = total_mem/total_instance

# print("toatal number of instances of the app", total_instance)
# print("total memory consumption by all the app instances", total_mem)
# print("average memory consumption per app instance", mem_per_instance)


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

    def __repr__(self):
        layers = []
        def parse_layer(nodes):
            next_layer = []
            layer_val = ''
            for node in nodes:
                if node is None:
                    layer_val += 'N '
                    continue
                layer_val += str(node.val)
                layer_val += ' '
                next_layer.append(node.left)
                next_layer.append(node.right)
            layers.append(layer_val)
            return next_layer

        nodes = [self]
        while nodes:
            nodes = parse_layer(nodes)

        p = ''
        for layer in layers[:-1]:
            p += layer
            p += '\n'
        return p

    def build(self, l):
        def add_leaf(node, i):
            if len(l) > i + 1 and l[i+1]:
                node.left = TreeNode(l[i+1])
            if len(l) > i + 2 and l[i+2]:
                node.right = TreeNode(l[i+2])
            return node.left, node.right, i + 2

        def add_layer(nodes, i):
            next_layer = []
            for node in nodes:
                left, right, i = add_leaf(node, i)
                if left: next_layer.append(left)
                if right: next_layer.append(right)
            return next_layer, i

        nodes = [self]
        i = 0
        while i < len(l):
            nodes, i = add_layer(nodes, i)

def matrixPrint(matrix):
    for raw in matrix:
        print(raw)


"""Common code to keep api handler DRY."""
import functools
import inspect
import re
from typing import Any, Callable, ParamSpec, TypeVar, cast

import schematics.exceptions

import db.conn
import journaling
from controllers.auth import AuthUser
from controllers.models import APIBaseError, HttpCode
from journaling import log
from pretty_ns import time_ns

Func = TypeVar("Func", bound=Callable[..., Any])

Param = ParamSpec("Param")
Result = TypeVar("Result")

def transaction(handler: Callable[Param, Result]) -> Callable[Param, Result]:
    """Decorate api handler into try-except to handle DB transaction."""

    @functools.wraps(handler)
    def transaction_wrapper(*args: Param.args, **kwargs: Param.kwargs) -> Result:
        try:
            return handler(*args, **kwargs)
        except APIBaseError as e:
            db.conn.session.rollback()
            log.error(f"{e}")
            return f"API error {e}", e.status  # type: ignore
        except schematics.exceptions.BaseError as e:
            db.conn.session.rollback()
            messages = []
            for field in e.errors:
                error_messsage = str(e.errors[field]).replace("Rogue", "Unknown")
                messages.append(f"{field} - {error_messsage}")
            log.error(f"Model validation error: {e}")
            return f'Wrong request parameters: {", ".join(messages)}', HttpCode.wrong_request  # type: ignore
        except TypeError as e:
            db.conn.session.rollback()
            missing_args = re.match(
                r"(.+)missing \d+ required positional argument(s)?: (.+)", str(e)
            )
            if missing_args:
                return f"Missing arguments: {missing_args[3]}", HttpCode.wrong_request  # type: ignore
            log.error(f"{e}", exc_info=True)
            return "Server internal error", HttpCode.unhandled_exception  # type: ignore
        except Exception as e:
            db.conn.session.rollback()
            log.error(f"{e}", exc_info=True)
            return "Server internal error", HttpCode.unhandled_exception  # type: ignore
        finally:
            db.conn.session.close()

    return transaction_wrapper

def api_result(handler: Func) -> Func:
    """Decorate api handler result.

    Expects from handler tuple with result object and optional code (default 200).
    Formats result as tuple (<result object>, <http result code>)
    """

    @functools.wraps(handler)
    def api_result_wrapper(*args, **kwargs):  # type: ignore
        journaling.request_start_time = time_ns()
        try:
            result = handler(*args, **kwargs)
            if isinstance(result, tuple):
                code = result[1]
                result = result[0]
            else:
                code = HttpCode.success
            return result, code
        finally:
            journaling.request_start_time = None

    # Removing our calculated argument auth_user from decorated function
    signature = inspect.signature(handler)
    params = []
    for param in signature.parameters.values():
        if param.name != "auth_user":
            params.append(param)
    # suppress "Callable[[VarArg(Any), KwArg(Any)], Any]" has no attribute "__signature__"
    api_result_wrapper.__signature__ = signature.replace(parameters=params)  # type: ignore[attr-defined]
    return cast(Func, api_result_wrapper)

def token_to_auth_user(handler: Callable[Param, Result]) -> Callable[Param, Result]:
    """Create auth_user parameter from token."""

    @functools.wraps(handler)  # preserve initial function signature
    def token_to_auth_user_wrapper(*args, **kwargs) -> Result:  # type: ignore
        if "auth_token" in kwargs:
            if kwargs["auth_token"] is not None:
                log.debug(f'Add auth_user to {handler.__name__}\n{kwargs["auth_token"]}')
                auth_user = AuthUser(kwargs["auth_token"])
                args = (auth_user,) + args
                journaling.user = auth_user.email
            else:
                log.warning("No or wrong user token in request")
                return "No or wrong user token in request", HttpCode.no_token  # type: ignore
            del kwargs["auth_token"]
        try:
            return handler(*args, **kwargs)
        finally:
            journaling.user = None

    # suppress "Callable[[VarArg(Any), KwArg(Any)], Any]" has no attribute "__signature__"
    token_to_auth_user_wrapper.__signature__ = inspect.signature(handler)  # type: ignore[attr-defined]
    return token_to_auth_user_wrapper


"""
14.2 平移
平移就是将对象换一个位置。如果你要沿（x，y）方向移动，移动的距离
是（tx，ty），你可以以下面的方式构建移动矩阵：
        [ 1 0 tx ]
    M = [ 0 1 ty ]

你可以使用Numpy 数组构建这个矩阵（数据类型是np.float32），然
后把它传给函数cv2.warpAffine()
"""
import cv2
import numpy as np

img = cv2.imread("../../../resource/img/1.jpg");
rows, cols = img.shape[:2];

M = np.float32([[1,0,100],[0,1,100]]);
"""
cv2.warpAffine(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]]) → dst
Applies an affine transformation仿射变换 to an image.
Parameters:
    src – input image.
    M – 2 * 3 transformation matrix. 变换矩阵
    dsize – size of the output image.
"""
dst = cv2.warpAffine(img, M, (cols,rows));

cv2.imshow("dst",dst);
cv2.waitKey(3000);
cv2.destroyAllWindows();

#函数cv2.warpAffine() 的第三个参数的是输出图像的大小，它的格式应该是图像的（宽，高）。应该记住的是图像的宽对应的是列数，高对应的是行数。


from mvc.view.tela_inicio_selecao_partida import TelaInicioSelecaoPartida
from mvc.control.controlador_jogador import ControladorJogador
from mvc.model.partida import Partida
from mvc.control.controlador_inteligencia_artificial import ControladorInteligenciaArtificial
from mvc.control.controlador_partida import ControladorPartida

class ControladorInicioSelecaoPartida:
    def __init__(self, controlador_principal):
        self._controlador_principal = controlador_principal
        self._tela_inicio_partida = TelaInicioSelecaoPartida(self)
        self._controlador_jogador = ControladorJogador(self)
        self._controlador_inteligencia_artifical = ControladorInteligenciaArtificial(self)
        self._controlador_partida = ControladorPartida()
        self._partida = []

        # função que enviará a chamada para o loop da partida
    def abre_tela_inicio_partida(self, jogador_1):
        button, values = self._tela_inicio_partida.open_tela_inicio_selecao_partida()
        while (button == 'OK' and (values['baralho'] == '' and values['oponente'] == '')) or \
                (button == 'OK' and (values['baralho'] == '' or values['oponente'] == '')):
            self._tela_inicio_partida.show_message("Erro", "As opções não podem ficar em branco!")
            button, values = self._tela_inicio_partida.open_tela_inicio_selecao_partida()
        tipo_oponente = values['oponente']
        if tipo_oponente == 'Computador':
            jogador_2 = self._controlador_jogador.inlcuir_usuario_maquina()
            self.inicio_partida_maquina(jogador_1, values['baralho'], jogador_2, 'Grego')
        elif tipo_oponente == 'Humano':
            jogador_2 = self._controlador_jogador.abre_tela_login_segundo_jogador(jogador_1)
            while not jogador_2:
                jogador_2 = self._controlador_jogador.abre_tela_login_segundo_jogador(jogador_1)
            baralho_2 = self._controlador_jogador.abre_tela_baralho_segundo_jogador()
            self.inicio_partida_humano(jogador_1, values['baralho'], jogador_2, baralho_2)
        if button == 'Menu Principal':
            self._controlador_principal.abre_tela_inicial()

    def inicio_partida_humano(self, jogador_1, tipo_baralho_1, jogador_2, tipo_baralho_2):
        jogador_1_memoria = self._controlador_jogador.criar_jogador_humano_memoria(jogador_1)
        jogador_2_memoria = self._controlador_jogador.criar_jogador_humano_memoria(jogador_2)
        self._partida = Partida(jogador_1_memoria, tipo_baralho_1, jogador_2_memoria, tipo_baralho_2)
        self._controlador_partida.abre_tela_confirmacao_partida_humano(self._partida)
        print('imprimindo da partida')
        print('primeiro jogador é ' + self._partida.jogador_1['apelido'])
        print('segundo jogador é ' + self._partida.jogador_2['apelido'])
        print('baralho do primeiro jogador é do tipo ' + self._partida.baralho_1)
        print('baralho do segundo jogador é do tipo  ' + self._partida.baralho_2)

    def inicio_partida_maquina(self, jogador_1, tipo_baralho_1, jogador_2, tipo_baralho_2):
        jogador_1_memoria = self._controlador_jogador.criar_jogador_humano_memoria(jogador_1)
        self._partida = Partida(jogador_1_memoria, tipo_baralho_1, jogador_2, tipo_baralho_2)
        self._controlador_partida.abre_tela_confirmacao_partida_maquina(self._partida)
        print('imprimindo da partida')
        print('primeiro jogador é ' + self._partida.jogador_1['apelido'])
        print('segundo jogador é ' + self._partida.jogador_2.apelido)
        print('baralho do primeiro jogador é do tipo ' + self._partida.baralho_1)
        print('baralho do segundo jogador é do tipo  ' + self._partida.baralho_2)


nome = str(input("Qual seu nome: "))
print(
  f"-ahhh... que sono... bem acho que é hora de acordar \n (você levanta...) {nome}-...temho q escovar os dentes...   "
)
escolha1 = str(input("Vai escovar os dentes? s/n: ")).upper()
#N_escovar
if escolha1 == "N":
 print(f"-ahh.... depois faço isso")
elif escolha1 == "S":
  print("Vc escova os dentes.")
else:
  print("Escreva direito disgraça!")


import os
import shutil
import sys

TARGET_PATH = r'F:\Octopath_Traveler2_Localization_Fix\UnrealPakSwitch'
OCTO_PATH = r'F:\SteamLibrary\steamapps\common\Octopath_Traveler2\Octopath_Traveler2\Content\Paks'

def main():
    scriptFolder = os.path.split(__file__)[0]
    sourceFolder = os.path.join(scriptFolder, 'Output')
    with os.scandir(sourceFolder) as it:
        for entry in it:
            if entry.is_file():
                fileName, filePath = entry.name, entry.path
                if fileName.startswith('TalkData_ZH_CN'):
                    outputFolder = os.path.join(TARGET_PATH, r'Octopath_Traveler2\Content\Talk\Database')
                    if not os.path.exists(outputFolder):
                        os.makedirs(outputFolder)
                    shutil.copy2(filePath, outputFolder)
                elif fileName.startswith('GameTextZH_CN'):
                    outputFolder = os.path.join(TARGET_PATH, r'Octopath_Traveler2\Content\GameText\Database')
                    if not os.path.exists(outputFolder):
                        os.makedirs(outputFolder)
                    shutil.copy2(filePath, outputFolder)
                elif fileName.endswith('.ttf'):
                    outputFolder = os.path.join(TARGET_PATH, r'Octopath_Traveler2\Content\UserInterface\Common\Font')
                    if not os.path.exists(outputFolder):
                        os.makedirs(outputFolder)
                    shutil.copyfile(filePath, os.path.join(outputFolder, os.path.splitext(fileName)[0]) + '.ufont')
    os.chdir(os.path.join(TARGET_PATH, r'v11.27\2\3'))
    executeResult = os.popen(r'UnrealPak.exe ..\..\..\Octopath_Traveler2-WindowsNoEditor_cnfix.pak -Create=..\..\..\lista.txt -compress')
    for line in executeResult.read().splitlines():
        print(line)
    shutil.copy2(os.path.join(TARGET_PATH, 'Octopath_Traveler2-WindowsNoEditor_cnfix.pak'), OCTO_PATH)

if __name__ == '__main__':
    main()


# from GUI import GUI
# from HAL import HAL
import cv2.cv2 as cv
import numpy as np

def get_interesting_points(img) -> list:
    """
    Get the interesting points of the image
    :param img: image to be processed
    :return: list of interesting points (i, j)
    """
    canny = cv.Canny(img, 100, 200)
    points = [(x, y) for y, x in zip(*canny.nonzero()) if y < img.shape[1] // 2]
    print(f"{len(points)} points found")
    return points

def get_3d_line_equation(position_cam: str, image_point_2d: tuple) -> tuple:
    """
    Get the line equation in 3D space
    :param position_cam: position of the camera ('right' or 'left')
    :param image_point: point of the image
    :return: line equation in 3D space given direction and point.
    """
    cam_3d_esc = HAL.getCameraPosition(position_cam)
    optical_point_2d = HAL.graficToOptical(position_cam, [*image_point_2d, 1])
    direction_vect = HAL.backproject(position_cam, optical_point_2d)[:3]

# Get points
# im_left = HAL.getImage('left')
# im_right = HAL.getImage('right')

im_left = cv.imread('img_left.png')
im_right = cv.imread('img_left.png')

points_left_2d = get_interesting_points(im_left)

for point in points_left_2d:
    cv.circle(im_left, point, 1, (0, 0, 255), -1)

cv.imshow('left', im_left)
cv.waitKey(0)

# while True:
#
#     cv.imshow("Image right", im_right)
#     cv.imshow("Image left", im_left)
#     cv.waitKey(0)
    # GUI.showImages(im_left, im_right, True)


import numpy as np
import cv2
from PIL import Image
import math

def rotate(image_path, degrees_to_rotate, save_location):
    img_obj = Image.open(image_path)
    rotated_image = img_obj.rotate(degrees_to_rotate)
    rotated_image.save(save_location)
    rotated_image.show()

def invert_color(image_path, save_location):
    img_obj = Image.open(image_path)
    img_obj.show()
    img_matrix = np.array(img_obj)
    img_matrix = 255 - img_matrix
    img = Image.fromarray(img_matrix,'RGB')
    img.save(save_location)
    img.show()
    return img

def exp(image_path, integer_to_exp, save_location):
    img_obj = Image.open(image_path)
    img_obj.show()
    img_matrix = np.array(img_obj)
    img_matrix = np.exp(img_matrix)
    # for i in range (1, integer_to_exp):
    #     img_matrix = img_matrix * img_matrix
    img = Image.fromarray(img_matrix,'RGB')
    img.save(save_location)
    img.show()
    return img

def log(image_path, integer_to_exp, save_location):
    img_obj = Image.open(image_path)
    img_obj.show()
    img_matrix = np.array(img_obj)
    img_matrix = np.log(img_matrix)
    img = Image.fromarray(img_matrix,'RGB')
    img.save(save_location)
    img.show()
    return img

def move(image_path, tx, ty):
    img = cv2.imread(path)
    num_rows, num_cols, chanel = img.shape[:3]  # get the size of the matrix
    translation_matrix = np.float32([ [1,0,tx], [0,1,ty] ])

    img_translation = img.copy()

    for i in range (0, num_rows):
        for j in range (0, num_cols):
            img_translation[i][j] = 0

    cont_rows = 0
    for i in range (ty, num_rows):
        cont_cols = 0
        for j in range (tx, num_cols):
            img_translation[i][j][0] = img[cont_rows][cont_cols][0]
            img_translation[i][j][1] = img[cont_rows][cont_cols][1]
            img_translation[i][j][2] = img[cont_rows][cont_cols][2]
            cont_cols += 1
        cont_rows += 1

    # img_translation = cv2.warpAffine(img, translation_matrix, (num_cols, num_rows)) #traslete function with opencv
    cv2.imshow('Translation', img_translation)
    cv2.waitKey()

def scale(image_path, sx, sy):
    img = cv2.imread(path)
    num_rows, num_cols = img.shape[:2]
    cx, cy = np.indices((num_rows, num_cols))
    translation_matrix = np.float32([ [sx,0,0], [0,sy,0] ])
    img_matrix = np.array(img)

    img_translation = cv2.warpAffine(img, translation_matrix, (num_cols, num_rows))
    cv2.imshow('Scale', img_translation)
    cv2.waitKey()

def crotate(image_path, alpha):
    img = cv2.imread(path)
    num_rows, num_cols = img.shape[:2]
    r_alpha = alpha*math.pi/180

    # cy, cx = np.indices((num_rows, num_cols))
    aux_x = num_cols/2.0
    aux_y = num_rows/2.0

    img_rotated = img.copy()

    for i in range (0, num_rows):
        aux_i = float(i)/(num_rows-1)
        if(i < aux_y):
            aux_i -= 1
        for j in range (0, num_cols):
            aux_j = float(j)/(num_cols-1)
            if(j < aux_x):
                aux_j -= 1
            dx = aux_i*math.cos(r_alpha) - aux_j*math.sin(r_alpha)
            dy = aux_i*math.sin(r_alpha) + aux_j*math.cos(r_alpha)
            # print("dx, dy", dx, dy)
            if(dy < 0):
                dy = (dy+1) * (num_rows-1)
            else:
                dy = dy * (num_rows-1)
            if(dx < 0):
                dx = (dx+1) * (num_cols-1)
            else:
                dx = dx * (num_cols-1)

            if int(dx) >= num_cols or int(dy) >= num_rows:
                img_rotated[i][j] = 0
            else:
                img_rotated[i][j] = img[int(dx)][int(dy)]

    cv2.imshow('Rotate', img_rotated)
    cv2.waitKey()

    # center = (num_cols/2, num_rows/2)
    # translation_matrix = cv2.getRotationMatrix2D(center, alpha, 1.0)
    # img_translation = cv2.warpAffine(img, translation_matrix, (num_cols, num_rows))
    # cv2.imshow('Rotate2', img_translation)
    # cv2.waitKey()

if __name__ == "__main__":
    path = "/home/sergio/TCG/imagenesTCG/cameraman.jpg"
    save = "/home/sergio/TCG/results/result.jpg"
    # invert_color(path, save)
    exp(path, 2 , save)
    # log(path, 2 , save)
    # crotate(path, 90)
    # move(path, 100, 80)
    # scale(path, 1, 0.5)


import split_data
from dataload.dataload import load_data
from utils.utils import load_checkpoint, build_model
from model.resnet50 import create_model
import torch
from train import train

def main():
    images_dir = 'data/UTKFace/images'
    base_data_dir = 'data/UTKFace'
    train_split = 0.7
    valid_split = 0.2

    # Hyperparameters
    aug_p = 0.4
    batch_size = 64
    base_model = 'resnet50'
    dropout_p = 0.4
    freeze = True
    num_layers = 120
    learning_rate = 1e-03
    unfrozen_learning_rate = 3e-05
    epochs = 10
    split_data.split(base_data_dir, images_dir, train_split, valid_split)
    trainloader, validloader, testloader = load_data(base_data_dir, images_dir, aug_p, batch_size)
    model = create_model(base_model, freeze, num_layers, dropout_p)
    criterion_mae, criterion_bce, optimizer, scheduler = build_model(model, epochs, learning_rate, True)
    model, train_bce_losses, train_mae_losses, valid_bce_losses, valid_mae_losses, \
    best_loss = train(trainloader, validloader, model, criterion_mae, criterion_bce, optimizer, epochs, scheduler = scheduler)

    print(f'{"*"*10} Unfreezing {"*"*10}')
    # Unfreeze
    model = create_model(base_model, freeze = False, dropout_p=dropout_p)
    model, _ = load_checkpoint(model, file_path='saved_models/multi_task.pt')
    criterion_mae, criterion_bce, optimizer, scheduler = build_model(model, epochs, unfrozen_learning_rate, True)
    model, train_bce_losses, train_mae_losses, valid_bce_losses, valid_mae_losses, \
    best_loss = train(trainloader, validloader, model, criterion_mae, criterion_bce, optimizer, epochs, best_loss, scheduler)

    model_scripted = torch.jit.script(model)
    model_scripted.save('saved_models/multitask_final.pt')

if __name__ == "__main__":
    main()


#Return True if the string "cat" and "dog" appear the same number of times in the given string.

def cat_dog(str):
	cat_count = 0
	dog_count = 0
	for i in range(len(str)):
		if str[i:i+3] == 'cat':
			cat_count += 1
		if str[i:i+3] == 'dog':
			dog_count += 1
	return cat_count == dog_count

print(
cat_dog('catdog'),
cat_dog('catcat'),
cat_dog('1cat1cadodog'))


with open('input.txt') as f:
    grid = [line.strip() for line in f]

print('rows: ' + str(len(grid)))
width = len(grid[0])

trees = 0
pos = 0
for row in grid:
    if row[pos] == '#':
        trees += 1
    pos = (pos + 3) % width

print(trees)


import string

import flowers
import tree
import bush
from extenderr import *
import random
#----------------------------------------------
class Container:
    def __init__(self):
        self.store = []
    def file_in(self, strArray):
        arrayLen = len(strArray)
        i = 0  # Индекс, задающий текущую строку в массиве
        figNum = 0
        while i < arrayLen:
            str = strArray[i]
            key = int(str)  # преобразование в целое
            if key == 1:  # признак дерева
                i += 1
                if i >= len(strArray) - 1:
                    return 0
                plant = Tree(strArray[i], strArray[i + 1])
                i += 2
            elif key == 2:  # признак куста
                i += 1
                if i >= len(strArray) - 1:
                    return 0
                plant = Bush(strArray[i], strArray[i + 1])
                i += 2
            elif key == 3:
                i += 1
                if i >= len(strArray) - 1:
                    return 0
                plant = Flowers(strArray[i], strArray[i + 1])
                i += 2
            else:
                # что-то пошло не так. Должен быть известный признак
                # Возврат количества прочитанных растений
                return figNum
            # Количество пробелами растений увеличивается на 1
            if i == 0:
                return figNum
            figNum += 1
            self.store.append(plant)
        return figNum

    def random_in(self, plantsNumbers):
        if plantsNumbers < 1:
            return False
        for i in range(plantsNumbers):
            letters = string.ascii_lowercase
            rand_string = ''.join(random.choice(letters) for i in range(random.randint(1, 15)))
            key = random.randint(1, 3)
            if key == 1:
                plant = Tree(rand_string, random.randint(1, 100))
            elif key == 2:
                plant = Bush(rand_string, random.randint(1, 12))
            else:
                plant = Flowers(rand_string, random.randint(1, 3))
            self.store.append(plant)

    def Print(self):
        print("Container is store", len(self.store), "plants:\n")
        for plant in self.store:
            plant.Print()
        pass

    def Write(self, ostream):
        ostream.write("Container is store {} plants:\n".format(len(self.store)))
        for plant in self.store:
            plant.Write(ostream)
            ostream.write("\n")
        pass

    def sort(self):
        length = len(self.store)
        swapped = True
        start_index = 0
        end_index = length - 1

        while (swapped == True):

            swapped = False

            # проход слева направо
            for i in range(start_index, end_index):
                if (self.store[i].quotient() > self.store[i + 1].quotient()):
                    # обмен элементов
                    self.store[i], self.store[i + 1] = self.store[i + 1], self.store[i]
                    swapped = True

            # если не было обменов прерываем цикл
            if (not (swapped)):
                break

            swapped = False

            end_index = end_index - 1

            # проход справа налево
            for i in range(end_index - 1, start_index - 1, -1):
                if (self.store[i].quotient() > self.store[i + 1].quotient()):
                    # обмен элементов
                    self.store[i], self.store[i + 1] = self.store[i + 1], self.store[i]
                    swapped = True

            start_index = start_index + 1


import sys

def f_gold ( N ) :
    """
 Return the number of gold numbers in the given string.
 """
    N = N.split ( )
    l = ( len ( N ) ) // 2
    count = 0
    for i in range ( 1 , l + 1 ) :
        s = N [ : i ]
        l1 = len ( s )
        t = N [ i : l1 + i ]
        if s [ 0 ] == '0' or t [ 0 ] == '0' :
            continue
        if s == t :
            count += 1
    return count

if __name__ == '__main__':
    param = [
    ('ZCoQhuM',),
    ('2674377254',),
    ('11',),
    ('LbuGlvRyWAPBpo',),
    ('26382426486138',),
    ('111010111010',),
    ('hUInqJXNdbfP',),
    ('5191',),
    ('1110101101',),
    ('2202200',)
        ]
    n_success = 0
    print("class,mutant,test_index,result")
    for i, parameters_set in enumerate(param):
        try:
            print("BREAKING_NUMBER_FIRST_PART_INTEGRAL_DIVISION_SECOND_POWER_10," + sys.argv[1] + "," + str(i) + "," + str(f_gold(*parameters_set)))
        except:
            print("BREAKING_NUMBER_FIRST_PART_INTEGRAL_DIVISION_SECOND_POWER_10," + sys.argv[1] + "," + str(i) + ",EXCEPTION")


class Employee:
	def __init__ (self,no,name,leaves):
		self.empno = no
		self.empname = name
		self.leaves = leaves

class Company:

	def __init__ (self,name,emp):
		self.cname = name
		self.emps = emp

	def display_leave(self,enum,ltype):
		for emp in self.emps:
			if emp.empno == enum:

				for lt,nl in emp.leaves.items():
					if lt == ltype:

						print (emp.leaves[lt])

	def leave_application(self,enum,ltype,nday):
		for emp in self.emps:
			if emp.empno == enum:
				for lt,nl in emp.leaves.items():
					if lt == ltype:
						if nday >= emp.leaves[lt]:
							return "Granted"
						else:
							return "Rejected"

if __name__ == '__main__':
	n = int(input("Enter number of employee objects"))

	leave = {}

	empl = []

	for i in range(n):

		num = int(input("enter employee number"))
		name = input("enter name")

		leave['CL'] = int(input("enter CL"))
		leave['EL'] = int(input("enter EL"))
		leave['SL'] = int(input("enter SL"))
		empl.append(Employee(num,name,leave))

	c = Company("Job Portal",empl)

	search_enum = int(input("Enter search e num"))
	search_type = input("enter search type")
	search_ndays = int(input("enter leave days"))

	c.display_leave(search_enum,search_type)
	message=c.leave_application(search_enum,search_type,search_ndays)

	print (message)


# -*- coding: UTF-8 -*-
## Copyright 2009-2013 Luc Saffre
## This file is part of the Lino project.
## Lino is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
## Lino is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with Lino; if not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals

import logging
logger = logging.getLogger(__name__)

import os
import sys
#~ import imp
import codecs
import atexit
#~ import collections
from UserDict import IterableUserDict

from django.db.models import loading
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.functional import LazyObject
from django.db import models
#from django.shortcuts import render_to_response
#from django.contrib.auth.models import User
from django.contrib.contenttypes import generic

from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.sites.models import Site, RequestSite
from django.http import HttpResponse,HttpResponseRedirect, Http404
from django.template import RequestContext, Context, loader
from django.utils.http import urlquote, base36_to_int
from django.utils.translation import ugettext as _

from django.utils.safestring import mark_safe

import lino

from lino import dd
#~ from lino.core import signals
#~ from lino.core import actions
from lino.core import fields
from lino.core import layouts
from lino.core import actors
from lino.core import actions
from lino.core import dbtables
from lino.utils import class_dict_items

#~ from lino.utils.config import load_config_files, find_config_file
#~ from lino.utils import choosers
#~ from lino.utils import codetime
from lino.utils import curry
#~ from lino.models import get_site_config
#~ from north import babel
from lino.utils import AttrDict
#~ from lino.core import perms

#~ BLANK_STATE = ''

#~ DONE = False

#~ self.GFK_LIST = []

def set_default_verbose_name(f):
    """
    If the verbose_name of a ForeignKey was not set by user code,
    Django sets it to ``field.name.replace('_', ' ')``.
    We replace this default value by ``f.rel.to._meta.verbose_name``.
    This rule holds also for virtual FK fields.
    """
    if f.verbose_name == f.name.replace('_', ' '):
        f.verbose_name = f.rel.to._meta.verbose_name

#~ def shutdown_site(self):
    #~ models_list = models.get_models(include_auto_created=True)
    #~ for m in models_list:
        #~ ...

def startup_site(self):
    """
    This is the code that runs when you call :meth:`lino.site.Site.startup`.
    This is a part of a Lino site setup.
    The Django Model definitions are done, now Lino analyzes them and does certain actions.

    - Verify that there are no more pending injects
    - Install a DisableDeleteHandler for each Model into `_lino_ddh`
    - Install :class:`lino.dd.Model` attributes and methods into Models that
      don't inherit from it.

    """
    if len(sys.argv) == 0:
        process_name = 'WSGI'
    else:
        process_name = ' '.join(sys.argv)
    #~ logger.info("Started %s on %r (PID %s).", process_name,self.title,os.getpid())
    logger.info("Started %s (using %s) --> PID %s",
        process_name,settings.SETTINGS_MODULE,os.getpid())
    logger.info(self.welcome_text())

    def goodbye():
        logger.info("Done %s (PID %s)",process_name,os.getpid())
    atexit.register(goodbye)

    #~ analyze_models(self)

    #~ print 20130219, __file__, "setup_choicelists 1"

    #~ logger.info("Analyzing models...")

    #~ self = settings.SITE
    #~ logger.info(self.welcome_text())

    #~ """
    #~ Activate the site's default language
    #~ """
    #~ dd.set_language(None)

    #~ logger.info(lino.welcome_text())
    #~ raise Exception("20111229")

    models_list = models.get_models(include_auto_created=True)
    # this also triggers django.db.models.loading.cache._populate()

    if self.user_model:
        self.user_model = dd.resolve_model(self.user_model,
            strict="Unresolved model '%s' in user_model.")
    #~ if self.person_model:
        #~ self.person_model = dd.resolve_model(self.person_model,strict="Unresolved model '%s' in person_model.")

    #~ print 20130219, __file__, "setup_choicelists 2"

    if self.project_model:
        self.project_model = dd.resolve_model(self.project_model,
            strict="Unresolved model '%s' in project_model.")

    #~ print 20130219, __file__, "setup_choicelists 3"

    for m in self.override_modlib_models:
        dd.resolve_model(m,
            strict="Unresolved model '%s' in override_modlib_models.")

    for model in models_list:
        #~ print 20130216, model
        #~ fix_field_cache(model)

        model._lino_ddh = DisableDeleteHandler(model)

        for k in dd.Model.LINO_MODEL_ATTRIBS:
            if not hasattr(model,k):
                #~ setattr(model,k,getattr(dd.Model,k))
                setattr(model,k,dd.Model.__dict__[k])
                #~ model.__dict__[k] = getattr(dd.Model,k)
                #~ logger.info("20121127 Install default %s for %s",k,model)

        if isinstance(model.hidden_columns,basestring):
            model.hidden_columns = frozenset(dd.fields_list(model,model.hidden_columns))

        if model._meta.abstract:
            raise Exception("Tiens?")

        self.modules.define(model._meta.app_label,model.__name__,model)

        for f in model._meta.virtual_fields:
            if isinstance(f,generic.GenericForeignKey):
                settings.SITE.GFK_LIST.append(f)

    for a in models.get_apps():
        #~ for app_label,a in loading.cache.app_store.items():
        app_label = a.__name__.split('.')[-2]
        #~ logger.info("Installing %s = %s" ,app_label,a)

        for k,v in a.__dict__.items():
            if isinstance(v,type) and issubclass(v,layouts.BaseLayout):
                #~ print "%s.%s = %r" % (app_label,k,v)
                self.modules.define(app_label,k,v)
            #~ if isinstance(v,type) and issubclass(v,dd.Plugin):
                #~ self.plugins.append(v)

            #~ if isinstance(v,type)  and issubclass(v,dd.Module):
                #~ logger.info("20120128 Found module %s",v)
            if k.startswith('setup_'):
                self.modules.define(app_label,k,v)

    self.setup_choicelists()
    self.setup_workflows()

    for model in models_list:

        for f, m in model._meta.get_fields_with_model():
            #~ if isinstance(f,models.CharField) and f.null:
            if f.__class__ is models.CharField and f.null:
                msg = "Nullable CharField %s in %s" % (f.name,model)
                raise Exception(msg)
                #~ if f.__class__ is models.CharField:
                    #~ raise Exception(msg)
                #~ else:
                    #~ logger.info(msg)
            elif isinstance(f,models.ForeignKey):
                #~ f.rel.to = dd.resolve_model(f.rel.to,strict=True)
                if isinstance(f.rel.to,basestring):
                    raise Exception("%s %s relates to %r (models are %s)" % (model,f.name,f.rel.to,models_list))
                set_default_verbose_name(f)

                """
                If JobProvider is an MTI child of Company,
                then mti.delete_child(JobProvider) must not fail on a
                JobProvider being refered only by objects that can refer
                to a Company as well.
                """
                if hasattr(f.rel.to,'_lino_ddh'):
                    #~ f.rel.to._lino_ddh.add_fk(model,f) # 20120728
                    f.rel.to._lino_ddh.add_fk(m or model,f)

    dd.pre_analyze.send(self,models_list=models_list)
    # MergeActions are defined in pre_analyze.
    # And MergeAction needs the info in _lino_ddh to correctly find keep_volatiles

    for model in models_list:

        """
        Virtual fields declared on the model must have
        been attached before calling Model.site_setup(),
        e.g. because pcsw.Person.site_setup()
        declares `is_client` as imported field.
        """

        model.on_analyze(self)

        for k,v in class_dict_items(model):
            if isinstance(v,dd.VirtualField):
                v.attach_to_model(model,k)

    #~ logger.info("20130817 attached model vfs")

    actors.discover()

    actors.initialize()
    dbtables.discover()
    #~ choosers.discover()
    actions.discover_choosers()

    #~ from lino.core import ui
    #~ ui.site_setup(self)

    for a in actors.actors_list:
        a.on_analyze(self)

    #~ logger.info("20130121 GFK_LIST is %s",['%s.%s'%(full_model_name(f.model),f.name) for f in settings.SITE.GFK_LIST])
    dd.post_analyze.send(self,models_list=models_list)

    logger.info("Languages: %s. %d apps, %d models, %s actors.",
        ', '.join([li.django_code for li in self.languages]),
        len(self.modules),
        len(models_list),
        len(actors.actors_list))

    #~ logger.info(settings.INSTALLED_APPS)

    self.on_each_app('site_setup')

    """
    Actor.after_site_setup() is called after the apps' site_setup().
    Example: pcsw.site_setup() adds a detail to properties.Properties,
    the base class for properties.PropsByGroup.
    The latter would not
    install a `detail_action` during her after_site_setup()
    and also would never get it later.
    """
    for a in actors.actors_list:
        a.after_site_setup(self)

    #~ self.on_site_startup()

    self.resolve_virtual_fields()

    #~ logger.info("20130827 startup_site done")

class DisableDeleteHandler():
    """
    Used to find out whether a known object can be deleted or not.
    Lino's default behaviour is to forbit deletion if there is any other
    object in the database that refers to this. To implement this,
    Lino installs a DisableDeleteHandler instance on each model
    during :func:`analyze_models`. In an attribute `_lino_ddh`.
    """
    def __init__(self,model):
        self.model = model
        self.fklist = []

    def add_fk(self,model,fk):
        self.fklist.append((model,fk))

    def __str__(self):
        return ','.join([m.__name__+'.'+fk.name for m,fk in self.fklist])

    def disable_delete_on_object(self,obj):
        #~ print 20101104, "called %s.disable_delete(%s)" % (obj,self)
        #~ h = getattr(self.model,'disable_delete',None)
        #~ if h is not None:
            #~ msg = h(obj,ar)
        #~     if msg is not None:
            #~     return msg
        for m,fk in self.fklist:
            #~ kw = {}
            #~ kw[fk.name] = obj
            #~ if not getattr(m,'allow_cascaded_delete',False):
            if not fk.name in m.allow_cascaded_delete:
                n = m.objects.filter(**{fk.name : obj}).count()
                if n:
                    msg = _("Cannot delete %(self)s because %(count)d %(refs)s refer to it.") % dict(
                      self=obj,count=n,
                      refs=m._meta.verbose_name_plural or m._meta.verbose_name+'s')
                    #~ print msg
                    return msg
        return None

def unused_generate_dummy_messages(self):
    fn = os.path.join(self.source_dir,'dummy_messages.py')
    self.dummy_messages
    raise Exception("use write_message_file() instead!")


from datetime import datetime

import sys

__author__ = 'Anubhav Jain <ajain@lbl.gov>'

"""
A Chronograph implementation used to time execution of code. Features include:
    * support for named Chronographs and labeled splits
    * reporting
    * multiple verbosity levels
    * built-in logging
    * JSON-compatible output data, including timestamps of start/stop
    * custom exceptions if desired
    * pain-free global management of multiple Chronographs
    * function decorators
    * support of with() syntax
    * cast to float gives total time
    * unit tested

Not intended for extremely precise timing (e.g., sub-millisecond level).
"""

all_chronographs = {}  # global list of chronographs

def get_chronograph(name, **kwargs):
    """
    Get a chronograph and save it the global list of chronographs

    :param name: (str) the name of this chronograph
    :param kwargs: (**kwargs) parameters to feed into the Chronograph constructor
    :return: a Chronograph object
    """
    if name not in all_chronographs:
        all_chronographs[name] = Chronograph(name, **kwargs)

    return all_chronographs[name]

def add_chronograph(**kwargs1):
    """
    A function decorator: each execution of the function will be timed as a separate split.
    By default the Chronograph name will be the function name.

    :param kwargs1: (**kwargs1) parameters to feed into the Chronograph constructor
    :return: (this is a function decorator)
    """

    def _add_chronograph_internal(func):
        def _decorator(*args, **kwargs):
            my_name = func.__name__
            my_chronograph = get_chronograph(**kwargs1) if "name" in kwargs1 else get_chronograph(my_name, **kwargs1)
            my_chronograph.start()
            return_data = func(*args, **kwargs)
            my_chronograph.stop()
            return return_data
        return _decorator
    return _add_chronograph_internal

def get_split_time(split_data, allow_still_running=False):
    if "stop" in split_data:
        stop_time = split_data["stop"]
    elif allow_still_running:
        stop_time = datetime.now()
    else:
        raise ChronographError("Cannot get split data; make sure 'stop' is defined or use 'allow_still_running' option.")

    return (stop_time - split_data['start']).total_seconds()

class ChronographError(Exception):
    pass

class Chronograph():

    def __init__(self, name=None, verbosity=0, logger=None, log_lvl=None, start_timing=False, throw_exceptions=False):
        """
        A class to represent a Chronograph for timing code execution

        :param name: (str) a name, useful when reporting or saving global Chronographs
        :param verbosity: (int) set to 0=silent operation, 2=most verbose operation
        :param logger: (Logger) logging object for writing output. Defaults to sys.stdout
        :param log_lvl: (str) level to log at, e.g. "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"
        :param start_timing: (bool) set to True if you want to start timing immediately (calls the start() function)
        :param throw_exceptions: (bool) set to True if you want invalid Chronograph commands to result in exceptions
        """
        self.name = name
        self.header = name if name else "Unnamed Chronograph"
        self._timing_data = []
        self.verbosity = verbosity
        self.throw_exceptions = throw_exceptions

        if logger:
            self.print_fnc = getattr(logger, log_lvl.lower())
        else:
            self.print_fnc = sys.stdout.write

        if start_timing:
            self.start()

    def start(self, label=None):
        """
        Starts timing a new split.

        :param label: (str) a label to apply to this split (useful for reporting)
        """
        if not self.timing_data or "stop" in self.timing_data[-1]:
            label = label if label else str(len(self.timing_data)+1)
            self.timing_data.append({"start": datetime.now(), "label": label})
            if self.verbosity >= 2:
                self.print_fnc("{}: Split ({}) started at: {}\n".format(self.header, label, self.timing_data[-1]["start"]))
            return True
        else:
            msg = "{}: Warning: Cannot start Chronograph while in current state! Stop or reset chronograph before starting.\n".format(self.header)
            if self.throw_exceptions:
                raise ChronographError(msg)
            self.print_fnc(msg)
            return False

    def stop(self):
        """
        Stops timing.
        """
        if self.timing_data and "stop" not in self.timing_data[-1]:
            self.timing_data[-1]["stop"] = datetime.now()
            if self.verbosity >= 2:
                self.print_fnc("{}: stopped at: {}\n".format(self.header, self.timing_data[-1]["start"]))
            if self.verbosity >= 1:
                last_split = self.last_split
                last_split_text = "Last split ({}) time: {} s.".format(last_split['label'], get_split_time(last_split))

                self.print_fnc("{}: Total elapsed time: {} s. {}\n".format(self.header, self.total_elapsed_time, last_split_text))
            return True
        else:
            self.print_fnc("{}: Warning: Cannot stop Chronograph while in current state! Start chronograph first.\n".format(self.header))
            return False

    def reset(self):
        """
        Resets and clears all timing data.
        """
        self.timing_data = []
        if self.verbosity >= 2:
            self.print_fnc("{}: Reset at: {}\n".format(self.header, self.timing_data[-1]["start"]))
            return True
        return False

    def split(self, label=None):
        """
        Stops the current split and immediately starts a new split, perhaps with a new label.

        :param label: (str) a label to apply to this split (useful for reporting)
        :return: (bool) if the split was created successfully (used internally)
        """
        success = self.stop()
        if success:
            success = self.start(label=label)
        return success

    @property
    def total_elapsed_time(self):
        """
        The total elapsed time (all splits) for the Chronograph

        :return: (float)
        """
        elapsed_time = 0.0
        for t in self.timing_data:
            start_time = t['start']
            stop_time = t['stop'] if 'stop' in t else datetime.now()
            elapsed_time += (stop_time - start_time).total_seconds()

        return elapsed_time

    @property
    def last_split(self):
        """
        The complete timing data of the last completed split.

        :return: (dict)
        """
        for t in reversed(self.timing_data):
            if 'stop' in t:
                return t
        return False

    @property
    def last_split_time(self):
        """
        The time elapsed for the last completed split.

        :return: (float)
        """
        return get_split_time(self.last_split) if self.last_split else 0

    @property
    def timing_data(self):
        """
        All timing data.

        :return: (JSON array of dicts)
        """
        return self._timing_data

    @timing_data.setter
    def timing_data(self, new_data):
        self._timing_data = new_data

    def report(self, printout=False):
        """
        Prints a full report of timing data as a string.
        """
        report_str = "Report for {}\n".format(self.header)
        for t in self.timing_data:
            split_time = get_split_time(t, True)
            running_text = "" if "stop" in t else " (still running)"
            report_str += "Split {}: {}{}\n".format(t["label"], split_time, running_text)

        report_str += "Total elapsed time: {}\n".format(self.total_elapsed_time)

        if printout:
            self.print_fnc(report_str)

        return report_str

    def __float__(self):
        return self.total_elapsed_time

    def __str__(self):
        return "{} with total elapsed time: {}".format(self.header, self.total_elapsed_time)

    def __repr__(self):
        return "{} with total elapsed time: {} and timing data: {}".format(self.header, self.total_elapsed_time, self.timing_data)

    def __enter__(self):
        self.start()

    def __exit__(self, type, value, tb):
        self.stop()


from django.shortcuts import render, redirect
from django.views.decorators.http import require_safe, require_POST
from .models import Movie, Genre
from django.http import JsonResponse
from django.shortcuts import get_object_or_404

# Create your views here.
@require_safe
def index(request):
    movies = Movie.objects.all()
    context = {
        'movies':movies,
    }
    return render(request, 'movies/index.html', context)

@require_POST
def movie_like(request, movie_pk):
    if request.user.is_authenticated:
        movie = Movie.objects.get(pk=movie_pk)
        user = request.user

        if movie.like_users.filter(pk=user.pk).exists():
            movie.like_users.remove(user)
            is_liked = False
        else:
            movie.like_users.add(user)
            is_liked = True
        context = {
            'is_liked': is_liked,
        }
        return JsonResponse(context)
    return redirect('acctouns:login')

@require_safe
def detail(request, movie_pk):
    movie = Movie.objects.get(pk=movie_pk)
    context = {
        'movie': movie,
    }
    return render(request, 'movies/detail.html', context)

@require_safe
def recommended(request):
    # 상위 3개 장르 추출
    G = Genre.objects.all()
    G_count = {i.name:0 for i in G}
    if request.user.is_authenticated:
        user = request.user
        movies = user.like_movies.all()
        for movie in movies:
            genre = movie.genres.all()
            for i in genre:
                G_count[i.name] += 1
        new_G = sorted(G_count.items(), key=lambda x: x[1], reverse=True)[:3]
        preferences = [Genre.objects.get(name=i[0]).id for i in new_G]

        movies = Movie.objects.filter(genres__id__in=preferences).order_by('-vote_average')
        movies = list(set(movies))[:10]

    return render(request, 'movies/recommended.html', {'movies': movies})


import functools
import logging
import threading
import time
from collections import deque
from resource import getrusage, RUSAGE_SELF

from django.conf import settings
from django.db.backends.utils import CursorWrapper

from .collector import statsd

PROCESSING_TIME_METRIC_PREFIX = getattr(
    settings, 'PROCESSING_TIME_METRIC_PREFIX', 'processing_time'
)
REQUESTS_COUNTER_METRIC_PREFIX = getattr(
    settings, 'REQUESTS_COUNTER_METRIC_PREFIX', 'requests_count'
)

METRIC_NAME_TMPL = getattr(
    settings,
    'REQUESTS_METRIC_NAME_TMPL',
    '{prefix}.{url_name}.{request_method}.{status_code}'
)
ALL_URLS_METRIC_NAME_TMPL = getattr(
    settings,
    'REQUESTS_ALL_URLS_METRIC_NAME_TMPL',
    '{prefix}_all_urls.{request_method}'
)
UNKNOWN_URL_NAME = 'unknown'

REQUESTS_METRICS_ENABLED = getattr(
    settings,
    'ENABLE_REQUESTS_AND_QUERIES_METRICS',
    True
)
LARGE_NUMBER_OF_QUERIES_THRESHOLD = getattr(
    settings,
    'LARGE_NUMBER_OF_QUERIES_THRESHOLD',
    25
)
LONG_QUERIES_THRESHOLD_MS = getattr(
    settings,
    'LONG_QUERIES_THRESHOLD_MS',
    250
)

logger = logging.getLogger(__name__)

queries_data = threading.local()
old_execute = CursorWrapper.execute
old_executemany = CursorWrapper.executemany

class QueryLogEntry:
    sql: str
    duration: float

    def __init__(self, sql: str, duration: float):
        self.sql = sql,
        self.duration = duration

    def __str__(self):
        return "'{}' took {} ms".format(self.sql, self.duration * 1000)

def get_queries_log() -> deque:
    if not hasattr(queries_data, 'queries'):
        queries_data.queries = deque(maxlen=9000)
    return queries_data.queries

def add_query_log(duration: float, sql: str) -> None:
    get_queries_log().append(QueryLogEntry(sql=sql, duration=duration))

@functools.wraps(old_execute)
def new_execute(self, sql, params=None):  # type: ignore
    """
    Wraps original cursor execute method and adds thread safe timing to it.
    """
    start = time.monotonic()
    try:
        return old_execute(self, sql, params)
    finally:
        duration = time.monotonic() - start
        add_query_log(sql=sql, duration=duration)

@functools.wraps(old_executemany)
def new_executemany(self, sql, param_list):  # type: ignore
    """
    Wraps original cursor executemany method and adds thread safe timing to it.
    """
    start = time.monotonic()
    try:
        return old_executemany(self, sql, param_list)
    finally:
        duration = time.monotonic() - start
        add_query_log(sql=sql, duration=duration)

# Monkey patch
def patch_cursor() -> None:
    CursorWrapper.execute = new_execute
    CursorWrapper.executemany = new_executemany

def get_per_query_stat(query_stats):
    return "\n".join(str(stat) for stat in query_stats)

class RequestMetricsMiddleware(object):
    """
    Middleware reporting request metrics (such as processing time) to statsd

    How to use it:
    * add this middleware at the beginning of MIDDLEWARE_CLASSES in your
      settings
    * configure statsd in your settings:
      http://statsd.readthedocs.io/en/v3.2.1/configure.html#in-django
    """

    IGNORED_PATHS = (
        'javascript-catalog',
        'microservice_contract-health',
        'microservice_contract-ping',
        'microservice_contract-ping-service-id',
        'microservice_contract-info',
        'microservice_public_endpoints',
    )

    def process_request(self, request):
        request._request_start_time = time.monotonic()
        request._start_resources = getrusage(RUSAGE_SELF)
        get_queries_log().clear()

    def _collect_metrics(self, request, response):
        if not REQUESTS_METRICS_ENABLED:
            return
        if not request.resolver_match:
            return

        try:
            url_name = request.resolver_match.url_name
        except AttributeError:
            logger.warning(
                'URL resolver not found', extra={'path': request.path}
            )
            url_name = UNKNOWN_URL_NAME

        view_name = request.resolver_match.view_name
        if view_name in self.IGNORED_PATHS:
            return

        common_log_params = {
            'request_method': request.method,
            'url_name': url_name,
            'status_code': response.status_code,
        }

        query_stats = get_queries_log()

        # processing time
        end_resources, end_time = getrusage(RUSAGE_SELF), time.monotonic()
        real_time = (end_time - request._request_start_time) * 1000
        sys_time = (end_resources.ru_stime - request._start_resources.ru_stime) * 1000
        user_time = (end_resources.ru_utime - request._start_resources.ru_utime) * 1000
        cpu_time = sys_time + user_time
        queries_time = sum(stat.duration for stat in query_stats) * 1000

        processing_time_metric_name = METRIC_NAME_TMPL.format(
            prefix=PROCESSING_TIME_METRIC_PREFIX, **common_log_params
        )
        processing_time_all_urls_metric_name = ALL_URLS_METRIC_NAME_TMPL.format(
            prefix=PROCESSING_TIME_METRIC_PREFIX, **common_log_params
        )
        processing_time = int(real_time)
        statsd.timing(processing_time_metric_name, processing_time)
        statsd.timing(processing_time_all_urls_metric_name, processing_time)

        # requests counter
        requests_counter_metric_name = METRIC_NAME_TMPL.format(
            prefix=REQUESTS_COUNTER_METRIC_PREFIX, **common_log_params
        )
        statsd.incr(requests_counter_metric_name)

        queries_count = len(query_stats)

        data = {
            'queries_time': queries_time,
            'queries_count': queries_count,
            'real_time': real_time,
            'sys_time': sys_time,
            'user_time': user_time,
            'cpu_time': cpu_time,
            'cpu_real_ratio': cpu_time / real_time * 100,
            'queries_real_ratio': queries_time / real_time * 100,
        }
        metadata = {
            'path': request.get_full_path(),
            'url_name': url_name,
            'view_name': view_name,
            'method': request.method,
            'http_user_agent': request.META.get('HTTP_USER_AGENT'),
            'username': request.user.username,
        }

        logger.info(
            'Request time:\n'
            '\treal: {real_time}\n'
            '\tsys: {sys_time}\n'
            '\tuser: {user_time}\n'
            '\ttotal CPU time: {cpu_time}\n'
            '\tCPU to real time ratio: {cpu_real_ratio}\n'

            'Queries:\n'
            '\tcount: {queries_count}\n'
            '\ttotal time: {queries_time}\n'
            '\tqueries time to real time ratio: {queries_real_ratio}'.format(
                **data
            ), extra={
                **data,
                **metadata
            }
        )

        if queries_count > LARGE_NUMBER_OF_QUERIES_THRESHOLD:
            logger.warning("A lot of queries ({}) in {}: {}".format(
                queries_count, view_name, get_per_query_stat(query_stats)),
                extra={**metadata}
            )
        elif queries_time > LONG_QUERIES_THRESHOLD_MS:
            logger.warning("Long queries (total of {} ms) in {}: {}".format(
                queries_time, view_name, get_per_query_stat(query_stats)),
                extra={**metadata}
            )

    def process_response(self, request, response):
        try:
            self._collect_metrics(request, response)
        except Exception:
            logger.exception('Exception during collecting metrics')
        return response


"""Home URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home_page, name='home'),
    path('About', views.About_Page, name='About'),
    path('Contact Us', views.Contact_Page, name='Contact Us'),

    # Admin------------
    path('Admin_Login', views.Admin_Login, name='Admin_Login'),
    path('Admin_', views.Admin_, name='Admin_'),
    path('Admin_Logout', views.Admin_Logout, name='Admin_Logout'),

    # Student--------
    path('Student_Signup', views.Save_signup, name='Student_Signup'),
    path('Student_Login', views.Student_Login, name='Student_Login'),
    path('Student_', views.Student_, name='Student_'),
    path('Student_Logout', views.Student_Logout, name='Student_Logout'),

    # Teacher-------
    path('Teacher_Signup', views.Teacher_signup, name='Teacher_Signup'),
    path('Teacher_Login', views.Teacher_Login, name='Teacher_Login'),
    path('Teacher_', views.Teacher_, name='Teacher_'),
    path('Teacher_Logout', views.Teacher_Logout, name='Teacher_Logout'),

]


import argparse

my_parser = argparse.ArgumentParser()

my_parser.add_argument(
    '-v',
    '--verbosity',
    action='store',
    type=int,
    metavar='LEVEL'
)

args = my_parser.parse_args()

print(vars(args))

"""
$ python metavar_example.py -h
usage: metavar_example.py [-h] [-v LEVEL]

optional arguments:
  -h, --help            show this help message and exit
  -v LEVEL, --verbosity LEVEL
"""


from re import search

input = open("05.in", "r")
data = input.read().splitlines()[0]

# perform the reactions
i = 0
while i < len(data) - 1:
    # ascii letter number xor 32 is the same letter in opposite case
    if chr(ord(data[i]) ^ 32) == data[i + 1]:
        # shorten the string by 2
        data = data[0:i] + data[i+2:]

        # go back 1 index (to possible react something that was blocked)
        if i != 0:
            i -= 1
    else:
        i += 1

print(len(data))


# https://leetcode.com/problems/decode-the-message/
# 2325. Decode the Message
class Solution:
    def decodeMessage(self, key: str, message: str) -> str:
        subs = {' ': ' '}
        alpha = 'a'
        for c in key:
            if c in subs:
                continue
            subs[c] = alpha
            alpha = chr(ord(alpha) + 1)
            if alpha > 'z':
                break

        return ''.join([subs[c] for c in message])

print(Solution().decodeMessage('the quick brown fox jumps over the lazy dog',
                               'vkbs bs t suepuv'))
print(Solution().decodeMessage('eljuxhpwnyrdgtqkviszcfmabo',
                               'zwx hnfx lqantp mnoeius ycgk vcnjrdb'))


"""
https://www.imdb.com/title/tt0110475/
"""

import numpy as np

class MuraMaskCalculator:
    def __init__(self, L: int, size_mm = 22.08, thickness = 1.0, aperture_shape = "circle", aperture_radius_mm = 0.170):
        """
        Creates a Coded Aperture mask object. the main mask array is contained in self.mask_array but
            the simulation needs other info as well which is kept here. Default values are from the Rozhkov setup

        """
        self.L = L  # Rank of the mask
        self.mask_array = self.create(L)  # Creates the mask array

        # Mask Properties
        self.size_px = self.mask_array.shape[0]
        self.size_mm = size_mm  # height of the mask
        self.t = thickness # thickness of the mask. Unused
        self.aperture_shape = aperture_shape  # aperture shape of the mask. Unused
        self.aperture_radius_mm = aperture_radius_mm  # aperture radius. assumes circular apertures

        #Calculated vals
        self.pixel_mm = self.size_mm / self.size_px

    def create(self, L: int):
        # Creates the MURA NTHT mask based on quadratic residues with rank L.
        # This is just Tobi'S code slightly modified for readability

        quadratic_res = np.array([])
        for x in range(int(np.ceil(L / 2))):
            quadratic_res = np.append(quadratic_res, np.remainder(x ** 2, L))
        quadratic_res = np.unique(quadratic_res)
        A = np.zeros((L, L))
        for x in range(A.shape[0]):
            for y in range(A.shape[1]):
                x_is_quadratic_residue = np.any(np.in1d(quadratic_res, x))
                y_is_quadratic_residue = np.any(np.in1d(quadratic_res, y))
                if x == 0:
                    A[x, y] = 0
                elif y == 0 and x != 0:
                    A[x, y] = 1
                elif x_is_quadratic_residue and y_is_quadratic_residue:
                    A[x, y] = 1
                elif not x_is_quadratic_residue and not y_is_quadratic_residue:
                    A[x, y] = 1
                else:
                    A[x, y] = 0
        ntht = np.zeros((A.shape[0] * 2, A.shape[1] * 2))
        ntht[::2, ::2] = A
        ntht = np.rot90(ntht)
        ntht = np.tile(ntht, (2, 2))
        ntht = ntht[1:-2, 2:-1]
        return ntht


import pandas as pd
import numpy as np
from src.transform.data_transformation import RULAdder, ConstantColumnDropper
from src.transform.data_transformation import SequenceCreator, DataScaler

def test_RULAdder():
    transformer = RULAdder()

    # Create a sample DataFrame
    df = pd.DataFrame({
        'Engine': [1, 1, 1, 2, 2, 2],
        'Cycle': [1, 2, 3, 1, 2, 3]
    })

    # Apply RULAdder
    transformed_df = transformer.transform(df)

    # Assertions
    assert 'RUL' in transformed_df.columns
    assert 'max_cycle' not in transformed_df.columns
    assert all(transformed_df.query("Engine == 1")['RUL'] == [2, 1, 0])
    assert all(transformed_df.query("Engine == 2")['RUL'] == [2, 1, 0])

def test_ConstantColumnDropper():
    transformer = ConstantColumnDropper()

    # Create a sample DataFrame
    df = pd.DataFrame({
        'Engine': [1, 1, 1],
        'Cycle': [1, 2, 3],
        'Constant': [5, 5, 5],
        '(Physical Core Speed) (rpm)': [1000, 1000, 1000]
    })

    # Apply ConstantColumnDropper
    transformed_df = transformer.fit_transform(df)

    # Assertions
    assert 'Constant' not in transformed_df.columns
    assert '(Physical Core Speed) (rpm)' not in transformed_df.columns

def test_SequenceCreator():
    transformer = SequenceCreator(sequence_length=2)

    # Create a sample DataFrame
    df = pd.DataFrame({
        'Engine': [1, 1, 2, 2],
        'Cycle': [1, 2, 1, 2],
        'RUL': [1, 0, 1, 0]
    })

    # Apply SequenceCreator
    sequences, labels = transformer.transform_with_labels(df)

    # Assertions for transform_with_labels method
    assert sequences.shape == (2, 2, 2)
    assert all(labels == [0, 0])

def test_DataScaler():
    transformer = DataScaler()

    # Create a sample 3D array
    X = np.array([
        [[1, 2], [3, 4]],
        [[5, 6], [7, 8]]
    ])

    # Apply DataScaler
    transformed_X = transformer.fit_transform(X)

    # Assertions
    assert transformed_X.shape == X.shape
    assert transformed_X.min() >= 0
    assert transformed_X.max() <= 1


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

import numpy as np

class Model(nn.Module):
    def __init__(self, args):
        super(Model, self).__init__()
        self.input_layer = nn.Linear(1, 1000)
        self.activation = nn.GELU()
        self.output_layer = nn.Linear(1000, 1)

    def forward(
        self,
        x_enc,
        x_mark_enc,
        x_dec,
        x_mark_dec,
        enc_self_mask=None,
        dec_self_mask=None,
        dec_enc_mask=None,
    ):
        out = self.input_layer(x_enc)
        out = self.activation(out)
        out = self.output_layer(out)

        return out


from pathlib import Path

import pandas as pd
import pysam
from tqdm import tqdm

def split_bam_file_by_cell_barcodes(bam_file_path: Path,
                                    cell_barcodes: set[str],
                                    output_folder: Path) -> None:
    """
    Split .bam file to multiple smaller ones, each containing reads from a single cell.
    :param bam_file_path: Path to a .bam file with reads.
    :param cell_barcodes: Set of cell barcodes. Reads with barcodes not present in cell_barcodes will be ignored.
    :param output_folder: Folder to which the resulting files will be written.
    :return: None.
    """
    output_folder.mkdir(parents=True, exist_ok=True)
    samfile_input = pysam.AlignmentFile(bam_file_path, "rb")
    output_file_names_by_barcode = {barcode: output_folder / f"{barcode}.bam" for barcode in cell_barcodes}
    output_samfiles_by_barcode = {barcode: pysam.AlignmentFile(file_path, "wb",
                                                               template=samfile_input)
                                  for barcode, file_path in output_file_names_by_barcode.items()}
    for read in tqdm(samfile_input, desc=f'Processing reads from the input .bam file {bam_file_path}'):
        if not (read.has_tag('CB') and read.has_tag('UB') and read.get_tag('UB') != '-'):
            continue

        read_barcode = read.get_tag('CB')
        if read_barcode in cell_barcodes:
            output_samfiles_by_barcode[read_barcode].write(read)

    for samfile_output in output_samfiles_by_barcode.values():
        samfile_output.close()
    for file_name in tqdm(output_file_names_by_barcode.values(), desc='Indexing .bam files'):
        pysam.index(str(file_name))

def split_star_solo_output_by_cell_barcodes(star_solo_output_path: Path,
                                            output_folder_path: Path) -> None:
    barcodes_df = pd.read_csv(
        star_solo_output_path / Path('Solo.out/GeneFull/filtered/barcodes.tsv'),
        delimiter='\t',
        names=['barcode'])
    split_bam_file_by_cell_barcodes(
        bam_file_path=star_solo_output_path / 'Aligned.sortedByCoord.out.bam',
        cell_barcodes=set(barcodes_df['barcode']),
        output_folder=output_folder_path / star_solo_output_path.name)

if __name__ == "__main__":
    for folder in Path(
            '/cellfile/datapublic/jkoubele/leibniz_institute_data/aligned/20201014_582_KLR/GEX').iterdir():
        split_star_solo_output_by_cell_barcodes(star_solo_output_path=folder,
                                                output_folder_path=Path(
                                                    '/cellfile/datapublic/jkoubele/leibniz_institute_data/splitted_by_cells/20201014_582_KLR/GEX/'))


from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from data.kicker_data import get_kicker_data

def log_regression():
    x, y = get_kicker_data()
    scaler = StandardScaler()
    x_scaled = scaler.fit_transform(x)

    lr = LogisticRegression(C=1)
    lr.fit(x_scaled, y)
    return lr


#!/usr/bin/env python3

from os.path import isfile,getmtime
from glob import glob
from time import sleep,time
from os import system
import os
from subprocess import Popen,PIPE
import sys

sys.path.append('/home/ubuntu/shapeology_code/scripts')

from lib.utils import *

config = configuration(os.environ['yaml'])
params=config.getParams()

scripts_dir=params['paths']['scripts_dir']

local_data=params['paths']['data_dir']
script='process_file.py'
exec_dir=params['paths']['exec_dir']

if __name__=='__main__':
    Recent=False
    for logfile in glob(exec_dir+'/Controller*.log'):
        gap=time() - Last_Modified(logfile)
        if gap <120: # allow 2 minute idle
            print(logfile,'gap is %6.1f'%gap)
            Recent=True
            break
    if(not Recent):
        # Check that another 'controller' is not running
        stdout,stderr = runPipe('ps aux')
        Other_controller=False
        for line in stdout:
            if 'PopulateExtractedCells.py' in line:
                Other_controller=True
                break

        if Other_controller:
            print('Other PopulateExtractedCells.py is running')
        else:
            command='python3 {0}/PopulateExtractedCells.py'.format(exec_dir)
            output='{0}/logs/Controller-{1}.log'.format(exec_dir,int(time()))
            print('about to run',command,'withoutput=',output)
            run(command+' &> '+output + ' &')

            # Controller.py [-h] scripts_dir script s3location local_data


from OptitrackManager import OptitrackManager
from ArduinoManager import ArduinoManager
from RobotBase import RobotBase
import time
import threading
import math
import asyncio
from TelemetryManager import TelemetryManager
import transformations as tf
import random

optitrack_data = None
optitrack_id = 25
ultrasonic_data = None
robot = RobotBase()

def current_milli_time():
    return round(time.time() * 1000)

last_time = current_milli_time()

def q_to_angle(orient):
    euler = tf.euler_from_quaternion(orient)
    angle = euler[1]
    if(abs(euler[2]) < 2 or angle < 0):
        angle += ((math.pi / 2) - angle) * 2
    if(euler[1] < 0 and abs(euler[2]) > 2):
        angle += ((math.pi / 2) - abs(euler[1])) * 2
    return angle

class Coordinator:
    arduino = None
    optitrack = None
    telemetry = None

    ultrasonic_values = None
    optitrack_data = None

    def __init__(self):
        None

    def _ultrasonic_callback(self, values):
        values = [x or 999 for x in values]
        #print(values)
        self.ultrasonic_values = values

    def _optitrack_callback(self, bodies, markers, timing):
        optitrack_id = 25
        for body in bodies:
            if body.id_ != optitrack_id:
                continue
            self.optitrack_data = body
            #print(f'{body.position[0]}\t{body.position[1]}\t{body.position[2]}\t')

    async def start(self):
        self.arduino = ArduinoManager('/dev/ttyACM0', self._ultrasonic_callback)
        self.optitrack = OptitrackManager(self._optitrack_callback)
        self.telemetry = TelemetryManager(9090)

        print('Running all start sequences')
        await asyncio.gather(
            self.arduino.start(),
            self.optitrack.start(),
            self.telemetry.start(),
            self._loop()
        )

    async def _loop(self):
        await asyncio.sleep(1.0)
        print('Starting main loop')
        while True:
            if self.optitrack_data is None:
                await asyncio.sleep(1)
                print('Waiting for optitrack...')
                continue

            angle = q_to_angle(self.optitrack_data.orientation)
            angle = (angle + math.pi) % (math.pi * 2)
            robot.set_position((self.optitrack_data.position[0] * -1, self.optitrack_data.position[2]), angle)
            robot.set_ultrasonic(self.ultrasonic_values)
            #robot.set_ultrasonic([200, 200, 200, 200, 200])

            v, w = robot.get_velocity(self.telemetry.frame)
            w = w + random.uniform(-0.09, 0.09)
            v = v + random.uniform(-0.09, 0.09)
            #w = w * 1.1
            #v = min(v, -0.5)
            #v = 0

            self.arduino.send_speed(v, w)
            self.telemetry.send_frame()

            await asyncio.sleep(0.05)

    def kill(self):
        #self.arduino.send_kill()
        None

if __name__ == '__main__':
    coordinator = Coordinator()
    try:
        asyncio.get_event_loop().run_until_complete(coordinator.start())
    except KeyboardInterrupt:
        coordinator.kill()
        print('Killed by interrupt')