from collections import defaultdict

day = 8

example_filename = f'day{day}/day{day}_ex.txt'
example_input = open(example_filename).readlines()

filename = f'day{day}/day{day}.txt'
puzzle_input = open(filename).readlines()

def get_lines(input):
  return [[[val.strip() for val in x.split(' ')] for x in line.split(' | ')] for line in input]

TOP = 'top'
TOP_LEFT = 'top left'
TOP_RIGHT = 'top right'
MIDDLE = 'middle'
BOTTOM_LEFT = 'bottom left'
BOTTOM_RIGHT = 'bottom right'
BOTTOM = 'bottom'

segments = {TOP, TOP_LEFT, TOP_RIGHT, MIDDLE, BOTTOM_LEFT, BOTTOM_RIGHT, BOTTOM}

nums = {
  0: {TOP, TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT, BOTTOM},
  1: {TOP_RIGHT, BOTTOM_RIGHT},
  2: {TOP, TOP_RIGHT, MIDDLE, BOTTOM_LEFT, BOTTOM},
  3: {TOP, TOP_RIGHT, MIDDLE, BOTTOM_RIGHT, BOTTOM},
  4: {TOP_LEFT, TOP_RIGHT, MIDDLE, BOTTOM_RIGHT},
  5: {TOP, TOP_LEFT, MIDDLE, BOTTOM_RIGHT, BOTTOM},
  6: {TOP, TOP_LEFT, MIDDLE, BOTTOM_LEFT, BOTTOM_RIGHT, BOTTOM},
  7: {TOP, TOP_RIGHT, BOTTOM_RIGHT},
  8: {TOP, TOP_LEFT, TOP_RIGHT, MIDDLE, BOTTOM_LEFT, BOTTOM_RIGHT, BOTTOM},
  9: {TOP, TOP_LEFT, TOP_RIGHT, MIDDLE, BOTTOM_RIGHT, BOTTOM}
}

def get_count(letter_counts, loc):
  segment_counts = {segment: len(list(filter(lambda num: segment in nums[num], nums))) for segment in segments}
  return filter(lambda l: letter_counts[l] == segment_counts[loc], letter_counts).__next__()

def get_signal(signals, length):
  return [signal for signal in signals if len(signal) == length][0]

def get_output_number(line):
  signals, output = line
  letter_counts = defaultdict(int)
  for signal in signals:
    for letter in signal:
      letter_counts[letter] += 1

  top_left = get_count(letter_counts, TOP_LEFT)
  bottom_left = get_count(letter_counts, BOTTOM_LEFT)
  bottom_right = get_count(letter_counts, BOTTOM_RIGHT)
  top_right = filter(lambda l: l != bottom_right, get_signal(signals, len(nums[1]))).__next__()
  top = filter(lambda l: l not in {top_right, bottom_right}, get_signal(signals, len(nums[7]))).__next__()
  middle = filter(lambda l: l not in {top_left, top_right, bottom_right}, get_signal(signals, len(nums[4]))).__next__()
  bottom = filter(lambda l: l not in {top_left, bottom_left, bottom_right, top_right, top, middle}, letter_counts).__next__()

  mapping = {
    top: TOP,
    top_left: TOP_LEFT,
    top_right: TOP_RIGHT,
    middle: MIDDLE,
    bottom_left: BOTTOM_LEFT,
    bottom_right: BOTTOM_RIGHT,
    bottom: BOTTOM
  }

  return int(''.join([str(filter(lambda n: nums[n] == {mapping[letter] for letter in val}, nums).__next__()) for val in output]))

def part_1(input):
  lines = get_lines(input)
  return sum([sum([1*(len(item) in {2,3,4,7}) for item in line[1]]) for line in lines])

def part_2(input):
  lines = get_lines(input)
  return sum(list(map(get_output_number, lines)))

print(f'Part 1 example: {part_1(example_input)}')
print(f'Part 1 puzzle: {part_1(puzzle_input)}')

print(f'Part 2 example: {part_2(example_input)}')
print(f'Part 2 puzzle: {part_2(puzzle_input)}')


# https://leetcode.com/problems/best-time-to-buy-and-sell-stock
class Solution:
    # generalized solution
    # can handle negative prices, also min's losses if applicable
    # this algo is re-used in "maximum-subarray"
    def maxProfit(self, prices: list[int]) -> int:
        if len(prices) <= 1:
            return 0

        # min has to be the first value seen, rather than 0
        p_min: int = prices[0]
        max_profit: int = prices[1] - prices[0]

        for price in prices[1:]:
            profit: int = price - p_min
            max_profit = max(max_profit, profit)
            p_min = min(p_min, price)

        # would return min loss, but instructions say "return max profit or 0"
        return max_profit if max_profit > 0 else 0

    # # naive solution - doesn't handle negative prices nor does it minimize losses
    # def maxProfit(self, prices: list[int]) -> int:
    #     # min has to be the first value seen, rather than 0
    #     p_min: int = prices[0]
    #     max_profit: int = 0
    #
    #     for price in prices:
    #         if price < p_min:
    #             p_min = price
    #             continue
    #         profit: int = price - p_min
    #         if profit > max_profit:
    #             max_profit = profit
    #
    #     return max_profit

    # # my attempt to recreate my friend's very different algo
    # def maxProfit(self, prices: list[int]) -> int:
    #     if len(prices) < 2:
    #         return 0
    #     if len(prices) == 2:
    #         profit = prices[1] - prices[0]
    #         return profit if profit >= 0 else 0
    #
    #     yester_price: int = prices[1]
    #     yester_profit: int = prices[1] - prices[0]
    #     max_profit: int = yester_profit
    #
    #     for price in prices[2:]:
    #         today_profit: int = price - yester_price
    #         hodl_profit: int = yester_profit + today_profit
    #         better_profit: int = max(hodl_profit, today_profit)
    #         max_profit = max(max_profit, better_profit)
    #         yester_profit = better_profit
    #         yester_price = price
    #
    #     return max_profit if max_profit >= 0 else 0


__author__ = 'Togo-PC'

from tkinter import *
import string
import _thread
from time import sleep

DIM=14
btn=[[Button for x in range(DIM)]for y in range(DIM)]
btnCB=[]
for i in range(DIM):
    btnCB.append([])
    for j in range(DIM):
        btnCB[i].append(0)
#colors=['WHITE','RED','YELLOW','BLUE','PURPLE']
#colors=['WHITE','ORANGE','PURPLE','RED','BLUE']
colors=['WHITE','ORANGE','PURPLE']

def frame(root,side):
    w=Frame(root)
    w.pack(side=side,expand=YES,fill=BOTH)  #可拉伸，横纵向填充
    return w

def nextColor(color):
    global colors
    num=len(colors)
    for i in range(num):
        if colors[i]==color:
            return colors[(i+1)%num]  #############################
    #return 'BLUE'

def button(root,side,text,command=None,bg='WHITE'):
    w=Button(root,text=text,command=lambda:w.config(bg=nextColor(w['bg'])   ),bg=bg)
    w.pack(side=side,expand=YES,fill=BOTH)
    return w

def allToWhite():
    for x in range(DIM):
        for y in range(DIM):
            btn[x][y].config(bg='WHITE')

def Chess(point,level=0,maxRotate=8):
    rotate_count=0
    matrix=[[0 for col in range(5)]for row in range(5)]
    minp0,minp1=DIM,DIM
    for p in point:
        minp0=p[0] if p[0]<minp0 else minp0
        minp1=p[1] if p[1]<minp1 else minp1

    for p in point:
        matrix[p[0]-minp0][p[1]-minp1]=1

    def rotate(rotate_count,matrix):
        rotate_count += 1
        if (rotate_count != 5):
            matrix = [[matrix[4 - row][col] for row in range(5)] for col in range(5)]
        else:
            matrix = [[matrix[4 - row][col] for col in range(5)] for row in range(5)]
        rotate_count = 0 if rotate_count == maxRotate else rotate_count
        return rotate_count,matrix
    def minxy():
        minx,miny=5,5
        for x in range(5):
            for y in range(5):
                if matrix[x][y]:
                    minx=x if x<minx else minx
                    miny=y if y<miny else miny
        return minx,miny
    def calc():
        minx,miny=minxy()
        ans=0
        for x in range(5):
            for y in range(5):
                if matrix[x][y]:
                    realx,realy=x-minx,y-miny
                    id=realx*5+realy
                    ans+=1<<id
        return ans

    minans=calc()

    #print("minans=",minans,sep='')
    rotate_count,matrix=rotate(rotate_count,matrix)
    while rotate_count:
        minans=calc() if minans>calc() else minans
        #print("minans=",minans,calc())
        rotate_count,matrix=rotate(rotate_count,matrix)
    return minans

ChessDict = {}
ChessDict['1'] = Chess([[2,2]], 0, 1)  # the level is given by subjectivity
ChessDict['2'] = Chess([[1, 2], [2, 2]], 0, 2)
ChessDict['3'] = Chess([[2, 1], [2, 2], [2, 3]], 0, 2)
ChessDict['4'] = Chess([[1, 2], [2, 2], [2, 3]], 0, 4)
ChessDict['5'] = Chess([[2, 0], [2, 1], [2, 2], [2, 3]], 0, 2)
ChessDict['6'] = Chess([[1, 1], [2, 1], [2, 2], [2, 3]], 1, 4)
ChessDict['7'] = Chess([[1, 2], [2, 1], [2, 2], [2, 3]], 0, 4)
ChessDict['8'] = Chess([[1, 1], [1, 2], [2, 1], [2, 2]], 0, 1)
ChessDict['9'] = Chess([[1, 1], [1, 2], [2, 2], [2, 3]])
ChessDict['10'] = Chess([[2, 0], [2, 1], [2, 2], [2, 3], [2, 4]], 0, 2)
ChessDict['11'] = Chess([[2, 0], [2, 1], [2, 2], [2, 3], [1, 3]], 1)
ChessDict['12'] = Chess([[1, 0], [1, 1], [2, 1], [2, 2], [2, 3]], 1)
ChessDict['13'] = Chess([[1, 2], [1, 3], [2, 1], [2, 2], [2, 3]])
ChessDict['14'] = Chess([[1, 1], [2, 1], [2, 2], [2, 3], [1, 3]], 0, 4)
ChessDict['15'] = Chess([[1, 1], [2, 0], [2, 1], [2, 2], [2, 3]], 1)
ChessDict['16'] = Chess([[1, 2], [2, 2], [3, 1], [3, 2], [3, 3]], 0, 4)
ChessDict['17'] = Chess([[1, 1], [2, 1], [3, 1], [3, 2], [3, 3]], 0, 4)
ChessDict['18'] = Chess([[1, 1], [1, 2], [2, 2], [2, 3], [3, 3]], 0, 4)
ChessDict['19'] = Chess([[1, 1], [2, 1], [2, 2], [2, 3], [3, 3]])
ChessDict['20'] = Chess([[1, 1], [2, 1], [2, 2], [2, 3], [3, 2]])
ChessDict['21'] = Chess([[1, 2], [2, 1], [2, 2], [2, 3], [3, 2]], 0, 1)

def confirm():
    global btnCB
    down=[]
    out=[]
    id=1

    #print(btnCB)
    for x in range(DIM):
        for y in range(DIM):
            if ((btn[x][y]['bg']==colors[id])&(btnCB[x][y]!=id)):
                #print(x,y)
                down.append([x,y])
                out.append(x)
                out.append(y)
                btnCB[x][y]=id
                #print(btnCB)
    #print(str(down))
    '''
    for x in range(len(down)):
        for y in range(len(down[x])):
            if (x==len(down) & y==len(down[x])):
                print(down[x][y])
            else:
                print(str(down[x][y]),end='')
    '''
    #print(down)
    #print(len(out))
    for x in range(len(out)):
        if (x==len(out)-1):
            print(out[x])
        else:
            print(out[x],',',sep='',end='')

    f=open("Player2Data.txt","w")
    for x in range(len(out)):
        if (x==len(out)-1):
            f.write(str(out[x])+'\n')
        else:
            f.write(str(out[x])+',')
    CID=Chess(down)
    for x in range(1,22):
        if ChessDict[str(x)]==CID:
            break
    print(x)
    print(1)

    f.write(str(x)+"\n")######################################################ChessID
    f.write("1\n")

    #f.write(str(down))
    #print(btnCB)
    #print()

def ReadFile(num=0):
    result=[]
    with open("data"+str(num)+".txt",'r') as f:
        for line in f:
            result.append(list(map(int,line.split(' '))))
    for xy in result:
        x,y=xy[0],xy[1]
        btn[x][y].config(bg=colors[num])
    f.close()
    #print(result)
'''
def BtnCmd():
    i=0
    while (1):
        i=i+1
        if (i==1000000):
            ReadFile(1)
            ReadFile(2)
            i=0
'''

def CCFO(x,y,num):
    btn[x][y].config(bg=colors[num])

class ChessBoard(Frame):
    def __init__(self,DIM):
        Frame.__init__(self)  #############################important
        self.pack(expand=YES,fill=BOTH)
        self.master.title("Blokus Board")
        self.master.geometry('600x600')

        global btn

        for x in range(DIM):
            line=frame(self,TOP)
            for y in range(DIM):
                btn[x][y]=button(line,LEFT,'')

        line=frame(self,TOP)
        '''
        displayX=IntVar()
        entryX=Entry(line,relief=SUNKEN)
        entryX.pack(side=LEFT,expand=YES,fill=BOTH)
        displayY=IntVar()
        entryY=Entry(line,relief=SUNKEN)
        entryY.pack(side=LEFT,expand=YES,fill=BOTH)
        btncc=Button(line,text="C C",command=lambda : btn[int(entryX.get())][int(entryY.get())].config(bg=nextColor(btn[int(entryX.get())][int(entryY.get())]['bg'])) )
        btncc.pack(side=LEFT,expand=YES,fill=BOTH)
        '''
        btnConfirm=Button(line,text="Confirm",command=confirm)
        btnConfirm.pack(side=LEFT,expand=YES,fill=BOTH)
        btnClear=Button(line,text="Clear",command=allToWhite)
        btnClear.pack(side=LEFT,expand=YES,fill=BOTH)

        btnFile1=Button(line,text="Read",command=lambda x=1:ReadFile(x))
        #btnFile1=Button(line,text="Read",command=BtnCmd)
        btnFile1.pack(side=LEFT,expand=YES,fill=BOTH)
        btnFile2=Button(line,text="Read",command=lambda x=2:ReadFile(x))
        btnFile2.pack(side=LEFT,expand=YES,fill=BOTH)
'''
if __name__=='__main__':
    #print('Here we go')
    cb=ChessBoard(DIM)
    cb.mainloop()

cb=ChessBoard(DIM)
cb.mainloop()
'''

cb=ChessBoard(DIM)
def ml():
    global cb
    cb.mainloop()

def rf():
    while (1):
        sleep(1)
        result=[]
        with open("data0.txt",'r') as f:
            for line in f:
                result.append(list(map(int,line.split(' '))))
        for xyz in result:
            l=len(xyz)
            if (not (0<=l<DIM)):
                continue
            x,y,z=xyz[0],xyz[1],xyz[2]
            if (not (0<=z<len(colors))):
                continue
            if 1<=z<=2:
                z=3-z
            btn[x][y].config(bg=colors[z])
        f.close()

_thread.start_new_thread(ml,())
_thread.start_new_thread(rf,())
sleep(1000)


######################################
# Groupe BI 2
# Lenny BACKORY
# Andrew BAYISSA
# Joris ANGAMAN
# Martin DIAMANT
# Amel LASSAL
# Thomas TURPIN
# https://github.com/uvsq22004392/projet_incendie
######################################

# Importation des librairies #

import tkinter as tk
import random as rd

# Définition des constantes #

LARGEUR, HAUTEUR = 500, 700
TAILLE_CASE = 10
DUREE_FEU = 5
DUREE_CENDRES = 2

# Définition des variables globales #

cases = []
cases_graphismes = []

racine = tk.Tk()

canvas = tk.Canvas(racine, height=LARGEUR, width=LARGEUR//2, bg="white")
canvas.grid(column=0)
canvas2 = tk.Canvas(racine, height=LARGEUR, width=HAUTEUR, bg="white")
canvas2.grid(column=1, row=0)

# Définition des fonctions #

def etat_foret(nf):
    """Gère la probabilité de propagation de feu à une case de forêt."""
    proba = nf * 0.1 * 100
    feu = rd.randint(0, 100)
    if feu < proba:
        return "feu"

def terrain():
    """Génère un type de terrain aléatoire."""
    a = rd.randint(0, 3)
    if a == 0:
        return ["foret", 0]
    if a == 1:
        return ["prairie", 0]
    if a == 2:
        return ["eau", 0]
    if a == 3:
        return ['feu', DUREE_FEU]

def couleur(lieu):
    """Retourne la couleur en fonction de la case."""
    if lieu == "foret":
        return "#157120"
    if lieu == "prairie":
        return "#1DE034"
    if lieu == "eau":
        return "#1D87E0"
    if lieu == "feu":
        return "#E0211D"
    if lieu == "cendres":
        return "#817776"
    if lieu == "cendres_eteintes":
        return "#000000"

def refresh():
    """Redessine le terrain."""
    for i in range(HAUTEUR // TAILLE_CASE):
        for j in range(LARGEUR // TAILLE_CASE):
            canvas2.create_rectangle(
                                    (i * TAILLE_CASE, j * TAILLE_CASE),
                                    (i * TAILLE_CASE + TAILLE_CASE,
                                     j * TAILLE_CASE + TAILLE_CASE),
                                    fill=couleur(cases[i][j][0]),
                                    width=0)

def generer_terrain():
    """Fonction terrain() puis refresh()."""
    global cases
    cases = []
    cases = [[terrain() for i in range(LARGEUR // TAILLE_CASE)]
             for i in range(HAUTEUR // TAILLE_CASE)]
    refresh()

def etape_suivante():
    """Gère le déroulement de la simulation."""
    global cases
    for i in range(1, HAUTEUR // TAILLE_CASE - 1):
        for j in range(1, LARGEUR // TAILLE_CASE - 1):
            if cases[i][j][0] == 'foret':
                nf = 0
                if cases[i-1][j][0] == 'feu':
                    nf += 1
                if cases[i+1][j][0] == 'feu':
                    nf += 1
                if cases[i][j+1][0] == 'feu':
                    nf += 1
                if cases[i-1][j-1][0] == 'feu':
                    nf += 1
                if etat_foret(nf) == "feu":
                    cases[i][j] = ["feu", DUREE_FEU]
            elif cases[i][j][0] == 'prairie':
                if cases[i-1][j][0] == 'feu' or cases[i+1][j][0] == 'feu' \
                        or cases[i][j+1][0] == 'feu' \
                        or cases[i][j-1][0] == 'feu' \
                        or cases[i-1][j][0] == 'feu' \
                        or cases[i+1][j][0] == 'feu':
                    cases[i][j] = ["feu", DUREE_FEU]
            if cases[i][j][0] == "feu":
                cases[i][j][1] += -1
                if cases[i][j][1] <= 0:
                    cases[i][j][0], cases[i][j][1] = "cendres", DUREE_CENDRES
            elif cases[i][j][0] == "cendres":
                cases[i][j][1] += -1
                if cases[i][j][1] <= 0:
                    cases[i][j] = ["cendres_eteintes"]

    refresh()

# Programme principal #

bouton1 = tk.Button(racine, text="Génération de terrain aléatoire",
                    font=("helvetica", "10"), command=generer_terrain)
bouton1.place(x=0, y=100)

bouton2 = tk.Button(racine, text="Sauvegarde du terrain",
                    font=("helvetica", "10"))
bouton2.place(x=0, y=130)

bouton3 = tk.Button(racine, text="Charger un terrain",
                    font=("helvetica", "10"))
bouton3.place(x=0, y=160)

bouton4 = tk.Button(racine, text="Prochaine étape",
                    font=("helvetica", "10"), command=etape_suivante)
bouton4.place(x=0, y=200)

bouton5 = tk.Button(racine, text="Démarrer la simulation",
                    font=("helvetica", "10"))
bouton5.place(x=0, y=230)

bouton6 = tk.Button(racine, text="Stopper la simulation",
                    font=("helvetica", "10"))
bouton6.place(x=0, y=260)

racine.mainloop()


import socket
import time

s = socket.socket()
host = socket.gethostname()
port = 8080
s.bind((host, port))
s.listen()
print("waiting for connectiions")
conn, addr = s.accept()
print("client got connected")
time.sleep(3)

conn.send("welcome to server".encode())
while 1:
    msg = input(str(">>"))
    msg = msg.encode()
    conn.send(msg)
    print("message sent")
    msg2=conn.recv(1024)
    msg2=msg2.decode()
    print("client message:",msg2)


import pygame, sys
import random

pygame.init()

# Defining some colors
BLACK = (0, 0, 0)

# Setting the width and height of the screen [width, height]
width = 900
height = 600
size = (width, height)
screen = pygame.display.set_mode(size)
window = screen.get_rect()

# Defining some variables for game functionality
score_add = True # variable to indicate when to add a point
score = 0
highscore = 0
wallx = 840 # starting width of the walls (pipes)
birdy = 288 # starting height of the bird
gap = 60 # variable to manipulate the gap between walls(pipes). The actual gap is 2 times gap
offset_var = 50 # variable determining the range for the random generation of the offset
offset = random.randint(-offset_var, offset_var) # randomly generating the offset variable (the higher it is the bigger distance between consecutive gaps)
wallspeed = 0.5 # the speed at which the walls are moving to the left of the screen

# Defining the walls that the bird has to move through and the bird itself
wallup = pygame.image.load("top.png").convert_alpha() #Source: http://www.palmentieri.it/flappyjam/pipe.png
walldown = pygame.image.load("bottom.png").convert_alpha() #Source: http://www.palmentieri.it/flappyjam/pipe.png
bird = pygame.image.load("bird.png").convert_alpha() #Source: http://www.ellison.rocks/clumsy-bird/data/img/bg.png
birdRect = pygame.Rect(435, birdy, bird.get_width(), bird.get_height()) # getting rectangles of all images to make mathematics and collision correct
wallupRect = pygame.Rect(wallx, (-200 - gap + offset), wallup.get_width(), wallup.get_height())
walldownRect = pygame.Rect(wallx, (300 + gap + offset), walldown.get_width(), walldown.get_height())

# Setting the caption for the game
pygame.display.set_caption("FlappyBird the Game by Milosz Kadziela")

# Loading the image that will be used as the game background
background_image = pygame.image.load("bg.png").convert_alpha()

# Defining some fonts that will be used in the messages below
font = pygame.font.Font('freesansbold.ttf', 24) #d efining smallest font that will be used for controls description
font2 = pygame.font.Font('freesansbold.ttf', 32) # defining a bigger font that will be used for main directional messages
font3 = pygame.font.Font('freesansbold.ttf', 40) # defining even bigger font that will be used for the main_menu title of the game
font4 = pygame.font.Font('freesansbold.ttf', 50) # defining the biggest for that will be used for "top of the screen" messages

# Defining some messages that will be displayed on the screen throughout the gameplay (directional messages - key instuctions)
controls_msg = font2.render("'C' - Controls", True, BLACK)
quit_msg = font2.render("'Q' - Quit", True, BLACK)
menu_msg = font2.render("'M' - Menu", True, BLACK)
restart_msg = font2.render(" 'R' - Restart", True, BLACK)
game_msg = font2.render("'P' - Play", True, BLACK)
back_msg = font2.render("'B' - Back", True, BLACK)

# Defining some other messages that will be visible in the game
name_msg = font3.render("FlappyBird the Game by Milosz Kadziela", True, BLACK)
gameover_msg = font4.render("Game Over!", True, BLACK)
controls_heading_msg = font2.render("Controls:", True, BLACK)
controls_description_msg = font.render("To fly the bird use 'SPACEBAR'", True, BLACK)
score_msg = font.render("Score: ", True, BLACK)
highscore_msg = font.render("Highscore: ", True, BLACK)
diff_heading_msg = font4.render("Choose the diffuculty:", True, BLACK)
diff1_msg = font.render("'1' - Easy ", True, BLACK)
diff2_msg = font.render("'2' - Medium ", True, BLACK)
diff3_msg = font.render("'3' - Hard ", True, BLACK)

def update():
	'''Function responsible for conroling the movement of the walls, generating the gap, controlling the movement of the bird
	adding score and restating the position of walls when they reacg the left side of the screen'''
	global wallx, wallspeed, wallup, walldown, score, score_add, offset, x, wallupRect, walldownRect, birdy, birdRect, score_msg
	wallx -= wallspeed
	birdy += 0.2
	wallupRect = pygame.Rect(wallx, (-200 - gap + offset), wallup.get_width(), wallup.get_height())
	walldownRect = pygame.Rect(wallx, (300 + gap + offset), walldown.get_width(), walldown.get_height())
	birdRect = pygame.Rect(435, birdy, bird.get_width(), bird.get_height())
	if score_add == True:
		if wallx < 450:
			score += 1
			score_add = False
	if wallx < 0:
		score_add = True
		offset = random.randint(-offset_var, offset_var)
		wallx = 900

# Variable used to manage how fast the screen updates
clock = pygame.time.Clock()

# Setting the starting value for the variable which is used to navigate through modules in MainLoop
gamestate = "Menu"

# HERE STARTS THE PROGRAM MAIN LOOP CONTAINING 5 SUB-LOOPS FOR MENU PURPOSES AND THE LIVE GAME
while True:
	# --- MainLoop ---
	while gamestate == "Menu":
		# Event loop displaying Menu window
		for event in pygame.event.get():
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_q:
					sys.exit()
				if event.key == pygame.K_c:
					gamestate = "Controls"
				if event.key == pygame.K_p:
					gamestate = "Settings"
			if event.type == pygame.QUIT:
				sys.exit()

		screen.blit(background_image, [0,0]) #sets the image as the background
		screen.blit(name_msg, [60, 100]) #blicts the message in the middle of the screen
		screen.blit(game_msg, [380, 200]) #blits the message in the middle of the screen
		screen.blit(controls_msg, [50,530]) #blits the message to bottom left corner
		screen.blit(quit_msg, [705, 530]) #blits the message to bottom right corner

		# Updating the screen
		pygame.display.flip()

		# Limiting to 60 frames per second
		clock.tick(60)

	while gamestate == "Settings":
		# Event loop displaying Difficulty_settings window
		for event in pygame.event.get():
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_q:
					sys.exit()
				if event.key == pygame.K_1:
					offset_var = 50
					wallspeed = 0.5
					gamestate = "Game"
				if event.key == pygame.K_2:
					offset_var = 100
					wallspeed = 0.7
					gamestate = "Game"
				if event.key == pygame.K_3:
					offset_var = 200
					wallspeed = 0.9
					gamestate = "Game"
				if event.key == pygame.K_b:
					gamestate = "Menu"
			if event.type == pygame.QUIT:
				sys.exit()

		screen.blit(background_image, [0, 0])
		screen.blit(diff_heading_msg, [175, 50])
		screen.blit(diff1_msg, [380, 160])
		screen.blit(diff2_msg, [365, 200])
		screen.blit(diff3_msg, [380, 240])
		screen.blit(back_msg, [705, 530])

		pygame.display.flip()
		clock.tick(60)

	while gamestate == "Controls":
		# Event loop displaying Controls window
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				sys.exit()
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_m:
					gamestate = "Menu"

		screen.blit(background_image, [0, 0])
		screen.blit(menu_msg, [50, 530])
		screen.blit(controls_heading_msg, [400,50])
		screen.blit(controls_description_msg, [270,300])

		pygame.display.flip()

		clock.tick(60)

	while gamestate == "Game":
		# --- Live game loop ---
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				sys.exit()
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_q:
					sys.exit()
				if event.key == pygame.K_SPACE:
					birdy -= 60

		# Declaring the collision statement check. To see if the bird has collided with any of the walls
		if birdRect.colliderect(wallupRect) or birdRect.colliderect(walldownRect):
			gamestate = "Gameover"
		# Declaring the collision statement check. To see if the bird has collided with the top or bottom of the screen
		# +20 and -20 to make it eaier to go through gaps that generate just at the top or bottom of the screen on the highest difficulty
		if birdRect.top < window.top - 20 or birdRect.bottom > window.bottom + 20:
			gamestate = "Gameover"
		update()

		score_msg = font2.render("Score: " + str(score), True, BLACK)

		screen.blit(background_image, [0, 0])
		screen.blit(wallup, (wallx, (-200 - gap + offset))) # blitting the screen with the upper wall
		screen.blit(walldown, (wallx, (300 + gap + offset))) # blitting the screen with the bottom wall
		screen.blit(bird, (435, birdy)) # blitting the screen with the bird
		screen.blit(score_msg, [400, 20]) # blitting the screen with the "live-updated" score msg at the top of the screen

		pygame.display.flip()

	while gamestate == "Gameover":
		# Event loop displaying Gameover window
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				sys.exit()
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_m:
					wallx = 900
					birdy = 288
					score = 0
					update()
					gamestate = "Menu"
				if event.key == pygame.K_r:
					wallx = 900 # setting the position of bird and walls to the original, so that user gets a fresh start when they hit restart
					birdy = 288
					score = 0
					update()
					gamestate = "Game"

		# condition for potential change of the highscore if the player surpasses the previous best
		if score > highscore:
			highscore = score
		score_msg = font.render("Score: " + str(score), True, BLACK)
		highscore_msg = font.render("Highscore: " + str(highscore), True, BLACK)

		screen.blit(background_image, [0, 0])
		screen.blit(menu_msg, [685, 530])
		screen.blit(restart_msg, [50,530])
		screen.blit(gameover_msg, [300, 120])
		screen.blit(score_msg, [400, 200])
		screen.blit(highscore_msg, [375, 240])

		pygame.display.flip()

		clock.tick(60)
# Close the window and quit
pygame.quit()


from JsonHttpRetriever import JsonHttpRetriever
from UrlProvider import UrlProvider
from HospitalService import HospitalService
from DateConverter import DateConverter
from Hospital import Hospital
from HospitalServiceCode import HospitalServiceCode

class HospitalServiceProvider(JsonHttpRetriever):
    def __init__(self):
        JsonHttpRetriever.__init__(self)

    def get(self, code, priority, hospital, ssn, start_date):
        if isinstance(code, HospitalServiceCode):
            code = code.code

        if isinstance(hospital, Hospital):
            hospital = hospital.id_hospital

        self.setUrl(UrlProvider.healthServiceAvailability(code, priority, hospital, ssn, start_date))

        jsonservices = self.load()

        if self.areThereErrors():
            print("CRITICAL: server side error:", self.rawdata)
            return []

        services = []

        #generating a single service for every possible combination
        for jsonservice in jsonservices:
            for date in jsonservice['date']:
                for orari in date['orari']:
                    s = HospitalService()
                    s.code = code
                    s.hospital = hospital
                    s.date = DateConverter.fromStringToDate(date['data'], orari)
                    s.hospital = jsonservice['sede']['descrizione']
                    s.id_hospital = jsonservice['sede']['idStruttura']
                    s.unit = jsonservice['unitaOfferente']['descrizione']
                    s.id_unit = jsonservice['unitaOfferente']['idStruttura']

                    services.append(s)

        return services


from scrapy_splash import SplashRequest
from scrapy.selector import Selector
import scrapy
import json

class ListingsSpider(scrapy.Spider):

    name = "listings"
    allowed_domains = ["www.centris.ca"]
    position = {"startPosition": 0}

    http_user = "user"
    http_pass = "userpass"

    script = """
            function main(splash, args)

              splash:on_request(function(request)
                  if request.url:find("css") then
                   request.abort()
                  end
              end)

              splash.private_mode_enabled = false
              splash.images_enabled = false
              splash.js_enabled = false

              req_headers = {
                ["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36",
                ["Accept-Language"] = "en-GB,en;q=0.9,en-US;q=0.8,es;q=0.7"
              }

              splash:set_custom_headers(req_headers)

              assert(splash:go(args.url))
              assert(splash:wait(1.5))

              splash:set_viewport_full()
              return splash:html()

            end
        """

    def start_requests(self):

        yield scrapy.Request(
            url="https://www.centris.ca/UserContext/Lock",
            method="POST",
            headers={
                "x-requested-with": "XMLHttpRequest",
                "Content-Type": "application/json",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"

            },
            body=json.dumps({"uc": 0}),
            callback=self.generate_uck
        )

    def generate_uck(self, response):

        uck = response.text

        query = {
            "query": {
                "UseGeographyShapes": 0,
                "Filters": [
                    {
                        "MatchType": "CityDistrictAll",
                        "Text": "Montréal (All boroughs)",
                        "Id": 5
                    }
                ],
                "FieldsValues": [
                    {
                        "fieldId": "CityDistrictAll",
                        "value": 5,
                        "fieldConditionId": "",
                        "valueConditionId": ""
                    },
                    {
                        "fieldId": "Category",
                        "value": "Residential",
                        "fieldConditionId": "",
                        "valueConditionId": ""
                    },
                    {
                        "fieldId": "SellingType",
                        "value": "Rent",
                        "fieldConditionId": "",
                        "valueConditionId": ""
                    },
                    {
                        "fieldId": "LandArea",
                        "value": "SquareFeet",
                        "fieldConditionId": "IsLandArea",
                        "valueConditionId": ""
                    },
                    {
                        "fieldId": "RentPrice",
                        "value": 0,
                        "fieldConditionId": "ForRent",
                        "valueConditionId": ""
                    },
                    {
                        "fieldId": "RentPrice",
                        "value": 1500,
                        "fieldConditionId": "ForRent",
                        "valueConditionId": ""
                    }
                ]
            },
            "isHomePage": True
        }

        yield scrapy.Request(
            url="https://www.centris.ca/property/UpdateQuery",
            method="POST",
            body=json.dumps(obj=query),
            headers={
                 "Content-Type": "application/json",
                 "x-requested-with": "XMLHttpRequest",
                 "x-centris-uc": 0,
                 "x-centris-uck": uck,
                 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"
             },
            callback=self.update_query,
            meta={"suck": uck}
        )

    def update_query(self, response):

        fuck = response.request.meta["suck"]

        yield scrapy.Request(
            url="https://www.centris.ca/Property/GetInscriptions",
            method="POST",
            body=json.dumps(self.position),
            headers={
                "Content-Type": "application/json",
                "x-requested-with": "XMLHttpRequest",
                "x-centris-uc": 0,
                "x-centris-uck": fuck,
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"
            },
            callback=self.parse,
            meta={"duck": fuck}
        )

    def parse(self, response):

        buck = response.request.meta["duck"]
        resp = json.loads(s=response.body)
        html = resp.get("d").get("Result").get("html")

        # with open(file="index.html", mode="w") as f:
        #     f.write(html)

        sel = Selector(text=html)
        apts = sel.xpath("//div[contains(@class, 'property-thumbnail-item')]")

        for apt in apts:

            relative_url = apt.xpath(".//div[@class='shell']/a/@href").get()
            absolute_url = f"https://www.centris.ca/en{relative_url[3:]}"
            price = apt.xpath("normalize-space(.//div//div[@class='price']/span[1]//text())").get()

            yield SplashRequest(
                url=absolute_url,
                callback=self.parse_summary,
                endpoint="execute",
                args={
                    "lua_source": self.script
                },
                meta={
                    "cat": apt.xpath("normalize-space(.//span[@class='category']//div/text())").get(),
                    "fea": apt.xpath("normalize-space(.//div[@class='cac']/text())").get(),
                    "pri": price.replace("\xa0", ""),
                    "cit": apt.xpath(".//span[@class='address']/div[2]//text()").get(),
                    "link": absolute_url
                }
            )

        count = resp.get("d").get("Result").get("count")
        increment = resp.get("d").get("Result").get("inscNumberPerPage")

        if self.position["startPosition"] <= count:

            self.position["startPosition"] += increment

            yield scrapy.Request(
                url="https://www.centris.ca/Property/GetInscriptions",
                method="POST",
                body=json.dumps(self.position),
                headers={
                    "Content-Type": "application/json",
                    "x-requested-with": "XMLHttpRequest",
                    "x-centris-uc": 0,
                    "x-centris-uck": buck,
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"
                },
                callback=self.parse,
                meta={"duck": buck}
            )

    def parse_summary(self, response):

        yield {
            "address": response.xpath("(//h2[@itemprop='address']/text())[1]").get(),
            "description": response.xpath("normalize-space(//div[@itemprop='description']/text())").get(),
            "features": response.request.meta["fea"],
            "price": response.request.meta["pri"],
            "city": response.request.meta["cit"],
            "url": response.request.meta["link"],
            "category": response.request.meta["cat"]
        }


from gui.Scaleform.managers.windows_stored_data import DATA_TYPE, TARGET_ID
from gui.Scaleform.managers.windows_stored_data import stored_window
from messenger.gui.Scaleform.data.MembersDataProvider import MembersDataProvider
from messenger.gui.Scaleform.meta.LobbyChannelWindowMeta import LobbyChannelWindowMeta
from messenger.gui.Scaleform.view.SimpleChannelWindow import SimpleChannelWindow

@stored_window(DATA_TYPE.CHANNEL_WINDOW, TARGET_ID.CHANNEL_CAROUSEL)

class LobbyChannelWindow(SimpleChannelWindow, LobbyChannelWindowMeta):

    def _populate(self):
        super(LobbyChannelWindow, self)._populate()
        channel = self._controller.getChannel()
        if channel.haveMembers():
            membersDP = MembersDataProvider()
            membersDP.setFlashObject(self.as_getMembersDPS())
            self._controller.setMembersDP(membersDP)
        else:
            self.as_hideMembersListS()

    def _dispose(self):
        if self._controller is not None:
            self._controller.removeMembersDP()
        super(LobbyChannelWindow, self)._dispose()
        return


#!/usr/bin/python2
# -*- coding: utf-8 -*-
# pylint: disable=all

#------------------------------------------------------
# Import der Libraries
#------------------------------------------------------
import clr
clr.AddReference("IronPython.SQLite.dll")
clr.AddReference("IronPython.Modules.dll")
import sqlite3

#------------------------------------------------------
# Klasse
#------------------------------------------------------
class DBConnector( object ):
    ''' Instanziert eine Datenbank als Objekt '''
    def __init__( self, dbfile ):
        """ Instanz einer Datenbank erstellen. """
        self.ClassName = "DBConnector"
        thisActionName = "__init__"

        self._connection = sqlite3.connect(
            dbfile,
            check_same_thread=False,
            detect_types=sqlite3.PARSE_DECLTYPES
            | sqlite3.PARSE_COLNAMES )
        self._cursor = self._connection.cursor()

    def __del__( self ):
        """ Close the instanced database connection on destroy. """
        thisActionName = "__del__"
        self._connection.close()

    def execute( self, sql_query, query_args=None ):
        """ Execute a sql query on the instanced database. """
        thisActionName = "execute"

        if query_args:
            self._cursor.execute( sql_query, query_args )
        else:
            self._cursor.execute( sql_query )

        return self._cursor

    def commit( self ):
        """ Commit any changes of the instanced database. """
        thisActionName = "commit"

        try:
            self._connection.commit()
            return True
        except sqlite3.Error:
            return False

    def close( self ):
        """ Close the instanced database connection. """

        self._connection.close()
        return


import logging
import os
from urllib.parse import quote

from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.db.models import QuerySet
from django.http import Http404, HttpRequest, HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.template.loader import render_to_string
from django.views.decorators.http import require_http_methods
from weasyprint import CSS, HTML

from ..models import TypeOfAnimals
from ..models.animals import Animal
from ..models.awg import Awg, AwgMember
from ..models.fosterer import (
    FosterApplication,
    FostererExistingPetDetail,
    FostererPersonInHomeDetail,
    FostererProfile,
    FostererReferenceDetail,
)

@login_required()
@require_http_methods(["POST", "GET"])
def application(request):
    user = request.user

    # check if person has completed fosterer profile. if not send to fill.
    try:
        fosterer_profile = FostererProfile.objects.get(user=user)
    except FostererProfile.DoesNotExist:
        return redirect("/fosterer")

    if not fosterer_profile.is_complete:
        return redirect("/fosterer")

    if request.method == "POST":
        animal_id = request.POST.get("animal_id")

        try:
            animal = Animal.objects.get(pk=animal_id)
        except Animal.DoesNotExist as e:
            raise Http404("No Animal matches the given query.") from e

        # check if application exists already
        try:
            FosterApplication.objects.get(fosterer=fosterer_profile, animal=animal)
            return render(
                request,
                "foster_application/exists.html",
                {
                    "user": user,
                    "pageTitle": "Foster application already exists",
                },
            )
        except FosterApplication.DoesNotExist:
            pass

        application = FosterApplication(
            fosterer=fosterer_profile,
            animal=animal,
            status=FosterApplication.Statuses.PENDING,
            reject_reason_detail=None,
        )

        application.save()

        return render(
            request,
            "foster_application/complete.html",
            {
                "user": user,
                "pageTitle": "Foster application complete",
            },
        )

    else:
        # GET method expects animal_id in query string
        animal_id = request.GET.get("animal_id", None)
        animal = get_object_or_404(Animal, pk=animal_id)

    return render(
        request,
        "foster_application/application.html",
        {
            "user": user,
            "animal": animal,
            "fosterer_profile": fosterer_profile,
            "pageTitle": "Foster Application",
            "current_url_escaped": quote(request.get_full_path()),
        },
    )

@login_required()
def download_foster_application(request: HttpRequest) -> HttpResponse:
    fosterer_id = request.GET.get("fosterer_id", None)
    animal_id = request.GET.get("animal_id", None)

    user = request.user
    awg_member = AwgMember.objects.filter(user=user).first()
    if not awg_member:
        raise PermissionDenied("You are not a member of an AWG")

    awg: Awg = awg_member.awg

    if not awg.status == "PUBLISHED":
        raise PermissionDenied("Your AWG is not published")

    fosterer: FostererProfile = get_object_or_404(FostererProfile, pk=fosterer_id)
    animal: Animal = get_object_or_404(Animal, pk=animal_id)
    foster_application: FosterApplication = get_object_or_404(
        FosterApplication, fosterer=fosterer, animal=animal
    )

    existing_animals: QuerySet[
        FostererExistingPetDetail
    ] = FostererExistingPetDetail.objects.filter(fosterer_profile=fosterer)
    references: QuerySet[
        FostererReferenceDetail
    ] = FostererReferenceDetail.objects.filter(fosterer_profile=fosterer)
    people_in_home: QuerySet[
        FostererPersonInHomeDetail
    ] = FostererPersonInHomeDetail.objects.filter(fosterer_profile=fosterer)

    animal_type_labels = []
    if fosterer.type_of_animals:
        animal_type_labels = [
            TypeOfAnimals(animal_type).label for animal_type in fosterer.type_of_animals
        ]

    category_of_animals_labels = []
    if fosterer.category_of_animals:
        category_of_animals_labels = [
            fosterer.CategoryOfAnimals(category).label
            for category in fosterer.category_of_animals
        ]

    dog_size_labels = []
    if fosterer.dog_size:
        dog_size_labels = [
            fosterer.DogSize(dog_size).label for dog_size in fosterer.dog_size
        ]

    behaviour_labels = []
    if fosterer.behavioural_attributes:
        behaviour_labels = [
            fosterer.BehaviouralAttributes(behaviour).label
            for behaviour in fosterer.behavioural_attributes
        ]

    experience_categories_labels = []
    if fosterer.experience_categories:
        experience_categories_labels = [
            fosterer.ExperienceCategories(experience).label
            for experience in fosterer.experience_categories
        ]

    context = {
        "application": foster_application,
        "existing_animals": existing_animals,
        "references": references,
        "people_in_home": people_in_home,
        "animal_type_labels": animal_type_labels,
        "dog_size_labels": dog_size_labels,
        "category_of_animals_labels": category_of_animals_labels,
        "behaviour_labels": behaviour_labels,
        "experience_categories_labels": experience_categories_labels,
    }

    pdf_string = render_to_string("fosterer_profile/pdf.html", context, request)
    pdf_file = HTML(string=pdf_string).write_pdf(
        stylesheets=[
            CSS(string="@page { size: letter portrait; margin: 1cm }"),
            CSS(filename=os.path.join(settings.STATIC_ROOT, "vendor/normalize.css")),
            CSS(filename=os.path.join(settings.STATIC_ROOT, "css/pdf.css")),
        ]
    )

    response = HttpResponse(pdf_file, content_type="application/pdf")
    response["Content-Disposition"] = f"filename=fosterer-profile-{fosterer_id}.pdf"
    for a in existing_animals:
        logging.info("animal spayed_neutered is %s", a.spayed_neutered)
    return response


"""
https://www.pythonforengineers.com/audio-and-digital-signal-processingdsp-in-python/
"""
import signalwave

def main():
    frequency = 500
    sampling_rate = 48000
    amplitude = 16000
    time_ = 2

    wave1 = signalwave.signalwave(frequency, sampling_rate, time=time_)
    abs_wave = [abs(signal) for signal in wave1]

    # Plot the 2 waves
    signalwave.plot(wave1, abs_wave)

    signalwave.save_wave(wave1, file_path='wave.wav')
    signalwave.save_wave(abs_wave, file_path='abs_wave.wav')

if __name__ == '__main__':
    main()


# coding: utf-8

# # Object Detection Demo
# Welcome to the object detection inference walkthrough!  This notebook will walk you step by step through the process of using a pre-trained model to detect objects in an image. Make sure to follow the [installation instructions](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md) before you start.

# # Imports

# In[1]:

import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import math
import argparse

from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image

# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")
from utils import ops as utils_ops

if tf.__version__ < '1.4.0':
  raise ImportError('Please upgrade your tensorflow installation to v1.4.* or later!')

# ## Env setup

# In[2]:

# ## Object detection imports
# Here are the imports from the object detection module.

# In[3]:

from utils import label_map_util

from utils import visualization_utils as vis_util

# # Model preparation

# ## Variables
#
# Any model exported using the `export_inference_graph.py` tool can be loaded here simply by changing `PATH_TO_CKPT` to point to a new .pb file.
#
# By default we use an "SSD with Mobilenet" model here. See the [detection model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md) for a list of other models that can be run out-of-the-box with varying speeds and accuracies.

# In[4]:

# What model to download.
MODEL_NAME = 'ball_inference_graph_32744'

# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = 'object_detection/' + MODEL_NAME + '/frozen_inference_graph.pb'

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('training', 'object-detection.pbtxt')

NUM_CLASSES = 1

"""
# What model to download.
MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'

# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')

NUM_CLASSES = 90
"""

# ## Load a (frozen) Tensorflow model into memory.

# In[5]:

detection_graph = tf.Graph()
with detection_graph.as_default():
  od_graph_def = tf.GraphDef()
  with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
    serialized_graph = fid.read()
    od_graph_def.ParseFromString(serialized_graph)
    tf.import_graph_def(od_graph_def, name='')

# ## Loading label map
# Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`.  Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine

# In[6]:

label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

# ## Helper code

# In[7]:

def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size
  return np.array(image.getdata()).reshape(
      (im_height, im_width, 3)).astype(np.uint8)

# In[ ]:

def run_inference_for_single_image(image, graph):
    with graph.device('/device:GPU:0'):
        with graph.as_default():
            config = tf.ConfigProto(allow_soft_placement = True)
            with tf.Session(config=config) as sess:
                # Get handles to input and output tensors
                ops = tf.get_default_graph().get_operations()
                all_tensor_names = {output.name for op in ops for output in op.outputs}
                tensor_dict = {}
                for key in [
                        'num_detections', 'detection_boxes', 'detection_scores',
                        'detection_classes', 'detection_masks'
                ]:
                    tensor_name = key + ':0'
                    if tensor_name in all_tensor_names:
                        tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
                                tensor_name)
                if 'detection_masks' in tensor_dict:
                    # The following processing is only for single image
                    detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
                    detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
                    # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
                    real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
                    detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
                    detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
                    detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
                            detection_masks, detection_boxes, image.shape[0], image.shape[1])
                    detection_masks_reframed = tf.cast(
                            tf.greater(detection_masks_reframed, 0.5), tf.uint8)
                    # Follow the convention by adding back the batch dimension
                    tensor_dict['detection_masks'] = tf.expand_dims(
                            detection_masks_reframed, 0)
                image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')

                # Run inference
                output_dict = sess.run(tensor_dict,
                                                             feed_dict={image_tensor: np.expand_dims(image, 0)})

                # all outputs are float32 numpy arrays, so convert types as appropriate
                output_dict['num_detections'] = int(output_dict['num_detections'][0])
                output_dict['detection_classes'] = output_dict[
                        'detection_classes'][0].astype(np.uint8)
                output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
                output_dict['detection_scores'] = output_dict['detection_scores'][0]
                if 'detection_masks' in output_dict:
                    output_dict['detection_masks'] = output_dict['detection_masks'][0]
        return output_dict

import cv2

def preprocess(image_np):
  hsv = cv2.cvtColor(image_np, cv2.COLOR_BGR2HSV)

  lower_red = np.array([0, 130, 33])
  upper_red = np.array([19, 255, 255])

  lower_red2 = np.array([164, 111, 0])
  upper_red2 = np.array([180, 255, 255])

  mask = cv2.inRange(hsv, lower_red, upper_red)
  mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
  mask_tot = mask | mask2

  mask_tot = cv2.erode(mask_tot, None, iterations=3)
  mask_tot = cv2.dilate(mask_tot, None, iterations=3)

  image_np = cv2.bitwise_and(image_np, image_np, mask=mask_tot)

  return image_np

def calculate_3d_cord(bbox, image):
    """
    :param bbox: Bounding box, normalized coordinates [y0,x0,y1,x1]
    :return: dict{"d": distance,
                    "center_x" : .. ,
                    "center_y" : ..}
    """
    #Get angles
    ang_hoz = math.radians(59.68)
    ang_ver = math.radians(36)

    h, w, _ = image.shape
    y0 = bbox[0]*h
    x0 = bbox[1]*w
    y1 = bbox[2]*h
    x1 = bbox[3]*w
    #size_bbox = (np.abs(y0-y1) + np.abs(x0-x1)) / 2
    center_y = y0 + np.abs(y0-y1)/2 - h/2
    center_x = x0 + np.abs(x0-x1)/2 - w/2

    d = find_distance(image, x1, x0, y1, y0)

    # x_meter = x_pixel * meter_hoz/pixel
    center_x = center_x * (2 * d * math.tan(ang_hoz / 2)) / w
    center_y = center_y * (2 * d * math.tan(ang_ver / 2)) / h

    return {"d" : d, "center_x": center_x, "center_y" : center_y}

def find_distance(image, xmax, xmin, ymax, ymin):
    """
    Finds the distance to the object given by the cords of the bounding box
    """
    resy, resx, _ = image.shape

    r = ((xmax - xmin) / resx + (ymax - ymin) / resy) / 2

    return 0.1168 / r

def plot_points(points, image, roll, lw, rx, ry):
    """
    :param points: [x_cord [m], y_cord [m], distance [m]]
    :param image: image [h, w, 3]
    :param roll: size of rolling window (int)
    :return: None - Plots points
    """
    import pandas as pd
    from mpl_toolkits.mplot3d import Axes3D

    #Get angels
    ang_hoz = math.radians(59.68)
    ang_ver = math.radians(36)

    #Get image dimensions
    h, w, _ = image.shape

    #Convert to numpy matrix
    points = np.array(points)
    x = points[:,0]
    y = -points[:,1]
    z = points[:,2]

    #Smooth depth
    z = pd.DataFrame(z)
    z = np.array(z.rolling(roll).mean()).flatten()

    y = pd.DataFrame(y)
    y = np.array(y.rolling(ry).mean()).flatten()

    x = pd.DataFrame(x)
    x = np.array(x.rolling(rx).mean()).flatten()

    fig = plt.figure()
    ax = plt.axes(projection='3d')

    ax.plot(x, y, z, '-b', zdir = 'y', label='3D Estimate', linewidth=lw)

    z_min = np.min(z[~np.isnan(z)])
    z_max = np.max(z[~np.isnan(z)])
    z_range = z_max-z_min
    ax.set_ylim(0, z_max + 0.5*z_range)

    lim = float((2*z_max*math.tan(ang_hoz/2)))
    ax.set_xlim(-lim/2, lim/2)
    ax.set_zlim(-lim/2, lim/2)

    ax.set_xlabel('X axis [M]')
    ax.set_ylabel('Depth [M]')
    ax.set_zlabel('Y [M]')
    ax.view_init(30, 230)

    """ Code for finding optimal angel
    for angle in range(150, 280):
        print(angle)
        ax.view_init(30, angle)
        plt.draw()
        plt.pause(.01)
    """

    plt.show()

def detect_vid(video, fraction):
    cap = cv2.VideoCapture(video)
    count = 0
    points = []
    image_np_org = None

    with detection_graph.as_default():
      with tf.Session(graph=detection_graph) as sess:
        while(cap.isOpened()):
          ret, image_np = cap.read()
          if not ret:
              break
          image_np_org = np.copy(image_np)
          count += 1
          if ret and (count % int(1/fraction) == 0):

              image_np = preprocess(image_np)

              # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
              image_np_expanded = np.expand_dims(image_np, axis=0)
              image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
              # Each box represents a part of the image where a particular object was detected.
              boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
              # Each score represent how level of confidence for each of the objects.
              # Score is shown on the result image, together with the class label.
              scores = detection_graph.get_tensor_by_name('detection_scores:0')
              classes = detection_graph.get_tensor_by_name('detection_classes:0')
              num_detections = detection_graph.get_tensor_by_name('num_detections:0')
              # Actual detection.
              (boxes, scores, classes, num_detections) = sess.run(
                  [boxes, scores, classes, num_detections],
                  feed_dict={image_tensor: image_np_expanded})
              # Visualization of the results of a detection.

              vis_util.visualize_boxes_and_labels_on_image_array(
                image_np_org,
                np.squeeze(boxes),
                np.squeeze(classes).astype(np.int32),
                np.squeeze(scores),
                category_index,
                use_normalized_coordinates=True,
                line_thickness=8,
                min_score_thresh=.3)

              if scores[0][0] > 0.15:
                  point = calculate_3d_cord(boxes[0][0], image_np_org)
                  points.append([point["center_x"], point["center_y"], point["d"]])
                  print(point)
                  if count % 4 == 0:
                      #pass
                      cv2.imwrite("detections/" + video[16:-4] + "_{}".format(count) + ".png",
                                  image_np_org)
              cv2.imshow('object detection', cv2.resize(image_np_org, (1200,800)))
              if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break

        plot_points(points, image_np_org, 12, 3, 2, 2)
        cap.release()
        cv2.destroyAllWindows()

    cap.release()
    cv2.destroyAllWindows()

def detect_vid2(video, fraction):
    cap = cv2.VideoCapture(video)
    count = 0
    ret, image = cap.read()
    with detection_graph.as_default():
      with tf.Session(graph=detection_graph) as sess:
        ops = tf.get_default_graph().get_operations()
        all_tensor_names = {output.name for op in ops for output in op.outputs}
        tensor_dict = {}
        for key in [
                'num_detections', 'detection_boxes', 'detection_scores',
                'detection_classes', 'detection_masks'
        ]:
            tensor_name = key + ':0'
            if tensor_name in all_tensor_names:
                tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
                        tensor_name)
        if 'detection_masks' in tensor_dict:
            # The following processing is only for single image
            detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
            detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
            # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
            real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
            detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
            detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
            detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
                    detection_masks, detection_boxes, image.shape[0], image.shape[1])
            detection_masks_reframed = tf.cast(
                    tf.greater(detection_masks_reframed, 0.5), tf.uint8)
            # Follow the convention by adding back the batch dimension
            tensor_dict['detection_masks'] = tf.expand_dims(
                    detection_masks_reframed, 0)
        image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')

        while(cap.isOpened()):
          ret, image = cap.read()
          image_org = np.copy(image)
          image = preprocess(image)
          count += 1
          if ret and (count % int(1/fraction) == 0):
              #Run inference
              output_dict = sess.run(tensor_dict,
                                                           feed_dict={image_tensor: np.expand_dims(image, 0)})

              # all outputs are float32 numpy arrays, so convert types as appropriate
              output_dict['num_detections'] = int(output_dict['num_detections'][0])
              output_dict['detection_classes'] = output_dict[
                      'detection_classes'][0].astype(np.uint8)
              output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
              output_dict['detection_scores'] = output_dict['detection_scores'][0]
              if 'detection_masks' in output_dict:
                  output_dict['detection_masks'] = output_dict['detection_masks'][0]

              box = []

              for i, cat in enumerate(output_dict['detection_classes']):
                  s = output_dict['detection_scores'][i]
                  c = category_index[cat]['name']
                  if s < 0.02:
                      print("fail")
                      break

                  if c in ["Ball"]:
                      box.append(output_dict['detection_boxes'][i])
                      break

              if len(box) > 0:
                  vis_util.draw_bounding_box_on_image_array(image_org, box[0][0], box[0][1],
                                                            box[0][2], box[0][3])

              cv2.imshow('object detection', cv2.resize(image_org, (1200,800)))
              if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break

        cap.release()
        cv2.destroyAllWindows()

    cap.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='Video Detection')
  parser.add_argument('--video',  help='path to video file', default = "vid_data/videos/vid2.mov")
  parser.add_argument('--fraction', default=1,
                      help='fraction of images processed')

  args = parser.parse_args()
  detect_vid(args.video, float(args.fraction))


import os
import os.path
import shutil
import tempfile
import pickledb
import numpy as np
import networkx as nx
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt

class Helper:

    def __init__(self, G):
        self._g = G
        self._dimensions = G.nodes['0'].keys()

    def color(self, node):
        vec = np.array([self._g.nodes[node][d] for d in self._dimensions])
        ref = np.zeros_like(vec)
        ref[0] = 1

        d = np.sqrt(np.sum([e ** 2 for e in vec]))
        theta = vec.dot(ref) / np.sqrt(np.sum(vec ** 2) * np.sum(ref ** 2))
        return d * np.sin(theta)

    def weights_color(self):
        weights = [attr['weight'] for *_, attr in self._g.edges(data=True)]
        if weights:
            weights = np.array(weights)
            weights = weights / np.max(weights)
        colors = [(0.2, 0.2, 0.2, w) for w in weights]
        return colors

    @property
    def dimensions(self):
        return self.dimensions

class RandomGraph:

    def __init__(self, filename, trackid):
        self._outdb = pickledb.load(filename, False)
        self._trackid = trackid
        tmpgraph = nx.parse_gml(self._outdb.get(trackid + '_0'))
        self._pos = nx.random_layout(tmpgraph)

        nkeys = self._outdb.totalkeys() - 1
        snapshot_rate = self._outdb.get('_params')['snapshot_rate']
        self._snapshots = range(0, nkeys * snapshot_rate, snapshot_rate)

    def _load(self, graphid):
        return nx.parse_gml(self._outdb.get(graphid))

    def _plot(self, stepid):
        G = self._load(self._trackid + '_' + stepid)
        helper = Helper(G)
        nodecolors = [helper.color(node) for node in G.nodes]
        nodesize = 30
        edgecolor = helper.weights_color()

        nodes = nx.draw_networkx_nodes(G, self._pos, \
                node_color=nodecolors, node_size=nodesize, linewidths=.3, \
                edgecolors='#333333', cmap=plt.cm.Spectral)
        edges = nx.draw_networkx_edges(G, self._pos, node_size=nodesize, \
                width=.5)
        if edges:
            edges._edgecolors = mcolors.to_rgba_array(edgecolor)

    def plot_gif(self, filename, deleteimgs=True):
        tmpdir = tempfile.mkdtemp()
        imgcounter = 0
        for i in self._snapshots:
            imgname = '%04d.png' % imgcounter
            path = os.path.join(tmpdir, imgname)
            self.plot(str(i), path)
            imgcounter += 1

        os.system(f'convert {tmpdir}/* -delay 50 -loop 0 {filename}')

        if deleteimgs:
            shutil.rmtree(tmpdir)

    def plot(self, stepid, filename):
        self._plot(stepid)
        plt.savefig(filename, dpi=150, bbox_inches='tight', \
                pad_inches=-0.05)
        plt.clf()

class ClusterGraph(RandomGraph):
    def __init__(self, filename, trackid):
        self._outdb = pickledb.load(filename, False)
        self._trackid = str(trackid)

        nkeys = self._outdb.totalkeys() - 1
        snapshot_rate = self._outdb.get('_params')['snapshot_rate']
        last_snapshot = nkeys * snapshot_rate
        self._snapshots = range(0, last_snapshot, snapshot_rate)

        graphid = trackid + '_' + str(last_snapshot - snapshot_rate)
        tmpgraph = nx.parse_gml(self._outdb.get(graphid))
        self._pos = nx.spring_layout(tmpgraph)

class SpringGraph(RandomGraph):
    def _load(self, graphid):
        G = nx.parse_gml(self._outdb.get(graphid))
        self._pos = nx.spring_layout(G)
        return G

class ScatterPlot:

    def __init__(self, filename, trackid):
        self._outdb = pickledb.load(filename, False)
        self._trackid = trackid
        nkeys = self._outdb.totalkeys() - 1
        snapshot_rate = self._outdb.get('_params')['snapshot_rate']
        self._snapshots = range(0, nkeys * snapshot_rate, snapshot_rate)

    def _load(self, graphid):
        return nx.parse_gml(self._outdb.get(graphid))

    def _plot(self, stepid):
        G = self._load(self._trackid + '_' + stepid)
        helper = Helper(G)
        nodecolors = [helper.color(node) for node in G.nodes]
        time = np.full_like(nodecolors, stepid)
        plt.scatter(time, nodecolors, s=2, c="#555555")

    def plot(self, filename):
        for i in self._snapshots:
            self._plot(str(i))

        plt.savefig(filename, dpi=150, bbox_inches='tight')
        plt.clf()


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

# In[1]:

import pandas as pd
Location = "C:/Users/Kevin/Desktop/datasets/PVY01.xls"
df = pd.read_excel(Location)

# In[2]:

df.head()

# In[3]:

df.columns = ['first','last','sex','age','exer','hrs','grd','addr']
df.head()

# In[ ]:


import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddle.io import Dataset
from paddle.vision.transforms import Compose, Normalize
from paddle.vision.models import LeNet
import math
import numpy as np
import random
import os
from PIL import Image
normalize = Normalize(mean=[127.5],
                        std=[127.5],
                        data_format='HWC')

#创建数据集读取
class RandomDataset(Dataset):
    def __init__(self, root = "data",mode="train"):
        self.mode = mode
        if mode == "train":
            self.txt_file = os.path.join(root,"train.txt")
        else:
            self.txt_file = os.path.join(root,"test.txt")
        self.records_list = []
        self.parse_dataset()

    def __getitem__(self, idx):
        path=self.records_list[idx][0]
        img = Image.open(path)
        img = img.resize((28, 28), Image.BILINEAR)
        img = normalize(img)
        label = int(self.records_list[idx][1])
        return img, label

    def __len__(self):
        return len(self.records_list)

    def parse_dataset(self):
        print(self.txt_file)
        with open(self.txt_file,'r') as f:
            for line in f.readlines():
                img_path, label = line.strip().split()
                self.records_list.append([img_path,label])
        random.shuffle(self.records_list)
train_dataset=RandomDataset()
test_dataset=RandomDataset(mode="test")

train_dataset=RandomDataset()
test_dataset=RandomDataset(mode="test")
train_loader = paddle.io.DataLoader(train_dataset, batch_size=32, shuffle=True)
test_loader = paddle.io.DataLoader(test_dataset, batch_size=32, shuffle=False)
# 加载训练集 batch_size 设为 64
def train(model):
    model.train()
    epochs = 10
    optim = paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters())
    # 用Adam作为优化函数
    for epoch in range(epochs):
        for batch_id, data in enumerate(train_loader()):
            x_data = data[0]
            y_data = data[1]
            y_data = paddle.unsqueeze(y_data, axis=1)
            predicts = model(x_data)
            loss = F.cross_entropy(predicts, y_data)
            # 计算损失
            acc = paddle.metric.accuracy(predicts, y_data,k=1)
            loss.backward()
            if batch_id % 300 == 0:
                print("epoch: {}, batch_id: {}, loss is: {}, acc is: {}".format(epoch, batch_id, loss.numpy(), acc.numpy()))
            optim.step()
            optim.clear_grad()
        model.eval()
        for batch_id, data in enumerate(train_loader()):
            x_data = data[0]
            y_data = data[1]
            y_data = paddle.unsqueeze(y_data, axis=1)
            predicts = model(x_data)
            loss = F.cross_entropy(predicts, y_data)
            # 计算损失
            test_acc = paddle.metric.accuracy(predicts, y_data,k=1)
            #loss.backward()
        print("test:loss is: {}, acc is: {}".format(loss.numpy(), acc.numpy()))
        model.train()
        if epoch % 2 == 0:
            paddle.save(model.state_dict(), "Tibetan_epoch"+str(epoch)+".pdparams")
model = LeNet()
train(model)


from dataclasses import dataclass
from enum import Enum
from pathlib import Path

class TargetTypes(Enum):
    DIRECTORY = 1
    FILE = 2

@dataclass
class BaseTarget:
    path: Path
    type: TargetTypes

    def __init__(self, path: Path):
        if not hasattr(self, "type"):
            raise NotImplementedError(
                "You need to set the type for BaseTarget subclass"
            )

        self.path = path


# Name: appleAndOrange.py
# Author: Robin Goyal
# Last-Modified: November 12, 2017
# Purpose: Check the number of apples and oranges that hit Sam's tree

def main():

    s, t = list(map(int, input().strip().split(' ')))
    a, b = list(map(int, input().strip().split(' ')))

    # Pointless line but the challenge included it
    m, n = list(map(int, input().strip().split(' ')))

    apples_dist = list(map(int, input().strip().split(' ')))
    oranges_dist = list(map(int, input().strip().split(' ')))

    print(num_hits(s, t, a, apples_dist))
    print(num_hits(s, t, b, oranges_dist))

def num_hits(start, end, tree_dist, fruit_dists):
    '''
    start: starting location of house
    end: ending location of house
    tree_dist: location of fruit tree
    fruit_dists: locations of fallen fruit relative to tree_dist

    output: count of the number of fruits that hit the house
    '''

    count_hits = 0

    for loc in fruit_dists:

        # Check if fallen fruit is within the range of the house location
        if start <= (loc + tree_dist) <= end:
            count_hits += 1

    return count_hits

main()


import re
import json
import csv

class TrainingDataParser:

    def __init__(self, src_path):
        self.src_path = src_path

    def to_dict(self):
        user_posts = {}
        current_id = None
        for line in open(self.src_path):
            if '<user id' in line:
                user_id = re.findall('<user id="(.*?)"', line)[0]
                current_id = user_id
                topic = re.findall('topic="(.*?)"', line)[0]
                gender = re.findall('gender="(.*?)"', line)[0]
                age = re.findall('age="(.*?)"', line)[0]
                if user_id not in user_posts:
                    user_posts[user_id] = {
                        'topic': topic,
                        'gender': gender,
                        'age': age,
                    }
                else:
                    print(f"Duplicate id {user_id}")
            elif '</user>' in line:
                current_id = None
            elif line != '\n' and 'post>' not in line:
                if 'posts' in user_posts[current_id]:
                    user_posts[current_id]['posts'].append(line)
                else:
                    user_posts[current_id]['posts'] = [line]
        return user_posts

    def to_csv(self, file_output=False, output_path='src/data/post_processed', output_name='training.csv'):
        data = self.to_dict()

        rowlist = []
        for user in data:
            for sentence in data[user]['posts']:
                row = [user, data[user]['gender'], data[user]['age'], data[user]['topic'], sentence.strip()]
                rowlist.append(row)

        if file_output:
            file = open(f"{output_path}/{output_name}", "w", encoding="utf-8", newline='')
            writer = csv.writer(file, delimiter=',',
                                lineterminator='\r\n',
                                quoting=csv.QUOTE_NONNUMERIC
                                )
            writer.writerow(['Id', 'Gender', 'Age', 'Topic', 'Sentence'])
            writer.writerows(rowlist)
            file.close()
        return rowlist

    def to_json(self):
        return json.dumps(self.to_dict())


class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        result = []
        added = []
        anagrams = {}

        for x in strs:
            sortedWord = ''.join(sorted(x))
            if sortedWord in anagrams:
                anagrams[sortedWord].append(x)
            else:
                anagrams[sortedWord] = [x]
        return anagrams.values()


#!/usr/bin/env python3
"""Test creation of volumes when containers are being created"""

import random
import unittest
import docker

from control.container import Container
from control.service import create_service

class VolumeCreationTests(unittest.TestCase):
    """
    Double check that volumes are being created correctly. A later class will
    check that they are being removed correctly.
    """

    @classmethod
    def setUpClass(cls):
        cls.dclient = docker.Client('unix://var/run/docker.sock')

    def setUp(self):
        # control.options.debug = True
        self.image = ''
        self.conf = {}
        self.container_volumes = []
        self.container_name = 'unittest_volumecreation_{}'.format(
            random.randint(1, 65535))

    def tearDown(self):
        try:
            self.dclient.remove_container(self.container_name, v=True, force=True)
            for vol in self.container_volumes:
                self.dclient.remove_volume(vol)
        except docker.errors.NotFound:
            pass

    @unittest.expectedFailure
    def test_anon_volumes(self):
        """
        Make sure that anonymous volumes are correctly registered

        Currently unimplemented and will fail
        """
        self.image = 'busybox'
        self.conf = {
            "image": self.image,
            "container": {
                "name": self.container_name,
                "hostname": "busybox",
                "volumes": ["/var"]
            }
        }
        serv = create_service(self.conf, './Controlfile')
        container = Container(serv).create(prod=False)
        container.start()
        self.assertEqual(len(container.inspect['Mounts']), 1)
        self.assertEqual(len(container.inspect['Mounts'][0]['Name']), 65)
        self.assertEqual(container.inspect['Mounts'][0]['Destination'], '/var')
        self.assertTrue(
            container.inspect['Mounts'][0]['Source'].startswith(
                '/var/lib/docker/volumes'),
            msg="Unexpected mount source: {}".format(
                container.inspect['Mount'][0]['Source']))

    def test_named_volumes(self):
        """Make sure that named volumes are correctly registered"""
        volume_name = "control_unittest_volume{}".format(random.randint(1, 65535))
        self.container_volumes.append(volume_name)
        self.image = 'busybox'
        self.conf = {
            "image": self.image,
            "container": {
                "name": self.container_name,
                "hostname": "busybox",
                "volumes": ["{}:/var".format(volume_name)]
            }
        }
        serv = create_service(self.conf, './Controlfile')
        container = Container(serv).create(prod=False)
        container.start()
        self.assertEqual(len(container.inspect['Mounts']), 1)
        self.assertEqual(len(container.inspect['Mounts'][0]['Name']), len(volume_name))
        self.assertEqual(container.inspect['Mounts'][0]['Destination'], '/var')
        self.assertTrue(
            container.inspect['Mounts'][0]['Source'].startswith(
                '/var/lib/docker/volumes'),
            msg="Unexpected mount source: {}".format(
                container.inspect['Mounts'][0]['Source']))

    def test_mounted_volumes(self):
        """Make sure that mounted volumes are correctly registered"""
        import tempfile

        temp_dir = tempfile.TemporaryDirectory()
        self.image = 'busybox'
        self.conf = {
            "image": self.image,
            "container": {
                "name": self.container_name,
                "hostname": "busybox",
                "volumes": ["{}:/var".format(temp_dir.name)]
            }
        }
        serv = create_service(self.conf, './Controlfile')
        container = Container(serv).create(prod=False)
        container.start()
        self.assertEqual(len(container.inspect['Mounts']), 1)
        self.assertEqual(container.inspect['Mounts'][0]['Destination'], '/var')
        self.assertTrue(
            container.inspect['Mounts'][0]['Source'] == temp_dir.name,
            msg="Unexpected mount source: {}".format(
                container.inspect['Mounts'][0]['Source']))
        temp_dir.cleanup()

def setUpModule():
    """Ensure that our test images exist"""
    dclient = docker.Client('unix://var/run/docker.sock')
    dclient.pull('busybox:latest')

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


import RPi.GPIO as GPIO
import time
chan_list = [26, 19, 13, 6, 5, 11, 9, 10, 17]
GPIO.setmode(GPIO.BCM)
GPIO.setup(chan_list, GPIO.OUT)

numbers={7:26, 6:19, 5:13, 4:6, 3:5, 2:11, 1:9, 0:10}
GPIO.output(chan_list,0)

GPIO.cleanup()