#--------------------------------
#Group No. 31
#Team Members
#Akshay Agarwal, 1141290,Melbourne
#Avi Patel,1143213,Melbourne
#Monit Patel,1135025,Melbourne
#Prabha Choudhary,1098776,Melbourne
#Shubham Parakh,1098807,Melbourne
#--------------------------------
import dash_html_components as html
import dash_core_components as dcc
import plotly.graph_objs as go
import DataExtractor as de

cities = ["Adelaide","Brisbane","Melbourne","Perth","Sydney"]

age = ["Youth","Adult","Senior-citizens"]
melbourne_count = de.age_data("Melbourne")
sydney_count = de.age_data("Sydney")
perth_count = de.age_data("Perth")
adelaide_count = de.age_data("Adelaide")
brisbane_count = de.age_data("Brisbane")

unique_user=de.unique_user_cities()

twitter = go.Pie(labels = cities,values=unique_user)
youth_data = [adelaide_count[0],brisbane_count[0],melbourne_count[0],perth_count[0],sydney_count[0]]
aurin_data = go.Bar(x=cities,y=youth_data)

tab_3_layout = html.Div([
    html.Div([
        html.H3('Distribution of twitter users across cities',style={
            'textAlign': 'center'}
        ),
        dcc.Graph(id='graph',
                  figure={
                      'data': [ twitter ]
                  },
                  style={'padding-right': '1px'}
                  )
    ], style={'width': '50%', 'display': 'inline-block'}),

    html.Div([

        html.H3('Age Demography across cities', style={
            'textAlign': 'center',
        }),
        dcc.Graph(id='graph1',
                  figure={
                      'data': [ aurin_data ]
                  }
                  ),
    ], style={'width': '50%', 'display': 'inline-block'}),

    html.Div(id='page-1-content')
])


# uncompyle6 version 3.6.7
# Python bytecode 2.6 (62161)
# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: build/bdist.linux-x86_64/egg/archipelagentvmcasting/vmcastmaker.py
# Compiled at: 2013-03-20 13:50:16
import datetime, os, uuid

class VMCastMaker:

    def __init__(self, title, uuid, description, language, baseserverurl, basepath):
        self.baseserverurl = baseserverurl
        self.basepath = basepath
        self.title = title
        self.uuid = uuid
        self.description = description
        self.language = language
        self.items = []

    def init_feed(self):
        self.feed = "<?xml version='1.0' encoding='utf-8'?>\n"
        self.feed += "   <rss version='2.0'>\n"
        self.feed += '   <channel>\n'
        self.feed += '        <title>' + self.title + '</title>\n'
        self.feed += '        <link>' + self.baseserverurl + '</link>\n'
        self.feed += '        <uuid>' + self.uuid + '</uuid>\n'
        self.feed += '        <description>' + self.description + '</description>\n'
        self.feed += '        <language>' + self.language + '</language>\n'

    def add_item(self, title, description, link, uuid, dlurl, size):
        self.items.append({'title': title, 'description': description,
           'link': link,
           'uuid': uuid,
           'dlurl': dlurl,
           'size': size})

    def makeVMCast(self):
        for item in self.items:
            item_string = '        <item>\n'
            item_string += '            <title>' + item['title'] + '</title>\n'
            item_string += '            <link>' + item['link'] + '</link>\n'
            item_string += '            <uuid>' + item['uuid'] + '</uuid>\n'
            item_string += "            <enclosure url='" + item['dlurl'] + "' length='" + item['size'] + "' type='application/enomalism2-xvm2'/>\n"
            item_string += '            <description>\n            <![CDATA[\n                ' + item['description'] + '\n            ]]>\n            </description>\n'
            item_string += '            <pubDate>' + str(datetime.datetime.now()) + '</pubDate>\n'
            item_string += '        </item>\n'
            self.feed += item_string

        self.feed += '    </channel>\n</rss>'
        return self.feed

    def writeFeed(self, path='./rss.xml'):
        f = open(path, 'w')
        f.write(self.makeVMCast())
        f.close()

    def parseDirectory(self, path='.'):
        self.init_feed()
        self.items = []
        xvm2_files = [ x for x in os.listdir(path) if x.endswith('.xvm2') ]
        for xvm2_file in xvm2_files:
            size = os.path.getsize(path + '/' + xvm2_file)
            item_uuid = uuid.uuid3(uuid.NAMESPACE_URL, xvm2_file)
            self.add_item(xvm2_file.replace('.xvm2', ''), 'Auto imported vmcast', self.baseserverurl, str(item_uuid), self.baseserverurl + '/' + xvm2_file, str(size))


from mathutils import *
from plotutils import *

class BPM():
    bpm1_vert_CF=49
    bpm1_hor_CF=49*0.793
    bpm2_vert_CF=13
    bpm2_hor_CF=13*0.707
    bpm3_vert_CF=8.6
    bpm3_hor_CF=8.6*0.707
    bpm4_vert_CF=9.5
    bpm4_hor_CF=9.5
    roiposx=0
    roiposy=0
    roisizex=0
    roisizey=0
    cam_exposure=0
    cam_gain=0
    sig2fwmh=2.355

    def __print_info(self, label, a, b, amp, com, sigma, conv_fact, comabs):
        print("*** " + label + " Gaussian Fit ***:")
        print("   Inclination: " + '{:.3e}'.format(a))
        print("    Background: " + '{:.3f}'.format(b))
        print("     Amplitude: " + '{:.3f}'.format(amp))
        print("         Sigma: " + '{:.3f}'.format(sigma))
        print("          FWHM: " + '{:.3f}'.format(self.sig2fwmh*sigma))
        print("          Mean: " + '{:.3f}'.format(comabs))
        print("     Sigma(um): " + '{:.3f}'.format(sigma*conv_fact))
        print("      FWHM(um): " + '{:.3f}'.format(sigma*conv_fact*self.sig2fwmh))

    def BPM1_Vertical_Profile(self):
        label = "BPM1 Vertical Profile"
        print("Analysing...")
        self.__grabdata_bpm1()
        vec = caget("PINK:PG01:Stats2:ProfileAverageY_RBV")
        N = int(self.roisizey)
        pos0 = self.roiposy
        pos1 = self.roiposy+self.roisizey
        myCF = self.bpm1_vert_CF
        filename="bpm1_ver"
        self.__bpmanalysis(vec, pos0, pos1, N, label, filename, myCF)

    def BPM1_Horizontal_Profile(self):
        label = "BPM1 Horizontal Profile"
        print("Analysing...")
        self.__grabdata_bpm1()
        vec = caget("PINK:PG01:Stats2:ProfileAverageX_RBV")
        N = int(self.roisizex)
        pos0 = self.roiposx
        pos1 = self.roiposx+self.roisizex
        myCF = self.bpm1_hor_CF
        filename="bpm1_hor"
        self.__bpmanalysis(vec, pos0, pos1, N, label, filename, myCF)

    def BPM2_Vertical_Profile(self):
        label = "BPM2 Vertical Profile"
        print("Analysing...")
        self.__grabdata_bpm2()
        vec = caget("PINK:PG04:Stats2:ProfileAverageY_RBV")
        N = int(self.roisizey)
        pos0 = self.roiposy
        pos1 = self.roiposy+self.roisizey
        myCF = self.bpm2_vert_CF
        filename="bpm2_ver"
        self.__bpmanalysis(vec, pos0, pos1, N, label, filename, myCF)

    def BPM2_Horizontal_Profile(self):
        label = "BPM2 Horizontal Profile"
        print("Analysing...")
        self.__grabdata_bpm2()
        vec = caget("PINK:PG04:Stats2:ProfileAverageX_RBV")
        N = int(self.roisizex)
        pos0 = self.roiposx
        pos1 = self.roiposx+self.roisizex
        myCF = self.bpm2_hor_CF
        filename="bpm2_hor"
        self.__bpmanalysis(vec, pos0, pos1, N, label, filename, myCF)

    def BPM3_Vertical_Profile(self):
        label = "BPM3 Vertical Profile"
        print("Analysing...")
        self.__grabdata_bpm3()
        vec = caget("PINK:PG03:Stats2:ProfileAverageY_RBV")
        N = int(self.roisizey)
        pos0 = self.roiposy
        pos1 = self.roiposy+self.roisizey
        myCF = self.bpm3_vert_CF
        filename="bpm3_ver"
        self.__bpmanalysis(vec, pos0, pos1, N, label, filename, myCF)

    def BPM3_Horizontal_Profile(self):
        label = "BPM3 Horizontal Profile"
        print("Analysing...")
        self.__grabdata_bpm3()
        vec = caget("PINK:PG03:Stats2:ProfileAverageX_RBV")
        N = int(self.roisizex)
        pos0 = self.roiposx
        pos1 = self.roiposx+self.roisizex
        myCF = self.bpm3_hor_CF
        filename="bpm3_hor"
        self.__bpmanalysis(vec, pos0, pos1, N, label, filename, myCF)

    def BPM4_Vertical_Profile(self):
        label = "BPM4 Vertical Profile"
        print("Analysing...")
        self.__grabdata_bpm4()
        vec = caget("PINK:PG02:Stats2:ProfileAverageY_RBV")
        N = int(self.roisizey)
        pos0 = self.roiposy
        pos1 = self.roiposy+self.roisizey
        myCF = self.bpm4_vert_CF
        filename="bpm4_ver"
        self.__bpmanalysis(vec, pos0, pos1, N, label, filename, myCF)

    def BPM4_Horizontal_Profile(self):
        label = "BPM4 Horizontal Profile"
        print("Analysing...")
        self.__grabdata_bpm4()
        vec = caget("PINK:PG02:Stats2:ProfileAverageX_RBV")
        N = int(self.roisizex)
        pos0 = self.roiposx
        pos1 = self.roiposx+self.roisizex
        myCF = self.bpm4_hor_CF
        filename="bpm4_hor"
        self.__bpmanalysis(vec, pos0, pos1, N, label, filename, myCF)

    def __grabdata_bpm1(self):
        self.roiposx = caget("PINK:PG01:ROI1:MinX_RBV")
        self.roiposy = caget("PINK:PG01:ROI1:MinY_RBV")
        self.roisizex = caget("PINK:PG01:ROI1:SizeX_RBV")
        self.roisizey = caget("PINK:PG01:ROI1:SizeY_RBV")
        self.cam_exposure = caget("PINK:PG01:AcquireTime_RBV")
        self.cam_gain = caget("PINK:PG01:Gain_RBV")

    def __grabdata_bpm2(self):
        self.roiposx = caget("PINK:PG04:ROI1:MinX_RBV")
        self.roiposy = caget("PINK:PG04:ROI1:MinY_RBV")
        self.roisizex = caget("PINK:PG04:ROI1:SizeX_RBV")
        self.roisizey = caget("PINK:PG04:ROI1:SizeY_RBV")
        self.cam_exposure = caget("PINK:PG04:AcquireTime_RBV")
        self.cam_gain = caget("PINK:PG04:Gain_RBV")

    def __grabdata_bpm3(self):
        self.roiposx = caget("PINK:PG03:ROI1:MinX_RBV")
        self.roiposy = caget("PINK:PG03:ROI1:MinY_RBV")
        self.roisizex = caget("PINK:PG03:ROI1:SizeX_RBV")
        self.roisizey = caget("PINK:PG03:ROI1:SizeY_RBV")
        self.cam_exposure = caget("PINK:PG03:AcquireTime_RBV")
        self.cam_gain = caget("PINK:PG03:Gain_RBV")

    def __grabdata_bpm4(self):
        self.roiposx = caget("PINK:PG02:ROI1:MinX_RBV")
        self.roiposy = caget("PINK:PG02:ROI1:MinY_RBV")
        self.roisizex = caget("PINK:PG02:ROI1:SizeX_RBV")
        self.roisizey = caget("PINK:PG02:ROI1:SizeY_RBV")
        self.cam_exposure = caget("PINK:PG02:AcquireTime_RBV")
        self.cam_gain = caget("PINK:PG02:Gain_RBV")

    def __bpmanalysis(self, vec, pos0, pos1, N, label, filename, myCF):

        vecb = vec[0:N]
        xvecabs = range(pos0,pos1)
        xvec = range(0,N)
        weights = [ 1.0] * len(xvec)
        #pl = plot(vecb, label , xvec)[0]
        pl = plot(vecb, label, xvecabs)[0]
        pl.setLegendVisible(True)
        (a, b, amp, com, sigma) = fit_gaussian_linear(vecb, xvec, None, weights)
        self.__print_info(label, a, b, amp, com, sigma, myCF, com+pos0)
        ff = Gaussian(amp, com, sigma)
        gauss = [ff.value(i) + a*i + b for i in xvec]
        ss = LinePlotSeries("Gaussian Fit")
        pl.addSeries(ss)
        #ss.setData(xvec, gauss)
        ss.setData(xvecabs, gauss)
        self.__setup_file(fname=filename)
        self.__Save_Data(label, myCF, a, b, amp, com, com+pos0, sigma, sigma*self.sig2fwmh, sigma*myCF, sigma*self.sig2fwmh*myCF, xvecabs, vecb, gauss)
        ## save beamline/station snapshot
        pink_save_bl_snapshot()
        print("Done")

    def __setup_file(self, fname="bpm"):
        set_exec_pars(open=False, name=fname, reset=True)

    def __Save_Data(self, label, CV, ga, gb, gamp, gmean, gmeanabs, gsigma, gfwhm, gsigmaum, gfwhmum, xdata, yprofile, ygauss):
        save_dataset("info/bpm", label)
        save_dataset("camera/exposure", self.cam_exposure)
        save_dataset("camera/gain", self.cam_gain)
        save_dataset("camera/conv_factor", CV)
        save_dataset("ROI/MinX", self.roiposx)
        save_dataset("ROI/MinY", self.roiposy)
        save_dataset("ROI/SizeX", self.roisizex)
        save_dataset("ROI/SizeY", self.roisizey)
        save_dataset("gaussian/inclination", ga)
        save_dataset("gaussian/background", gb)
        save_dataset("gaussian/amplitude", gamp)
        save_dataset("gaussian/mean_roi", gmean)
        save_dataset("gaussian/mean_absolute", gmeanabs)
        save_dataset("gaussian/sigma", gsigma)
        save_dataset("gaussian/FWHM", gfwhm)
        save_dataset("gaussian/sigma_um", gsigmaum)
        save_dataset("gaussian/FWHM_um", gfwhmum)
        save_dataset("plot/xdata", xdata)
        save_dataset("plot/profile", yprofile)
        save_dataset("plot/gauss_fit", ygauss)


"""Program to calculate vacation cost."""

def answer():
    """Return 42 always."""
    return 42

def hotel_cost(nights):
    """Return total hotel cost of $140 per night."""
    return 140.0 * nights

def plane_ride_cost(city):
    """Return the airfare for the trip."""
    city = city.lower()
    cost = {'charlotte': 183.0,
            'tampa': 222.0,
            'pittsburgh': 222.0,
            'los angeles': 475.0}

    return cost[city]

def rental_car_cost(days):
    """Calculate the cost of a retal car."""
    car_cost = 40.0 * days
    if days >= 7:
        car_cost = car_cost - 50.0
    elif days >= 3:
        car_cost = car_cost - 20.0

    return car_cost

def trip_cost(city, days, spending_money=0):
    """Calculate the total vacation cost."""
    total = (hotel_cost(days) +
             plane_ride_cost(city) +
             rental_car_cost(days) +
             spending_money)

    return total

print (trip_cost("Los Angeles", 5, 600))


from __future__ import absolute_import, division, print_function

import os
import time
import tempfile
import shutil
import random
import subprocess
from functools import partial
from threading import Thread
import unittest
import hashlib

from tornado.escape import json_encode,json_decode
from tornado.ioloop import IOLoop
import requests
from pymongo import MongoClient

from file_catalog.urlargparse import encode as jquery_encode

class TestServerAPI(unittest.TestCase):
    def setUp(self):
        self.tmpdir = tempfile.mkdtemp(dir=os.getcwd())
        self.addCleanup(partial(shutil.rmtree, self.tmpdir))
        self.address = 'http://localhost:8888'
        self.mongo_port = random.randint(10000,50000)
        dbpath = os.path.join(self.tmpdir,'db')
        os.mkdir(dbpath)
        dblog = os.path.join(dbpath,'logfile')

        if 'TEST_DATABASE_HOST' not in os.environ:
            m = subprocess.Popen(['mongod', '--port', str(self.mongo_port),
                                  '--dbpath', dbpath, '--smallfiles',
                                  '--quiet', '--nounixsocket',
                                  '--logpath', dblog])
            self.addCleanup(partial(time.sleep, 0.3))
            self.addCleanup(m.terminate)

    def clean_db(self, host, port):
        db = MongoClient(host=host, port=port).file_catalog
        colls = db.list_collection_names()
        for c in colls:
            if 'system' not in c:
                db.drop_collection(c)

    def start_server(self, config_override={}):
        env = dict(os.environ)
        env.update(config_override)
        env['MONGODB_PORT'] = str(self.mongo_port)
        env['DEBUG'] = '1'

        if 'TEST_DATABASE_HOST' in os.environ:
            env['MONGODB_HOST'] = os.environ['TEST_DATABASE_HOST']
        if 'TEST_DATABASE_PORT' in os.environ:
            env['MONGODB_PORT'] = os.environ['TEST_DATABASE_PORT']
        self.clean_db(env['MONGODB_HOST'], int(env['MONGODB_PORT']))
        s = subprocess.Popen(['python', '-m', 'file_catalog'], env=env)
        self.addCleanup(s.terminate)
        time.sleep(2)

    def get_token(self):
        if 'TOKEN_URL' in os.environ:
            r = requests.get(os.environ['TOKEN_URL']+'/token?scope=file_catalog')
            r.raise_for_status()
            return r.json()['access']
        else:
            raise Exception('testing token service not defined')

    def test_01_HATEOAS(self):
        self.start_server()
        r = requests.get(self.address+'/api')
        r.raise_for_status()
        data = r.json()
        self.assertIn('_links', data)
        self.assertIn('self', data['_links'])
        self.assertIn('files', data)

        for m in ('post','put','delete','patch'):
            r = getattr(requests, m)(self.address+'/api')
            with self.assertRaises(Exception):
                r.raise_for_status()

    def test_05_login(self):
        self.start_server()
        r = requests.get(self.address+'/login')
        r.raise_for_status()

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestStringMethods)
    unittest.TextTestRunner(verbosity=2).run(suite)


'''
    报告：
        1.加载器：加载所有测试用例并得到所有用例
        2.使用运行器运行这些测试用例并生成报告
    任务2：
        减乘除：进行测试（）
        实现报告的邮件发送
'''
from HTMLTestRunner import HTMLTestRunner  # 运行器
import unittest

# 1.加载所有用例
tests = unittest.defaultTestLoader.discover(r"D:\python\110",pattern="test*.py")

# 2.使用运行器
runner = HTMLTestRunner.HTMLTestRunner(
    title = "这是一份银行的测试报告",
    description="工商银行的测试报告",
    verbosity=1,
    stream= open("银行.html",mode="w+",encoding="utf-8")
)

# 3.运行所有用例
runner.run(tests)

# 4.实现邮件发送


from collections import deque
class PrefixTree():

	def __init__(self, nullNode):
		self.root = nullNode

	def addNode(self, parent, value):
		alreadyThere = False
		for child in parent.children:
			if child.element == value:
				child.count += 1
				alreadyThere = True
		if not alreadyThere:
			newKids = []
			newNode = TreeNode(value, parent, newKids)
			parent.children.append(newNode)

	def removeNode(self, value):
		q = deque(self.root.getChildren())
		current = q.pop()
		while current != None:
			if current.element == value:
				current.parent.children.remove(current)
			elif current.getChildren != None:
				for child in current.getChildren:
					q.append(child)

			current = q.pop()

	def buildPath(self, word):
		next = self.root
		for i in range(1, len(word)+1):
			current = next
			if len(current.children) == 0:
				newNode = TreeNode(word[0:i], current, [])
				current.addChild(newNode)
				next = newNode
			else :
				alreadyThere = False
				for child in current.children:
					if child.element == word[0:i]:
						alreadyThere = True
						next = child
						child.unique = False
				if not alreadyThere:
					newNode = TreeNode(word[0:i], current, [])
					current.addChild(newNode)
					next = newNode

	def buildTree(self, wordList):
		for word in wordList:
			self.buildPath(word)

	def printTree(self):
		q = deque(self.root.getChildren())
		current = q.popleft()
		while current != None:
			print(current.unique)
			print(current.element)
			print([item.element for item in current.getChildren()])
			print("\n")
			for child in current.getChildren():
				q.append(child)
			if len(q) > 0:
				current = q.popleft()
			else:
				current = None

	def uniquePrefixes(self):
		uniques = []
		q = deque(self.root.getChildren())
		current = q.popleft()
		while current != None:
			if current.unique == True:
				uniques.append(current.element)
			else:
				for child in current.getChildren():
					q.append(child)
			if len(q) > 0:
				current = q.popleft()
			else:
				current = None
		return uniques

class TreeNode():

	def __init__(self, value, ancestor, kids):
		self.element = value
		self.parent = ancestor
		self.children = kids
		self.unique = True

	def getChildren(self):
		return self.children

	def getParent(self):
		return self.parent

	def addChild(self, node):
		self.children.append(node)


x = int(input("please enter the value of 'x': "))
y = int(input("please enter the value of 'y': "))

isEven = x % 2 == 0

choice = input('\nMenu:\n(E)ven\n(O)dd\n(S)quared\n(Q)uit\n').upper()
while choice != 'Q':
    if choice == 'E':
        # even
        print('Even numbers')
        for i in range(x, y + 1, 2):
            if not isEven:
                print(i + 1, end=' ')
            else:
                print(i, end=' ')
    elif choice == 'O':
        # odd
        print('\nOdd numbers')
        for i in range(x, y + 1, 2):
            if isEven:
                print(i + 1, end=' ')
            else:
                print(i, end=' ')
    elif choice == 'S':
        # squared
        print('\nsquared numbers')
        for i in range(x, y):
            print(i ** 2, end=' ')
    else:
        print('Invalid option')

    choice = input('Menu:\n(E)ven\n(O)dd\n(S)quared\n(Q)uit\n').upper()
print('Finished.')


import numpy as np

#rpi_gpio_out = 0
# lbo = 0
# bri = 0
# initial_waiting_time = 2 #in seconds
#x = np.zeros(fs*initial_waiting_time)

# def master_timer(lbo, bri):
# 	global rpi_gpio_out
# 	rpi_gpio_out = 0
# 	time.sleep(bri)
# 	rpi_gpio_out = 1

def matlab_buffer(list,grp,overlap):
	z=(grp-len(list)%(grp-overlap))%grp
	list=list+[0]*z
	return [list[i:i+grp] for i in range(0,len(list)-overlap,grp-overlap)]

def adapt_threshold(df,pre=8,post=7):
	N=len(df)
	m=[]
	for i in range(0,min(post, N)):
		k = min(i + pre, N)
		m = np.append(m,np.mean(df[0:k]))

	if N > (post + pre):
		m = np.append(m,np.mean(np.array(matlab_buffer(df, post + pre + 1, post + pre)),axis=1))

	for i in range(N-pre,N):
		j = max(i - post, 1)-1
		m = np.append(m,np.mean(df[j:len(df)-1]))
	df1=np.zeros(len(df))
	np.subtract(np.array(df),np.array(m),df1)
	return (df1>0)*df1

def onset_detection(x, xold, theta1, theta2, oldmag, fs=44100):
	x=np.append(xold,x)
	x=np.diff(x)
	o_step  	= 1024
	o_win_len   = o_step * 2
	win_hann 	= np.hanning(o_win_len)
	df = []
	x_fft	= np.fft.fft(win_hann*x)
	x_fft	= x_fft[0:np.int(len(x_fft)/2)]
	mag   = (np.absolute(x_fft))
	theta = np.angle(x_fft)
	dev   = ((theta-2*theta1+theta2 + np.pi) %  (-2 * np.pi)) + np.pi
	meas  = oldmag - (mag*np.exp(1j* dev))
	df = np.sum(np.sqrt(np.power((np.real(meas)),2) + np.power((np.imag(meas)),2)))
	return (df, theta, theta1, mag)

def part_adapt_thresh(inp):
	m=np.mean(inp);
	inp=inp-m
	out=inp*(inp>0)
	return out


# 千万不要再傻乎乎地在pandas里面写for循环，记住用map、apply、applymap三大函数！！！！！！

import pandas as pd
import csv

txt = pd.read_table("zzz_all.txt",sep="\t")
txt["number"] = txt.index
txt = txt.drop_duplicates(subset=['ORF_ID', 'strand', 'ORF_length', 'ORF_gstart', 'ORF_gstop', 'AAseq'],keep="first")
txt = txt[txt["ORF_length"]<=300]
#给txt文件加上编号，并去重复行
txt.to_csv("zzz_merge.txt",sep="\t",header=True,index=False)

gtf = pd.read_table("zzz_all.gtf",sep="\t",header=None)
gtf["number"] = 0
gtf.iloc[gtf[gtf[2]=="ORF"].index,9] = 1
gtf["Number"] = gtf["number"].cumsum()
gtf["Number"] = gtf["Number"] - 1
#number = -1
#for i in gtf.index:
#    if gtf.iloc[i,2] == "ORF":number +=1
#    gtf.iloc[i,9] = number
#给gtf文件加上编号
f = lambda e,l : (e in l)
overlap = gtf["Number"].apply(f,args=(txt["number"],))
#gtf的number列的行号是否在txt的number列中，输出True or False到overlap列表里面
gtf = gtf[overlap]
#gtf = gtf.iloc[:,0:9]
gtf.drop("number",axis=1,inplace=True)
gtf.to_csv("zzz_merge.gtf",sep="\t",header=False,index=False,quoting=csv.QUOTE_NONE)


from db import Database
from query import fetch_session, fetch_touchevent, fetch_sensordata
from models import Grid

import pandas as pd
import numpy as np

import argparse

def filter_touchevents(te):
    # only consider touch down events
    te = te[te['type'] == 'TOUCH_DOWN']
    # only consider hits
    te = te[te['is_hit']]
    return te

def feature_normalize(dataset):
    mu = np.mean(dataset, axis=0)
    sigma = np.std(dataset, axis=0)
    return (dataset - mu) / sigma

def query_sessions(db, userid):
    session_query = fetch_session(userid)
    df = db.query(session_query)
    return df

def query_and_normalize_dataframes(db, user_id, session_code):
    q_touch_event = fetch_touchevent(user_id, session_code)
    touch_event_df = db.query(q_touch_event)

    # filter on touch down
    touch_event_df = filter_touchevents(touch_event_df)

    q_sensor_q = fetch_sensordata(user_id, session_code, 'GYROSCOPE')
    g_sensor_df = db.query(q_sensor_q)
    for axis in ['x', 'y', 'z']:
        g_sensor_df[axis] = feature_normalize(g_sensor_df[axis])

    a_sensor_q = fetch_sensordata(user_id, session_code, 'ACCELEROMETER')
    a_sensor_df = db.query(a_sensor_q)
    for axis in ['x', 'y', 'z']:
        a_sensor_df[axis] = feature_normalize(a_sensor_df[axis])

    if g_sensor_df.empty or a_sensor_df.empty or touch_event_df.empty:
        # in case of an empty data frame continue with the program.
        return None

    return touch_event_df, g_sensor_df, a_sensor_df

def remove_duplicates(t_df, g_df, a_df):
    """Removes duplicates on given data frames"""
    subset = ['timestamp', 'user_id']
    t_df = t_df.drop_duplicates(subset=subset)
    g_df = g_df.drop_duplicates(subset=subset)
    a_df = a_df.drop_duplicates(subset=subset)
    return t_df, g_df, a_df

def create_session_dataframe(db, session_df, user_id):
    grid_dfs = []

    # iterate over every session of user
    for index, row in session_df.iterrows():

        session_code = row['session_code']

        touch_event_df, g_sensor_df, a_sensor_df = query_and_normalize_dataframes(db, user_id, session_code)
        touch_event_df, g_sensor_df, a_sensor_df = remove_duplicates(touch_event_df, g_sensor_df, a_sensor_df)

        # iterate over gridshapes
        grid_shapes = np.unique(touch_event_df['grid_shape'].values).tolist()

        for shape in grid_shapes:
            grid = Grid(shape, user_id)
            grid.setup(touch_event_df, a_sensor_df, g_sensor_df)
            grid_df = grid.to_df(save=False)

            # add columns
            grid_df['device_model'] = row['device_model']
            grid_df['lab_mode'] = row['lab_mode']
            grid_df['body_posture'] = row['body_posture']
            grid_df['typing_modality'] = row['typing_modality']
            grid_df['hand'] = row['hand']
            grid_df['mood'] = row['mood']
            grid_df['grid_shape'] = str(shape)
            grid_df['session_id'] = str(user_id) + '-' + str(index)
            grid_df['session_code'] = session_code

            grid_dfs.append(grid_df)

    return pd.concat(grid_dfs)

def main():
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument(
        "-u", "--user", dest="user",
        help="user id of the user to query", type=int, required=True
    )
    parser.add_argument(
        "-o", "--out", dest="out",
        help="destination of the output file", metavar="FILE", required=True
    )

    args = parser.parse_args()

    # create Database
    db = Database()

    session_df = query_sessions(db, args.user)
    dataframe = create_session_dataframe(db, session_df, args.user)
    dataframe.to_csv(args.out)

    # close database connection
    del db

if __name__ == '__main__':
    main()


#!/usr/bin/python3
# -*- coding:utf-8 -*-
# from get_comment import SQL
import io
import os
import sys

from jieba.analyse import ChineseAnalyzer
from whoosh.fields import *
from whoosh.index import create_in
from whoosh.index import open_dir
from whoosh.qparser import QueryParser

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# 导入中文分词工具
analyser = ChineseAnalyzer()
# 创建索引结构: 没有结构，就是很多文本文件，一行一行的，总之很多行
schema = Schema(full_line=TEXT(stored=True, analyzer=analyser))
# 数据和索引所在目录，以及索引名称
ix = create_in("shegongku_idx", schema=schema, indexname='allin1line')

# 返回root下的文件列表（不包含子目录）
def traverseFile(root):
    flist = []
    for f in os.listdir(root):
        f_path = os.path.join(root, f)
        if os.path.isfile(f_path):
            flist.append(f_path)
            print(f_path)
        else:
            flist += traverseFile(f_path)
    return flist

# 处理数据文件，每个文件每一行，加进去
writer = ix.writer()
for fn in traverseFile("shegongku_db"):
    with open(fn, 'r', encoding='utf-8') as f:
        print(fn, "...")
        lines = 0
        while True:
            line1 = f.readline()
            if line1:
                writer.add_document(full_line=line1)
                lines += 1
            else:
                break
        print(fn, lines, "added")
writer.commit()
print("index finished")
# 以上为建立索引的过程

index1 = open_dir("shegongku_idx", indexname='allin1line')
parser1 = QueryParser("full_line", index1.schema)
while True:
    with index1.searcher() as searcher:
        print("pls input what u want to search:")
        key = input()
        myquery = parser1.parse(key)
        resultss = searcher.search(myquery, limit=2000)
        # print(type(resultss))
        for result1 in resultss:
            d1 = dict(result1)['full_line']
            print(d1)


#!/usr/bin/env python
'''
Project: Parser
Author: Spencer Rathbun
Date: 1/24/2012
Summary: Parser. See the readme for details. Originally from http://code.google.com/p/pyparser/source/browse/pycparser/c_parser.py
'''
import re, logging
import ply.yacc

from Lexer import Lexer
from Helpers import PLYParser

class Parser(PLYParser):
	def __init__(
			self,
			lex_optimize=True,
			lextab='pyparser.lextab',
			yacc_optimize=True,
			yacctab='pyparser.yacctab',
			yacc_debug=False):
		""" Create a new parser.

			Some arguments for controlling the debug/optimization
			level of the parser are provided. The defaults are
			tuned for release/performance mode.
			The simple rules for using them are:
			*) When tweaking the lexer/parser, set these to False
			*) When releasing a stable parser, set to True

			lex_optimize:
				Set to False when you're modifying the lexer.
				Otherwise, changes in the lexer won't be used, if
				some lextab.py file exists.
				When releasing with a stable lexer, set to True
				to save the re-generation of the lexer table on
				each run.

			lextab:
				Points to the lex table that's used for optimized
				mode. Only if you're modifying the lexer and want
				some tests to avoid re-generating the table, make
				this point to a local lex table file (that's been
				earlier generated with lex_optimize=True)

			yacc_optimize:
				Set to False when you're modifying the parser.
				Otherwise, changes in the parser won't be used, if
				some parsetab.py file exists.
				When releasing with a stable parser, set to True
				to save the re-generation of the parser table on
				each run.

			yacctab:
				Points to the yacc table that's used for optimized
				mode. Only if you're modifying the parser, make
				this point to a local yacc table file

			yacc_debug:
				Generate a parser.out file that explains how yacc
				built the parsing table from the ammar.
		"""
		self.logger = logging.getLogger('parser')
		self.lex = Lexer(
			error_func=self._lex_error_func,
			type_lookup_func=self._lex_type_lookup_func)

		self.lex.build(
			optimize=lex_optimize,
			lextab=lextab)
		self.tokens = self.lex.tokens

		self.parser = ply.yacc.yacc(
			module=self,
			start='statements',
			debug=yacc_debug,
			optimize=yacc_optimize,
			tabmodule=yacctab)

		self.addresses = []
		self.accounts = {}
		self.statements = 0
		self.totalPages = 0

		self.pdf_doc = PDFDoc()
		self.pdf_doc.InitSecurityHandler()
		self.timesRoman = Font.Create(self.pdf_doc.GetSDFDoc(), Font.e_times_roman, True)
		self.courierNew = Font.Create(self.pdf_doc.GetSDFDoc(), Font.e_courier, True)
		self.eb = ElementBuilder()
		self.writer = ElementWriter()

	def parse(self, text, filename='', debuglevel=0):
		""" Parses a file and returns a pdf.

			text:
				A string containing the C source code

			filename:
				Name of the file being parsed (for meaningful
				error messages)

			debuglevel:
				Debug level to yacc
		"""
		self.lex.filename = filename
		self.lex.reset_lineno()
		self._scope_stack = [set()]
		self.logger.info("_______________________________________________")
		self.logger.info("parsing input...")
		if not text or text.isspace():
			return []
		else:
			self.logger.info("_______________________________________________")
			self.logger.info("finished parsing input file...")
			return self.parser.parse(text, lexer=self.lex, debug=debuglevel)

	######################--   PRIVATE   --######################

	##
	## Precedence and associativity of tokens
	##
	precedence = (
			('left', 'LINENO'),
			('left', 'STARTPAGE'),
	)

	def _lex_error_func(self, msg, line, column):
		self._parse_error(msg, self._coord(line, column))

	def _lex_type_lookup_func(self, name):
		""" Looks up types that were previously defined with
			typedef.
			Passed to the lexer for recognizing identifiers that
			are types.
		"""
		return self._is_type_in_scope(name)

	def p_empty(self, p):
		'empty : '
		p[0] = ''

	def p_error(self, p):
		if p:
			self._parse_error(
				'before: %s' % p.value,
				self._coord(p.lineno))
		else:
			self._parse_error('At end of input', '')

	def p_statements(self, p):
		'''statements : statements pagelist
                      | pagelist'''
		pass

	def p_pagelist(self, p):
		'''pagelist : addrpage
                    | page'''
		pass

	def p_addrpage(self, p):
		'''addrpage : STARTPAGE lines address lines'''
		if self.addresses[-1].find('******************') == -1:
			self.totalPages += 1
			self.statements += 1
			pagestr = ''
			for s in p[2:]:
				pagestr = "{0}{1}".format(pagestr, s)
			self.buildNewPage(pagestr)

			# add new entry to accts
			self.accounts[str(self.statements)] = [1, [str(self.totalPages)], self.addresses[-1], [], None]

	def p_page(self, p):
		'''page : STARTPAGE lines'''
		if self.addresses[-1].find('******************') == -1:
			self.totalPages += 1
			pagestr = ''
			for s in p[2:]:
				pagestr = "{0}{1}".format(pagestr, s)
			self.buildNewPage(pagestr)
			self.accounts[str(self.statements)][0] = self.accounts[str(self.statements)][0] + 1
			self.accounts[str(self.statements)][1].append(str(self.totalPages))

	def p_address(self, p):
		'''address : beginaddress lines stopaddress'''
		self.addresses.append(p[2])
		p[0] = "{0}{1}{2}".format(p[1], p[2], p[3])

	def p_lines(self, p):
		'''lines : lines line
                 | line'''
		if len(p) > 2:
			p[0] = "{0}{1}".format(p[1], p[2])
		else:
			p[0] = p[1]

	def p_line(self, p):
		'''line : linedata LINENO
		        | LINENO'''
		if len(p) == 3:
			p[0] = "{0}\n".format(p[1])
		else:
			p[0] = "\n"

	def p_linedata(self, p):
		'''linedata : linedata WHITESPACE
				| linedata NUMBER
				| linedata TEXT
				| empty'''
		if len(p) == 3:
			p[0] = "{0}{1}".format(p[1], p[2])
		else:
			p[0] = "{0}".format(p[1])

	def p_beginaddress(self, p):
		'''beginaddress : linedata STARTADDRESS LINENO
                        | linedata STARTADDRESS linedata LINENO'''
		if len(p) == 4:
			p[0] = "{0}{1}\n".format(p[1], p[2])
		else:
			p[0] = "{0}{1}{2}\n".format(p[1], p[2], p[3])

	def p_stopaddress(self, p):
		'''stopaddress : linedata ENDADDRESS LINENO
                       | linedata ENDADDRESS linedata LINENO'''
		if len(p) == 4:
			p[0] = "{0}{1}\n".format(p[1], p[2])
		else:
			p[0] = "{0}{1}{2}\n".format(p[1], p[2], p[3])

	######################--   PDF BUILDING    --################

	def buildNewPage(self, pagestr):
		"""Create a new page and add the string contents as text elements."""
		self.logger.debug("building page {0}...".format(self.totalPages))
		page = self.pdf_doc.PageCreate(Rect(0, 0, 612, 794))
		self.writer.Begin(page)
		self.eb.Reset()

		# begin writing text elements to the current page
		element = self.eb.CreateTextBegin(self.courierNew, 8)
		element.SetTextMatrix(1, 0, 0, 1, 30, 750) # last two digits are x, y coords on page measured from LOWER RIGHT corner
		self.writer.WriteElement(element)

		# loop over the split string and write each line
		for item in pagestr.split('\n'):
			element = self.eb.CreateTextRun(item)
			element.GetGState().SetLeading(10)         # Set the spacing between lines
			self.writer.WriteElement(element)
			self.writer.WriteElement(self.eb.CreateTextNewLine())

		self.writer.WriteElement(self.eb.CreateTextEnd())
		self.writer.End()
		# add the page to the document
		self.pdf_doc.PagePushBack(page)

	def savePDF(self, filename):
		"""Save the current pdf with the input filename."""
		self.logger.debug("saving {0}...".format(filename))
		self.pdf_doc.Save(filename, SDFDoc.e_compatibility)

	def closePDF(self):
		"""Close the current pdf."""
		self.pdf_doc.Close()

#------------------------------------------------------------------------------
if __name__ == "__main__":
	PDFNet.Initialize('L & D Mail Masters(ldmailmasters.com):CPU:1::W:AMC(20120118):3D4E42F925150FCAF1B425461F9C92CA03BA1CA4C9900B3699D039F1F0FA')
	filename = 'test data/Gold Reserve -test file.txt'
	text = open(filename).read()
	parser = Parser(lex_optimize=False, yacc_debug=True, yacc_optimize=False)
	#sys.write(time.time() - t1)

	#buf = '''
		#int (*k)(int);
	#'''

	## set debuglevel to 2 for debugging
	t = parser.parse(text, filename=filename, debuglevel=2)
	parser.savePDF('test.pdf')
	parser.closePDF()


#===========================================================================
#
# Command line processing
#
#===========================================================================

import argparse
from .. import broker
from . import config
from . import start

#===========================================================================

def run( args ):
   """Parse command line arguments to poll the inverter.

   = INPUTS
   - args   [str]: List of command line arguments.  [0] should be the
            program name.
   """
   p = argparse.ArgumentParser( prog=args[0],
                                description="SMA inverter reader" )
   p.add_argument( "-c", "--configDir", metavar="configDir",
                   default="/var/config/tHome",
                   help="T-Home configuration directory." )
   p.add_argument( "-l", "--log", metavar="logFile",
                   default=None, help="Logging file to use.  Input 'stdout' "
                   "to log to the screen." )
   p.add_argument( "--debug", default=False, action="store_true",
                   help="Debugging - no sending, just print" )
   c = p.parse_args( args[1:] )

   if c.debug:
      c.log = "stdout"

   # Parse the sma and broker config files.
   cfg = config.parse( c.configDir )
   log = config.log( cfg, c.log )

   if c.debug:
      log.setLevel( 10 )

   # Create the MQTT client and connect it to the broker.
   client = broker.connect( c.configDir, log )

   start.start( cfg, client, debug=c.debug )

#===========================================================================


from django.urls import path
from django.contrib.auth.decorators import login_required
from . import views

app_name = 'courtroom'

urlpatterns = [
    path('', login_required(views.CourtroomListView.as_view()), name='courtroom_list'),
    path('add_courtroom/', views.add_courtroom, name='add_courtroom'),
    path('edit_courtroom/', views.edit_courtroom, name='edit_courtroom'),
    path('delete_courtroom/', views.delete_courtroom, name='delete_courtroom'),
]


#Run this program in https://trinket.io/python/f7ad7f9864
#This program takes some text and a key to shift the text by. For example, if you put the letter h, and the key 3. The program would shift the letter h up 3 spaces, i, j, k. The out put should be k.

#declare variables
text = input("Input text: ")
#check that key is a digit
while True:
  key = input("Input key: ")
  if (key.isdigit()):
    break

ascii = 0
encodedText = ""
##loop going though each character for text
for i in range(len(text)):
#check if letter
    if (text[i].isalpha()) == True:
#check if lowercase
      if (text[i].islower()) == True:
#shift letter by key
        ascii = (int(ord(text[i]))-97+int(key))%26
        encodedText = (str(encodedText) + chr(ascii+97))
#if not lowercase than must be uppercase
      else:
#shift letter by key
        ascii = (int(ord(text[i]))-65+int(key))%26
        encodedText = (str(encodedText) + chr(ascii+65))
    else:
      encodedText = encodedText + text[i]
#print encrypted result
print(encodedText)


import unittest
from application import create_app
import json

class TestClass(unittest.TestCase):

    def setUp(self):
        self.app = create_app("testing")
        self.client = self.app.test_client

        self.request_body = {
            "id": 565,
            "title": "Elevator Maintenance",
            "department": "Accounts",
            "detail": "We need to repair asap",
            "status": "urgent"
        }

        with self.app.test_client() as c:
            self.res = c.post('api/v1/users/requests/', headers={'Authorization': 'Bearer token',
                                                                 'Content-Type': 'application/json; charset=utf-8'}, data=json.dumps(self.request_body))

    def test_request_creation(self):
        self.assertEqual(self.res.status_code, 201)
        self.assertIn('title', json.loads(self.res.data))

    def test_get_all_requests(self):
        self.assertEqual(self.res.status_code, 201)
        res = self.client().get('api/v1/users/requests/',
                                headers={'Authorization': 'Bearer token', 'Content-Type': 'application/json; charset=utf-8'})
        self.assertEqual(res.status_code, 200)
        self.assertIn('title', json.loads(res.data)['requests'][0])

    def test_get_single_request(self):
        self.assertEqual(self.res.status_code, 201)
        id = json.loads(self.res.data)["id"]
        res = self.client().get('api/v1/users/requests/{}/'.format(id),
                                headers={'Authorization': 'Bearer token', 'Content-Type': 'application/json; charset=utf-8'})
        self.assertEqual(res.status_code, 200)
        self.assertEqual(len(json.loads(res.data)['requests']), 1)
        self.assertIn('title', json.loads(res.data)['requests'][0])

    def test_put_request(self):
        self.assertEqual(self.res.status_code, 201)
        id = json.loads(self.res.data)["id"]
        title = json.loads(self.res.data)["title"]
        newObj = json.loads(self.res.data)
        newObj["title"] = title
        res = self.client().put('api/v1/users/requests/{}/'.format(id), headers={'Authorization': 'Bearer token',
                                                                                'Content-Type': 'application/json; charset=utf-8'}, data=json.dumps(newObj))
        self.assertEqual(res.status_code, 201)
        self.assertEqual(json.loads(self.res.data)["title"], title)

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


import tensorflow as tf
import tensorflow.keras as keras
import pandas as pd
import numpy as np
import pickle, os, gc, glob
from tqdm import tqdm
from tensorflow.keras.models import Model

def normalize_channel(img):
    shape = img.shape
    for i in range(shape[0]):
        map = img[i,:,:,:]
        mean = np.mean(map)
        std = np.std(map)
        if std == 0.0:
            pass
        else:
            img[i,:,:,:] = (map - mean) / std
    img = img.transpose()
    return img

def normalize(img):
    mean = np.mean(img)
    std = np.std(img)
    img = (img - mean) / std
    return img.transpose()

def calc_score(y, y_p):
    score = np.zeros(5)

    true_sum = y.sum(axis = 0)
    error = np.absolute(y-y_p)
    error = error.sum(axis = 0)

    score = error / true_sum
    weight = np.array([0.3, 0.175, 0.175, 0.175, 0.175])
    score = np.sum(score * weight)

    return

DATA_PATH = "../fMRI_train_pk"
df = pd.read_csv("train_scores.csv")
df = df.dropna().reset_index()

file_ls = []
y_ls = np.zeros(shape = (df.shape[0], 5))

loading_np = pickle.load(open('loading.pk', 'rb'))
fnc_np = pickle.load(open('fnc.pk', 'rb'))

for idx, row in df.iterrows():
    file_ls.append(os.path.join(DATA_PATH, str(int(row["Id"]))+".pk"))
    ys = row[2:].values
    y_ls[idx] = ys

y_true = np.array(y_ls)
y_pred = np.zeros(shape = (len(file_ls), 5), dtype = np.float32)

modeldir = '../saved model'
model_list = glob.glob(modeldir+'/*.h5')

for m in model_list:
    model = keras.models.load_model(m)
    i = 0
    for file, load, fnc in tqdm(list(zip(file_ls, loading_np, fnc_np))):
        f = None
        with open(file, 'rb') as f:
            img = pickle.load(f)

        img = normalize(img)
        y = model((img[np.newaxis], load.reshape((1,26)), fnc.reshape((1,1383))))
        y_pred[i] = np.squeeze(y)
        i += 1
        gc.collect()

        print(calc_score(y_true, y_pred))


import os
import shutil
import tempfile
import urllib.request
from django.core.management.base import BaseCommand
from storage.zipfile import unzip
from uk_geo_utils.management.commands.import_onspd import Command as LocalImporter

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('url', action='store')

    def handle(self, **options):
        url = options['url']
        self.stdout.write('Downloading data from %s ...' % (url))
        tmp = tempfile.NamedTemporaryFile()
        urllib.request.urlretrieve(url, tmp.name)
        tempdir = unzip(tmp.name)
        data_path = os.path.join(tempdir, 'Data')
        try:
            cmd = LocalImporter()
            cmd.handle(**{ 'path': data_path })
        finally:
            self.cleanup(tempdir)

    def cleanup(self, tempdir):
        # clean up the temp files we created
        try:
            shutil.rmtree(tempdir)
        except OSError:
            self.stdout.write("Failed to clean up temp files.")


import uuid

import pytest
from tests.factories import ApiaryFactory
from tests.factories import HiveFactory

from aristaeus.domain.services.unit_of_work import UnitOfWork

@pytest.mark.parametrize("async_app", ["11111111-1111-1111-1111-111111111111"], indirect=True)
async def test_create_apiary(async_app):
    data = {"name": "a name", "honey_kind": "too good", "location": "everywhere"}
    response = await async_app.post("/apiary", json=data)
    assert response.status_code == 201, response.text

    data = response.json()
    assert data["name"] == "a name", data
    assert data["location"] == "everywhere", data
    assert data["honey_kind"] == "too good", data
    assert data["organization_id"] == "11111111-1111-1111-1111-111111111111", data

@pytest.mark.parametrize("async_app", ["11111111-1111-1111-1111-111111111111"], indirect=True)
@pytest.mark.parametrize(
    "payload",
    (
        {"name": "a name", "honey_kind": "too good", "location": None},
        {"name": "a name", "honey_kind": "too good"},
        {"location": "a name", "honey_kind": "too good"},
        {"location": "a name", "name": "too good"},
    ),
)
async def test_create_apiary__wrong_payload(async_app, payload):
    response = await async_app.post("/apiary", json=payload)
    assert response.status_code == 422, response.text

@pytest.mark.parametrize("async_app", ["11111111-1111-1111-1111-111111111111"], indirect=True)
async def test_get_apiary__unknown(async_app):
    response = await async_app.get(f"/apiary/{uuid.uuid4()}")
    assert response.status_code == 404, response.text

@pytest.mark.parametrize("async_app", ["11111111-1111-1111-1111-111111111111"], indirect=True)
async def test_get_apiary__get(async_app):
    data = {"name": "a name", "honey_kind": "too good", "location": "everywhere"}
    response = await async_app.post("/apiary", json=data)
    assert response.status_code == 201, response.text

    swarm_id = response.json()["public_id"]
    response = await async_app.get(f"/apiary/{swarm_id}")
    assert response.status_code == 200, response.text
    assert len(response.json()) >= 1

@pytest.mark.parametrize("async_app", ["22222222-2222-2222-2222-222222222222"], indirect=True)
async def test_list_apiaries(async_app):
    apiaries = ApiaryFactory.build_batch(
        5, organization_id=uuid.UUID("22222222-2222-2222-2222-222222222222"), hive_count=1
    )
    hives = [HiveFactory.create(apiary=apiary) for apiary in apiaries]

    async with UnitOfWork() as uow:
        for apiary in apiaries:
            await uow.apiary.save(apiary)
        for hive in hives:
            await uow.hive.save(hive)

    response = await async_app.get("/apiary")

    assert response.status_code == 200, response.text
    assert len(response.json()) == 5, response.text
    data = response.json()
    for apiary in data:
        assert apiary["hive_count"] == 1

@pytest.mark.parametrize("async_app", ["11111111-1111-1111-1111-111111111111"], indirect=True)
@pytest.mark.parametrize(
    "payload",
    (
        {"honey_kind": "new honey_kind"},
        {"location": "new location"},
        {"name": "new name"},
    ),
)
async def test_put_apiary__success(async_app, payload):
    data = {"name": "a name", "honey_kind": "too good", "location": "everywhere"}
    response = await async_app.post("/apiary", json=data)
    assert response.status_code == 201, response.text
    apiary_id = response.json()["public_id"]

    response = await async_app.put(f"/apiary/{apiary_id}", json=payload)
    assert response.status_code == 200, response.text

    data = response.json()
    for key, value in payload.items():
        assert data[key] == value

@pytest.mark.parametrize("async_app", ["11111111-1111-1111-1111-111111111111"], indirect=True)
async def test_delete_apiary__success(async_app):
    data = {"name": "a name", "honey_kind": "too good", "location": "everywhere"}
    response = await async_app.post("/apiary", json=data)
    assert response.status_code == 201, response.text
    apiary_id = response.json()["public_id"]

    response = await async_app.delete(f"/apiary/{apiary_id}")
    assert response.status_code == 204, response.text

    response = await async_app.get(f"/apiary/{apiary_id}")
    assert response.status_code == 404, response.text


import datetime

import backtrader as bt
import pandas as pd
import matplotlib.pyplot as plt

from fxincome.const import PATH, SPREAD
from fxincome.utils import JsonModel
from fxincome import logging, logger, f_logger
from fxincome.spread.predict_spread import predict_pair_spread

class SpreadData(bt.feeds.PandasData):
    """
    Spread = leg2 ytm - leg1 ytm.  YTM's unit is %.
    The prices(OHLC) = Leg1's full price - Leg2's full price.
    Buy at price means buy leg1, sell leg2 with the same size. The net cash flow of buy is -price * size.
    Sell at price means sell leg1, buy leg2 with the same size. The net cash flow of sell is +price * size.
    The position of Spread is either >0, =0, or <0.
    Position > 0 means LONG spread, i.e. LONG leg1, SHORT leg2.
    Position < 0 means SHORT spread, i.e. SHORT leg1, LONG leg2.
    """

    # Lines besides those required by backtrader (datetime, OHLC, volume, openinterest).
    lines = (
        "code_leg1",
        "out_leg1",
        "ytm_leg1",
        "lend_rate_leg1",
        "code_leg2",
        "vol_leg2",
        "out_leg2",
        "ytm_leg2",
        "lend_rate_leg2",
        "spread",
        "spread_min",
    )

    params = (
        ("datetime", "DATE"),
        ("close", "CLOSE"),
        ("open", "OPEN"),
        ("high", "HIGH"),
        ("low", "LOW"),
        ("volume", "VOL_LEG1"),
        ("openinterest", -1),
        ("code_leg1", "CODE_LEG1"),
        ("out_leg1", "OUT_BAL_LEG1"),
        ("ytm_leg1", "YTM_LEG1"),
        ("lend_rate_leg1", "LEND_RATE_LEG1"),
        ("code_leg2", "CODE_LEG2"),
        ("vol_leg2", "VOL_LEG2"),
        ("out_leg2", "OUT_BAL_LEG2"),
        ("ytm_leg2", "YTM_LEG2"),
        ("lend_rate_leg2", "LEND_RATE_LEG2"),
        ("spread", "SPREAD"),
        ("spread_min", "SPREAD_MIN"),
    )

class SpreadStrategy(bt.Strategy):
    SIZE = 1e6  # 1 million size for 100 million face value of bond
    INIT_CASH = 1e7  # 10 million initial cash for 100 million face value of bond

    def __init__(self):
        self.data = self.getdatabyname(self.ST_NAME)
        self.spread = self.data.spread
        self.spread_min = self.data.spread_min
        self.open = self.data.open
        self.high = self.data.high
        self.low = self.data.low
        self.volume = self.data.volume  # leg1 volume
        self.vol_leg2 = self.data.vol_leg2
        self.out_leg1 = self.data.out_leg1
        self.out_leg2 = self.data.out_leg2
        self.ytm_leg1 = self.data.ytm_leg1
        self.ytm_leg2 = self.data.ytm_leg2
        self.lend_rate_leg1 = self.data.lend_rate_leg1
        self.lend_rate_leg2 = self.data.lend_rate_leg2
        self.total_fee = 0.0
        self.leg1_code = str(int(self.data.code_leg1[0]))
        self.cash_flow_leg1 = pd.read_csv(
            PATH.SPREAD_DATA + f"cash_flow_{self.leg1_code}.csv", parse_dates=["DATE"]
        )
        self.cash_flow_leg1["DATE"] = self.cash_flow_leg1["DATE"].dt.date
        self.leg2_code = str(int(self.data.code_leg2[0]))
        self.cash_flow_leg2 = pd.read_csv(
            PATH.SPREAD_DATA + f"cash_flow_{self.leg2_code}.csv", parse_dates=["DATE"]
        )
        self.cash_flow_leg2["DATE"] = self.cash_flow_leg2["DATE"].dt.date
        self.result = pd.read_csv(
            PATH.SPREAD_DATA + f"{self.leg1_code}_{self.leg2_code}_bt.csv",
            parse_dates=["DATE"],
        )
        self.result["DATE"] = self.result["DATE"].dt.date
        self.result["Profit"] = 0.0
        self.result["TotalFee"] = 0.0
        self.result["Sell"] = 0.0
        self.result["Buy"] = 0.0
        self.last_day = self.data.datetime.date(
            0
        )  # In init(), date(0) is the last day.

    def log(self, txt, dt=None, legs=None, level=logging.DEBUG):
        dt = dt or self.getdatabyname(self.ST_NAME).datetime.date(0)
        legs = legs or f"{self.leg1_code}_{self.leg2_code}"
        f_logger.log(level, f"{legs} - {dt:%Y%m%d} - {txt}")

    def _calculate_lend_fee(
        self, face_value: int, rate: float, direction: str
    ) -> float:
        """
        Calculate the lending fee for a bond. Direction must be 'borrow' or 'lend'.
        Args:
            face_value (int):   face value of the bond
            rate (float):       lending rate. 1 means 1% annual rate.
            direction (str):    'borrow' means the bond is borrowed and must pay lending fee.
                                'lend' means the bond is lent out and receive lending fee.
        Returns:
            fee(float): lending fee. Positive means receive fee, negative means pay fee.
        """
        rate = rate / 100
        if direction == "borrow":
            fee = (
                -rate
                * abs(face_value)
                / 365
                * (self.data.datetime.date(1) - self.data.datetime.date(0)).days
            )
        elif direction == "lend":
            fee = (
                rate
                * abs(face_value)
                / 365
                * (self.data.datetime.date(1) - self.data.datetime.date(0)).days
            )
        else:
            raise ValueError("direction must be 'borrow' or 'lend'")
        return fee

    def _process_fee_coupon(self):
        """
        This method is supposed to be called in next().
        It processes lending fee and coupon payment at the end of each day.
        (1)Lending fee is based on today's position and rate. Cash change at T+1. Only fee for borrowing is considered.
        (2)Coupon payment is based on T+1's actual coupon. Cash change at T+1.
        """
        lend_fee = 0.0
        if self.getposition(self.data).size < 0:
            lend_fee = self._calculate_lend_fee(
                face_value=self.getposition(self.data).size * 100,
                rate=self.lend_rate_leg1[0],
                direction="borrow",
            )
        elif self.getposition(self.data).size > 0:
            lend_fee = self._calculate_lend_fee(
                face_value=self.getposition(self.data).size * 100,
                rate=self.lend_rate_leg2[0],
                direction="borrow",
            )
        self.broker.add_cash(
            lend_fee
        )  # Lending fee for borrowing is negative. broker.add_cash() takes effect at T+1.
        self.total_fee += lend_fee  # Total fee is accumulated up to now.
        self.result.loc[
            self.result["DATE"] == self.data.datetime.date(0), "TotalFee"
        ] = self.total_fee

        # Coupon payment dates of cash_flow are dates when we receive coupon payments.
        # We receive coupon payments at T+1 only when we hold the bond at T.
        # Coupon payment dates are sometimes not trading days. Backtrader datafeed's dates are all trading days.
        # We compute the left payment times to determine whether we receive coupon payments at T+1.
        today_leg1_remaining_payment_times = len(
            self.cash_flow_leg1[
                self.cash_flow_leg1["DATE"] > self.data.datetime.date(0)
            ]
        )
        today_leg2_remaining_payment_times = len(
            self.cash_flow_leg2[
                self.cash_flow_leg2["DATE"] > self.data.datetime.date(0)
            ]
        )
        tomorrow_leg1_remaining_payment_times = len(
            self.cash_flow_leg1[
                self.cash_flow_leg1["DATE"] > self.data.datetime.date(1)
            ]
        )
        tomorrow_leg2_remaining_payment_times = len(
            self.cash_flow_leg2[
                self.cash_flow_leg2["DATE"] > self.data.datetime.date(1)
            ]
        )
        if tomorrow_leg1_remaining_payment_times < today_leg1_remaining_payment_times:
            coupon_row_num = (
                len(self.cash_flow_leg1) - today_leg1_remaining_payment_times
            )
            # Leg1's holder will receive coupon payments at T+1.
            # Negative position means we short sell leg1, so we need to pay coupon to the lender.
            # Positive position means we hold leg1, so we receive coupon.
            coupon = (
                self.cash_flow_leg1.iloc[coupon_row_num]["AMOUNT"]
                * self.getposition(self.data).size
            )
            self.log(f"coupon payment {coupon}", dt=self.data.datetime.date(1))
            self.broker.add_cash(coupon)
        if tomorrow_leg2_remaining_payment_times < today_leg2_remaining_payment_times:
            coupon_row_num = (
                len(self.cash_flow_leg2) - today_leg2_remaining_payment_times
            )
            # Leg2's holder will receive coupon payments at T+1.
            # Negative position means we hold leg2, so we receive coupon.
            # Positive position means we short sell leg2, so we need to pay coupon to the lender.
            coupon = (
                -self.cash_flow_leg2.iloc[coupon_row_num]["AMOUNT"]
                * self.getposition(self.data).size
            )
            self.log(f"coupon payment {coupon}", dt=self.data.datetime.date(1))
            self.broker.add_cash(coupon)

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            return
        # Check if an order has been completed
        # Attention: broker could reject order if not enough cash
        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    f"Order {order.ref}, BUY EXECUTED, {order.executed.price:.2f}, {order.executed.size:.2f}"
                )
                self.result.loc[
                    self.result["DATE"] == self.data.datetime.date(0), "Buy"
                ] = 1
            elif order.issell():
                self.log(
                    f"Order {order.ref}, SELL EXECUTED, {order.executed.price:.2f}, {order.executed.size:.2f}"
                )
                self.result.loc[
                    self.result["DATE"] == self.data.datetime.date(0), "Sell"
                ] = 1
        elif order.status in [
            order.Canceled,
            order.Margin,
            order.Rejected,
            order.Expired,
        ]:
            self.log(f"Order {order.ref} Canceled/Margin/Rejected/Expired")

class BaselineStrategy(SpreadStrategy):
    ST_NAME = "baseline"

    def __init__(self):
        super().__init__()

    def next(self):
        # The last day has no tomorrow.
        if self.data.datetime.date(0) == self.last_day:
            self.result.loc[
                self.result["DATE"] == self.data.datetime.date(0), "TotalFee"
            ] = self.total_fee
            self.result.loc[
                self.result["DATE"] == self.data.datetime.date(0), "Profit"
            ] = (self.broker.getvalue() - self.INIT_CASH)
            return

        self._process_fee_coupon()

        # trading logic
        condition1 = self.spread[0] >= -0.03
        condition2 = self.vol_leg2[0] < self.volume[0]
        condition3 = self.spread[0] > self.spread_min[0] * 0.9
        condition4 = self.getposition(self.data).size < 0
        condition5 = self.spread[0] >= -0.005
        condition6 = self.out_leg2[0] > self.out_leg1[0] * 0.8
        condition7 = self.out_leg2[0] < self.out_leg1[0] * 0.6
        condition8 = self.spread[0] <= -0.04
        condition9 = self.vol_leg2[0] - self.volume[0] > 1e11
        condition10 = self.getposition(self.data).size == 0
        if condition10 & condition1 & condition2 & condition7:
            self.sell(size=self.SIZE)
        if condition3 & condition8 & condition9:
            if condition4:
                self.close()
                self.buy(size=self.SIZE)
            elif condition10:
                self.buy(size=self.SIZE)
        elif condition5 & condition6:
            self.close()
        self.result.loc[self.result["DATE"] == self.data.datetime.date(0), "Profit"] = (
            self.broker.getvalue() - self.INIT_CASH
        )

class PredictStrategy(SpreadStrategy):
    ST_NAME = "predict"

    def __init__(self):
        super().__init__()
        self.model_name_up = "spread_0.665_XGB_20230428_1020"
        self.model_attr = JsonModel.load_attr(
            self.model_name_up, PATH.SPREAD_MODEL + JsonModel.JSON_NAME
        )
        self.days_forward_up = self.model_attr.labels["LABEL"]["days_forward"]
        self.threshold_up = abs(self.model_attr.labels["LABEL"]["spread_threshold"])
        self.up_preds = predict_pair_spread(
            self.model_name_up, self.leg1_code, self.leg2_code
        )
        self.model_name_down = "spread_0.635_XGB_20230428_1029"
        self.model_attr = JsonModel.load_attr(
            self.model_name_down, PATH.SPREAD_MODEL + JsonModel.JSON_NAME
        )
        self.days_forward_down = self.model_attr.labels["LABEL"]["days_forward"]
        self.threshold_down = abs(self.model_attr.labels["LABEL"]["spread_threshold"])
        self.down_preds = predict_pair_spread(
            self.model_name_down, self.leg1_code, self.leg2_code
        )
        self.unit_size_up = self.SIZE / self.days_forward_up
        self.unit_size_down = self.SIZE / self.days_forward_down
        self.buy_records = list()  # a list of tuple (spread, date)
        self.long_position = 0  # Unit is the same as SIZE.
        self.sell_records = list()  # a list of tuple (spread, date)
        self.short_position = 0  # Unit is the same as SIZE.

    def next(self):
        today = self.data.datetime.date(0)
        up_preds = self.up_preds.query("DATE ==@today")
        down_preds = self.down_preds.query("DATE ==@today")
        # The last day has no tomorrow.
        if (
            self.data.datetime.date(0) == self.last_day
            or len(up_preds) == 0
            or len(down_preds) == 0
        ):
            self.result.loc[
                self.result["DATE"] == self.data.datetime.date(0), "TotalFee"
            ] = self.total_fee
            self.result.loc[
                self.result["DATE"] == self.data.datetime.date(0), "Profit"
            ] = (self.broker.getvalue() - self.INIT_CASH)
            return

        self._process_fee_coupon()

        # trading logic
        up_pred = int(up_preds.pred.iat[0])
        down_pred = int(down_preds.pred.iat[0])
        # check if we need to close position
        for buy_record in self.buy_records:
            prediction_correct = self.spread[0] >= buy_record[0] + self.threshold_up
            end_of_period = self.data.datetime.date(0) - buy_record[
                1
            ] == datetime.timedelta(days=self.days_forward_up)
            stop_loss = self.spread[0] <= buy_record[0] - 2 * self.threshold_up
            if (
                prediction_correct
                or (end_of_period and not up_pred == 1)
                or stop_loss
            ):
                self.sell(data=self.data, size=self.unit_size_up)
                self.buy_records.remove(buy_record)
                self.long_position -= self.unit_size_up
            elif end_of_period and up_pred == 1:
                # Update the cost of trade but hold position
                self.buy_records.remove(buy_record)
                self.buy_records.append((self.spread[0], self.data.datetime.date(0)))
        for sell_record in self.sell_records:
            prediction_correct = self.spread[0] <= sell_record[0] - self.threshold_down
            end_of_period = self.data.datetime.date(0) - sell_record[
                1
            ] == datetime.timedelta(days=self.days_forward_down)
            stop_loss = self.spread[0] >= sell_record[0] + 2 * self.threshold_down
            if (
                prediction_correct
                or (end_of_period and not down_pred == 1)
                or stop_loss
            ):
                self.buy(data=self.data, size=self.unit_size_down)
                self.sell_records.remove(sell_record)
                self.short_position -= self.unit_size_down
            elif end_of_period and down_pred == 1:
                # Update the cost of trade but hold position
                self.sell_records.remove(sell_record)
                self.sell_records.append((self.spread[0], self.data.datetime.date(0)))

        # # check if we need to open position
        if (up_pred == 1) and (self.long_position < self.SIZE):
            self.buy(data=self.data, size=self.unit_size_up)
            self.buy_records.append((self.spread[0], self.data.datetime.date(0)))
            self.long_position += self.unit_size_up
        if (down_pred == 1) and (self.short_position < self.SIZE):
            self.sell(data=self.data, size=self.unit_size_down)
            self.sell_records.append((self.spread[0], self.data.datetime.date(0)))
            self.short_position += self.unit_size_down

        self.result.loc[self.result["DATE"] == self.data.datetime.date(0), "Profit"] = (
            self.broker.getvalue() - self.INIT_CASH
        )

def plot_spread(leg1, leg2):
    input_file = PATH.SPREAD_DATA + f"{leg1}_{leg2}_result.csv"
    data = pd.read_csv(input_file, parse_dates=["DATE"])
    fig = plt.figure(num=1, figsize=(15, 5))
    ax = fig.add_subplot(111, label="1")
    ax2 = fig.add_subplot(111, label="2", frame_on=False)
    lns1 = ax.plot(data["DATE"], data["SPREAD"], color="r", label="SPREAD")
    lns = lns1
    ax.set_xlabel("Date")
    ax.set_ylabel("Spread")
    for i in range(0, len(data["Buy"])):
        if data["Buy"][i] == 1:
            ax.annotate(
                "Buy",
                xy=(data["DATE"][i], data["SPREAD"][i]),
                xytext=(data["DATE"][i], data["SPREAD"][i] - 0.01),
                arrowprops=dict(facecolor="green", shrink=0.05),
            )
    for i in range(0, len(data["Sell"])):
        if data["Sell"][i] == 1:
            ax.annotate(
                "Sell",
                xy=(data["DATE"][i], data["SPREAD"][i]),
                xytext=(data["DATE"][i], data["SPREAD"][i] + 0.01),
                arrowprops=dict(facecolor="yellow", shrink=0.05),
            )
    lns2 = ax2.plot(data["DATE"], data["Profit"], label="Profit")
    lns += lns2
    ax2.set_ylabel("Profit")
    ax2.xaxis.tick_top()
    ax2.yaxis.tick_right()
    ax2.xaxis.set_label_position("top")
    ax2.yaxis.set_label_position("right")
    labs = [l.get_label() for l in lns]
    ax.legend(lns, labs, loc=0, fontsize=10)
    plt.title(f"{leg1} and {leg2} Spread Trading")
    plt.tight_layout()
    plt.show()

def main():
    # Baseline
    # for i in range(0, 15):
    #     leg1_code = SPREAD.CDB_CODES[i]
    #     leg2_code = SPREAD.CDB_CODES[i + 1]
    #     cerebro = bt.Cerebro()
    #     input_file = PATH.SPREAD_DATA + leg1_code + '_' + leg2_code + '_bt.csv'
    #     price_df = pd.read_csv(input_file, parse_dates=['DATE'])
    #     # minimum spread in the past 15 days are used as the threshold to open a position
    #     price_df['SPREAD_MIN'] = price_df['SPREAD'].rolling(15).min()
    #     price_df.loc[:, ['SPREAD_MIN']] = price_df.loc[:, ['SPREAD_MIN']].fillna(method='backfill')
    #     price_df = price_df.dropna()
    #     data1 = SpreadData(dataname=price_df, nocase=True)
    #     cerebro.adddata(data1, name=BaselineStrategy.ST_NAME)
    #     cerebro.addstrategy(BaselineStrategy)
    #     cerebro.broker.set_cash(BaselineStrategy.INIT_CASH)
    #     logger.info(leg1_code + '_' + leg2_code)
    #     strategies=cerebro.run()
    #     logger.info(f'PROFIT: {(cerebro.broker.get_value() - BaselineStrategy.INIT_CASH ) / 10000:.2f}')
    #     strategies[0].result.to_csv(PATH.SPREAD_DATA + f'{leg1_code}_{leg2_code}_result.csv', index=False)
    # for i in range(0, 15):
    #     leg1_code = SPREAD.CDB_CODES[i]
    #     leg2_code = SPREAD.CDB_CODES[i + 1]
    #     plot_spread(leg1_code,leg2_code)

    # Prediction
    for i in range(11, 14):
        leg1_code = SPREAD.CDB_CODES[i]
        leg2_code = SPREAD.CDB_CODES[i + 1]
        cerebro = bt.Cerebro()
        input_file = PATH.SPREAD_DATA + leg1_code + "_" + leg2_code + "_bt.csv"
        price_df = pd.read_csv(input_file, parse_dates=["DATE"])
        # minimum spread in the past 15 days are used as the threshold to open a position
        price_df["SPREAD_MIN"] = price_df["SPREAD"].rolling(15).min()
        price_df.loc[:, ["SPREAD_MIN"]] = price_df.loc[:, ["SPREAD_MIN"]].fillna(
            method="backfill"
        )
        price_df = price_df.dropna()
        # data_long and data_short are the same data feeds, but with different names.
        # data_long is for predicting long strategy, and data_short is for predicting short strategy.
        data_long = SpreadData(dataname=price_df, nocase=True)
        cerebro.adddata(data_long, name=PredictStrategy.ST_NAME)
        cerebro.addstrategy(PredictStrategy)
        cerebro.broker.set_cash(PredictStrategy.INIT_CASH)
        logger.info(leg1_code + "_" + leg2_code)
        strategies = cerebro.run()
        logger.info(
            f"PROFIT: {(cerebro.broker.get_value() - PredictStrategy.INIT_CASH) / 10000:.2f}"
        )
        strategies[0].result.to_csv(
            PATH.SPREAD_DATA + f"{leg1_code}_{leg2_code}_result.csv", index=False
        )
    for i in range(11, 14):
        leg1_code = SPREAD.CDB_CODES[i]
        leg2_code = SPREAD.CDB_CODES[i + 1]
        plot_spread(leg1_code, leg2_code)

if __name__ == "__main__":
    main()


from app import App
import assets
from components.events.mouse import *
import controllers
from controllers.mouse import MouseController
from controllers.room import RoomController
from controllers.scene import SceneController
from controllers.watch import WatchController
from controllers.world import WorldController
from models.character import *
from views.room import FloorTileView

ROOM_ROWS = 20
ROOM_COLUMNS = 20

class LD37(App):
    def hasRequiredComponents(this):
        available = not this.getViewer() is None
        available &= not this.getLoader() is None
        available &= not this.getRenderer() is None
        available &= not this.getCamera() is None
        available &= not this.getInput() is None
        return available

    def onRequiredComponentsAvailable(this):
        # Define the final viewer pixel dimensions.
        viewer = this.getViewer()
        viewerLength = ROOM_COLUMNS * FloorTileView.FloorTileHeight
        viewerHeight = ROOM_ROWS * FloorTileView.FloorTileLength
        viewer.initialize((viewerLength, viewerHeight))

        # Load assets before using them, logging the loading for debugging if necessary.
        assets.loadAssets(this.getLoader(), this.getLogger())

        # Attach the camera to the viewer, and also provide a renderer for displayed snapshots.
        this.getCamera().initialize(viewer, this.getRenderer())

        # Track the 3 main mouse buttons (no exotic MMORPG setups please).
        this.getInput().initialize([BUTTON_LEFT, BUTTON_MIDDLE, BUTTON_RIGHT])

        # Indicate that the game is ready to enter the main game loop.
        this.__ready = True

    def onRequiredComponentsNotAvailable(this):
        this.__ready = False

    def isReady(this):
        return this.__ready

    def play(this):
        if not this.__ready:
            logger = this.getLogger()

            if not logger is None:
                logger.debug("The required components are not available, and thus the game was not ready for playing.")

        else:
            # Get the components used in the game loop.
            viewer = this.getViewer()
            camera = this.getCamera()
            input = this.getInput()
            renderer = this.getRenderer()

            # Create the world.
            world = WorldController()

            # Being on time is relatively useful.
            watch = world.addController("Watch", WatchController())

            # Add a scene.
            scene = world.addController("Scene", SceneController(viewer.getDimensions()))

            # Build the scene.
            room = RoomController(ROOM_ROWS, ROOM_COLUMNS, watch)

            ## TODO: Make this a task, so that the addition or removal of a character activates the door.
#            room.addCharacter(DetectiveModel())
#            room.addCharacter(OfficerModel(1))
#            room.addCharacter(LawyerModel(2))
#            room.addCharacter(AccusedModel(3))
            room.addCharacter(WitnessModel(4))

            scene.addController("InterrogationRoom", room)

            # Attach mouse inputs to the scene.
            mouse = world.addController("Mouse", MouseController(input, camera, scene))

            # Enter and maintain the game loop.
            quitting = False
            while not quitting:
                quitting = input.refresh()

                if not quitting:
                    # Update the world.
                    world.update()

                    # Clear the viewer.
                    viewer.clear()

                    # Capture an image from the scene.
                    camera.capture(scene)

                    # Refresh the viewer.
                    viewer.refresh()

        # Clean up to shut down the game.
        this.getCamera().terminate()
        this.getViewer().terminate()

def main():
    LD37().play()

if __name__ == "__main__":
    main()


from selenium import webdriver
import time
from lxml import etree
driver_path = 'chromedriver.exe'

driver = webdriver.Chrome(executable_path=driver_path)

driver.get('https://www.baidu.com/')

for cookie in driver.get_cookies():
    print(cookie)

print("*"*30)

print(driver.get_cookies('PSTM'))

driver.delete_all_cookies()


import re
import urllib.request
import lxml.html  as lh
import json

#parse init
urls = ["http://pikabu.ru/search.php?q=gif&page=%s"%(i) for i in range(1, 53)]
results = []

for url in urls:
    req = urllib.request.Request(url, headers={
                    'Connection': 'close',
                    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36'
                    })
    site = urllib.request.urlopen(req)
    html = site.read().decode(site.headers.get_content_charset())
    doc = lh.fromstring(html)
    meta = doc.xpath('//meta')
    allmeta = ""
    for el in meta:
        allmeta += lh.tostring(el,encoding='unicode')
    print("Page url:"+url)
    print("Number of posts: %s"%len(doc.xpath('//div[@class="story"]')))
    for elem in doc.xpath('//div[@class="story"]'):
        try:
            title = elem.xpath('.//a[@class="story__title-link "]//text()')[0]
            post_url = elem.xpath('.//div[@class="story__header"]//a[@class="story__title-link "]//@href')[0]
            content_urls = elem.xpath('.//div[@class="story__wrapper"]//a[contains(concat(" ", normalize-space(@class), " "), "b-gifx__state ")]//@href')
            tag_elems = elem.xpath('.//div[@class="story__header"]//a[@class="story__tag"]//text()')
            rating = elem.xpath('.//div[@class="story__left"]//div[@class="story__rating-count"]//text()')[0].strip()
            print("Post url:"+post_url)
        except Exception:
            print('Empty data')
            continue
        if len(content_urls) < 1:
            print('No gif')
            continue
        tags=[]
        for tag in tag_elems:
            tags.append(tag.strip())
        result = {
            "url":url,
            "title":title,
            "tags":tags,
            "rating":rating,
            "post":post_url,
            "gifs":content_urls,
            "meta":allmeta,
            "html":html
        }

        f = open('pikabu.json', 'a')
        js = json.dumps(result, ensure_ascii=False)
        f.write(js+'\n')
        f.close()


import sys

# Example of using a Generator to express an arithmetic sequence
# This shows that generators are massively more memory efficient
def my_range(n: int):
    print("my_range starts")
    start: int = 0
    while start < n:
        print("my_range is returning {}".format(start))
        yield start
        start += 1

big_range = my_range(5)

print("big_range is {} bytes".format(sys.getsizeof(big_range)))  # 120 bytes

big_list = []
for val in big_range:
    big_list.append(val)

print("big_list is {} bytes".format(sys.getsizeof(big_list)))  # 87624 bytes

# For arithmetic sequences, we can just use the Range datatype

print(big_range)
print(big_list)


from rest_framework import serializers

from .models import *

class StainSerializer(serializers.HyperlinkedModelSerializer):

    party = serializers.PrimaryKeyRelatedField(
            queryset = Party.objects.all(),
            )
    category = serializers.PrimaryKeyRelatedField(
            queryset = Category.objects.all(),
            )
    reporter = serializers.PrimaryKeyRelatedField(
            queryset = Reporter.objects.all(),
            )

    factor_display = serializers.ReadOnlyField(source='get_factor_display')
    result_display = serializers.ReadOnlyField(source='get_result_display')

    class Meta:
        model = Stain
        fields = (  'id',
                    'party',
                    'category', 'category_name', 'category_domain',
                    'reporter', 'reporter_name',
                    'decision_administration',
                    'decision_letter',
                    'decision_basis',
                    'decision_contents',
                    'decision_date',
                    'factor',
                    'factor_display',
                    'result',
                    'result_display',
                    'result_contents',
                    'result_date',
                )

class LatestStainSerializer(serializers.HyperlinkedModelSerializer):

    party_id = serializers.ReadOnlyField(source='party.id')
    class Meta:
        model = Stain
        fields = (  'id',
                    'party_id',
                    'party_name',
                    'category_name', 'category_domain',
                    'reporter_name',
                    'decision_date',
                )

class PartySerializer(serializers.HyperlinkedModelSerializer):

    genre = serializers.ReadOnlyField()
    genre_display = serializers.ReadOnlyField(source='get_genre_display')
    score = serializers.ReadOnlyField()

    class Meta:
        model = Party
        fields = ('id', 'name', 'code', 'phone', 'address','genre', 'score',
                'genre_display',)

    @staticmethod
    def create_party_from_dict(SubPartyModel, validated_data):
        # create party instance
        p_dict = validated_data.pop('party')
        p, created = Party.objects.get_or_create(
                name = p_dict.pop('name'),
                code = p_dict.pop('code'),
                phone = p_dict.pop('phone'),
                defaults = p_dict)

        if not created:
            p.address = p_dict['address']
            p.save()

        # create subparty instance
        instance, created = SubPartyModel.objects.get_or_create(
                party = p,
                defaults = validated_data)

        if not created:
            for (key, value) in validated_data.items():
                setattr(instance, key, value)
            instance.save()

        return instance

    @staticmethod
    def update_party_by_dict(instance, validated_data):
        # update party instance
        p_dict = validated_data.pop('party')
        dirty = False
        p = instance.party
        for (key, value) in p_dict.items():
            if getattr(p, key) != value:
                setattr(p, key, value)
                dirty = True

        if dirty:
            p.save()

        # update subparty instance
        for (key, value) in validated_data.items():
            setattr(instance, key, value)
        instance.save()
        return instance

class PartyWithStainsSerializer(PartySerializer):

    stains = StainSerializer(many=True, read_only=True)

    class Meta:
        model = Party
        fields = ('id', 'name', 'code', 'phone', 'address','genre', 'score',
                'genre_display', 'stains')

class EnterpriseSerializer(serializers.HyperlinkedModelSerializer):

    party = PartySerializer()
    status_display = serializers.ReadOnlyField(source='get_status_display')

    class Meta:
        model = Enterprise
        fields = (  'id',
                    'party',
                    'business_type',
                    'principal_name',
                    'principal_code',
                    'registered_capital',
                    'establish_date',
                    'business_time_limit_start',
                    'business_time_limit_end',
                    'registration_authority',
                    'approve_date',
                    'status',
                    'status_display',
                    'business_range',
                )

    def create(self, validated_data):
        return PartySerializer.create_party_from_dict(Enterprise, validated_data)

    def update(self, instance, validated_data):
        return PartySerializer.update_party_by_dict(instance, validated_data)

class EnterpriseDetailSerializer(EnterpriseSerializer):

    party = PartyWithStainsSerializer()

class InstitutionSerializer(serializers.HyperlinkedModelSerializer):

    party = PartySerializer()

    class Meta:
        model = Institution
        fields = (  'id',
                    'party',
                )

    def create(self, validated_data):
        return PartySerializer.create_party_from_dict(Institution, validated_data)

    def update(self, instance, validated_data):
        return PartySerializer.update_party_by_dict(instance, validated_data)

class InstitutionDetailSerializer(InstitutionSerializer):

    party = PartyWithStainsSerializer()

class SocialOrganizationSerializer(serializers.HyperlinkedModelSerializer):

    party = PartySerializer()

    class Meta:
        model = SocialOrganization
        fields = (  'id',
                    'party',
                )

    def create(self, validated_data):
        return PartySerializer.create_party_from_dict(SocialOrganization, validated_data)

    def update(self, instance, validated_data):
        return PartySerializer.update_party_by_dict(instance, validated_data)

class SocialOrganizationDetailSerializer(SocialOrganizationSerializer):

    party = PartyWithStainsSerializer()

class CitizenSerializer(serializers.HyperlinkedModelSerializer):

    party = PartySerializer()
    education_display = serializers.ReadOnlyField(source='get_education_display')

    class Meta:
        model = Citizen
        fields = ('id', 'party', 'education',
                'education_display', 'career', 'work_unit',
                )

    def create(self, validated_data):
        return PartySerializer.create_party_from_dict(Citizen, validated_data)

    def update(self, instance, validated_data):
        return PartySerializer.update_party_by_dict(instance, validated_data)

class CitizenDetailSerializer(CitizenSerializer):

    party = PartyWithStainsSerializer()

class AdministrationSerializer(serializers.HyperlinkedModelSerializer):

    party = PartySerializer()

    class Meta:
        model = Administration
        fields = (  'id',
                    'party',
                )

    def create(self, validated_data):
        return PartySerializer.create_party_from_dict(Administration, validated_data)

    def update(self, instance, validated_data):
        return PartySerializer.update_party_by_dict(instance, validated_data)

class AdministrationDetailSerializer(AdministrationSerializer):

    party = PartyWithStainsSerializer()


# @Author: JY
# @Date:   2019-02-18T09:54:51+09:00
# @Filename: e_26.py
# @Last modified by:   JY
# @Last modified time: 2019-02-18T15:55:14+09:00
# @Copyright: JeeY

filename_00 = 'result_05.result'
filename_01 = 'train_dataset_for_fastText_00.fastText'

full_list = list()

with open(filename_00, 'r', encoding='utf-8') as f:
    switch = 1
    while True:
        line = f.readline()
        if not line: break
        line = line.split()
        if switch == 1:
            one_sent = list()
            switch = 0
            continue
        if line == []:
            full_list.append(one_sent)
            switch = 1
            continue

        for i,j in enumerate(line[3:]):
            if i%2 == 0:
                one_sent.append(j)

with open(filename_01, 'w', encoding='utf-8') as f:
    for i in full_list:
        line = ' '.join(i)
        f.write(line + '\n')

## endl


"""2D convolutional model for Allen data."""

layer_structure = [
    {
        'layers': ['conv'],
        'weights': [64],
        'names': ['conv1_1'],
        'filter_size': [5],
        'activation': ['selu'],
        'activation_target': ['post'],
        'dropout': [0.5],
        'dropout_target': ['post']
    },
    {
        'layers': ['pool'],
        'weights': [None],
        'names': ['pool1'],
        'filter_size': [2]
    },
    {
        'layers': ['conv'],
        'weights': [64],
        'names': ['conv2_1'],
        'filter_size': [1],
        'activation': ['selu'],
        'activation_target': ['post']
    },
]

output_structure = [
    {
        'layers': ['sparse_pool'],
        'weights': [103],  # Output size
        'names': ['sp2'],
    }
]


def test():
  g=0
  for i in range(0,201):
    for j in range(0,101):
        if i+2*j>200:break
        for k in range(0,41):
            if i+2*j+5*k>200:break
            for m in range(0,21):
                if i+2*j+5*k+10*m>200:break
                for n in range(0,11):
                    if i+2*j+5*k+10*m+20*n>200:break
                    for l in range(0,5):
                        if i+2*j+5*k+10*m+20*n+50*l>200:break
                        for s in range(0,3):
                            if i+2*j+5*k+10*m+20*n+50*l+100*s>200: break
                            for u in range(0,2):
                                if i+2*j+5*k+10*m+20*n+50*l+100*s+200*u==200:
                                    g+=1
  print(g)
import time

def time_code(arg):
    '''For running code once,and take time'''
    start = time.clock()
    arg()
    end = time.clock()
    print ('Code time %.6f seconds' % (end - start))

time_code(test)


import os
import pandas as pd
import requests

PATH = "C:/Users/Yin/Documents/DataPy"

r = requests.get('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data')

with open(PATH + 'Iris.data', 'w') as f:
    f.write(r.text)

#print(os.listdir(PATH))    #打印 PATH 所在地址的目录
os.chdir(PATH)       #改变当前工作目录到指定的路径

df = pd.read_csv(PATH + 'iris.data', names=["sepal length", "sepal width", "petal length", "petal width", "class"])

#df.head() # 顶部
#df.ix[:4,:2]
#df.ix[:3, [x for x in df.columns if 'width' in x]]     #df.ix[:3, ['sepal width','petal width']]
#df['class'].unique()
#df[df['class']=='Iris-virginica'].reset_index(drop=True)
print()


#Brandon Troisi
#4/19/16
#mosaic.py

import lsystem
import shapes

def tile(x,y,scale):
	'''
	Draws a square tile of unit length 1, which then is modified based on the scale
	Draws a set of triangles inside this square that is scale by scale in size with
	lower left corner at (x,y). This creates scale by scale triangles in a square.
	'''
	Square1=shapes.Square(1)
	Square1.draw(x,y,scale)

	x0=x
	y0=y
	for i in range (10):
		x0=x+i*scale/10
		for j in range(10):
			y0=y-j*scale/10-scale/10
			Triangle1=shapes.Triangle(1)
			Triangle1.setColor('blue')
			Triangle1.draw(x0,y0,scale/10)

def mosaic(x,y,scale,Nx,Ny):
	'''
	Draws array of tiles Nx by Ny, where each tile is of size scale by scale and lower
	left corner is at (x,y).
	'''

	for i in range(Nx):
		x0=x+i*scale
		for j in range(Ny):
			y0=y+j*scale*1.02
			tile(x0,y0,scale)

def tile2(x,y,scale):
	'''
	Draws an unfilledtriangle tile of unit length 1, which then is modified based
	on the scale. Draws a set of triangles inside this square that is of size scale
	with the lower left corner at (x,y). This creates a series of red triangles in a
	triangle.
	'''
	Triangle1=shapes.TriangleU(1)
	Triangle1.draw(x,y,scale)

	for i in range (10):
		shift=0
		numTriangles=10-i
		for j in range(numTriangles):
			if scale%20==0:
				x0=x+i*scale/10+shift
				y0=y+j*scale/11.5
				Triangle1=shapes.Triangle(1)
				Triangle1.setColor('red')
				Triangle1.draw(x0,y0,scale/10)
				shift+=scale/20
			else:
				x0=x+i*scale/10+shift
				y0=y+j*scale/11.59
				Triangle1=shapes.Triangle(1)
				Triangle1.setColor('red')
				Triangle1.draw(x0,y0,scale/10)
				shift+=scale/20

if __name__=='__main__':
	mosaic(-200,-200,50,5,4)
	tile2(-70,-45,120)
	tile2(-200,-45,120)

	raw_input('Enter to exit')


# https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/
class Solution:
    def findLongestWord(self, s: str, d: List[str]) -> str:
        res=""
        maxLen=0
        for word in d:
            pW=0
            pS=0
            while pW<len(word) and pS<len(s):
                if word[pW]==s[pS]:
                    pW+=1
                    pS+=1
                else:
                    pS+=1
            if pW==len(word): #ie:word found in S
                if len(word)>maxLen or (len(word)==maxLen and word<res): #the reason for the OR is to return the smallest word if both have the same length
                    res=word
                    maxLen=len(word)

        return res


#!/usr/local/bin/python3.4
import urllib.request,flask,os,re, sys,hashlib,tempfile, shutil, contextlib,collections,mimetypes,cv2,shutil,numpy
from lxml.html import HTMLParser, document_fromstring
import lxml.etree
def get_html_at_url(url,charset="UTF-8"):
    req = urllib.request.Request(url)
    resp = urllib.request.urlopen(req)
    return resp.read().decode(charset)
def make_etree(html,url):
    parser = HTMLParser(encoding='UTF-8')
    root = document_fromstring(html,parser=parser,base_url=url)
    return root

app = flask.Flask(__name__)

@app.route('/')
def root_page():
    return flask.render_template('root.html')

@app.route('/view/')
def view_page():
    social = r"facebook.com|whatsapp.com|instagram.com|twitter.com"
    url = flask.request.args.get("url")
    if re.search(social, url):
        sys.exit(1)
    else:
        req = urllib.request.Request(url)
        rawhtml = urllib.request.urlopen(req)
        req.add_header('User-Agent', 'PurdueUniversityClassProject/1.0 (yang900@purdue.edu https://goo.gl/dk8u5S)')
        htmldecode = test(url)
        return "<base href=" + url + htmldecode.decode('UTF-8') + ">"

#--------------------------------------------------milestone2

@contextlib.contextmanager
def pushd_temp_dir(base_dir=None, prefix="tmp.hpo."):
    if base_dir is None:
        proj_dir = sys.path[0]
        # e.g., "/home/ecegridfs/a/ee364z15/hpo"

        main_dir = os.path.join(proj_dir, "data")
        # e.g., "/home/ecegridfs/a/ee364z15/hpo/data"

    # Create temp directory
    temp_dir_path = tempfile.mkdtemp(prefix=prefix, dir=base_dir)

    try:
        start_dir = os.getcwd()  # get current working directory
        os.chdir(temp_dir_path)  # change to the new temp directory
        try:
            yield
        finally:
            # No matter what, change back to where you started.
            os.chdir(start_dir)
    finally:
        # No matter what, remove temp dir and contents.
        shutil.rmtree(temp_dir_path, ignore_errors=True)

def make_filename(url, extension):
    #print(url)
    output = hashlib.sha1(url).hexdigest()
    return output+'.'+extension

@contextlib.contextmanager
def fetch_images(etree):
    with pushd_temp_dir():
        filename_to_node = collections.OrderedDict()
        imgsrc = etree.findall('.//img')
        for nodeimg in imgsrc:
            src = nodeimg.base_url + nodeimg.get('src')
            #print(src)
            resp = urllib.request.urlopen(src)
            exten = mimetypes.guess_extension(resp.info().get("Content-Type"))
            regex = r"(?P<dot>.)(?P<ext>[A-Za-z0-9]+)"
            exten = re.match(regex,exten).group(2)
            url = src.encode('utf8')
            filename = make_filename(url, exten)
            with open(os.path.join(filename), "wb") as output:
                output.write(resp.read())
            filename_to_node[filename] = nodeimg
        yield filename_to_node

def get_image_info(filename):
    faceDictList = []
    outputDict = {}
    img = cv2.imread(filename)
    face_cascade = cv2.CascadeClassifier('/home/ecegridfs/a/ee364/site-packages/cv2/data/haarcascade_frontalface_default.xml')
    img_grayscale = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    facelist = face_cascade.detectMultiScale(img_grayscale, 1.3, 5)
    outputDict["w"] = img.shape[1]
    outputDict["h"] = img.shape[0]
    for faces in facelist:
        facesDict={}
        facesDict["x"] = faces[0]
        facesDict["y"] = faces[1]
        facesDict["w"] = faces[2]
        facesDict["h"] = faces[3]
        faceDictList.append(facesDict)
        add_glasses(filename,facesDict)
    outputDict["faces"] = faceDictList
# Credit: Adapted from tutorial in OpenCV-Python Tutorials, cv2.imread, Face Detection using Haar Cascades,
#         License: PSFL https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_tutorials.html
#         https://docs.opencv.org/3.0-beta/modules/imgcodecs/doc/reading_and_writing_images.html?highlight=imread#cv2.imread
#         https://docs.opencv.org/3.4/d7/d8b/tutorial_py_face_detection.html
    return outputDict

def find_profile_photo_filename(filename_to_etree):
    for key in filename_to_etree:
            img=get_image_info(key)
            imgArea = img['w']*img['h']
            for faces in img['faces']:
                faceArea = faces['w']*faces['h']
                if (faceArea/imgArea >=0.3):
                    add_glasses(key,faces)
                    return [key,faces]
    return

def copy_profile_photo_to_static(filename):
    shutil.copy(filename, sys.path[0]+"/static")
    return os.path.join(app.static_folder,filename)

#-------------milestone3
def add_glasses(filename, face_info):
    y=0
    centerOfEyes=[]
    #print(filename)
    eye_cascade = cv2.CascadeClassifier('/home/ecegridfs/a/ee364/site-packages/cv2/data/haarcascade_eye.xml')
    image = cv2.imread(filename)
    glass_img = cv2.imread(sys.path[0]+'/testglass.png') #imporm glasses image
    img_grayscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    eyes =  eye_cascade.detectMultiScale(img_grayscale)
    for (eyeX,eyeY,eyeW,eyeH) in eyes:  #locate the center of eyes
        centerOfEyes.append([int(eyeX+0.5*eyeW), int(eyeY+0.5*eyeH)])
    if len(centerOfEyes) == 0:
        centerOfEyes.append([(int(face_info.get('w')*0.3)+face_info.get('x')), int(face_info.get('h')*0.4+face_info.get('y'))])
        centerOfEyes.append([(int(face_info.get('w')*0.7)+face_info.get('x')), int(face_info.get('h')*0.4+face_info.get('y'))])
    #---------borrow code
    overlay_img = numpy.ones(image.shape,numpy.uint8)*255
    h,w = glass_img.shape[:2]
    scaling_factor = 2.5*abs(centerOfEyes[1][0]-centerOfEyes[0][0])/w
    overlay_glasses = cv2.resize(glass_img,None,fx=scaling_factor,fy=scaling_factor,interpolation=cv2.INTER_AREA)
    x = centerOfEyes[0][0] if centerOfEyes[0][0]<centerOfEyes[1][0] else centerOfEyes[1][0]
    x -= 0.3*overlay_glasses.shape[1]
    y += 1.2*overlay_glasses.shape[0]
    h, w  = overlay_glasses.shape[:2]
    overlay_img[int(y):int(y+h), int(x):int(x+w)] = overlay_glasses
    ret, mask = cv2.threshold(cv2.cvtColor(overlay_img, cv2.COLOR_BGR2GRAY), 120, 255, cv2.THRESH_BINARY)

    #combine glass and face then save the photo in static folder
    final_img =cv2.add(cv2.bitwise_and(image, image, mask=mask),cv2.bitwise_and(overlay_img, overlay_img, mask=cv2.bitwise_not(mask)))
    cv2.imwrite(app.static_folder+"/glassesface.jpg",final_img)

    #cv2.imshow('Lets wear Glasses', final_img)
    #cv2.waitKey()
    #cv2.destroyAllWindows()
    return app.static_folder+"/glassesface.jpg"

#m3 step2

def test(url):
    html = get_html_at_url(url)
    etree = make_etree(html,url)
    path=""
    with fetch_images(etree) as filename_to_node:
        facePhotoName = find_profile_photo_filename(filename_to_node)
        path=copy_profile_photo_to_static(facePhotoName[0])

        glassFace = add_glasses(facePhotoName[0],facePhotoName[1])
        print("glassface  :",glassFace)
        static_url = flask.url_for('static', filename=os.path.basename(glassFace), _external=True)
        print("static url   :",static_url)
        phtotNode = filename_to_node.get(facePhotoName[0])
        phtotNode.set("src", static_url)
        #print("face photo: ", phtotNode)

    return lxml.etree.tostring(etree)

if __name__ == '__main__':

    app.run(host="127.0.0.1", port=os.environ.get("ECE364_HTTP_PORT", 8000),
            use_reloader=True, use_evalex=False, debug=True, use_debugger=False)
    # Credit:  Alex Quinn.  Used with permission.  Preceding line only.

    # print(make_filename('http://people.eecs.berkeley.edu/~graham/SLG1jpg.jpeg', 'jpg'))
    #filename = '43cdcd7c62213cf0af22cef70f330af53987d490.jpeg'
    #face_info = {'w': 99, 'x': 23, 'h': 99, 'y': 52}
    #add_glasses('manface.jpg', face_info)
    #test("http://alexquinn.org/")
    #get_image_info("testface.jpg")