import numpy as np
import pandas as pd
import chord
from matplotlib import cm

def map_interaction_function(value):
    return 0 if value == 1 else 1

def map_interaction_color_function(value):
    d = {0.0: 'black', 0.5: 'red', 1: 'white', 2: 'blue'}
#    print(value)
#    print(d[value])
    return d[value]

df = pd.read_csv('pokemontypes.csv', index_col=0, skiprows=1)
df = df.astype(float)

arc_lengths = np.array([1 for _ in df.columns])
pkmn_types = df.columns
type_colors = ['#aaaa99', '#ff4422', '#3399ff', '#ffcc33', '#77cc55', '#66ccff', '#bb5544', '#aa5599', '#ddbb55', '#8899ff',
               '#ff5599', '#aabb22', '#bbaa66', '#6666bb', '#7766ee', '#775544', '#aaaabb', '#ee99ee'
        ]

chord = chord.Chord()
chord.make_arcs(arc_lengths)
#chord.make_labels(pkmn_types, text_colors=type_colors, text_kwargs={'fontsize': 10, 'bbox': props})
chord.make_labels([s.upper() for s in pkmn_types], text_colors='white', background_colors=type_colors)
#chord.make_labels([s.upper() for s in pkmn_types], text_colors=type_colors, background_colors='white', bbox_colors='white')

#chord.make_chords_from_centers_of_arcs(interactions=df.values, map_interaction_function=map_interaction_function, map_interaction_color_function=map_interaction_color_function, direction='forward')
chord.make_chords_both_directions(interactions=df.values, map_interaction_function=map_interaction_function, map_interaction_color_function=map_interaction_color_function)

#print(df)

chord.show()


import numpy as np
import matplotlib.pyplot as plt
import imageio

#https://medium.com/swlh/python-animated-images-6a85b9b68f86
#pip install imageio
#pip install imageio-ffmpeg
#pip install pygifsicle

image_path = './img_list/'

x=np.arange(0,1,0.001)
for i in range(10):
	plt.clf()
	plt.plot(x,x*float(i),label='y='+str(i)+'*x')
	plt.ylim(0,10)
	plt.legend()
	plt.savefig(image_path+str(i)+'.png')

image_list = []
for i in range(10):
    image_list.append(imageio.imread(image_path+str(i)+'.png'))

imageio.mimwrite(image_path+'animated_from_images.gif', image_list)


import pandas as pd
from sklearn.model_selection import train_test_split
import math
import operator

source_data= pd.read_csv('..\\mydata\\iris.data',header=None)

# print(source_data)

data = source_data[list(range(5))]

# print(data.shape)

train_data,test_data, = train_test_split(data,test_size=0.5)
train_data = train_data.values
test_data = test_data.values

# print(train_data.values[0][0])
# print(test_data.values)

def euclideanDistance(data1,data2,length):
    distance = 0
    for i in range(length):
        distance += pow((data1[i]-data2[i]),2)
    return math.sqrt(distance)

# def test1():
#     data1 = [2, 2, 2, 'a']
#     data2 = [4, 4, 4, 'b']
#     distance = euclideanDistance(data1, data2, 3)
#     print ('Distance: ' + repr(distance))

def findNeighbors(traindata,testdata,k):
    distance = []
    length = len(testdata) -1
    for i in range(len(traindata)):
        dist = euclideanDistance(testdata,traindata[i],length)
        distance.append((traindata[i],dist))
    distance.sort(key = operator.itemgetter(1))
    neighbors = []
    for x in range(k):
        neighbors.append(distance[x][0])
    return neighbors

def getResponse(ngber):
    classVotes = {}
    for x in range(len(ngber)):
        response = ngber[x][-1]
        if response in classVotes:
            classVotes[response] += 1
        else:
            classVotes[response] =1
    sortedVotes = sorted(classVotes.items(),key=operator.itemgetter(1),reverse=True)
    return sortedVotes[0][0]

def getAccuracy(test,predic):
    correct = 0;
    for x in range(len(test)):
        if test[x][-1] is predic[x]:
            correct += 1
        else:
            print("-----------> actul:"+test[x][-1]+" and predic:"+predic[x])
    return (correct/float(len(test)))*100

if __name__ == '__main__':
    prediction = []
    k = 3
    for x in range(len(test_data)):
        neighbors = findNeighbors(train_data,test_data[x],k)
        res = getResponse(neighbors)
        prediction.append(res)
        print('>>>> predicted=' + repr(res) + ', actual=' + repr(test_data[x][-1]))
    accuracy = getAccuracy(test_data, prediction)
    print('Accuracy: ' + repr(accuracy) + '%')


# Warning: May need to be started twice!
import requests
# import os
import time
import subprocess

p = subprocess.Popen(['run_controller.cmd'])
# Testing launch error catching
# if p.poll() is not None:
#     print ("failed to start!")
#     exit(1)
# else:
#     p = subprocess.Popen(['run_controller.cmd'])

time.sleep(5)

def Axis1SetZero():
    payload = {'Axis1SetZero': False}
    SetZero1 = requests.put('http://192.168.0.105/kas/plcvariables?format=text',data=payload)
    payload = {'Axis1SetZero': True}
    SetZero1 = requests.put('http://192.168.0.105/kas/plcvariables?format=text', data=payload)
    return SetZero1.status_code

def Axis2SetZero():
    payload = {'Axis2SetZero': False}
    SetZero2 = requests.put('http://192.168.0.105/kas/plcvariables?format=text',data=payload)
    payload = {'Axis2SetZero': True}
    SetZero2 = requests.put('http://192.168.0.105/kas/plcvariables?format=text', data=payload)
    return SetZero2.status_code

def ReadActualPosition12():
    ActualPos12 = requests.get('http://192.168.0.105/kas/plcvariables?variables=ActPos1,ActPos2&format=text')
    return ActualPos12.text  # two values separated with comma

# Returns only status codes; 200 - normal
def EnableMotors(retry_num = 3):
    retry_attempts = 0
    try:
        payload = "OpenButton=False"
        EnableMotorsS1 = requests.put('http://192.168.0.105/kas/plcvariables?format=text', data=payload)
        payload = "CloseButton=True"
        EnableMotorsS2 = requests.put('http://192.168.0.105/kas/plcvariables?format=text', data=payload)
        Stat1Enabled = requests.get('http://192.168.0.105/kas/plcvariables?variables=Stat1Enabled&format=text')
        Stat2Enabled = requests.get('http://192.168.0.105/kas/plcvariables?variables=Stat2Enabled&format=text')
        return EnableMotorsS1.status_code, EnableMotorsS2.status_code, Stat1Enabled.text, Stat2Enabled.text
    except:
        print("trying again")
        if (retry_attempts <= retry_num):
            time.sleep(retry_attempts)
            retry_attempts += 1
            EnableMotors()
        else:
            print ("Failed to enable motors")
            return False

# Returns only status codes; 200 - normal
def DisableMotors():
    payload = "CloseButton=False"
    EnableMotorsS1 = requests.put('http://192.168.0.105/kas/plcvariables?format=text',data=payload)
    payload = "OpenButton=True"
    EnableMotorsS2 = requests.put('http://192.168.0.105/kas/plcvariables?format=text',data=payload)
    Stat1Enabled = requests.get('http://192.168.0.105/kas/plcvariables?variables=Stat1Enabled&format=text')
    Stat2Enabled = requests.get('http://192.168.0.105/kas/plcvariables?variables=Stat2Enabled&format=text')
    return EnableMotorsS1.status_code, EnableMotorsS2.status_code, Stat1Enabled.text, Stat2Enabled.text

def checkMotorReadiness1():
    Stat1Enabled = requests.get('http://192.168.0.105/kas/plcvariables?variables=Stat1Enabled&format=text')
    #print(Stat1Enabled.text)
    return Stat1Enabled.text  # staus code; 200 - normal

def checkMotorReadiness2():
    Stat2Enabled = requests.get('http://192.168.0.105/kas/plcvariables?variables=Stat1Enabled&format=text')
    #print(Stat2Enabled.text)
    return Stat2Enabled.text  # staus code; 200 - normal

# Change Axis1 parameters
def Axis1Parameters(angle, velocity, acceleration):
    payload1 = {'Axis1RelDistance': angle}
    payload2 = {'Axis1Vel': velocity}
    payload3 = {'Axis1Accel': acceleration}
    r1 = requests.put('http://192.168.0.105/kas/plcvariables?format=text',data=payload1)
    r2 = requests.put('http://192.168.0.105/kas/plcvariables?format=text', data=payload2)
    r2 = requests.put('http://192.168.0.105/kas/plcvariables?format=text', data=payload3)
    s1 = requests.get('http://192.168.0.105/kas/plcvariables?variables=Axis1RelDistance&format=text')
    s2 = requests.get('http://192.168.0.105/kas/plcvariables?variables=Axis1Vel&format=text')
    s3 = requests.get('http://192.168.0.105/kas/plcvariables?variables=Axis1Accel&format=text')
    if angle == float(s1.text):
        s1 = 1
    else:
        s1 = 0
    if velocity == float(s2.text):
        s2 = 1
    else:
        s2 = 0
    if acceleration == float(s3.text):
        s3 = 1
    else:
        s3 = 0
    return s1, s2, s3  # statuses: 1 - normal, 0 - fault

# Change Axis2 parameters
def Axis2Parameters(angle, velocity, acceleration):
    payload1 = {'Axis2RelDistance': angle}
    payload2 = {'Axis2Vel': velocity}
    payload3 = {'Axis2Accel': acceleration}
    r1 = requests.put('http://192.168.0.105/kas/plcvariables?format=text',data=payload1)
    r2 = requests.put('http://192.168.0.105/kas/plcvariables?format=text', data=payload2)
    r2 = requests.put('http://192.168.0.105/kas/plcvariables?format=text', data=payload3)
    s1 = requests.get('http://192.168.0.105/kas/plcvariables?variables=Axis2RelDistance&format=text')
    s2 = requests.get('http://192.168.0.105/kas/plcvariables?variables=Axis2Vel&format=text')
    s3 = requests.get('http://192.168.0.105/kas/plcvariables?variables=Axis2Accel&format=text')
    if angle == float(s1.text):
        s1 = 1
    else:
        s1 = 0
    if velocity == float(s2.text):
        s2 = 1
    else:
        s2 = 0
    if acceleration == float(s3.text):
        s3 = 1
    else:
        s3 = 0
    return s1, s2, s3  # statuses: 1 - normal, 0 - fault

def runMotors(axis):
    if axis == 1:
        payload = {'TestDrive1': True}
        DriveMotors = requests.put('http://192.168.0.105/kas/plcvariables?format=text', data=payload)
    elif axis == 2:
        payload = {'TestDrive2': True}
        DriveMotors = requests.put('http://192.168.0.105/kas/plcvariables?format=text', data=payload)
    return DriveMotors.status_code

def positionWaiter(timeout, threshold, rel_motion, prev_angle):
    # for i in range(0,10):
    print('control = ', float((ReadActualPosition12()).split(",")[0]))
    print ("outcome", ((abs(float((ReadActualPosition12()).split(",")[0])) - (prev_angle + rel_motion))))
    while ((abs(float((ReadActualPosition12()).split(",")[0]) - (prev_angle + rel_motion))) > threshold):
        actual_angle = ReadActualPosition12()
        time.sleep(timeout)
        print(actual_angle)

    print("match!")
    return True

# Motor tests
EnableMotors()
time.sleep(2)
Axis1SetZero()
Axis2SetZero()
time.sleep(2)

or_reading = ReadActualPosition12()
print("Initial position is: ", or_reading)
prev_angle = float((or_reading).split(",")[0])
print(prev_angle)
# Go to actual angle required
angle1 = 360.0  # dgrees
velocity = 150.0  # degree/second
acceleration = 600.0  # degree/second^2
#print(Axis2Parameters(angle2, velocity, acceleration))
print(Axis1Parameters(angle1, velocity, acceleration))

print(runMotors(1))
#print(runMotors(2))
#time.sleep(5)
positionWaiter(0.1, 0.5, angle1, prev_angle)

DisableMotors()


#1123.py
import cv2
import numpy as np
import random

#1
WIDTH = 92
HEIGHT = 112
def load_face(filename='./data/faces.csv', test_ratio=0.2):
    file = open(filename, 'r')
    lines = file.readlines()

    N = len(lines)
    faces = np.empty((N, WIDTH*HEIGHT), dtype=np.uint8 )
    labels = np.empty(N, dtype = np.int32)
    for i, line in enumerate(lines):
        filename, label = line.strip().split(';')
        labels[i] = int(label)
        img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
        faces[i, :] = img.flatten()

# shuffling and seperate train and test data
    indices = list(range(N))
    random.seed(1) # same random sequences, so the same result
    random.shuffle(indices)
    shuffle_faces = faces[indices]
    shuffle_labels = labels[indices]

    test_size = int(test_ratio*N)

    test_faces = shuffle_faces[:test_size]
    test_labels = shuffle_labels[:test_size]

    train_faces = shuffle_faces[test_size:]
    train_labels = shuffle_labels[test_size:]
    return train_faces, train_labels, test_faces, test_labels

train_faces, train_labels, test_faces, test_labels = load_face()
print('train_faces.shape=',  train_faces.shape)
print('train_labels.shape=', train_labels.shape)
print('test_faces.shape=',   test_faces.shape)
print('test_labels.shape=',  test_labels.shape)

#2
N = 80
mean, eigenFace = cv2.PCACompute(train_faces, mean=None, maxComponents=N)
print('mean.shape = ', mean.shape)
print('eigenFace.shape=',  eigenFace.shape)

Y =cv2.PCAProject(train_faces, mean, eigenFace) # train result
print('Y.shape=', Y.shape)

#3: display eigen Face
dst = np.zeros((8*HEIGHT, 10*WIDTH), dtype=np.uint8)
for i in range(N):
  x = i%10
  y = i//10
  x1 = x*WIDTH
  y1 = y*HEIGHT
  x2 = x1+WIDTH
  y2 = y1+HEIGHT

  img = eigenFace[i].reshape(HEIGHT, WIDTH)
  dst[y1:y2, x1:x2] = cv2.normalize(img,None,0,255,cv2.NORM_MINMAX)
cv2.imshow('eigenFace %s'%N, dst)

#4: predict test_faces using  y = eigenFace(face - mean) and min distance
correct_count = 0
for i, face in enumerate(test_faces):
    y =cv2.PCAProject(face.reshape(1,-1), mean, eigenFace)
    dist=np.sqrt(np.sum((Y-y)**2,axis=1))
    k = np.argmin(dist)
    predict_label = train_labels[k]

    if test_labels[i]== predict_label:
        correct_count+= 1
    print('test_labels={}: predicted:{}'.format(
                     test_labels[i], predict_label))

accuracy = correct_count / float(len(test_faces))
print('accuracy=', accuracy)


"""
This module features a class that extracts a power spectrogram from a
signal.
"""

import logging

import numpy as np

from praudio.transforms.transform import TransformType, Transform
from praudio.transforms.stft import STFT
from praudio.io.signal import Signal

logger = logging.getLogger(__name__)

class PowerSpectrogram(Transform):
    """This class extracts a power spectrogram from a signal. It's a
    concrete Transform.

    Attributes:
        - power: Power to which we raise the spectrum. Default is 2
        - stft: STFT object used to extract Short-Time Fourier Transform
    """

    def __init__(self,
                 frame_length: int = 2048,
                 hop_length: int = 1024,
                 win_length: int = 2048,
                 window: str = "hann",
                 power: int = 2):
        super().__init__(TransformType.POWERSPECTROGRAM)
        self.power = power
        self.stft = STFT(frame_length,
                         hop_length,
                         win_length,
                         window)

    def process(self, signal: Signal) -> Signal:
        """Extract power spectrogram from waveform and modify signal.
        First we extract the STFT. Then, we apply the absolute value and
        raise it to the target power.

        :param signal: Signal object. Note: this transforms works only with
            waveform data

        :return: Modified signal
        """
        signal = self.stft.process(signal)
        signal.name = self._prepend_transform_name(signal.name)
        signal.data = self._raise_to_power(np.abs(signal.data))
        logger.info("Applied %s to %s", self.name.value, signal.file)
        return signal

    def _raise_to_power(self, array: np.ndarray):
        return array ** self.power


import numpy as np
import matplotlib.pyplot as plt
from readdata import read as rd
from pydmd import HODMD
def fuc(x):
    fucresult = np.cos(x)*np.sin(np.cos(x))+np.cos(x*.2)*np.sin(x)+x*(25-x)/100
    return fucresult
import plotcheck
#just test
#path = "/home/bwei/PycharmProjects/data lib/long wind"
#windset = rd(path)
#name = raw_input('the name of data set?')
x = np.linspace(0, 30, 128)
realwindset = fuc(x)
realwindset.shape = (len(realwindset),)
#realwindset = realwindset + np.random.rand(128)
#x = np.linspace(1, len(realwindset), len(realwindset))
hodmd = HODMD(svd_rank=0, exact=True, opt=True, d=58).fit(realwindset)
hodmd.reconstructed_data.shape
hodmd.plot_eigs()
hodmd.original_time['dt'] = hodmd.dmd_time['dt'] = x[1] - x[0]
hodmd.original_time['t0'] = hodmd.dmd_time['t0'] = x[0]
hodmd.original_time['tend'] = hodmd.dmd_time['tend'] = x[-1]

plt.plot(hodmd.original_timesteps, realwindset, '.', label='realwindset')
plt.plot(x, realwindset, '-', label='original function')
plt.plot(hodmd.dmd_timesteps, hodmd.reconstructed_data[0].real, '--', label='DMD output')
plt.legend()
plt.show()

extrap = 100
extrapx = np.linspace(0, extrap, extrap*20)
original_fuc = fuc(extrapx)

hodmd.dmd_time['tend'] = extrap
fig = plt.figure(figsize=(15, 5))
plt.plot(hodmd.original_timesteps, realwindset, '.', label='snapshots')
plt.plot(extrapx, original_fuc, '-', label='original function')
plt.plot(hodmd.dmd_timesteps, hodmd.reconstructed_data[0].real, '--', label='DMD output')
plt.legend()
plt.show()
reconstruct = np.dot(hodmd.modes, hodmd.dynamics)
plotcheck.pl(np.transpose(reconstruct))


from makiflow.core import MakiTensor
from makiflow.layers import ConvLayer
from makiflow.layers import ReshapeLayer

class DCParams:
    TYPE = 'DetectorClassifier'
    NAME = 'name'
    CLASS_NUMBER = 'class_number'
    DBOXES = 'dboxes'

    REG_X_NAME = 'reg_x_name'
    RKW = 'rkw'
    RKH = 'rkh'
    RIN_F = 'rin_f'
    USE_REG_BIAS = 'use_reg_bias'
    REG_INIT_TYPE = 'reg_init_type'

    CLASS_X_NAME = 'class_x_name'
    CKW = 'ckw'
    CKH = 'ckh'
    CIN_F = 'cin_f'
    USE_CLASS_BIAS = 'use_class_bias'
    CLASS_INIT_TYPE = 'class_init_type'

class DetectorClassifier:
    """
    This class represents a part of SSD algorithm. It consists of several parts:
    conv layers -> detector -> confidences + localization regression.
    """
    def __init__(
            self,
            reg_fms: MakiTensor, rkw, rkh, rin_f,
            class_fms: MakiTensor, ckw, ckh, cin_f,
            num_classes, dboxes: list, name,
            use_reg_bias=True, use_class_bias=True,
            reg_init_type='he', class_init_type='he'
    ):
        """
        Parameters
        ----------
        reg_fms : MakiTensor
            Source of features for the bbox regressor.
        rkw : int
            Width of the regressor's kernel.
        rkh : int
            Height of the regressor's kernel.
        rin_f : int
            Number of the input feature maps for the regressor.
        class_fms : MakiTensor
            Source of features for the classificator.
        ckw : int
            Width of the classificator's kernel.
        ckh : int
            Height of the classificator's kernel.
        cin_f : int
            Number of the input feature maps for the classificator.
        num_classes : int
            Number of classes to be classified + 'no object' class. 'no object' class is used for
            background.
        dboxes : list
            List of tuples of the default boxes' characteristics (width and height). Each characteristic
            must be represented in relative coordinates. Boxes' coordinates are always in the center of
            the cell of the feature map. Example:
            [(1, 1), (0.5, 1.44), (1.44, 0.5)] - (1,1) - center box matches one cell of the feature map.
            We recommend to use the following configuration:
            [
                (1, 1), (1, 2), (2, 1),
                (1.26, 1.26), (1.26, 2.52), (2.52, 1.26),
                (1.59, 1.59), (1.59, 3.17), (3.17, 1.59)
            ]
            This configuration corresponds to bboxes in RetinaNet.
        name : str or int
            Will be used as conjugation for the names of the classificator and regressor.
        """
        self.reg_x = reg_fms
        self.rkw = rkw
        self.rkh = rkh
        self.rin_f = rin_f
        self.class_x = class_fms
        self.ckw = ckw
        self.ckh = ckh
        self.cin_f = cin_f
        self.class_number = num_classes
        self._dboxes = dboxes
        self.name = str(name)
        self.use_class_bias = use_class_bias
        self.use_reg_bias = use_reg_bias
        self.reg_init_type = reg_init_type
        self.class_init_type = class_init_type

        classifier_out_f = num_classes * len(dboxes)
        bb_regressor_out_f = 4 * len(dboxes)
        self.classifier = ConvLayer(
            ckw, ckh, cin_f, classifier_out_f, use_bias=use_class_bias,
            activation=None, padding='SAME', kernel_initializer=class_init_type,
            name='SSDClassifier_' + str(name)
        )
        self.bb_regressor = ConvLayer(
            rkw, rkh, rin_f, bb_regressor_out_f, use_bias=use_reg_bias,
            activation=None, padding='SAME', kernel_initializer=reg_init_type,
            name='SSDBBDetector_' + str(name)
        )
        self._make_detections()

    def _make_detections(self):
        """
        Creates list with "flattened" predicted confidences and regressed localization offsets for each dbox.
        Example: [confidences, offsets]
        """
        n_dboxes = len(self._dboxes)

        # FLATTEN PREDICTIONS OF THE CLASSIFIER
        confidences = self.classifier(self.class_x)
        # [BATCH SIZE, WIDTH, HEIGHT, DEPTH]
        conf_shape = confidences.get_shape()
        # width of the tensor
        conf_w = conf_shape[1]
        # height of the tensor
        conf_h = conf_shape[2]
        conf_reshape = ReshapeLayer([-1, conf_w * conf_h * n_dboxes, self.class_number], 'ConfReshape_' + self.name)
        self._confidences = conf_reshape(confidences)

        # FLATTEN PREDICTIONS OF THE REGRESSOR
        offsets = self.bb_regressor(self.reg_x)
        # [BATCH SIZE, WIDTH, HEIGHT, DEPTH]
        off_shape = offsets.get_shape()
        # width of the tensor
        off_w = off_shape[1]
        # height of the tensor
        off_h = off_shape[2]
        # 4 is for four offsets: [x1, y1, x2, y2]
        off_reshape = ReshapeLayer([-1, off_w * off_h * n_dboxes, 4], name='OffReshape_' + self.name)
        self._offsets = off_reshape(offsets)

    def get_dboxes(self):
        return self._dboxes

    def get_conf_offsets(self):
        return [self._confidences, self._offsets]

    def get_feature_map_shape(self):
        """
        It is used for creating default boxes since their size depends
        on the feature maps' widths and heights.
        """
        return self.reg_x.get_shape()

    def get_height_width(self):
        pass

    def to_dict(self):
        return {
            'type': DCParams.TYPE,
            'params': {
                DCParams.REG_X_NAME: self.reg_x.get_name(),
                DCParams.RKW: self.rkw,
                DCParams.RKH: self.rkh,
                DCParams.RIN_F: self.rin_f,
                DCParams.USE_REG_BIAS: self.use_reg_bias,
                DCParams.REG_INIT_TYPE: self.reg_init_type,

                DCParams.CLASS_X_NAME: self.class_x.get_name(),
                DCParams.CKW: self.ckw,
                DCParams.CKH: self.ckh,
                DCParams.CIN_F: self.cin_f,
                DCParams.USE_CLASS_BIAS: self.use_class_bias,
                DCParams.CLASS_INIT_TYPE: self.class_init_type,

                DCParams.CLASS_NUMBER: self.class_number,
                DCParams.DBOXES: self._dboxes,
                DCParams.NAME: self.name
            }
        }


from pygame import *
from math import *

def listToInt(l):
    data = []
    for e in l:
        if e != '':
            data.append(floor(float(e)))
    return(data)

def listToFloat(l):
    print(l)
    data = []
    for e in l:
        if e != '':
            data.append(float(e))
    print(data)
    return(data)

def getIndex(addrs, addr):
    for i in range(len(addrs)):
        if (addrs[i][0] == addr[0]):
            return i
    return False

def AAfilledRoundedRect(surface, rect, color, radius=0.4):
    """
    AAfilledRoundedRect(surface,rect,color,radius=0.4)

    surface : destination
    rect    : rectangle
    color   : rgb or rgba
    radius  : 0 <= radius <= 1
    """

    rect = Rect(rect)
    color = Color(*color)
    alpha = color.a
    color.a = 0
    pos = rect.topleft
    rect.topleft = 0, 0
    rectangle = Surface(rect.size, SRCALPHA)

    circle = Surface([min(rect.size)*3]*2, SRCALPHA)
    draw.ellipse(circle, (0, 0, 0), circle.get_rect(), 0)
    circle = transform.smoothscale(circle, [int(min(rect.size)*radius)]*2)

    radius = rectangle.blit(circle, (0, 0))
    radius.bottomright = rect.bottomright
    rectangle.blit(circle, radius)
    radius.topright = rect.topright
    rectangle.blit(circle, radius)
    radius.bottomleft = rect.bottomleft
    rectangle.blit(circle, radius)

    rectangle.fill((0, 0, 0), rect.inflate(-radius.w, 0))
    rectangle.fill((0, 0, 0), rect.inflate(0, -radius.h))

    rectangle.fill(color, special_flags=BLEND_RGBA_MAX)
    rectangle.fill((255, 255, 255, alpha), special_flags=BLEND_RGBA_MIN)

    return surface.blit(rectangle, pos)


# Constants
QUESTION_DATA = [
    {"text": "A slug's blood is green.", "answer": "True"},
    {"text": "The loudest animal is the African Elephant.", "answer": "False"},
    {
        "text": "Approximately one quarter of human bones are in the feet.",
        "answer": "True",
    },
    {
        "text": "The total surface area of a human lungs is the size of a football pitch.",
        "answer": "True",
    },
    {
        "text": "In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take it home to eat.",
        "answer": "True",
    },
    {
        "text": "In London, UK, if you happen to die in the House of Parliament, you are entitled to a state funeral.",
        "answer": "False",
    },
    {"text": "It is illegal to pee in the Ocean in Portugal.", "answer": "True"},
    {"text": "You can lead a cow down stairs but not up stairs.", "answer": "False"},
    {"text": "Google was originally called 'Backrub'.", "answer": "True"},
    {"text": "Buzz Aldrin's mother's maiden name was 'Moon'.", "answer": "True"},
    {
        "text": "No piece of square dry paper can be folded in half more than 7 times.",
        "answer": "False",
    },
    {"text": "A few ounces of chocolate can to kill a small dog.", "answer": "True"},
]

class Question:
    def __init__(self, text, answer, question_number, score) -> None:
        self.text = text
        self.answer = answer
        self.question_number = question_number
        self.score = score
        self.users_answer = None
        self.correct = False

    def get_users_answer(self) -> str:
        valid_answers = ("true", "false")

        while self.users_answer not in valid_answers:
            self.users_answer = input(
                f"Q.{self.question_number}: {self.text} (True/False): "
            ).lower()

        return self.users_answer

    def check_users_answer(self) -> bool:
        if self.answer == self.users_answer.capitalize():
            self.correct = True
            self.score += 1
            return True

    def game_status(self) -> str:
        if self.correct:
            return f"""You got it right!
The correct answer was: {self.answer}.
Your current score is: {self.score}/{self.question_number}."""

        return f"""That's wrong.
The correct answer was: {self.answer}.
Your current score is: {self.score}/{self.question_number}."""

def main() -> None:
    question_number = 0
    score = 0

    for questions in QUESTION_DATA:
        question_number += 1
        text = questions["text"]
        answer = questions["answer"]

        print()
        play = Question(text, answer, question_number, score)
        play.get_users_answer()
        if play.check_users_answer():
            score += 1
        print(play.game_status())

if __name__ == "__main__":
    main()


from mystorytime.LLM_queries import LLM_split_and_describe

chapter = "Léa était une petite fille ordinaire, mais elle rêvait de devenir une sorcière puissante. Chaque nuit, elle s'endormait en imaginant des sorts spectaculaires et des potions magiques. Un matin, alors qu'elle se réveillait, une lettre mystérieuse glissa par la fente de sa porte. Elle était invitée à rejoindre l'école des sorciers pour y suivre sa formation. Léa était remplie de joie, mais elle savait qu'elle devait prouver ses compétences pour gagner sa place. Quelle épreuve l'attendait-elle ?"

result = LLM_split_and_describe(chapter, n_panels=4)

def test_result_keys_and_values():
    expected_keys = ['text', 'image_desc']

    assert len(result) == 4

    for item in result:
        assert all(key in item for key in expected_keys)
        assert item['text'] in chapter
        assert item['image_desc'] != ""

test_result_keys_and_values()


'''
Exercício Python 73: Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre:

a) Os 5 primeiros times.

b) Os últimos 4 colocados.

c) Times em ordem alfabética.

d) Em que posição está o time da Chapecoense.
'''

times=("Corinthians",
        "Palmeiras",
        "São Paulo",
        "Atlético Mineiro",
        "Botafogo",
        "Santos",
        "Fluminense",
        "Coritiba",
        "América"
        "Avaí",
        "Internacional",
        "Athletico",
        "Red Bull",
        "Flamengo",
        "Goiás",
        "Cuiabá",
        "Atlético",
        "Juventude",
        "Ceará",
        "Fortaleza",

)
print("*"*60)
print("\033[1;32m5 primeiros colocados do brasileirão em 24/05/2022: ")

for i in range(5):
    print("Colocação: {} | Time: {}".format(i+1,times[i]))

for time in times[:4]:
        print("| Time: {}".format(time))

print("*"*60)
print("\033[1;35mOs últimos 4 colocados: ")
for i in range(15,19):
    print("Colocação: {} | Time: {}".format(i+2,times[i]))

print("*"*60)
print("\033[1;36mTimes em ordem alfabética: ")

# sorted de strings as organizam em ordem alfabética

for time in sorted(times):

    print(f"{time}")

busca=input("\033[minsira o nome do time que vc deseja saber a posição: ").strip().title()

if busca in times:

    print("{} - posição : {} colocado".format(busca,times.index(busca)+1))
else:
    print("Esse time não tá no campeonado brasileiro de 2022")


from math import sin, cos, pi
from pygame import draw

class Spark:
    def __init__(self, pos, angle, speed, color=(255, 255, 255)):
        self.pos = list(pos)
        self.angle = angle
        self.speed = speed
        self.color = color

    def update(self):
        self.pos[0] += cos(self.angle) * self.speed
        self.pos[1] += sin(self.angle) * self.speed

        self.speed = max(0, self.speed - 0.1)

        return not self.speed

    def render(self, surf, offset=[0, 0]):
        render_points = [
            (self.pos[0] + cos(self.angle) * self.speed * 3 - offset[0], self.pos[1] + sin(self.angle) * self.speed * 3 - offset[1]),
            (self.pos[0] + cos(self.angle + pi * 0.5) * self.speed * 0.5 - offset[0], self.pos[1] + sin(self.angle + pi * 0.5) * self.speed * 0.5 - offset[1]),
            (self.pos[0] + cos(self.angle + pi) * self.speed * 0.5 - offset[0], self.pos[1] + sin(self.angle + pi) * self.speed * 0.5 - offset[1]),
            (self.pos[0] + cos(self.angle - pi * 0.5) * self.speed * 0.5 - offset[0], self.pos[1] + sin(self.angle - pi * 0.5) * self.speed * 0.5 - offset[1]),
        ]

        draw.polygon(surf, self.color, render_points)


# 이분그래프
import sys
sys.stdin = open('input.txt', 'r')
sys.setrecursionlimit(10**6)
input = sys.stdin.readline

K = int(input()) # 테스트 케이스
isEven = True

def dfs(v):
  global isEven
  visited[v] = True
  for i in A[v]:
    if not visited[i]:
      # 인접노드는 같은 집합 x
      check[i] = (check[v] + 1) % 2
      dfs(i)
    # 이미 방문한 노드가 현재 내 노드와 같은 집합이면 이분그래프 아님
    elif check[v] == check[i]:
      isEven = False

for _ in range(K):
  V, E = map(int, input().split()) # 정점개수, 간선개수
  A = [[] for _ in range(V+1)] # 인접리스트
  visited = [False] * (V+1) # 방문체크리스트
  check = [0] * (V+1) # 집합 구분 리스트
  isEven = True
  for i in range(E): # 인접리스트 값 저장
    s, e = map(int, input().split())
    A[s].append(e)
    A[e].append(s)

  for i in range(1, V+1):
    if isEven:
      dfs(i)
    else:
      break

  if isEven:
    print('YES')
  else:
    print('NO')


n, k = map(int, input().split())
coin = sorted([int(input()) for _ in range(n)], reverse=True)
cnt = 0
while k > 0:
    for c in coin:
        if c <= k:
            q, r = divmod(k, c)
            cnt += q
            k = r
print(cnt)


import numpy as np
from sklearn.cluster import DBSCAN
from tifffile import imsave, imread
from tqdm import tqdm
from skimage.morphology import dilation, disk
from catboost import Pool, CatBoostRegressor, CatBoostError
import argparse

def parse_image(path):
    extension = path.split('.')[-1]
    if extension == 'npz':
        im = np.load(path)
        img = im['arr_0']
    else:
        img = imread(path)
    return img, extension

def save_image(img, extension):
    if extension == 'npz':
        np.savez('res.' + extension, img)
    else:
        imsave('res.' + extension, img)

def check_intersection(img):
    mask = np.ones(img.shape[1:3], dtype=bool)
    for i in range(len(img)):
        msk = img[i] == 0
        mask = mask * msk
    return np.count_nonzero(mask)

def create_train_data(target_image, training_images, target_mask, train_mask, j,
                      window_size, geospatial=True):
    target_image_window = target_image[:, j: j + window_size]
    target_mask_window = target_mask[:, j: j + window_size]
    if np.count_nonzero(target_mask_window) == 0:
        return 0, 0, 0, 0, 0
    train_mask_window = train_mask[:, j: j + window_size]
    training_images_window = training_images[:, :, j: j + window_size]
    train_data = np.array([training_images_window[m][train_mask_window] for m in
                           range(len(training_images_window))])
    train_label = target_image_window[train_mask_window]
    train_data = np.moveaxis(train_data, 0, 1)
    if geospatial:
        coordinates = np.array(np.where(train_mask_window))
        coordinates = np.moveaxis(coordinates, 0, 1)
        train_data = np.concatenate([train_data, coordinates], axis=1)
    restore_data = np.array(
        [training_images_window[m][target_mask_window] for m in
         range(len(training_images_window))])
    restore_data = np.moveaxis(restore_data, 0, 1)
    if geospatial:
        coordinates = np.array(np.where(target_mask_window))
        coordinates = np.moveaxis(coordinates, 0, 1)
        restore_data = np.concatenate([restore_data, coordinates], axis=1)
    return train_data, train_label, restore_data, \
           target_mask_window, target_image_window

def create_train_data_quick(target_image, training_images, target_mask,
                            train_mask, i, j, window_size, geospatial=True):
    target_image_window = target_image[i: i + window_size, j: j + window_size]
    target_mask_window = target_mask[i: i + window_size, j: j + window_size]
    if np.count_nonzero(target_mask_window) == 0:
        return 0, 0, 0, 0, 0
    train_mask_window = train_mask[i: i + window_size, j: j + window_size]
    training_images_window = training_images[:, i: i + window_size,
                             j: j + window_size]
    train_data = np.array([training_images_window[m][train_mask_window] for m in
                           range(len(training_images_window))])
    train_label = target_image_window[train_mask_window]
    train_data = np.moveaxis(train_data, 0, 1)
    if geospatial:
        coordinates = np.array(np.where(train_mask_window))
        coordinates = np.moveaxis(coordinates, 0, 1)
        train_data = np.concatenate([train_data, coordinates], axis=1)
    restore_data = np.array(
        [training_images_window[m][target_mask_window] for m in
         range(len(training_images_window))])
    restore_data = np.moveaxis(restore_data, 0, 1)
    if geospatial:
        coordinates = np.array(np.where(target_mask_window))
        coordinates = np.moveaxis(coordinates, 0, 1)
        restore_data = np.concatenate([restore_data, coordinates], axis=1)
    return train_data, train_label, restore_data, \
           target_mask_window, target_image_window

def create_order(img):
    number_of_skips = [np.count_nonzero(img[i] == 0) for i in
                       range(img.shape[0])]
    order = [i for i in range(img.shape[0])]
    order = [x for x, _ in
             sorted(zip(order, number_of_skips), key=lambda pair: pair[1])]
    return order

def create_horizontal_iteration(img, mask, average_segment_length=1):
    horizontal_iteration = [0]
    coordinates = np.where(mask)[1][0]
    horizontal_iteration = horizontal_iteration + [i for i in
                                                   range(coordinates,
                                                         img.shape[-1],
                                                         average_segment_length)
                                                   ]
    horizontal_iteration.append(img.shape[-1])
    return horizontal_iteration

def _dummy_restore(img_volume, mask_volume):
    def roll_down(mask, i):
        for m in range(i, i + 30):
            if not mask[m]:
                return m
            return m

    for channel in range(img_volume.shape[3]):
        mask = img_volume[:, :, :, channel] == 0
        mask = mask * mask_volume
        if np.count_nonzero(mask) != 0:
            indexes = np.where(mask)
            (numbers, i_s, j_s) = indexes
            for number, i, j in zip(numbers.tolist(), i_s.tolist(),
                                    j_s.tolist()):
                img_volume[number, i, j, channel] = img_volume[
                    number, i - 1, j, channel] if i - 1 > 0 else img_volume[
                    number, roll_down(mask_volume[number, :, j], i), j, channel]
    return img_volume

def _quick_restore(
        img_volume,
        mask_volume,
        restoration_order,
        window_size=479,
        min_value=0.,
        max_value=1.,
        verbose=True,
        geospatial=True
):
    model = CatBoostRegressor(
        learning_rate=0.2,
        depth=5,
        loss_function='RMSE',
        verbose=0,
        num_trees=300

    )

    for target_image_number in tqdm(restoration_order, disable=not verbose):
        target_image = img_volume[target_image_number]
        target_mask = mask_volume[target_image_number]
        if np.count_nonzero(target_mask) == 0:
            continue
        train_mask = dilation(target_mask, disk(1))
        train_mask = train_mask ^ target_mask
        training_images = np.concatenate([img_volume[:target_image_number],
                                          img_volume[target_image_number + 1:]],
                                         axis=0)
        threshold = (target_image.shape[0] - window_size,
                     target_image.shape[1] - window_size)
        for i in range(0, target_image.shape[0], window_size):
            for j in range(0, target_image.shape[1], window_size):
                if i > threshold[0]:
                    i = threshold[0]
                if j > threshold[1]:
                    j = threshold[1]
                for channel in range(img_volume.shape[-1]):
                    train_data, train_label, restore_data, \
                    target_mask_window, \
                    target_image_window = create_train_data_quick(
                        target_image[:, :, channel],
                        training_images[:, :, :, channel],
                        target_mask,
                        train_mask, i, j,
                        window_size, geospatial=geospatial
                    )
                    if type(train_data) == int:
                        continue
                    train_pool = Pool(train_data, train_label)
                    try:
                        model.fit(train_pool)
                        restore_pool = Pool(restore_data)
                        res = model.predict(restore_pool)
                    except CatBoostError:
                        res = np.full((restore_data.shape[0],),
                                      np.average(train_label[0]))
                    target_image_window[target_mask_window] = res
                    img_volume[target_image_number, i:i + window_size,
                    j: j + window_size,
                    channel] = target_image_window
    img_volume = np.nan_to_num(img_volume, nan=0.0)
    img_volume = np.clip(img_volume, min_value, max_value)
    return img_volume

def _restore_images(
        img_volume,
        mask_volume,
        restoration_order,
        average_segment_length=479,
        min_value=0.,
        max_value=1.,
        verbose=True,
        geospatial=True
):
    model = CatBoostRegressor(
        learning_rate=0.2,
        depth=4,
        loss_function='RMSE',
        verbose=0,
        num_trees=210

    )
    for target_image_number in tqdm(restoration_order, disable=not verbose):
        target_image = img_volume[target_image_number]
        target_mask = mask_volume[target_image_number]
        if np.count_nonzero(target_mask) == 0:
            continue
        train_mask = dilation(target_mask, disk(1))
        restore_indexes = np.where(train_mask)
        indexes = np.moveaxis(np.array(restore_indexes), 0, 1)
        labels = DBSCAN(eps=1.5).fit_predict(indexes)
        train_masks = []
        target_masks = []
        for i in set(labels):
            ind = np.where(labels == i)
            train_mask_2 = np.zeros(shape=train_mask.shape, dtype=bool)
            rst = tuple((restore_indexes[0][ind], restore_indexes[1][ind]))
            train_mask_2[rst] = True
            target_masks.append(train_mask_2 * target_mask)
            train_masks.append((train_mask_2 ^ target_masks[-1]) * ~target_mask)

        training_images = np.concatenate([img_volume[:target_image_number],
                                          img_volume[target_image_number + 1:]],
                                         axis=0)
        for train_mask_current, target_mask_current in zip(train_masks,
                                                           target_masks):
            horizontal_iteration = create_horizontal_iteration(
                target_image[:, :, 0],
                train_mask_current,
                average_segment_length=average_segment_length
            )
            for m in range(len(horizontal_iteration) - 1):
                for channel in range(img_volume.shape[-1]):
                    j = horizontal_iteration[m]
                    window_size = horizontal_iteration[m + 1] - j
                    train_data, train_label, restore_data, \
                    target_mask_window, target_image_window = create_train_data(
                        target_image[:, :, channel],
                        training_images[:, :, :, channel],
                        target_mask_current,
                        train_mask_current,
                        j, window_size, geospatial=geospatial
                    )
                    if type(train_data) == int:
                        continue
                    train_pool = Pool(train_data, train_label)
                    try:
                        model.fit(train_pool)
                        restore_pool = Pool(restore_data)
                        res = model.predict(restore_pool)
                    except CatBoostError:
                        res = np.full((restore_data.shape[0],),
                                      np.average(train_label[0]))
                    target_image_window[target_mask_window] = res
                    img_volume[target_image_number, :, j: j + window_size,
                    channel] = target_image_window
    img_volume = np.nan_to_num(img_volume, nan=0.0)
    img_volume = np.clip(img_volume, min_value, max_value)
    return img_volume

def quick_restore(
        img_volume,
        mask_volume,
        range_object=None,
        min_value=0.,
        max_value=1.,
        verbose=True
):
    try:
        assert img_volume.shape[0] == mask_volume.shape[0]
    except AssertionError:
        print('First dimension of img_volume and mask_volume must be equal!')

    try:
        assert len(mask_volume.shape) == 3
    except AssertionError:
        print('Mask must have 3 dimensions (num_images, height, width)!')

    try:
        assert check_intersection(~mask_volume) == 0
    except AssertionError:
        print(
            'Your images do not fully cover all missing pixels! Add more '
            'images to your batch.')

    if len(img_volume.shape) == 3:
        img_volume = np.expand_dims(img_volume, -1)
    for i in range(img_volume.shape[-1]):
        img_volume[:, :, :, i][mask_volume] = 0
    if range_object is None:
        range_object = create_order(img_volume)
    img_volume = _dummy_restore(img_volume, mask_volume)
    img_volume = _quick_restore(
        img_volume,
        mask_volume,
        range_object,
        min_value=min_value,
        max_value=max_value,
        verbose=verbose
    )
    return img_volume

def full_restore(
        img_volume,
        mask_volume,
        range_object=None,
        min_value=0.,
        max_value=1.,
        no_quick=False,
        verbose=True
):
    if range_object is None:
        range_object = create_order(img_volume)
    img_volume = quick_restore(
        img_volume,
        mask_volume,
        range_object=[] if no_quick else None,
        min_value=min_value,
        max_value=max_value,
        verbose=verbose
    )
    img_volume = _restore_images(
        img_volume,
        mask_volume,
        range_object,
        min_value=min_value,
        max_value=max_value,
        verbose=verbose
    )
    return img_volume

def main():
    parser = argparse.ArgumentParser(
        description='This script performs restoration of the Landsat 7 images.'
    )
    parser.add_argument('path_to_file', type=str,
                        help='Path to the file you want to restore. Currently '
                             'supported '
                             'formats are .npz and .tif. Note that your file '
                             'should have '
                             'shape (num_images, height, width, num_channels).')
    parser.add_argument('path_to_mask', type=str,
                        help='Path to the mask. Note that the mask must be of'
                             'shape (num_images, height, width). You can '
                             'create proper '
                             'mask with "create_mask.py".')
    parser.add_argument('--algorithm', type=str, default='quick',
                        choices=['quick', 'full'],
                        help='Type of the algorithm to use.')
    parser.add_argument('--silent', action='store_true')
    parser.add_argument('--order', type=int, action='extend', nargs='+',
                        help='You can specify which images you want to '
                             'restore and the order of restoration. '
                             "If you don't specify this parameter, all of "
                             "your images will be restored."
                             "Note that if you use full version of the "
                             "algorithm even if you specify only "
                             "part of the images to be restored, still all of "
                             "your images will be restored"
                             "but the full version of the algorithm will be "
                             "applied only to specified images."
                             "If you don't" 'want this behavior use option '
                             '"--noquick"')
    parser.add_argument('--noquick', action='store_true')
    parser.add_argument('--min', type=float, default=-1.)
    parser.add_argument('--max', type=float, default=1.)
    args = parser.parse_args()
    img_volume, extension = parse_image(args.path_to_file)
    mask_volume, _ = parse_image(args.path_to_mask)
    if args.algorithm == 'quick':
        img_volume = quick_restore(
            img_volume,
            mask_volume,
            range_object=args.order,
            min_value=args.min,
            max_value=args.max,
            verbose=not args.silent
        )
    elif args.algorithm == 'full':
        img_volume = full_restore(
            img_volume,
            mask_volume,
            range_object=args.order,
            min_value=args.min,
            max_value=args.max,
            verbose=not args.silent,
            no_quick=args.noquick
        )
    save_image(img_volume, extension)
    print('Restoration has ended! Result is saved in file "res.{}"'.format(
        extension))

if __name__ == '__main__':
    main()


from sklearn.metrics import confusion_matrix
import numpy
#import pdb
import math

class Metrics(object):
    """
    Contains evaluation metrics

    """
    def __init__(self, nclasses):
        self.nclasses= nclasses
        self.fp = 0
        self.fn = 0
        self.tp = 0
        self.cost = 0
        self.error = 0
        self.prec = 0
        self.rec = 0
        self.fmes = 0
        self.conf_mat= numpy.zeros([nclasses, nclasses], dtype= numpy.float32)

    def reset(self):
        self.fp = 0
        self.fn = 0
        self.tp = 0
        self.cost = 0
        self.error = 0
        self.prec = 0
        self.rec = 0
        self.fmes = 0
        self.conf_mat= numpy.zeros([self.nclasses, self.nclasses], dtype= numpy.float32)
        self.mean_iou_index= 0

    def update_metrics_batch(self, preds, y):
        error = 0
        cost = 0
        for i in range(preds.shape[0]):
            self.update_metrics(preds[i],y[i],error,cost)

    def update_metrics(self, preds, y, error, cost):
        self.error += error
        self.cost += cost
        cf_m= confusion_matrix(y.flatten(), preds.flatten(), range(0, self.nclasses))
        self.conf_mat+=cf_m

    def compute_rates(self, nonignore=None):
        perclass_tp = numpy.diagonal(self.conf_mat).astype(numpy.float32)
        if nonignore is not None:
            perclass_fp = self.conf_mat[nonignore,:].sum(axis=0) - perclass_tp #SUM(nji) - nii
        else:
            perclass_fp = self.conf_mat.sum(axis=0) - perclass_tp #SUM(nji) - nii

        perclass_fn = self.conf_mat.sum(axis=1) - perclass_tp

        if self.nclasses == 2:
            self.tp= perclass_tp[1]
            self.fp= perclass_fp[1]
            self.fn= perclass_fn[1]
        self.iou= perclass_tp/(perclass_fp+ perclass_tp+ perclass_fn)
        if nonignore is not None:
            self.iou= self.iou[nonignore]
        else:
            self.iou= self.iou[:-1]

        self.mean_iou_index= self.getScoreAverage(self.iou)

    def getScoreAverage(self, scoreList):
        validScores = 0
        scoreSum    = 0.0
        for score in scoreList:
            if not math.isnan(score):
                validScores += 1
                scoreSum += score
        if validScores == 0:
            return float('nan')
        return scoreSum / validScores

    def compute_final_metrics(self, nmini_batches, nonignore=None):
        self.compute_rates(nonignore)
        if not (self.tp==0 and (self.fp==0 or self.fn==0)):
            self.prec= numpy.true_divide(self.tp,self.tp+self.fp)
            self.rec= numpy.true_divide(self.tp, self.tp+self.fn)
            self.fmes= (2*self.rec*self.prec)/(self.rec+self.prec)
        self.error /= nmini_batches
        self.cost /= nmini_batches
        return self.mean_iou_index


import json
import os
import requests
import time
import urllib
import urllib.request
from flask import Flask, Response, request

app = Flask(__name__)

URLSCANIO_API_KEY = os.getenv('URLSCANIO_API_KEY')
SLEEP_TIME = os.getenv('SLEEP_TIME', default=3)
RETRY = os.getenv('RETRY', default=5)
print(URLSCANIO_API_KEY)

@app.route('/')
def hello():
    if 'url' not in request.args:
        return get_error_response("url parametresi verilmedi")

    url = request.args["url"]

    headers = {'API-Key': URLSCANIO_API_KEY, 'Content-Type': 'application/json'}
    data = {"url": url, "visibility": "public"}
    response = requests.post('https://urlscan.io/api/v1/scan/', headers=headers, data=json.dumps(data)).json()

    if 'api' not in response:
        return get_error_response(response['message'])

    data = json.dumps(response['api'])
    api_url = data[1:-1]

    for x in range(RETRY):
        time.sleep(SLEEP_TIME)

        try:
            json_data = urllib.request.urlopen(api_url)
            db = json.loads(json_data.read())

            return get_succes_response(db)
        except:
            pass

    return get_error_response("Server Zaman Aşımına Uğradı")

def get_error_response(msg):
    return Response('{"success": false, "message": "' + msg + '"}', mimetype='application/json')

def get_succes_response(data):
    return Response('{"success": true, "data": ' + json.dumps(data) + '}', mimetype='application/json')

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)


import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
import dash_daq as daq
import dash_leaflet as dl
from dash_extensions.javascript import Namespace
import dash_leaflet.express as dlx
from dash_extensions.javascript import arrow_function
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd

from app import app, db

### ----------------------------- SETUP ---------------------------------- ###

# Load data
cosmos_targets = pd.read_sql_table('view_cosmos_targets', con=db.engine)
project_outcomes = pd.read_sql_table('view_project_outcomes', con=db.engine)

# prep data for chart
df = project_outcomes.merge(
    cosmos_targets[['cpa_name', 'long_form', 'quantity']],
    how='right',
    on=['cpa_name', 'long_form'])

df['contribution'] = df['total_outcomes'] / df['quantity']

def plot_cosmos(df):

    fig = go.Figure()
    bar_width = .7

    fig.add_traces(go.Bar(
            x=df['contribution'],
            y=df['long_form'],
            name='Outcomes',
            orientation='h',
            width=bar_width
        ))

    fig.update_layout(barmode='stack')

    return fig

def get_project_points(cpa: str):
    df_cpa = project_outcomes[project_outcomes['cpa_name'] == cpa] if cpa else project_outcomes
    df_cpa = df_cpa[['project_nickname', 'cpa_name', 'coordinate_x', 'coordinate_y']].dropna().drop_duplicates()
    dicts = df_cpa.to_dict('rows')
    for item in dicts:
        item['tooltip'] = item['project_nickname']
        item['popup'] = item['cpa_name']
    geojson = dlx.dicts_to_geojson(dicts, lat='coordinate_x', lon="coordinate_y")
    return dlx.geojson_to_geobuf(geojson)

### ----------------------------- LAYOUT --------------------------------- ###

### SELECT REGION ###
_regions = cosmos_targets['cpa_name'].unique()
_region_options = [{'label': region, 'value': region} for region in _regions]

select_region = dcc.Dropdown(
    id='select-region',
    placeholder='Select a CPA',
    options=_region_options
)

### COSMOS CHART ###
cosmos_chart = dcc.Graph(
    id='cosmos-chart',
    config = {
        'displayModeBar': 'hover',
        'doubleClick': False,
        'scrollZoom': False,
        'modeBarButtonsToRemove': [
            'zoom2d', 'select2d', 'lasso2d',
            'zoomIn2d', 'zoomOut2d', 'autoScale2d',
            'resetScale2d', 'hoverClosestCartesian',
            'hoverCompareCartesian'
            ],
        'displaylogo': False
    }
)

### DATE RANGE SLIDER ###
date_slider = daq.Slider(
    id='date-slider',
    min=5,
    max=15,
    handleLabel={"showCurrentValue": True, "label": "yr"},
    updatemode='mouseup',
    color='blue',
    size = 265*2,
    marks={'5': '5 yr', '10': '10 yr', '15': 'Beyond'}
)

### MAP ###

# set up scatter points
ns = Namespace('dlx', 'scatter')
geojson = dl.GeoJSON(data=get_project_points(None), id='geojson', format='geobuf',
                     zoomToBounds=True,
                     cluster=True,
                     zoomToBoundsOnClick=True,
                     superClusterOptions=dict(radius=150))

# add cpa boundaries
cpa_boundaries = dl.GeoJSON(id='rfmp',
                            url="/assets/cpa.json",
                            zoomToBounds=True,
                            hoverStyle=arrow_function(dict(weight=5, color='#666', dashArray='')))  # must be in assets folder

# create map
map = dl.Map(id='map',
             children= [dl.TileLayer(), cpa_boundaries, geojson],
             style={'width': '100%', 'height': '50vh', 'margin': "auto", "display": "block"})

### PROJECT WINDOW ###
_projects = [
    'Project A',
    'Project B',
    'Project C',
    'Project D'
]

projects_card = dbc.Card(
    dbc.CardBody(
        dcc.Checklist(
            options = [{'label': "\t" + project, 'value': project} for project in _projects],
            labelStyle={'display': 'block'}
        )
    )
)

### LAYOUT ###
layout = html.Div(
    dbc.Row(
        [
            dbc.Col([
                select_region,
                cosmos_chart,
                dbc.Row(date_slider, justify='center', align='center')
                ], width={'size': 7, 'offset': 1}
            ),
            dbc.Col([
                map
                ], width=3
            )
        ]
    )
)

### ---------------------------- CALLBACKS ------------------------------- ###

@app.callback(
    Output('cosmos-chart', 'figure'),
    [Input('select-region', 'value')]
)
def update_chart(region):
    if region:
        filt = df['cpa_name'] == region
        return plot_cosmos(df[filt])
    else:
        return plot_cosmos(df)


# Import dependencies
import numpy as np
import tensorflow as tf
import pandas as pd

# Defining the model class
class LongShortTermMemoryModel:
    def __init__(self, encoding_size):
        # Model constants
        cell_state_size = 128

        # Cells
        cell = tf.contrib.rnn.BasicLSTMCell(cell_state_size)

        # Model input
        self.batch_size = tf.placeholder(tf.int32, [])  # Needed by cell.zero_state call, and can be dependent on usage (training or generation)
        self.x = tf.placeholder(tf.float32, [None, None, 26])  # Shape: [batch_size, max_time, encoding_size]
        self.y = tf.placeholder(tf.float32, [None, None, encoding_size])  # Shape: [batch_size, max_time, encoding_size]
        self.in_state = cell.zero_state(self.batch_size, tf.float32)  # Can be used as either an input or a way to get the zero state

        # Model variables
        W = tf.Variable(tf.random_normal([cell_state_size, encoding_size]))
        b = tf.Variable(tf.random_normal([encoding_size]))

        # Model operations
        lstm, self.out_state = tf.nn.dynamic_rnn(cell, self.x, initial_state=self.in_state)  # lstm has shape: [batch_size, max_time, cell_state_size]

        # Logits, where tf.einsum multiplies a batch of txs matrices (lstm) with W
        logits = tf.nn.bias_add(tf.einsum('bts,se->bte', lstm, W), b)  # b: batch, t: time, s: state, e: encoding

        # Predictor
        self.f = tf.nn.softmax(logits)

        # Cross Entropy loss
        self.loss = tf.losses.softmax_cross_entropy(self.y, logits)

# Creating the training set

data = pd.read_csv('emojis50.csv')
index_to_emoji = data['Emoji']

results = []
for i in range(len(index_to_emoji)):
    results.append([int(j == i) for j in range(len(index_to_emoji))])

# Encodes all letters a-z as input vector for model
characters = dict()

for i in range(97, 97+26):
    characters[chr(i)] = [0 if not j == i-97 else 1 for j in range(26)]

encoding_size = len(results)

x_train = [
    [characters[x] for x in string] for string in data['Name']
]
y_train = [
    [results[i]] for i in range(len(results))
]

LEARNING_RATE = 0.1
EPOCHS = 5000

# Creating model and initializing session
model = LongShortTermMemoryModel(encoding_size)

# Training: adjust the model so that its loss is minimized
minimize_operation = tf.train.RMSPropOptimizer(LEARNING_RATE).minimize(model.loss)

# Create session object for running TensorFlow operations
session = tf.Session()

# Initialize tf.Variable objects
session.run(tf.global_variables_initializer())

# Initialize model.in_state
zero_state = session.run(model.in_state, {model.batch_size: 1})

# Training the model
# Trained an equal ammount of times on all emojis
for epoch in range(EPOCHS):
    session.run(minimize_operation, {model.batch_size: 1, model.x: [x_train[epoch%50]], model.y: [y_train[epoch%50]], model.in_state: zero_state})

# Function for predicting emoji from text
def predict(text):
    y = ''
    state = session.run(model.in_state, {model.batch_size: 1})

    for c in text:
        y, state = session.run([model.f, model.out_state], {model.batch_size: 1, model.x: [[characters[c]]], model.in_state: state})

    return index_to_emoji[y[0].argmax()]

# Test program. Let's user input a string and prints the resulting emoji.
text = input('Please input a word:\t').split()[0].lower()
while not text == 'exit':
    print("Program returns:", predict(text))
    text = input('Please input a word:\t').split()[0].lower()
print('\nExiting program.')

session.close()


from django.conf import settings
from django.db import models

from .signals import user_logged_in
from .utils import get_client_city_data, get_client_ip

class UserSessionManager(models.Manager):
    def create_new(self, user, session_key=None, ip_address=None, city_data=None):
        session_new = self.model()
        session_new.user = user
        session_new.session_key = session_key
        if ip_address is not None:
            session_new.ip_address = ip_address
            if city_data:
                session_new.city_data = city_data
                try:
                    city = city_data['city']
                except:
                    city = None
                session_new.city = city
                try:
                    country = city_data['country_name']
                except:
                    country = None
            session_new.country = country
            session_new.save()
            return session_new
        return None

class UserSession(models.Model):
    user            = models.ForeignKey(settings.AUTH_USER_MODEL)
    session_key     = models.CharField(max_length=60, null=True, blank=True)
    ip_address      = models.GenericIPAddressField(null=True, blank=True)
    city_data       = models.TextField(null=True, blank=True)
    city            = models.CharField(max_length=120, null=True, blank=True)
    country         = models.CharField(max_length=120, null=True, blank=True)
    active          = models.BooleanField(default=True)
    timestamp       = models.DateTimeField(auto_now_add=True)

    objects = UserSessionManager()

    def __str__(self):
        city = self.city
        country = self.country
        if city and country:
            return f"{city}, {country}"
        elif city and not country:
            return f"{city}"
        elif country and not city:
            return f"{country}"
        return self.user.username

def user_logged_in_receiver(sender, request, *args, **kwargs):
    user = sender
    ip_address = get_client_ip(request)
    city_data = get_client_city_data(ip_address)
    request.session['CITY'] = str(city_data.get('city', 'New York'))
    session_key = request.session.session_key
    UserSession.objects.create_new(
                user=user,
                session_key=session_key,
                ip_address=ip_address,
                city_data=city_data
                )

user_logged_in.connect(user_logged_in_receiver)


# -*- coding:utf-8 -*-
from bottle import request, HTTPResponse
import json
import twitter_client as tc
import db_create_tables as db
import kw_apis_main

dbname = './example.db'
# dbname = './schetweet.db'

def add_tweet_group(request):
    body = request.json

    sched_start_date = body['sched_start_date']
    interval = body['interval']

    conn = db.connect_db(dbname)
    cursor = db.get_cursor(conn)
    result = db.add_group(cursor, sched_start_date, interval)
    db.commit(conn)
    conn.close()

    res_body = {'gid': result}
    return res_body

def update_tweet_group(request):
    print("Content-Type: {}".format(request.get_header))
    body = request.json
    print(body)

    gid = body['gid']
    sched_start_date = body['sched_start_date']
    interval = body['interval']
    status = body['status']

    conn = db.connect_db(dbname)
    cursor = db.get_cursor(conn)
    result = db.update_tweet_group(conn, cursor, gid, sched_start_date, interval, status)
    conn.close()
    print("Updated the tweet group with gid: {}, sched_start_date: {}, interval: {}, status: {}".format(gid, sched_start_date, interval, status))

    res_body = {}
    return res_body

def search_tweet_groups_by_date(request):

    print("Content-Type: {}".format(request.get_header))
    body = request.json
    print(body)

    date = body["date"]

    conn = db.connect_db(dbname)
    cursor = db.get_cursor(conn)
    # cursor.execute("SELECT * FROM sched_tweet_groups")
    result = db.search_group_by_date(cursor, date)
    conn.close()

    res_body = result
    return res_body

def delete_tweet_group(request):

    body = request.json

    gid = body['gid']

    conn = db.connect_db(dbname)
    cursor = db.get_cursor(conn)
    result = db.del_group(cursor, gid)
    db.commit(conn)
    conn.close()

    print("Deleted the tweet group with gid {}".format(result))

    res_body = {'gid': result }
    return res_body

def get_formatted_org_tweet_text(org_tweet_id):
    twitter = tc.twitter_auth()
    res = tc.get_tweet(twitter, org_tweet_id)
    org_tweet_text = 'Blank'
    if res.status_code == 200:
        tweet = json.loads(res.text)
        org_tweet_text = tweet['text'] + ' by ' + tweet['user']['name'] + ' at ' + tweet['created_at']
    return org_tweet_text

def update_tweet(request):
    # Tweet(RT, 画像付TweetもTweetとして取り扱う) 新規登録・更新用API。
    # ポストされるデータのidの定義の有無で新規または更新を判定。
    # 新規登録：
    #   id未定義の場合。rt_flagが必須(0: tweet, 1: RT)
    #   gid(推奨 default=0), subid(推奨 default=0), text(推奨 default='')、org_tweet_id(推奨 default=0) 。
    #   idを採番して返す。
    # 更新：
    #   id定義の場合。rt_flagが必須(0: tweet, 1: RT)
    #   tweetの場合、text、retweetの場合、org_tweet_idが推奨（ブランクの場合は空欄または0で更新される）
    #   gid, subidは無視。

    ## Session ID認証成功の場合のメイン処理
    req_error = False;
    body = request.json

    # 入力のチェック
    try:
        id = body['id']
        new_tweet = False;
    except KeyError:
        new_tweet = True;

    # rt_flag (必須)
    try:
        rt_flag = int(body['rt_flag'])
    except KeyError:
        rt_flag = 0;

    if rt_flag == 1:
        try:
            org_tweet_id = body['org_tweet_id']
        except KeyError:
            org_tweet_id = 0;
    elif rt_flag == 0:
        try:
            text = body['text']
        except KeyError:
            text = '';

    conn = db.connect_db(dbname)
    cursor = db.get_cursor(conn)

    if new_tweet == True:  # 新規登録
        try:
            gid = body['gid']
        except KeyError:
            gid = 0;

        try:
            subid = body['subid']
        except KeyError:
            subid = 0;

        if rt_flag == 0:
            id = db.add_tweet(cursor, gid, subid, text)  # return gid
            print("Added new tweet {} with gid {}, subid {}, and text {}".format(id, gid, subid, text))
        elif rt_flag == 1:
            # Retweet対象のtweetのテキストを取得
            org_tweet_text = get_formatted_org_tweet_text(org_tweet_id)
            id = db.add_retweet(cursor, gid, subid, org_tweet_id, org_tweet_text)
            print("Added new retweet {} with gid {}, subid {}, and org_tweet_id {} ({})".format(id, gid, subid, org_tweet_id, org_tweet_text))
    else:  # 更新
        if rt_flag == 0:
            id = db.update_tweet(cursor, id, text)
            print("Updated the tweet with id {}, and text {}".format(id, text))
        elif rt_flag == 1:
            # Retweet対象のtweetのテキストを取得
            org_tweet_text = get_formatted_org_tweet_text(org_tweet_id)
            id = db.update_retweet(cursor, id, org_tweet_id, org_tweet_text)
            print("Updated the retweet with id {}, and org_tweet_id {}({})".format(id, org_tweet_id, org_tweet_text))

    db.commit(conn)
    conn.close()

    res_body = {'id': id}
    if rt_flag == 1:
        res_body['org_tweet_text'] = org_tweet_text

    return res_body

def search_tweets_by_gid(request):

    print("Content-Type: {}".format(request.get_header))
    body = request.json
    print(body)

    gid = body["gid"]

    conn = db.connect_db(dbname)
    cursor = db.get_cursor(conn)
    # cursor.execute("SELECT * FROM sched_tweet_groups")
    result = db.search_tweets_by_gid(cursor, gid)

    conn.close()

    print("Search tweets with gid {}.".format(gid))

    res_body = result
    return res_body

def delete_tweet(request):

    body = request.json

    id = body['id']

    conn = db.connect_db(dbname)
    cursor = db.get_cursor(conn)
    db.del_tweet(cursor, id)
    db.commit(conn)
    conn.close()

    print("Deleted the tweet with id {}".format(id))

    res_body = {'id': id}
    return res_body


import os
import subprocess
import traceback

from conans import tools

def _get_package_version(package_recipe_path, pkg_version):
    version = pkg_version or tools.load(os.path.join(package_recipe_path, "version.txt"))

    return version

def _print_pkg_processing_report(package_list, processing_ok, process_label_suffix):
    if package_list:
        print("%d %s package %s" % (
            len(package_list), ("successful" if processing_ok else "failed"), process_label_suffix))

        for pkg in package_list:
            print(f"{'** Success **' if processing_ok else '-- Failed --'} <-> {pkg}")

def exec_common_cmd(cmd_opts_list, cmd_title_label, cmd_suffix_label, pkg_name, nla_recipes_dir,
                    excluded_recipes_list, remote=None, pkg_version=None, profile_name=None,
                    recipe_profile_exclusion_list=None, profiles_dir_path=None, use_recipe_path=False, shared=None):
    print(f"{cmd_title_label} package: {pkg_name}")

    successful_ops = []
    failed_ops = []
    pkg_process_exclusion_msg = "Processing of package %s is excluded!"

    for root, dirs, files in os.walk(nla_recipes_dir):
        for recipe_dir in dirs:
            if excluded_recipes_list and recipe_dir in excluded_recipes_list:
                print(pkg_process_exclusion_msg % pkg_name)
                continue

            if excluded_recipes_list and pkg_name and pkg_name in excluded_recipes_list:
                print(pkg_process_exclusion_msg % pkg_name)
                break

            cmd_opts = [cmd_opt for cmd_opt in cmd_opts_list]
            print("Input command template:")
            print(cmd_opts)

            if shared and pkg_name != "*":
                cmd_opts.append("-o %s:shared=%s" % (pkg_name, shared))

            if profile_name and profiles_dir_path:
                if recipe_profile_exclusion_list and (
                        pkg_name not in recipe_profile_exclusion_list or recipe_dir not in recipe_profile_exclusion_list):
                    cmd_opts.append("--profile")
                    cmd_opts.append(os.path.join(profiles_dir_path, profile_name))

            if use_recipe_path:
                cmd_opts.append(os.path.join(root, (recipe_dir if pkg_name == "*" else pkg_name)))

            the_pkg = (pkg_name if pkg_name != "*" else recipe_dir)
            the_version = (pkg_version or "") if pkg_name != "*" else None

            cmd_opts.append("%s/%s@" % (the_pkg, _get_package_version(os.path.join(root, the_pkg), the_version)))

            if remote:
                cmd_opts.append("-r")
                cmd_opts.append(remote)
            print("Command to be executed is:")
            print(cmd_opts)
            completed_process = subprocess.run([cmd_opt for cmd_opt in cmd_opts], text=True,
                                               stderr=subprocess.STDOUT)

            try:
                completed_process.check_returncode()
            except Exception as e:
                failed_ops.append(recipe_dir if pkg_name == "*" else pkg_name)
                print("Failed to process package: %s! Please check error details below: %s" % (
                    recipe_dir if pkg_name == "*" else pkg_name, e))
                traceback.print_exc()

                if pkg_name == "*":
                    continue
                else:
                    break

            successful_ops.append(recipe_dir if pkg_name == "*" else pkg_name)
            print("Successfully processed package: %s" % recipe_dir if pkg_name == "*" else pkg_name)

            if pkg_name != "*":
                break
        if pkg_name != "*":
            break

    _print_pkg_processing_report(successful_ops, True, cmd_suffix_label)
    _print_pkg_processing_report(failed_ops, False, cmd_suffix_label)


"""RBTools version and package information.

These variables and functions can be used to identify the version of
Beanbag Tools. They're largely used for packaging purposes.
"""

#: The version of RBTools
#:
#: This is in the format of:
#:
#: (Major, Minor, Micro, Patch, alpha/beta/rc/final, Release Number, Released)
#:
VERSION = (5, 0, 0, 0, 'alpha', 0, False)

def get_version_string():
    """Return the version as a human-readable string.

    Returns:
        str:
        The version number as a human-readable string.
    """
    major, minor, micro, patch, tag, relnum, is_release = VERSION

    version = '%s.%s' % (major, minor)

    if micro or patch:
        version += '.%s' % micro

        if patch:
            version += '.%s' % patch

    if tag != 'final':
        if tag == 'rc':
            version += ' RC'
        else:
            version += ' %s ' % tag

        version += '%s' % relnum

    if not is_release:
        version += ' (dev)'

    return version

def get_package_version():
    """Return the version as a Python package version string.

    Returns:
        str:
        The version number as used in a Python package.
    """
    major, minor, micro, patch, tag, relnum = __version_info__

    version = '%s.%s' % (major, minor)

    if micro or patch:
        version += '.%s' % micro

        if patch:
            version += '.%s' % patch

    if tag != 'final':
        version += '%s%s' % (
            {
                'alpha': 'a',
                'beta': 'b',
            }.get(tag, tag),
            relnum)

    return version

def is_release():
    """Return whether this is a released version.

    Returns:
        bool:
        ``True`` if this is a released version of the package.
        ``False`` if it is a development version.
    """
    return VERSION[-1]

__version_info__ = VERSION[:-1]
__version__ = get_package_version()


import subprocess

from cros.factory.probe.lib import cached_probe_function
from cros.factory.utils import process_utils

class DetachableBaseFunction(cached_probe_function.CachedProbeFunction):
  """Probe the detachable base information."""

  PROGRAM = 'hammer_info.py'
  FIELDS = [
      'ro_version',
      'rw_version',
      'wp_screw',
      'wp_all',
      'touchpad_id',
      'touchpad_pid',
      'touchpad_fw_version',
      'touchpad_fw_checksum',
      'key_version',
      'challenge_status']

  def GetCategoryFromArgs(self):
    return None

  @classmethod
  def ProbeAllDevices(cls):
    try:
      ret = {}
      for field in cls.FIELDS:
        ret[field] = process_utils.CheckOutput('%s %s' % (cls.PROGRAM, field),
                                               shell=True, log=True).strip()
      return [ret]

    except subprocess.CalledProcessError:
      return []


import cv2
import mediapipe as mp
import time

# to check frame rate
time.sleep(20)
cap = cv2.VideoCapture(0)

mpHands = mp.solutions.hands
hands = mpHands.Hands()  # parameters already difined
mpDrawLine = mp.solutions.drawing_utils  # to draw multiple lines
prevTime = 0
currTime = 0

while True:
    success, img = cap.read()
    imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    results = hands.process(imgRGB)  # processing rgb IMG
    # print(results.multi_hand_landmarks)

    # to check if we have multiple hand
    if results.multi_hand_landmarks:
        for handlms in results.multi_hand_landmarks:
            for id, lm in enumerate(handlms.landmark):
                # print(id,lm)
                # c-> channels of img
                height, width, c = img.shape
                # position of centre
                cx, cy = int(lm.x * width), int(lm.y * height)
                print(id, cx, cy)

                if id == 4:  # circle for id 1
                    cv2.circle(img, (cx, cy), 15, (255, 0, 255), cv2.FILLED)

            mpDrawLine.draw_landmarks(img, handlms, mpHands.HAND_CONNECTIONS)  # for single hand
            # mpHands.HAND_CONNECTIONS: for connection with dots

    # frame rate
    currTime = time.time()
    fps = 1 / (currTime - prevTime)
    prevTime = currTime
    # display on screen
    cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3,
                (255, 0, 255), 3)
    # 3->thickness, (255,0,255)->color,
    # to capture img
    cv2.imshow("Image", img)
    cv2.waitKey(1)


from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from ui.mindmap import MainScreen
from kivy.properties import BooleanProperty, ObjectProperty, StringProperty, OptionProperty, ListProperty, NumericProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.button import Button

from ui.node import Node
from ui.drawingplane import DrawingPlane
from ui.hoverablebutton import HoverableToggleButton, HoverableButton
from ui.modifyplanepopup import AddNewPlanePopup, EditPlanePopup, DeleteNodePopup, DeletePlanePopup

from kivy.lang import Builder

Builder.load_file('ui/kv/sidebar.kv')

class SideBar(BoxLayout):
    mainScreen: MainScreen = ObjectProperty()

    is_opened: bool = BooleanProperty(False)
    background_color: list[float, float, float] = ListProperty([.4, .4, .5, 1])

    def open_sideBar(self) -> None:
        self.is_opened = True

    def close_sideBar(self) -> None:
        self.is_opened = False

    def toggle_sideBar(self) -> None:
        self.is_opened = not self.is_opened

def string_contains_phrase(string: str, phrase: str) -> bool:
    string: str = string.lower()
    phrase: str = phrase.lower()
    return phrase in string

class NodeListSideBar(SideBar):
    nodes: list[Node] = ListProperty([])
    nodeList: BoxLayout = ObjectProperty(None)
    filterField: TextInput = ObjectProperty(None)
    currentFilter: str = StringProperty("")

    def update_nodes(self, nodes: list[Node]) -> None:
        self.nodes = nodes
        self.update_nodeList()

    def handle_filter(self) -> None:
        self.currentFilter = self.filterField.text
        self.update_nodeList()

    def update_nodeList(self) -> None:
        for node in self.nodes:
            node.bind(name=self.update_when_node_changed)
        if self.currentFilter == None or self.currentFilter == "":
            self.nodeList.clear_widgets()
            for node in self.nodes:
                self.nodeList.add_widget(NodeItem(self, node))
        else:
            phrase: str = self.currentFilter
            self.nodeList.clear_widgets()
            for node in self.nodes:
                if string_contains_phrase(node.name, phrase):
                    self.nodeList.add_widget(NodeItem(self, node))

    def update_when_node_changed(self, node: Node, name: str) -> None:
        self.update_nodeList()

class NodeItem(HoverableToggleButton):
    node: Node = ObjectProperty()
    nodeName: str = StringProperty()
    sideBar: NodeListSideBar = ObjectProperty()

    def __init__(self, sideBar: NodeListSideBar, node: Node, **kwargs) -> None:
        super().__init__(**kwargs)
        self.node = node
        self.nodeName = self.node.name
        self.sideBar = sideBar
        self.node.bind(state=self.set_state)

    def on_mouseover(self, window, pos) -> None:
        pass

    def set_state(self, node: Node, state: str) -> None:
        self.state = state

    def select_node(self) -> None:
        self.node.switch_state()

    def reset_highlight(self) -> None:
        self.button_color = self.default_color

    def pressed_highlight(self) -> None:
        self.button_color = self.highlight_color

class PlaneListSideBar(SideBar):
    mainScreen = ObjectProperty(None)
    addPlaneButton: Button = ObjectProperty(None)

    planes: list[DrawingPlane] = ListProperty([])
    planeList: BoxLayout = ObjectProperty()
    filterField: TextInput = ObjectProperty(None)
    currentFilter: str = StringProperty("")

    def update_planes(self, planes: list[DrawingPlane]) -> None:
        self.planes = planes
        self.update_planeList()

    def handle_filter(self) -> None:
        self.currentFilter = self.filterField.text
        self.update_planeList()

    def update_planeList(self) -> None:
        for plane in self.planes:
            plane.bind(name=self.update_when_plane_changed)
            plane.bind(nodeList=self.update_when_plane_changed)
        if self.currentFilter == None or self.currentFilter == "":
            self.planeList.clear_widgets()
            for plane in self.planes:
                self.planeList.add_widget(PlaneItem(self.mainScreen, plane))
        else:
            phrase: str = self.currentFilter
            self.planeList.clear_widgets()
            for plane in self.planes:
                if string_contains_phrase(plane.name, phrase):
                    self.planeList.add_widget(PlaneItem(self.mainScreen, plane))

    def handle_addNewPlane(self) -> None:
        addNewPlanePopup: AddNewPlanePopup = AddNewPlanePopup(self.mainScreen)
        addNewPlanePopup.open()

    def update_when_plane_changed(self, plane: DrawingPlane, name: str) -> None:
        self.update_planeList()

class PlaneItem(RelativeLayout):
    mainScreen: MainScreen = ObjectProperty()

    planeItemButton: PlaneItemButton = ObjectProperty()
    plane: DrawingPlane = ObjectProperty()
    planeName: str = StringProperty()
    nodeCount: int = NumericProperty()
    isCurrentPlane: bool = BooleanProperty()

    def __init__(self, mainScreen: MainScreen, plane: DrawingPlane, **kwargs) -> None:
        super().__init__(**kwargs)
        self.plane = plane
        self.planeName = self.plane.name
        self.mainScreen = mainScreen
        self.nodeCount = len(self.plane.nodeList)
        plane.set_myButtonOnPlaneList(self)
        self.change_highligt(plane.isCurrentPlane)

    def handle_edit(self) -> None:
        editlanePopup: EditPlanePopup = EditPlanePopup(self.mainScreen, self.plane)
        editlanePopup.open()

    def handle_delete(self) -> None:
        if self.isCurrentPlane:
            return
        DeletePlanePopup(self.plane, self.mainScreen)

    def change_highligt(self, isCurrentPlane) -> None:
        self.isCurrentPlane = isCurrentPlane
        if isCurrentPlane:
            self.planeItemButton.button_color = self.planeItemButton.highlight_color
        else:
            self.planeItemButton.button_color = self.planeItemButton.default_color

class PlaneItemButton(Button):
    mainScreen: MainScreen = ObjectProperty()
    plane: DrawingPlane = ObjectProperty()
    sideBar: PlaneListSideBar = ObjectProperty()
    button_color: tuple[float, float, float, float]

    def select_plane(self) -> None:
        self.mainScreen.planePackage.set_topPlane(self.plane)
        self.mainScreen.drawRegion.display_topPlane()

class RightSideBar(SideBar):
    nameField: PropertyTextInput = ObjectProperty(None)
    descriptionField: PropertyTextInput = ObjectProperty(None)

    currentSelectedNode: Node = ObjectProperty(None, allownone = True)

    def set_node_to_edit(self, node: Node) -> None:
        self.do_stuff_before_swapping()
        self.currentSelectedNode = node
        self.display_node_properties()

    def display_node_properties(self) -> None:
        if self.currentSelectedNode != None:
            self.set_fields(self.currentSelectedNode)
        else:
            self.clear_fields()

    def set_field(self, field: str, value: str) -> None:
        if hasattr(self, field):
            textField: PropertyTextInput = getattr(self, field)
            textField.text = value

    def set_fields(self, node: Node) -> None:
        self.set_field("nameField", str(node.name))
        self.set_field("descriptionField", str(node.shortDescription))

    def clear_fields(self) -> None:
        self.set_field("nameField", "")
        self.set_field("descriptionField", "")

    def delete_current_node(self) -> None:
        if self.currentSelectedNode != None:
            DeleteNodePopup(self.currentSelectedNode)

    def do_stuff_before_swapping(self) -> None:
        self.nameField.focus = False
        self.descriptionField.focus = False

class PropertyTextInput(TextInput):
    sideBar: sideBar = ObjectProperty(None)

    def on_focus(self, what, value) -> None:
        if value == False:
            print(self.property, self.sideBar.currentSelectedNode)
            setattr(self.sideBar.currentSelectedNode, self.property, self.text)


import os, pickle

class Recipe:
    def __init__(self, name, ingredients):
        self.name = name
        self.ingredients = ingredients

    def print_recipe(self):
        print(self.name)
        for i in self.ingredients:
            print(f' - {" ".join(["".join(str(j)) for j in i])}')

# with open("recipes.dat") as reader:
#     recipebook = reader.read()

def recipe_names(list):
    for i, recipe in enumerate(list):
        print(f"{i+1}. {recipe.name}")

def add(recipe_list):
    # global recipe_list
    name = input("Recipe name: ")
    ingredients = []
    while True:
        ingredient = []
        ingr = input("Ingredient: ")
        print("Please enter values as a decimal.")
        qty = float(input("Quantity: "))
        unit = input("Unit: ")
        ingredient.append(qty)
        ingredient.append(unit)
        ingredient.append(ingr)
        ingredients.append(ingredient)
        exit = input("Add another ingredient? (yes/no): ")
        if exit == "no":
            break
        else:
            continue
    new_recipe = Recipe(name, ingredients)
    recipe_list.append(new_recipe)

def view_recipe(recipe, recipe_list):
    if recipe.isdigit():
        recipe = int(recipe)
    if isinstance(recipe, int):
        if recipe > len(recipe_list):
            print("Recipe not found.")
        else:
            recipe_list[recipe - 1].print_recipe()
    elif isinstance(recipe, str):
        for i in recipe_list:
            if recipe.lower() == i.name.lower():
                i.print_recipe()
                break
        else:
            print("Recipe not found.")

def ingredient_search(ingredient, recipe_list):
    count = 0
    for recipe in recipe_list:
        # found = False
        for index, ingr in enumerate(recipe.ingredients):
            if ingredient.lower() in recipe.ingredients[index][2].lower():
                # found = True
                count += 1
                print(recipe.name)
                break
    if count == 0:
        print("Ingredient not found.")

def increase_recipe(recipe, recipe_list):
    multiply = int(input("How many times do you want to increase the recipe? "))
    increased_recipe = recipe
    for index, ingredient in enumerate(increased_recipe.ingredients):
        increased_recipe.ingredients[index][0] = multiply * increased_recipe.ingredients[index][0]
    increased_recipe.print_recipe()

def menu():
    recipe_list = initialize()
    while True:
        os.system("clear")
        print("Recipe Book Menu Options")
        print("""
        1. View Recipe List
        2. Add Recipe
        3. View a Recipe
        4. Search by Ingredient
        5. Increase Recipe Quantity
        6. Exit
              """)
        while True:
            try:
                option = int(input("Make a selection: "))
                break
            except ValueError:
                print()
                print("Please enter the integer value for the menu item you want to select")
                print()

        if option == 1:
            recipe_names(recipe_list)
            print()
            print("Press 'enter' to continue")
            input()
        elif option == 2:
            add(recipe_list, recipe_list)
        elif option == 3:
            recipe_names(recipe_list)
            print()
            recipe = input("Which recipe do you want to see? ")
            view_recipe(recipe, recipe_list)
            print()
            print("Press 'enter' to continue")
            input()
        elif option == 4:
            ingredient = input("Which ingredient do you want to find? ")
            ingredient_search(ingredient, recipe_list)
            print()
            print("Press 'enter' to continue")
            input()
        elif option == 5:
            recipe_names(recipe_list)
            print()
            recipe = int(input("Which recipe number do you want to multiply? "))
            recipe = recipe_list[recipe - 1]
            increase_recipe(recipe, recipe_list)
            print()
            print("Press 'enter' to continue")
            input()
        elif option == 6:
            with open("recipes.dat", "wb") as f:
                pickle.dump(recipe_list, f)
            break
        else:
            print("That is not a valid menu option.")
            print()
            print("Press 'enter' to continue")
            input()

# recipe_1 = Recipe(
#     "PB&J",
#     [[2, "slices", "bread"], [4, "tablespoons", "smooth peanut butter"],
#      [2, "tablespoons", "strawberry jelly"]])

# recipe_2 = Recipe("Ramen Noodles",
#                   [[1, "package", "instant noodles"],
#                    [1, "packet", "seasoning"], [2, "cups", "water"]])

# recipe_3 = Recipe("Macaroni and cheese",
#                   [[1, "cup", "macaroni"],
#                    [2, "cups", "water"], [1, "cup", "shredded cheese"]])

# recipe_list = [recipe_1, recipe_2, recipe_3]

# dump = (recipe_list, get_file)

"""
0. Remove lines 13-14
1. Open the recipes.dat file and pickle.dump the list into it
2. Comment out/delete the code once we have our list data in the recipes.dat file
"""
# with open("recipes.dat", "wb") as f:
#     pickle.dump(recipe_list, f)

"""
3. Comment out/delete all of the code we used to setup our recipes
"""

"""
4. Create the initialize function below and add the function call inside the menu function and save it to recipe_list
"""
def initialize():
    with open("recipes.dat", "rb") as f:
        recipe_list = pickle.load(f)
    return recipe_list

"""
5. Modify the add function and pass recipe_list as a parameter to all the functions that need it; remove the global recipe_list
"""

"""
6. Fix search by ingredient function; change found = False to a count = 0
"""

"""
7. Add the pickle.dump code in the Exit option before exiting the program to save the recipe data
"""


import os
import torch
import time
import deepspeed
import argparse
from transformers import pipeline

parser = argparse.ArgumentParser()
parser.add_argument("--model", "-m", type=str, help="hf model name")
parser.add_argument("--deepspeed", action="store_true", help="use deepspeed inference")
parser.add_argument("--dtype",
                    type=str,
                    default="fp16",
                    choices=["fp16",
                             "fp32",
                             "int8"],
                    help="int8, fp16, or fp32")
parser.add_argument("--graphs", action="store_true", help="CUDA Graphs on")
parser.add_argument("--kernel-inject", action="store_true", help="inject kernels on")
parser.add_argument("--max-tokens", type=int, default=50, help="max new tokens")
parser.add_argument("--local_rank",
                    type=int,
                    default=int(os.getenv("LOCAL_RANK",
                                          "0")),
                    help="local rank")
parser.add_argument("--world_size",
                    type=int,
                    default=int(os.getenv("WORLD_SIZE",
                                          "1")),
                    help="world size")
parser.add_argument("--trials", type=int, default=30, help="number of trials")
args = parser.parse_args()

def print_latency(latency_set, title, warmup=3):
    # trim warmup queries
    latency_set = list(latency_set)
    latency_set = latency_set[warmup:]
    count = len(latency_set)
    if count > 0:
        latency_set.sort()
        n50 = (count - 1) * 0.5 + 1
        n90 = (count - 1) * 0.9 + 1
        n95 = (count - 1) * 0.95 + 1
        n99 = (count - 1) * 0.99 + 1
        n999 = (count - 1) * 0.999 + 1

        avg = sum(latency_set) / count
        p50 = latency_set[int(n50) - 1]
        p90 = latency_set[int(n90) - 1]
        p95 = latency_set[int(n95) - 1]
        p99 = latency_set[int(n99) - 1]
        p999 = latency_set[int(n999) - 1]

        print(f"====== latency stats {title} ======")
        print("\tAvg Latency: {0:8.2f} ms".format(avg * 1000))
        print("\tP50 Latency: {0:8.2f} ms".format(p50 * 1000))
        print("\tP90 Latency: {0:8.2f} ms".format(p90 * 1000))
        print("\tP95 Latency: {0:8.2f} ms".format(p95 * 1000))
        print("\tP99 Latency: {0:8.2f} ms".format(p99 * 1000))
        print("\t999 Latency: {0:8.2f} ms".format(p999 * 1000))

deepspeed.init_distributed("nccl")

if args.local_rank == 0:
    print("BENCHMARK SETTINGS:")
    print(f"\tMODEL: {args.model}")
    print(f"\tMAX_TOKENS: {args.max_tokens}")
    print(f"\tDTYPE: {args.dtype}")
    print(f"\tCUDA_GRAPHS: {args.graphs}")
    print(f"\tKERNEL_INJECT: {args.kernel_inject}")

if args.dtype == "int8":
    dtype = torch.int8
elif args.dtype == "fp16":
    dtype = torch.float16
else:
    dtype = torch.float32

pipe = pipeline("text-generation",
                model=args.model,
                framework="pt",
                device=args.local_rank)

if dtype == torch.float16:
    pipe.model.half()

if args.deepspeed:
    pipe.model = deepspeed.init_inference(
        pipe.model,
        dtype=dtype,
        mp_size=args.world_size,
        replace_with_kernel_inject=args.kernel_inject,
        replace_method="auto",
        enable_cuda_graph=args.graphs,
    )
    pipe.model.profile_model_time()

responses = []
times = []
mtimes = []
for i in range(args.trials):
    torch.cuda.synchronize()
    start = time.time()
    r = pipe("DeepSpeed is", do_sample=False, max_new_tokens=args.max_tokens)
    torch.cuda.synchronize()
    end = time.time()
    responses.append(r)
    times.append(end - start)  # / (args.max_tokens - 3))
    mtimes.append(sum(pipe.model.model_times()))

if args.local_rank == 0:
    print_latency(times, "(e2e) latency")
    print_latency(mtimes, "(model-only) latency")
    print_latency(map(lambda t: t / (args.max_tokens - 3),
                      times),
                  "(e2e) per token latency")
    print(f"RESPONSE 0:")
    print("-" * 30)
    print(responses[0][0]["generated_text"])
    print("-" * 30)


import torch
import torch.nn as nn

import torch.nn.functional as F

class FeatureScorer(nn.Module):
    def __init__(self, args, features=None):
        super(FeatureScorer, self).__init__()
        self.args = args
        self.features = features
        if "without_feature" not in args.keys():
            args.without_feature = False
        self.use_feature = ((not args.without_feature)
                            and (features is not None))

        if self.use_feature:
            self.word_feature_weight = nn.Embedding(self.args.n_word_features,
                                                    self.args.n_labels)
            self.unigram_feature_weight = nn.Embedding(
                self.args.n_unigram_features, self.args.n_labels)
            self.bigram_feature_weight = nn.Embedding(
                self.args.n_bigram_features, self.args.n_labels)
            self.trigram_feature_weight = nn.Embedding(
                self.args.n_trigram_features, self.args.n_labels)
            self.morphology_feature_weight = nn.Parameter(
                torch.ones(3, self.args.n_labels))
        else:
            self.word_feature_weight = nn.Embedding(self.args.n_words,
                                                    self.args.n_labels)

    def extra_repr(self):
        s = f"use_feature={self.use_feature}, "
        if self.use_feature:
            s += "\n(morphology_feature_weight): "
            s += f"{self.morphology_feature_weight.__class__.__name__}("
            s += f"{', '.join(map(str, self.morphology_feature_weight.shape))})"
        return s

    def forward(self, words):
        """

        Args:
            words (torch.Tensor): [batch_size, seq_len]

        Returns:

        """
        if self.use_feature:
            word_features, unigram_features, bigram_features, trigram_features, morphology_features = self.features
            word_scores = self.word_feature_weight(word_features)
            unigram_scores = self.unigram_feature_weight(unigram_features)
            bigram_scores = self.bigram_feature_weight(bigram_features)
            trigram_scores = self.trigram_feature_weight(trigram_features)
            morphology_scores = morphology_features.float(
            ) @ self.morphology_feature_weight
            # [n_words, n_labels]
            scores = word_scores + unigram_scores + bigram_scores + trigram_scores + morphology_scores
        else:
            scores = self.word_feature_weight.weight

        emits = F.embedding(words, torch.log_softmax(scores, dim=0))

        return emits


from app.models.order import order_database
from flask import jsonify, request
from flask_jwt_extended import *
import json, datetime

mysqldb_order = order_database()

@jwt_required()
def createOrderController(**params):
    print("p")
    order = {
        "order_id":params["order_id"],
        "created_at":datetime.date.today(),
        "customer_name":params["customer_name"],
        "admin_id":params["admin_id"],
    }
    print(order)
    mysqldb_order.createOrder(**order)
    mysqldb_order.dataCommit()
    for beverage in params["beverage"]:
        data = {
            "order_id":order["order_id"],
            "beverage_id":beverage["beverage_id"],
            "qty":beverage["qty"],
        }
        print(data)
        mysqldb_order.createOrderDetail(**data)
        mysqldb_order.dataCommit()

    return jsonify({"message":"Success"})

@jwt_required()
def viewOrderController():
    dbresult = mysqldb_order.viewOrder()
    result = []
    for items in dbresult:
        order = {
            "order_id": items[0],
            "created_at": items[1],
            "customer_name": items[2],
            "total": items[4]
        }
        result.append(order)

    return jsonify(result)

@jwt_required()
def viewOrderByDateController(**params):
    dbresult = mysqldb_order.viewOrderByDate(**params)
    result = []
    for items in dbresult:
        order = {
            "order_id": items[0],
            "created_at": items[1],
            "customer_name": items[2],
            "total": items[4]
        }
        result.append(order)

    return jsonify(result)

@jwt_required()
def deleteOrderController(**params):
    mysqldb_order.deleteOrder(**params)
    mysqldb_order.dataCommit()
    return jsonify({"message":"Success"})