# !/usr/bin/python3
# -*- coding: utf-8 -*-

"""
@Author: 闫继龙
@Version: ??
@License: Apache Licence
@CreateTime: 2019/7/20 11:04
@Describe：
    基于多层感知机 两层深度网络实现训练动作分类
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from actionRecognition import input_data
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

# 数据处理
actions_data = input_data.read_data_sets('src/actions_data.npy', test_size=0.1)

'''定义相关参数(超参数)'''
batch_size = 100  # 设置每一轮训练的batch大小
learning_rate = 0.8  # 设置学习率
learning_rate_decay = 0.999  # 学习率的衰减系数,一般设置为非常接近于1的值
max_steps = 30000  # 最大训练步数
training_step = tf.Variable(0, trainable=False)

'''定义全连接的前向网络，定义得到一个隐藏层和输出层的前向传播计算方式，激活函数用relu'''

def hidden_layer(input_tensor, weights1, bias1, weights2, bias2, layer_name):
    layer1 = tf.nn.relu(tf.matmul(input_tensor, weights1) + bias1)
    outLayer = tf.matmul(layer1, weights2) + bias2
    return outLayer

import numpy as np

def next_batch_data(batch_step, batch_size, actions_set):
    actions_data = actions_set['train_data']
    actions_label = actions_set['train_label']

    complex_array = np.concatenate([actions_data, actions_label], axis=1)
    if ((batch_step + 1) * batch_size) < len(actions_data):

        return complex_array[batch_step * batch_size:(batch_step + 1) * batch_size, :-10], \
               complex_array[batch_step * batch_size:(batch_step + 1) * batch_size, -10:]
    else:
        np.random.shuffle(complex_array)
        return complex_array[: batch_size, :-10], complex_array[: batch_size, -10:]

# 开始
x = tf.compat.v1.placeholder(tf.float32, [None, 1890], name='x-input')  # 输入数据
y_ = tf.compat.v1.placeholder(tf.float32, [None, 10], name='y-output')  # 标签

# 生成隐藏层参数，隐藏层有1890个神经单元，其中weights包含1890*500个参数
weights1 = tf.Variable(tf.random.truncated_normal([1890, 500], stddev=0.1))
bias1 = tf.Variable(tf.constant(0.1, shape=[500]))
# 生成输出层参数，输出层10个神经元，weights2包含500*10 = 5000个参数
weights2 = tf.Variable(tf.random.truncated_normal([500, 10], stddev=0.1))
bias2 = tf.Variable(tf.constant(0.1, shape=[10]))

# 开始计算经过神经网络前向传播后得到的y值
y = hidden_layer(x, weights1, bias1, weights2, bias2, 'y')

'''为了提高采用随机梯度下降算法的训练神经网络得到的模型在测试集上的表现，
    使用“滑动平均模型”应用到隐藏层与输出层的权重参数与偏置参数
    使用“滑动平均模型”计算影子变量
'''
# 初始化一个"滑动平均类"，衰减率为0.99
# 为了使这个训练前期可以更新得更快，这里提供了num_updates参数，并设置为当前网络的训练轮数
averages_class = tf.train.ExponentialMovingAverage(decay=0.99, num_updates=training_step)
# 定义一个更新变量滑动平均值的操作，需要向滑动平均类的apply()函数提供一个参数列表
# train_variables() 函数返回集合图上 Graph.TRAINABLE_VARIABLES中的元素，这个集合的元素就是所有没有指定trainable=false的元素
averages_op = averages_class.apply(tf.compat.v1.trainable_variables())  # 应用到集合图上所有权重参数和偏置参数，随着每次迭代动态改变参数值

# 再次计算经过神经网络前向传播后得到的y的值，这里使用了滑动平均，但要牢记滑动平均值只是一个影子变量
average_y = hidden_layer(x, weights1, bias1, weights2, bias2, 'average_y')

'''开始计算交叉熵损失函数'''
# 计算交叉熵函数J（w），logits是前向传播的结果，axis=1 按行获取最大值的下标，即对应识别的结果
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, axis=1))
# 正则化 λR(w)
regularizer = tf.contrib.layers.l2_regularizer(0.0001)
regularization = regularizer(weights1) + regularizer(weights2)
# 总的损失函数= J（w）+ λR(w)
loss = tf.reduce_mean(cross_entropy) + regularization

''' 使用随机梯度下降SGD优化器，学习率采用指数衰减的方式
    learning_rate: 学习率 0.8
    global_step：当前训练次数
    decay_steps：衰减速度
    decay_rate：衰减系数，小于1的较大数 0.99
'''
# 设置指数衰减法来设置学习率，staircase=false,即学习率连续衰减
learning_rate = tf.compat.v1.train.exponential_decay(learning_rate=learning_rate, global_step=training_step,
                                                     decay_steps=100, decay_rate=learning_rate_decay, staircase=True)
train_op_step = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss=loss,
                                                                                global_step=training_step)

'''
    在训练这个模型时，每过一遍数据，既要通过反向传播来更新神经网络中的参数，又需要更新每一个参数的滑动平均值
    control_dependencies()用于完成这样的一次性的多次操作
    # 下面两行代码，可以用一行代码替换
    # train_op = tf.group(train_op_step,averages_op)
'''
with tf.control_dependencies([train_op_step, averages_op]):
    train_op = tf.no_op(name='train')  # 什么都不做，仅做为点位符使用控制边界。

'''检查使用了滑动平均值模型的神经网络前向传播是否正确，平均值就是模型在这一组数据上的正确率，求准确率'''
current_prediction = tf.equal(tf.argmax(average_y, axis=1), tf.argmax(y_, axis=1))
accuracy = tf.reduce_mean(tf.cast(current_prediction, tf.float32))  # tf.cast()这里将布尔类型变为float32类型的数据

''' 构建会话 '''
init_op = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
    sess.run(init_op)

    # 准备验证数据
    validate_feed = {x: actions_data['validation_data'], y_: actions_data['validation_label']}
    # 准备测试数据
    test_feed = {x: actions_data['test_data'], y_: actions_data['test_label']}

    for i in range(max_steps):
        # 每训练1000次计算滑动模型在验证数据集上的结果
        if i % 1000 == 0:
            validate_accuracy = sess.run(accuracy, feed_dict=validate_feed)
            print('After % d training step(s),validation accuracy using average model is %g%%' % (
                i, validate_accuracy * 100))

        # 产生这一轮的batch训练数据，并进行训练
        xs, ys = next_batch_data(batch_step=i, batch_size=batch_size, actions_set=actions_data)
        sess.run(train_op, feed_dict={x: xs, y_: ys})

    # 得到正确率
    test_accuracy = sess.run(accuracy, feed_dict=test_feed)
    print("After %d training step(s)，test accuracy using average model is %g%%" % (max_steps, test_accuracy * 100))


import numpy as np
import matplotlib.pyplot as plt
from multiagent.core import World, Agent, Landmark, GravityWorld, Planet, Spaceship
from multiagent.scenario import BaseScenario

class Scenario(BaseScenario):
    colors = plt.cm.rainbow(np.linspace(0,1,20))

    def make_world(self):
        world = GravityWorld()
        # add agents
        world.agents = [Spaceship() for i in range(1)]
        for i, agent in enumerate(world.agents):
            agent.name = 'agent %d' % i
            agent.collide = True
            agent.silent = True
        # add landmarks
        world.landmarks = [Landmark() for i in range(1)]
        for i, landmark in enumerate(world.landmarks):
            landmark.name = 'landmark %d' % i
            landmark.collide = False
            landmark.movable = False
        # # add obstacles
        obstacles = [Planet() for i in range(2)]
        for i, obstacle in enumerate(obstacles):
            obstacle.name = 'obstacle %d' % i
            obstacle.collide = True
            obstacle.movable = False
        world.landmarks.extend(obstacles)

        # make initial conditions
        self.reset_world(world)
        return world

    def reset_world(self, world):
        # random properties for agents
        for i, agent in enumerate(world.agents):
            agent.color = np.array([1.0, 1.0, 1.0])
        # random properties for landmarks
        for i, landmark in enumerate(world.landmarks):
            landmark.color = self.colors[np.random.randint(len(self.colors))][:-1]
        world.landmarks[0].color = self.colors[np.random.randint(len(self.colors))][:-1]

        # set random initial states
        for agent in world.agents:
            agent.state.p_pos = np.random.uniform(-0.75,+0.75, world.dim_p)
            agent.state.p_vel = np.zeros(world.dim_p)
            agent.state.c = np.zeros(world.dim_c)
        for i, landmark in enumerate(world.landmarks):
            landmark.state.p_pos = np.random.uniform(-0.75,+0.75, world.dim_p)
            landmark.state.p_vel = np.zeros(world.dim_p)

    def reward(self, agent, world):
        dist2 = np.sum(np.square(agent.state.p_pos - world.landmarks[0].state.p_pos))
        return -dist2

    def observation(self, agent, world):
        # get positions of all entities in this agent's reference frame
        entity_pos = []
        for entity in world.landmarks:
            entity_pos.append(entity.state.p_pos - agent.state.p_pos)
        return np.concatenate([agent.state.p_vel] + entity_pos)


#!/usr/bin/env python3
import pygame
import pygame.camera
import time
import os
import PIL.Image
import cups
import RPi.GPIO as GPIO
import subprocess

from shutil import copyfile
from threading import Thread
from pygame.locals import *
from time import sleep
from PIL import Image, ImageDraw
from subprocess import *

# initialise global variables
Numeral = ""  # Numeral is the number display
Message = ""  # Message is a fullscreen message
SubMessage = ""
LongMessage = ""
BackgroundColor = ""
CountDownPhoto = ""
CountPhotoOnCart = ""
SmallMessage = ""  # SmallMessage is a lower banner message
TotalImageCount = 0  # Counter for Display and to monitor paper usage
PhotosPerCart = 30  # Selphy takes 16 sheets per tray
imagecounter = 0
imagefolder = 'Photos'
backupfolder = '/media/pi/90B6-124C/trouw'
templatePath = os.path.join('Photos', 'Template', "template.png") #Path of template image
ImageShowed = False
Printing = False
BUTTON_PIN = 25
IMAGE_WIDTH = 594
IMAGE_HEIGHT = 445
image_size = (IMAGE_WIDTH, IMAGE_HEIGHT)
os.environ["SDL_AUDIODRIVER"] = "dsp"

# Load the background template
bgimage = PIL.Image.open(templatePath)

#Setup GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# initialise pygame
pygame.init()  # Initialise pygame
pygame.font.init()
pygame.camera.init()
pygame.mouse.set_visible(False)
# pygame.mouse.set_visible(False) #hide the mouse cursor
infoObject = pygame.display.Info()
screen_size = (infoObject.current_w,infoObject.current_h)
screen = pygame.display.set_mode(screen_size, pygame.FULLSCREEN)  # Full screen  , pygame.FULLSCREEN
background = pygame.Surface(screen_size)  # Create the background object
background = background.convert()  # Convert it to a background

screenPicture = pygame.display.set_mode(screen_size, pygame.FULLSCREEN)  # Full screen
backgroundPicture = pygame.Surface(screen_size)  # Create the background object
backgroundPicture = background.convert()  # Convert it to a background

transform_x = infoObject.current_w # how wide to scale the jpg when replaying
transfrom_y = infoObject.current_h # how high to scale the jpg when replaying

# Initialise the camera object
# camera.resolution = (infoObject.current_w, infoObject.current_h)
camera_resolution = (IMAGE_WIDTH, IMAGE_HEIGHT)
#(infoObject.current_w, infoObject.current_h)
camera_devices = pygame.camera.list_cameras()
camera = pygame.camera.Camera(camera_devices[0],camera_resolution)
# camera.set_controls(True, False, 50)

# A function to handle keyboard/mouse/device input events
def input(events):
    for event in events:  # Hit the ESC key to quit the slideshow.
        if (event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE)):
            pygame.quit()

# set variables to properly display the image on screen at right ratio
def set_demensions(img_w, img_h):
    # Note this only works when in booting in desktop mode.
    # When running in terminal, the size is not correct (it displays small). Why?

    # connect to global vars
    global transform_y, transform_x, offset_y, offset_x

    # based on output screen resolution, calculate how to display
    ratio_h = (infoObject.current_w * img_h) / img_w

    if (ratio_h < infoObject.current_h):
        #Use horizontal black bars
        #print "horizontal black bars"
        transform_y = ratio_h
        transform_x = infoObject.current_w
        offset_y = (infoObject.current_h - ratio_h) / 2
        offset_x = 0
    elif (ratio_h > infoObject.current_h):
        #Use vertical black bars
        #print "vertical black bars"
        transform_x = (infoObject.current_h * img_w) / img_h
        transform_y = infoObject.current_h
        offset_x = (infoObject.current_w - transform_x) / 2
        offset_y = 0
    else:
        #No need for black bars as photo ratio equals screen ratio
        #print "no black bars"
        transform_x = infoObject.current_w
        transform_y = infoObject.current_h
        offset_y = offset_x = 0

def InitFolder():
    global imagefolder
    global Message
    global LongMessage
    global SubMessage

    Message = 'Folder Check...'
    UpdateDisplay()
    Message = ''

    #check image folder existing, create if not exists
    if not os.path.isdir(imagefolder):
        os.makedirs(imagefolder)

    imagefolder2 = os.path.join(imagefolder, 'images')
    if not os.path.isdir(imagefolder2):
        os.makedirs(imagefolder2)

def DisplayText(fontSize, textToDisplay):
    global Numeral
    global Message
    global LongMessage
    global SubMessage
    global screen
    global background
    global pygame
    global ImageShowed
    global screenPicture
    global backgroundPicture
    global CountDownPhoto

    if (BackgroundColor != ""):
        background.fill(pygame.Color("black"))
    if (textToDisplay != ""):
        font = pygame.font.Font(None, fontSize)
        text = font.render(textToDisplay, 1, (227, 157, 200))
        textpos = text.get_rect()
        textpos.centerx = background.get_rect().centerx
        textpos.centery = background.get_rect().centery
        if(ImageShowed):
            backgroundPicture.blit(text, textpos)
        else:
            background.blit(text, textpos)

def UpdateDisplay():
    # init global variables from main thread
    global Numeral
    global Message
    global SubMessage
    global LongMessage
    global screen
    global background
    global pygame
    global ImageShowed
    global screenPicture
    global backgroundPicture
    global CountDownPhoto

    background.fill(pygame.Color("white"))  # White background

    if (BackgroundColor != ""):
        background.fill(pygame.Color("black"))

    if (Message != ""):
        font = pygame.font.SysFont("Brandon Grotesque Bold", 100)
        text = font.render(Message, True, (0, 0, 0))
        textpos = text.get_rect()
        textpos.centerx = background.get_rect().centerx
        textpos.centery = background.get_rect().centery
        if(ImageShowed):
            backgroundPicture.blit(text, textpos)
        else:
            background.blit(text, textpos)

    if(LongMessage != ""):
        font = pygame.font.SysFont("Brandon Grotesque Bold", 80)
        text = font.render(LongMessage, True, (0, 0, 0))
        textpos = text.get_rect()
        textpos.centerx = background.get_rect().centerx
        textpos.centery = background.get_rect().centery - 40
        if(ImageShowed):
            backgroundPicture.blit(text, textpos)
        else:
            background.blit(text, textpos)
        font = pygame.font.SysFont("Brandon Grotesque Bold", 100)
        text = font.render(SubMessage, True, (0, 0, 0))
        textpos = text.get_rect()
        textpos.centerx = background.get_rect().centerx
        textpos.centery = background.get_rect().centery + 40
        if(ImageShowed):
            backgroundPicture.blit(text, textpos)
        else:
            background.blit(text, textpos)

    if (Numeral != ""):
        font = pygame.font.SysFont("Brandon Grotesque Bold", 200)
        text = font.render(Numeral, True, (255, 255, 255))
        textpos = text.get_rect()
        textpos.centerx = background.get_rect().centerx
        textpos.centery = background.get_rect().centery
        if(ImageShowed):
            backgroundPicture.blit(text, textpos)
        else:
            background.blit(text, textpos)

    if (CountDownPhoto != ""):
        #print(displaytext)
        font = pygame.font.SysFont("Brandon Grotesque Bold", 200)
        text = font.render(CountDownPhoto, True, (0, 0, 0))
        textpos = text.get_rect()
        textpos.centerx = background.get_rect().centerx
        textpos.centery = background.get_rect().centery
        if(ImageShowed):
            backgroundPicture.blit(text, textpos)
        else:
            background.blit(text, textpos)

    if(ImageShowed == True):
        screenPicture.blit(backgroundPicture, (0, 0))
    else:
        screen.blit(background, (0, 0))

    pygame.display.flip()
    return

def ShowPicture(file, delay):
    global pygame
    global screenPicture
    global backgroundPicture
    global ImageShowed
    backgroundPicture.fill((0, 0, 0))
    img = pygame.image.load(file)
    img = pygame.transform.scale(img, (1020,780))  # Make the image full screen
    #backgroundPicture.set_alpha(200)
    backgroundPicture.blit(img, (120,0))
    screen.blit(backgroundPicture, (0, 0))
    pygame.display.flip()  # update the display
    ImageShowed = True
    time.sleep(delay)

def ShowResult(file, delay):
    global pygame
    global screenPicture
    global backgroundPicture
    global ImageShowed
    backgroundPicture.fill((255, 255, 255))
    img = pygame.image.load(file)
    img = pygame.transform.scale(img, (320,720))  # Make the image fit screen
    #backgroundPicture.set_alpha(200)
    backgroundPicture.blit(img, (480,0))
    screen.blit(backgroundPicture, (0, 0))
    pygame.display.flip()  # update the display
    ImageShowed = True
    time.sleep(delay)

# display one image on screen
def show_image(image_path):
    screen.fill(pygame.Color("white")) # clear the screen
    img = pygame.image.load(image_path) # load the image
    img = img.convert()
    set_demensions(img.get_width(), img.get_height()) # set pixel dimensions based on image
    x = (infoObject.current_w / 2) - (img.get_width() / 2)
    y = (infoObject.current_h / 2) - (img.get_height() / 2)
    screen.blit(img,(x,y))
    pygame.display.flip()

def CapturePicture():
    global imagecounter
    global imagefolder
    global Numeral
    global Message
    global LongMessage
    global SubMessage
    global screen
    global background
    global screenPicture
    global backgroundPicture
    global pygame
    global ImageShowed
    global CountDownPhoto
    global BackgroundColor

    image = None

    BackgroundColor = ""
    Numeral = ""
    Message = ""
    UpdateDisplay()
    time.sleep(1)
    CountDownPhoto = ""
    UpdateDisplay()
    background.fill(pygame.Color("black"))
    screen.blit(background, (0, 0))
    pygame.display.flip()
    BackgroundColor = "black"

    streaming = True
    countdown = 0
    x = 3
    Numeral = str(x)
    Message = ""

    while streaming:
        if image:
            if camera.query_image():
                image = camera.get_image(image)
        else:
            image = camera.get_image()

        image = pygame.transform.flip(image, True, False)
        image2 = pygame.transform.scale(image, screen_size)
        background.blit(image2, (0, 0))
        font = pygame.font.SysFont("Brandon Grotesque Bold", 200)
        text = font.render(str(x), True, (255, 255, 255))
        textpos = text.get_rect()
        textpos.centerx = background.get_rect().centerx
        textpos.centery = background.get_rect().centery
        background.blit(text, textpos)
        screen.blit(background, (0,0))
        pygame.display.flip()  # update the display
        countdown = countdown + 1
        if countdown == 10:
            x = x - 1
            if x == 0:
                streaming = False
            else:
                countdown = 0
    BackgroundColor = ""
    Numeral = ""
    LongMessage = ""
    Message = ""
    UpdateDisplay()
    photo_ready = camera.query_image()
    time.sleep(0.5)
    while not photo_ready:
        photo_ready = camera.query_image()
    image = camera.get_image(image)
    image = pygame.transform.flip(image, True, False)
    image2 = pygame.transform.scale(image,screen_size)
    image = pygame.transform.scale(image,camera_resolution)
    background.blit(image2, (0, 0))
    screen.blit(background, (0,0))
    imagecounter = imagecounter + 1
    ts = time.time()
    filename = os.path.join(imagefolder, 'images', str(imagecounter)+"_"+str(ts) + '.png')
    pygame.image.save(image, filename)
    #time.sleep(1)
    ShowPicture(filename, 1)
    ImageShowed = False
    return filename

def TakePictures():
    global imagecounter
    global imagefolder
    global backupfolder
    global Numeral
    global Message
    global LongMessage
    global SubMessage
    global screen
    global background
    global pygame
    global ImageShowed
    global CountDownPhoto
    global BackgroundColor
    global Printing
    global PhotosPerCart
    global TotalImageCount

    LongMessage = ""

    input(pygame.event.get())

    camera.start()

    CountDownPhoto = "Foto 1/3"
    filename1 = CapturePicture()

    CountDownPhoto = "Foto 2/3"
    filename2 = CapturePicture()

    CountDownPhoto = "Foto 3/3"
    filename3 = CapturePicture()

    camera.stop()

    CountDownPhoto = ""
    Message = "Even geduld..."
    UpdateDisplay()

    image1 = PIL.Image.open(filename1)
    image2 = PIL.Image.open(filename2)
    image3 = PIL.Image.open(filename3)
    TotalImageCount = TotalImageCount + 1

    bgimage.paste(image1, (57, 194))
    bgimage.paste(image2, (57, 664))
    bgimage.paste(image3, (57, 1137))

    # Create the final filename
    ts = time.time()
    Final_Image_Name = os.path.join(imagefolder, "Final_" + str(TotalImageCount)+"_"+str(ts) + ".png")
    Backup_Image_Name = os.path.join(backupfolder, "Final_" + str(TotalImageCount)+"_"+str(ts) + ".png")
    # Save it to the raspberry SD card and backup to usb drive
    bgimage.save(Final_Image_Name)
    try:
        copyfile(Final_Image_Name, Backup_Image_Name)
    except Exception as filex:
        print("USB not found")
    # Save a temp file, its faster to print from the pi than usb
    temppath = os.path.join('Temp', 'tempprint.png')
    bgimage.save(temppath)
    ShowResult(temppath,3)
    #bgimage2 = bgimage.rotate(90)
    #bgimage2.save(temppath)
    ImageShowed = False
    Message = ""
    Printing = False
    WaitForPrintingEvent()
    Numeral = ""
    Message = ""
    SubMessage = ""
    LongMessage = ""
    if Printing:
        if os.path.isfile(temppath):
            # Open a connection to cups
            conn = cups.Connection()
            # get a list of printers
            # printers = conn.getPrinters()
            # select printer 0
            printer_name = "Canon_MP250_series"
            Message = "Aan het printen..."
            UpdateDisplay()
            time.sleep(1)
            # print the buffer file
            printqueuelength = len(conn.getJobs())
            if printqueuelength > 1:
                ShowPicture(temppath,3)
                conn.enablePrinter(printer_name)
                Message = "Probleem met de printer... :("
                UpdateDisplay()
                time.sleep(1)
            else:
                conn.printFile(printer_name, temppath, "PhotoBooth", {})
                time.sleep(40)
    Message = ""
    Numeral = ""
    ImageShowed = False
    UpdateDisplay()
    os.remove(filename1)
    os.remove(filename2)
    os.remove(filename3)

def MyCallback(channel):
    global Printing
    GPIO.remove_event_detect(BUTTON_PIN)
    pygame.event.clear()
    Printing=True

def WaitForPrintingEvent():
    global BackgroundColor
    global Numeral
    global Message
    global LongMessage
    global SubMessage
    global Printing
    global pygame
    countDown = 5
    GPIO.add_event_detect(BUTTON_PIN, GPIO.RISING)
    GPIO.add_event_callback(BUTTON_PIN, MyCallback)

    while Printing == False and countDown > 0:
        if(Printing == True):
            return
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_DOWN:
                    GPIO.remove_event_detect(BUTTON_PIN)
                    Printing = True
                    return
        BackgroundColor = ""
        Numeral = ""
        SubMessage = str(countDown)
        LongMessage = "Druk op de knop om je foto af te drukken"
        UpdateDisplay()
        countDown = countDown - 1
        time.sleep(1)

    GPIO.remove_event_detect(BUTTON_PIN)
    pygame.event.clear()

def uploadToGP(filename):
    p = Popen(['/usr/bin/share/gpup','-a "trouw"', filename], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)

def WaitForEvent():
    global pygame
    NotEvent = True
    while NotEvent:
            input_state = GPIO.input(BUTTON_PIN)
            if input_state == False:
                    NotEvent = False
                    return

            try:
                for event in pygame.event.get():
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_ESCAPE:
                            pygame.quit()
                        if event.key == pygame.K_DOWN:
                            NotEvent = False
                            return
                    if event.type == QUIT:
                        pygame.quit()
            except:
                pygame.quit()

            time.sleep(0.2)
    pygame.event.clear()

def main(threadName, *args):
    InitFolder()

    try:
        while True:
            show_image('images/start_camera.jpg')
            WaitForEvent()
            time.sleep(0.2)
            TakePictures()
    except Exception as e:
        print(e)
        GPIO.cleanup()
        pygame.quit()

# launch the main thread
Thread(target=main, args=('Main', 1)).start()


import matplotlib.pyplot as plt
import networkx as nx

#### Adding nodes
g = nx.Graph ()
g.add_node(1)
g.add_nodes_from ( ['b','c','d'])
g.add_nodes_from ('xyz')

#### Adding edges

g = nx. Graph( [('a','b') ,('b','c') ,('c','a')] )
g.add_edge('a', 'd')
g.add_edges_from([( 'd', 'c'), ('d', 'b')])

#### Add node attributes
g = nx.Graph()
g.add_node (1, name ='Obrian')
g.add_nodes_from([2], name ='Quintana')
g.node[1]['name']
g.node[1] # Python dictionary

#### Add edge attributes
g.add_edge(1, 2, weight=4.0 )
g[1][2]['weight'] = 5.0  # edge already added
g[1][2]
g.add_edges_from([(3 ,4) ,(4 ,5)], w =3.0)
g.add_weighted_edges_from([(6 ,7 ,3.0)]) # adds third value in tuple as ‘weight ’ attr
g[6][7]
g.add_edge(5 ,6)
g[5][6]

#### Number of nodes
g = nx.Graph()
g.add_edges_from([(1 ,2) ,(1 ,3)])
g.add_node('a')
len(g)
g. number_of_nodes()
g. order ()

#### Number of edges
g.number_of_edges()

g.nodes()
g.edges()

#  access the adjacency dictionary as G[n]:
g[1]
g.degree(1)

## node and edge iterators
g = nx.Graph()
g.add_edges_from([(1 ,2) ,(1 ,3)])
g.add_node('a')

for node in g.nodes():
    print(node, g.degree(node))

## edge iterators
g.add_edge(1,3,weight=2.5)
g[1][2]['weight'] = 1.5
for n1,n2,attr in g.edges(data=True):
    print(n1,n2,attr['weight'])

## Deal with weighted graphs
dg = nx.DiGraph()
dg.add_weighted_edges_from([(1,4,0.5), (3,1,0.75)])
dg.out_degree(1,weight='weight')
dg.degree(1,weight='weight')
dg.successors(1)
dg.predecessors(1)

## Deal with multigraphs
MG = nx.MultiGraph()
MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)])
dict(MG.degree(weight='weight'))
## To calcuate the shortest path, we have to convert it to a standard graph
GG = nx.Graph()
for n, nbrs in MG.adjacency():
    for nbr, edict in nbrs.items():
        minvalue = min([d['weight'] for d in edict.values()])
        GG.add_edge(n, nbr, weight = minvalue)
nx.shortest_path(GG, 1, 3)

## Generating graphs
Gc = nx.complete_graph(5)
nx.draw(Gc)

# Chain (path) graph
Gp = nx.path_graph(5)
nx.draw(Gp)

# Grid graph
Gg = nx.grid_graph ([4 ,4 ,4]) # 3D, 4^3 nodes
nx.draw(Gg)

# Erdos-Reny random graphs
n = 50
p = 0.1
Gr = nx.erdos_renyi_graph(n,p)
nx.draw(Gr)

# Preferential Attachment networks
n = 50
m = 4
Gpa = nx.barabasi_albert_graph(n, m)
nx.draw(Gpa)

# Small world networks
n = 50
k = 6
p = 0.3
Gsw = nx.watts_strogatz_graph(n, k, p)
nx.draw(Gsw)

### Graph operations
# Induced subgraph view of G on nodes in nbunch
G = nx.path_graph(4)
nx.draw(G)
H = G.subgraph([0, 1, 2])
nx.draw(H)

# Graph union
G1 = nx.path_graph(4)
G2 = nx.complete_graph(5)
U = nx.disjoint_union(G1,G2)
nx.draw(U)

# Return Cartesian product graph
CP = nx.cartesian_product(G1,G2)
nx.draw(CP)

# Combine graphs identifying nodes common to both
G1 = nx.Graph()
G1.add_edges_from([(1 ,2) ,(1 ,3)])
G2 = nx.Graph()
G2.add_edges_from([(3 ,4) ,(4,5)])
CO = nx.compose(G1,G2)
nx.draw(CO)

# graph complement
Gc = nx.complete_graph(5)
nx.draw(Gc)
ebunch=[(1, 2), (2, 3)]
Gc.remove_edges_from(ebunch)
nx.draw(Gc)
GP = nx.complement(Gc)
nx.draw(GP)

#### Python dictionaries
# Keys and values can be of any data type
fruit_dict={"apple":1,"orange":[0.23,0.11],42:True}
# Can retrieve the keys and values as Python lists (vector)
fruit_dict.keys()
fruit_dict.values()
# Or return tuples of (key,value)
fruit_dict.items()

# To iterate:
for k, v in fruit_dict.items():
    print(k, v)

#### Drawing networks
G_florentine = nx.florentine_families_graph()
nx.draw(G_florentine, with_labels=True)

# We can use graph layouts to set node positions for graph drawing.
pos = nx.spring_layout(G_florentine)
nx.draw(G_florentine, pos, with_labels=True)

pos = nx.circular_layout(G_florentine)
nx.draw(G_florentine, pos, with_labels=True)

## Advanced graph drawing samples
G = nx.random_geometric_graph(200, 0.125)
# position is stored as node attribute data for random_geometric_graph
pos = nx.get_node_attributes(G, 'pos')

# find node near center (0.5,0.5)
dmin = 1
ncenter = 0
for n in pos:
    x, y = pos[n]
    d = (x - 0.5)**2 + (y - 0.5)**2
    if d < dmin:
        ncenter = n
        dmin = d

# color by path length from node near center
p = dict(nx.single_source_shortest_path_length(G, ncenter))

plt.figure(figsize=(8, 8))
nx.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4)
nx.draw_networkx_nodes(G, pos, nodelist=list(p.keys()),
                       node_size=80,
                       node_color=list(p.values()),
                       cmap=plt.cm.Reds_r)

plt.xlim(-0.05, 1.05)
plt.ylim(-0.05, 1.05)
plt.axis('off')
plt.show()


import requests
import json

searcher = {"consumer_key":"CONSUMER KEY", "access_token":"ACCESS TOKEN", "count" : "1000", "domain":"DOMAIN NAME"}

r = requests.post("https://getpocket.com/v3/get", data = searcher)

r_dict = json.loads(r.text)

# look up individual article ids

items = r_dict['list']

item_list = []

# create a list of article ids to iterate through

for k, v in items.items():
    item_list.append(k)

# delete all the articles corresponding to the articles in the list

for item in item_list:
    r2 = requests.post('https://getpocket.com/v3/send', data = {
            'consumer_key': 'CONSUMER KEY',
            'access_token': 'ACCESS TOKEN',
            'actions': json.dumps([{
                'item_id': '{}'.format(item),
                'action':'archive'
             }])
        })


def inserthelp(rt, k, e):
    if rt is None:  # Empty tree: create a leaf node for root
        return TTNode(k, e, None, None, None, None, None)
    elif rt.isLeaf():  # At leaf node: insert here
        return rt.add(TTNode(k, e, None, None, None, None, None))
    elif k < rt.lkey():  # Insert left
        retval = inserthelp(rt.lchild(), k, e)
        if retval == rt.lchild():
            return rt
        else:
            return rt.add(retval)
    elif rt.rkey() is None and k < rt.rkey():
        retval = inserthelp(rt.cchild(), k, e)
        if retval == rt.cchild():
            return rt
        else:
            return rt.add(retval)
    else: # Insert right
        retval = inserthelp(rt.rchild(), k, e)
        if retval == rt.rchild():
            return rt
        else:
            return rt.add(retval)

# Add a new key/value pair to the node. There might be a subtree
# associated with the record being added. This information comes
# in the form of a 2-3 tree node with one key and a (possibly null)
# subtree through the center pointer field.
def add(it):
    if rkey is None:  # Only one key, add here
        if lkey < it.lkey():
            rkey = it.lkey()
            rval = it.lval()
            center = it.lchild()
            right = it.cchild()
        else:
            rkey = lkey
            rval = lval
            right = center
            lkey = it.lkey()
            lval = it.lval()
            center = it.cchild()
        return self
    elif lkey >= it.lkey():  # Add left
        N1 = TTNode(lkey, lval, None, None, it, self, None)
        it.setLeftChild(left)
        left = center
        center = right
        right = None
        lkey = rkey
        lval = rval
        rkey = None
        rval = None
        return N1
    elif rkey >= it.lkey():  # Add center
        it.setCenterChild(TTNode(rkey, rval, None, None, it.cchild(), right, None))
        it.setLeftChild(self)
        rkey = rval = right = None
        return it
    else:  # Add right
        N1 = TTNode(rkey, rval, None, None, self, it, None)
        it.setLeftChild(right)
        right = rkey = rval = None
        return N1


import logging
import os
import random
import secrets
import subprocess
import sys
import time

import kubernetes
from celery.exceptions import Ignore, SoftTimeLimitExceeded

from config import get_snapshot_dir, get_working_dir
from jobs.base.job import Job

# Kubernetes namespace to put job pods in
namespace = "jobs"

logger = logging.getLogger(__name__)

api_client = None
if "KUBERNETES_SERVICE_HOST" in os.environ:
    # Running in a pod on the cluster so load the cluster's config
    kubernetes.config.load_incluster_config()
    api_instance = kubernetes.client.CoreV1Api()
else:
    # Running outside of a cluster, probably during development
    if __name__ == "__main__":
        # Explicitly running this script so connect to active cluster
        api_client = kubernetes.config.new_client_from_config()
        api_instance = kubernetes.client.CoreV1Api(api_client)
    else:
        # Otherwise only connect to a Minikube cluster to avoid polluting
        # a production cluster accidentally.
        # Do not raise an exception so that devs without Minikube
        # installed can at least import this file. Just warn.
        api_instance = None
        try:
            status = subprocess.run(["minikube", "status"])
            if status.returncode == 0:
                try:
                    api_client = kubernetes.config.new_client_from_config(
                        context="minikube"
                    )
                    api_instance = kubernetes.client.CoreV1Api(api_client)

                    try:
                        # Create the job namespace. In production, this namespace
                        # needs to be created manually.
                        api_instance.create_namespace(
                            body={
                                "apiVersion": "v1",
                                "kind": "Namespace",
                                "metadata": {"name": namespace},
                            }
                        )
                    except kubernetes.client.rest.ApiException:
                        # Assume that exception was because namespace already exists
                        pass
                except kubernetes.config.config_exception.ConfigException as exc:
                    logger.warning(exc)
            else:
                logger.warning(
                    "Minikube does not appear to be running. Run: minikube start"
                )
        except FileNotFoundError:
            logger.warning("Could not find Minikube. Is it installed?")

class KubernetesSession(Job):
    """
    Runs a session as a pod in a Kubernetes cluster.

    This class in intended for scalably provisioning untrusted sessions.
    It uses the K8s API to create a new pod inside a cluster, usually but
    not necessarily, the same cluster this process is in.
    """

    def do(self, *args, **kwargs):
        """
        Start the session.

        Override of `Job.do` which updates the job state with the
        URL of the session before starting the session.
        """
        # Get session parameters, falling back to defaults either set
        # as environment variables or the values hard coded below.

        # Project to start session for
        project = kwargs.get("project")
        assert project is not None, "A project id is required to start a session"

        # Snapshot to start session for (if any)
        snapshot = kwargs.get("snapshot")
        snapshot_url = kwargs.get("snapshot_url")
        assert not (
            snapshot and not snapshot_url
        ), "A snapshot_url is required for snapshots"

        # Key to control access to the session
        key = kwargs.get("key")
        assert key is not None, "A job key is required for a session"

        # Container image to use
        container_image = kwargs.get("container_image") or os.getenv(
            "SESSION_CONTAINER_IMAGE", "stencila/executa-midi"
        )

        # Session timeout and timelimit defaults
        timeout = kwargs.get("timeout") or os.getenv(
            "SESSION_TIMEOUT_DEFAULT", 600  # 10 minutes
        )
        timelimit = kwargs.get("timelimit") or os.getenv(
            "SESSION_TIMELIMIT_DEFAULT", 3600  # 1 hour
        )

        # Node pool
        node_pool = kwargs.get("node_pool") or os.getenv(
            "SESSION_NODE_POOL_DEFAULT", "sessions"
        )

        # Session CPU and memory requests and limits
        cpu_request = kwargs.get("cpu_request") or os.getenv(
            "SESSION_CPU_REQUEST_DEFAULT", 0.1  # 10% of a vCPU / core
        )
        cpu_limit = kwargs.get("cpu_limit") or os.getenv(
            "SESSION_CPU_LIMIT_DEFAULT", 1  # 100% of a vCPU / core
        )
        mem_request = kwargs.get("mem_request") or os.getenv(
            "SESSION_MEM_REQUEST_DEFAULT", 600  # 600MiB
        )
        mem_limit = kwargs.get("mem_limit") or os.getenv(
            "SESSION_MEM_LIMIT_DEFAULT", 600  # 600MiB
        )

        # Network policy applied to sessions
        network_policy = kwargs.get("network_policy") or os.getenv(
            "SESSION_NETWORK_POLICY_DEFAULT", "jobs-network-policy-1"
        )

        # Update the job with a custom state to indicate
        # that we are waiting for the pod to start.
        self.notify(state="LAUNCHING")

        # Create a session name which we can use to terminate the pod
        # (use `pod_name` to avoid clash with `Job.name`)
        self.pod_name = "session-" + (self.task_id or secrets.token_hex(16))

        # Add pod name to logger's extra contextual info
        self.logger = logging.LoggerAdapter(logger, {"pod_name": self.pod_name})

        # Protocols and ports that the session will listen on.
        # Note that random is about the best we can do (we do not
        # know which ports are already in use because we do not
        # know which machine this pod will be assigned to).
        # There is a small probability of clashes.
        ports = {
            "ws": random.randint(10000, 65535),
            "http": random.randint(10000, 65535),
        }

        # Construct the command to run in the session container
        executa_args = (
            f"--key={key} --timeout={timeout} --timelimit={timelimit} "
            + " ".join(
                f"--{protocol}=0.0.0.0:{port}" for protocol, port in ports.items()
            )
        )
        command = [
            "/bin/bash",
            "-c",
            "--",
            f"""
            touch /semaphores/started
            executa serve {executa_args}
            touch /semaphores/finished
            """,
        ]

        if snapshot:
            init_containers = [
                # Container to ensure that the snapshot is on the host
                {
                    "name": "init",
                    "image": "stencila/hub-groundsman",
                    "imagePullPolicy": "IfNotPresent",
                    "command": ["sh"],
                    "args": ["groundsman.sh", snapshot, snapshot_url],
                    "volumeMounts": [{"name": "snapshots", "mountPath": "/snapshots"}],
                }
            ]

            sidecar_containers = [
                # Container which provides readonly access to the snapshot directory while
                # still allowing the session to write temporary files to it.
                # This is done in a separate sidecar container to avoid having the session
                # container be privileged.
                # It can not be in an initContainer because it must be `umount` needs
                # to be called in preStop phase.
                {
                    "name": "sidecar",
                    "image": "ubuntu:20.04",
                    "securityContext": {"privileged": True},
                    # Create an overlay mount with the data directory as the lower directory
                    # The `tail` makes this container, and thus the mount, run forever.
                    "command": ["/bin/bash", "-c", "--"],
                    "args": [
                        """
                    mkdir -p /overlay/{upper,work}
                    mount -t overlay overlay \
                            -o lowerdir=/data,upperdir=/overlay/upper,workdir=/overlay/work \
                            /work
                    chown 1000:1000 /work

                    touch /semaphores/ready
                    while [ ! -f /semaphores/finished ]
                    do
                        sleep 1
                    done
                    """
                    ],
                    # Unmount otherwise this container will never terminate.
                    "lifecycle": {
                        "preStop": {"exec": {"command": ["umount", "/work"]}}
                    },
                    "volumeMounts": [
                        # Read only data directory (snapshot directory)
                        {
                            "name": "snapshots",
                            "subPath": snapshot,
                            "mountPath": "/data",
                            "readOnly": True,
                        },
                        # Temporary working directory for overlay mount to use
                        {"name": "overlay", "mountPath": "/overlay"},
                        # Bidirectional mount allowing the session container
                        # to mount the /work directory
                        {
                            "name": "work",
                            "mountPath": "/work",
                            "mountPropagation": "Bidirectional",
                        },
                        # Semaphores directory allowing communitcation
                        # with the session container
                        {"name": "semaphores", "mountPath": "/semaphores"},
                    ],
                }
            ]

            volume_mounts = [
                {"name": "work", "mountPath": "/work"},
                {"name": "semaphores", "mountPath": "/semaphores"},
            ]

            volumes = [
                {
                    "name": "snapshots",
                    "hostPath": {"path": "/var/lib/stencila/hub/snapshots"},
                },
                {"name": "overlay", "emptyDir": {}},
                {"name": "work", "emptyDir": {}},
                {"name": "semaphores", "emptyDir": {}},
            ]

        else:

            init_containers = []

            sidecar_containers = []

            volume_mounts = [
                {
                    "name": "work",
                    "mountPath": "/work",
                    "mountPropagation": "HostToContainer",
                    "readOnly": True,
                }
            ]

            volumes = [
                {
                    "name": "work",
                    "hostPath": {
                        "path": f"/var/lib/stencila/hub/storage/working/{project}"
                    },
                },
                {"name": "semaphores", "emptyDir": {}},
            ]

        # Pod manifest
        pod = {
            "apiVersion": "v1",
            "kind": "Pod",
            "metadata": {
                "name": self.pod_name,
                "labels": {"method": "session", "networkPolicy": network_policy},
            },
            "spec": {
                "nodeSelector": {"cloud.google.com/gke-nodepool": node_pool},
                "initContainers": init_containers,
                "containers": sidecar_containers
                + [
                    {
                        "name": "session",
                        "image": container_image,
                        "command": command,
                        "securityContext": {"runAsUser": 1000, "runAsGroup": 1000},
                        "ports": [{"containerPort": port} for port in ports.values()],
                        "readinessProbe": {
                            "tcpSocket": {"port": ports["ws"]},
                            "initialDelaySeconds": 2,
                            "periodSeconds": 1,
                            "failureThreshold": 60,
                        },
                        "volumeMounts": volume_mounts,
                        "workingDir": "/work",
                        "resources": {
                            "requests": {
                                "cpu": cpu_request,
                                "memory": "{}Mi".format(mem_request),
                            },
                            "limits": {
                                "cpu": cpu_limit,
                                "memory": "{}Mi".format(mem_limit),
                            },
                        },
                    }
                ],
                "volumes": volumes,
                # Do not restart this pod when it stops
                "restartPolicy": "Never",
                # Do not automatically mount a token for K8s API access
                "automountServiceAccountToken": False,
            },
        }

        # Try to create the pod, but it it already exists then ignore
        # the job (do not record any state from here but remove it from the queue).
        # See https://docs.celeryproject.org/en/latest/userguide/tasks.html#ignore
        try:
            self.logger.debug("Creating pod")
            api_instance.create_namespaced_pod(
                body=pod, namespace=namespace,
            )
        except kubernetes.client.rest.ApiException as exc:
            if exc.reason == "Conflict":
                raise Ignore()
            else:
                raise exc

        # Wait for pod to be ready so that we can get its IP address
        self.logger.debug("Waiting for pod")
        while True:
            pod = api_instance.read_namespaced_pod(
                name=self.pod_name, namespace=namespace
            )
            # Check readiness of the container
            # The Python API `V1ContainerStatus` does not expose `started`
            # so we use `ready` and a `readinessProbe` (above).
            phase = pod.status.phase
            ready = (
                pod.status.container_statuses
                and len(pod.status.container_statuses)
                and pod.status.container_statuses[0].ready
                or False
            )
            if phase == "Running" and ready:
                break
            time.sleep(0.25)
        ip = pod.status.pod_ip

        # Update the job state with the internal URLs of the pod
        urls = dict(
            (protocol, f"{protocol}://{ip}:{port}") for protocol, port in ports.items()
        )
        self.notify(state="RUNNING", urls=urls)

        self.logger.debug("Started pod")

        try:
            self.poll()
        except (SoftTimeLimitExceeded, KeyboardInterrupt):
            return self.terminated()
        except kubernetes.client.rest.ApiException as exc:
            # Log the exception if it is not an expected
            # SoftTimeLimitExceeded exception (used for cancelling
            # / terminating jobs)
            if "SoftTimeLimitExceeded" not in exc.reason:
                logger.exception(exc)
            # Always terminate the pod if there has been an exception
            return self.terminated()

        self.logger.info("Pod finished")
        return self.completed()

    def attach(self):
        """
        Attach to the pod's stdout and stderr streams.
        """
        response = kubernetes.stream.stream(
            api_instance.connect_get_namespaced_pod_attach,
            name=self.pod_name,
            namespace=namespace,
            container="executa",
            stderr=True,
            stdout=True,
            stdin=False,
            tty=False,
        )
        if hasattr(response, "is_open"):
            while response.is_open():
                response.update(timeout=1)
                stdout = response.readline_stdout(timeout=3)
                self.info(stdout)
                stderr = response.readline_stderr(timeout=3)
                self.info(stderr)
        else:
            self.info(response)

    def poll(self):
        """
        Poll the session until it stops running.
        """
        while True:
            pod = api_instance.read_namespaced_pod(
                name=self.pod_name, namespace=namespace
            )
            if pod.status.phase != "Running":
                return
            time.sleep(3)

    def terminated(self):
        """
        Stop the session.
        """
        if self.pod_name:
            self.logger.info("Terminating pod")
            api_instance.delete_namespaced_pod(name=self.pod_name, namespace=namespace)
            self.pod_name = None

    def completed(self):
        """
        Clean up the pod if the pod completed i.e. timeout or timelimit

        If we do not do this clean up then these finished pods just end up
        polluting the namespace.
        """
        if self.pod_name:
            self.logger.info("Deleting pod")
            api_instance.delete_namespaced_pod(name=self.pod_name, namespace=namespace)
            self.pod_name = None

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--debug", default=False, type=bool, help="Output debug log entries"
    )
    parser.add_argument(
        "--project", type=int, help="Project the session is for (e.g. 1234)"
    )
    parser.add_argument(
        "--snapshot",
        default=None,
        type=str,
        help="Snapshot the session is for (e.g. GnnxNtxDsmiqafKsfF6gsP)",
    )
    parser.add_argument(
        "--snapshot-url",
        default=None,
        type=str,
        help="The URL of the snapshot zip archive (if any)",
    )
    parser.add_argument(
        "--timeout",
        default=None,
        type=int,
        help="Durations of inactivity until session times out (s)",
    )
    parser.add_argument(
        "--timelimit", default=None, type=int, help="Maximum time limit (s)",
    )
    parser.add_argument(
        "--network-policy",
        default=None,
        type=str,
        help="Network policy to apply to the pod",
    )
    args = parser.parse_args()

    logger.setLevel(logging.DEBUG if args.debug else logging.INFO)

    session = KubernetesSession()
    session.run(
        project=args.project,
        snapshot=args.snapshot,
        snapshot_url=args.snapshot_url,
        key=secrets.token_urlsafe(8),
        timeout=args.timeout,
        timelimit=args.timelimit,
        network_policy=args.network_policy,
    )


"""
113. 路径总和 II
给你二叉树的根节点 root 和一个整数目标和 targetSum ，找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
"""
from collections import defaultdict, deque

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution(object):
    # 深度搜索
    def hasPathSum_dfs(self, root, targetSum):
        if not root:
            return False
        if not root.left and not root.right:
            return targetSum == root.val
        return self.hasPathSum_dfs(root.left, targetSum - root.val) \
               or self.hasPathSum_dfs(root.right, targetSum - root.val)

    # 广度搜索
    def hasPathSum_bfs(self, root, targetSum):
        if not root:
            return False
        que_node = deque([root])
        que_val = deque([root.val])
        while que_node:
            node = que_node.popleft()
            tmp = que_val.popleft()
            if not node.left and not node.right:
                if tmp == targetSum:
                    return True
            if node.left:
                que_node.append(node.left)
                que_val.append(node.left.val + tmp)
            if node.right:
                que_node.append(node.right)
                que_val.append(node.right.val + tmp)
        return False

if __name__ == '__main__':
    solution = Solution()
    node5 = TreeNode(5)
    node4 = TreeNode(4)
    node3 = TreeNode(3, node4, node5)
    node2 = TreeNode(2)
    root = TreeNode(1, node2, node3)
    fun = solution.hasPathSum_bfs(root, 3)
    print(fun)


from typing import cast, Any, Callable, ClassVar, Dict, Generic, List, Optional, Type, TypeVar, Union

from typing_extensions import Protocol

__all__ = [
    "Module",
    "Dependency",
    "construct_component",
    "define_arguments_recursive"
]

class ModuleSettings:
    def __init__(self, cls, main_settings) -> None:
        object.__setattr__(self, "cls", cls)
        object.__setattr__(self, "main_settings", main_settings)

    def __getattribute__(self, item):
        cls = object.__getattribute__(self, "cls")
        main_settings = object.__getattribute__(self, "main_settings")
        for entry in cls.__mro__:
            try:
                settings = getattr(main_settings, entry.__name__)
                return getattr(settings, item)
            except AttributeError:
                continue

        raise AttributeError("'" + cls.__name__ + "' object has no setting '" + item + "'")

    def __setattr__(self, key, value):
        cls = object.__getattribute__(self, "cls")
        main_settings = object.__getattribute__(self, "main_settings")
        for entry in cls.__mro__:
            try:
                settings = getattr(main_settings, entry.__name__)
                getattr(settings, key)
                setattr(settings, key, value)
                return
            except AttributeError:
                continue

        raise AttributeError("'" + cls.__name__ + "' object has no setting '" + key + "'")

class Settings:
    def __init__(self, cls: Type['Module']) -> None:
        self.cls: Type['Module'] = cls

    def __get__(self, obj: 'Module', objtype: Any = None) -> 'ModuleSettings':
        return ModuleSettings(self.cls, obj.main_settings)

    def __set__(self, obj: 'Module', settings: 'Settings'):
        setattr(obj.main_settings, self.cls.__name__, settings)

class HasModulesMapping(Protocol):
    active_modules: Dict[Type['Module'], 'Module']

class Module:
    settings: ClassVar['Settings']
    main_settings: 'HasModulesMapping'

    def __init__(self, *args, **kwargs):  # workaround for type checking
        pass

    def __new__(cls: Type['Module'], main_settings: 'HasModulesMapping', *args, **kwargs) -> 'Module':
        instance: 'Module' = super(Module, cls).__new__(cls)
        instance.main_settings = main_settings
        return instance

ComponentTypeT = TypeVar('ComponentTypeT', bound=Module)

def construct_component(cls: Type[ComponentTypeT], main_settings: 'HasModulesMapping',
                        *args, **kwargs) -> ComponentTypeT:

    if not getattr(main_settings, "active_modules", None):
        main_settings.active_modules = {}

    if cls not in main_settings.active_modules:
        cls.settings = Settings(cls)

        # The module instance is constructed manually, because we need to set
        # settings attribute before constructor is called
        instance: 'Module' = cls.__new__(cls, main_settings=main_settings)

        # https://github.com/python/mypy/blob/master/mypy/checkmember.py#180
        # Accessing __init__ in statically typed code would compromise
        # type safety unless used via super().
        # noinspection PyArgumentList
        # pylint: disable = unnecessary-dunder-call
        instance.__init__(*args, **kwargs)  # type: ignore
        main_settings.active_modules[cls] = instance
    return cast(ComponentTypeT, main_settings.active_modules[cls])

DependencyTypeT = TypeVar('DependencyTypeT', bound=Module)

class Dependency(Generic[DependencyTypeT]):
    def __init__(self, cls: Type[DependencyTypeT]) -> None:
        self.cls = cls

    # The source and the target of the dependency are different modules,
    # so we need to use different type variables to annotate them.
    # instance parameter of the __get__ method is source module.
    def __get__(self, instance: Module, owner: Any) -> Callable[..., DependencyTypeT]:
        def constructor_function(*args, **kwargs) -> DependencyTypeT:
            return construct_component(self.cls, instance.main_settings, *args, **kwargs)
        return constructor_function

def get_dependencies(cls: Type[Module], result: Optional[List[Type[Module]]] = None) -> List[Type[Module]]:
    if result is None:
        result = []

    result.append(cls)

    # parent classes
    all_dependencies: List[Type[Module]]
    all_dependencies = [x for x in cls.__mro__ if issubclass(x, Module) and x != Module and x != cls]
    # dependencies
    all_dependencies.extend([x.cls for x in cls.__dict__.values() if isinstance(x, Dependency)])

    for dependency in all_dependencies:
        if dependency not in result:
            get_dependencies(dependency, result)

    return result

def define_arguments_recursive(cls, argument_parser):  # TODO: return here after ModuleArgumentParser is annotated
    modules = get_dependencies(cls)

    for current_module in modules:
        if "define_arguments" in current_module.__dict__:
            argument_parser.dest_prefix = current_module.__name__ + '.'
            # noinspection PyUnresolvedReferences
            current_module.define_arguments(argument_parser)

    argument_parser.dest_prefix = ''


def solution(lottos, win_nums):
    answer = []
    cnt = 0
    zero = 0

    for i in range(0,6):
        if lottos[i] == 0 :
            zero+=1
        elif lottos[i] in win_nums:
            cnt+=1

    # 모든 0인 경우 - 1등 혹은 6등 가능
    if zero == 6:
        answer = [1,6]
    # 모든 숫자가 로또 번호에 있는 경우 - 1등만 가능
    elif cnt == 6 :
        answer = [1,1]
    # 숫자는 다 있지만 일치하는 게 없는 경우 - 6등만 가능
    elif cnt == 0 and zero == 0 :
        answer = [6,6]
    # 숫자와 0이 함께 있는 경우 - 최고, 최저 순위
    else :
        answer = [7-(zero+cnt), 7-cnt]

    return answer

Level 1/14 로또의 최고 순위와 최저 순위.py

14 로또의 최고 순위와 최저 순위.py


import matplotlib.pyplot as plt
import tdclient
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime
from modules.environ_params import *

query = "with t as (" \
		"select td_time_format(time, 'yyyy-MM-dd') as apply_date, * " \
		"from sweeper.merchant_epc_info" \
		") " \
		"select apply_date, count(merchant_id) as applicants " \
		"from t " \
		"group by apply_date " \
		"order by apply_date"

data = []
with tdclient.Client(TD_APIKEY) as td:
	job = td.query('analytics_cn', query, type='presto')
	job.wait()
	for row in job.result():
		print(row)
		data.append(row)

data = np.asarray(data)
pdata = pd.DataFrame(data=data[:, 1].astype(int),
					 index=pd.to_datetime(data[:, 0], format='%Y-%m-%d'),
					 columns=['new_epc_applicants'])

fig, ax = plt.subplots()

ts = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
text_1 = 'Updated time: ' + ts
text_2 = 'Applicants today = ' + str(data[-1, 1].astype(int))
text_3 = 'Cumulative applicants = ' + str(np.sum(data[:, 1].astype(int)))

pdata.plot(ax=ax)
ax.text(x=0.07, y=0.93, s=text_1, transform=ax.transAxes)
ax.text(x=0.07, y=0.88, s=text_2, transform=ax.transAxes)
ax.text(x=0.07, y=0.83, s=text_3, transform=ax.transAxes)
plt.show()


#!/bin/env python
import wx
from model import *

class wxFlowFrame(wx.Frame):

    def __init__(self):
        self.model = FlowModel()
        self.model.addListener(self.UpdateText)

        wx.Frame.__init__(self, None, -1, "wxFlow")
        self.panel = wx.Panel(self, -1)
        self.staticText = wx.StaticText(self.panel, -1, "")

        self.model.SetSut("EPGxxxxxxxxxxxxxxxxxx")

    def UpdateText(self, model):
        self.staticText.SetLabel(model.sut)

class wxFlowApp(wx.App):
    def __init__(self):
        wx.App.__init__(self, redirect=False)

    def OnInit(self):
        self.frame = wxFlowFrame()
        self.frame.Show()
        self.SetTopWindow(self.frame)
        return True

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = wxFlowFrame()
    frame.Show(True)
    app.MainLoop()


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

import urllib2
import urllib

class LineNotifyRequest:
    __url = 'https://notify-api.line.me/api/notify'
    __apiToken = None;
    __message = None;

    def setToken(self, token):
        self.__apiToken = token

    def setMessage(self, message):
        self.__message = message

    def send(self):
        values = { 'message' : self.__message }
        headers = { 'Authorization' : 'Bearer {t}'.format(t=self.__apiToken) }

        data = urllib.urlencode(values)
        req = urllib2.Request(self.__url, data, headers)
        response = urllib2.urlopen(req)
        the_page = response.read()
        return the_page


from jinja2 import Environment, FileSystemLoader
from parser import Parser
from util import load_config, uri_to_qname, uri_to_anchor
import datetime
#import sass

jinja_env = Environment(loader=FileSystemLoader('templates'), autoescape=False)
jinja_env.filters['to_link'] = uri_to_anchor
jinja_env.filters['to_qname'] = uri_to_qname
jinja_env.globals['timestamp'] = datetime.datetime.now().strftime('%A, %b %d %Y at %X')

def compile():

	owl_parser = Parser()
	page_data = {
		'ontology': owl_parser.process(),
		'metadata': load_config()['site_info'] }

	#print data_dict

	with open('templates/base.html', 'rb') as base_template_file, \
		open('output/index.html', 'wB') as output:
		template = jinja_env.get_template( 'base.html')
		rendered_html = template.render(page_data=page_data)
		output.write(rendered_html)

if __name__ == '__main__':
	compile()


import re
from .dict.errorfix_dictrionary import ErrorFixDictionary

class KoreanErrorCorrector(object):
    """
    correct wronly tagged POS
    """

    def __init__(self,
                 path_userdict = None,
				 userdict_patterns = None):

        if not path_userdict and not userdict_patterns:
            raise ValueError("At least one of path_userdict or userdict_patterns should be given")

        dictionary, self.entries = ErrorFixDictionary.open(USER_PATH=path_userdict,
                                                           PATTERN_LIST=userdict_patterns)
        self.correct_dict = dictionary.correct_dict
        keys = sorted(list(self.correct_dict.keys()), key=lambda x: len(x), reverse=True)
        self.patterns = '|'.join(keys)

    def correct(self, tkn_attrs):
        tokens = tkn_attrs.termAtt
        tags = tkn_attrs.posTagAtt
        merge_text = ' '.join([t + '_' + p for t, p in zip(tokens, tags)])

        match = re.findall(pattern=self.patterns, string=merge_text)
        if match:
            for m in match:
                merge_text = merge_text.replace(m, self.correct_dict.get(m))

            splits = merge_text.split(' ')
            tokens, tags = [], []
            for s in splits:
                t, p = s.split('_')
                tokens.append(t)
                tags.append(p)

        tkn_attrs.termAtt = tokens
        tkn_attrs.posTagAtt = tags
        return tkn_attrs


# Author: OMKAR PATHAK
# Created On: 31st July 2017

# Best = Average = Worst = O(nlog(n))

# merge function to merge the separated lists
def merge(a,b):
    """ Function to merge two arrays """
    c = []
    while len(a) != 0 and len(b) != 0:
        if a[0] < b[0]:
            c.append(a[0])
            a.remove(a[0])
        else:
            c.append(b[0])
            b.remove(b[0])
    if len(a) == 0:
        c += b
    else:
        c += a
    return c

# Code for merge sort
def sort(x):
    """ Function to sort an array using merge sort algorithm """
    if len(x) == 0 or len(x) == 1:
        return x
    else:
        middle = len(x)//2
        a = sort(x[:middle])
        b = sort(x[middle:])
        return merge(a,b)

# time complexities
def bestcase_complexity():
    return 'O(nlogn)'

def averagecase_complexity():
    return 'O(nlogn)'

def worstcase_complexity():
    return 'O(nlogn)'

# easily retrieve the source code of the sort function
def get_code():
    import inspect
    return inspect.getsource(sort), inspect.getsource(merge)


import textwrap
from bibliopixel import gen_matrix as mapGen
from bibliopixel.layout.multimap import MultiMapBuilder
from bibliopixel.layout import Rotation as MatrixRotation

R090 = MatrixRotation.ROTATE_90
R270 = MatrixRotation.ROTATE_270

class ULTiMap(MultiMapBuilder):
    '''
    Return the map for array of ULTiM8x8 boards.
    total LED count is 64 * n_8x8_row * n_8x8_col
    '''

    def __init__(self, n_8x8_row, n_8x8_col):
        MultiMapBuilder.__init__(self)
        self.n_8x8_row = n_8x8_row
        self.n_8x8_col = n_8x8_col
        for row_i in range(n_8x8_row):
            self.addRow(mapGen(8, 8 * n_8x8_col, serpentine=True,
                               rotation=[R090, R270][row_i % 2],
                               y_flip=False))
        self.w = len(self.map[0])
        self.h = len(self.map)

    def toH(self, f):
        ultim = 'ULTIM%dx%d' % (self.h, self.w)
        print('#ifdef %s' % ultim, file=f)
        print('#define MatrixWidth %d' % self.w, file=f)
        print('#define MatrixHeight %d' % self.h, file=f)

        lines = ['uint16_t MatrixMap[MatrixHeight][MatrixWidth] = {']
        for row in self.map:
            lines.append('{' + ','.join(map(str, row)) + '},')
        lines.append('};')
        lines = '\n'.join(lines)
        print(lines, file=f)

        print('#endif', file=f)
        print('', file=f)

## build 24x24 array map
### test old way
ultim24x24 = MultiMapBuilder()
ultim24x24.addRow(mapGen(8, 24, serpentine=True,
                  rotation=MatrixRotation.ROTATE_90,
                  y_flip=False))
ultim24x24.addRow(mapGen(8, 24, serpentine=True,
                  rotation=MatrixRotation.ROTATE_270,
                  y_flip=False))
ultim24x24.addRow(mapGen(8, 24, serpentine=True,
                  rotation=MatrixRotation.ROTATE_90,
                  y_flip=False))

def test():
    import numpy
    my_24x24 = numpy.array(ULTiMap(3, 3).map)
    u24x24 = numpy.array(ultim24x24.map)
    assert numpy.linalg.norm(my_24x24 - u24x24) < 1e-8
test()

def create_map_h():
    f = open('MatrixMaps.h', 'w')
    # maps = [ultim8x8, ultim8x24, ultim24x24, ultim48x24, ultim8x72, ultim16x56]
    sizes = ((1, 1), (1, 3), (3, 3), (6, 3), (1, 9), (2, 7))
    for n_8x8_row, n_8x8_col in sizes:
        mmb = ULTiMap(n_8x8_row, n_8x8_col)
        mmb.toH(f)
    print('wrote', f.name)
create_map_h()


# 1218. Longest Arithmetic Subsequence of Given Difference
# Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is
# an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.
#
# Example 1:
# Input: arr = [1,2,3,4], difference = 1
# Output: 4
# Explanation: The longest arithmetic subsequence is [1,2,3,4].

# Example 2:
# Input: arr = [1,3,5,7], difference = 1
# Output: 1
# Explanation: The longest arithmetic subsequence is any single element.

# Example 3:
# Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
# Output: 4
# Explanation: The longest arithmetic subsequence is [7,5,3,1].

class Solution:
    def longestSubsequence(self, arr, difference):
        count = {}
        for num in arr:
            if num - difference in count:
                count[num] = count[num - difference] + 1
            else:
                count[num] = 1
        return max(count.values())

# func = Solution()
# arr = [1, 5, 7, 8, 5, 3, 4, 2, 1]
# difference = -2
# print(func.longestSubsequence(arr, difference))  # Output: 4

LeetCode/Training/1218. Longest Arithmetic Subsequence of Given Difference.py


import pandas as pd

format_str = 'out_str'
format_table = 'out_table'

def find_affected_deals(deals_table, events_table, out_format=format_table):
    dcolumns, deals = deals_table
    ecolumns, events = events_table
    index_columns = ['Peril', 'Location']
    df_deals = pd.DataFrame(data = deals, columns = dcolumns).set_index(index_columns)
    df_events = pd.DataFrame(data = events, columns = ecolumns).set_index(index_columns)
    df_affected = df_deals[df_deals.index.isin(df_events.index)]
    if out_format == format_str:
        return str(df_affected)
    df_affected = df_affected.reset_index()
    return (df_affected.columns.values.tolist(), df_affected.values.tolist())


# -*- coding: utf-8 -*-
import unittest2 as unittest

from zope.component import getMultiAdapter

from plone.app.angularjs.testing import\
    PLONE_APP_ANGULARJS_INTEGRATION_TESTING

class TestAppIndex(unittest.TestCase):

    layer = PLONE_APP_ANGULARJS_INTEGRATION_TESTING

    def setUp(self):
        self.app = self.layer['app']
        self.portal = self.layer['portal']
        self.request = self.layer['request']

    def test_view_is_registered(self):
        self.assertTrue(
            getMultiAdapter(
                (self.portal, self.request),
                name="index.html"
            )
        )


#plot Bayes solution vs MLE solution for spherical harmonics based MAPDS-
#similar aspect: Both need more steps to converge than the default. yay.
import os
import numpy as np
import pandas as pd
from glob import glob
from os.path import *
from matplotlib import pyplot as plt
from ipdb import set_trace
import pickle

def findSubjects(path):
    return [x.split(os.sep[-1])[-1] for x in glob(join(path,'sub*'))]

def plotOneSub(sub,path):
    subPath = join(path,sub)
    phasePaths = [join(subPath,'phase{:02d}'.format(x),'quadruplet') for x in [2,4]]
    angles = np.array(range(8)) /4 *np.pi
    for ii,path in enumerate(phasePaths):
        fig = plt.figure(figsize=(10,10))
        ax = fig.add_subplot(111,projection = 'polar')
        MLE = pd.read_excel(join(path,'coords_MLE.xlsx'),header = None, names = ['angles','radii'])
        with open(join(path,'meanSolution_longWarmup_narrow.pic'),'rb') as f:
            bayes = pickle.load(f)
        ax.plot(angles,MLE.radii,label = 'MLE')
        ##set_trace()
        ax.plot(angles,bayes['radii'],label = 'Bayes')
        ax.set_title('MLE vs. Bayes, subject: {}'.format(sub))
        ax.legend()
        fig.savefig(join(path,'MLE_vs_Bayes_longWarmpup_narrow_mean.png'))

if __name__ == '__main__':
    base = r'C:\Users\neugebauer\Documents\Experiments\MAPDS\testData'
    subjects = findSubjects(base)
    for s in subjects:
        plotOneSub(s,base)
        print('done with {}'.format(s))


"""
Basic server simulating media transmission similar to DASH.
Some parameters are provided for adjusting the maximum bandwidth,
the representations available for transmission, the size and length of media chunks,
and the rime between requests.  Developed in conjunction with a client script.

(C)2020 Gianluca Traversa, London, United Kingdom.

email gianlu.traversa@gmail.com

"""

import socket,os,sys,random,time
from _thread import *

ServerSocket = socket.socket()
host = '127.0.0.1'
port = 1233

_clients = []
_frameSize = 2048
_initBandwith = 300
_totalBandwidth = 300

try:
    ServerSocket.bind((host, port))
except socket.error as e:
    print(str(e))

print('Waiting for a Connection..')
ServerSocket.listen(5)

def threaded_client(connection,_address):
    """Create a client connection on a new thread for simple DASH simulation"""
    _timeCreated = time.time()
    _chunkLength = 3                                                            #Length of segment request in seconds
    _flgFirst = 1
    _maxClientBandwidth = 0
    global _totalBandwidth
    try:
        while True:
            _data = connection.recv(_frameSize)                                     #Initial conditions set by the client
            if not _data:
                break
            _bandwidth,_req,_timer,_qualiReq,_segNum,_currentClient = data_parse(_data,_address)            #Return of initial conditions to pass to bandwidth limiter simulation
            if _flgFirst:                                                           #On fisrst connection with a client
                _currentClient['Bandwidth'] = _bandwidth
                _currentClient['Max Bandwidth']= _bandwidth
                _totalBandwidth = _totalBandwidth-_bandwidth                        #Allcoate desired bandwidth to client
                _flgFirst=0
                print('First connection for: ' +_address[0]+':'+str(_address[1]))
            if _totalBandwidth<0:                                                   #Requested bandwidth > available bandwidth
                bandwidth_sharing()
                _totalBandwidth = 0

            if _req:
                _chunkSize = chunk_quality(_qualiReq,_segNum)                       #If client is requesting data
                send_chunk(connection,_bandwidth=_currentClient['Bandwidth'],_bytesSent=_chunkSize,_timer=_timer,_chunkLength=_chunkLength)
                print('_________________________')
                print("Chunk sent to: "+ _address[0]+':'+str(_address[1]))
            elif not _req:                                                          #Client buffer is full, send 0 length segment to ACK conneciton
                send_chunk(connection,_bandwidth=_currentClient['Bandwidth'],_bytesSent=0,_timer=_timer,_chunkLength=0)
        conncection_closed(_currentClient)
        connection.close()
    except socket.error as e:
        conncection_closed(_currentClient)
        connection.close()
        print(str(e))

def data_parse(_data,_address):
    """Parse client setup data, updates client and returns setup variables"""
    _setup = _data.decode('utf-8').split(',')                                   #Data received as encoded CSV
    _currentClient = 0
    for client in _clients:
        if client['Port']==_address[1]:
            _currentClient = client                                             #Select current client based on port number
            break
    _bandwidth = int(_setup[0])
    _req = bool(int(_setup[1]))
    _currentClient['Request']=_req
    _timer = float(_setup[2])
    _currentClient['Timer']=_timer
    _qualiReq = str(_setup[3])
    _segNum = int(_setup[4])
    return  _bandwidth,_req,_timer,_qualiReq,_segNum,_currentClient

def send_chunk(connection,_bandwidth,_bytesSent,_timer,_chunkLength):
    """Simulation of limted bandwidth channel"""
    _sendTime = _bytesSent / _bandwidth                                         #Equivalent download time of chunk with given size (MBit) and bandwidth (MBit/s)
    time.sleep(max(_sendTime,_timer))                                           #Local transfer de layed by equivalent 'download' time OR minimum request time '_timer'
    reply = str(_chunkLength) + ',' + str(_bytesSent)                           #Length of chunk in seconds sent back to client
    connection.sendall(str.encode(reply))

def save_client(_address):
    """Taskes connection information and stores as a dict in list of clients"""
    _clientDict = {}
    _address = str(_address).strip("()").replace("'","").split(', ')            #Some parsing to get IP and port  of client socket
    for info in _address:
        if info.__contains__("."):
            _clientDict['IP']=info
        else:
            _clientDict['Port']=int(info)
    _clientDict['Bandwidth'] = 0                                                #Default parameters for every client
    _clientDict['Request']= 1
    _clientDict['Timer']= 0
    _clients.append(_clientDict)
    print('Connected to: ' + _clientDict['IP'] + ':' + str(_clientDict['Port']))

def start_client(_client,_address):
    """Start new thread for new connection"""
    start_new_thread(threaded_client, (_client, _address))

def conncection_closed(_currentClient):
    """Eliminte client from list of clients when the connection is closed"""
    global _totalBandwidth
    print('Connection closed with: ' +_currentClient['IP']+':'+str(_currentClient['Port']))
    _totalBandwidth+= _currentClient['Bandwidth']                               #Free ALLOCATED bandwidth, not maximum given by client
    _clients.remove(_currentClient)
    bandwidth_sharing()                                                         #Reallocate increased bandwidth to other clients

def chunk_quality(_qualiReq,_segNum):
    """Find chunk size for desired quality and send it to the client"""
    _chosenQuali=[]
    _240p = [23.50,23.40,23.11,22.59,21.97,21.44,21.22,21.45,22.22,23.46,25.00,26.58,28.03,29.19,29.92,30.18,30.04,29.64,29.17,28.79,-1]
    _360p = [52.87,52.65,51.99,50.82,49.42,48.24,47.74,48.27,49.98,52.78,56.25,59.81,63.07,65.67,67.31,67.91,67.59,66.69,65.63,64.77,-1]
    _480p=  [118.97,118.47,116.98,114.35,111.20,108.54,107.41,108.60,112.46,118.75,126.56,134.57,141.91,147.75,151.45,152.79,152.08,150.05,147.67,145.73,-1]
    _720p=  [267.68,266.56,263.21,257.29,250.20,244.22,241.67,244.35,253.04,267.19,284.77,302.79,319.30,332.44,340.76,343.78,342.17,337.61,332.26,327.88,-1]
    _1080p= [602.28,599.75,592.22,578.90,562.96,549.49,543.76,549.80,569.35,601.18,640.72,681.28,718.43,747.99,766.71,773.50,769.88,759.63,747.59,737.74,-1]
    _reprs = {'_240p': _240p,'_360p':_360p,'_480p':_480p,'_720p':_720p,'_1080p':_1080p}
    _chosenQuali = _reprs[str(_qualiReq)]
    return _chosenQuali[_segNum]

def bandwidth_sharing():
    """Allocate bandwidth to clients proportionally"""
    global _initBandwith
    _totalBandwidthReq = 0
    for client in _clients:
        _totalBandwidthReq+= client['Max Bandwidth']                            #Find the total of the max bandwidth the clients request
    print('Total Requested Bandwidth: '+ str(_totalBandwidthReq))

    if not _totalBandwidthReq:                                                  #In case of no requests
        _totalBandwidthReq = _initBandwith
    _scaleFactor = _initBandwith/_totalBandwidthReq                             #Ratio of available to requested bandwidth
    for client in _clients:
        client['Bandwidth']=client['Max Bandwidth']*min(_scaleFactor,1)         #Scaling of each max bandwidth ans setting allocated bandwidth

def main():
    while True:
        _client, _address = ServerSocket.accept()
        save_client(_address)
        start_client(_client,_address)
    ServerSocket.close()

if __name__ == '__main__':
    main()


import sys
sys.path.append('../lsmaker')
import os
import numpy as np
import pandas as pd
from shapely.geometry import LineString
#from GISio import df2shp

def get_ls_skiprows_nrows(xtr):
    with open(xtr) as f:
        knt = 0
        while True:
            line = next(f)
            knt += 1
            if '! head specified line sinks' in line:
                skiprows = knt + 1
            if '! stream linkages' in line:
                nrows = knt - skiprows -1
                break
    return skiprows, nrows

def get_linesink_results(xtr):
    """Read linesink results from GFLOW extract (.xtr) file into dataframe.
    """
    names = ['x1',
             'y1',
             'x2',
             'y2',
             'spec_head',
             'calc_head',
             'discharge',
             'width',
             'resistance',
             'depth',
             'baseflow',
             'overlandflow',
             'BC_pct_err',
             'label']
    ls_skiprows, nrows = get_ls_skiprows_nrows(xtr)

    return pd.read_csv(xtr, skiprows=ls_skiprows, nrows=nrows, header=None, names=names)

def plot_flooding_arcpy(grdfile, dem,
                        outpath='flooding',
                        solver_x0=0, solver_y0=0, scale_xy=0.3048, epsg=None,
                        dem_mult=0.3048, nearfield=None,
                        resample_heads=True, resample_cellsize=10):
    """Subtract gridded heads from GFLOW from DEM; save results as raster.
    (requires arcpy and rasterio)

    gridfile: str
        Gridded heads file output from GFLOW (*.GRD)
    dem:
        DEM for model area.
    outpath :
        Folder for writing output raster(s) to.
    solver_x0 : float
    solver_y0 : float
        To get the solve origin (solver_x0, solver_y0), in GFLOW choose Tools > GFLOW Database Viewer,
        then View > Base Tables > Model.
    scale_xy : float
        Multiplier to convert GFLOW coordinates to GIS coordinates.
    epsg : int
        EPSG code for GIS projected coordinate system (e.g. 26715 for NAD27 UTM zone 15)
    dem_mult : float
        Multiplier from DEM elevation units to GFLOW units.
    nearfield : str
        Shapefile of model nearfield.
    resample_heads : boolean
        Resample gridded GFLOW heads (typically coarse) to finer resolution using bilinear interpolation).
    resample_cellsize : float
        Cellsize for resampled heads (typically same as DEM resolution).

    Notes
    =====

    """
    try:
        import arcpy
    except:
        print('Method requires arcpy.')
        return

    if not os.path.isdir(outpath):
        os.makedirs(outpath)
    arcpy.env.workspace = outpath
    #arcpy.Delete_management('*')
    arcpy.env.overwriteOutput = True
    arcpy.CheckOutExtension('Spatial')

    print('reading {}...'.format(dem))
    demft = arcpy.Raster(dem) * dem_mult
    solver_x0 = solver_x0
    solver_y0 = solver_y0
    wtfile = os.path.join(outpath,'heads_prj.tiff')
    print('reading {}...'.format(grdfile))
    hds = surferGrid(grdfile)
    hds.scale_xy(scale_xy)
    hds.offset_xy(solver_x0, solver_y0)
    hds.write_raster(wtfile, epsg=epsg)

    arcpy.Resample_management(wtfile, 'wtfile_rs', resample_cellsize, "BILINEAR")
    flooding = arcpy.sa.Minus(demft, 'wtfile_rs')
    arcpy.MakeFeatureLayer_management(nearfield, 'nf')
    arcpy.Clip_management(flooding,'#', 'fldcp', nearfield, "#", "ClippingGeometry")
    flooding = arcpy.sa.SetNull('fldcp', 'fldcp', "VALUE > 0")
    print('writing {}/flooding...'.format(outpath))
    flooding.save('flooding')

def write_streamflow_shapefile(xtr, outshp=None, solver_x0=0, solver_y0=0,
                               coords_mult=0.3048, epsg=None):
    """Read linesink results from GFLOW extract (.xtr) file and write to shapefile.
    To get the solve origin (solver_x0, solver_y0), in GFLOW choose Tools > GFLOW Database Viewer,
    then View > Base Tables > Model.
    """
    if outshp is None:
        outshp = '{}_streamflow.shp'.format(xtr[:-4])
    df = get_linesink_results(xtr)
    df = df[df.resistance.values > 0].copy() # only include
    df[['x1', 'x2']] = df[['x1', 'x2']] * coords_mult + solver_x0
    df[['y1', 'y2']] = df[['y1', 'y2']] * coords_mult + solver_y0
    df['geometry'] = [LineString([(r.x1, r.y1), (r.x2, r.y2)]) for i, r in df.iterrows()]
    GISio.df2shp(df, outshp, epsg=epsg)

class surferGrid:
    def __init__(self, grdfile=None, data=None):
        self.header = None
        self.nrow = None
        self.ncol = None
        self.xmin = None
        self.xmax = None
        self.ymin = None
        self.ymax = None
        self.zmax = None
        self.zmin = None
        self.data = data
        if grdfile is not None:
            self.read_grd(grdfile)

    def _read_grd_header(self, grdfile):
        with open(grdfile) as input:
            self.header = input.next()
            self.nrow, self.ncol = map(int, input.next().strip().split())
            self.xmin, self.xmax = map(float, input.next().strip().split())
            self.ymin, self.ymax = map(float, input.next().strip().split())
            self.zmin, self.zmax = map(float, input.next().strip().split())

    def scale_xy(self, mult=1):
        self.xmin *= mult
        self.xmax *= mult
        self.ymin *= mult
        self.ymax *= mult

    def scale_z(self, mult=1):
        self.zmin *= mult
        self.zmax *= mult

    def offset_xy(self, x0=0, y0=0):
        self.xmin += x0
        self.xmax += x0
        self.ymin += y0
        self.ymax += y0

    def read_grd(self, grdfile):
        self._read_grd_header(grdfile)
        data = np.loadtxt(grdfile, skiprows=5)
        self.data = np.reshape(data, (self.ncol, self.nrow))

    def write_grd(self, fname='output.grd'):

        with open(fname, 'w') as output:
            header = self.header.strip() + '\n'
            header += '{:.0f} {:.0f}\n'.format(self.nrow, self.ncol)
            header += '{:.2f} {:.2f}\n'.format(self.xmin, self.xmax)
            header += '{:.2f} {:.2f}\n'.format(self.ymin, self.ymax)
            header += '{:.2f} {:.2f}'.format(self.zmin, self.zmax)
            np.savetxt(output, self.data, fmt='%.2f', delimiter=' ', header=header, comments='')

    def write_raster(self, fname='output', epsg=None):
        try:
            import rasterio
            from rasterio import transform
        except ImportError:
            print('This method requires Rasterio')
            return

        tfm = transform.from_bounds(self.xmin, self.ymin, self.xmax, self.ymax, self.ncol, self.nrow)
        if epsg is not None:
            crs = {'init': 'epsg:{}'.format(epsg)}
        else:
            crs = None

        with rasterio.drivers():
            with rasterio.open(fname,
                               'w',
                               driver='GTiff',
                               width=self.ncol,
                               height=self.nrow,
                               count=1,
                               dtype=np.float64,
                               nodata=0,
                               transform=tfm,
                               crs=crs) as dst:
                dst.write_band(1, np.flipud(self.data))


from xprocess import xprocess

from os import chdir
from types import FunctionType

def change_directory(cwd, todo, args=(), **kwargs):
    if type(todo) == FunctionType:
        def cd(cwd, todo3, args):
            chdir(cwd)
            todo3(*args)
        todo2 = cd
        kwargs=dict(cwd=cwd, todo3=todo, args=args)
    else:
        todo2 = todo
        kwargs[r'cwd'] = cwd
    with xprocess(todo2, **kwargs):
        pass

from withtmp import TestWithTmp

from touch import touch

from pathlib import Path
from sys import executable as python

class T(TestWithTmp):
    def test0process(self):
        tmp = Path(self.tmp)
        def todo():
            touch('t')
        change_directory(tmp, todo)
        self.assertTrue(Path(tmp, r't').exists())
    def test1popen(self):
        tmp = self.tmp
        change_directory(tmp, (python, r'-c', r"open('t', r'wb').close()"))
        self.assertTrue(Path(tmp, r't').exists())


import numpy as np
import cv2

cap = cv2.VideoCapture(0)
frame = cv2.imread('mix.jpg')

upper_bounds = []
lower_bounds = []
colors = []

# blue 0
upper_bounds.append(np.array([125,255,255]))
lower_bounds.append(np.array([101,157,101]))
colors.append((255,0,0))

# green 1
upper_bounds.append(np.array([100,255,200]))
lower_bounds.append(np.array([50,110,65]))
colors.append((0,255,0))

# yellow 2
upper_bounds.append(np.array([40,255,255]))
lower_bounds.append(np.array([13,139,76]))
colors.append((0,255,255))

# orange 3
upper_bounds.append(np.array([18,255,228]))
lower_bounds.append(np.array([0,126,19]))
colors.append((0,128,255))

# red 4
upper_bounds.append(np.array([255,255,255]))
lower_bounds.append(np.array([115,120,33]))
colors.append((0,0,255))

# white 5
upper_bounds.append(np.array([105,140,147]))
lower_bounds.append(np.array([74,0,78]))
colors.append((255,255,255))

# black 6
upper_bounds.append(np.array([124,255,100]))
lower_bounds.append(np.array([0,0,0]))
colors.append((0,0,0))

morph_kernel = np.ones((5,5), np.uint8)
bound_index = 6

def parse_keyboard(key):
    # lower bounds
    if key == ord('o'):
        lower_bounds[bound_index][0] += 1
    elif key == ord('l'):
        lower_bounds[bound_index][0] -= 1
    elif key == ord('i'):
        lower_bounds[bound_index][1] += 1
    elif key == ord('k'):
        lower_bounds[bound_index][1] -= 1
    elif key == ord('u'):
        lower_bounds[bound_index][2] += 1
    elif key == ord('j'):
        lower_bounds[bound_index][2] -= 1

    # upper bounds
    elif key == ord('e'):
        upper_bounds[bound_index][0] += 1
    elif key == ord('d'):
        upper_bounds[bound_index][0] -= 1
    elif key == ord('w'):
        upper_bounds[bound_index][1] += 1
    elif key == ord('s'):
        upper_bounds[bound_index][1] -= 1
    elif key == ord('q'):
        upper_bounds[bound_index][2] += 1
    elif key == ord('a'):
        upper_bounds[bound_index][2] -= 1

def draw_contours(inp, outp__img):
    cv2.rectangle(outp__img, (220, 140), (420, 340), (0, 255, 0), 2)

    for i in range(len(upper_bounds)-1):
        m = cv2.inRange(inp[140:340, 220:420], lower_bounds[i], upper_bounds[i])
        m = cv2.erode(m, morph_kernel, iterations=1)
        m = cv2.dilate(m, morph_kernel, iterations=1)
        im2, contours, hierarchy = cv2.findContours(m, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        # im2, contours, hierarchy = cv2.findContours(m, 1, 2)
        for c in contours:
            # x,y,w,h = cv2.boundingRect(c)
            # cv2.rectangle(outp, (x,y), (x+w,y+h), (0,255,0), 2)
            rect = cv2.minAreaRect(c)
            box = cv2.boxPoints(rect)
            for j in range(len(box)):
                box[j] = [box[j][0]+220, box[j][1]+140]
            box = np.int0(box)
            cv2.drawContours(outp__img, [box], 0, colors[i], 2)

while True:
    ret, frame = cap.read()
    outp = np.copy(frame)
    outp2 = np.copy(frame)

    filtered = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(filtered, lower_bounds[bound_index], upper_bounds[bound_index])
    # mask = cv2.erode(mask, morph_kernel, iterations=1)
    # mask = cv2.dilate(mask, morph_kernel, iterations=1)
    cv2.bitwise_and(frame, frame, outp2, mask)

    draw_contours(filtered, outp)

    # outp = cv2.cvtColor(outp, cv2.COLOR_HSV2BGR)
    cv2.putText(outp, "Upper: {}".format(upper_bounds[bound_index]), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
    cv2.putText(outp, "Lower: {}".format(lower_bounds[bound_index]), (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

    cv2.imshow('Rubics', np.hstack((frame, outp, outp2)))
    cv2.imshow('masks', mask)

    key = cv2.waitKey(1) & 0xFF
    if key == 27: # 27 is the escape key
        break
    else:
        parse_keyboard(key)

cap.release()
cv2.destroyAllWindows()


#!/usr/bin/env python
import os,sys
import argparse
from collections import defaultdict,Counter
import copy
import sqlite3
import time
from time import gmtime, strftime
import numpy as np
def write_CR():
	#ALL	900365017	2875105	0.00319326600403
	#ELSE	85530991	352474	0.00412100919069
	#ENSG00000000003	25890	148	0.00571649285438
	overall = []
	lines = []
	with file(options.conversion,'w') as CR_output:
		CR_output.write("\t".join(["#ALL",str(all_cov),str(all_C),str(all_C/(all_cov+0.0))]))
		CR_output.write("\n")
		for key in sorted(result_cov.keys()):
			C = result_C.get(key)
			cov = result_cov.get(key)
			if cov is not None and cov > 0:
				if C is None:
					C = 0
				nonCR = C/(cov+0.0)
				line = "\t".join([key,str(cov),str(C),str(nonCR)]) + "\n"
				lines.append(line)
				if cov > 1000:
					overall.append(nonCR)
		CR_output.write("#Median\t%.8f\n" % np.median(overall))
		CR_output.write("#Mean\t%.8f\n" % np.mean(overall))
		CR_output.write("#90%%\t%.8f\n" % np.percentile(overall,90))
		CR_output.write("#75%%\t%.8f\n" % np.percentile(overall,75))
		CR_output.write("#50%%\t%.8f\n" % np.percentile(overall,50))
		CR_output.write("#25%%\t%.8f\n" % np.percentile(overall,25))
		CR_output.write("#10%%\t%.8f\n" % np.percentile(overall,10))
		for line in lines:
			CR_output.write("#")
			CR_output.write(line)

def create_connection(db_file):
	if os.path.isfile(db_file):
		conn = sqlite3.connect(db_file)
	else:
		raise IOError("Database file not exist.\n")
	return conn

def search(cursor,chr,dir,pos):
	cursor.execute("SELECT gene,name,trans,isoform,biotype FROM locations WHERE chr=? AND dir=? AND pos=?",(chr,dir,pos))
	rows = cursor.fetchall()
	if rows:
		return [str(i) for i in rows[0]]
	else:
		return None

def Tideup(chr,pos_1,dir,PIPLEUPS,SURROUNDINGS):
	global cursor,output,all_C,all_cov
	#print 2,len(PIPLEUPS),len(SURROUNDINGS)
	query = search(cursor,chr,dir,pos_1)
	if query is not None:
		gene,name,trans,isoform,biotype = query
		GENE = gene
	else:
		gene,name,trans,isoform,biotype = ["NA"] * 5
		GENE = "ELSE"
	bases = sorted(Counter(zip(PIPLEUPS,SURROUNDINGS)).items(),key=lambda x:x[0][1])
	counts = {'A':0,'T':0,'C':0,'G':0,'total':0,'CT':0}
	bins = {i: {'A':0,'T':0,'C':0,'G':0,'total':0,'CT':0} for i in [1,2,3,4,5,6,7,8,9,10,15,20]}
	limits = [99999, 20, 15, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
	for (base,surr),count in bases:
		if surr > limits[-1]:
			while surr > limits[-1]:
				index = limits.pop()
				bins[index] = copy.copy(counts)

		if base != "N":
			counts["total"] += count
			counts[base] += count
		if base == "C" or base == "T":
			counts["CT"] += count
	for item in limits:
		bins[item] = copy.copy(counts)
	#output.write("\t".join([str(i) for i in limits])+"\n")
	#write to disk
	output.write("\t".join([chr,str(pos_1),dir,gene,name,trans,isoform,biotype])) #information
	output.write("\t")
	output.write("\t".join([str(counts['total']),str(counts['CT']),str(counts['A']),str(counts['T']),str(counts['C']),str(counts['G'])])) #Overall count
	for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 99999][:-1]:
		output.write("\t")
		output.write(str(i))
		output.write(";")
		output.write(",".join([str(bins[i]['total']),str(bins[i]['CT']),str(bins[i]['C'])])) #SP=bins[i]['total']/counts['total']
	output.write("\n")

	#Add values to result_cov and result_C
	result_C[GENE] += counts['C']
	result_cov[GENE] += counts['CT']
	all_C += counts['C']
	all_cov += counts['CT']

def check(chr,pos_1,dir,pileup,surrounding):
	global PIPLEUPS,SURROUNDINGS,last
	if not last: #first in
		last = (chr,pos_1,dir)
		PIPLEUPS.extend(pileup)
		SURROUNDINGS.extend(surrounding)
	else:
		if last == (chr,pos_1,dir): #keep putting items
			PIPLEUPS.extend(pileup)
			SURROUNDINGS.extend(surrounding)
		else: #To output
			#print 1,len(PIPLEUPS),len(SURROUNDINGS)
			Tideup(last[0],last[1],last[2],PIPLEUPS,SURROUNDINGS)
			PIPLEUPS = []
			SURROUNDINGS = []
			last = (chr,pos_1,dir)
			PIPLEUPS.extend(pileup)
			SURROUNDINGS.extend(surrounding)

if __name__ == "__main__":
	description = """
	"""
	parser = argparse.ArgumentParser(prog="",fromfile_prefix_chars='@',description=description,formatter_class=argparse.RawTextHelpFormatter)
	#Require
	group_require = parser.add_argument_group("Required")
	group_require.add_argument("-i","--input",dest="input",required=True,help="input pileup, sorted")
	group_require.add_argument("-o","--output",dest="output",required=True,help="output") #chr start_0 start
	group_require.add_argument("--CR",dest="conversion",required=True,help="gene conversion rate")
	group_require.add_argument("--db",dest="database",required=True,help="database, base-gene annotation")
	group_optional = parser.add_argument_group("Optional")
	group_optional.add_argument("-c","--coverage",dest="cov",default=10,type=int,help="coverage, default=10")
	group_optional.add_argument("-r","--ratio",dest="ratio",default=0.1,type=float,help="m5C level/ratio, default=0.1")
	group_optional.add_argument("-p","--pvalue",dest="pvalue",default=0.05,type=float,help="binomial pvalue, default=0.05")
	group_other = parser.add_argument_group("Other")
	options = parser.parse_args()

	sys.stderr.write("[%s] Reading input...\n" % strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

	database = create_connection(options.database)
	cursor = database.cursor()
	# cursor.execute("PRAGMA cache_size =8000")
	# cursor.execute("PRAGMA page_size = 8192")
	# cursor.execute("PRAGMA temp_store =2")
	# cursor.execute("PRAGMA synchronous=OFF")
	cursor.execute("PRAGMA journal_mode = WAL") #do not need a write lock while reading, so enable multiple reading

	#init
	result_cov = defaultdict(int)
	result_C = defaultdict(int)
	all_cov = 0
	all_C = 0
	PIPLEUPS= []
	SURROUNDINGS = []
	last = None
	with open(options.input,'r') as input,file(options.output+"_tmp",'w') as output:
		#10      100007581(1-based)       -       C       ENST00000260702 3519    T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
		#10      100007581       -       C       Genome  100007581       T,T,T,T,T,T,T,T,T,T,T   0,0,0,0,0,0,0,0,0,0,0
		line = input.readline()
		while (line):
			row = line.strip().split("\t")
			chr = row[0]
			pos_1 = row[1]
			dir = row[2]
			base = row[3] # as transcript
			pileup = row[6].split(",")
			surrounding = [int(i) for i in row[7].split(",")]
			if base == "C":
				check(chr,pos_1,dir,pileup,surrounding)
			line = input.readline()
		Tideup(last[0],last[1],last[2],PIPLEUPS,SURROUNDINGS)
	sys.stderr.write("[%s] Finished reading input.\n" % strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
	#get conversion rates
	write_CR()
	sys.stderr.write("[%s] Calculating conversion rates...\n" % strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
	os.system("cat %s %s > %s" % (options.conversion,options.output+"_tmp",options.output))
	os.remove(options.output+"_tmp")
	sys.stderr.write("[%s] All finished!\n" % strftime("%Y-%m-%d %H:%M:%S", time.localtime()))


# -*- coding: utf-8 -*-
"""
Create Time: 2021/1/27 15:40
Author: Kevin
"""
# -*- coding: utf-8 -*-
import os
import re
import numpy as np
import pandas as pd
from data_analysis_python.TrainingDataUtil import readConfigFile, makeFrequencySeries
from data_analysis_python.SampleProperties import SampleProperties
from data_analysis_python.VaporNoiseUtil import removeVapor,Net
from tensorflow import keras

def predictFiles(trainSampNames, fRange):
	fileName = r'D:\数据\test\xls\安工院压片202101250309.xls'
	data = pd.read_excel(fileName)
	t = data.iloc[:,0].tolist()
	ref = data.iloc[:,1].tolist()
	num_col = data.shape[1]
	seriesList = []
	width = int((fRange[1] - fRange[0]) * 100)*2
	inputShape = (1, width, 1)
	for i in range(2,num_col):
		d = float(re.findall(r"\d+\.?\d*", data.columns[i])[0])
		sp = SampleProperties(t, ref, t, data.iloc[:,i].tolist(), d)
		absorption = np.array(sp.calAbsorptionRate())
		reflection = np.array(sp.calRefractiveIndex())
		f = sp.f
		absorption = absorption[(f > fRange[0]) & (f < fRange[1])]
		reflection = reflection[(f > fRange[0]) & (f < fRange[1])]

		(_, xf) = makeFrequencySeries(t, data.iloc[:,i].tolist(), fRange[0], fRange[1])
		xf.append(absorption.tolist())
		xf1 = xf[0] + xf[1]
		x = []
		x.append(xf1)
		series = np.array(x).reshape(inputShape)
		seriesList.append(series)
	seriesList = np.array(seriesList)
	model = keras.models.load_model(workPath)
	# Classify all the series from the input file
	predicts = model.predict(seriesList)
	numSamps = len(trainSampNames)

	for predict in predicts:
		line = ""
		for i in range(numSamps):
			sampName = trainSampNames[i]
			sampPredict = predict[i]
			line += sampName + " {:.3f}".format(sampPredict)
			if i < numSamps - 1:
				line += ", "
		print(line)

if __name__ == "__main__":
	workPath = os.getcwd()
	configFileDir = os.path.join(workPath, "config2.txt")
	(_, fRange, _, _, trainSampNames, _) = readConfigFile(configFileDir)

	predictFiles(trainSampNames,fRange)