#!/usr/bin/env python
from __future__ import print_function
import pygame
from std_srvs.srv import Empty
from geometry_msgs.msg import Twist
from std_msgs.msg import Empty
from sensor_msgs.msg import Range
from nav_msgs.msg import Odometry
from ardrone_autonomy.msg import Navdata
from gazebo_msgs.srv import GetModelState, GetModelPropertiesRequest
from tf.transformations import euler_from_quaternion
from math import atan2
import rospy
import roslib
roslib.load_manifest('teleop_twist_keyboard')

#Modulos para obtencao dos status do drone
def ReceiverND1(Navdata):
    global status_1
    status_1 = Navdata.state

def ReceiverND2(Navdata):
    global status_2
    status_2 = Navdata.state

def ReceiverND3(Navdata):
    global status_3
    status_3 = Navdata.state

#Modulos para a obtencao das posicoes e angulos dos Drones
def XYT1(msg):
    global x1
    global y1
    global theta1

    x1 = msg.pose.pose.position.x
    y1 = msg.pose.pose.position.y

    rot_q = msg.pose.pose.orientation
    (roll, pitch, theta1) = euler_from_quaternion(
        [rot_q.x, rot_q.y, rot_q.z, rot_q.w])

def XYT2(msg):
    global x2
    global y2
    global theta2

    x2 = msg.pose.pose.position.x
    y2 = msg.pose.pose.position.y

    rot_q = msg.pose.pose.orientation
    (roll, pitch, theta2) = euler_from_quaternion(
        [rot_q.x, rot_q.y, rot_q.z, rot_q.w])

def XYT3(msg):
    global x3
    global y3
    global theta3

    x3 = msg.pose.pose.position.x
    y3 = msg.pose.pose.position.y

    rot_q = msg.pose.pose.orientation
    (roll, pitch, theta3) = euler_from_quaternion(
        [rot_q.x, rot_q.y, rot_q.z, rot_q.w])

#Modulos para imprimir a velocidade caso precise
def vels(speed, turn):
    return "currently:\tspeed %s\tturn %s " % (speed, turn)

#Modulos para a obtencao da altura dos drones
def ALT1(msg):
    global H1
    H1 = msg.range

def ALT2(msg):
    global H2
    H2 = msg.range

def ALT3(msg):
    global H3
    H3 = msg.range

#Modulo para o calculo das distancias entre os drones
def DistDrone(x1,x2,x3,y1,y2,y3):
    D12 = ((x1-x2)**2 + (y1-y2)**2)**(float(1)/2)

    D13 = ((x1-x3)**2 + (y1-y3)**2)**(float(1)/2)

    D23 = ((x3-x2)**2 + (y3-y2)**2)**(float(1)/2)

    return (D12, D13, D23)

#Modulo para o controle autonomo
def Auto_Control(x, y, theta1, Partida1, Destino1):
    xa = 0
    ya = 0
    za = 0
    tha = 0
    d = 0
    xi, yi = Partida1
    xf, yf = Destino1

    inc_x = xf - x
    inc_y = yf - y
    angle_to_goal = atan2(inc_y, inc_x)

    d = abs((yf - yi)*x + (xi - xf)*y + (xf*yi - xi*yf)) / \
            ((yi-yf)**2 + (xf-xi)**2)**(float(1)/2)

    if angle_to_goal - theta1 > 0.1:
        tha = 0.5
    elif angle_to_goal - theta1 < -0.1:
        tha = -0.5
    else:
        tha = 0
        # relacao do ponto a reta
        position = (xf - xi) * (y - yi) - (yf - yi) * \
            (x - xi)  # esquerda + e direita -

        if (d > 0.1 and position > 0):
            ya = -1
        elif d > 0.1 and position < 0:
            ya = 1
        else:
            ya = 0
            if yf - y > 0.05:
                xa = 1
            else:
                xa = 0

    return (xa, ya, tha, d)

#Modulo para o controle pelo usuario e que so funciona caso os drones estegam a mais de 2 metros de distancia
def Key_Control(keys, xa, ya, za, tha, D12, D13, D23):
    if (keys[pygame.K_w] and D12 > 2 and D13 > 2 and D23 > 2):
        x = 1

    elif (keys[pygame.K_s] and D12 > 2 and D13 > 2 and D23 > 2):
        x = -1
    else:
        x = xa

    if (keys[pygame.K_a] and D12 > 2 and D13 > 2 and D23 > 2):
        y = 1
    elif (keys[pygame.K_d] and D12 > 2 and D13 > 2 and D23 > 2):
        y = -1
        print("d")
    else:
        y = ya

    if (keys[pygame.K_LEFT] and D12 > 2 and D13 > 2 and D23 > 2):
        th = 1
        print("LEFT")
    elif (keys[pygame.K_RIGHT] and D12 > 2 and D13 > 2 and D23 > 2):
        th = -1
        print("RIGHT")
    else:
        th = tha

    if keys[pygame.K_UP]:
        z = 1
        print("UP")
    elif keys[pygame.K_DOWN]:
        z = -1
        print("Down")
    else:
        z = za

    return (x, y, z, th)

# subscrive para o sonar_height para pegar a altra dos drones
SubAL1 = rospy.Subscriber("/ardrone_1/sonar_height", Range, ALT1)
SubAL2 = rospy.Subscriber("/ardrone_2/sonar_height", Range, ALT2)
SubAL3 = rospy.Subscriber("/ardrone_3/sonar_height", Range, ALT3)

# subscrive para Navdata para pegar o status do Drone
SubND1 = rospy.Subscriber("/ardrone_1/navdata", Navdata, ReceiverND1)
SubND2 = rospy.Subscriber("/ardrone_2/navdata", Navdata, ReceiverND2)
SubND3 = rospy.Subscriber("/ardrone_3/navdata", Navdata, ReceiverND3)

# subscrive para ground_truth para pegar as posicoes do drone
SubOD1 = rospy.Subscriber("/ardrone_1/ground_truth/state", Odometry, XYT1)
SubOD2 = rospy.Subscriber("/ardrone_2/ground_truth/state", Odometry, XYT2)
SubOD3 = rospy.Subscriber("/ardrone_3/ground_truth/state", Odometry, XYT3)

# Publisher no cmd_vel para o controle dos drones
pub1 = rospy.Publisher('/ardrone_1/cmd_vel', Twist, queue_size=1)
pub2 = rospy.Publisher('/ardrone_2/cmd_vel', Twist, queue_size=1)
pub3 = rospy.Publisher('/ardrone_3/cmd_vel', Twist, queue_size=1)

# Publisher no takeoff para os drones planarem
pubo1 = rospy.Publisher('/ardrone_1/takeoff', Empty, queue_size=1)
pubo2 = rospy.Publisher('/ardrone_2/takeoff', Empty, queue_size=1)
pubo3 = rospy.Publisher('/ardrone_3/takeoff', Empty, queue_size=1)

# Publisher no land para os drones pousar
publ1 = rospy.Publisher('/ardrone_1/land', Empty, queue_size=1)
publ2 = rospy.Publisher('/ardrone_2/land', Empty, queue_size=1)
publ3 = rospy.Publisher('/ardrone_3/land', Empty, queue_size=1)
vazio = Empty()

# Cria um node no servidor ros
rospy.init_node('LaSid')

# Coloca os valores da velocidade de movimentacao e rotacao
speed = rospy.get_param("~speed", 0.5)
turn = rospy.get_param("~turn", 1.0)

# Inicacao de alguns parametros
xa, xb, xc = 0 ,0 ,0
ya, yb, yc = 0 ,0 ,0
za, zb, zc = 0 ,0 ,0
tha, thb, thc = 0 ,0 ,0
d1, d2, d3 = 0, 0, 0
D12, D13, D23 = 0, 0, 0

# Define as posicoes iniciais e finais dos drones
Partida1 = (6, -8)
Destino1 = (6, 8)

Partida2 = (2, -8)
Destino2 = (2, 8)

Partida3 = (-2, -8)
Destino3 = (-2, 8)

# Linha de comando necessario para conexao com o ros
r = rospy.Rate(4)

# Inicia o pygame
pygame.init()

# Tamanho da tela
pygame.display.set_mode((800, 300))

looping = True

# Variavel responsavel qual drone sera controlado
ConDrone = 0

while looping:

    # Pega os valores das distancias entre os drones
    D12, D13, D23 = DistDrone(x1,x2,x3,y1,y2,y3)

    # Verifica os botoes apertados na tela do pygame
    for event in pygame.event.get():
        # Se apertar o botao de fechar ele fecha a tela
        if event.type == pygame.QUIT:
            looping = False

        #Verifica os botoes que foram apertados
        if event.type == pygame.KEYDOWN:

            # Se o botao V o drone selecionado plana
            if event.key == pygame.K_v:
                if ConDrone == 1:
                    pubo1.publish(vazio)

                elif ConDrone ==  2:
                    pubo2.publish(vazio)

                elif ConDrone == 3:
                    pubo3.publish(vazio)

            # Se apertar o botao B o drone selecionado ira pousar
            if event.key == pygame.K_b:
                if ConDrone == 1:
                    publ1.publish(vazio)
                elif ConDrone == 2:
                    publ2.publish(vazio)
                elif ConDrone == 3:
                    publ3.publish(vazio)

            # Se o botao de 1 a 4 for apertado muda o drone a ser controlado
            # O 4 ira servir para todos os drones planarem
            if event.key == pygame.K_1:
                ConDrone = 1
            if event.key == pygame.K_2:
                ConDrone = 2
            if event.key == pygame.K_3:
                ConDrone = 3
            if event.key == pygame.K_4:
                ConDrone = 4

    # Caso o botao 4 tenha sido apertado todos os drones irao planar
    if ConDrone == 4:
        ConDrone = 1
        pubo1.publish(vazio)
        pubo2.publish(vazio)
        pubo3.publish(vazio)

    # Pega os valores x, y , th dos drones no controle autonomo e a distancia ate o destino
    xa, ya, tha, d1 = Auto_Control(x1, y1, theta1, Partida1, Destino1)
    xb, yb, thb, d2 = Auto_Control(x2, y2, theta2, Partida2, Destino2)
    xc, yc, thc, d3 = Auto_Control(x3, y3, theta3, Partida3, Destino3)

    # Pega os botoes que estao sendo pressionados
    keys = pygame.key.get_pressed()

    # A depender do drone selecionado pega os valores de x ,y, th dos drone pelo controle de usuario
    if ConDrone == 1:
        xa, ya, za, tha = Key_Control(keys, xa, ya, za, tha, D12, D13, D23)
    elif ConDrone == 2:
        xb, yb, zb, thb = Key_Control(keys, xb, yb, zb, thb, D12, D13, D23)
    elif ConDrone == 3:
        xc, yc, zc, thc = Key_Control(keys, xc, yc, zc, thc, D12, D13, D23)

    # Bloco para os Drones esperarem uns aos outros
    if abs(  (Destino1[1] - y1) - (Destino2[1] - y2) )  > 1:
        if (Destino1[1] - y1) < (Destino2[1] - y2)  and (xa != -1):
            xa = 0
        if (Destino1[1] - y1) > (Destino2[1] - y2)  and (xb != -1):
            xb = 0
    if abs(  (Destino1[1] - y1) - (Destino3[1] - y3) )  > 1:
        if (Destino1[1] - y1) < (Destino3[1] - y3)  and (xa != -1):
            xa = 0
        if (Destino1[1] - y1) > (Destino3[1] - y3)  and (xc != -1):
            xc = 0
    if abs(  (Destino3[1] - y3) - (Destino2[1] - y2) )  > 1:
        if (Destino3[1] - y3) < (Destino2[1] - y2)  and (xc != -1):
            xc = 0
        if (Destino3[1] - y3) > (Destino2[1] - y2)  and (xb != -1):
            xb = 0

    # Bloco para os drones pousarem quando chegarem no destino
    if ( abs((Destino1[1] - y1) ) < 0.2 ):
        publ1.publish(vazio)
        xa, ya, za = 0, 0, 0
    if ( abs((Destino2[1] - y2))  < 0.2 ):
        publ2.publish(vazio)
        xb, yb, zb = 0, 0, 0
    if ( abs((Destino3[1] - y3))  < 0.2 ):
        publ3.publish(vazio)
        xc, yc, zc = 0, 0, 0

    # Bloco de protecao para um dos drones nao chegar mais perto que 1.5, se chega o que estive em sua rota pousa
    if (D12 < 1.5):
        if (d1 > d2):
            publ2.publish(vazio)
        else:
            publ1.publish(vazio)

    if (D13 < 1.5):
        if (d1 > d3):
            publ3.publish(vazio)
        else:
            publ1.publish(vazio)

    if (D23 < 1.5):
        if (d2 > d3):
            publ3.publish(vazio)
        else:
            publ2.publish(vazio)

    # Cria modulos de movimentacao para cada um dos drones
    twist1 = Twist()
    twist2 = Twist()
    twist3 = Twist()

    # Modifica os valores de movimentacao do drone 1
    twist1.linear.x = xa*speed
    twist1.linear.y = ya*speed
    twist1.linear.z = za*speed
    twist1.angular.x = 0
    twist1.angular.y = 0
    twist1.angular.z = tha*turn

    # Publica os valores de movimentacao do drone 1
    pub1.publish(twist1)

    # Modifica os valores de movimentacao do drone 2
    twist2.linear.x = xb*speed
    twist2.linear.y = yb*speed
    twist2.linear.z = zb*speed
    twist2.angular.x = 0
    twist2.angular.y = 0
    twist2.angular.z = thb*turn

    # Publica os valores de movimentacao do drone 1
    pub2.publish(twist2)

    # Modifica os valores de movimentacao do drone 3
    twist3.linear.x = xc*speed
    twist3.linear.y = yc*speed
    twist3.linear.z = zc*speed
    twist3.angular.x = 0
    twist3.angular.y = 0
    twist3.angular.z = thc*turn
    # Publica os valores de movimentacao do drone 3
    pub3.publish(twist3)

    r.sleep()
pygame.quit()


# Inheritance is sharing functionalities among multiple classes

from OOP import ApplePhone

class Iphone8(ApplePhone):
    serial_number = 0
    owner = None

    def __init__(self, camera, processor, screen_size):
        self.camera = camera
        self.processor = processor
        self.screen_size = screen_size

    def get_screen_size(self):
        print("the size of screen is %s inches" % self.screen_size)

    def get_processor(self):
        print("the processor of the phone is %s MHz" % self.processor)

    @classmethod
    def update_serial_number(cls):
        cls.serial_number += 1
        cls.owner = "ABC"
        print("The serial number of the is %s" % cls.serial_number)
        print("The owner is %s" % cls.owner)

def f1(): # this is an independent function and what is inside the function should have four spaces gap
    iphone_81= Iphone8(60, 200, 6)
    iphone_81.get_processor()
    iphone_81.get_screen_size()
    iphone_81.can_call()
    iphone_81.click_pic()
    iphone_81.update_serial_number()

    iphone_82 = Iphone8(100, 500, 5)
    iphone_82.get_processor()
    iphone_82.get_screen_size()
    iphone_82.can_call()
    iphone_82.click_pic()
    iphone_82.update_serial_number()

f1()

#types of inheritance
# 1. Single Inheritance = one parent , one child
# 2. Multiple Inheritance = 2 parents, 1 child
# 3. Multilevel Inheritance = 1 parent, 1 child(parent), 1 child
# 4. Hierarchical Inheritance = 1 parent, multiple child
# 5. Hybrid Inheritance = combination of more than one inheritance

#assignment  Implement the above inheritance type with University


from .base_data_module import BaseDataModule
from .processor import get_dataset,processors
from transformers import AutoTokenizer

from dataclasses import dataclass
from torch.utils.data import DataLoader

import random
import warnings
from typing import Any,Dict,List,Tuple,Optional,Union

from transformers.file_utils import PaddingStrategy
from transformers.models.bert import BertTokenizer, BertTokenizerFast
from transformers.tokenization_utils_base import BatchEncoding, PreTrainedTokenizerBase

class ESL(BaseDataModule):
    def __init__(self,args)->None:
        super().__init__(args)
        self.processor = processors[self.args.task_name](self.args.data_dir,self.args.use_prompt)
        self.tokenizer = AutoTokenizer.from_pretrained(self.args.model_name_or_path)

        self.num_labels = len(self.processor.get_labels())

        event_list = ["[subject_start]","subject_end","object_start","object_end"]
        class_list = [f"[class{i}]" for i in range(0,self.num_labels)]

        num_add_tokens = self.tokenizer.add_special_tokens({"additional_special_tokens":event_list})
        num_add_tokens = self.tokenizer.add_special_tokens({"additional_special_tokens":class_list})

        so_list = ["[sub]","[obj]"]
        num_add_toens = self.tokenizer.add_special_tokens({"additional_special_tokens":so_list})

        prompt_tokens = [f"[T{i}]" for i in range(1,6)]
        self.tokenizer.add_special_tokens({'additional_special_tokens': prompt_tokens})

    def setup(self,stage=None):
        self.data_train = get_dataset("train",self.args,self.tokenizer,self.processor)
        self.data_val = get_dataset("dev",self.args,self.tokenizer,self.processor)
        self.data_test = get_dataset("test",self.args,self.tokenizer,self.processor)

    def prepare_data(self):
        pass

    def get_tokenizer(self):
        return self.tokenizer

    @staticmethod
    def add_to_argparse(parser):
        BaseDataModule.add_to_argparse(parser)
        parser.add_argument("--task_name",type=str,default="normal",help="[normal,reloss,ptune]")
        parser.add_argument("--model_name_or_path",type=str,default="/home/tanwen/bert-base-uncased",help="Number of examples to operate on per forward step.")
        parser.add_argument("--max_seq_length",type=int,default=512,help="the max sequence word length")
        parser.add_argument("--ptune-k",type=int,default=7,help="experiment to research few-shot")


from graphics import *

# pending 3 - 11

def circle_program():
    win = GraphWin()
    shape = Circle(Point(50, 50), 20)
    shape.setOutline("red")
    shape.setFill("red")
    shape.draw(win)
    for i in range(10):
        p = win.getMouse()
        c = shape.getCenter()
        dx = p.getX() - c.getX()
        dy = p.getY() - c.getY()
        shape.move(dx, dy)
    win.close()

def square_program():
    win = GraphWin()
    square = Rectangle(Point(50, 50), Point(90, 90))
    square.setOutline("red")
    square.setFill("red")
    square.draw(win)
    c = square.getCenter()
    for i in range(10):
        p = win.getMouse()
        new_square = square.clone()
        new_square.move(p.getX() - c.getX(), p.getY() - c.getX())
        new_square.draw(win)
    text = Text(Point(100, 30), "Click again to quit")
    text.draw(win)
    win.getMouse()
    win.close()

def archery_program():
    """
    This program draws an archery target.
    """
    initial_radius = eval(input("Enter the radius of the yellow circle: "))

    circles = ["white", "black", "blue", "red", "yellow"]
    len_circles = len(circles)

    radius = initial_radius * len_circles

    win = GraphWin()
    for color in circles:

        circle = Circle(Point(100, 90), radius)
        circle.setOutline(color)
        circle.setFill(color)
        circle.draw(win)

        radius = radius - initial_radius

    text = Text(Point(100, 180), "Click again to quit")
    text.draw(win)
    win.getMouse()
    win.close()

def main():
    options = {1: circle_program,
               2: square_program,
               3: archery_program}

    menu = """ Menu:
               Press 1 to execute "Circle Program"
               Press 2 to execute "Square Program"
               Press 3 to execute "Archery Program"
               """
    print(menu)
    option = eval(input())
    options[option]()

main()


from pde import PDE, ScalarField, CartesianGrid, MemoryStorage, plot_kymograph

NX = 100 # number of cells in x
TMAX = 220 # time
DT = .01 # step

def simulate_ks_1d(nx:int = NX,
                   tmax:float = TMAX,
                   dt:float = DT,
                   state:ScalarField = None,
                   ) -> MemoryStorage:
    if not (isinstance(state, ScalarField) and state):
        grid = CartesianGrid([[1, nx]], [nx], periodic=True)
        state = ScalarField.from_expression(grid, "sin(x)")
        #state = ScalarField.random_uniform(grid)
    else:
        grid = state.grid
    sim = MemoryStorage()
    eq = PDE({"u": "-gradient_squared(u) / 2 - laplace(u + laplace(u))"})
    eq.solve(state, t_range = tmax, dt = dt, tracker = sim.tracker(10 * dt))
    return sim

if __name__ == '__main__':
    sim = simulate_ks_1d()
    plot_kymograph(sim)


"""
Dependency Minimal Recursion Semantics ([DMRS]_)

.. [DMRS] Copestake, Ann. Slacker Semantics: Why superficiality,
  dependency and avoidance of commitment can be the right way to go.
  In Proceedings of the 12th Conference of the European Chapter of
  the Association for Computational Linguistics, pages 1–9.
  Association for Computational Linguistics, 2009.
"""

from delphin.dmrs._exceptions import (
    DMRSError,
    DMRSSyntaxError,
    DMRSWarning,
)
from delphin.dmrs._dmrs import (
    DMRS,
    Node,
    Link,
    FIRST_NODE_ID,
    RESTRICTION_ROLE,
    BARE_EQ_ROLE,
    EQ_POST,
    HEQ_POST,
    NEQ_POST,
    H_POST,
    CVARSORT,
)
from delphin.dmrs._operations import from_mrs
# Default modules need to import the PyDelphin version
from delphin.__about__ import __version__  # noqa: F401

__all__ = [
    'FIRST_NODE_ID',
    'RESTRICTION_ROLE',
    'BARE_EQ_ROLE',
    'EQ_POST',
    'HEQ_POST',
    'NEQ_POST',
    'H_POST',
    'CVARSORT',
    'DMRS',
    'Node',
    'Link',
    'from_mrs',
    'DMRSError',
    'DMRSSyntaxError',
    'DMRSWarning',
]


#{
 # Driver Code Starts
#Initial Template for Python 3

# } Driver Code Ends
#User function Template for python3

class Solution:
    def insertNewEvent(self, N, intervals, newEvent):
        # Code here
        intervals.append(newEvent)
        intervals.sort(key=lambda i:i[0])
        res = [intervals[0]]
        for x1, y1 in intervals[1:]:
            x, y = res[-1]
            if x1<=y:res[-1][1]=max(y, y1)
            else:res.append([x1, y1])
        return res

#{
 # Driver Code Starts.
if __name__ == '__main__':
    t = int(input ())
    for _ in range (t):
        N = int(input())
        intervals = [list(map(int, input().split())) for i in range(N)]
        newEvent = list(map(int, input().split()))
        ob = Solution()
        res = ob.insertNewEvent(N, intervals, newEvent)
        print('[', end = '')
        for i in range(len(res)):
            print('[', end = '')
            print(str(res[i][0])+','+str(res[i][1]), end = '')
            print(']', end = '')
            if i < len(res)-1:
                print(',', end='')
        print(']')
# } Driver Code Ends


'''
Code for generating the optical flow and normalising videos. Based on Koki's
code from :
https://github.com/liwii/naked-people-tools

The normalisation is done in the same way as the original I3C paper.
'''
import numpy as np
import cv2
import skvideo.io
from pathlib import Path

def get_len(filepath:str):
    # Get the number of frames in a video
    cap = cv2.VideoCapture(filepath)
    length =  int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    cap.release()
    return length

def get_flow_rgb(filepath: str):
    # Get the optical flow using OpenCV
    # https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_video/py_lucas_kanade/py_lucas_kanade.html

    # flow.shape (2, frame_count, height, width)
    # flow[0] is dx, flow[1] is dy
    # Use TV-L1 algorithm instead, since it is used in mlb-youtube dataset
    # https://www.ipol.im/pub/art/2013/26/article.pdf

    cap = cv2.VideoCapture(filepath)
    length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    _, frame1 = cap.read()
    prvf = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
    flow_video = []
    rgb_video = [frame1]
    for i in range(length - 1):
        success, frame2 = cap.read()
        if not success:
            break
        rgb_video.append(frame2)
        nextf = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
        optical_flow = cv2.optflow.createOptFlow_DualTVL1()
        flow_frame = optical_flow.calc(prvf, nextf, None)
        # flow_frame = cv2.calcOpticalFlowFarneback(prvf,nextf, None, 0.5, 3, 15, 3, 5, 1.2, 0)
        flow_video.append(flow_frame)
        prvf = nextf
    cap.release()
    flow_video = np.array(flow_video)
    rgb_video = np.array(rgb_video)
    return flow_video, rgb_video[:-1]

def normalise_rgb(rgb):
    # For rgb we just center and normalise
    rgb = rgb.astype(np.float16)
    rgb -= 127.5
    rgb /= 127.5
    return rgb

def normalise_flow(flow):
    # For the flow, we truncate to +- 20, and then normalise
    flow = np.clip(flow, -20,20)
    flow /= 20
    return flow


import cv2
import numpy as np

def minutiae_at(pixels, i, j, kernel_size): #kesisme sayisi yontemi sirt uclarini ve catallari tespit etmek icin kullanilmakta
    #geçiş sayısı algoritması 3x3 piksel bloklarına bakılacaktir #orta piksel siyahsa (sırt icin)
    if pixels[i][j] == 1: # pixelin boyutu bir ise
        if kernel_size == 3: #3x3 boyut matris oluşturulur
            cells = [(-1, -1), (-1, 0), (-1, 1),        # p1 p2 p3
                   (0, 1),  (1, 1),  (1, 0),            # p8    p4
                  (1, -1), (0, -1), (-1, -1)]           # p7 p6 p5
        else:
            cells = [(-2, -2), (-2, -1), (-2, 0), (-2, 1), (-2, 2),                 # p1 p2 p3
                   (-1, 2), (0, 2),  (1, 2),  (2, 2), (2, 1), (2, 0),               # p8    p4
                  (2, -1), (2, -2), (1, -2), (0, -2), (-1, -2), (-2, -2)]           # p7 p6 p5
        values = [pixels[i + l][j + k] for k, l in cells] #0'dan 1'e kaç kez gectigi sayilir
        crossings = 0
        for k in range(0, len(values)-1):
            crossings += abs(values[k] - values[k + 1]) #sifirdan bire gitme sayisi
        crossings //= 2
        if crossings == 1: #sinirdaki piksel sırtla bir kez kesisirse
            return "ending" #sırt sonudur
        if crossings == 3: #sinirdaki piksel sırtla uc kez kesisirse
            return "bifurcation" #sirt catalanmasidir
    return "none"

def calculate_minutiaes(im, kernel_size=3): #3x3 matris ile minutiaes noktalarını hesaplayan fonksiyon
    biniry_image = np.zeros_like(im)
    biniry_image[im<10] = 1.0
    biniry_image = biniry_image.astype(np.int8)
    (y, x) = im.shape
    result = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB) #resim renkli hale getirilir
    colors = {"ending" : (150, 0, 0), "bifurcation" : (0, 150, 0)} #catallanma nokt. mavi, uc nokt. kırmızı olur
    for i in range(1, x - kernel_size//2): #her piksel minutia'ını itere ettik
        for j in range(1, y - kernel_size//2):
            minutiae = minutiae_at(biniry_image, j, i, kernel_size) #her piksel icin minutai yineleme
            if minutiae != "none":
                cv2.circle(result, (i,j), radius=2, color=colors[minutiae], thickness=2) #noktalar r=2 olan daireler ile belirtildi
    return result


'''
counting
'''

'''
count example
'''
# ccc = dict()
# ccc['csev'] = 1
# ccc['cwen'] = 1

# print(ccc)

# ccc['cwen'] = ccc['cwen'] + 1
# print(ccc)

'''Dictionaries Tracebacks
Error to reference key which is not in the dictionary
Use "in" operator to see if a key is in the dictionary
'''
# ccc = dict()
# print(ccc['csev'])
# 'csev' in ccc

'''When we see a new Name
'''
# counts = dict()
# names = ['csev','cwen','csev','zqian','csev']
# for name in names :
#     if name not in counts:
#         counts[name] = 1
#     else:
#         counts[name] = counts[name] + 1
# print(counts)

# if name in counts:
#     x = counts[name]
# else:
#     x = 0

# x = counts.get(name, 0)
'''When we see a new Name
Simplified counting with get()
'''
counts = dict()
names = ['csev','cwen','csev','zqian','csev']
for name in names :
    counts[name] = counts.get(name, 0) + 1
print(counts)


# -*- coding: utf-8 -*-
# Scrapy settings for Visions project
from datetime import datetime
import os

BOT_NAME = 'Visions'

SPIDER_MODULES = ['Visions.spiders']
NEWSPIDER_MODULE = 'Visions.spiders'

LOG_ENABLED = True
LOG_ENCODING = 'utf-8'
timestamp = datetime.now().strftime('%Y-%b-%d:%I-%M-%p')
LOG_FILE = str(os.getcwd() + '/Visions/LOGS/' + BOT_NAME + '-' + timestamp + '.log')

# Export results, as a json feed, to file
FEED_DIR = '/'.join(os.getcwd().split('/')[:-1]) + '/Visions/Visions/FEEDS/'
FEED_URI = 'file:///' + FEED_DIR + timestamp + '.json'
FEED_FORMAT = 'json'

FEED_EXPORTERS = {
     'json': 'scrapy.contrib.exporter.JsonItemExporter',
}


"""
Weave Grid
"""

from .grid import (
    Grid,
    Cell,
    CellOver,
    CellUnder,
)

class GridWeave(Grid):
    """
    Weave Grid
    """

    def __init__(self, *args, use_kruskal: bool = False, weave: int = 0, **kwargs):
        self.use_kruskal = use_kruskal
        self.weave = weave / 100
        super().__init__(*args, **kwargs)

    def prepare_grid(self):
        if self.use_kruskal:
            CellOver.get_neighbors = lambda: Cell.neighbors
        else:
            CellOver.get_neighbors = lambda: CellOver.neighbors_copy

        for l in range(self.levels):
            for c in range(self.columns):
                for r in range(self.rows):
                    self[c, r, l] = CellOver(r, c, l) if self[c, r, l] is None else None
                    self[c, r, l].request_tunnel_under += lambda cell, neighbor: self.tunnel_under(neighbor)

    def tunnel_under(self, cell_over):
        """
        Tunnel under the specified cell of type 'CellOver'

        Returns the resulting 'CellUnder'
        """
        new_cell = CellUnder(cell_over)
        self._cells.append(new_cell)
        self._union_find.data[new_cell] = new_cell
        return new_cell


#!/usr/bin/python3
""" Computes perimeter of an island """

def island_perimeter(grid):
    """ island_perimeter:

        Args:
            grid, a list of list of integers

        Return: perimeter of the island described in grid
    """

    rows = len(grid)
    cols = len(grid[0])
    perimeter = 0
    for i in range(rows):
        for j in range(cols):
            if grid[i][j] == 1:
                if i == 0 or grid[i-1][j] == 0:
                    perimeter += 1
                if i == rows-1 or grid[i+1][j] == 0:
                    perimeter += 1
                if j == 0 or grid[i][j-1] == 0:
                    perimeter += 1
                if j == cols-1 or grid[i][j+1] == 0:
                    perimeter += 1
    return perimeter


#User function Template for python3

class Solution:
    def countSpecialNumbers(self, N, arr):
        # Code here
        m = max(arr)
        res = [0]*(m+1)
        for a in arr:
            if res[a] <= 1:
                for b in range(a, m+1, a):
                    res[b] += 1
        return sum(res[a] > 1 for a in arr)

#{
 # Driver Code Starts
#Initial Template for Python 3

if __name__ == '__main__':

    T = int(input())
    while T > 0:
        N=int(input())
        arr = [int(i) for i in input().split()]
        ob = Solution()
        print(ob.countSpecialNumbers(N, arr))

        T -= 1
# } Driver Code Ends


from robustness.model_utils import make_and_restore_model
from robustness.datasets import CIFAR, CustomCIFAR
import sys
import numpy as np
import os
from scipy.special import softmax, expit
import torch
from torch.utils.data import TensorDataset, DataLoader

def check_normal(preds, labels):
	pred_labels = np.argmax(softmax(preds, axis=-1), axis=-1)
	print('acc:', np.mean(pred_labels==labels))

def check_hamming(dim, scores, labels, t, name):
	scores = expit(scores)
	if not os.path.exists('eval/hamming/hamming_labels_{}.npy'.format(name)):
		idxs = np.arange(dim)
		rep = np.load('../data/rnd_label_c10_5.npy')[idx].T
		samples = np.array([[1 if u >= 0.5 else 0 for u in v] for v in scores])
		preds, preds_dist, preds_score = [], [], []
		for i in np.arange(samples.shape[0]):
			_pred = np.repeat(samples[i].reshape((-1, len(samples[i]))), rep.shape[0], axis=0)
			dists = np.sum(np.absolute(_pred - rep), axis=1)
			min_dist = np.min(dists)
			pred_labels = np.arange(len(dists))[dists==min_dist]
			pred_scores = [np.sum([scores[i][k] if samples[i][k] == rep[j][k] else 1-scores[i][k] for k in np.arange(len(scores[i]))]) for j in pred_labels]
			pred_label = pred_labels[np.argmax(pred_scores)]
			preds.append(pred_label)
			preds_dist.append(dists[pred_label])
			preds_score.append(np.max(pred_scores))
		np.save('eval/hamming/hamming_labels_{}.npy'.format(name), preds)
		np.save('eval/hamming/hamming_labels_dists_{}.npy'.format(name), preds_dist)
		# np.save('eval/hamming/hamming_labels_score_{}.npy'.format(name), preds_score)
		preds = np.array(preds)
		preds_dist = np.array(preds_dist)
	else:
		preds = np.load('eval/hamming/hamming_labels_{}.npy'.format(name))
		preds_dist = np.load('eval/hamming/hamming_labels_dists_{}.npy'.format(name))
	print('avg Hamming distance:{}, max:{}, min:{}, med:{}'.format(np.mean(preds_dist), np.max(preds_dist), np.min(preds_dist), np.median(preds_dist)))
	print(t, 'acc:', np.sum(preds_dist[preds == labels] < t) / len(labels))
	print(t, 'acc:', np.sum(preds_dist[preds != labels] < t) / len(labels))

def main():
	path = sys.argv[-1]
	metrics = sys.argv[-2]

	name = 'pred'
	if sys.argv[-3].startswith('advs'):
		name+= '_advs'

	if not os.path.exists('eval/{}_{}.npy'.format(name, path.split('/')[-1][:-3])):
		if path.endswith('_best.pt'):
			ds = CustomCIFAR(int(path.split('/')[-1].split('_')[0]), '/home/zhuzby/data')
		else:
			ds = CIFAR('/home/zhuzby/data')
		model, _ = make_and_restore_model(arch='resnet50', dataset=ds, resume_path=path)
		model = model.eval()
		if sys.argv[-3].startswith('advs'):
			im_adv = np.load(sys.argv[-3])
			labs = np.load(os.path.join(sys.argv[-3].split('/')[0], 'labels_'+sys.argv[-3].split('/')[1]))
			data = TensorDataset(torch.tensor(im_adv), torch.tensor(labs))
			test_loader = DataLoader(data, batch_size=128, num_workers=8, shuffle=False)
		else:
			_, test_loader = ds.make_loaders(workers=8, batch_size=128)
		preds, labels = [], []
		for i, (im, label) in enumerate(test_loader):
			output, _ = model(im)
			label = label.cpu().numpy()
			preds = output.detach().cpu().numpy() if len(preds)==0 else np.vstack((preds, output.detach().cpu().numpy()))
			labels = label if len(labels)==0 else np.hstack((labels, label))
		np.save('eval/{}_{}.npy'.format(name, path.split('/')[-1][:-3]), preds)
		np.save('eval/label_{}.npy'.format(path.split('/')[-1][:-3]), labels)
	else:
		preds = np.load('eval/{}_{}.npy'.format(name, path.split('/')[-1][:-3]))
		labels = np.load('eval/label_{}.npy'.format(path.split('/')[-1][:-3]))

	if metrics == 'origin':
		check_normal(preds, labels)
	elif metrics == 'hamming':
		check_hamming(int(path.split('/')[-1].split('_')[0]), preds, labels, int(sys.argv[-4]), path.split('/')[-1][:-3])

if __name__ == '__main__':
	main()

multi-label non robust training/evaluate.py


from operator import itemgetter

K = 450
with open("input.txt", "r") as f:
    seq = f.readlines()

in_parties = {}
in_sigma = 0

for s in seq:
    split = s.split()
    name = ' '.join(split[:-1])
    cnt = int(split[-1])

    if name not in in_parties.keys():
        in_parties[name] = 0

    in_parties[name] += cnt
    in_sigma += cnt

def fill_missing(mods, res, sigma_places):
    mods = sorted(mods, key=itemgetter(1), reverse=True)
    mods = sorted(mods, key=itemgetter(2), reverse=True)

    for i in range(K - sigma_places):
        res[mods[i][0]] += 1

    return res

def count_places(parties, sigma):
    res = {}
    mods = []
    sigma_places = 0

    for name in parties.keys():
        res[name] = parties[name] * K // sigma
        sigma_places += res[name]
        mods.append((name, parties[name], parties[name] * K % sigma))

    return fill_missing(mods, res, sigma_places)

for k, v in count_places(in_parties, in_sigma).items():
    print(k, v)


import cv2
import numpy as np
# matrix = [
#     [0,0,0],
#     [0,0,0],
#     [0,0,0],
#     ]
img =  cv2.imread('images/1.jpg')
img = cv2.resize(img, (img.shape[1] // 2,img.shape[0] // 2))
#размытие - только нечетные
img = cv2.GaussianBlur(img, (9,9),0)
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img = cv2.Canny(img, 200,200)
kernel = np.ones((5,5), np.uint8)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, kernel, iterations=1)
#cv2.imshow('Result',img)
#img[0:150,0:150]
cv2.imshow('Result',img)
print(img.shape)
cv2.waitKey(0)


from django.http import HttpResponse
from django.shortcuts import render
from testModel.models import Admin

def hello(request):

    #return HttpResponse("Hello world !I am kumanxuan!! ")

    #return render(request,'test.html')
    methodC = {}
    if (request.method=='GET'):
        methodC['method']='这个是一一个Get处理方法'
    else:
        methodC['method']='这个是一一个Post处理方法'

    #admin = Admin(name='kumanxuan',detail='666',description='No why!')
    #admin.save()
    #成功向数据库插入数据，现在插上提取数据。
    res = Admin.objects.all()

    listName = []
    listDescription = []

    #print(res.item())

    for x in res:
        #pass
     #for y in range(0,2):
        listName.append(x.name)
        listDescription.append(x.description)
    #methodC['dbInfo'] = res

    #当循环储存好数值之后，就把列表的数值赋值给字典。
    methodC['name'] = listName
    methodC['description'] = listDescription
    print(methodC)
    return render(request,'test.html',methodC)

##哦哦，原来这个地方的VIEW是相当于php里面的MVC结构里面的Controller啦。
def TestModelSql(request):
    pass


from abc import ABC, abstractmethod
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset

from h01_data.process import get_data_file_base as get_file_names
from util import util

class BaseDataset(Dataset, ABC):
    # pylint: disable=too-many-instance-attributes

    def __init__(self, data_path, language, representation, embedding_size,
                 mode, classes=None, words=None, max_instances=None):
        self.data_path = data_path
        self.language = language
        self.mode = mode
        self.representation = representation
        self.embedding_size = embedding_size
        self.max_instances = max_instances

        self.input_name_base = get_file_names(data_path, language)
        self.process(classes, words)

        assert len(self.x) == len(self.y)
        self.n_instances = len(self.x)

    def process(self, classes, words):
        if self.representation not in ['onehot', 'random']:
            self._process(classes)
            self.words = words
            self.n_words = None
        else:
            self._process_index(classes, words)

    def _process_index(self, classes, words):
        x_raw, y_raw = self.load_data(self.iterate_index)

        self.load_index(x_raw, words=words)
        self.load_classes(y_raw, classes=classes)

    def _process(self, classes):
        x_raw, y_raw = self.load_data(self.iterate_embeddings)

        self.load_embeddings(x_raw)
        self.load_classes(y_raw, classes=classes)

    def load_data(self, iterator):
        x_raw, y_raw = self._load_data(iterator)
        if self.max_instances is not None:
            x_raw = x_raw[:self.max_instances]
            y_raw = y_raw[:self.max_instances]
        return x_raw, y_raw

    @abstractmethod
    def _load_data(self, iterator):
        pass

    def iterate_index(self):
        data_ud = util.read_data(self.input_name_base % (self.mode, 'ud'))

        for (sentence_ud, words) in data_ud:
            yield sentence_ud, np.array(words)

    def iterate_embeddings(self):
        data_ud = util.read_data(self.input_name_base % (self.mode, 'ud'))
        data_embeddings = util.read_data(self.input_name_base % (self.mode, self.representation))

        for (sentence_ud, _), sentence_emb in zip(data_ud, data_embeddings):
            yield sentence_ud, sentence_emb

    def load_embeddings(self, x_raw):
        self.assert_size(x_raw)
        self.x = torch.from_numpy(x_raw)

    def assert_size(self, x):
        assert len(x[0]) == self.embedding_size

    @abstractmethod
    def load_index(self, x_raw, words=None):
        pass

    def load_classes(self, y_raw, classes=None):
        self.y, self.classes = self.factorize(y_raw, classes)
        self.n_classes = self.classes.shape[0]

    def factorize(self, data_raw, classes=None):
        if self.mode != 'train':
            assert classes is not None

        if classes is None:
            data, classes = pd.factorize(data_raw, sort=True)
        else:
            new_classes = set(data_raw) - set(classes)
            if new_classes:
                classes = np.concatenate([classes, list(new_classes)])

            classes_dict = {pos_class: i for i, pos_class in enumerate(classes)}
            data = np.array([classes_dict[token] for token in data_raw])

        return torch.from_numpy(data), classes

    def __len__(self):
        return self.n_instances

    def __getitem__(self, index):
        return (self.x[index], self.y[index])


from six import string_types
from sys import exit
from time import time
from types import FunctionType

from nozdormu.loader import BenchLoader
from nozdormu.runner import BenchRunner

class BenchProgram:
    """This program loads and runs the tests"""

    module = None # For testing purposes

    def __init__(self, module='__main__', benchLoader=BenchLoader,
                 benchRunner=BenchRunner):
        self.benchLoader = benchLoader
        self.benchRunner = benchRunner
        if isinstance(module, string_types):
            self.module = __import__(module)
            for part in module.split('.')[1:]:
                self.module = getattr(self.module, part)
        self.load()
        self.run()

    def load(self):
        loader = self.benchLoader()
        self.bench = loader.loadFromModule(self.module)

    def run(self):
        runner = self.benchRunner()
        self.result = runner.run(self.bench)

main = BenchProgram


from django.db import models
from .TblSetups import TblSetups

class TblSetupSetups(models.Model):
    setup = models.ForeignKey(TblSetups, on_delete=models.CASCADE, related_name="setup_id_setup")
    sub_setup = models.ForeignKey(TblSetups, on_delete=models.CASCADE, related_name="setup_id_sub_setup")
    created = models.DateTimeField()
    created_by = models.BigIntegerField(blank=True, null=True)
    type = models.CharField(max_length=11)
    active = models.IntegerField()
    modified = models.DateTimeField(blank=True, null=True)
    modified_by = models.BigIntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'tbl_setup_setups'
        unique_together = (('setup_id', 'sub_setup_id', 'created'),)


import os
from glob import glob
from tensorflow.keras.preprocessing.sequence import pad_sequences
from keras.models import load_model
import numpy as np

# Define paths to data and model files
DATA_DIR = "../data/piano_rolls"
MODEL_FILE = "../model/model.h5"
EVAL_FILE = "../data/eval_files.txt"

SEQUENCE_LENGTH = 1024  # You can adjust this value based on your preference

def load_data(file_list):
    """
    Load the data from the given list of file paths.

    Args:
        file_list (List[str]): List of file paths.

    Returns:
        np.ndarray: Loaded data as a numpy array.
    """
    data = [np.load(file, allow_pickle=True) for file in file_list]
    data = pad_sequences(data, maxlen=SEQUENCE_LENGTH, dtype='float32')
    return data

if __name__ == '__main__':
    # Load the validation data
    with open(EVAL_FILE, "r") as f:
        eval_files = f.read().splitlines()

    eval_files = [os.path.join(file) for file in eval_files]
    eval_data = load_data(eval_files)

    # Load the model and evaluate it
    model = load_model(MODEL_FILE)
    evaluation = model.evaluate(eval_data, eval_data)

    # Print the evaluation metrics
    print("Evaluation metrics:")
    for i, metric_name in enumerate(model.metrics_names):
        print(f"{metric_name}: {evaluation[i]}")


import os
import json
from pathlib import Path
from flask import Flask, render_template, request, Response, jsonify
from werkzeug.exceptions import HTTPException
from dotenv import load_dotenv
from models import Categorie, Client, Inventaire, Location, Materiel
import utils

# load environment variables
env_path = Path('.') / '.env'
load_dotenv(env_path)

# crÃ©er un objet Flask
app = Flask(__name__)

# avoir l'objet connexion pour la base de donnÃ©es
cnx = utils.connect_to_mysql_database(
    app, os.environ['db_host'], os.environ['db_user'], os.environ['db_name'],
    os.environ['db_password'], int(os.environ['db_port']),
    autocommit=True)

@app.route('/', methods=['GET', 'POST'])
def index():
    return Response(json.dumps({"message": "Bienvenue Ã  notre API ðŸ™‚"}), status=200, mimetype='application/json')

# se connecter
@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    login_employe = data.get('login')
    mdp = data.get('mdp')

    # obtenir un curseur
    cursor = cnx.cursor()

    # se_connecter : sql function retourne true/false si les identifiants sonts correctes
    cursor.execute("SELECT se_connecter(%s , %s)", (login_employe, mdp))

    peut_se_connecter = cursor.fetchone()[0]

    if not peut_se_connecter:
        cursor.close()
        return Response(json.dumps({"autoriser": False, "error": "Vos identifiants sont incorrects"}), mimetype='application/json', status=400)

    # procÃ©dure stockÃ© qui retourne l'employÃ©
    cursor.execute('CALL get_employe_par_identifiants(%s , %s)',
                   (login_employe, mdp))
    employe = cursor.fetchone()
    print(employe)

    cursor.close()

    employe_id, nom, prenom, adresse_id, image_url, email, magasin_id, actif, *_ = employe

    return Response(json.dumps({"id": employe_id, "nom": nom, "prenom": prenom, "image_url": image_url, "email": email,  "adresseId":  adresse_id, "magasinId": magasin_id, "actif": actif == 1, "autoriser": True, "error": None}), mimetype='application/json', status=200)

# on envoient une list de materiel dans l'inventaire d'un magasin en particulier
# avec materiel_id ,  nom et la quantite
@app.route('/inventaire_magasin/<int:id_magasin>', methods=['GET'])
def inventaire_magasin(id_magasin):
    cursor = cnx.cursor()
    cursor.execute("""SELECT m.materiel_id , m.nom ,  COUNT(*) as quantite from inventaire i
                        INNER JOIN materiel m ON m.materiel_id = i.materiel_id
                        WHERE i.magasin_id = %s
                        GROUP BY m.materiel_id """, (id_magasin,))
    data = cursor.fetchall()

    cursor.close()

    json_data = [Inventaire(row[0], row[1], row[2]).to_dict() for row in data]

    return Response(json.dumps(json_data), mimetype='application/json', status=200)

# avoir le dÃ©tail d'un materiel
@app.route('/materiel/<int:id_materiel>', methods=['GET'])
def materiel_detail(id_materiel):
    cursor = cnx.cursor()
    cursor.execute(
        'SELECT * from materiel m inner join categorie c on c.categorie_id= m.categorie_id where materiel_id = %s', (id_materiel,))
    data = list(cursor.fetchone())
    # Object of type datetime is not JSON serializable
    # data[9] = str(data[9])  # (updated_at) convert datetime object to string
    cursor.close()

    print(data)

    materiel = Materiel(data[0], data[2], data[3],
                        data[4], data[5], data[6], data[7], data[8], data[10], data[11])

    return Response(materiel.to_json(), mimetype='application/json', status=200)

# une liste avec tous les noms du matereils
@app.route('/get_nom_materiels', methods=['GET'])
def get_nom_materiels():
    cursor = cnx.cursor()
    cursor.execute('select nom from materiel')

    materiels = [m[0] for m in cursor.fetchall()]
    print(materiels)

    cursor.close()

    return Response(json.dumps(materiels), mimetype='application/json', status=200)

# liste avec id et nom categorie
@app.route('/get_categories', methods=['GET'])
def get_categories():
    cursor = cnx.cursor()
    cursor.execute('select categorie_id , nom from categorie')

    data = cursor.fetchall()
    cursor.close()

    categories = [Categorie(categ[0], categ[1]).to_dict()
                  for categ in data]

    return Response(json.dumps(categories), mimetype='application/json', status=200)

# recupere toutes les location d'un magasin en particulier
@app.route('/get_locations/<int:id_magasin>', methods=['GET'])
def get_locations(id_magasin):
    cursor = cnx.cursor()
    cursor.execute('SELECT location_id , date_location , i.inventaire_id , m.nom , c.nom , c.prenom from location l INNER JOIN inventaire i ON i.inventaire_id = l.inventaire_id INNER JOIN client c ON c.client_id = l.client_id INNER JOIN materiel m ON m.materiel_id=i.materiel_id INNER JOIN employe e ON e.employe_id=l.employe_id WHERE e.magasin_id = %s', (id_magasin))

    data = cursor.fetchall()
    cursor.close()

    # loc est un tuple, *loc : spreading tuple
    locations = [Location(*loc).to_dict() for loc in data]
    print(locations)

    return Response(json.dumps(locations), mimetype='application/json', status=200)

# recupere toutes les location non rendus d'un magasin en particulier
@app.route('/get_locations_non_rendus/<int:id_magasin>', methods=['GET'])
def get_locations_non_rendus(id_magasin):
    cursor = cnx.cursor()
    cursor.execute('SELECT location_id , date_location , i.inventaire_id , m.nom , c.nom , c.prenom from location l INNER JOIN inventaire i ON i.inventaire_id = l.inventaire_id INNER JOIN client c ON c.client_id = l.client_id INNER JOIN materiel m ON m.materiel_id=i.materiel_id INNER JOIN employe e ON e.employe_id=l.employe_id WHERE e.magasin_id = %s AND l.date_retour IS NULL', (id_magasin))

    data = cursor.fetchall()
    cursor.close()

    locations = [Location(*loc).to_dict() for loc in data]
    print(locations)

    return Response(json.dumps(locations), mimetype='application/json', status=200)

# recupere les clients d'un magasin
@app.route('/get_clients/<int:id_magasin>', methods=['GET'])
def get_clients_magasin(id_magasin):
    cursor = cnx.cursor()
    cursor.execute(
        'select client_id , nom , prenom from client where magasin_id=%s', (id_magasin,))
    data = cursor.fetchall()
    cursor.close()

    clients = [Client(*row).to_dict() for row in data]

    return Response(json.dumps(clients), mimetype='application/json', status=200)

# Avoir les matereils disponible dans inventaire (inventaire_id n'est pas dans location or date_retour IS NOT NULL) d'un magasin
@app.route('/get_materiels_dispo/<int:id_magasin>', methods=['GET'])
def get_materiels_dispo(id_magasin):
    cursor = cnx.cursor()
    cursor.execute(
        'select  m.nom , i.inventaire_id from inventaire i INNER JOIN materiel m ON m.materiel_id = i.materiel_id WHERE i.inventaire_id NOT IN (select inventaire_id from location) OR EXISTS( select * from location l INNER JOIN employe e ON e.employe_id=l.employe_id WHERE e.magasin_id = %s AND l.date_retour IS NOT NULL AND i.inventaire_id = l.inventaire_id) ORDER BY i.inventaire_id', (id_magasin,))
    data = cursor.fetchall()
    cursor.close()

    inventaire = [{"NomMateriel": row[0], "IdInventaire": row[1]}
                  for row in data]

    return Response(json.dumps(inventaire), mimetype='application/json', status=200)

# + Insertion

@app.route('/create_materiel', methods=['POST'])
def create_materiel():
    data = request.get_json()
    nom = data.get('nom')
    description = data.get('description')
    marque = data.get('marque')
    duree_location = data.get('dureeLocation')
    cout_location = data.get('coutLocation')
    cout_remplacement = data.get('coutRemplacement')
    taille = data.get('taille')
    categorie_id = data.get('categorie_id')

    cursor = cnx.cursor()
    cursor.execute('INSERT INTO materiel(nom , description , marque , duree_location , cout_location , cout_remplacement , taille , categorie_id) values(%s , %s , %s , %s , %s , %s , %s , %s)',
                   (nom, description, marque, duree_location, cout_location, cout_remplacement, taille, categorie_id))

    cursor.close()

    return Response(json.dumps({"message": "ok"}), mimetype='application/json', status=201)

@app.route('/create_materiels_inventaire', methods=['POST'])
def create_materiels_inventaire():
    data = request.get_json()
    materiel = data.get('materiel')
    quantite = data.get('quantite')
    magasin_id = data.get('magasin_id')

    cursor = cnx.cursor()
    cursor.execute(
        'select materiel_id from materiel where nom = %s', (materiel))
    materiel_id = cursor.fetchone()[0]

    print(materiel_id)

    for _ in range(quantite):
        cursor.execute('INSERT INTO inventaire(materiel_id , magasin_id) values(%s , %s )',
                       (materiel_id, magasin_id))

    cursor.close()

    return Response(json.dumps({"message": "ok"}), mimetype='application/json', status=201)

@app.route('/create_location', methods=['POST'])
def materiels_par_magasin_employe():
    data = request.get_json()
    inventaire_id = data.get('inventaireId')
    client_id = data.get('clientId')
    employe_id = data.get('employeId')

    cursor = cnx.cursor()
    cursor.execute(
        'INSERT INTO location(inventaire_id , client_id, employe_id) VALUES(%s, %s , %s)', (inventaire_id, client_id, employe_id))
    cursor.close()

    return Response(json.dumps({"message": "ok"}), mimetype='application/json', status=201)

# + modification

@app.route('/update_materiel', methods=['POST'])
def update_materiel():
    data = request.get_json()
    id_materiel = data.get('idMateriel')
    nom = data.get('nom')
    description = data.get('description')
    marque = data.get('marque')
    duree_location = data.get('dureeLocation')
    cout_location = data.get('coutLocation')
    cout_remplacement = data.get('coutRemplacement')
    taille = data.get('taille')
    categorie_id = data.get('categorie_id')

    cursor = cnx.cursor()
    cursor.execute('UPDATE materiel set nom = %s , description = %s , marque = %s  , duree_location = %s , cout_location = %s , cout_remplacement = %s, taille =%s , categorie_id = %s where materiel_id=%s',
                   (nom, description, marque, duree_location, cout_location, cout_remplacement, taille, categorie_id, id_materiel))

    cursor.close()

    return Response(json.dumps({"message": "ok"}), mimetype='application/json', status=202)

# + Statistique (fait avec des vues SQL)

# materiel le plus et le moins empruntÃ©s par magsin
@app.route('/get_materiel_plus_moins_empruntes', methods=['GET'])
def get_materiel_plus_moins_empruntes():
    cursor = cnx.cursor()
    cursor.execute('SELECT * FROM materiel_tries_par_nbemprunts')
    data = cursor.fetchall()
    cursor.close()
    if len(data) != 0:
        materiel_plus_empruntes = {
            "idMateriel": data[0][0], "nomMateriel": data[0][1], "nbEmprunts": data[0][2]}
        materiel_moins_empruntes = {
            "idMateriel": data[-1][0], "nomMateriel": data[-1][1], "nbEmprunts": data[-1][2]}

        return Response(json.dumps({"materielPlusEmpruntes": materiel_plus_empruntes,
                                    "materielMoinsEmpruntes": materiel_moins_empruntes
                                    }),
                        status=200, mimetype='application/json')

    return Response(json.dumps({"message": "Aucun Elements touvÃ©s"}), status=404, mimetype='application/json')

# nombre de matÃ©riels empruntÃ©s sur le jour courant par magasin
@app.route('/get_nb_locations_aujourdhui', methods=['GET'])
def get_nb_location_aujourdhui():
    cursor = cnx.cursor()
    # utilisation de la vue, recupere id magasin et nombre de locations
    cursor.execute('SELECT * FROM get_nb_locations_aujourdhui_par_magasin;')
    data = cursor.fetchall()

    cursor.close()

    data = [{"magasinId": row[0], "nbLocations": row[1]} for row in data]

    return Response(json.dumps(data), mimetype='application/json', status=200)

# le client fidÃ¨le
@app.route('/get_client_fidele', methods=['GET'])
def get_client_fidele():
    cursor = cnx.cursor()
    cursor.execute('select * from client_fidele')

    data = cursor.fetchone()
    client = Client(data[0], data[1], data[2])

    return Response(client.to_json(), status=200, mimetype='application/json')

# le magasin avec plus de chiffre d'affaire
@app.route('/get_magasin_plus_CA', methods=['GET'])
def get_magasin_plus_ca():
    cursor = cnx.cursor()
    cursor.execute('SELECT * FROM magain_tries_par_ca')
    data = cursor.fetchone()

    return Response(json.dumps({"magasinId": data[0], 'CA': round(data[1], 2)}), status=200, mimetype='application/json')

# Error
@app.errorhandler(HTTPException)
def handle_exception(error):
    """Return JSON instead of HTML for HTTP errors."""
    # start with the correct headers and status code from the error
    response = error.get_response()
    # replace the body with JSON
    response.data = json.dumps({
        "code": error.code,
        "name": error.name,
        "description": error.description,
    })
    response.content_type = "application/json"
    return response

if __name__ == '__main__':
    app.run(debug=True, port=3000)


def solution(n,results):
	win = [set() for _ in range(n)]
	lose = [set() for _ in range(n)]
	result = 0
	for i in results:
		win[i[0]-1].update([i[1]])
		lose[i[1]-1].update([i[0]])
	for player in range(n):
		for i in win[player]:
			win[player] = win[player] | win[i-1]
	for player in range(n):
		for i in lose[player]:
			lose[player] = lose[player] | lose[i-1]

	for player in range(n):
		for i in win[player]:
			win[player] = win[player] | win[i-1]
	for player in range(n):
		for i in lose[player]:
			lose[player] = lose[player] | lose[i-1]

	for i in range(n):
		if len(win[i]) + len(lose[i]) == n-1:
			result += 1

	return result

print(solution(5,[[2,1],[2,3],[2,4],[2,5]]))


import json
import logging
from schema import *
from pony.orm import *
from hashlib import md5
from timeit import default_timer as timer

FORMAT = u'%(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger('ppd_logger')
logger.setLevel(logging.INFO)
formatter = logging.Formatter(FORMAT)

logfile = '/var/log/app/ppd_logger.log'
fh = logging.FileHandler(logfile, encoding = "UTF-8")

fh.setFormatter(formatter)
fh.setLevel(logging.INFO)
logger.addHandler(fh)

class JsonImporter():
    counter = {}
    line = ""
    filename = ""

    def __init__(self, filename=''):
        self.filename = filename
        self.counter = {
            'lines':0,
            'new':0,
            'updated':0,
            'skipped':0,
            'start': 0,
            'end': 0,
            'elapsed': 0
        }
        self.line = ""

    def mark_time(self):
        if (self.counter['start'] == 0) :
            self.counter['start'] = timer()
        self.counter['end'] = timer()
        self.counter['elapsed'] = (self.counter['end'] - self.counter['start'])
        if not (self.counter['lines'] % 1000) :
            print('.', end='', flush=True)

    def handle_line(self):
        self.counter['lines'] += 1
        rec = json.loads(self.line.strip())
        json_hash = md5(self.line.encode('utf-8').strip()).hexdigest()

        document = Document.get(record_id = rec['unitID'])
        if (document):
            if (json_hash != document.hash) :
                self.updateDocument(document,rec,json_hash)
            else :
                self.counter['skipped'] += 1
                logger.debug("%d - Not updated: %s - %0.2f" % (self.counter['lines'], rec['unitID'], self.counter['elapsed']))
        else :
            self.storeDocument(rec,json_hash)

    def updateDocument(self, document, rec, json_hash):
        scigroup = rec['identifications'][0]['scientificName']['scientificNameGroup']
        document.hash = json_hash
        document.source = rec['sourceSystem']['code']
        document.record = self.line
        document.status = 'Updated'
        document.nds_index = 'specimen'
        document.documenttype = 'specimen'
        document.scientific_name_group = scigroup

        self.counter['updated'] += 1

        logger.info("%d - Record updated: %s - %0.2f" % (self.counter['lines'], rec['unitID'], self.counter['elapsed']))

    def storeDocument(self, rec, json_hash):
        scigroup = rec['identifications'][0]['scientificName']['scientificNameGroup']
        try:
            document = Document(
                record_id = rec['unitID'],
                hash = json_hash,
                source = rec['sourceSystem']['code'],
                record = self.line,
                status = 'New',
                nds_index = 'specimen',
                documenttype = 'specimen',
                scientific_name_group = scigroup
            )
            logger.info("Document record stored: %s" % (rec['unitID']))
            self.counter['new'] += 1
        except:
            logger.error("Document already stored: %s" % (rec['unitID']))
            self.counter['skipped'] += 1

    @db_session
    def parse_json(self):
        self.mark_time()
        with open(self.filename, 'r') as f:
            for self.line in f:
                self.handle_line()
                self.mark_time()
        self.report()

    def report(self):
        print('.')
        logger.info("Execution time %0.2f seconds" % (self.counter['elapsed']))
        logger.info("%d lines processed" % (self.counter['lines']))
        logger.info("%d new records" % (self.counter['new']))
        logger.info("%d records updated" % (self.counter['updated']))
        logger.info("%d records skipped" % (self.counter['skipped']))

importer = JsonImporter(filename='/data/validation-output-20180626-104522--000.json')
importer.parse_json()


from django.db import models
from datetime import datetime
from django.contrib.auth.models import User

SERVICE_CHOICES = (
    ("Doctor care", "Doctor care"),
    ("Nursing care", "Nursing care"),
    ("Medical social services", "Medical social services"),
    ("Homemaker or basic assistance care", "Homemaker or basic assistance care"),
    )
TIME_CHOICES = (
    ("3 PM", "3 PM"),
    ("3:30 PM", "3:30 PM"),
    ("4 PM", "4 PM"),
    ("4:30 PM", "4:30 PM"),
    ("5 PM", "5 PM"),
    ("5:30 PM", "5:30 PM"),
    ("6 PM", "6 PM"),
    ("6:30 PM", "6:30 PM"),
    ("7 PM", "7 PM"),
    ("7:30 PM", "7:30 PM"),
)

class Appointment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    service = models.CharField(max_length=50, choices=SERVICE_CHOICES, default="Doctor care")
    day = models.DateField(default=datetime.now)
    time = models.CharField(max_length=10, choices=TIME_CHOICES, default="3 PM")
    time_ordered = models.DateTimeField(default=datetime.now, blank=True)
    def __str__(self):
        return f"{self.user.username} | day: {self.day} | time: {self.time}"


def konwertuj_na_zwykly_ulamek(liczba):
    def najblizszy_mianownik(liczba):
        for mianownik in range(1, 10):
            zaokraglona = round(liczba * mianownik)
            if abs(liczba - zaokraglona / mianownik) < 0.0001:
                return mianownik
        return 9

    mianownik = najblizszy_mianownik(liczba)
    licznik = int(round(liczba * mianownik))

    if licznik == 0:
        return "0/9"
    elif licznik == mianownik:
        return "9/9"
    else:
        return f"{licznik}/{mianownik}"

print(konwertuj_na_zwykly_ulamek(float(input())))


# -* coding: utf-8 *-
# (C) 2011 by Bernd Wurst <bernd@schokokeks.org>

# This file is part of Bib2011.
#
# Bib2011 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.
#
# Bib2011 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 Bib2011.  If not, see <http://www.gnu.org/licenses/>.

import datetime, hashlib

from lib.VorgangEintrag import VorgangEintrag
from lib.Preisliste import Preisliste
from lib.Kunde import Kunde

class Vorgang(object):
    def __init__(self, kunde=None):
        self.__preisliste = Preisliste()
        self.ID = None
        self.__manuelleLiterzahl = None
        self.__entryOrder = []
        self.__entries = {}
        if not kunde:
            kunde = Kunde()
        self.kunde = kunde
        self.abholung = ''
        self.telefon = ''
        self.__zeitpunkt = None
        self.paletten = 1
        self.changed = False
        self.rechnungsDaten = {'nummer': None, 'datum': None, "adresse": None}
        self.banktransfer = False
        self.payed = False
        self.zahlart = None
        self.xmlstring = None
        self.version = 0
        self.status = None
        self.zahlungen = []
        self.bio = False
        self.bio_lieferschein = None
        self.bio_kontrollstelle = None
        self.bio_lieferant = None
        self.originale = []
        self.__minprice_deleted = False

    def setXMLString(self, xmlstring):
        self.xmlstring = xmlstring

    def setVersion(self, version):
        self.version = version

    def getVersion(self):
        return self.version

    def setID(self, ID):
        self.ID = ID

    def getEAN13(self):
        if not self.ID:
            return None
        if len(self.ID) == 9:
            return '200' + self.ID
        if len(self.ID) > 9:
            md = hashlib.md5()
            md.update(self.ID)
            return '200' + '%09i' % (int(md.hexdigest()[:8], 16) % 1000000000)
        else:
            return None

    def getPreisliste(self):
        return self.__preisliste

    def newItem(self, anzahl, preislistenID = None, beschreibung = None, einzelpreis = None,
                liter_pro_einheit = None, einheit = '', preisliste_link = True,
                steuersatz = None, datum = None, autoupdate = True):
        ie = VorgangEintrag(self,
                          anzahl = anzahl,
                          preislistenID = preislistenID,
                          beschreibung = beschreibung,
                          einzelpreis = einzelpreis,
                          liter_pro_einheit = liter_pro_einheit,
                          einheit = einheit,
                          preisliste_link = preisliste_link,
                          steuersatz = steuersatz,
                          datum = datum,
                          autoupdate = autoupdate)
        return self.addItem(ie)

    def addItem(self, invoiceItem):
        handle = invoiceItem.getID()
        self.__entryOrder.append(handle)
        self.__entries[handle] = invoiceItem
        if self.__manuelleLiterzahl:
            if invoiceItem.getRabattstufe() and invoiceItem.getRabattstufe()[0] == 'liter':
                    invoiceItem.setRabattstufe(('liter', self.__manuelleLiterzahl))
            self.updateManuelleLiterzahl()
        self.berechneMindestpreis()
        self.changed = True
        return handle

    def berechneMindestpreis(self):
        if self.__minprice_deleted:
            return
        try:
            betrag = self.__preisliste.getPreis('minprice')
        except IndexError:
            # Kein Mindestpreis festgelegt
            return
        minprice_handle = None
        duplicates = []
        for key, e in self.__entries.items():
            if e.preislistenID == 'minprice':
                if minprice_handle:
                    duplicates.append(key)
                else:
                    minprice_handle = key
        for handle in duplicates:
            self.deleteItem(handle)
            # Das ist jetzt automatisch passiert, sonst hätte diese Funktion nichts gemacht
            self.__minprice_deleted = False
        if minprice_handle and betrag > 0:
            self.__entries[minprice_handle].setStueckzahl(1)
        elif minprice_handle and betrag <= 0:
            self.deleteItem(minprice_handle)
            # Das ist jetzt automatisch passiert, sonst hätte diese Funktion nichts gemacht
            self.__minprice_deleted = False
        elif betrag > 0 and not minprice_handle:
            self.newItem(1, 'minprice')

    def isRechnung(self):
        return (self.rechnungsDaten['nummer'] != None)

    def getRechnungsdatum(self):
        if not self.isRechnung():
            return None
        return self.rechnungsDaten['datum']

    def getRechnungsnummer(self):
        if not self.isRechnung():
            return None
        return self.rechnungsDaten['nummer']

    def setRechnungsdaten(self, datum, nummer = None):
        if not datum or not nummer or type(datum) != datetime.date:
            self.rechnungsDaten['nummer'] = None
            self.rechnungsDaten['datum'] = None
        else:
            self.rechnungsDaten['datum'] = datum
            self.rechnungsDaten['nummer'] = str(nummer)
        self.changed = True

    def setRechnungsadresse(self, adresse):
        self.rechnungsDaten['adresse'] = adresse

    def deleteItem(self, handle):
        if not handle in self.__entries.keys():
            raise IndexError("This VorgangEintrag is not known!")
        if self.__entries[handle].preislistenID == 'minprice':
            self.__minprice_deleted = True
        self.__entries[handle].unregister()
        self.berechneMindestpreis()
        self.changed = True

    def reallyDeleteItem(self, handle):
        if not handle in self.__entries.keys():
            raise IndexError("This VorgangEintrag is not known!")
        if self.__entries[handle].preislistenID == 'minprice':
            self.__minprice_deleted = True
        self.__entryOrder.remove(handle)
        del self.__entries[handle]
        self.berechneMindestpreis()
        self.changed = True

    def aendereAnzahl(self, handle, anzahl):
        self.__entries[handle].setStueckzahl(anzahl)
        self.berechneMindestpreis()
        self.changed = True

    def setManuelleLiterzahl(self, liter):
        try:
            if self.__manuelleLiterzahl is None and liter is None:
                # Es hat sich nichts geändert!
                return
            if self.__manuelleLiterzahl == int(liter):
                # Es hat sich nichts geändert!
                return
        except TypeError:
            pass
        try:
            self.__manuelleLiterzahl = int(liter)
        except:
            self.__manuelleLiterzahl = None
        self.updateManuelleLiterzahl()
        self.changed = True

    def updateManuelleLiterzahl(self):
        for item in self.getEntries():
            if item.getRabattstufe() and item.getRabattstufe()[0] == 'liter':
                if self.__manuelleLiterzahl:
                    item.setRabattstufe(('liter', self.__manuelleLiterzahl))
                else:
                    item.setRabattstufe(None)

    def getManuelleLiterzahl(self):
        return self.__manuelleLiterzahl

    def getEntry(self, handle):
        return self.__entries[handle]

    def getLiterzahl(self):
        liter = 0
        for ie in self.__entries.values():
            liter += ie.getLiterzahl()
        return liter

    def getEinzelpreis(self, handle):
        return self.__entries[handle].getPreis()

    def getSumme(self):
        summe = 0.0
        for ie in self.__entries.values():
            summe += ie.getSumme()
        return summe

    def getNormalsumme(self):
        summe = 0.0
        for ie in self.__entries.values():
            summe += ie.getNormalsumme()
        return summe

    def getSteuersummen(self):
        summen = {}
        for ie in self.__entries.values():
            tmp = (ie.getSteuersatz(), ie.getSteuersumme())
            if tmp[0] in summen.keys():
                summen[tmp[0]] += tmp[1]
            else:
                summen[tmp[0]] = tmp[1]
        return summen

    def getEntries(self):
        if self.changed:
            self.berechneMindestpreis()
        return [self.__entries[handle] for handle in self.__entryOrder]

    def setKunde(self, kunde):
        if kunde != self.kunde:
            self.kunde = kunde
            self.changed = True

    def getKunde(self):
        return self.kunde

    def getKundenname(self):
        if not self.kunde:
            return ''
        return self.kunde.getName()

    def setBanktransfer(self, value):
        if value:
            self.banktransfer = True
            self.setPayed(False)
            self.zahlart = 'ueberweisung'
        else:
            self.banktransfer = False
        self.changed = True

    def getBanktransfer(self):
        return self.banktransfer

    def setPayed(self, value):
        if value:
            self.payed = True
            self.setBanktransfer(False)
            self.zahlart = 'bar'
        else:
            self.payed = False
        self.changed = True

    def getPayed(self):
        return self.payed

    def setPayedEC(self, value):
        if value:
            self.payed = True
            self.banktransfer = True
            self.zahlart = 'ec'
        else:
            self.payed = False
        self.changed = True

    def getZahlart(self):
        return self.zahlart

    def getPartlyPayed(self):
        pp = False
        if not self.getPayed() and not self.getBanktransfer():
            if len(self.zahlungen) > 0:
                summe = 0.0
                for z in self.zahlungen:
                    summe += z['betrag']
                if summe > 0 and summe <= self.getSumme():
                    pp = True
        return pp

    def getZahlbetrag(self):
        summe = 0.0
        for z in self.zahlungen:
            summe += z['betrag']
        return self.getSumme() - summe

    def getZahlungen(self):
        return self.zahlungen

    def setAbholung(self, abholung):
        if abholung is None:
            abholung = ''
        self.abholung = str(abholung).strip()
        self.changed = True

    def getAbholung(self):
        return self.abholung

    def setTelefon(self, telefon):
        print ('FIXME: vorgang.setTelefon() wurde aufgerufen!')
        import traceback
        traceback.print_stack()
        pass

    def getTelefon(self):
        return self.kunde.getErsteTelefon()

    def setPaletten(self, pal):
        if int(pal) > 0:
            self.paletten = int(pal)
        self.changed = True

    def getPaletten(self):
        return self.paletten

    def setZeitpunkt(self, zeitpunkt):
        self.__zeitpunkt = zeitpunkt
        self.changed = True

    def getZeitpunkt(self):
        return self.__zeitpunkt

    def isBio(self):
        return self.bio

    def getBio(self):
        if self.bio:
            if self.bio_kontrollstelle:
                return self.bio_kontrollstelle
            else:
                return True
        return False

    def getBioLieferant(self):
        if self.bio and self.bio_lieferant:
            return self.bio_lieferant
        return None

    def getBioKontrollstelle(self):
        if self.bio and self.bio_kontrollstelle:
                return self.bio_kontrollstelle
        return None

    def getBioLieferschein(self):
        if self.bio and self.bio_lieferschein:
            return self.bio_lieferschein
        return None

    def setBio(self, bio, kontrollstelle = None, lieferant = None, lieferschein = None):
        oldbio = self.bio
        oldkontrollstelle = self.bio_kontrollstelle
        oldlieferant = self.bio_lieferant
        oldlieferschein = self.bio_lieferschein
        if bio:
            self.bio = True
        else:
            self.bio = False
        if bio and lieferschein:
            self.bio_lieferschein = lieferschein
        if bio and kontrollstelle:
            self.bio_kontrollstelle = str(kontrollstelle).strip()
        if bio and lieferant:
            self.bio_lieferant = str(lieferant).strip()
        if bio and not self.bio_kontrollstelle:
            self.bio_kontrollstelle = self.kunde.getOekoKontrollstelle()
            self.bio_lieferant = self.kunde.getAdresse()
        if oldbio != self.bio or oldkontrollstelle != self.bio_kontrollstelle or \
                oldlieferant != self.bio_lieferant or oldlieferschein != self.bio_lieferschein:
            self.changed = True

    def getStatus(self):
        return self.status

    def setStatus(self, status):
        if status != self.status:
            self.changed = True
            self.status = status

    def vorgangHinzufuegen(self, vorgang):
        if not self.kunde:
            self.kunde = vorgang.getKunde()
        if self.kunde.isBio() and vorgang.isBio():
            if not self.isBio():
                self.setBio(True, self.kunde.getOekoKontrollstelle())
        for neuerEintrag in vorgang.getEntries():
            found = False
            for alterEintrag in self.getEntries():
                if (alterEintrag.preislistenID == neuerEintrag.preislistenID and
                    alterEintrag.getPreis() == neuerEintrag.getPreis() and
                    alterEintrag.getDatum() == neuerEintrag.getDatum()):
                    found = True
                    alterEintrag.setStueckzahl(alterEintrag.getStueckzahl() + neuerEintrag.getStueckzahl())
            if not found:
                self.addItem(neuerEintrag.copy())
        self.originale.append(vorgang.ID)

    def __str__(self):
        ret = ''
        if self.kunde:
            ret += 'Kunde: %s\n' % self.kunde.getName()
        for item in self.getEntries():
            ret += '%3i %-5s  %-45s je %6.2f €  = %7.2f €\n' % (item['anzahl'], item['einheit'], item['beschreibung'], item['einzelpreis'], item['gesamtpreis'])
        ret += '=' * 81 + '\n'
        ret += ' ' * 54 + 'Rechnungsbetrag: %8.2f €\n' % self.getSumme()
        for satz, betrag in self.getSteuersummen().items():
            ret += ' ' * 59 + 'MwSt %4.1f%%: %8.2f €\n' % (satz, betrag)
        ret += ' ' * 54 + '      Literzahl: %8i l\n' % self.getLiterzahl()
        if self.getManuelleLiterzahl():
            ret += ' ' * 51 + 'Manuelle Literzahl: %8i l\n' % self.getManuelleLiterzahl()
        return ret

if __name__ == '__main__':
    i = Vorgang()
    _5er = i.newItem(10, '5er')
    _10er = i.newItem(20, '10er')
    gebraucht_5er = i.newItem(100, 'frischsaft')

    print (i)

    i.aendereAnzahl(_10er, 30)

    print (i)

    i.deleteItem(_10er)
    i.kunde.setName('Müller')

    print (i)

    mosten = i.newItem(2, '5er_vk')
    print (i)
    i.aendereAnzahl(mosten, 6)
    print (i)

    i = Vorgang()
    i.newItem(12, 'frischsaft')
    i.newItem(18, '5er')
    print (i)


import rospy
import tf
import tf_conversions.posemath as tfconv
import PyKDL

from geometry_msgs.msg import Vector3, Quaternion, Transform, TransformStamped
from visp_hand2eye_calibration.msg import TransformArray
from visp_hand2eye_calibration.srv import compute_effector_camera_quick

class HandEyeConnector(object):
    def __init__(self):

        # Frame which is rigidly attached to the camera
        # The transform from this frame to the camera optical frame is what
        # we're trying to compute.
        # For the eye-in-hand case, this is the end-effector frame.
        # For the eye-on-base case, this is the world or base frame.
        self.camera_parent_frame_id = rospy.get_param('~camera_parent_frame')

        # Frame which is rigidly attached to the marker
        # The transform from the camera parent frame to the marker parent frame
        # is given by forward kinematics.
        # For the eye-in-hand case, this is the world or base frame.
        # For the eye-on-base case, this is the end-effector frame.
        self.marker_parent_frame_id = rospy.get_param('~marker_parent_frame')

        self.publish_tf = rospy.get_param('~publish_tf')
        self.tf_suffix = rospy.get_param('~tf_suffix')
        self.sample_rate = rospy.get_param('~sample_rate')
        self.interactive = rospy.get_param('~interactive')

        # Compute the camera base to optical transform
        self.xyz_optical_base = rospy.get_param('~xyz_optical_base', [0,0,0])
        self.rpy_optical_base = rospy.get_param('~rpy_optical_base', [0,0,0])
        self.F_optical_base = PyKDL.Frame(
                PyKDL.Rotation.RPY(*self.rpy_optical_base),
                PyKDL.Vector(*self.xyz_optical_base))
        self.F_base_optical = self.F_optical_base.Inverse()

        # tf structures
        self.listener = tf.TransformListener()
        self.broadcaster = tf.TransformBroadcaster()

        # rate limiter
        self.rate = rospy.Rate(self.sample_rate)

        # input data
        self.hand_world_samples = TransformArray()
        self.camera_marker_samples = TransformArray()

        # marker subscriber
        self.aruco_subscriber = rospy.Subscriber(
                'aruco_tracker/transform',
                TransformStamped,
                self.aruco_cb,
                queue_size=1)

        # calibration service
        rospy.wait_for_service('compute_effector_camera_quick')
        self.calibrate = rospy.ServiceProxy(
                'compute_effector_camera_quick',
                compute_effector_camera_quick)

    def compute_calibration(self, msg):
        rospy.loginfo("Computing from %g poses..." % len(self.hand_world_samples.transforms) )
        result = None

        # Get the camera optical frame for convenience
        optical_frame_id = msg.header.frame_id

        try:
            result = self.calibrate(self.camera_marker_samples, self.hand_world_samples)
        except rospy.ServiceException as ex:
            rospy.logerr("Calibration failed: "+str(ex))
            return None

        if self.publish_tf:
            self.broadcaster.sendTransform(
                    (result.effector_camera.translation.x, result.effector_camera.translation.y, result.effector_camera.translation.z),
                    (result.effector_camera.rotation.x, result.effector_camera.rotation.y, result.effector_camera.rotation.z, result.effector_camera.rotation.w),
                    rospy.Time.now(),
                    optical_frame_id + self.tf_suffix,
                    self.camera_parent_frame_id)

        rospy.loginfo("Result:\n"+str(result))

        ec = result.effector_camera
        xyz = (ec.translation.x, ec.translation.y, ec.translation.z)
        xyzw = (ec.rotation.x, ec.rotation.y, ec.rotation.z, ec.rotation.w)
        rpy = tuple(PyKDL.Rotation.Quaternion(*xyzw).GetRPY())

        F_optical_world = PyKDL.Frame(PyKDL.Rotation.Quaternion(*xyzw), PyKDL.Vector(*xyz))
        F_base_world = F_optical_world * self.F_base_optical

        bw = tfconv.toMsg(F_base_world)
        xyz = (bw.position.x, bw.position.y, bw.position.z)
        xyzw = (bw.orientation.x, bw.orientation.y, bw.orientation.z, bw.orientation.w)
        rpy = tuple(PyKDL.Rotation.Quaternion(*xyzw).GetRPY())

        rospy.loginfo("Base xyz: ( %f %f %f ) rpy: ( %f %f %f ) xyzw: ( %f %f %f %f )" % (xyz+rpy+xyzw))

        return result

    def aruco_cb(self, msg):

        rospy.loginfo("Received marker sample.")

        # Get the camera optical frame for convenience
        optical_frame_id = msg.header.frame_id

        try:
            # Get the transform between the marker and camera frames (from FK)
            self.listener.waitForTransform(
                self.marker_parent_frame_id, self.camera_parent_frame_id,
                msg.header.stamp, rospy.Duration(0.1))

            (trans,rot) = self.listener.lookupTransform(
                self.marker_parent_frame_id, self.camera_parent_frame_id,
                msg.header.stamp)
        except tf.Exception as ex:
            rospy.logwarn(str(ex))
            return

        # Update data
        self.hand_world_samples.header.frame_id = optical_frame_id
        self.hand_world_samples.transforms.append(Transform(Vector3(*trans), Quaternion(*rot)))

        self.camera_marker_samples.header.frame_id = optical_frame_id
        self.camera_marker_samples.transforms.append(msg.transform)

        if len(self.hand_world_samples.transforms) != len(self.camera_marker_samples.transforms):
            rospy.logerr("Different numbers of hand-world and camera-marker samples.")
            return

        n_min = 2
        if len(self.hand_world_samples.transforms) < n_min:
            rospy.logwarn("%d more samples needed..." % (n_min-len(self.hand_world_samples.transforms)))
        else:
            self.compute_calibration(msg)

        # interactive
        if self.interactive:
            i = raw_input('Hit [enter] to accept this latest sample, or `d` to discard: ')
            if i == 'd':
                del self.hand_world_samples.transforms[-1]
                del self.camera_marker_samples.transforms[-1]
                self.compute_calibration(msg)
            raw_input('Hit [enter] to capture the next sample...')
        else:
            self.rate.sleep()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 21 09:27:08 2017

@author: derek
"""

import os
import numpy as np
import shutil

cubes_path = "/media/derek/disk1/kaggle_ndsb2017/resources/_tfrecords/"
tf_list = os.listdir(cubes_path)
train_perc = .8

for f in tf_list:
    if os.stat(cubes_path + f).st_size == 0:
        os.remove(cubes_path + f)

if not os.path.exists(cubes_path + "label0"):
    os.makedirs(cubes_path + "label0")
if not os.path.exists(cubes_path + "label1"):
    os.makedirs(cubes_path + "label1")
if not os.path.exists(cubes_path + "label2"):
    os.makedirs(cubes_path + "label2")
if not os.path.exists(cubes_path + "label3"):
    os.makedirs(cubes_path + "label3")
if not os.path.exists(cubes_path + "label4"):
    os.makedirs(cubes_path + "label4")
if not os.path.exists(cubes_path + "label5"):
    os.makedirs(cubes_path + "label5")

tf_list = os.listdir(cubes_path)
for f in tf_list:
    f_split = f.split("_")
    if len(f_split) == 2:
        if f_split[1][0] == "0":
            os.rename(cubes_path + f, cubes_path + "label0/" + f)
        if f_split[1][0] == "1":
            os.rename(cubes_path + f, cubes_path + "label1/" + f)
        if f_split[1][0] == "2":
            os.rename(cubes_path + f, cubes_path + "label2/" + f)
        if f_split[1][0] == "3":
            os.rename(cubes_path + f, cubes_path + "label3/" + f)
        if f_split[1][0] == "4":
            os.rename(cubes_path + f, cubes_path + "label4/" + f)
        if f_split[1][0] == "5":
            os.rename(cubes_path + f, cubes_path + "label5/" + f)

tf_list = os.listdir(cubes_path)
total_size = 0
max_size = 0
dir_sizes = {}
for label_ in tf_list:
    if os.path.isdir(cubes_path + label_):
        label_path = cubes_path + label_ + "/"
        dir_size = sum(os.path.getsize(label_path + f) for f in os.listdir(label_path) if os.path.isfile(label_path + f))
        dir_sizes[label_path]=dir_size
        total_size += dir_size
        if dir_size > max_size:
            max_size = dir_size

#add integer number of repeats of files to each directory to get close to evening out sizes
tf_list = os.listdir(cubes_path)
for label_ in tf_list:
    if os.path.isdir(cubes_path + label_):
        label_path = cubes_path + label_ + "/"
        label_files = os.listdir(label_path)
        file_sizes = [os.path.getsize(label_path + f) for f in label_files if os.path.isfile(label_path + f)]
        dir_size = np.sum(file_sizes)
        files = [f for f in label_files if os.path.isfile(label_path + f)]
        #running_sum = np.cumsum(file_sizes)
        add_size = max_size - dir_size
        label_files = os.listdir(label_path)
        duplicate_index = int(float(add_size)/dir_size)
        duplicate_list = files*(duplicate_index-1)
        for ff in duplicate_list:
            shutil.copyfile(label_path + ff, label_path + ff[:-9] +str(np.random.randint(10000,99999)) + ff[-9:])

#recalculate max_size
tf_list = os.listdir(cubes_path)
total_size = 0
max_size = 0
dir_sizes = {}
for label_ in tf_list:
    if os.path.isdir(cubes_path + label_):
        label_path = cubes_path + label_ + "/"
        dir_size = sum(os.path.getsize(label_path + f) for f in os.listdir(label_path) if os.path.isfile(label_path + f))
        dir_sizes[label_path]=dir_size
        total_size += dir_size
        if dir_size > max_size:
            max_size = dir_size

#add remaining files to even out difference
tf_list = os.listdir(cubes_path)
for label_ in tf_list:
    if os.path.isdir(cubes_path + label_):
        label_path = cubes_path + label_ + "/"
        label_files = os.listdir(label_path)
        file_sizes = [os.path.getsize(label_path + f) for f in label_files if os.path.isfile(label_path + f)]
        dir_size = np.sum(file_sizes)
        files = np.array([f for f in label_files if os.path.isfile(label_path + f)])
        running_sum = np.cumsum(file_sizes)
        add_diff = max_size - dir_size
        copy_list = files[running_sum < add_diff]
        for ff in copy_list:
            shutil.copyfile(label_path + ff, label_path + ff[:-9] +str(np.random.randint(10000,99999)) + ff[-9:])

#move files to train and test folders
tf_list = os.listdir(cubes_path)
if not os.path.exists(cubes_path + "train"):
    os.makedirs(cubes_path + "train")
if not os.path.exists(cubes_path + "test"):
    os.makedirs(cubes_path + "test")
for label_ in tf_list:
    if os.path.isdir(cubes_path + label_):
        label_path = cubes_path + label_ + "/"
        label_files = os.listdir(label_path)
        label_files.sort()
        label_files_len = len(label_files)
        train_len = int(label_files_len * train_perc)
        for ff in label_files[:train_len]:
             os.rename(label_path + ff, cubes_path + "train/" + ff)
        for ff in label_files[train_len:]:
             os.rename(label_path + ff, cubes_path + "test/" + ff)


from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity: int):
        self.mappings = OrderedDict()
        self.capacity = capacity
        self.used_capacity = 0

    def get(self, key: int) -> int:
        if key in self.mappings:
            self.mappings.move_to_end(key)
            return self.mappings[key]
        return -1

    def put(self, key: int, value: int) -> None:
        if key in self.mappings:
            self.mappings.move_to_end(key)
        else:
            if self.used_capacity < self.capacity:
                self.used_capacity += 1
            else:
                self.mappings.popitem(False)
        self.mappings[key] = value

if __name__ == "__main__":
    ex = LRUCache(2)
    ex.put(1, 1)
    ex.put(2, 2)
    assert ex.get(1) == 1
    ex.put(3, 3)
    assert ex.get(2) == -1
    ex.put(4, 4)
    assert ex.get(1) == -1
    assert ex.get(3) == 3
    assert ex.get(4) == 4


"""
Policy Gradient Reinforcement Learning
Uses a 3 layer neural network as the policy network
Uses tf.layers to build the neural network

"""
import tensorflow as tf
import numpy as np
from tensorflow.python.framework import ops

class Network:

    def __init__(
        self,
        learning_rate=0.01,
        reward_decay=0.95,
        load_path=None,
        save_path=None
    ):

        self.lr = learning_rate
        self.gamma = reward_decay
        self.episode_state = []
        self.episode_actions = []
        self.episode_rewards = []

        self.save_path = None
        if save_path is not None:
            self.save_path = save_path

        self.build_network()
        self.sess = tf.Session()
        self.sess.run(tf.global_variables_initializer())

        # 'Saver' op to save and restore all the variables
        self.saver = tf.train.Saver()

        # Restore model
        if load_path is not None:
            self.load_path = load_path
            self.saver.restore(self.sess, self.load_path)

    def clear_transitions(self):
        self.episode_state = []
        self.episode_rewards = []
        self.episode_actions = []

    def store_transition(self, s, a, r):

        self.episode_state.append(s)
        self.episode_rewards.append(r)
        self.episode_actions.append(a)

    def choose_action(self, state):
        '''
        Rather than choosing the action that has the highest value, we are using
        a biased sample, so that sometimes the action undertaken is not the best
        performing.  Although this will take longer to converge, it will allow us
        to explore actions not in our policy. As our policy becomes more confident
        in one specific action, then the choice will naturally become less random
        '''
        state = state[np.newaxis, :]
        actions = self.sess.run(self.outputs_softmax, feed_dict = {self.X: state})
        #if np.random.randint(1, 101) > 80:
        #    return np.random.randint(0, 4)
        #return np.random.choice(range(len(actions.ravel())), p=actions.ravel())

        #print(actions)
        #return np.argmax(actions[0])
        return np.random.choice(range(actions.shape[1]), p=actions.ravel())

    def learn(self, milestone=False):
        total_reward = self.discount_and_normalise_rewards()
        #print(self.episode_actions)
        # Train on episode
        self.sess.run(self.train_op, feed_dict={
             self.X: self.episode_state,
             self.Y: self.episode_actions,
             self.total_reward: total_reward
        })

        # Reset the episode data
        self.episode_state, self.episode_actions, self.episode_rewards  = [], [], []

        # Save checkpoint
        if milestone == True and self.save_path is not None:
            save_path = self.saver.save(self.sess, self.save_path)
        return total_reward

    '''
    Discount and normalise the reward.
    Early on during my development, zero standard deviation results were breaking my model
    so I return zero when one is found
    '''
    def discount_and_normalise_rewards(self):
        tot = 0
        rewards = [0] * len(self.episode_rewards)
        for t in reversed(range(len(self.episode_rewards))):
            tot = tot * self.gamma + self.episode_rewards[t]
            rewards[t] = tot

        # Standard deviations are equal to zero, return zeros
        # we won't learn anything from this
        return rewards

        if np.std(rewards) == 0:
            return np.zeros_like(self.episode_rewards)

        # Normalise by discounting the mean
        rewards -= np.mean(rewards)
        # Divide all rewards by standard deviation
        return rewards / np.std(rewards)

    def build_network(self):
        with tf.name_scope('inputs'):
            self.X = tf.placeholder(tf.float32, (None,4,4,3), name="X")
            self.Y = tf.placeholder(tf.int32, [None, ], name="Y")
            self.total_reward = tf.placeholder(tf.float32, [None, ], name="reward")

        conv1 = tf.layers.conv2d(
            inputs = self.X,
            filters = 16,
            kernel_size = [2, 2],
            strides = 1,
            padding = 'same', # this will keep it as a 4 * 4 grid
            activation = tf.nn.relu,
            kernel_initializer = tf.random_normal_initializer(mean=0, stddev=0.3),
            bias_initializer = tf.constant_initializer(0.1),

            name='conv1')

        conv2 = tf.layers.conv2d(
            inputs = conv1,
            filters = 16,
            kernel_size = [2, 2],
            strides = 1,
            padding = 'same', # This will reduce it to a 3 * 3 grid
            activation = tf.nn.relu,
            kernel_initializer = tf.random_normal_initializer(mean=0, stddev=0.3),
            bias_initializer = tf.constant_initializer(0.1),
            name='conv2')

        flat_convs = tf.layers.flatten(
            inputs=conv2
        )

        dense = tf.layers.dense(
            inputs = flat_convs,
            units = 32,
            activation = tf.nn.tanh,
            kernel_initializer = tf.random_normal_initializer(mean=0, stddev=0.3),
            bias_initializer = tf.constant_initializer(0.1),
            name = 'fc'
        )
        self.logits = tf.layers.dense(
            inputs = dense,
            units = 4,
            kernel_initializer = tf.random_normal_initializer(mean=0, stddev=0.3),
            bias_initializer = tf.constant_initializer(0.1),
            name='logits')

        # Softmax outputs
        self.outputs_softmax = tf.nn.softmax(logits=self.logits, name='action_probabilities')

        with tf.name_scope('loss'):

            # This is the standard type of loss function, that I couldn't get to perform well
            cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.Y, logits=self.logits, name="cross_entropy")
            loss = tf.reduce_mean(cross_entropy / - self.total_reward)

        with tf.name_scope('train'):
            self.train_op = tf.train.AdamOptimizer(self.lr).minimize(loss)


from PIL import Image

image = Image.open('estrellas.png')
width, height = image.size

for y in range(height):
    for x in range(width):
        pixel = image.getpixel((x, y))
        # print(f"Pixel at ({x}, {y}): R={pixel[0]}, G={pixel[1]}, B={pixel[2]}")
        if pixel[0] == 255:
            print("estrella encontrada en "+str(x)+","+str(y))

image.close()


import server
import json
import protocol
import sys

if __name__ == '__main__':
    config_file = sys.argv[1]
    id = int(sys.argv[2])
    with open(config_file, 'r') as f:
        config = json.load(f)
    server = server.Server(
        config["servers"], id, protocol.protocol_instance)
    try:
        server.run()
    except KeyboardInterrupt:
        server.disconnect()
        print('Server dropped')