"""
module for making curve controls

TODO: fix set_shape to orient correctly - fix cycles
"""

import pymel.core as pm
import journey.lib.utils.tools as tools
import journey.lib.utils.shapes as shapes
import journey.lib.utils.color as color
from maya.cmds import DeleteHistory
reload(tools)
reload(shapes)

class Control:
    control_list = []

    def __init__(self,
                 prefix='new',
                 scale=1.0,
                 trans_to='',
                 rot_to='',
                 rot_shape=True,
                 parent='',
                 shape='circle',
                 channels=['s', 'v']):
        """Short text

        Desc

        Args:
            prefix (str): name for the controller
            scale (float, int): initial scale of the controller
            trans_to (str): object to translate the controller to
            rot_to (str): object to rotate the controller to
            rot_shape (bool): whether the controller shape should match the top transform node translation
            parent (str): object to parent the controller under
            shape (str): visual shape to give the controller. Usable names can be found under journey.lib.utils.shapes
        """
        Control.control_list.append(self)

        self.ctrl_object = None
        self.ctrl_offset = None
        self.prefix = prefix
        self.scale = scale
        self.trans_to = trans_to
        self.rot_to = rot_to
        self.rot_shape = rot_shape
        self.parent = parent
        self.shape = shape
        self.channels = channels

    def set_shape(self, shape):
        if self.get_ctrl():
            exec ("return_shape = shapes.{0}(self.scale, self.prefix + '1_ctrl')".format(shape))
            pm.delete(pm.parentConstraint(self.get_ctrl(), return_shape))
            for shape in pm.PyNode(self.get_ctrl()).getShapes():
                pm.delete(shape)
            for shape in pm.PyNode(return_shape).getShapes():
                pm.parent(shape, self.get_ctrl(), s=True, r=True)
            pm.delete(return_shape)
            self.set_color()
            self.set_rotation()
        else:
            # exec("return_shape = shapes.{0}({1}, {2})".format(self.shape, self.scale, self.prefix + '_ctrl'))
            exec("return_shape = shapes.{0}(self.scale, self.prefix + '_ctrl')".format(shape))
            self.ctrl_object = return_shape

        return self.ctrl_object

    def get_shapes(self):
        return pm.PyNode(self.get_ctrl()).getShapes()

    def set_parent(self):
        pass

    def set_color(self, ctrl_color=''):
        ctrl_color = ctrl_color.upper()
        [pm.setAttr(s + '.ove', 1) for s in self.ctrl_object.getShapes()]

        if self.prefix.startswith('l_'):
            [pm.setAttr(s + '.ovc', color.BLUE) for s in self.ctrl_object.getShapes()]
        elif self.prefix.startswith('r_'):
            [pm.setAttr(s + '.ovc', color.RED) for s in self.ctrl_object.getShapes()]
        else:
            [pm.setAttr(s + '.ovc', color.YELLOW) for s in self.ctrl_object.getShapes()]

        if ctrl_color:
            exec('clr_key = color.{0}'.format(ctrl_color))
            [pm.setAttr(s + '.ovc', clr_key) for s in self.ctrl_object.getShapes()]

    def set_channels(self, channels):
        attr = tools.lock_channels(self.ctrl_object, channels)
        return attr

    def set_translation(self, *args):
        # translate control
        if pm.objExists(self.trans_to):
            pm.delete(pm.pointConstraint(self.trans_to, self.ctrl_offset))

    def set_rotation(self, *args):
        # rotate control
        if pm.objExists(self.rot_to):
            if not self.rot_shape:
                pm.cycleCheck(e=0)
                ctrl_shapes = self.ctrl_object.getShapes()
                loc = pm.spaceLocator()
                for shape in ctrl_shapes:
                    pm.parent(shape, loc, relative=1, shape=1)
                pm.delete(pm.orientConstraint(self.rot_to, self.ctrl_offset))
                pm.parent(loc, self.rot_to)
                pm.setAttr(loc + ".tx", 0)
                pm.setAttr(loc + ".ty", 0)
                pm.setAttr(loc + ".tz", 0)
                pm.makeIdentity(loc, apply=True, r=True, t=True)
                for shape in ctrl_shapes:
                    pm.parent(shape, self.ctrl_object, relative=1, shape=1)
                pm.delete(loc)
                pm.cycleCheck(e=1)
            else:
                pm.delete(pm.orientConstraint(self.rot_to, self.ctrl_offset))

    def create(self):
        # set controller shape
        self.set_shape(self.shape)

        # set offset group for controller and re-parent
        self.ctrl_offset = pm.group(n=self.prefix + '_offset_grp', em=1)
        pm.parent(self.ctrl_object, self.ctrl_offset)

        # parent offset group to parent if set
        if pm.objExists(self.parent):
            pm.parent(self.ctrl_offset, self.parent)

        self.set_color()
        self.set_translation()
        self.set_rotation()

        self.set_channels(self.channels)

        return self

    def movable_pivot(self, *args):
        piv_ctrl = pm.spaceLocator(n=self.prefix + '_piv_ctrl')

        pm.scale(self.scale, self.scale, self.scale,)
        pm.makeIdentity(piv_ctrl, apply=True, t=1, r=1, s=1, n=0)
        DeleteHistory(piv_ctrl)

        pm.delete(pm.parentConstraint(self.get_ctrl(), piv_ctrl))
        pm.parent(piv_ctrl, self.get_ctrl())

        tools.lock_channels(piv_ctrl, channels=['r', 's'])

        pm.addAttr(self.get_ctrl(), longName='MOVABLEPIVOT', nn='HAS MOVABLE PIVOT',
                   at="enum", en='=======')
        pm.setAttr(self.get_ctrl() + '.MOVABLEPIVOT', e=True, channelBox=True)

        pm.connectAttr(piv_ctrl + '.t', self.get_ctrl() + '.rotatePivot')
        pm.connectAttr(piv_ctrl + '.t', self.get_ctrl() + '.scalePivot')

    def set_pivot(self, node):
        get_piv = pm.xform(node, piv=True, q=True, ws=True)
        pm.xform(self.get_ctrl(), ws=True, piv=(get_piv[0], get_piv[1], get_piv[2]))
        pm.xform(self.get_offset(), ws=True, piv=(get_piv[0], get_piv[1], get_piv[2]))

    def set_shape_scale(self, scale):
        """Multiplies current scale value
        """
        scale = tools.convert_scale(scale)
        for shape in self.get_shapes():
            pm.scale(pm.select(shape + '.cv[:]'), scale[0], scale[1], scale[2], relative=True)

    def set_constraint(self, driven, mo=True, channels=['t', 'r', 's']):
        tools.matrix_constraint(self.get_ctrl(), driven, mo=mo, channels=channels)

    def freeze_transforms(self, channels=['s']):
        tools.unlock_channels(self.get_offset(), channels=channels)
        tools.unlock_channels(self.get_ctrl(), channels=channels)
        pm.makeIdentity(self.get_offset(), apply=True)
        DeleteHistory()
        tools.lock_channels(self.get_offset(), channels=channels)
        tools.lock_channels(self.get_ctrl(), channels=channels)

    def get_ctrl(self, *args):
        return self.ctrl_object

    def get_offset(self, *args):
        return self.ctrl_offset


import tensorflow as tf

class AttentionLayer:
    def __init__(self, name, enc_size, dec_size, hid_size, activ=tf.tanh):
        self.name = name
        self.enc_size = enc_size
        self.dec_size = dec_size
        self.hid_size = hid_size
        self.activ = activ
        with tf.variable_scope(name):
            self.dec = tf.get_variable('att_dec', shape=[dec_size, hid_size])
            self.enc = tf.get_variable('att_enc', shape=[enc_size, hid_size])
            self.vec = tf.get_variable('att_vec', shape=[hid_size, 1])[:, 0]

    def __call__(self, enc, dec, inp_mask):
        with tf.variable_scope(self.name):
            enc_prod = tf.einsum('aij,jk->aik', enc, self.enc)
            dec_prod = tf.matmul(dec, self.dec)
            scores = tf.einsum('aij,j->ai',
                               self.activ(tf.einsum('aij,aj->aij', enc_prod, dec_prod)), self.vec)
            scores = tf.exp(scores)
            scores = scores * tf.to_float(inp_mask)
            probs = tf.einsum('ai,a->ai', scores, 1 / tf.reduce_sum(scores, 1)) + 1e-150
            attn = tf.einsum('aij,ai->aj', enc, probs)

            return attn, probs


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

class BinaryTree():
  def __init__(self): #make tree
    self.root = None
  #preorder
  def preorder(self,n,cnt):
    if n=='A':
      cnt= 0

    if n !=None:
      print('-'*cnt,end = "")
      print(n.data)
      if n.left:
        cnt += 1
        self.preorder(n.left,cnt)
      if n.left != None:
        if n.right:
          cnt += 1
          self.preorder(n.right,cnt-1)
      if n.left == None:
        if n.right:
          cnt+=1
          self.preorder(n.right,cnt)
tree = BinaryTree()
n1 = Node('A')
n2 = Node('B')
n3 = Node('C')
n4 = Node('D')
n5 = Node('E')
n6 = Node('F')
n7 = Node('G')
n8 = Node('H')
n9 = Node('I')

tree.root = n1
n1.left = n2
n1.right = n7
n2.left = n3
n2.right = n4
n4.left = n5
n4.right = n6
n7.right = n8
n8.right = n9

print("preorder : ")
tree.preorder(tree.root,0)


import logging
import os

from pyramid.i18n import get_localizer, TranslationStringFactory
from pyramid.events import subscriber, BeforeRender, NewRequest
from pyramid_formalchemy.events import subscriber as fa_subscriber, \
        IAfterSyncEvent, IBeforeDeleteEvent

from pygall.models import Photo
from pygall.lib.imageprocessing import ip, get_info, ORIG

log = logging.getLogger(__name__)

@subscriber(BeforeRender)
def add_renderer_globals(event):
    request = event.get('request')
    if request:
        event['_'] = request.translate
        event['localizer'] = request.localizer

tsf = TranslationStringFactory('PyGall')

@subscriber(NewRequest)
def save_locale(event):
    locale = event.request.params.get('_LOCALE_', None)
    if locale:
        event.request.response.set_cookie('_LOCALE_', locale)

@subscriber(NewRequest)
def add_localizer(event):
    request = event.request
    localizer = get_localizer(request)
    def auto_translate(string):
        return localizer.translate(tsf(string))
    request.localizer = localizer
    request.translate = auto_translate

@fa_subscriber([Photo, IAfterSyncEvent])
def after_photo_sync(context, event):
    if context.time and context.md5sum:
        return
    uri = context.uri
    info = get_info(os.path.join(
        event.request.registry.settings['photos_dir'], ORIG, uri))
    if not context.time:
        context.time = info['date']
        log.debug("context.time = %s" % info['date'])
    if not context.md5sum:
        context.md5sum = info['md5sum']
        log.debug("context.md5sum = %s" % info['md5sum'])

@fa_subscriber([Photo, IBeforeDeleteEvent])
def before_photo_delete(context, event):
    ip.remove_image(context.uri)
    log.debug('ip.remove_image(%s)' % context.uri)


# Junk File Organizer
# Python Project To Sort Files

import os, shutil

print("Welcome To Junk File Organizer")
print("Program By - Pijush Konar")
print("--OPTIONS--")
print("Enter 1 For File Type Sorting")
print("Enter 2 For File Size Sorting")
typeofsort = input("Enter Sorting Method: ")
folderpath = input('Enter Your Folder Path To Sort The Files: ')

# To Sort According To Size

file_extensions={
       'Audio':('.mp3','.wav','.flac', '.m4a', '.aac'),
       'Video':('.mp4','.mkv','.MKV','.flv','.mpeg'),
       'Images':('.jpeg', '.jpg', '.tiff', '.gif', '.png'),
       'Docs':('.doc','.pdf','.txt','.docx','.xls', '.xlsx', '.ppt', '.pptx', '.xps'),
       'Archives':('.zip', '.7z', '.rar'),
       'Others':('.exe', '.apk', '.bat', '.bin'),
       'Programming':('.py', '.htm', '.html', '.html5', '.css', '.php', '.js')
}
new_path={
    "Organized":('Audio','Video','Images','Docs','Archives','Others','Programming')
}

if typeofsort=="1":
    def file_finder(folderpath,file_extensions):
        files=[]
        for file in os.listdir(folderpath):
            for extension in file_extensions:
                if file.endswith(extension):
                    files.append(file)
        return files

    for extensions_type,extension_tuple in file_extensions.items():
        folder_name=extensions_type.split('_')[0]
        folder_path=os.path.join(folderpath,folder_name)
        os.mkdir(folder_path)
        for item in (file_finder(folderpath,extension_tuple)):
            item_path=os.path.join(folderpath,item)
            item_new_path=os.path.join(folder_path,item)
            shutil.move(item_path,item_new_path)

    for extensions_type,extension_tuple in new_path.items():
        folder_name=extensions_type.split('_')[0]
        folder_path=os.path.join(folderpath,folder_name)
        os.mkdir(folder_path)
        for item in (file_finder(folderpath,extension_tuple)):
            item_path=os.path.join(folderpath,item)
            item_new_path=os.path.join(folder_path,item)
            shutil.move(item_path,item_new_path)
    print("Done Sorting :)")

# To Sort According To Size

if typeofsort=="2":
    def sizecheck(folderpath):
        list_dir=os.walk(folderpath)
        for dir,filename, file in list_dir:
            for f in file:
                sizeoffile=os.stat(dir+"/"+f).st_size
                try:
                    if sizeoffile < 1024:
                        if os.path.exists(folderpath+"/Byte_Files/"):
                            shutil.move(folderpath+"/"+f, folderpath+"/Byte_Files/"+f)
                        else:
                            os.mkdir(folderpath+"/Byte_Files/")
                            shutil.move(folderpath+"/"+f, folderpath+"/Byte_Files/"+f)
                    elif sizeoffile >= 1024 and sizeoffile < 1000*1024:
                        if os.path.exists(folderpath+"/KiloBytes_Files/"):
                            shutil.move(folderpath+"/"+f, folderpath+"/KiloBytes_Files/"+f)
                        else:
                            os.mkdir(folderpath+"/KiloBytes_Files/")
                            shutil.move(folderpath+"/"+f, folderpath+"/KiloBytes_Files/"+f)
                    elif sizeoffile >= 1000*1024 and sizeoffile <= 1000*1024*1024:
                        if os.path.exists(folderpath+"/MegaBytes_Files/"):
                            shutil.move(folderpath+"/"+f, folderpath+"/MegaBytes_Files/"+f)
                        else:
                            os.mkdir(folderpath+"/MegaBytes_Files/")
                            shutil.move(folderpath+"/"+f, folderpath+"/MegaBytes_Files/"+f)
                    else:
                        if os.path.exists(folderpath+"/GigaBytes_Files/"):
                            shutil.move(folderpath+"/"+f, folderpath+"/GigaBytes_Files/"+f)
                        else:
                            os.mkdir(folderpath+"/GigaBytes_Files/")
                            shutil.move(folderpath+"/"+f, folderpath+"/GigaBytes_Files/"+f)
                except FileExistsError:
                    continue
        print("Done Sorting :)")
    sizecheck(folderpath)

# To Sort According To Usage - To Be Added Later

# if typeofsort=="size":
#     def usagecheck(folderpath):
#         list_dir=os.walk(folderpath)
#         for dir,filename, file in list_dir:
#             for f in file:
#                 sizeoffile=os.stat(dir+"/"+f).st_atime
#                 try:

# func_to_call = {'ext':file_finder, 'size':sizecheck }
# func_to_call = {'size':sizecheck }
# func_to_call[typeofsort]()


from random import randint
'''n = 0
computador = randint(0, 10)
jogador = int(input('Digite um número inteiro entre 0 e 10: '))
while jogador != computador:
    print('Tente novamente!')
    jogador = int(input('Digite um número inteiro entre 0 e 10: '))
    n += 1
    print('Você ganhou! o número é: {}, você precisou de {} tentativas'.format(computador, n))
'''
computador = randint(0, 10)
acertou = False
palpites = 0
while not acertou:
    jogador = int(input('numero entre 0  e 10: '))
    palpites += 1
    if jogador == computador:
        acertou = True
    else:
        if jogador< computador:
            print('Mais alto')
        elif jogador > computador:
            print("Mais baixo")
print('Você ganhou! o número é: {}, você precisou de {} tentativas'.format(computador, palpites))


from mycroft import MycroftSkill, intent_handler
import RPi.GPIO as GPIO

GPIO.setup(14,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
GPIO.setup(18,GPIO.OUT)

class LedControl(MycroftSkill):

    def __init__(self):
        MycroftSkill.__init__(self)

    @intent_handler('led_skill.intent')
    def handle_led_skill(self, message):
        self.speak_dialog('led_skill')
        GPIO.output(14,True)
        GPIO.output(15,True)
        GPIO.output(18,True)

def create_skill():
    return LedControl()


import torch
import torch.nn as nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import random

learning_rate = 0.001
training_epochs = 15
batch_size = 100
drop_prob = 0.3

# MNIST dataset
mnist_train = dsets.MNIST(root='MNIST_data/',
                          train=True,
                          transform=transforms.ToTensor(),
                          download=True)

#test 데이터셋.
mnist_test = dsets.MNIST(root='MNIST_data/',
                         train=False,
                         transform=transforms.ToTensor(),
                         download=True)

data_loader = torch.utils.data.DataLoader(dataset=mnist_train,
                                          batch_size=batch_size,
                                          shuffle=True,
                                          drop_last=True)

linear1 = nn.Linear(784, 512, bias=True)
linear2 = nn.Linear(512, 512, bias=True)
linear3 = nn.Linear(512, 512, bias=True)
linear4 = nn.Linear(512, 512, bias=True)
linear5 = nn.Linear(512, 10, bias=True)
relu = nn.ReLU()
dropout = nn.Dropout(p=drop_prob)

nn.init.xavier_uniform_(linear1.weight)
nn.init.xavier_uniform_(linear2.weight)
nn.init.xavier_uniform_(linear3.weight)
nn.init.xavier_uniform_(linear4.weight)
nn.init.xavier_uniform_(linear5.weight)

model = nn.Sequential(linear1, relu, dropout,
                            linear2, relu, dropout,
                            linear3, relu, dropout,
                            linear4, relu, dropout,
                            linear5)

criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

total_batch = len(data_loader)
model.train()
for epoch in range(training_epochs):
    avg_cost = 0

    for X, Y in data_loader:
        X = X.view(100, 28 * 28)
        Y = Y

        optimizer.zero_grad()
        hypothesis = model(X)
        cost = criterion(hypothesis, Y)
        cost.backward()
        optimizer.step()

        avg_cost += cost / total_batch

    print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.9f}'.format(avg_cost))

print('Learning finished')

# Test model and check accuracy
with torch.no_grad():
    model.eval()    # set the model to evaluation mode (dropout=False)

    # Test the model using test sets
    X_test = mnist_test.test_data.view(-1, 28 * 28).float()
    Y_test = mnist_test.test_labels

    prediction = model(X_test)
    correct_prediction = torch.argmax(prediction, 1) == Y_test
    accuracy = correct_prediction.float().mean()
    print('Accuracy:', accuracy.item())

    # Get one and predict
    r = random.randint(0, len(mnist_test) - 1)
    X_single_data = mnist_test.test_data[r:r + 1].view(-1, 28 * 28).float()
    Y_single_data = mnist_test.test_labels[r:r + 1]

    print('Label: ', Y_single_data.item())
    single_prediction = model(X_single_data)
    print('Prediction: ', torch.argmax(single_prediction, 1).item())


# Generating dataset
import pandas as pd
# dictionary words
sf = pd.read_csv("words.txt")
sf["scribble"] = False
sf["label"] = "word"
#scribble words
nsf = pd.read_csv("scibble.txt")
nsf["scribble"] = True
nsf["label"] = "scribble"
word_list = [sf, nsf]
bulk = pd.concat(word_list)
bulk.to_csv("scribble_data.txt")


#User function Template for python3

class Solution:
    def select(self, arr, i):
        # code here
        # select() takes arr[] and starting point of unsorted array i as
        # input parameters and returns the selected element for each iteration
        # in selection sort

        min_index = i

        # find the min element index from the unsorted array
        for j in range(i+1,n):
            if arr[min_index]>arr[j]:
                min_index = j

        return min_index

    def selectionSort(self, arr,n):
        #code here

        # start iteration
        for i in range(n):
            min_index = self.select(arr,i)
            # swap
            arr[i], arr[min_index] = arr[min_index], arr[i]

        return arr

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

if __name__ == '__main__':
    t = int(input())
    for _ in range(t):
        n = int(input())
        arr = list(map(int, input().strip().split()))
        Solution().selectionSort(arr, n)
        for i in range(n):
            print(arr[i],end=" ")
        print()
# } Driver Code Ends


#Used to make UI for the game
import pygame
#Randomly chooses which way the ball will start moving
import random

#frame rate per second
FPS = 60

#size of our window
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600

#size of our paddle
PADDLE_WIDTH = 10
PADDLE_HEIGHT = 60
#distance from the edge of the window
PADDLE_BUFFER = 10

#size of our ball
BALL_WIDTH = 10
BALL_HEIGHT = 10

#speeds of paddle and ball
PADDLE_SPEED = 4
BALL_X_SPEED = 5
BALL_Y_SPEED = 4

#RGB for paddle and ball
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("PingAndPong")

def drawBall(ballXPos, ballYPos):
    ball = pygame.Rect(ballXPos, ballYPos, BALL_WIDTH, BALL_HEIGHT)
    pygame.draw.rect(screen, WHITE, ball)

def drawPaddle1(paddle1YPos):
    paddle1 = pygame.Rect(PADDLE_BUFFER, paddle1YPos, PADDLE_WIDTH, PADDLE_HEIGHT)
    pygame.draw.rect(screen, WHITE, paddle1)

def drawPaddle2(paddle2YPos):
    paddle2 = pygame.Rect(WINDOW_WIDTH - PADDLE_BUFFER - PADDLE_WIDTH, paddle2YPos, PADDLE_WIDTH, PADDLE_HEIGHT)
    pygame.draw.rect(screen, WHITE, paddle2)

def updateBall(paddle1YPos, paddle2YPos, ballXPos, ballYPos, ballXDirection, ballYDirection):

    ballXPos = ballXPos + ballXDirection * BALL_X_SPEED
    ballYPos = ballYPos + ballYDirection * BALL_Y_SPEED
    score = 0

    #checks for a collision, if the ball hits the left side
    if (
                        ballXPos <= PADDLE_BUFFER + PADDLE_WIDTH and ballYPos + BALL_HEIGHT >= paddle1YPos and ballYPos - BALL_HEIGHT <= paddle1YPos + PADDLE_HEIGHT):
        ballXDirection = 1
    elif (ballXPos <= 0):
        ballXDirection = 1
        score = -1
        return [score, paddle1YPos, paddle2YPos, ballXPos, ballYPos, ballXDirection, ballYDirection]

    if (
                        ballXPos >= WINDOW_WIDTH - PADDLE_WIDTH - PADDLE_BUFFER and ballYPos + BALL_HEIGHT >= paddle2YPos and ballYPos - BALL_HEIGHT <= paddle2YPos + PADDLE_HEIGHT):

        ballXDirection = -1

    elif (ballXPos >= WINDOW_WIDTH - BALL_WIDTH):

        ballXDirection = -1
        score = 1
        return [score, paddle1YPos, paddle2YPos, ballXPos, ballYPos, ballXDirection, ballYDirection]

    if (ballYPos <= 0):
        ballYPos = 0;
        ballYDirection = 1;

    elif (ballYPos >= WINDOW_HEIGHT - BALL_HEIGHT):
        ballYPos = WINDOW_HEIGHT - BALL_HEIGHT
        ballYDirection = -1
    return [score, paddle1YPos, paddle2YPos, ballXPos, ballYPos, ballXDirection, ballYDirection]

def updatePaddle1(action, paddle1YPos):

    if (action[1] == 1):
        paddle1YPos = paddle1YPos - PADDLE_SPEED

    if (action[2] == 1):
        paddle1YPos = paddle1YPos + PADDLE_SPEED

    if (paddle1YPos < 0):
        paddle1YPos = 0
    if (paddle1YPos > WINDOW_HEIGHT - PADDLE_HEIGHT):
        paddle1YPos = WINDOW_HEIGHT - PADDLE_HEIGHT
    return paddle1YPos

def updatePaddle2(paddle2YPos, ballYPos):
    if (paddle2YPos + PADDLE_HEIGHT/2 < ballYPos + BALL_HEIGHT/2):
        paddle2YPos = paddle2YPos + PADDLE_SPEED
    if (paddle2YPos + PADDLE_HEIGHT/2 > ballYPos + BALL_HEIGHT/2):
        paddle2YPos = paddle2YPos - PADDLE_SPEED
    if (paddle2YPos < 0):
        paddle2YPos = 0
    if (paddle2YPos > WINDOW_HEIGHT - PADDLE_HEIGHT):
        paddle2YPos = WINDOW_HEIGHT - PADDLE_HEIGHT
    return paddle2YPos

#game class
class PongGame:
    def __init__(self):
        num = random.randint(0,9)
        self.grzesiu = 0
        self.paddle1YPos = WINDOW_HEIGHT / 2 - PADDLE_HEIGHT / 2
        self.paddle2YPos = WINDOW_HEIGHT / 2 - PADDLE_HEIGHT / 2

        self.ballXDirection = 1
        self.ballYDirection = 1

        self.ballXPos = WINDOW_WIDTH/2 - BALL_WIDTH/2

        if(0 < num < 3):
            self.ballXDirection = 1
            self.ballYDirection = 1
        if (3 <= num < 5):
            self.ballXDirection = -1
            self.ballYDirection = 1
        if (5 <= num < 8):
            self.ballXDirection = 1
            self.ballYDirection = -1
        if (8 <= num < 10):
            self.ballXDirection = -1
            self.ballYDirection = -1

        num = random.randint(0,9)

        self.ballYPos = num*(WINDOW_HEIGHT - BALL_HEIGHT)/9

    def getPresentFrame(self):
        pygame.event.pump()
        screen.fill(BLACK)
        drawPaddle1(self.paddle1YPos)
        drawPaddle2(self.paddle2YPos)
        drawBall(self.ballXPos, self.ballYPos)
        image_data = pygame.surfarray.array3d(pygame.display.get_surface())
        pygame.display.flip()
        return image_data

    def getNextFrame(self, action):
        pygame.event.pump()
        score = 0
        screen.fill(BLACK)
        self.paddle1YPos = updatePaddle1(action, self.paddle1YPos)
        drawPaddle1(self.paddle1YPos)
        self.paddle2YPos = updatePaddle2(self.paddle2YPos, self.ballYPos)
        drawPaddle2(self.paddle2YPos)
        [score, self.paddle1YPos, self.paddle2YPos, self.ballXPos, self.ballYPos, self.ballXDirection, self.ballYDirection] = updateBall(self.paddle1YPos, self.paddle2YPos, self.ballXPos, self.ballYPos, self.ballXDirection, self.ballYDirection)
        drawBall(self.ballXPos, self.ballYPos)
        image_data = pygame.surfarray.array3d(pygame.display.get_surface())
        pygame.display.flip()
        self.grzesiu = self.grzesiu + score
        print ("Grzesiu is " + str(self.grzesiu))
        return [score, image_data]


import os
import shutil
from openpyxl import load_workbook
from django.http import HttpResponse, JsonResponse
from .models import *
from win32com import client
from django.template.loader import render_to_string
from django.core.cache import cache

def convert_to_pdf(input_path, output_path):
    excel = client.Dispatch(
        "Excel.Application"
    )  # 利用dispatch連接 microsoft 應用程式  這裡是連接到excel
    doc = excel.Workbooks.Open(input_path)
    doc.SaveAs(output_path, FileFormat=57)  # FileFormat = 57 是 PDF 格式
    doc.Close()
    excel.Quit()

def IDgenerator(year, Max_id, prefix):
    if year == int(Max_id[:4]):
        num = int(Max_id[-4:]) + 1
        ID = f"{year}{prefix}{str(num).zfill(4)}"
    else:
        num = 1
        ID = f"{year}{prefix}{str(num).zfill(4)}"
    return ID

def delete_action(type, id):
    object_data = type.objects.get(id=id)
    print(object_data)

    dest_folder = 'C://Users//user//Desktop//newpath'
    try:
        excel_file_path = os.path.abspath(object_data.excel_file)
        try:
            new_path = os.path.join(dest_folder, os.path.basename(excel_file_path))
            shutil.move(excel_file_path, new_path)
            object_data.excel_file = ""
            object_data.save()
        except:
            return None
    except:
        pass

    try:
        pdf_file_path = os.path.abspath(object_data.pdf_file)
        print(pdf_file_path)
        try:
            new_path = os.path.join(dest_folder, os.path.basename(pdf_file_path))
            shutil.move(pdf_file_path, new_path)
            object_data.pdf_file_path = ""
            object_data.save()
        except:
            return None
    except:
        pass
    object_data.delete()
    cache.delete(f"{type.__name__}:{object_data.id}")
    rest_form = type.objects.all().order_by("-date")
    prefix = str(type.__name__)[:2] + "s"
    prefix_lower = (str(type.__name__)[:2]).lower()
    data = render_to_string(f"back/async/{prefix_lower}list.html", {prefix: rest_form,"pc_type":type})
    print(data)
    return data

def pay_status_change(type, id):
    object_data = type.objects.get(id=id)
    if object_data.pay == False:
        object_data.pay = True
        object_data.save()
        all_form = type.objects.all().order_by("-date")
        prefix = str(type.__name__)[:2]
        prefix = prefix + "s"
        print(prefix)
        prefix_lower = str(type.__name__).lower()
        prefix_lower = prefix_lower[:2]
        print(prefix_lower)
        data = render_to_string(
            f"back/async/{prefix_lower}list.html", {prefix: all_form}
        )
        return data
    else:
        object_data.pay = False
        object_data.save()
        all_form = type.objects.all().order_by("-date")
        prefix = str(type.__name__)[:2]
        prefix = prefix + "s"
        print(prefix)
        prefix_lower = str(type.__name__).lower()
        prefix_lower = prefix_lower[:2]
        data = render_to_string(
            f"back/async/{prefix_lower}list.html", {prefix: all_form}
        )
        return data


import sqlite3
import time
import uuid
import datetime
from typing import Union, List, Tuple

class User(object):
    def __init__(self, chat_id: int, name: str):
        self.id = chat_id
        self.name = name

class Irrigation(object):
    def __init__(self, id, field_id, date, amount):
        self.id = id
        self.field_id = field_id
        self.date = date
        self.amount = amount

class NPK(object):
    def __init__(self, id, field_id, date, npk):
        self.id = id
        self.field_id = field_id
        self.date = date
        self.npk = npk

class Field(object):
    def __init__(
        self,
        id: int,
        name: str,
        creator_id: int,
        latitude: float,
        longitude: float,
        crop_start: datetime.date,
        crop_end: datetime.date,
        crop_name: str,
    ):
        self.id = id
        self.name = name
        self.creator_id = creator_id
        self.latitude = latitude
        self.longitude = longitude
        self.crop_start = crop_start
        self.crop_end = crop_end
        self.crop_name = crop_name

# All async in case we switch to Postgres
class Database(object):
    def __init__(self):
        self._db = sqlite3.connect("/home/db/agrobot.db")
        self._db.row_factory = sqlite3.Row

    async def get_all_users(self) -> List[User]:
        query = """
        SELECT id,
               name
        FROM users
        """
        cursor = self._db.cursor()
        cursor.execute(query)
        rows = cursor.fetchall()
        cursor.close()

        return [User(row["id"], row["name"]) for row in rows]

    async def get_user(self, chat_id) -> Union[User, None]:
        query = """
        SELECT id,
               name
        FROM users
        WHERE id = ?
        """
        args = (chat_id,)
        cursor = self._db.cursor()
        cursor.execute(query, args)
        row = cursor.fetchone()
        cursor.close()

        if row:
            return User(row["id"], row["name"])
        else:
            return None

    async def new_user(self, chat_id: int, name: str) -> User:
        query = """
        INSERT or REPLACE INTO users (id, name)
        VALUES (?, ?)
        """
        args = (chat_id, name)

        cursor = self._db.cursor()
        cursor.execute(query, args)
        self._db.commit()
        cursor.close()

        return User(chat_id, name)

    async def delete_user(self, id):
        query = """
        DELETE
        FROM users
        WHERE id = ?
        """
        args = (id,)
        cursor = self._db.cursor()
        cursor.execute("PRAGMA foreign_keys = ON")
        cursor.execute(query, args)
        self._db.commit()
        cursor.close()

    async def get_user_fields(self, id) -> List[Field]:
        query = """
        SELECT *
        FROM fields
        WHERE creator_id = ?
        """
        args = (id,)
        cursor = self._db.cursor()
        cursor.execute(query, args)
        rows = cursor.fetchall()
        cursor.close()
        return [
            Field(
                row["id"],
                row["name"],
                row["creator_id"],
                row["latitude"],
                row["longitude"],
                row["crop_start"],
                row["crop_end"],
                row["crop_name"],
            )
            for row in rows
        ]

    async def get_user_fields_irrs_npks(self, id):
        all_fields = []
        for field in await self.get_user_fields(id):
            field_irrigations = await self.get_irrigations(field.id)
            field_npks = await self.get_npks(field.id)
            all_fields.append([field, field_irrigations, field_npks])
        return all_fields

    async def get_user_field_dicts(self, id):
        field_dict = {}
        triplets = await self.get_user_fields_irrs_npks(id)
        for field, field_irrigations, field_npks in triplets:
            irrigation_events = []
            irrigation_ammounts = []
            for field_irrigation in field_irrigations:
                irrigation_events.append(field_irrigation.date)
                irrigation_ammounts.append(field_irrigation.amount)

            npk_events = []
            npk = []
            for field_npk in field_npks:
                npk_events.append(field_npk.date)
                npk.append(field_npk.npk)

            field_dict[field.id] = {
                "name": field.name,
                "latitude": field.latitude,
                "longitude": field.longitude,
                "crop_start": field.crop_start,
                "crop_end": field.crop_end,
                "crop_name": field.crop_name,
                "irrigation_events": irrigation_events,
                "irrigation_ammounts": irrigation_ammounts,
                "npk_events": npk_events,
                "npk": npk,
            }
        return field_dict

    async def add_field(
        self,
        id: int,
        name: str,
        creator_id: int,
        latitude: float,
        longitude: float,
        crop_start: datetime.date,
        crop_end: datetime.date,
        crop_name: str,
    ):
        query = """
        INSERT or REPLACE INTO fields(id, name, creator_id, latitude, longitude, crop_start, crop_end, crop_name)
               VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        """
        args = (
            id,
            name,
            creator_id,
            latitude,
            longitude,
            crop_start.strftime("%Y-%m-%d"),
            crop_end.strftime("%Y-%m-%d"),
            crop_name,
        )
        cursor = self._db.cursor()
        cursor.execute(query, args)
        self._db.commit()
        cursor.close()

    async def delete_field(self, id):
        query = """
        DELETE
        FROM fields
        WHERE id = ?
        """
        args = (id,)
        cursor = self._db.cursor()
        cursor.execute("PRAGMA foreign_keys = ON")
        cursor.execute(query, args)
        self._db.commit()
        cursor.close()

    async def get_field(self, id):
        query = """
        SELECT *
        FROM fields
        WHERE id = ?
        """
        args = (id,)
        cursor = self._db.cursor()
        cursor.execute(query, args)
        row = cursor.fetchone()
        cursor.close()
        if row:
            return row
        else:
            return None

    async def get_irrigations(self, field_id) -> List[Field]:
        query = """
        SELECT *
        FROM irrigations
        WHERE field_id = ?
        """
        args = (field_id,)
        cursor = self._db.cursor()
        cursor.execute(query, args)
        rows = cursor.fetchall()
        cursor.close()
        return [
            Irrigation(row["id"], row["field_id"], row["date"], row["amount"])
            for row in rows
        ]

    async def add_irrigation(self, id, field_id, date, amount):
        query = """
        INSERT or REPLACE INTO irrigations(id, field_id, date, amount)
               VALUES (?, ?, ?, ?)
        """
        args = (id, field_id, date.strftime("%Y-%m-%d"), amount)
        cursor = self._db.cursor()
        cursor.execute(query, args)
        self._db.commit()
        cursor.close()

    async def delete_irrigation(self, id: int):
        query = """
        DELETE
        FROM irrigations
        WHERE id = ?
        """
        args = (id,)
        cursor = self._db.cursor()
        cursor.execute(query, args)
        self._db.commit()
        cursor.close()

    async def get_npks(self, id) -> List[NPK]:
        query = """
        SELECT *
        FROM npks
        WHERE field_id = ?
        """
        args = (id,)
        cursor = self._db.cursor()
        cursor.execute(query, args)
        rows = cursor.fetchall()
        cursor.close()
        return [
            NPK(
                row["id"],
                row["field_id"],
                row["date"],
                [float(x) for x in row["npk"].split(" ")],
            )
            for row in rows
        ]

    async def add_npk(self, id, field_id, date, npk):
        query = """
        INSERT or REPLACE INTO npks(id, field_id, date, npk)
               VALUES (?, ?, ?, ?)
        """
        npk_str = " ".join(list(map(str, npk)))  # save as: [50,30,20] -> 50 30 20
        args = (id, field_id, date.strftime("%Y-%m-%d"), npk_str)
        cursor = self._db.cursor()
        cursor.execute(query, args)
        self._db.commit()
        cursor.close()

    async def delete_npk(self, id):
        query = """
        DELETE
        FROM npks
        WHERE id = ?
        """
        args = (id,)
        cursor = self._db.cursor()
        cursor.execute(query, args)
        self._db.commit()
        cursor.close()

    async def add_income(self, id, field_id, income_per_ga):
        query = """
        INSERT or REPLACE INTO income(id, field_id, income_per_ga)
               VALUES (?, ?, ?)
        """
        args = (id, field_id, income_per_ga)
        cursor = self._db.cursor()
        cursor.execute(query, args)
        self._db.commit()
        cursor.close()

    async def get_income(self, id):
        query = """
        SELECT *
        FROM income
        WHERE id = ?
        """
        args = (id,)
        cursor = self._db.cursor()
        cursor.execute(query, args)
        row = cursor.fetchone()
        cursor.close()

        if row:
            return row
        else:
            return None


def extract_participants(sentence: Span):
    participants_base_keywords_synonyms = prepare_base_keywords_synonyms()

    tmp_output = []
    output = []
    for word in sentence:
        if word.dep_ in {"nsubj", "nsubjpass"}:
            participant = Participant(word)
            if word.pos_ == "pron":
                participant.set_pronoun(True)
            tmp_output.append(participant)

    # Check if possible participant is a part of conjunction
    for word in sentence:
        if word.dep_ == "conj":
            for child in word.children:
                if child.dep_ in {"pobj", "dobj", "iobj", "attr"}:
                    participant = Participant(child)
                    if child.pos_ == "pron":
                        participant.set_pronoun(True)
                    tmp_output.append(participant)

    # Check if Participant is an acceptable entity
    for participant in tmp_output:
        participant_text = participant.get_participant_token().text

        insert_flag = False
        # Check whether participant is a pronoun
        if participant.is_pronoun():
            insert_flag = True

        if insert_flag is False:
            # Analyze participant hypernyms, in search for one of base keywords
            insert_flag = analyze_participants_hypernyms(participant_text,
				participants_base_keywords_synonyms)

        if insert_flag is False:
            # Check if participant is one of keywords
            insert_flag = validate_participant_keyword_list(participant_text)
        if insert_flag:
            output.append(participant)

    return output


from contextlib import closing
import pickle
import unittest
import json
import mock
import __builtin__

from docido_sdk.toolbox.file_ext import (
    FileProperties,
    iterator_to_file,
)
from docido_sdk.toolbox.http_ext import delayed_request
from docido_sdk.index.test import CustomJSONEncoder

class TestStreamFromRequest(unittest.TestCase):
    def test_pickle(self):
        s = delayed_request('http://google.com')
        json.dumps(repr(s))
        pickle.dumps(s)

    def test_json(self):
        s = delayed_request('http://google.com', param=dict(test='test'))
        self.assertEqual(
            '"{\\"param\\": {\\"test\\": \\"test\\"}}"',
            json.dumps(s, cls=CustomJSONEncoder)
        )
        with mock.patch.object(__builtin__, 'repr',
                               return_value=None) as test:
            CustomJSONEncoder().default('Test')
        test.assert_called_once_with('Test')

    def test_fetch_google(self):
        with delayed_request('http://google.com').open() as istr:
            istr = iterator_to_file(iter(istr))
            all_content = content = istr.read(50)
            while len(content) == 50:
                content = istr.read(50)
                all_content += content
        self.assertTrue(all_content.endswith(''))

        with delayed_request('http://google.com').open() as istr:
            istr = iterator_to_file(iter(istr))
            all_content_at_once = istr.read()
        self.assertTrue(all_content_at_once.endswith(''))

    def test_iterate(self):
        content = ['foo', 'bar']
        result = []
        with closing(iterator_to_file(iter(content))) as istr:
            for word in istr:
                result.append(word)
        self.assertEqual(content, result)

class TestFileProperties(unittest.TestCase):
    def test_file_type(self):
        self.assertEquals(FileProperties.file_type('foo.png'), 'image')
        self.assertEquals(FileProperties.file_type(None), 'other')
        self.assertEquals(FileProperties.file_type('foo.unknown'), 'other')
        self.assertEquals(
            FileProperties.file_type('foo.unknown', 'image/jpeg'),
            'image'
        )

    def test_mime_type(self):
        self.assertEquals(FileProperties.mime_type('foo.png'), 'image/png')
        self.assertEquals(FileProperties.mime_type('foo.unknown'), None)

if __name__ == '__main__':
    unittest.main()


'''
Remove some lines from a text file.

-----------------------------------------------------------
(c) 2013 Allegra Via and Kristian Rother
    Licensed under the conditions of the Python License

    This code appears in section 6.3.3 of the book
    "Managing Biological Data with Python".
-----------------------------------------------------------
'''

in_file = open('text.txt')
out_file = open('new.txt', 'w')

index = 0
indices_to_remove = [1, 2, 5, 6]
for line in in_file:
    index = index + 1
    if index not in indices_to_remove:
        out_file.write(line)

in_file.close()
out_file.close()


import chainer
import chainer.links as L
import chainer.functions as F
from chainer import cuda,Chain,optimizers,serializers
import numpy as np
import os
import argparse
import pylab
from model import Generator, Discriminator, VGG
from prepare import prepare_dataset

xp=cuda.cupy
cuda.get_device(0).use()

def set_optimizer(model,alpha=0.0002,beta=0.5):
    optimizer = optimizers.Adam(alpha=alpha,beta1=beta)
    optimizer.setup(model)

    return optimizer

def calc_vgg_loss(feat1, feat2):
    _,_,h,w=feat1.shape

    return F.mean_squared_error(feat1,feat2)/(h*w)

parser=argparse.ArgumentParser(description="ESRGAN")
parser.add_argument("--epoch",default=1000,type=int,help="the number of epochs")
parser.add_argument("--batchsize",default=2,type=int,help="batchsize")
parser.add_argument("--testsize",default=2,type=int,help="testsize")
parser.add_argument("--aw",default=0.005,type=float,help="weight of adversarial loss")
parser.add_argument("--l1",default=0.01,type=float,help="weight of l1 loss")
parser.add_argument("--interval",default=1,type=int,help="interval of snapshot")
parser.add_argument("--Ntrain",default=24000,type=int,help="the number of training images")
parser.add_argument("--iterations",default=2000,type=int,help="the numbef of iterations")

args = parser.parse_args()
epochs=args.epoch
batchsize=args.batchsize
testsize=args.testsize
adver_weight=args.aw
l1_weight=args.l1
interval=args.interval
Ntrain=args.Ntrain
iterations=args.iterations

image_path="/coco/"
image_list=os.listdir(image_path)

outdir="./output_train"
if not os.path.exists(outdir):
    os.mkdir(outdir)

test_box=[]
for i in range(testsize):
    rnd = np.random.randint(Ntrain + 1, Ntrain + 100)
    image_name = image_path + image_list[rnd]
    _, sr = prepare_dataset(image_name)
    test_box.append(sr)

x_test=chainer.as_variable(xp.array(test_box).astype(xp.float32))

generator=Generator()
generator.to_gpu()
gen_opt=set_optimizer(generator)
serializers.load_npz("./output_pretrain/generator_pretrain.model",generator)

discriminator=Discriminator()
discriminator.to_gpu()
dis_opt=set_optimizer(discriminator)

vgg=VGG()
vgg.to_gpu()
vgg_opt=set_optimizer(vgg)
vgg.base.disable_update()

for epoch in range(epochs):
    sum_gen_loss=0
    sum_dis_loss=0
    for batch in range(0,iterations,batchsize):
        hr_box=[]
        sr_box=[]
        for index in range(batchsize):
            rnd = np.random.randint(Ntrain)
            image_name = image_path + image_list[rnd]
            hr, sr = prepare_dataset(image_name)
            hr_box.append(hr)
            sr_box.append(sr)

        x=chainer.as_variable(xp.array(sr_box).astype(xp.float32))
        t=chainer.as_variable(xp.array(hr_box).astype(xp.float32))

        y=generator(x)
        y_dis=discriminator(y)
        t_dis=discriminator(t)
        y.unchain_backward()

        # Relativistic loss
        fake_mean=F.broadcast_to(F.mean(y_dis),(batchsize,1))
        real_mean=F.broadcast_to(F.mean(t_dis),(batchsize,1))
        dis_loss=F.mean(F.softplus(-(t_dis-fake_mean)))
        dis_loss+=F.mean(F.softplus(y_dis-real_mean))
        dis_loss /= 2

        # Adversarial loss
        #dis_loss = F.mean(F.softplus(y_dis)) + F.mean(F.softplus(-t_dis))

        discriminator.cleargrads()
        dis_loss.backward()
        dis_opt.update()
        dis_loss.unchain_backward()

        y=generator(x)
        y_dis=discriminator(y)

        # Relativistic loss
        fake_mean=F.broadcast_to(F.mean(y_dis),(batchsize,1))
        real_mean=F.broadcast_to(F.mean(t_dis),(batchsize,1))
        adver_loss=F.mean(F.softplus(-(y_dis-real_mean)))
        adver_loss+=F.mean(F.softplus(t_dis-fake_mean))
        adver_loss /= 2

        # Adversarial loss
        #adver_loss = F.mean(F.softplus(-y_dis))

        fake_feat1=vgg(y)
        real_feat1=vgg(t)
        real_feat1.unchain_backward()
        vgg_loss=calc_vgg_loss(fake_feat1,real_feat1)

        l1_loss=F.mean_absolute_error(y,t)

        gen_loss=vgg_loss+adver_weight*adver_loss+l1_weight*l1_loss

        generator.cleargrads()
        vgg.cleargrads()
        gen_loss.backward()
        gen_opt.update()
        vgg_opt.update()
        gen_loss.unchain_backward()

        sum_dis_loss+=dis_loss.data.get()
        sum_gen_loss+=gen_loss.data.get()

        if epoch%interval==0 and batch==0:
            serializers.save_npz("%s/generator_%d.model"%(outdir,epoch),generator)
            with chainer.using_config("train", False):
                y = generator(x_test)
            y = y.data.get()
            sr = x_test.data.get()
            for i_ in range(testsize):
                tmp = (np.clip((sr[i_,:,:,:])*127.5 + 127.5, 0, 255)).transpose(1,2,0).astype(np.uint8)
                pylab.subplot(testsize,2,2*i_+1)
                pylab.imshow(tmp)
                pylab.axis('off')
                pylab.savefig('%s/visualize_%d.png'%(outdir, epoch))
                tmp = (np.clip((y[i_,:,:,:])*127.5 + 127.5, 0, 255)).transpose(1,2,0).astype(np.uint8)
                pylab.subplot(testsize,2,2*i_+2)
                pylab.imshow(tmp)
                pylab.axis('off')
                pylab.savefig('%s/visualize_%d.png'%(outdir, epoch))

    print("epoch:{}".format(epoch))
    print("Discrimintor loss:{}".format(sum_dis_loss/Ntrain))
    print("Generator loss:{}".format(sum_gen_loss/Ntrain))


'''
Data Scientist.: Dr.Eddy Giusepe Chirinos Isidro
'''

'''
ChatGPT é uma variante do modelo de linguagem GPT-3, projetado especificamente
para geração de linguagem de conversação. Para usar o ChatGPT em Python, você precisará
instalar o cliente OpenAI API e obter uma chave de API.
'''
import os
import openai
import gradio as gr
from dotenv import load_dotenv

print('Minha chave Key: ', load_dotenv())
Eddy_API_KEY = os.environ['API_KEY']

# Configurar o cliente OpenAI API
openai.api_key = Eddy_API_KEY

# Configure o modelo e o prompt
model_engine = "text-davinci-003"
prompt = "Olá, como vai você, hoje?"

# Gerar uma resposta
completion = openai.Completion.create(
    engine=model_engine,
    prompt=prompt,
    max_tokens=1024,
    n=1,
    stop=None, # Especifica string ou sequência de strings que, se encontradas no texto gerado, farão com que o modelo pare de gerar mais texto.
    # Isso pode ser útil para controlar o comprimento do texto gerado ou para garantir que o modelo não gere conteúdo inapropriado.
    temperature=0.5, # Mais alta resultará em respostas mais variadas e potencialmente menos coerentes, mais baixa resultará em respostas mais
    # previsíveis e potencialmente mais coerentes.
)

response = completion.choices[0].text # A resposta retorna como uma string nesta variável response.
print(response)


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

from tqdm import tqdm

import numpy as np

from dataset import Dataset, EOS, SOS
from model import Seq2Seq

import random
import math
import argparse

def evaluate(model, eval_instances, num_eval_instances=None):
    criterion = nn.CrossEntropyLoss(size_average=False)
    instances = 0
    total_loss = 0
    for i, (word, target) in tqdm(enumerate(eval_instances), total=num_eval_instances):
        loss = model.train_step(word, target, criterion)

        num_preds, loss = rescale_loss(loss, target)
        instances += num_preds
        total_loss += (loss.item() * num_preds)

    avg_loss = total_loss / instances
    print("Eval PPL: {:4.4f}".format(math.exp(avg_loss)))
    return math.exp(avg_loss)

def free_run(model, instances):
    outputs = []
    for word in instances:
        outputs.append(model.free_run(word, return_attentions=True))
    return outputs

def rescale_loss(loss, target):
    #TODO does the loss scaling make sense
    num_preds = target.shape[0] * (target.shape[1] - 1)
    loss = loss / num_preds
    return num_preds, loss

def train(model, dataset, epochs=10, log_every=500, my_dev=[], save_name=None):
    criterion = nn.CrossEntropyLoss(size_average=False)
    params = model.parameters()
    optim = torch.optim.Adam(params, lr=5e-3)
    old_best_dev_ppl = np.inf
    for epoch in range(epochs):
        epoch_loss = 0
        instances = 0
        for i, (word, target) in tqdm(enumerate(dataset.train_epoch()), total=len(dataset.batches)):
            loss = model.train_step(word, target, criterion)

            num_preds, loss = rescale_loss(loss, target)
            instances += num_preds
            epoch_loss += (loss.item() * num_preds) # unscale loss

            loss.backward()
            optim.step()
            optim.zero_grad()

        epoch_loss = epoch_loss / instances
        print("Epoch {} train PPL: {:4.4f}".format(epoch, math.exp(epoch_loss)))
        with torch.no_grad():
            dev_ppl = evaluate(model, dataset.dev_set(), len(dataset.dev))
            if save_name != None and dev_ppl < old_best_dev_ppl:
                print("New Best")
                torch.save(model.state_dict(), save_name)
            old_best_dev_ppl = dev_ppl

def run(model):
    while True:
        word = input('> ')
        output, attentions = free_run(model, [model.dataset.wrap_word(word)])[0]
        arpa_string = ' '.join([model.dataset.ix_to_out[o] for o in output])
        print(arpa_string[:-5])
        print(dataset.translate_arpabet(arpa_string[:-5]))
        attentions = torch.cat(attentions, dim=0)
        print(attentions[:-1, 1:-1])

if __name__ == '__main__':
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument("--character-size", dest="character_size", default=64, type=int, help="size of the character embedding")
    parser.add_argument("--encoder", dest="encoder_size", default=64, type=int, help="size of the encoder hidden state")
    parser.add_argument("--epochs", dest="epochs", default=10, type=int, help="number of epochs to train for")
    parser.add_argument("--batch-size", dest="batch_size", default=50, type=int, help="max size of a full batch (batches can be smaller)")
    parser.add_argument("--debug", dest="debug", action="store_true", help="truncate the dataset for faster training")
    parser.add_argument("--save", dest="save", help="path to save best models by dev ppl")
    parser.add_argument("--run", dest="run", action="store_true", help="echos word back in IPA")
    parser.add_argument("--type", dest="type", default="base", help="Decoder type, one of: base, attn")

    args = parser.parse_args()

    random.seed(1)
    torch.manual_seed(1)

    device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
    dataset = Dataset(device, batch_size = args.batch_size, debug=args.debug)

    model = Seq2Seq(dataset, device, args.encoder_size, args.character_size, args.type)

    if args.run:
        #TODO unhardcode and implement a joint encoder-decoder model class
        model.load_state_dict(torch.load('attn_01.model'))
        run(model)
    else:
        try:
            train(model, dataset, args.epochs, log_every=len(dataset.batches) // 10, save_name=args.save)
        except KeyboardInterrupt:
            print("Interruped")


import taichi as ti
import numpy as np
import os
import utils
from engine.mpm_solver import MPMSolver

write_to_disk = False

if write_to_disk:
    os.makedirs('outputs', exist_ok=True)

# Try to run on GPU
ti.init(arch=ti.cuda, device_memory_GB=4.0)

gui = ti.GUI("Taichi Elements", res=512, background_color=0x112F41)

mpm = MPMSolver(res=(64, 64, 64), size=1)

mpm.set_gravity((0, -20, 0))

mpm.add_sphere_collider(center=(0.25, 0.5, 0.5),
                        radius=0.1,
                        surface=mpm.surface_slip)
mpm.add_sphere_collider(center=(0.5, 0.5, 0.5),
                        radius=0.1,
                        surface=mpm.surface_sticky)
mpm.add_sphere_collider(center=(0.75, 0.5, 0.5),
                        radius=0.1,
                        surface=mpm.surface_separate)

for frame in range(1500):
    mpm.add_cube((0.2, 0.8, 0.45), (0.1, 0.03, 0.1),
                 mpm.material_water,
                 color=0x8888FF)
    mpm.add_cube((0.45, 0.8, 0.45), (0.1, 0.03, 0.1),
                 mpm.material_water,
                 color=0xFF8888)
    mpm.add_cube((0.7, 0.8, 0.45), (0.1, 0.03, 0.1),
                 mpm.material_water,
                 color=0xFFFFFF)
    mpm.step(4e-3)
    particles = mpm.particle_info()
    np_x = particles['position'] / 1.0

    # simple camera transform
    screen_x = ((np_x[:, 0] + np_x[:, 2]) / 2**0.5) - 0.2
    screen_y = (np_x[:, 1])

    screen_pos = np.stack([screen_x, screen_y], axis=-1)

    gui.circles(screen_pos, radius=1.1, color=particles['color'])
    gui.show(f'outputs/{frame:06d}.png' if write_to_disk else None)


from collections import Counter
import sys
sys.path.append(".")

import vgmusic
from music21 import note, interval, stream
from typing import Dict, Generator, List
import json

class SongDataTracker:
    def __init__(self):
        self.highest_note = 0
        self.lowest_note = 5000
        self.total_note_length = 0.0
        self.note_count = 0
        self.total_rest_length = 0.0
        self.rest_count = 0
        self.range = 0

    def get_notes_to_rests(self) -> float:
        if self.total_rest_length > 0.0:
            return self.total_note_length / self.total_rest_length
        return 0.0

    def get_avg_note(self) -> float:
        if self.note_count > 0:
            return self.total_note_length / self.note_count
        return 0.0

    def get_avg_rest(self) -> float:
        if self.rest_count > 0:
            return self.total_rest_length / self.rest_count
        return 0.0

    def to_dict(self) -> Dict:
        tmp = {
            "highest_note": self.highest_note,
            "lowest_note": self.lowest_note,
            "total_note_length": self.total_note_length,
            "note_count": self.note_count,
            "total_rest_length": self.total_rest_length,
            "rest_count": self.rest_count,
            "range": self.range
        }

        if self.total_rest_length > 0.0:
            tmp["notes_to_rests"] = self.get_notes_to_rests()

        if self.note_count > 0:
            tmp["avg_note_length"] = self.get_avg_note()

        if self.rest_count > 0:
            tmp["avg_rest_length"] = self.get_avg_rest()

        return tmp

    def from_dict(self, inst: Dict):
        self.highest_note = inst.get("highest_note", 0)
        self.lowest_note = inst.get("lowest_note", 0)
        self.total_note_length = inst.get("total_note_length", 0.0)
        self.note_count = inst.get("note_count", 0)
        self.total_rest_length = inst.get("total_rest_length", 0)
        self.rest_count = inst.get("rest_count", 0)
        self.range = inst.get("range", 0)

    def process_stream(self, song_str: stream.Stream):
        new_range = song_str.analyze("ambitus")
        if new_range.semitones > self.range:
            self.range = new_range.semitones

        for gennote in song_str.flat.getElementsByClass(note.GeneralNote):
            if isinstance(gennote, note.Note):
                new_ps = gennote.pitch.ps
                if self.highest_note < new_ps:
                    self.highest_note = new_ps
                if self.lowest_note > new_ps:
                    self.lowest_note = new_ps

                self.total_note_length += gennote.duration.quarterLength
                self.note_count += 1
            elif isinstance(gennote, note.Rest):
                self.total_rest_length += gennote.duration.quarterLength
                self.rest_count += 1

    def compare_stream(self, song_str: stream.Stream, sdt) -> float:
        #notes_in_range = 0
        #note_count = 0
        #for note_obj in song_str.flat.getElementsByClass(note.Note):
        #    if self.lowest_note <= note_obj.pitch.ps <= self.highest_note:
        #        notes_in_range += 1
        #    note_count += 1
        #perc_in_range = 0.0

        range_diff = abs(sdt.range - self.range)
        range_diff_score = 1.0 - range_diff / 100.0

        ntr_diff_score = abs(sdt.get_notes_to_rests() - self.get_notes_to_rests())

        avg_note_diff = abs(sdt.get_avg_note() - self.get_avg_note())
        avg_rest_diff = abs(sdt.get_avg_rest() - self.get_avg_rest())

        scores = [range_diff_score, ntr_diff_score, avg_note_diff, avg_rest_diff]
        weights = [0.2, 0.2, 0.2, 0.2]

        tmp_sum = 0
        for i in range(len(scores)):
            tmp_sum += scores[i] * weights[i]
        return tmp_sum

class GenreDataTracker:
    def __init__(self):
        self.song_trackers: List[SongDataTracker] = []

    def append(self, tracker: SongDataTracker):
        self.song_trackers.append(tracker)

    def get_median_range(self) -> float:
        ranges = [tracker.range for tracker in self.song_trackers]
        size = len(ranges)
        if size == 1:
            return ranges[0]
        elif size == 0:
            return 0
        elif size % 2 == 0:
            return ranges[size // 2]
        else:
            return (ranges[size // 2] + ranges[size // 2 + 1]) / 2.0

    def compare(self, song: stream.Stream, song_dt: SongDataTracker) -> float:
        # given a stream, test the probability the stream belonds to this genre.
        probs = []
        for sdt in self.song_trackers:
            probs.append(sdt.compare_stream(song, song_dt))
        return sum(probs) / len(probs)

    def to_dict(self):
        tmp = {}

        tmp["tracker_data"] = []
        for tracker in self.song_trackers:
            tmp["tracker_data"].append(tracker.to_dict())

        tmp["median_range"] = self.get_median_range()

        return tmp

    def from_dict(self, inst: Dict):
        tracker_data = inst.get("tracker_data", [])
        for tracker_inst in tracker_data:
            sdt = SongDataTracker()
            sdt.from_dict(tracker_inst)
            self.song_trackers.append(sdt)

def calculate_stats_for_genres():
    genres = {}

    for game in vgmusic.get_games_by_console("nes"):

        if len(game.genres) > 0:
            print("Processing {}...".format(game.name))
            for song in game.fetch_all_songs():
                main_tracker = SongDataTracker()
                main_tracker.process_stream(song)

                for genre in game.genres:
                    if genre not in genres:
                        genres[genre] = GenreDataTracker()
                    genres[genre].append(main_tracker)

    final_dict = {}
    for genre in genres:
        final_dict[genre] = genres[genre].to_dict()
    with open("test_output/nes.json", "w") as f:
        f.write(json.dumps(final_dict, indent=4))

def calculate_for_unknown_games():
    with open("test_output/nes.json", "r") as f:
        raw_data = json.loads(f.read())
    genres: Dict[str, GenreDataTracker] = {}
    for genre in raw_data:
        gdt = GenreDataTracker()
        gdt.from_dict(raw_data[genre])
        genres[genre] = gdt

    def sort_genre_data(genre_data):
        return genre_data[1]

    final_dict = {}
    for game in vgmusic.get_games_by_console("nes"):
        if game.id > 0:
            continue
        print(game.name)
        genres_sum = {}
        genres_total = {}
        for song in game.fetch_all_songs():
            sdt = SongDataTracker()
            sdt.process_stream(song)
            for genre in genres:
                if genre not in genres_sum:
                    genres_sum[genre] = 0.0
                    genres_total[genre] = 0
                genres_sum[genre] += genres[genre].compare(song, sdt)
                genres_total[genre] += 1
        genres_avg = []
        for genre in genres_sum:
            genre_data = (
                genre,
                genres_sum[genre] / genres_total[genre]
            )
            genres_avg.append(genre_data)

        genres_avg.sort(key=sort_genre_data, reverse=True)

        top_3 = genres_avg[0:3]
        final_dict[game.name] = top_3

    with open("test_output/unknown_genres.json", "w") as f:
        f.write(json.dumps(final_dict, indent=4))

if __name__ == "__main__":
    #calculate_stats_for_genres()
    calculate_for_unknown_games()


class Location:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        if not self.float_validation():
            raise TypeError('X and Y Must be float')
        if not self.negative_validation():
            raise ValueError('X and Y cant be negative')

    def float_validation(self):
        """ validation for the init """
        if (type(self.x) != float) or (type(self.y) != float):
            return False
        else:
            return True

    def negative_validation(self):
        """ validation for the init """
        if (self.x < 0) or (self.y < 0):
            return False
        else:
            return True

    def distance_to(self, other):
        """returns the distance between two locations"""
        return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5

    def __str__(self):
        return str(self.x)+"_"+str(self.y)

class Customer:
    def __init__(self, name, id, credit=0):
        self.name = name
        self.id = id
        self.credit = credit

    def add_credit(self, addition):
        """adding the addition to the customers credit"""
        self.credit = self.credit + addition

class Trip:
    def __init__(self, customer, origin, destination):
        self.customer = customer
        self.origin = origin
        self.destination = destination
        """validations for the init"""
        if not isinstance(self.customer, Customer):
            raise TypeError("The types are not correct")
        if not isinstance(self.origin, Location):
            raise TypeError("The types are not correct")
        if not isinstance(self.destination, Location):
            raise TypeError("The types are not correct")

    def __len__(self):
        """returns the rounded distance between the origin and the destination"""
        return round(((self.destination.x - self.origin.x) ** 2 + (self.destination.y - self.origin.y) ** 2) ** 0.5)

class Taxi:
    def __init__(self, id, location, rate):
        self.id = id
        self.location = location
        self.rate = rate
        """the trips will be used later for counting the successful rides, adding 1 for every successful one"""
        self.trips = 0

    def get_trips(self):
        """returns the successful rides"""
        return self.trips

class Company:
    def __init__(self, taxi_lst=[], customer_lst=[]):
        self.taxi_lst = taxi_lst[:]
        self.customer_lst = customer_lst[:]
        self.successful_rides = 0
        self.not_successful_rides = 0

    def add_taxi(self, taxi):
        """adding a taxi to the taxi list"""
        self.taxi_lst.append(taxi)

    def add_customer(self, customer):
        """adding a customer to the customer list"""
        self.customer_lst.append(customer)

    def find_closest_taxi(self, trip):
        """if there are no taxis, return None"""
        if len(self.taxi_lst)==0:
            return None
        else:
            """if there are taxis, it's creating lists of locations and distances, and searching for the min distance"""
            taxis_locations_lst =[]
            taxis_distance_from_trip_origin_lst = []
            for taxi in self.taxi_lst:
                taxis_locations_lst.append(taxi.location)
            for location in taxis_locations_lst:
                taxis_distance_from_trip_origin_lst.append(location.distance_to(trip.origin))
            min_distance = min(taxis_distance_from_trip_origin_lst)
            """after finding the min distance, it finds for which taxi that belong, by using its index in the list"""
            index_of_min = taxis_distance_from_trip_origin_lst.index(min_distance)
            """finally, we've got the taxi with the min distance. Now we'll return it"""
            return self.taxi_lst[index_of_min]

    def handle_trip(self, trip):
        closest_taxi = self.find_closest_taxi(trip)
        """if the there are no taxis, so we'll count it and return false"""
        if closest_taxi == None:
            self.not_successful_rides = self.not_successful_rides + 1
            return False
        else:
            """if there is a taxi, we'll calculate its price: rate * trip's len"""
            price = (closest_taxi.rate) * (len(trip))
            """if the customer doesn't have enough money, the ride won'y happen - we'll count it and return false"""
            if trip.customer.credit < price:
                self.not_successful_rides = self.not_successful_rides + 1
                return False
            else:
                """if the customer is able to pay, the ride happens and the customers credit reduces by the price"""
                trip.customer.credit = trip.customer.credit - price
                """the taxis location is changing to the destination of the trip"""
                closest_taxi.location = trip.destination
                """we'll count this successful rides both for the company and for the taxi"""
                self.successful_rides = self.successful_rides + 1
                closest_taxi.trips = closest_taxi.trips + 1
                return True

    def get_success_percentage(self):
        """calculating the percentage of successful rides out of all the rides attempts"""
        return (self.successful_rides)/((self.successful_rides + self.not_successful_rides))


class Solution:
    def findJudge(self, N: int, trust: List[List[int]]) -> int:

        if len(trust) < N -1:
            return -1

        trust_arr = [0] * (N + 1)

        for i in range(0, len(trust)):
            trusting, trusted = trust[i]
            trust_arr[trusting] -=1
            trust_arr[trusted] +=1
        for i, score in enumerate(trust_arr[1:], 1):
            if score == N -1:
                return i
        return -1


"""
Wrapper around MAFFT and other tools to harmonize phased variants
"""
import os
import re
import sys
import shutil
import logging
import argparse
import multiprocessing
from io import BytesIO
from functools import partial
from collections import defaultdict

import pysam
from pysam import bcftools, samtools
from intervaltree import IntervalTree
from pywfa.align import WavefrontAligner  # pylint: disable=no-name-in-module
import truvari

DEFAULT_MAFFT_PARAM = "--auto --thread 1"

def parse_regions(argument):
    """
    Parse the --region argument
    returns list of regions
    """
    ret = []
    if not argument:
        return ret
    if os.path.exists(argument):
        for i in truvari.opt_gz_open(argument):
            try:
                chrom, start, end = i.strip().split('\t')[:3]
                start = int(start)
                end = int(end)
            except Exception:  # pylint: disable=broad-except
                logging.error("Unable to parse bed line %s", i)
                sys.exit(1)
            ret.append((chrom, start, end))
    else:
        for i in argument.split(','):
            try:
                chrom, start, end = re.split(':|-', i)
                start = int(start)
                end = int(end)
            except ValueError:
                logging.error("Unable to parse region line %s", i)
                sys.exit(1)
            ret.append((chrom, start, end))
    return ret

def merged_region_file(regions, buff=100):
    """
    Write a file for extracting reference regions with samtools
    returns the name of the temporary file made
    """
    m_dict = defaultdict(list)
    for i in regions:
        m_dict[i[0]].append((max(0, i[1] - buff), i[2] + buff))

    out_file_name = truvari.make_temp_filename()
    with open(out_file_name, 'w') as fout:
        for chrom in sorted(m_dict.keys()):
            intvs = IntervalTree.from_tuples(m_dict[chrom])
            intvs.merge_overlaps()
            for i in sorted(intvs):
                fout.write(f"{chrom}:{i.begin}-{i.end}\n")
    return out_file_name

def extract_reference(reg_fn, ref_fn):
    """
    Pull the reference
    """
    out_fn = truvari.make_temp_filename(suffix='.fa')
    with open(out_fn, 'w') as fout:
        fout.write(samtools.faidx(ref_fn, "-r", reg_fn))
    return out_fn

def make_haplotype_jobs(base_vcf, bSamples=None, comp_vcf=None, cSamples=None, prefix_comp=False):
    """
    Sets up sample parameters for extract haplotypes
    returns list of tuple of (VCF, sample_name, should_prefix, haplotype_number) and the sample names
    to expect in the haplotypes' fasta
    """
    ret = []
    if bSamples is None:
        bSamples = list(pysam.VariantFile(base_vcf).header.samples)
    for hap in [1, 2]:
        ret.extend([(base_vcf, samp, False, hap) for samp in bSamples])

    if comp_vcf:
        if cSamples is None:
            cSamples = list(pysam.VariantFile(comp_vcf).header.samples)
        for hap in [1, 2]:
            ret.extend([(comp_vcf, samp, prefix_comp or samp in bSamples, hap)
                        for samp in cSamples])

    samp_names = sorted({('p:' if prefix else '') + samp
                         for _, samp, prefix, _ in ret})
    return ret, samp_names

def fasta_reader(fa_str, name_entries=True):
    """
    Parses a fasta file as a string and yields tuples of (location, entry)
    if name_entries, the entry names are written to the value and location is honored
    """
    cur_name = None
    cur_entry = BytesIO()
    for i in fa_str.split('\n'):
        if not i.startswith(">"):
            cur_entry.write(i.encode())
            continue
        if cur_name is not None:
            cur_entry.write(b'\n')
            cur_entry.seek(0)
            yield cur_name, cur_entry.read()
        cur_name = i[1:]
        cur_entry = BytesIO()
        if name_entries:
            cur_name = cur_name.split('_')[-1]
            cur_entry.write((i + '\n').encode())

    cur_entry.write(b'\n')
    cur_entry.seek(0)
    yield cur_name, cur_entry.read()

def extract_haplotypes(data, ref_fn):
    """
    Given a data tuple of VCF, sample name, and prefix bool
    Call bcftools consensus
    Returns list of tuples [location, fastaentry] for every haplotype,
    so locations are duplicated
    """
    vcf_fn, sample, prefix, hap = data
    prefix = 'p:' if prefix else ''
    cmd = (f"--sample {sample} --prefix {prefix}{sample}_{hap}_ "
           f"-H{hap} -f {ref_fn} {vcf_fn}").split(' ')
    # Can't return generator from process
    return list(fasta_reader(bcftools.consensus(*cmd)))

def collect_haplotypes(ref_haps_fn, hap_jobs, threads):
    """
    Calls extract haplotypes for every hap_job
    """
    all_haps = defaultdict(BytesIO)
    with multiprocessing.Pool(threads, maxtasksperchild=1) as pool:
        to_call = partial(extract_haplotypes, ref_fn=ref_haps_fn)
        for haplotype in pool.imap(to_call, hap_jobs):
            for location, fasta_entry in haplotype:
                all_haps[location].write(fasta_entry)
        pool.close()
        pool.join()
    return all_haps

def consolidate_haplotypes_with_reference(all_haps, ref_haps_fn):
    """
    Generator for putting the reference into the haplotypes
    """
    m_ref = pysam.FastaFile(ref_haps_fn)
    for location in list(m_ref.references):
        all_haps[location].write(
            f">ref_{location}\n{m_ref[location]}\n".encode())
        all_haps[location].seek(0)
        yield all_haps[location].read()

def expand_cigar(seq, ref, cigar):
    """
    Put gaps '-' in sequence where needed
    """
    seq_pos = 0
    seq = list(seq)
    ref_pos = 0
    ref = list(ref)
    for code, span in cigar:
        if code == 2:
            seq.insert(seq_pos, '-' * span)
            seq_pos += 1
            ref_pos += span
        elif code == 1:
            ref.insert(ref_pos, '-' * span)
            seq_pos += span
            ref_pos += 1
        else:
            seq_pos += span
            ref_pos += span
    return "".join(ref), "".join(seq)

def wfa_to_vars(seq_bytes):
    """
    Align haplotypes independently with WFA
    Much faster than mafft, but may be less accurate at finding parsimonous representations
    """
    fasta = {k: v.decode() for k, v in fasta_reader(seq_bytes.decode(), False)}
    ref_key = [_ for _ in fasta.keys() if _.startswith("ref_")][0]
    reference = fasta[ref_key]

    aligner = WavefrontAligner(reference, span="end-to-end",
                               heuristic="adaptive")
    for haplotype in fasta:
        if haplotype == ref_key:
            continue
        seq = fasta[haplotype]
        aligner.wavefront_align(seq)
        assert aligner.status == 0
        fasta[haplotype] = expand_cigar(seq, reference, aligner.cigartuples)
    return truvari.msa2vcf(fasta)

def mafft_to_vars(seq_bytes, params=DEFAULT_MAFFT_PARAM):
    """
    Run mafft on the provided sequences provided as a bytestr and return msa2vcf lines
    """
    # Dev only method for overwriting test answers - don't use until code is good
    dev_name = None
    if "PHAB_WRITE_MAFFT" in os.environ and os.environ["PHAB_WRITE_MAFFT"] == "1":
        import hashlib  # pylint: disable=import-outside-toplevel
        dev_name = hashlib.md5(seq_bytes).hexdigest()

    cmd = f"mafft --quiet {params} -"
    ret = truvari.cmd_exe(cmd, stdin=seq_bytes)
    if ret.ret_code != 0:
        logging.error("Unable to run MAFFT")
        logging.error(ret.stderr)
        return ""

    if dev_name is not None:
        with open("repo_utils/test_files/external/fake_mafft/lookup/fm_" + dev_name + ".msa", 'w') as fout:
            fout.write(ret.stdout)

    fasta = {}
    for name, sequence in fasta_reader(ret.stdout, name_entries=False):
        fasta[name] = sequence.decode()
    return truvari.msa2vcf(fasta)

def harmonize_variants(harm_jobs, mafft_params, base_vcf, samp_names, output_fn, threads, method="mafft"):
    """
    Parallel processing of variants to harmonize. Writes to output
    """
    if method == "mafft":
        align_method = partial(mafft_to_vars, params=mafft_params)
    else:
        align_method = wfa_to_vars

    with open(output_fn[:-len(".gz")], 'w') as fout:
        fout.write(
            '##fileformat=VCFv4.1\n##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">\n')
        for ctg in pysam.VariantFile(base_vcf).header.contigs.values():
            fout.write(str(ctg.header_record))
        fout.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t")
        fout.write("\t".join(samp_names) + "\n")

        with multiprocessing.Pool(threads) as pool:
            for result in pool.imap_unordered(align_method, harm_jobs):
                fout.write(result)
            pool.close()
            pool.join()

    truvari.compress_index_vcf(output_fn[:-len(".gz")], output_fn)

# pylint: disable=too-many-arguments
# This is just how many arguments it takes
def phab(var_regions, base_vcf, ref_fn, output_fn, bSamples=None, buffer=100,
         mafft_params=DEFAULT_MAFFT_PARAM, comp_vcf=None, cSamples=None,
         prefix_comp=False, threads=1, method="mafft"):
    """
    Harmonize variants with MSA. Runs on a set of regions given files to create
    haplotypes and writes results to a compressed/indexed VCF

    :param `var_regions`: List of tuples of region's (chrom, start, end)
    :type `var_regions`: :class:`list`
    :param `base_vcf`: VCF file name
    :type `base_vcf`: :class:`str`
    :param `ref_fn`: Reference file name
    :type `ref_fn`: :class:`str`
    :param `output_fn`: Output VCF.gz
    :param `bSamples`: Samples from `base_vcf` to create haplotypes
    :type `bSamples`: :class:`list`
    :param `buffer`: Flanking reference bases to added to regions
    :type `buffer`: :class:`int`
    :param `mafft_params`: Parameters for mafft
    :type `mafft_params`: :class:`str`
    :param `comp_vcf`: VCF file name
    :type `comp_vcf`: :class:`str`
    :param `cSamples`: Samples from `comp_vcf` to create haplotypes
    :type `cSamples`: :class:`list`
    :param `prefix_comp`: Ensure unique sample names by prefixing comp samples
    :type `prefix_comp`: :class:`bool`
    :param `threads`: Number of threads to use
    :type `threads`: :class:`int`
    :param `method`: Alignment method to use mafft or wfa
    :type `method`: :class:`str`
    """
    logging.info("Preparing regions")
    region_fn = merged_region_file(var_regions, buffer)

    logging.info("Extracting haplotypes")
    ref_haps_fn = extract_reference(region_fn, ref_fn)
    hap_jobs, samp_names = make_haplotype_jobs(base_vcf, bSamples,
                                               comp_vcf, cSamples,
                                               prefix_comp)
    sample_haps = collect_haplotypes(ref_haps_fn, hap_jobs, threads)
    harm_jobs = consolidate_haplotypes_with_reference(sample_haps, ref_haps_fn)

    logging.info("Harmonizing variants")
    harmonize_variants(harm_jobs, mafft_params, base_vcf,
                       samp_names, output_fn, threads, method)
# pylint: enable=too-many-arguments

######
# UI #
######

def parse_args(args):
    """
    Pull the command line parameters
    """
    parser = argparse.ArgumentParser(prog="phab", description=__doc__,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("-r", "--region", type=str, required=True,
                        help="Bed filename or comma-separated list of chrom:start-end regions to process")
    parser.add_argument("-b", "--base", type=str, required=True,
                        help="Baseline vcf to MSA")
    parser.add_argument("-c", "--comp", type=str, default=None,
                        help="Comparison vcf to MSA")
    parser.add_argument("-f", "--reference", type=str, required=True,
                        help="Reference")
    parser.add_argument("--buffer", type=int, default=100,
                        help="Number of reference bases before/after region to add to MSA (%(default)s)")
    parser.add_argument("-o", "--output", type=str, default="phab_out.vcf.gz",
                        help="Output VCF")
    parser.add_argument("--bSamples", type=str, default=None,
                        help="Subset of samples to MSA from base-VCF")
    parser.add_argument("--cSamples", type=str, default=None,
                        help="Subset of samples to MSA from comp-VCF")
    parser.add_argument("-m", "--mafft-params", type=str, default=DEFAULT_MAFFT_PARAM,
                        help="Parameters for mafft, wrap in a single quote (%(default)s)")
    parser.add_argument("--align", type=str, choices=["mafft", "wfa"], default="mafft",
                        help="Alignment method accurate (mafft) or fast (wfa) (%(default)s)")
    parser.add_argument("-t", "--threads", type=int, default=1,
                        help="Number of threads (%(default)s)")
    parser.add_argument("--debug", action="store_true",
                        help="Verbose logging")
    args = parser.parse_args(args)
    return args

def check_requirements(align):
    """
    ensure external programs are in PATH
    """
    check_fail = False
    if align == "mafft":
        if not shutil.which("mafft"):
            logging.error("Unable to find mafft in PATH")
            check_fail = True
    return check_fail

def check_params(args):
    """
    Ensure files are okay to use
    """
    check_fail = False
    if not args.output.endswith(".vcf.gz"):
        logging.error("Output file must be a '.vcf.gz', got %s", args.output)
        check_fail = True
    if os.path.exists(args.output):
        logging.error("Output file already exists")
        check_fail = True
    if args.comp is not None and not os.path.exists(args.comp):
        logging.error("File %s does not exist", args.comp)
        check_fail = True
    if not os.path.exists(args.base):
        logging.error("File %s does not exist", args.base)
        check_fail = True
    if args.comp is not None and not args.comp.endswith(".gz"):
        logging.error(
            "Comparison vcf %s does not end with .gz. Must be bgzip'd", args.comp)
        check_fail = True
    if args.comp is not None and not os.path.exists(args.comp + '.tbi'):
        logging.error(
            "Comparison vcf index %s.tbi does not exist. Must be indexed", args.comp)
        check_fail = True
    if not args.base.endswith(".gz"):
        logging.error(
            "Base vcf %s does not end with .gz. Must be bgzip'd", args.base)
        check_fail = True
    if not os.path.exists(args.base + '.tbi'):
        logging.error(
            "Base vcf index %s.tbi does not exist. Must be indexed", args.base)
        check_fail = True
    if not os.path.exists(args.reference):
        logging.error("Reference %s does not exist", args.reference)
        check_fail = True

    return check_fail

def phab_main(cmdargs):
    """
    Main
    """
    args = parse_args(cmdargs)
    truvari.setup_logging(args.debug, show_version=True)
    if check_requirements(args.align) or check_params(args):
        logging.error("Couldn't run Truvari. Please fix parameters\n")
        sys.exit(100)

    if args.bSamples is not None:
        args.bSamples = args.bSamples.split(',')

    if args.comp and args.cSamples is not None:
        args.cSamples = args.cSamples.split(',')

    all_regions = parse_regions(args.region)
    phab(all_regions, args.base, args.reference, args.output, args.bSamples, args.buffer,
         args.mafft_params, args.comp, args.cSamples, threads=args.threads, method=args.align)

    logging.info("Finished phab")


import logging

from loader import dp
from aiogram.types import Message
from data.config import admins

@dp.message_handler(chat_id=admins, commands=['help_admin'])
async def admin_help(message: Message):
    logging.info(f'from: {message.chat.full_name}, text: {message.text}')
    text = [
        'Список команд администратора: ',
        '/add_meme - добавление нового мема в БД',
        '/cancel_meme - отмена добавления нового мема '
        '\n(можно импользовать на любом шаге добавления)',
        '/del_meme - удаление мема из БД.',
        '/cancel_del_meme - отмена удаления мема.',
        '/mail - рассылка всем пользователям бота.',
        '/cancel_mail - отмена рассылки.',
        '/update_memes - обновление мемов с сайта memepedia.ru'
    ]
    await message.answer('\n'.join(text))


for i in range(1,100):
    result=1
    if i%3 == 0:
        sure="Fizz"
        result=2
    if i%5 == 0:
        sure="Buzz"
        result=2
    if i%3 == 0 and i%5 == 0:
        sure="Fizzbuzz"
        result=2
    if result ==1:
        p=1
        multiples=0
        while (p<100):
            if i%p == 0:
                multiples= multiples + 1
                p+= 1
            else:
                p=p+1
        if multiples ==2:
            sure="Prime"
            result=2

    if result != 1:
        print(sure)
    else:
        print(i)


# Implement a recursive function to celculate the factorial of a given number

"""
1! = 1 × 1
2! = 2 × 1! --->2
3! = 3× 2! --->3 × 2 × 1
.
.
10! = 10 × 9!¡ --->10 × 9 × 8 ×...×1

Formula - no × (n-1 )!
"""

def fact_rec(n):
 if n==0 or n==1:
   return 1
 else:
    return n*fact_rec(n-1)

number = int(input("Enter a value :"))
res = fact_rec(number)

print("The factorial of {} is {}".format(number,res))

# importing the module
import calendar

# input the year
year=int(input('Enter the value of year: '))
leap_year=calendar.isleap(year)

# checking leap year
if leap_year: # to check condition
    print('The given year is a leap year.')
else:
    print('The given year is a non-leap year.')


import sys
input = sys.stdin.readline

def get_dir(dir):
    if dir == 1:
        return 0, -1
    elif dir == 2:
        return -1, -1
    elif dir == 3:
        return -1 , 0
    elif dir == 4:
        return -1, 1
    elif dir == 5:
        return 0 , 1
    elif dir == 6:
        return 1, 1
    elif dir == 7:
        return 1, 0
    elif dir == 8:
        return 1, -1

def move(n, cloud, dir, cnt):
    new_cloud = set()
    dx, dy = get_dir(dir)

    for position in cloud:
        x, y = position

        for _ in range(cnt):
            x += dx
            y += dy

            if x == 0:
                x = n
            elif x == n + 1:
                x = 1

            if y == 0:
                y = n
            elif y == n + 1:
                y = 1

        new_cloud.add((x, y))
    return new_cloud

def water_copy(n, cloud, graph):
    dx = [1, 1, -1, -1]
    dy = [1, -1, 1, -1]

    up = []

    for position in cloud:
        x, y = position
        x -= 1
        y -= 1

        cnt = 0
        for j in range(4):
            nx = x + dx[j]
            ny = y + dy[j]

            if (0 <= nx < n) and (0 <= ny < n):
                if graph[nx][ny] >= 1:
                    cnt += 1

        up.append(cnt)
    return up

def solve():
    # 입력
    n, m = map(int, input().split())
    graph = []

    for _ in range(n): graph.append(list(map(int, input().split())))

    cmd = []
    for _ in range(m):
        dir, cnt = map(int, input().split())
        cmd.append((dir, cnt))

    # 초기 구름 생성
    cloud = set()
    cloud.add((n, 1))
    cloud.add((n, 2))
    cloud.add((n - 1, 1))
    cloud.add((n - 1, 2))

    # 명령어 수행
    for i in range(m):
        dir, cnt = cmd[i]

        # 구름 이동
        cloud = move(n, cloud, dir, cnt)

        # 비 내림
        for position in cloud:
            x, y = position
            x -= 1
            y -= 1
            graph[x][y] += 1

        # 물복사버그
        up = water_copy(n, cloud, graph)
        index = 0
        for position in cloud:
            x, y = position
            x -= 1
            y -= 1
            graph[x][y] += up[index]
            index += 1

        # 새로운 구름 생성
        new_cloud = set()
        for j in range(n):
            for k in range(n):
                if graph[j][k] >= 2 and (j + 1, k + 1) not in cloud:
                    new_cloud.add((j + 1, k + 1))
                    graph[j][k] -= 2

        cloud = new_cloud

    # 결과 출력
    ans = 0
    for i in range(n):
        ans += sum(graph[i])

    print(ans)

solve()


# https://olimpiada.ic.unicamp.br/pratique/ps/2021/f2/lista/

N = int(input())

lista = [int(i) for i in input().split()]

esquerda, direita = 0, N-1

operacoes = 0
while esquerda < direita:
    if lista[esquerda] == lista[direita]:
        esquerda += 1
        direita -= 1

        continue

    if lista[direita] > lista[esquerda]:
        lista[esquerda+1] += lista[esquerda]
        esquerda += 1

    elif lista[direita] < lista[esquerda]:
        lista[direita-1] += lista[direita]
        direita -= 1

    operacoes += 1

print(operacoes)


import streamlit as st
import pandas as pd
import numpy as np

st.title('KKBOX Churn Prediction')

sentence = st.text_input('Input your mnso:')

members_data = pd.read_csv('members_v3.csv')
transactions_data = pd.read_csv('transactions_v2.csv')
user_logs_data = pd.read_csv('user_logs_v2.csv')

a = members_data[members_data.isin([sentence]).any(axis=1)]

b = transactions_data[transactions_data.isin([sentence]).any(axis=1)]

c = user_logs_data[user_logs_data.isin([sentence]).any(axis=1)]

result = pd.concat([a, b, c], ignore_index=True, sort=False)

def preprocessing(data):
    '''This preprocessing function is used to perform outliers removal, nan imputation '''

    # nan = 0  in city
    data['city'] = data['city'].fillna(0)

    # removing outliers
    data['bd'] = data['bd'].apply(lambda x: x if (x < 60.0) and (x > 0.0) else np.nan)
    # nan = median age in bd
    data['bd'] = data['bd'].fillna(19.0)

    #  male = 1 in gender
    data['gender'] = data['gender'].replace(to_replace='male', value=1)
    #  male = 2 in gender
    data['gender'] = data['gender'].replace(to_replace='female', value=2)
    #  nan = 0 in gender
    data['gender'] = data['gender'].fillna(0)

    # nan = 0 in registered_via
    data['registered_via'] = data['registered_via'].fillna(0)

    # nan = median date in the registration_init_time
    data['registration_init_time'] = data['registration_init_time'].fillna(20131114.0)
    # converting float date to datetime
    #data['registration_init_time'] = pd.to_datetime(data['registration_init_time'], format='%Y%m%d')

    # nan = 0 in payment_method_id
    data['payment_method_id'] = data['payment_method_id'].fillna(0)

    # nan = 30 in payment_plan_days
    data['payment_plan_days'] = data['payment_plan_days'].fillna(30.0)

    # nan = 149 in  plan_list_price
    data['plan_list_price'] = data['plan_list_price'].fillna(149.0)

    # nan = 149 in actual_amount_paid
    data['actual_amount_paid'] = data['actual_amount_paid'].fillna(149.0)

    # nan =  2 in is_auto_renew (2 is not mentioned)
    data['is_auto_renew'] = data['is_auto_renew'].fillna(2)

    # nan = median date in transaction_date
    data['transaction_date'] = data['transaction_date'].fillna(20170315.0)
    # converting float date to datetime
    #data['transaction_date'] = pd.to_datetime(data['transaction_date'], format='%Y%m%d')

    # nan = median date in membership_expire_date
    data['membership_expire_date'] = data['membership_expire_date'].fillna(20170419.0)
    # converting float date to datetime
    #data['membership_expire_date'] = pd.to_datetime(data['membership_expire_date'], format='%Y%m%d')

    #  nan =  2 in is_cancel (2 is not mentioned)
    data['is_cancel'] = data['is_cancel'].fillna(2)

    # nan = median date in 'date'
    data['date'] = data['date'].fillna(20170316.0)
    # converting float date to datetime
    #data['date'] = pd.to_datetime(data['date'], format='%Y%m%d')

    # removing outliers
    data['num_25'] = data['num_25'].apply(lambda x: x if (x <= 56.0) else np.nan)
    #  nan = 2 in num_25
    data['num_25'] = data['num_25'].fillna(2.0)

    # removing outliers
    data['num_50'] = data['num_50'].apply(lambda x: x if (x <= 21.0) else np.nan)
    # nan = 0 in num_50
    data['num_50'] = data['num_50'].fillna(0)

    # removing outliers
    data['num_75'] = data['num_75'].apply(lambda x: x if (x <= 10.0) else np.nan)
    # nan = 0 in num_75
    data['num_75'] = data['num_75'].fillna(0)

    # removing outliers
    data['num_985'] = data['num_985'].apply(lambda x: x if (x <= 11.0) else np.nan)
    # nan = 0 in num_985
    data['num_985'] = data['num_985'].fillna(0)

    # removing outliers
    data['num_100'] = data['num_100'].apply(lambda x: x if (x <= 75.0) else np.nan)
    # nan = 17 in num_100
    data['num_100'] = data['num_100'].fillna(14.0)

    # removing outliers
    data['num_unq'] = data['num_unq'].apply(lambda x: x if (x <= 69.0) else np.nan)
    #nan = 18 in num_unq
    data['num_unq'] = data['num_unq'].fillna(16.0)

    # removing outliers
    data['total_secs'] = data['total_secs'].apply(lambda x: x if (x <= 19476.59) else np.nan)
    # nan = 4548 in total_secs
    data['total_secs'] = data['total_secs'].fillna(4548.5495)

preprocessing(result)


import sys
import time
import unittest
from PublicPackage import HTMLTestRunnerCN, Email,Dingtalk

# 导入用例文件；导入数据文件;导入控件文件
sys.path.append('./Interface')
sys.path.append('./TestData')
sys.path.append('./TestCase')
sys.path.append('./PublicPackage')

# 指定测试用例为当前文件夹下的 interface 目录
test_dir = './TestCase'

# 执行所有用例将 pattern 参数改成 *
discover = unittest.defaultTestLoader.discover(test_dir, pattern='*_run.py')

if __name__ == "__main__":

  # 自动化报告文字修改、# 饼状图字体修改、# 生产报告时间
  report_title = '自动化接口测试报告'
  desc = '右侧饼状图展示通过率、失败率、错误率'

  now = time.strftime("%Y-%m-%d %H_%M_%S", time.localtime())
  report_file_now = 'TestReport/TestReport'+now+'.html'

  report_file = '/TestReport/TestReport.html'

  # 创建报告文件，打印报告数据

  with open(report_file, 'wb') as report:
      runner = HTMLTestRunnerCN.HTMLTestRunner(stream=report, title=report_title, description=desc)
      runner.run(discover)

  # 自动读取邮箱，发送邮件
  Email.email()

  # 钉钉群发消息
  Dingtalk.Send_Dingtalk()


import curses

# Initialize the curses screen
screen = curses.initscr()

# Set some basic screen options
curses.noecho()
curses.cbreak()
screen.keypad(True)

# Add some basic status information to the screen
screen.addstr(0, 0, "Fuzzing Status:")
screen.addstr(1, 0, "================")

# Define a function to update the status screen
def update_status(packet_count, crashes_found, unique_crashes_found):
    screen.addstr(3, 0, f"Packets sent: {packet_count}")
    screen.addstr(4, 0, f"Crashes found: {crashes_found}")
    screen.addstr(5, 0, f"Unique crashes found: {unique_crashes_found}")
    screen.refresh()

# Call the update_status function periodically to update the screen
update_status(100, 2, 1)

# Wait for user input before exiting
screen.getch()

# Restore the terminal settings
curses.nocbreak()
screen.keypad(False)
curses.echo()
curses.endwin()


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        # remove node at n-1, insert at 1
        # node 0 has node n
        # node 1 has node n-1

        # thoughts:
        # loop through nodes, find their tail node at the end of the linked list
        # change their next

        # find middle point of the linked list
        # reverse the second half of the linked list
        # combine the two linked list one after another.
        # Great problem that combines three linked list problems

        slow, fast = head, head.next
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

        secondHalfHead = slow.next
        prev = slow.next = None
        while secondHalfHead:
            temp = secondHalfHead.next
            secondHalfHead.next = prev
            prev = secondHalfHead
            secondHalfHead = temp

        # prev      curr    curr.next       temp
        #                                   temp = curr.next
        #                   curr.next = prev
        # prev = curr
        #          curr = temp

        firstHalfHead = head
        secondHalfHead = prev
        while secondHalfHead:
            # temp1 = firstHalfHead.next
            # firstHalfHead.next = secondHalfHead
            # firstHaflHead = temp1
            # temp2 = secondHalfHead.next
            # secondHalfHead.next = firstHalfHead
            # secondHalfHead = temp2
            temp1, temp2 = firstHalfHead.next, secondHalfHead.next
            firstHalfHead.next = secondHalfHead
            secondHalfHead.next = temp1
            firstHalfHead, secondHalfHead = temp1, temp2

        # first, second = head, prev
        # while second:
        #     tmp1, tmp2 = first.next, second.next
        #     first.next = second
        #     second.next = tmp1
        #     first, second = tmp1, tmp2