from pdb import set_trace as bb
import numpy as np
import torch

from torch.autograd import Variable

import pyro
from pyro.distributions import DiagNormal
from pyro.distributions import Bernoulli
import visdom

# from pyro.infer.abstract_infer import LikelihoodWeighting, lw_expectation
# from pyro.infer.importance_sampling import ImportanceSampling
from pyro.infer.kl_qp import KL_QP

import torchvision.datasets as dset
import torchvision.transforms as transforms
mnist = dset.MNIST(
    root='./data',
    train=True,
    transform=None,
    target_transform=None,
    download=True)
print('dataset loaded')

def local_model(i, datum):
    beta = Variable(torch.ones(1)) * 0.5
    c = pyro.sample("class_of_datum_" + str(i), Bernoulli(beta))
    mean_param = Variable(torch.zeros(784), requires_grad=True)
    # do MLE for class means
    m = pyro.param("mean_of_class_" + str(c[0]), mean_param)

    sigma = Variable(torch.ones(m.size()))
    pyro.observe("obs_" + str(i), DiagNormal(m, sigma), datum)
    return c

def local_guide(i, datum):
    alpha = torch.ones(1) * 0.1
    beta_q = Variable(alpha, requires_grad=True)
    guide_params = pyro.param("class_posterior_", beta_q)
    c = pyro.sample("class_of_datum_" + str(i), Bernoulli(guide_params))
    return c

def inspect_posterior_samples(i):
    c = local_guide(i, None)
    mean_param = Variable(torch.zeros(784), requires_grad=True)
    # do MLE for class means
    m = pyro.param("mean_of_class_" + str(c[0]), mean_param)
    sigma = Variable(torch.ones(m.size()))
    dat = pyro.sample("obs_" + str(i), DiagNormal(m, sigma))
    return dat

#grad_step = ELBo(local_model, local_guide, model_ML=true, optimizer="adam")
optim_fct = pyro.optim(torch.optim.Adam, {'lr': .0001})

data = Variable(mnist.train_data).float() / 255.
nr_samples = data.size(0)
grad_step = KL_QP(local_model, local_guide, optim_fct)

d0 = inspect_posterior_samples(0)
d1 = inspect_posterior_samples(1)

vis = visdom.Visdom()

nr_epochs = 50
# apply it to minibatches of data by hand:
for epoch in range(nr_epochs):
    total_loss = 0.
    for i in range(nr_samples):
        # print('starting datum '+str(i))
        # mod_forward=local_model(i,data[i])
        # mod_inv=local_guide(i,data[i])
        loss_sample = grad_step(i, data[i])
        total_loss += loss_sample
        dat = inspect_posterior_samples(i)
        d2 = dat.data.numpy().reshape((28, 28))
        do2 = data[i].view(28, 28).data.numpy()
        # grad_step(i,d)
        #print("loss per sample {}".format(loss_sample))
    vis.image(d2)
    vis.image(do2)
    print("loss per epoch {}".format(total_loss / nr_samples))


from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index),
    url('search', views.search),
    url('orphan_langs', views.get_orphan_langs),
    url('interviews', views.get_interviews),
    url('add_interview', views.add_interview),
    url('delete_interview', views.delete_interview),
    url('api/developer', views.developer_api),
]


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

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

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

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

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

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

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

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

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

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

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


# Copyright 2017 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import multiprocessing
import sys
import traceback

def run_catch_report_raise(func, *args, **kwargs):
    try:
        return func(*args, **kwargs)
    except:
        print('exception in {0}():'.format(func.__name__), file=sys.stderr)
        traceback.print_exc()
        raise

def func_create_node(args):
    import rclpy

    rclpy.init()

    node_name = 'create_node_test'
    node = rclpy.create_node(node_name)
    assert node.get_name() == node_name

    rclpy.shutdown()

    return True

def func_launch(function, args, message):
    pool = multiprocessing.Pool(1)
    result = pool.apply(
        func=run_catch_report_raise,
        args=(function, args)
    )

    assert result, message
    pool.close()
    pool.join()

def test_create_node():
    func_launch(func_create_node, [], 'create node failed')


from PIL import Image
import json
import numpy as np
#import preproc_beta
import os
import datetime
import sys

# THIS ONE TAKES 2 ms

def dist(f, t):
    return int((abs(f[0]-t[0])*2 + abs(f[1]-t[1])*2 + abs(f[2]-t[2]))*0.5)

def unimportant(rgb):
    return (rgb[0] <= 200 and rgb[1] <= 200 and rgb[2] <= 200) or (rgb[1] > 200 and rgb[2] > 200 and rgb[2] >= rgb[1])

slot_state = np.zeros((14, 13))
hops = []
final_list = []
cd = [0, 0]

tt = Image.open(sys.argv[1]).rotate(180)
#tt = Image.open("ttpxt.png")

# print(datetime.datetime.time(datetime.datetime.now()))

dim = tt.size

def updateNPCoord():
    global cd
    if cd[1] < 12:
        cd = [cd[0], cd[1]+1]
    else:
        cd = [cd[0]+1, 0]

'''
filled slot = (0,255,0)
empty slot = (255,255,0)
'''
cols = [(0, 255, 0), (255, 255, 0)]

start = []  # coordinates of the starting point

i = 0
while i < dim[0]:
    j = 0
    while j < dim[1]:
        rgb = tt.getpixel((i, j))
        if unimportant(rgb) == False:
            start = [i, j]
            i = dim[0]  # breaking the outer loop
            break  # breaking the inner loop
        j = j + 1
    i = i + 1

j = start[1]
i = start[0]

try:
    for b in range(14):

        for a in range(13):
            RGB = tt.getpixel((i, j))
            if unimportant(RGB) == False:
                if dist((203, 254, 51), RGB) < dist((255, 255, 204), RGB):
                    slot_state[cd[0], cd[1]] = 1

            updateNPCoord()

            if a == 12:
                break

            if b == 0:
                h = 1
                i = i + 1
                while unimportant(tt.getpixel((i, j))) == False:
                    i = i + 1
                    h = h + 1
                while unimportant(tt.getpixel((i, j))) == True:
                    i = i + 1
                    h = h + 1
                hops.append(h)
            else:
                i = i + hops[a]

    # printing
    # for x in range(13):
    #    print(int(slot_state[b][a]), end=' ')
    # print('\n')

        if b == 13:
            break

        i = start[0]
        j = j + 1
        while unimportant(tt.getpixel((i, j))) == False:
            j = j + 1
        while unimportant(tt.getpixel((i, j))) == True:
            j = j + 1

except IndexError:
    if cd[0] < 10 or cd[1] != 0:
        x = input("BAD FILE: Please upload a proper time table image...")
        exit()

# in case of a correctly cropped image, empty rows need be added to the top
# of the table, before rotation
for x in range(14 - cd[0]):
    tr = np.zeros(13)
    i = 13
    while i >= 1:
        slot_state[i] = slot_state[i-1]
        i = i - 1
    slot_state[0] = tr

# rotating the array
slot_state = np.rot90(slot_state, 2, (0, 1))

'''a = 0
while a < 13:
    b = 0
    while b < 13:
        final_list.append(int(slot_state[a,b] + slot_state[a+1, b]))
        b = b + 1
    a = a + 2'''

f = []
for i in range(0, 5):
    f.append([])
    for j in range(0, 22):
        f[i].append(0)
k = 0
for i in range(0, 10, 2):
    if slot_state[i][0] == 0 and slot_state[i+1][0] == 0:
        f[k][0] = 1
    if slot_state[i][0] == 0 and slot_state[i+1][0] == 0 and slot_state[i+1][1] == 0:
        f[k][1] = 1
    if slot_state[i][1] == 0 and slot_state[i+1][1] == 0:
        f[k][2] = 1
    if slot_state[i][1] == 0:
        f[k][3] = 1
    if slot_state[i][2] == 0 and slot_state[i+1][2] == 0:
        f[k][4] = 1
    if slot_state[i][2] == 0 and slot_state[i+1][2] == 0 and slot_state[i+1][3] == 0:
        f[k][5] = 1
    if slot_state[i, 3] == 0 and slot_state[i+1][3] == 0:
        f[k][6] = 1
    if slot_state[i][3] == 0 and slot_state[i+1][4] == 0:
        f[k][7] = 1
    if slot_state[i][4] == 0 and slot_state[i+1][4] == 0 and slot_state[i+1][5] == 0:
        f[k][8] = 1
    if slot_state[i][4] == 0 and slot_state[i+1][5] == 0:
        f[k][9] = 1
    if slot_state[i][6] == 0 and slot_state[i+1][6] == 0:
        f[k][10] = 1
    if slot_state[i][6] == 0 and slot_state[i+1][6] == 0 and slot_state[i+1][7] == 0:
        f[k][11] = 1
    if slot_state[i][7] == 0 and slot_state[i+1][7] == 0:
        f[k][12] = 1
    if slot_state[i][7] == 0:
        f[k][13] = 1
    if slot_state[i][8] == 0 and slot_state[i+1][8] == 0:
        f[k][14] = 1
    if slot_state[i][8] == 0 and slot_state[i+1][8] == 0 and slot_state[i+1][9] == 0:
        f[k][15] = 1
    if slot_state[i][9] == 0 and slot_state[i+1][9] == 0:
        f[k][16] = 1
    if slot_state[i][9] == 0 and slot_state[i+1][10] == 0:
        f[k][17] = 1
    if slot_state[i][10] == 0 and slot_state[i+1][10] == 0 and slot_state[i+1][11] == 0:
        f[k][18] = 1
    if slot_state[i][10] == 0 and slot_state[i+1][11] == 0:
        f[k][19] = 1
    if slot_state[i][12] == 0:
        f[k][20] = 1
    if slot_state[i][12] == 0:
        f[k][21] = 1
    k = k+1

# print(datetime.datetime.time(datetime.datetime.now()))
# os.remove("ttpxt.png")
# print(json.dumps(final_list))
'''i=0
for y in final_list:
    if(i==0):
        s="Monday"
        print(s)
        print("\n")
    elif(i==13):
        s="Tuesday"
        print("\n")
        print(s)
    elif(i==26):
        s="Wednesday"
        print("\n")
        print(s)
    elif(i==39):
        s="Thrusday"
        print("\n")
        print(s)
    elif(i==52):
        s="Friday"
        print("\n")
        print(s)

    if(y==0):
            if(i%13==0):
                print("8:00-9:00 ")
            if(i%13==1):
                print("9:00-10:00 ")
            if(i%13==2):
                print("10:00-11:00 ")
            if(i%13==3):
                print("11:00-12:00 ")
            if(i%13==4):
                print("12:00-13:00 ")
            if(i%13==5):
                print("13:00-14:00 ")
            if(i%13==6):
                print("14:00-15:00 ")
            if(i%13==7):
                print("15:00-16:00 ")
            if(i%13==8):
                print("16:00-17:00 ")
            if(i%13==9):
                print("17:00-18:00 ")
            if(i%13==10):
                print("18:00-18:50 ")
            if(i%13==11):
                print("18:50-19:00 ")
            if(i%13==12):
                print("19:00-20:00 ")
    if(i==64):
        break
    i=i+1
    '''
print(f)

# x = input("\nGive any input to continue...")

exit()


from django.urls import path
from . import views
from django.urls import path, include
from django.contrib.auth import views as auth_views

app_name = 'products'

urlpatterns = [
    path('', views.product_list, name='product_list'),
    path('api/messages/<int:receiver_id>/', views.message_list, name='message-list'),
    path('login/', auth_views.LoginView.as_view(),name = 'login'),
    path('logout/', auth_views.LogoutView.as_view(), name = 'logout'),
    path('list/', views.product_list, name='product_list'),
    path('categories/', views.category_list, name='category_list'),
    path('listbycategory/<str:category_slug>/', views.product_list_by_cat, name='product_list_by_category'),
    path('product_detail/<int:id>/', views.product_detail, name='product_detail'),
    path('dashboard/', views.dashboard, name='dashboard'),
    path('addcategory/', views.add_category, name='add_category'),
    path('addproduct/', views.add_product, name='add_product'),
    path('createuser/', views.create_user, name='createuser'),
]


import json
# import logging

from django.http import HttpResponse
# from django.shortcuts import get_object_or_404

from mainapp.views.base_view import BaseView
from mainapp.models import Retailer, Item
from mainapp.dto.json_response import JsonResponse

# API: http://localhost:8000/retailer/Batalan/product/B1
class QuestionListView(BaseView):
    def get(self, request, retailer_id, product_id):
        # logger = logging.getLogger(__name__)

        # The request will always be satisfied by a JsonResponse
        response = JsonResponse()

        # Attempt to get the specified retailer
        try:
            retailer = Retailer.objects.get(merchant_id=retailer_id)
        except Retailer.DoesNotExist:
            # Retailer doesn't exist so update the JsonResponse and send it back
            response.success = False
            response.errors['request_failed'] = "No retailer found for id %s" % retailer_id
            return HttpResponse(json.dumps(response.to_dict()), content_type="application/json", status=403)

         # Now try to find the specified item
        try:
            item = Item.objects.get(retailer_id=retailer.id, retailer_product_id=product_id)
            response.payload = item.to_dict()
            response.success = True

        except Item.DoesNotExist:
            # no item found so return a response
            response.errors['request_failed'] = "No item found for id %s" % product_id
            return HttpResponse(json.dumps(response.to_dict()), content_type="application/json", status=404)

        except Item.MultipleObjectsReturned:
            # this shouldn't happen but need to handle it just in case
            response.errors['request_failed'] = "Multiple items found for id %s and retailer %s. This should not happen!" % (product_id, retailer_id)
            return HttpResponse(json.dumps(response.to_dict()), content_type="application/json", status=404)

        return HttpResponse(json.dumps(response.to_dict()), content_type="application/json", status=200)


import os
from IPython.display import Image, display
from tensorflow.keras.preprocessing.image import load_img
import PIL
from PIL import ImageOps
import re
import numpy as np
import tensorflow as tf
import keras
from keras import layers
from tensorflow.python.client import device_lib
import random
from tensorflow.keras.models import Model
import matplotlib.pyplot as plt
from keras import backend as K
from keras.callbacks import Callback
from sklearn.model_selection import train_test_split
from datetime import datetime
from tensorflow.keras import regularizers
# import neptune.new as neptune
import neptune
from decouple import config
import json
import keras_tuner as kt

access_token = config('NEPTUNE_API_TOKEN')
########################################################################################################################
run = neptune.init(project_qualified_name='abdalraheem.ijjeh/PhCs-dispersion-curves',
                   api_token=access_token)
neptune.create_experiment('regression model')
neptune.append_tag('regression')
########################################################################################################################
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = '2'

# working path env
env_path = '/home/aijjeh/Desktop/Phd_Projects/PC_uint_cell_dispersion_curves/'

# Hyperparameters
hyperparameters = {'samples': 7000,
                   'n_size': 6650,
                   'normalised': True,
                   'batches': 32,
                   'num_filters': 8,
                   'kernel_size': 3,
                   'img_shape': (256, 256, 1),
                   'epochs': 10000,
                   'dropout': 0.2,
                   'levels': 8,
                   'learning_rate': 3e-4,
                   'patience_epochs': 3000,
                   'val_split': 0.075,
                   'hidden_layer': 3,
                   'decay:steps': 100000,
                   'decay_rate': 0.96}

os.chdir(env_path)
json = json.dumps(hyperparameters)
f = open('hyper_par.json', 'w')
f.write(json)
f.close()

# Learning schedule
# lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
#     hyperparameters['learning_rate'],
#     decay_steps=hyperparameters['decay:steps'],
#     decay_rate=hyperparameters['decay_rate'],
#     staircase=False)
#
# Optimizer = keras.optimizers.Adam(hyperparameters['learning_rate'])

#  Loading dataset
def load_dataset():
    os.chdir(env_path + 'dataset/')

    X_train = np.load('train_xy_img_samples_%d.npy' % hyperparameters['samples'])
    print(X_train.shape)

    Y_train = np.load('train_y_samples_%d.npy' % hyperparameters['samples'])

    print(Y_train.shape)

    if hyperparameters['normalised']:
        Y_train = Y_train[:, :, 0] / np.max(Y_train[:, :, 0])
        normal_ = 'normalised'
    else:
        Y_train = Y_train[:, :, 0]
        normal_ = 'not_normalised'

    x_train = X_train[:hyperparameters['n_size']]
    y_train = Y_train[:hyperparameters['n_size']]

    return x_train, y_train, normal_

########################################################################################################################
# Model
########################################################################################################################
def conv_block(in_blk, num, k_size):
    layer11 = tf.keras.layers.Conv2D(num,
                                     (k_size, k_size),
                                     padding='same',
                                     activation='relu',
                                     )(in_blk)
    # layer12 = tf.keras.layers.Conv2D(num,
    #                                  (k_size, k_size),
    #                                  padding='same',
    #                                  activation='relu')(layer11)
    # concat = tf.keras.layers.concatenate([layer11, layer12], axis=-1)  # , in_blk
    # BN_layer = tf.keras.layers.BatchNormalization()(layer11)
    return layer11

def root_mean_squared_error(y_true, y_pred):
    return K.sqrt(K.mean(K.square(y_pred - y_true)))

def custom_loss(y_true, y_pred):
    return tf.keras.losses.MSE(y_true, y_pred)

def coeff_determination(y_true, y_pred):
    SS_res = K.sum(K.square(y_true - y_pred))
    SS_tot = K.sum(K.square(y_true - K.mean(y_true)))
    return 1 - SS_res / (SS_tot + K.epsilon())

def build_model(hp):
    inputs_1 = tf.keras.Input(shape=hyperparameters['img_shape'])
    # x = tf.image.resize(inputs_1, (128, 128))
    # x = tf.keras.layers.Flatten()(inputs_1)

    # x1 = inputs_1
    # x_fft = tf.transpose(x1, [0, 3, 1, 2])
    # x_fft = tf.signal.fft2d(tf.cast(x_fft, dtype=tf.complex64))
    # x_fft = tf.signal.fftshift(x_fft, axes=(-2, -1))
    # x_fft = tf.transpose(x_fft, [0, 2, 3, 1])
    # x_fft = abs(x_fft)
    # print(x_fft)

    # x = tf.keras.layers.concatenate([inputs_1, x_fft], axis=-1)
    # print(x)
    x = inputs_1
    # skip_tensor = []
    for i in range(hp.Int('conv_blocks', min_value=3, max_value=8, default=3)):  # Int specifies the dtype of the values
        filters = hp.Int('filters_' + str(i), min_value=8, max_value=32, step=4)
        k_size = hp.Int('k_size', min_value=3, max_value=7, step=2)
        x = conv_block(x, filters, k_size)
        if hp.Choice('pooling_' + str(i), ['avg', 'max']) == 'max':  # hp.Choice chooses from a list of values
            x = tf.keras.layers.MaxPool2D()(x)
        else:
            x = tf.keras.layers.AvgPool2D()(x)
        # x = tf.keras.layers.MaxPool2D((2, 2))(x)
        # skip_tensor.append(x)

    # for j in reversed(range(int(hyperparameters['levels'] / 2) - 1, hyperparameters['levels'])):
    #     x = tf.keras.layers.concatenate((x, skip_tensor[j]), axis=-1)
    #     x = tf.keras.layers.UpSampling2D((2, 2))(x)
    #     x = conv_block(x, hyperparameters['num_filters'] * 2 ** j, hyperparameters['kernel_size'])

    # x = tf.keras.layers.Conv2D(1, 1, padding='same', activation='sigmoid')(x)
    # x = tf.keras.layers.Flatten()(x)
    # output1 = tf.keras.layers.GlobalAvgPool2D()(x)

    output1 = tf.keras.layers.Flatten()(x)
    output1 = tf.keras.layers.Dense(output1.shape[-1],
                                    activation='relu')(output1)

    h_levels = hp.Int('h_levels', min_value=1, max_value=3, step=1)

    for h in range(h_levels):
        dropouts_l = hp.Float('dropout', min_value=.1, max_value=.35, step=0.05, default=None)
        dense_units = hp.Int('units', min_value=1024, max_value=8192, step=512)
        output1 = tf.keras.layers.Dense(dense_units,
                                        activation='relu')(output1)
        output1 = tf.keras.layers.Dropout(dropouts_l)(output1)

    # dense_units_1 = hp.Int('units1', min_value=1464, max_value=2042, step=32)
    #
    # output1 = tf.keras.layers.Dense(dense_units_1,
    #                                 activation='relu')(output1)
    # output1 = tf.keras.layers.Dropout(dropouts_l)(output1)
    # output1 = tf.keras.layers.Dense(dense_units_1,
    #                                 activation='relu')(output1)
    # output1 = tf.keras.layers.Dropout(hp.Float('dropout',
    #                                            min_value=.15,
    #                                            max_value=.35,
    #                                            step=0.05,
    #                                            default=None))(output1)
    output1 = tf.keras.layers.Dense(1464)(output1)

    ####################################################################################################################
    # Model
    ####################################################################################################################
    model = tf.keras.models.Model(inputs=inputs_1, outputs=output1, name='AE_Model')
    model.compile(optimizer=keras.optimizers.Adam(hp.Float('learning_rate',
                                                           min_value=9e-5,
                                                           max_value=9e-4,
                                                           sampling='log')),
                  loss=custom_loss,
                  metrics=[tf.keras.metrics.RootMeanSquaredError()],
                  run_eagerly=True)

    model.summary()

    return model

# initialize tuner to run the model.
# using the Hyper band search algorithm
tuner = kt.Hyperband(
    hypermodel=build_model,
    objective='val_loss',
    max_epochs=200,
    factor=3,
    hyperband_iterations=1,
    directory="Keras_tuner_dir",
    project_name="Keras_tuner_Demo")

# calling dataset func
X, Y, s = load_dataset()

checkpoint_filepath = env_path + 'temp/checkpoint/PC_model_%s_%d_lr_%s_filters_%d_levels_%d_batches_%d_epochs_%d_dropout_%s_val_split_%s_hidden_%d.h5' % (
    s,
    hyperparameters['samples'],
    hyperparameters['learning_rate'],
    hyperparameters['num_filters'],
    hyperparameters['levels'],
    hyperparameters['batches'],
    hyperparameters['epochs'],
    hyperparameters['dropout'],
    hyperparameters['val_split'],
    hyperparameters['hidden_layer'])

callbacks = [tf.keras.callbacks.EarlyStopping(monitor='val_root_mean_squared_error',
                                              patience=hyperparameters['patience_epochs'],
                                              mode='min'),
             tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_filepath,
                                                monitor='val_loss',
                                                save_best_only=True)]

# Run the search
tuner.search(X, Y,
             validation_split=hyperparameters['val_split'],
             epochs=hyperparameters['epochs'],
             callbacks=[callbacks])

# Get the optimal hyperparameters
best_hps = tuner.get_best_hyperparameters(1)[0]

# get the best model
best_model = tuner.get_best_models(1)[0]

nblocks = best_hps.get('conv_blocks')
nlevels = best_hps.get('h_levels')

print(f'Number of conv blocks: {nblocks}')
for hyparam in [f'filters_{i}' for i in range(nblocks)] + [f'pooling_{i}' for i in range(nblocks)] + ['h_levels'] \
               + ['units'] + ['dropout'] + ['learning_rate'] + ['k_size']:
    print(f'{hyparam}: {best_hps.get(hyparam)}')

# display model structure
# plot_model(best_model, 'best_model.png', show_shapes=True)

# show model summary
best_model.summary()
ANN_model = tuner.hypermodel.build(best_hps)

history = ANN_model.fit(x=X,
                        y=Y,
                        batch_size=hyperparameters['batches'],
                        validation_split=hyperparameters['val_split'],
                        epochs=hyperparameters['epochs'],
                        callbacks=[callbacks])

val_acc_per_epoch = history.history['val_loss']
best_epoch = val_acc_per_epoch.index(max(val_acc_per_epoch)) + 1
print('Best epoch: %d' % (best_epoch,))

hypermodel = tuner.hypermodel.build(best_hps)
hypermodel.fit(X, Y, epochs=best_epoch, validation_split=0.2)

os.chdir(env_path + 'h5_models/')
hypermodel.save("VAE_Quarter_samples_%d_encoder_latent_decoder_dense_ver_3.h5" % hyperparameters['samples'])


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

import pickle

import plotly.express as px

# import plotly.offline as pyo
import plotly.graph_objs as go

import_thing = pickle.load(open("../data/processed/final_forecast.p", "rb"))
df_fcst = import_thing["forecast"]
df_billings = import_thing["billings"]
df_billings["is_forecast"] = 0
df_fcst["is_forecast"] = 1

df = pd.concat([df_billings, df_fcst], join="outer", ignore_index=True)
df = df.fillna(0)
df.sort_values(by=["curr", "BU", "period"], inplace=True)

df["period"] = df["period"].astype("string")

df_2019 = df[df["period"].str.match("2019")]

df2 = (
    df_2019.set_index(["curr", "BU", "period"])
    .stack()
    .reset_index(name="Val")
    .rename(columns={"level_1": "X"})
)

df_2019_US = df2[df2["level_3"].str.contains("_US")].copy()
df_2019_US["curr"] = df_2019_US["curr"].astype("string")
df_2019_US["BU"] = df_2019_US["BU"].astype("string")
df_2019_US["period"] = df_2019_US["period"].astype("string")
df_2019_US["level_3"] = df_2019_US["level_3"].astype("string")
df_2019_US.rename(columns={"level_3": "type"}, inplace=True)

df_2019_gb = df_2019_US.groupby(["curr", "BU", "type"]).sum()

df_2019_gb.reset_index(inplace=True)
df_2019_gb["base"] = "test"
print(df_2019_gb.head(10))
print(len(df_2019_gb))

df_2019_gb = df_2019_gb[df_2019_gb["Val"] > 0]

fig = px.sunburst(df_2019_gb, path=["BU", "curr", "type"], values="Val")
fig.show()


from numpy import *
import sqlite3
import sys
import scipy
import Gnuplot, Gnuplot.funcutils, time

class DiscreteSurprisalDistrubution(object):
    def graph(self,surprisal_database):
        surprisal_list = self.readGraph(surprisal_database)

        if surprisal_list:
            surprisal_list.sort()
            float_values = [float(j) for j in surprisal_list]
            total = float(len(float_values))
            (float_values,bins) = scipy.histogram(float_values, bins=1000)
            float_values = [i/total for i in float_values]
            plot = Gnuplot.Gnuplot(persist=1)
            plot.xlabel("surprisal")
            plot.ylabel("Frequency")
            dat = Gnuplot.Data(float_values)
            plot.plot(dat)

    def readGraph(self, surprisal_database):
        # Create database
        surprisal_list = []

        # Get the number of changes
        conn = sqlite3.connect(surprisal_database)
        c = conn.cursor()
        c.execute("SELECT * FROM surprisal_data")
        for row in c:
            surprisal_list.append(row[1])
        conn.close()
        return surprisal_list

if __name__ == '__main__':
    d = DiscreteSurprisalDistrubution()
    d.graph(sys.argv[1])


from django.test import TestCase, Client
from django.urls import reverse

from unittest.mock import patch
from rest_framework.test import APITestCase

class ViewsTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.home_url = reverse('home')

    def test_home_GET(self):
        response = self.client.get(self.home_url)

        self.assertEquals(response.status_code, 200)
        self.assertTemplateUsed(response, 'core/home.html')

    def test_home_POST(self):
        with patch('core.views.convert') as mocked_convert:
            mocked_convert.return_value = 20
            response = self.client.post(self.home_url, data={
                'convert_from': 'USD',
                'convert_into': 'EUR',
                'amount': '10',
            })

            self.assertEquals(response.status_code, 200)
            self.assertTemplateUsed(response, 'core/home.html')
            self.assertEquals(response.context['amount'], 20)

class ConverterTestCase(TestCase):
    def test_convert(self):
        with patch('core.converter.get_rates') as mocked_get_rates:
            mocked_get_rates.return_value = {'CZK': 23.232026, 'EUR': 0.919583, 'PLN': 3.95897, 'USD': 1}
            response = self.client.post(reverse('home'), data={
                'convert_from': 'USD',
                'convert_into': 'EUR',
                'amount': '1',
            })
            self.assertEquals(response.context['amount'], 0.919583)

class ApiTestCase(APITestCase):
    def setUp(self):
        self.api_convert_url = reverse('api-convert')

    def test_api_convert(self):
        with patch('core.converter.get_rates') as mocked_get_rates:
            mocked_get_rates.return_value = {'CZK': 23.232026, 'EUR': 0.919583, 'PLN': 3.95897, 'USD': 1}
            data = {'convert_from': 'USD', 'convert_into': 'EUR', 'amount': '1'}
            response = self.client.get(self.api_convert_url, data)

            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.data['amount'], 0.919583)

    def test_api_convert_invalid_data(self):
        data = {'convert_from': 'USD', 'convert_into': 'EUR', 'amount': 'oops'}
        response = self.client.get(self.api_convert_url, data)

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.data['Error'], 'Invalid data')

    def test_api_convert_unsupported_currency(self):
        data = {'convert_from': 'UDD', 'convert_into': 'RUB', 'amount': '1'}
        response = self.client.get(self.api_convert_url, data)

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.data['Error'], 'Unsupported currency')


from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.selector import HtmlXPathSelector

from blackwidow.items import HeelsItem

class FancySpider(CrawlSpider):

    name = 'fancy'
    allowed_domains = ['fancy.com', ]
    start_urls = ['http://fancy.com/vinta', ]

    rules = (
        # find next page
        Rule(
            SgmlLinkExtractor(
                allow=(r'vinta/fancyd/\d+', ),  # http://fancy.com/vinta/fancyd/1365620197
                restrict_xpaths=('//div[@id="content"]//div[contains(@class, "pagination")]', ),
                unique=True,
            ),
            follow=True,
        ),
        # find detail page then parse it
        Rule(
            SgmlLinkExtractor(
                allow=(r'things/\d+/\S+', ),  # http://fancy.com/things/392410187429841177/Lenny-Sandals-by-MIA
                restrict_xpaths=('//div[@id="content"]//ol[contains(@class, "stream")]', ),
                unique=True,
            ),
            callback='parse_item_detail',
        ),
    )

    def parse_item_detail(self, response):
        """
        Scrapy creates scrapy.http.Request objects for each URL in the
        start_urls attribute of the Spider, and assigns them the parse method
        of the spider as their callback function.
        """

        hxs = HtmlXPathSelector(response)

        item = HeelsItem()

        item['comment'] = hxs.select('//*[@id="content"]//figure//figcaption/text()').extract()
        item['image_urls'] = hxs.select('//*[@id="content"]//span[contains(@class, "wrapper-fig-image")]//img/@src').extract()
        item['source_url'] = response.url

        return item


import numpy as np
from scipy.optimize import fsolve

def equations(p):
    x, y = p
    return y - x**2 + 1, np.exp(x) + x*(1 - y) - 1

result = []
for i in range(-10, 10):
    x1, y1 = fsolve(equations, (i, i))
    x1 = round(x1, 6)
    y1 = round(y1, 6)
    if (x1, y1) not in result:
        result.append((x1, y1))
print(result)


"""Tests for pycounter.sushi"""

from __future__ import absolute_import

import unittest
import os
from httmock import urlmatch, HTTMock
import datetime

from pycounter import sushi
import pycounter.exceptions

@urlmatch(netloc=r'(.*\.)?example\.com$')
def sushi_mock(url, request):
    path = os.path.join(os.path.dirname(__file__),
                        'data', 'sushi_simple.xml')
    with open(path, 'rb') as datafile:
        return datafile.read().decode('utf-8')

@urlmatch(netloc=r'(.*\.)?example\.com$')
def bogus_mock(url, request):
    return "Bogus response with no XML"

class TestHelpers(unittest.TestCase):
    def test_ns(self):
        self.assertEqual(
            sushi._ns("sushi", "name"),
            "{http://www.niso.org/schemas/sushi}name")

class TestConvertRawSimple(unittest.TestCase):
    def setUp(self):
        path = os.path.join(os.path.dirname(__file__),
                            'data', 'sushi_simple.xml')
        with open(path, 'rb') as datafile:
            self.report = sushi._raw_to_full(datafile.read())

    def test_report(self):
        self.assertEqual(self.report.report_type, u'JR1')
        self.assertEqual(self.report.report_version, 4)

class TestSushiRequest(unittest.TestCase):
    def setUp(self):
        with HTTMock(sushi_mock):
            self.report = sushi.get_report('http://www.example.com/Sushi',
                                           datetime.date(2015, 1, 1),
                                           datetime.date(2015, 1, 31)
                                           )

    def test_report(self):
        self.assertEqual(self.report.report_type, u'JR1')
        self.assertEqual(self.report.report_version, 4)

class TestBogusXML(unittest.TestCase):
    def test_request(self):
        with HTTMock(bogus_mock):
            self.assertRaises(pycounter.exceptions.SushiException,
                              sushi.get_report,
                              'http://www.example.com/bogus',
                              datetime.date(2015, 1, 1),
                              datetime.date(2015, 1, 31)
                              )


"""Run reduced model
Select a reduced subset of parameters
to vary in the model
"""

from model import fcn, dim_mat
import numpy as np
import matplotlib.pyplot as plt
import pyutil.numeric as ut
from numpy.linalg import norm
from scipy.linalg import svd, qr
from copy import copy

## Setup
# --------------------------------------------------
n_samp = int(1e2)
# par = range(7)                  # Parameter indices to include, ascending
par = [0,1,3,4,5,6]             # Skip A_0
m   = len(par)
tol = 1e-3                      # Tolerance for matrix_rank
u   = np.array([1,1,-2])        # Units for thrust

# Make nominal values global, len=7
P_0 = 101e3                     # Freestream pressure, Pa
P_e = P_0 * 10                  # Exit pressure, Pa
A_0 = 1.5                       # Capture area, m^2
A_e = 1.                        # Nozzle exit area, m^2
U_0 = 100.                      # Freestream velocity, m/s
U_e = U_0 * 2                   # Exit velocity, m/s
a_0 = 343.                      # Ambient sonic speed, m/s

X_nom = np.array([P_0,P_e,A_0,A_e,U_0,U_e,a_0])

## Function definitions
# --------------------------------------------------
_epsilon = np.sqrt(np.finfo(float).eps)

def grad(x,f,f0=None,h=_epsilon):
    """Computes a FD approximation to the gradient
    at a point
    """
    # If necessary, calculate f(x)
    if f0:
        pass
    else:
        f0 = f(x)

    # Ensure query point is np.array
    if type(x).__module__ == np.__name__:
        pass
    else:
        x = np.array(x)

    # Calculate gradient
    dF = np.empty(np.size(x))   # Reserve space
    E  = np.eye(np.size(x))     # Standard basis
    for i in range(np.size(x)):
        dF[i] = (f(x+E[:,i]*h)-f0)/h

    return dF

## Run script
# --------------------------------------------------
# Parameter bounds
fac = 1.15

X_l = np.array(X_nom)*fac
X_u = np.array(X_nom)/fac

# Log-Parameter bounds
logq_l = np.log(X_l); logq_u = np.log(X_u)
# Log-Objective and gradient
xpt = lambda q: np.exp(0.5*(q+1) * (logq_u-logq_l) + logq_l)
def qpt(p):
    res = copy(X_nom)
    res[par] = p
    return res

fun = lambda p: fcn(xpt(qpt(p)))

# Monte Carlo method
Q_samp = 2*np.random.random((n_samp,m)) - 1
F_samp = []
G_samp = []
for ind in range(n_samp):
    # Evaluate function at point
    # q = Q_samp[ind]
    f_val = fun(Q_samp[ind])
    g_val = grad(Q_samp[ind],fun,f0=f_val)*2/(logq_u[par]-logq_l[par])
    # Record values
    F_samp.append(f_val)
    G_samp.append(g_val)
# Construct C
G = np.array(G_samp)
C = G.T.dot(G)
# Compute Active Subspace
W,L,_ = svd(C)

# Console output
print("Computation complete!")
print("L = {}".format(L))

## Analysis
# --------------------------------------------------
D = np.array(dim_mat)[:,par]    # Take only used parameters
N = ut.null(D)

#
as_dim = ut.as_dim(L)
W_1 = W[:,:as_dim]
dim = D.dot(W_1)
rnk = np.linalg.matrix_rank(dim,tol=tol)

# Project out the dimensions of thrust
Qtmp,Rtmp = qr(np.concatenate((ut.col(u),dim),axis=1))
Qc = Qtmp[:,1:rnk]; Qc = Qc / Qc[0]

# Console printout
print("dim = \n{}".format(dim))
print("rank(dim) = {}".format(rnk))


# -*- coding: utf-8 -*-

from odoo import models, fields, api
import base64
from lxml import etree

import logging
_logger = logging.getLogger(__name__)

from .special_dict import CaselessDictionary

class IrAttachment(models.Model):
    _inherit = 'ir.attachment'

    @api.depends('invoice_ids')
    def _compute_account_invoice_count(self):
        for attach in self:
            try:
                attach.invoice_count = len(attach.invoice_ids)
            except Exception:
                pass
    @api.depends('payment_ids')
    def _compute_account_payment_count(self):
        for attach in self:
            try:
                attach.payment_count = len(attach.payment_ids)
            except Exception:
                pass

    cfdi_uuid = fields.Char("CFDI UUID", copy=False)
    #cfdi_type = fields.Selection([('E','Emisor'),('R','Receptor')],"CFDI Invoice Type", copy=False)
    cfdi_type = fields.Selection([
    ('I', 'Facturas de clientes'), #customer invoice, Emisor.RFC=myself.VAT, Customer invoice
    ('SI', 'Facturas de proveedor'), #Emisor.RFC!=myself.VAT, Supplier bill
    ('E', 'Notas de crédito clientes'), #customer credit note, Emisor.RFC=myself.VAT, Customer credit note
    ('SE', 'Notas de crédito proveedor'), #Emisor.RFC!=myself.VAT, Supplier credit note
    ('P', 'REP de clientes'), #Emisor.RFC=myself.VAT, Customer payment receipt
    ('SP', 'REP de proveedores'), #Emisor.RFC!=myself.VAT, Supplier payment receipt
    ('N', 'Nominas de empleados'), #currently we shall not do anythong with this type of cfdi, Customer Payslip
    ('SN', 'Nómina propia'), #currently we shall not do anythong with this type of cfdi, Supplier Payslip
    ('T', 'Factura de traslado cliente'), #currently we shall not do anythong with this type of cfdi, WayBill Customer
    ('ST', 'Factura de traslado proveedor'),], #currently we shall not do anythong with this type of cfdi, WayBill Supplier
    "Tipo de comprobante",
    copy=False)

    date_cfdi = fields.Date('Fecha')
    rfc_tercero = fields.Char("RFC tercero")
    nombre_tercero = fields.Char("Nombre tercero")
    cfdi_total = fields.Float("Importe")
    creado_en_odoo = fields.Boolean("Creado en odoo", copy=False)
    invoice_ids = fields.One2many("account.invoice",'attachment_id',"Facturas")
    invoice_count = fields.Integer(compute='_compute_account_invoice_count', string='# de facturas', store=True)

    payment_ids = fields.One2many("account.payment",'attachment_id',"Pagos")
    payment_count = fields.Integer(compute='_compute_account_payment_count', string='# de pagos', store=True)

    serie_folio = fields.Char("Folio")

    @api.model
    def create(self, vals):
        ctx = self._context.copy()
        if ctx.get('is_fiel_attachment'):
            datas = vals.get('datas')
            if datas:
                xml_content = base64.b64decode(datas)
                if b'xmlns:schemaLocation' in xml_content:
                    xml_content = xml_content.replace(b'xmlns:schemaLocation', b'xsi:schemaLocation')
                try:
                    tree = etree.fromstring(xml_content)
                except Exception as e:
                    _logger.error('error : '+str(e))
                    raise
                try:
                    ns = tree.nsmap
                    ns.update({'re': 'http://exslt.org/regular-expressions'})
                except Exception:
                    ns = {'re': 'http://exslt.org/regular-expressions'}

                tfd_namespace = {'tfd': 'http://www.sat.gob.mx/TimbreFiscalDigital'}
                tfd_elements = tree.xpath("//tfd:TimbreFiscalDigital", namespaces=tfd_namespace)
                tfd_uuid = tfd_elements and tfd_elements[0].get('UUID')
                cfdi_type = vals.get('cfdi_type','I')

                if cfdi_type in ['I','E','P','N','T']:
                    element_tag = 'Receptor'
                else:
                    element_tag = 'Emisor'
                try:
                    elements = tree.xpath("//*[re:test(local-name(), '%s','i')]"%(element_tag), namespaces=ns)
                except Exception:
                    _logger.info("No encontró al Emisor/Receptor")
                    elements = None
                client_rfc, client_name = '', ''
                if elements:
                    attrib_dict = CaselessDictionary(dict(elements[0].attrib))
                    client_rfc = attrib_dict.get('rfc')
                    client_name = attrib_dict.get('nombre')

                vals.update({
                        'cfdi_uuid' :tfd_uuid,
                        'rfc_tercero' : client_rfc,
                        'nombre_tercero' : client_name,
                        'cfdi_total' : tree.get('Total', tree.get('total')),
                        'date_cfdi' : tree.get('Fecha',tree.get('fecha')),
                        'serie_folio' : tree.get('Folio',tree.get('folio'))
                    })
        return super(IrAttachment, self).create(vals)

    @api.multi
    def action_view_payments(self):
        payments = self.mapped('payment_ids')
        if payments and payments[0].payment_type=='outbound':
            action = self.env.ref('account.action_account_payments_payable').read()[0]
        else:
            action = self.env.ref('account.action_account_payments').read()[0]

        if len(payments) > 1:
            action['domain'] = [('id', 'in', payments.ids)]
        elif len(payments) == 1:
            action['views'] = [(self.env.ref('account.view_account_payment_form').id, 'form')]
            action['res_id'] = payments.ids[0]
        else:
            action = {'type': 'ir.actions.act_window_close'}
        return action

    @api.multi
    def action_view_invoice(self):
        invoices = self.mapped('invoice_ids')
        action = self.env.ref('account.action_invoice_tree1').read()[0]
        if len(invoices) > 1:
            action['domain'] = [('id', 'in', invoices.ids)]
        elif len(invoices) == 1:
            action['views'] = [(self.env.ref('account.invoice_form').id, 'form')]
            action['res_id'] = invoices.ids[0]
        else:
            action = {'type': 'ir.actions.act_window_close'}
        return action

    @api.multi
    def action_renmove_invoice_link(self):
        for attach in self:
            if attach.invoice_ids:
                attach.invoice_ids.write({'attachment_id' : False})
            if attach.payment_ids:
                attach.payment_ids.write({'attachment_id' : False})
            vals = {'res_id':False, 'res_model':False, 'l10n_mx_edi_cfdi_name':False}
            if attach.creado_en_odoo:
                vals.update({'creado_en_odoo':False})
                #attach.creado_en_odoo=False
            attach.write(vals)
        return True


import json
import os
from pprint import pprint

from fastapi import File, UploadFile, APIRouter, Form
from fastapi.responses import FileResponse

from db.paper import db_upload_paper, db_query_papers, db_submit_paper
from settings import DATA_DIR

api_paper = APIRouter(tags=["paper"])

def get_file_path(id: str):
    return os.path.join(DATA_DIR, id)

def download_file(file: UploadFile, file_path: str):
    f1 = file.file.read()
    with open(file_path, "wb") as f2:
        f2.write(f1)

@api_paper.post("/upload/", summary="上传论文")
async def create_upload_paper(
        file: UploadFile = File(...),
        data: str = Form(...)
):
    upload_temp_file_data = json.loads(data)
    user_openid = upload_temp_file_data["user_openid"]
    file_data = upload_temp_file_data["file"]
    name = file_data["name"]
    time = file_data["time"]
    path = file_data["path"]
    size = file_data["size"]
    id = f"{time}-{name}"

    # 下载文件
    download_file(file, get_file_path(id))

    # 返回数据
    data = {
        "id": id,
        "user_openid": user_openid,
        "file_name": name,
        "file_size": size,
        "file_path": path,
        "time": time,
        "status": "uploaded",
    }
    db_upload_paper(data)
    pprint(data)
    return data

@api_paper.get("/submit/")
async def submit_paper(id: str):
    res = db_submit_paper(id)
    return res

@api_paper.get("/query/", summary="获取论文列表")
async def query_papers(user_openid: str = "test"):
    return db_query_papers(user_openid)

@api_paper.get("/download/", summary="下载报告")
async def download_paper(id: str = "test.json"):
    return FileResponse(get_file_path(id))


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

class wxFlowFrame(wx.Frame):

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

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

        self.model.SetSut("EPGxxxxxxxxxxxxxxxxxx")

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

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

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

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


"""                                             Briefing about the simulation
This program simulates a three body system; Sun, Earth, a passing star. The passing star starts from 50 AU above the
Solar system plane. We throw the star with a speed (or we can change the speed or give a list of speeds), then after a
time that it reaches around 50 AU below the solar plane, we stop the single simulation and check if the planet orbit
reaches beyond the HZ aroound sun (0.8AU-1.2AU). Then we do this simulation for different inclinations and directions
of the planet orbit and we change the place of the planet on the orbit. After this, we can make a 3D plot (a grand plot
with many subplots in 2D) and if in a simulation, after the flyby, the planet stays in HZ, we plot it in black, otherwise
in gray."""

"""
this is a different approach using a 3-level search
"""

import rebound
import math
import operator
import os
import numpy as np

'''we define listing'''
def get_list(r, s, lim, rel=operator.le):
    my_list = []
    while rel(r, lim):
        my_list.append(r)
        r += s
    return my_list

'''we define listing for vz in 10**x form'''
def get_log_list(r, s, lim, rel=operator.le):
    my_list = []
    while rel(r, lim):
        my_list.append(10**r)
        r += s
    return my_list

'''defining the Maxwell-Boltzman distribution'''
def f_maxwell(v, sigma):
    f_v=0.2437*((v**2)/(sigma*3))*math.exp(-(v**2)*0.22676/(sigma**2))
    return f_v

'''initializing some parameters'''
#####################
x_max=60
x_min0=1.2

v_sigma=120/30
#####################

v_mode=2.1*v_sigma
print('Vmode={v_m:.2f}'.format(v_m=v_mode))
v_min=v_mode-v_sigma
print('V_min={v_m:.2f}'.format(v_m=v_min))
v_max=v_mode+v_sigma
print('V_max={v_m:.2f}'.format(v_m=v_max))
v_step=2*v_sigma/10
print('V_step={v_m:.2f}'.format(v_m=v_step))

vz_list = get_list(v_min, v_step, v_max, rel=operator.le)
print("v:", vz_list)

m_list= get_list(3.1, 0.1, 5.01)
print("m:", m_list)

Percentage_array=[]

# '''calculating the dimensions of the figure (subplots in height and width)'''

for m in m_list:
    res = {}
    with open('/Users/atefeh-behzad/Exoplanet_Simulations/Bulge/Vmode({Vmode:.2f}))_m({m:.2f}).txt'.format(Vmode=v_mode, m=m), 'w+') as g:
        g.write('m\tv\tx\n')
        sum_maxwell = 0  # summing up the maxwell distribution
        sum_sectionmaxwell = 0  # summing up the cross sections on the velocity distribution
        for v in vz_list:
            level = 1
            x_min=x_min0
            while level<6:
                if level==1:
                    omega_count=4
                    inc_count=4
                    f_count=4
                    x_step=0.2
                    print('level 1')
                if level==2:
                    omega_count=5
                    inc_count=5
                    f_count=5
                    x_step=0.02
                    print('level 2')
                if level==3:
                    omega_count=7
                    inc_count=7
                    f_count=7
                    x_step=0.01
                    print('level 3')
                if level==4:
                    omega_count=10
                    inc_count=10
                    f_count=10
                    x_step=0.01
                    print('level 4')
                if level==5:
                    print('level 5')
                    g.write('{m:.2f}\t{v:.2f}\t{x:.2f}\n'.format(m=m, v=v, x=x))
                    # if vx[0,0]==0:
                    #     vx=vxtemp
                    # else:
                    #     np.append(vx,vxtemp)
                    f_v=f_maxwell(v, v_sigma)
                    sum_maxwell+=f_v
                    sum_sectionmaxwell+=(f_v*math.pi*x**2)
                    break

                stepcounter=0
                '''here we make lists of omega,x,vz,inc and m'''
                omega_list = get_list(0, 2 * math.pi / omega_count, 2 * math.pi - math.pi / omega_count,
                                      rel=operator.le)
                inc_list = get_list(r=-((math.pi / 2) - math.pi / (inc_count)), s=math.pi / (inc_count),
                                    lim=math.pi / 2, rel=operator.le)
                f_list = get_list(r=2 * math.pi / f_count - 0.0001, s=2 * math.pi / f_count, lim=2 * math.pi)
                x_list = get_list(x_min, x_step, x_max)

                for x in x_list:

                    counter = 0                                                         # this is the counter for calculating percentage
                    print('\nLevel={level:.0f}\tv={v:.3f}\tm={m:.2f}\tx={x:.2f}'.format(level=level,v=v, x=x, m=m))

                    for inc in inc_list:

                        inc_name= (inc+math.pi/2)*inc_count/(math.pi)

                        for o in omega_list:

                            for f in f_list:

                                sim = rebound.Simulation()                              #the simulation starts here
                                sim.add(m=1)                                            #add Sun
                                sim.add(m=3e-6, a=1, Omega=o, inc=inc, f=f)             #add Earth
                                sim.add(m=m, x=x, z=50, vz=v)                           #add the passing star
                                a_c = sim.calculate_orbits()[0]
                                initenergy = sim.calculate_energy()                     #total initial kinetic and potential energy
                                initangmom= sim.calculate_angular_momentum()            #total initial angular momentum in 3 dimensions
                                sim.integrate(round(2 * 50 / (-v), 0))                  #integration

                                a_e = sim.calculate_orbits()[0]                         #calculating orbital elements of the planet after the integration

                                '''determine the color of HZ orbits in omega-inc plot'''
                                if (abs(a_e.a)*(1+a_e.e))<(1.37) and (abs(a_e.a)*(1-a_e.e))>(0.95):
                                    counter += 1

                    Percentage = (round((counter / (inc_count * omega_count * (f_count))) * 100, 2))
                    stepcounter+=1
                    if Percentage >= 95:
                        if stepcounter==1:
                            x_min=x_min-0.05
                            level-=1
                            print("THERE WAS A STEP ERROR")
                        # g.write('{v:.2f}\t{m:.2f}\t{hw:.2f}\t{x:.2f}\n'.format(v=-v, m=m, hw=2*hw, x=x))
                        if level==1:
                            x_min=x-0.8
                        if level==2:
                            x_min=x-0.1
                        if level==3:
                            x_min=x-0.05
                        if level==4:
                            vxtemp=np.array([[v],[x]])
                        level+=1
                        break
        g.write('sum of all maxwell points: {mp:.2f}\nsum of cross sections over maxwell: {cp:.3f}\n'.format(mp=sum_maxwell, cp=sum_sectionmaxwell))
        g.write('mean cross section= {cs:.3f}\n'.format(cs=sum_sectionmaxwell/sum_maxwell))
os.system('say "finished"')


from itertools import combinations
def solve(ll):
	ll2=combinations(ll,4)
	count=0
	for i in ll2:
		if sum(i)==0:
			count+=1
	return count

def main():
	ll=list(map(int,input().split()))
	ans=solve(ll)
	print(ans)
if __name__ == '__main__':
	main()


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

from typing_extensions import Protocol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    result.append(cls)

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

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

    return result

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

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

    argument_parser.dest_prefix = ''


import os
import os.path

import imageio
import pyglet

def create_gif(gif_name, path, duration):
    frames = []
    pngFiles = os.listdir(path)
    image_list = [os.path.join(path, f) for f in pngFiles]
    for image_name in image_list:
        # 读取 png 图像文件
        frames.append(imageio.imread(image_name))
    # 保存为 gif
    imageio.mimsave(gif_name, frames, 'GIF', duration=duration)

    ag_file = "2.gif"
    animation = pyglet.resource.animation(ag_file)
    sprite = pyglet.sprite.Sprite(animation)

    # 创建一个窗口并将其设置为图像大小
    win = pyglet.window.Window(width=sprite.width, height=sprite.height)

    # 设置窗口背景颜色 = r, g, b, alpha
    # 每个值从 0.0 到 1.0
    green = 0, 1, 0, 1
    pyglet.gl.glClearColor(*green)

    @win.event
    def on_draw():
        win.clear()
        sprite.draw()

    pyglet.app.run()

    return

def main():
    gif_name = '1.gif'
    path = 'D:\project\PycharmProject\TestApplication\image'  # 指定图片文件路径
    duration = 0.5
    create_gif(gif_name, path, duration)

if __name__ == "__main__":
    main()


import functools
import time

def stopwatch(func):
    @functools.wraps(func)
    def wrapped(*args, **argv):
        print('`'+str(func.__name__)+'` started')
        time_start = time.perf_counter()
        result = func(*args, **argv)
        time_finish = time.perf_counter()
        time_watch = time_finish - time_start
        print('`'+str(func.__name__)+'` finished in '+str(round(time_watch,2))+'s')
        return result
    return wrapped


# fig_ggn_hyperpolarization.py ---
# Author: Subhasis  Ray
# Created: Tue Feb 12 14:53:34 2019 (-0500)
# Last-Updated: Tue Feb 12 15:37:32 2019 (-0500)
#           By: Subhasis  Ray
# Version: $Id$

# Code:
"""Supplementary figures showing GGN hyperpolarization when PN->KC
connection is not clustered"""

from __future__ import print_function
import sys
if sys.platform == 'win32':
    sys.path.append('D:/subhasis_ggn/model/analysis')
else:
    sys.path += ['/home/rays3/projects/ggn/analysis',
                 '/home/rays3/projects/ggn/morphutils',
                 '/home/rays3/projects/ggn/nrn']
import os
import h5py as h5
import numpy as np
import random
from matplotlib import pyplot as plt

import network_data_analysis as nda
import pn_kc_ggn_plot_mpl as myplot

datadir = '/data/rays3/ggn/olfactory_network'

#jid = '20161955'
# jid = '20162331'
jid = '20162116'
fname = nda.find_h5_file(jid, datadir)
fig, ax = plt.subplots()
with h5.File(fname, 'r') as fd:
    spike_counts = [ds.shape[0] for ds in fd['/data/event/kc/kc_spiketime'].values()]
    spiking = len(np.flatnonzero(spike_counts))
    print('spiking kcs:{}'.format(spiking))
    myplot.plot_ggn_vm(
        ax, fd,
        fd['/data/uniform/ggn_basal/GGN_basal_Vm'], 'dend_b', 1)
    ax.set_xlabel('Time (ms)')
    ax.set_ylabel('GGN Vm (mV)')
    ax.tick_params(right=False, top=False)
    ax.set_xlim(500, 2500)
fig.set_frameon(False)
fig.set_size_inches(20/2.54, 10/2.54)
fig.savefig('supp_4_ggn_ig_hyperpolarization.svg')

# 50.0,1.4,2.7,20162064
jid = '20162064'
fname = nda.find_h5_file(jid, datadir)
fig, ax = plt.subplots()
with h5.File(fname, 'r') as fd:
    spike_counts = [ds.shape[0] for ds in fd['/data/event/kc/kc_spiketime'].values()]
    spiking = len(np.flatnonzero(spike_counts))
    print('spiking kcs:{}'.format(spiking))
    myplot.plot_ggn_vm(ax, fd,
                       fd['/data/uniform/ggn_basal/GGN_basal_Vm'], 'dend_b', 1)
    ax.set_xlabel('Time (ms)')
    ax.set_ylabel('GGN Vm (mV)')
    ax.set_xlim(500, 2500)
    ax.tick_params(right=False, top=False)
fig.set_frameon(False)
fig.set_size_inches(20/2.54, 10/2.54)
fig.savefig('supp_5_ggn_ig_de_hyperpolarization.svg')

#
# fig_ggn_hyperpolarization.py ends here


import json
import requests
import traceback

from .exceptions import APIResponseError

class PaginatedListResponse:
    """
    Iterable JSON API listing response with pagination

    By default django rest framework compatible. Override methods to fetch data
    from other types of responses.
    """

    def __init__(self, url, headers=dict, debug=False):
        self.headers = headers
        self.debug = debug

        self.__page_url__ = url
        self.__status_code__ = None
        self.__error_response__ = None
        self.__total_records__ = None
        self.__records__ = []

    def __len__(self):
        """
        Return total records in response

        If no data has been fetched, get first page to get total count
        """

        # Get first page to get count
        if not self.__records__ and self.__page_url__:
            self.__get_page__()

        return self.__total_records__

    def __get_page__(self):
        """
        Get next page for data

        Raises StopIteration if no more pages are available
        """

        if self.__page_url__ is None:
            raise StopIteration

        self.__records__ = []
        try:
            if self.debug:
                print('DEBUG get {}'.format(self.__page_url__))
            res = requests.get(self.__page_url__, headers=self.headers)
            self.__status_code__ = res.status_code
            if res.status_code == 200:
                data = json.loads(res.content)
                self.__records__ = self.get_records(data)
                self.__page_url__ = self.get_next_page_url(data)
                self.__total_records__ = self.get_total_records_count(data)
            else:
                self.__error_response__ = str(res.content, 'utf-8') if res.content else ''
                raise APIResponseError(
                    'Error getting {}: returns status code {}{}'.format(
                        self.__page_url__,
                        res.status_code,
                        ' ({})'.format(self.__error_response__) if self.__error_response__ else ''
                    )
                )
        except Exception as e:
            if self.debug:
                print(traceback.print_exc())
            raise APIResponseError('Error loading data: {}'.format(e))

    def __iter__(self):
        return self

    def __next__(self):
        """
        Get next record from iterator.

        Loads next page as side effect if available, until all pages are loaded
        """

        if self.__records__:
            # Got records to return, pop one and return it
            return self.__records__.pop(0)

        elif self.__page_url__:
            # Got a page URL to load, load page and pop first record from loaded response
            self.__get_page__()
            if self.__records__:
                return self.__records__.pop(0)
            else:
                raise StopIteration
        else:
            raise StopIteration

    def get_records(self, data):
        """
        Get records from data

        By default look up 'records' attribute (django rest framework compatible)
        """
        if isinstance(data, dict):
            if 'results' in data:
                return data.get('results', [])
            else:
                return [data]
        elif isinstance(data, list):
            return data
        else:
            raise ValueError('Unexpected data type: {}'.type(data))

    def get_next_page_url(self, data):
        """
        Get next page's URL from data

        By default look up 'next' field (django rest framework compatible)
        """
        if isinstance(data, dict):
            return data.get('next', None)
        return None

    def get_total_records_count(self, data):
        """
        Get count of total records

        By default look up 'count' field (django rest framework compatible)
        """
        if isinstance(data, dict):
            return data.get('count', None)
        elif isinstance(data, list):
            return len(data)
        else:
            return None


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

"""
使用摄像头拍摄一段视频
"""

from builtins import WindowsError
import cv2

def capture_video():
    """
    捕获视频
    """
    cap = cv2.VideoCapture(0)  # 构建一个VideoCapture对象

    if not cap.isOpened():  # 判断摄像头是否打开，未打开使用cap.open()来打开摄像头
        raise WindowsError('camera is not opened')

    while True:
        ret, frame = cap.read()  # 一帧一帧的捕获图像
        if not ret:
            print('can not receive frame, existing...')
            break

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # 将捕获的图像转换为灰度图
        cv2.imshow("frame", gray)  # 展示灰度图,形成视频录制的效果

        # waitKey(1) 中的数字代表等待按键输入之前的无效时间，单位为毫秒，在这个时间段内按键 ‘q’ 不会被记录，在这之后按键才会被记录
        # 与操作是因为cv2.waitKey(1) 的返回值不止8位，但是只有后8位实际有效，为避免产干扰，通过 ‘与’ 操作将其余位置0
        if cv2.waitKey(5) & 0xFF == ord("q"):
            break

    # 展示获取的图像的宽度和高度
    print(f"width: {cap.get(3)}\nheight: {cap.get(4)}")

    # 重新设置图像的宽高
    # cap.set(3, 320)
    # cap.set(4, 240)

    # 当退出循环之后，释放对象，关闭所有窗口
    cap.release()
    cv2.destroyAllWindows()

def main():
    capture_video()

if __name__ == "__main__":
    main()


import numpy as np

from gp_gradients import dEI_dx

from Acquisitions import EI

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

from scipy.optimize import minimize
from scipy.optimize import Bounds

import time

def grad_ascent(x, grad_x,  domain, D , t, alpha= 4):

    flag =0

    x_new= x+ grad_x*(alpha/(alpha+t))

    for i in range(D):
        if domain[i][0]> x_new[0, i] or domain[i][1]< x_new[0, i]:
            flag= 1
            break

    if flag==1:
        x_new= x.copy()

    return x_new, flag

def EI_optimize(model, noise, x, kernel, Xt, Yt, f_best, num_restarts, domain, D, num_iter=100):

    # u_x, var_x = model.predict_f(x); u_x = u_x.numpy(); var_x = var_x.numpy()
    # sigma_x= np.sqrt(var_x)

    def EI_negative_gradient(x):

        x = x.reshape(1, -1)

        u_x, var_x = model.predict_f(x); u_x = u_x.numpy(); var_x = var_x.numpy();
        sigma_x = np.sqrt(var_x)

        def _EI_negative_gradient(u_x, sigma_x, kernel, Xt, Yt, x ,noise):

            grad_x= dEI_dx(f_best, u_x, sigma_x, kernel, Xt, Yt, x, noise)

            grad_x= grad_x.flatten()

            return -grad_x

        return _EI_negative_gradient(u_x, sigma_x, kernel, Xt, Yt, x ,noise)

    def EI_negative(x):

        x = x.reshape(1, -1)
        u_x, var_x = model.predict_f(x); u_x = u_x.numpy(); var_x = var_x.numpy();
        sigma_x = np.sqrt(var_x)

        def _EI_negative(x, sigma_x, u_x, f_best):

            EI_x= EI(sigma_x, u_x, f_best)

            EI_x= EI_x.flatten()

            return -EI_x

        return _EI_negative(x, sigma_x, u_x, f_best)

    lower = [domain[i][0] for i in range(len(domain))]; upper = [domain[i][1] for i in range(len(domain))]

    '''optimization with grad_ascent'''
    # x_list= np.empty([num_restarts, x.shape[1]])
    x_list= np.empty([num_restarts, x.shape[1]])
    value_list= np.empty([num_restarts, 1])
    grad_list= np.empty([num_restarts, x.shape[1]])

    x_all_list= []
    x0_list= np.zeros([num_restarts, D])

    t1_ga= time.process_time_ns()

    for i in range(num_restarts):

        x= np.random.uniform(lower, upper, (1,D))
        x0_list[i, :] = x[0, :]
        xi_list= np.zeros([0, D])

        for k in range(num_iter):

            grad_x= -EI_negative_gradient(x)
            x, flag= grad_ascent(x, grad_x, domain ,D, k)
            # print('x, grad_x', x, grad_x)
            xi_list= np.append(xi_list, x, axis=0)

            if flag==1:
                break

        x_all_list.append(xi_list)

        value_x= -EI_negative(x); value_x= value_x.reshape(1,-1)
        grad_x = -EI_negative_gradient(x); grad_x= grad_x.reshape(1,-1)

        x_list[i, :]= x[0,:]
        value_list[i,:]= value_x[0,:]
        grad_list[i,:] = grad_x[0,:]

    t2_ga= time.process_time_ns()
    t_ga= t2_ga- t1_ga

    index_max= int(np.argmax(value_list, axis= 0))
    x_opt= x_list[index_max, :].reshape(1,-1)
    value_opt= value_list[index_max, :].reshape(1,-1)
    grad_opt= grad_list[index_max, :].reshape(1,-1)

    '''optimization with scipy'''
    lower= []; upper= []
    for i in range(len(domain)):
        lower.append(domain[i][0])
        upper.append(domain[i][1])
    b= Bounds(lb= lower, ub= upper )

    x_opt_list_sci= np.zeros([num_restarts, D])
    x_value_list_sci= np.zeros([num_restarts, 1])
    x_grad_sci_list= np.zeros([num_restarts, D])

    t1_sci= time.process_time_ns()

    for i in range(num_restarts):

        x0 = x0_list[i, :].reshape(1,-1)
        result= minimize(EI_negative, x0, bounds=b, method= 'L-BFGS-B', jac= EI_negative_gradient, options= {'maxiter': num_iter})
        x_sci= result['x']; x_grad_sci= -result['jac']; x_value_sci= -result['fun']
        x_sci = x_sci.reshape(1,-1); x_grad_sci= x_grad_sci.reshape(1,-1); x_value_sci= x_value_sci.reshape(1,-1)

        x_opt_list_sci[i, :]= x_sci[0,:]
        x_value_list_sci[i,:]= x_value_sci[0,:]
        x_grad_sci_list[i,:] = x_grad_sci[0,:]

    index_opt_sci= np.argmax(x_value_list_sci, axis=0)
    x_opt_sci= x_opt_list_sci[index_opt_sci, :].reshape(1,-1)
    x_opt_value_sci= x_value_list_sci[index_max, :].reshape(1,-1)
    x_opt_grad_sci= x_grad_sci_list[index_opt_sci, :].reshape(1,-1)

    t2_sci= time.process_time_ns()
    t_sci= t2_sci- t1_sci

    print('x_value_sci:{}, x_value_GA:{}'.format(x_opt_value_sci, value_opt))
    print('sci_time:{}(s), ga_time:{}(s)'.format(t_sci*10**(-9), t_ga*10**(-9)))
    print('x_sci:{}, x_ga:{}'.format(x_opt_sci, x_opt))

    return x_opt, value_opt, grad_opt, x_all_list, x_list, value_list, grad_list, x0_list

def comparison_of_optimum_with_grid(f_best, model, domain, kernel, Xt, Yt, D, noise= 10**(-4)):

    num_restarts= 3

    '''compare with grid'''
    x_grid1 = np.linspace(domain[0][0], domain[0][1], 101);

    X_grid = x_grid1.reshape(-1,1)

    u_X, var_X= model.predict_f(X_grid);
    u_X = u_X.numpy(); var_X = var_X.numpy(); sigma_X= np.sqrt(var_X)

    EI_X= EI(sigma_X, u_X, f_best)

    lower = [domain[i][0] for i in range(len(domain))];
    upper = [domain[i][1] for i in range(len(domain))]
    x0= np.random.uniform(lower, upper, (1,D))

    x_pred_opt, x_pred_opt_val, grad_pred_opt, x_all_list, x_list, value_list, grad_list, x0_list= \
        EI_optimize(model, noise, x0, kernel, Xt, Yt, f_best, num_restarts, domain, D, num_iter=100)

    if D==1:
        plt.figure()
        plt.plot(X_grid[:,0], EI_X[:,0])
        plt.scatter(x_pred_opt[0,:], x_pred_opt_val[0,:], color= 'blue')
        plt.scatter((x_all_list[0])[:,0], np.zeros([x_all_list[0].shape[0], ]), color= 'orange', alpha= 0.5)
        plt.scatter(x0_list[:,0], np.zeros([x0_list.shape[0], ]), color= 'red', alpha= 0.5)

        plt.show()

def comparison_of_optimum_with_grid_2d(f_best, model, domain, kernel, Xt, Yt, D, noise=10 ** (-4)):

    num_restarts = 3

    '''compare with grid'''
    x_grid1 = np.linspace(domain[0][0], domain[0][1], 21);
    x_grid2=  np.linspace(domain[1][0], domain[1][1], 21);
    X1, X2= np.meshgrid(x_grid1, x_grid2); X1 = (X1.flatten()).reshape(-1,1); X2= (X2.flatten()).reshape(-1,1)
    X_grid = np.append(X1, X2, axis=1)

    u_X, var_X = model.predict_f(X_grid);
    u_X = u_X.numpy();
    var_X = var_X.numpy();
    sigma_X = np.sqrt(var_X)

    EI_X = EI(sigma_X, u_X, f_best)

    lower = [domain[i][0] for i in range(len(domain))];
    upper = [domain[i][1] for i in range(len(domain))]
    x0 = np.random.uniform(lower, upper, (1, D))

    x_pred_opt, x_pred_opt_val, grad_pred_opt, x_all_list, x_list, value_list, grad_list, x0_list = \
        EI_optimize(model, noise, x0, kernel, Xt, Yt, f_best, num_restarts, domain, D, num_iter=100)

    if D == 2:
        fig = plt.figure()
        ax = Axes3D(fig)
        ax.scatter3D(X_grid[:,0], X_grid[:,1], EI_X[:,0], color= 'red', alpha= 0.5)
        ax.scatter3D(x_pred_opt[0,0], x_pred_opt[0,1], x_pred_opt_val[0,0], color= 'green')
        ax.scatter3D((x_all_list[0])[:, 0], (x_all_list[0])[:, 1], np.zeros([x_all_list[0].shape[0], ]), color='orange', alpha=0.5)
        plt.show()

    # if D==2:


# Authors: Adam Li <adam2392@gmail.com>
#          Alex Rockhill <aprockhill@mailbox.org>
# License: BSD Style.

from ...utils import verbose
from ..utils import _data_path_doc, _get_version, _version_doc, _download_mne_dataset

@verbose
def data_path(
    path=None, force_update=False, update_path=True, download=True, *, verbose=None
):  # noqa: D103
    return _download_mne_dataset(
        name="epilepsy_ecog",
        processor="untar",
        path=path,
        force_update=force_update,
        update_path=update_path,
        download=download,
    )

data_path.__doc__ = _data_path_doc.format(
    name="epilepsy_ecog", conf="MNE_DATASETS_EPILEPSY_ECOG_PATH"
)

def get_version():  # noqa: D103
    return _get_version("epilepsy_ecog")

get_version.__doc__ = _version_doc.format(name="epilepsy_ecog")


from django.shortcuts import render, redirect
from .models import Company, Trading
from users.models import User
from .forms import TradeForm, BidForm, CompanyForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import Share as var
from .models import  Bidding as bidvar
from django.core.paginator import Paginator
import time as setInterval
from django.views.defaults import page_not_found, server_error
# from threading import Timer

def trade(request):
	return render(request, 'home/trade-close.html')

def alert_update(request):
	User.objects.filter(id=request.user.id).update(alert='')
	return redirect('mycompanies')

def add_mycompanies(request):
	if request.user.is_superuser:
		for bid in bidvar.objects.all():
			if bid.buyer:
				temp = var.objects.filter(company=bid.company)
				if not temp:
					var.objects.create(company=bid.company,
								  	   shareholder=bid.buyer,
								   	   percentage_of_share=100)
					coins = User.objects.get(id=bid.buyer.id).eCoins - bid.bidding_price
					print(coins)
					User.objects.filter(id=bid.buyer.id).update(eCoins=coins)
		return redirect('timepage')
	else:
		return redirect('home')

def coming(request):
	return render(request, 'home/comingsoon.html')

def closed(request):
    return render(request, 'home/closed.html')

def trading_closed(request):
	return render(request, 'home/closed_trading.html')

def comingbidding(request):
	return render(request, 'home/comingsoon.html')

def company(request, pg=1):
	company_list = Company.objects.order_by('id')
	paginator = Paginator(company_list, 25)

	context = {
		'Companys' : paginator.page(pg),
		'page' : pg,
		'paginator' : paginator,
	}
	return render(request, 'home/companies.html', context)

def timepage(request):
	if request.user.is_superuser:
		return render(request, 'home/save.html')
	else:
		return redirect('comingsoon')

def time(request):
	if request.user.is_superuser:
		i = var.objects.all();
		for j in i:
			coin = j.shareholder.eCoins + j.percentage_of_share*j.company.multiplication_factor*10
			User.objects.filter(id = j.shareholder.id).update(eCoins = coin)
		return redirect('timepage')
	else:
		return redirect('comingsoon')

@login_required()
def tradingUpdateView(request, id=None, pg=1):
	if id:
		if not Trading.objects.filter(id = id):
			return render(request, 'home/trade-close.html')
		trade = Trading.objects.get(id = id)
		if request.method == 'POST' and trade.seller != request.user:
			form = TradeForm(request.POST, instance=trade)
			if trade.highest_bid < int(form['highest_bid'].value()):
				prev_bid = trade.highest_bid
				if request.user.eCoins >= int(form['highest_bid'].value()):
					if int(form['highest_bid'].value())%100 == 0 and form.is_valid():
						if trade.buyer != trade.seller:
							if trade.buyer != request.user:
								coins = User.objects.get(id=trade.buyer.id).eCoins + prev_bid
								User.objects.filter(id=trade.buyer.id).update(eCoins=coins)
							else:
								messages.add_message(request, messages.INFO, f'You are already the highest bidder on same company.' )
					else:
						messages.add_message(request, messages.INFO, f'You need to place bid in multiple of 100\'s only.' )
					trade.buyer = request.user
					form.save()
					coins = User.objects.get(id=trade.buyer.id).eCoins - trade.highest_bid
					User.objects.filter(id=trade.buyer.id).update(eCoins=coins)
					messages.add_message(request, messages.INFO, f'Your Bid has been placed sucessfully on {trade.company.company_name}.' )
				else:
					messages.add_message(request, messages.INFO, 'You don\'t have enough E-Coins to place this bid.' )
			else:
				messages.add_message(request, messages.INFO, 'Enter a bid price higher than the current highest bid price.')
		else:
			messages.add_message(request, messages.INFO, 'You can\'t bid on your own company')
		return redirect('trading', pg=pg)

	form = TradeForm()
	trade_list = Trading.objects.order_by('-id')
	paginator = Paginator(trade_list, 10)
	context = {
		'form':form,
		'Tradings' : paginator.page(pg),
		'page' : pg,
		'paginator' : paginator,
		'Companys': Company.objects.order_by('-id')
	}

	return render(request, 'home/trading.html', context)

@login_required
def tradingCloseView(request, id=None):
	trade = Trading.objects.get(id=id)
	if trade.seller == request.user:
		if trade.buyer != trade.seller:
			coins = request.user.eCoins + trade.highest_bid
			User.objects.filter(id=trade.seller.id).update(eCoins=coins)

			messages.add_message(request, messages.INFO, f'Trade has been closed successfully for {trade.highest_bid} E-Coins')

			alert_message = f'{trade.percentage_for_sale}% shares of the company \'{trade.company}\' have been added to your companies.'
			User.objects.filter(id=trade.buyer.id).update(alert=alert_message)

		obj = var.objects.filter(company=trade.company).filter(shareholder=trade.buyer)
		if obj:
			sum = obj.first().percentage_of_share + trade.percentage_for_sale
			obj.update(percentage_of_share=sum)
		else:
			var.objects.create(company=trade.company,
								 shareholder=trade.buyer,
								 percentage_of_share=trade.percentage_for_sale)
		trade.delete()
	return redirect('mytrade')

@login_required
def bidding(request, id=None, pg=1):
	if id:
		a = bidvar.objects.all();
		bid = bidvar.objects.filter(id = id).first()
		if request.method == 'POST':
			form = BidForm(request.POST, instance=bid)
			for b in a:
				if b.buyer == request.user:
					messages.add_message(request, messages.INFO, 'You can\'t have highest bid on two Companies')
					return redirect('bidding', pg=pg)
			if bid.bidding_price < int(form['bidding_price'].value()):
				if request.user.eCoins > int(form['bidding_price'].value()):
					if int(form['bidding_price'].value())%100 == 0 and form.is_valid():
						bid.buyer = request.user
						form.save()
						messages.add_message(request, messages.INFO, f'Your Bid has been placed sucessfully on {bid.company.company_name}' )
					else:
						messages.add_message(request, messages.INFO, 'You need to place bid in multiple of 100\'s only.'  )

				else:
					messages.add_message(request, messages.INFO, 'You don\'t have enough E-Coins to place this bid.' )
			else:
				messages.add_message(request, messages.INFO, 'Enter a Bid Price higher than the current Highest Bid Price')
			return redirect('bidding', pg=pg)

	form = BidForm()
	bid_list = bidvar.objects.filter(visible=True).order_by('-id')
	paginator = Paginator(bid_list, 13)
	context = {
		'form' : form,
		'Bid' : paginator.page(pg),
		'page' : pg,
		'paginator' : paginator,
		'Companys': Company.objects.order_by('-id')
	}
	return render(request, 'home/letsbid.html', context)

@login_required
def mycompanies(request, id=None):
	if id:
		current_share = var.objects.get(id = id)
		if request.method == 'POST':
			form = CompanyForm(request.POST)
			per_for_sale = int(form['percentage_for_sale'].value())
			if per_for_sale >= 5 and per_for_sale <= int(current_share.percentage_of_share) and form.is_valid():
				form.instance.company = current_share.company
				form.instance.your_bid_price = int(form['lowest_bid_price'].value())
				form.instance.seller = request.user
				form.instance.buyer = request.user
				obj = form.save()
				obj.highest_bid = form.cleaned_data.get('lowest_bid_price')
				obj.save()
				per_of_share = current_share.percentage_of_share - per_for_sale
				var.objects.filter(id=id).update(percentage_of_share=per_of_share)
				return redirect('trading', pg=1)
			elif per_for_sale < 5:
				messages.add_message(request, messages.INFO, 'You need to sell minimum 5 percent of Shares')
			elif per_for_sale > int(current_share.percentage_of_share):
				messages.add_message(request, messages.INFO, 'Add a value less than current share')
			return redirect('mycompanies')
	else:
		form = CompanyForm()

	context = {
		'form' : form,
		'Shares': var.objects.filter(shareholder=request.user).exclude(percentage_of_share=0).order_by('-id'),
	}
	return render(request, 'home/mycompanies.html', context)

def home(request):
    return render(request, 'home/home.html')

def mytrade(request):
	context = {
		'Trades': Trading.objects.filter(seller=request.user).order_by('-id'),
	}
	return render(request, 'home/mytrade.html', context)

def mybid(request):
	context = {
		'Trades': Trading.objects.filter(buyer=request.user).order_by('-id'),
	}
	return render(request, 'home/mybids.html', context)

def mycompanies_notrade(request):
	messages.add_message(request, messages.INFO, 'The trade can not be placed before 23-08-2020 17:00.')
	return redirect(mycompanies)


import cv2
from matplotlib import pyplot as plt

# Reading the image and converting to grayscale
img = cv2.imread('pic.png')
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# GLOBAL THRESHOLDING
retval, thresh1 = cv2.threshold(image, 110, 255, cv2.THRESH_BINARY)
retval1, thresh2 = cv2.threshold(image, 110, 255, cv2.THRESH_BINARY_INV)
retval2, thresh3 = cv2.threshold(image, 110, 255, cv2.THRESH_TRUNC)
retval3, thresh4 = cv2.threshold(image, 110, 255, cv2.THRESH_TOZERO)
retval4, thresh5 = cv2.threshold(image, 110, 255, cv2.THRESH_TOZERO_INV)

titles = ['Original image', 'Thresh binary', 'Thresh Binary_Inv', 'Trunc', 'Tozero', 'Tozero_Inv']
images = [image, thresh1, thresh2, thresh3, thresh4, thresh5]

for i in range(6):
    plt.subplot(2, 3, i + 1), plt.imshow(images[i], 'gray')
    plt.title(titles[i])
    plt.xticks([]), plt.yticks([])
plt.show()

# ADAPTIVE THRESHOLDING
adapt_thresh1 = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
adapt_thresh2 = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

adapt_titles = ['original image', 'Thresh_binary', 'Adaptive_mean', 'Adaptive_gaussian']
adapt_images = [image, thresh1, adapt_thresh1, adapt_thresh2]

for i in range(4):
    plt.subplot(2, 2, i + 1), plt.imshow(adapt_images[i], 'gray')
    plt.title(adapt_titles[i])
    plt.xticks([]), plt.yticks([])
plt.show()

# Otsu's BINARIZATION
# Before Gaussian filtering
retval, otsu_thresh1 = cv2.threshold(image, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)

# After Gaussian filtering
blur = cv2.GaussianBlur(image, (5, 5), 0)
retval5, otsu_thresh2 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

otsu_titles = ['original image', 'Histogram', 'Global thresholding',
               'original image', 'Histogram', "Otsu's thresholding",
               'Gaussian filtered image', 'Histogram', "Otsu's thresholding"]
otsu_images = [image, 0, thresh1,
               image, 0, otsu_thresh1,
               blur, 0, otsu_thresh2]

for i in range(3):
    plt.subplot(3, 3, i * 3 + 1), plt.imshow(otsu_images[i * 3], 'gray')
    plt.title(otsu_titles[i * 3 + 1]), plt.xticks([]), plt.yticks([])
    plt.subplot(3, 3, i * 3 + 2), plt.hist(otsu_images[3 * i].ravel(), 256)
    plt.title(otsu_titles[3 * i + 2]), plt.xticks([]), plt.yticks([])
    plt.subplot(3, 3, 3 * i + 3), plt.imshow(otsu_images[3 * i + 2], 'gray')
    plt.title(otsu_titles[3 * i + 2]), plt.xticks([]), plt.yticks([])
plt.show()


import os
import urllib.request
from flask import Flask, request, redirect, jsonify
from werkzeug.utils import secure_filename
from flask_cors import CORS, cross_origin

UPLOAD_FOLDER = 'uploads/files/'

app = Flask(__name__)

cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

ALLOWED_EXTENSIONS = set(['pdf'])

def allowed_file(filename):
	return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/hello', methods=['GET'])
@cross_origin()
def hello_world():
	return jsonify(hello='world')

@app.route('/upload', methods=['POST'])
@cross_origin()
def upload_file():
	# check if the post request has the file part
	if 'files[]' not in request.files:
		resp = jsonify({'message': 'No file part in the request'})
		resp.status_code = 400
		return resp

	files = request.files.getlist('files[]')

	errors = {}
	success = False

	for file in files:
		if file and allowed_file(file.filename):
			filename = secure_filename(file.filename)
			file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
			success = True
		else:
			errors[file.filename] = 'File type is not allowed'

	if success and errors:
		errors['message'] = 'File(s) successfully uploaded'
		resp = jsonify(errors)
		resp.status_code = 500
		return resp
	if success:
		resp = jsonify(
            {
                'summary': {
                    'positions': [
                        {
                            'stock': 'ITAUSA',
                            'averagePrice': 21.10,
                            'sellingPrice': 10.00,
                            'profitLoss': -11.10
                        },
                        {
                            'stock': 'ITAUSA',
                            'averagePrice': 21.10,
                            'sellingPrice': 30.00,
                            'profitLoss': 8.90
                        }
                    ],
                    'totalPL': -2.2,
                    'tax': 0
                }
            })
		resp.status_code = 201
		return resp
	else:
		resp = jsonify(errors)
		resp.status_code = 500
		return resp

if __name__ == "__main__":
    # create the uploads directory if it doesn't exist
    if not os.path.exists(UPLOAD_FOLDER):
        os.makedirs(UPLOAD_FOLDER)

    app.run(host='0.0.0.0', debug=True)