import torchvision.transforms as TF
import torchvision.transforms.functional as TFF
import numpy as np
from PIL import Image
import argparse
from pathlib import Path
from tqdm.auto import tqdm

def _get_new_shape(img):
    H, W = np.array(img).shape[:2]
    H_new, W_new = 512, round(512 * W / H)
    return H_new, W_new

def resize_image(img):
    H_new, W_new = _get_new_shape(img)
    mode = TF.InterpolationMode.BILINEAR
    return TFF.resize(img, (H_new, W_new), interpolation=mode)

def resize_mask(img):
    H_new, W_new = _get_new_shape(img)
    mode = TF.InterpolationMode.NEAREST
    return TFF.resize(img, (H_new, W_new), interpolation=mode)

def resize_folder(source, target, rtype):
    source ,target = Path(source), Path(target)
    print('source is ', source.absolute())
    target.mkdir(exist_ok=False, parents=True)
    skipped = []
    for pt in tqdm(list(source.iterdir())):
        if pt.suffix in ['.jpg', '.png']:
            image = Image.open(pt)
            if rtype == 'image':
                image = resize_image(image)
            else:
                image = resize_mask(image)
            targ_name = pt.name[:-len(pt.suffix)] + '.png'
            image.save(target / targ_name)
        else:
            skipped.append(pt.name)
    print(f'Skipped files: {", ".join(skipped)}')

if __name__ == '__main__':
    parser = argparse.ArgumentParser('resize')
    parser.add_argument('--source', type=str, help='absolute path to source folder', required=True)
    parser.add_argument('--target', type=str, help='absolute path to target folder', required=True)
    parser.add_argument('--type', choices=['image', 'mask'], help='resize type', required=True)
    args = parser.parse_args()
    print(args)
    print('Start resizing...')
    resize_folder(args.source ,args.target, args.type)
    print('Resizing ended')


"""
This code is supported by the website: https://www.guanjihuan.com
The newest version of this code is on the web page: https://www.guanjihuan.com/archives/5375
"""

import numpy as np

def hamiltonian(width=3, length=3):   # 方格子哈密顿量
    h = np.zeros((width*length, width*length))
    # y方向的跃迁
    for x in range(length):
        for y in range(width-1):
            h[x*width+y, x*width+y+1] = 1
            h[x*width+y+1, x*width+y] = 1
    # x方向的跃迁
    for x in range(length-1):
        for y in range(width):
            h[x*width+y, (x+1)*width+y] = 1
            h[(x+1)*width+y, x*width+y] = 1
    return h

h = hamiltonian()
print(h)


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

import requests,time,hashlib,json,uuid
from config import Config
cf = Config.Config()

def databuild(**kwargs):
    """
    公用的函数，构造data参数
    :param kwargs:
    :return:
    """
    data = json.dumps(kwargs)
    print(data)
    return data

def body(data: str, guid=0, app_id='1000001', app_key='DJYWeb', token='', sign='', ) -> dict:
    # 获取时间戳，先转换成整形，再转换字符串
    t = int(time.time())
    timestamp = str(t)
    # 构造nonce_str
    nonce_str = str(uuid.uuid1())
    # 通用请求头
    dic = {
        'app_id': app_id,
        'timestamp': timestamp,
        'nonce_str': nonce_str,
        'token': token,
        'sign': sign,
        'data': data
    }
    # 去除空值的键,构造新字典
    dic = {key: value for key, value in dic.items() if value}
    # 对key做字典升序排序，得到有序参数列表ascending_order_dic
    ascending_order_dic = sorted(dic.items(), key=lambda d: d[0], reverse=False)
    # 按照URL键值对的格式拼接成字符串
    list_str = ""
    for k, v in ascending_order_dic:
        list_str += k + '=' + v + '&'
    # 进行MD5运算
    m = hashlib.md5()
    m.update(list_str.encode('UTF-8'))
    strMD5 = m.hexdigest()
    # 字符串转大写，得到请求签名signature
    signature = strMD5.upper()
    # 构造body
    body = {
        'app_id': app_id,
        'guid': guid,
        'timestamp': timestamp,
        'nonce_str': nonce_str,
        'token': token,
        'app_key': app_key,
        'data': data,
        'signature': signature,
    }

    return body

def body_a(data: str, guid=0, app_id='1000001', app_key='DJYWeb', token='', sign='',AppVer='1.0',DeviceType='android',Lang='zh' ) -> dict:
    # 获取时间戳，先转换成整形，再转换字符串
    t = int(time.time())
    timestamp = str(t)
    # 构造nonce_str
    nonce_str = str(uuid.uuid1())
    # 通用请求头
    dic = {
        'app_id': app_id,
        'timestamp': timestamp,
        'nonce_str': nonce_str,
        'token': token,
        'sign': sign,
        'data': data
    }
    # 去除空值的键,构造新字典
    dic = {key: value for key, value in dic.items() if value}
    # 对key做字典升序排序，得到有序参数列表ascending_order_dic
    ascending_order_dic = sorted(dic.items(), key=lambda d: d[0], reverse=False)
    # 按照URL键值对的格式拼接成字符串
    list_str = ""
    for k, v in ascending_order_dic:
        list_str += k + '=' + v + '&'
    # 进行MD5运算
    m = hashlib.md5()
    m.update(list_str.encode('UTF-8'))
    strMD5 = m.hexdigest()
    # 字符串转大写，得到请求签名signature
    signature = strMD5.upper()
    # 构造body
    body = {
        'app_id': app_id,
        'guid': guid,
        'timestamp': timestamp,
        'nonce_str': nonce_str,
        'token': token,
        'app_key': app_key,
        'data': data,
        'signature': signature,
        'AppVer' : AppVer,
        'DeviceType' : DeviceType,
        'Lang' : Lang
    }

    return body

def djy_get_vcode(phonenum,app_id,app_key):
    """
    大佳营模板获取验证码
    :param phonenum:
    :param url:
    :return: vcode
    """
    data = databuild(SPhone=phonenum)
    Body = body(data=data, guid=0, app_id=app_id, app_key=app_key)
    response = requests.post(url=cf.host + 'api/v1/VCodeManager/GetVCode', json=Body)
    try:
        vcode = response.json()['Data']
        return vcode
    except Exception:
        print(Exception)

def labor_pre_login(phonenum, vcode,app_key):
    """
    大佳营模板预登陆接口
    :param phonenum:
    :param vcode:
    :param url:
    :return: tenanttype
    """
    data = databuild(Mobile=phonenum, VerifyCode=vcode)
    Body = body(data=data, guid=0, app_id='1000001', app_key=app_key)
    response = requests.post(url=cf.host+'api/v1/DJY_Login/Labor_Pre_Login', json=Body)
    try:
        tenanttype = response.json()['Data']['TenantType']
        return tenanttype
    except Exception:
        print(Exception)

def labor_weblogin(phonenum,app_key):
    """
    劳务模板登陆接口
    :param phonenum:
    :return: Data
    """
    vcode = djy_get_vcode(phonenum=phonenum, app_id='1000001', app_key=app_key)
    tenanttype = labor_pre_login(phonenum=phonenum,vcode=vcode,app_key=app_key)
    data = databuild(Mobile=phonenum, VerifyCode=vcode, tenanttype=tenanttype)
    Body = body(data=data, guid=0, app_id='1000001', app_key=app_key)
    response = requests.post(url=cf.host+'api/v1/DJY_Login/Labor_WebLogin', json=Body)
    try:
        Data = response.json()['Data']
        return Data
    except Exception:
        print(Exception)

def applet_login(phonenum,vcode,appid,appkey,tenantype):
    """小程序登陆"""
    #构建data
    data = databuild(mobile=phonenum, vcode=vcode,tenant_type=tenantype)
    #构建body体
    Body = body(data=data, guid=0, app_id=appid, app_key=appkey)
    response = requests.post(url=cf.host+'api/v1/DJY_Login/MiniLogin', json=Body,verify=False)
    try:
        result = response.json()
        return result
    except Exception:
        print("登陆失败，请定位")

def app_login(phone,appid,app_key,TenantType):
    # 构建data
    vcode = djy_get_vcode(phonenum=phone, app_id='1000001', app_key=app_key)
    data = databuild(Mobile=phone, VerifyCode=vcode,DeviceID='863178040256927',TenantType=TenantType)
    # 构建body体
    Body = body_a(data=data, guid=0, app_id=appid, app_key=app_key,AppVer='1.0')
    response = requests.post(url=cf.host + 'api/v1/DJY_Login/Labor_S_AppLogin', json=Body, verify=False)
    try:
        result = response.json()
        return result
    except Exception:
        print("登陆失败，请定位")

if __name__ == '__main__':
    res = app_login(phone='13340000001',appid='1000001',app_key='DJYApp',TenantType=2)
    print(res)
    # res = labor_weblogin('13340000001',app_key='DJYWeb')
    # print(res)


"""
방문을 했음을 set을 이용하여 구현하려고 했지만 testcase 2개만 통과하고 나머지는 실패로 뜸.
왜인지 찾아보니 0-1-2 / 3-4 이렇게 영역이 따로 생기는 경우에 마지막에 서로 연결을 해줘야하는데,
각 원소만 방문한 이후에 연결한 것을 체크하지 않고 끝나버리기 때문에 실패로 뜨는 것이라고 한다.

해결을 위해 len(set) == n 까지 while문을 돌며 cost[0], cost[1] 중 하나라도 set에 없는 경우에
set에 넣어주고 거리를 합산해준다.
"""

def solution_mine(n, costs):
    island = [i for i in range(n)]
    costs.sort(key=lambda x: x[2])
    s1 = s2 = set()
    cnt = 0
    for c in costs:
        s1.add(c[0])
        s2.add(c[1])
        cnt += c[2]
        if s1 == set(island) == s2:
            return cnt

def solution(n, costs):
    island = [i for i in range(n)]
    costs.sort(key=lambda x: x[2])
    s = set()
    cnt = 0
    s.add(0)
    while len(s) != n:
        for c in costs:
            if c[0] in s or c[1] in s:
                if c[0] in s and c[1] in s:
                    continue
                s.add(c[0])
                s.add(c[1])
                cnt += c[2]
                break
    return cnt

n = 4
c = [[0, 1, 1], [0, 2, 2], [1, 2, 5], [1, 3, 1], [2, 3, 8]]
print(solution(n, c))


import subprocess, os

def getStatus():
	# COMPLETED: connceted to a wiif
	# DISCONNECTED: could mean connection went wrong or in AP mode
	# SCANNING
	# ASSOCIATING
	# UNKNOWN: some error occured and we don't know the state

	try:
		result = subprocess.check_output('wpa_cli -i wlan0 status | grep wpa_state', shell=True)
		sResult = result.decode('utf-8').strip()
		state = sResult.split('=')
		if (len(state) == 2):
			return state[1]
		else:
			return "UNKNOWN"

	except:
		return "UNKNOWN"

def isAP():
	try:
		result = subprocess.check_output('systemctl status hostapd | grep Active:', shell=True)
		sResult = result.decode('utf-8').strip()
		isActive = sResult.split(' ')
		if (len(isActive) >= 2):
			isActive = isActive[1]
			if (isActive == "active"):
				return "ap"
			else:
				return "no_ap"
		return "unknown"
	except:
		return "unknown"

def listWifi():
	try:
		result = subprocess.check_output('sudo iw dev wlan0 scan ap-force | grep SSID', shell=True)
		sResult = result.decode('utf-8')
		wifiList = []
		for line in sResult.split('\n'):
			line = line.strip()
			if (len(line) > 7 and line[0] != '*'):
				wifiList.append(line[6:])
	except:
		wifiList = None

	return wifiList

def stopAP():
	try:
		path = os.path.dirname(__file__)
		result = subprocess.check_output('sudo ' + path + '/stop_ap.sh', shell=True)
	except:
		pass

def startAP():
	try:
		path = os.path.dirname(__file__)
		result = subprocess.check_output('sudo ' + path + '/start_ap.sh', shell=True)
	except:
		pass

def connectToAP(ssid, pw):
	fileHandle = open('/etc/wpa_supplicant/wpa_supplicant.conf','w')
	fileHandle.write('country=DE\n')
	fileHandle.write('ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n')
	fileHandle.write('update_config=1\n')
	fileHandle.write('network={\n')
	fileHandle.write('ssid="' + ssid + '"\n')
	fileHandle.write('scan_ssid=1\n')
	fileHandle.write('psk="' + pw + '"\n')
	fileHandle.write('key_mgmt=WPA-PSK\n')
	fileHandle.write('}\n')
	fileHandle.close()

	stopAP()


import kmmessage
import time
import logging

'''
Keith Murray
email: kmurrayis@gmail.com
'''
from asecretplace import getPythonHelperBotKeys
smstoaddr = getPythonHelperBotKeys.GETSMSADDR()
mmstoaddr = getPythonHelperBotKeys.GETMMSADDR()
emailtoaddr = getPythonHelperBotKeys.GETEMAILADDR()

def getUserFeedbackViaText(outgoingMsg, recipAddr=smstoaddr, tryAgainDelayMin=5):
    """
    Sends a text message to the recipient and waits for a reply
    Parameters
    ----------
    outgoingMsg : str
        The message going to the user
    recipAddr : str
        Email Address string the recipient is at
    tryAgainDelayMin : int
        Number of minutes between each repeated sent message. Networks don't often
        prioritize these messages, and 'loose' them fairly frequently, or don't
        pass them through until multiple hours have passed. If there's no reply
        in `tryAgainDelayMin` time, another message is sent, until `resendTotalCount`
        attempts have been made
    Returns
    -------
    msg : str
        The body of the email recieved IF it came in after the outgoing message was
        sent and before the `hardStopLimitMin` timelimit has been reached and was
        sent by the same address as `recipAddr`.  If `hardStopLimitMin` is reached,
        returns an empty string.
    Notes
    -----
    It's not the cleanest function, but it works
    Eventually I will build in a varible that mutes the messages between a defined
    timespan (night or during work hours)
    """
    # Bodge it
    quietAtNight = False
    tryResending = True
    resendTotalCount = 3
    if tryAgainDelayMin == -1:
        tryResending = False
    hardStopLimitMin = 60

    # Flush pop queue
    msg_From, msg_Body = kmmessage.checkForMessage()

    # Message User
    kmmessage.sms_message_Send(msg=outgoingMsg, recip=recipAddr)

    # wait for reply
    startTime = time.time()
    shortWaitStart = startTime
    sentCount = 1
    while True:
        timeSince = time.time() - startTime
        # Hard break if there's been no reply for a long period
        if timeSince > hardStopLimitMin*60:
            # It's over, we've waited too long. Time to move on
            msg = ""
            break
        # Resend message in case it got lost (happens mildly often)
        # Happened, 3 messages, zero recieved
        if tryResending:
            if sentCount < resendTotalCount:
                if (time.time() - shortWaitStart) > (tryAgainDelayMin * 60):
                    kmmessage.sms_message_Send(msg=outgoingMsg, recip=recipAddr)
                    sentCount += 1
                    shortWaitStart = time.time()
        # Wait and check for new email
        time.sleep(30)
        msg_From, msg_Body = kmmessage.checkForMessage()
        msg = ""
        # Parse new emails to see if they're from recipAddr
        for i in range(len(msg_From)):
            trimmed = msg_From[i].strip('<').strip('>')
            print(recipAddr, trimmed)
            logging.debug(recipAddr, trimmed)

            if recipAddr == trimmed:
                msg = msg_Body[i]
                break
        if msg != "":
            break

    return msg

def send_update(outgoingMsg, recipAddr=smstoaddr):
    # Message User

    maxTotalWaitTime = 5*60*60
    backoffTime = 30 # starting amount of time required to wait after an error. it will then double
    maxBackoffTime = 60*60
    i = 0
    startTime = time.time()
    while True:
        try:
            kmmessage.sms_message_Send(msg=outgoingMsg, recip=recipAddr)
            break
        except Exception as err:
            logging.info("Caught exception\n" + err)

        # Grow the amount of time it tries
        if time.time()-startTime > maxTotalWaitTime:
            break
        wait = min(backoffTime* (2**i), maxBackoffTime)
        time.sleep(wait)
        i += 1
    return

def send_karma_plot(outgoingMsg, outMedia, sbjLine, recipAddrMMS=mmstoaddr, recipAddrEmail=emailtoaddr, input_subject_Line=""):
    # Message User

    maxTotalWaitTime = 5*60*60
    backoffTime = 30 # starting amount of time required to wait after an error. it will then double
    maxBackoffTime = 60*60
    i = 0
    startTime = time.time()

    if ('mms' in input_subject_Line) and ('email' in input_subject_Line):
        out_email = True
        out_mms = True
    elif ('mms' in input_subject_Line):
        out_email = False
        out_mms = True
    elif ('email' in input_subject_Line):
        out_email = True
        out_mms = False
    else:
        out_mms = True
        out_email = True

    email_Sent = False
    mms_Sent = False
    while True:
        try:
            if out_email and not email_Sent:
                logging.debug("Sending Karma Plot: Email")
                kmmessage.message_Send_Full_Email([recipAddrEmail], sbjLine, outgoingMsg, files=[outMedia])
                email_Sent = True
                time.sleep(1)
            if out_mms and not mms_Sent:
                logging.debug("Sending Karma Plot: MMS")
                kmmessage.mms_message_Send(recipAddrMMS,outgoingMsg,outMedia)
                mms_Sent = True
            break
        except Exception as err:
            logging.info("Caught exception\n" + str(err))

        # Grow the amount of time it tries
        if time.time()-startTime > maxTotalWaitTime:
            break
        wait = min(backoffTime* (2**i), maxBackoffTime)
        time.sleep(wait)
        i += 1

    return


'''
Created on Oct 15, 2014

@author: ezulkosk
'''
from structures.exceptions import LexerException

tokens = (
    'AND',
    'OR',
    'NOT',
    'ID',
    'NUMBER',
    'BOOL',
    'GRAPH',
    'ASSERT',
    'LPAREN',
    'RPAREN',
    'LBRACKET',
    'RBRACKET',
    'COMMA',
    'EQUALS',
    'DOT',
    'SAGEGRAPH',
    'STR'
    )
# Tokens
reserved = {
   'graph' : 'GRAPH',
   'sagegraph' : 'SAGEGRAPH',
   'bool' : 'BOOL',
   'assert' : 'ASSERT'
}

t_DOT = r'\.'
t_AND    = r'&'
t_OR   = r'\|'
t_NOT   = r'!'
t_LPAREN  = r'\('
t_RPAREN  = r'\)'
t_EQUALS  = r'='
t_LBRACKET = r'\['
t_RBRACKET = r'\]'
t_COMMA = r','
t_STR = '".+"'

def t_NUMBER(t):
    r'\d+'
    try:
        t.value = int(t.value)
    except ValueError:
        print("Integer value too large %d", t.value)
        t.value = 0
    return t

def t_ID(t):
    r'[a-zA-Z_][a-zA-Z_0-9]*'
    t.type = reserved.get(t.value,'ID')    # Check for reserved words
    return t

# Ignored characters
t_ignore = " \t"

def t_newline(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")

def t_error(t):
    raise LexerException("illegal character '" + str(t.value[0]) + ".", t.lineno)

def t_COMMENT(t):
    r'\#.*'
    pass
    # No return value. Token discarded


# Predict in Keras
import json
from tensorflow.keras.preprocessing.text import tokenizer_from_json
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.sequence import pad_sequences
import numpy as np
from nltk.stem import WordNetLemmatizer
import re

stopwords = nltk.corpus.stopwords.words('english')
lemmatizer = WordNetLemmatizer()

# This can be replaced with the model location
SAVE_PATH = ''

negative_tweet_text = 'i had an very sick bad service'
positive_tweet_text = 'i had an excellent service'

#Define the indexing for each possible label in a dictionary
class_to_index = {"Neutral":0, "Negative":1, "Positive": 2}

#Creates a reverse dictionary
index_to_class = dict((v,k) for k, v in class_to_index.items())

ids_to_names = lambda n: np.array([index_to_class.get(x) for x in n])

def preprocess_tweet(tweet_text):
    tweet_text = re.sub('[^a-zA-Z]', ' ', tweet_text)
    tweet_text = tweet_text.lower()
    tweet_text = tweet_text.split()
    tweet_text = [lemmatizer.lemmatize(word) for word in tweet_text if (not(word in set(stopwords))) & (len(word)>1) ]
    tweet_text = ' '.join(tweet_text)
    return tweet_text

with open(f'{save_path}/keras_model_files/keras_tokenizer.json') as f:
    data = json.load(f)
    keras_tokenizer = tokenizer_from_json(data)

reconstructed_keras_model = load_model(f'{current_path}/keras_model_files/keras_model')

preprocessed_tweet = [preprocess_tweet(tweet_text) for tweet_text in [negative_tweet_text, positive_tweet_text]]

predict_texts_to_sequences = keras_tokenizer.texts_to_sequences(preprocessed_tweet)
predict_texts_to_sequences = pad_sequences(predict_texts_to_sequences, padding='post', maxlen=max_len)

keras_predictions = np.argmax(reconstructed_keras_model.predict(predict_texts_to_sequences), axis=1)

keras_prediction_labels_test = ids_to_names(keras_predictions)

print(keras_prediction_labels_test)


import json
import random

with open("text.json", "r") as f:
    try:
        file = f.read()
        file_dict = json.loads(file)
    except Exception as e:
        print(f"Error: {e}")

lifes = file_dict['life']
rand_word = random.choice(file_dict['words'])
letters = []

print("You need to guess the word letter by letter. You have 10 lifes, Have fun!")

while lifes > 0:
    word = ""
    for letter in rand_word:
        if letter in letters:
            word += letter
        else:
            word += "-"
    print(f"Word: {word}")
    print(f"Lifes: {lifes}")

    answer = input("Guess letter> ")
    letters.append(answer)

    if answer in rand_word:
        print("Correct!")
    else:
        print("Wrong!")
        lifes -= 1

    if all(letter in letters for letter in rand_word):
        print(f"Congrats!! The word you guessed is: {rand_word}")
        print(rand_word)
        break

    if lifes == 0:
        print(f"You lost! The word was: {rand_word}")


# Inspired by flashing lights on maintenance vehicles

#!/usr/bin/env python

import time

from blinkt import set_clear_on_exit, set_pixel, show

set_clear_on_exit()

def show_all(state):
    for i in range(8):
        val = state * 255
        set_pixel(i, val, val, val)
    show()

def show_bank1(state):
    for i in range(4):
        set_pixel(i, 250, 50, 0)
    show()

def show_bank2(state):
    for i in range(4):
        set_pixel(i+4, 250, 50, 0)
    show()

def flash_bank1():
    show_bank1(1)
    time.sleep(0.05)
    show_all(0)
    time.sleep(0.05)

def flash_bank2():
    show_bank2(1)
    time.sleep(0.05)
    show_all(0)
    time.sleep(0.05)

def dot():
    show_all(1)
    time.sleep(0.05)
    show_all(0)
    time.sleep(0.2)

def dash():
    show_all(1)
    time.sleep(0.2)
    show_all(0)
    time.sleep(0.2)

def space():
    time.sleep(0.1)

morse = '1111022220'

while True:
    for m in morse:
        if m == '0':
            space()
        elif m == '1':
            flash_bank1()
        elif m == '2':
            flash_bank2()


from app.model.notification import Notification

def read(file_path: str, delimiter=",", column_names: [str]=(), use_header=False):
    column_dict = {
        "message": 0,
        "reporter": 1
    }

    def make_define(names):
        if len(names) > 0:
            column_dict.clear()
            for i, n in enumerate(names):
                _n = n.lower()
                column_dict[_n] = i

    def to_notification(items):
        n = Notification(message="", reporter="")
        for c in column_dict:
            if hasattr(n, c):
                setattr(n, c, items[column_dict[c]])
        return n

    make_define(column_names)
    with open(file_path, mode="rt", encoding="utf-8", newline="") as f:
        header = use_header

        if delimiter == ",":
            import csv
            reader = csv.reader(f)
            for row in reader:
                if header:
                    make_define(row)
                    header = False
                else:
                    yield to_notification(row)
        else:
            for ln in f:
                _ln = ln.replace("\r", "").replace("\n", "")
                row = _ln.split(delimiter)
                if header:
                    make_define(row)
                    header = False
                else:
                    yield to_notification(row)


from .utils import memoized
from .classes import DB, Column

from .exceptions import (DriverNotFound,
                         DBNotConnected)

_connection = None

def get_driver(driver):
    driver_path = 'drivers.%s_driver' % (driver,)
    try:
        return memoized(__import__)(driver_path, globals(), locals(), -1)
    except ImportError:
        raise DriverNotFound(driver_path)

def create_schema():
    if not _connection:
        raise DBNotConnected()

    schema = get_driver(DB.driver).create_schema(
        'users',
        Column('email', ('varchar', 255), unique=True),
        Column('password', ('varchar', 255)),
        Column('activation_code', ('char', 40), unique=True),
        Column('status', ('char', 1), default='P'),  # Pending, Blocked, Active
        Column('login_attempts', ('int',), default='0'),
        Column('last_attempt', ('int',), default='0'),
    )

    execute(schema)

def execute(sql, values=None):
    return get_driver(DB.driver).execute(_connection, sql, values)

def create(sql, values=None):
    return get_driver(DB.driver).create(_connection, sql, values)


times = int(input()) # 测资数量
number = input() # 中奖号码

word2bonus = {0: 0, 1: 0, 2: 0, 3: 500, 4: 2000, 5: 5000, 6: 50000, 7: 300000, 8: 1000000}
# 建立对应奖金的转换字典 (也可以使用串列(list)或其他方式)

bonus = 0 # 存放中奖的总金额
for t in range(times): # 循环times次
    nums = input().split(',') # 读入每一行对奖号码，并以“,”分割成串列

    for num in nums: # 遍历每一个需要兑奖的号码
        same = 0 # 存放末尾n码相同的数量
        for i in range(1, 9): # 检查号码的每个字
            if (num[-i] == number[-i]): # 检查倒数第i个字是否相同
                same = i # 若相同，则纪录末尾n码相同
            else:
                break # 不同则跳出循环，当倒数第n码不同，则无需继续往前比较
        bonus += word2bonus[same] # 转换中奖的奖金并加到总奖金

print(bonus) # 输出总奖金


# Test for Riot Games API
# Anton Chen

import math
import os
import requests
import json
import pandas as pd
import tkinter as tk
from PIL import Image, ImageTk

API_URL = "api.riotgames.com"
DDRAGON_URL = "https://ddragon.leagueoflegends.com"
API_KEY = ""

# Test variables
SUMMONER = "Aegis"
DF = None

# Tkinter

def selectChamp(idx, champs, root):
    champ = champs[idx]

    #newWindow = tk.Toplevel(root)
    #newWindow.title(champ)
    #newWindow.geometry("200x720")

    getWinRates(champ)

def setSummoner(name):
    global SUMMONER
    global DF
    SUMMONER = name

    # Check if a file exists for this summoner. If no, download data first
    if not os.path.exists("{}.json".format(SUMMONER)):
        # Get the summoner PUUID and get all normal matches SR
        puuid = getSummonerPUUID(SUMMONER)
        matches = getAllMatches(puuid, "normal", 400) # 400 is SR draft pick 5v5

        data = []

        for i in range(len(matches)):
            m = MatchHandler(matches[i])
            data.append(m.__dict__)

        with open("{}.json".format(SUMMONER), "w") as f:
            json.dump(data, f)

    # Load the data into a dataframe
    DF = pd.read_json("{}.json".format(SUMMONER), orient="records")
    DF = DF.astype({"playerChamp":"category","enemyChamp":"category", "win":"category", "matchID":"string"})
    DF = DF.drop(["matchID"], axis=1)
    DF = DF.pivot_table(index=["playerChamp", "enemyChamp"], columns="win", aggfunc="size", fill_value=0)
    print(DF)

# Pandas

def getWinRates(champ):
    winRate = DF[DF["playerChamp",:] == champ]
    print(winRate)

# Help classes

class MatchHandler():
    def __init__(self, matchID):
        self.matchID = matchID

        matchData = self.getMatch()
        self.initialize(matchData)

    def getMatch(self):
        region = "europe"
        url = "https://{}.{}/lol/match/v5/matches/{}".format(region, API_URL, self.matchID)
        headers = {"X-Riot-Token": API_KEY}

        res = requests.get(url, headers=headers)

        if res.status_code == 200:
            return res.json()
        else:
            return

    def initialize(self, data):
        players_data = data["info"].get("participants")
        players = []
        position = ""
        summonerChamp = ""
        enemyChamp = ""
        win = True

        for i in range(len(players_data)):
            player = {"champion": players_data[i].get("championName"),
                      "position": players_data[i].get("individualPosition"),
                      "summoner": players_data[i].get("summonerName"),
                      "win": players_data[i].get("win")
                      }
            if player.get("summoner") == SUMMONER:
                summonerChamp = player.get("champion")
                position = player.get("position")
                win = player.get("win")
            else:
                players.append(player)

        for i in range(len(players)):
            if players[i].get("position") == position:
                enemyChamp = players[i].get("champion")
                break

        self.playerChamp = summonerChamp
        self.enemyChamp = enemyChamp
        self.win = win

    def test(self):
        print(self.__dict__)

class MatchPlayerHandler():
    def __init__(self, puuid):
        self.puuid = puuid

# Riot Games API

def getSummoner(name):
    server = "euw1"
    url = "https://{}.{}/lol/summoner/v4/summoners/by-name/{}".format(server, API_URL, name)
    headers = {"X-Riot-Token": API_KEY}

    res = requests.get(url, headers=headers)

    if res.status_code == 200:
        return res.json()
    else:
        return

def getSummonerID(name):
    res = getSummoner(name)

    return res.get("id")

def getSummonerPUUID(name):
    res = getSummoner(name)

    return res.get("puuid")

def getMatches(puuid, gType, qType, start=0, count=100):

    region = "europe"
    url = "https://{}.{}/lol/match/v5/matches/by-puuid/{}/ids?type={}&queue={}&start={}&count={}".format(region, API_URL, puuid, gType, qType, start, count)
    headers = {"X-Riot-Token": API_KEY}

    res = requests.get(url, headers=headers)

    if res.status_code == 200:
        return res.json()
    else:
        return

def getAllMatches(puuid, gType, qType):
    index = 0
    count = 100
    matches = []

    while True:
        res = getMatches(puuid, gType, qType, start=index, count=count)
        matches += res
        index += 100

        if len(res) < 100:
            break

    return matches

def getMastery(summ_id):
    region = "europe"
    url = "https://{}.{}/lol/champion-mastery/v4/champion-masteries/by-summoner/{}".format(region, API_URL, summ_id)
    headers = {"X-Riot-Token": API_KEY}

    res = requests.get(url, headers=headers)

    if res.status_code == 200:
        return res.json()
    else:
        return

# Data Dragon

def getLatestVers():
    url = "{}/api/versions.json".format(DDRAGON_URL)

    res = requests.get(url)

    if res.status_code == 200:
        return res.json()[0]
    else:
        return

def getChampionData():
    vers = getLatestVers()
    url = "{}/cdn/{}/data/en_US/champion.json".format(DDRAGON_URL, vers)

    res = requests.get(url)

    if res.status_code == 200:
        return res.json().get("data")
    else:
        return

def getChampionIcons(data):
    vers = getLatestVers()
    icons = []

    for champ in data.keys():
        url = "{}/cdn/{}/img/champion/{}.png".format(DDRAGON_URL, vers, champ)

        res = requests.get(url)

        if res.status_code == 200:
            img = ImageTk.PhotoImage(data=res.content)
            icons.append(img)
        else:
            break

    return icons

# App

def main():
    root = tk.Tk()

    #m = MatchHandler(matches[0])
    champData = getChampionData()
    champIcons = getChampionIcons(champData)

    # Window settings
    root.title("Champion Matchup Analyzer")

    width = 1280
    height = 720
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    center_x = int(screen_width/2 - width/2)
    center_y = int(screen_height/2 - height/2)

    root.geometry(f"{width}x{height}+{center_x}+{center_y}")

    # Grid

    nCols = 10                              # Champions per row
    champCount = len(champData)
    champs = list(champData)
    nRows = math.ceil(champCount / nCols)

    # Input

    tk.Label(root, text="Summoner Name").grid(row=0, column=0)
    entry = tk.Entry(root)
    entry.grid(row=0, column=1)
    tk.Button(root, text="Confirm", command=lambda:setSummoner(entry.get())).grid(row=0, column=2)

    # Buttons

    idx = 0

    for i in range(nRows):
        for j in range(nCols):
            tk.Button(root, image=champIcons[idx], command=lambda k=idx:selectChamp(k, champs, root)).grid(row=i+1, column=j)
            idx += 1

            if idx >= champCount:
                break

    root.mainloop()

main()


import argparse
import os
import sys
import signal

from deephyper.search.util import load_attr_from

HPS_SEARCHES = {
    'ambs': 'deephyper.search.hps.ambs.AMBS',
    'ga': 'deephyper.search.hps.ga.GA'
}

def add_subparser(parsers):
    parser_name = 'hps'

    parser = parsers.add_parser(
        parser_name, help='Command line to run hyper-parameter search.')

    subparsers = parser.add_subparsers()

    for name, module_attr in HPS_SEARCHES.items():
        search_cls = load_attr_from(module_attr)

        subparser = subparsers.add_parser(name=name, conflict_handler='resolve')
        subparser = search_cls.get_parser(subparser)

        subparser.set_defaults(func=main)

def main(**kwargs):
    search_name = sys.argv[2]
    search_cls = load_attr_from(HPS_SEARCHES[search_name])
    search_obj = search_cls(**kwargs)
    try:
        on_exit = load_attr_from(f'{search_obj.__module__}.on_exit')
        signal.signal(signal.SIGINT, on_exit)
        signal.signal(signal.SIGTERM, on_exit)
    except AttributeError as e: # on_exit is not defined
        raise e
    search_obj.main()


import json

from recruitment.bamboo_hr.entities.bamboo_employee import BambooEmployee
from recruitment.bamboo_hr.entities.bamboo_time_off import BambooTimeOff
from recruitment.bamboo_hr import util

class BambooHrApi():

    def employee(self, context, params):
        '''Gets an employee'''

        headers = context['headers']
        method = "GET"
        url = "/employees/{id}".format(id=params["employee_id"])
        querystring = {"fields":"employee_id,firstName,lastName,dateOfBirth,address1,address2,city,state,zipcode,country,hireDate,bestEmail"}

        result = json.loads(util.get_bamboo_request(method, url, headers, params=querystring).text)

        bamboo_employee = BambooEmployee(
            employee_id=result["id"],
            first_name=result["firstName"],
            last_name=result["lastName"],
            date_of_birth=result["dateOfBirth"],
            address1=result["address1"],
            address2=result["address2"],
            city=result["city"],
            state=result["state"],
            zip_code=result["zipcode"],
            country=result["country"],
            hire_date=result["hireDate"],
            work_email=result["bestEmail"]
        )
        return bamboo_employee.__dict__


#   Author: Ana Luisa Mata Sanchez
#   Course: CS2302
#   Assignment: Lab #6
#   Instructor: Olac Fuentes
#   Description: Program to draw mazes using dsf
#   T.A.: Anindita Nath, Maliheh Zargaran
#   Last modified: 04/11/2019
#   Purpose: To compare time differences between compressed and non-compressed disjoint set forest

import matplotlib.pyplot as plt
import numpy as np
import random
import time

###################################### Code provided and written by Dr. Fuentes ######################################
def DisjointSetForest(size):
    return np.zeros(size,dtype=np.int)-1

def dsfToSetList(S):
    #Returns aa list containing the sets encoded in S
    sets = [ [] for i in range(len(S)) ]
    for i in range(len(S)):
        sets[find(S,i)].append(i)
    sets = [x for x in sets if x != []]
    return sets

def find(S,i):
    # Returns root of tree that i belongs to
    if S[i]<0:
        return i
    return find(S,S[i])

def find_c(S,i): #Find with path compression
    if S[i]<0:
        return i
    r = find_c(S,S[i])
    S[i] = r
    return r

def union(S,i,j):
    # Joins i's tree and j's tree, if they are different
    ri = find(S,i)
    rj = find(S,j)
    if ri!=rj:
        S[rj] = ri

def union_c(S,i,j):
    # Joins i's tree and j's tree, if they are different
    # Uses path compression
    ri = find_c(S,i)
    rj = find_c(S,j)
    if ri!=rj:
        S[rj] = ri

def union_by_size(S,i,j):
    # if i is a root, S[i] = -number of elements in tree (set)
    # Makes root of smaller tree point to root of larger tree
    # Uses path compression
    ri = find_c(S,i)
    rj = find_c(S,j)
    if ri!=rj:
        if S[ri]>S[rj]: # j's tree is larger
            S[rj] += S[ri]
            S[ri] = rj
        else:
            S[ri] += S[rj]
            S[rj] = ri

def draw_maze(walls,maze_rows,maze_cols,cell_nums=False):
    fig, ax = plt.subplots()
    for w in walls:
        if w[1]-w[0] ==1: #vertical wall
            x0 = (w[1]%maze_cols)
            x1 = x0
            y0 = (w[1]//maze_cols)
            y1 = y0+1
        else:#horizontal wall
            x0 = (w[0]%maze_cols)
            x1 = x0+1
            y0 = (w[1]//maze_cols)
            y1 = y0
        ax.plot([x0,x1],[y0,y1],linewidth=1,color='k')
    sx = maze_cols
    sy = maze_rows
    ax.plot([0,0,sx,sx,0],[0,sy,sy,0,0],linewidth=2,color='k')
    if cell_nums:
        for r in range(maze_rows):
            for c in range(maze_cols):
                cell = c + r*maze_cols
                ax.text((c+.5),(r+.5), str(cell), size=10,
                        ha="center", va="center")
    ax.axis('off')
    ax.set_aspect(1.0)

def wall_list(maze_rows, maze_cols):
    # Creates a list with all the walls in the maze
    w =[]
    for r in range(maze_rows):
        for c in range(maze_cols):
            cell = c + r*maze_cols
            if c!=maze_cols-1:
                w.append([cell,cell+1])
            if r!=maze_rows-1:
                w.append([cell,cell+maze_cols])
    return w

###################################### MY CODE ######################################

#Method that removes walls and creates the dsf using the standard union and find methods
def create_standard_dsf_maze(S,walls):
    #If there is only one set it means that all cells are reacheable from any cell
    while len(dsfToSetList(S))>1:
        #Finds a wall to remove
        d = random.randint(0,len(walls)-1)
        #If the elements that share a wall are not in the same set, remove it
        if find(S,walls[d][0]) != find(S,walls[d][1]):
            #make the elements belong to the same set
            union(S,walls[d][0],walls[d][1])
            #remove the wall
            walls.pop(d)

#Method that removes walls and creates the dsf using the union by size and compressed find methods
def create_compressed_dsf_maze(SC,wallsC):
    #If there is only one set it means that all cells are reacheable from any cell
    while len(dsfToSetList(SC))>1:
        #Finds a wall to remove
        dC = random.randint(0,len(wallsC)-1)
        #If the elements that share a wall are not in the same set, remove it
        if find_c(SC,wallsC[dC][0]) != find_c(SC,wallsC[dC][1]):
            #make the elements belong to the same set
            union_by_size(SC,wallsC[dC][0],wallsC[dC][1])
            #remove the wall
            wallsC.pop(dC)

plt.close("all")
maze_rows = 10
maze_cols = 15

#wall list & dsf for standard method
walls = wall_list(maze_rows,maze_cols)
S = DisjointSetForest(maze_rows*maze_cols)

#wall list & dsf for compressed method
wallsC = wall_list(maze_rows,maze_cols)
SC = DisjointSetForest(maze_rows*maze_cols)

#draw initial maze
draw_maze(walls,maze_rows,maze_cols,cell_nums=True)

print("######## Maze using standard find and union ########\n")

iStandardMazeT = time.time()
create_standard_dsf_maze(S,walls)
fStandardMazeT = time.time()
draw_maze(walls,maze_rows,maze_cols)

print("Time it took to create the maze:", fStandardMazeT-iStandardMazeT)
print("Maze row size:", maze_rows)
print("Maze column size:", maze_cols)

print("\n######## Maze using compressed find and union by size ########\n")

iCompressedMazeT = time.time()
create_compressed_dsf_maze(SC,wallsC)
fCompressedMazeT = time.time()
draw_maze(wallsC,maze_rows,maze_cols)

print("Time it took to create the maze:", fCompressedMazeT-iCompressedMazeT)
print("Maze row size:", maze_rows)
print("Maze column size:", maze_cols)


from typing import List, Optional
import time
import enum
from pathlib import Path
import json
import shutil

from doit.tools import create_folder, config_changed
from requests import Session

from elm_doc.elm_project import ElmPackage, ModuleName, fetch_releases
from elm_doc.run_config import Build
from elm_doc.tasks import html as html_tasks
from elm_doc.utils import Namespace

class actions(Namespace):
    def write_package_releases(output_path: Path, version: str, timestamp: int):
        releases = {version: timestamp}
        with open(str(output_path), 'w') as f:
            json.dump(releases, f)

    def link_latest_package_dir(output_path: Path, package_dir: Path):
        package_dir.mkdir(parents=True, exist_ok=True)
        # prefer relative path to make the built documentation directory relocatable
        if output_path.is_symlink():
            output_path.unlink()
        output_path.symlink_to(package_dir.relative_to(output_path.parent), target_is_directory=True)

    def copy_package_file(package_file: Path, output_path: Path):
        if package_file.is_file():
            shutil.copy(str(package_file), str(output_path))

    def copy_package_docs_json(package: ElmPackage, output_path: Path):
        source = package.path / package.DOCS_FILENAME
        shutil.copy(str(source), str(output_path))

class Context(enum.Enum):
    '''In order to delay the creation of tasks for project dependencies,
    the basenames of the delayed tasks need to be different than those
    for the main project tasks for doit to correctly pick up.

    This enum provides a way for differentiating those two contexts when
    creating tasks in this module, which are shared between the two.
    '''
    Project = 'project'
    Dependency = 'dep'

    def basename(self, suffix):
        return '{}_{}'.format(self.value, suffix)

def _package_task_name(package):
    return '{}/{}'.format(package.name, package.version)

def create_dependency_tasks(session: Session, package: ElmPackage, run_config: Build):
    task_name = _package_task_name(package)
    package_modules = package.sorted_exposed_modules()
    package_output_path = package_docs_root(run_config.output_path, package)

    # package docs.json
    docs_json_path = package_output_path / package.DOCS_FILENAME
    yield {
        'basename': Context.Dependency.basename('copy_docs_json'),
        'name': task_name,
        'actions': [(create_folder, (str(package_output_path),)),
                    (actions.copy_package_docs_json, (package, docs_json_path))],
        'targets': [docs_json_path],
        'file_dep': [package.path / package.DOCS_FILENAME]
    }

    yield from create_package_page_tasks(
        Context.Dependency, session, package, package_modules, run_config)

def create_package_page_tasks(
        context: Context,
        session: Session,
        package: ElmPackage,
        package_modules: List[ModuleName],
        run_config: Build):
    task_name = _package_task_name(package)
    package_output_path = package_docs_root(run_config.output_path, package)
    page_flags = {'mount_point': run_config.mount_point}

    # package index page
    package_index_output = package_output_path / 'index.html'
    yield {
        'basename': context.basename('top_page'),
        'name': task_name,
        'actions': [(html_tasks.actions.write, (package_index_output,), page_flags)],
        'targets': [package_index_output],
        'uptodate': [config_changed(page_flags)],
    }

    # package versions page
    package_versions_output = package_output_path.parent / 'index.html'
    yield {
        'basename': context.basename('versions_page'),
        'name': task_name,
        'actions': [(html_tasks.actions.write, (package_versions_output,), page_flags)],
        'targets': [package_versions_output],
        'uptodate': [config_changed(page_flags)],
    }

    # package elm.json
    elm_json_filename = 'elm.json'
    package_elm_json = package.path / elm_json_filename
    output_elm_json_path = package_output_path / elm_json_filename
    if package_elm_json.is_file():
        yield {
            'basename': context.basename('elm_json'),
            'name': task_name,
            'actions': [(actions.copy_package_file, (package_elm_json, output_elm_json_path))],
            'targets': [output_elm_json_path],
            'file_dep': [package_elm_json],
        }

    # package readme
    readme_filename = 'README.md'
    package_readme = package.path / readme_filename
    output_readme_path = package_output_path / readme_filename
    if package_readme.is_file():
        yield {
            'basename': context.basename('readme'),
            'name': task_name,
            'actions': [(actions.copy_package_file, (package_readme, output_readme_path))],
            'targets': [output_readme_path],
            'file_dep': [package_readme],
        }

    # package releases
    package_releases_output = package_output_path.parent / 'releases.json'
    if context == Context.Dependency:
        releases = fetch_releases(session, package.name)
        timestamp = releases.get(package.version, 1)
    else:
        timestamp = int(time.time())
    content = {'version': package.version, 'timestamp': timestamp}
    yield {
        'basename': context.basename('releases'),
        'name': task_name,
        'actions': [(actions.write_package_releases, (package_releases_output,), content)],
        'targets': [package_releases_output],
        'uptodate': [config_changed(content)]
    }

    # link from /latest
    latest_path = package_output_path.parent / 'latest'
    uptodate_config = {'link_target': str(package_output_path.relative_to(run_config.output_path))}
    yield {
        'basename': context.basename('latest_link'),
        'name': task_name,
        'actions': [(actions.link_latest_package_dir, (latest_path, package_output_path))],
        'targets': [latest_path],
        'uptodate': [config_changed(uptodate_config)]
    }

    # package about
    output_about_path = package_output_path / 'about'
    yield {
        'basename': context.basename('about'),
        'name': task_name,
        'actions': [(html_tasks.actions.write, (output_about_path,), page_flags)],
        'targets': [output_about_path],
        'uptodate': [config_changed(page_flags)],
    }

    # module pages
    for module_name in package_modules:
        module_output = package_output_path / module_name.replace('.', '-')
        yield {
            'basename': context.basename('module_page'),
            'name': '{}:{}'.format(task_name, module_name),
            'actions': [(html_tasks.actions.write, (module_output,), page_flags)],
            'targets': [module_output],
            'uptodate': [config_changed(page_flags)],
        }

def package_docs_root(output_path: Optional[Path], package: ElmPackage) -> Path:
    return output_path / 'packages' / package.user / package.project / package.version


import numpy as np
import zmq

class ObsSpace():
    def __init__(self):
        self.shape = [96, 1]

class ActionSpace():
    def __init__(self):
        self.shape = [12, 1]

    def sample(self):
        return np.clip(((np.random.rand(12)*(40.0-7.5))+7.5), 7.5, 40.0)

class TensegrityEnv:
    def __init__(self):
        self.context = zmq.Context()
        print("Connecting to Tensegrity Robot...")
        self.socket = self.context.socket(zmq.REQ)
        self.socket.connect("tcp://localhost:5555")
        self._max_episode_steps = 500
        self.action_space = ActionSpace()
        self.observation_space = ObsSpace()
        self.counter = 0

    def send_array(self, A, flags=0, copy=True, track=False):
        """send a numpy array with metadata"""
        md = dict(
            dtype = str(A.dtype),
            shape = A.shape,
        )
        self.socket.send_json(md, flags|zmq.SNDMORE)
        return self.socket.send(A, flags, copy=copy, track=track)

    def recv_array(self, flags=0, copy=True, track=False):
        """recv a numpy array"""
        md = self.socket.recv_json(flags=flags)
        msg = self.socket.recv(flags=flags, copy=copy, track=track)
        buf = bytearray(msg)
        A = np.frombuffer(buf, dtype=md['dtype'])
        return A.reshape(md['shape'])

    def _calculate_reward(self, state):
        vels = state[36:72]
        return np.mean(vels)

    def sample(self):
        return (np.random.rand(12)*0.95)

    def reset(self, rand_face=False):
        print('Resetting agent')
        if rand_face:
            self.socket.send(b"reset2")
        else:
            self.socket.send(b"reset")
        s = self.recv_array()
        self.counter = 0
        return s

    def step(self, action):
        self.counter += 1
        self.socket.send(b"step")
        message = self.socket.recv()
        self.send_array(action)
        next_state = self.recv_array()
        reward = self._calculate_reward(next_state)
        if self.counter < self._max_episode_steps:
            done = False
        else:
            done = True
        info = {}
        return next_state, reward, done, info

    def render(self):
        pass

    def close(self):
        pass


#!/usr/bin/env python3

import asyncio
import struct
import random
import time
from bleak import BleakClient, BleakScanner

prepare_delay_ms = 4000
use_sync = False # Enables synchronization protocol

DDD_SERVICE_UUID     = "32e61089-2b22-4db5-a914-43ce41986c70"
DDD_REQ_CHAR_UUID    = "32e6108b-2b22-4db5-a914-43ce41986c70"
DDD_RESP_CHAR_UUID   = "32e6108c-2b22-4db5-a914-43ce41986c70"
DDD_NOSYNC_CHAR_UUID = "32e6108d-2b22-4db5-a914-43ce41986c70"

CONN_TIMEOUT = 20.0 # seconds

# < means little endian
# L means unsigned long (4B), l means signed long, B means unsigned byte
REQ_PREPARE_LAYOUT = "<LBBB"
REQ_COMMIT_LAYOUT = "<lBBB"
RESP_LAYOUT = "<LBBH"

class Sync:
    # Requests
    PREPARE = 1
    COMMIT = 2
    ABORT = 3
    # Responses
    VOTE_COMMIT = 1
    VOTE_ABORT = 2
    ACK = 3

CMD_LUT = {
    "on": 1,
    "off": 2,
    "l": 3,
    "r": 4,
    "f": 5,
    "b": 6,
    "z": 7,
    "go": 8,
    "stop": 9,
    "d": 10,
}

start_ms = int(time.time() * 1000)

def now_ms():
    # Can't use process_time since we're probably sleeping a lot with async
    return int(time.time() * 1000) - start_ms

class Channels:
    def __init__(self, i, buckler, addr, chs):
        self.id = i
        self.buckler = buckler
        self.addr = addr
        self.req_ch = chs[0]
        self.resp_ch = chs[1]
        self.nosync_ch = chs[2]
        self.recorded_rtts = []

    async def do_nosync(self, cmd_id):
        return await self.buckler.write_gatt_char(
            self.nosync_ch,
            struct.pack("B", cmd_id),
            response=False
        )

    async def prepare(self, seq_no, t1, cmd_id):
        """
        Performs a 2PC prepare.

        Returns the rough clock error if the result is valid, or None if the the result was invalid.
        """
        i = self.id
        print(f"# {i} sending 2PC prepare [t1={t1}]")
        # PTP/2PC from leader to follower
        await self.buckler.write_gatt_char(
            self.req_ch,
            # Prepare:
            # - target time [ms]: u32
            # - 2PC command: u8
            # - robot command: u8
            # - seq_no: u8
            struct.pack(
                REQ_PREPARE_LAYOUT,
                t1 + prepare_delay_ms,
                Sync.PREPARE,
                cmd_id,
                seq_no
            ),
            response=True
        )
        # Since we're using write w/ response, use post-write time as t4
        t4 = now_ms()
        # PTP/2PC from follower to leader
        t2_e, sync_resp_id, resp_seq_no, _ = struct.unpack(
            RESP_LAYOUT,
            await self.buckler.read_gatt_char(self.resp_ch)
        )
        # Peripheral assumes t2 = t3 (we don't need that kind of granularity)
        rtt = t4 - t1
        err = t2_e - t1 + rtt // 2
        self.recorded_rtts.append(rtt)
        print(f"# {i} estimated RTT: {rtt}; e: {err}")
        if resp_seq_no != seq_no:
            print(f"# {i} unexpected sequence number: got {resp_seq_no}, exp {seq_no}")
            return None
        if sync_resp_id == Sync.VOTE_COMMIT:
            print(f"# {i} voted commit [t2+e={t2_e}, t4={t4}]")
            return err
        elif sync_resp_id == Sync.VOTE_ABORT:
            print(f"# {i} voted abort")
            return None
        else:
            print(f"# {i} voted invalid ({sync_resp_id})")
            return None

    async def wait_for_ack(self, seq_no):
        _, sync_resp_id, resp_seq_no, _ = struct.unpack(
            RESP_LAYOUT,
            await self.buckler.read_gatt_char(self.resp_ch)
        )
        if resp_seq_no != seq_no:
            print(f"# {self.id} unexpected sequence number: got {resp_seq_no}, exp {seq_no}")
            return False
        return sync_resp_id == Sync.ACK

    async def commit(self, seq_no, err):
        print(f"# {self.id} sending 2PC commit [e={err}]")
        await self.buckler.write_gatt_char(
            self.req_ch,
            # Commit:
            # - _: u32
            # - e: i32
            # - 2PC command: u8
            # - _: u8
            # - seq_no: u8
            struct.pack(REQ_COMMIT_LAYOUT, err, Sync.COMMIT, 0, seq_no),
            response=True
        )
        return await self.wait_for_ack(seq_no)

    async def abort(self, seq_no):
        print(f"# {self.id} sending 2PC abort")
        await self.buckler.write_gatt_char(
            self.req_ch,
            struct.pack(REQ_PREPARE_LAYOUT, 0, Sync.ABORT, 0),
            response=False
        )
        return await self.wait_for_ack(seq_no)

    async def disconnect(self):
        return await self.buckler.disconnect()

    async def try_reconnect(self):
        if await self.buckler.is_connected():
            print(f"{self.id} still connected, doing nothing")
        else:
            print(f"{self.id} attempting reconnect...")
            self.buckler = BleakClient(self.addr)
            self.req_ch, self.resp_ch, self.nosync_ch = await get_buckler_ch(self.buckler)
            print(f"{self.id} reconnected")
            return

async def get_buckler_ch(buckler):
    await buckler.connect(timeout=CONN_TIMEOUT)
    # Get service
    svs = await buckler.get_services()
    sv = svs.get_service(DDD_SERVICE_UUID)
    # Get characteristic
    return (
        sv.get_characteristic(DDD_REQ_CHAR_UUID).handle,
        sv.get_characteristic(DDD_RESP_CHAR_UUID).handle,
        sv.get_characteristic(DDD_NOSYNC_CHAR_UUID).handle,
    )

# https://bleak.readthedocs.io/en/latest/usage.html
async def run():
    global prepare_delay_ms, use_sync
    print("searching for DDDs...")
    buckler_0 = None
    buckler_1 = None
    addr_0 = None
    addr_1 = None
    while buckler_0 is None or buckler_1 is None:
        devices = await BleakScanner.discover()
        for d in devices:
            # print(f"device {d} at address {d.address}")
            if "EE149" in d.name:
                print(f"discovered device {d}")
                if buckler_0 is None and "(0)" in d.name:
                    buckler_0 = BleakClient(d.address)
                    addr_0 = d.address
                    print(f"discovered DDD 0 @ addr {d.address}")
                    if buckler_1 is not None:
                        break
                if buckler_1 is None and "(1)" in d.name:
                    buckler_1 = BleakClient(d.address)
                    addr_1 = d.address
                    print(f"discovered DDD 1 @ addr {d.address}")
                    if buckler_0 is not None:
                        break
        if buckler_0 is None or buckler_1 is None:
            print("retrying discovery...")

    ch_0 = None
    ch_1 = None
    try:
        print("DDDs found, verifying characteristics...")
        channel_tuples = await asyncio.gather(
            get_buckler_ch(buckler_0),
            get_buckler_ch(buckler_1)
        )
        ch_0 = Channels(0, buckler_0, addr_0, channel_tuples[0])
        ch_1 = Channels(1, buckler_1, addr_1, channel_tuples[1])
        print("Both DDDs ready!")

        seq_no = random.randint(0, 256)
        while True:
            try:
                seq_no += 1
                seq_no %= 256 # Ensure doesn't overflow byte
                cmd = input(f"ddd seq_no={seq_no}> ").strip()
                toks = cmd.split()
                if cmd in ("q", "quit", "exit"):
                    print("quitting")
                    break
                elif cmd in ("ns", "nosync"):
                    print("disabled sync")
                    use_sync = False
                elif cmd == "sync":
                    print(f"enabled sync (delay {prepare_delay_ms} ms)")
                    use_sync = True
                elif cmd in ("rc", "reconnect", "reset"):
                    await asyncio.gather(ch_0.try_reconnect(), ch_1.try_reconnect())
                elif len(toks) > 0 and toks[0] == "setdelay":
                    prepare_delay_ms = int(toks[1])
                    print(f"set sync delay to {prepare_delay_ms} ms")
                elif cmd in CMD_LUT:
                    cmd_id = CMD_LUT[cmd]
                    if use_sync:
                        print(f"# Beginning 2PC sequence {seq_no}")
                        t1 = now_ms()
                        err0, err1 = await asyncio.gather(
                            ch_0.prepare(seq_no, t1, cmd_id),
                            ch_1.prepare(seq_no, t1, cmd_id)
                        )
                        if not err0 or not err1:
                            print("# Aborting 2PC")
                            await asyncio.gather(
                                ch_0.abort(seq_no),
                                ch_1.abort(seq_no)
                            )
                            continue
                        c0, c1 = await asyncio.gather(
                            ch_0.commit(seq_no, err0),
                            ch_1.commit(seq_no, err1)
                        )
                        if not c0 or not c1:
                            print("# Missed a 2PC ACK (nothing left to do)")
                    else:
                        print("# Transmitting commands with no sync")
                        await asyncio.gather(
                            ch_0.do_nosync(cmd_id),
                            ch_1.do_nosync(cmd_id)
                        )
                else:
                    print(f"invalid command: {cmd}")
            except KeyboardInterrupt:
                break
            except Exception as e:
                print(e)
                pass
    finally:
        if ch_0 is not None:
            print(f"DDD 0 RTTs: {ch_0.recorded_rtts}")
        if ch_1 is not None:
            print(f"DDD 1 RTTs: {ch_1.recorded_rtts}")
        await asyncio.gather(ch_0.disconnect(), ch_1.disconnect())

loop = asyncio.get_event_loop()
loop.run_until_complete(run())


import yaml

class DictionaryTagger(object):
    def __init__(self, dictionary_paths):
        files = [open(path, 'r') for path in dictionary_paths]
        dictionaries = [yaml.load(dict_file) for dict_file in files]
        map(lambda x: x.close(), files)
        self.dictionary = {}
        self.max_key_size = 0
        for curr_dict in dictionaries:
            for key in curr_dict:
                if key in self.dictionary:
                    self.dictionary[key].extend(curr_dict[key])
                else:
                    self.dictionary[key] = curr_dict[key]
                    self.max_key_size = max(self.max_key_size, len(str(key)))

    def tag(self, postagged_sentences):
        return [self.tag_sentence(sentence) for sentence in postagged_sentences]

    def tag_sentence(self, sentence):
        def sentiment_tag(w, t):
            if w in self.dictionary:
                t.append(self.dictionary[w.lower()][0])
                res = (w, t)
                return res
            else:
                res = (w, t)
                return res
        k = [sentiment_tag(word, tag) for (word, tag) in sentence]
        return k

# Compute value of single segment
def value_of(sentiment):
    if sentiment == 'positive': return 1
    if sentiment == 'negative': return -1
    return 0

# Sum sentiment score for whole document
def sentiment_score(d):
    # Sum occurences of sentiment words and normalize on length of the document
    return sum([value_of(tag) for sentence in d for (lit, tags) in sentence for tag in tags])/len(d)


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

from sanic import Sanic
from sanic_jwt import Initialize

from app.blueprints import offers_bp
from config import Config

def get_app():
    app = Sanic(__name__)

    Initialize(
        app,
        secret=Config.SECRET,
        cookie_set=True,
        cookie_strict=False,
        auth_mode=False)

    app.config.update(dict(LOGO=Config.LOGO))

    app.blueprint(offers_bp)

    return app


import visa
import numpy
import time
import decimal
import matplotlib.pyplot as plt
import csv
from datetime import datetime
import os
import argparse
import itertools
import sys
import threading

# run if this file is the main program
if __name__ == '__main__':

    print("""

    """)

    parser = argparse.ArgumentParser()
    parser.add_argument('output_folder', type=str, help='Name of folder to dump sweep data.')
    parser.add_argument('start_wavelength', type=int, help='Start wavelength of sweep.  Needs to be an integer.')
    parser.add_argument('stop_wavelength', type=int, help='Stop wavelength of sweep.  Needs to be an integer.')
    parser.add_argument('step_wavelength', type=float, help='Step of sweep in nanometers [nm].')

    args = parser.parse_args()

    rm = visa.ResourceManager()
    resources = rm.list_resources()
    ##print(resources)

    power_meter = rm.open_resource('USB0::0x1313::0x8022::M00521521::INSTR')
    laser = rm.open_resource('GPIB0::1::INSTR')

    '''
    Interface independent commands using
    standardized IEEE 488.2 SCPI commands
    '''
    _SANTEC_CMD_LIST_GPIB = {
        'id?' :                 '*IDN?',
        'sweep_speed?' :        ':SOUR:WAV:SWE:SPE?',
        'ld_enable?' :          ':SOUR:POW:STAT?',
        'ext_trig' :            'SOUR:TRIG:INP:EXT 0',
        'trig_mode' :           ':TRIG:OUTP %d',
        'trig_step' :           ':TRIG:OUTP:STEP %.4f',
        'sweep_status?' :       ':SOUR:WAV:SWE:STAT?',
        'enable_input_trig':    ':SOUR:TRIG:INP:EXT %d',
        'wavelength' :          ':SOUR:WAV %0.4f',
        'power' :               ':SOUR:POW:LEV %0.4f',
        'power_units' :         ':SOUR:POW:UNIT %d',
        'ld_enable' :           ':SOUR:POW:STAT %d',
        'open_shutter' :        ':SOUR:POW:SHUT 1',
        'close_shutter' :       ':SOUR:POW:SHUT 0',
        'sweep_start' :         ':SOUR:WAV:SWE:STAR %.4f',
        'sweep_end' :           ':SOUR:WAV:SWE:STOP %.4f',
        'sweep_step' :          ':SOUR:WAV:SWE:STEP %.4f',
        'sweep_speed' :         ':SOUR:WAV:SWE:SPE %.1f',
        'sweep_mode' :          ':SOUR:WAV:SWE:MOD %d',
        'sweep_number' :        ':SOUR:WAV:SWE:CYCL %d',
        'sweep_delay' :         ':SOUR:WAV:SWE:DEL %.4f',
        'step_dwell' :          ':SOUR:WAV:SWE:DWEL %.4f',
        'start_sweep' :         ':SOUR:WAV:SWE:STAT 1',
        'stop_sweep' :          ':SOUR:WAV:SWE:STAT 0',
        'reset' :               '*RST',
        'wavelength?' :         ':SOUR:WAV?', # get wavelength
        'power?' :              ':SOUR:POW?' # get power
    }

    SANTEC_CMD_TABLE_SERIAL = {
        'id?': '*IDN?',
        'sweep_speed?': 'SN',
        'ext_trig': 'TRE',
        'trig_mode': 'TM%d',
        'trig_step': 'TW%.4f',
        'wavelength': 'WA%.4f',
        'power': 'OP%.4f',
        'open_shutter': 'SO',
        'close_shutter': 'SC',
        'sweep_start': 'SS%.4f',
        'sweep_end': 'SE%.4f',
        'sweep_speed': 'SN%.1f',
        'sweep_mode': 'SM%d',
        'start_sweep': 'SG1',
        'stop_sweep': 'SG0',
        'reset': '*RST',
        'wavelength?': 'WA',  # get wavelength
        'power?': 'OP',
    }

    class SantecTSL550():

        def get_id(self):
            return laser.query('*IDN?')

        def check_shutter(self):
            return int(laser.query(':POW:SHUT?'))

        def open_shutter(self):
            return laser.write(':POW:SHUT 0')

        def close_shutter(self):
            return laser.write(':POW:SHUT 1')

        def get_wavelength(self):
            return float(laser.query(':SOUR:WAV?'))

        def set_wavelength(self, wavelength):
            #print(wavelength)
            return laser.write(':WAV %0.4f' % (wavelength))

        def is_operation_complete(self):
            return laser.query('*OPC?')

    class ThorlabsPM320E():

        def get_id(self):
            return power_meter.query('*IDN?')

        def start_measurement_channel_1(self):
            power_meter.write(':MEAS:INIT1')

        def start_measurement_channel_2(self):
            power_meter.write(':MEAS:INIT2')

        def check_measurement_status_channel_1(self):
            return power_meter.query(':MEAS:CHECK1?')
            # returns unicode aka a string
            # '1\n' means still measuring
            # '0\n' means measurement is done

        def check_measurement_status_channel_2(self):
            return power_meter.query(':MEAS:CHECK2?')
            # returns unicode aka a string
            # '1\n' means still measuring
            # '0\n' means measurement is done

        def get_power_channel_1(self):
            return float(power_meter.query(':FETCH:POW1:VAL?'))

        def get_power_channel_2(self):
            return float(power_meter.query(':FETCH:POW2:VAL?'))

        def is_operation_complete(self):
            return power_meter.query('*OPC?')

        # The 2 methods below in line 161-165 use the 'POW[1,2]:VAL?' command instead, which
        # immediately grabs the power value.
        # Sometimes this causes '+- inf' overflow errors in the Thorlabs OPM.  Mostly w/ short sweeps.
        # A better sequence is implemented as such: set wavelength, wait until wavelength is reached, start
        # measurement, wait until measurement is done, fetch power value, loop back.

        #def get_power_channel_1(self):
        #    return float(power_meter.query(':POW1:VAL?'))

        #def get_power_channel_2(self):
        #    return float(power_meter.query(':POW2:VAL?'))

    # used to interpolate numbers between start and stop points with a floating point (decimal) number step
    def float_range(start, stop, step):
        while start < stop:
            yield float(start)
            start += decimal.Decimal(step)

    # asynchronous spinner displayed when measurements are being taken.
    # creates separate thread for spinner.
    # Google 'python asynchronous progress spinner' to see where I jacked the code from.
    def spinner():
        spinner = itertools.cycle('-/|\\')
        while True:
            sys.stdout.write(spinner.next())  # write the next character
            sys.stdout.flush()  # flush stdout buffer (actual character display)
            sys.stdout.write('\b')  # erase the last written char
            time.sleep(0.05)
            if done:
                return

    '''
    # I tried to get an icon to spin while measuring.  Ended up stalling the program.
    # Spinner uses parallel thread.  Google 'python asynchronous progress spinner' to see
    # where I jacked the code from.

    spinner = itertools.cycle('-/|\\')
    while True:
        sys.stdout.write(spinner.next())  # write the next character
        sys.stdout.flush()  # flush stdout buffer (actual character display)
        sys.stdout.write('\b')  # erase the last written char
        time.sleep(0.05)
    '''

    # objects for Santec laser, thorlabs OPM classes, and args
    s = SantecTSL550()
    t = ThorlabsPM320E()
    start = args.start_wavelength
    stop = args.stop_wavelength
    step = args.step_wavelength

    # open shutter if closed
    if s.check_shutter() == 1:
        s.open_shutter()
        print('Shutter Opened!')

    '''
    # start spinner in separate thread
    done = False
    spin_thread = threading.Thread(target=spinner)
    spin_thread.start()
    '''

    # generate list of wavelengths to be swept
    wavelength_list = list(float_range(start, stop + step, step))
    #print(wavelength_list)

    # create empty list to dump power values into
    power_list = []

    # set wavelength
    counter = 0
    for i in wavelength_list:
        print('Set Wavelength to: %f' % i)
        s.set_wavelength(i)
        #print('Operation not complete if zero: {0}'.format(s.is_operation_complete()))

        while s.is_operation_complete() != '1\n':
            #print('Set operation not complete yet!  Wavelength is now: {0}'.format(s.get_wavelength()))
            time.sleep(0.05)
            counter += 1

            # Sometimes the set_wavelength sets to the correct wavelength, but
            # operation is not marked as complete.
            # This just waits a few cycles and moves on.  The values are correct.
            if counter > 10:
                break

        # reset counter
        counter = 0

        #print('Set operation complete.  Evidence: {0}'.format(s.is_operation_complete()))
        #print('This is the actual wavelength set : %f' % s.get_wavelength())
        #print('Wavelength to be measured: %f' % s.get_wavelength())

        # now that wavelength is set, start measurement
        power_meter.write(':MEAS:INIT1')

        # wait for measurement to complete
        # the string '1\n' means still measuring
        # the string '0\n' means measurement is done
        # sometimes the measurement is so fast it skips this while loop
        while power_meter.query(':MEAS:CHECK1?') == '1\n':
            #print('I am measuring!')
            time.sleep(0.05)
            # time.sleep of 0.05 or 50ms is enough for about one loop.  Shorter times like 0.005 loop more.

        # add fetched power to power_list defined above
        power_list.append(t.get_power_channel_1())
        print('Done measuring!  Appended to list!')

        # print power appended to list
        #print('Fetch: {}'.format(power_meter.query(':FETCH:POW1:VAL?')))

    # create interweaved list of wavelength1, power1, wavelength2, power2, etc...
    power_wavelength_list = [val for pair in zip(wavelength_list, power_list) for val in pair]
    #print(power_wavelength_list)

    # directory creation
    # create 'data' folder with date and time in same directory as this 'sweep.py', then save plot graph and csv there
    the_date_time = datetime.now().strftime('%m-%d-%Y @ %I.%M.%S%p')

    #folder_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '%s', 'data', '%s' % (args.output_folder, the_date_time)))
    folder_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data', '%s %s' % (args.output_folder, the_date_time)))
    #print(folder_path)
    # if folder does not exist, then create it!
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

    # generate and format plot
    fig = plt.figure()

    plt.plot(wavelength_list, power_list)
    #plt.plot(wavelength_list, 10*numpy.log10(power_list*1000))
    plt.title('Thorlabs PM320E OPM Power vs. Santec TSL-550 Laser Wavelength')
    plt.xlabel('Wavelength [nm]')
    plt.ylabel('Power [W]')
    #plt.ylabel('Power [dBm]')
    plt.autoscale(enable=True, axis="y", tight=False)
    plt.grid(which='major', axis='both')

    # save graph and csv
    fig.savefig(os.path.join(folder_path, 'graph.png'))

    data_path = folder_path + "\data.txt"
    file_handle = open(data_path, 'w+')
    file_handle.write(str(power_wavelength_list))
    file_handle.close()

    '''
    # stop spinner and combine threads
    done = True
    spin_thread.join()
    print('Done!')
    '''

    #show plot at end
    plt.show()

'''
spinner = itertools.cycle('-/|\\')
    while True:
        sys.stdout.write(spinner.next())  # write the next character
        sys.stdout.flush()  # flush stdout buffer (actual character display)
        sys.stdout.write('\b')  # erase the last written char
        time.sleep(0.05)
'''

'''
# Laser takes time to move, so sometimes it's not yet in place.
# Usually the small step size and fast laser sweep are quick enough to skip this while loop.
while s.get_wavelength() != i:

    # Santec sometimes gets stuck on a previous wavelength and then gets trapped in this while loop
    # b/c the loop is waiting for the current wavelength.  Santec gets stuck b/c the first
    # 's.set_wavelength(i)' is not recieved, possibly b/c it's busy with a previous command.
    # A counter keeps track of the santec delay and if it hangs too long (10 is arbitrary) the desired
    # wavelength is set again.
    # If counter is set to 100, the wavelength usually sets itself around the 50th count, however
    # if counter is set to 10, the wavelength usually sets itself around the 13th count.
    # It appears that either waiting or spamming the OPM works, though there may be deeper implications
    # here.
    # There's a lot to be said about this stupid counter.
    if counter > 10:
        s.set_wavelength(i)
        print('This wavelength was set again: {0}'.format(s.set_wavelength(i)))

    print('Number of loops waiting for wavelength to reach set_wav: %d' % counter)
    counter += 1

# reset counter to 0 when while loop is exited
counter = 0
'''

'''
print('Query: {}'.format(power_meter.query(':POW1:VAL?')))
#print(power_meter.query(':FETCH:POW1:VAL?'))

print('Init Meas.')
power_meter.write(':MEAS:INIT1')

while power_meter.query(':MEAS:CHECK1?') == '1\n':
    print('I am measuring!')
    time.sleep(0.05)

print(power_meter.query(':MEAS:CHECK1?'))

print('Fetch: {}'.format(power_meter.query(':FETCH:POW1:VAL?')))

date_time = str(datetime.datetime.now())
results_dir = os.path.join('data',"%s_%s-%s-%s" % (args.output_folder, date_time[0:10], date_time[11:13], date_time[14:16]))

if not os.path.exists(results_dir):
    os.makedirs(results_dir)

power_wavelength_list.write_to_file("%s/%s" % (results_dir, "data.csv"))
power_wavelength_list.write_plot_to_file("%s/%s" % (results_dir, "plot.png"), show = True, write = True)
print "Dumped data in %s" % (results_dir)

# interweave two lists of equal length
l1 = [1,2,3,4,5,6,7,8,9]
l2 = [1,2,3,4,5,6,7,8,9]

print([val for pair in zip(l1,l2) for val in pair])

# alternative step number generator but is more complicated,
# working with number of samples rather than step size.
samples = 1 / step * (stop - start) + 1
for i in numpy.linspace(start, stop, num=samples, endpoint=True, retstep=True):
     print(i)

'''


import json

class GradeEncoder(json.JSONEncoder):
    def default(self, obj):
        return {"Course": obj.course,
                "Title": obj.title,
                "Period": obj.period,
                "Letter": obj.letter,
                "Score": obj.score,
                "Teacher": obj.teacher
               }

def output(grades):
    print(json.dumps(grades, cls=GradeEncoder))


from django.urls import path
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
    TokenVerifyView
)

from api.v1.views import RoomViewSet, MessageViewSet

urlpatterns = [
    path("token/", TokenObtainPairView.as_view(), name="token_obtain_pair"),
    path("refresh/", TokenRefreshView.as_view(), name="token_refresh"),
    path("verify/", TokenVerifyView.as_view(), name="token_verify"),
    path("room/", RoomViewSet.as_view({'get': 'list', 'post': 'create'})),
    path("room/<pk>/messages", MessageViewSet.as_view({'get': 'list'}))
]


from django.db import models

from utils.helpers import upload_image, optimize_image

# Create your models here.

class Beneficiary(models.Model):
    REQUIRED_IMAGE_RATIO = (350, 200)

    image = models.ImageField(upload_to=upload_image)
    image_date = models.DateField(help_text="Image clicked date")
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = "Beneficiaries"

    def __str__(self):
        return f"{self.image_date}"

    def save(self, *args, **kwargs):
        self.image_date = self.image_date if self.image_date else self.created.date()
        super(Beneficiary, self).save(*args, **kwargs)
        optimize_image(self.image, self.REQUIRED_IMAGE_RATIO)


import json
import shutil
import os
import cv2
import numpy as np
from pathlib import Path
from random import shuffle

def save_cmu_split_indices(train_per=0.95, save_dir=(Root_Dir / "src/HandEst/data/Public_HandData/CMU_Panoptic/split_indices")):
    cmu_labels_path = (Root_Dir / "src/HandEst/data/Public_HandData/CMU_Panoptic/hand143_panopticdb/hands_v143_14817.json").as_posix()
    labels = json.load(open(cmu_labels_path,"r"))
    labels_list = labels['root']
    num_indices = len(labels_list)
    indices = np.arange(start=0, stop=num_indices)
    shuffle(indices)

    train_indices = indices[0:int(num_indices*train_per)]
    val_indices = indices[int(num_indices*train_per)::]

    train_per_int = int(train_per*100)
    train_sp = Path(save_dir) / f"train_indices_{train_per_int}.npy"
    np.save(train_sp.as_posix(), train_indices)
    val_sp = Path(save_dir) / f"val_indices_{100-train_per_int}.npy"
    np.save(val_sp.as_posix(),val_indices)

def visualize_box(image, x_center, y_center, box_w, box_h):
    img_h,img_w, _ = image.shape
    x_center *= img_w
    y_center *= img_h
    box_h *= img_h
    box_w *= img_w
    pt1 = (int(x_center-(box_w/2)),int(y_center-(box_h/2)))
    pt2 = (int(x_center+(box_w/2)),int(y_center+(box_h/2)))

    image = cv2.rectangle(image, pt1=pt1,pt2=pt2, color=[0,255,0], thickness=3)
    cv2.imshow('test', image)
    cv2.waitKey()
    return
def convert_cmu_data_2_yolo(train_indices, val_indices):
    #right hand class is custom yolo class
    hand_class = 0

    #load cmu labels
    cmu_labels_path = (Root_Dir / "src/HandEst/data/Public_HandData/CMU_Panoptic/hand143_panopticdb/hands_v143_14817.json").as_posix()
    labels = json.load(open(cmu_labels_path,"r"))
    cmu_image_dir = (Root_Dir / "src/HandEst/data/Public_HandData/CMU_Panoptic/hand143_panopticdb/imgs").as_posix()

    #create yolo dataset dir
    yolo_dir = Path("/home/inseer/Research/yolov7/CMU_Panoptic")
    yolo_dir.mkdir(exist_ok=True ,parents=True)
    yolo_img_dir = yolo_dir / "images"
    yolo_img_dir.mkdir(exist_ok=True)
    (yolo_img_dir / "train").mkdir(exist_ok=True)
    (yolo_img_dir / "val").mkdir(exist_ok=True)
    yolo_label_dir = yolo_dir / "labels"
    yolo_label_dir.mkdir(exist_ok=True)
    (yolo_label_dir / "train").mkdir(exist_ok=True)
    (yolo_label_dir / "val").mkdir(exist_ok=True)

    labels_list = labels['root']

    #create train/val catalogues
    train_cat_path = (yolo_dir / "train.txt").as_posix()
    val_cat_path  = (yolo_dir / "val.txt").as_posix()
    train_cat = open(train_cat_path,"w")
    val_cat = open(val_cat_path,"w")

    for e_i, entry in enumerate(labels_list):
        #get cmu annotation data
        img_path = Path(entry['img_paths'])
        img_ext = img_path.suffix
        img_name = img_path.with_suffix('').name
        img_h, img_w = entry['img_height'], entry['img_width']
        bbox_center = entry['objpos']
        bbox_scale = entry['scale_provided']
        #new data for yolo txt file
        x_center, y_center = np.round(np.asarray(bbox_center)).astype(dtype=int)
        square_len = np.round(175*bbox_scale).astype(dtype=int)
        box_h , box_w = 2*square_len, 2*square_len
        #normalize data
        x_center = np.round(x_center / img_w, 4)
        y_center = np.round(y_center / img_h, 4)
        box_w = np.round(box_w / img_w, 4)
        box_h = np.round(box_h / img_h, 4)
        #write data to txt file
        val_ann = True if e_i in val_indices else False
        if val_ann:
            txt_path = (yolo_label_dir / f"val/{img_name}").with_suffix('.txt')
        else:
            txt_path = (yolo_label_dir / f"train/{img_name}").with_suffix('.txt')

        with open(txt_path.as_posix(), 'w') as file:
            file.write(f"{hand_class} {x_center} {y_center} {box_w} {box_h}\n")

        #copy image
        img_path = (Path(cmu_image_dir) / img_name).with_suffix(img_ext)
        if val_ann:
            new_img_path = (yolo_img_dir / f"val/{img_name}").with_suffix(img_ext)
            rel_path = f"./images/val/{img_name}{img_ext}"
            val_cat.write(f"{rel_path}\n")

        else:
            new_img_path = (yolo_img_dir / f"train/{img_name}").with_suffix(img_ext)
            rel_path = f"./images/train/{img_name}{img_ext}"
            train_cat.write(f"{rel_path}\n")

        shutil.copy(src=img_path.as_posix(), dst=new_img_path.as_posix())

        #test annotation
        # image = cv2.imread(img_path.as_posix())
        # visualize_box(image, x_center,y_center,box_w,box_h)
        # print(entry["img_paths"])
    train_cat.close()
    val_cat.close()

if __name__ == "__main__":
    train_indices = np.load(
        (Root_Dir / "src/HandEst/data/Public_HandData/CMU_Panoptic/split_indices/train_indices_95.npy").as_posix(),
        allow_pickle=True)
    val_indices = np.load(
        (Root_Dir / "src/HandEst/data/Public_HandData/CMU_Panoptic/split_indices/val_indices_5.npy").as_posix(),
        allow_pickle=True)

    convert_cmu_data_2_yolo(train_indices,val_indices)


'''Peça ao usuário o valor em Fahrenheit, converta para Celsius e faça um bloco de condicionais, informando as seguintes questões, se o valor em Celsius estiver entre 20 e 25 graus, mande o usuário sair de bermuda, se estiver entre 19 e 15, mande ele levar um casaco, se estiver entre 0 e 14 mande ele assistir Netflix e tomar um café. Lembre-se, use sua criatividade, construa um terminal interativo para o usuário, peça o seu nome, por exemplo, faça seu código com qualidade.'''

#Entrada
F = float(input(f'Informe a temperatura em Fahrenheit: '))

#Processamento
C = (5/9)*(F-32)
C = round(C, 2)

#Saída
if C >25:
    print(f'Hoje é dia de praia, com essa temperatura.')
elif 25<= C >=20:
    print(f'A temperatura está boa para sair de bermuda.')
elif 19<= C >=15:
    print(f'É melhor levar um casaco com essa temperatura.')
elif 14<= C >=0:
    print(f'Fique em casa, assitindo um Neflix e tomando um café, pois a temperatura tá barril.')


import pandas as pd
import numpy as np
import sys

# load the dataset
df = pd.read_csv(sys.argv[1], index_col=0)

# Transpose the dataframe before one-hot encoding
df_transposed = df.transpose()

# Create an empty DataFrame to store the one-hot encoded data
one_hot_df_transposed = pd.DataFrame(index=df_transposed.index)

# Iterate through the columns of the transposed DataFrame to perform custom one-hot encoding
for col in df_transposed.columns:
    unique_values = df_transposed[col].unique()
    # Skip encoding for 'N' alleles
    unique_values = [val for val in unique_values if val != 'N']
    for unique_value in unique_values:
        new_col_name = f"{col}_{unique_value}"
        one_hot_df_transposed[new_col_name] = (df_transposed[col] == unique_value).astype(int)
    # Set to 'nan' where 'N' allele is present
    if 'N' in df_transposed[col].unique():
        n_indices = df_transposed[df_transposed[col] == 'N'].index
        for unique_value in unique_values:
            new_col_name = f"{col}_{unique_value}"
            one_hot_df_transposed.loc[n_indices, new_col_name] = np.nan

# Replace empty cells with 'nan'
one_hot_df_transposed.replace(np.nan, 'nan', inplace=True)

# Save the modified DataFrame to a CSV file
one_hot_df_transposed.to_csv(sys.argv[2])


#!/usr/bin/env python
from __future__ import print_function
import os
import argparse
import textwrap
import numpy as np
import dictlearn as dl

class ImageOpen(argparse.Action):
    def __init__(self, option_strings, dest, nargs=None, **kwargs):
        super(ImageOpen, self).__init__(option_strings, dest, **kwargs)

    def __call__(self, parser, namespace, path, option_string=None):
        if path is None:
            setattr(namespace, self.dest, (None, None))

        if not os.path.isfile(path):
            raise ValueError('Cannot find image %s' % path)

        _, ext = os.path.splitext(path)

        if ext == '.npy':
            image = np.load(path)
        else:
            image = dl.imread(path)

        setattr(namespace, self.dest, (image, path))

def is_rgb(image):
    """
        Check if an image is RGB type. True mean probably True,
        False definitely not RGB image
    """
    return (
        image.ndim == 3 and image.shape[-1] == 3
        and image.min() >= 0 and image.max() <= 255
    )

def subtract_mask(image, drawing):
    """
        Create a mask by drawing on the image drawing, then extract this
        mask by subtracting image from drawing

    :param image:
        Original image
    :param drawing:
        Original image with mask drawn on top
    :return:
        Difference of drawing and image
    """
    if is_rgb(drawing):
        drawing = dl.rgb2gray(drawing)

    if is_rgb(image):
        image = dl.rgb2gray(image)
        thresh = 3
        return np.abs(drawing - image) < thresh

    if image.ndim == 2 and drawing.ndim == 3 and drawing.shape[2] == 3:
        drawing = dl.rgb2gray(drawing)
        thresh = 0.5
    else:
        raise ValueError('Incompatible shapes, {} and {}'
                         .format(image.shape, drawing.shape))

    return np.abs(drawing - image) < thresh

def extract_color(image, color):
    assert image.dtype.kind in 'iu', 'Need image of integer type'

    if image.ndim == 3:
        if image.shape[2] in [3, 4]:
            # RGB[A] image
            if len(color) == 1:
                color.append(color[0])
                color.append(color[0])
            elif len(color) != 3:
                raise ValueError('Need RGB color for RGB image, not {}'
                                 .format(color))
            if image.shape[2] == 4:
                # RGBA - Discard alpha
                image = image[:, :, :-1]

            mask = np.logical_not(np.all(image[:, :] == color, axis=2))
        else:
            # Standard 3D image
            if len(color) != 1:
                raise ValueError('Can only take one color value for greyscale image, not'
                                 ' {}'.format(len(color)))

            mask = image[:, :, :] != color[0]
    elif image.ndim == 2:
        # 2D greyscale
        if len(color) != 1:
            raise ValueError('Cannot extract color {} from greyscale image, color '
                             'has to be a single number, grey value'.format(color))

        mask = image[:, :] != color[0]
    else:
        raise ValueError('Can only extract mask from 2D or 3D images, not {}D'
                         .format(image.ndim))

    return mask

def create_geometry(image, point):
    # todo finish
    raise NotImplementedError()

def write_mask(mask, path, output=None):
    if output is None:
        name, ext = os.path.splitext(path)
        output = '{}_mask{}'.format(name, ext)

    _, ext = os.path.splitext(output)

    if ext == '.npy':
        np.save(output, mask)
    else:
        dl.imsave(output, mask)

    print('Mask saved to: {}'.format(output))

if __name__ == '__main__':
    description = textwrap.dedent("""\
    Script for creating a boolean mask for some image

    Possible ways of creating the mask:

    Drawing:
        If '--drawing path/to/some/image' argument is used the it's
        assumed that 'path/to/some/image' is the input image with
        some drawing up top. The drawing image should be RGB for
        the best results (input image need not be). The mask is
        created by subtracting the input image from the drawing.

    Extract colored region:
        If '--color R G B' argument is set then every pixel in the
        input image is marked for inpainting if its color is identical
        to [R, G, B]. The input image should be RGB for the best
        results. It's possible for the input image to be grayscale and
        then extract a single color value, but the results from this
        will not be as good

    Random mask:
        If '--random' is used then a random mask is created.
        The number of pixels marked for inpainting is determined
        by '--ratio [0.0 - 1.0]'. If ratio is set to 0.7 then
        30%% of the pixels will be removed.

    Points:
        Not used
    """)

    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )

    parser.add_argument(
        'input', type=str, action=ImageOpen, help='Create mask for this image'
    )

    parser.add_argument(
        '-d', '--drawing', type=str, action=ImageOpen,
        help='Image with mask drawn on top. Input image '
             'is subtracted from this to create the mask'
    )

    parser.add_argument(
        '-c', '--color', nargs='+', type=int,
        help='RGB Color. Mark every thing in input image of this color as mask'
    )

    parser.add_argument(
        '-p', '--point', nargs='*', type=str,
        help='List of points, to mark the boundaries of the mask '
             'Two points: Line, three points: Triangle, four points: Box'
    )

    parser.add_argument(
        '-r', '--random', action='store_true',
        help='Create random mask for image, adjust corrution level with --ratio'
    )

    parser.add_argument(
        '--ratio', type=float, default=0.5,
        help=r'How many of the pixels to keep if random mask. 0.7 keeps 70%% of the '
             'original data, and removes 30%%'
    )

    parser.add_argument(
        '-o', '--output', type=str, help='Where to save the mask, with image format.'
    )

    args = parser.parse_args()

    inp_image, inp_path = args.input

    mask = None

    if args.drawing is not None:
        mask = subtract_mask(inp_image, args.drawing[0])
    elif args.color is not None:
        mask = extract_color(inp_image, args.color)
    elif args.point is not None:
        mask = create_geometry(inp_image, args.point)
    elif args.random:
        if not is_rgb(inp_image) and inp_image.ndim == 3:
            raise SystemExit('Cannot create random mask from 3D image')
        h, w = inp_image.shape
        mask = np.random.rand(h, w) < args.ratio
    else:
        raise SystemExit(
            'Cannot create mask. Need at least one method for generating the mask.\n'
            'Run: python {} --help'.format(parser.prog)
        )

    write_mask(mask, inp_path, args.output)


# Third-party
import astropy.units as u
import astropy.coordinates as coord
from astropy.tests.helper import quantity_allclose
import numpy as np
import pytest

# Project
from ..reference_plane import ReferencePlaneFrame

def test_sanity():

    rep1 = coord.CartesianRepresentation(x=[0, 1.],
                                         y=0,
                                         z=0, unit=u.pc)

    rep2 = coord.CartesianRepresentation(x=0,
                                         y=[0, 1.],
                                         z=0, unit=u.pc)

    rep3 = coord.CartesianRepresentation(x=0,
                                         y=0,
                                         z=[0, 1.], unit=u.pc)

    # Try for many origins:
    rnd = np.random.RandomState(seed=42)

    for _ in range(128):
        origin = coord.ICRS(ra=rnd.uniform(0, 360)*u.deg,
                            dec=rnd.uniform(-90, 90)*u.deg,
                            distance=rnd.uniform(10, 100)*u.pc)

        ref_c = ReferencePlaneFrame(rep1, origin=origin)
        icrs = ref_c.transform_to(coord.ICRS)
        assert icrs.dec[1] > icrs.dec[0]
        assert quantity_allclose(icrs.ra[0], icrs.ra[1])

        ref_c = ReferencePlaneFrame(rep2, origin=origin)
        icrs = ref_c.transform_to(coord.ICRS)
        assert icrs.ra[1] > icrs.ra[0]

        ref_c = ReferencePlaneFrame(rep3, origin=origin)
        icrs = ref_c.transform_to(coord.ICRS)
        assert icrs.distance[0] > icrs.distance[1]
        assert quantity_allclose(icrs.ra[0], icrs.ra[1])
        assert quantity_allclose(icrs.dec[0], icrs.dec[1])

def test_transform():
    rep = coord.CartesianRepresentation(x=1, y=2, z=3, unit=u.pc)
    ref_c1 = ReferencePlaneFrame(rep)

    with pytest.raises(ValueError):
        ref_c1.transform_to(coord.ICRS)

    with pytest.raises(ValueError):
        ref_c2 = ReferencePlaneFrame(rep, origin=coord.Galactic())


import sys

sys.stdin = open('input.txt')

code = {
    '0001101': '0', '0011001': '1', '0010011': '2',
    '0111101': '3', '0100011': '4', '0110001': '5',
    '0101111': '6', '0111011': '7', '0110111': '8', '0001011': '9',
}

T = int(input())
for t in range(1, T+1):
    N, M = map(int, input().split())
    code_ls = [input() for _ in range(N)]
    k = 0
    sum_odd = 0 # 홀수
    sum_even = 0 #짝수
    answer = 0

    for check in code_ls:
        if '1' in check:
            for i in range(M-1, 1, -1):
                if check[i] == '1' and k == 0:
                    k = i
                    break

            start = k - 56 + 1
            for i in range(1, 9):
                result = check[start:start+7]
                start += 7
                if i % 2 == 1:  # 홀수 자리
                    sum_odd += int(code[result])
                else:   # 짝수 자리
                    sum_even += int(code[result])
            break

    if (sum_odd * 3 + sum_even) % 10 == 0:
        answer = sum_odd + sum_even

    print(f'#{t} {answer}')


from tkinter import * # import 111 是与111模块相关联，调用其中文件是111.kk
# from 222 import * 是说把222所有的东西化为本模块的东西，可以直接调用其中的文件
# from 222 import ccc 是说从222中调用ccc

app=Tk()
app.title("TVN Game Show")
app.geometry('300x100+200+100')

b1=Button(app,text="correct",width=10)
b1.pack(side='left',padx=10,pady=10)#pack是一种方法确定b1的位置

b2=Button(app,text="wrong",width=10)
b2.pack(side='right',padx=10,pady=10)

app.mainloop


import unittest

from .puzzle13 import *

class ComputerTest(unittest.TestCase):
    def xtest_execute(self):
        intcode = (109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101,
                   1006, 101, 0, 99)
        inputs = []
        outputs = Computer(intcode).execute(inputs)
        self.assertSequenceEqual(outputs, intcode)

    def test_process_outputs(self):
        outputs = (1,2,3,6,5,4)
        tiles, _ = process_outputs(outputs)
        self.assertEqual(len(tiles), 2)

        tile1, tile2 = tiles
        self.assertEqual(type(tile1), HorizontalPaddleTile)
        self.assertEqual((tile1.x, tile1.y), (1, 2))

        self.assertEqual(type(tile2), BallTile)
        self.assertEqual((tile2.x, tile2.y), (6, 5))


import Seq1
import jinja2
import pathlib
import json
import http.client

DICT_GENES = {"FRAT1": "ENSG00000165879",
         "ADA": "ENSG00000196839",
         "FXN": "ENSG00000165060",
         "RNU6_269P": "ENSG00000212379",
         "MIR633": "ENSG00000207552",
         "TTTY4C": "ENSG00000228296",
         "RBMY2YP": "ENSG00000227633",
         "FGFR3": "ENSG00000068078",
         "KDR": "ENSG00000128052",
         "ANK2": "ENSG00000145362"
         }

def read_template_html_file(filename):
    content = jinja2.Template(pathlib.Path(filename).read_text())
    return content

def print_colored(message, color):
    import termcolor
    import colorama
    colorama.init(strip="False")
    print("To server: ", end="")
    print(termcolor.colored(message, color))

def format_command(command):
    return command.replace("\n", "").replace("\r", "")

def get_json(endpoint):
    SERVER = "rest.ensembl.org"
    PARAMETERS = "?content-type=application/json"
    connection = http.client.HTTPConnection(SERVER)
    connection.request("GET", endpoint + PARAMETERS)
    response = connection.getresponse()
    return json.loads(response.read().decode())

def list_sp(limit):
    list_species = get_json("/info/species")["species"]
    context = {"length": len(list_species)}
    try:
        context["limit"] = min(int(limit), context["length"])
        context["common_name"] = []
        for e in list_species[:min(int(limit), context["length"])]:
            context["common_name"].append(e["common_name"].capitalize())
        return context
    except:
        return {"error": "Need an integer for limit parameter"}

def karyotype(specie):
    try:
        context = {"list_karyotype": get_json("/info/assembly/" + specie)["karyotype"], "specie": specie}
        return context
    except KeyError:
        context = {"error": "Need the name of a valid species for karyotype"}
        return context

def chromo_len(specie, chromo):
    response = get_json("/info/assembly/" + specie)
    context = {"specie": specie, "chromosome": chromo}
    try:
        for d in response["top_level_region"]:
            if d["coord_system"] == "chromosome" and d["name"] == chromo:
                context["length"] = d["length"]
        return context
    except KeyError:
        context["error"] = "Need the name of a valid species and chromosome"
        return context

def seq(gene_name):
    response = get_json("/sequence/id/" + DICT_GENES[gene_name])
    seq = Seq1.Seq(response["seq"])
    return seq

def info(gene_name):
    response = get_json("/sequence/id/" + DICT_GENES[gene_name])
    desc = response["desc"].split(":")
    context = {"gene_name": gene_name, "start": desc[3], "chr_name": desc[1], "end": desc[4], "length": int(desc[4]) - int(desc[3]), "id": response["id"]}
    return context

def calc(gene_name):
    sequence = seq(gene_name)
    context = {"gene_name": gene_name, "length": sequence.len(), "perc_dict": sequence.count_percentage()}
    return context


import numpy as np

def split(word):
    return [ch for ch in word]

datos = open('input3.txt').read().split("\n")
datos = [split(i) for i in datos]
datos = np.transpose(datos)

gamma = ''
epsilon = ''

for i in datos:
    conteo_1 = 0
    conteo_0 = 0
    for j in i:
        if j == "1":
            conteo_1 += 1
        else:
            conteo_0 += 1
    if conteo_1 > conteo_0:
        gamma += "1"
        epsilon +="0"
    else:
        gamma += "0"
        epsilon +="1"

gamma_decimal = 0
for digit in gamma:
    gamma_decimal = gamma_decimal*2 + int(digit)

epsilon_decimal = 0
for digit in epsilon:
    epsilon_decimal = epsilon_decimal*2 + int(digit)

print('gamma: ', gamma_decimal, " epsilon: ", epsilon_decimal, " total: ", gamma_decimal * epsilon_decimal)


#
# @lc app=leetcode id=1822 lang=python3
#
# [1822] Sign of the Product of an Array
#

# @lc code=start
class Solution:
    def arraySign(self, nums: List[int]) -> int:
        s=1
        for i in nums:
            s*=i
        if s>0:
            return 1
        elif s==0:
            return 0
        else :
            return -1

# @lc code=end