import pennylane as qml
from pennylane import numpy as np

num_wires = 5
dev1 = qml.device('default.qubit', wires=num_wires)

@qml.qnode(dev1)
def circuit():
	output = []

	# Encoding the data (Variational Encoding)
	qml.RX(1.01, wires=[0])
	qml.RX(0.81, wires=[1])
	qml.RX(0.81, wires=[2])
	qml.RX(1.3e-2, wires=[3])
	qml.RX(0.16, wires=[4])

	qml.RZ(1.01, wires=[0])
	qml.RZ(0.81, wires=[1])
	qml.RZ(0.81, wires=[2])
	qml.RZ(1.3e-2, wires=[3])
	qml.RZ(0.16, wires=[4])

	# Making the Parameterised QUantum Circuit (PQC)
	qml.RX(1.10, wires=[0])
	qml.RZ(0.75, wires=[0])
	qml.CNOT(wires=[0, 1])
	qml.RX(0.82, wires=[0])
	qml.RX(0.84, wires=[1])
	qml.RZ(0.53, wires=[0])
	qml.RZ(0.81, wires=[1])
	qml.CNOT(wires=[1, 2])
	qml.CNOT(wires=[0, 1])
	qml.RX(0.60, wires=[2])

	qml.RX(0.56, wires=[1])
	qml.RZ(0.98, wires=[2])
	qml.RZ(0.93, wires=[1])
	qml.CNOT(wires=[2, 3])
	qml.CNOT(wires=[1, 2])
	qml.RX(0.34, wires=[3])

	qml.RX(0.21, wires=[2])
	qml.RZ(1.20, wires=[3])
	qml.RZ(8.7e-2, wires=[2])
	qml.CNOT(wires=[3, 4])
	qml.CNOT(wires=[2, 3])
	qml.RX(0.90, wires=[4])

	qml.RX(-0.18, wires=[3])
	qml.RZ(0.49, wires=[4])
	qml.RZ(0.83, wires=[3])
	qml.CNOT(wires=[3, 4])

	qml.RX(0.72, wires=[4])
	qml.RZ(87, wires=[4])

	for i in range(num_wires):
		output.append(qml.expval(qml.PauliZ(i)))

	return output

print(circuit())


# from typing_extensions import ParamSpec
from .Database import Database

class DataRepository:
    @staticmethod
    def json_or_formdata(request):
        if request.content_type == 'application/json':
            gegevens = request.get_json()
        else:
            gegevens = request.form.to_dict()
        return gegevens

# relays

    @staticmethod
    def read_status_relays():
        sql = "SELECT h.actuatorId, h.Datum, h.status_actuator FROM historiek as h WHERE Datum = (SELECT MAX(Datum) FROM historiek WHERE actuatorId = h.actuatorId GROUP BY actuatorId) order by actuatorId"
        return Database.get_rows(sql)

    @staticmethod
    def read_status_relay_by_id(id):
        sql = "SELECT historiekId, datum, status_actuator, commentaar, actuatorId, actieId  from historiek WHERE actuatorId = %s ORDER BY Datum DESC LIMIT 1;"
        params = [id]
        return Database.get_one_row(sql, params)

    @staticmethod
    def insert_status_relay(datum, status, actuatorid, actieId):
        sql = "INSERT INTO historiek (datum, status_actuator, actuatorId, actieId) VALUES (%s, %s, %s, %s)"
        params = [datum, status, actuatorid, actieId]
        return Database.execute_sql(sql, params)

# historiek sensors
    @staticmethod
    def read_historiek():
        sql = "SELECT * from historiek"
        return Database.get_rows(sql)

    @staticmethod
    def read_historiek_by_sensor_id(id):
        sql = "SELECT * from historiek WHERE sensorId = %s"
        params = [id]
        return Database.get_rows(sql, params)

    @staticmethod
    def read_historiek_by_sensor_id_last(id):
        sql = "SELECT * from historiek WHERE sensorId = %s ORDER BY Datum DESC LIMIT 1;"
        params = [id]
        return Database.get_rows(sql, params)

    @staticmethod
    def read_historiek_last_24_hours(id):
        sql = "SELECT * FROM historiek WHERE sensorId = %s AND datum >= NOW() - INTERVAL 1 DAY"
        params = [id]
        return Database.get_rows(sql, params)

    @staticmethod
    def read_historiek_last_24_hours_every_hour(id):
        sql = "SELECT * FROM historiek WHERE sensorId = %s AND datum >= NOW() - INTERVAL 1 DAY GROUP BY DATE(datum), HOUR(datum)"
        params = [id]
        return Database.get_rows(sql, params)

    @staticmethod
    def read_historiek_by_date(id, startdate, enddate):
        sql = "SELECT * FROM historiek WHERE sensorId = %s AND datum between %s and %s"
        Params = [id, startdate, enddate]
        return Database.get_rows(sql, Params)

    @staticmethod
    def insert_historiek(datum, value, commentaar, sensorid, actieId):
        sql = "INSERT INTO historiek (datum, waarde_sensor, commentaar, sensorId, actieId) VALUES (%s, %s, %s, %s, %s)"
        params = [datum, value, commentaar, sensorid, actieId]
        return Database.execute_sql(sql, params)


input_list = input("Введіть список чисел розділених комою: ")

list = [int(x.strip()) for x in input_list.split(',')]

if len(list) == 0:

    list1 = []
    list2 = []
else:
    half = len(list) // 2
    list1 = list[:half]
    list2 = list[half:]
    if len(list) % 2 != 0:
        list2 = list[half+1:]

split_lists = [list1, list2]
print(split_lists)


# -*- coding: utf-8 -*-
"""
Created on Tue Nov  6 09:09:32 2018

@author: nivosco
"""

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

class LossHistory(tf.keras.callbacks.Callback):
    def on_train_begin(self, logs={}):
        self.losses = []
        self.val_losses = []
    def on_batch_end(self, batch, logs={}):
        self.losses.append(logs.get('loss'))
        self.val_losses.append(self.model.evaluate(self.validation_data[0], self.validation_data[1])[0])

class cnn_model:
    def __init__(self,input_shape, num_classes):
        self.model = tf.keras.models.Sequential()
        self.model.add(tf.keras.layers.Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=input_shape))
        self.model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu'))
        self.model.add(tf.keras.layers.MaxPool2D(pool_size=(2, 2)))
        self.model.add(tf.keras.layers.Dropout(0.25))
        self.model.add(tf.keras.layers.Flatten())
        self.model.add(tf.keras.layers.Dense(128, activation='relu'))
        self.model.add(tf.keras.layers.Dropout(0.5))
        self.model.add(tf.keras.layers.Dense(num_classes, activation='softmax'))
    def compile(self):
        self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
    def train(self,x_train,y_train,batch_size,epochs,x_test,y_test):
        self.lossHistory = LossHistory()
        self.model.fit(x_train, y_train,batch_size=batch_size,epochs=epochs,verbose=1, validation_data=(x_test, y_test), callbacks=[self.lossHistory])

def lossPlot(cnn_model):
    plt.plot(np.arange(0,len(cnn_model.lossHistory.losses)),cnn_model.lossHistory.losses,'r',label='Train loss')
    plt.plot(np.arange(0,len(cnn_model.lossHistory.val_losses)),cnn_model.lossHistory.val_losses,'b',label='Validation loss')
    plt.title('Loss function convergence graph')
    plt.xlabel('Batch')
    plt.ylabel('Loss')
    plt.legend()
    plt.savefig('loss.png')
    plt.show()

## Parameters
batch_size = 128
num_classes = 10
epochs = 1
img_rows, img_cols = 28, 28

## Read the training set
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(-1,img_rows,img_cols,1)
x_test = x_test.reshape(-1,img_rows,img_cols,1)

## build, train and evaluate the models
cnn_model = cnn_model((img_rows,img_cols,1),num_classes)
cnn_model.compile()
cnn_model.train(x_train,y_train,batch_size,epochs,x_test,y_test)

## plot the loss function
lossPlot(cnn_model)


# coding: utf-8
import os
import json

def load_actor_list():
    """
    将演员姓名存入列表
    :return: actor_list
    """
    actor_list = []
    with open("./actor.txt","r") as r:
        lines = r.readlines()
        for line in lines:
            line = line.strip('\n')
            actor_list.append(line)
    # print(actor_list)
    return actor_list

def load_totaloffice_attributes(actor_list):
    """
    计算演员经验值指标
    :param actor_list:
    :return: actor_experience
    """
    actor_experience = {}
    experience = {}
    for name in actor_list:
        filename = "./actor_office/" + name + ".json"
        if os.path.exists(filename):
            with open(filename,"r") as r:
                count = 0
                per_acotr = json.load(r)
                # print(per_acotr)
                for per_movie in per_acotr:
                    office = per_movie['office']
                    if office == 'null':
                        office = 0
                    else:
                        office = int(office.replace("万",""))
                    count += office
                actor_experience[name] = count
    # print(actor_experience)
    max_office,min_office = evaluate(actor_experience)
    for name in actor_experience.keys():
        sorce = normalized(actor_experience[name],max_office,min_office)
        experience[name] = sorce
    print("Empirical indicator: \n")
    print(experience)
    return experience

def load_time_attributes(star,end,actor_list):
    """
    计算时效性指标
    :param star:
    :param end:
    :param actor_list:
    :return:
    """
    # 获取该段时间内设计该演员的新闻数量
    actor_new = {}
    for name in actor_list:
        filename = "./new/" + name + ".txt"
        if os.path.exists(filename):
            count = 0
            with open(filename,"r") as r:
                news = r.readlines()
                for new in news:
                    new = new.strip('\n')
                    year = new.split('\t')[0]
                    num = new.split('\t')[1]
                    if int(year) >= star and int(year) <= end:
                        count += int(num)
                actor_new[name] = count

    # 获取该段时间内演员的票房数量
    actor_office = {}
    for name in  actor_list:
        filename = "./actor_office/" + name + ".json"
        if os.path.exists(filename):
            count = 0
            with open(filename,"r") as r:
                per_actor = json.load(r)
                for per_movie in per_actor:
                    if per_movie['year'] >= star and per_movie['year'] <= end:
                        office = per_movie['office']
                        if office == 'null':
                            office = 0
                        else:
                            office = int(office.replace("万", ""))
                        count += office
                actor_office[name] = count

    # 计算时效性指标
    max_office, min_office = evaluate(actor_office)
    max_new, min_new = evaluate(actor_new)
    time = {}
    for name in actor_list:
        if name in actor_office.keys() and name in actor_new.keys():
            sorce_office = normalized(actor_office[name],max_office,min_office)
            sorce_new = normalized(actor_new[name],max_new,min_new)
            time[name] = sorce_office + sorce_new
    print("Timeliness indicator: \n")
    print(time)
    return time

def load_actieve(actor_list,star,end):
    baidu = {}
    actieve = {}
    with open("./record.txt","r") as r:
        lines = r.readlines()
        for line in lines:
            line = line.strip('\n')
            flag = line.split(' ')[-1]
            names = line.split(' ')[0:-1]
            name = ''
            for i in names:
                name += i
            baidu[name] = flag
    # print(baidu)
    for name in actor_list:
        filename = "./演员活跃度/" + name + '.txt'
        if os.path.exists(filename) and name in baidu.keys():
            with open(filename, "r") as r:
                sorce = 0
                wei = 0
                aware = 0
                bai = 0
                lines = r.readlines()
                for line in lines:
                    line = line.strip('\n')
                    weibo = line.split(',')[0]

                    if weibo == "1":
                        wei = 1
                    awares = line.split(',')[1:]

                    for i in awares:
                        if int(i) >= star and int(i) <= end:
                            aware = 1
                    if baidu[name] == "1":
                        bai = 1
                sorce = (wei + bai + aware) * 0.3
                actieve[name] = sorce
    print("Character indicator: \n")
    print(actieve)
    return actieve

def evaluate(dict):
    Max = max(dict.values())
    Min = min(dict.values())
    return Max,Min

def normalized(value,Max,Min):
    return 0.5/(Max - Min)*(value - Min)

def ranking(actor_list,experience,time,actieve):
    total = {}
    for name in actor_list:
        if name in experience.keys() and name in time.keys() and name in actieve.keys():
            total[name] = experience[name] + time[name] + actieve[name]
    # with open("./actor_ranking_2015-2018.json","w") as w:
    #     json.dump(total,w)
    print(total)
    dict = sorted(total.items(), key=lambda d: d[1], reverse=True)
    for i in dict:
        print(str(i) + '\n')
if __name__ == '__main__':
    actor_list = load_actor_list()
    experience = load_totaloffice_attributes(actor_list)
    time = load_time_attributes(2015,2018,actor_list)
    actieve = load_actieve(actor_list,2011,2015)
    ranking(actor_list,experience,time,actieve)


import socket
import tqdm
import os

SEPERATOR = "[SEPARATOR]"
BUFFER_SIZE = 4096 #How many data sent each step

#HomeServer ip adress
host = "192.168.1.5"

# port
port = 5001

filename = "test.fnk"

filesize = os.path.getsize(filename)

s= socket.socket()

print(f"[+] Connecting to {host}:{port}")
try:
	s.connect((host,port))
	print("[+] Connection Sucessfull!")
	pass
except Exception as e:
	print(f"[!] Connection unsucessfull!")
	print(f"[!] error code: {e}")
	exit()

s.send(f"{filename}{SEPERATOR}{filesize}".encode("utf-8"))

progess = tqdm.tqdm(range(filesize), f"Sending{filename}", unit = "B", unit_scale = True, unit_divisor= 1024)

with open(filename, "rb") as f:
	while True:
		bytes_read = f.read(BUFFER_SIZE)
		if not bytes_read:
			break

		s.sendall(bytes_read)

		progess.update(len(bytes_read))

s.close()


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

'''
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

给定一个有序链表，将其中重复节点全部删除，只留下出现一次的节点。

Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
'''
class ListNode:
    def __init__(self, x):

        if isinstance(x, list):
            self.val = x[0]
            self.next = None
            head = self
            for i in range(1, len(x)):
                head.next = ListNode(x[i])
                head = head.next
        else:
            self.val = x
            self.next = None

    def output(self):
        '''
        输出链表
        '''
        result = str(self.val)
        head = self.next
        while(head is not None):
            result += f' -> {head.val}'
            head = head.next
        return '(' + result + ')'

def deleteDuplicates(head):
    """
    :type head: ListNode
    :rtype: ListNode
    与第83题相似，不同之处在于，83题是出现多次的节点只留下一个，而本题是出现多次的节点一个也不留。
    所以本题需要维护两个指针p1和p2，p1左边的始终是只出现过一次的，p2用来遍历。
    """
    if not head or not head.next:
        return head

    # 在head前追加一个节点
    p = ListNode(0)
    p.next = head
    p1, p2 = p, head
    # 开始遍历
    while(p2):
        # 判断p2及右邻是否相同，如果相同，则全部跳过
        if p2.next and p2.val == p2.next.val:
            v = p2.val
            while(p2 and p2.val == v):
                p2 = p2.next
        else: # 如果不同，则可以将p1指向p2，然后各进一步
            p1.next = p2
            p1 = p1.next
            p2 = p2.next
    p1.next = None
    return p.next

if '__main__' == __name__:
    head = ListNode([1,2,3,3,4,4,5,5])
    head = deleteDuplicates(head)
    print(head.output())


import requests
import pygal

from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS

url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:", r.status_code)

response_dict = r.json()

print("Total Repositories:", response_dict['total_count'])

repo_dicts = response_dict['items']

names, plot_dicts = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])
    plot_dicts.append({
        'value': repo_dict['stargazers_count'],
        'label': repo_dict['description'] if repo_dict['description'] is not None else '',
        'xlink': repo_dict['html_url']
    })

style = LS('#333366', base_style=LCS)

config = pygal.Config()
config.x_label_rotation = 45
config.show_legend = False
config.title_font_size = 24
config.label_font_size = 14
config.major_label_font_size = 18
config.truncate_label = 15
config.show_y_guides = False
config.width = 1000

chart = pygal.Bar(config, style=style)
chart.title = "Most Starred Python Projects - Github"
chart.x_labels = names

chart.add('', plot_dicts)

chart.render_to_file('python_repos.svg')


#Faça um Programa que leia um vetor de 5 números inteiros, mostre a soma, a multiplicação e os números.

def soma(lista_soma):
    i = 0
    for recebe in range(5):
        i = i + 1
        number = int(input('Digite o {}° valor -> '.format(i)))
        lista_soma.append(number)
    print('A sua lista é: ', lista_soma)
    print('A soma dos valores é: ', sum(lista))

def multi(lista_mult):
    multi = 1
    for numero in lista_mult:
        multi *= numero
    print('A multiplicação dos valores é: ', multi)

lista = []
soma(lista)
multi(lista)


from django import forms
from . import models
from .models import Category

class CreateArticle(forms.ModelForm):

    class Meta:
        model = models.Article
        fields = ['title', 'body', 'thumb', 'category', 'slug']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['category'].empty_label = 'No Category'

class CommentForm(forms.ModelForm):
    class Meta:
        model = models.Comment
        fields = ['text']
        widgets = {
            'text': forms.Textarea(attrs={'rows': 4, 'cols': 15, 'placeholder': 'Write your comment here'}),
        }


import nltk

def stackfind(idea):
  from nltk.tokenize import word_tokenize
  nltk.download("book")
  nltk.download("omw")
  ml=[]

  idea=word_tokenize(idea)
  from nltk.corpus import stopwords
  stop_words=set(stopwords.words("english"))
  filtered=[]
  for w in idea:
    if w not in stop_words:
      filtered.append(w)

  from nltk.stem import WordNetLemmatizer
  lemmatizer=WordNetLemmatizer()
  stemmed=[]
  for w in filtered:
    stemmed.append(lemmatizer.lemmatize(w))

  from nltk.corpus import wordnet
  L1=[] #opencv
  synonymns1=[]

  for i in wordnet.synsets("image"):
    for l in i.lemmas():
      synonymns1.append(l.name())
  for i in wordnet.synsets("gesture"):
    for l in i.lemmas():
      synonymns1.append(l.name())

  i1=set(stemmed).intersection(synonymns1)
  if len(i1)>0:
    ml.append("opencv")

  L2=["video","detect","text"] #teseract
  synonymns2=[]
  for x in L2:
    for i in wordnet.synsets(x):
      for l in i.lemmas():
        synonymns2.append(l.name())

  i2=set(stemmed).intersection(L2)

  if len(i2)==3:
    ml.append("teseract")

  L4=["app","mobile"] #AppDev
  synonymns4=[]
  for x in L4:
    for i in wordnet.synsets(x):
      for l in i.lemmas():
        synonymns4.append(l.name())

  i4=set(stemmed).intersection(synonymns4)

  if len(i4)>0:
    ml.append("AppDev")

  L3=["video","edit","editing"] #AE
  synonymns3=[]
  for x in L3:
    for i in wordnet.synsets(x):
      for l in i.lemmas():
        synonymns3.append(l.name())

  i3=set(stemmed).intersection(synonymns3)

  if len(i3)>=2:
    print("AfterEffects")
    ml.append("AfterEffects")

  L5=["web","site","website","scrape"] #Website
  synonymns5=[]
  for x in L5:
    for i in wordnet.synsets(x):
      for l in i.lemmas():
        synonymns5.append(l.name())

  i5=set(stemmed).intersection(synonymns5)

  if len(i5)>=1:
    ml.append("HTML")
    ml.append("CSS")
    ml.append("JS")
  return ml


from setuptools import setup, find_packages
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='poloniex_aio',
    use_scm_version=True,
    setup_requires=['setuptools_scm'],
    url='https://github.com/OlivierCazade/poloniex_aio',
    author='Olivier Cazade',
    author_email='olivier.cazade@gmail.com',
    license='MIT',
    packages=find_packages(),
    description='An async library for Poloniex api',
    long_description=long_description,
    python_requires='>=3.5'
)


"""
给定一个仅包含小写字母的字符串，求它的最长回文子串的长度。
所谓回文串，指左右对称的字符串。
所谓子串，指一个字符串删掉其部分前缀和后缀（也可以不删）的字符串
数据范围：字符串长度1≤s≤350
进阶：时间复杂度：
O(n) ，空间复杂度：O(n)
输入描述：
输入一个仅包含小写字母的字符串

输出描述：
返回最长回文子串的长度

示例1
输入：
cdabbacc
复制
输出：
4
复制
说明：
abba为最长的回文子串
"""

my_str = input()

def func(str_input):
    max_len = 0
    for i in range(len(str_input)):
        for j in range(len(str_input) -1, i-1, -1):
            if str_input[i: j + 1][::-1] == str_input[i: j + 1]:
                if j + 1 -i > max_len:
                    max_len = j + 1 -i
    return max_len

print(func(my_str))


#import MoexParser
import sqlite3

'''

    2 БД:
        1) Одна таблица - SEC_ID и SHORTNAME.
        2) Много таблиц с названиями от SEC_ID по две колонки: дата и цена закрытия.

'''

class MoexDataWorker():

    def __init__(self):

        self.SECID_SHORTNAME_DATABASE_NAME = 'secid_shortname_data.db'
        self.SECID_SHORTNAME_TABLENAME = 'std_table'
        self.HISTORY_STOCKS_DATABASE_NAME = 'history_stocks_data.db'

    def create_table_ssdb(self):
        conn = sqlite3.connect(self.SECID_SHORTNAME_DATABASE_NAME)
        cursor = conn.cursor()

        sql = "CREATE TABLE %s\
                                      (secid text, shortname text)\
                                   " % str("'" + str(self.SECID_SHORTNAME_TABLENAME) + "'")

        cursor.execute(sql)

    def create_table_hsdb(self, sec_id):
        conn = sqlite3.connect(self.HISTORY_STOCKS_DATABASE_NAME)
        cursor = conn.cursor()

        sql = "CREATE TABLE %s\
                                      (date text, close_price text)\
                                   " % str("'" + str(sec_id) + "'")

        cursor.execute(sql)

    def get_last_date(self, sec_id, cursor):

        try:
            cursor.execute("SELECT date FROM '" + str(sec_id) + "'")
            date_arr = cursor.fetchall()
            return date_arr[len(date_arr) - 1][0]

        except Exception as e:
            return None

    def get_stock_info(self, sec_id):
        conn = sqlite3.connect(self.SECID_SHORTNAME_DATABASE_NAME)
        cursor = conn.cursor()

        cursor.execute("SELECT * FROM '" + str(self.SECID_SHORTNAME_TABLENAME) + "' WHERE secid LIKE '" + str(sec_id) + "'")

        ans = []

        ans.append(cursor.fetchall()[0])
        #ans.append(cursor.fetchall()[1])

        conn = sqlite3.connect(self.HISTORY_STOCKS_DATABASE_NAME)
        cursor = conn.cursor()

        cursor.execute("SELECT * FROM '" + str(sec_id) + "'")

        ans += cursor.fetchall()

        return ans

    def add_secid_and_shortname(self, sec_id, shortname, conn=None):
        if conn == None:
            conn = sqlite3.connect(self.SECID_SHORTNAME_DATABASE_NAME)

        cursor = conn.cursor()

        #cursor.execute("SELECT * FROM '" + self.SECID_SHORTNAME_TABLENAME + "' WHERE secid LIKE " + str(sec_id))
        #tmp = cursor.fetchall()
        tmp = None

        if tmp == None or len(tmp) == 0:
            cursor.execute("INSERT INTO '" + self.SECID_SHORTNAME_TABLENAME + "' VALUES (?,?) ", [sec_id, shortname])
            conn.commit()

    def add_history_stock_data(self, sec_id, data, conn=None):
        if conn == None:
            conn = sqlite3.connect(self.HISTORY_STOCKS_DATABASE_NAME)
        cursor = conn.cursor()

        last_date = self.make_arr_from_date(self.get_last_date(sec_id, cursor))
        new_date = self.make_arr_from_date(data[0])

        if not (last_date == None) and not (new_date == None):
            if last_date[0] > new_date[0] or (last_date[0] == new_date[0] and last_date[1] >= new_date[1]) or \
                    (last_date[0] == new_date[0] and last_date[1] == new_date[1] and last_date[2] >= new_date[2]):
                return

        try:
            cursor.execute("INSERT INTO '" + str(sec_id) + "' VALUES (?,?) ", [data[0], data[1]])
            conn.commit()
        except sqlite3.OperationalError as e:
            self.create_table_hsdb(sec_id)
            self.add_history_stock_data(sec_id, data, conn)

    def get_all_secid(self):
        conn = sqlite3.connect(self.SECID_SHORTNAME_DATABASE_NAME)
        cursor = conn.cursor()

        cursor.execute("SELECT secid FROM '" + str(self.SECID_SHORTNAME_TABLENAME) + "'")

        return cursor.fetchall()

    def make_arr_from_date(self, str_date):
        if str_date == None:
            return None
        return [int(i) for i in str_date.split('-')]


"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""

from setuptools import setup
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

with open(path.join(here, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

setup(

    name='deepstomata',
    version='1.0',
    description='iterative calculation of stomatal pores ',
    long_description=long_description,
    url='https://github.com/totti0223/',
    author='Yosuke Toda',
    author_email='tyosuke@aquaseerser.com',
    license='MIT',

    # https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        'Development Status :: 3 - Alpha',
        #'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.5',
        'Topic :: Scientific/Engineering :: Image Recognition'
    ],
    keywords='Facial Recognition Technology for Automated Stomatal Aperture Measurement',
    packages=['deepstomata'],
    install_requires=open('requirements.txt').read().splitlines(),
    package_data={
        "deepstomata": ["models/*", "config.ini"]
    }
)


# https://leetcode.com/problems/valid-parentheses/

class Solution:
    # @return a boolean
    def isValid(self, s):
        stack = []
        l = len(s)
        pairDic = dict()
        pairDic["}"] = "{"
        pairDic[")"] = "("
        pairDic["]"] = "["
        for i in range(l) :
            c = s[i]
            if c in ["{","(","["] :
                stack.append(c)
            else :
                if stack : # more than one item in stack
                    top = stack.pop()
                    if top != pairDic[c] :
                        return False
                else :
                    return False
        if stack :
            return False
        else :
            return True


#_*_ coding: utf-8 _*_
# 선형회귀분석 2.1

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf

# 학습데이터 생성
num_points = 1000
vectors_set = []

for i in xrange(num_points):
    x1 = np.random.normal(0.0,0.55)
    y1 = x1 * 0.1 + 0.3 + np.random.normal(0.0,0.03)
    vectors_set.append([x1,y1])

x_data = [v[0] for v in vectors_set]
y_data = [v[1] for v in vectors_set]

# 그래프로 보여주는 부분
# plt.plot(x_data, y_data, 'ro')
# plt.show()

# 매개변수 지정(가설지정)
W = tf.Variable(tf.random_uniform([1],-1.0,-1.0))
b = tf.Variable(tf.zeros([1]))
y = x_data * W + b

# 경사 하강법에 의한 비용함수(오차함수) => 함수값을 최소화하는 알고리즘
# y값과 y_data값의 차이를 알기위해 그 사이의 거리를 제곱한 후 평균내어 계산함
loss = tf.reduce_mean(tf.square(y - y_data))

# 경사하강법은 초기 시작점에서 함수의 값이 최소화되는 방향으로 매개변수를 변경하는 것을 반복적으로 수행하는 알고리즘
# W(기울기)를 음의 방향쪽으로 진행하면서 반복적으로 최적화 수행
# 보통 양의 값을 만들기위해 거리값을 제곱, 기울기 계산을 위해 오차함수는 미분이 가능해야 함
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)

# 세션 초기화
init = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)

# 세션 반복수행(훈련)
# 경사 하강법 알고지즘을 수행할 때마다 평면의 한 지점에서 시작하여 더 작은 오차를 갖는 직선을 찾아 이동
# 오차함수의 기울기를 계산하기 위해 텐서플로는 오차함수를 미분함
# 반복이 일어날 때마다 움직힐 방향을 알아내기 위해 W,b에 대한 편미분방정식 계산이 필요함
for step in xrange(8):
    sess.run(train)
    # print step, sess.run(W),sess.run(b)
    plt.plot(x_data,y_data,'ro')
    plt.plot(x_data,sess.run(W)*x_data * sess.run(b))
    plt.xlabel('x')
    plt.ylabel('y')
    plt.show()
    print(step,sess.run(loss))


import os
import sys

class VMTranslator:
    """
    docstring for VMTranslator
    """
    def __init__(self, file_path):
        """
        @attr self.vm_files (list of str): the xxx.vm needed to be translated
        @attr self.asm_filename(str): output filename
        @attr self.output_path(str): path for output filename
        @attr self.symbol_index(int): use it to make sure that each symbol is unique
        @attr self.ret_index(int): use it to make sure that each ret label is unique
        """
        self.vm_files = []
        self.asm_codes = []
        self.symbol_index = 0
        self.ret_index = 0
        if os.path.isdir(file_path):
            for file in os.listdir(file_path):
                if file[-2:] == "vm":
                    self.vm_files.append(os.path.join(file_path, file))
            assert len(self.vm_files) > 0,"please choose a dir with xxx.vm files in it"
            self.asm_filename = "A.asm"
            self.output_path = file_path
            self.multi = True
        else:
            self.vm_filename = os.path.basename(file_path)
            suffix = self.vm_filename[self.vm_filename.find(".") + 1:]
            assert suffix == "vm","please choose a vm file like xxx.vm"
            self.vm_files=[file_path]
            self.asm_filename = os.path.basename(file_path)[:-2] + "asm"
            if file_path.find("/") == -1:
                self.output_path = os.getcwd()
            else:
                self.output_path = file_path[:file_path.rfind('/')]
            self.multi = False

    def parse(self):
        """
        translate the vm files in self.vm_files into assembly codes, store them into self.asm_codes
        """
        if self.multi:
            self.asm_codes+=["@256","D=A","@SP","M=D"] # set SP=256
            self.asm_codes+=["@1","D=A","@LCL","M=D"]
            self.asm_codes+=["@2","D=A","@ARG","M=D"]
            self.asm_codes+=["@3","D=A","@THIS","M=D"]
            self.asm_codes+=["@4","D=A","@THAT","M=D"]
            push_D=["@SP","A=M","M=D","@SP","M=M+1"]
            self.asm_codes+=(["@bootstrap","D=A"]+push_D) # push retAddr
            for x in ["LCL","ARG","THIS","THAT"]: # push LCL,ARG,THIS,THAT
                self.asm_codes+=(["@"+x,"D=M"]+push_D)
            self.asm_codes+=["@5","D=A","@SP","D=M-D","@ARG","M=D"]# ARG=SP-n-5
            self.asm_codes+=["@SP","D=M","@LCL","M=D"] # LCL=SP
            self.asm_codes+=["@Sys.init","0;JMP","(bootstrap)"]
        for file in self.vm_files:
            single_parse = SingleVMTranslator(file, self.symbol_index, self.ret_index)
            single_parse.parse()
            self.asm_codes += single_parse.asm_codes
            self.symbol_index = single_parse.symbol_index
            self.ret_index = single_parse.ret_index

    def save_file(self):
        """
        save self.asm_codes into xxx.asm file
        """
        output = os.path.join(self.output_path, self.asm_filename)
        with open (output,'w') as file:
            for line in self.asm_codes:
                file.write(line + '\n')

class SingleVMTranslator:
    """
    translator a .vm into assembly codes for hack machine
    """

    def __init__(self, file_path, symbol_index, ret_index):
        """
        open the file and ignore blanks and comments
        @attr self.vm_filename(str): input file
        @attr self.codes(list of str): a list contains clean vm code with no blank or comment
        @attr self.asm_codes(list of str): a list contains assembly codes generated from self.codes
        @attr self.symbol_index(int): use it to make sure that each symbol is unique
        @attr self.ret_idx(int): use it to make sure that each ret label is unique
        """

        #获取VM文件的名字
        self.vm_filename = os.path.basename(file_path)
        suffix = self.vm_filename[self.vm_filename.find(".") + 1:]
        assert suffix == "vm","please choose an input file named xxx.vm"
        #定义保存vm code和 asm code的列表
        self.codes = []
        self.asm_codes = []

        #处理文件，清除空格及注释，从文件中转换为字符串列表
        with open (file_path,'r') as file:
            for line in file:
                _line = line.strip()
                if len(_line) == 0 or _line[0] == '/':
                    continue
                if _line.find('/') != -1:
                    _line = _line[:_line.find('/')]
                self.codes.append(_line.strip())

        #vm code与asm code的映射对照表
        self.arith_dict = {
            "not":"!","neg":"-","add":"+","sub":"-","and":"&","or":"|",
		"eq":"JNE","lt":"JGE","gt":"JLE",
        }
        self.mapping = {
            "local":"LCL","argument":"ARG","this":"THIS","that":"THAT",
		"temp":"5","pointer":"3",
        }

        self.symbol_index = symbol_index
        self.ret_index = ret_index
        self.cur_funcname = ""

    def parse(self):
        """
        for each code in self.codes generate its corresponding assmembly codes
        """
        #遍历翻译每一行vm code
        for code in self.codes:
            part = code.split()
            if len(part) == 1:
                if part[0] == "return":
                    #翻译return vm code
                    self.asm_codes += ["\n//" + code]
                    self.asm_codes += self.ret_asm()
                else:
                    #翻译 逻辑算法指令 vm code
                    self.asm_codes += ["\n//" + code]
                    self.asm_codes += self.arith_asm(part[0])
            elif part[0] == "push":
                self.asm_codes += ["\n//" + code]
                self.asm_codes += self.push_asm(part[1:])
            elif part[0] == "pop":
                self.asm_codes += ["\n//" + code]
                self.asm_codes += self.pop_asm(part[1:])
            elif part[0] == "label":
                self.asm_codes += ["\n//" + code]
                label_ = self.cur_funcname + "$" + part[1]
                self.asm_codes += ["(" + label_ + ")"]
            elif part[0] == "goto":
                self.asm_codes += ["\n//" + code]
                label_ = self.cur_funcname + "$" + part[1]
                self.asm_codes += ["@" + label_, "0;JMP"]
            elif part[0] == "if-goto":
                self.asm_codes += ["\n//" + code]
                label_ = self.cur_funcname + "$" + part[1]
                self.asm_codes += ["@SP","A = M - 1","D=M","@" + label_, "D;JNE"]
            elif part[0] == "function":
                self.asm_codes += ["\n//" + code]
                self.asm_codes += self.function_asm(part[1:])
            elif part[0] == "call":
                self.asm_codes += ["\n//" + code]
                self.asm_codes += self.call_asm(part[1:])
            else:
                raise ValueError("illegal vm codes found")
    def call_asm(self, command):
        """
        generate assembly code for call commands
        @param command(list of str): call command like [func_name,argument_num]
        @attr: the call code can div into serises of commands:
                push retaddress
                push LCL
                push ARG
                push THIS
                push THAT
                ARG = SP - n - 5
                LCL = SP
                goto func_name
                (retaddress)
        """
        label = "End$" + command[0] + "$" + str(self.ret_index)
        self.ret_index += 1
        push_label = ["@SP","A=M","M=D","@SP","M=M+1"]
        asm_code = (["@"+ label, "D=A"] + push_label)
        for x in ["LCL","ARG","THIS","THAT"]:
            asm_code += (["@"+ x, "D=M"] + push_label)
        asm_code += ["@" + str(int(command[1]) + 5), "D=A", "@SP", "D=M-D", "@ARG", "M=D"]
        asm_code += ["@SP","D=M","@LCL","M=D"]
        asm_code += ["@" + command[0], "0;JMP"]
        asm_code += ["(" + label + ")"]

        return asm_code

    def ret_asm(self):
        """
        generate assembly codes for return commands
        """
        asm_code  = ["@LCL","D=M","@R15","M=D"] # put LCL into R15
        asm_code += ["@5","D=A","@R15","A=M-D","D=M","@R14","M=D"] # put retAddr into R14
        asm_code += ["@SP","AM=M-1","D=M","@ARG","A=M","M=D"] # *ARG=pop()
        asm_code += ["@ARG","D=M+1","@SP","M=D"] # SP=ARG+1
        asm_code += ["@R15","A=M-1","D=M","@THAT","M=D"] # THAT=*(FRAME-1)
        asm_code += ["@2","D=A","@R15","A=M-D","D=M","@THIS","M=D"] #THIS=*(FRAME-2)
        asm_code += ["@3","D=A","@R15","A=M-D","D=M","@ARG","M=D"] # ARG=*(FRAME-3)
        asm_code += ["@4","D=A","@R15","A=M-D","D=M","@LCL","M=D"] # LCL=*(FRAME-4)
        asm_code += ["@R14","A=M","0;JMP"] # goto retAddr

        return asm_code

    def function_asm(self, command):
        """
        generate assembly codes for function code
        @param command(str of list): [function_name, local var num]
        """
        self.cur_funcname = command[0]
        asm_code = ["(" + command[0] + ")"]
        for i in range(int(command[1])):
            asm_code += ["@SP", "A=M","M=0","@SP","M = M+1"]
        return asm_code
    def arith_asm(self, command):
        """
        generate assembly code for arithmetic commands
        @para command(str): the arithmetic command to be translate
        """
        if command in ["not","neg"]:
            spec = "M=" + self.arith_dict[command] + "M"
            asm_code = ["@SP",'A=M-1',spec]
        if command in ["add","sub","and","or"]:
            spec = "M=M" + self.arith_dict[command] + "D"
            asm_code = ["@SP","AM=M-1","D=M","A=A-1",spec]
        #使用跳转符号实现算术比较
        if command in ["eq","lt","gt"]:
            symbol=command+"_"+str(self.symbol_index)
            symbol1="@"+symbol
            symbol2="("+symbol+")"
            spec="D;"+self.arith_dict[command]
            asm_code=["@SP","AM=M-1","D=M","A=A-1","D=M-D","M=0",symbol1,spec,"@SP","A=M-1","M=-1",symbol2]
            self.symbol_index+=1
        return asm_code
    def push_asm(self, command):
        """
        generate assembly codes for push command
        @param command(list of str): the push command to be translate
        """
        asm_code = []
        if command[0] == "constant":
            asm_code = ["@" + command[1], "D = A"]
        if command[0] in ["local","argument","this","that"]:
            asm_code=["@"+command[1],"D=A","@"+self.mapping[command[0]],"A=M+D","D=M"]
        if command[0] in ["temp","pointer"]:
            asm_code=["@"+command[1],"D=A","@"+self.mapping[command[0]],"A=A+D","D=M"]
        if command[0] == "static":
            symbol = "@" + self.vm_filename[:-3] + "." + command[1]
            asm_code = [symbol,"D=M"]

        return asm_code + ["@SP","A=M","M=D","@SP","M=M+1"]

    def pop_asm(self, command):
        """
        generate assembly codes for pop command
        @param command(list of str): command to be translate
        """
        asm_code = []
        if command[0] in ["local","argument","this","that"]:
            asm_code = ["@"+command[1],"D=A","@"+self.mapping[command[0]],"D=M+D","@R15","M=D"]
        if command[0] in ["temp","pointer"]:
            asm_code = ["@"+command[1],"D=A","@"+self.mapping[command[0]],"D=A+D","@R15","M=D"]
        elif command[0] == "static":
            symbol="@"+self.vm_filename[:-3]+"."+command[1]
            asm_code=[symbol,"D=A","@R15","M=D"]

        return asm_code + ["@SP","AM=M-1","D=M","@R15","A=M","M=D"]
def main():
    assert len(sys.argv)>=2,"please enter a filename or dir"
    file_path = sys.argv[1]
    vmtranslator = VMTranslator(file_path)
    vmtranslator.parse()
    vmtranslator.save_file()

if __name__ == '__main__':
    main()


from django import forms

from MainScreen.models import Member, Due

choice = (
    (1, "Included"),
    (0, "Excluded"),
    (-1, "Not Applicable")
)

class NewDue(forms.Form):
    due_id = forms.CharField(label='Due ID')
    due_type = forms.CharField(label='Due Type')
    due_amount = forms.DecimalField(label='Due Amount')
    due_fineamt = forms.DecimalField(label='Fine Amount (Yearly)')
    is_head = forms.ChoiceField(choices=choice)
    is_pension = forms.ChoiceField(choices=choice)
    is_nri = forms.ChoiceField(choices=choice)
    is_govt = forms.ChoiceField(choices=choice)
    is_male = forms.ChoiceField(choices=choice)
    account_serial = forms.CharField(label='Account Serial')

ward_choices = (
    ("Moolavattom ward", "Moolavattom ward"),
    ("Masjid ward", "Masjid ward"),
    ("Sasthavattom ward", "Sasthavattom ward")
)

class NewMember(forms.Form):
    family_number = forms.IntegerField()
    jp_number = forms.DecimalField(max_digits=1000, decimal_places=2)
    name = forms.CharField()
    is_due_apply = forms.BooleanField(label='Is Due Apply?')
    is_pension = forms.BooleanField(required=False, label='Is Pension?')
    is_nri = forms.BooleanField(required=False, label='Is NRI?')
    is_govt = forms.BooleanField(required=False, label='Is Govt?')
    is_male = forms.BooleanField(required=False, label='Is Male?')
    is_alive = forms.BooleanField(required=False, label='Is Alive?')
    age = forms.IntegerField()
    mobile = forms.IntegerField(required=False)
    email = forms.CharField(required=False)
    description = forms.CharField(required=False)
    remarks = forms.CharField(required=False)

    def __init__(self, *args, **kwargs):
        super(NewMember, self).__init__(*args, **kwargs)
        self.fields['name'].widget.attrs['cols'] = 40

class NewFamily(forms.Form):
    family_no = forms.IntegerField()
    census_no = forms.IntegerField()
    house_name = forms.CharField()
    area = forms.ChoiceField(choices=ward_choices)
    postoffice = forms.CharField()
    address = forms.CharField()
    jp_number = forms.DecimalField(max_digits=1000, decimal_places=2)
    name = forms.CharField()
    is_due_apply = forms.BooleanField(label='Is Due Apply?')
    is_pension = forms.BooleanField(required=False, label='Is Pension?')
    is_nri = forms.BooleanField(required=False, label='Is NRI?')
    is_govt = forms.BooleanField(required=False, label='Is Govt?')
    is_male = forms.BooleanField(required=False, label='Is Male?')
    is_alive = forms.BooleanField(required=False, label='Is Alive?')
    age = forms.IntegerField()
    mobile = forms.IntegerField(required=False)
    email = forms.CharField(required=False)
    description = forms.CharField(required=False)
    remarks = forms.CharField(required=False)

class EditMember(forms.ModelForm):
    class Meta:
        model = Member
        exclude = ['serial', 'financial_year_serial', 'jp_number',
                   'description']
        widgets = {
            'area': forms.Select(choices=ward_choices),
        }

    def __init__(self, *args, **kwargs):
        super(EditMember, self).__init__(*args, **kwargs)
        self.fields['name'].widget.attrs['cols'] = 22
        self.fields['name'].widget.attrs['rows'] = 1
        self.fields['house_name'].widget.attrs['cols'] = 22
        self.fields['house_name'].widget.attrs['rows'] = 1
        self.fields['family_number'].widget.attrs['cols'] = 22
        self.fields['family_number'].widget.attrs['rows'] = 1
        self.fields['email'].widget.attrs['cols'] = 22
        self.fields['email'].widget.attrs['rows'] = 1
        self.fields['area'].widget.attrs['cols'] = 22
        self.fields['area'].widget.attrs['rows'] = 1
        self.fields['address'].widget.attrs['cols'] = 22
        self.fields['address'].widget.attrs['rows'] = 1
        self.fields['remarks'].widget.attrs['cols'] = 22
        self.fields['remarks'].widget.attrs['rows'] = 1
        self.fields['postoffice'].widget.attrs['cols'] = 22
        self.fields['postoffice'].widget.attrs['rows'] = 1

        self.validate = kwargs.pop('validate', False)
        self.fields['email'].required = False
        self.fields['house_name'].required = False
        self.fields['mobile'].required = False
        self.fields['remarks'].required = False
        self.fields['address'].required = False
        self.fields['area'].required = False
        self.fields['postoffice'].required = False

        self.fields['name'].label = "Name"
        self.fields['is_active'].label = "Is Active?"
        self.fields['is_head'].label = "Is Head?"
        self.fields['is_due_apply'].label = "Is Due Apply?"
        self.fields['is_pension'].label = "Is Pension?"
        self.fields['is_nri'].label = "Is NRI?"
        self.fields['is_govt'].label = "Is Govt"
        self.fields['is_male'].label = "Is Male?"
        self.fields['is_alive'].label = "Is Alive?"

class EditDues(forms.ModelForm):
    class Meta:
        model = Due
        exclude = ['account_serial', 'due_display_id', 'due_financial_year', 'due_type', 'applied']

    def __init__(self, *args, **kwargs):
        super(EditDues, self).__init__(*args, **kwargs)
        self.fields['due_amount'].label = "Due Amount"
        self.fields['due_fineamt'].label = "Due Fine Amount"
        self.fields['is_head'].label = "Is Head?"
        self.fields['is_pension'].label = "Is Pension?"
        self.fields['is_nri'].label = "Is NRI?"
        self.fields['is_govt'].label = "Is Govt"
        self.fields['is_male'].label = "Is Male?"
        self.fields['due_active'].label = "Due Active?"


"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""
class Solution:
    """
    @param head: The first node of linked list.
    @return: The head of linked list.
    """
    def insertionSortList(self, head):
        dummy = ListNode(0, head)
        pre, cur = dummy, head
        while cur:
            if cur.next and cur.next.val < cur.val:
                while pre.next and pre.next.val < cur.next.val:
                    pre = pre.next
                pre.next, cur.next, pre.next.next, pre = \
                    cur.next, cur.next.next, pre.next, dummy
            else:
                cur = cur.next
        return dummy.next


"""
รับข้อมูลเข้ามา ตั้งชื่อตัวแปรว่า val โดยทำการทดสอบโดยกรอก 50 เข้าไป
"""

"""
แปลงค่าจาก val เป็น int แล้วเก็บไว้ในตัวแปร val
"""

"""
ตรวจว่าชนิดตัวของ val ว่าคือชนิดอะไร แล้วแสดงผลออกมา
"""

"""
ทำการคำนวณ โดยให้ val บวกเท่ากับ ((((val บวก 50) ยกกำลัง 2 - 23) หารปัดเศษ 52 คูณ 7 ) % 2)
"""

val = 50
val += (((val + 50) ** 2 - 23) // 52 * 7) % 2

"""
แสดงผลออกมาแล้วตรวจว่า val มีค่ามากกว่าหรือเท่ากับ 50 หรือเปล่า
"""

"""
แสดงผลออกมาแล้วตรวจว่า val มีค่ามากกว่าหรือเท่ากับ 60 หรือเปล่า
"""

"""
แสดงผลข้อมูล val โดยให้จัดรูปแบบสตริงให้เป็นตัวอย่างแบบนี้ "ผลลัพธ์ที่ได้ 51 แบบ" โดย 51 แทนตัวแปร val
"""


from decimal import Decimal

import pytest
from hypothesis import example, given, settings
from hypothesis import strategies as st

from vyper import ast as vy_ast
from vyper.exceptions import OverflowException, TypeMismatch, ZeroDivisionException

st_decimals = st.decimals(
    min_value=-(2**32), max_value=2**32, allow_nan=False, allow_infinity=False, places=10
)

@pytest.mark.fuzzing
@settings(max_examples=50)
@given(left=st_decimals, right=st_decimals)
@example(left=Decimal("0.9999999999"), right=Decimal("0.0000000001"))
@example(left=Decimal("0.0000000001"), right=Decimal("0.9999999999"))
@example(left=Decimal("0.9999999999"), right=Decimal("0.9999999999"))
@example(left=Decimal("0.0000000001"), right=Decimal("0.0000000001"))
@pytest.mark.parametrize("op", "+-*/%")
def test_binop_decimal(get_contract, assert_tx_failed, op, left, right):
    source = f"""
@external
def foo(a: decimal, b: decimal) -> decimal:
    return a {op} b
    """
    contract = get_contract(source)

    vyper_ast = vy_ast.parse_to_ast(f"{left} {op} {right}")
    old_node = vyper_ast.body[0].value
    try:
        new_node = old_node.evaluate()
        is_valid = True
    except ZeroDivisionException:
        is_valid = False

    if is_valid:
        assert contract.foo(left, right) == new_node.value
    else:
        assert_tx_failed(lambda: contract.foo(left, right))

def test_binop_pow():
    # raises because Vyper does not support decimal exponentiation
    vyper_ast = vy_ast.parse_to_ast("3.1337 ** 4.2")
    old_node = vyper_ast.body[0].value

    with pytest.raises(TypeMismatch):
        old_node.evaluate()

@pytest.mark.fuzzing
@settings(max_examples=50)
@given(
    values=st.lists(st_decimals, min_size=2, max_size=10),
    ops=st.lists(st.sampled_from("+-*/%"), min_size=11, max_size=11),
)
def test_nested(get_contract, assert_tx_failed, values, ops):
    variables = "abcdefghij"
    input_value = ",".join(f"{i}: decimal" for i in variables[: len(values)])
    return_value = " ".join(f"{a} {b}" for a, b in zip(variables[: len(values)], ops))
    return_value = return_value.rsplit(maxsplit=1)[0]
    source = f"""
@external
def foo({input_value}) -> decimal:
    return {return_value}
    """
    contract = get_contract(source)

    literal_op = " ".join(f"{a} {b}" for a, b in zip(values, ops))
    literal_op = literal_op.rsplit(maxsplit=1)[0]
    vyper_ast = vy_ast.parse_to_ast(literal_op)
    try:
        vy_ast.folding.replace_literal_ops(vyper_ast)
        expected = vyper_ast.body[0].value.value
        is_valid = -(2**127) <= expected < 2**127
    except (OverflowException, ZeroDivisionException):
        # for overflow or division/modulus by 0, expect the contract call to revert
        is_valid = False

    if is_valid:
        assert contract.foo(*values) == expected
    else:
        assert_tx_failed(lambda: contract.foo(*values))


'''
v6
Uses datagen.flow_from_dataframe instead of datagen.flow_from_directory
v5
This version provides support to Resnet, and training some backend model layers
From:
https://www.apriorit.com/dev-blog/647-ai-applying-deep-learning-to-classify-skin-cancer-types
It does not use .h5 but the new format to save models.
v4
Code that saves all training history in a pickle file.
Saves AUC, ROC, etc as part of the history, in this pickle file.
'''
#tutorial in part from https://wandb.ai/sayakpaul/efficientnet-tl/reports/Transfer-Learning-With-the-EfficientNet-Family-of-Models--Vmlldzo4OTg1Nw

from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Input, Dropout, GlobalAveragePooling2D
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
import tensorflow_hub as hub
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
import numpy as np
import sklearn.metrics
from sklearn.metrics import confusion_matrix, roc_curve, auc, recall_score, f1_score, precision_score, precision_recall_curve
from tensorflow.keras.models import Model
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
import seaborn as sn
import os
import sys
import shutil
import pickle
import argparse
import pandas as pd
from tensorflow.keras.applications.resnet import ResNet152, preprocess_input
from tensorflow.keras.callbacks import TensorBoard

#To avoid the warning in
#https://github.com/tensorflow/tensorflow/issues/47554
from absl import logging
logging.set_verbosity(logging.ERROR)

def get_training_model_xception(url, trainable=False):
    #https://www.analyticsvidhya.com/blog/2022/04/binary-classification-on-skin-cancer-dataset-using-dl/
    model = Sequential()
    base = Xception(include_top=False, weights="imagenet", input_shape=(200,200,3), pooling='avg')
    for lay in base.layers: lay.trainable = True # false for transfer learning
    model.add(base)
    model.add(Dropout(0.5))
    model.add(Flatten())
    model.add(Dense(10,'relu'))
    model.add(Dropout(0.5))
    model.add(Dense(1,'sigmoid'))
    return model

def get_training_model_resnet(trainable=False):
    # from https://www.apriorit.com/dev-blog/647-ai-applying-deep-learning-to-classify-skin-cancer-types
    #Download data from https://storage.googleapis.com/tensorflow/keras-applications/resnet/resnet152_weights_tf_dim_ordering_tf_kernels_notop.h5
    base_model = ResNet152(weights='imagenet', include_top=False)
    x = base_model.output
    x = GlobalAveragePooling2D()(x)
    #x = Dense(1000, activation='relu')(x)
    x = Dense(100, activation='relu')(x)
    x = Dropout(0.25)(x)
    predictions = Dense(1, activation='sigmoid')(x)

    for i, layer in enumerate(base_model.layers):
        print(i, layer.name)

    if True:
        # freeze all layers
        for layer in base_model.layers:
            layer.trainable = False
    else:
        # freeze up to given layer
        layer_num = 483
        for layer in base_model.layers[:layer_num]:
            layer.trainable = False
        for layer in base_model.layers[layer_num:]:
            layer.trainable = True

    model = Model(inputs=base_model.input, outputs=predictions)

    return model

def get_training_model_effnet(url, trainable=False):
    # Load the respective EfficientNet model but exclude the classification layers
    extractor = hub.KerasLayer(url, input_shape=(img_size, img_size, 3), trainable=trainable)

    # Construct the head of the model that will be placed on top of the
    # the base model
    model = tf.keras.models.Sequential([
        extractor,
        tf.keras.layers.Dropout(0.8),
        tf.keras.layers.Dense(200, activation="relu"),
        tf.keras.layers.BatchNormalization(),
        #tf.keras.layers.Dense(80, activation="relu"),
        #tf.keras.layers.BatchNormalization(),
        #tf.keras.layers.Dropout(0.5),
        #tf.keras.layers.Dense(60, activation="relu"),
        #tf.keras.layers.BatchNormalization(),
        #tf.keras.layers.Dropout(0.5),
        tf.keras.layers.Dense(1, activation="sigmoid")
    ])

    #layers = model.weights
    #for i in range( len(layers) ):
    #    print(i, layers[i].name)

    return model

def get_training_model_fixed():

    img_width = 240
    img_height = 240
    # Define the input shape of the images
    input_shape = (img_width, img_height, 3)

    num_output_neurons = 1

    # Define the CNN model
    model = Sequential()
    if True:
        model.add(Conv2D(60, (8,8), input_shape=input_shape, activation='swish'))
        model.add(MaxPooling2D((2,2)))
        model.add(Dropout(0.4))
        model.add(Conv2D(53, (5,5), activation='swish'))
        model.add(MaxPooling2D((2,2)))
        model.add(Dropout(0.4))
        model.add(Flatten())
        model.add(Dense(1, activation='sigmoid'))

    return model

def decrease_num_negatives(df, desired_num_negative_examples):
    '''
    Create dataframe with desired_num_rows rows from df
    '''
    shuffled_df = df.sample(frac=1).reset_index(drop=True)
    neg_examples = shuffled_df[shuffled_df['target'] == '0'].copy()
    neg_examples = neg_examples.head( round(desired_num_negative_examples) ).copy()

    pos_examples = shuffled_df[shuffled_df['target'] == '1'].copy()
    newdf = pd.concat([neg_examples, pos_examples], ignore_index=True)
    newdf = newdf.sample(frac=1).reset_index(drop=True) #shuffle again
    return newdf

def get_balanced_dataframe(df, desired_num_negative_examples, desired_num_positive_examples):
    '''
    Create dataframe with desired_num_rows rows from df
    '''
    shuffled_df = df.sample(frac=1).reset_index(drop=True)
    neg_examples = shuffled_df[shuffled_df['target'] == '0'].copy()
    neg_examples = neg_examples.head( round(desired_num_negative_examples) ).copy()

    pos_examples = shuffled_df[shuffled_df['target'] == '1'].copy()
    pos_examples = pos_examples.head( round(desired_num_positive_examples) ).copy()

    newdf = pd.concat([neg_examples, pos_examples], ignore_index=True)
    newdf = newdf.sample(frac=1).reset_index(drop=True) #shuffle again
    return newdf

if __name__ == '__main__':
    print("=====================================")
    print("Train NN classifier")

    parser = argparse.ArgumentParser()
    #required arguments
    parser.add_argument('--num_desired_train_examples',type=int,help='Desired number of training examples (for both classes 0 and 1, assuming there are 324 examples of 1)',required=True)

    args = parser.parse_args()
    num_desired_train_examples = args.num_desired_train_examples

    plt.close("all")

    #%% CHECK ALL VARIABLES AND REPLACE VALUES AS NEEDED
    simulation_ID = 22 # model from Optuna, but using AUC as loss instead of accuracy
    #--------------------------------------------------------------------------
    #num_desired_train_examples = 40
    img_size = 240
    #model_url = 'https://tfhub.dev/google/efficientnet/b1/feature-vector/1' #non-trainable
    #model_url = 'https://tfhub.dev/google/efficientnet/b1/classification/1'

    #From https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/tf2_image_retraining.ipynb?hl=vi#scrollTo=FlsEcKVeuCnf
    model_url = 'https://tfhub.dev/google/imagenet/efficientnet_v2_imagenet1k_b1/feature_vector/2'
    use_augment = False
    type_augment = "Albumentations"
    test_id = str(simulation_ID) #test number
    data_id = "unbal" #ratio
    effnet_model = str(1)
    #--------------------------------------------------------------------------

    # Define the folders for train, validation, and test data
    #Laptop:
    #train_folder = 'D:/temp/test_50percent_teste4/train_50percent_teste4/'
    #validation_folder = 'D:/temp/test_50percent_teste4/val_50percent_teste4/'
    #test_folder = 'D:/temp/test_50percent_teste4/test_50percent_teste4'

    # Define the folders for train, validation, and test data
    #PC:
    train_folder = 'D:/sofia/ufpa/tcc/dataset_updated/train'
    validation_folder = 'D:/sofia/ufpa/tcc/dataset_updated/val'
    test_folder = 'D:/sofia/ufpa/tcc/dataset_updated/test'

    train_csv = 'D:/sofia/ufpa/tcc/train_data.csv'
    test_csv = 'D:/sofia/ufpa/tcc/test_data.csv'
    validation_csv = 'D:/sofia/ufpa/tcc/val_data.csv'

    if False:
        print(traindf.info())
        print(traindf.head())
        print(traindf.describe())
        print(traindf.value_counts())

    if True:
        #do not remove header
        traindf=pd.read_csv(train_csv,dtype=str)
        testdf=pd.read_csv(test_csv,dtype=str)
        validationdf=pd.read_csv(validation_csv,dtype=str)
    else:
        #remove header
        traindf=pd.read_csv(train_csv,dtype=str, header=None)
        testdf=pd.read_csv(test_csv,dtype=str, header=None)
        validationdf=pd.read_csv(validation_csv,dtype=str, header=None)

    '''
    D:/sofia/ufpa/tcc/data_intofolders
    Train NN classifier
    train:
    target
    1    324
    0    18227 = 18551-324
    Name: count, dtype: int64
    test:
    target
    0    9754
    1     184
    Name: count, dtype: int64
    validation:
    target
    0    4561
    1      76
    Name: count, dtype: int64
    '''

    if num_desired_train_examples >= 324:
        #the 324 positive examples will always be part of the training set
        num_desired_negative_train_examples = num_desired_train_examples - 324
        traindf = decrease_num_negatives(traindf, num_desired_negative_train_examples)
    else:
        num_desired_negative_train_examples = np.floor(num_desired_train_examples / 2.0)
        desired_num_positive_examples = num_desired_train_examples - num_desired_negative_train_examples
        traindf = get_balanced_dataframe(traindf, num_desired_negative_train_examples, desired_num_positive_examples)

    testdf = decrease_num_negatives(testdf, 184)
    validationdf = decrease_num_negatives(validationdf, 76)

    print('train:')
    print(traindf['target'].value_counts())
    print('test:')
    print(testdf['target'].value_counts())
    print('validation:')
    print(validationdf['target'].value_counts())

    # Define the image size and other parameters
    image_size = (img_size, img_size)
    batch_size = 12
    epochs = 100
    num_classes = 2

    if use_augment:
        title_id = 'Augment - ' + type_augment + ' - test: ' + test_id + ' -' + ' ratio: ' + data_id
        base_name = 'effnetb' + effnet_model + '_augment_testeC' + test_id + '_' + data_id + '_tr_ex_' + str(num_desired_train_examples)
    else:
        title_id = 'No augment - ' + 'test: ' + test_id + ' -' + ' ratio: ' + data_id
        base_name = 'effnetb' + effnet_model + '_no_augment_testeC' + test_id + '_' + data_id + '_tr_ex_' + str(num_desired_train_examples)

    #Important: output folder
    output_dir = os.path.join('../outputs/unbalanced/id_' + str(simulation_ID), base_name)

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
        print("Created folder ", output_dir)

    #%%
    #copy script
    copied_script = os.path.join(output_dir, os.path.basename(sys.argv[0]))
    shutil.copy2(sys.argv[0], copied_script)
    print("Just copied current script as file", copied_script)

    #model = get_training_model_effnet(model_url, trainable=False)
    # model = get_training_model_resnet(trainable=False)
    model = get_training_model_fixed()
    print("just got the model")

    model.compile(loss='binary_crossentropy',
                  optimizer=Adam(learning_rate=0.005),
                  metrics=["accuracy", tf.keras.metrics.AUC()])
                  #metrics=["accuracy"])

    model.summary()

    train_datagen = ImageDataGenerator(rescale=1./255)

    train_generator = train_datagen.flow_from_dataframe(
            dataframe = traindf,
            directory = train_folder,
            x_col="image_name",
            y_col="target",
            target_size=image_size,
            batch_size=batch_size,
            class_mode='binary',
            shuffle=True
        )

    # Loading and preprocessing the training, validation, and test data
    validation_datagen = ImageDataGenerator(rescale=1./255)
    test_datagen = ImageDataGenerator(rescale=1./255)

    validation_generator = validation_datagen.flow_from_dataframe(
            dataframe = validationdf,
            directory = validation_folder,
            x_col="image_name",
            y_col="target",
            target_size=image_size,
            batch_size=batch_size,
            class_mode='binary',
            shuffle=True
    )

    test_generator = test_datagen.flow_from_dataframe(
            dataframe = testdf,
            directory = test_folder,
            x_col="image_name",
            y_col="target",
            target_size=image_size,
            batch_size=batch_size,
            class_mode='binary',
            shuffle=True
    )

    # Count effective number of examples, to make sure
    #print(train_generator.classes)  # numpy array with all labels
    #actual_num_desired_train_examples = train_generator.classes.shape[0]  #flow from directory
    actual_num_desired_train_examples = train_generator.n #flow from dataframe
    print("actual_num_desired_train_examples=", actual_num_desired_train_examples)
    if actual_num_desired_train_examples != num_desired_train_examples:
        print("Updating num_desired_train_examples to", actual_num_desired_train_examples)
        num_desired_train_examples = actual_num_desired_train_examples
        # update base_name
        base_name = 'effnetb' + effnet_model + '_no_augment_testeC' + test_id + '_' + data_id + '_tr_ex_' + str(num_desired_train_examples)

    # Define the EarlyStopping callback
    metric_to_monitor = 'val_auc' #'val_accuracy'
    metric_mode = 'max'
    early_stopping = EarlyStopping(monitor=metric_to_monitor, patience=10, mode=metric_mode)
    #early_stopping = EarlyStopping(monitor='val_auc', patience=5)

    #look at https://www.tensorflow.org/guide/keras/serialization_and_saving
    #do not use HDF5 (.h5 extension)
    #best_model_name = 'best_model_' + base_name + '.h5'
    best_model_name = 'best_model_' + base_name
    best_model_name = os.path.join(output_dir, best_model_name)
    mcp_save = ModelCheckpoint(best_model_name, save_best_only=True, monitor=metric_to_monitor, mode=metric_mode)
    reduce_lr_loss = ReduceLROnPlateau(monitor=metric_to_monitor, factor=0.5, patience=3, verbose=1, min_delta=1e-5, mode=metric_mode)
    # Define Tensorboard as a Keras callback
    tensorboard = TensorBoard(
    log_dir= os.path.join('.\logsunb', base_name),
    #log_dir= '.\logs',
    histogram_freq=1,
    write_images=True
    )

    # Training the model
    history = model.fit(
        train_generator,
        steps_per_epoch=train_generator.samples // batch_size,
        epochs=epochs,
        validation_data=validation_generator,
        callbacks=[early_stopping, mcp_save, reduce_lr_loss, tensorboard]
    )

    # Save the last model
    #look at https://www.tensorflow.org/guide/keras/serialization_and_saving
    #do not use HDF5 (.h5 extension)
    #last_model_name = 'last_model_' + base_name + '.h5'
    last_model_name = 'last_model_' + base_name
    last_model_name = os.path.join(output_dir, last_model_name)
    print("Saving ", last_model_name, "...")
    model.save(last_model_name)

    # Read the best model
    # add custom_objects according to https://stackoverflow.com/questions/61814614/unknown-layer-keraslayer-when-i-try-to-load-model
    model = load_model(best_model_name, custom_objects={'KerasLayer':hub.KerasLayer})

    # Evaluating the best model on the test set
    test_loss, test_accuracy, test_auc = model.evaluate(test_generator)
    print('Test loss:', test_loss)
    print('Test accuracy:', test_accuracy)
    print('Test AUC:', test_auc)

    # Generate predictions --> labels: predicted and true
    predictions = model.predict(test_generator)

    # defining the metrics
    train_loss = history.history['loss']
    val_loss = history.history['val_loss']
    train_acc = history.history['accuracy']
    val_acc = history.history['val_accuracy']

    # Plot the metrics over epochs
    plt.plot(train_loss, label='Training Loss')
    plt.plot(val_loss, label='Validation Loss')
    plt.plot(train_acc, label='Training Accuracy')
    plt.plot(val_acc, label='Validation Accuracy')
    plt.xlabel('Epoch')
    plt.ylabel('Metric')
    plt.legend()
    #plt.show()

    metrics_name = 'metrics_' + base_name + '.png'
    plt.title('Metrics - ' + title_id)
    plt.savefig(os.path.join(output_dir, metrics_name))

    # Convert predictions into values 0 or 1
    N = len(predictions)
    pred_labels = np.zeros( (N,) )
    my_threshold = 0.5 # assume a threshold given predictions are in range [0, 1]
    for i in range(N):
        if predictions[i] > my_threshold:
            pred_labels[i] = 1
        else:
            pred_labels[i] = 0
    true_labels = test_generator.classes

    true_labels = test_generator.classes

    fpr, tpr, thresholds = roc_curve(true_labels, predictions, pos_label=1)
    auc = auc(fpr, tpr)
    print('AUC:', auc)

    recall = recall_score(true_labels, pred_labels)
    f1 = f1_score(true_labels, pred_labels)
    precis = precision_score(true_labels, pred_labels)

    pr_precision, pr_recall, pr_thresholds = precision_recall_curve(true_labels, predictions, pos_label=1)

    print('Recall: ', recall)
    print('Precision: ', precis)
    print('F1-score: ', f1)

    # Compute confusion matrix
    cm = confusion_matrix(true_labels, pred_labels)

    # Plot confusion matrix with Seaborn
    plt.figure()
    sn.heatmap(cm, annot=True, fmt='d')
    plt.title('Confusion matrix - ' + title_id)
    plt.xlabel('Predicted label')
    plt.ylabel('True label')
    #plt.show()

    #save the cm
    cm_filename = 'cm_' + base_name + '.png'
    plt.savefig(os.path.join(output_dir, cm_filename))

    # add to history
    history.history['num_desired_train_examples'] = num_desired_train_examples
    history.history['test_accuracy'] = test_accuracy
    history.history['test_loss'] = test_loss
    history.history['test_confusion_matrix'] = cm
    history.history['recall'] = recall
    history.history['f1'] = f1
    history.history['precis'] = precis
    history.history['auc'] = auc
    history.history['roc_fpr'] = fpr
    history.history['roc_tpr'] = tpr
    history.history['roc_thresholds'] = thresholds
    history.history['pr_precision'] = pr_precision
    history.history['pr_recall'] = pr_recall
    history.history['pr_thresholds'] = pr_thresholds

    # https://stackoverflow.com/questions/41061457/keras-how-to-save-the-training-history-attribute-of-the-history-object
    pickle_file_path = os.path.join(output_dir, 'trainHistoryDict.pickle')
    with open(pickle_file_path, 'wb') as file_pi:
        pickle.dump(history.history, file_pi)

    # Write accuracies and losses to a text file
    file_name = 'classification_output_' + base_name + '.txt'
    with open(os.path.join(output_dir, file_name), 'w') as f:
        f.write('validation_acc\n')
        f.write(str(val_acc))
        f.write('\ntrain_acc\n')
        f.write(str(train_acc))
        f.write('\nvalidation_loss\n')
        f.write(str(val_loss))
        f.write('\ntrain_loss\n')
        f.write(str(train_loss))
        f.write('\ntest_acc\n')
        f.write(str(test_accuracy))
        f.write('\nnum_desired_train_examples\n')
        f.write(str(num_desired_train_examples))


T = int(input())

def htob(n):
    bin = ['0']*4
    idx = -1
    while n > 0:
        n, d = n // 2, n % 2
        bin[idx] = str(d)
        idx -= 1

    return ''.join(bin)

for test_case in range(1, T + 1):
    N, lst = input().split()
    N = int(N)
    lst = list(lst)

    ans = ''
    for i in range(N):
        if lst[i].isdigit():
            ans += htob(int(lst[i]))
        else:
            h = '1' + str(ord(lst[i])-ord('A'))
            ans += htob(int(h))

    print(f'#{test_case}', ans)


from fastapi import FastAPI
import helper
from models import Email, FacebookPost
import content

app = FastAPI()

@app.post("/extract")
async def extract(email: Email):

    content = email.content

    response = helper.extract_email(content)

    arguments = response.choices[0]["message"]["function_call"]["arguments"]

    name = eval(arguments).get("name")
    category = eval(arguments).get("category")
    summary = eval(arguments).get("summary")
    priority = eval(arguments).get("priority")

    return {"name": name, "category": category, "summary": summary, "priority": priority}

@app.post("/create")
async def create(fb: FacebookPost):

    niche = fb.niche
    company = fb.company
    website = fb.website
    topic = fb.topic
    title = fb.title

    response = content.create_fb_content(niche, company, website, topic)

    return {"content": response}


import discord
from discord.ext import commands
from wiki import Wiki

bot = commands.Bot(command_prefix="?")
wiki = Wiki()

@bot.event
async def on_ready():
    print("Logged in as")
    print(bot.user.name)
    print(bot.user.id)
    print("------")

@bot.command()
async def ping(ctx):
    await ctx.send(f"Pong! In {round(bot.latency * 1000)}ms")

@bot.command()
async def lookup(ctx, term):
    d = wiki.lookup(term)
    embed = discord.Embed(title=d["title"], url=d["url"], description=d["desc"])
    embed.set_thumbnail(url=d["image"])

    for k, v in d.items():
        if k not in ["title", "url", "desc", "image"]:
            embed.add_field(name=k, value=v, inline=False)

    await ctx.send(embed=embed)

bot.run(open("token.txt", "r").read())


from moviepy.editor import *
from toolbox import *
from mpyscenes import *
from ..helpers import *

class SceneObject:
    """Base class which defines the properties of an object in a movie scene.
    SceneObjects can be added directly to a Movie if they are more or less
    persistent in a movie.  For animated or special behaviors in a movie, a
    SceneObject can have one or more SceneActions applied to it."""

    def __init__(self, **kwargs):
        self.pos = Point(0, 0)
        self.color = (255, 255, 255)
        self.opacity = 1
        self.scale = 1.0
        self.angle = 0.0
        self.blur = 0
        self.layer = 0
        self.shearx = 0
        self.sheary = 0
        self.x_anim = None
        self.y_anim = None
        self.op_anim = None
        self.scale_anim = None
        self.blur_anim = None
        self.enable_anim = None
        self.angle_anim = None
        self.color_r_anim = None
        self.color_g_anim = None
        self.color_b_anim = None
        self.shearx_anim = None
        self.sheary_anim = None
        self.clip_obj = None
        self.mask_obj = None
        self.is_mask = False
        for k, v in kwargs.items():
            if k in self.__dict__:
                if "color" in k:
                    self.__dict__[k] = color_to_tuple(v)
                else:
                    self.__dict__[k] = v
        if "pixsize" in kwargs:
            self.pixsize = size_preset_tuple(kwargs["pixsize"])
        else:
            self.pixsize = (0, 0)
        if "pos" in kwargs:
            self.set_pos(kwargs["pos"])

        self.prev_color = (255, 255, 255)
        self.fps = 60
        self.buildin = []
        self.buildout = []
        self.actions = []
        self.animators = {}

    def __str__(self):
        s = []
        s.append("SceneObject: %s" % (type(self)))
        for k, v in self.__dict__.items():
            if isinstance(v, dict):
                s.append("  %s:" % (k))
                for ak, av in v.items():
                    s.append("    %s: %s" % (ak, av))
            else:
                s.append("  %s: %s" % (k, v))
        return "\n".join(s)

    @property
    def pix_pos(self):
        x = (self.pos[0] - 0.5) * self.pixsize[0]
        y = (self.pos[1] - 0.5) * self.pixsize[1]
        return x, y

    @property
    def animator_count(self):
        all_animators = [
            self.x_anim,
            self.y_anim,
            self.op_anim,
            self.scale_anim,
            self.blur_anim,
            self.enable_anim,
            self.angle_anim,
            self.color_r_anim,
            self.color_g_anim,
            self.color_b_anim,
            self.shearx_anim,
            self.sheary_anim,
        ]
        ac = 0
        for a in all_animators:
            if a is not None:
                if a.is_active:
                    ac += 1
        return ac

    @property
    def pix_size(self):
        return (self.pixsize[0], self.pixsize[1])

    def pix_dim(self, p):
        return int(p[0] * self.pixsize[0]), int(p[1] * self.pixsize[1])

    def rect_pix_dim(self, rect):
        return int(rect.width * self.pixsize[0]), int(rect.height * self.pixsize[1])

    def set_pos(self, pos, y=None):
        self.pos = Point(pos, y)

    def update_frame_opacity(self, frame):
        if self.op_anim is not None:
            self.opacity = self.op_anim[frame]

    def update_frame_scale(self, frame):
        if self.scale_anim is not None:
            self.scale = self.scale_anim[frame]

    def update_frame_angle(self, frame):
        if self.angle_anim is not None:
            self.angle = self.angle_anim[frame]

    def update_frame_blur(self, frame):
        if self.blur_anim is not None:
            self.blur = self.blur_anim[frame]

    def update_frame_shearx(self, frame):
        if self.shearx_anim is not None:
            self.shearx = self.shearx_anim[frame]

    def update_frame_sheary(self, frame):
        if self.sheary_anim is not None:
            self.sheary = self.sheary_anim[frame]

    def update_frame_color(self, frame):
        color = list(self.color)
        if self.color_r_anim is not None:
            color[0] = int(self.color_r_anim[frame])
        if self.color_g_anim is not None:
            color[1] = int(self.color_g_anim[frame])
        if self.color_b_anim is not None:
            color[2] = int(self.color_b_anim[frame])
        self.prev_color = self.color
        self.color = tuple(color)

    def shear_angles(self):
        angx, angy = 0, 0
        if self.shearx:
            angx = math.degrees(math.atan2(self.shearx, 1))
        if self.sheary:
            angy = math.degrees(math.atan2(self.sheary, 1))
        return angx, angy

    def transform_img(self, img, rect, scale=1.0, no_rotate=False):
        rw, rh = self.pix_dim((rect.width, rect.height))
        xc, yc = self.pix_dim(rect.get_centre())
        angx, angy = self.shear_angles()
        if abs(1.0 - scale) > 0:
            img = ImageOps.scale(img, scale)
        img = add_margin(img, int(max(rw / 2, rh / 2)))
        img = img.rotate(self.angle, expand=True)
        x0, y0 = int(xc - img.size[0] / 2), int(yc - img.size[1] / 2)
        x0 += int(2 * rh * math.sin(math.radians(angx)))
        y0 += int(2 * rw * math.sin(math.radians(angy)))
        ps = (self.pixsize[0], self.pixsize[1])
        if self.shearx:
            img = img.transform(ps, Image.AFFINE, (1.0, self.shearx, 0, 0, 1, 0))
        if self.sheary:
            img = img.transform(ps, Image.AFFINE, (1.0, 0, 0, self.sheary, 1, 0))
        return img, x0, y0

    def assign_animator_from_key(self, key, animator):
        if key == "x":
            self.x_anim = animator
        elif key == "y":
            self.y_anim = animator
        elif key == "left":
            self.left_anim = animator
        elif key == "right":
            self.right_anim = animator
        elif key == "width":
            self.width_anim = animator
        elif key == "height":
            self.height_anim = animator
        elif key == "top":
            self.top_anim = animator
        elif key == "bottom":
            self.bottom_anim = animator
        elif key == "opacity":
            self.op_anim = animator
        elif key == "blur":
            self.blur_anim = animator
        elif key == "scale":
            self.scale_anim = animator
        elif key == "angle":
            self.angle_anim = animator
        elif key == "color_r":
            self.color_r_anim = animator
        elif key == "color_g":
            self.color_g_anim = animator
        elif key == "color_b":
            self.color_b_anim = animator
        elif key == "draw":
            self.draw_anim = animator
        elif key == "shearx":
            self.shearx_anim = animator
        elif key == "sheary":
            self.sheary_anim = animator

    def object_value_from_key(self, key):
        if key == "x":
            return self.pos.x
        elif key == "y":
            return self.pos.y
        elif key == "left":
            return self.rect.left
        elif key == "right":
            return self.rect.right
        elif key == "width":
            return self.rect.width
        elif key == "height":
            return self.rect.height
        elif key == "top":
            return self.rect.top
        elif key == "bottom":
            return self.rect.bottom
        elif key == "opacity":
            return self.opacity
        elif key == "blur":
            return self.blur
        elif key == "scale":
            return self.scale
        elif key == "angle":
            return self.angle
        elif key == "color_r":
            return self.color[0]
        elif key == "color_g":
            return self.color[1]
        elif key == "color_b":
            return self.color[2]
        elif key == "draw":
            return self.draw_length
        elif key == "shearx":
            return self.shearx
        elif key == "sheary":
            return self.sheary
        return None

    def add_action(self, actions):
        actions = listify(actions)
        t0 = actions[0].delay
        for action in actions:
            action.delay = t0
            self.actions.append(action)
            t0 += action.duration

    def add_buildin(self, actions):
        actions = listify(actions)
        t0 = actions[0].delay
        for action in actions:
            action.delay = t0
            self.buildin.append(action)
            t0 += action.duration

    def add_buildout(self, actions):
        actions = listify(actions)
        t0 = actions[0].delay
        for action in actions:
            action.delay = t0
            self.buildout.append(action)
            t0 += action.duration

    def _setup_action_animators(self, actions, start_time=0, **kwargs):
        max_duration = 0
        if len(actions) > 0:
            for action in actions:
                t0 = start_time + action.delay
                td = action.duration + action.delay
                action.setup_animators(start_time=t0, fps=self.fps, **kwargs)
                if "loc" in action.__dict__:
                    self.loc = action.loc
                if td > max_duration:
                    max_duration = td
        return max_duration

    def _initialize_first_animator(self, key, animators):
        a = animators[0]
        if a.link_to_previous:
            a.link_to_previous = False
            v = self.object_value_from_key(key)
            if v is not None:
                a.start_value = v
                if a.previous_to_value is not None:
                    a.stop_value = a.previous_to_value
                else:
                    a.stop_value = a.start_value + a.offset_from_previous

    def _assign_animators(self, key, animators):
        self._initialize_first_animator(key, animators)
        a = AnimatorGroup(animators[0].start_frame, [animators[0]])
        a.fps = self.fps
        if len(animators) > 1:
            for animator in animators[1:]:
                delay = animator.start_frame - a.stop_frame
                a.add_animator(animator, with_delay=delay)
        self.assign_animator_from_key(key, a)
        if key == "x":
            if "loc" in self.__dict__:
                self.pos = Point(0, self.loc)
        elif key == "y":
            if "loc" in self.__dict__:
                self.pos = Point(self.loc, 0)

    def setup_scene(self, start_time=0, **kwargs):
        for action in [*self.buildin, *self.actions, *self.buildout]:
            action.fps = self.fps
        # self.setup_actions()
        t0 = start_time
        t0 += self._setup_action_animators(self.buildin, start_time=t0, **kwargs)
        t0 += self._setup_action_animators(self.actions, start_time=t0, **kwargs)
        t0 += self._setup_action_animators(self.buildout, start_time=t0, **kwargs)
        self.animators = {}
        for action in [*self.buildin, *self.actions, *self.buildout]:
            for k, v in action.animators.items():
                if v is None:
                    continue
                if k not in self.animators:
                    if isinstance(v, list):
                        self.animators[k] = v
                    else:
                        self.animators[k] = [v]
                else:
                    if isinstance(v, list):
                        self.animators[k].extend(v)
                    else:
                        self.animators[k].append(v)
        for k, v in self.animators.items():
            self._assign_animators(k, v)


import sys, os
import numpy as np
import scipy
from scipy.io.wavfile import read, write
from scipy.signal import lfilter
import scipy.signal
from sinsum import sinsum
import matplotlib.pyplot as plt

def lpc_ref(signal, order):
    """Compute the Linear Prediction Coefficients.

    Return the order + 1 LPC coefficients for the signal. c = lpc(x, k) will
    find the k+1 coefficients of a k order linear filter:

      xp[n] = -c[1] * x[n-2] - ... - c[k-1] * x[n-k-1]

    Such as the sum of the squared-error e[i] = xp[i] - x[i] is minimized.

    Parameters
    ----------
    signal: array_like
        input signal
    order : int
        LPC order (the output will have order + 1 items)

    Notes
    ----
    This is just for reference, as it is using the direct inversion of the
    toeplitz matrix, which is really slow"""
    if signal.ndim > 1:
        raise ValueError("Array of rank > 1 not supported yet")
    if order > signal.size:
        raise ValueError("Input signal must have a lenght >= lpc order")

    if order > 0:
        p = order + 1
        r = np.zeros(p, signal.dtype)
        # Number of non zero values in autocorrelation one needs for p LPC
        # coefficients
        nx = np.min([p, signal.size])
        x = np.correlate(signal, signal, 'full')
        r[:nx] = x[signal.size-1:signal.size+order]
        phi = np.dot(scipy.linalg.inv(scipy.linalg.toeplitz(r[:-1])), -r[1:])
        return np.concatenate(([1.], phi))
    else:
        return np.ones(1, dtype = signal.dtype)

def lpc_to_formants(lpc, sr):
    """Convert LPC to formants directly"""

    # extract roots, get angle and radius
    roots = np.roots(lpc)

    pos_roots = roots[np.imag(roots) >= 0]
    if len(pos_roots) < len(roots) // 2:
        pos_roots = list(pos_roots) + [0] * (len(roots) // 2 - len(pos_roots))
    if len(pos_roots) > len(roots) // 2:
        pos_roots = pos_roots[: len(roots) // 2]

    w = np.angle(pos_roots)
    a = np.abs(pos_roots)

    order = np.argsort(w)
    w = w[order]
    a = a[order]

    freqs = w * (sr / (2 * np.pi))
    bws = -0.5 * (sr / (2 * np.pi)) * np.log(a)

    # exclude DC and sr/2 frequencies
    return freqs, bws

def lpc_okno(okno_signala, red, fs):
    """Funkcija, ki poračuna frekvence in amplitude formantov v danem oknu
    signala z uporabo LPC analize."""
    # filtriranje vhodnega signala
    okno_signala = okno_signala * np.hanning(okno_signala.shape[0])
    okno_signala = lfilter([1], [1.0, 0.63], okno_signala)

    # določitev koeficientov LPC filtra z linearno regresijo
    A = lpc_ref(okno_signala, red)

    # Določitev frekvenc in pasovnih širin formantov
    formanti, pasovne_sirine = lpc_to_formants(A, fs)
    amplitude = np.exp(pasovne_sirine / 60)
    return formanti[1:5],  amplitude[1:5]


def solution(nums):
    # answer = 0
    pocket = len(set(nums))
    choose = len(nums)//2
    # if choose > pocket:
    #     answer = pocket
    # else:
    #     answer = choose
    # return answer
    return min(pocket, choose)

print(solution([3,3,3,2,2,2]))


# Standard Library
import traceback
import io

def email_function_failure_traceback(send_email_function):
    def decorator(original_func):
        def new_func(*args, **kwargs):
            try:
                function_value = original_func(*args, **kwargs)
            except Exception as e:
                exc_string = io.StringIO()
                traceback.print_exc(file=exc_string)
                message = exc_string.getvalue()
                message = message.replace('line ', '

line ')
                send_email_function(message)
                raise e
            return function_value
        return new_func
    return decorator


import json

import requests

from sdcclient._common import _SdcCommon

class EventsClientV2(_SdcCommon):
    def __init__(self, token="", sdc_url='https://app.sysdigcloud.com', ssl_verify=True, custom_headers=None):
        super().__init__(token, sdc_url, ssl_verify, custom_headers)
        self.product = "SDC"

    def get_events(self, name=None, category=None, direction='before', status=None, limit=100, pivot=None):
        '''**Description**
            Returns the list of Sysdig Monitor events.

        **Arguments**
            - **name**: filter events by name. Default: None.
            - **category**: filter events by category. Default: ['alert', 'custom', 'docker', 'containerd', 'kubernetes'].
            - **direction**: orders the list of events. Valid values: "before", "after". Default: "before".
            - **status**: status of the event as list. Default: ['triggered', 'resolved', 'acknowledged', 'unacknowledged']
            - **limit**: max number of events to retrieve. Default: 100.
            - **pivot**: event id to use as pivot. Default: None.

        **Success Return Value**
            A dictionary containing the list of events.

        **Example**
            `examples/list_events.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_events.py>`_
        '''
        valid_categories = ['alert', 'custom', 'docker', 'containerd', 'kubernetes']

        if category is None:
            category = valid_categories

        for c in category:
            if c not in valid_categories:
                return False, "Invalid category '{}'".format(c)

        valid_status = ["triggered", "resolved", "acknowledged", "unacknowledged"]
        if status is None:
            status = valid_status

        for s in status:
            if s not in valid_status:
                return False, "Invalid status '{}'".format(s)

        if direction not in ["before", "after"]:
            return False, "Invalid direction '{}', must be either 'before' or 'after'".format(direction)

        options = {
            'alertStatus': status,
            'category': ','.join(category),
            'dir': direction,
            'feed': 'true',
            'include_pivot': 'true',
            'include_total': 'true',
            'limit': str(limit),
            'pivot': pivot,
            'filter': name,
        }
        params = {k: v for k, v in options.items() if v is not None}
        res = requests.get(self.url + '/api/v2/events/', headers=self.hdrs, params=params, verify=self.ssl_verify)
        return self._request_result(res)

    def delete_event(self, event):
        '''**Description**
            Deletes an event.

        **Arguments**
            - **event**: the event object as returned by :func:`~SdcClient.get_events`.

        **Success Return Value**
            `None`.

        **Example**
            `examples/delete_event.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_event.py>`_
        '''
        if 'id' not in event:
            return [False, "Invalid event format"]

        res = requests.delete(self.url + '/api/v2/events/' + str(event['id']), headers=self.hdrs,
                              verify=self.ssl_verify)
        if not self._checkResponse(res):
            return [False, self.lasterr]
        return [True, None]

    def post_event(self, name, description=None, severity=None, event_filter=None, tags=None):
        '''**Description**
            Send an event to Sysdig Monitor. The events you post are available in the Events tab in the Sysdig Monitor UI and can be overlied to charts.

        **Arguments**
            - **name**: the name of the new event.
            - **description**: a longer description offering detailed information about the event.
            - **severity**: syslog style from 0 (high) to 7 (low).
            - **event_filter**: metadata, in Sysdig Monitor format, of nodes to associate with the event, e.g. ``host.hostName = 'ip-10-1-1-1' and container.name = 'foo'``.
            - **tags**: a list of key-value dictionaries that can be used to tag the event. Can be used for filtering/segmenting purposes in Sysdig Monitor.

        **Success Return Value**
            A dictionary describing the new event.

        **Examples**
            - `examples/post_event_simple.py <https://github.com/draios/python-sdc-client/blob/master/examples/post_event_simple.py>`_
            - `examples/post_event.py <https://github.com/draios/python-sdc-client/blob/master/examples/post_event.py>`_
        '''
        options = {
            'name': name,
            'description': description,
            'severity': severity,
            'filter': event_filter,
            'tags': tags
        }
        edata = {
            'event': {k: v for k, v in options.items() if v is not None}
        }
        res = requests.post(self.url + '/api/v2/events/', headers=self.hdrs, data=json.dumps(edata),
                            verify=self.ssl_verify)
        return self._request_result(res)


'''launch dolphin, mainly for recording replays'''

from pathlib import Path
import subprocess
import json
from secrets import token_hex as rand_hex
from time import sleep
from os import rename as move_file
import os
import shutil
# import ubjson
import slippi
import video_tools

# dolphin.ini important settings:
# (no seekbar)
#
# MainWindowPosX = 535
# MainWindowPosY = 17
# MainWindowWidth = 600
# MainWindowHeight = 620
# __ didn't adjust these really
# RenderWindowXPos = 485
# RenderWindowYPos = 57
# RenderWindowWidth = 779
# RenderWindowHeight = 636
#
# => 584x480 (original 73:60 ratio)
#
# EmulationSpeed > 1.0 doesn't seem to work, so no gains there
#
# PauseMovie = True ? hopefully stops replay after n frames; EDIT - it doesn't
#
# make sure muted

# trick to record multiple replays faster: use multiple dolphin instances

def record_replay(replay_filepath, output_dir='../vid_out/', slowdown_factor=1.1):

    # paths
    replay_filepath = Path(replay_filepath)
    dolphin_folder_path = Path(r'../dolphin')
    executable_path = dolphin_folder_path / 'Slippi Dolphin.exe'
    iso_path = read_json('../settings.json')['iso_path']
    tmp_output_folder = Path('../tmp/dolphin_process_0')    # if multiple dolphins output to same folder, there would be default filename conflicts with "framedump0.avi"
    real_output_folder = Path(output_dir)

    DEFAULT_VIDEO_NAME = 'framedump0.avi'
    old_video_path = tmp_output_folder  / DEFAULT_VIDEO_NAME
    new_video_name = replay_filepath.stem + '.avi'
    new_video_path = real_output_folder / new_video_name

    # clear tmp (could have files if error on last run)
    shutil.rmtree(tmp_output_folder)
    os.mkdir(tmp_output_folder)

    # get how long it should take to finish playback
    game = slippi.Game(replay_filepath)
    num_frames = len(game.frames)
    FPS = 60
    duration_sec = num_frames / FPS

    # prep instructions for slippi dolphin to replay
    comm_filepath = generate_commfile(replay_filepath)

    # start dolphin, giving commfile (location) and other misc flags
    # for standard dolphin cmd line, see
    #  https://wiki.dolphin-emu.org/index.php?title=Help:Contents
    process = subprocess.Popen([
        str(executable_path),
        '-i', str(comm_filepath),
        '--hide-seekbar',
        '-e', str(iso_path),
        '-b',
        # '-l',
        # '-d',
        '--output-directory', str(tmp_output_folder),
    ])

    # I wish I could get a dolphin.on_start_playback and on_finish
    #   but this crude dircheck and sleep() will have to suffice

    # wait until video file is created, signaling start
    # print('waiting on dolphin start..')
    while not os.listdir(tmp_output_folder):
        pass
    # print('dolphin has started playing')

    # wait in realtime for replay to finish
    # 4:02 (+123 f) of game duration only made 3:41 of video with slowdown; guess my computer is not fast enough for realtime
    # 244 s made 221 s, so multiply by factor of 244/221 ~= 1.104
    sleep(slowdown_factor * duration_sec) # overshoot with extra time as buffer

    # close dolphin, which will finish recording
    process.terminate()

    # give it time to close so video file can be modified
    sleep(1)

    # abort if video is too short (ie didn't finish)
    if video_tools.num_frames(str(old_video_path)) < num_frames:
        raise Exception('Video did not finish recording; trying again with slowdown_factor + 0.1 ?')
        # return record_replay(replay_filepath, output_dir, slowdown_factor+0.1)
        return -1

    # prep new location
    if new_video_path.exists():
        os.remove(new_video_path)
    # move_file(old_video_path, new_video_path)

    # trim excess "waiting for game.." frames and move to final location
    video_tools.trim(0, num_frames, str(old_video_path), str(new_video_path))

    # alternative idea to implement:
    # use SlippstreamClient (libmelee)
    # read replay file and use libmelee to set up game
    #     (characters, costumes, stage, ports, [tags?])
    # listen for gameevent or menuevent in slippstream client or something
    #     to signal game start and game end
    #
    #     could I start and stop recording on demand?

def play_replay(replay_filepath):
    # mainly just for testing
    replay_filepath = Path(replay_filepath)
    dolphin_folder_path = Path(r'../dolphin')
    executable_path = dolphin_folder_path / 'Slippi Dolphin.exe'
    iso_path = read_json('../settings.json')['iso_path']

    comm_filepath = generate_commfile(replay_filepath)

    return subprocess.Popen([
        str(executable_path),
        '-i', str(comm_filepath),
        # '-m', str(replay_filepath),
        '--hide-seekbar',
        '-e', str(iso_path),
        '-b',
        # '-C', '<System>.Movie.DumpFrames=False'
        # '-C', 'Movie.DumpFrames=False'
        # '-l',
        # '-d',
        # '--output-directory', str(tmp_output_folder),
    ])

def generate_commfile(replay_filepath):
    # comm file is used to tell slippi-dolhpin how to play a replay
    # https://github.com/project-slippi/slippi-wiki/blob/master/COMM_SPEC.md
    # I feel these should be turned into command line flags for simplicity/consistency with slippi dolphin cmd line

    unique_id = rand_hex(3*4)   # n bytes
    comm_filepath = Path(f'../tmp/commfile_{unique_id}.json')
    write_json(comm_filepath, {
        # 'mode': 'normal',   # default normal, or mirror or spectate
        'replay': str(replay_filepath),
        'isRealTimeMode': True,       # seems to prevent slowdowns?
        'commandId': unique_id,
        'startFrame': -123,
        # 'endFrame': num_frames,
    })
    return comm_filepath

# def enhanced_slippi_dolphin_argparse():
#     # remove need for callers to create commfile (-i)
#     # add dolphin configurability
#
#     custom_cmds = {
#         '-r', 'replay filepath'
#         '--config', '[section].[key]=[value]'
#     }
#     args = argparse.args()
#
#     # if there are custom commands, do them
#     for cmd in args:
#         if cmd in custom_cmds:
#             perform(cmd)
#             args.remove(cmd)
#
#     # do the rest of normal slippi dolphin cmdline
#     return subprocess.Popen(args)

def write_json(fp, data):
    with open(fp, 'w') as file:
        json.dump(data, file)

def read_json(fp):
    with open(fp, 'r') as file:
        return json.load(file)

if __name__ == '__main__':
    # record_replay(r'../test/Game_20210408T225110.slp', slowdown_factor=1.25)
    play_replay(r'../test/Game_20210408T225110.slp')


import math
n = int(input())
li = list()

for i in range(n):
    x1, y1, r1, x2, y2, r2 = map(int, input().split())
    dis = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)  # 둘 사이의 거리

    if dis == 0 and r1 == r2:   # 두 원이 겹칠 때
        li.append(-1)
    elif abs(r1 - r2) == dis or r1 + r2 == dis:  # 내접, 외접일 때
        li.append(1)
    elif abs(r1 - r2) < dis < (r1 + r2):  # 두 원이 두 점에서 만날 때
        li.append(2)
    else:
        li.append(0)

for i in range(n):
    print(li[i])