import os
from pprint import pprint

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

from app_ml.functionalities.constants import SPARK_WINDOW, MONGO_URL, WINDOW, SAVED_MODEL_PATH, POSTGRES_URL
from app_ml.functionalities.preprocessing import create_test_set
from app_ml.models.RNN import RNN
from sqlalchemy import create_engine, insert, MetaData, Table
from collections import Counter
import pymongo
import tensorflow as tf
import numpy as np
import datetime

DATES = [datetime.datetime(2021, 2, 17, 9, 13, 27), datetime.datetime(2021, 2, 18, 21, 33, 2)]

FILES = [
    'opel_corsa_01',
    'opel_corsa_02'
    # 'peugeot_207_01'
    # 'peugeot_207_02'
]

def read_driver_route_id_from_mongo():
    cars_db = pymongo.MongoClient(MONGO_URL)['cars']
    routes_collection = cars_db['routes']
    cursor = routes_collection.aggregate(
        [
            {'$group': {'_id': {'DriverId': '$DriverId', 'RouteId': '$RouteId'}}}
        ]
    )
    driver_route_ids = [(d['_id']['DriverId'], d['_id']['RouteId']) for d in cursor]
    return driver_route_ids

def predict_for_file(model, file):
    x_test, y_test = create_test_set(WINDOW, file)
    x_test, _ = model.preprocess_test(x_test, y_test)
    predictions = model.model.predict(x_test)
    results = np.argmax(predictions, axis=1)
    return results

def make_scores(results):
    results_count = Counter(results)
    aggressive_count = 0 if results_count.get(0) is None else results_count.get(0)
    normal_count = 0 if results_count.get(1) is None else results_count.get(1)
    total_count = aggressive_count + normal_count
    return aggressive_count / total_count, normal_count / total_count

def make_postgres_data_list(route_id, results):
    data = []
    start = 10
    for i in range(0, len(results)):
        end = start + SPARK_WINDOW - 1
        aggressive_score, normal_score = make_scores(results[i])
        d = {
                'route_id': route_id, 'start_time': start, 'end_time': end,
                'aggressive_score': aggressive_score, 'normal_score': normal_score
            }
        data.append(d)
        start = end + 1
    return data

def insert_to_postgres_db(route_id, driver_id, date, model, engine, file):
    results = predict_for_file(model, file)
    spark_windowed_results = [results[i:SPARK_WINDOW+i] for i in range(0, len(results) - SPARK_WINDOW, SPARK_WINDOW)]
    data = make_postgres_data_list(route_id, spark_windowed_results)
    meta = MetaData(engine)
    routes = Table('routes', meta, autoload=True)
    scores = Table('scores', meta, autoload=True)
    routes_stmt = insert(routes).values({'route_id': route_id, 'user_id': driver_id, 'date': date, 'is_active': 0})
    scores_stmt = insert(scores).values(data)
    conn = engine.connect()
    conn.execute(routes_stmt)
    conn.execute(scores_stmt)
    conn.execute('COMMIT')
    conn.close()

def main():
    driver_route_ids = read_driver_route_id_from_mongo()
    model = RNN((20, 15), 2)
    model.model = tf.keras.models.load_model(SAVED_MODEL_PATH, compile=False)
    engine = create_engine(POSTGRES_URL)
    for i in range(0, len(FILES)):
        insert_to_postgres_db(driver_route_ids[i][1], driver_route_ids[i][0], DATES[i], model, engine, FILES[i])
    engine.dispose()
    print('Data inserted successfully to PostgresDB')

if __name__ == '__main__':
    main()


def find_max_min(arg):#created function find_max_min with arg as its parameter.
  ans = []
  max_num = max(arg)
  min_num = min(arg)
  if min_num == max_num:
    length = len(arg)
    ans.append(length)
  else:
    ans.append(min_num)
    ans.append(max_num)
  return ans
#the labels used rhime with the expected inputs and out puts
#forexampla max_num to mean maximum number, Min_number for minimum number, arg for argument e.t.c


# coding: utf8
# auto: flytrap
import unittest
from custom import CustomCarry, Seed, change_custom_seed, _default_custom_seed

class CustomTest(unittest.TestCase):
    def test_custom_class(self):
        print('custom_class:1')
        custom = CustomCarry()
        c = custom.next()
        self.assertEqual(c, '1')
        c1 = CustomCarry('99')
        c2 = CustomCarry('01')
        self.assertEqual(c1 + c2, '100')
        c1 = CustomCarry('88')
        c2 = CustomCarry('11')
        self.assertEqual(c1 + c2, '99')
        c1 = CustomCarry('b')
        c1.SEED_LIST = ['ab']
        c2 = CustomCarry('b')
        c2.SEED_LIST = ['ab']
        self.assertEqual(c1 + c2, 'ba')

    def test_seed(self):
        print('seed:2')
        seed = Seed('abc')
        CustomCarry.SEED_LIST = seed
        c = CustomCarry()
        self.assertEqual(c.SEED_LIST, 'abc')
        _default_custom_seed()

    def test_change_custom_seed(self):
        print('change_custom_seed:3')
        change_custom_seed(['abc', 'd'])
        self.assertEqual(CustomCarry.SEED_LIST, 'abcd')
        _default_custom_seed()

    def test_iter_password(self):
        print('iter_password:4')
        import string
        change_custom_seed(string.printable)
        c = CustomCarry(CustomCarry.SEED_LIST[0] * 6)
        self.assertEqual(c.next(), '000001')
        self.assertEqual(c.next(), '000002')
        for i in xrange(100):
            c.next()
        self.assertEqual(c.next(), '000013')
        for i in xrange(10000):
            c.next()
        self.assertEqual(c.next(), '000114')
        _default_custom_seed()

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


from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import GridSearchCV
import catboost as cb
import xgboost as xgb
import pandas as pd

def gradientBoost(X,y):
    gboost=GradientBoostingRegressor(random_state=11)
    params={'max_depth':[1,2,3],'n_estimators':[100,300,500,1000]}
    search=GridSearchCV(estimator=gboost,param_grid=params,scoring='r2',cv=3,return_train_score=True,verbose=2)
    search.fit(X,y)
    print('Best parameters for Gradient Boosting are:', search.best_params_)
    return search.best_estimator_

def catboost(X,y):
    cboost=cb.CatBoostRegressor(silent=True)
    params={'learning_rate':[0.1,0.5,0.01,0.05],'iterations':[100,300,500,1000],'depth':[1,2]}
    search=GridSearchCV(estimator=cboost,param_grid=params,scoring='r2',cv=3,return_train_score=True,verbose=2)
    search.fit(X,y)
    print('Best parameters for CatBoost are:', search.best_params_)
    return search.best_estimator_

def xgboost(X,y):
    xgboost=xgb.XGBRegressor(objective ='reg:linear',enable_cateorical=True)
    params={'learning_rate':[0.1,0.5,0.01,1],'n_estimators':[10,30,100,500],'colsample_bytree':[0.3,0.5],
                'max_depth':[1,2,3,4,5], 'alpha': [0.1,1,0.01,10]}
    search=GridSearchCV(estimator=xgboost,param_grid=params,scoring='r2',cv=3,return_train_score=True,verbose=1)
    search.fit(X,y)
    print('Best parameters for XgBoost are:', search.best_params_)
    return search.best_estimator_


#14499. 주사위 굴리기
"""
cube의 정보를 세 개의 배열에 담는다.

LR = [top, right, under, left]
UD = [top, left, under, front]
FB = [front, left, back, right]

[1] Idea 확인
[2] rotate시킬때 잘못했음
[3] 문제를 똑바로 안 읽었음.

"""

import sys
input = sys.stdin.readline

N,M,x,y,K = map(int,input().rstrip().split())

boards = [list(map(int,input().rstrip().split())) for _ in range(N)]

commands = list(map(int,input().rstrip().split()))

dx = [0,0,1,-1]
dy = [1,-1,0,0]

direction_dicts = {1:"R", 2:"L", 3:"U", 4:"D"}
operation_pos_dicts = {i:j for (i,j) in zip(list("RLUD"),[(0,1),(0,-1),(-1,0),(1,0)])}

def rotate_cube(board, lr, ud, fb, x,y,direction):
    dx, dy = operation_pos_dicts[direction]
    nx = x+ dx
    ny = y+ dy
    top, right, under, left = lr
    back = ud[1]
    front = ud[-1]
    if nx<0 or ny<0 or nx>=N or ny>=M :
        return False, (lr,ud,fb), (x,y)
    flag = True
    while flag:
        if direction == "R": #right
            lr = [lr[-1]] +lr[:-1]
            ud = [left,back,right,front]
            fb = [front,under,back,top]
        elif direction == "L" : # left
            lr = lr[1:]+[lr[0]]
            ud = [right,back,left,front]
            fb = [front,top,back,under]
        elif direction == "D": # Down
            lr = [back,right,front,left]
            ud = [back,under,front,top]
            fb = [top,left,under,right]
        elif direction == "U": #Up
            lr = [front,right,back,left]
            ud = [front,top,back,under]
            fb = [under,left,top,right]
        flag = False
    if board[nx][ny]!= 0 :
        under = board[nx][ny]
        lr[2] = under
        ud[2] = under
        board[nx][ny] = 0

    elif board[nx][ny] == 0 :
        board[nx][ny] = lr[2]

    return True, (lr,ud,fb), (nx,ny)

lr = [0,0,0,0] ; ud = [0,0,0,0] ; fb = [0,0,0,0]

for command in commands:
    operation = direction_dicts[command]
    flag, (lr, ud, fb), (x,y) = rotate_cube(boards,lr,ud,fb,x,y,operation)
    if not flag :        continue
    print(lr[0])


import os
import sys
import urllib.request
import urllib.parse
import datetime
import time
import json

client_id ='GWWUHPgV0uguJWvgsMFu'
client_secret = 'slKycSCDf4'

# url 접속 요청 후 응답리턴함수

def getRequestUrl(url):
    req = urllib.request.Request(url)
    req.add_header("X-Naver-Client-Id", client_id)
    req.add_header('X-Naver-Client-Secret', client_secret)

    try:
        res = urllib.request.urlopen(req)
        if res.getcode() == 200:
            print(f"[{datetime.datetime.now()} ] Url Request Success")
            return res.read().decode('utf-8')
    except Exception as e:
        print(e)
        print(f"[{datetime.datetime.now()}] Error for URL : {url}")
        return None

def getNaverSearch(node, srcText, start, display):
    base = 'https://openapi.naver.com/v1/search'
    node = f'/{node}.json'
    text = urllib.parse.quote(srcText) # url주제어 맞춰서 파싱
    parmeters=f'?query={text}&start={start}&diplay={display}'

    url = base + node + parmeters
    resDecode  = getRequestUrl(url)

    if resDecode == None:
        return None
    else:
        return json.loads(resDecode)

def getPostData(post, jsonResult, cnt):
    title = post['title']
    description = post['description']
    org_link = post['originallink']
    link = post['link']

    pDate = datetime.datetime.strptime(post['pubDate'], '%a, %d %b %Y %H:%M:%S +0900')
    pDate= pDate.strftime('%Y-%m-%d %H:%M:%S')

    jsonResult.append({'cnt':cnt, 'title':title, 'description':description,
                        'org_link':org_link, 'link':link, 'pDate':pDate})

# 실행최초함수
def main():
    node = 'news'
    srcText = input('검색어를 입력하세요: ')
    cnt = 0
    jsonResult= []
    jsonRes = getNaverSearch(node, srcText, 1, 50)

    total = jsonRes['total']

    while ((jsonRes != None) and (jsonRes['display'] != 0)):
        for post in jsonRes['items']:
            cnt +=1
            getPostData(post, jsonResult,cnt)
        # 만약 50개를 다돌았다고 치면 51개부터 시작해야하기때문에 기존 display값을 더해준다.
        start = jsonRes['start'] + jsonRes['display']
        jsonRes = getNaverSearch(node, srcText,start, 50)

    print(f'전체 검색 : {total} 건')

    # file output
    with open(f'./{srcText}_naver_{node}.json',mode='w',encoding='utf-8') as outfile:
        jsonFile = json.dumps(jsonResult, indent = 4, sort_keys = True, ensure_ascii=False)
        outfile.write(jsonFile)

    print(f'가져온 데이터 : {cnt} 건')
    print(f'{srcText}_naver_{node}.json SAVED')

if __name__ == '__main__':
    main()


import socket
import os

ADDR='./sockfile'

try:
    os.unlink(ADDR)

except OSError:
    if os.path.exists(ADDR):
        raise

skt=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
skt.bind(ADDR)      #进程中传输时，绑定文件名字
skt.listen(5)

while True:
    sk,addr=skt.accept()
    print('addr:',addr)
    while True:
        data=sk.recv(1024)
        print(data.decode())
        sk.send('nihao'.encode())


#mymodule.py
GLOBAL_CHARS = []

GLOBAL_CURSOR = ['UP', 'DOWN', 'LEFT', 'RIGHT', 'UPARROW', 'DOWNARROW', 'LEFTARROW', 'RIGHTARROW', 'PAGEUP', 'PAGEDOWN', 'HOME', 'END', 'INSERT', 'DELETE', 'DEL', 'BACKSPACE', 'TAB', 'SPACE']

GLOBAL_SYSTEM = ['ENTER', 'ESCAPE', 'PAUSE BREAK', 'PRINTSCREEN', 'MENU APP', 'F1', 'F2','F3','F4','F5','F6','F7','F8','F9','F10','F11','F12']

GLOBAL_MODIFIERS = ['SHIFT', 'ALT', 'CTRL', 'GUI', 'CTRL SHIFT', 'ALT SHIFT', 'CTRL ALT', 'CTRL GUI', 'CTRL ALT GUI', 'CTRL SHIFT GUI', 'CTRL ALT SHIFT GUI', 'SHIFT GUI', 'ALT GUI', 'ALT CTRL', 'GUI SHIFT','ALT CTRL GUI', 'ALT CTRL SHIFT', 'ALT GUI SHIFT', 'CTRL GUI SHIFT', 'ALT CTRL GUI SHIFT']
GLOBAL_DELAY = '50' # in ms

## Excluding COMMAND
## Keyboard Fn key? Use 'xev' tool to identify actual key use

def gen_chars():
    ascii_chars = [chr(i) for i in range(128)]
    global GLOBAL_CHARS
    GLOBAL_CHARS = ascii_chars[33:127]

def combine(prefix, suffix):
    list = []
    for i in prefix:
        for j in suffix:
            list.append(i + ' ' + j)
    return list

def ducky(list):
    with open('fuzzyDuckling.txt', 'w') as f:
        for i in list:
            f.write(i)
            f.write('\n')
            f.write('DELAY ' + GLOBAL_DELAY)
            f.write('\n')

## Script start
gen_chars()

print(GLOBAL_CHARS)

final_list = combine(GLOBAL_MODIFIERS, GLOBAL_CHARS + GLOBAL_CURSOR + GLOBAL_SYSTEM)

ducky(final_list)


# -*- coding: utf-8 -*-
# @Time    : 2022 09
# @Author  : yicao
import csv
import os
import time

import numpy as np
import torch
import math

from utils import log_util

class RecordTest:
    def __init__(self, log_file, test_file):
        self.log_file = log_file
        self.test_file = test_file + ' test.csv'
        self.test_acc_sum = 0.0
        self.test_cnt = 0
        with open(self.test_file, 'w') as f:
            csv_write = csv.writer(f)
            csv_write.writerow(['epoch', 'Test Acc'])
        print(f"创建记录文件：{self.test_file}")

    def record_test(self, outputs, labels):
        _, predicted = torch.max(outputs.data, 1)
        correct = (predicted == labels).sum().item()
        acc = 100. * correct / labels.size(0)
        self.test_acc_sum += acc
        self.test_cnt += 1

    def print_test(self, epoch=0):
        test_acc = round((self.test_acc_sum / self.test_cnt), 4)
        self.log("---------------------Test---------------------")
        self.log(f"Test Acc: {test_acc}%")
        self.log("---------------------Test---------------------")
        with open(self.test_file, 'a+') as f:
            csv_write = csv.writer(f)
            csv_write.writerow([epoch, test_acc])
        self.test_acc_sum, self.test_cnt = 0, 0
        return test_acc

    def log(self, line):
        log_util.log(self.log_file, line)

class RecordTrain:
    def __init__(self, log_file, train_file, print_freq):
        self.acc_sum = 0
        self.loss_sum = 0
        self.cnt = 0
        self.log_file = log_file
        self.train_file = train_file + ' train.csv'
        self.print_freq = print_freq
        self.last_time = time.time()

    def record_init(self):
        self.acc_sum = 0
        self.loss_sum = 0
        self.last_time = time.time()

    def record_train(self, loss, outputs, labels, msg="", epoch=0):
        _, predicted = torch.max(outputs.data, 1)
        correct = (predicted == labels).sum().item()
        acc = 100. * correct / labels.size(0)

        self.acc_sum += acc
        self.loss_sum += loss

        if self.cnt % self.print_freq == (self.print_freq - 1):
            self.log(
                f"{msg}epoch: {epoch}, iter: {self.cnt}, acc: {round(self.acc_sum / self.print_freq, 4)}%,"
                f" loss: {round(self.loss_sum / self.print_freq, 4)}, time: {round(time.time() - self.last_time, 3)}s")
            with open(self.train_file, 'a+') as f:
                csv_write = csv.writer(f)
                csv_write.writerow([epoch, self.cnt, round(self.acc_sum / self.print_freq, 4),
                                    round(self.loss_sum / self.print_freq, 4)])
            self.record_init()
        self.cnt += 1

    def log(self, line):
        log_util.log(self.log_file, line)

class RecordAccUtil:
    def __init__(self, batch_size, train_number=1, test_number=1, print_batch=100, log_file="", csv_name=None):
        self.log_file = log_file
        self.csv_name = csv_name
        self.loss_list = []  # 存储每个batch的loss
        self.acc_list = []  # 存储每个batch的acc
        self.epoch = 0
        self.total_iter = 0  # 当前迭代次数
        self.batch_size = batch_size
        self.train_number = train_number  # 训练集大小
        self.test_number = test_number  # 测试集大小
        self.epoch_batch_size = math.ceil(self.train_number / self.batch_size)  # 一个epoch的batch_size数
        self.print_batch = print_batch  # 打印周期
        self.print_train_acc = 0
        self.print_loss = 0
        self.print_test_acc = 0
        self.last_time = time.time()

        self.train_csv_name = csv_name + ' train.csv'
        self.test_csv_name = csv_name + ' test.csv'
        with open(self.train_csv_name, 'w') as f:
            csv_write = csv.writer(f)
            csv_write.writerow(['epoch', 'iter', 'acc', 'loss'])
        with open(self.test_csv_name, 'w') as f:
            csv_write = csv.writer(f)
            csv_write.writerow(['epoch', 'Test Acc'])
        print(f"创建记录文件：{self.train_csv_name}")
        print(f"创建记录文件：{self.test_csv_name}")

    def record_train(self, loss, outputs, labels, msg="", epoch=0):
        _, predicted = torch.max(outputs.data, 1)
        correct = (predicted == labels).sum().item()
        acc = 100. * correct / labels.size(0)
        self.acc_list.append(acc)
        self.loss_list.append(loss)

        self.print_train_acc += acc
        self.print_loss += loss

        if self.total_iter % self.print_batch == (self.print_batch - 1):
            self.log(
                f"{msg}epoch: {self.epoch}, iter: {self.total_iter}, acc: {round(self.print_train_acc / self.print_batch, 4)}%,"
                f" loss: {round(self.print_loss / self.print_batch, 4)}, time: {round(time.time() - self.last_time, 3)}s")
            with open(self.train_csv_name, 'a+') as f:
                csv_write = csv.writer(f)
                csv_write.writerow([epoch, self.total_iter, round(self.print_train_acc / self.print_batch, 4),
                                    round(self.print_loss / self.print_batch, 4)])
            self.print_train_acc, self.print_loss = 0, 0
            self.last_time = time.time()

        self.total_iter += 1
        self.epoch = int(self.total_iter / self.epoch_batch_size)

    def record_train_nll(self, loss, outputs, labels, msg="", epoch=0):
        label_pred = outputs.max(dim=1)[1]
        correct = len(outputs) - torch.sum(torch.abs(label_pred - labels))  # 正确的个数
        acc = (100. * correct / labels.size(0)).item()
        self.acc_list.append(acc)
        self.loss_list.append(loss)

        self.print_train_acc += acc
        self.print_loss += loss

        if self.total_iter % self.print_batch == (self.print_batch - 1):
            self.log(
                f"{msg}epoch: {self.epoch}, iter: {self.total_iter}, acc: {round(self.print_train_acc / self.print_batch, 4)}%,"
                f" loss: {round(self.print_loss / self.print_batch, 4)}, time: {round(time.time() - self.last_time, 3)}s")
            with open(self.train_csv_name, 'a+') as f:
                csv_write = csv.writer(f)
                csv_write.writerow([epoch, self.total_iter, round(self.print_train_acc / self.print_batch, 4),
                                    round(self.print_loss / self.print_batch, 4)])
            self.print_train_acc, self.print_loss = 0, 0
            self.last_time = time.time()

        self.total_iter += 1
        self.epoch = int(self.total_iter / self.epoch_batch_size)

    def record_test(self, outputs, labels):
        _, predicted = torch.max(outputs.data, 1)
        correct = (predicted == labels).sum().item()
        acc = 100. * correct / labels.size(0)
        self.print_test_acc += acc

    def record_test_nnl(self, outputs, labels):
        label_pred = outputs.max(dim=1)[1]
        acc = len(outputs) - torch.sum(torch.abs(label_pred - labels))  # 正确的个数
        self.print_test_acc += acc.detach().cpu().numpy()

    def print_test_accuracy(self, epoch):
        test_acc = round((self.print_test_acc / self.test_number) * 100, 4)
        self.log("---------------------Test---------------------")
        self.log(f"Test Acc: {test_acc}%")
        self.log("---------------------Test---------------------")
        with open(self.test_csv_name, 'a+') as f:
            csv_write = csv.writer(f)
            csv_write.writerow([epoch, test_acc])
        self.print_test_acc = 0
        return test_acc

    def log(self, line):
        log_util.log(self.log_file, line)

class RecordCompressUtil:
    def __init__(self, model_length):
        self.total_compress = 0  # 总压缩率
        self.total_idx = 0
        self.epoch_compress = 0  # 单个epoch的压缩率
        self.epoch_idx = 0
        self.model_length = model_length

    def record_compress(self, bitmaps: np.ndarray):
        self.epoch_compress += np.count_nonzero(bitmaps)
        self.epoch_idx += 1

    def epoch_end(self):
        log_util.log(self.epoch_compress)
        log_util.log(self.epoch_idx)
        compress = self.epoch_compress / self.epoch_idx
        log_util.log(compress)
        log_util.log(f"epoch训练结束， 平均稀疏率为：{round(compress * 100 / self.model_length, 2)}%")
        self.epoch_compress = 0
        self.epoch_idx = 0
        self.total_compress += compress
        self.total_idx += 1

    def train_end(self):
        compress = self.total_compress / self.total_idx
        log_util.log(f"全部训练结束， 平均稀疏率为：{round(compress * 100 / self.model_length, 2)}%")

class RecordCompressLayerUtil:
    def __init__(self, optim: torch.optim.Optimizer, mod_len, print_size, create_csv=False, csv_name=None):
        self.mod_len = mod_len
        self.layer_size = []
        self.m = 0
        self.print_size = print_size
        self.print_t = 0
        self.create_csv = create_csv
        self.csv_name = csv_name

        # 计算模型层数m和各层的参数量q
        for param in optim.param_groups[0]['params']:
            params = param.data.view(-1)
            self.m += 1
            self.layer_size.append(len(params))
        self.rs = np.zeros(self.m)
        self.layer_size = np.array(self.layer_size)

        if self.create_csv & (self.csv_name is not None):
            with open(os.path.join('results', self.csv_name), 'w') as f:
                csv_write = csv.writer(f)
                csv_write.writerow(range(self.m))

    def record_compress(self, bitmap: np.ndarray):
        # 根据bitmap记录本轮各层传递的参数量
        start = 0
        for idx, x in enumerate(self.layer_size):
            self.rs[idx] += np.count_nonzero(bitmap[start:start + x])
            start += x
        self.print_t += 1

        if self.print_size == self.print_t:
            self.print_t = 0
            self.rs = self.rs / self.print_size / self.layer_size
            print_list = list(map(lambda k: round(k, 3) if round(k, 3) != 0 else k, self.rs))
            self.rs = np.zeros(self.m)
            # log_util.log(f"各层稀疏率为: {print_list}")
            if self.create_csv & (self.csv_name is not None):
                with open(os.path.join('results', self.csv_name), 'a+') as f:
                    csv_write = csv.writer(f)
                    csv_write.writerow(print_list)


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

"""
Author: HuHao <huhao1@cmcm.com>
Date: '2018/7/19'
Info:

"""

import os,traceback,re,sys,string
from calendar import month_abbr
from collections import namedtuple

import textwrap

def test_text():
	text = 'yeah, but no, but yeah, but no, but yeah'
	print(text.startswith('yeah'))
	print(text.startswith('no'))
	print(text.find('no')) # 第10个字符出现 no
	print(text.rfind('no')) # 从左往右数 第28个字符为最右匹配项

def split_by_re():
	text1 = '11/27/2012'
	text2 = 'Nov 27, 2012'

	# 判断是否匹配，注 text1 = '11/27/2012a' 依然能够被匹配上 1/27/a2012 不能被匹配
	if re.match(r'\d+/\d+/\d+',text1):
		print('matched')
	else:
		print("not matched")

	# 打包拆分
	data = re.findall(r'(\d+)/(\d+)/(\d+)',text1)
	if data:
		day,month,year = data[0]
		print(day,month,year)
	else:
		print("not matched")

def multi_match():
	text1 = '11/27/2012'
	# 匹配模式将被多次使用时，可先编译保存,等效于 re.compile('(\\d+)/(\\d+)/(\\d+)')
	datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
	datepat = re.compile('(\\d+)/(\\d+)/(\\d+)')

	if datepat.match(text1):
		print("matched")
	else:
		print("not matched")

	data = datepat.findall(text1) # [(11,23,2012)]
	if data:
		day,month,year = data[0]
		print(day,month,year)
	else:
		print("not matched")

	for m in datepat.finditer(text1):  # [(11,23,2012)]
		print(m.groups())

	m = datepat.match('11/27/2013abcd')
	print(m.groups()) # ('11', '27', '2013') groups 会按匹配模式进行解封
	print(m.group()) # 11/27/2013 group 只会显示匹配区段，不会解封

	# 成功匹配多份
	text = '12/12/2018,11/12/2018'
	data = datepat.findall(text) # [('12', '12', '2018'), ('11', '12', '2018')]
	print(data)

	# 以(\d+)/(\d+)/(\d+) 结尾
	pattern = re.compile(r'(\d+)/(\d+)/(\d+)$')
	print(pattern.match('12/12/2012')) # <_sre.SRE_Match object; span=(0, 10), match='12/12/2012'>
	print(pattern.match('12/12/2012a')) # None

def do_replace():
	text = 'yeah, but no, but yeah, but no, but yeah'
	replace_text = text.replace('yeah', 'yep')
	print(replace_text) # yep, but no, but yep, but no, but yep 替换

def use_more():
	'''
	re.sub 对原字符串 按 年-月-日 顺序进行翻转

	:return:
	'''
	text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
	changed_text = re.sub(r'(\d+)/(\d+)/(\d+)',r'\3-\1-\2',text) # \1 \2 \3 按序引用前面成功匹配的 (\d+)
	print(changed_text) # Today is 2012-11-27. PyCon starts 2013-3-13.

	# 匹配模式将被多次使用时，可将匹配模板先定下来，然后复用即可 《《《
	datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
	changed_text = datepat.sub(r'\3-\1-\2',text)
	print(changed_text) # Today is 2012-11-27. PyCon starts 2013-3-13.

	# 复杂逻辑匹配，可以传入转换函数解决 《《《
	data = datepat.sub(change_month,text) # Today is 27 Nov 2012. PyCon starts 13 Mar 2013.
	print(data)

def change_month(m):
	#datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
	#text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
	mon_name = month_abbr[int(m.group(1))] # 数字月转换成为英文缩写
	return '{day} {month} {year}'.format(day=m.group(2),month=mon_name,year=m.group(3))
	# Today is 27 Nov 2012. PyCon starts 13 Mar 2013.

def multi_match():
	datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
	text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'

	organized_text,cnt = datepat.subn(r'\3-\1-\2',text)
	print(organized_text,cnt) # Today is 2012-11-27. PyCon starts 2013-3-13. 2 匹配次数

def ignore_case():
	text = 'UPPER PYTHON, lower python, Mixed Python'
	data = re.findall('python',text,flags=re.IGNORECASE)
	print(data) # ['PYTHON', 'python', 'Python']

	# 忽略大小写，统计将python 替换成为 snake
	data = re.sub('python','snake',text,flags=re.IGNORECASE)
	print(data) # UPPER snake, lower snake, Mixed snake

# 闭包函数
def matchcase(word):
	def replace(m):
		text = m.group()
		if text.isupper():
			return word.upper()
		elif text.islower():
			return word.lower()
		elif text[0].isupper():
			return word.capitalize()
		else:
			return word
	return replace

def shortest_match():
	str_pat = re.compile(r'\"(.*)\"')
	text1 = 'Computer says "no."'
	data = str_pat.findall(text1)
	print(data) # ['no.']

	text2 = 'Computer says "no." Phone says "yes."'
	data = str_pat.findall(text2)
	print(data) # ['no." Phone says "yes.'] 默认最长匹配

	str_pat2 = re.compile(r'\"(.*?)\"') # 添加 ? 最短匹配
	data = str_pat2.findall(text2)
	print(data) # ['no.', 'yes.']

def multi_line_match():
	comment = re.compile(r'/\*(.*?)\*/')
	text1 = '/* this is a comment */'
	text2 = '''/* this is a
	multiline comment */
	'''
	data = comment.findall(text1)
	print(data) # [' this is a comment ']

	data = comment.findall(text2)
	print(data) # []

	comment = re.compile(r'/\*(.*?)\*/',re.DOTALL)
	data = comment.findall(text2)
	print(data) # [' this is a\n\tmultiline comment ']

def test_join():
	parts = ['Is','Chicago','Not','Chicago?']
	print(' '.join(parts)) # 空格连接
	print(','.join(parts)) # , 连接
	print(''.join(parts))  # 直接拼接

	a = 'Is Chicago'
	b = 'Not Chicago?'

	print(a+' '+b) # Is Chicago Not Chicago?

	print('{} {}'.format(a,b))
	print('{} {}'.format(a,b))

def test_generator():
	data = ['ACME',50,91.1]
	print(','.join(str(d) for d in data)) # 通过生成器凭借字段

def test_print():
	a = '1'
	b = 'a'
	c = 's'
	# 只能处理 str
	print(a+':'+b+":"+c) # 1:a:s
	# print(':'.join([a,b,c])) # 1:a:s
	print(a,b,c,sep=':') # 1:a:s

def test_write():
	a = 'a b c'
	b = 'aa bb cc'

	# 只发生一次IO ，数据量小的情况下，比较合适
	with open('write1.txt' ,'w') as f:
		f.write(a+b)
		f.close()

	# 数据量大的情况下，先拼接会占用比较大内存，分开落盘比较合适
	with open('write2.txt' ,'w') as f:
		f.write(a)
		f.write(b)
		f.close()

# yield 所在的函数就是生成器
def sample():
	yield 'Is'
	yield 'Chicago'
	yield 'Not'
	yield 'Chicago?'

def combine(source,maxsize):
	parts = []
	size = 0
	for part in source:
		parts.append(part)
		size += len(part)
		if size > maxsize:
			yield ''.join(parts)
			parts = []
			size = 0
		yield ''.join(parts)

class People:
	def __init__(self,name,n):
		self.name = name
		self.n = n

def test_fill():
	s = '{name} has {n} messages.'
	print(s.format(name='Guid',n =37)) # Guid has 37 messages.
	name = 'Guid'
	n = 37
	print(s.format_map(vars())) # Guid has 37 messages.

	p = People('Guide',38)
	print(s.format_map(vars(p))) # Guide has 38 messages.

class safesub(dict):
	def __missing__(self,key):
		return '{' + key +'}'

def test_fill2():
	'''
	format 与 format_map 在 {var} 字段缺失情况下，会报错
	在对象中定义__missing__ 函数可以防止，字段缺失异常
	:return:
	'''
	s = '{name} has {n} messages.'
	name = 'Guid'
	n = 37
	del n
	print(s.format_map(safesub(vars())))

def sub(text):
	'''
	显示调用函数栈
	sub() 函数使用 sys._getframe(1) 返回调用者的栈帧。可以从中访问属性 f_locals 来获得局部变量。
	:param text:
	:return:
	'''
	return text.format_map(safesub(sys._getframe(1).f_locals))

def sub1():
	name = 'Guido'
	n = 27
	print(sub('Hello {name}')) # Hello Guido
	print(sub('You have {n} messages.')) # You have 27 messages.
	print(sub('Your favorite color is {color}')) # Your favorite color is {color}

	print('{name} has {n} messages.'.format_map(vars())) # Guido has 27 messages.

	s = string.Template('$name has $n messages.') # Guido has 27 messages.
	print(s.substitute(vars()))

def test_textwrap():
	s = '''Look into my eyes, look into my eyes, the eyes, the eyes, the eyes, not around the eyes, don't look around the eyes, look into my eyes, you're under.'''
	print(textwrap.fill(s,50)) # 将长字符串以50个字符间距切割打印输出
	print(textwrap.fill(s,40,initial_indent='  ')) # 首行缩进
	'''
	  Look into my eyes, look into my eyes,
	the eyes, the eyes, the eyes, not around
	the eyes, don't look around the eyes,
	look into my eyes, you're under.

	'''

	print(textwrap.fill(s,40,subsequent_indent='  ')) # 首行出露
	'''
	Look into my eyes, look into my eyes,
        the eyes, the eyes, the eyes, not
        around the eyes, don't look around the
        eyes, look into my eyes, you're under.

	'''

	print(os.get_terminal_size()) # 80 获取终端尺寸

if __name__=="__main__":
	try:
		# test_text()
		# split_by_re()
		# multi_match()
		# do_replace()
		# use_more()
		# multi_match()
		# ignore_case()

		# 保持大小写格式
		# text = 'UPPER PYTHON, lower python, Mixed Python'

		# data = re.sub('python',matchcase('snake'),text,flags=re.IGNORECASE)
		# print(data) # UPPER SNAKE, lower snake, Mixed Snake

		# shortest_match()

		# multi_line_match()

		# test_join()

		# test_generator()

		# test_print()

		# test_write()

		# print(' '.join(sample()))
		#
		# with open('write3.txt','w') as f:
		# 	for x in sample():
		# 		f.write(x)
		# 	f.close()

		# with open('write3.txt','w') as f:
		# 	for part in combine(sample(),32):
		# 		f.write(part)

		# test_fill()

		# test_fill2()

		# sub1()

		test_textwrap()

		pass
	except:
		traceback.print_exc()
	finally:
		os._exit(0)


from django.urls import path
from.import views

app_name ="hospital"

urlpatterns = [
    path('',views.index,name="index"),
    path('about',views.about,name="about"),
    path('contact',views.contact,name="contact"),
    path('appointment',views.appointment,name="appointment"),
    path('doctorprofile',views.doctorprofile,name="doctorprofile"),
    path('single',views.single,name="single"),
    path('gallery',views.gallery,name="gallery"),
    path('staffprofile',views.staffprofile,name="staffprofile"),
    path('user_register', views.user_register, name="user_register"),
    path('user_login', views.user_login, name="user_login"),
    path('user_logout', views.user_logout, name="user_logout"),
    path('user_welcome', views.user_welcome, name="user_welcome"),
    path('profile', views.profile, name="profile"),
    path('doctor1', views.doctor1, name="doctor1"),
    path('doctor2', views.doctor2, name="doctor2"),
    path('doctor3', views.doctor3, name="doctor3"),
    path('doctor4', views.doctor4, name="doctor4"),
    path('doctor5', views.doctor5, name="doctor5"),
    path('doctor6', views.doctor6, name="doctor6"),
    path('doctor7', views.doctor7, name="doctor7"),
    path('doctor8', views.doctor8, name="doctor8"),
    path('doctor9', views.doctor9, name="doctor9"),
    path('doctor10', views.doctor10, name="doctor10"),
    path('doctor11', views.doctor11, name="doctor11"),
    path('doctor12', views.doctor12, name="doctor12"),
    path('doctor13', views.doctor13, name="doctor13"),
    path('doctor14', views.doctor14, name="doctor14"),
    path('patientform', views.patientform, name="patientform"),
    path('auth', views.auth, name="auth"),
    path('authL', views.authL, name="authL"),
    path('authR', views.authR, name="authR"),
    path('thankyou', views.thankyou, name="thankyou"),
]


from Kock.drawing.bar_graph import *
from Kock.Orf.function_orf_methods import *
from Kock.Orf.class_id_methods import *
from Kock.Orf.orf_relation_methods import *
from Kock.readwrite.read_input_files import *

if __name__ == '__main__':
    # Lectura del fichero tb_functions.
    classes, functions = read_input_files_general()
    df_function = df_function_transform(functions)

    # Pregunta 1.1
    pregunta = '1.1'
    title = 'Número de ORFs por clase (Top 10)'
    result = count_orf_by_class(df_function)
    print('{} - {}.'.format(pregunta, title))
    result = result.nlargest(10, 'ORF')
    print(result)
    y = list(result['ORF'])
    labels = list(result.index)
    simple_horizontal_bar_graph(y, title, labels=labels)

    # Pregunta 1.2
    description = 'Respiration'
    class_id = class_id_by_description(classes, description)
    num_orf = count_orf_by_class(df_function, class_id)
    print('1.2 - Número de ORFs para la clase {}, con identificador {}: {}'.format(description, class_id, num_orf))

    # Pregunta 2.1
    description = 'protein'
    pregunta = '2.1'
    title = 'Número de clases con descripción "' + description + '" y uno o más ORF'
    result = count_class_by_description(df_function, description)
    print('{} - {}: {}'.format(pregunta, title, result))
    pregunta = ['pregunta: ' + pregunta]
    simple_horizontal_bar_graph([result], title, labels=pregunta)

    # Pregunta 2.2
    rel_dic = read_input_files_detallada()
    description = 'hydro'
    pregunta = '2.2'
    long = 13
    title = 'Promedio de ORFs tipo "' + description + '".'
    result = average_orf_by_word(df_function, rel_dic, description, long)
    print('{} - Promedio de ORFs cuya descripción contiene la palabra "{}" y '
          'es de una longitud de {}: {}.'.format(pregunta, description, long, result))
    pregunta = ['pregunta: ' + pregunta]
    simple_horizontal_bar_graph([result], title, labels=pregunta)

    # Pregunta 3
    title = 'Número de clases por dimensión'
    pregunta = '3'
    print('{} - {}'.format(pregunta, title))
    dim_dic = class_number_by_dimensions(classes)
    x = []
    y = []
    for k, v in dim_dic.items():
        print('{}: {} clases.'.format(k, v))
        y.append(k)
        x.append(v)
    x_title = 'Dimensiones'
    y_title = '# Clases'
    simple_vertical_bar_graph(x, title, x_title, y_title, y)


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

' hipnuc protocol module '

import threading
import struct
import datetime
import time

class HipnucFrame_Exception(Exception):
    def __init__(self,err='HI221GW Frame Error'):
        Exception.__init__(self,err)

class HipnucFrame_NoValid_Exception(HipnucFrame_Exception):
    def __init__(self,err='No valid frame received'):
        Exception.__init__(self,err)

class HipnucFrame_NotCompleted_Exception(HipnucFrame_Exception):
    def __init__(self,err='No full frame received'):
        Exception.__init__(self,err)

class HipnucFrame_ErrorFrame_Exception(HipnucFrame_Exception):
    def __init__(self,err='Error frame'):
        Exception.__init__(self,err)

def _parse_data_packet_0x90(data_section:list,node_num = None):
    module_id = {
        "id": data_section[0],
    }
    return module_id

def _parse_data_packet_0xD1(data_section:list,node_num = None):
    quaternion_list = []

    # for pos in range(node_num):
    pos = 0
    t_pos = pos * 16
    W = float(struct.unpack("<f", bytes(data_section[t_pos:t_pos + 4]))[0])
    t_pos += 4
    X = float(struct.unpack("<f", bytes(data_section[t_pos:t_pos + 4]))[0])
    t_pos += 4
    Y = float(struct.unpack("<f", bytes(data_section[t_pos:t_pos + 4]))[0])
    t_pos += 4
    Z = float(struct.unpack("<f", bytes(data_section[t_pos:t_pos + 4]))[0])

    temp_dic = {
        "W":round(W,3),
        "X":round(X,3),
        "Y":round(Y,3),
        "Z":round(Z,3)
    }
    quaternion_list.append(temp_dic)

    quaternion = {
        "quat":quaternion_list
    }

    return quaternion

def _parse_data_packet_0xA0(data_section:list,node_num = None):
    acc_list = []

    # for pos in range(node_num):
    pos = 0
    t_pos = pos * 6
    X = int(struct.unpack("<h", bytes(data_section[t_pos:t_pos + 2]))[0])
    t_pos += 2
    Y = int(struct.unpack("<h", bytes(data_section[t_pos:t_pos + 2]))[0])
    t_pos += 2
    Z = int(struct.unpack("<h", bytes(data_section[t_pos:t_pos + 2]))[0])

    temp_dic = {
        "X":round(X,3),
        "Y":round(Y,3),
        "Z":round(Z,3)
    }
    acc_list.append(temp_dic)

    acc = {
        "acc":acc_list
    }

    return acc

def _parse_data_packet_0xB0(data_section:list,node_num = None):
    gyr_list = []

    # for pos in range(node_num):
    pos = 0
    t_pos = pos * 6
    X = int(struct.unpack("<h", bytes(data_section[t_pos:t_pos + 2]))[0])
    t_pos += 2
    Y = int(struct.unpack("<h", bytes(data_section[t_pos:t_pos + 2]))[0])
    t_pos += 2
    Z = int(struct.unpack("<h", bytes(data_section[t_pos:t_pos + 2]))[0])

    temp_dic = {
        "X":round(X,3),
        "Y":round(Y,3),
        "Z":round(Z,3)
    }
    gyr_list.append(temp_dic)

    gyr = {
        "gyr":gyr_list
    }

    return gyr

def _parse_data_packet_0xC0(data_section:list,node_num = None):
    mag_list = []

    # for pos in range(node_num):
    pos = 0
    t_pos = pos * 6
    X = int(struct.unpack("<h", bytes(data_section[t_pos:t_pos + 2]))[0])
    t_pos += 2
    Y = int(struct.unpack("<h", bytes(data_section[t_pos:t_pos + 2]))[0])
    t_pos += 2
    Z = int(struct.unpack("<h", bytes(data_section[t_pos:t_pos + 2]))[0])

    temp_dic = {
        "X":round(X,3),
        "Y":round(Y,3),
        "Z":round(Z,3)
    }
    mag_list.append(temp_dic)

    mag = {
        "mag":mag_list
    }

    return mag

def _parse_data_packet_0xD0(data_section:list,node_num = None):
    eul_list = []

    # for pos in range(node_num):
    pos = 0
    t_pos = pos * 6
    Pitch = struct.unpack("<h", bytes(data_section[t_pos:t_pos + 2]))[0]
    Pitch = Pitch/100
    t_pos += 2
    Roll = struct.unpack("<h", bytes(data_section[t_pos:t_pos + 2]))[0]
    Roll = Roll/100
    t_pos += 2
    Yaw = struct.unpack("<h", bytes(data_section[t_pos:t_pos + 2]))[0]
    Yaw = Yaw/10

    temp_dic = {
        "Pitch":round(Pitch,2),
        "Roll":round(Roll,2),
        "Yaw":round(Yaw,2)
    }
    eul_list.append(temp_dic)

    euler = {
        "euler":eul_list
    }

    return euler

def _parse_data_packet_0x91(data_section:list,node_num = None):
    pos = 0
    id_temp_list = []
    timestamp_temp_list = []
    acc_temp_list = []
    gyr_temp_list = []
    mag_temp_list = []
    eul_temp_list = []
    quat_temp_list = []

    # id
    id = data_section[pos]
    id_dic = {
        "":id
    }

    id_temp_list.append(id_dic)
    pos += 1
    #reserved
    pos += 6
    #timestamp
    timestamp = int(struct.unpack("<I", bytes(data_section[pos:pos + 4]))[0])
    timestamp_dic = {
        "(s)":round(timestamp/1000,3)
    }

    timestamp_temp_list.append(timestamp_dic)
    pos += 4
    #acc
    acc_X = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    acc_Y = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    acc_Z = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    acc_dic = {
        "X":round(acc_X,3),
        "Y":round(acc_Y,3),
        "Z":round(acc_Z,3)
    }
    acc_temp_list.append(acc_dic)
    #gyr
    gyr_X = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    gyr_Y = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    gyr_Z = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    gyr_dic = {
        "X": round(gyr_X,3),
        "Y": round(gyr_Y,3),
        "Z": round(gyr_Z,3)
    }
    gyr_temp_list.append(gyr_dic)
    #mag
    mag_X = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    mag_Y = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    mag_Z = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    mag_dic = {
        "X": round(mag_X),
        "Y": round(mag_Y),
        "Z": round(mag_Z)
    }
    mag_temp_list.append(mag_dic)
    #eul
    eul_Roll = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    eul_Pitch = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    eul_Yaw = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    eul_dic = {
        "Roll": round(eul_Roll, 2),
        "Pitch": round(eul_Pitch, 2),
        "Yaw": round(eul_Yaw, 2)
    }
    eul_temp_list.append(eul_dic)

    #quat
    quat_W = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    quat_X = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    quat_Y = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    quat_Z = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
    pos += 4
    quat_dic = {
        "W": round(quat_W,3),
        "X": round(quat_X,3),
        "Y": round(quat_Y,3),
        "Z": round(quat_Z,3),
    }
    quat_temp_list.append(quat_dic)

    temp_dic_list = {
        "id":id_temp_list,
        "timestamp":timestamp_temp_list,
        "acc":acc_temp_list,
        "gyr":gyr_temp_list,
        "mag":mag_temp_list,
        "euler":eul_temp_list,
        "quat":quat_temp_list
    }
    return temp_dic_list

def _parse_data_packet_0x93(data_section:list,node_num = None):
    pos = 0
    id_temp_list = []
    timestamp_temp_list = []
    acc_temp_list = []
    gyr_temp_list = []

    # id
    id = data_section[pos]
    id_temp_list.append(id)
    pos += 1
    #reserved
    pos += 6
    #timestamp
    timestamp = int(struct.unpack("<I", bytes(data_section[pos:pos + 4]))[0])
    timestamp_temp_list.append(timestamp)
    pos += 4
    #acc
    acc_X = int(struct.unpack("<h", bytes(data_section[pos:pos + 2]))[0])
    pos += 2
    acc_Y = int(struct.unpack("<h", bytes(data_section[pos:pos + 2]))[0])
    pos += 2
    acc_Z = int(struct.unpack("<h", bytes(data_section[pos:pos + 2]))[0])
    pos += 2
    acc_dic = {
        "X":acc_X,
        "Y":acc_Y,
        "Z":acc_Z
    }
    acc_temp_list.append(acc_dic)
    #gyr
    gyr_X = int(struct.unpack("<h", bytes(data_section[pos:pos + 2]))[0])
    pos += 2
    gyr_Y = int(struct.unpack("<h", bytes(data_section[pos:pos + 2]))[0])
    pos += 2
    gyr_Z = int(struct.unpack("<h", bytes(data_section[pos:pos + 2]))[0])
    pos += 2
    gyr_dic = {
        "X": gyr_X,
        "Y": gyr_Y,
        "Z": gyr_Z
    }
    gyr_temp_list.append(gyr_dic)

    temp_dic = {
        "id":id_temp_list,
        "timestamp":timestamp_temp_list,
        "acc":acc_temp_list,
        "gyr":gyr_temp_list,
    }
    return temp_dic

rel_node_num = 0
module_node_num = 0
def _parse_data_packet_0x62(data_section:list,node_num = None):
    global rel_node_num
    global module_node_num
    global data_packet_properties
    id_temp_list = []
    gwid_temp_list = []
    timestamp_temp_list = []
    acc_temp_list = []
    gyr_temp_list = []
    mag_temp_list = []
    eul_temp_list = []
    quat_temp_list = []
    pos = 0

    gwid = data_section[0]
    id_dic = {
            "":gwid
        }
    gwid_temp_list.append(id_dic)

    cnt = data_section[1]
    rel_node_num = cnt
    module_node_num = cnt
    data_packet_properties[0x62]["data_len"] = 5 + (76 * cnt)
    pos += 2
    #reserved
    pos += 5
    #0x91 packet
    for node in range(cnt):
        #packet id
        pos += 1

        # id
        id = data_section[pos]
        id_dic = {
            "":id
        }
        id_temp_list.append(id_dic)
        pos += 1
        #reserved
        pos += 6
        #timestamp
        timestamp = int(struct.unpack("<I", bytes(data_section[pos:pos + 4]))[0])
        timestamp_dic = {
            "(s)":round(timestamp/1000,3)
        }

        timestamp_temp_list.append(timestamp_dic)
        pos += 4

        #acc
        acc_X = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        acc_Y = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        acc_Z = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        acc_dic = {
            "X":round(acc_X,3),
            "Y":round(acc_Y,3),
            "Z":round(acc_Z,3)
        }
        acc_temp_list.append(acc_dic)
        #gyr
        gyr_X = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        gyr_Y = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        gyr_Z = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        gyr_dic = {
            "X": round(gyr_X,3),
            "Y": round(gyr_Y,3),
            "Z": round(gyr_Z,3)
        }
        gyr_temp_list.append(gyr_dic)
        #mag
        mag_X = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        mag_Y = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        mag_Z = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        mag_dic = {
            "X": round(mag_X),
            "Y": round(mag_Y),
            "Z": round(mag_Z)
        }
        mag_temp_list.append(mag_dic)
        #eul
        eul_Roll = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        eul_Pitch = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        eul_Yaw = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        eul_dic = {
            "Roll": round(eul_Roll, 2),
            "Pitch": round(eul_Pitch, 2),
            "Yaw": round(eul_Yaw, 2)
        }
        eul_temp_list.append(eul_dic)

        #quat
        quat_W = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        quat_X = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        quat_Y = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        quat_Z = float(struct.unpack("<f", bytes(data_section[pos:pos + 4]))[0])
        pos += 4
        quat_dic = {
            "W": round(quat_W,3),
            "X": round(quat_X,3),
            "Y": round(quat_Y,3),
            "Z": round(quat_Z,3),
        }
        quat_temp_list.append(quat_dic)

        temp_dic_list = {
            "id":id_temp_list,
            "timestamp":timestamp_temp_list,
            "acc":acc_temp_list,
            "gyr":gyr_temp_list,
            "mag":mag_temp_list,
            "euler":eul_temp_list,
            "quat":quat_temp_list
        }

    temp_dic = {
        "GWD":gwid_temp_list,
        "id":id_temp_list,
        "timestamp":timestamp_temp_list,
        "acc":acc_temp_list,
        "gyr":gyr_temp_list,
        "mag":mag_temp_list,
        "euler":eul_temp_list,
        "quat":quat_temp_list
    }
    return temp_dic

rel_node_num = 0
module_node_num = 0
#only for 400hz acc and gyro
def _parse_data_packet_0x63(data_section:list,node_num = None):
    global rel_node_num
    global module_node_num
    global data_packet_properties
    id_temp_list = []
    timestamp_temp_list = []
    acc_temp_list = []
    gyr_temp_list = []

    pos = 0
    gwid = data_section[0]
    cnt = data_section[1]
    rel_node_num = cnt
    module_node_num = cnt
    data_packet_properties[0x63]["data_len"] = 5 + (24 * cnt)
    pos += 2
    #reserved
    pos += 5
    #0x93 packet
    for node in range(cnt):
        #packet id
        pos += 1

        # id
        id = data_section[pos]
        id_dic = {
            "":id
        }
        id_temp_list.append(id_dic)
        pos += 1
        #reserved
        pos += 6
        #timestamp
        timestamp = int(struct.unpack("<I", bytes(data_section[pos:pos + 4]))[0])
        timestamp_dic = {
            "(s)":round(timestamp/1000,3)
        }

        timestamp_temp_list.append(timestamp_dic)
        pos += 4

        #acc
        acc_X = float(struct.unpack("<h", bytes(data_section[pos:pos + 2]))[0])/1000
        pos += 2
        acc_Y = float(struct.unpack("<h", bytes(data_section[pos:pos + 2]))[0])/1000
        pos += 2
        acc_Z = float(struct.unpack("<h", bytes(data_section[pos:pos + 2]))[0])/1000
        pos += 2

        acc_dic = {
            "X":round(acc_X,3),
            "Y":round(acc_Y,3),
            "Z":round(acc_Z,3)
        }
        acc_temp_list.append(acc_dic)
        #gyr
        gyr_X = float(struct.unpack("<h", bytes(data_section[pos:pos + 2]))[0])/10
        pos += 2
        gyr_Y = float(struct.unpack("<h", bytes(data_section[pos:pos + 2]))[0])/10
        pos += 2
        gyr_Z = float(struct.unpack("<h", bytes(data_section[pos:pos + 2]))[0])/10
        pos += 2
        gyr_dic = {
            "X": round(gyr_X,3),
            "Y": round(gyr_Y,3),
            "Z": round(gyr_Z,3)
        }
        gyr_temp_list.append(gyr_dic)

    temp_dic = {
        "GWD":gwid_temp_list,
        "id":id_temp_list,
        "timestamp":timestamp_temp_list,
        "acc":acc_temp_list,
        "gyr":gyr_temp_list,
    }
    return temp_dic
data_packet_properties = {
    # id
    0x90: {
        "type": "id",
        "id_len": 1,
        "data_len": 1,
        "parse method": _parse_data_packet_0x90,
        "gw_data":False
    },

    # acc
    0xA0: {
        "type": "acc",
        "id_len": 1,
        "data_len": 6,
        "parse method": _parse_data_packet_0xA0,
        "gw_data": False
    },
    # gyr
    0xB0: {
        "type": "gyr",
        "id_len": 1,
        "data_len": 6,
        "parse method": _parse_data_packet_0xB0,
        "gw_data": False
    },
    # mag
    0xC0: {
        "type": "mag",
        "id_len": 1,
        "data_len": 6,
        "parse method": _parse_data_packet_0xC0,
        "gw_data": False
    },
    # float_eul
    0xD0: {
        "type": "euler",
        "id_len": 1,
        "data_len": 6,
        "parse method": _parse_data_packet_0xD0,
        "gw_data": False
    },
    # quat
    0xD1: {
        "type": "quat",
        "id_len": 1,
        "data_len": 16,
        "parse method": _parse_data_packet_0xD1,
        "gw_data":False
    },
    # imusol
    0x91: {
        "type": "imusol",
        "id_len": 1,
        "data_len": 76,
        "parse method": _parse_data_packet_0x91,
        "gw_data": False
    },
    # gwimusol
    0x62: {
        "type": "gwsol",
        "id_len": 1,
        "data_len": 76 * 1,
        "parse method": _parse_data_packet_0x62,
        "gw_data": True
    },

    # imusol only raw
    0x93: {
        "type": "imusol_raw",
        "id_len": 1,
        "data_len": 24,
        "parse method": _parse_data_packet_0x93,
        "gw_data": False
    },

    # gwsol only raw
    0x63: {
        "type": "gwsol_raw",
        "id_len": 1,
        "data_len": 24 * 1,
        "parse method": _parse_data_packet_0x63,
        "gw_data": True
    }
}

def crc16_update(buffer_list, cal_len, cal_pos, crc=0):
    for temp_j in range(cal_len):
        byte = buffer_list[temp_j + cal_pos]
        crc ^= byte << 8
        crc &= 0xffffffff
        for temp_i in range(8):
            temp = crc << 1
            temp &= 0xffffffff
            if (crc & 0x8000):
                temp ^= 0x1021
                temp &= 0xffffffff
            crc = temp

    return (crc & 0xffff)

SampleRate = 0
SamplesReceived = 0
prevSamplesReceived = 0
sample_rate_alive_flag = True

def sample_rate_timer_cb(sample_timer):
    global SampleRate,SamplesReceived,prevSamplesReceived,sample_rate_alive_flag

    SampleRate = SamplesReceived - prevSamplesReceived
    prevSamplesReceived = SamplesReceived
    print("每秒幀率：",SampleRate,datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))

    if sample_rate_alive_flag == True:
        sample_timer = threading.Timer(1.00, sample_rate_timer_cb,args=(sample_timer,))
        sample_timer.start()

def sample_rate_timer_close():
    global sample_rate_alive_flag
    sample_rate_alive_flag = False

# 找到幀頭
def find_frameheader(buffer_list:list):
    # 循環查找，直至拋出異常
    while True:
        # 查找幀頭的第一個標識符0x5a,若未找到，將會拋出ValueError異常
        try:
            header_ind = buffer_list.index(0x5a)
        except ValueError:
            raise HipnucFrame_NotCompleted_Exception

        if header_ind + 1 > len(buffer_list) - 1:
            raise HipnucFrame_NotCompleted_Exception

        if buffer_list[header_ind + 1] == 0xa5:
            # 找到幀頭標識符0x5aa5，返回幀頭位置
            return header_ind
        else:
            # 未找到幀頭標識符，切片繼續查找
            buffer_list = buffer_list[header_ind + 1:]

# 驗證獲取長度
def _get_frame_length(buffer_list, header_pos):
    return int(struct.unpack("<h", bytes(buffer_list[header_pos + 2:header_pos + 4]))[0])

# 驗證長度是否合法
def _verify_frame_length(buffer_list:list, header_pos):
    # 獲取到幀長度
    frame_len = int(struct.unpack("<h", bytes(buffer_list[header_pos + 2:header_pos + 4]))[0])
    # 判斷幀長度是否合法
    if frame_len >= 1024:
        raise HipnucFrame_ErrorFrame_Exception
    elif frame_len + header_pos + 6 > len(buffer_list) :
        raise  HipnucFrame_NotCompleted_Exception

# 驗證crc是否正確
def _verify_frame_crc(buffer_list, header_pos=0):
    # 獲取到幀長度
    frame_len = int(struct.unpack("<h", bytes(buffer_list[header_pos + 2:header_pos + 2 + 2]))[0])
    # 獲取幀內的crc
    f_crc = int(struct.unpack("<H", bytes(buffer_list[header_pos + 4:header_pos + 4 + 2]))[0])
    # 計算幀的crc
    cal_crc = crc16_update(buffer_list, 4, header_pos, 0)
    cal_crc = crc16_update(buffer_list, frame_len, header_pos + 6, cal_crc)

    if cal_crc != f_crc:
        raise HipnucFrame_ErrorFrame_Exception

# 截取一條完整且合法的幀，並將幀頭幀尾返回
def intercept_one_complete_frame(buffer_list):
    # 找幀頭
    header_pos = find_frameheader(buffer_list)
    try:
        frame_len = int(struct.unpack("<H", bytes(buffer_list[header_pos + 2:header_pos + 2 + 2]))[0])
    except struct.error:
        raise HipnucFrame_NotCompleted_Exception
    end_pos = header_pos + 5 + frame_len
    # 驗證幀長度
    _verify_frame_length(buffer_list, header_pos)
    # 驗證crc
    _verify_frame_crc(buffer_list, header_pos)

    return header_pos, end_pos

# 從完整幀中獲取資訊
def extraction_information_from_frame(frame_list:list, inf_fifo,report_datatype: dict = None):
    # 幀率統計
    global SamplesReceived
    global rel_node_num
    global module_node_num
    SamplesReceived = SamplesReceived + 1
    # 處理數據幀
    data_dic = {}
    pos = 0

    data_frame_list = frame_list[6:]

    #遍歷解析數據段內包含的數據
    while len(data_frame_list) > 0:
        if data_frame_list[0] in data_packet_properties:

            temp_dic = data_packet_properties[data_frame_list[0]]["parse method"](data_frame_list[1:],module_node_num)

            try:
                if report_datatype[data_packet_properties[data_frame_list[0]]["type"]] == True:
                    data_dic.update(temp_dic)
                else:
                    pass

            except KeyError:
                pass

            if data_packet_properties[data_frame_list[0]]["gw_data"] == True:
                rel_node_num = module_node_num
            else:
                rel_node_num = 1

            id_len = data_packet_properties[data_frame_list[0]]["id_len"]

            if data_frame_list[0] == 0x62:
                data_len = 76 * rel_node_num + 8
            elif data_frame_list[0] == 0x63:
                data_len = 24 * rel_node_num + 8

            else:
                data_len = data_packet_properties[data_frame_list[0]]["data_len"] * rel_node_num

            data_frame_list = data_frame_list[id_len + data_len:]
        else:
            # raise HipnucFrame_ErrorFrame_Exception
            data_frame_list = data_frame_list[1:]

    inf_fifo.put(data_dic)


import os
import gzip
import numpy as np
import struct
import urllib
from urllib import request

# load compressed MNIST gz files and return numpy arrays
def load_data(filename, label = False):
    with gzip.open(filename) as gz:
        magic_number = struct.unpack('I', gz.read(4))
        n_items = struct.unpack('>I', gz.read(4))
        if not label:
            n_rows = struct.unpack('>I', gz.read(4))[0]
            n_cols = struct.unpack('>I', gz.read(4))[0]
            res = np.frombuffer(gz.read(n_items[0] * n_rows * n_cols), dtype = np.uint8)
            res = res.reshape(n_items[0], n_rows * n_cols)
        else:
            res = np.frombuffer(gz.read(n_items[0]), dtype = np.uint8)
            res = res.reshape(n_items[0], 1)
    return res

# one-hot encode a 1-D array
def one_hot_encode(array, num_of_classes):
    return np.eye(num_of_classes)[array.reshape(-1)]

def prepare_data(dataset, data_folder):
    data_folder = os.path.join(data_folder, dataset)
    print('making data directory ' + data_folder + '...')
    os.makedirs(data_folder, exist_ok = True)

    def download_data(url, filename):
        if not os.path.isfile(filename):
            print('downloading ' + url)
            urllib.request.urlretrieve(url, filename = filename)
        else:
            print(filename + ' exists, using it')

    print('downloading training data ...')
    download_data('http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz', './data/mnist/train-images.gz')
    download_data('http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz', './data/mnist/train-labels.gz')
    print('done.')
    print('downloading testing data ...')
    download_data('http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz', './data/mnist/test-images.gz')
    download_data('http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz', './data/mnist/test-labels.gz')
    print('done.')

    print('Prepared training dataset is stored here:', data_folder)

    X_train = load_data(os.path.join(data_folder, 'train-images.gz'), False) / 255.0
    X_test = load_data(os.path.join(data_folder, 'test-images.gz'), False) / 255.0

    y_train = load_data(os.path.join(data_folder, 'train-labels.gz'), True).reshape(-1)
    y_test = load_data(os.path.join(data_folder, 'test-labels.gz'), True).reshape(-1)

    print(X_train.shape, y_train.shape, X_test.shape, y_test.shape, sep = '\n')

    return X_train, X_test, y_train, y_test


"""Loads pre-pickled data and feature sets"""
import os
import pickle

from sentiment import utils

def get_labeled_sentiment_data():
    """
    Load pre-pickled sentiment data with labels.
    """
    pickle_file = os.path.join(utils.get_project_root(),
                               'data/pickles/sentiment_data_labeled.pickle')
    with open(pickle_file, 'rb') as f:
        return pickle.load(f)

def get_word_features():
    """
    Returns the top word features in training data.
    Use the existing pickled data.

    :param num_feat: number of features to consider, defaulted to 5k.
    :return: a list of top features (words)
    """
    pickle_file = os.path.join(utils.get_project_root(),
                               'data/pickles/word_features_5k.pickle')
    with open(pickle_file, 'rb') as f:
        return pickle.load(f)

def get_feature_sets():
    """
    Load pre-pickled feature sets data.
    Feature sets structure: a list of tuples: e.g.
    [({'good': True, 'silly': False, ...}, 'pos'),
    ({'good': False, 'silly': True, ...}, 'neg'), (...)]

    :return: Feature sets.
    """
    pickle_file = os.path.join(utils.get_project_root(),
                               'data/pickles/feature_sets.pickle')
    with open(pickle_file, 'rb') as f:
        return pickle.load(f)


class Solution:
    # @param A : list of list of integers
    # @return a list of list of integers
    def solve(self, A):
        row = len(A)
        col = len(A[0])
        for i in range(row):
            for j in range(i):
                A[i][j], A[j][i] = A[j][i], A[i][j]
        return A
A = [[1, 0], [1, 0]]
print(Solution().solve(A))


import sys
INF = sys.maxsize

n = int(input())

arr = list(map(int, input().split()))
arr.sort()

start = 0
end = len(arr) - 1

pair = []
min_val = INF
while start < end:
    total = arr[start] + arr[end]
    # 둘 간의 합을 기존과 비교해 작은걸 채택하고, 두 용액의 산성도도 별도 변수에 저장
    if abs(total) < min_val:
        min_val = abs(total)
        pair = (arr[start], arr[end])

    if total >= 0:
        end -= 1
    else:
        start += 1

print(*pair)


import azureml.core
from azureml.core import Workspace, Experiment
from azureml.core.authentication import ServicePrincipalAuthentication
from azureml.core.compute import ComputeTarget, DatabricksCompute
from azureml.exceptions import ComputeTargetException
from azureml.pipeline.steps import PythonScriptStep
from azureml.pipeline.core import Pipeline, PipelineData
from azureml.core.dataset import Dataset
from azureml.pipeline.core.graph import PipelineParameter
from azureml.core.runconfig import RunConfiguration, CondaDependencies
import os

from azureml.core.authentication import AzureCliAuthentication
cli_auth = AzureCliAuthentication()
##from azureml.core.authentication import MsiAuthentication
##msi_auth = MsiAuthentication()

##------------- Get Workspace

subscriptionId = "<your subscription id>"  # make this a parameter
resourceGroup = "<your resource group>" # make this a parameter
workspaceName = "<your ml workspace name>" # make this a parameter

ws = Workspace(subscriptionId, resourceGroup, workspaceName, auth=cli_auth)
print("Workspace => ",ws.name)

##------------- Pipeline Configuration

sourceDirectory = "./code"
remoteComputeTargetName = "default" # make this a parameter
computeTarget = ws.compute_targets[remoteComputeTargetName]

run_config = RunConfiguration(conda_dependencies=CondaDependencies.create(
        conda_packages=['numpy', 'pandas',
                        'scikit-learn', 'tensorflow', 'keras'],
        pip_packages=['azure', 'azureml-core',
                      'azure-storage',
                      'azure-storage-blob',
                      'azureml-dataprep']))
run_config.environment.docker.enabled = True

##------------- Pipeline Parameters

datasetName = PipelineParameter(name="datasetName", default_value="qualitydataset")
datasetStorePath = PipelineParameter(name="datasetStorePath", default_value="/inputdata/train.csv")
modelName = PipelineParameter(name="modelName", default_value="quality_gbm_model.pkl")

##------------- Data preprocessing step
preprocessingStep = PythonScriptStep(name="preprocess_step",
                        script_name="preprocess.py",
                        source_directory=sourceDirectory,
                        compute_target=computeTarget,
                        arguments=[
                            "--datasetName", datasetName,
                            "--datasetStorePath", datasetStorePath,
                        ],
                        runconfig=run_config,
                        allow_reuse=False)
print("Data preprocessing Step created")

##------------- Model Training step
trainingStep = PythonScriptStep(name="training_step",
                        script_name="train.py",
                        source_directory=sourceDirectory,
                        compute_target=computeTarget,
                        arguments=[
                            "--datasetName", datasetName,
                            "--modelName", modelName
                        ],
                        runconfig=run_config,
                        allow_reuse=False)
print("Model Training Step created")

##------------- Scoring and Output step
scoringStep = PythonScriptStep(name="scoring_step",
                        script_name="score.py",
                        source_directory=sourceDirectory,
                        compute_target=computeTarget,
                        arguments=[
                            "--modelName", modelName
                        ],
                        runconfig=run_config,
                        allow_reuse=False)
print("Scoring and output Step created")

##------------- Create Pipeline

trainingStep.run_after(preprocessingStep)
scoringStep.run_after(trainingStep)

qualityMLPipeline = Pipeline(workspace=ws, steps=[scoringStep])
print ("Quality Prediction pipeline is built")

qualityMLPipeline.validate()
print("Quality Prediction pipeline simple validation complete")

##------------- Submit an Experiement using the Pipeline

pipelineRun = Experiment(ws, 'quality_prediction_gb').submit(qualityMLPipeline)
print("Quality Prediction pipeline submitted for execution")

##------------- Publish Pipeline

#publishedPipeline = qualityMLPipeline.publish(name="NewQualityPrediction-Pipeline", description="Quality Prediction pipeline",version="0.1")
publishedPipeline = pipelineRun.publish_pipeline(name="NewQualityPrediction-Pipeline", description="Quality Prediction pipeline",version="0.1")
print("Newly published pipeline id => ",publishedPipeline.id)
print("Newly published pipeline endpoint => ", publishedPipeline.endpoint)


from flask import Flask, render_template, request, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///weight.db'
db = SQLAlchemy(app)

class WeightEntry(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    weight = db.Column(db.Float, nullable=False)

@app.route('/')
def index():
    weight_entries = WeightEntry.query.all()
    return render_template('index.html', weight_entries=weight_entries)

@app.route('/add_weight', methods=['POST'])
def add_weight():
    try:
        weight = float(request.form.get('weight'))
        if weight <= 0:
            flash('Вага повинна бути більше 0', 'danger')
        else:
            new_entry = WeightEntry(weight=weight)
            db.session.add(new_entry)
            db.session.commit()
            flash('Вага успішно додана', 'success')
    except ValueError:
        flash('Некоректні дані введені', 'danger')

    return redirect(url_for('index'))

if __name__ == '__main__':
    db.create_all()
    app.secret_key = 'your_secret_key'
    app.run(debug=True)


#!/usr/bin/python3
# -*- coding:utf-8 -*-
import sys
import os
from configparser import ConfigParser
import time
from ctypes import *
import logging
import time
from PIL import Image,ImageDraw,ImageFont
import traceback
import calendar
import datetime
from datetime import date
from dateutil.parser import parse
from dateutil.rrule import rrule, DAILY

logging.basicConfig(level=logging.DEBUG)
calendar.setfirstweekday(firstweekday=0)
runningDir = os.path.dirname(os.path.realpath(__file__))
festivalsDays={}
holiDays={}
workDays={}

#panel config
panel_width = 800
panel_hight = 600

zone0_x = 0
zone0_y = 10
zone1_x = panel_width/3
zone1_y = 10
zone2_x = panel_width/3*2
zone2_y = 10
zone3_x = 0
zone3_y = panel_hight/2.68 + 10
zone4_x = panel_width/2
zone4_y = panel_hight/2.68 + 10

def DrawScreen(draw):
    today=datetime.date.today()
    Year = today.strftime('%Y')
    Month = today.strftime('%m')
    Day = today.strftime('%d')

    currentMonth = int(Month)
    currentYear = int(Year)
    position0Month = currentMonth - 1
    position0Year = currentYear
    position2Month = currentMonth + 1
    position2Year = currentYear

    if(position0Month <= 0):
        position0Month = position0Month + 12
        position0Year = currentYear - 1
    if position2Month > 12:
        position2Month = position2Month - 12
        position2Year = position2Year + 1

    SetDayStatus(festivalsDays, holiDays, workDays, str(position0Year))
    SetDayStatus(festivalsDays, holiDays, workDays, str(currentYear))
    SetDayStatus(festivalsDays, holiDays, workDays, str(position2Year))

#    draw.line((zone1_x, 0, zone1_x, zone3_y), fill = 0)
#    draw.line((zone2_x, 0, zone2_x, zone3_y), fill = 0)
    draw.line((0, zone3_y, panel_width, zone3_y), fill = 0)
    draw.line((zone4_x, zone4_y, zone4_x, panel_hight), fill = 0)

    DrawMonth(zone0_x, zone0_y, position0Year, position0Month)
    DrawMonth(zone1_x, zone1_y, currentYear, currentMonth)
    DrawMonth(zone2_x, zone2_y, position2Year, position2Month)
    DrawBeginTask(zone3_x, zone3_y)
    DrawDueTask(zone4_x,zone4_y)
def DrawBeginTask(original_x, original_y):
    cfg = ConfigParser()
    cfg.read(runningDir + '/tasks/task.ini')
    row = 0
    fontTitle = ImageFont.truetype(runningDir + '/pic/Font.ttc', 20)
    fontTask = ImageFont.truetype(runningDir + '/pic/Font.ttc', 19)
    fontTime = ImageFont.truetype(runningDir + '/pic/Font.ttc', 17)
    draw.text((original_x + 162, original_y + 10), u'待办事项', font = fontTitle, fill = 0)
    for f in cfg['BeginTasks']:
        if row > 10:
            draw.text((original_x + 12, original_y + 40 + row*28), "......", font = fontTask, fill = 0)
            break
        task = cfg.get(u'BeginTasks',f)
        title = task.split('|')[0]
        beginTime = task.split('|')[1]
        dueTime = task.split('|')[2]
        title = TrimString(title, 15)
        draw.text((original_x + 4, original_y + 48 + row*28), title, font = fontTask, fill = 0)
        if(beginTime != "null"):
            beginTime = beginTime.split(' ')[2][0:5]
            draw.text((original_x + 305, original_y + 48 + row*28), beginTime, font = fontTime, fill = 0)
        if(dueTime != "null"):
            dueTime = dueTime.split(' ')[2][0:5]
            draw.text((original_x + 355, original_y + 48 + row*28), dueTime, font = fontTime, fill = 0)
        row = row + 1
def DrawDueTask(original_x, original_y):
    cfg = ConfigParser()
    cfg.read(runningDir + '/tasks/task.ini')
    row = 0
    fontTitle = ImageFont.truetype(runningDir + '/pic/Font.ttc', 20)
    fontTask = ImageFont.truetype(runningDir + '/pic/Font.ttc', 19)
    fontTime = ImageFont.truetype(runningDir + '/pic/Font.ttc', 18)
    draw.text((original_x + 162, original_y + 10), u'今日截止', font = fontTitle, fill = 0)
    for f in cfg['DueTasks']:
        if row > 10:
            draw.text((original_x + 12, original_y + 40 + row*28), "......", font = fontTask, fill = 0)
            break
        task = cfg.get(u'DueTasks',f)
        title = task.split('|')[0]
        beginTime = task.split('|')[1]
        dueTime = task.split('|')[2]
        title = TrimString(title, 15)
        draw.text((original_x + 4, original_y + 48 + row*28), title, font = fontTask, fill = 0)
        if(beginTime != "null"):
            beginTime = beginTime.split(' ')[2][0:5]
            draw.text((original_x + 305, original_y + 48 + row*28), beginTime, font = fontTime, fill = 0)
        if(dueTime != "null"):
            dueTime = dueTime.split(' ')[2][0:5]
            draw.text((original_x + 355, original_y + 48 + row*28), dueTime, font = fontTime, fill = 0)
        row = row + 1
def TrimString(srcString, width):
        TrimedString = ""
        count = 0
        for i in range(len(srcString)):
            if len(srcString[i]) == len(srcString[i].encode('utf-8')):
                count = count + 0.5
            else:
                count = count + 1
        if count <= (width):
            return srcString
        else:
            count = 0
            for i in range(len(srcString)):
                if len(srcString[i]) == len(srcString[i].encode('utf-8')):
                    count = count + 0.5
                else:
                    count = count + 1
                if count >= width:
                    break
                TrimedString = TrimedString + srcString[i]
        return TrimedString + "..."
def DrawMonth(original_x, original_y,year, month):
    dateMatrix = calendar.monthcalendar(year, month)
    fontTitle = ImageFont.truetype(runningDir + '/pic/Font.ttc', 18)
    draw.text((original_x + 100, original_y), str(year)+u'年'+str(month)+u'月', font = fontTitle, fill = 0)
    weekList = [u'一',u'二',u'三',u'四',u'五',u'六',u'日']

    for i in range(0,7):
        draw.text((original_x + 2 + i*36, original_y + 25), weekList[i], font = fontTitle, fill = 0)
    for row in range(len(dateMatrix)):
        for col in range(len(dateMatrix[row])):
            DrawDate(dateMatrix, row, col,original_x,original_y,year,month)

def DrawDate(dateMatrix, row, col,original_x,original_y,year,month):
    fontDate = ImageFont.truetype(runningDir + '/pic/Font.ttc', 16)
    fontFestival = ImageFont.truetype(runningDir + '/pic/Font.ttc', 15)
    today = datetime.date.today()
    currentDay = 0
    rowSpan = 34
    colSpan = 36
    monthValue = str(month)
    dayValue = str(dateMatrix[row][col])
    if month < 10:
        monthValue = '0' + str(month)
    if dateMatrix[row][col] < 10:
        dayValue = '0' + str(dateMatrix[row][col])
    keyValue = str(year) + monthValue + dayValue
    if today.strftime('%Y%m%d') == keyValue :
        currentDay = 1
        draw.rectangle((original_x + 0 + col*colSpan, original_y + 55 + row*rowSpan, original_x  + col*colSpan + 19, original_y + 72 + row*rowSpan), fill = 0)
    else:
        currentDay = 0
    if  dateMatrix[row][col] == 0:
        return
    if dateMatrix[row][col] < 10:
        draw.text((original_x + 5 + col*colSpan, original_y + 55 + row*rowSpan), str(dateMatrix[row][col]), font = fontDate, fill = currentDay)
    else:
        draw.text((original_x + 1 + col*colSpan, original_y + 55 + row*rowSpan), str(dateMatrix[row][col]), font = fontDate, fill = currentDay)
    #绘制节日名称
    if (keyValue in festivalsDays.keys()):
        draw.text((original_x + 20 + col*colSpan, original_y + 48 + row*rowSpan), festivalsDays[keyValue][0], font = fontFestival, fill = 0)
        draw.text((original_x + 20 + col*colSpan, original_y + 64 + row*rowSpan), festivalsDays[keyValue][1], font = fontFestival, fill = 0)
    #绘制放假标志
    if (keyValue in holiDays.keys()):
        draw.rectangle((original_x + 0 + col*colSpan, original_y + 55 + row*rowSpan, original_x  + col*colSpan + 19, original_y + 72 + row*rowSpan), outline = 0)
    #绘制上班标志
    if (keyValue in workDays.keys()):
        draw.arc((original_x + 1 + col*colSpan, original_y + 55 + row*rowSpan, original_x  + col*colSpan + 19, original_y + 72 + row*rowSpan), 0, 360, fill = 0)

def SetDayStatus(festivalsDays,holidays, workDays, year):
    cfg = ConfigParser()
    cfg.read(runningDir + '/days/'+year+'.ini')
    for f in cfg['节日日期']:
        dates = cfg.get(u'节日日期',f)
        festivalsDays[year+cfg.get(u'节日日期',f)] = f
    for f in cfg['放假日期']:
        dates = cfg.get(u'放假日期',f)
        if '-' in dates:
            start = int(dates.split('-')[0]) + int(year)*10000
            end = int(dates.split('-')[1])  + int(year)*10000
            for i in rrule(DAILY, dtstart=parse(str(start)), until=parse(str(end))):
                holidays[i.date().strftime('%Y%m%d')] = f
        else:
            holidays[year+cfg.get(u'放假日期',f)] = f
    for f in cfg['调休上班日期']:
        dates = cfg.get(u'调休上班日期',f)
        if dates != '':
            dateList = dates.split(',')
            for d in dateList:
                workDays[year + d] = f
def TaskFileUpdated(LastSyncTime):
    Cfg = ConfigParser()
    Cfg.read(runningDir + '/tasks/task.ini')
    if(not Cfg.has_option('Info','Last sync time')):
        return 0
    CfgSyncTime = Cfg.get('Info','Last sync time')
    if(LastSyncTime[0] != CfgSyncTime):
        LastSyncTime[0] = CfgSyncTime
        return 1
    else:
        return 0

try:
    logging.info("The daemon starts...")
    LastSyncTime = ['']
    while 1:
        if(TaskFileUpdated(LastSyncTime)):
            logging.info("Start to update...")
            Himage = Image.new('1', (800, 600), 255)  # 255: clear the frame
            draw = ImageDraw.Draw(Himage)
            DrawScreen(draw)
            Himage.save(runningDir + '/pic/epd.bmp', 'bmp')
            epdLib = cdll.LoadLibrary(runningDir + "/IT8951/epd.so")
            epdLib.epd_6inch_init()
            epdLib.Display_epd_bmp()
            epdLib.edp_6inch_deinit()
            logging.info("Finish...")
        time.sleep(1)
except IOError as e:
    logging.info(e)

except KeyboardInterrupt:
    logging.info("ctrl + c:")
    exit()


import os
from telegram.ext import Updater
from telegram.error import BadRequest, Unauthorized

TOKEN = os.environ.get('TELEGRAM_TOKEN')
updater = Updater(token=TOKEN)
bot = updater.dispatcher.bot

def send_message(chat_id: int, text: str):
    try:
        bot.send_message(chat_id=chat_id, text=text)
        return True
    except BadRequest:
        return False
    except Unauthorized:
        print(f'Unauthorized: {chat_id}')
        return False


import numpy as np
from scipy.special import factorial

ident = 'dick6D'
d = 6
title_plot = r'$f_6(u)=\left(\prod_{i=2}^6 u_i^{i-1} \right) \exp\left\{\prod_{i=1}^6 u_i\right\}$'
mat_folder = 'simuDick/d6'
true_val = np.exp(1.) - np.sum(1. / factorial(np.arange(6)))
orders = [1, 2, 4, 6, 8]
min_neval = 100
max_neval = 2 * 10**7
nks = 20
nreps = 50

def phi(u):
    pu = 1.
    for i in range(1, d):
        pu = pu * u[:, i]**i
    return pu * np.exp(np.prod(u, axis=-1))


# django imports
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.decorators import permission_required
from django.core.urlresolvers import reverse
from django.db import IntegrityError
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.template import RequestContext
from django.template.loader import render_to_string

# lfs imports
from lfs.catalog.models import Product
from lfs.catalog.models import ProductPropertyValue
from lfs.catalog.models import Property
from lfs.catalog.models import PropertyGroup
from lfs.core.signals import product_removed_property_group

@permission_required("manage_shop", login_url="/login/")
def manage_properties(request, product_id, template_name="manage/product/properties.html"):
    """
    """
    product = get_object_or_404(Product, pk=product_id)

    # Generate list of product property groups; used for enter value
    product_property_groups = []
    for property_group in product.property_groups.all():
        properties = []
        for property in property_group.properties.order_by("groupspropertiesrelation"):
            # Try to get the value, if it already exists.
            try:
                ppv = ProductPropertyValue.objects.get(property = property, product=product)
            except ProductPropertyValue.DoesNotExist:
                value = ""
            else:
                value = ppv.value

            # mark selected options "selected"
            options = []
            for option in property.options.all():
                options.append({
                    "id"       : option.id,
                    "name"     : option.name,
                    "selected" : str(option.id) == value
                })

            properties.append({
                "id"      : property.id,
                "name"    : property.name,
                "type"    : property.type,
                "options" : options,
                "value"   : value,
            })

        product_property_groups.append({
            "id"   : property_group.id,
            "name" : property_group.name,
            "properties" : properties,
        })

    # Generate list of all property groups; used for group selection
    product_property_group_ids = [p["id"] for p in product_property_groups]
    shop_property_groups = []
    for property_group in PropertyGroup.objects.all():

        shop_property_groups.append({
            "id" : property_group.id,
            "name" : property_group.name,
            "selected" : property_group.id in product_property_group_ids,
        })

    return render_to_string(template_name, RequestContext(request, {
        "product" : product,
        "product_property_groups" : product_property_groups,
        "shop_property_groups" : shop_property_groups,
    }))

@permission_required("manage_shop", login_url="/login/")
def update_property_groups(request, product_id):
    """Updates property groups for the product with passed id.
    """
    selected_group_ids = request.POST.getlist("selected-property-groups")

    for property_group in PropertyGroup.objects.all():
        # if the group is within selected groups we try to add it to the product
        # otherwise we try do delete it
        if str(property_group.id) in selected_group_ids:
            try:
                property_group.products.get(pk=product_id)
            except ObjectDoesNotExist:
                property_group.products.add(product_id)
        else:
            property_group.products.remove(product_id)
            product = Product.objects.get(pk=product_id)
            product_removed_property_group.send([property_group, product])

    url = reverse("lfs_manage_product", kwargs={"product_id" : product_id})
    return HttpResponseRedirect(url)

@permission_required("manage_shop", login_url="/login/")
def update_properties(request, product_id):
    """Updates properties for product with passed id.
    """
    # Update properties' values
    for key, value in request.POST.items():
        if key.startswith("property") == False:
            continue

        property_id = key.split("-")[1]
        property = get_object_or_404(Property, pk=property_id)
        product = get_object_or_404(Product, pk=product_id)

        try:
            ppv = ProductPropertyValue.objects.get(product = product_id, property = property_id)
        except ProductPropertyValue.DoesNotExist:
            if not property.is_valid_value(value):
                value = 0
            ProductPropertyValue.objects.create(product=product, property = property, value=value)
        else:
            if not property.is_valid_value(value):
                value = 0

            ppv.value = value
            ppv.save()

    url = reverse("lfs_manage_product", kwargs={"product_id" : product_id})
    return HttpResponseRedirect(url)


import itertools
import math
import pickle
from collections import defaultdict,Counter
import collections
import copy
import spacy
from spacy.lang.en.stop_words import STOP_WORDS
Q = 'Los The Angeles Boston Times Globe Washington Post'
DoE = {'Los Angeles Times':0, 'The Boston Globe':1,'The Washington Post':2, 'Star Tribune':3}

tokens = Q.split()
#token list
counter = collections.Counter(tokens)
#token_count
token_dictionary=dict(counter)
subset_of_doe = []
DoE_list = list(DoE.keys())
for L in range(1, len(tokens)+1):
    for subset in itertools.combinations(tokens, L):
        string = ' '.join(list(subset))
        #print(string)
        if string in DoE_list:
            if string not in subset_of_doe:
                subset_of_doe.append(string)

combination_of_subset = []
for L in range(0, len(subset_of_doe)+1):
    for subset in itertools.combinations(subset_of_doe, L):
        combination_of_subset.append(list(subset))

entities = []
for i in combination_of_subset:
    n = []
    if i != []:
        for j in i:
            n += j.split()
        counter = collections.Counter(n)
        dictionary=dict(counter)
        if(all((k in token_dictionary and token_dictionary[k]>=v) for k,v in dictionary.items())):
            entities.append(i)
    else:
        entities.append(i)
splits = {}
count = 0
for e in entities:
    splits[count] = {}
    token_list = copy.deepcopy(tokens)
    n = []
    if e != []:
        for j in e:
            n += j.split()
        for item in n:
            token_list.remove(item)
        splits[count] = {'tokens':token_list}
    else:
            splits[count] = {'tokens':token_list}
    splits[count]['entities'] = e
    count += 1
return splits


import aiosqlite
from datetime import datetime

DB = 'db.sqlite'

async def search_db_entry(user_id, type, kind, location, distance):
    curdate = str(datetime.now().strftime('%Y%m%d'))
    query = f"SELECT * FROM geteilt where expires_at > {curdate}"
    query += f" AND user_id <> {user_id}"
    if type != 'all':
        query += f" AND type = '{type}'"
    if kind != 'all':
        query += f" AND kind = '{kind}'"

    if location is not None:
        dist = int(distance) * 1000
        query += f" AND (PtDistWithin(geteilt.latlng, PointFromText('POINT({location.longitude} {location.latitude})', 4326), {dist})=TRUE)"

    query += ";"
    res = []
    async with aiosqlite.connect(DB) as db:
        await db.enable_load_extension(True)
        await db.load_extension('mod_spatialite')
        async with db.execute(query) as cursor:
            async for row in cursor:
                res.append(row)
    return res

async def delete_db_entry(entry_uid):
    async with aiosqlite.connect(DB) as db:
        await db.execute(f"DELETE FROM geteilt WHERE id = {entry_uid};")
        await db.commit()

async def search_db_own_entry(user_id):
    query = f"SELECT * FROM geteilt WHERE user_id = {user_id};"
    res = []
    async with aiosqlite.connect(DB) as db:
        async with db.execute(query) as cursor:
            async for row in cursor:
                res.append(row)
    return res

async def add_db_entry(user_id, user_lang, type, kind, location, description, expires_at):
    currentDateTime = datetime.now().strftime('%Y%m%d')
    async with aiosqlite.connect(DB) as db:
        await db.enable_load_extension(True)
        await db.execute("SELECT load_extension('mod_spatialite');")
        last_row = None
        async with db.execute("INSERT INTO geteilt(user_id, user_lang, type, kind, lat, lng, desc, inserted_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);",
                (user_id, user_lang, type, kind, location.latitude, location.longitude,
                description, currentDateTime, str(expires_at.strftime('%Y%m%d')))) as cursor:
            last_row = cursor.lastrowid
        await db.execute(f"UPDATE geteilt SET latlng = PointFromText('POINT({location.longitude} {location.latitude})', 4326) WHERE id = {last_row};")
        await db.commit()

async def add_db_subscription(user_id, user_lang, type, kind, location, distance):
    currentDateTime = datetime.now().strftime('%Y%m%d')
    async with aiosqlite.connect(DB) as db:
        await db.enable_load_extension(True)
        await db.execute("SELECT load_extension('mod_spatialite');")
        lat = None
        lng = None
        if location is not None:
            lat = location.latitude
            lng = location.longitude
        last_row = None
        if distance == 'search_everywhere':
            distance = None
        else:
            distance = int(distance) * 1000
        async with db.execute("INSERT INTO subscriptions(user_id, user_lang, type, kind, lat, lng, distance, inserted_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?);",
                (user_id, user_lang, type, kind, lat, lng, distance, currentDateTime)) as cursor:
            last_row = cursor.lastrowid
        if location is not None:
            await db.execute(f"UPDATE subscriptions SET latlng = PointFromText('POINT({location.longitude} {location.latitude})', 4326) WHERE id = {last_row};")
        await db.commit()

async def delete_db_subscription(entry_uid):
    async with aiosqlite.connect(DB) as db:
        await db.execute(f"DELETE FROM subscriptions WHERE id = {entry_uid};")
        await db.commit()

async def search_db_subscriptions(user_id, type, kind, location):
    query = f"""SELECT user_id, user_lang, distance FROM subscriptions WHERE
        user_id <> {user_id}
        AND (type = '{type}' OR type = 'all') AND (kind = '{kind}' or kind = 'all')
        AND (subscriptions.latlng is NULL OR
            (PtDistWithin(subscriptions.latlng, PointFromText('POINT({location.longitude} {location.latitude})', 4326), subscriptions.distance)=TRUE))"""
    res = []
    async with aiosqlite.connect(DB) as db:
        await db.enable_load_extension(True)
        await db.load_extension('mod_spatialite')
        async with db.execute(query) as cursor:
            async for row in cursor:
                res.append(row)
    return res

async def search_db_own_subscriptions(user_id):
    query = f"SELECT * FROM subscriptions WHERE user_id = {user_id};"
    res = []
    async with aiosqlite.connect(DB) as db:
        async with db.execute(query) as cursor:
            async for row in cursor:
                res.append(row)
    return res

async def check_point_col_exists(db):
    point_col_exists = False
    async with db.execute("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'geteilt';") as cursor:
        async for row in cursor:
            point_col_exists = 'POINT' in row[0]
    return point_col_exists

async def init_db():
    async with aiosqlite.connect(DB) as db:
        point_col_exists = await check_point_col_exists(db)
        if not point_col_exists:
            await db.enable_load_extension(True)
            await db.execute("SELECT load_extension('mod_spatialite');")
            await db.execute("SELECT InitSpatialMetaData();")
            await db.execute("""CREATE TABLE IF NOT EXISTS geteilt (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER,
                user_lang VARCHAR(2),
                type VARCHAR(10),
                kind VARCHAR(10),
                lat FLOAT,
                lng FLOAT,
                desc TEXT,
                inserted_at TEXT,
                expires_at TEXT
                );""")
            await db.execute("SELECT AddGeometryColumn('geteilt', 'latlng', 4326, 'POINT', 'XY');")
            await db.execute("SELECT CreateSpatialIndex('geteilt', 'latlng');")

            await db.execute("""CREATE TABLE IF NOT EXISTS subscriptions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER,
                user_lang VARCHAR(2),
                type VARCHAR(10),
                kind VARCHAR(10),
                lat FLOAT,
                lng FLOAT,
                distance INTEGER,
                inserted_at TEXT
                );""")
            await db.execute("SELECT AddGeometryColumn('subscriptions', 'latlng', 4326, 'POINT', 'XY');")
            await db.execute("SELECT CreateSpatialIndex('subscriptions', 'latlng');")
            await db.commit()


import pandas as pd
import urllib.request
import bs4 as bs
import re

class Movie_Titles:
    def __init__(self, movie_df, refresh_on_start, engine):
        self.df = movie_df
        self.refresh_on_start = refresh_on_start
        self.engine = engine

    def get_titles(self):
        """Obtain the titles of the movies in the movies dataframe.
        Outputs a dataframe with movie URLs and Title."""

        if self.refresh_on_start == True:
            con = self.engine.connect()
            con.execute('drop table if exists TITLES_OLD')

            con.execute('alter table if exists TITLES rename to TITLES_OLD')
            con.execute('create table TITLES ( Code varchar not null, Title varchar)')
            df = self.df
            movie_idx=df['Code'].unique()
            df_title = pd.DataFrame()
            pattern = '"name":(.*),"description"'

            for i in movie_idx:

                source = urllib.request.urlopen(i)
                soup = bs.BeautifulSoup(source, "html.parser")
                for gen in soup.find_all('script', {'type': "application/ld+json"}):
                    i_json = str(gen)
                    title = re.search(pattern, i_json).group(1)

                    temp_dict = [
                            {
                                'Code': i,
                                'Title': title,

                            }
                        ]
                    temp = pd.DataFrame.from_records(temp_dict)
                    temp.to_sql('TITLES', self.engine, if_exists='append', index = False)
                    df_title = pd.concat([df_title, temp])
            print("TITLES have been updated")

            return df_title


import os
import random

from hangman_words import word_list
from hangman_art import stages, logo

def main_menu():
    """
    Displays the main menu and returns the user's choice.
    """
    clear()
    print(logo)
    print("Welcome to Hangman Game!")
    print("\nMain Menu:")
    print("1. Start a New Game")
    print("2. Game Description")
    print("3. Exit")
    while True:
        choice = input("Enter your choice (1/2/3): ")
        try:
            choice = int(choice)
            if choice > 3 or choice < 1:
                print("Invalid input! Enter your choice (1/2/3): ")
                continue
        except ValueError:
            print("Invalid input! Enter your choice (1/2/3): ")
            continue
        return choice

def game_description():
    """
    Displays the game description.
    """
    clear()
    print(logo)
    print("\nHangman is a word-guessing game where you have"
          " to guess a hidden word letter by letter.")
    print("You can make a limited number of incorrect guesses"
          " before the hangman is complete.")
    print("Your goal is to guess the word before the hangman is fully drawn.")
    print("Good luck!\n")
    input("Press ENTER to continue")

def clear():
    """
    Clears the terminal to prevent clutter.
    """
    os.system('cls' if os.name == 'nt' else 'clear')

def display_stage(lives, guesses, message):
    """
    Displays the current stage of the hangman game.
    """
    clear()
    print(stages[lives])
    print(f"{' '.join(guesses)}")
    print(message)
    while True:
        guess = input("Guess a letter: ").lower()
        if len(guess) == 0:
            print("Guess cannot be empty")
        elif len(guess) > 1:
            print("Guess should not be more than one character!")
        elif not guess.isalpha():
            print("Guess should be a letter")
        else:
            return guess

def main():
    chosen_word = random.choice(word_list)
    word_length = len(chosen_word)

    end_of_game = False
    lives = 6

    menu_choice = main_menu()
    if menu_choice == 3:
        end_of_game = True
        print("Goodbye!")
        return
    elif menu_choice == 2:
        game_description()
        main()
    else:
        display = ["_" for _ in range(word_length)]
        current_guesses = []
        current_message = ''
        while not end_of_game:
            guess = display_stage(lives, display, current_message)

            if guess in current_guesses:
                current_message = f"You've already guessed {guess}"
            elif guess not in chosen_word:
                lives -= 1
                current_message = f"You guessed {guess}"
                "that's not in the word.You lose a life."
                if lives == 0:
                    end_of_game = True
                    clear()
                    print(stages[lives])
                    print("You are out of lives!")
                    print(f"The word was: {chosen_word}.")
                    print("You lose. Good luck next time!")
            else:
                for position in range(word_length):
                    letter = chosen_word[position]
                    if letter == guess:
                        current_message = "Correct guess!"
                        display[position] = letter
            current_guesses.append(guess)
            if "_" not in display:
                end_of_game = True
                clear()
                print(stages[lives])
                print("You got it!")
                print(f"The word was: {chosen_word}.")
                print("You win! Great job!")

        while True:
            play_again = input("Do you want to play again? Y or N: ").lower()
            if play_again not in ["y", "n"]:
                print("Invalid input!")
            elif play_again == 'y':
                main()
            else:
                print("Thank you for playing Hangman. Goodbye!")
                return

main()


n=int(input("Enter the limit: \n"))
# for i in range(1, n + 1):
#         for j in range(1, i + 1):
#             print("2", end=" ")
#         print()

num = 65

#     # outer loop to handle number of rows
# for i in range(0, n):
#     num = num + 1
#             # not re assigning num
#             # num = 1

#             # inner loop to handle number of columns
#             # values changing acc. to outer loop
#     for j in range(0, i+1):

#                 # printing number
#         print(chr(num), end=" ")

#                 # incrementing number at each column

#             # ending line after each row
#     print("")

for i in range(n,0,-1):
    print(" "*(n-i),end=" ")
    for j in range(1,i+1):
        print(chr(num),end=" ")
        num += 1
    num = 65
    print()


'''
heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
'''

class Solution:
    def pacificAtlantic(self, heights) :
        m, n = len(heights), len(heights[0])
        visit_p = [[0] * n for _ in range(m)]
        visit_a = [[0] * n for _ in range(m)]
        for i in range(m):
            for j in range(n):
                if j == 0 or i == 0:
                   self.dfs(heights, i, j, visit_a)
                if i == m-1 or j == n-1:
                   self.dfs(heights,i,j, visit_p)
        res = []
        for i in range(m):
            for j in range(n):
                if visit_p[i][j] and visit_a[i][j]:
                   res.append([i,j])
        return res

    def dfs(self,heights, i, j, visited):
        m, n = len(heights), len(heights[0])
        visited[i][j] = 1
        for x, y in [(i + 1, j), (i, j + 1),(i-1,j),(i,j-1)]:
            if 0 <= x < m and 0 <= y < n and visited[x][y] == 0:
                if heights[x][y] >= heights[i][j]:
                   self.dfs(heights, x, y, visited)

heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
print(Solution().pacificAtlantic(heights))

广度深度优先搜索/417. 太平洋大西洋水流问题.py

417. 太平洋大西洋水流问题.py