from server_manager.models import Application, EdgeServer, Client, Cluster

from django_pandas.io import read_frame

import random
import pandas as pd
import math
import numpy as np

cluster = EdgeServer.objects.filter(cluster_id = cluster_label)
cluster_df = read_frame(cluster, fieldnames=['application_id', 'server_id', 'x', 'y', 'capacity', 'used', 'cluster_id'])
servers_in_cluster = cluster_df['server_id']

relations_df = pd.read_csv('./simulation/out/relationship.csv', names = ['client_id', 'related_clients'])
print(relations_df)
#ランダム選択で初期化
allocated_server_id = cluster_df.iloc[int(random.random() * cluster_df.shape[0])]['server_id']
print("allocated_server_id : ", allocated_server_id)

#関連性の高いユーザー順で10人(変数となる)からなるリスト

print("client_id", str(client_id))
print("cluster_label", str(cluster_label))
print(relations_df[relations_df['client_id'] == str(client_id)])
print("test", relations_df.loc[0,'client_id'])
print("type", type(relations_df.loc[0,'client_id']))
related_clients_list = list(map(int, relations_df.loc[0,'related_clients'].strip('[]').split(', ')))

#その10人が同じクラスターに所属していれば, そのサーバーにクライアントを割り当て. 所属していなければrandomに選択
for client_id in related_clients_list:
    client = Client.objects.get(client_id = client_id)
    if client.home.server_id in servers_in_cluster:
        allocated_server_id = client.home.server_id
        print("rellocated_server_id : ", allocated_server_id)


import sys
import os
import MaxPlus
import pymxs
rt = pymxs.runtime

import re

# to add module from parent folder
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

from maxsdk import layer as sdkLayer

def check_layers_names(silent = False):
    ##check layers name
    layers = sdkLayer.getAllLayers()
    layer_zero = rt.LayerManager.getLayer(0)
    shared = rt.LayerManager.getLayerFromName("SHARED")
    ignore_layers = []
    sdkLayer.getLayerChildren(layer_zero,ignore_layers)
    sdkLayer.getLayerChildren(shared, ignore_layers)
    wrong_layers = ""
    if(layers is not None):
        for l in layers:
            if l in ignore_layers:
                continue
            x = re.search("^(?!x).*$",l.name)
            if x is not None:
                wrong_layers  += l.name +"\n"

    if len(wrong_layers)>0:
        if not silent:
            rt.messageBox("WARNING!!!\n\n Followwing Objects DO NOT respect naming convention, layer LOD not specified,should be of type xN \n\n{0} ".format(wrong_layers))
        return False
    else:
        return True

def run():
    if check_layers_names():
        rt.messageBox("Layer's name validated")


# -*- coding: utf8 -*-
import tensorflow as tf
from utils import *
from dataUtils import save_batch_data
import time
import numpy as np
from scipy.misc import imsave

class DAE(object):
    def __init__(self, sess, Rshape, Ushape, Ishape, noise=0, u_units=20, i_units=20,layer=0, learning_rate=0.01,
                 n_epoch=100, is_training=True, batch_size=20,decay=0.95, save_freq=1,
                 reg_lambda=0.0, rho=0.05, sparse_lambda=0.0, alpha=1,beta=1,delta=1,
                 summary_handle=None):

        self.sess = sess
        self.is_training = is_training
        self.u_units = u_units              # 用户网络，隐层节点数
        self.i_units = i_units              # 商品网络，隐层节点数
        self.layer = layer                  # 是第几层
        self.n_epoch = n_epoch
        self.n_batch = Rshape[0]*Rshape[1]//(batch_size**2)
        self.batch_size = batch_size
        self.Rshape = Rshape
        self.Usize = Ushape[1]
        self.Isize = Ishape[1]

        self.lr_init = learning_rate
        self.stddev = 0.02                   # 初始化参数用的
        self.noise = noise                  # dropout水平，是数\
        self.dropout_p = 0.5                # dropout层保持概率
        self.rho = rho                      # 稀疏性系数
        self.sparse_lambda = sparse_lambda
        self.lr_decay = decay
        self.change_lr_epoch = int(n_epoch*0.3) # 开始改变lr的epoch数
        self.regularizer = tf.contrib.layers.l2_regularizer #使用L1或L2正则化

        self.reg_lambda = reg_lambda        # U,V正则化系数,float
        self.lambda_u = self.reg_lambda           # U网络权重正则化系数
        self.lambda_i = self.reg_lambda            # I网络权重正则化系数
        self.alpha = alpha                  # U和I重建误差中，权衡S与X的系数
        self.beta = beta                    # 总loss中，U网络的重建误差权重
        self.delta = delta                  # 总loss重，I网络的重建误差权重

        self.save_freq = save_freq          # 特征的总保存次数，每次保存n/save_freq条
        self.save_batch_size = Rshape[0]//save_freq
        self.summ_handle = summary_handle
        self.build(self.is_training)

    # ------------------------- 隐层 -------------------------------------
    def hidden(self, input, units, noise, layerlambda,name = "default"):
        input_size = int(input.shape[1])
        with tf.variable_scope(name):
            # mask噪声
            corrupt = tf.layers.dropout(input,rate= noise,training=self.is_training)
            # 加性高斯噪声
            # corrupt = tf.add(input,noise * tf.random_uniform(input.shape))
            ew = tf.get_variable('enc_weights',shape=[input_size, units],
                                 initializer=tf.random_normal_initializer(mean=0.0,stddev=self.stddev),
                                 regularizer=self.regularizer(layerlambda))

            sew = tf.summary.histogram(name + '/enc_weights', ew)

            eb = tf.get_variable('enc_biases',shape=[1,units],
                                initializer=tf.constant_initializer(0.0),dtype=tf.float32,
                                regularizer=self.regularizer(layerlambda))
            seb = tf.summary.histogram(name+'/enc_biases',eb)
            fc1 = tf.add(tf.matmul(corrupt,ew),eb)
            act1 = tf.nn.sigmoid(tf.layers.batch_normalization(fc1))
            character = act1
            self.ew = ew
            self.eb = eb

            dw = tf.transpose(ew)
            db = tf.get_variable('dec_biases',shape=[1,input_size],
                                initializer=tf.constant_initializer(0.0),dtype=tf.float32,
                                regularizer=self.regularizer(layerlambda))
            sdb = tf.summary.histogram(name+'/dec_biases',db)
            self.summ_handle.add_summ(sew, seb,sdb)
            fc = tf.add(tf.matmul(act1,dw),db)

            out = tf.sigmoid(fc)

        return character, out

    def build(self,is_training=True):
        self.lr = tf.placeholder(tf.float32, name='learning_rate')
        self.R = tf.placeholder(tf.float32,None,name="Rating_Matrix")
        # --------------- 用户网络 ---------------------------------------------------------
        layer_name = "User_layer" + str(self.layer)
        # self.u_x = tf.placeholder(tf.float32,[self.batch_size, self.Rshape[1]+self.Usize],name="user_input")
        self.u_x = tf.placeholder(tf.float32, [None, self.Rshape[1] + self.Usize], name="user_input")
        self.U, self.u_out = self.hidden(self.u_x,self.u_units,
                                                   self.noise,self.lambda_u, name=layer_name)

        reg_losses = tf.losses.get_regularization_losses(layer_name)
        for loss in reg_losses:
            tf.add_to_collection('losses' + layer_name, loss)
        reg_losses_u = tf.get_collection('losses'+layer_name)
        self.rec_loss_u = mse_by_part(self.u_out, self.u_x,self.Rshape[1],self.alpha)
        tf.add_to_collection('losses'+layer_name,self.rec_loss_u)
        self.sparse_loss = self.sparse_lambda * sparse_loss(self.rho,self.U)
        tf.add_to_collection('losses' + layer_name, self.sparse_loss)
        self.u_loss = tf.add_n(tf.get_collection('losses'+layer_name))  # U网络重建误差
        self.reg_losses = list(reg_losses_u)
        # --------------- 商品网络 ---------------------------------------------------------

        layer_name = "Item_layer" + str(self.layer)
        self.i_x = tf.placeholder(tf.float32,[None,self.Rshape[0]+self.Isize],name="item_input")
        self.V, self.i_out = self.hidden(self.i_x,self.i_units,
                                                    self.noise, self.lambda_i,name=layer_name)

        reg_losses = tf.losses.get_regularization_losses(layer_name)
        for loss in reg_losses:
            tf.add_to_collection('losses' + layer_name, loss)
        self.reg_losses.extend(tf.get_collection('losses'+layer_name))
        self.rec_loss_i = mse_by_part(self.i_out, self.i_x,self.Rshape[0],self.alpha)
        tf.add_to_collection('losses'+layer_name, self.rec_loss_i)
        self.sparse_loss = self.sparse_lambda * sparse_loss(self.rho,self.V)
        tf.add_to_collection('losses' + layer_name, self.sparse_loss)
        self.i_loss = tf.add_n(tf.get_collection('losses'+layer_name))  # I网络重建误差

        # 总loss
        self.R_hat = tf.matmul(self.U,tf.transpose(self.V))
        self.rec_loss = mse_mask(self.R,self.R_hat)
        reg_loss_u_and_i = tf.reduce_sum(tf.norm(self.U,axis=1))+tf.reduce_sum(tf.norm(self.V,axis=1))
        self.reg_losses.append(reg_loss_u_and_i)
        self.loss = self.rec_loss + self.reg_lambda * reg_loss_u_and_i+\
                    self.beta * self.u_loss + self.delta * self.i_loss
        # 输出预测准确度，和文献比一下
        self.rmse = rmse_mask(self.R,self.R_hat)

    def train(self, read_data_path, save_data_path, load_data_batch_func, train_vals, summ_writer, summ_handle):
        temp = set(tf.all_variables())
        self.optimizer = tf.train.AdamOptimizer(self.lr, beta1=0.9).minimize(self.loss,var_list=train_vals)
        # adam中有slot,需要初始化。
        tf.initialize_variables(set(tf.all_variables()) - temp).run()

        counter = 0
        current_lr = self.lr_init
        begin_time = time.time()
        # --------------------------------- 训练 --------------------------------------------------
        for epoch in range(self.n_epoch-1):
            if epoch > self.change_lr_epoch:
                current_lr = current_lr * self.lr_decay
            for batch in range(self.n_batch):
                counter += 1
                # 每个batch读一次数据 想按batch读，就需要每层的特征图都存下来，很占空间
                batch_u, batch_i, batch_R = load_data_batch_func(read_data_path,
                                        batch_size=self.batch_size)

                _, loss, rec_loss, reg_loss,loss_u,loss_i, U, V, summ_loss =\
                    self.sess.run([self.optimizer,self.loss,self.rmse, self.reg_losses,self.rec_loss_u,self.rec_loss_i,
                                self.U, self.V, summ_handle.summ_loss[0]],
                                  feed_dict={self.u_x: batch_u,self.i_x:batch_i, self.R:batch_R,self.lr:current_lr})
                summ_writer.add_summary(summ_loss,epoch * self.n_batch + batch)
                if counter%50==0:
                # 记录w,b
                    summ_ew, summ_eb, summ_db = self.sess.run([summ_handle.summ_enc_w[0], summ_handle.summ_enc_b[0],
                                                                        summ_handle.summ_dec_b[0]],
                                                              feed_dict={self.u_x: batch_u, self.i_x: batch_i,
                                                                         self.R: batch_R, self.lr: current_lr})
                    summ_writer.add_summary(summ_ew, epoch * self.n_batch + batch)
                    summ_writer.add_summary(summ_eb, epoch * self.n_batch + batch)
                    summ_writer.add_summary(summ_db, epoch * self.n_batch + batch)
            print("epoch ",epoch," train loss: ", loss," rec loss: ", rec_loss," reg loss: ",reg_loss,
                  " loss u: ",loss_u," loss i: ",loss_i,
                  " sparse coef: ",tf.reduce_mean(tf.reduce_mean(U)).eval()+tf.reduce_mean(tf.reduce_mean(V)).eval(),
                 " time:",str(time.time()-begin_time))

        #----------------------- 最后一个epoch,除了训练，还要记录wb的分布 --------------------------
        epoch = self.n_epoch - 1
        for batch in range(self.n_batch):
            counter += 1
            batch_u, batch_i, batch_R = load_data_batch_func(read_data_path,
                                                             batch_size=self.batch_size)
            _, loss, self.ewarray, self.ebarray, summ_loss, summ_ew,summ_eb,summ_db\
                = self.sess.run([self.optimizer, self.loss,self.ew,self.eb,
                                summ_handle.summ_loss[0],summ_handle.summ_enc_w[0],summ_handle.summ_enc_b[0],
                                summ_handle.summ_dec_b[0]],
                                feed_dict={self.u_x: batch_u, self.i_x: batch_i, self.R: batch_R, self.lr: current_lr})
            summ_writer.add_summary(summ_loss, epoch * self.n_batch + batch)
            summ_writer.add_summary(summ_ew, epoch * self.n_batch + batch)
            summ_writer.add_summary(summ_eb, epoch * self.n_batch + batch)
            summ_writer.add_summary(summ_db, epoch * self.n_batch + batch)

        # ----------------------- 记录抽取的特征 --------------------------
        Us = []
        Vs = []
        outs =[]
        save_batch_data(save_data_path, inputU = Us, inputV=Vs, is_New=True)
        for batch in range(self.save_freq):
            batch_u, batch_i, batch_R = load_data_batch_func(read_data_path,
                                                             batch_size=self.save_batch_size)
            U, V, Rhat = self.sess.run([self.U, self.V, self.R_hat],
                                feed_dict={self.u_x: batch_u, self.i_x: batch_i, self.R: batch_R, self.lr: current_lr})
            Us.append(U)
            Vs.append(V)
            outs.append(Rhat)
            save_batch_data(save_data_path,inputU=U,inputV=V)
        self.next_U = np.concatenate(tuple(Us))
        self.next_V = np.concatenate(tuple(Vs))
        self.rec = np.concatenate(tuple(outs))
        print("feature saved. time:",str(time.time()-begin_time))
        # -------------------------------------------------------------------


y = 100
global x
x= 99
def test1():
    #print(x) #will referenced before assignment
    x = y-2
    print(y)
    #del y  #will make wrong
    del x
def test2():
    if x==99:
        print("x is 99")
        #x = 0 still can't change global
    elif x != 99 :
        print('x is not 99')
        #x = 1 still can't change global

test1()
test2()
print(x)

def test3():
    global z
    z = 123
    print(z)

test3()
print(z)


from random import randint

class Cell:
    #definition du constructeur d'une cellule.
    def __init__(self, x=15, y=15):
        self.x = x
        self.y = y
        self.vivant = randint(0,1)
        self.nbvoisin = 0

#On verifie le nombre de voisin au coordonnées voisines
    def CheckVoisin(self,y,x,grid):
        self.nbvoisin= 0
        if self.grid[x+1][y] == 1:
                    nbvoisin = nbvoisin+1
        if self.grid[x+1][y-1] == 1:
                    nbvoisin = nbvoisin + 1
        if self.grid[x+1][y+1] == 1:
                    nbvoisin = nbvoisin + 1
        if self.grid[x][y] == 1:
                    nbvoisin = nbvoisin+1
        if self.grid[x][y-1] == 1:
                    nbvoisin = nbvoisin + 1
        if self.grid[x][y+1] == 1:
                    nbvoisin = nbvoisin + 1
        if self.grid[x-1][y] == 1:
                    nbvoisin = nbvoisin+1
        if self.grid[x-1][y-1] == 1:
                    nbvoisin = nbvoisin + 1
        if self.grid[x-1][y+1] == 1:
                    nbvoisin = nbvoisin + 1
        print(self.nbvoisin)

#On affecte les regles en fonction du nombre de voisins.
    def EtatVoisin(self):
        if self.vivant == 0:
            if self.nbvoisin == 3:
                self.vivant = 1
                self.grid[row][column] == 2
        print(self.vivant)
        if self.vivant == 1:
            if self.nbvoisin >3:
                self.vivant=0
            if self.nbvoisin <2:
                self.vivant = 0
                self.grid[row][column] == 1
        print(self.vivant)


def menu(num):
    """
    Функция вывода меню
    :param num: сумма наличных денег
    :return: ответ пользователя
    """
    print(f'Доступная сумма: {num} руб.', end='\n\n')  # вывод наличных денег с добавлением пустой строки
    print('1. Пополнить счет')
    print('2. Совершить покупку')
    print('3. История покупок')
    print('4. Выход')
    ans = input('Введите номер пункта: ')  # ввод пункт меню пользователем
    return ans

def add(num, hist):
    """
    Добавление суммы покупки и ее наименования покупки
    :param num: количество наличных денег
    :param hist: список покупок
    :return: измененное количество наличных денег и список покупок
    """
    sale = input('Введите сумму покупки: ')  # ввод суммы покупки
    while not sale.replace('.', '', 1).isdigit():  # пока ввод пользователя с убиранием точек не цифры
        sale = input('Введите сумму покупки: ')  # снова ввести суммы
    sale = float(sale)  # перевод суммы в дробный тип данных
    if sale > num:  # если сумма покупки больше, чем сумма наличных денег
        print('Сумма покупки больше наличных денег')
    else:  # иначе
        name = input('Введите название покупки: ') # ввод название покупки
        hist.append((name, sale))  # добавление названия и суммы покупки в архив истории
        num -= sale  # вычитание суммы покупки из наличных денег
    return num, hist

def balans():
    num = 0
    history = []  # объявление глобальных переменных
    while True:  # вечный цикл
        ans = menu(num)  # получение ответа пользователя
        while ans not in ['1', '2', '3', '4']:  # пока ответ не в списке
            ans = menu(num)  # получение ответа пользователя
        if ans == '1':  # если выбран ответ 1
            amount = input('Введите сумму: ')  # ввод добавляемой суммы наличных денег
            while not amount.replace('.', '', 1).isdigit():   # пока ввод пользователя с убиранием точек не цифры
                amount = input('Введите сумму: ')  # повторить ввод суммы
            num += float(amount)  # добавить сумму к общей сумме наличных денег
        elif ans == '2':  # если ответ 2
           num, history = add(num, history)  # запустить функцию добавления продуктов
        elif ans == '3':  # если ответ 3
            for name, sale in history:  # перебрать все элементы списка истории
                print(f'Было куплено {name} за {sale} руб.')  # и вывести его
        else:  # иначе
            break  # выйти из основного цикла
        print()


from package import *

def mobile_send_code(openId, mobile):  # 输入手机号，获取短息验证码
    dict = {"scf": "ms", "mobile": "{}".format(mobile)}
    mobile_send_code_url = 'https://h5.ele.me/restapi/eus/login/mobile_send_code'
    # mobile_send_code_url = 'https://restapi.ele.me/eus/login/mobile_send_code'
    try:
        r = requests.post(mobile_send_code_url, headers=HEADERS, json=dict, timeout=25, verify=False)
        # if r.status_code == 400 and r.json()['message'] == '账户存在风险,需要图形验证码':
        if r.status_code == 400:
            result = get_captcha(openId, mobile)
            if result['status'] == 0:
                result = {'status': 1, 'message': result['message']}
                return result
            else:
                return result
        else:
            if r.status_code == 200 and 'validate_token' in r.json():
                result = {'status': 0, 'message': '验证码发送成功，请在5分钟内回复收到的验证码：\n\n注：若需重新发送手机号请先回复数字“2”哦', 'validate_token': r.json()['validate_token'], 'mobile': mobile}
                return result
            else:
                result = {'status': 2, 'message': r.json()['message']+'\n建议换个手机号试试哦'}
                return result
    except:
        write_log(3, '{}'.format(traceback.format_exc()))
        result = {'status': -1, 'message': '验证码发送失败，请重新发送手机号绑定'}
        return result

def get_captcha(openId, mobile):  # 获取短息验证码时出现图形验证码验证方法
    captcha_url = 'https://h5.ele.me/restapi/eus/v3/captchas'
    # captcha_url = 'https://restapi.ele.me/eus/v4/captchas'
    captcha_dict = {"captcha_str": "{}".format(mobile)}
    try:
        r = requests.post(captcha_url, headers=HEADERS, data=captcha_dict, verify=False, timeout=25)
        print(r.text)
        if r.status_code == 200:
            captcha_hash = r.json()['captcha_hash']
            imgbase64 = r.json()['captcha_image'].split(',')[-1]
            imagedata = base64.b64decode(imgbase64)
            img_path = '{}\{}.jpg'.format(CAPTCHA_IMG_PATH, openId)
            file = open(img_path, "wb")
            file.write(imagedata)
            file.close()
            return {'status': 0, 'message': '{}'.format(captcha_hash)}
        else:
            result = {'status': -1, 'message': '账号在获取图形验证码验证时出错了，请发送手机号重试'}
            return result
    except:
        write_log(3, '{}'.format(traceback.format_exc()))
        result = {'status': -1, 'message': '账号在获取图形验证码验证时出错了，请发送手机号重试'}
        return result
def captcha_yz(mobile, captcha_hash, captcha, openId):
    try:
        mobile_send_code_url = 'https://h5.ele.me/restapi/eus/login/mobile_send_code'
        # mobile_send_code_url = 'https://restapi.ele.me/eus/login/mobile_send_code'
        captcha_dict1 = {"scf": "ms", "mobile": "{}".format(mobile),
                         "captcha_hash": "{}".format(captcha_hash), "captcha_value": "{}".format(captcha)}
        r = requests.post(mobile_send_code_url, headers=HEADERS, data=captcha_dict1, verify=False, timeout=25)
        print(r.text)
        # 死循环，直到图形验证码出入正确为止
        if r.status_code == 400 and r.json()['message'] == '图形验证码错误':
            result = {'status': 1, 'message': '验证码验证错误'}
            return result
        elif r.status_code == 200 and 'validate_token' in r.json():
            conn = sqlite3.connect(ELEME_DATA_PATH)  # 饿了么数据库地址
            cursor = conn.cursor()  # 获取游标
            cursor.execute("SELECT open_id FROM sign_val_token")
            openIds = cursor.fetchall()
            if (openId,) in openIds:
                cursor.execute(
                    "UPDATE sign_val_token SET mobile = '{}', validate_token = '{}' where open_id = '{}'".format(mobile,
                                                                                r.json()['validate_token'], openId))
                conn.commit()
            else:
                cursor.execute(
                    "INSERT INTO sign_val_token (open_id, mobile, validate_token) VALUES ('{}', '{}', '{}')".format(
                        openId, mobile, r.json()['validate_token']))
                conn.commit()
            result = {'status': 0, 'message': '验证码发送成功，请在5分钟内回复收到的验证码：\n\n注：若需重新发送手机号请先发送“2”哦'}
            return result
        else:
            result = {'status': -1, 'message': '验证码验证失败，请重新发送手机号绑定'}
            return result
    except:
        write_log(3, '{}'.format(traceback.format_exc()))
        result = {'status': -1, 'message': '验证码验证失败，请重新发送手机号绑定'}
        return result

def login_by_mobile(validate_code, validate_token, mobile):  # 获取到短信验证码后登录，提取最新sid（身份认证信息）
    try:
        dict = {"mobile": "{}".format(mobile), "validate_token": "{}".format(validate_token),
                "validate_code": "{}".format(validate_code)}
        login_by_mobile_url = 'https://h5.ele.me/restapi/eus/login/login_by_mobile'
        # login_by_mobile_url = 'https://restapi.ele.me/eus/login/login_by_mobile'
        r = requests.post(login_by_mobile_url, headers=HEADERS, data=dict, verify=False, timeout=25)
        if r.status_code == 200:
            if 'SID' in r.cookies and 'USERID' in r.cookies:
                sid = r.cookies['SID']
                users_id = r.cookies['USERID']
                result = {'status': 0, 'sid': sid, 'users_id': users_id}
                return result
            else:
                result = {'status': 1, 'message': '验证失效了，请重新发送手机号'}
                return result
        elif r.status_code == 400:
            result = {'status': 2, 'message': '验证码错误，请重新发送验证码'}
            return result
        else:
            result = {'status': 1, 'message': '验证失效了，请重新发送手机号'}  # 这种情况一般是短信验证码错误，接码网站上最新的饿了么短信不是你前15秒发的，刚好也有人用此号码接了饿了么短信
            return result
    except:
        write_log(3, '{}'.format(traceback.format_exc()))
        result = {'status': -1, 'message': '验证出现错误，请重新发送验证码试试吧'}
        return result


# -----------------------------------------------------------------------
# Modified from imaginaire(https://github.com/NVlabs/imaginaire)
# -----------------------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation.  All rights reserved.
#
# This work is made available under the Nvidia Source Code License-NC.
# To view a copy of this license, check out LICENSE.md
# -----------------------------------------------------------------------

def get_paired_input_image_channel_number(data_cfg):
    """
    Get number of channels for the input image.
    """
    num_channels = 0
    for ix, data_type in enumerate(data_cfg.input_types):
        for k in data_type:
            if k in data_cfg.input_image:
                num_channels += data_type[k].num_channels
                # print('Concatenate %s for input.' % data_type)
    print('\tNum. of channels in the input image: %d' % num_channels)
    return num_channels

def get_paired_input_label_channel_number(data_cfg, video=False):
    """
    Get number of channels for the input label map.

    Args:
        data_cfg (obj): Data configuration structure.
        video (bool): Whether we are dealing with video data.
    Returns:
        num_channels (int): Number of input label map channels.
    """
    num_labels = 0
    if not hasattr(data_cfg, 'input_labels'):
        return num_labels
    for ix, data_type in enumerate(data_cfg.input_types):
        for k in data_type:
            if k in data_cfg.input_labels:
                num_labels += data_type[k].num_channels
                if getattr(data_type[k], 'use_dont_care', False):
                    print(data_type[k].use_dont_care)
                    num_labels += 1
            # print('Concatenate %s for input.' % data_type)

    if video:
        num_time_steps = getattr(data_cfg.train, 'initial_sequence_length', None)
        num_labels *= num_time_steps
        num_labels += get_paired_input_label_channel_number(data_cfg) * (num_time_steps - 1)

    print('\tNum. of channels in the input label: %d' % num_labels)
    return num_labels


import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
from tornado import web, gen
from tornado.options import define, options
from tornado.escape import json_encode
from tools.dbutil import maddb, mongodb
from tools.westutil import write_cmitem
from tools.ThreadPool import ThreadPool
from tools.otherutil import dateoffset, xldate, trunc
from ntmadservice import *
from PriceChangeSnapshot import PriceChangeLive
from rampdiff import test_rampdiff
from datetime import datetime, timedelta
import json
import time
import os
import pdb

logger = logging.getLogger('')
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
fh = logging.FileHandler(r'\\SINEMC114042\risktech\Tools\IRG\Log\restfultest.log')
fh.setFormatter(formatter)
console = logging.StreamHandler()
console.setFormatter(formatter)

logger.addHandler(console)

class BaseHandler(tornado.web.RequestHandler):
    @property
    def mongo(self):
        return self.application.mongo

class RampDiff(BaseHandler):
    def post(self):
        try:
            baseSet = self.get_argument("baseSet")
            destSet = self.get_argument("destSet")
            setDate = self.get_argument("setDate")
            t = xldate(datetime.strptime(setDate, '%d/%m/%Y'))
            self.set_header('Content-Type', 'application/json')
            self.write(json_encode(test_rampdiff(baseSet, t, destSet, t)))
        except Exception as e:
            self.write(e)

    def get(self):
        pass

class RebuildIndex(BaseHandler):

    def post(self):
        self.reglib = list(self.mongo.meteor.errtemplate.find({},{"_id":0}))
        self.mongo.rebuildIndex(self.reglib, buildall=True)
        print("rebuild complete")
        self.write("OK")

    def get(self):
        pass

class runriskHander(BaseHandler):

    def post(self):
        try:
            t_now = datetime.now()
            activity= self.mongo

            body = str(self.request.body)
            request = json.loads("{"+body[3:-2]+"}")
            logger.info(request)

            session_id = request["user-name"] + "_" + t_now.strftime("%H%M%S")

            tornado.ioloop.IOLoop.instance().add_callback(self.ntmadcallback, session_id, request)
            self.write("%s" % (session_id))
        except Exception as e:
            logger.info("session ended in error %s" % e)
            activity.end_session("Error", datetime.now(), session_id)
            self.write("NOK")

    @gen.coroutine
    def ntmadcallback(self, session_id, request):

        try:
            logger.info("callback started for %s" % session_id)

            cmd = ntmadcmd(session_id, request)

            logger.info(cmd.depcmds)
            logger.info(cmd.cmds)

            logger.info("session initiated %s" % session_id)
            self.mongo.start_session(session_id, request, cmd.db)

            if len(cmd.depcmds):
                tornado.ioloop.IOLoop.instance().add_callback(self.ntmadtask, cmd, True)
            else:
                if len(cmd.fx2d):
                    x, y = cmd.fx2d
                    if not "X" in x:
                        x, y = y, x
                    xccy = x.split(".")[-1]
                    xccy = xccy[:3]+"/"+xccy[3:]
                    yccy = y.split(".")[-1]
                    yccy = yccy[:3]+"/"+yccy[3:]
                    sts = write_cmitem([xccy] + request[x].split(","), "Cedar.Public.Singapore Pilot.Ranges.FX2DMATRIX xAxis")
                    sts = sts and write_cmitem([yccy] + request[y].split(","), "Cedar.Public.Singapore Pilot.Ranges.FX2DMATRIX yAxis")

                tornado.ioloop.IOLoop.instance().add_callback(self.ntmadtask, cmd, False)

            logger.info("callback ended for %s" % session_id)
        except Exception as e:
            logger.error("%s ended in error %s" % (session_id, e))
            self.mongo.end_session("Error", session_id)

    @gen.coroutine
    def ntmadtask(self, cmd, dep):
        try:
            ntmad_ret = cmd.submit(dep)
            logger.info(ntmad_ret)
            self.mongo.insert_jobs(cmd.session_id, ntmad_ret)
            while not self.mongo.is_done(ntmad_ret["job_id"]):
                yield gen.Task(tornado.ioloop.IOLoop.instance().add_timeout, time.time()+1)
            if dep:
                tornado.ioloop.IOLoop.instance().add_callback(self.ntmadtask, cmd, False)
            else:
                self.mongo.end_session("Done", cmd.session_id)
                logger.info("session id %s ended" % cmd.session_id)
        except Exception as e:
            logger.error("%s ended in error %s" % (session_id, e))
            self.mongo.end_session("Error", session_id)

class queryjobsHandler(BaseHandler):
    def get(self):
        session_id = self.get_argument("session_id")
        response = self.mongo.query_session(session_id, self.application.sysdate)
        logger.info(response)
        self.write(json_encode(response))

class MainHandler(BaseHandler):
    def get(self):
        self.write("Web Service for interstellar")

class Application(tornado.web.Application):

    def __init__(self):
        handlers = [
                (r"/", MainHandler),
                (r"/interstellar/rampdiff", RampDiff),
                (r"/interstellar/rebuildindex", RebuildIndex),
                (r"/ntmadservice/runrisk", runriskHander),
                (r"/ntmadservice/queryjob", queryjobsHandler)
        ]
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)

        self.menus = json.load(open("menuConfig.json"))
        self.menus_mtime = os.path.getmtime(os.path.abspath("menuConfig.json"))
        self.mad = maddb(json.load(open("madQuery.json")))
        self.mongo = mongodb('mongodb://localhost:3001/', self.mad)
        self.sysdate = datetime.today()
        self.reglib = list(self.mongo.meteor.errtemplate.find({},{"_id":0}))

    def rollsysdate(self):
    	logger.info("system rolled")
    	self.sysdate = datetime.today()
    	tornado.ioloop.IOLoop.instance().add_timeout(timedelta(seconds=24*60*60), self.rollsysdate)

    def rrqueueRefresh(self):
        self.mongo.updateProgress(self.sysdate)

    def jobqueueRefresh(self, inception=False):
        mtime = os.path.getmtime(os.path.abspath("menuConfig.json"))
        if self.menus_mtime > mtime:
            self.menus = json.load(open("menuConfig.json"))
            self.menus_mtime = mtime

        baseDt = dateoffset(self.sysdate, -1,"%d/%m/%Y")
        for loc, v in self.menus.items():
            farm = v["mad"]
            for scene, vv in v["scenes"].items():
                for batch, jobs in vv["monitor"].items():
                    self.mongo.refreshQueue(farm, baseDt, batch, jobs, scene, inception)

        self.mongo.rebuildIndex(self.reglib)

    def livefeed(self):
        logger.info("PriceChangeLive")
        df = PriceChangeLive()
        self.mongo.updateLiveFeed(json.loads(df.to_json(orient="records")))

if __name__ == "__main__":
    app = Application()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(8080)
    #app.listen(443)

    delta = trunc(dateoffset(app.sysdate, 1))-app.sysdate
    tornado.ioloop.IOLoop.instance().add_timeout(timedelta(seconds=delta.seconds+7*60*60), app.rollsysdate)
    app.jobqueueRefresh(True)
    tornado.ioloop.PeriodicCallback(app.jobqueueRefresh, 5*1000*60).start()
    app.livefeed()
    tornado.ioloop.PeriodicCallback(app.livefeed, 1*1000*60).start()
    tornado.ioloop.PeriodicCallback(app.rrqueueRefresh, 1000*1).start()
    logger.info("interstellar started")
    tornado.ioloop.IOLoop.instance().start()


import datetime
import unittest
import os
import json

import salvitobot
from salvitobot import utils
from salvitobot.exceptions import NoCountryError
from salvitobot.exceptions import ProcedureError

class TestUtils(unittest.TestCase):
    def setUp(self):
        self.maxDiff = None
        self.cwd = os.path.abspath(os.path.dirname(__file__))
        self.bot = salvitobot.Bot()

        with open(os.path.join(self.cwd, 'Quake', '1.json'), 'r') as handle:
            self.data1 = json.loads(handle.read())

    def test_get_quake(self):
        self.bot.get_quake(my_dict=self.data1, country='Venezuela')
        result = self.bot.quake
        expected = 1
        self.assertEqual(expected, len(result))

    def test_get_quake_strange_country(self):
        self.bot.get_quake(my_dict=self.data1, country='Vulcan')
        result = self.bot.quake
        expected = 0
        self.assertEqual(expected, len(result))

    def test_get_quake_from_web(self):
        self.bot.urls = [
            'http://pastebin.com/raw.php?i=0WuxsixK',
        ]
        self.bot.get_quake(country='Venezuela')
        result = self.bot.quake
        expected = 1
        self.assertEqual(expected, len(result))

    def test_get_quake_no_country(self):
        self.assertRaises(NoCountryError, self.bot.get_quake, self.data1)

    def test_is_new_quake(self):
        self.bot.get_quake(my_dict=self.data1, country='Venezuela')
        expected = True
        result = self.bot.is_new_quake()
        self.assertEqual(expected, result)

    def test_is_new_quake_false_empty(self):
        self.bot.get_quake(my_dict=self.data1, country='Narnia')
        result = self.bot.is_new_quake()
        self.assertFalse(result)

    def test_is_new_quake_false_in_db(self):
        item = {
            'longitude': 126.3037,
            'time': 1423215548040,
            'latitude': 9.5166,
            'country': 'cortes',
            'place': '28km NNE de Cortes, Philippines',
            'tuit': 'SISMO. 4.8 grados mb en 28km NNE de Cortes, Philippines. A horas  http://earthquake.usgs.gov/earthquakes/eventpage/usc000tmn4',
            'type': 'earthquake',
            'magnitude_type': 'mb',
            'detail': 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/usc000tmn4.geojson',
            'link': 'http://earthquake.usgs.gov/earthquakes/eventpage/usc000tmn4',
            'code': 'c000tluz',
            'depth': 84.37,
            'datetime_utc': datetime.datetime(2015, 2, 6, 9, 39, 8, 39999),
            'tz': 480,
            'magnitude': 4.8,
        }
        utils.save_to_db(item, test=True)
        self.bot.get_quake(my_dict=self.data1, country='Venezuela')
        expected = False
        result = self.bot.is_new_quake(test=True)
        self.assertEqual(expected, result)

    def test_is_new_quake_no_country(self):
        self.assertRaises(ProcedureError, self.bot.is_new_quake)

    def test_extract_nearby_cities(self):
        country = 'Venezuela'
        self.bot.get_quake(my_dict=self.data1, country=country)
        result = utils.extract_nearby_cities(self.bot.quake[0], country)
        expected = "a 4 km al SO de Coloncito, a 15 km al ENE de La Fria y a 32 km al ESE de Puerto Santander, Colombia"
        self.assertEqual(expected, result)

    def test_write_post_no_country(self):
        self.assertRaises(ProcedureError, self.bot.write_stories)

    def test_write_post_nothing_to_post(self):
        self.bot.get_quake(self.data1, country='Venezuela')
        self.bot._quakes_to_write = []
        expected = "Nothing to do."
        result = self.bot.write_stories()
        self.assertEqual(expected, result)

    def test_write_post(self):
        self.bot.get_quake(self.data1, country='Venezuela')
        self.bot.is_new_quake()
        self.bot.write_stories()
        result = self.bot.stories
        self.assertTrue(len(result) > 0)


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

from odoo import api, models, fields, _

from odoo.addons.payment.models.payment_acquirer import ValidationError

import logging
import uuid

_logger = logging.getLogger(__name__)

class TipiRegieTransaction(models.Model):
    _inherit = 'payment.transaction'

    tipiregie_operation_identifier = fields.Char(
        string='Operation identifier',
        help='Reference of the request of TX as stored in the acquirer database'
    )

    tipiregie_return_url = fields.Char(
        string='Return URL',
    )

    @api.model
    def _tipiregie_form_get_tx_from_data(self, idop):
        if not idop:
            error_msg = _('Tipi Regie: received data with missing idop!')
            _logger.error(error_msg)
            raise ValidationError(error_msg)

        # find tx -> @TDENOTE use txn_id ?
        txs = self.env['payment.transaction'].sudo().search([('tipiregie_operation_identifier', '=', idop)])
        if not txs or len(txs) > 1:
            error_msg = 'Tipi Regie: received data for idop %s' % idop
            if not txs:
                error_msg += '; no order found'
            else:
                error_msg += '; multiple order found'
            _logger.error(error_msg)
            raise ValidationError(error_msg)
        return txs[0]

    @api.multi
    def _tipiregie_form_validate(self, idop):
        self.ensure_one()

        # If transaction is already done, we don't try to validate again.
        if self.state in ['done']:
            return True

        if not idop:
            error_msg = _('Tipi Regie: received data with missing idop!')
            _logger.error(error_msg)
            raise ValidationError(error_msg)

        data = self.acquirer_id.tipiregie_get_result_from_web_service(idop)
        status = data.get('resultrans')

        if status in ['P']:
            _logger.info('Validated Tipi Regie payment for tx %s: set as done' % self.reference)
            self.write({
                'state': 'done',
                'date_validate': fields.Datetime.now()
            })
            return True
        elif status in ['A']:
            _logger.info('Received notification for Tipi Regie payment %s: set as canceled' % (self.reference))
            self.write({
                'state': 'cancel',
            })
            return True
        elif status in ['R']:
            error = 'Received notification for Tipi Regie payment %s: set as error' % self.reference, status
            _logger.info(error)
            self.write({
                'state': 'error',
                'state_message': error,
            })
            return True
        else:
            error = 'Received unrecognized status for Tipi Regie payment %s: %s, set as error' % (
                self.reference,
                status
            )
            _logger.error(error)
            self.write({
                'state': 'error',
                'state_message': error,
            })
            return False

    @api.multi
    def tipiregie_generate_operation(self):
        for tx in self:
            email = tx.partner_id.email
            price = int(tx.amount * 100)
            object = tx.reference.replace('/', '  slash  ')
            acquirer_reference = tx.acquirer_reference or '%.15d' % int(uuid.uuid4().int % 899999999999999)
            try:
                idop = tx.acquirer_id.tipiregie_get_id_op_from_web_service(email, price, object, acquirer_reference)
            except:
                idop = ''

            tx.write({
                'acquirer_reference': acquirer_reference,
                'tipiregie_operation_identifier': idop,
            })

        return


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec  8 12:20:18 2019

@author: ishuu
"""

def sieve(n):
    prime = [True for i in range(n+1)]
    p = 2
    count = 0
    while(p*p <= n):
        if(prime[p] == True):
            for i in range(p*p, n+1, p):
                prime[i] = False
        p += 1
        for p in range(n):
            if prime[p]:
                count += 1
    return count

a = int(input())
b = int(input())
c =  sieve(a)
d = sieve(b)

print(d-c)


# Time:  O(n^3)
# Space: O(n^2)

# 1039
# Given N, consider a convex N-sided polygon with vertices labelled A[0], A[i], ..., A[N-1] in clockwise order.
#
# Suppose you triangulate the polygon into N-2 triangles.  For each triangle, the value of that triangle is
# the product of the labels of the vertices, and the total score of the triangulation is the sum of these values
# over all N-2 triangles in the triangulation.
#
# Return the smallest possible total score that you can achieve with some triangulation of the polygon.

from typing import List

class Solution(object):
    # [3,7,4,5] only needs to compute 4 multiplications
    # p = 3: mult(3,7,4), mult(7,4,5)
    # p = 4: mult(3,7,5), mult(3,4,5)
    def minScoreTriangulation2(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        N = len(A)
        dp = [[0]*N for _ in range(N)]
        for l in range(3, len(A)+1):
            for i in range(len(A)-l+1):
                j = i+l-1;
                dp[i][j] = float("inf")
                for k in range(i+1, j):
                    dp[i][j] = min(dp[i][j], dp[i][k]+dp[k][j] + A[i]*A[k]*A[j])
        return dp[0][-1]

    # TLE: dfs + memorization. E.g. [3,7,4,5] needs to compute 8 multiplications containing repeated computation which
    # are not prevented by cache:
    #  mult(5,3,7)+helper(7,4,5)
    #  mult(3,7,4)+helper(3,4,5)
    #  mult(7,4,5)+helper(3,7,5)
    #  mult(4,5,3)+helper(3,7,4)
    def minScoreTriangulation(self, A: List[int]) -> int:
        from functools import reduce, lru_cache
        import operator

        @lru_cache(None)
        def helper(nums):
            N = len(nums)
            if N == 3:
                return reduce(operator.mul, nums)

            return min(nums[(i - 1) % N] * nums[i] * nums[(i + 1) % N] + helper(nums[:i] + nums[i + 1:])
                       for i in range(N))

        return helper(tuple(A))

print(Solution().minScoreTriangulation([3,7,4,5,])) # 144: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144
print(Solution().minScoreTriangulation([1,3,1,4,1,5])) # 13, minimum score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.


#!/usr/bin/python3

import sys, random

assert sys.version_info >= (3,4), "This script requires at least Python 3.4"

def random_encounter_generator(num60to89, provision):
        """Randomly chooses between 5 pregenerated scenarios.

        num -> function"""

        if(num60to89 < 66):
                return random_encounter_horde()

        elif(num60to89 < 72):
                return random_encounter_bandits(provision)

        elif(num60to89 < 78):
                return random_encounter_dogs()

        elif(num60to89 < 84):
                return random_encounter_helpinghand(provision)

        elif(num60to89 < 90):
                return random_encounter_deer(provision)

def random_encounter_horde():
        while True:
                dec = str.upper(input("A sea of the living dead stands before you. You must try to sneak past it or return to the door. Please enter \"Return\" or \"Sneak\".\n"))
                if(dec == "SNEAK"):
                        if random.randint(0,100) > 75:
                                print("You have found a can of pineapple juice in a shack. Not much, but it will sustain you for a day.")
                                return 1
                        else:
                                print("The effort was fruitless; there was simply no way around the horde. You return home empty-handed.")
                                return 0
                elif(dec == "RETURN"):
                        print("You turn back in the face of the horde, with nothing to show for your wasted time.")
                        return 0
                else:
                        print("Please enter \"Return\" or \"Sneak\".")

def random_encounter_bandits(amtfood):
        while True:
                dec = str.upper(input("""An armed man, covered in dirt, sits on a blue chair in front of you.""" +
                                      """There is a can of tomato soup under his chair. Will you fight him for the can or leave?\nPlease enter \"Fight\" or \"Leave\".\n"""))
                if(dec == "FIGHT"):
                        if random.randint(0,100) > 50:
                                print("You successfully surprise the gruff man, choking him and stealing his meal. He would do the same, after all.")
                                return 1
                        else:
                                print("The strong man overpowers you and begins to fire at you. You barely escape and, in your haste, drop a can of food.")
                                if amtfood > 0:
                                        return -1
                                else:
                                        return 0
                elif(dec == "LEAVE"):
                        print("You do not trust that you could overpower this man. You return home empty-handed.")
                        return 0

                else:
                        print("Please enter \"Fight\" or \"Leave\".")

def random_encounter_dogs():
        while True:
                dec = str.upper(input("""A group of wild dogs - perhaps once domesticated - are whining outside a door inside an overgrown house.""" +
                                      """\nWill you attempt to open the door? Please enter \"Yes\" or \"No\".\n"""))
                if(dec == "YES"):
                        if random.randint(0, 100) > 50:
                                print("The wild dogs allow you to open the door for them. They begin feasting on the corpse within, distracted while you grab a can of dog food for yourself.")
                                return 1
                        else:
                                print("The wild dogs bark and chase you away from the door. You remain uninjured, but are forced to return to the bunker empty-handed.")
                                return 0
                elif(dec == "NO"):
                        print("Deciding not risk upsetting the canines, you return home without anything to show for your trip.")
                        return 0

                else:
                              print("Please enter \"Yes\" or \"No\".")

def random_encounter_helpinghand(amtfood):
        while True:
                dec = str.upper(input("A man stands alone in a clearing. He is well-armed. Do you approach? Please enter \"Yes\" or \"No\".\n"))
                if dec == "YES":
                        if random.randint(0,100) > 30:
                                print("The man spots you, and waves at you. He has a smile on his face. After a short conversation, he agrees to give you a can of tuna and sends you on your way.")
                                return 1
                        else:
                                print("The man spots you and waves you over. When you get close, however, he holds you at gunpoint and demands a can of food. You are forced to give him one.")
                                if amtfood > 0:
                                        return -1
                                else:
                                        return 0
                elif dec == "NO":
                        print("No other oppurtunities present themselves. You find no food and are forced to return to the bunker with nothing.")
                        return 0

                else:
                        print("Please enter \"Yes\" or \"No\".")

def random_encounter_deer(amtfood):
        while True:
                dec = str.upper(input("A great stag has impaled itself upon a piece of rebar and has died. Will you harvest what you can? Please enter \"Yes\" or \"No\".\n"))
                if dec == "YES":
                        if random.randint(0,100) > 10:
                                print("The stag's meat provides two days of much-appreciated fresh meat to your diet after you collect what you can.")
                                return 2
                        else:
                                print("When you eat the meat, you come to realize it has made you even more starving than before. You are forced to eat a can of food to survive.")
                                if amtfood > 0:
                                        return -1
                                else:
                                        return 0

                elif dec == "NO":
                        print("You cannot risk getting sick from meat, no matter how fresh. You unfortunately return home empty handed.")
                        return 0

                else:
                        print("Please enter \"Yes\" or \"No\".")

#declaring variables

#Guesses which can be depleted by other activities, such as searching for food or being exhausted by lack of food.
hours = 10
#A player can guess between 1 and 100.
guess_range = 100
# The player has 3 nights of food to start with. When it reaches zero, the player will begin to oversleep.
provisions = 3
#Nights are the score.
nights = 0
# Keeps track of whether the player got inside.
inside = 0
# Luck determines whether a scavenging session is successful.
luck = 0
# To exit the game early
end = False

#generate a random integer between 1 and 100 (inclusive) and store it in the variable [number]

# Main set of code

while(hours > 0 and not end):
        nightsSTR = str(nights)
        provisionsSTR = str(provisions)
        print("You have survived " + nightsSTR + " nights. \nYou have " + provisionsSTR + " nights of food.\nEnter \"Quit\" to quit.")
        inside = 0
        combo = random.randint(1,guess_range)
        while(hours > 0 and not end):
                scavOrGuess = input("Would you like to scavenge for food or guess the combo? Each takes one hour.\n")

                if(str.upper(scavOrGuess) == ("SCAVENGE") or str.upper(scavOrGuess) == ("SCAVENGE FOR FOOD") or str.upper(scavOrGuess) == "FOOD"):
                        hours -= 1
                        luck = random.randint(1,100)
                        if(luck < 60):
                                print("You found no food in the overgrown buildings surrounding the bunker.")
                        elif(luck >= 60 and luck <90):
                                provisions = provisions + random_encounter_generator(luck, provisions)
                        elif(luck >= 90):
                                print("You found a delicious, beautiful can of baked beans in the burnt-out rubble of a house. Provisions +1. ")
                                provisions += 1

                elif(str.upper(scavOrGuess) == ("GUESS") or str.upper(scavOrGuess) == ("GUESS THE COMBO") or str.upper(scavOrGuess) == ("COMBO")):
                        while(hours > 0 and not end):
                                #ask the user for a response and store it in the variable [guess]
                                guess = input("Input a combination between 1 and 100.\n")

                                #a try/except block is a great tool for programmers to be able to deal with errors. In this instance, it reports an error if the user enters something other than an integer
                                try:
                                        #convert the guess to an integer
                                        guess = int(guess)

                                #check if the guess is less than the random number
                                        if guess < combo:
                                                print('Too low!')
                                                hours -= 1

                                        elif guess > combo:
                                                print("Too high!")
                                                hours -= 1

                                        elif guess == combo:
                                                print("You got in!")
                                                nights += 1
                                                hours = 10
                                                inside = 1
                                                break

                                        hoursSTR = str(hours)
                                        print("You have " + hoursSTR + " hours left.")
                                except ValueError:
                                        if str.upper(guess) == "QUIT":
                                                end = True
                                        else:
                                                print('Please enter a whole number.')
                        if(inside == 1):
                                break
                elif(str.upper(scavOrGuess) == "QUIT"):
                     end = True
        if(provisions == 0):
                hours -= random.randint(2, 6)
                hoursSTR = str(hours)
                print("Due  to lack of food, you overslept. You only have " + hoursSTR + " hours today.")
        elif(provisions > 0):
                provisions -= 1

print("You have died. You survived " + nightsSTR + " nights.")


import re

f = open("NLU.train", "r")
statement = ""
nameTag = ""
idTag = ""
tagStart = False

for line in f:
    if "<" in line:
        tagStart = True
        if tagStart == True:
          wordList = re.sub("[^\w]", " ",  statement).split()
        # print("This is statement:",statement)
        print("This is a word list", wordList)
        continue
    else:
      # print(line)
      statement = line
      if "name=" in line:
        nameTag = line
        continue
      if "id=" in line:
        idTag = line
        continue

    if ">" in line:
        tagStart = False
        print("This is statement:",statement)
        print("This is idTag------",idTag)
        print("This is nameTag------",nameTag)
        nameTag = ""
        idTag = ""
        # print (line)
        continue


# Your task is to complete this function
# Function should return True/False or 1/0
# Graph(graph) is a defaultict of type List
# n is no of Vertices
from collections import defaultdict
def Cycle1(v, visited, g, d):
	visited[v]=1
	d[v]+=1
	for i in g[v]:

		if(visited[i]==0):

			if(Cycle1(i, visited, g, d)):
				return True
		else:
			if(d[i]>0):
				return True
	d[v]-=1
	return False

def isCyclic(n, g)	:
	visited=[0]*n
	d=defaultdict(int)
	for i in range(n):
		if(Cycle1(i , visited, g, d))==True:
			return True

	# d=defaultdict(int)
	# for i in range(n):
	# 	if(Cycle1(i, visited, g, d))==True:
	# 		return Truen ,graph

#{
#  Driver Code Starts

from collections import defaultdict

def creategraph(n, arr, graph):
    i = 0
    while i < 2 * e:
        graph[arr[i]].append(arr[i + 1])
        # graph[arr[i + 1]].append(arr[i])
        i += 2

if __name__ == '__main__':
    t = int(input())
    for i in range(t):
        n,e = list(map(int, input().strip().split()))
        arr = list(map(int, input().strip().split()))
        graph = defaultdict(list)
        creategraph(e, arr, graph)
        if isCyclic(n, graph):
            print(1)
        else:
            print(0)
# } Driver Code Ends


"""Tests for pyglint."""

import subprocess
import sys

def test_example():
    args = [
        sys.executable,
        "-m",
        "pylint",
        "--load-plugins",
        "examples.mylinter",
        "examples/to-be-linted.py",
    ]
    output = subprocess.run(args, check=False, stdout=subprocess.PIPE).stdout.decode()
    assert "bad-name" in output
    assert "import-from" in output


'''
Created on Jan 24, 2019

@author: fb
'''

import os
from pip._vendor.colorama.ansi import Back
from pyspark import SparkConf, SparkContext

def main():
    """
        @summary: plain main method
    """

    file_out_name = 'out/word_counts'

    sparkCtx = initSpark()

    myRDD = readFile(sparkCtx, "t8.shakespeare.txt")
    wordCounts = myRDD.flatMap(lambda line: line.split(" ")).map(lambda word: (word, 1)).reduceByKey(lambda x, y: x + y)

    # sort by values descending
    wcByValue = wordCounts.sortBy(lambda wordCounts: wordCounts[1], ascending=False)

    # print on console
    # printResult(wcByValue)

    # print the result to a file
    wcByValue.coalesce(1).saveAsTextFile(file_out_name)

def printResult(resRDD):
    """
        @summary: prints out the resulting tuples
    """
    for word, count in resRDD.collect():
        print("{} : {} ".format(word, count))

def prepFile(fname, start, stop):
    """
        @summary: removing lines from a file, beginning by @start, ending by @stop
        @param fname: filename
        @param start: line number to start
        @param stop: line number to stop
    """
    import fileinput

    for line in fileinput.input(fname, inplace=1, backup='.orig'):
        if start <= fileinput.lineno() < start + stop:
            pass
        else:
            print(line[:-1])

    fileinput.close()

def readFile(sc, filename):
    """
        @summary: reads in a file with the given name and returns a RDD
        @param sc: SparkContext
    """

    # fname = 'in/numbers.txt'
    prepFile("in/" + filename, 0, 243)

    return sc.textFile("in/" + filename)

def initSpark():
    """
        @summary: initialises the SparkContext
    """
    conf = SparkConf().setAppName("CountWords").setMaster("local[*]")
    sc = SparkContext(conf=conf)

    return sc

if __name__ == '__main__':
    main()


from __future__ import division
from __future__ import print_function
import numpy as np
import scipy.sparse as spse

import convenient as cvnt

def blochFromPureState(minus, plus):
    """
        construct a Bloch vector from the pure state

        |psi> = minus |-> + plus |+>

        if it is not normed, the normed coefficients will be used
    """
    n = np.sqrt(abs(minus)**2 + abs(plus)**2)
    assert np.all(n != 0)

    minus /= n
    plus  /= n

    z = abs(plus)**2 - abs(minus)**2
    x = 2*np.real(minus*np.conj(plus))
    y = 2*np.imag(minus*np.conj(plus))
    return x,y,z

class qBit (object):
    """
        qBit representation using Bloch's vector (x,y,z)

        RHO_qbit = 1/2 [E + x SIG_x + y SIG_y + z SIG_z]
    """
    def __init__(self, x=0, y=0, z=1, state = None, matrix = None, traceCheck = True, hermitianCheck = True):
        if state != None:
            self.fromPureState(*state)
        elif matrix != None:
            self.fromMatrix(matrix, traceCheck, hermitianCheck)
        else:
            assert (x**2 + y**2 + z**2) <= 1
            self._x = x
            self._y = y
            self._z = z

    @property
    def x(self):
        return self._x
    @property
    def y(self):
        return self._y
    @property
    def z(self):
        return self._z

    def __repr__(self):
#         print(type(self._x))
#         print(type(self._y))
#         print(type(self._z))

        r = "1/2 [E + {:.3e} SIG_x + {:.3e} SIG_y + {:.3e} SIG_z]".format(self._x, self._y, self._z)
        return r

#     def __str__(self):
#         return str(0.5 * np.array([[1 - self._z, self._x + 1j*self._y],
#                                    [self._x - 1j*self._y, 1 + self._z]]))

    def getAsCOO(self):
        """
            return RHO_qbit as density matrix (scypi.sparse.cco_matrix type)
        """
        data = 0.5 * np.array([1 - self._z, 1 + self._z, self._x + 1j*self._y, self._x - 1j*self._y])
        row = [0,1,0,1]
        col = [0,1,1,0]
        return spse.coo_matrix((data, (row,col)), shape=(2,2))

    def getAsDense(self):
        """
            return RHO_qbit as density matrix (2x2 numpy array)
        """
        return self.getAsCOO().todense()

    def getAsPureState(self):
        """
            use current Bloch vector scaled to length 1

            return the coefficients of the corresponding pure state

            |psi> = minus |-> + plus |+>

            where minus is chosen to be real
        """
        if self._z == 1:
            return np.array([0., 1.])
        elif self._z == -1:
            return np.array([1., 0.])
        else:
            r = np.sqrt(self._x**2 + self._y**2 + self._z**2)
            assert r != 0
            minus = np.sqrt(self._x**2 + self._y**2) / r / np.sqrt(2*(1+self._z/r))
            plus = (self._x - 1j*self._y) / 2 / minus
            return np.array([minus, plus])

    def fromPureState(self, minus, plus):
        """
            construct a Bloch vector from the pure state

            |psi> = minus |-> + plus |+>

            if it is not normed, the normed coefficients will be used
        """

        self._x, self._y, self._z = blochFromPureState(minus, plus)

    def fromMatrix(self, rho, traceCheck = True, hermitianCheck = True):
        if traceCheck:
            assert np.allclose(rho[0,0] + rho[1,1], 1)
        if hermitianCheck:
            assert np.allclose(rho[0,1] - np.conj(rho[1,0]), 0)

        self._z = float(1 - 2*np.real(rho[0,0]))
        self._x = float(np.real(2*rho[0,1]))
        self._y = float(np.imag(2*rho[0,1]))

def testQBit(n):
    print("run testQBit ...")
    qB = qBit()

    for i in range(n):
        state = np.array([np.random.rand()+1j*np.random.rand(),np.random.rand()+1j*np.random.rand()])
        qB.fromPureState(*state)
        statePrime = qB.getAsPureState()

        state /= np.sqrt(sum(abs(state)**2))
        phi = np.angle(state[0])
        state *= np.exp(-1j*phi)

        assert np.allclose(state, statePrime)

    print("done!\n")

def runTests():
    runs = 100
    testQBit(runs)

if __name__ == "__main__":
    runTests()


import math

# deghat baraye mosavi bodan adad
epsilon = 1e-12

# bode matrice vorodi dade shode
n = int(input())

# tabe baraye namayesh matrice
def print_matrix(A):
	for i in range(len(A)):
		for j in range(len(A[i])):
			print ("%.6f" % A[i][j], end = " ")
		print()
	print()

# tabe baraye zarbe do matrice n dar n
def multiply(A, B):
	result = []
	for i in range(n):
		result.append([0 for j in range(n)])

	for i in range(n):
		for j in range(n):
			for k in range(n):
				result[i][j] += A[i][k] * B[k][j]
	return result

# matrice givens baraye davarane khane (row, col) ba zavie ke cosinos aan barabare c va sinos aan barabare s ast
def givens(row, col, c, s):
	G = []
	for i in range(n):
		G.append([0 for j in range(n)])
	for i in range(n):
		G[i][i] = 1

	G[row][row] = c
	G[col][col] = c
	G[row][col] = s
	G[col][row] = -s
	return G

# bedast avordan tajzie QR
def QR(A):

	# ebteda Q ra matrice hamani gharar midahim
	Q = []
	for i in range(n):
		Q.append([0 for j in range(n)])
	for i in range(n):
		Q[i][i] = 1

	# baraye sotoone i mikhahim satr haie i + 1 ta n - 1 ra 0 konim
	for i in range(n):
		# deraie (i, i) matrix ra ba meghdari nasfer az aan sotoon jaigozin mikonim
		if abs(A[i][i]) < epsilon :
			for j in range(i + 1, n):
				if abs(A[j][i]) >= epsilon:
					A[j], A[i] = A[i], A[j]
					break

		# agar (i, i) nasefri mojood nabashad matrice voroodi dade shode varoon pazir nist
		if abs(A[i][i]) < epsilon:
			print("Matrix is not inversable!")
			exit()

		# baraye tam satr ha i + 1 ta n - 1 mannade j mikhahim ba komake A[i][i] meghdare A[j][i] ra sefr konim
		for j in range(i + 1, n):
			r = math.sqrt(A[j][i] * A[j][i] + A[i][i] * A[i][i])
			c, s = A[i][i] / r, -A[j][i] / r
			A = multiply(givens(j, i, c, s), A) # A ra dar matrice givens(j, i, c, s) zarb konim A[j][i] sefr mishavad
			Q = multiply(Q, givens(j, i, c, -s)) # givens(j, i, c, -s) haman varoon givens(j, i, c, s) ast

	return [Q, A]

#voroodi gereftan az karbar
A = []
for i in range(n):
	A.append([int(num) for num in input().split(' ')])

# print kardan javab
Q, R = QR(A)
print ("Q:")
print_matrix(Q)
print("R: ")
print_matrix(R)


#calss header
class _EMANCIPATION():
	def __init__(self,):
		self.name = "EMANCIPATION"
		self.definitions = [u'the process of giving people social or political freedom and rights: ']

		self.parents = []
		self.childen = []
		self.properties = []
		self.jsondata = {}

		self.specie = 'nouns'

	def run(self, obj1 = [], obj2 = []):
		return self.jsondata


import pandas as pd

import os

def huifu(s):
    return s[:9] + s[16:]

f = open(r"C:\Users\qeaw\Desktop\tongji\fude.txt","r")

s = f.read()

f.close()

l = eval(s[4:])
ll = [huifu(i) for i in l]

os.chdir(r"C:\stock_data")

def xianshi(gpdm):
    os.chdir(r"C:\stock_data")
    df = pd.read_table(gpdm, skiprows=1, skipfooter=1, engine="python", parse_dates=True, )

    now_c = []
    for i in df.columns:
        i = i.strip(" ")
        now_c.append(i)
    df.columns = now_c

    datadf = df.loc[1028:]
    datadf.index = range(len(datadf))

    rmin = datadf["成交额"].rolling(window=30).min()
    rmax = datadf["成交额"].rolling(window=30).max()
    rmean = datadf["成交额"].rolling(window=30).mean()

    os.chdir(r"C:\Users\qeaw\Desktop\rrr\result3")
    result = []
    m = 0
    for i in range(30, len(datadf)):
        dn = 0
        liangjia = 0
        liang = 0
        for j in range(1, 30):
            pricen = datadf.loc[i - j]["收盘"]
            pricey = datadf.loc[i - j - 1]["收盘"]
            rate = (pricen / pricey) - 1
            v = datadf.loc[i - j]["成交额"]
            vv = v / rmean[i - j]
            zhongjian =((30-j) / 30)*  rate * vv
            liangjia += pricen * v
            liang += v
            dn += zhongjian

        if datadf["成交额"][i] < rmin[i - 1] and datadf["收盘"][i] <= liangjia / liang and dn > 0 and i > m and not datadf.loc[i]["收盘"] > datadf.loc[i - 1][
            "收盘"] * 1.03 and not datadf.loc[i]["收盘"] < datadf.loc[i - 1]["收盘"] * 0.98:
            c = True
            n = i
            db = datadf.loc[i]["日期"]
            pb = datadf.loc[i]["收盘"]
            qb = datadf.loc[i]["成交额"]
            print(db,dn)
            for j in range(n, len(datadf)):
                if datadf["成交额"][j] > rmax[j - 1] and c:
                    m = j
                    ds = datadf.loc[j]["日期"]
                    ps = datadf.loc[j]["收盘"]
                    qs = datadf.loc[j]["成交额"]

                    s = ps / pb
                    result.append(s)
                    ss = f"buy: {db}\t{pb}\t{qb}\nsell:{ds}\t{ps}\t{qs}\n"
                    with open(gpdm[:9] + "jiaoyi" + gpdm[9:], "a") as f:
                        f.write(ss)

                    c = False

    zheng =0
    fu = 0
    for i in result:
        if i>1:
            zheng +=1
        if i<1:
            fu += 1
    os.chdir(r"C:\Users\qeaw\Desktop\rrr\result4")
    with open(gpdm[:9] + "zongjie" + gpdm[9:], "a") as f:
        pingjun = pd.Series(result).mean()
        zong = pd.Series(result).product()
        print(f"平均收益：{pingjun}")
        print(f"总收益：{zong}")
        f.write(f"平均收益：{pingjun}\n")

        f.write(f"总收益：{zong}\n")

        f.write(f"正收益次数：{zheng}，负收益次数：{fu}\n")

for i in ll:
    xianshi(i)


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

#内置模块导入
import uuid
import os
import xlrd
import datetime
#django模块导入
from django.shortcuts import render
from django.http import Http404
from django.conf import settings
from django.core.urlresolvers import reverse
#项目模块淡入
from .classes.testcrm import OtVillage, OtCustomer, OtCity, OtOrder
from .models import Excel, Generator, GenerateRoom, Updater, FlownodeFolder
from .forms import UploadExcelForm, IsMatchForm, GenerateorForm, UpdaterForm, DelGenerateorForm
from .configs import EACH_PAGE_NUMBER, SHOW_PAGE_NUMBWER, FLOWNODE_FOLDER_PATH

from .functions.page_separater import Page_Separater
from .functions.converters import generator_to_list
from .functions.migrators import from_generateRoom_to_OtCustomer
from .functions.timers import on_time_do
from .functions.validators import is_same_room, is_str_like_room
from .functions.comparers import precision_match

#显示上传的Excel文件
def excel_index(request,excel_page):
    '''获取用户提交的excel文件,并记入数据库当中,上传成功后自动返回该页面,同时显示出最新的excel表记录.每个excel表记录对应一个显示excel内容的连接'''
    try:
        #页码参数转换
        excel_page=int(excel_page)
        if excel_page > 0:
            errors_dict={}
            #提交表单时更新excel表
            if request.method == 'POST':
                form = UploadExcelForm(request.POST,request.FILES)
                if form.is_valid():
                    #通过表单获取文件
                    clean_data=form.cleaned_data
                    excel_file=clean_data.get('excelFile',None)
                    #判断传入文件的格式
                    ext_name=os.path.splitext(excel_file.name)[1]
                    if ext_name in ['.xls','.xlsx']:
                        #写入数据库记录
                        excel=Excel()
                        #保存原始文件名
                        excel.originName=excel_file.name
                        #替换唯一文件名
                        excel_file.name=str(uuid.uuid1())+ext_name
                        excel.savePath=excel_file

                        excel.enableStatus=None
                        excel.delStatus=0
                        excel.save()

                        #更新MD5值与sha1值
                        excel.save_md5_sha1()
                        excel.save(update_fields=['md5','sha1'])

                        return render(request,'DataManagement/base/base_saved.html',{
                                'goback_path':request.path,
                                'saved_file':excel.originName})

                errors_dict['NotExcelError']='文件格式为xls或xlsx.'
            else:
                form=UploadExcelForm()

            #筛选出Excel对象
            uper=excel_page*EACH_PAGE_NUMBER
            lower=(excel_page-1)*EACH_PAGE_NUMBER
            each_page_excel=Excel.objects.exclude(delStatus__exact=True).order_by('-id')[lower:uper]
            #生成页码
            items_length=Excel.objects.filter(delStatus__exact=False).count()
            max_page_number=(items_length//EACH_PAGE_NUMBER)+1
            page_list=Page_Separater(
                items_len=items_length,
                now_page_num=excel_page,
                each_page_num=EACH_PAGE_NUMBER,
                show_page_num=SHOW_PAGE_NUMBWER
                )
            #定义context_dict
            context_dict={
                'excel_page':excel_page,
                'page_list':page_list,
                'max_page_number':max_page_number,
                'each_page_excel':each_page_excel,
                'form':form,
                'errors_dict':errors_dict
            }
            return render(request,'DataManagement/Excel/excel_index.html',context_dict)
    except:
        return Http404()

#显示Excel文件细节
def excel_detail(request,excel_page,excel_id,detail_page):
    '''分页显示每个excel表的内容,并可根据每页的内容决定是否与数据库当中的房间数据匹配.'''
    try:
        #确认页码参数
        excel_page=int(excel_page)
        detail_page=int(detail_page)
        if excel_page > 0 and detail_page > 0:
            #读取excel
            uper=detail_page*EACH_PAGE_NUMBER
            lower=(detail_page-1)*EACH_PAGE_NUMBER
            excel=xlrd.open_workbook(os.path.join(settings.MEDIA_ROOT,str(Excel.objects.get(id=excel_id).savePath)))
            sheet=excel.sheet_by_index(0)
            #切片读取部分excel
            items_length=sheet.nrows
            if items_length < uper:
                uper=items_length
            each_page_row=[[sheet.row_values(row_num),'N/A'] for row_num in range(lower,uper)]
            #生成页码
            max_page_number=(items_length//EACH_PAGE_NUMBER)+1
            page_list=Page_Separater(
                items_len=items_length,
                now_page_num=detail_page,
                each_page_num=EACH_PAGE_NUMBER,
                show_page_num=SHOW_PAGE_NUMBWER
                )

            #定义context_dict
            context_dict={
                'excel_page':excel_page,
                'excel_id':excel_id,
                'detail_page':detail_page,
                'page_list':page_list,
                'each_page_row':each_page_row,
                'max_page_number':max_page_number,
                'form':IsMatchForm()
            }
            #提交确认配对后执行配对操作
            if request.method == 'POST':
                form=IsMatchForm(request.POST)
                if form.is_valid():
                    #通过表单确认开始匹配任务
                    clean_data=form.cleaned_data
                    is_match=clean_data.get('isMatch',False)
                    if is_match:
                        context_dict['each_page_row']=each_page_row
            return render(request,'DataManagement/Excel/excel_detail.html',context_dict)
    except:
        return Http404()

#生成器列表
def generator_index(request,generator_page):

    #确认页码参数
    generator_page=int(generator_page)
    if generator_page > 0:
        #提交表单时更新Generator表
        if request.method == 'POST':
            form = GenerateorForm(request.POST)
            if form.is_valid():
                #通过表单获取生成器参数,并更新Generator表
                clean_data=form.cleaned_data
                generator=Generator()
                generator.cityId=clean_data['cityId'].cid
                generator.village=clean_data['village']
                generator.period=clean_data.get('period')
                generator.building=clean_data.get('building')
                generator.stand=clean_data.get('stand')
                generator.cell=clean_data.get('cell')
                generator.room=clean_data['room']
                generator.startTime=None
                generator.generateStatus=None
                generator.delStatus=False

                generator.save()

                #写入数据库记录
                for each_period in generator_to_list(generator.period):
                    if not OtVillage.objects.filter(pid__exact=clean_data['cityId'].cid,village__exact=(clean_data['village']+each_period)):
                        new_village=OtVillage()
                        new_village.pid=clean_data['cityId'].cid
                        new_village.village=clean_data['village']+each_period
                        new_village.tjorder=9999
                        new_village.hot=9999
                        new_village.save()

                return render(request,'DataManagement/base/base_saved.html',{
                        'goback_path':request.path,
                        'saved_file':"生成器:{0}".format(generator.id)})
        else:
            form=GenerateorForm()

        #筛选出Generator对象
        uper=generator_page*EACH_PAGE_NUMBER
        lower=(generator_page-1)*EACH_PAGE_NUMBER
        each_page_generator=Generator.objects.filter(delStatus__exact=False).order_by('-id')[lower:uper]
        for each_generator in each_page_generator:
            each_generator.city_name=OtCity.objects.get(cid=each_generator.cityId).cname
        #生成页码
        items_length=Generator.objects.filter(delStatus__exact=False).count()
        max_page_number=(items_length//EACH_PAGE_NUMBER)+1
        page_list=Page_Separater(
            items_len=items_length,
            now_page_num=generator_page,
            each_page_num=EACH_PAGE_NUMBER,
            show_page_num=SHOW_PAGE_NUMBWER
            )
        #定义context_dict
        context_dict={
            'generator_page':generator_page,
            'page_list':page_list,
            'max_page_number':max_page_number,
            'each_page_generator':each_page_generator,
            'form':form
        }
        return render(request,'DataManagement/generator/generator_index.html',context_dict)
    return Http404()

#显示生成器所生成的房间信息,并在首次生成房间信息
def generator_detail(request,generator_page,generator_id,detail_page):
    '''分页显示每个生成器的生成内容'''
    #确认页码参数
    generator_page=int(generator_page)
    detail_page=int(detail_page)
    #确定页码参数
    if generator_page > 0 and detail_page > 0:

        #读取生成器
        uper=detail_page*EACH_PAGE_NUMBER
        lower=(detail_page-1)*EACH_PAGE_NUMBER
        generator=Generator.objects.get(id=generator_id)
        #根据生成状态切片生成数据
        if generator.generateStatus == None:
            #生成栋列表
            if generator.period != 'N/A':
                period_list=list(generator_to_list(generator.period))
            else:
                period_list=['N/A']
            #生成栋列表
            if generator.building != 'N/A':
                building_list=list(generator_to_list(generator.building))
            else:
                building_list=['N/A']
            #生成座列表
            if generator.stand != 'N/A':
                stand_list=list(generator_to_list(generator.stand))
            else:
                stand_list=['N/A']
            #生成单元列表
            if generator.cell != 'N/A':
                cell_list=list(generator_to_list(generator.cell))
            else:
                cell_list=['N/A']
            #生成房间列表
            if generator.room != 'N/A':
                room_list=list(generator_to_list(generator.room))
            else:
                room_list=['N/A']

            #获得village的id
            for each_period in period_list:
                village=OtVillage.objects.get(pid__exact=generator.cityId,village__exact=(generator.village+each_period))
                #循环生成房间信息
                for each_building in building_list:
                    for each_stand in stand_list:
                        for each_cell in cell_list:
                            for each_room in room_list:
                                generate_room=GenerateRoom()
                                generate_room.village=village
                                generate_room.number=each_building+each_stand
                                generate_room.cell=each_cell
                                generate_room.room=each_room
                                generate_room.generator=generator
                                generate_room.save()

            #生成房间无错误后修改生成器状态
            generator.generateStatus=True
            generator.startTime=datetime.datetime.now()
            generator.save(update_fields=['generateStatus','startTime'])

        each_page_generate_room=GenerateRoom.objects.filter(delStatus__exact=False,generator__exact=generator).order_by('-id')[lower:uper]
        items_length=GenerateRoom.objects.filter(delStatus__exact=False,generator__exact=generator).count()
        #生成页码
        max_page_number=(items_length//EACH_PAGE_NUMBER)+1
        page_list=Page_Separater(
            items_len=items_length,
            now_page_num=detail_page,
            each_page_num=EACH_PAGE_NUMBER,
            show_page_num=SHOW_PAGE_NUMBWER
            )

        #提交上传器记录
        if request.method == 'POST':
            form=UpdaterForm(request.POST)
            if form.is_valid():
                #通过表单确认上传器参数
                clean_data=form.cleaned_data
                updater=Updater()
                updater.generator=generator
                updater.updateTime=clean_data['updateTime']
                updater.save()
                #触发定时上传函数

                if request.POST.get('_nowUpdater') == "立刻上传" or request.POST.get('_lazyUpdater') == "定时上传":
                    generate_room_list=GenerateRoom.objects.filter(delStatus__exact=False,generator__exact=generator)
                    if request.POST.get('_lazyUpdater') == "定时上传":
                        on_time_do(start_time=updater.updateTime,
                                   plan=from_generateRoom_to_OtCustomer,
                                   plan_args=generate_room_list)
                    else:
                        from_generateRoom_to_OtCustomer(generate_room_list)
                    updater.updateStatus=True
                    updater.delStatus=False
                    updater.save(update_fields=['updateStatus','delStatus'])
                    generate_room_list.update(updater=updater)
                return render(request,'DataManagement/base/base_saved.html',{
                        'goback_path':request.path,
                        'saved_file':"上传器:{0}".format(updater.id)})
        else:
            form=UpdaterForm()

        #定义context_dict
        context_dict={
            'generator_page':generator_page,
            'generator_id':generator_id,
            'detail_page':detail_page,
            'page_list':page_list,
            'each_page_generate_room':each_page_generate_room,
            'max_page_number':max_page_number,
            'form':form
        }
        return render(request,'DataManagement/Generator/generator_detail.html',context_dict)
    return Http404()

def updater_index(request,updater_page):

    #确认页码参数
    updater_page=int(updater_page)
    if updater_page > 0:
        #提交表单时删除对应指定的房间记录
        if request.method == 'POST':
            form = DelGenerateorForm(request.POST)
            if form.is_valid():
                #写入数据库记录
                for each_del_updater_id in request.POST.getlist('delUpdater'):
                    each_del_updater=Updater.objects.get(id=each_del_updater_id)
                    for each_del_room in GenerateRoom.objects.filter(updater__exact=each_del_updater):
                        OtCustomer.objects.filter(id=each_del_room.customerId).delete()
                    GenerateRoom.objects.filter(updater__exact=each_del_updater).update(updateStatus=False,updater=None,customerId=0)

                    each_del_updater.updateStatus=False
                    each_del_updater.delStatus=True
                    each_del_updater.save(update_fields=['updateStatus','delStatus'])

                return render(request,'DataManagement/base/base_deleted.html',{
                        'goback_path':request.path,
                        'saved_file':"上传器:{0}".format(request.POST.getlist('delGenerator'))})
        else:
            form=DelGenerateorForm()

        #筛选出updater对象
        uper=updater_page*EACH_PAGE_NUMBER
        lower=(updater_page-1)*EACH_PAGE_NUMBER
        each_page_updater=Updater.objects.filter(delStatus__exact=False).order_by('-id')[lower:uper]
        for updater in each_page_updater:
            #modelroom为1时表示该房间为样板间
            generate_room_list=GenerateRoom.objects.filter(updater=updater)
            #生成器对应生成的房间数
            updater.generateRoom_count=generate_room_list.count()
            #上传器对应上传的房间数
            updater.room_update_count=0
            for each_generate_room in generate_room_list:
                each_generate_room.vid=each_generate_room.village.id
                if is_same_room(compare_room=each_generate_room,be_compare_room=OtCustomer.objects.get(id=each_generate_room.customerId)):
                    updater.room_update_count+=1
            room_id_list=generate_room_list.values_list('customerId')
            #计算样板间数和订单数
            updater.modelroom_count=OtCustomer.objects.filter(modelroom=1,id__in=room_id_list).count()
            updater.order_count=OtOrder.objects.filter(cid__in=room_id_list).count()
        #生成页码
        items_length=Updater.objects.filter(delStatus__exact=False).count()
        max_page_number=(items_length//EACH_PAGE_NUMBER)+1
        page_list=Page_Separater(
            items_len=items_length,
            now_page_num=updater_page,
            each_page_num=EACH_PAGE_NUMBER,
            show_page_num=SHOW_PAGE_NUMBWER
            )
        #定义context_dict
        context_dict={
            'generator_page':updater_page,
            'page_list':page_list,
            'max_page_number':max_page_number,
            'each_page_updater':each_page_updater,
            'form':form
        }
        return render(request,'DataManagement/updater/updater_index.html',context_dict)
    return Http404()

def updater_detail(request,updater_page,updater_id,detail_page):
    pass

def flownode_folder_index(request,flownode_folder_page,auto_match):

    #确认页码参数
    start_time=datetime.datetime.now()
    flownode_folder_page=int(flownode_folder_page)
    if flownode_folder_page > 0 and (auto_match == 'on' or auto_match == 'no'):

        #初始化
        each_page_folder=[]
        uper=flownode_folder_page*EACH_PAGE_NUMBER
        lower=(flownode_folder_page-1)*EACH_PAGE_NUMBER
        folder_list=[folder for folder in next(os.walk(FLOWNODE_FOLDER_PATH))[1]
                     if (folder.find('-城市id-') != -1)]

        #匹配楼盘名
        for each_folder in folder_list[lower:uper]:
            city_id=each_folder.split('-城市id-')[1]
            #将未记录的节点文件夹录入FlownodeFolder表中
            if not FlownodeFolder.objects.filter(folderPath=each_folder).exists():
                #判断城市id的有效性
                if (OtCity.objects.filter(cid=city_id).exists()
                    and OtCity.objects.get(cid=city_id).cname != '中国'
                    and OtCity.objects.get(cid=OtCity.objects.get(cid=city_id).pid).cname != '中国'):
                    low_city_list=[str(each_city[0]) for each_city in OtCity.objects.filter(pid=city_id).values_list('cid')]
                else:
                    continue
                #创建节点文件夹对象,并 将对应城市及其下级记入数据表
                folder=FlownodeFolder.objects.create(folderPath=each_folder,
                                                     cityIds=','.join(low_city_list+[city_id]))
            else:
                folder=FlownodeFolder.objects.get(folderPath=each_folder)

            #若为匹配模式
            clean_each_folder=each_folder.replace('-城市id-','').replace(city_id,'')
            if folder.customerId == None and folder.delStatus == False and auto_match == 'on':
                folder.village_list=[]
                for each_city_id in folder.cityIds.split(','):
                    city=OtCity.objects.get(cid=city_id)
                    up_city=OtCity.objects.get(cid=city.pid)
                    folder.village_list+=[{'up_city':up_city,
                                          'city':city,
                                          'village':each_village}
                                         for each_village in OtVillage.objects.filter(pid=each_city_id)
                                         if (precision_match(clean_each_folder,each_village.village) > 66)]
                each_page_folder.append(folder)
            if folder.customerId == None and folder.delStatus == True and auto_match == 'on':
                each_page_folder.append(folder)
            if folder.customerId != None and auto_match == 'on':
                folder.customer=OtCustomer.objects.get(id=folder.customerId)
                each_page_folder.append(folder)
            #若不为匹配模式
            if folder.customerId == None and auto_match == 'no':
                each_page_folder.append(folder)

            if folder.customerId != None and auto_match == 'no':
                folder.customer=OtCustomer.objects.get(id=folder.customerId)
                each_page_folder.append(folder)

        #生成页码
        items_length=len(folder_list)
        max_page_number=(items_length//EACH_PAGE_NUMBER)+1
        page_list=Page_Separater(
            items_len=items_length,
            now_page_num=flownode_folder_page,
            each_page_num=EACH_PAGE_NUMBER,
            show_page_num=SHOW_PAGE_NUMBWER
            )
        #定义context_dict
        end_time=datetime.datetime.now()
        context_dict={
            'flownode_folder_page':flownode_folder_page,
            'page_list':page_list,
            'max_page_number':max_page_number,
            'auto_match':auto_match,
            'each_page_folder':each_page_folder,
            'used_time':end_time-start_time
        }
        return render(request,'DataManagement/flownode_folder/flownode_folder_index.html',context_dict)
    return Http404()

def flownode_folder_match(request,flownode_folder_page,auto_match):

    #删除提交的节点文件夹
    if request.method == 'POST' and request.POST.get('_delFolder'):
        #表单以节点文件夹id的形式提交
        del_folder_list=request.POST.getlist('delFolderSelect')
        for each_folder_id in del_folder_list:
            del_folder=FlownodeFolder.objects.get(id=each_folder_id)
            del_folder.delStatus=True
            del_folder.save(update_fields=['delStatus'])

        return render(request,'DataManagement/base/base_deleted.html',{
                        'goback_path':reverse('DataManagement_urls:flownode_folder_index',
                                              kwargs={'flownode_folder_page':flownode_folder_page,
                                                      'auto_match':auto_match}),
                        'saved_file':"节点文件夹:{0}".format(del_folder_list)})

    #确认页码参数及初始化
    flownode_folder_page=int(flownode_folder_page)
    context_dict={'flownode_folder_page':flownode_folder_page,
                  'auto_match':auto_match,}
    if flownode_folder_page > 0 and auto_match == 'on' and request.method == 'POST':
        #若表单提交为显示匹配的房间
        if request.POST.get('_matchVillage'):
            each_page_folder=[]
            select_village_list=request.POST.getlist('villageSelect')
            #表单以"节点文件夹id-城市id-楼盘id"形式提交
            for each_select_village in select_village_list:
                folder_id,city_id,village_id=each_select_village.split('-')
                folder=FlownodeFolder.objects.get(id=folder_id)
                village=OtVillage.objects.get(id=village_id)
                village.customer_list=[each_customer for each_customer
                                       in OtCustomer.objects.filter(vid=village_id)
                                       if is_str_like_room(be_compare_str=folder.folderPath,compare_room=each_customer)]
                city=OtCity.objects.get(cid=city_id)
                up_city=OtCity.objects.get(cid=city.pid)
                folder.village_list=[{'up_city':up_city,
                                     'city':city,
                                     'village':village}]
                each_page_folder.append(folder)
            context_dict['each_page_folder']=each_page_folder
            return render(request,'DataManagement/flownode_folder/flownode_folder_match.html',context_dict)

        #若表单提交为匹配房间id
        if request.POST.get('_matchCustomer'):

            select_customer_list=request.POST.getlist('customerSelect')
            #表单以"节点文件夹id-房间id"形式提交
            for each_select_customer in select_customer_list:
                folder=FlownodeFolder.objects.get(id=each_select_customer.split('-')[0])
                folder.customerId=each_select_customer.split('-')[1]
                folder.save(update_fields=['customerId'])

            return render(request,'DataManagement/base/base_saved.html',{
                        'goback_path':reverse('DataManagement_urls:flownode_folder_index',
                                              kwargs={'flownode_folder_page':flownode_folder_page,
                                                      'auto_match':auto_match}),
                        'saved_file':"房间匹配列表:{0}".format(select_customer_list)})
        return Http404()
    return Http404()


__author__ = 'Philip Liberato'

"""
Assume the parameter is a any valid list containing comparable values of the same type. Return a tuple where the first
value is the maximum value found in the list (based on the > operator) and the second value in the tuple is the minimum
value found in the list (based on the < operator).  If the list is empty, return the special Python value None.

Examples:
    For the list [1, 3, 3], return (3, 1)
    For the list [3, 1, -2], return (3, -2)
    For the list ['Q', 'Z', 'C', 'A'], return ('Z', 'A')

Note: Constraint for this homework: do not use the built-in Python methods max() or min() for this.
"""

def maxmin(list):
    """The maxmin function returns a tuple of the max value followed by the min value in the given list."""
    max_val = ""
    min_val = ""
    if len(list) == 0:
        return None
    for element in list:
        if element is list[0]:
            max_val = element
            min_val = element
        if element > max_val:
            max_val = element
        if element < min_val:
            min_val = element
    return max_val, min_val

"""
Assume that list1 and list2 are valid lists.  Return a list that contains items that are found in both lists.
If there are no such common items, return an empty list.  The list returned will not contain any duplicate items.

Note: Constraint for this homework: do not use the built-in Python support for sets for this.
"""

def common_items(list1, list2):
    """The common_items function returns a list of common elements found in both provided lists."""
    common_elements = []
    for items1 in list1:
        for items2 in list2:
            if items1 == items2 and contains(common_elements, items1) is False:
                common_elements.append(items1)
    return common_elements

def contains(a_list, element):
    """The contains function returns True if an element is contained in a list."""
    for item in a_list:
        if item == element:
            return True
    return False

"""
Assume that list1 and list2 are valid lists. Return a list that contains items that only occur in one of list1 or list2
(i.e. not in both lists). The list returned will not contain any duplicate items.

Note: Constraint for this homework: do not use the built-in Python support for sets for this.
"""

def notcommon_items(list1, list2):
    """The notcommon_items function returns a list containing the elements found in only one of the two given lists."""
    notcommon_elements = []
    for items1 in list1:
        if contains(list2, items1) is False and contains(notcommon_elements, items1) is False:
            notcommon_elements.append(items1)
    for items2 in list2:
        if contains(list1, items2) is False and contains(notcommon_elements, items2) is False:
            notcommon_elements.append(items2)
    return notcommon_elements

"""
Assume the parameter is a valid list that may contain duplicate items.  Return a dictionary that stores counts of how
often each item occurs, i.e. each key in the dictionary will be a unique item from the list, and that key's value will
be how often it occurs in the list.

Example:
    For the list [1, 3, 2, 2, 3, 1, 1, 2], the dictionary returned would contain {1: 3, 2: 3, 3: 2}
"""

def count_list_items(list):
    """The count_list_items function returns a dictionary of the frequency each element appears in a given list."""
    dictionary = {}
    if len(list) == 0:
        return dictionary
    for item in list:
        if contains(dictionary.keys(), item):
            dictionary[item] += 1
        else:
            dictionary[item] = 1
    return dictionary

def test_maxmin():
    """Test function to assert that maxmin() works properly."""
    assert maxmin(['a', 'b', 'c']) == ('c', 'a')
    assert maxmin([2, 8, -4, 9]) == (9, -4)

def test_common_items():
    """Test function to assert that common_items() works properly."""
    assert common_items([1, 2, 3], [1, 2, 3]) == [1, 2, 3]
    assert common_items([1, 2, 3], [4, 5, 6]) == []
    assert common_items([1, 2, 3], []) == []
    assert common_items([], [4, 5, 6]) == []
    assert common_items([], []) == []
    assert common_items([1, 2, 3], [1, 7, 5]) == [1]
    assert common_items(['A', 'Z', 'G'], ['G', 'B', 'D', 'G']) == ['G']
    assert common_items(['a', 'A'], ['A']) == ['A']

def test_notcommon_items():
    """Test function to assert that notcommon_items() works properly."""
    assert notcommon_items([1, 2], [3, 4]) == [1, 2, 3, 4]
    assert notcommon_items([4, 7, 8], [3, 6, 8]) == [4, 7, 3, 6]
    assert notcommon_items([7, 8, 9], [7, 8, 9]) == []
    assert notcommon_items([], [3, 6, 8]) == [3, 6, 8]
    assert notcommon_items([], []) == []

def test_count_list_items():
    """Test function to assert that count_list_items() works properly."""
    assert count_list_items([1, 2, 3, 4, 5]) == {1: 1, 2: 1, 3: 1, 4: 1, 5: 1}
    assert count_list_items([1, 4, 7, 2, 9, 1, 7, 7, 4]) == {1: 2, 2: 1, 4: 2, 7: 3, 9: 1}
    assert count_list_items([]) == {}

def main():
    """main function"""
    test_maxmin()
    test_common_items()
    test_count_list_items()
    test_notcommon_items()

if __name__ == '__main__':
    main()


import sqlite3

def find_user_id(username):
    try:
        sqliteConnection = sqlite3.connect('db.sqlite3')
        cursor = sqliteConnection.cursor()
        sql_select_query = """SELECT * FROM auth_user WHERE username = ?"""
        cursor.execute(sql_select_query, (username,))
        record = cursor.fetchone()
        cursor.close()

    except sqlite3.Error as error:
        print(error)
    finally:
        if (sqliteConnection):
            sqliteConnection.close()
        return str(record[0])