from django import forms

from applications.base.models import Comuna, Pais, Region
from applications.base.utils import validarRut
from applications.empresa.models import Afp, Apv, Banco, CajasCompensacion, MutualSecurity, Salud
from applications.remuneracion.models import Concept

class BanksForm(forms.ModelForm):

    tags_input_general = {
        'class': 'form-control',
    }

    ban_nombre = forms.CharField(label="Nombre", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    ban_codigo = forms.CharField(label="Código", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    ban_activo = forms.ChoiceField(initial='S', label='Banco Activo?', choices=Banco.OPCIONES,
                                   widget=forms.Select(attrs=tags_input_general), required=False)

    class Meta:
        model = Banco
        fields = (
            "ban_nombre", "ban_codigo", "ban_activo"
        )

class CountryForm(forms.ModelForm):

    tags_input_general = {
        'class': 'form-control',
    }

    tags_input_readonly = {
        'class': 'form-control',
        'readonly': 'readonly'
    }

    pa_nombre = forms.CharField(label="Nombre", widget=forms.TextInput(
        attrs=tags_input_readonly), required=True)
    pa_codigo = forms.IntegerField(label="Nombre", widget=forms.TextInput(
        attrs=tags_input_readonly), required=True)

    class Meta:
        model = Pais
        fields = (
            "pa_nombre", "pa_codigo"
        )

class RegionForm(forms.ModelForm):

    tags_input_readonly = {
        'class': 'form-control',
        'readonly': 'readonly'
    }

    tags_input_select2_readonly = {
        'class': 'form-control select2-show-search',
        'readonly': 'readonly'
    }

    re_nombre = forms.CharField(label="Nombre", widget=forms.TextInput(
        attrs=tags_input_readonly), required=True)
    pais = forms.ModelChoiceField(label="País", required=True,
                                  queryset=Pais.objects.all(), widget=forms.Select(attrs=tags_input_select2_readonly))
    re_numeroregion = forms.CharField(label="Sigla", widget=forms.TextInput(
        attrs=tags_input_readonly), required=False)
    re_numero = forms.IntegerField(label="N° región", widget=forms.TextInput(
        attrs=tags_input_readonly), required=True)

    class Meta:
        model = Region
        fields = (
            "re_nombre", "pais", "re_numeroregion", "re_numero"
        )

class CommuneForm(forms.ModelForm):

    tags_input_readonly = {
        'class': 'form-control',
        'readonly': 'readonly'
    }

    tags_input_select2_readonly = {
        'class': 'form-control select2-show-search',
        'readonly': 'readonly'
    }

    com_nombre = forms.CharField(label="Nombre", widget=forms.TextInput(
        attrs=tags_input_readonly), required=True)
    com_numero = forms.IntegerField(label="N° comuna", widget=forms.TextInput(
        attrs=tags_input_readonly), required=True)
    region = forms.ModelChoiceField(label="Región", required=True,
                                    queryset=Region.objects.all(), widget=forms.Select(attrs=tags_input_select2_readonly))

    class Meta:
        model = Comuna
        fields = (
            "com_nombre", "com_numero", "region"
        )

class AfpForm(forms.ModelForm):

    tags_input_general = {
        'class': 'form-control',
    }

    afp_codigoprevired = forms.CharField(label="Código Previred", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    afp_nombre = forms.CharField(label="Nombre", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    afp_tasatrabajadordependiente = forms.FloatField(label="Tasa trabajador Dependiente", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    afp_sis = forms.FloatField(label="Seguro de Invalidez y Sobrevivencia (SIS)", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    afp_tasatrabajadorindependiente = forms.FloatField(label="Tasa trabajador independiente", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    afp_activo = forms.ChoiceField(initial='S', label='Afp Activa?', choices=Afp.OPCIONES,
                                   widget=forms.Select(attrs=tags_input_general), required=False)

    class Meta:
        model = Afp
        fields = (
            "afp_codigoprevired", "afp_nombre", "afp_tasatrabajadordependiente", "afp_sis", "afp_tasatrabajadorindependiente", "afp_activo"
        )

class ApvForm(forms.ModelForm):

    tags_input_general = {
        'class': 'form-control',
    }

    apv_nombre = forms.CharField(label="Nombre", widget=forms.TextInput(
        attrs=tags_input_general), required=True)

    apv_nombrerazonsocial = forms.CharField(label="Razón Social", widget=forms.TextInput(
        attrs=tags_input_general), required=False)

    class Meta:
        model = Apv
        fields = (
            "apv_nombre", "apv_nombrerazonsocial"
        )

class SaludForm(forms.ModelForm):

    tags_input_readonly = {
        'class': 'form-control',
        'readonly': 'readonly'
    }

    tags_input_general = {
        'class': 'form-control',
    }

    sa_nombre = forms.CharField(label="Nombre", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    sa_codigo = forms.CharField(label="Código", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    sa_tipo = forms.ChoiceField(initial='F', label="Tipo Entidad?", choices=Salud.TIPO,
                                widget=forms.Select(attrs=tags_input_general), required=True)
    sa_activo = forms.ChoiceField(initial='S', label='Entidad de Salud Activa?', choices=Salud.OPCIONES,
                                  widget=forms.Select(attrs=tags_input_general), required=False)

    class Meta:
        model = Salud
        fields = (
            "sa_nombre", "sa_codigo", "sa_tipo", "sa_activo"
        )

class CajasCompensacionForm(forms.ModelForm):

    tags_input_readonly = {
        'class': 'form-control',
        'readonly': 'readonly'
    }

    tags_input_general = {
        'class': 'form-control',
    }

    cc_nombre = forms.CharField(label="Nombre", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    cc_codigo = forms.CharField(label="Código", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    cc_rut = forms.CharField(label="Rut", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    cc_activo = forms.ChoiceField(initial='S', label='Caja de Compensacion Activa?', choices=CajasCompensacion.OPCIONES,
                                  widget=forms.Select(attrs=tags_input_general), required=False)

    def clean_cc_rut(self):
        data = self.cleaned_data["cc_rut"]

        if not validarRut(data):
            self.add_error('cc_rut', "El rut no es valido")
        return data

    class Meta:
        model = CajasCompensacion
        fields = (
            "cc_nombre", "cc_codigo", "cc_rut", "cc_activo"
        )

class MutualSecurityForm(forms.ModelForm):

    tags_input_general = {
        'class': 'form-control',
    }

    ms_name = forms.CharField(label="Nombre", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    ms_rut = forms.CharField(label="Rut", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    ms_codeprevired = forms.CharField(label="Código", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    ms_active = forms.ChoiceField(initial='S', label='Activa?', choices=MutualSecurity.OPTIONS,
                                  widget=forms.Select(attrs=tags_input_general), required=False)

    def clean_ms_rut(self):
        data = self.cleaned_data["ms_rut"]

        if not validarRut(data):
            self.add_error('ms_rut', "El rut no es valido")
        return data

    class Meta:
        model = MutualSecurity
        fields = (
            "ms_name", "ms_rut", "ms_codeprevired", "ms_active"
        )

class ConceptsForm(forms.ModelForm):

    tags_input_general = {
        'class': 'form-control',
    }

    tags_input_select = {
        'class': 'form-control select2-one',
    }

    conc_name = forms.CharField(label="Nombre Concepto", widget=forms.TextInput(
        attrs=tags_input_general), required=True)
    conc_typeconcept = forms.ChoiceField(label="Tipo concepto", choices=Concept.TYPE_CLASSIFICATION,
                                widget=forms.Select(attrs=tags_input_select), required=True)
    conc_clasificationconcept = forms.ChoiceField(label="Clasificación concepto", choices=Concept.CLASSIFICATION,
                                widget=forms.Select(attrs=tags_input_select), required=True)
    conc_search_field = forms.ChoiceField(label="Tipo de entidad", help_text="** Este campo solo se debe usar para el caso de los descuentos de salud y afp", choices=Concept.SEARCH_FIELDS,
                                widget=forms.Select(attrs=tags_input_select), required=False)
    conc_remuneration_type = forms.ChoiceField(label="Tipo de remuneración", choices=Concept.REMUNERATION_TYPE,
                                widget=forms.Select(attrs=tags_input_select), required=False)

    class Meta:
        model = Concept
        fields = (
            "conc_name", "conc_typeconcept", "conc_clasificationconcept", "conc_search_field", "conc_remuneration_type"
        )


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Sun June 29 01:30:00 2014

@author: Chang Long Zhu
@email: changlongzj@gmail.com
"""

import sys
import actionlib
import rospy
import smach

from control_msgs.msg import PointHeadAction, PointHeadActionGoal, PointHeadResult, PointHeadActionGoal, PointHeadGoal
from move_joints_group import move_joints_group
from smach_ros.simple_action_state import SimpleActionState

POINTING_FRAME = 'head_mount_xtion_rgb_optical_frame'
#POINTING_FRAME = 'stereo_link'
TOPIC_ACTION = '/head_controller/point_head_action'

class prepare_move_head(smach.State):
    def __init__(self, point_to_look, frame_id):
        smach.State.__init__(self,
                             outcomes=['succeeded', 'aborted', 'preempted'],
                             input_keys=['standard_error', 'target_frame_id', 'target_point'],
                             output_keys=['standard_error', 'point_goal'])
        self.s_point_to_look = point_to_look #[x, y, z]
        self.s_frame_id = frame_id #base_link...
    def execute(self, userdata):
        rospy.loginfo('Executing Move head')

        frame_id = self.s_frame_id if self.s_frame_id else userdata.target_frame_id
        point_to_look = self.s_point_to_look if self.s_point_to_look else userdata.target_point

        look_goal = PointHeadGoal()
        look_goal.target.header.frame_id = frame_id
        look_goal.target.point.x = point_to_look[0]
        look_goal.target.point.y = point_to_look[1]
        look_goal.target.point.z = point_to_look[2]

        look_goal.pointing_frame = POINTING_FRAME
        if POINTING_FRAME == 'head_mount_xtion_rgb_optical_frame':
            look_goal.pointing_axis.x = 0.0
            look_goal.pointing_axis.y = 0.0
            look_goal.pointing_axis.z = 1.0
        elif POINTING_FRAME == 'stereo_link':
            look_goal.pointing_axis.x = 1.0
            look_goal.pointing_axis.y = 0.0
            look_goal.pointing_axis.z = 0.0

        look_goal.min_duration.secs = 1.0

        rospy.loginfo('Sending this goal: ' + str(look_goal))

        userdata.point_goal = look_goal

        return 'succeeded'

class move_head_to_point(smach.StateMachine):

    """
    This SM moves the head in order to look at a specified point

    Required parameters: None

    Optional parameters: None

    Output keys:
        @key standard_error: Error

    Input keys:
        @key target_frame_id: the frame_id in which the Point Specified is based. Example: 'base_link', 'stereo_link'.
        @key target_point: the Point [x, y, z] for the robot to look at.

    """
    def __init__(self, point_to_look=None, frame_id=None):
        smach.StateMachine.__init__(self,
                                    outcomes=['succeeded', 'aborted', 'preempted'],
                                    input_keys=['standard_error', 'target_frame_id', 'target_point'],
                                    output_keys=['standard_error', 'point_goal'])
        with self:
            # Preparation of the SM
            smach.StateMachine.add('prepare_move_head',
                                    prepare_move_head(point_to_look, frame_id),
                                    transitions={'succeeded':'send_look_to_point', 'preempted':'preempted', 'aborted':'aborted'})

            def point_head_result_cb(self, error, point_info):
                print('Point Head Result: ' + str(point_info))
                print('ERROR: ' + str(error))

            smach.StateMachine.add('send_look_to_point',
                                   SimpleActionState(TOPIC_ACTION,
                                                     PointHeadAction,
                                                     goal_key='point_goal',
                                                     exec_timeout=rospy.Duration(15.0),
                                                     result_cb=point_head_result_cb,
                                                     input_keys=['standard_error'],
                                                     output_keys=['standard_error']),
                                   transitions={'succeeded':'succeeded', 'preempted':'preempted', 'aborted':'aborted'})

def main(args):
    rospy.init_node('look_to_point')

    sm = smach.StateMachine(outcomes=['succeeded', 'preempted', 'aborted', 'end_searching'])
    with sm:
        smach.StateMachine.add(
            'gesture_state',
            move_head_to_point(point_to_look=[1, 1, 0], frame_id='stereo_link'),
            transitions={'succeeded': 'succeeded','preempted':'preempted', 'aborted':'aborted'})

    sm.execute()
    rospy.spin()

if __name__ == '__main__':
    main(sys.argv)


import numpy as np
from pysrvf.main_mean import get_data_mean
import time
# from scipy.io import savemat

### ----- 1d examples ----- ###
# Bumps
# Shape is (N x T)
# Xdata = np.load('../data/1d/two_bumps.npy')
# qmean, pmean, pmean_scaled, reformatted_Xdatam _ = get_data_mean(Xdata)

### ----- 2d examples ----- ###
# Dog curves
# Shape is (N x n x T)
Xdata = np.load('../data/3d/sine_curves.npy')
qmean, pmean, pmean_scaled, reformatted_Xdata, qarr, alpha_t_arr = get_data_mean(Xdata)

# 2d parametric curves
# Shape is (n x T x N)
# Xdata = np.load('../data/2d/misc.npy')
# t = time.time()
# # do stuff
# qmean, pmean, pmean_scaled, reformatted_Xdata, _ = get_data_mean(Xdata, subject_first = False)
# print(time.time() - t)

### ----- 3d examples ----- ###
# Xdata = np.load('../data/3d/sine_curves.npy')
# qmean, pmean, pmean_scaled, reformatted_Xdata, _ = get_data_mean(Xdata)

### Plot data and mean ###
import matplotlib.pyplot as plt
N, n, T = np.shape(reformatted_Xdata)

if n == 1:
	for c in reformatted_Xdata:
		plt.plot(range(T), c[0,:], alpha = 0.25)
	plt.plot(range(T), pmean_scaled[0,:], 'k--')
elif n == 2:
	for c in reformatted_Xdata:
		plt.plot(c[0,:], c[1,:], alpha = 0.4)
elif n == 3:
	from mpl_toolkits.mplot3d import Axes3D
	fig = plt.figure()
	ax = fig.add_subplot(111, projection='3d')
	for c in reformatted_Xdata:
		ax.plot(c[0,:], c[1,:], c[2,:], alpha = 0.4)
	ax.plot(pmean_scaled[0,:], pmean_scaled[1,:], pmean_scaled[2,:], 'k--')

plt.show()


#setup
'START BLOCK'
import pygame
import keyboard
import math

from sprites import *
from map import *

pygame.init()

screen = pygame.display.set_mode((1200,600))

running = True

clock = pygame.time.Clock()

font = pygame.font.Font(None,32)
'END BLOCK'

#environment
'START BLOCK'
groundshift = 0

#should only be used for rendering, not collisions or anything else
#IMPORTANT - THIS IS LITERALLY USED TO RENDER EVERYTHING IN THE ENTIRE GAME
camX = 600
#literally used for nothing
camY = 0

time = 0
day = 1
daycolor = (200,200,250)
'END BLOCK'

#players
'START BLOCK'
class player1:
    X = 0
    Y = 455

    direction = 'left'
    move = 'none'

    class sword:
        sprite = sword #not actually used

        sword = 0
        length = 0
        state = 'none'

        rect = sprite.get_rect()

    sprite = p1
    rect = sprite.get_rect()
    rect.topleft = (X,Y)

class player2:
    X = 0
    Y = 455

    direction = 'left'
    move = 'none'

    class sword:
        sprite = sword

        sword = 0
        length = 0
        state = 'none'

        rect = sprite.get_rect()

    sprite = p2
    rect = sprite.get_rect()
    rect.topleft = (X,Y)

screenX = 0

bothmoving = False

speed = 3

health = 100
'END BLOCK'

#enemies
'START BLOCK'
enemies = []

enemytimer = 500
'END BLOCK'

#main loop
while running:

    #quit
    'START BLOCK'
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    'END BLOCK'

    #environment
    'START BLOCK'
    #sky
    screen.fill(daycolor)

    time = time + 0.1

    #sunrise
    if time > 0 and time < 200:
        daycolor = (0+time,0+time,50+time)
    #day
    if time > 200 and time < 1000:
        daycolor = (200,200,250)
    #sunset
    if time > 1000 and time < 1200:
        daycolor = (200-time+1000,200-time+1000,250-time+1000)
    #night
    if time > 1200 and time < 2000:
        daycolor = (0,0,50)
    if time > 2000:
        time = 0
        day = day + 1

    #ground
    for i in range (17):
        if bothmoving:
            groundshift = camX%80
        screen.blit(ground,(-80+i*80+groundshift,camY+500))

    #houses
    for houseX in houseXs:
        screen.blit(house,(camX+houseX,camY+400))
    for doorX in doorXs:
        screen.blit(doorsprite,(camX+doorX,camY+450))

    #grass
    for grass in grassdata:
        if camX+grass['X'] > -100 and camX+grass['X'] < 1300:
            if grass['type'] == 0:
                grasssprite = grass1
            if grass['type'] == 1:
                grasssprite = grass2
            screen.blit(grasssprite,(camX+grass['X'],camY+490))
    'END BLOCK'

    #die
    'START BLOCK'
    if health <= 0:
        running = False
    'END BLOCK'

    #movement
    'START BLOCK'
    #p1
    a = keyboard.is_pressed('a')
    d = keyboard.is_pressed('d')

    #p2
    left = keyboard.is_pressed('left')
    right = keyboard.is_pressed('right')

    #p1
    if a != d:
        if a:
            player1.X = player1.X - speed
            player1.move = 'left'
            player1.direction = 'left'
        if d:
            player1.X = player1.X + speed
            player1.move = 'right'
            player1.direction = 'right'

    else:
        player1.move = 'none'

    #p2
    if left != right:
        if left:
            player2.X = player2.X - speed
            player2.direction = 'left'
            player2.move = 'left'
        if right:
            player2.X = player2.X + speed
            player2.move = 'right'
            player2.direction = 'right'

    else:
        player2.move = 'none'

    #p1
    if camX+player1.X < 50:
        player1.X = 50 - camX
    if camX+player1.X > 1130:
        player1.X = 1130 - camX

    #p2
    if camX+player2.X < 50:
        player2.X = 50 - camX
    if camX+player2.X > 1130:
        player2.X = 1130 - camX

    #rect used for collisions
    player1.rect = player1.sprite.get_rect()
    player1.rect.topleft = (player1.X,player1.Y)

    player2.rect = player2.sprite.get_rect()
    player2.rect.topleft = (player2.X,player2.Y)

    #camera
    if player1.move == player2.move:
        if player1.move == 'left':
            camX = camX + 3
        if player1.move == 'right':
            camX = camX - 3

        if not player1.move == 'none':
            bothmoving = True

    if player1.direction == 'right':
        screen.blit(pygame.transform.scale(player1.sprite,(20,45)),(camX+player1.X,camY+player1.Y))
    if player1.direction == 'left':
        screen.blit(pygame.transform.flip(pygame.transform.scale(player1.sprite,(20,45)),True,False),(camX+player1.X,camY+player1.Y))
    if player2.direction == 'right':
        screen.blit(pygame.transform.scale(player2.sprite,(20,45)),(camX+player2.X,camY+player2.Y))
    if player2.direction == 'left':
        screen.blit(pygame.transform.flip(pygame.transform.scale(player2.sprite,(20,45)),True,False),(camX+player2.X,camY+player2.Y))
    'END BLOCK'

    #sword
    'START BLOCK'
    #p1
    if player1.sword.sword > 0:
        player1.sword.sword = player1.sword.sword - 1

    if player1.sword.sword < 0:
        player1.sword.sword = player1.sword.sword + 1
        if player1.sword.sword == 0:
            player1.sword.sword = 30

    if keyboard.is_pressed('w'):
        if player1.sword.sword == 0:
            player1.sword.sword = -30
            player1.sword.length = 0
            player1.sword.state = 'out'

    if player1.sword.sword < 0:
        if player1.sword.state == 'out':
            player1.sword.length = player1.sword.length + 1
            if player1.sword.length == 15:
                player1.sword.state = 'in'

        if player1.sword.state == 'in':
            player1.sword.length = player1.sword.length - 1

        if player1.direction == 'left':
            screen.blit(sword,(camX+player1.X-20-player1.sword.length,camY+player1.Y+10))
            player1.sword.rect.topleft = (player1.X-20-player1.sword.length,player1.Y+10)
        if player1.direction == 'right':
            screen.blit(pygame.transform.flip(sword,True,False),(camX+player1.X+10+player1.sword.length,camY+player1.Y+10))
            player1.sword.rect.topleft = (player1.X+10+player1.sword.length,player1.Y+10)

    #p2
    if player2.sword.sword > 0:
        player2.sword.sword = player2.sword.sword - 1

    if player2.sword.sword < 0:
        player2.sword.sword = player2.sword.sword + 1
        if player2.sword.sword == 0:
            player2.sword.sword = 30

    if keyboard.is_pressed('up'):
        if player2.sword.sword == 0:
            player2.sword.sword = -30
            player2.sword.length = 0
            player2.sword.state = 'out'

    if player2.sword.sword < 0:
        if player2.sword.state == 'out':
            player2.sword.length = player2.sword.length + 1
            if player2.sword.length == 15:
                player2.sword.state = 'in'

        if player2.sword.state == 'in':
            player2.sword.length = player2.sword.length - 1

        if player2.direction == 'left':
            screen.blit(sword,(camX+player2.X-20-player2.sword.length,camY+player2.Y+10))
            player2.sword.rect.topleft = (player2.X-20-player2.sword.length,camY+player2.Y+10)
        if player2.direction == 'right':
            screen.blit(pygame.transform.flip(sword,True,False),(camX+player2.X+10+player2.sword.length,camY+player2.Y+10))
            player2.sword.rect.topleft = (player2.X+10+player2.sword.length,camY+player2.Y+10)
    'END BLOCK'

    #enemy spawning
    'START BLOCK'
    enemytimer = enemytimer - 1

    #spawn enemies
    if enemytimer < 1:
        if random.randint(0,1) == 1:
            enemyX = -100
        else:
            enemyX = 1300

        enemies.append({'type':'normal',
                        'X':enemyX-camX,'Y':460+camY,'direction':'left','knockback':0,
                        'target':'none','targettimer':0,
                        'health':2,'hurttimer':0,
                        'attacktimer':0,'damage':1})

        enemytimer = random.randint(200,350)

    #clear dead enemies
    for enemy in enemies:
        if enemy['health'] < 1:
            enemies.remove(enemy)
    'END BLOCK'

    #enemy AI
    'START BLOCK'
    for enemy in enemies:

        if enemy['type'] == 'normal':
            enemyrect = zombie1.get_rect()
            enemyrect.topleft = (enemy['X'],enemy['Y'])

            #whether or not the zombie can take damage
            if enemy['hurttimer'] > 0:
                enemy['hurttimer'] = enemy['hurttimer'] - 1

            #targeting
            if enemy['targettimer'] > 0:
                enemy['targettimer'] = enemy['targettimer'] - 1

            if enemy['targettimer'] == 0:
                if math.dist(enemyrect.center,player1.rect.center) > math.dist(enemyrect.center,player2.rect.center):
                    enemy['target'] = '2'
                    enemy['targettimer'] = 120
                if math.dist(enemyrect.center,player2.rect.center) > math.dist(enemyrect.center,player1.rect.center):
                    enemy['target'] = '1'
                    enemy['targettimer'] = 120

            #chase
            if enemy['target'] == '1' and not abs(enemyrect.centerx-player1.rect.centerx) < 1:
                if enemyrect.centerx > player1.rect.centerx:
                    enemy['X'] = enemy['X'] - 1
                    enemy['direction'] = 'left'
                if enemyrect.centerx < player1.rect.centerx:
                    enemy['X'] = enemy['X'] + 1
                    enemy['direction'] = 'right'

            if enemy['target'] == '2' and not abs(enemyrect.centerx-player2.rect.centerx) < 15:
                if enemyrect.centerx > player2.rect.centerx:
                    enemy['X'] = enemy['X'] - 1
                    enemy['direction'] = 'left'
                if enemyrect.centerx < player2.rect.centerx:
                    enemy['X'] = enemy['X'] + 1
                    enemy['direction'] = 'right'

            #when hit
            if (enemyrect.colliderect(player1.sword.rect) and player1.sword.sword < 0) or (enemyrect.colliderect(player2.sword.rect) and player2.sword.sword < 0):
                if enemy['hurttimer'] == 0:
                    enemy['health'] = enemy['health'] - 1
                    enemy['knockback'] = 7
                    enemy['hurttimer'] = 40

            #takes knockback
            if enemy['knockback'] > 0:
                if enemy['direction'] == 'left':
                    enemy['X'] = enemy['X'] + enemy['knockback']
                if enemy['direction'] == 'right':
                    enemy['X'] = enemy['X'] - enemy['knockback']

                enemy['knockback'] = enemy['knockback'] - 1

            #attack
            if enemy['target'] == '1':
                if abs(enemyrect.centerx-player1.rect.centerx) < 30:
                    if enemy['attacktimer'] == 0:
                        enemy['attacktimer'] = 40
                    else:
                        enemy['attacktimer'] = enemy['attacktimer'] - 1
                        if enemy['attacktimer'] == 0:
                            health = health - enemy['damage']

            if enemy['target'] == '2':
                if abs(enemyrect.centerx-player2.rect.centerx) < 30:
                    if enemy['attacktimer'] == 0:
                        enemy['attacktimer'] = 40
                    else:
                        enemy['attacktimer'] = enemy['attacktimer'] - 1
                        if enemy['attacktimer'] == 0:
                            health = health - enemy['damage']

            #draws the sprite
            if enemy['direction'] == 'left':
                screen.blit(pygame.transform.flip(zombie1,True,False),(camX+enemy['X'],camY+enemy['Y']))
            if enemy['direction'] == 'right':
                screen.blit(zombie1,(camX+enemy['X'],camY+enemy['Y']))
    'END BLOCK'

    #displays
    'START BLOCK'
    healthdisplay = font.render(str(health),True,(0,0,0))
    screen.blit(heart,(30,30))
    screen.blit(healthdisplay,(60,30))
    'END BLOCK'

    #necessary stuff
    'START BLOCK'
    pygame.display.update()
    clock.tick(60)
    'END BLOCK'

#quit
pygame.quit()


import json
import random
def zero():
    puti = "D:\\нейронка\\pamiati\\"
    t = 100
    k = 0
    p = 0
    mas = []
    for j in range(49):
        j = str(j)
        hp = json.load(open(puti + j + 'hp.txt', 'r'))
        json.dump(0, open(puti + j + 'str.txt', 'w', encoding="UTF-8"))
        if hp > 0:
            mas.append(j)
            json.dump(100, open(puti + j + 'hp.txt', 'w', encoding="UTF-8"))
    mos = json.load(open(puti + str(mas[len(mas)-1]) + '.txt', 'r'))
    x = random.randint(1, 5)
    for j in range(x):
        r = random.randint(0, 58)
        mos[r]=random.randint(0, 44)
    for j in range(49):
        j = str(j)
        hp = json.load(open(puti + j + 'hp.txt', 'r'))
        if hp <= 0:
            json.dump(100, open(puti + j + 'hp.txt', 'w', encoding="UTF-8"))
            cikl = json.load(open(puti + mas[k] + '.txt', 'r'))
            #print(k)
            json.dump(cikl, open(puti + j + '.txt', 'w', encoding="UTF-8"))
            if p == 6:
                k+=1
                p=0
            p+=1

нейронка/zero.py


from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import CreateView, DeleteView
from django.db.models import F, Q
from django.http import HttpResponse
import csv
from datetime import datetime, date, timedelta
from django.core.paginator import Paginator

from .models import Booking
from .forms import VenderBookingForm, CadastrarBookingForm, EditarBookingForm

# Create your views here.
@login_required(login_url='/login/')
def Index(request):
    bookings = Booking.objects.all()
    queryset = request.GET.get('q')
    if queryset:
        bookings = Booking.objects.filter(
            Q(number_booking__icontains=queryset))

    return render (request, 'booking/index.html', {'bookings': bookings})

class BookingCreate(SuccessMessageMixin,CreateView):
    today = date.today()
    model = Booking
    form_class = CadastrarBookingForm
    template_name = 'booking/cadastrar-booking.html'
    success_url = '/'
    success_message = 'Booking Cadastrado com sucesso!!!!'

    def form_valid(self, form):
        form.instance.status = 'Vazio'
        form.instance.cadastrado_por = self.request.user
        return super(BookingCreate, self).form_valid(form)

@login_required(login_url='/login/')
def EditarBookingDisponivel(request, id=None):
    booking = get_object_or_404(Booking, id=id)
    form = EditarBookingForm(request.POST or None, instance=booking)
    if form.is_valid():
        obj = form.save()
        obj.save()
        messages.success(request, 'Booking editado com sucesso.')
        return redirect('/')
    return render(request, 'booking/editar-booking-disponivel.html', {'form': form})

@login_required(login_url='/login/')
def ListaBookingDisponivel(request):
    from django.db.models.functions import ExtractDay
    from django.db.models import F, Func
    from django.db.models import Avg, F
    if request.user.funcionario.escritorio:
        bookings = Booking.objects.filter(status='Vazio').filter(escritorio=request.user.funcionario.escritorio)

        queryset = request.GET.get('q')
        if queryset:
            bookings = Booking.objects.filter(
                Q(number_booking__icontains=queryset)).filter(status='Vazio')
    else:
        bookings = Booking.objects.filter(status='Vazio')
        queryset = request.GET.get('q')
        if queryset:
            bookings = Booking.objects.filter(
                Q(number_booking__icontains=queryset)).filter(status='Vazio')

    paginator = Paginator(bookings, 10)  # Show 25 contacts per page

    page = request.GET.get('page')
    bookings = paginator.get_page(page)

    return render (request, 'booking/lista-booking-disponivel.html', {'bookings': bookings})

@login_required(login_url='/login/')
def RemoverBookingDisponivel(request, id=None):
    booking = get_object_or_404(Booking, id=id)
    if request.method == "POST":
        booking.delete()
        messages.success(request, 'Booking removido com sucesso!')
        return redirect('/booking/lista-booking-disponivel/')
    return render(request, 'booking/deletar-booking-disponivel.html', {'booking': booking})

@login_required(login_url='/login/')
def ListaBookingVendido(request):
    #Exibi a lista com apenas os bookings da filial do funcionario )
    if request.user.funcionario.escritorio:
        bookings = Booking.objects.filter(status='Vendido').filter(escritorio=request.user.funcionario.escritorio)
        queryset = request.GET.get('q')
        if queryset:
            bookings = Booking.objects.filter(
                Q(number_booking__icontains=queryset)).filter(status='Vendido')
    #Exibi a lista contendo todos os bookings
    else:
        bookings = Booking.objects.filter(status='Vendido')
        queryset = request.GET.get('q')
        if queryset:
            bookings = Booking.objects.filter(
                Q(number_booking__icontains=queryset)).filter(status='Vendido')
    return render (request, 'booking/lista-booking-vendido.html', {'bookings': bookings})

@login_required(login_url='/login/')
def RemoverBookingVendido(request, id=None):
    booking = get_object_or_404(Booking, id=id)
    if request.method == "POST":
        booking.delete()
        messages.success(request, 'Booking removido com sucesso!')
        return redirect('/booking/lista-booking-vendido/')
    return render(request, 'booking/deletar-booking-vendido.html', {'booking': booking})

@login_required(login_url='/login/')
def VenderBooking(request, id=None):
    booking = get_object_or_404(Booking, id=id)
    form = VenderBookingForm(request.POST or None, instance=booking)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.status = 'Vendido'
        obj.vendido_por = request.user
        obj.save()
        messages.success(request, 'Booking vendido com sucesso')
        return redirect('/')
    return render(request, 'booking/vender-booking.html', {'form': form})

@login_required(login_url='/login/')
def EditarBookingVendido(request, id=None):
    booking = get_object_or_404(Booking, id=id)
    form = CadastrarBookingForm(request.POST or None, instance=booking)
    if form.is_valid():
        obj = form.save()
        obj.save()
        messages.success(request, 'Booking editado com sucesso.')
        return redirect('/')
    return render(request, 'booking/editar-booking-vendido.html', {'form': form})

@login_required(login_url='/login/')
def VisualizarBookingVendido(request):
    booking = request.GET.get('id')
    if booking:
        booking = Booking.objects.get(id=booking)
    return render(request, 'booking/visualizar-booking-vendido.html',{'booking': booking})

@login_required(login_url='/login/')
def VisualizarBookingDisponivel(request):
    booking = request.GET.get('id')
    if booking:
        booking = Booking.objects.get(id=booking)
    return render(request, 'booking/visualizar-booking-disponivel.html',{'booking': booking})

def ExportarCSV(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="relatorio-booking.csv"'

    bookings = Booking.objects.filter(escritorio=request.user.funcionario.escritorio)

    writer = csv.writer(response)
    writer.writerow(['id','number_booking','pol','pod','navio','commodity','eta','armador','quantidade','type','status',
                     'cotacao','shipper','contrato_venda','cadastrado_por','data_cadastro','vendido_por','data_venda',
                     'escritorio','data_ddl_draft','hora_ddl_draft','observacoes'
                     ])
    for booking in bookings:
        writer.writerow([booking.id ,booking.number_booking,booking.pol,booking.pod,booking.navio,booking.commodity,
                         booking.eta ,booking.armador, booking.quantidade, booking.type, booking.status, booking.cotacao,
                         booking.shipper, booking.contrato_venda, booking.cadastrado_por, booking.data_cadastro,
                         booking.vendido_por, booking.data_venda, booking.escritorio,booking.data_ddl_draft,
                         booking.hora_ddl_draft ,booking.observacoes
                         ])
    return response


# © 2021 - today Numigi (tm) and all its contributors (https://bit.ly/numigiens)
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).

from odoo.addons.test_http_request.common import mock_odoo_request
from odoo.tests.common import TransactionCase
from ..controllers.portal import PortalChatterWithAttachments

class TestControllers(TransactionCase):
    def setUp(self):
        super().setUp()
        self.controller = PortalChatterWithAttachments()
        self.task = self.env["project.task"].create({"name": "My Task"})
        self.res_model = "project.task"
        self.res_id = self.task.id
        self.message = "Hello"
        self.initial_message_count = self._get_message_count()
        self.headers = {
            "Referer": "localhost/my/task",
            "Content-Type": "multipart/form-data",
        }

    def test_portal_chatter_post(self):
        with mock_odoo_request(self.env, headers=self.headers):
            self.controller.portal_chatter_post(
                self.res_model, self.res_id, self.message
            )

        assert self._get_message_count() == self.initial_message_count + 1

    def _get_message_count(self):
        return len(self.task.message_ids)


class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        def distance(x2,y2):
            # x1,y1 are 0,0 origin
            return ((x2-0)**2 + (y2-0)**2)**0.5

        heap = []

        # O(nlogn)
        for idx, (x2,y2) in enumerate(points):
            heappush(heap,(distance(x2,y2), [x2,y2]))
        ans = []
        # O(klogn)
        for i in range(k):
            ans.append(heappop(heap)[1])
        return ans

Arrays, Matrix, Stack, Queue, Heaps/P973 - kClosestPointsToOrigin.py


import random
import time
while True:
    print(""" 1. Roll the dice                 2.Exit         """)
    user = int(input("Select an option\n"))
    if user == 1:
        number = random.randint(1,6)
        print("rolling ...")
        time.sleep(5)
        print("Done")
        time.sleep(2)
        print(number)
        break
    else:
        break


import logging

from aiogram import types
from aiogram.dispatcher import FSMContext

from keyboards.inline import dynamic_keyboards
from loader import dp
from states.states import *
from utils.db_api.python_mysql import mysql_connection

@dp.message_handler(content_types="any", state=AddInformation.all_states)
async def add_money(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    msg_text = message.text
    conn = mysql_connection()
    c = conn.cursor(buffered=True)
    state_name = await state.get_state()
    state_data = await state.get_data()
    logging.info(f'{user_id} {msg_text}')
    info_type = state_data.get('info_type')
    param_id = state_data.get('param_id')
    brand_id = state_data.get('brand_id')
    if info_type == 'params':
        for one_param in msg_text.split("\n"):
            one_param = one_param.strip()
            if one_param:
                c.execute("select count(*) from options where option_name = %s and param_id = %s",
                          (one_param, param_id))
                if not c.fetchone()[0]:
                    c.execute("insert into options (param_id, option_name) values (%s, %s)",
                              (param_id, one_param))
                    conn.commit()
    elif info_type == 'options':
        for one_param in msg_text.split("\n"):
            one_param = one_param.strip()
            c.execute("select option_id from options where param_id = %s and option_name = %s",
                      (param_id, one_param,))
            option_id = c.fetchone()[0]
            c.execute("select category_id from brands where brand_id = %s",
                      (brand_id,))
            category_id = c.fetchone()[0]
            if one_param:
                c.execute("select count(*) from brand_params "
                          "where brand_id = %s and param_id = %s and option_id = %s",
                          (brand_id, param_id, option_id))
                if not c.fetchone()[0]:
                    c.execute("insert into brand_params (param_id, brand_id, option_id, category_id) "
                              "values (%s, %s, %s, %s)",
                              (param_id, brand_id, option_id, category_id))
                    conn.commit()
    elif info_type == 'brands':
        c.execute("select category_id, is_serial, is_model, parent_id from brands where brand_id = %s", (brand_id,))
        category_id, parent_is_serial, parent_is_model, parent_parent_id = c.fetchone()
        if parent_is_serial:
            is_serial = 0
            is_model = 1
        elif parent_is_model:
            raise
        else:
            is_serial = 1
            is_model = 0
        for one_param in msg_text.split("\n"):
            one_param = one_param.strip()
            if one_param:
                c.execute("select count(*) from brands where brand_name = %s and parent_id = %s",
                          (one_param, brand_id))
                if not c.fetchone()[0]:
                    c.execute("insert into brands (category_id, parent_id, brand_name, is_serial, is_model) "
                              "values (%s, %s, %s, %s, %s)",
                              (category_id, brand_id, one_param, is_serial, is_model))
                    conn.commit()
    elif info_type == 'brands_params':
        for one_model in msg_text.split("\n"):
            one_model = one_model.strip()
            param_params = one_model.split('  ')

            model_name = param_params[0].strip()
            model_params = param_params[1:]

            c.execute("select count(*) from brands where brand_name = %s and parent_id = %s", (model_name, brand_id))
            if not c.fetchone()[0]:
                c.execute("insert into brands (brand_name, parent_id) values (%s, %s)",
                          (model_name, brand_id))
                conn.commit()
            c.execute("select brand_id, category_id "
                      "from brands where brand_name = %s and parent_id = %s", (model_name, brand_id))
            model_id, category_id = c.fetchone()
            for one_param in model_params:
                one_param = one_param.strip()
                c.execute("select param_id, option_id from options where option_name = %s",
                          (one_param,))
                try:
                    param_id, option_id = c.fetchone()
                    c.execute("select count(*) from brand_params "
                              "where param_id = %s and option_id = %s and brand_id = %s",
                              (param_id, option_id, model_id))

                    # assert 1 == 0
                    if not c.fetchone()[0]:
                        c.execute("insert into brand_params (category_id, brand_id, param_id, "
                                  "option_id, param_position) "
                                  "values (%s, %s, %s, %s, %s)",
                                  (category_id, model_id, param_id, option_id,
                                   1 if param_id == 1 else (3 if param_id == 2 else 0)))
                    conn.commit()
                except Exception as e:
                    logging.info(f'{e, model_name, one_param}')
                    pass
    await message.answer("Успех ✅")
    if info_type == 'params':
        await message.answer(f'Выберите параметр',
                             reply_markup=await dynamic_keyboards.params_for_admin(c))
    elif info_type in ('brands', 'brands_params'):
        await message.answer(f'Выберите бренд',
                             reply_markup=await dynamic_keyboards.brands_for_admin(c))
    c.close()
    conn.close()


"""
    Unit tests over parameter combinations of the library.

    TODO ADD MORE
"""
from minorminer import find_embedding as find_embedding_orig
from warnings import warn
import os
import sys
import time

# Given that this test is in the tests directory, the calibration data should be
# in a sub directory. Use the path of this source file to find the calibration
calibration_dir = os.path.join(os.path.dirname(
    os.path.abspath(__file__)), "calibration")

def find_embedding(Q, A, return_overlap=False, **args):
    args['verbose'] = 0
    args['tries'] = 1
    if return_overlap:
        emb, succ = find_embedding_orig(
            Q, A, return_overlap=return_overlap, **args)
        if not succ:
            return emb, succ
        elif check_embedding(Q, A, emb, **args):
            if check_embedding.warning:
                warn(check_embedding.warning, RuntimeWarning)
            return emb, succ
        else:
            raise RuntimeError(
                "bad embedding reported as success (%s)" % (check_embedding.errcode))
    else:
        emb = find_embedding_orig(Q, A, return_overlap=return_overlap, **args)
        if emb:
            if not check_embedding(Q, A, emb, **args):
                raise RuntimeError(
                    "bad embedding reported as success (%s)" % (check_embedding.errcode))
            elif check_embedding.warning:
                warn(check_embedding.warning, RuntimeWarning)
        return emb

def check_embedding(Q, A, emb, **args):
    from networkx import Graph, is_connected
    check_embedding.warning = None
    Qg = Graph()
    Ag = Graph()
    Qg.add_edges_from(Q)
    Ag.add_edges_from(A)

    qubhits = 0
    footprint = set()
    var = {}
    for x in Qg:
        try:
            embx = emb[x]
        except KeyError:
            check_embedding.errcode = "missing chain"
            return False
        for q in embx:
            var[q] = x
        footprint.update(embx)
        qubhits += len(embx)
        if not is_connected(Ag.subgraph(embx)):
            check_embedding.errcode = "broken chain for %s: (%s)" % (x, embx)
            return False
    if len(footprint) != qubhits:
        check_embedding.errcode = "overlapped chains"
        return False

    Qv = Graph()
    for p, q in Ag.edges():
        try:
            Qv.add_edge(var[p], var[q])
        except KeyError:
            continue
    for x, y in Qg.edges():
        if not Qv.has_edge(x, y):
            check_embedding.errcode = "missing edge"
            return False

    for x, chain in args.get("fixed_chains", {}).items():
        if set(chain) != set(emb[x]):
            check_embedding.errcode = "fixed chain mismatch"
            return False
    for x, domain in args.get("restrict_chains", {}).items():
        if not set(domain) >= set(emb[x]):
            check_embedding.warning = "restrict chain mismatch"

    return True

def Path(n):
    return [(i, i + 1) for i in range(n - 1)]

def Grid(n):
    return [((x, y), (x + dx, y + dy)) for a in range(n) for b in range(n - 1) for (x, y, dx, dy) in [(a, b, 0, 1), (b, a, 1, 0)]]

def Clique(n):
    return [(u, v) for u in range(n) for v in range(u)]

def Biclique(n):
    return [(u, v) for u in range(n) for v in range(n, 2 * n)]

def Chimera(n, l=4):
    return [((x, y, u, k), (x + dx, y + dy, u, k))
            for a in range(n)
            for b in range(n - 1)
            for k in range(l)
            for x, y, u, dx, dy in [(b, a, 0, 1, 0), (a, b, 1, 0, 1)]
            ] + [((x, y, 0, k), (x, y, 1, kk)) for x in range(n) for y in range(n) for k in range(l) for kk in range(l)]

def NAE3SAT(n):
    import networkx
    from math import ceil
    from random import seed, randint
    seed(18293447845779813366)
    c = int(ceil(sum(randint(1, ceil(n * 4.2)) for _ in range(100)) / 100.))
    return networkx.generators.k_random_intersection_graph(c, n, 3).edges()

def ChordalCycle(p):
    import networkx
    G = networkx.generators.chordal_cycle_graph(p)
    G.remove_edges_from(list(G.selfloop_edges()))
    return G.edges()

def GeometricGraph(n, pos=None):
    import networkx
    G = networkx.generators.geometric.random_geometric_graph(
        n, n**-.333, dim=2, pos=pos)
    if pos is not None:
        for g in G:
            if len(list(G[g])) == 0:
                del pos[g]
    return G.edges()

def CartesianProduct(n):
    import networkx
    K = networkx.generators.complete_graph(n)
    return networkx.product.cartesian_product(K, K).edges()

def GridChimeraEmbedding(n):
    emb = {}
    M = [[0, 2, 2, 0], [1, 3, 3, 1], [1, 3, 3, 1], [0, 2, 2, 0]]
    for x in range(n):
        for y in range(n):
            emb[x, y] = [(x // 2, y // 2, 0, M[x % 4][y % 4]),
                         (x // 2, y // 2, 1, M[y % 4][x % 4])]
    return emb

def mask_wxw(n, w=2, l=4):
    return {(X // w, Y // w): [(x, y, u, k) for x in range(X, X + w) for y in range(Y, Y + w) for u in (0, 1) for k in range(l)] for X in range(0, n, w) for Y in range(0, n, w)}

success_count_functions = []

def success_count(n, *a, **k):
    from functools import wraps
    from math import log

    def count_successes(f):
        global success_count_functions
        success_count_functions.append([f, n, a, k])
        if os.path.exists(os.path.join(calibration_dir, f.__name__)):
            S, N = load_success_count_calibration(f)
            N += (S == N)
            accept_prob = .01  # 1% false negative rate
            tts = int(log(accept_prob * S / N, 1 - S / N) + 1)
            false_prob = (S / N) * (1 - S / N)**tts

            @wraps(f)
            def test_run():
                for i in range(tts):
                    if f(*a, **k):
                        break
                else:
                    assert False, "took %d tries without success, this should only happen %.02f%% of the time" % (
                        tts, false_prob * 100)
        else:
            def test_run():
                raise RuntimeError(
                    "%s is not calibrated -- run calibrate_all() or calibrate_new()" % (f.__name__))

        test_run.original = f
        return test_run
    return count_successes

def calibrate_success_count(f, n, a, k, directory=calibration_dir, M=None):
    succ = 0
    if M is None:
        M = 10000
    N = M * n
    print("calibrating %s, %d trials " % (f.__name__, N))
    t0 = time.clock()
    for i in range(N):
        if i % (N / 10) == 0:
            print("%d " % (10 * i // N))
            sys.stdout.flush()
        succ += bool(f(*a, **k))
    print()
    dt = time.clock() - t0
    print("%s: %.04e per trial; success rate %.01f%% " %
          (f.__name__, dt / N, succ * 100. / N))
    if directory != calibration_dir and os.path.exists(os.path.join(calibration_dir, f.__name__)):
        olds, oldn = load_success_count_calibration(f)
        print("standard is %.01f%%" % (olds * 100. / oldn))
    else:
        print()
    with open(os.path.join(directory, f.__name__), "w") as cal_f:
        cal_f.write(repr((succ, float(N))))

def load_success_count_calibration(f, directory=calibration_dir):
    with open(os.path.join(directory, f.__name__)) as cal_f:
        return eval(cal_f.read())

def calibrate_all(directory=calibration_dir, M=None):
    global success_count_functions

    if not os.path.exists(directory):
        os.mkdir(directory)

    for f, n, a, k in success_count_functions:
        calibrate_success_count(f, n, a, k, directory=directory, M=M)
        print()

def calibrate_new(directory=calibration_dir, M=None):
    for f, n, a, k in success_count_functions:
        if os.path.exists(os.path.join(directory, f.__name__)):
            continue
        else:
            calibrate_success_count(f, n, a, k, directory=directory, M=M)

def success_perfect(n, *a, **k):
    from functools import wraps

    def is_perfect(f):
        @wraps(f)
        def test_run():
            for _ in range(n):
                assert bool(f(*a, **k)), "test fail"
        test_run.original = f
        return test_run
    return is_perfect

def success_bounce(n, *a, **k):
    from functools import wraps

    def is_perfect(f):
        @wraps(f)
        def test_run():
            succs = sum(bool(f(*a, **k)) for _ in range(n))
            assert False, "%d successes out of %d trials" % (succs, n)
        test_run.original = f
        return test_run
    return is_perfect

def check_args(prob, hard, initial_chains=None, fixed_chains=None, restrict_chains=None, skip_initialization=False):
    import networkx
    probg = networkx.Graph()
    probg.add_edges_from(prob)

    hardg = networkx.Graph()
    hardg.add_edges_from(hard)

    assert networkx.is_connected(hardg), "hardware graph not connected"
    assert networkx.is_connected(probg), "problem graph not connected"

    if fixed_chains is not None:
        for v, chain in fixed_chains.items():
            assert probg.has_node(
                v), "fixed_chains vars not contained in problem graph"
            for q in chain:
                assert hardg.has_node(
                    q), "fixed_chains chains not contained in hardware graph"
        if initial_chains is not None:
            for v in fixed_chains:
                assert v not in initial_chains, "fixed_chains chains overwrite initial chains"
        if restrict_chains is not None:
            for v in fixed_chains:
                assert v not in restrict_chains, "fixed_chains chains are restricted"

    if initial_chains is not None:
        for v, chain in initial_chains.items():
            assert probg.has_node(
                v), "initial vars not contained in problem graph"
            for q in chain:
                assert hardg.has_node(
                    q), "initial chains not contained in hardware graph"
        if skip_initialization:
            for u, v in probg.edges():
                edgelord = {z for q in initial_chains[v] for z in hardg.neighbors(
                    q)} | set(initial_chains[v])
                assert set(
                    initial_chains[u]) & edgelord, "%s and %s are connected as variables but not as initials" % (u, v)

    if restrict_chains is not None:
        fullset = set(hardg.nodes())
        for v, chain in restrict_chains.items():
            assert probg.has_node(
                v), "restricted vars not contained in problem graph"
            for q in chain:
                assert hardg.has_node(
                    q), "restricted chains not contained in hardware graph"
        for u, v in probg.edges():
            edgelord = {z for q in restrict_chains.get(v, fullset) for z in hardg.neighbors(
                q)} | set(restrict_chains.get(v, fullset))
            assert set(restrict_chains.get(
                u, fullset)) & edgelord, "%s and %s are connected as variables but not as domains" % (u, v)

@success_count(100, 5)
def test_path_label_00(n):
    p = Path(n)
    return find_embedding(p, p)

@success_count(100, 5)
def test_path_label_01(n):
    p = Path(n)
    L = [str(i) for i in range(n)]
    Lp = [(L[x], L[y]) for x, y in p]
    return find_embedding(p, Lp)

@success_count(100, 5)
def test_path_label_10(n):
    p = Path(n)
    L = [str(i) for i in range(n)]
    Lp = [(L[x], L[y]) for x, y in p]
    return find_embedding(Lp, p)

@success_count(100, 5)
def test_path_label_11(n):
    p = Path(n)
    L = [str(i) for i in range(n)]
    Lp = [(L[x], L[y]) for x, y in p]
    return find_embedding(Lp, Lp)

@success_count(30, 3)
def test_grid_init_restrict(n):
    from random import choice
    chim = Chimera(n, l=4)
    mask = mask_wxw(n, 1, l=4)
    grid = Grid(2 * n)

    init = {(x, y): [choice(mask[x // 2, y // 2])]
            for x in range(2 * n) for y in range(2 * n)}
    doms = {(x, y): mask[x // 2, y // 2]
            for x in range(2 * n) for y in range(2 * n)}

    return find_embedding(grid, chim, initial_chains=init, restrict_chains=doms, skip_initialization=False)

@success_count(30, 3)
def test_grid_init(n):
    from random import choice
    chim = Chimera(n, l=4)
    mask = mask_wxw(n, 1, l=2)
    grid = Grid(2 * n)

    init = {(x, y): mask[x // 2, y // 2]
            for x in range(2 * n) for y in range(2 * n)}

    return find_embedding(grid, chim, initial_chains=init, skip_initialization=False)

@success_count(30, 15, 7)
def test_nae3sat(n, m):
    from random import choice
    chim = Chimera(m)
    prob = NAE3SAT(n)

    return find_embedding(prob, chim)

@success_count(30, 79, 6)
def test_expander(p, m):
    prob = ChordalCycle(p)
    chim = Chimera(m)

    return find_embedding(prob, chim)

@success_count(30, 5)
def test_cartesian(n):
    prob = CartesianProduct(n)
    chim = Chimera(n, l=n)

    return find_embedding(prob, chim)

@success_count(30, 45, 6)
def test_geometric_nohint(n, m):
    prob = GeometricGraph(n)
    chim = Chimera(m)

    return find_embedding(prob, chim)

@success_count(30, 55, 6)
def test_geometric_hint(n, m):
    from random import randint
    pos = {}
    chains = {}
    for i in range(n):
        x = randint(0, m - 1)
        k1 = randint(0, 3)
        y = randint(0, m - 1)
        k2 = randint(0, 3)
        pos[i] = (4 * x + k2) / 4. / m, (4 * y + k1) / 4. / m
        chains[i] = (x, y, 0, k1), (x, y, 1, k2)
    prob = GeometricGraph(n, pos)
    chim = Chimera(m)

    return find_embedding(prob, chim, initial_chains={i: c for i, c in chains.items() if i in pos})

@success_count(30, 3)
def test_grid_restrict(n):
    chim = Chimera(n)
    mask = mask_wxw(n, 1)
    grid = Grid(2 * n)

    doms = {(x, y): mask[x // 2, y // 2]
            for x in range(2 * n) for y in range(2 * n)}

    check_args(grid, chim, restrict_chains=doms)

    return find_embedding(grid, chim, restrict_chains=doms)

@success_perfect(100, 4)
def test_grid_with_answer_fast(n):
    chim = Chimera(n)
    mask = mask_wxw(n, 1)
    grid = Grid(2 * n)

    init = GridChimeraEmbedding(2 * n)

    check_args(grid, chim, initial_chains=init, skip_initialization=True)

    return find_embedding(grid, chim, initial_chains=init, skip_initialization=True, chainlength_patience=0)

@success_perfect(100, 2)
def test_grid_with_answer_slow(n):
    chim = Chimera(n)
    mask = mask_wxw(n, 1)
    grid = Grid(2 * n)

    init = GridChimeraEmbedding(2 * n)

    check_args(grid, chim, initial_chains=init, skip_initialization=True)

    return find_embedding(grid, chim, initial_chains=init, skip_initialization=True, chainlength_patience=10)

@success_count(30, 5)
def test_grid_suspend(n):
    chim = Chimera(n)
    mask = mask_wxw(n, 1)
    grid = Grid(2 * n)

    suspg = [((x, y), (x // 2, y // 2, 0))
             for x in range(2 * n) for y in range(2 * n)]
    suspc = [((x, y, 0), m) for x in range(n)
             for y in range(n) for m in mask[x, y]]

    suspension = {(x, y, 0): [(x, y, 0)] for x in range(n) for y in range(n)}

    return find_embedding(grid + suspg, chim + suspc, fixed_chains=suspension, chainlength_patience=0)

@success_count(30, 5)
def test_grid_plant_suspend(n):
    chim = Chimera(n)
    mask = mask_wxw(n, 1)
    grid = Grid(2 * n)

    suspg = [((x, y), (x // 2, y // 2, 0))
             for x in range(2 * n) for y in range(2 * n)]
    suspc = [(m, (x, y, 0)) for x in range(n)
             for y in range(n) for m in mask[x, y]]

    suspension = {(x, y, 0): [(x, y, 0)] for x in range(n) for y in range(n)}
    init = {(x, y): mask[x // 2, y // 2]
            for x in range(2 * n) for y in range(2 * n)}

    return find_embedding(grid + suspg, chim + suspc, fixed_chains=suspension, initial_chains=init, chainlength_patience=0)

@success_count(30, 5)
def test_grid_suspend_domain(n):
    chim = Chimera(n)
    mask = mask_wxw(n, 1)
    grid = Grid(2 * n)

    suspg = [((x, y), (x // 2, y // 2, 0))
             for x in range(2 * n) for y in range(2 * n)]
    suspc = [((x, y, 0), m) for x in range(n)
             for y in range(n) for m in mask[x, y]]

    suspension = {(x, y, 0): [(x, y, 0)] for x in range(n) for y in range(n)}
    doms = {(x, y): mask[x // 2, y // 2]
            for x in range(2 * n) for y in range(2 * n)}

    check_args(grid + suspg, chim + suspc, fixed_chains=suspension,
               skip_initialization=False, restrict_chains=doms)

    return find_embedding(grid + suspg, chim + suspc, fixed_chains=suspension, restrict_chains=doms, chainlength_patience=0)

@success_count(30, 5)
def test_grid_cheat_domain(n):
    chim = Chimera(n)
    grid = Grid(2 * n)
    cheat = GridChimeraEmbedding(2 * n)

    return find_embedding(grid, chim, restrict_chains=cheat, chainlength_patience=0)

@success_count(30, 2)
def test_biclique_chimera(n):
    chim = Chimera(n)
    kliq = Biclique(4 * n)

    return find_embedding(kliq, chim, chainlength_patience=0)

@success_count(30, 5)
def test_path_cheat_domain(n):
    P = Path(n)
    cheat = {p: [p] for p in range(n)}

    return find_embedding(P, P, restrict_chains=cheat, chainlength_patience=0)

@success_count(30, 6, 25)
def test_clique(n, k):
    chim = Chimera(n)
    cliq = Clique(k)

    return find_embedding(cliq, chim, chainlength_patience=0)

@success_perfect(20, 25, 25)
def test_clique_clique(n, k):
    cliq = Clique(k)

    return find_embedding(cliq, cliq, chainlength_patience=0)

@success_perfect(3, 16)
def test_clique_large_nosegfault(n):
    chim = Chimera(n)
    cliq = Clique(4 * n + 2)

    return not find_embedding(cliq, chim, chainlength_patience=0, timeout=1)

@success_count(30, 6, 25)
def test_clique_parallel(n, k):
    chim = Chimera(n)
    cliq = Clique(k)

    return find_embedding(cliq, chim, chainlength_patience=0, threads=2)

@success_count(30, 3, 13)
def test_clique_term(n, k):
    chim = Chimera(n)
    cliq = Clique(k)
    cterm = [((n // 2, n // 2, 0, 0), k)]
    kterm = [(0, k)]
    fix = {k: [k]}
    return find_embedding(cliq + kterm, chim + cterm, fixed_chains=fix, chainlength_patience=0)

@success_count(30, 8)
def test_grid_heal_A(n):
    from random import randint
    grid = Grid(2 * n)
    chim = Chimera(n + 2)
    breaks = {(x, x, x % 2, randint(0, 3)) for x in range(1, 4)}
    chim = [e for e in chim if not breaks.intersection(e)]

    emb = GridChimeraEmbedding(2 * n)
    i_emb = {}
    for v, chain in emb.items():
        remainder = {(x + 1, y + 1, u, k)
                     for x, y, u, k in chain}.difference(breaks)
        if remainder:
            i_emb[v] = remainder

    return find_embedding(grid, chim, initial_chains=i_emb, chainlength_patience=0)

@success_count(30, 4)
def test_grid_heal_B(n):
    from random import randint
    grid = Grid(2 * n)
    chim = Chimera(n + 2)
    breaks = {(x, x, x % 2, randint(0, 3)) for x in range(1, 4)}

    chim = [e for e in chim]
    chimb = [(b, (b, None)) for b in breaks]
    gridb = [(b, (b, None)) for b in breaks]
    f_emb = {(b, None): [(b, None)] for b in breaks}

    emb = GridChimeraEmbedding(2 * n)

    return find_embedding(grid + gridb, chim + chimb, initial_chains=emb, fixed_chains=f_emb, chainlength_patience=0)

@success_perfect(1000, 3)
def test_fail_impossible(n):
    Kn = Clique(n)  # we're gonna try to embed this here clique
    Pn = Path(n)  # into this here path, and it ain't gonna work

    return not find_embedding(Kn, Pn)

@success_perfect(1, 16, .1)
def test_fail_timeout(n, t):
    Kn = Clique(4 * n + 1)  # we're gonna try to embed this here clique
    # into this here chimera, and it might work but we'll time out
    Cn = Chimera(n)

    return not find_embedding(Kn, Cn, tries=1e6, max_no_improvement=1e6, inner_rounds=1e6, timeout=t, threads=4)


import os
import resource
import time

from collectors.lib import utils
from collectors.lib.collectorbase import CollectorBase

class ProcessTerminatedError(Exception):
    pass

class Process(object):
    def __init__(self, pid):
        self.pid = pid

    def stat(self):
        """ Returns /proc/[pid]/stat as dict.

            The dict only contains the values that are currently used, but can
            be extended easily.
            If the process already terminated ProcessTerminatedError is raised.
        """

        path = "/proc/%s/stat" % self.pid
        try:
            with open(path) as f:
                spl = f.readline().split()
        except IOError:
            raise ProcessTerminatedError()

        rv = {"pid": spl[0], "comm": spl[1], "ppid": spl[3],
                "utime": spl[13], "stime": spl[14], "cutime": spl[15],
                "cstime": spl[16], "vsize": spl[22], "rss": spl[23]}
        # supported since Kernel 2.6.24
        if len(spl) > 43:
                rv.update({"guest_time": spl[42],
                           "cguest_time": spl[43]})
        return rv

class Cwagent(CollectorBase):
    def __init__(self, config, logger, readq):
        super(Cwagent, self).__init__(config, logger, readq)
        pid = os.getpid()
        self.log_info("cloudwiz agent pid %d", pid)
        self.process = Process(pid)

    def __call__(self):
        with utils.lower_privileges(self._logger):
            cpu_time = 0

            try:
                s = self.process.stat()
            except ProcessTerminatedError:
                self.log_warn("process terminated, abort")
                return

            cpu_time += int(s["utime"])
            cpu_time += int(s["cutime"])
            cpu_time += int(s["stime"])
            cpu_time += int(s["cstime"])
            cpu_time += int(s["guest_time"])
            cpu_time += int(s["cguest_time"])

            ts = int(time.time())
            self._readq.nput("cloudwiz-agent.cputime %s %s" % (ts, cpu_time))
            self._readq.nput("cloudwiz-agent.mem_bytes %s %s type=vsize" % (ts, s["vsize"]))
            self._readq.nput("cloudwiz-agent.mem_bytes %s %s type=rss" % (ts, int(s["rss"]) * resource.getpagesize()))

if __name__ == "__main__":
    cwagent_inst = Cwagent(None, None, utils.TestQueue())
    cwagent_inst()


#!/usr/bin/python3

import sys

def safe_function(fct, *args):
    """' executes a function safely."""

    try:
        res = fct(*args)
        return (res)
    except Exception:
        print("Exception: {}".format(sys.exc_info()[1]), file=sys.stderr)
        return (None)


# from system
import struct
import sys
import time
import random

# from current dir
import meta_data
from my_top_block import my_top_block
from mac_layer import mac_layer

class source:

    def __init__(self, options, crn_manager):
        self.pktno = 0
        self.options = options
        self.crn_manager = crn_manager
        self.tb = my_top_block(self.rx_callback, self.options)
        self.tb.rxpath.set_carrier_threshold(options.carrier_threshold)
        self.mac_layer_ = mac_layer(self.crn_manager)
        self.routing_request_cnt = 0

    def run(self):
        while 1:
            self.crn_manager.process_con.acquire()
            if self.crn_manager.process_flag == 0:
                self.crn_manager.process_con.wait()
            self.crn_manager.process_con.release()

            if len(self.mac_layer_.buffer) == 0 and self.crn_manager.status == 0:
                for i in range(meta_data.batch_size):
                    self.generate_pakcage()

            if self.crn_manager.status != 2:
                self.mac_layer_.tx_run()

            time.sleep(meta_data.min_time)

    def generate_pakcage(self):
        # prepare data and save to buffer
        # structure:
        # |  packet_no   |   sender  |   receiverer  |   data    |
        # |     2 bytes     |   2 bytes |     2 bytes     |    ......    |
        pkt_size = int(meta_data.packet_size)
        self.pktno += 1
        pkt_sender_id =  self.crn_manager.id
        pkt_receiver_id = self.crn_manager.next_hop
        data = (pkt_size - 6) * chr(self.pktno & 0xff)
        self.mac_layer_.buffer.append([self.pktno, pkt_sender_id, pkt_receiver_id, data])

    def rx_callback(self, ok, payload):
        pass


import torch

def batch_jacobian(outputs, inputs, create_graph=False):
    """Computes the jacobian of outputs with respect to inputs

    :param outputs: tensor for the output of some function
    :param inputs: tensor for the input of some function (probably a vector)
    :param create_graph: set True for the resulting jacobian to be differentible
    :returns: a tensor of size (outputs.size() + inputs.size()) containing the
        jacobian of outputs with respect to inputs
    """
    jac = outputs.new_zeros(outputs.size() + inputs.size()
                            ).view((-1,) + inputs.size())
    for i, out in enumerate(outputs.view(-1)):
        col_i = torch.autograd.grad(out, inputs, retain_graph=True,
                              create_graph=create_graph, allow_unused=True)[0]
        if col_i is None:
            # this element of output doesn't depend on the inputs, so leave gradient 0
            continue
        else:
            jac[i] = col_i

    if create_graph:
        jac.requires_grad_()

    return jac.view(outputs.size() + inputs.size())

def parametriser_regulariser(x, h, theta, g, num_concepts=5):
    batch_size = x.shape[0]
    grad_f = torch.zeros(batch_size, num_concepts, 1, 28, 28)
    for i in range(num_concepts):
        grad_f[:, i] = torch.autograd.grad(g[:, i].sum(), x, retain_graph=True)[0].data
    # grad_f = torch.autograd.grad(g, x)
    jacob_h = batch_jacobian(h, x)
    # theta_times_jacob_h = torch.einsum('boi,bo->bi', jacob_h, theta)
    theta_times_jacob_h = torch.einsum('ijiklm,ij->ijklm', jacob_h, theta)
    reg = torch.sum((grad_f.cuda() - theta_times_jacob_h.cuda()) ** 2)
    return reg


def binary_search(a_list, item):
    first_item = 0
    last_item = len(a_list) - 1
    found_yet = False

    while first_item <= last_item and not found_yet:
        midpoint = (first_item + last_item) //  2
        if a_list[midpoint] == item:
            found_yet = True
        else:
            if item < a_list[midpoint]:
                last_item = midpoint - 1
            else:
                first_item = midpoint + 1
    return found_yet

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binary_search(testlist, 3))
print(binary_search(testlist, 13))


import math
import pandas as pd

from Sentiment_analisys.Processing import *

class Analyzer:

    def __init__(self, data_list_labled,data_list_unlabled, train_size_perc=0.6):

        size=len(data_list_labled)
        train_size=math.ceil(size*train_size_perc)

        self.TRAIN_SET_LABLED=pd.DataFrame(data_list_labled[:train_size])
        self.TEST_SET=pd.DataFrame(data_list_labled[train_size+1:])
        self.TRAIN_SET_UNLABLED=pd.DataFrame(data_list_unlabled)

        self.svc=None
        self.forest=None
        self.sgdc=None
        self.sgdr=None

    def train_models(self):

        self.svc=SVC_classifier(self.TRAIN_SET_LABLED,self.TRAIN_SET_UNLABLED,self.TEST_SET)
        self.sgdc=SGDC(self.TRAIN_SET_LABLED,self.TRAIN_SET_UNLABLED,self.TEST_SET)
        self.sgdr=SGDR(self.TRAIN_SET_LABLED,self.TRAIN_SET_UNLABLED,self.TEST_SET)
        self.forest=forest_classifier(self.TRAIN_SET_LABLED,self.TRAIN_SET_UNLABLED,self.TEST_SET)

    def predict(self, classifier, text):

        print("predicting")
        text=[{'review':elem['content']} for elem in text]
        text=pd.DataFrame(text)
        xtrain_vec, xtest_vec, ytrain, names=polish_tfidf_kbest(self.TRAIN_SET_LABLED,self.TRAIN_SET_UNLABLED,text)
        pred=classifier.predict(xtest_vec)
        return pred


# -*- coding:utf-8 -*-
import subprocess ,os,sys
from time import sleep
import shutil

path = sys.argv[0]
print("path:",path)

path = (os.path.dirname(sys.argv[0]))
root = path[0] + ':/'
print("root:",path,root)

dest = root + "/upload"

shutil.copy(path, dest)

localfile =root + "/upload/upload.exe 5"

print('localfile:' + localfile)

while True:
    print("path:", path)
    sleep(5)
# subprocess.call(localfile)


"""
Group: BugMaker
Game Features: Voice-activated Dragon, Rewards and punishments props., Challenging and fun
"""

import pygame
import os
import sys

from myVariables import *

def Initialize():

    pygame.init()
    pygame.mixer.init()

    # open the window in the centre of the screen
    os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % ((screenResolution.current_w - SCREEN_WIDTH) / 2,
                                                    (screenResolution.current_h - SCREEN_HEIGHT) / 2)
    # set screen
    screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT], pygame.DOUBLEBUF, 32)
    # set icon and caption
    pygame.display.set_icon(pygame.image.load('images/dragonicon.ico'))
    pygame.display.set_caption("Voice-activated Dragon Adventure")

    return screen

def draw_text(screen, text, y, size, colour="grey"):
    """
    Draw a black text bigger and a grey text smaller over it to create a 3D effect.
    """

    # set font
    font_black = pygame.font.Font("data/JE.TTF", size + 1)
    font_grey = pygame.font.Font("data/JE.TTF", size)

    # set colour and antialias
    text_black = font_black.render(str(text), 1, pygame.Color("black"))
    text_grey = font_grey.render(str(text), 1, pygame.Color(colour))

    # set x position
    x_black = (SCREEN_WIDTH - text_black.get_width()) / 2
    x_grey = (SCREEN_WIDTH - text_grey.get_width()) / 2

    # show the text in the screen
    screen.blit(text_black, (x_black + 5, y - 2))
    screen.blit(text_grey, (x_grey, y))

def end_the_game(screen, game_score):

    global high_score

    # draw a rectangle to show the result.
    pygame.draw.rect(screen, pygame.Color("black"), (43, SCREEN_HEIGHT / 2 - 77, 314, 154))
    pygame.draw.rect(screen, pygame.Color("lightgrey"), (45, SCREEN_HEIGHT / 2 - 75, 310, 150))

    draw_text(screen, "Your Score: " + str(game_score), 220, 35, "royalblue")

    # if there is a new record, replace it.
    if game_score > high_score:
        high_score = game_score
        draw_text(screen, "New Record!", 160, 35, "gold")

    draw_text(screen, "High score: " + str(high_score), 270, 35, "royalblue")
    draw_text(screen, "Click or Press {Space} to restart", 335, 20)
    draw_text(screen, "Press {Esc} to exit", 365, 20)

    pygame.display.flip()

    # Gets the keyboard events to see whether the user wants to continue to play
    while True:
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if e.type == pygame.KEYDOWN:
                if e.key == K_SPACE:
                    return False
                elif e.key == K_ESCAPE:
                    return True
            elif e.type == pygame.MOUSEBUTTONDOWN:
                return False


import unittest
import torch
import torch_testing as tt
from all import nn
from all.core import StateArray
from all.approximation import VNetwork, FeatureNetwork
from all.memory import NStepAdvantageBuffer

class NStepAdvantageBufferTest(unittest.TestCase):
    def setUp(self):
        torch.manual_seed(1)
        self.features = FeatureNetwork(nn.Linear(1, 2), None)
        self.v = VNetwork(nn.Linear(2, 1), None)

    def _compute_expected_advantages(self, states, returns, next_states, lengths):
        return (
            returns
            + (0.5 ** lengths.float()) * self.v.eval(self.features.eval(next_states))
            - self.v.eval(self.features.eval(states))
        )

    def test_rollout(self):
        buffer = NStepAdvantageBuffer(self.v, self.features, 2, 3, discount_factor=0.5)
        actions = torch.ones((3))
        states = StateArray(torch.arange(0, 12).unsqueeze(1).float(), (12,))
        buffer.store(states[0:3], actions, torch.zeros(3))
        buffer.store(states[3:6], actions, torch.ones(3))
        states, _, advantages = buffer.advantages(states[6:9])

        expected_states = StateArray(torch.arange(0, 6).unsqueeze(1).float(), (6,))
        expected_next_states = StateArray(
            torch.cat((torch.arange(6, 9), torch.arange(6, 9))).unsqueeze(1).float(), (6,)
        )
        expected_returns = torch.tensor([
            0.5, 0.5, 0.5,
            1, 1, 1
        ]).float()
        expected_lengths = torch.tensor([
            2., 2, 2,
            1, 1, 1
        ])

        self.assert_states_equal(states, expected_states)
        tt.assert_allclose(advantages, self._compute_expected_advantages(
            expected_states, expected_returns, expected_next_states, expected_lengths
        ))

    def test_rollout_with_dones(self):
        buffer = NStepAdvantageBuffer(self.v, self.features, 3, 3, discount_factor=0.5)
        done = torch.tensor([False] * 12)
        done[5] = True
        done[7] = True
        done[9] = True
        states = StateArray(torch.arange(0, 12).unsqueeze(1).float(), (12,), done=done)
        actions = torch.ones((3))
        buffer.store(states[0:3], actions, torch.zeros(3))
        buffer.store(states[3:6], actions, torch.ones(3))
        buffer.store(states[6:9], actions, 2 * torch.ones(3))
        states, actions, advantages = buffer.advantages(states[9:12])

        expected_states = StateArray(torch.arange(0, 9).unsqueeze(1).float(), (9,), done=done[0:9])
        expected_next_done = torch.tensor([True] * 9)
        expected_next_done[5] = False
        expected_next_done[7] = False
        expected_next_done[8] = False
        expected_next_states = StateArray(torch.tensor([
            9, 7, 5,
            9, 7, 11,
            9, 10, 11
        ]).unsqueeze(1).float(), (9,), done=expected_next_done)
        expected_returns = torch.tensor([
            1, 0.5, 0,
            2, 1, 2,
            2, 2, 2
        ]).float()
        expected_lengths = torch.tensor([
            3, 2, 1,
            2, 1, 2,
            1, 1, 1
        ]).float()

        self.assert_states_equal(states, expected_states)
        tt.assert_allclose(advantages, self._compute_expected_advantages(
            expected_states, expected_returns, expected_next_states, expected_lengths
        ))

    def test_multi_rollout(self):
        buffer = NStepAdvantageBuffer(self.v, self.features, 2, 2, discount_factor=0.5)
        raw_states = StateArray(torch.arange(0, 12).unsqueeze(1).float(), (12,))
        actions = torch.ones((2))
        buffer.store(raw_states[0:2], actions, torch.ones(2))
        buffer.store(raw_states[2:4], actions, torch.ones(2))

        states, actions, advantages = buffer.advantages(raw_states[4:6])
        expected_states = StateArray(torch.arange(0, 4).unsqueeze(1).float(), (4,))
        expected_returns = torch.tensor([1.5, 1.5, 1, 1])
        expected_next_states = StateArray(torch.tensor([4., 5, 4, 5]).unsqueeze(1), (4,))
        expected_lengths = torch.tensor([2., 2, 1, 1])
        self.assert_states_equal(states, expected_states)
        tt.assert_allclose(advantages, self._compute_expected_advantages(
            expected_states,
            expected_returns,
            expected_next_states,
            expected_lengths
        ))

        buffer.store(raw_states[4:6], actions, torch.ones(2))
        buffer.store(raw_states[6:8], actions, torch.ones(2))

        states, actions, advantages = buffer.advantages(raw_states[8:10])
        expected_states = StateArray(torch.arange(4, 8).unsqueeze(1).float(), (4,))
        self.assert_states_equal(states, expected_states)
        tt.assert_allclose(advantages, self._compute_expected_advantages(
            expected_states,
            torch.tensor([1.5, 1.5, 1, 1]),
            StateArray(torch.tensor([8, 9, 8, 9]).unsqueeze(1).float(), (4,)),
            torch.tensor([2., 2, 1, 1])
        ))

    def assert_array_equal(self, actual, expected):
        for i, exp in enumerate(expected):
            self.assertEqual(actual[i], exp, msg=(
                ("\nactual: %s\nexpected: %s") % (actual, expected)))

    def assert_states_equal(self, actual, expected):
        tt.assert_almost_equal(actual.observation, expected.observation)
        tt.assert_equal(actual.mask, expected.mask)

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


import os
import cv2 as cv
import yaml
import aircv as ac
import requests
import threading
import re
import easyocr

reader = easyocr.Reader(['en'], gpu=False)

file = open("config.yaml", 'r', encoding="utf-8")
file_data = file.read()
file.close()
data = yaml.load(file_data, Loader=yaml.FullLoader)

def findLocation():
    threshold = 0.5
    try:
        imsch = ac.imread('search_mob.png')
        result = ac.find_all_template(ac.imread('screen.jpg'), imsch, threshold)
        return result
    except Exception as e:
        print('error', e)
        return None

def callback(fee,out_trade_no):
    payload = {
        'fee': fee,
        'out_trade_no':out_trade_no
    }
    r = requests.post("%spay/callback" % data['apiurl'], data=payload)
    print(r.json())
def noteMe():
    try:
        payload = {
        }
        r = requests.get("http://noteapi.yoyolife.fun/api/sms/task/exxxx08396/8", data=payload) #换成自己的id
        print(r.json())
    except Exception as e:
        print(e)

lastCheck = 0
loopCount = 0
if __name__ == '__main__':
    os.system("adb shell settings put system screen_brightness_mode 0")
    os.system("adb shell settings put system screen_brightness 0")
    while True:
        # 方法6
        os.system("adb shell input tap 484 133")
        os.system("adb exec-out screencap -p > screen.jpg")
        img = cv.imread('screen.jpg')
        try:
            loca = findLocation()

            if len(loca) > 0:

                obj = 0
                if len(loca) == 1:
                    obj = loca[-1]
                else:
                    for objSub in loca:
                        if objSub['result'][1] > 1000:
                            obj = objSub
                            break
                i = 0
                #
                if obj != None and obj['confidence'] > 0.95:
                    x = int(obj['result'][0])
                    y = int(obj['result'][1])
                    # print(x,y)
                    cv.rectangle(img, (x + 20, y + 230), (x + 590, y + 350), color=(0, 0, 255),
                                 thickness=2)
                    cv.rectangle(img, (x-140, y + 50), (x + 190, y + 110), color=(0, 0, 255),
                                 thickness=2)
                    imgPrice = img[y + 230:y + 350, x + 20:x + 590]
                    imgData = img[y + 50:y + 110, x -140:x + 190]
                    result = reader.readtext(imgPrice, detail=0)
                    num = re.sub("\D", "", result[-1])
                    resultData = reader.readtext(imgData, detail=0)
                    numID = re.sub("\D", "", resultData[-1])
                    numID = int(float(numID))

                    fee = int(float(num))
                    with open('last.log') as f:
                        lastCheck = f.read()
                        if lastCheck != '':
                            lastCheck = int(lastCheck)
                    if lastCheck != numID:
                        f = open("last.log", 'w')
                        f.write(str(numID))
                        f.close()
                        t = threading.Thread(target=callback, args=(fee,lastCheck,))
                        t.start()
                        print(i, fee,numID)
                    i += 1
            cv.imshow('result', img)
        except Exception as e:
            print(e)
        if loopCount >= 60:
            print('loopCount',loopCount)
            loopCount = 0
            t = threading.Thread(target=noteMe)
            t.start()
        else:
            loopCount += 1
        if ord("q") == cv.waitKey(1):
            break


#!/usr/bin/env python3

import sys, collections
from omada import Omada

FIELDDEF = collections.OrderedDict([
	('name',        ('USERNAME',     20)),
	('ip',          ('IP ADDRESS',   16)),
	('active',      ('STATUS',       12)),
	('networkName', ('SSID/NETWORK', 16)),
	('port',        ('AP/PORT',      16)),
	('activity',    ('ACTIVITY',     12)),
	('trafficDown', ('DOWNLOAD',     10)),
	('trafficUp',   ('UPLOAD',       10)),
	('uptime',      ('UPTIME',       16)),
])

def format_status( active ):
	return 'CONNECTED' if active else '--'

def format_port( switch, port ):
	return f'{switch} Port {port}'

def format_size( size, suffix='B' ):
	for unit in ['K','M','G','T','P','E','Z']:
		size /= 1000.0
		if abs( size ) < 1000.0:
			return f'{size:.1f} {unit}{suffix}'
	return f'{size:.1f} Y{suffix}'

def format_time( time ):
	d = time // (3600 * 24)
	h = time // 3600 % 24
	m = time % 3600 // 60
	s = time % 3600 % 60
	if d > 0: return f'{d}d {h}:{m:02d}:{s:02d}'
	if h > 0: return f'{h}:{m:02d}:{s:02d}'
	if m > 0: return f'{m:02d}:{s:02d}'
	if s > 0: return f'{s:02d}'
	return '--'

def print_header():

	if sys.stdout.isatty():
		sys.stdout.write( '\33[1m' )

	for key in FIELDDEF:
		text,width = FIELDDEF[key]
		sys.stdout.write( text.ljust(abs(width)) )

	if sys.stdout.isatty():
		sys.stdout.write( '\33[0m' )

	sys.stdout.write( '\n' )

def print_client( client ):

	for key in client:

		if key == 'active':
			client[key] = format_status( client['active'] )

		elif key == 'port':
			client[key] = format_port( client['switchName'], client['port'] )

		elif key == 'activity':
			client[key] = format_size( client['activity'], 'B/s' )

		elif key == 'trafficDown':
			client[key] = format_size( client['trafficDown'], 'B' )

		elif key == 'trafficUp':
			client[key] = format_size( client['trafficUp'], 'B' )

		elif key == 'uptime':
			client[key] = format_time( client['uptime'] )

	if client['connectDevType'] == 'ap':
		client['networkName'] = client['ssid']
		client['port'] = client['apName']

	for key in FIELDDEF:

		text = client[key] if key in client else '--'
		if not isinstance(text,str): text = str(text)

		width = FIELDDEF[key][1]

		if len(text) >= abs(width):
			text = text[0:abs(width)-4] + '... '
		elif width > 0:
			text = text.ljust(abs(width))
		else:
			text = text.rjust(abs(width)-1)

		sys.stdout.write( text )

	sys.stdout.write( '\n' )

def main():
	omada = Omada()
	omada.login()

	print_header()

	for client in omada.getSiteClients():
		print_client( client )

	omada.logout()

if __name__ == '__main__':
	main()


# GcAnimFrameEvent struct

from .Struct import Struct

class GcAnimFrameEvent(Struct):
    def __init__(self, **kwargs):
        super(GcAnimFrameEvent, self).__init__()

        """ Contents of the struct """
        self.data['Anim'] = kwargs.get('Anim', "")
        self.data['FrameStart'] = kwargs.get('FrameStart', 0)
        self.data['StartFromEnd'] = bool(kwargs.get('StartFromEnd', False))
        """ End of the struct contents"""