'''
Exercício 1 - Máximo

Escreva a função maximo que recebe 2 números inteiros como parâmetro e
devolve o maior deles.

Note que

maximo(3,4) deve devolver 4

maximo(0,-1) deve devolver 0
'''
def main():
    valor1 = int(input('Digite o primeiro valor: '))
    valor2 = int(input('Digite o segundo valor: '))
    print(maximo(valor1, valor2))

def maximo(a, b):
    if a >= b:
        return a
    else:
        return b

main()

'''
#desenvolvendo os testes padronizados
def test_maximo34():
    assert maximo(3, 4) == 4

def test_maximo01():
    assert maximo(0, -1) == 0
'''


import os

from typing import Callable, Tuple

DIRPATH = os.path.dirname(os.path.abspath(__file__))

REQUIRED_FIELDS = set(['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid',])

def solve_one(data: str):
	return sum(all(field in passport for field in REQUIRED_FIELDS) for passport in data.split('\n\n'))

def test_one():
	with open(os.path.join(DIRPATH, 'input.in')) as input_file:
		data = input_file.read()
	assert solve_one('''ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm

iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929

hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm

hcl:#cfa07d eyr:2025 pid:166559648
iyr:2011 ecl:brn hgt:59in''') == 2
	print(solve_one(data))

def is_int_in_range(
	value: str,
	precheck: Callable[[str], bool],
	get_range: Callable[[str], Tuple[int, int]],
	parse_int: Callable[[str], int] = int,
) -> bool:
	try:
		num = parse_int(value)
		if not precheck(value):
			return False

		low, high = get_range(value)
		return low <= num <= high
	except:
		return False

YEAR_RANGES = {
	'byr': (1920, 2002),
	'iyr': (2010, 2020),
	'eyr': (2020, 2030)
}

def is_valid(field: str, value: str):
	if not value:
		return False

	if field in YEAR_RANGES:
		return is_int_in_range(
			value,
			lambda value: len(value) == 4,
			lambda _: YEAR_RANGES[field]
		)
	elif field == 'hgt':
		return is_int_in_range(
			value,
			lambda value: any(value.endswith(suffix) for suffix in ('in', 'cm')),
			lambda value: (150, 193) if value.endswith('cm') else (59, 76),
			lambda value: int(value[:-2])
		)
	elif field == 'hcl':
		if value[0] != '#':
			return False
		if any(char.isupper() for char in value):
			return False
		try:
			int(value[1:], 16)
			return True
		except:
			return False
	elif field == 'ecl':
		return value in ('amb', 'blu', "brn", 'gry', 'grn', 'hzl', 'oth')
	elif field == 'pid':
		if len(value) != 9:
			return False
		try:
			int(value)
			return True
		except:
			return False

def test_is_valid():
	assert is_valid('byr', '2002')
	assert not is_valid('byr', '2003')

	assert is_valid('hgt', '60in')
	assert is_valid('hgt', '190cm')
	assert not is_valid('hgt', '190in')
	assert not is_valid('hgt', '190')

	assert is_valid('hcl', '#123abc')
	assert not is_valid('hcl', '#123abC')
	assert not is_valid('hcl', '#123abz')
	assert not is_valid('hcl', '123abc')

	assert is_valid('ecl', 'brn')
	assert not is_valid('ecl', 'wat')

	assert is_valid('pid', '000000001')
	assert not is_valid('pid', '0123456789')

def solve_two(data: str):
	return sum(
		all(
			field in passport
			and is_valid(field, passport.split(field + ':')[1].split(' ')[0].split()[0].strip())
			for field in REQUIRED_FIELDS
		)
		for passport in data.split('\n\n')
	)

def test_two():
	with open(os.path.join(DIRPATH, 'input.in')) as input_file:
		data = input_file.read()
	assert solve_two('''eyr:1972 cid:100
hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926

iyr:2019
hcl:#602927 eyr:1967 hgt:170cm
ecl:grn pid:012533040 byr:1946

hcl:dab227 iyr:2012
ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277

hgt:59cm ecl:zzz
eyr:2038 hcl:74454a iyr:2023
pid:3556412378 byr:2007''') == 0
	assert solve_two('''pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980
hcl:#623a2f

eyr:2029 ecl:blu cid:129 byr:1989
iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm

hcl:#888785
hgt:164cm byr:2001 iyr:2015 cid:88
pid:545766238 ecl:hzl
eyr:2022

iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719''') == 4
	print(solve_two(data))


__author__ = 'easycui'

from problem2 import *
from problem3 import *
from problem4 import *
import numpy as np
import matplotlib.pyplot as plt

def train(data, tree, conti, title):
    """

    :param data: training data, it should be a np.array with shape(n*k+1), K is the attribute num, the last
                column is the label
    :return: return generated  decision tree
    """
    gen_mktree(data, title, tree, 0, "nil", conti)
    # tree2dot("3_c tree",tree)
def train_e(data, tree, conti, title, maxdepth):
    """

    :param data: training data, it should be a np.array with shape(n*k+1), K is the attribute num, the last
                column is the label
    :return: return generated  decision tree
    """
    e_gen_mktree(data, title, tree, 0, "nil", conti, 0, maxdepth)
    # tree2dot("3_c tree",tree)

def test(data, tree, conti, title):
    return cltree(data, tree, conti, title)

def plot(training_error, test_error):
    a = [2, 3, 4, 5]
    plt.plot(a, training_error)
    plt.plot(a, test_error)
    plt.show()

def main():
    data, title = parseCSV("./mpg_train.csv",'num')

    # 5.b

    tree = TreeNode("nil")
    conti = np.array([0, 1, 1, 1, 1,0])
    train(data, tree, conti, title)
    tree2dot("5_b tree", tree)
    # 5.c
    #training_error_rate = test(data, tree, conti, title)

    data, title = parseCSV("./mpg_test.csv",'num')
    test_error_rate = test(data, tree, conti, title)
    print("training error rate and test error rate are:")
    #print(training_error_rate, test_error_rate)
    #
    # # 5.d
    # data, title = parseCSV("./mpg_train.csv",'num')
    # conti = np.array([0, 1, 1, 1, 0, 0])
    # tree = TreeNode("nil")
    # train(data, tree, conti, title)
    # tree2dot("5_d tree", tree)
    # training_error_rate = test(data, tree, conti, title)
    # data, title = parseCSV("./mpg_test.csv",'num')
    #
    # test_error_rate = test(data, tree, conti, title)
    # print("5_d: training error rate and test error rate are:")
    # print(training_error_rate, test_error_rate)
    #
    # # 5.e
    # training_error=[]
    # test_error=[]
    #
    # for i in range(2,6):
    #     data, title = parseCSV("./mpg_train.csv",'num')
    #     conti = np.array([0, 1, 1, 1, 1,0])
    #     tree = TreeNode("nil")
    #     train_e(data, tree, conti, title, i)
    #     tree2dot("5_e tree_" + str(i), tree)
    #     # 5.c
    #     training_error_rate = test(data, tree, conti, title)
    #     data, title = parseCSV("./mpg_test.csv",'num')
    #     test_error_rate = test(data, tree, conti, title)
    #     training_error.append(training_error_rate)
    #     test_error.append(test_error_rate)
    # print(training_error,test_error)
    # plot(training_error, test_error)

if __name__=="__main__":
    main()


books=[]
do=input()
while do != "end":
    if do[:6] == "return":
        books.append(do[7:])
        print(len(books))
    elif do == "shelf":
        if len(books) == 0:
            print("no book")
        else:
            pop = books.pop()
            print(pop)
    elif do == "top":
        if len(books) == 0:
            print("no book")
        else:
            print(books[-1])
    elif do == "list":
        print(books)
    do=input()


import direct.directbase.DirectStart
from direct.showbase.DirectObject import DirectObject
from pandac.PandaModules import *
from direct.actor.Actor import Actor
from direct.interval.IntervalGlobal import *
from direct.task import Task

from direct.gui.OnscreenImage import OnscreenImage
from pandac.PandaModules import TransparencyAttrib
from direct.gui.OnscreenText import OnscreenText
from direct.gui.DirectGui import *

import sys, math, os, random
import world, entity, projectile

from pandac.PandaModules import Filename

class PlayerTank(entity.entity): #use to create player tank
    def __init__(self, world):
        #NOTE!!!: I couldn't get the models to load conveniently (I believe panda needs an absolute path
        #So in your panda config file (located in Panda3d-1.5.3/etc paste the line where the sumotanks file is
        #for me I had to paste: model-path    C:\Documents and Settings\therrj\Desktop\sumotanks\art\tank
        #Put this where the other model-path lines are
        #If there is a more convenient way to do this feel free
        self.isMoving = False

        self.base = Actor("baseblue.egg", {"moveforwards":"forwards.egg","movebackwards":"backwards.egg", "turnleft":"left.egg","turnright":"right.egg"})
        self.turret = Actor("turretblue.egg")
        self.cannon = Actor("cannonblue.egg")
        self.base.delete()
        self.turret.delete()
        self.cannon.delete()
        self.base = Actor("basepurple.egg", {"moveforwards":"forwards.egg","movebackwards":"backwards.egg", "turnleft":"left.egg","turnright":"right.egg"})
        self.turret = Actor("turretpurple.egg")
        self.cannon = Actor("cannonpurple.egg")
        self.base.delete()
        self.turret.delete()
        self.cannon.delete()
        self.base = Actor("basegreen.egg", {"moveforwards":"forwards.egg","movebackwards":"backwards.egg", "turnleft":"left.egg","turnright":"right.egg"})
        self.turret = Actor("turretgreen.egg")
        self.cannon = Actor("cannongreen.egg")
        self.base.delete()
        self.turret.delete()
        self.cannon.delete()
        self.base = Actor("baseyellow.egg", {"moveforwards":"forwards.egg","movebackwards":"backwards.egg", "turnleft":"left.egg","turnright":"right.egg"})
        self.turret = Actor("turretyellow.egg")
        self.cannon = Actor("cannonyellow.egg")
        self.base.delete()
        self.turret.delete()
        self.cannon.delete()
        self.base = Actor("basered.egg", {"moveforwards":"forwards.egg","movebackwards":"backwards.egg", "turnleft":"left.egg","turnright":"right.egg"})
        self.turret = Actor("turretred.egg")
        self.cannon = Actor("cannonred.egg")
        self.base.delete()
        self.turret.delete()
        self.cannon.delete()

        self.cannon = Actor("cannongreen.egg")
        self.cannon.setScale(.75)
        self.cannon.reparentTo(render)
        self.turret = Actor("turretgreen.egg")
        self.turret.setScale(.75)
        self.turret.reparentTo(render)

        self.base = Actor("basegreen.egg", {"moveforwards":"forwards.egg","movebackwards":"backwards.egg", "turnleft":"left.egg","turnright":"right.egg"})
        self.base.setScale(.75)
        self.base.reparentTo(render)
        self.base.setPos(60,60,0)
        self.base.setH(-40)
        self.cannon.setH(-90)

        self.moveforwardscontrol=self.base.getAnimControl("moveforwards") #Set animation control for moveforwards
        self.movebackwardsscontrol=self.base.getAnimControl("movebackwards") #Set animation control for moveforwards
        self.turnleftcontrol=self.base.getAnimControl("turnleft") #Set animation control for moveforwards
        self.turnrightcontrol=self.base.getAnimControl("turnright") #Set animation control for moveforwards

        self.headlight = Spotlight("headLight")
        self.headlightNP = render.attachNewNode(self.headlight)
        self.headlightstatus = 0

        self.xycameradistance = 15
        self.zcameradistance = 15
        self.cannonmove = 5

        self.keyMap = {"left":0, "right":0, "forward":0, "back":0, "headlight":0, "fire":0}

        self.prevtimeforTurret = 0
        self.prevtimeforBase = 0

        self.allowmovement = False

        self.crosshair = Actor("panda-model")
        #self.crosshair.reparentTo(render)
        self.crosshair.setScale(.000000001)
        #self.crosshair.setH(180)

        self.crosshair2d = OnscreenImage(image = "cannoncrosshair.png", pos=(0,0,0),scale=0.1)
        self.crosshair2d.setTransparency(TransparencyAttrib.MAlpha)

        #camera.setPosHpr(self.base.getX(), self.base.getY() + 10, self.base.getZ(), self.cannon.getH(),180,180) #Set camera position, heading, pitch and roll

        self.currentweapon = 1 #1 for cannon 2 for machine gun
        self.currentweaponimage = OnscreenImage(image = "cannonimage.png", pos=(-.99,0,.92),scale=.3)
        self.currentweaponimage.setTransparency(TransparencyAttrib.MAlpha)

        self.damage = 1
        self.crosshair3d = [] #Crosshair in 3d space (needs to be converted to 2d for drawing crosshair)

        self.prevtimeforPlayer = 0

        self.haschangedtexture = False

        self.world = world
        self.nodePath = self.addCollisionBoundaries()

        self.projectiles = list()
        self.fireCountCannon = 60
        self.fireCountMG = 10
        self.firedCannon = False
        self.firedMG = False

        self.oldvel = entity.force(0,0)

        entity.entity.__init__(self, 5)

    def addCollisionBoundaries(self):
        self.cHandler = CollisionHandlerEvent()
        self.cHandler.setInPattern("hit-%in")
        cSphere = CollisionSphere(0, 0, 0, 3)
        cNode = CollisionNode("Player")
        cNode.addSolid(cSphere)
        cNP = self.base.attachNewNode(cNode)
        #cNP.show()

        base.cTrav.addCollider(cNP, self.cHandler)

        self.accept("hit-Enemy", self.playerHitEnemy)

        return cNP

    def playerHitEnemy(self, entry):
        if entry.getFromNode().getName() == "Bullet" or entry.getFromNode().getName() == "Cannon":
            return
        XDiff = -(self.vel.xcomp()-self.world.computer.oldvel.xcomp())
        YDiff = -(self.vel.ycomp()-self.world.computer.oldvel.ycomp())
        speed = self.vel.magnitude
        if self.vel.magnitude >= 0:
            speed += .3
        else:
            speed -= .3
        if XDiff > 0:
            if YDiff > 0:
                Angle = math.degrees(math.atan(YDiff/XDiff))
                XSpeed = -speed*math.cos(math.radians(Angle))
                YSpeed = -speed*math.sin(math.radians(Angle))
            elif YDiff < 0:
                Angle = math.degrees(math.atan(YDiff/XDiff))
                XSpeed = -speed*math.cos(math.radians(Angle))
                YSpeed = -speed*math.sin(math.radians(Angle))
        elif XDiff < 0:
            if YDiff > 0:
                Angle = 180 + math.degrees(math.atan(YDiff/XDiff))
                XSpeed = -speed*math.cos(math.radians(Angle))
                YSpeed = -speed*math.sin(math.radians(Angle))
            elif YDiff < 0:
                Angle = -180 + math.degrees(math.atan(YDiff/XDiff))
                XSpeed = -speed*math.cos(math.radians(Angle))
                YSpeed = -speed*math.sin(math.radians(Angle))
        elif XDiff == 0:
            if YDiff > 0:
                Angle = -90
            else:
                Angle = 90
            XSpeed = -speed*math.cos(math.radians(Angle))
            YSpeed = -speed*math.sin(math.radians(Angle))
        elif YDiff == 0:
            if XDiff < 0:
                Angle = 0
            else:
                Angle = 180
            XSpeed = -speed*math.cos(math.radians(Angle))
            YSpeed = -speed*math.sin(math.radians(Angle))
        self.oldvel = self.vel
        if self.damage < 5:
            damfact = 5
        damfact = self.damage
        self.vel.magnitude = -damfact*.3*math.sqrt((math.pow(XSpeed,2) + math.pow(YSpeed,2)))
        if self.vel.magnitude < -4:
            self.vel.magnitude = -4
        self.damage += 1
        # uncomment the next line for debug infos
        #print entry

    def setkeyMap(self, keyMap):
        self.keyMap = keyMap

    def setTexture(self,key):
        basepos = self.base.getPos()
        basehpr = self.base.getHpr()
        turrethpr = self.turret.getHpr()
        cannonhpr = self.cannon.getHpr()
        self.base.delete()
        self.turret.delete()
        self.cannon.delete()
        if key == 4: #Blue
            self.base = Actor("baseblue.egg", {"moveforwards":"forwards.egg","movebackwards":"backwards.egg", "turnleft":"left.egg","turnright":"right.egg"})
            self.turret = Actor("turretblue.egg")
            self.cannon = Actor("cannonblue.egg")
        if key == 5: #Purple
            self.base = Actor("basepurple.egg", {"moveforwards":"forwards.egg","movebackwards":"backwards.egg", "turnleft":"left.egg","turnright":"right.egg"})
            self.turret = Actor("turretpurple.egg")
            self.cannon = Actor("cannonpurple.egg")
        if key == 6: #Green
            self.base = Actor("basegreen.egg", {"moveforwards":"forwards.egg","movebackwards":"backwards.egg", "turnleft":"left.egg","turnright":"right.egg"})
            self.turret = Actor("turretgreen.egg")
            self.cannon = Actor("cannongreen.egg")
        if key == 7: #Yellow
            self.base = Actor("baseyellow.egg", {"moveforwards":"forwards.egg","movebackwards":"backwards.egg", "turnleft":"left.egg","turnright":"right.egg"})
            self.turret = Actor("turretyellow.egg")
            self.cannon = Actor("cannonyellow.egg")
        if key == 8: #Red
            self.base = Actor("basered.egg", {"moveforwards":"forwards.egg","movebackwards":"backwards.egg", "turnleft":"left.egg","turnright":"right.egg"})
            self.turret = Actor("turretred.egg")
            self.cannon = Actor("cannonred.egg")
        self.base.setScale(.75)
        self.base.reparentTo(render)
        self.base.setPosHpr(basepos,basehpr)
        self.turret.setScale(.75)
        self.turret.reparentTo(render)
        self.turret.setHpr(turrethpr)
        self.cannon.setScale(.75)
        self.cannon.reparentTo(render)
        self.cannon.setHpr(cannonhpr)
        self.moveforwardscontrol=self.base.getAnimControl("moveforwards") #Set animation control for moveforwards
        self.movebackwardsscontrol=self.base.getAnimControl("movebackwards") #Set animation control for moveforwards
        self.turnleftcontrol=self.base.getAnimControl("turnleft") #Set animation control for moveforwards
        self.turnrightcontrol=self.base.getAnimControl("turnright") #Set animation control for moveforwards
        self.haschangedtexture = True
        self.nodePath = self.addCollisionBoundaries()

    def setcurrentWeapon(self, weapon, image):
        self.currentweaponimage.destroy()
        self.currentweapon = weapon
        self.currentweaponimage = OnscreenImage(image = image, pos=(-.99,0,.92),scale=.3)
        self.currentweaponimage.setTransparency(TransparencyAttrib.MAlpha)

    def toggleHeadlights(self):
        if self.headlightstatus == 1: #Headlight is on...turn it off
            #print "Turn headlight off"
            render.clearLight(self.headlightNP)
            self.headlightstatus = 0
        elif self.headlightstatus == 0: #Headlight is off...turn it on
            #print "Turn headlight on"
            render.setLight(self.headlightNP)
            self.headlightstatus = 1

    def setHeadlights(self,task):
        self.headlight.setColor(VBase4(1, 1, 1, 1))
        lens = PerspectiveLens()
        self.headlight.setLens(lens)

        dist = .1
        angle = deg2Rad(self.turret.getH())
        dx = dist * math.sin(angle) #Calculate change in x direction
        dy = dist * -math.cos(angle)#Calculate change in y direction
        self.headlightNP.setPosHpr(self.base.getX()+dx,self.base.getY()+dy,self.base.getZ(),self.base.getH()+180,self.base.getP(),0)
        return Task.cont

    def getCoordinates(self):
        position = self.turret.getPos()
        return([self.turret.getX(),self.turret.getY(),self.turret.getZ()])

    def movePlayer(self,task):
      if self.allowmovement:
        """Code to move the base of the players tank"""
        delta = task.time - self.prevtimeforPlayer
        self.update()
        self.base.setPos(self.base.getX() + self.vel.xcomp(), self.base.getY() + self.vel.ycomp(), 0)
        if self.haschangedtexture == True:
            self.haschangedtexture = False
            self.isMoving = False
        if self.keyMap["forward"]:
            angle = self.base.getH()
            self.move.magnitude = 1.2
            self.move.angle = deg2Rad(angle-90)
        elif self.keyMap["back"]:
            angle = self.base.getH()
            self.move.magnitude = -1.2
            self.move.angle = deg2Rad(angle-90)
        if self.keyMap["left"]:
            self.base.setH(self.base.getH() + delta*100) #fiddle with this number to determine how fast it moves)
        elif self.keyMap["right"]:
            self.base.setH(self.base.getH() - delta*100) #fiddle with this number to determine how fast it moves)
        if not self.keyMap["forward"] and not self.keyMap["back"]:
           self.move.magnitude = 0
        #Code to determine animations:
        if self.keyMap["forward"]:

            if self.isMoving == False:
                self.moveforwardscontrol.setPlayRate(4)#set play rate for moveforwards animation
                self.base.loop("moveforwards")
                self.isMoving = True
        elif self.keyMap["back"]:
            if self.isMoving == False:
                self.movebackwardsscontrol.setPlayRate(4)#set play rate for movebackwards animation
                self.base.loop("movebackwards")
                self.isMoving = True
        elif self.keyMap["left"]:
            if self.isMoving == False:
                self.turnleftcontrol.setPlayRate(4)#set play rate for turnleft animation
                self.base.loop("turnleft")
                self.isMoving = True
        elif self.keyMap["right"]:
            if self.isMoving == False:
                self.turnrightcontrol.setPlayRate(4)#set play rate for turnright animation
                self.base.loop("turnright")
                self.isMoving = True
        else:
            if self.isMoving:
                self.base.stop()
                self.isMoving = False

        if self.isMoving:
            self.soundqueue.loop('engine')#, [self.base.getX()], [self.base.getY()], [self.base.getZ()])
        else:
               self.isMoving = False

        if self.isMoving:
            self.soundqueue.loop('engine')
        else:
            self.soundqueue.unloop('engine')

        self.moveplayerTurret()
        self.oldvel = self.vel
        self.prevtimeforPlayer = task.time
        return Task.cont

    def fire(self, task):
        delta = task.time - self.prevtimeforPlayer
        #print "Turret Pos: ", self.turret.getPos()
        if self.firedCannon:
            self.fireCountCannon -= 1
            if self.fireCountCannon == 0:
                self.fireCountCannon = 60
                self.firedCannon = False
        if self.firedMG:
            self.fireCountMG -= 1
            if self.fireCountMG == 0:
                self.fireCountMG = random.randint(6,11)
                self.firedMG = False
        if self.keyMap["fire"] and ((not self.firedCannon and self.currentweapon == 1) or (not self.firedMG and self.currentweapon == 2)):
            lenCannon = 1
            if self.currentweapon == 1:
                shot = projectile.projectile(.1, self, lenCannon, deg2Rad(self.cannon.getP()+90), deg2Rad(self.cannon.getH()-90), 1 )
                self.soundqueue.enqueue('cannon', self.base.getX(), self.base.getY(), self.base.getZ())
            else:
                shot = projectile.projectile(.1, self, lenCannon, deg2Rad(self.cannon.getP()+90), deg2Rad(self.cannon.getH()-90), 2 )
                self.soundqueue.enqueue('bang', self.base.getX(), self.base.getY(), self.base.getZ())
            shot.velx += self.vel.xcomp()
            shot.vely += self.vel.ycomp()

            proj = lenCannon * math.sin(self.cannon.getP()+90)
            tipx = proj * math.cos(self.cannon.getH()-90)
            tipy = proj * math.sin(self.cannon.getH()-90)
            tipz = lenCannon * math.cos(self.cannon.getP()+90)
            shot.model.setPos((self.base.getX()), (self.base.getY()), (self.base.getZ()-1))
            shot.model.setH(self.cannon.getH())
            #print "Shot model: ", shot.model.getPos()
            #print "Cannon model: ", self.cannon.getPos()
            self.projectiles.append(shot)
            if self.currentweapon == 1:
                self.firedCannon = True
            else:
                self.firedMG = True
        for i in range(len(self.projectiles)):
            if i < len(self.projectiles):
                if self.projectiles[i].model.getZ() < -20 or self.projectiles[i].model.getZ() > 150 or math.sqrt((self.projectiles[i].model.getX()) ** 2 + (self.projectiles[i].model.getY()) ** 2) > 200:
                    base.cTrav.removeCollider(self.projectiles[i].nodePath)
                    self.projectiles[i].model.removeNode()
                    del self.projectiles[i]
                    i -= 1
                else:
                    self.projectiles[i].model.setPos(self.projectiles[i].model.getX() + self.projectiles[i].velx, self.projectiles[i].model.getY() + self.projectiles[i].vely, self.projectiles[i].model.getZ() + self.projectiles[i].velz)
                    self.projectiles[i].grav()
        self.prevtimeforPlayer = task.time
        return Task.cont

    def moveplayerTurret(self):
        #Set Position on top of base:
        baseposition = self.base.getPos()
        self.turret.setPos(self.base.getX(),self.base.getY(),self.base.getZ())

        if base.mouseWatcherNode.hasMouse():
            x=base.mouseWatcherNode.getMouseX() #get mouse coordinates
            y=base.mouseWatcherNode.getMouseY()
            move = [x,y] #Where mouse moved to
            factor = 10
            base.win.movePointer(0, 400, 300) #Move cursor to center of screen
            deltaHeading = self.cannon.getH() + move[0] * -100 #Calculate change in heading
            deltaPitch = self.cannon.getP() + move[1] * -100   #Calculate change in pitch

            if deltaPitch < -15:
                deltaPitch = -15
            if deltaPitch > 1:
                deltaPitch = 1

            self.turret.setH(deltaHeading) #Animate change in heading
            self.cannon.setH(deltaHeading)
            #self.turret.setP(deltaPitch)   #Animate change in pitch - this would be for the actual gun, if we were going to give it the ability to move up and down
            self.cannon.setP(deltaPitch)   #Animate change in pitch - this would be for the actual gun, if we were going to give it the ability to move up and down

        dist = self.cannon.getP()*-1 #When the cannon pitches upwards it moves backwards a bit...this fixes it...but I have no idea why it works
        angle = deg2Rad(self.cannon.getH())
        dx = dist * math.sin(angle) #Calculate change in x direction
        dy = dist * -math.cos(angle)#Calculate change in y direction
        dx = dx/40
        dy = dy/40
        self.cannon.setPos(self.base.getX()+dx,self.base.getY()+dy,self.base.getZ())

        position = self.cannon.getPos()
        xposition = self.cannon.getX() #Used to get current coordinates of the turret
        yposition = self.cannon.getY()
        zposition = self.cannon.getZ()

        dist = 20
        angle = deg2Rad(self.cannon.getH())
        dx = dist * math.sin(angle) #Calculate change in x direction
        dy = dist * -math.cos(angle)#Calculate change in y direction

        dist = 15
        angle = deg2Rad(self.cannon.getP())
        dz = dist*math.tan(angle)   #Calculate change in pitch

        pitch = self.cannon.getP()  #Set pitch of camera (limits it so player can only look so high and so low)
        if self.cannon.getP() > 8.6:
            pitch = 8.6
        if self.cannon.getP() < -4.0:
            pitch = -4.0
        pitch +=5
        camera.setPosHpr(xposition-dx,yposition-dy,self.base.getZ()+5,self.cannon.getH()+180,-pitch,0) #Set camera position, heading, pitch and roll

        #Set Crosshair position - If you are moving rediculously fast this gets out of alignment...I don't know why

        if self.currentweapon == 1:
            dist = 40
            angle = deg2Rad(self.cannon.getH())
            dx = dist * math.sin(angle) #Calculate change in x direction
            dy = dist * -math.cos(angle)#Calculate change in y direction

        if self.currentweapon == 2:
            dist = 60
            angle = deg2Rad(self.cannon.getH())
            dx = dist * math.sin(angle) #Calculate change in x direction
            dy = dist * -math.cos(angle)#Calculate change in y direction

        xvalues = (xposition+dx-xposition)  #Distance formula
        yvalues = (yposition+dy-yposition)
        xsquared = math.pow(xvalues,2)
        ysquared = math.pow(yvalues,2)
        distance = math.sqrt(xsquared+ysquared)
        pitch = self.cannon.getP()*-1
        pitch = deg2Rad(pitch)
        dz = (math.tan(pitch)) * (distance)

        self.crosshair.setPosHpr(xposition+dx,yposition+dy,dz,self.turret.getH(),0,0)
        # Convert the point into the camera's coordinate space
        p3d = base.camera.getRelativePoint(self.crosshair, Point3(self.crosshair.getX(),self.crosshair.getY(),self.crosshair.getZ()))
        # Ask the lens to project the 3-d point to 2-d.
        p2d = Point2()

        if base.camLens.project(p3d, p2d):
            self.crosshair2d.destroy()
            if self.currentweapon == 1:
                self.crosshair2d=OnscreenImage(image = "cannoncrosshair.png", pos=(p2d[0],0,p2d[1]),scale=0.1)
                self.crosshair2d.setTransparency(TransparencyAttrib.MAlpha)
            elif self.currentweapon == 2:
                self.crosshair2d=OnscreenImage(image = "machineguncrosshair.png", pos=(p2d[0],0,p2d[1]),scale=0.1)
                self.crosshair2d.setTransparency(TransparencyAttrib.MAlpha)


import os
from pathlib import Path
from typing import Any, Dict, List, Optional

from .exceptions import NoArgsException
from .utils import Site, TechnologiesProcessor, read_json

ABS_PATH = Path(__file__).resolve().parent

class Pywappalyzer:
    def __init__(self):
        self.technologies = read_json(
            str(os.path.join(ABS_PATH, "db/technologies.json"))
        )
        self.categories = read_json(str(os.path.join(ABS_PATH, "db/categories.json")))

    def analyze(self, url: str) -> Dict[str, List[str]]:
        """
        Analyze technologies of web page
        :param url: Url of web site
        :return: Dictionary of technologies.
            {"Web servers": ["Nginx"], ...}
        """
        site = Site(url=url)
        if site.headers is None:
            raise NoArgsException("No site headers")

        headers: Dict[str, Any] = site.headers
        processor = TechnologiesProcessor(
            headers=headers,
            site=site,
            technologies=self.technologies,
            categories=self.categories,
        )

        return processor.analyze()

    def analyze_html(
        self, html: Optional[bytes] = None, *, file: Optional[str] = None
    ) -> Dict[str, List[str]]:
        """
        Analyze HTML from file or provided variable
        :param html: HTML content
        :param file: File with HTML content
        :return: Dictionary of technologies
        """
        if file:
            with open(file, "rb") as f:
                html = f.read()

        if not html and not file:
            raise NoArgsException("Provide html or file argument to function")

        result = TechnologiesProcessor.analyze_html(
            html=html, technologies=self.technologies, categories=self.categories  # type: ignore
        )
        return result

    def use(self, technologies: dict) -> None:
        """
        Use provided technologies/categories json
        """
        self.technologies = technologies["technologies"]
        self.categories = technologies["categories"]


import string
import random
import operator
from operator import itemgetter

class WordFun:

    def __init__(self, word_file):
        self.wordFile = word_file
        chunk = self.wordFile.read()
        self.words = chunk.split("\n")
        self.n_gram_index = {}
        self.n_gram_stats = {}
        return

    def find_n_gram_matches(self, n = 2):
        letters = list(string.ascii_lowercase)
        consonants = list(filter(lambda x: x not in ['a', 'e', 'i', 'o', 'u'], letters))
        chosen = random.sample(consonants, n)
        matches = list(filter(lambda x: "".join(chosen) in x, self.words))
        print("chosen = " + str(chosen))
        input("Press enter to continue...")
        print("matches = " + str(matches))
        return

    def gen_stats_of_n_grams(self, n = 2):
        n_words = 0
        letters = list(string.ascii_lowercase)
        consonants = list(filter(lambda x: x not in ['a', 'e', 'i', 'o', 'u'], letters))
        for word in self.words:
            length = len(word)
            if length >= n:
                for i in range(length - n + 1):
                    n_gram = word[i:(i+n)]
                    #if (n_gram[0] in consonants) and (n_gram[1] in consonants):
                    if all(x in consonants for x in n_gram):
                        if n_gram in self.n_gram_index:
                            wordlist = self.n_gram_index[n_gram]
                            count = self.n_gram_stats[n_gram]
                            self.n_gram_index[n_gram] = wordlist + [word]
                            self.n_gram_stats[n_gram] = count + 1
                        else:
                            self.n_gram_index[n_gram] = [word]
                            self.n_gram_stats[n_gram] = 1
            n_words = n_words + 1
            if n_words % 10000 == 0:
                print("word = " + word + ", n_words = " + str(n_words))
        self.n_gram_stats = sorted(self.n_gram_stats.items(), key = itemgetter(1), reverse = True)

        for (n_gram, count) in self.n_gram_stats:
            print("n_gram = " + n_gram + ", count = " + str(count))
        print(len(self.n_gram_stats))
        return

if __name__ == '__main__':
    word_file = open("C:\\Users\\bibudh.lahiri\\Desktop\\words.txt", "r")
    wf = WordFun(word_file)
    #wf.find_n_gram_matches(2)
    wf.gen_stats_of_n_grams()


from django.contrib import admin
from .models import Custom_User
from .forms import CustomUserCreationForm
from django.contrib.auth.admin import UserAdmin

# Register your models here.
class CustomUserAdmin(UserAdmin):
    model = Custom_User
    add_form = CustomUserCreationForm
    fieldsets = (
        *UserAdmin.fieldsets,
        (
            'Personal info',
            {
                'fields': (
                    'DOB',
                )
            }
        )
    )

admin.site.register(Custom_User, CustomUserAdmin)


#!/usr/bin/python3
"""define a class"""

class Square:
    """
    A class used to represent a Square

    ...

    Attributes
    ----------
    __size : int
        the size of the square
    __position : tuple
        the position of the square

    Methods
    -------
    area():
        Returns the area of the square
    my_print():
        Prints the square with the character #
    """

    def __init__(self, size=0, position=(0, 0)):
        """
        Constructs all the necessary attributes for the square object.

        Parameters
        ----------
            size : int
                the size of the square (default is 0)
            position : tuple
                the position of the square (default is (0,0))
        """

        self.size = size
        self.position = position

    @property
    def size(self):
        """
        Retrieves the value of __size
        """
        return self.__size

    @size.setter
    def size(self, value):
        """
        Sets the value of __size

        Parameters
        ----------
        value : int
            the size of the square

        Raises
        ------
        TypeError
            if size is not an integer
        ValueError
            if size is less than 0
        """
        if not isinstance(value, int):
            raise TypeError("size must be an integer")
        if value < 0:
            raise ValueError("size must be >= 0")
        self.__size = value

    @property
    def position(self):
        """
        Retrieves the value of __position
        """
        return self.__position

    @position.setter
    def position(self, value):
        """
        Sets the value of __position

        Parameters
        ----------
        value : tuple
            the position of the square

        Raises
        ------
        TypeError
            if position is not a tuple of 2 positive integers
        """
        if not isinstance(value, tuple) or \
                len(value) != 2 or \
                not all(isinstance(i, int) and i >= 0 for i in value):
            raise TypeError("position must be a tuple of 2 positive integers")
        self.__position = value

    def area(self):
        """
        Returns the area of the square
        """
        return self.__size ** 2

    def my_print(self):
        """
        Prints the square with the character #

        If size is equal to 0, print an empty line
        position should be used by using space
        """
        if self.__size == 0:
            print("")
        else:
            for i in range(self.__position[1]):
                print("")
            for i in range(self.__size):
                print(" " * self.__position[0], end="")
                print("#" * self.__size)


import numpy as np
from matplotlib import pyplot as plt, gridspec
from pathlib import Path
import imageio as iio
import arabic_reshaper
from persiantools import digits
from bidi.algorithm import get_display
import pandas as pd

plt.rcParams["figure.figsize"] = (11, 12)

def cast_to_int(value):
    return int(round(value))

rows = {
    1: type('Dimension', (), {"height": 0.1, 'width': [0.2, 0.4]}),
    2: type('Dimension', (), {"height": 0.2, 'width': []}),
    3: type('Dimension', (), {"height": 0.25, 'width': [0.15, 0.3]}),
    4: type('Dimension', (), {"height": 0.70, 'width': []}),
    5: type('Dimension', (), {"height": 0.75, 'width': [0.15, 0.3]}),
    6: type('Dimension', (), {"height": 1, 'width': []}),
}

dat = [1, 2, 3, 4, 5, 6, 7, 8, -9, 8, 7, 6, 5, 4, 9]

def remove_axis(ax0):
    ax0.spines['top'].set_visible(False)
    ax0.spines['right'].set_visible(False)
    ax0.spines['left'].set_visible(False)
    ax0.spines['bottom'].set_visible(False)
    ax0.set_xticks([])
    ax0.set_yticks([])
    ax0.set_anchor('W')
    return ax0

fonts = type("Fonts", (), {
    'yekan_bold': Path("utils/fonts/fonts/IRANYEKANBOLD.TTF"),
    'yekan_extra_bold': Path("utils/fonts/fonts/IRANYEKANEXTRABOLD.TTF"),
    'yekan_light': Path("utils/fonts/fonts/IRANYEKANLIGHT.TTF"),
    'yekan': Path("utils/fonts/fonts/IRANYEKANBLACK.TTF"),
    'yekan_num': Path("utils/fonts/fonts/IRANYEKANREGULARFANUM.TTF"),

})

class Plot:

    def __init__(self, width=100, height=100):
        self.gs = None
        self.width = width
        self.height = height
        self.logo_dailytahlil = iio.imread("utils/img/logo_daily_tahlil.png")
        self.logo_tadbirgaran = iio.imread("utils/img/logo_kargozari.png")
        self.icon_bars = iio.imread("utils/img/icon_bars.png")

    def grid_method(self):
        self.gs = gridspec.GridSpec(self.height, self.width, wspace=0, hspace=0)
        ax_daily_tahlil_logo = plt.subplot(
            self.gs[:cast_to_int(rows[1].height * self.height), :cast_to_int(rows[1].width[0] * self.width)])

        ax_tadbirgaran_logo = plt.subplot(
            self.gs[:cast_to_int(rows[1].height * self.height),
            cast_to_int((rows[1].width[0] + 0.02) * self.width):cast_to_int(rows[1].width[1] * self.width)])

        ax_main_title = plt.subplot(
            self.gs[:cast_to_int(rows[1].height * self.height), cast_to_int(rows[1].width[1] * self.width):])

        ax_legend_first_1 = plt.subplot(
            self.gs[cast_to_int(rows[2].height * self.height):cast_to_int(rows[3].height * self.height),
            :cast_to_int(rows[3].width[0] * self.width)])

        ax_legend_first_2 = plt.subplot(
            self.gs[cast_to_int(rows[2].height * self.height):cast_to_int(rows[3].height * self.height),
            cast_to_int(rows[3].width[0] * self.width):cast_to_int(rows[3].width[1] * self.width)])

        ax_legend_first_3 = plt.subplot(
            self.gs[cast_to_int(rows[2].height * self.height):cast_to_int(rows[3].height * self.height),
            cast_to_int(rows[3].width[1] * self.width):])

        ax_others = plt.subplot(self.gs[cast_to_int(rows[3].height * self.height):, :])

        ax_daily_tahlil_logo = remove_axis(ax_daily_tahlil_logo)
        ax_tadbirgaran_logo = remove_axis(ax_tadbirgaran_logo)
        ax_main_title = remove_axis(ax_main_title)
        ax_legend_first_1 = remove_axis(ax_legend_first_1)
        ax_legend_first_2 = remove_axis(ax_legend_first_2)
        ax_legend_first_3 = remove_axis(ax_legend_first_3)

        ax_daily_tahlil_logo.imshow(self.logo_tadbirgaran)
        # title = "این یک متن تست است." + "(ُ1401/10/07)"
        # title = digits.en_to_fa(title)
        # title = get_display(arabic_reshaper.reshape(title))

        # title = "خروج پول حقیقی"
        # title = digits.en_to_fa(title)
        # title = get_display(arabic_reshaper.reshape(title))

        # ax_legend_first_1.bar([0, 1], [0, 1])
        # ax_legend_first_1.text(5, -20, title, font=fonts.yekan_light, size=14, color="gray")
        # ax_legend_first_1.imshow(self.icon_bars, )
        # ax_legend_first_2.imshow(self.icon_bars, )
        # ax_legend_first_3.imshow(self.icon_bars, )
        ax_tadbirgaran_logo.imshow(self.logo_dailytahlil)
        title = "این یک متن تست است." + "(ُ1401/10/07)"
        title = digits.en_to_fa(title)
        title = get_display(arabic_reshaper.reshape(title))
        ax_main_title.text(0.1, 1.75, title, font=fonts.yekan_extra_bold, size=20)
        plt.subplots_adjust(wspace=0, hspace=0)
        self.plot_values(xvals=dat, yvals=dat, title="", ax=ax_others)
        plt.show()

    def plot_values(self, xvals, yvals, title, ax):
        ax.imshow(self.logo_dailytahlil, aspect='auto', extent=(0, len(xvals), min(yvals) / 2, max(yvals) / 2),
                  alpha=0.1,
                  zorder=1)
        xvals = [xvals[i] for i in range(len(yvals)) if not (yvals[i] == np.inf or pd.isna(yvals[i]))]
        yvals = [i for i in yvals if not (i == np.inf or pd.isna(i))]
        xvals = [digits.en_to_fa(get_display(arabic_reshaper.reshape(str(i)))) for i in xvals]
        plt_title = title
        reshaped_text = arabic_reshaper.reshape(plt_title)
        artext = get_display(reshaped_text)
        position = np.arange(len(xvals))
        ax.bar(position, yvals, align='center', linewidth=0)
        for i in position:
            ax.axvline(x=i, ymin=-10 ** 30, ymax=10 ** 30, color='#e6e7e9', linewidth=30, alpha=1, zorder=-1)
        ax.set_xticks(position, xvals)
        ax.set_title(artext, font=fonts.yekan, loc='right', size=14, color='gray')
        ax.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='off')
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['bottom'].set_visible(False)
        ax.spines['left'].set_visible(False)
        ax.tick_params(bottom=False, labelrotation=0, top=False, right=False, left=False)
        ylabels = ax.get_yticks()
        xlabels = ax.get_xticks()
        ylabels = [str(i) for i in ylabels]

        labels = [
            digits.en_to_fa(
                f"({i.replace('-', '').replace(' ', '')[:4]})" if '-' in i else i[:4])
            for
            i in ylabels]
        ylabels = [float(i) for i in ylabels]
        ax.set_yticks(ticks=ylabels, labels=labels, font=fonts.yekan_num)
        ax.set_xticks(ticks=xlabels, labels=xvals, font=fonts.yekan_num, rotation=90)

        # newax = fig.add_axes([0.8, 0.8, 0.2, 0.2], anchor='NE', zorder=1)
        # ax.axvline(x=np.mean(xlabels[len(xlabels) - 2:]), ymin=-1000, ymax=1000, linewidth=0.2, color='black')
        # ax.imshow(self.logo_dailytahlil, extent=[0, 3, -5, 5])

    def barplot_legend(self):
        pass

x = Plot()
x.grid_method()
x.logo_dailytahlil.resize()


class Graph:
    def __init__(self) -> None:
        self.number_of_nodes = 0
        self.adjacency_list = dict()

    def addVertex(self, node):
        self.adjacency_list[node] = []
        self.number_of_nodes += 1

    def addEdge(self, node1, node2):
        # undirected
        if node1 in self.adjacency_list.keys() and node2 in self.adjacency_list.keys():
            self.adjacency_list[node1].append(node2)
            self.adjacency_list[node2].append(node1)
        else:
            print("both verticies must exist")

    def showConnections(self):
        all_nodes = list(self.adjacency_list.keys())
        for node in all_nodes:
            node_connections = self.adjacency_list[node]
            connections = ""
            for vertex in node_connections:
                connections += str(vertex) + " "
            print(f"{node} --> {connections}")

# class Graph {
#   constructor() {
#     this.numberOfNodes = 0;
#     this.adjacentList = {
#     };
#   }
#   addVertex(node)  {
#   }
#   addEdge(node1, node2) {
#     //undirected Graph
#   }
#   showConnections() {
#     const allNodes = Object.keys(this.adjacentList);
#     for (let node of allNodes) {
#       let nodeConnections = this.adjacentList[node];
#       let connections = "";
#       let vertex;
#       for (vertex of nodeConnections) {
#         connections += vertex + " ";
#       }
#       console.log(node + "-->" + connections);
#     }
# }
# }

myGraph = Graph()
myGraph.addVertex("0")
myGraph.addVertex("1")
myGraph.addVertex("2")
myGraph.addVertex("3")
myGraph.addVertex("4")
myGraph.addVertex("5")
myGraph.addVertex("6")
myGraph.addEdge("3", "1")
myGraph.addEdge("3", "4")
myGraph.addEdge("4", "2")
myGraph.addEdge("4", "5")
myGraph.addEdge("1", "2")
myGraph.addEdge("1", "0")
myGraph.addEdge("0", "2")
myGraph.addEdge("6", "5")

myGraph.showConnections()
# Answer:
# 0-->1 2
# 1-->3 2 0
# 2-->4 1 0
# 3-->1 4
# 4-->3 2 5
# 5-->4 6
# 6-->5


import tensorflow as tf

sess = tf.InteractiveSession()

# n x 50 x 50 input
images = tf.placeholder(tf.bool, shape=[None, 2500])
# n x 1 output
labels = tf.placeholder(tf.bool, shape=[None, 1])

# weights and bias init 0
W = tf.Variable(tf.zeros([2500,1]))
b = tf.Variable(tf.zeros([1]))

# init variables
sess.run(tf.global_variables_initializer())

# set predictions
predictions = tf.sigmoid(tf.matmul(images, W) + b)


from celery import shared_task
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
from celery_practice import settings

@shared_task(bind=True)
def send_mail_func(self):
    users=get_user_model().objects.all()
    for user in users:
        mail_subject="Hii suraj here celery testing"
        message="we have new offer going to start from tomorrow till wednseday morning. please Hurry up!!!!"
        to_email=user.email
        send_mail(
            subject=mail_subject,
            message=message,
            from_email=settings.EMAIL_HOST_USER,
            recipient_list=[to_email],
            fail_silently=True,
        )

    return "Done"


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function

import csv
import datetime
import sys

USD = 'USD'
POSITION_TEXT = 'Position closed'
FEE_TEXT = 'Trading fees'
FUNDCOST_TEXT = 'funding cost'
FUNDFEE_TEXT = 'Unused Margin Funding Fee'
FUNDPAY_TEXT = 'Funding Payment'

DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'

class ProfitCalc(object):
    def __init__(self, csvfiles):
        self._csvfiles = csvfiles

    def print_amount(self, amount, desc=None, prefix=' '):
        if desc:
            desc = ' (%s)' % desc
        print('%s%10.2f%s' % (prefix, amount, desc or ''))

    def process(self):
        dates = []
        positions = []
        fees = []
        fundcosts = []
        fundpays = []

        for csvfile in self._csvfiles:
            with open(csvfile, 'r') as f:
                data = f.read()

            reader = csv.reader(data.splitlines())
            for row in reader:
                currency = row[0]
                if currency != USD:
                    continue

                desc = row[2]
                amount = float(row[3])
                datestr = row[5]

                dates.append(
                    datetime.datetime.strptime(datestr, DATETIME_FORMAT))
                if POSITION_TEXT in desc:
                    positions.append(amount)
                elif FEE_TEXT in desc:
                    fees.append(amount)
                elif FUNDCOST_TEXT in desc or FUNDFEE_TEXT in desc:
                    fundcosts.append(amount)
                elif FUNDPAY_TEXT in desc:
                    fundpays.append(amount)

        total_margin = sum(positions)
        total_fees = sum(fees)
        total_fundcosts = sum(fundcosts)
        total_funding = sum(fundpays)

        print('Profit from %s to %s:' % (min(dates), max(dates)))
        self.print_amount(total_margin, 'margin earnings')
        self.print_amount(total_fees, 'trading fees')
        self.print_amount(total_fundcosts, 'funding costs')
        self.print_amount(total_funding, 'funding earnings')
        print('-' * 30)
        self.print_amount(
                total_margin + total_fees + total_fundcosts + total_funding,
                prefix='=')

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('Usage: %s ledger-downloaded-from-bitfinex.csv' % sys.argv[0])
        sys.exit()

    ProfitCalc(sys.argv[1:]).process()


# -*- coding: utf-8 -*-
# +
# %load_ext autoreload
# %autoreload 2

import subspace as sub
import numpy as np
import cv2
import multiprocessing as multi
import draw
from matplotlib import pyplot as plt

# -

# ### 4.1 Multiprozessing Hough Algorithmus
#
# Die Hough Transformation wurde aufgrund des einfachen Algorithmus der auch auf [Wikipedia](
# https://de.wikipedia.org/wiki/Hough-Transformation) zu finden ist implementiert.
# Hier ist der entsprechende Pseudocode:
#
# $
# \texttt{max}_d \texttt{ := } \sqrt{bildhöhe^2 + bildbreite^2} \\
# \texttt{min}_d \texttt{ := } \texttt{max}_d \cdot -1 \\
# \texttt{houghRaum}[0 \ldots \pi][\texttt{min}_d \ldots \texttt{max}_d] := 0 \\
# \texttt{foreach pixel != 0 do} \\
# \hspace{0.5cm}\texttt{for } \alpha := 0 \texttt{ to } \pi \texttt{ do } \\
# \hspace{1.0cm}  \texttt{d := pixel}_x \cdot \cos(\alpha ) + \texttt{pixel}_y \cdot \sin(\alpha ) \\
# \hspace{1.0cm}  \texttt{houghRaum}[\alpha][\texttt{d}]++ \\
# \hspace{0.5cm}\texttt{end}\\
# \texttt{end}\\
# $
#
# Der Code musste auf die Subspaces angepasst werden. Der größte Unterschied ist das durchlaufen des Raumes.
# Zunächst wird dafür eine virtuelle Achse gebildet die jede diskrete Zelle in allen 3 Subspaces einmal durchläuft. Außerdem muss im Gegesatz zum normalen hough beide Achsen des Parameterraums durchlaufen werden.
# Sonst werden duch die Diskretisierung viele Geraden nicht gefunden.
#
# In dem folgenden Codeblock ist ein Durchlauf eines (x, y) paares auf den Subspaces. Dies ist equivalent zu
# diesem Teil des pseudocodes.
#
# $
# \texttt{for } \alpha := 0 \texttt{ to } \pi \texttt{ do } \\
# \hspace{0.5cm}  \texttt{d := pixel}_x \cdot \cos(\alpha ) + \texttt{pixel}_y \cdot \sin(\alpha ) \\
# \hspace{0.5cm}  \texttt{houghRaum}[\alpha][\texttt{d}]++ \\
# \texttt{end}\\
# $
#
# Nachdem die subspace Achse berechnet wurde werden sie umgeformt, dass man jeweils Wertepaare `(x, x, 1)` erhält. Im nächsten Schritt werden über entsprechende Matrizen entweder `a` oder `b` für den jeweiligen Wert ausgerechnet und in einem Subspace eingefügt. Der Wert wird dabei auf `1` gesetzt, dadurch wird ein Wert für den selben Wert von `x` o.`y` nicht doppelt gesetzt.

def _hough_vec_process(input_values):
  resolution = int(input_values[6, 0])
  Ma = input_values[0:3]
  Mb = input_values[3:6]

  values, _ = sub.subspace_axis(resolution)
  values = np.c_[ values, values, np.ones(len(values)) ]

  space = sub.subspaces_create(resolution, dtype = np.uint8)
  for M in [Ma, Mb]:
    ab_array = np.einsum('ij,...j', M, values)[:, :2]
    ab_array = ab_array[~np.isnan(ab_array[:, 0])]
    if ab_array.size > 0:
      # long running
      np.apply_along_axis(lambda ab: sub.subspaces_itemset(space, ab, 1), 1, ab_array)

  return space

# Die beiden Matrizen werden bestimmt durch Umformung von
#
# $$
#     ax + b + y = 0
# $$
#
# und entsprechende Umwandlung in eine Matrix. Die Umformungen lauten dabei.
#
# $$
#     a = -b\frac{1}{x} + \frac{-y}{x} \\
#     b = -ax - y
# $$
#
# Für Bildpixel die 0 sind wird eine invalide Matrix ausgegeben, diese wird im späteren Verlauf
# herausgefiltert.

# +
nan_m = np.array([
        [np.nan, 0, 0],
        [0, np.nan, 0],
        [0, 0, np.nan]
      ])

def _value_filter_a_iterate(src_xy):
  src, x, y = src_xy
  if x == 0 or sub.subspaces_item(src, (x, y)) == 0:
    return nan_m
  return np.array([
    [-1/x, 0, -y/x],
    [1, 0, 0],
    [0, 0, 1]
  ])

def _value_filter_b_iterate(src_xy):
  src, x, y = src_xy
  if sub.subspaces_item(src, (x, y)) == 0:
    return nan_m
  return np.array([
    [1, 0, 0],
    [0, -x, -y],
    [0, 0, 1]
  ])

# -

# Zuletzt die Funktion `hough_vec` die zunächst alle `(x,y)` paare durch cartesisches Produkt der
# beiden möglichen Achsenwerte des gesamten Subspaces ermittelt (`prod`). Daraufhin parallel die
# matrizen berechnet. Die invaliden Matrizen werden gefiltert und schließlich werden auf allen
# verfügbaren Kernen die Hough durchgänge vollzogen. Da die Datenmenge hier extrem ansteigt und die
# Cpu-Kerne möglichst augenutzt werden sollten wird zudem die maximale chunk size ausgerechnet.
#
# Die Chunk Size gibt an wieviel Matrizen ein Prozess ausrechnen soll. Wenn eine chunk size von 1
# gewählt wird resultiert dies in excesiver IPC und die Prozessorkerne werden nicht ausgelastet.
# Wählt man die Chunk Size zu hoch wird die dabei entstehende Menge an Subspaces so groß, dass
# man den verfügbaren Speicher überlastet, oder sogar einen Out of Memory erhält.
#
# $$
# max(chunksize) < \frac{memory}{overhead * 3 * (resolution * resolution * sizeof(subspace\; element))}
# $$
#
# Eine weitere Optimierung wäre es die Addition der einzelnen subspaces zum Schluss zu parallelisieren.
# Über eine Art Map-Reduce Verfahren. Im Augenblick werden diese zum übergeordneten subspace dazugerechnet
# sobald diese verfügbar sind. Außerdem lassen sich verschiedene wiederholende Operationen auch vorberechnen.
# Unter andem die Matrizen verändern sich nicht bei der selben resolution, oder auch die achsen.

def hough_vec(src: sub.subspaces_t, max_memory: int) -> sub.subspaces_t:
  resolution = sub.subspaces_resolution(src)
  cpus = multi.cpu_count() - 2
  ss = sub.subspaces_create(resolution)
  values, _ = sub.subspace_axis(resolution)

  # cartesian product
  prod = sub.cartesian_product(values, values)

  # needs the most amount of time
  with multi.Pool(multi.cpu_count()) as p:
    iterate = [[src, x, y] for x, y in prod]
    chunksize = max(1, (len(iterate) // multi.cpu_count()))
    Ma_iterate = np.array(p.map(_value_filter_a_iterate, iterate, chunksize = chunksize))
    Mb_iterate = np.array(p.map(_value_filter_b_iterate, iterate, chunksize = chunksize))

  # filter out matrices where both are nan for the same pixel
  M_iterate_filter = ~np.isnan(Ma_iterate[:,0,0]) & ~np.isnan(Mb_iterate[:,0,0])

  Ma_iterate = Ma_iterate[M_iterate_filter].reshape(-1, 3, 3)
  Mb_iterate = Mb_iterate[M_iterate_filter].reshape(-1, 3, 3)

  M_iterate = np.column_stack((Ma_iterate, Mb_iterate, np.full((len(Ma_iterate), 3, 3), resolution)))

  print("done setup")
  with multi.Pool(multi.cpu_count()) as p:
    size_of_subspaces =  2 * 3 * (resolution * resolution)
    max_chunk_size = max_memory // (size_of_subspaces * cpus)
    chunksize = min(max_chunk_size, max(1, (len(M_iterate) // multi.cpu_count())))
    print("chunksize: {} on {} GiB total memory with subspaces_size = {} and max_chunk = {}".format(chunksize, max_memory / 1024**3, size_of_subspaces, max_chunk_size))
    iterator = p.imap_unordered(_hough_vec_process, M_iterate, chunksize = chunksize)
    for i, space in enumerate(iterator):
      sub.subspaces_add_to(ss, space)
      draw.progress(i, len(M_iterate))

  return ss

if __name__ == '__main__':
  image_path = '../images/hough.png'
  resolution = 200

  image = cv2.imread(image_path)
  image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  image = cv2.resize(image, (resolution, resolution))

  src = sub.subspaces_from_image(resolution, image)

  ss = hough_vec(src)

  fig, axs = plt.subplots(1, 3, sharey=True)
  for i, space in enumerate(ss):
    axs[i].imshow(space, 'gray', extent=[-1, 1, 1, -1])


from keras.datasets import mnist
dataset = mnist.load_data('mymnist.db')
train , test = dataset
X_train , y_train = train
X_test , y_test = test
X_train_1d = X_train.reshape(-1 , 28*28)
X_test_1d = X_test.reshape(-1 , 28*28)
X_train = X_train_1d.astype('float32')
X_test = X_test_1d.astype('float32')
from keras.utils.np_utils import to_categorical
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(units=1024, input_dim=28*28, activation='relu'))
model.add(Dense(units=512, activation='relu'))
model.add(Dense(units=400, activation='relu'))
model.add(Dense(units=200, activation='relu'))
model.add(Dense(units=128, activation='relu'))
model.add(Dense(units=64, activation='relu'))
model.add(Dense(units=32, activation='relu'))
model.add(Dense(units=10, activation='softmax'))
model.summary()

from keras.optimizers import RMSprop
model.compile(optimizer=RMSprop(), loss='categorical_crossentropy',
             metrics=['accuracy']
             )

h = model.fit(X_train, y_train, epochs=2)
model.save("mnistmodel.h5")
print("model trained successfully")
prediction = model.evaluate(X_test,y_test)
#added a comment
#another comment
with open("accuracy.txt","w") as out_file:

        out_string = ""
        out_string += str(prediction[1])
        out_file.write(out_string)
print("file created successfully")


import json
from starlette.responses import Response
from pydantic import typing

from fastapi_extra.shcema.response_wrapper import ResponseWrapper

class WrapperResponse(Response):
    media_type = "application/json"

    def render(self, content: typing.Any) -> bytes:
        response = {}
        if not isinstance(content, ResponseWrapper):
            response['result'] = content
        else:
            response = content
        return json.dumps(
            response,
            ensure_ascii=False,
            allow_nan=False,
            indent=None,
            separators=(",", ":"),
        ).encode("utf-8")


'''
Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4
'''

import operator
from functools import reduce

class Solution:
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        for i in range(0,len(nums)-1,2):
            if nums[i] != nums[i+1]:
                return nums[i]

        return nums[-1]

    def singleNumber2(self,nums):
        return reduce(operator.xor,nums)

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        from functools import reduce
        return reduce(lambda x, y: x^y, nums)

if __name__ == '__main__':
    solution = Solution()
    print(solution.singleNumber([4,1,2,1,2]))
    print(solution.singleNumber2([4,1,2,1,2]))


#!/usr/bin/env python3

import rospy
from autoware_msgs.msg import Lane, WaypointState
from visualization_msgs.msg import MarkerArray, Marker
from std_msgs.msg import ColorRGBA

class GlobalPathVisualizer:
    def __init__(self):

        # Publishers
        self.global_path_markers_pub = rospy.Publisher('global_path_markers', MarkerArray, queue_size=1, latch=True)

        # Subscribers
        rospy.Subscriber('global_path', Lane, self.global_path_callback, queue_size=1)

    def global_path_callback(self, lane):
        marker_array = MarkerArray()

        if len(lane.waypoints) == 0:
            # create marker_array to delete all visualization markers
            marker = Marker()
            marker.header.frame_id = lane.header.frame_id
            marker.action = Marker.DELETEALL
            marker_array.markers.append(marker)

        else:
            # Pose arrows
            for i, waypoint in enumerate(lane.waypoints):

                # color the arrows based on the waypoint steering_flag (blinker)
                if waypoint.wpstate.steering_state == WaypointState.STR_LEFT:
                    color = ColorRGBA(1.0, 0.0, 0.0, 1.0)
                elif waypoint.wpstate.steering_state == WaypointState.STR_RIGHT:
                    color = ColorRGBA(0.0, 0.0, 1.0, 1.0)
                else:
                    color = ColorRGBA(0.0, 1.0, 0.0, 1.0)

                marker = Marker()
                marker.header.frame_id = lane.header.frame_id
                marker.header.stamp = rospy.Time.now()
                marker.ns = "Waypoint pose"
                marker.id = i
                marker.type = marker.ARROW
                marker.action = marker.ADD
                marker.pose = waypoint.pose.pose
                marker.scale.x = 0.4
                marker.scale.y = 0.1
                marker.scale.z = 0.1
                marker.color = color
                marker_array.markers.append(marker)

            # velocity labels
            for i, waypoint in enumerate(lane.waypoints):
                marker = Marker()
                marker.header.frame_id = lane.header.frame_id
                marker.header.stamp = rospy.Time.now()
                marker.ns = "Velocity label"
                marker.id = i
                marker.type = marker.TEXT_VIEW_FACING
                marker.action = marker.ADD
                marker.pose = waypoint.pose.pose
                marker.scale.z = 0.5
                marker.color = ColorRGBA(1.0, 1.0, 1.0, 1.0)
                marker.text = str(round(waypoint.twist.twist.linear.x * 3.6, 1))
                marker_array.markers.append(marker)

            # line strips
            marker = Marker()
            marker.header.frame_id = lane.header.frame_id
            marker.header.stamp = rospy.Time.now()
            marker.ns = "Path"
            marker.type = marker.LINE_STRIP
            marker.action = marker.ADD
            marker.id = 0
            marker.pose.orientation.w = 1.0
            marker.scale.x = 1.5
            marker.color = ColorRGBA(0.9, 0.6, 1.0, 0.6)
            for waypoint in lane.waypoints:
                marker.points.append(waypoint.pose.pose.position)
            marker_array.markers.append(marker)

        self.global_path_markers_pub.publish(marker_array)

    def run(self):
        rospy.spin()

if __name__ == '__main__':
    rospy.init_node('global_path_visualizer', log_level=rospy.INFO)
    node = GlobalPathVisualizer()
    node.run()


#!/usr/bin/env python

import rospy
import string
import math
import sys

#from time import time
from sensor_msgs.msg import LaserScan
#from geometry_msgs.msg import Twist
#from visualization_msgs.msg import Marker

degrees2rad = math.pi/180.0
rsvURG = LaserScan()

def cb_LaserScan(dt):
	global rsvURG
	rsvURG = dt

rospy.init_node("urgtalker_node")
#We only care about the most recent measurement, i.e. queue_size=1
pub = rospy.Publisher('/torosif/scan', LaserScan, queue_size=1)
#srv = Server(imuConfig, reconfig_callback)  # define dynamic_reconfigure callback
#diag_pub = rospy.Publisher('diagnostics', DiagnosticArray, queue_size=1)
#diag_pub_time = rospy.get_time();
sub = rospy.Subscriber('/last', LaserScan, cb_LaserScan)

seq=0
rospy.loginfo("Start UrgScan to Rosif ...")

while not rospy.is_shutdown():

    pub.publish(rsvURG)
    rospy.sleep(0.1)


#!/usr/bin/env python

from PersonRepository import PersonRepository
from faceHelpers import *
from definitions import IMAGE_FOLDER_PATH

############################# Util ############################################
def getListOfFaces(faceList):
    """
    Utility function to get list of faceIds from detected faces list
    """
    faceIdList = [faceDict['faceId'] for faceDict in faceList]
    return faceIdList

def detectAndIdentifyPerson(personGroupId):
    image = IMAGE_FOLDER_PATH + '/Testing/Friends.jpg'

    # Detect faces in the image
    detectedFacesList = detectPersonFace(image, attributes='age,emotion,smile')
    print('printing detected faces list')
    print(detectedFacesList)
    # Get list of detected faceId's
    detectedFaceIds = getListOfFaces(detectedFacesList)

    identificationDetails = identifyPersonFace(detectedFaceIds, personGroupId)
    print(identificationDetails)

# Write a method to match the candidates of a face-match with name of person in the person_group
#[{'faceId': 'f386a877-9826-4bbc-b205-70280a04787e', 'candidates': []}, {'faceId': 'bb29b634-4389-4e64-bdb4-68f5fd2d7ea8', 'candidates': [{'personId': 'aaaafc9e-764c-4311-a5b2-dc9685d00872', 'confidence': 0.64918}]}, {'faceId': 'f7ea64c8-2ebd-45b2-9b05-f8b773ea17f0', 'candidates': []}, {'faceId': 'b85d01e3-e9c9-4fb2-86f1-8d7a4676aacb', 'candidates': []}, {'faceId': '64be6a92-a198-4f24-af9c-2428ab4be89e', 'candidates': []}]

if __name__ == '__main__':
    personGroupId = 'criminals'
    detectAndIdentifyPerson(personGroupId)


import os, argparse
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf

import IPython.display as display
from PIL import Image
import pathlib
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

AUTOTUNE = tf.data.experimental.AUTOTUNE
DS_SIZE = 918
BATCH_SIZE = 32
IMG_SIZE = 224
IMG_HEIGHT = 224
IMG_WIDTH = 224
CLASS_NAMES = None

#-----------------LOAD DATA----------------------#
def get_label(file_path):
    # convert the path to a list of path components
    parts = tf.strings.split(file_path, os.path.sep)
    # The second to last is the class-directory
    if (parts[-2] == CLASS_NAMES[0]):
        return 0
    else:
        return 1

def decode_img(img):
    # convert the compressed string to a 3D uint8 tensor
    img = tf.image.decode_jpeg(img, channels=3)
    # Use `convert_image_dtype` to convert to floats in the [0,1] range.
    img = tf.image.convert_image_dtype(img, tf.float32)
    # resize the image to the desired size.
    img = (img/127.5) - 1
    return tf.image.resize(img, [IMG_HEIGHT, IMG_WIDTH])

def process_path(file_path):
    label = get_label(file_path)
    # load the raw data from the file as a string
    img = tf.io.read_file(file_path)
    img = decode_img(img)
    return img, label

def load_data(data_dir):
    global CLASS_NAMES

    data_dir = pathlib.Path(data_dir)

    classes = []
    for i in np.array([item.name for item in data_dir.glob('*') if item.name != "LICENSE.txt"]):
        if i=='.DS_Store':
            continue
        else:
            classes.append(i)
    CLASS_NAMES = np.array(classes)

    list_ds = tf.data.Dataset.list_files(str(data_dir/'*/*'))
    labeled_ds = list_ds.map(process_path, num_parallel_calls=AUTOTUNE)
    return labeled_ds
#------------------------------------------------#

#------------PREPARE FOR TRAINING----------------#

def show_batch(image_batch, label_batch):
    plt.figure(figsize=(10,10))
    for n in range(25):
        ax = plt.subplot(5,5,n+1)
        plt.imshow(image_batch[n])
        plt.title(CLASS_NAMES[label_batch[n]==1][0].title())
        plt.axis('off')
    plt.savefig('pic.png')

def split_dataset_and_prepare(ds, cache=True, shuffle_buffer_size=1000):
    train_size = int(0.7 * DS_SIZE)
    val_size = int(0.15 * DS_SIZE)
    test_size = int(0.15 * DS_SIZE)

    train_dataset = ds.take(train_size)
    test_dataset = ds.skip(train_size)
    val_dataset = ds.skip(val_size)
    test_dataset = ds.take(test_size)

    train_batches = train_dataset.shuffle(shuffle_buffer_size).batch(BATCH_SIZE)
    validation_batches = val_dataset.batch(BATCH_SIZE)
    test_batches = test_dataset.batch(BATCH_SIZE)

    return train_batches, validation_batches, test_batches

#------------------------------------------------#

#------------LOAD MODEL FROM BASE----------------#

def load_model():
    IMG_SHAPE = (IMG_SIZE, IMG_SIZE, 3)
    base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE, include_top=False, weights='imagenet')

    base_model.trainable = False

    global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
    prediction_layer = tf.keras.layers.Dense(1)
    model = tf.keras.Sequential([base_model, global_average_layer, prediction_layer])

    base_learning_rate = 0.0001
    model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=base_learning_rate),
              loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              metrics=['accuracy'])

    return base_model, model

#------------------------------------------------#

#------------------TRAIN-------------------------#

def train_model(model, train_batches, validation_batches, test_batches):
    initial_epochs = 20
    validation_steps = 20

    loss0, accuracy0 = model.evaluate(validation_batches, steps=validation_steps)

    print("initial loss: {:.2f}".format(loss0))
    print("initial accuracy: {:.2f}".format(accuracy0))
    history = model.fit(train_batches, epochs=initial_epochs, validation_data=validation_batches)

    loss1, accuracy1 = model.evaluate(test_batches, steps=validation_steps)
    print("new loss: {:.2f}".format(loss1))
    print("new accuracy: {:.2f}".format(accuracy1))

    return history

def train_model_fine(base_model, model, history, train_batches, validation_batches, test_batches, model_name):
    initial_epochs = 20
    validation_steps = 20

    base_model.trainable = True
    fine_tune_at = 100

    for layer in base_model.layers[:fine_tune_at]:
        layer.trainable =  False

    base_learning_rate = 0.0001
    model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              optimizer = tf.keras.optimizers.RMSprop(lr=base_learning_rate/10),
              metrics=['accuracy'])

    fine_tune_epochs = 20
    total_epochs =  initial_epochs + fine_tune_epochs

    history_fine = model.fit(train_batches, epochs=total_epochs, initial_epoch =  history.epoch[-1], validation_data=validation_batches)

    loss1, accuracy1 = model.evaluate(test_batches, steps=validation_steps)
    print("new loss: {:.2f}".format(loss1))
    print("new accuracy: {:.2f}".format(accuracy1))

    model.save('saved_model/' + model_name)

#------------------------------------------------#

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--data_dir",
        type=str,
        default="../images",
        help="Directory containing folders of images of each category"
    )
    parser.add_argument(
        "--model_name",
        type=str,
        default="new_model",
        help="Name of saved model"
    )
    FLAGS = parser.parse_args()

    labeled_ds = load_data(FLAGS.data_dir)
    train_batches, validation_batches, test_batches = split_dataset_and_prepare(labeled_ds)

    base_model, model = load_model()

    history = train_model(model, train_batches, validation_batches, test_batches)

    train_model_fine(base_model, model, history, train_batches, validation_batches, test_batches, FLAGS.model_name)


from contextlib import nullcontext as does_not_raise
from typing import Callable, List

import pytest
from pydantic import ValidationError

from geolib.geometry.one import Point
from geolib.models.dsheetpiling.dsheetpiling_model import DSheetPilingModel
from geolib.models.dsheetpiling.internal import _DEFAULT_SURFACE_NAME
from geolib.models.dsheetpiling.internal import Surface as InternalSurface
from geolib.models.dsheetpiling.internal import Surfaces
from geolib.models.dsheetpiling.settings import (
    LateralEarthPressureMethodStage,
    PassiveSide,
    Side,
)
from geolib.models.dsheetpiling.surface import Surface

@pytest.fixture
def _model() -> DSheetPilingModel:
    model = DSheetPilingModel()
    model.add_stage(
        name="Initial stage",
        passive_side=PassiveSide.DSHEETPILING_DETERMINED,
        method_left=LateralEarthPressureMethodStage.KA_KO_KP,
        method_right=LateralEarthPressureMethodStage.KA_KO_KP,
    )
    return model

@pytest.fixture
def make_surface() -> Surface:
    def _make_surface(name: str):
        return Surface(name=name, points=[Point(x=0, z=0), Point(x=1, z=0)])

    return _make_surface

class TestSurfaces:
    @pytest.mark.unittest
    @pytest.mark.parametrize(
        "points,run_expectation",
        [
            pytest.param([Point(x=0, z=0)], does_not_raise(), id="Single point"),
            pytest.param(
                [Point(x=0, z=0), Point(x=1, z=0)], does_not_raise(), id="Multiple points"
            ),
            pytest.param(
                [],
                pytest.raises(
                    ValidationError, match=r"ensure this value has at least 1 items"
                ),
                id="No points",
            ),
            pytest.param(
                [Point(x=-1, z=0)],
                pytest.raises(
                    ValidationError,
                    match=r"All x-coordinates must be greater than or equal to 0, found",
                ),
                id="Negative x-coordinates",
            ),
            pytest.param(
                [Point(x=1, z=0)],
                pytest.raises(
                    ValidationError,
                    match=r"X-coordinate first point should be zero, received",
                ),
                id="First x-coordinate not zero",
            ),
            pytest.param(
                [Point(x=0, z=0), Point(x=10, z=0), Point(x=5, z=0)],
                pytest.raises(
                    ValidationError, match=r"x-coordinates must be strictly increasing"
                ),
                id="Not strictly increasing",
            ),
        ],
    )
    def test_surface_initialization_with_different_points_arguments(
        self, points: List[Point], run_expectation
    ):
        surface_name = "Ground level -2m"
        with run_expectation:
            Surface(name=surface_name, points=points)

    @pytest.mark.integrationtest
    def test_dsheetpilingmodel_add_surface_invalid_stage_id_raises_ValueError(
        self, _model: DSheetPilingModel, make_surface: Callable
    ):
        surface = make_surface(name=_DEFAULT_SURFACE_NAME)
        invalid_stage_id = (
            len(_model.datastructure.input_data.construction_stages.stages) + 1
        )

        with pytest.raises(
            ValueError, match=r"Stage \d+ is not added to the internal datastructure"
        ):
            _model.add_surface(surface=surface, side=Side.BOTH, stage_id=invalid_stage_id)

    @pytest.mark.integrationtest
    @pytest.mark.parametrize(
        "side",
        [
            pytest.param(Side.LEFT, id="Left side"),
            pytest.param(Side.RIGHT, id="Right side"),
            pytest.param(Side.BOTH, id="Both sides"),
        ],
    )
    def test_dsheetpilingmodel_add_surface_internal_surfaces_updated(
        self, _model: DSheetPilingModel, make_surface: Callable, side: Side
    ):
        """Validate if surface is refered in [SURFACES]"""

        surface_name = "Ground level -2m"
        current_stage = _model.current_stage
        assert surface_name != _DEFAULT_SURFACE_NAME
        surface = make_surface(surface_name)

        # _model.add_surface(surface=surface, side=Side.LEFT, stage_id=0)
        _model.add_surface(surface=surface, side=side, stage_id=current_stage)

        assert isinstance(_model.datastructure.input_data.surfaces, Surfaces)
        assert len(_model.datastructure.input_data.surfaces.surfaces) == 1
        internal = _model.datastructure.input_data.surfaces.surfaces[current_stage]
        assert isinstance(internal, InternalSurface)
        assert internal.name == surface_name
        assert len(internal.points) == len(surface.points)
        for i, (point, internal_point) in enumerate(
            zip(surface.points, internal.points), start=1
        ):
            assert i == internal_point["Nr"]
            assert point.x == internal_point["X-coord"]
            assert point.z == internal_point["Value"]

    @pytest.mark.integrationtest
    @pytest.mark.parametrize(
        "side, left_surface_name, right_surface_name",
        [
            pytest.param(
                Side.LEFT, "Left surface", _DEFAULT_SURFACE_NAME, id="Left side"
            ),
            pytest.param(
                Side.RIGHT, _DEFAULT_SURFACE_NAME, "Right surface", id="Right side"
            ),
            pytest.param(Side.BOTH, "Same surface", "Same surface", id="Both sides"),
        ],
    )
    def test_dsheetpilingmodel_add_surface_internal_construction_stages(
        self,
        _model: DSheetPilingModel,
        make_surface: Callable,
        side: Side,
        left_surface_name: str,
        right_surface_name: str,
    ):
        """Validate if surface is refered in [CONSTRUCTION STAGES]"""
        current_stage = _model.current_stage

        if side == Side.LEFT:
            assert left_surface_name != _DEFAULT_SURFACE_NAME
            surface = make_surface(left_surface_name)
        elif side == Side.RIGHT:
            assert right_surface_name != _DEFAULT_SURFACE_NAME
            surface = make_surface(right_surface_name)
        else:
            assert left_surface_name == right_surface_name != _DEFAULT_SURFACE_NAME
            surface = make_surface(right_surface_name)

        _model.add_surface(surface=surface, side=side, stage_id=current_stage)

        assert (
            _model.datastructure.input_data.construction_stages.stages[
                current_stage
            ].surface_left
            == left_surface_name
        )
        assert (
            _model.datastructure.input_data.construction_stages.stages[
                current_stage
            ].surface_right
            == right_surface_name
        )


from sklearn.linear_model import LogisticRegression
from skmultilearn.dataset import load_dataset
from skmultilearn.problem_transform import BinaryRelevance
from src.helpers import test_score

X_train, y_train, feature_names, label_names = load_dataset("emotions", "train")
X_test, y_test, _, _ = load_dataset("emotions", "test")
X_train = X_train.toarray()
y_train = y_train.toarray()[:, 0].reshape(-1, 1)

X_test = X_test.toarray()
y_test = y_test.toarray()[:, 0].reshape(-1, 1)

classifier = LogisticRegression()
# classifier = BinaryRelevance(classifier)
classifier.fit(X_train, y_train)
prediction = classifier.predict(X_train)
test_score(y_train, prediction)

prediction = classifier.predict(X_test)
print(y_test.shape, prediction.shape)
test_score(y_test, prediction)


import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

# -------------------------------------------------------------------------------------------------------
data = pd.read_csv('data/Cleaned/Cleaned_channelData.csv')
data.head()

data.drop('Unnamed: 0', axis = 1, inplace = True)
data.columns

# -------------------------------------------------------------------------------------------------------

# Selecting quantitative columns
cols = ['Subscribers', 'Viewers', 'Videos_made', 'start_day']
sns.histplot(data['start_year'], bins = 50)
# -------------------------------------------------------------------------------------------------------

# KMeans
kmeans = KMeans(n_clusters=2).fit(df)
centroids = kmeans.cluster_centers_
print(centroids[:, 0], centroids[:, 1])

# -------------------------------------------------------------------------------------------------------

# Add a 'Cluster' column to your DataFrame to indicate cluster membership
df['Cluster'] = kmeans.labels_

# Create a scatter plot to visualize the data points and centroids
plt.figure(figsize=(10, 6))

# Scatter plot for each cluster
for cluster in range(3):
    plt.scatter(df[df['Cluster'] == cluster][cols[0]],
                df[df['Cluster'] == cluster][cols[1]],
                label=f'Cluster {cluster}')

# Plot cluster centroids
plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', s=100, color='black', label='Centroids')

# Label axes
plt.xlabel(cols[0])
plt.ylabel(cols[1])

# Add a legend
plt.legend()

# Show the plot
plt.show()

# -------------------------------------------------------------------------------------------------------

scaled_df = StandardScaler().fit_transform(df)

# Elbow method

#initialize kmeans parameters
kmeans_kwargs = {
"init": "random",
"n_init": 10,
"random_state": 1,
}

#create list to hold SSE values for each k
sse = []
for k in range(1, 11):
    kmeans = KMeans(n_clusters=k, **kmeans_kwargs)
    kmeans.fit(scaled_df)
    sse.append(kmeans.inertia_)

#visualize results
plt.plot(range(1, 11), sse)
plt.xticks(range(1, 11))
plt.xlabel("Number of Clusters")
plt.ylabel("SSE")
plt.show()
# -------------------------------------------------------------------------------------------------------

# Silhouette Method
from sklearn.metrics import silhouette_score
range_n_clusters = [2, 3, 4, 5, 6, 7, 8]
silhouette_avg = []
for num_clusters in range_n_clusters:
    # initialise kmeans
    kmeans = KMeans(n_clusters=num_clusters)
    kmeans.fit(scaled_df)
    cluster_labels = kmeans.labels_
    # silhouette score
    silhouette_avg.append(silhouette_score(scaled_df, cluster_labels))

plt.plot(range_n_clusters,silhouette_avg,'bx-')
plt.xlabel('‘Values of K’')
plt.ylabel('‘Silhouette score’')
plt.title('‘Silhouette analysis For Optimal k’')
plt.show()
# -------------------------------------------------------------------------------------------------------

# -------------------------------------------------------------------------------------------------------


animals = [False] * 3  # [0] = C, [1] = R , [2] = S
tCase = int(input())
indexChooser = lambda a: (0, int(a[0])) if 'C' in a else((1, int(a[0])) if 'R' in a else (2, int(a[0])))
percentConverter = lambda n, animal: n * 100 / sum(animal)

for i in range(tCase):
    tempArray = input().split(' ')
    index, amount = indexChooser(tempArray)
    animals[index] += amount

display = ["Total: %i cobaias" % sum(animals),
           "Total de coelhos: %i" % animals[0],
           "Total de ratos: %i" % animals[1],
           "Total de sapos: %i" % animals[2],
           "Percentual de coelhos: %.2f %s" % (percentConverter(animals[0], animals), '%'),
            "Percentual de ratos: %.2f %s" % (percentConverter(animals[1], animals), '%'),
            "Percentual de sapos: %.2f %s" % (percentConverter(animals[2], animals), '%'),
           ]

for out in display:
    print(out)


from math import sqrt

def makeSieve(sieveSize):
	sieve = [True for i in range(sieveSize)]
	sieve[0] = False
	sieve[1] = False

	# declare all multiples of two nonprime
	for composite in range(4, sieveSize, 2):
		sieve[composite] = False

	for num in range(3, int(sqrt(sieveSize))):
		# print(num)
		if not sieve[num]:
			continue
		for composite in range(num ** 2, sieveSize, 2 * num):
			sieve[composite] = False
	return sieve

if __name__ == "__main__":
	from time import time
	startTime = time()
	sieve = makeSieve(10**7)
	# primeList = []
	# for num in range(10**7):
	# 	if sieve[num]:
	# 		primeList.append(num)
	# print(primeList)

	print("done")
	print('This took', time() - startTime)


# type hints/annotation module
from typing import List, Tuple, Union, Any

import keras
import numpy as np

import data.data_util
import models.parsing.tokenizer
import models.storage.store

class BaseModel:
    # keys for hyperparameters
    KEY_TEST_SPLIT = "test_split"
    KEY_EPOCHS = "epochs"
    KEY_BATCH_SIZE = "batch_size"
    KEY_VALIDATION_SPLIT = "validation_split"
    KEY_EMBEDDING_SIZE = "embedding_size"
    KEY_MAX_CONFESSION_LENGTH = "max_confession_length"
    KEY_DATA_PATH = "data_path"
    KEY_DEPOLARIZE = "should_depolarize_data"
    DEFAULT_HYPERPARAMETER_VALUE_MAP = {
        "test_split": 0.20,
        "epochs": 100,
        "batch_size": 64,
        "validation_split": 0.33,
        "embedding_size": 16,
        "max_confession_length": 400,
        "data_path": "all_confessions/all",
        "should_depolarize_data": False,
    }

    def __init__(self, model_type_name: str):
        """
        initializes the model.
        :param model_type_name : str
            This can be "lstm", "regression", "classification", or
            anything of the sort. This model is used to to store
            the model after training.
        """
        self.model_type_name = model_type_name
        self.model = None
        self.train_data, self.train_labels, self.test_data, self.test_labels = None, None, None, None
        # class attributes to be used at training
        self.sequences, self.labels, self.max_sequence_length = None, None, None
        self.num_words, self.word_to_index, self.index_to_word = None, None, None
        # setting up parameters to be used later when testing/using the model
        self.hyperparams = {}
        self.last_train_history = None
        # Set the model's metadata (things are things that are needed
        # when predicting, which should also be loaded and not lost when
        # saving the model).
        self._metadata_attributes = [
            "max_sequence_length",
            "num_words",
            "word_to_index",
            "index_to_word",
            "last_train_history",
            "__hyperparams__"
        ]
        # setup the model
        self.setup_base_data()

    def get_hyperparam(self, key: str) -> Any:
        """
        gets a hyperparameter, make sure to use one of the static
        "KEY_" attributes of the BaseModel class
        """
        BaseModel.assert_valid_key(key)
        return self.hyperparams.get(key, BaseModel.DEFAULT_HYPERPARAMETER_VALUE_MAP.get(key, None))

    def set_hyperparam(self, key: str, value: Any) -> None:
        """
        sets hyperparameter, make sure to use one of the static "KEY_"
        attributes of the BaseModel class
        """
        BaseModel.assert_valid_key(key)
        self.hyperparams[key] = value

    def register_metadata(self, metadata_attr: str):
        self._metadata_attributes.append(metadata_attr)

    @staticmethod
    def assert_valid_key(hyperparameter_key: str) -> None:
        """
        throws if the hyperparameter key is not amongst the
        BaseModel's hyperparameters
        """
        key_attributes = {attr for attr in dir(BaseModel) if "KEY_" in attr}
        key_values = {getattr(BaseModel, key) for key in key_attributes}
        assert hyperparameter_key in key_values, "the key given is not a valid key attribute"

    def setup_base_data(self) -> None:
        """
        sets up attributes to use in the class, such as
        num_words and max_sequence_length
        """
        max_confession_length = self.get_hyperparam(BaseModel.KEY_MAX_CONFESSION_LENGTH)
        texts, labels = self.load_base_data(max_confession_length)
        sequences, num_words, index_to_word, word_to_index = models.parsing.tokenizer.get_text_items(texts)
        max_sequence_length = models.parsing.tokenizer.find_max_sentence_length(sequences)
        # update these attributes for this class instance
        self.sequences, self.max_sequence_length, self.labels = sequences, max_sequence_length, labels
        self.num_words, self.word_to_index, self.index_to_word = num_words, word_to_index, index_to_word

    def update_train_and_test_data(self):
        self.train_data, self.train_labels, self.test_data, self.test_labels = self.get_train_and_test_data()

    def get_train_and_test_data(self):
        """
        gets the test and train data for this model
        """
        np_data, np_labels = self.parse_base_data(self.sequences, self.labels)
        # shuffle the data
        np_data, np_labels = BaseModel.shuffle_data(np_data, np_labels)
        split = int(np_data.shape[0] - (self.get_hyperparam(BaseModel.KEY_TEST_SPLIT) * np_data.shape[0]))
        train_d, train_l = np_data[:split, :], np_labels[:split, :]
        test_d, test_l = np_data[split:, :], np_labels[split:, :]
        return train_d, train_l, test_d, test_l

    @staticmethod
    def shuffle_data(np_data: np.ndarray, np_labels: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
        """
        shuffles the data and labels given, and returns the shuffled
        version in.
        """
        _, data_col_index = np_data.shape
        data_label_combination = np.hstack((np_data, np_labels))
        np.random.shuffle(data_label_combination)
        return data_label_combination[:, :data_col_index], data_label_combination[:, data_col_index:]

    def load_base_data(self, max_confession_length: int) -> Tuple[List[str], Tuple[Union[int, float], ...]]:
        """
        loads the base data, which contains all the texts and
        all the labels.
        """
        data_path = self.get_hyperparam(BaseModel.KEY_DATA_PATH)
        all_data = data.data_util.load_text_with_every_label(data_path, max_confession_length)
        texts, labels = zip(*[
            (row[data.data_util.CONFESSION_TEXT_INDEX], row[data.data_util.CONFESSION_REACTION_INDEX])
            for row in all_data
        ])
        return texts, labels

    def train(self) -> None:
        """
        trains self.model in place
        """
        assert self.train_data is not None, \
            "test_data is None. The model may not have been trained. " \
            "Call the method `update_train_and_test_data` " \
            "on this instance of %s" % self.__class__.__name__
        history = self.model.fit(
                self.train_data,
                self.train_labels,
                epochs=self.get_hyperparam(BaseModel.KEY_EPOCHS),
                batch_size=self.get_hyperparam(BaseModel.KEY_BATCH_SIZE),
                validation_split=self.get_hyperparam(BaseModel.KEY_VALIDATION_SPLIT),
        )
        self.last_train_history = history.history

    def evaluate(self) -> Tuple[Any, Any]:
        """ evaluates the model and returns the metrics """
        # don't evaluate if we set the validation split to 0.
        val_split = self.get_hyperparam(BaseModel.KEY_VALIDATION_SPLIT)
        if val_split == 0.0:
            return None, None
        assert self.test_data is not None, \
            "test_data is None. The model may not have been trained. " \
            "Call the method `update_train_and_test_data` " \
            "on this instance of %s" % self.__class__.__name__
        evaluation = self.model.evaluate(self.test_data, self.test_labels)

        if len(evaluation) == 0:
            return None, None
        loss, metric = evaluation
        return loss, metric

    def predict(self, data_point: np.ndarray) -> Any:
        return self.model.predict(data_point)

    def save(self) -> None:
        """
        saves the model into /models/storage with a name that uses all
        the model's hyperparameters
        """
        models.storage.store.save_model(
                self.model,
                self.model_type_name,
                self.get_hyperparam(BaseModel.KEY_EMBEDDING_SIZE),
                self.get_hyperparam(BaseModel.KEY_EPOCHS),
                self.get_hyperparam(BaseModel.KEY_BATCH_SIZE),
                self.get_hyperparam(BaseModel.KEY_VALIDATION_SPLIT),
        )
        models.storage.store.save_model_metadata(
                self.get_model_metadata(),
                self.model_type_name,
                self.get_hyperparam(BaseModel.KEY_EMBEDDING_SIZE),
                self.get_hyperparam(BaseModel.KEY_EPOCHS),
                self.get_hyperparam(BaseModel.KEY_BATCH_SIZE),
                self.get_hyperparam(BaseModel.KEY_VALIDATION_SPLIT),
        )

    def get_model_metadata(self) -> dict:
        """ get the model's metadata, specified with self.metadata_attributes """
        metadata = {
            "__attributes__": self._metadata_attributes,
            "__hyperparams__": self.hyperparams,
        }
        for attr in self._metadata_attributes:
            if attr == "__hyperparams__":
                continue
            metadata[attr] = getattr(self, attr, None)
        return metadata

    def load(self) -> None:
        """ loads the model in place into self.model """
        model_path = models.storage.store.get_model_title(
                self.model_type_name,
                self.get_hyperparam(BaseModel.KEY_EMBEDDING_SIZE),
                self.get_hyperparam(BaseModel.KEY_EPOCHS),
                self.get_hyperparam(BaseModel.KEY_BATCH_SIZE),
                self.get_hyperparam(BaseModel.KEY_VALIDATION_SPLIT),
        )
        print("loading model from %s" % model_path)
        self.model = keras.models.load_model(model_path)
        model_metadata = models.storage.store.load_model_metadata(model_path)
        self._metadata_attributes = model_metadata["__attributes__"]
        self.set_model_metadata_attr(model_metadata)

    def set_model_metadata_attr(self, model_metadata: dict) -> None:
        """ set the model data attributes one by one """
        for attr in model_metadata["__attributes__"]:
            if attr == "__hyperparams__":
                # handle __hyperparams__ differently
                hyperparams = model_metadata.get(attr, {})
                for h_key, h_value in hyperparams.items():
                    self.set_hyperparam(h_key, h_value)
                continue
            if attr == "index_to_word":
                self.index_to_word = {
                    int(index): word
                    for index, word in model_metadata.get(attr, {}).items()
                }
                continue
            setattr(self, attr, model_metadata.get(attr, None))

    def pad_sequences(
            self,
            sequences: List[List[int]],
            maximum_sequence_len: int = None,
            padding: str = "post") -> np.ndarray:
        """
        pad the sequences with pad characters. If the maximum_sequence_len
        is not given, we use the default one that belongs to this class.
        Otherwise, we use what is provided. This maximum_sequence_len parameter
        is  necessary for RNN/LSTM models.
        """
        if maximum_sequence_len is None:
            maximum_sequence_len = self.max_sequence_length
        return models.parsing.tokenizer.pad_data_sequences(
                sequences,
                self.word_to_index,
                maximum_sequence_len,
                padding=padding
        )

    # **********************************
    # Creates the model and evaluates it
    # **********************************

    def run(self, save: bool = True) -> None:
        """
        runs the model
        """
        self.setup_base_data()
        self.update_train_and_test_data()
        self.create()
        self.train()
        self.evaluate()
        if save:
            self.save()

    # *****************************
    # Methods to test the model out
    # *****************************

    def convert_text_to_padded_sequence(self, text: str) -> np.ndarray:
        sequence = models.parsing.tokenizer.convert_text_to_sequence(text, self.word_to_index)
        return self.pad_sequences([sequence])

    # ***************************************************
    # Methods to be implemented by all inheriting classes
    # ***************************************************

    def parse_base_data(
            self,
            sequences: List[List[int]],
            labels: Tuple[Union[int, float], ...]) -> Tuple[np.ndarray, np.ndarray]:
        """
        given all the texts and labels, convert them into
        numpy arrays of training data and labels.
        use self.pad_sequences with sequences to pad
        """
        raise NotImplementedError

    def create(self) -> None:
        """
        creates self.model in place
        use self.num_words and self.max_sequence_length for embedding layer
        """
        raise NotImplementedError

if __name__ == '__main__':
    pass


#!/usr/bin/python3
"""Real definition of a rectangle"""

class Rectangle:
    """defination of class named Rectangle"""
    def __init__(self, width=0, height=0):
        """
        constructor method __init__ for Rectangle class
        initializes instance attribute width and height
        """
        self.height = height
        self.width = width

    @property
    def width(self):
        """
        use to define getter method for width
        attribute
        """
        return self.__width

    @width.setter
    def width(self, value):
        """
        setter method for width attribute
        resposible for validating input values and
        setting value of private attr __width
        """
        if isinstance(value, int) is False:
            raise TypeError("width must be an integer")
        elif value < 0:
            raise ValueError("width must be >=0")
        else:
            self.__width = value

    @property
    def height(self):
        """
        to define getter method for height attribute
        to allow access of value of height
        """
        return self.__height

    @height.setter
    def height(self, value):
        """
        setter method for height attribute
        if value id none integer 'TypeError' is raise
        raise ValueError when value < 0
        """
        if isinstance(value, int) is False:
            raise TypeError("height must be an integer")
        elif value < 0:
            raise ValueError("height must be >= 0")
        else:
            self.__height = value


"""
You are standing at a magical well. It has two positive integers written on it: a and b. Each time you cast a magic marble into the well,
it gives you a * b dollars and then both a and b increase by 1. You have n magic marbles. How much money will you make?

Example

For a = 1, b = 2 and n = 2, the output should be
magicalWell(a, b, n) = 8.

You will cast your first marble and get $2, after which the numbers will become 2 and 3. When you cast your second marble, the well will
give you $6. Overall, you'll make $8. So, the output is 8.
"""
def magicalWell(a, b, n):
    total = 0
    for x in range(n):
        total += a*b
        a += 1
        b += 1
    return total


#!/usr/bin/env python3

## Description
# Broadcast a tuple to port=port in its current network
#

import socket
import time
import struct
import random

import msg_struct

port      = 12345
netmask   = '255.255.255.0'

hostname  = socket.gethostname()
ip        = socket.gethostbyname(hostname)
print('Hostname          : {}'.format(hostname))
print('IP Address        : {}'.format(ip))

# Create UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Set it to broadcast at SOL_SOCKET level to 1
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

for i in range(0, 25):
  msg = struct.pack(msg_struct.tMsg,
                    int(time.time()),
                    i,
                    random.random(),
                    'Hello world {:>3d}'.format(i).encode()
                    )
  # Broadcast the message the local network
  sock.sendto(msg, ('<broadcast>', port))

  time.sleep(1)

# Close socket
sock.close()