import vk_api
from datetime import datetime
from db_logic import DBLogic

class VkTools:
    def __init__(self, acces_token):
        self.api = vk_api.VkApi(token=acces_token)
        self.db_logic = DBLogic()
        self.offset = 0

    def get_profile_info(self, user_id):
        """
        получение информации о пользователе
        """
        info, = self.api.method('users.get', {'user_id': user_id,
                                              'fields': 'city,bdate,sex,relation'})
        user_info = {'name': f"{info['first_name']} {info['last_name']}",
                     'id': info['id'],
                     'bdate': info.get('bdate'),
                     'sex': info.get('sex'),
                     'city_name': info.get('city')['title'],
                     'city_id': info.get('city')['id'],
                     }
        return user_info

    @staticmethod
    def formation_search_terms(params):
        """
        формирование условий поиска партнера
        """
        age = datetime.now().year - int(params['bdate'].split('.')[2])
        search_terms = {'count': 50,
                        'age_from': age - 5,
                        'age_to': age + 5,
                        'sex': 1 if params['sex'] == 2 else 2,
                        'city': params['city_id'],
                        'city_name': params['city_name'],
                        'status': 6,
                        'is_closed': False}
        return search_terms

    def data_acquisition_user(self, user_id):
        """
        получение фотографий партнера
        """
        attachment = None
        photos = self.api.method('photos.get', {'owner_id': user_id,
                                                'album_id': 'profile',
                                                'extended': 1})
        if photos['count'] > 0:
            photos = sorted(photos['items'], key=lambda x: x['likes']['count'] + x['comments']['count'],
                            reverse=True)[0:3]
            attachment = ','.join([f'photo{photo["owner_id"]}_{photo["id"]}' for photo in photos])
        return attachment

    def search_users(self, search_terms):
        """
        получение списка партнеров
        """
        search_terms['offset'] = self.offset
        users = self.api.method('users.search', search_terms)
        return users['items'] if users.get('items') is not None else []

    def request_for_data_user(self, params_id, search_terms):
        """
        получение информации о партнере
        """
        user_id = None
        user_name = None
        attachment = None
        users = self.search_users(search_terms)
        while user_name is None:
            if users is False:
                users.extend(self.search_users(search_terms))
            user = users.pop()
            user_id = user['id']
            self.offset += 1
            if not self.db_logic.getting_verified_id(params_id, user_id):
                self.db_logic.viewing(params_id, user_id)
                if user['can_access_closed']:
                    user_name = f"{user['first_name']} {user['last_name']}"
                    attachment = self.data_acquisition_user(user_id)
        return user_id, user_name, attachment

    def city_id(self, name):
        """
        определение индетификатора города
        """
        name = name.split(', ')
        city = self.api.method('database.getCities',
                               {'q': {name[0]},
                                'need_all': 0})
        if city['count'] == 0:
            return None, None
        if len(name) > 1:
            for c in city['items']:
                if c.get('region') == name[1].capitalize():
                    return c['id'], name[0]
        return city['items'][0]['id'], name[0]


class Production:
    def __init__(self,production):
        # 产生式的非终结符
        self.nonTerminal = set()
        # 产生式的终结符
        self.terminal = set()
        # 产生式列表
        self.productionList = []
        # 所有符号first集合
        self.firsrset = {}
        #产生式，快速获取产生式
        self.mplist = {}
        self.setProduction(production)

    def getFirstSet(self):
        return self.firsrset

    def getproductionList(self):
        return self.productionList

    # 从confi生成产生式
    def setProduction(self,production):
        for o in production:
            self.productionList.append(ProductinAtom(o["left"],o["right"]))
        self.genNonTerminalTerminal()
        self.genFirstSet()

    # 生成终结符，非终结符，map查找
    def genNonTerminalTerminal(self):
        for Atom in self.productionList:
            self.nonTerminal.add(Atom.getleft())
            for i in Atom.getright():
                self.terminal.add(i)
        self.terminal.difference_update(self.nonTerminal)

        for s in self.nonTerminal:
            pro = []
            for t in self.productionList:
                if t.getleft() == s:
                    pro.append(t)
            self.mplist[s] = pro

    # 生成first集合
    def genFirstSet(self):
        for str in self.terminal:
            self.getFirstData(str)
        for str in self.nonTerminal:
            self.getFirstData(str)

    def getLeftMplist(self,left):
        return self.mplist.get(left)

    # 对某一个符号，生成first集合
    def getFirstData(self,str):
        d = FirstSetData()
        if self.firsrset.get(str) != None:
            return self.firsrset.get(str)

        self.firsrset[str] = d
        # 是终结符
        if str in self.terminal:
            d.add(str)
            d.endToken = False
        else:
            canGetEnd = False
            for p in self.mplist.get(str):
                tmpRight = p.getright()
                if len(tmpRight) == 0:
                    canGetEnd = True
                else:
                    for tmpstr in tmpRight:
                        if tmpstr in self.terminal:
                            d.add(tmpstr)
                            break
                        else:
                            firstData = self.getFirstData(tmpstr)
                            d.add(firstData)
                            if not firstData.isEndToken():
                                break
                        if tmpstr == tmpRight[len(tmpRight)-1]:
                            canGetEnd = True
            d.endToken = canGetEnd
        return d

    # 打印
    def __str__(self):
        pass

# done
class ProductinAtom:
    def __init__(self,left=None,right =None):
        self.left = left
        self.right = right

    def getleft(self):
        return self.left

    def getright(self):
        return self.right

    def __str__(self):
        return "ProductionAtom{" +\
                "left='" + self.left + '\'' +\
                ", right=" + '['+','.join(self.right) + ']'\
                "}"

    def __eq__(self, other):
        if not isinstance(other,ProductinAtom):
            return False
        else:
            return self.left.__eq__(other.left) and self.right.__eq__(other.right)

class FirstSetData:
    def __init__(self,endToken = False):
        self.data  = set()
        self.endToken = endToken

    # str:添加的fitst集
    def add(self,str):
        if isinstance(str,FirstSetData):
            self.data = self.data.union(str.data)
        else:
            self.data.add(str)

    def getData(self):
        return self.data

    # str：移除的first集
    def remove(self):
        self.data.remove(str)

    def clear(self):
        self.data.clear()

    def isEndToken(self):
        return self.endToken

    def __str__(self):
        return "FirstSetData{" +\
                "data=[" + ','.join(self.data) +\
                "], endToken=" + str(self.endToken) +\
                '}'

    def __eq__(self, other):
        if not isinstance(other,FirstSetData):
            return False
        if self.endToken == other.endToken and self.data == other.data:
            return True
        if len(self.data) != len(other.data):
            return False
        return self.endToken == other.endToken and self.data.issuperset(other.data)


#개선된 다익스트라 알고리즘 사용
import heapq

INF = int(1e9) #무한을 나타내는 변수
N, M, C = map(int, input().split())
graph = [[] for _ in range(N+1)]
for _ in range(M) :
  X, Y, Z = map(int, input().split())
  graph[X].append((Y, Z))

distance = [INF] * (N+1) #각 도시에 전보를 보내는 시간을 무한으로 설정

queue = []
heapq.heappush(queue, (0, C)) #전보를 보내는 도시는 C, 자기 자신과의 시간은 0
distance[C] = 0
while queue :
  dist, now = heapq.heappop(queue)
  if distance[now] < dist : continue #이미 처리된 도시라면 건너뛴다
  for i in graph[now] : #통로가 있는 곳을 돌면서
    cost = dist + i[1]
    if cost < distance[i[0]] : #현재 설정된 시간보다 시간이 적게 든다면 재설정
      distance[i[0]] = cost
      heapq.heappush(queue, (cost, i[0]))

cnt = 0 #전보를 보낼 수 있는 도시의 총 개수
total_time = 0 #전보를 보내는 총 시간
for i in range(1, N+1) :
  if distance[i] != INF and distance[i] : #통로가 존재하고, 자기 자신이 아니라면
    cnt += 1
    total_time = max(total_time, distance[i]) #제일 오래 걸린 시간이 전보를 보내는 총 시간

print(cnt, end=' ')
print(total_time)


import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt

import random

def main_1():
    mnist = tf.keras.datasets.mnist

    (x_train, y_train), (x_test, y_test) = mnist.load_data()
    x_train, x_test = x_train/255.0, x_test/255.0

    model = tf.keras.models.Sequential([
        tf.keras.layers.Flatten(input_shape=(28, 28)),
        tf.keras.layers.Dense(128, activation='relu'),
        tf.keras.layers.Dropout(0.2),
        tf.keras.layers.Dense(10, activation='softmax')
    ])

    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])

    model.fit(x_train, y_train, epochs=5)
    model.evaluate(x_test, y_test, verbose=2)

def main_2():
    fashion_mnist = keras.datasets.fashion_mnist
    (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
    class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
                   'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
    print("image的格式为：" + str(train_images.shape))

    model = keras.Sequential([
        keras.layers.Flatten(input_shape=(28, 28)),
        keras.layers.Dense(128, activation='relu'),
        keras.layers.Dense(10)
    ])

    model.compile(optimizer='adam',
                  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                  metrics=['accuracy'])

    model.fit(train_images, train_labels, epochs=10)

    test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
    print("\nTest accuracy:", test_acc)
    print("\nTest Loss:", test_loss)

    probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])
    predictions = probability_model.predict(test_images)
    print(predictions[0])
    print("---------------------------------------------------")

    print(np.argmax(predictions[0]))
    print("This image is an " + class_names[int(np.argmax(predictions[0]))])

    img = test_images[124]
    print(img.shape)
    img = (np.expand_dims(img, 0))
    print(img.shape)

    predictions_single = probability_model.predict(img)
    print(predictions_single)
    print("The result is " + class_names[int(np.argmax(predictions_single))])
    print("The true label is " + class_names[test_labels[124]])

    i = 12
    plt.figure(figsize=(6, 3))
    plt.subplot(1, 2, 1)
    plot_image(i, predictions[i], test_labels, test_images, class_names)
    plt.subplot(1, 2, 2)
    plot_value_array(i, predictions[i], test_labels)
    plt.show()

def plot_image(i, predictions_array, true_label, img, class_names):
    predictions_array, true_label, img = predictions_array, true_label[i], img[i]
    plt.grid(False)
    plt.xticks([])
    plt.yticks([])

    plt.imshow(img, cmap=plt.cm.binary)

    predicted_label = np.argmax(predictions_array)
    if predicted_label == true_label:
        color = 'blue'
    else:
        color = 'red'

    plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
                                         100*np.max(predictions_array),
                                         class_names[true_label]),
               color=color)

def plot_value_array(i, predictions_array, true_label):
    predictions_array, true_label = predictions_array, true_label[i]
    plt.grid(False)
    plt.xticks(range(10))
    plt.yticks([])
    thisplot = plt.bar(range(10), predictions_array, color="#777777")
    plt.ylim([0, 1])
    predicted_label = np.argmax(predictions_array)

    thisplot[predicted_label].set_color('red')
    thisplot[true_label].set_color('blue')

def build_data():
    num_sha1 = 0
    num_md5 = 0
    num_mysql = 0
    with open("jiami_v3.txt", "w") as f:
        with open("sha1.txt", "r") as ff:
            while 1:
                h = ff.readline()
                if h:
                    num_sha1 += 1
                    index = h.find(":")
                    h = h[:index+1] + "0\n"
                    # SHA1
                    f.write(h)
                else:
                    break
        with open("sha1_2.txt", "r") as ff:
            while 1:
                h = ff.readline()
                if h:
                    num_sha1 += 1
                    index = h.find(":")
                    h = h[:index+1] + "0\n"
                    # SHA1
                    f.write(h)
                else:
                    break
        with open("MD5_401.txt", "r") as ff:
            while 1:
                h = ff.readline().strip('\n')
                if h:
                    num_md5 += 1
                    h = h + ":1\n"
                    # MD5
                    f.write(h)
                else:
                    break
        with open("mysql5.txt", "r") as ff:
            while 1:
                h = ff.readline()
                if h:
                    num_mysql += 1
                    index = h.find(":")
                    h = h[:index+1] + "2\n"
                    # MYSQL
                    f.write(h)
                else:
                    break
        with open("mysql_2.txt", "r") as ff:
            while 1:
                h = ff.readline()
                if h:
                    num_mysql += 1
                    index = h.find(":")
                    h = h[:index+1] + "2\n"
                    f.write(h)
                else:
                    break
        with open("mysql_3.txt", "r") as ff:
            while 1:
                h = ff.readline()
                if h:
                    num_mysql += 1
                    index = h.find(":")
                    h = h[:index+1] + "2\n"
                    f.write(h)
                else:
                    break
        with open("mysql_4.txt", "r") as ff:
            while 1:
                h = ff.readline()
                if h:
                    num_mysql += 1
                    index = h.find(":")
                    h = h[:index+1] + "2\n"
                    f.write(h)
                else:
                    break
        with open("mysql_5.txt", "r") as ff:
            while 1:
                h = ff.readline().strip("*")
                if h:
                    num_mysql += 1
                    index = h.find(":")
                    h = h[:index+1] + "2\n"
                    f.write(h)
                else:
                    break
    print("SHA1数量：" + str(num_sha1))
    print("MD5数量：" + str(num_md5))
    print("MYSQL数量：" + str(num_mysql))

    data_s = []
    with open("jiami_v3.txt", "r") as f:
        while 1:
            h = f.readline().strip("\n")
            if h:
                data_s.append(h)
            else:
                break

    random.shuffle(data_s)

    i = len(data_s) * 0.3
    train = data_s[int(i):]
    test = data_s[:int(i)]

    train_x = []
    train_y = []
    test_x = []
    test_y = []

    for i in train:
        h = i.split(":")
        x = np.array([[ord(str(i))] for i in h[0]], dtype='int16')
        train_x.append(x)
        train_y.append(int(h[1]))

    for i in test:
        h = i.split(":")
        x = np.array([[ord(str(i))] for i in h[0]], dtype='int16')
        test_x.append(x)
        test_y.append(int(h[1]))

    train_x = np.asarray(train_x, dtype='int16')
    train_y = np.asarray(train_y)
    test_x = np.asarray(test_x, dtype='int16')
    test_y = np.asarray(test_y)

    print("处理完成")

    return (train_x, train_y), (test_x, test_y)

def main():
    (train_x, train_y), (test_x, test_y) = build_data()
    print(train_x.shape)
    class_names = ['SHA1', 'MD5', 'MYSQL']

    model = keras.models.Sequential([
        keras.layers.Flatten(input_shape=(40, 1)),
        keras.layers.Dense(128, activation='relu'),
        keras.layers.Dense(128, activation='relu'),
        keras.layers.Dense(128, activation='relu'),
        keras.layers.Dense(128, activation='relu'),
        keras.layers.Dense(128, activation='relu'),
        keras.layers.Dense(128, activation='relu'),
        keras.layers.Dense(128, activation='relu'),
        keras.layers.Dense(3)
    ])

    model.compile(optimizer='adam',
                  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                  metrics=['accuracy'])

    model.fit(train_x, train_y, epochs=3)

    test_loss, test_acc = model.evaluate(test_x, test_y, verbose=2)
    print("\nTest accuracy:", test_acc)
    print("\nTest Loss:", test_loss)

    prediction_model = keras.models.Sequential([model, keras.layers.Softmax()])

    mi1 = "62ffe6ed9eb1f842e1247defbd27906b667a9182"  # SHA1
    mi2 = "cdc4fecad57588abdbdf4eaf7b15018992b0f652"  # MYSQL
    mi3 = "320c246daaae25c66081f6dbaaae25c66081f6db"  # MD5

    mi1 = np.array([[ord(i)] for i in mi1], dtype='int16')
    mi2 = np.array([[ord(i)] for i in mi2], dtype='int16')
    mi3 = np.array([[ord(i)] for i in mi3], dtype='int16')

    mi1 = np.expand_dims(mi1, 0)
    mi2 = np.expand_dims(mi2, 0)
    mi3 = np.expand_dims(mi3, 0)

    prediction1 = prediction_model.predict(mi1)
    prediction2 = prediction_model.predict(mi2)
    prediction3 = prediction_model.predict(mi3)

    print("One is " + class_names[int(np.argmax(prediction1))])
    print("Two is " + class_names[int(np.argmax(prediction2))])
    print("Three is " + class_names[int(np.argmax(prediction3))])

if __name__ == "__main__":
    main()


# Filename:mythreading.py
# coding:gbk
# A program to simulate selling tickets in multi-thread way
# Written by Ching

import threading
import time
import os
import random

# 这个函数可以做其他的家务活
def doChore():
    time.sleep(0.5)

def printTicket(num):
    print("remain ticket:",num)

# 这每一个线程要处理的函数
def booth(tid):
    global i
    global lock
    while True:
        lock.acquire()  # 上锁或者等待其他线程释放所，锁，或等待其他线程正在持有锁
        if i != 0:
            i = i - 1  # 售出一张票
            print(tid,':now left:', "Z" + str(int(random.random() * 1000)))  # 打印已售出的车票
            # doChore()  # 其他关键业务
            printTicket(i)
        else:
            print("Thread_id",tid,"No more ticket")  # 打印没有票了
            os._exit(0)  # 全部线程立刻退出
        lock.release()  # 释放锁
        doChore()  # 非关键业务

# Start of the main function 主函数
i = 100  # 票的数量
lock = threading.Lock()  # 给线程上锁

# 开启10个线程
for k in range(10):
    new_thread = threading.Thread(target=booth,args=(k,))  # 给线程设置目标函数
    new_thread.start()  # 开始运行线程


import pprint

import sys
sys.stdout = open("err.txt","w")

a = open("err.log").read().split()
print(len(a))

l = []

for i in range(len(a)//11):
	l.append(a[i*11:i*11+11])

pprint.pprint(l)


from bs4 import BeautifulSoup
import requests

def bs4_config(path=''):
    """
    This function configs a parsing process by making a full URL.
    :param path: Relative URL path of the web page (Default: empty string).
    :return: BeautifulSoup object with html content and parser.
    """
    root_url = 'https://subslikescript.com/'
    website = f'{root_url}{path}'
    content = requests.get(website).text
    return BeautifulSoup(content, 'lxml')

def main():
    """
    This function uses BeautifulSoup library and scrapes movie transcripts from multiple pages of a website,
    extracts the title and transcript of each movie, and saves them to separate text files.
    :return: None
    """
    soup = bs4_config('movies')
    last_page = soup.select_one('li.page-item:nth-last-child(2)').get_text()
    for page in range(1, int(last_page) + 1):
        soup = bs4_config(f'movies?page={page}')
        box = soup.find('article', class_='main-article')
        links = [link['href'] for link in box.find_all('a')]

        for link in links:
            soup = bs4_config(link)
            box = soup.find('article', class_='main-article')
            title = box.find('h1').get_text()
            transcript = box.find('div', class_='full-script').get_text(strip=True, separator=' ')

            with open(f'{title}.txt', mode='w', encoding='utf-8') as file:
                file.write(transcript)

if __name__ == '__main__':
    main()


import pickle
from collections import defaultdict
import itertools
import operator
from torch.utils.data import DataLoader, Dataset
import torch
import json
from functools import reduce
from itertools import accumulate
import random
import numpy as np

U_PATH, B_PATH = {}, {}
U_PATH['wq'] = '../data/WQ/main_exp'
U_PATH['wq_train1test2'] = '../data/WQ/train1test2_exp'
U_PATH['sq'] = '../data/SQ'
for i in [1,2,3]:
    U_PATH[f'pq{i}'] = f'../data/PQ/PQ{i}'
    U_PATH[f'pql{i}'] = f'../data/PQ/PQL{i}'
for i in range(11):
    U_PATH[f'wpq{i}'] = f'../data/PQ/exp3/UHop/{i}'
U_PATH['exp4'] = '../data/PQ/exp4'
U_PATH['grid2_4'] = '../data/grid-world/problem_16_4_2'
U_PATH['grid4_6'] = '../data/grid-world/problem_16_6_4'
U_PATH['grid6_8'] = '../data/grid-world/problem_16_8_6'
U_PATH['grid8_10'] = '../data/grid-world/problem_16_10_8'
B_PATH['wq'] = '../data/baseline/KBQA_RE_data/webqsp_relations/MODE_data.txt'
#PATH['wq'] = '../data/baseline/KBQA_RE_data/webqsp_relations/WebQSP.RE.MODE.with_boundary.withpool.dlnlp.txt'
B_PATH['sq'] = '../data/baseline/KBQA_RE_data/sq_relations/MODE.replace_ne.withpool'
for i in [1,2,3]:
    B_PATH[f'pq{i}'] = f'../data/PQ/baseline/PQ{i}/MODE_data1.txt'
    B_PATH[f'pql{i}'] = f'../data/PQ/baseline/PQL{i}/MODE_data1.txt'
for i in range(11):
    B_PATH[f'wpq{i}'] = f'../data/PQ/exp3/baseline/{i}/MODE_data.txt'
B_PATH['exp4'] = '../data/PQ/exp4/baseline/MODE_data.txt'

from itertools import accumulate

def quick_collate(batch):
    return batch[0]

def random_split(dataset, train_p, valid_p):
    random.shuffle(dataset.data_objs)
    return Subset(dataset.data_objs[:int(len(dataset)*train_p)]), Subset(dataset.data_objs[int(len(dataset)*train_p):])

class Subset(Dataset):
    def __init__(self, data_objs):
        self.data_objs = data_objs
    def __getitem__(self, idx):
        return self.data_objs[idx]
    def __len__(self):
        return len(self.data_objs)

class PerQuestionDataset(Dataset):
    def __init__(self, args, mode, word2id, rela2id):
        super(PerQuestionDataset, self).__init__()
        self.data_objs = self._get_data(args, mode, word2id, rela2id)
    def _get_data(self, args, mode, word2id, rela2id):
        data_objs = []
        if args.framework == 'UHop':
            file_path = U_PATH[args.dataset]
            print(file_path)
            with open(f'{file_path}/{mode}_data.txt', 'r') as f:
                for i, line in enumerate(f):
                    print(f'\rreading line {i}', end='')
                    data = json.loads(line)
                    data = self._numericalize(data, word2id, rela2id, args.q_representation, 'UHop')
                    data_objs.append(data)
        elif args.framework == 'baseline':
            file_path = B_PATH[args.dataset.lower()]
            print(file_path)
            with open(file_path.replace('MODE', mode), 'r') as f:
                for i, line in enumerate(f):
                    print(f'\rreading line {i}', end='')
                    anses, candidates, question = line.strip().split('\t')
                    # modify because of 'noNegativeAnswer' in sq data
                    candidates = [[x, [], 0] for x in candidates.split() if x not in anses.split() and x!='noNegativeAnswer']
                    # modify for "#head_entity#" label in sq dataset
                    ques = question.replace('$ARG1', '').replace('$ARG2', '')
                    ques = ques.replace('<e>', 'TOPIC_ENTITY').replace('#head_entity#', 'TOPIC_ENTITY').strip()
                    for ans in anses.split():
                        data = (i, ques, [[[ans, [], 1]]+candidates])
                        data = self._numericalize(data, word2id, rela2id, args.q_representation, 'baseline')
                        data_objs.append(data)
        return data_objs
    def _numericalize(self, data, word2id, rela2id, q_representation, framework):
        index, ques, step_list = data[0], data[1], data[2]
        if q_representation == "bert":
            ques = self._bert_numericalize_str(ques)
        else:
            ques = self._numericalize_str(ques, word2id, [' '])
        if framework == 'baseline':
            tuples = []
            for t in step_list[0]:
                num_rela = self._numericalize_str(t[0], rela2id, ['.'])
                num_rela_text = self._numericalize_str(t[0], word2id, ['.', '_'])
                num_prev = [self._numericalize_str(prev, rela2id, ['.']) for prev in t[1]]
                num_prev_text = [self._numericalize_str(prev, word2id, ['.', '_']) for prev in t[1]]
                tuples.append((num_rela, num_rela_text, num_prev, num_prev_text, t[2]))
            new_step_list = tuples
        else:
            new_step_list = []
            for step in step_list:
                new_step = []
                for t in step:
                    num_rela = self._numericalize_str(t[0], rela2id, ['.'])
                    num_rela_text = self._numericalize_str(t[0], word2id, ['.', '_'])
                    num_prev = [self._numericalize_str(prev, rela2id, ['.']) for prev in t[1]]
                    num_prev_text = [self._numericalize_str(prev, word2id, ['.', '_']) for prev in t[1]]
                    new_step.append((num_rela, num_rela_text, num_prev, num_prev_text, t[2]))
                new_step_list.append(new_step)
        return index, ques, new_step_list
    def _numericalize_str(self, string, map2id, dilemeter):
        #print('original str:', string)
        if len(dilemeter) == 2:
            string = string.replace(dilemeter[1], dilemeter[0])
        dilemeter = dilemeter[0]
        tokens = string.strip().split(dilemeter)
        tokens = [map2id[x] if x in map2id else map2id['<unk>'] for x in tokens]
        #print('tokens:', tokens)
        return tokens
    def _bert_numericalize_str(self, seq):
        tokens = self.bert_tokenizer.tokenize(seq)
        tokens = self.bert_tokenizer.convert_tokens_to_ids(tokens)
        return tokens
    def __len__(self):
        return len(self.data_objs)
    def __getitem__(self, index):
        return self.data_objs[index]

if __name__ == '__main__':
    with open('../data/WQ/main_exp/rela2id.json', 'r') as f:
        rela2id =json.load(f)
    word2id_path = '../data/glove.300d.word2id.json'
    with open(word2id_path, 'r') as f:
        word2id = json.load(f)
    class ARGS():
        def __init__(self):
            self.dataset = 'wq'
            self.mode = 'train'
        pass
    args = ARGS()
    dataset = PerQuestionDataset(args, 'train', word2id, rela2id)
    print()
    print(0, dataset[100][0])
    print(1, dataset[100][1])
    print(2, dataset[100][2])
    print(len(dataset[100]))


use_model='a3c'#dqn, a2c, a3c, ppo
mode='train'
#openai gym environments
#--------
env_name="CartPole-v0"
use_net='fc_1'#fc_1, lenet, VGG
small_batch=False
#---------
#env_name="Breakout-v0"
#use_net='lenet'
#-------
import gym
Environment=gym.make(env_name)
no_of_actions= Environment.action_space.n
observation_shape=Environment.observation_space.shape
render=False
##--------------
#action_details=Environment.unwrapped.get_action_meanings() #cartpole doesnt has this action meanings but breakout does
#print(action_details)
#print(Environment.action_space.sample())
##--------------
#tensorflow details
input_shape=(None,)+observation_shape
output_shape = (None,)+ (no_of_actions,)
batch_size=4
lr=1E-2
actor_lr=lr
critic_lr=lr
tf_logdir='./graphs/'+use_model+'aclr_'+str(actor_lr)+',crlr'+str(critic_lr)+'/'
import os,shutil
if os.path.exists(tf_logdir):
    shutil.rmtree(tf_logdir)
LOSS_V=100.0#should be float
dir_="./tmp/"+env_name+"/"+use_model
import os
if not os.path.exists(dir_):
    os.makedirs(dir_)
ckpt_dir=dir_+"/model.ckpt"
#RL_agent details
if use_model=='human':
    max_no_episodes=3
    ckpt_episode=1
else:
    max_no_episodes=1000
    ckpt_episode=100

if env_name=='Breakout-v0':
    GAMMA=1
else:
    GAMMA = 0.99

#epsilon greedy, not the learning rate
if mode=='train':
    eps_start = 0.9
    create_video= False
else:
    eps_start = 0.0
    create_video= True

eps_stop  = 0.0
eps_steps = max_no_episodes
d_eps= (eps_start-eps_stop)/eps_steps

#A3C details
THREADS=2

##networks
if use_net=='fc_1':
    from networks.FCN_one_hidden import *
    net=FCN_one_hidden
elif use_net=='lenet':
    from networks.lenet import *
    net=lenet
elif use_net=='VGG':
    from networks.VGG import *
    net=VGG

##observations
# Episodic batch with lr=E-2, Loss_v=100, Epochs=2K, A2C algo works on Cart-pole.
# To work with A2C on cart-pole, when learning online with batch of 10 it takes 3K epochs with Loss_V=1000 and lr=E-3
# To work with A3C on cart-pole, When learning online with batch of 10 it takes 2K epochs with Loss_V=1000 and lr=E-2, THREADS=2


#이진분류
#1. 마지막 아웃풋레이어, activation = 'sigmoid'사용
#2. loss = 'binary_crossentropy'사용
#값이 0과 1로만 나올 수 있게 해줘야함!

import numpy as np
from tensorflow.python.keras.models import Sequential, Model
from tensorflow.python.keras.layers import Dense, Input
from sklearn.model_selection import train_test_split
import pandas as pd
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.covariance import EllipticEnvelope  #reshape필요
from xgboost import XGBRegressor

#1. 데이터
path = 'd:/study/_data/dacon_diabetes/'
path_save = './_save/dacon_diabetes/'

train_csv= pd.read_csv(path+'train.csv', index_col=0)
print(train_csv)
# [652 rows x 9 columns] #(652,9)

test_csv= pd.read_csv(path+'test.csv', index_col=0)
print(test_csv)
#(116,8) #outcome제외

# print(train_csv.isnull().sum()) #결측치 없음
# print(train_csv.columns)
# Index(['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin',
#        'BMI', 'DiabetesPedigreeFunction', 'Age', 'Outcome'],
#       dtype='object')

x = train_csv.drop(['Outcome'], axis=1)
# print(x)
y = train_csv['Outcome']
# print(y)

###이상치 처리###

#이상치 찾는 함수(df)
def outliers(data_out):
    quartile_1, q2, quartile_3 = np.percentile(data_out, [25, 50, 75], axis=0)
    print('1사분위 : ', quartile_1)
    print('q2 : ', q2)
    print('3사분위 : ', quartile_3)
    iqr = quartile_3 - quartile_1
    print('iqr : ', iqr)
    lower_bound = quartile_1 - (iqr * 1.5)
    upper_bound = quartile_3 + (iqr * 1.5)
    return np.where((data_out>upper_bound) | (data_out<lower_bound))
outliers_loc = outliers(x)

print(outliers_loc)
print('이상치의 위치 : ', list(outliers_loc))

# outliers_loc = 9999
x[outliers_loc] = 9999
import matplotlib.pyplot as plt
plt.boxplot(x)
plt.show()

# ###결측치제거###
# train_csv = train_csv.dropna()   #결측치 삭제함수 .dropna()
# print(train_csv.isnull().sum())
# # print(train_csv.info())
# print(train_csv.shape)  #(1328, 10)

imputer = IterativeImputer(estimator=XGBRegressor())
x = imputer.fit_transform(x)
train_csv =x
train_csv = pd.DataFrame(train_csv)
test_csv = pd.DataFrame(test_csv)
train_csv.columns = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin','BMI', 'DiabetesPedigreeFunction', 'Age']
test_csv.columns = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin','BMI', 'DiabetesPedigreeFunction', 'Age']
print(train_csv)
print(test_csv)

x_train, x_test, y_train, y_test = train_test_split(
    x, y, shuffle=True, random_state=640, test_size=0.2,
    stratify=y
)

#data scaling(스케일링)
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.preprocessing import RobustScaler, MaxAbsScaler
# scaler = MinMaxScaler()
scaler = MaxAbsScaler()
scaler.fit(x_train) #x_train범위만큼 잡아라
x_train = scaler.transform(x_train) #변환
#x_train의 변환 범위에 맞춰서 하라는 뜻이므로 scaler.fit할 필요x
x_test = scaler.transform(x_test)
test_csv = scaler.transform(test_csv)

#2. 모델구성
input1 = Input(shape=(8, ))
dense1 = Dense(8, activation='linear')(input1)
dense2 = Dense(4, activation='relu')(dense1)
dense3 = Dense(8, activation='relu')(dense2)
dense4 = Dense(4, activation='relu')(dense3)
output1 = Dense(1, activation='sigmoid')(dense4)
model = Model(inputs=input1, outputs=output1)
#이진분류 - 마지막 아웃풋레이어, 'sigmoid'사용 (0,1사이로 한정)

#3. 컴파일, 훈련

model.compile(loss='binary_crossentropy', optimizer='adam',   #이진분류 - loss, 'binary_crossentropy'사용
              metrics=['accuracy','mse']
              )

from tensorflow.python.keras.callbacks import EarlyStopping
es = EarlyStopping(monitor='val_loss', patience=10, mode='min',
              verbose=1,
              restore_best_weights=True
             )

hist = model.fit(x_train, y_train, epochs=999, batch_size=32,
          validation_split=0.1,
          verbose=1,
          callbacks=[es]
          )

#4. 평가, 예측
results = model.evaluate(x_test, y_test)
print('results:', results)

y_predict = np.round(model.predict(x_test)) #np.round:반올림 / 예측값을 반올림해서 0,1의 값이 나올 수 있도록해줌 (0.5까지는 0으로, 0.6부터는 1로)

from sklearn.metrics import r2_score, accuracy_score
acc = accuracy_score(y_test, y_predict)
print('acc: ', acc)

#submission.csv생성
y_submit = np.round(model.predict(test_csv))  #np.round y_submit에도 해야함!!****
# print(y_submit)

submission = pd.read_csv(path + 'sample_submission.csv', index_col=0)
submission['Outcome'] = y_submit
# print(submission)

submission.to_csv(path_save + 'submit_0313_1800_MaxScaler.csv') # 파일생성

import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family'] = 'Malgun Gothic'
plt.figure(figsize=(9,6))
plt.plot(hist.history['loss'], marker='.', c='red')
plt.plot(hist.history['val_loss'], marker='.', c='blue')
plt.title('따릉이')
plt.xlabel('epochs')
plt.ylabel('loss, val_loss')
plt.legend(('로스', '발_로스'))
plt.grid()
plt.show()

'''
1. 0.65점
acc:0.70/seed: 640784
2. 0.65점
acc:0.74/seed: 88463

3. 0.75점*
acc:0.73
4. 0.78점**
acc:  0.72 /seed:321847
5. [1410]
results: [0.6158730387687683, 0.7022900581359863, 0.2031799852848053]
acc:  0.7022900763358778
6. [0309_1420]/ 0.818점***2등
*stratify=y
results: [0.7886713743209839, 0.7175572514533997, 0.19658119976520538]
acc:  0.71
seed:640, Dense(8,4,8,4,1), batch_size=32

7. [0310_1830]0.810점
results: [0.5848807096481323, 0.694656491279602, 0.20382462441921234]
acc:  0.6946564885496184
patience=310, epochs=10010

8. RobScaler
Epoch 00423: early stopping
results: [0.5853256583213806, 0.7633587718009949, 0.17271968722343445]
acc:  0.7633587786259542
9. MaxScaler

'''


from flask import Blueprint, jsonify, request
from flask_login import login_required, current_user
from peewee import DoesNotExist
from playhouse.shortcuts import model_to_dict

from services import story_auth
from models.character import Character

character = Blueprint('characters', __name__, url_prefix='/api/<int:storyid>/characters')

@character.route('/')
@login_required
@story_auth
def get_all_chars(storyid):
    try:
        characters = [model_to_dict(character, recurse=False) for character in Character.select(
        ).where(Character.story_id == storyid)]
        return jsonify(characters), 200
    except DoesNotExist:
        return jsonify(error='Error finding resources'), 500
    except Exception as e:
        return jsonify(error='Internal server error'), 500

@character.route('/<int:charid>')
@login_required
@story_auth
def get_one_char(storyid, charid):
    try:
        character = Character.get_by_id(charid)
        return jsonify(model_to_dict(character)), 200
    except DoesNotExist:
        return jsonify(error='Character does not exist.'), 404

@character.route('/new', methods=['POST'])
@login_required
@story_auth
def create_char(storyid):
    body = request.get_json()
    character = Character.create(**body, story_id=storyid)
    return jsonify(model_to_dict(character)), 201

@character.route('/edit/<int:charid>', methods=['PUT'])
@login_required
@story_auth
def edit_char(storyid, charid):
    try:
        body = request.get_json()
        (Character
            .update(**body)
            .where((Character.id == charid) & (Character.story_id == storyid))
            .execute())
        character = Character.get_by_id(charid)
        return jsonify(model_to_dict(character)), 203
    except DoesNotExist:
        return jsonify(error='Character does not exist.'), 404

@character.route('/delete/<int:charid>', methods=['DELETE'])
@login_required
@story_auth
def delete_char(storyid, charid):
    try:
        (Character
            .delete()
            .where(Character.id == charid)
            .execute())
        return jsonify(message=None), 204
    except DoesNotExist:
        return jsonify(error='Character not found.'), 404


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

# # SECOND ASSIGNMENT
#
# **GROUP: EARTHQUAKES**
#
# Guadagnini Michele - 1230663
#
# Lambertini Alessandro - 1242885
#
# Pagano Alice - 1236916
#
# Puppin Michele - 1227474

# Import main packages
import pandas as pd
import numpy as np
import scipy as sp
import seaborn as sns
import matplotlib.pyplot as plt
import bokeh.palettes as palette # For palette of colors

import time
import os
import glob
from joblib import Parallel, delayed
import dask.dataframe as dd

class plot_hist:

        def mass(self,df,fMT,metal,ce_str,m_str): #(dataframe,fMT,metal)

                fig = plt.figure(figsize=(30,30))
                ax = [fig.add_subplot(3,3,s) for s in range(1,len(fMT)+1)] #nrows,ncols,index
                fig.suptitle('Plots of distribution of mass '+m_str+' '+ce_str, fontsize=30)
                col = sns.color_palette(palette.viridis(len(metal)))

                for i in range(0,len(fMT)):
                        for j in range(0,len(metal)):
                                #edge = np.logspace(np.log10(df[i][j]['mt1[4]'].min()), np.log10(df[i][j]['mt1[4]'].max()), 30)
                                sns.distplot(df[i][j][m_str],kde=False,norm_hist=False,label=metal[j],
                                                        hist_kws={"histtype": "step","lw": 2},ax=ax[i],color=col[j])

                        ax[i].set_title('Distribution of mass '+m_str+' for fMT={}'.format(fMT[i]),fontsize=18)
                        ax[i].set_xlabel('m $[M_\odot]$',fontsize=18)
                        ax[i].set_ylabel('Counts',fontsize=18)
                        #ax[i].set_xscale('log')
                        ax[i].legend(title='Metallicity',fontsize=14,title_fontsize=16,loc='upper right')
                        ax[i].tick_params(axis="x", labelsize=16)
                        ax[i].tick_params(axis="y", labelsize=16)
                        ax[i].grid(True, which="both", ls="-",color='0.93')
                        ax[i].set_axisbelow(True)

                if not os.path.isdir('./hist_fMT'):
                        os.mkdir('./hist_fMT')

                plt.savefig('hist_fMT/hist_'+m_str+'_fMT_'+ce_str+'.pdf', format='pdf')
                plt.close()

        def dtimes(self,df,fMT,metal,ce_str): #(dataframe,fMT,metal)

                fig = plt.figure(figsize=(30,30))
                ax = [fig.add_subplot(3,3,s) for s in range(1,len(fMT)+1)] #nrows,ncols,index
                fig.suptitle('Plots of distribution of delay times ' + ce_str,fontsize=30)
                col = sns.color_palette(palette.viridis(len(metal)))

                for i in range(0,len(fMT)):
                        for j in range(0,len(metal)):
                                #edge = np.logspace(np.log10(df[i][j]['t_step[1]'].min()), np.log10(df[i][j]['t_step[1]'].max()), 30)
                                sns.distplot(df[i][j]['dtimes'],kde=False,norm_hist=False,label=metal[j],
                                                        hist_kws={"histtype": "step","lw": 2},ax=ax[i],color=col[j])

                        ax[i].set_title('Distribution of delay times for fMT={}'.format(fMT[i]),fontsize=18)
                        ax[i].set_xlabel('t $[Myr]$',fontsize=18)
                        ax[i].set_ylabel('Counts',fontsize=18)
                        #ax[i].set_xscale('log')
                        #ax[i].set_yscale('log')
                        ax[i].legend(title='Metallicity',fontsize=14,title_fontsize=16,loc='upper right')
                        ax[i].tick_params(axis="x", labelsize=16)
                        ax[i].tick_params(axis="y", labelsize=16)
                        ax[i].grid(True, which="both", ls="-",color='0.93')
                        ax[i].set_axisbelow(True)

                if not os.path.isdir('./hist_fMT'):
                        os.mkdir('./hist_fMT')

                plt.savefig('hist_fMT/hist_dtimes_fMT_'+ce_str+'.pdf', format='pdf')
                plt.close()

        def frac_CE(self,df_CE,df_nCE,fMT,metal): #(dataframe,fMT,metal)

                num_fMT_CE = []
                num_fMT_nCE = []

                for i in range(len(fMT)):
                        num_CE = 0
                        num_nCE = 0
                        for j in range(len(metal)):
                                num_CE += df_CE[i][j].shape[0]
                                num_nCE += df_nCE[i][j].shape[0]
                        num_fMT_CE.append(num_CE)
                        num_fMT_nCE.append(num_nCE)

                frac_fMT_CE = [a/(a+b) for a,b in zip(num_fMT_CE,num_fMT_nCE)]
                frac_fMT_nCE = [b/(a+b) for a,b in zip(num_fMT_CE,num_fMT_nCE)]

                fMT = [0.1,0.2,0.3,0.4,0.5,0.7,1]
                fig = plt.figure(figsize=(10,10))
                ax = fig.add_subplot(111)
                fig.suptitle('Plots of fraction of CE BH system',fontsize=30)

                ax.plot(fMT,frac_fMT_CE,'.',color='#440154')
                ax.set_xticks([i/10 for i in range (1,11)])
                ax.set_title('Fraction of CE BH system')
                ax.set_xlabel('fMT')
                ax.set_ylabel('Fraction')
                ax.grid(color='0.93')

                if not os.path.isdir('./hist_fMT'):
                        os.mkdir('./hist_fMT')

                plt.savefig('hist_fMT/frac_CE.pdf', format='pdf')
                plt.close()


import os

import pytest
import pandas as pd
from datetime import datetime, date
from rules import rule_price_earning_ratio

@pytest.mark.parametrize("date_range, from_date_str, outcome", [
    ("1y", "Oct 23 2021", "Oct 23 2020"),
    ("2 years", "Oct 23 2021", "Oct 24 2019"),
    ("1m", "Oct 23 2021", "Sep 23 2021"),
    ("2months", "Oct 24 2021", "Aug 25 2021"),
    ("1d", "Oct 23 2021", "Oct 22 2021"),
    ("2 days", "Oct 23 2021", "Oct 21 2021")
])
def test_extract_date(date_range, from_date_str, outcome):
    from_date = datetime.strptime(from_date_str, "%b %d %Y")
    outcome_date = datetime.strptime(outcome, "%b %d %Y")
    assert outcome_date == rule_price_earning_ratio.extract_date(date_range, from_date)

@pytest.fixture
def load_stock_a():
    stock_a = os.path.join(os.getcwd(), "rules/tests/", "test_data_stock_a.csv")
    df_stock_a = pd.read_csv(stock_a)
    df_stock_a['date'] = pd.to_datetime(df_stock_a['date']).dt.date
    return df_stock_a

@pytest.mark.parametrize("percentile_threshold, date_range, outcome", [
    ("0.1", "1m", False),
    ("0.2", "1m", True),
    ("0.5", "1m", True),
])
def test_filter_by_percentile(load_stock_a, percentile_threshold, date_range, outcome):
    assert outcome == rule_price_earning_ratio.filter_by_percentile(load_stock_a, percentile_threshold, date_range)


import copy
import json
import os
import shutil

import pytest
from django.conf import settings
from django.db.models import Model
from django.db.models.fields.files import FieldFile
from django.db.models.query import QuerySet
from django.template import Context

from monitor_web.models.plugin import (
    CollectorPluginConfig,
    CollectorPluginInfo,
    CollectorPluginMeta,
    OperatorSystem,
    PluginVersionHistory,
)
from monitor_web.plugin.manager import PluginManagerFactory
from monitor_web.plugin.manager.script import ScriptPluginManager

a = os.path.exists("tests")

with open(os.path.join(settings.BASE_DIR, "tests/web/plugin/test_data/create_data.json")) as f:
    CREATE_DATA = json.loads(f.read())

with open(os.path.join(settings.BASE_DIR, "tests/web/plugin/test_data/update_data.json")) as f:
    UPDATE_DATA = json.loads(f.read())

with open(os.path.join(settings.BASE_DIR, "tests/web/plugin/test_data/plugin.json")) as f:
    PLUGIN_DATA = json.loads(f.read())

with open(os.path.join(settings.BASE_DIR, "tests/web/plugin/test_data/info.json")) as f:
    INFO_DATA = json.loads(f.read())

with open(os.path.join(settings.BASE_DIR, "tests/web/plugin/test_data/config.json")) as f:
    CONFIG_DATA = json.loads(f.read())

with open(os.path.join(settings.BASE_DIR, "tests/web/plugin/test_data/current_version.json")) as f:
    CURRENT_VERSION_DATA = json.loads(f.read())
IMPORT_TMP_PATH = os.path.join(settings.BASE_DIR, "tests/web/plugin/test_data/import_test_package/")

@pytest.fixture
def create_plugin_manager(mocker):
    plugin = CollectorPluginMeta(plugin_id="test_plugin", plugin_type="Script")
    config = CollectorPluginConfig()
    info = CollectorPluginInfo()
    version = PluginVersionHistory(plugin=plugin, config=config, info=info)
    mocker.patch.object(PluginVersionHistory.objects, "filter", return_value=QuerySet())
    mocker.patch.object(QuerySet, "last", return_value=version)
    plugin_manager = PluginManagerFactory.get_manager(plugin, "admin")
    return plugin_manager

@pytest.fixture
def update_plugin_manager(mocker):
    create_params = copy.deepcopy(PLUGIN_DATA)
    create_params.pop("scripts")
    create_params.pop("plugin_display_name")
    plugin = CollectorPluginMeta(**create_params)
    config = CollectorPluginConfig(**CONFIG_DATA)
    info = CollectorPluginInfo(**INFO_DATA)
    CURRENT_VERSION_DATA.update({"plugin": plugin, "config": config, "info": info})
    version = PluginVersionHistory(**CURRENT_VERSION_DATA)
    mocker.patch.object(PluginVersionHistory.objects, "filter", return_value=QuerySet())
    mocker.patch.object(QuerySet, "last", return_value=version)
    plugin_manager = PluginManagerFactory.get_manager(plugin, "admin", tmp_path=IMPORT_TMP_PATH)
    return plugin_manager

@pytest.fixture
def mock_save(mocker):
    mocker.patch.object(Model, "save", return_value=None)
    mocker.patch.object(FieldFile, "save", return_value=None)

def new_version(plugin_obj, config_version=None, info_version=None):
    plugin = CollectorPluginMeta(plugin_id="test_plugin", plugin_type="Exporter")
    config = CollectorPluginConfig()
    info = CollectorPluginInfo()
    clear_version = PluginVersionHistory(plugin=plugin, config=config, info=info)
    clear_version.config_version = config_version
    clear_version.info_version = info_version
    return clear_version

class TestBaseManager(object):
    CREATE_DATA = CREATE_DATA
    UPDATE_DATA = UPDATE_DATA
    PLUGIN_DATA = PLUGIN_DATA
    INFO_DATA = INFO_DATA
    CONFIG_DATA = CONFIG_DATA
    CURRENT_VERSION_DATA = CURRENT_VERSION_DATA

    def test_create_version(self, mocker, create_plugin_manager, mock_save):
        mocker.patch.object(CollectorPluginMeta, "generate_version", return_value=create_plugin_manager.version)
        version, need_debug = create_plugin_manager.create_version(self.CREATE_DATA)
        assert version.config.config2dict() == {
            "collector_json": {
                "windows": {"file_id": 1, "file_name": "test_exporter", "md5": "7c1d4ddacd44f1fcee4cf353a54c50e6"}
            },
            "config_json": [],
            "is_support_remote": False,
        }
        assert version.info.info2dict() == {
            "metric_json": [],
            "description_md": "this is a test",
            "plugin_display_name": "test_plugin",
            "logo": "",
        }
        assert version.config_version == 1
        assert version.info_version == 1
        assert version.stage == "unregister"
        assert version.signature == ""
        assert need_debug is True

    def test_update_version(self, update_plugin_manager, mock_save, mocker):
        mocker.patch.object(CollectorPluginMeta, "generate_version", new_version)
        version, need_debug = update_plugin_manager.update_version(self.UPDATE_DATA)
        assert version.info_version == 2
        assert version.config_version == 2
        assert need_debug is True
        assert version.version_log == "this is a test"

    def test_make_package(self, update_plugin_manager, mocker):
        try:
            update_plugin_manager.tmp_path = "tests/web/plugin/tmp_path"
            update_plugin_manager.tmp_path = "tmp_path"
            mocker.patch.object(OperatorSystem.objects, "os_type_list", return_value=["windows", "linux", "aix"])
            return_value = update_plugin_manager.make_package()
            assert os.path.basename(return_value) == "test_plugin.tgz"
        finally:
            shutil.rmtree(update_plugin_manager.tmp_path)

    def test_get_context(self, update_plugin_manager):
        assert update_plugin_manager.get_context() == Context(
            {
                "metric_json": [
                    {
                        "fields": [
                            {
                                "name": "a",
                                "is_active": True,
                                "is_diff_metric": False,
                                "type": "double",
                                "monitor_type": "metric",
                                "unit": "",
                                "description": "a",
                            }
                        ],
                        "table_name": "default",
                        "table_desc": "默认分类",
                    }
                ],
                "plugin_id": "test_plugin",
                "plugin_display_name": "test_plugin",
                "version": "1.1",
                "config_version": 1,
                "plugin_type": "Script",
                "tag": "办公应用",
                "description_md": "this is a test",
                "config_json": [
                    {"default": "", "type": "text", "description": "", "name": "param_pos_cmd", "mode": "opt_cmd"},
                    {"default": "", "type": "text", "description": "", "name": "params_env", "mode": "env"},
                    {"default": "", "type": "text", "description": "", "name": "params_opt_cmd", "mode": "opt_cmd"},
                ],
                "collector_json": {
                    "windows": {
                        "script_content_base64": "QGVjaG8gb2ZmDQplY2hvIDExMQ==",
                        "type": "bat",
                        "filename": "test_plugin.bat",
                    }
                },
                "signature": "",
                "is_support_remote": False,
                "version_log": "",
            }
        )

    def test_start_debug(self, update_plugin_manager, mocker):
        get_debug_config_context_mock = mocker.patch.object(
            ScriptPluginManager,
            "get_debug_config_context",
            return_value={
                "bkmonitorbeat_debug.yaml": {"host": "127.0.0.1", "period": "10"},
                "env.yaml": {"cmd_args": "23"},
            },
        )
        render_config_template_mock = mocker.patch(
            "monitor_web.plugin.manager.base.api.node_man.render_config_template",
            side_effect=[{"id": 1}, {"id": 2}, {"id": 3}],
        )
        start_debug_mock = mocker.patch(
            "monitor_web.plugin.manager.base.api.node_man.start_debug", return_value={"task_id": 11}
        )
        start_debug_params = {"collector": {"host": "127.0.0.1", "period": "10"}, "plugin": {"host_num": "23"}}
        start_debug_host_info = {"bk_cloud_id": 0, "ip": "10.0.1.9", "bk_biz_id": 2}
        assert update_plugin_manager.start_debug(1, 1, start_debug_params, start_debug_host_info) == {"task_id": 11}

        get_debug_config_context_mock.assert_called_once_with(
            1, 1, {"collector": {"host": "127.0.0.1", "period": "10"}, "plugin": {"host_num": "23"}}
        )
        render_config_template_mock.assert_any_call(
            {
                "plugin_name": "test_plugin",
                "plugin_version": "*",
                "name": "env.yaml",
                "version": 1,
                "data": {"cmd_args": "23"},
            }
        )
        render_config_template_mock.assert_any_call(
            {
                "plugin_name": "test_plugin",
                "plugin_version": "*",
                "name": "bkmonitorbeat_debug.yaml",
                "version": 1,
                "data": {"host": "127.0.0.1", "period": "10"},
            }
        )
        start_debug_mock.assert_called_once_with(
            {
                "plugin_name": "test_plugin",
                "version": "1.1",
                "config_ids": [1, 2],
                "host_info": {"bk_cloud_id": 0, "ip": "10.0.1.9", "bk_biz_id": 2},
            }
        )

    def test_stop_debug(self, update_plugin_manager, mocker):
        stop_debug_mock = mocker.patch("monitor_web.plugin.manager.base.api.node_man.stop_debug", return_value=True)
        assert update_plugin_manager.stop_debug(11) is True
        stop_debug_mock.assert_called_once_with(task_id=11)

    def test_query_debug_install(self, update_plugin_manager, mocker):
        query_debug_mock = mocker.patch(
            "monitor_web.plugin.manager.base.api.node_man.query_debug",
            return_value={"status": "INSTALL", "message": "installing", "step": ""},
        )
        assert update_plugin_manager.query_debug(11) == {"status": "INSTALL", "log_content": "installing"}
        query_debug_mock.assert_called_once_with(task_id=11)

    def test_query_debug_failed(self, update_plugin_manager, mocker):
        query_debug_mock = mocker.patch(
            "monitor_web.plugin.manager.base.api.node_man.query_debug",
            return_value={"status": "FAILED", "message": "is_failed"},
        )
        assert update_plugin_manager.query_debug(11) == {"status": "FAILED", "log_content": "is_failed"}
        query_debug_mock.assert_called_once_with(task_id=11)

    def test_query_debug_success(self, update_plugin_manager, mocker):
        query_debug_mock = mocker.patch(
            "monitor_web.plugin.manager.base.api.node_man.query_debug",
            return_value={"status": "SUCCESS", "message": "is_success"},
        )
        assert update_plugin_manager.query_debug(11) == {"status": "SUCCESS", "log_content": "is_success"}
        query_debug_mock.assert_called_once_with(task_id=11)

    def test_query_debug_process(self, update_plugin_manager, mocker):
        query_debug_mock = mocker.patch(
            "monitor_web.plugin.manager.base.api.node_man.query_debug",
            return_value={"status": "DEBUG", "message": "FETCH_DATA", "step": "DEBUG_PROCESS"},
        )
        assert update_plugin_manager.query_debug(11) == {"status": "FETCH_DATA", "log_content": "FETCH_DATA"}
        query_debug_mock.assert_called_once_with(task_id=11)

    def test_release_config(self, update_plugin_manager, mocker):
        release_config_mock = mocker.patch("monitor_web.plugin.manager.base.api.node_man.release_config")
        update_plugin_manager.release_config(1, 1, "env.yaml")
        release_config_mock.assert_called_once_with(
            {"plugin_name": "test_plugin", "plugin_version": "1_1", "name": "env.yaml", "version": 1}
        )

    def test_get_tmp_version(self, update_plugin_manager, mocker):
        assert update_plugin_manager.get_tmp_version() == update_plugin_manager.version


import uuid

from tcmenu.remote.commands.command_factory import CommandFactory
from tcmenu.remote.protocol.message_field import MessageField

def test_menu_pairing_command():
    phone_name = "Android Phone"
    phone_uuid = uuid.uuid4()

    command = CommandFactory.new_pairing_command(name=phone_name, uuid=phone_uuid)
    assert command.name == phone_name
    assert command.uuid == phone_uuid
    assert isinstance(command.command_type, MessageField) is True
    assert command.command_type.id == "PR"


# IBM-1 Alignment Model
# iteratively learns word alignments
# includes a naive noisy channel decoder
# Santi(chai) Pornavalai
# 31.3.19
# tested with Python 3.7.2

# math stuff
import numpy
# serialized saving
import pickle
# tokenization
import re
# language model
from language_model import Ngrams

class AlignmentModel:
	""" Implementation of IBM Model 1. Uses EM to learn lexical/alighment
	 probabilities. Language model is included to turn this into a noisy-channel
	 model. A simple decode algorithm is used. External scripts for evaluation
	 Per convention, variables with e mark target language and f for source, or
	 noisy model """
	def __init__(self):

		# Vocabulary indices
		self.__e_vocab = dict()
		self.__f_vocab = dict()
		# inverse mapping of the above
		self.ind2word_f = dict()
		self.ind2word_e = dict()

		# main lexical alignment weights
		self.trans_prob =[]

		# sentinels for keeping
		self.__num_e = int()
		self.__num_f = int()

		#
		self.data_type = numpy.float16
		self.lang_mod = []

		self.punct_filter =re.compile(r'[^\w]')

	def build_save_lm(self,fname):
		""" builds N-gram language model and dumps to binary """
		with open(fname,"wb") as langfile:
			self.lang_mod =  Ngrams("data/brown.txt")
			pickle.dump(self.lang_mod, langfile)

	def load_lm(self,fname):
		""" loads N-gram language model from binary file"""
		print("loading language model")
		with open(fname,"rb") as langfile:
			self.lang_mod = pickle.load(langfile)

	def translate_sentence(self, in_sent):
		""" translates sentence by simply replacing words """
		in_sent = in_sent.split()
		return " ".join([self.translate_word(w) for w in in_sent])

	def decode(self, in_sent):
		""" A naive noisy channel decoder
			fetches a few candidate translations for a target word
			selects the word which has the
			 highest probability given previous word.
			 This can be highly improved upon by using a variation of the viterbi algorithm
			 e.g viterbi with beamsearch.

			 takes sentence string as argument and returns translated sentence as string

			  """
		#print("translating :", in_sent)
		in_sent = (self.punct_filter.sub(' ',in_sent)).lower()
		in_sent = in_sent.split()
		if len(in_sent) < 2:
			if len(in_sent) > 0:
				return self.translate_word(in_sent[0])
			else:
				return ""
		results = [self.translate_word(in_sent[0])]
		# go through words in sentence
		for i in range(1,len(in_sent)):
			prev_word = results[i-1]
			curr_word = in_sent[i]
			# get 10 candidate translations
			# this number can be varied

			candidates, scores = self.get_n_best(curr_word,5)
			# candidate with highest probability
			tmp_cand = [self.lang_mod.get_prob(prev_word,w)*score for w,score in zip(candidates,scores)]
			enum = list(enumerate(tmp_cand))

			best = max(enum, key = lambda x: x[1])[0]

			results.append(candidates[best])

		return " ".join(results)

	def lazy_reader(self, fname):
		""" A corpus iterator. Takes a tsv file
			in the form

			ENGLISH SENTENCE 1 <TAB>  FRENCH SENTENCE 1
			ENGLISH SENTENCE 2 <TAB>  FRENCH SENTENCE 2

			performs minimal tokenization and sets all the words to lowercase
			"""
		# native f to e translation
		with open(fname,"r") as f:
			pattern = re.compile(r'[^\w]')
			for line in f:
				# verify input later
				foreign , native= line.split("\t")

				native = (pattern.sub(' ',native)).lower()
				foreign = (pattern.sub(' ',foreign)).lower()
				yield  native.strip().split(), foreign.strip().split()

	def trans_prob_getter(self, e_word, f_word):
		""" getter for translation probability"""
		ind_e = self.__e_vocab[e_word]
		ind_f = self.__f_vocab[f_word]
		return self.trans_prob[ind_e][ind_f], ind_e, ind_f

	# e to f

	def get_max(self,word):
		""" get the best translation of word"""
		try:
			ind = self.__e_vocab[word]
		except KeyError:
			print("word not found")
			return 0
		res = numpy.argmax(self.trans_prob[ind])
		return res

	def get_n_best(self,word, n = 10):
		""" get k best for a given target word"""
		# argpartition used to avoid sorting the whole array
		# this approach is O(n) worst case
		try:
			ind = self.__e_vocab[word]
		except KeyError:
			ind = 0
			#raise(ValueError("unknown vocabulary"))
		res = numpy.argpartition(self.trans_prob[ind],-n)
		scores = [self.trans_prob[ind][s] for s in res[-n:]]
		return [self.ind2word_f[word] for word in res[-n:]], scores

	def translate_word(self,word):
		ind_of_best = self.get_max(word)
		return self.ind2word_f[ind_of_best]

	# f to e

	### wrapper functions but for the other way around

	def get_max_e(self,word):
		ind = self.__f_vocab[word]
		res = numpy.argmax(self.trans_prob.T[ind])
		return res

	def get_n_best_e(self,word, n = 10):
		# argpartition used to avoid sorting the whole array
		# this approach is O(n) worst case

		ind = self.__f_vocab[word]
		res = numpy.argpartition(self.trans_prob.T[ind],-n)
		return [self.ind2word_f[word] for word in res[-n:]]

	def translate_word_e(self,word):
		ind_of_best = self.get_max_e(word)
		return self.ind2word_e[ind_of_best]

	def save_weights(self, tm_fname, idx_fname):
		""" dumps translation probabilities and
		indices into two files"""
		with open(tm_fname, "wb") as w_file:
			numpy.save(w_file, self.trans_prob)
		with open(idx_fname, "wb") as idx_file:
			pickle.dump((self.ind2word_e, self.ind2word_f, self.__e_vocab, self.__f_vocab),idx_file)

	def load_weights(self, tm_fname, idx_fname):
		""" loads translation probabilities and
			indices from two files"""

		with open(tm_fname, "rb") as w_file:
			self.trans_prob = numpy.load(w_file)

		with open(idx_fname, "rb") as idx_file:
			self.ind2word_e, self.ind2word_f, self.__e_vocab, self.__f_vocab = pickle.load(idx_file)

	def train(self, fname, iterations = 3, debug = False):
		""" IBM Model 1 alignment model. Trains lexical alignments using
		expectation maxization. Faithful implementation of the pseudo-code as seen
		in the slides from P. Koehn

		This algorithm converges very quickly (2-3 iterations). This can use up a lot of memory. To
		solve this I recommend using half-precision floats (np.float16). This takes 1/4 less memory compared
		to numpy default doubles. There is a trade off in terms of speed but it is relative negligeble.

		The debug option prints the sum of the element-wise difference between previous iterations.
		The smaller the better.

		"""
		# train t(e|f ) or corpus
		# collect counts and build array
		count_e_words = 0
		count_f_words = 0

		for e_sent, f_sent in self.lazy_reader(fname):
			for e_token in e_sent:
				if self.__e_vocab.get(e_token) == None:
					self.__e_vocab[e_token] = count_e_words
					self.ind2word_e[count_e_words] = e_token
					count_e_words += 1

			for f_token in f_sent:
				if self.__f_vocab.get(f_token) == None:
					self.__f_vocab[f_token] = count_f_words
					self.ind2word_f[count_f_words] = f_token
					count_f_words += 1

		uniform = 1 / (count_e_words + count_f_words -2 )
		dimensions = (count_e_words, count_f_words)

		print(count_e_words)
		print(count_f_words)
		self.trans_prob = numpy.full(dimensions, uniform, dtype=self.data_type)

		for it in range(iterations):
			print("starting iteration: ", it)
			count_ef = numpy.zeros(dimensions, dtype=self.data_type)
			total_f = numpy.zeros((dimensions[1],), dtype=self.data_type)

			for e_sent, f_sent in self.lazy_reader(fname):
				sent_total = {e : 0 for e in set(e_sent)}
				for e_token in e_sent:
					for f_token in f_sent:
						sent_total[e_token] += self.trans_prob_getter(e_token,f_token)[0]

				for e_token in e_sent:
					for f_token in f_sent:
						#ind_e = self.__e_vocab[e_token]
						#ind_f = self.__f_vocab[f_token]

						tp, ind_e, ind_f =  self.trans_prob_getter(e_token,f_token)
						val = tp / sent_total[e_token]
						count_ef[ind_e][ind_f] += val
						total_f[ind_f] += val

			print("normalizing")
			if debug:
				print("convergence")
				print(numpy.abs(numpy.sum(self.trans_prob - count_ef / total_f ,dtype = self.data_type)))
			self.trans_prob = count_ef / total_f

	def translate_all(self,fname, print_out = False):
		""" translates all sentences in a given file"""
		results = []
		with open(fname,"r") as f:
			for line in f:
				translation = self.decode(line)
				if print_out:
					print(translation)
				results.append(translation)
		return results

	def verify(self):
		""" debugging function for checking translation probabilities
			by summing up the rows and checking if equal to 1
			using half-precision floats often causes
			a lot of rows to not add up to 1 correctly.
			In practice this doesn't make that big of a difference"""
		width, length = self.trans_prob.shape
		print(width,length)

		for i in numpy.sum(self.trans_prob,dtype=self.data_type,axis=0):
			#if not numpy.isclose(i,1.0,rtol=1e-2):
			print(i)

if __name__ == "__main__":
	model_1 = AlignmentModel()
	model_1.build_save_lm("langmod_en")
	model_1.train("data/e_f.txt",iterations = 3)

	#print(model_1.get_n_best("large"))
	#print(model_1.get_n_best("je",2))
	model_1.load_weights("trans_weights", "vocab_index")
	model_1.translate_all("french_test.txt",True)
	#model_1.verify()
	#model_1.load_lm("langmod_en")
	#print(model_1.get_n_best("bois", 10))
	#model_1.save_weights("trans_weights_1", "vocab_index_1")
	#print(model_1.decode("elle est une chatte"))
	#print(model_1.decode())
	#print(model_1.decode("je suis une baguette"))
	#print(model_1.decode("je bois du vin"))

	while True:
		in_string = input("enter a sentence in french: ")
		print(model_1.decode(in_string))
		#print(model_1.translate_sentence(in_string))

	#print(model_1.decode("je ne puis le dire"))

	#model_1.save_weights("tf_weights", "word_idx")
	#print(model_1.trans_prob)


from game.hilo import Deck

class Director:

    def __init__(self):

        self.playingCard = []
        self.isPlaying = True
        self.gameScore = 300
        self.totalScore = 0

        for i in range(1):
            hiloDeck = Deck()
            self.playingCard.append(hiloDeck)

    def StartGame(self):

        while self.isPlaying:
            self.GetInputs()
            self.DoUpdates()
            self.DoOutputs()

    def GetInputs(self):

        firstCard = ""
        for i in range(len(self.playingCard)):
            hiloDeck = self.playingCard[i]
            firstCard += f"{hiloDeck.cardOne} "
        print()
        print(f"The card is {firstCard}")

    def DoUpdates(self):

        if not self.isPlaying:
            return

        for i in range(len(self.playingCard)):
            hiloDeck = self.playingCard[i]
            hiloDeck.Draw()
            self.gameScore += hiloDeck.playerPoints
        self.totalScore += self.gameScore

    def DoOutputs(self):

        if not self.isPlaying:
            return

        secondCard = ""
        for i in range(len(self.playingCard)):
            hiloDeck = self.playingCard[i]
            secondCard += f"{hiloDeck.cardTwo} "

        print(f"Next card was: {secondCard}")
        print(f"Your score is: {self.totalScore}")

        drawCard = input("Play Again? [y/n] ")

        self.gameScore = 0
        self.isPlaying = self.gameScore > -1

        self.isPlaying = (drawCard == "y")


import numpy as np
from PIL import Image, ImageFont, ImageDraw, ImageChops
from matplotlib import pyplot

text = 'L'
fontfile = '../fonts/Lato-Black.ttf'
result = []

def trim(arr):
    B = np.argwhere(arr)
    (ystart, xstart), (ystop, xstop) = B.min(0), B.max(0) + 1
    atrim = arr[ystart:ystop, xstart:xstop]
    return atrim

for outsize in range(10, 100, 10):

    img = Image.fromarray(np.zeros((2*outsize, 2*outsize)))
    draw = ImageDraw.Draw(img)

    font = ImageFont.truetype(fontfile, outsize)

    tsize = font.getsize(text)

    # draw.text((x, y),"Sample Text",(r,g,b))
    draw.text((outsize/2, outsize/2), text, 1, font=font)
    #draw.text(((1.1*outsize - tsize[0]) / 2, 1.1*outsize / 2 - tsize[1]), text, 1, font=font)
    #draw.text((0,0), text, 1, font=font)
    arr = np.asarray(img)
    atrim = trim(arr)
    result.append(atrim)
    result.append(arr)

#np.save("fontimg.npy", result)

tot = len(result)
for i in range(tot):
    pyplot.subplot(1,tot,i+1)
    pyplot.imshow(result[i], interpolation='none')
pyplot.show()


from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response

from customization_app.models import Customization, MenuCustomization
from menu_app.models import Menu
from temperorycart.models import CartMenuCustomization
class CustomizationMenu(APIView):

	def post(self,request):
		for i in request.data['customId']:
			try:
				customObj = Customization.objects.get(id = i)
				menuObj = Menu.objects.get(id = request.data['menuId'])
				menuCustomObj = MenuCustomization.objects.get(menu_id = request.data['menuId'],customization_id = i)
				cartMenuCustomObj = CartMenuCustomization.objects.get(customization = i,menu_id = request.data['menuId'], customUser = request.user.id)
				cartMenuCustomObj.quantity += 1
				cartMenuCustomObj.save()
				return Response({"status":"customization quantity increased"})
			except Customization.DoesNotExist:
				return Response({"error":"no such customisations exist"}, status=status.HTTP_404_NOT_FOUND)
			except Menu.DoesNotExist:
				return Response({"error":"no such Menu exist"}, status=status.HTTP_404_NOT_FOUND)
			except MenuCustomization.DoesNotExist:
				return Response({"error":"no such Customization  exist for this particular menu"}, status=status.HTTP_404_NOT_FOUND)
			except CartMenuCustomization.DoesNotExist:
				cartMenuCustomObj = CartMenuCustomization(customization = customObj,menu_id = menuObj, customUser = request.user, quantity = 1)
				cartMenuCustomObj.save()
				return Response({"status":"customization applied"})


from wrapper import Wrapper

class AHBLite_wrapper(Wrapper):
    def __init__(self,component,path,info):
        Wrapper.__init__(self,component,path,info)
        self.name+="_AHBlite_wrapper"

    def generateWrapper(self):
        Wrapper.generateWrapper(self)

    def module_Signals(self):
        ver=""
        #AHB-Lite signals
        ver+="\n//AHB-Lite signals\n"
        ver+="//Global signals\n\tinput  wire        HCLK,\n\tinput  wire        HRESETn,\n"
        ver+="//Master signals\n\tinput  wire [23:14] HADDR,\n\tinput  wire [2:0] HBURST,\n\tinput  wire        HMASTLOCK,\n\tinput  wire [3:0]  HPROT,\n\tinput  wire [2:0]  HSIZE,\n\tinput  wire [1:0]  HTRANS,\n\tinput  wire [31:0] HWDATA,\n\tinput  wire        HWRITE,\n"
        ver+="//Slave signals\n\toutput wire [31:0] HRDATA,\n\toutput wire        HREADYOUT,\n\toutput wire        HRESP,\n"
        ver+="//Decoder signal\n\tinput  wire        HSEL,\n"
        ver+="//Multiplexer Signal\n\tinput wire         HREADY,\n"

        return ver

    def map_Signals(self):
        ver=""
        ver+="assign  rd_enable  = HSEL & (~HWRITE);\nassign  wr_enable = HSEL & HWRITE;\n"
        ver+="assign HRESP = 1'b0;\nassign HREADYOUT = 1'b1;\n"

        return ver

    def module_regs(self):
        return Wrapper.module_regs(self)

    def registers_wires(self):
        return Wrapper.registers_wires(self)

    def IO_assignments(self):
        ver=""
        #output always blocks
        ver+="\n//Write"
        for i in range(len(self.regs)):
            if self.regs[i]['access']==0:
                    name=self.regs[i]['name']
                    size=self.regs[i]['size']
                    offeset=int(self.regs[i]['offset'])
                    ver+=("\n//Register: %s\n" %name)
                    ver+=("wire %s_select = wr_enable & (HADDR[23:14] == 10'd%d);\n" %(name, offeset))
                    ver+="always @(posedge HCLK or negedge HRESETn)\nbegin\n\tif (~HRESETn)\n"
                    ver+=("\t\t%s <= %d'h0;\n" %(name,size))
                    ver+=("\telse if (%s_select)\n" %name)
                    ver+=("\t\t%s <= HWDATA;\nend\n" %name)

        #input assignment
        ver+="\n//Read\n"
        ver+="assign HRDATA = \n"
        for i in range(len(self.regs)):
            name=self.regs[i]['name']
            size=self.regs[i]['size']
            offeset=int(self.regs[i]['offset'])
            ver+=("\t(HADDR[23:14] == 10'd%d) ? {%d'd0,%s} :\n"%(offeset, (32-size),name))
        ver+="\t32'hDEADBEEF;\n"

        return ver

    def instantion(self,instname,HCLK,HRESETn,HADDR,HBURST,HMASTLOCK,HPROT,HSIZE,HTRANS,HWDATA,HWRITE,HRDATA,HREADYOUT,HRESP,HSEL,HREADY):

        self.clk=HCLK
        self.reset=HRESETn

        ver=""

        #IP registers wires
        ver+=self.ip_registers_wires()

        #IP irqs wires
        ver+=self.ip_irqs_wires()

        #wrapper instantiation
        ver+=("%s %s( " %(self.name,instname))
        #IP interface signals instantiation
        ver+=self.ip_registers_signals()
        #bus signals instantiation
        ver+=(".HCLK(%s), .HRESETn(%s), .HADDR(%s), .HBURST(%s), .HMASTLOCK(%s), .HPROT(%s), .HSIZE(%s), .HTRANS(%s), .HWDATA(%s), .HWRITE(%s), .HRDATA(%s), .HREADYOUT(%s), .HRESP(%s), .HSEL(%s), .HREADY(%s)" %(HCLK,HRESETn,HADDR,HBURST,HMASTLOCK,HPROT,HSIZE,HTRANS,HWDATA,HWRITE,HRDATA,HREADYOUT,HRESP,HSEL,HREADY))
        ver+=");\n"

        #Actual IP instantiation
        ver+=self.ip_instantiation()

        return ver

    def ip_registers_wires(self):
        return Wrapper.ip_registers_wires(self)

    def ip_registers_signals(self):
        return Wrapper.ip_registers_signals(self)

    def ip_irqs_wires(self):
        return Wrapper.ip_irqs_wires(self)

    def ip_irqs_signals(self):
        return Wrapper.ip_irqs_signals(self)

    def ip_instantiation(self):
        return Wrapper.ip_instantiation(self)


from ..packaging import split_inventory_presamples
from .model_base import ModelBase
try:
    from bw2data.backends.peewee.proxies import Exchange
    from bw2data.backends.peewee.schema import ExchangeDataset
except ImportError:
    Exchange = ExchangeDataset = None

class InventoryBaseModel(ModelBase):
    """Base class for presample models which take a selection of inventory exchanges."""
    def find_exchanges(self, data):
        """Find exchanges and return in a common format. ``data`` is a list of objects used to find exchanges.

        Exchanges can be specified by:

        * A dictionary in the correct format already.
        * ``(input key, output key)``. Will raise a ``ValueError`` if multiple exchanges match.
        * ``(input key, output key, type)``. Type is an exchange type as a string, e.g. technosphere. Will raise a ``ValueError`` if multiple exchanges match.
        * ``bw2data.backends.peewee.proxies.Exchange`` object.

        If Brightway2 is not installed, only dictionaries can be used.

        ``data`` can have mixed types.

        Exchanges are returned as dictionaries, with at least the following keys:

        * input: input key, e.g. ('foo', 'bar')
        * output: output key, e.g. ('foo', 'bar')
        * amount: float
        * type: str, e.g. production

        Most exchanges also include keys like "uncertainty type", "unit", and "name", but do not rely on these keys being present.

        """
        return [self._finder(obj) for obj in data]

    def _finder(self, obj):
        if isinstance(obj, dict):
            return obj
        elif not Exchange:
            raise ImportError("Brightway2 not installed")
        elif isinstance(obj, Exchange):
            return obj._data
        elif isinstance(obj, (list, tuple)) and len(obj) == 2:
            (input_db, input_code), (output_db, output_code) = obj
            qs = ExchangeDataset.select().where(
                ExchangeDataset.input_code==input_code,
                ExchangeDataset.input_database==input_db,
                ExchangeDataset.output_code==output_code,
                ExchangeDataset.output_database==output_db
            )
            if qs.count() != 1:
                raise ValueError("Can't find one exchange for inputs: {}".format(obj))
            return Exchange(qs.get())._data
        elif isinstance(obj, (list, tuple)) and len(obj) == 3:
            (input_db, input_code), (output_db, output_code), kind = obj
            qs = ExchangeDataset.select().where(
                ExchangeDataset.input_code==input_code,
                ExchangeDataset.input_database==input_db,
                ExchangeDataset.output_code==output_code,
                ExchangeDataset.output_database==output_db,
                ExchangeDataset.type==kind
            )
            if qs.count() != 1:
                raise ValueError("Can't find one exchange for inputs: {}".format(obj))
            return Exchange(qs.get())._data
        else:
            raise ValueError("Can't understand this exchange identifier: {}".format(obj))

    @property
    def matrix_data(self):
        if not hasattr(self, "matrix_array"):
            raise ValueError("Must run model first")

        reformat = lambda lst: [(o['input'], o['output'], o['type']) for o in lst]
        return split_inventory_presamples(self.matrix_array, reformat(self.data))


from __future__ import absolute_import, division, print_function
# This script reports a number of space group properties given a space
# group symbol or symmetry matrices, or a combination of the two.

from cctbx import sgtbx
from cctbx.sgtbx import harker
from cctbx.web import io_utils
from cctbx.web import cgi_utils
from six.moves import range

def interpret_form_data(form):
  inp = cgi_utils.inp_from_form(form,
    (("sgsymbol", ""),
     ("convention", "")))
  inp.shelx_latt = []
  inp.symxyz = []
  if ("symxyz" in form):
    lines = form["symxyz"].value.split("\015\012")
    for l in lines:
      # Treat SHELX LATT & SYMM cards
      s = l.strip()
      CARD = s[:4].upper()
      if   (CARD == "LATT"):
        inp.shelx_latt.append(s[4:])
      elif (CARD == "SYMM"):
        inp.symxyz.append(s[4:].strip())
      else:
        # Plain symmetry operations
        for s in l.split(";"):
          s = s.strip()
          if (s != ""): inp.symxyz.append(s)
  return inp

def str_ev(ev):
  return "[%d,%d,%d]" % ev

def rt_mx_analysis_header():
  print("
")
  print("Matrix")
  print("Rotation-part type")
  print("Axis direction")
  print("Screw/glide component")
  print("Origin shift")
  print("
")

def rt_mx_analysis(s):
  print("
")
  print("<tt>" + str(s) + "</tt>")
  r_info = sgtbx.rot_mx_info(s.r())
  t_info = sgtbx.translation_part_info(s)
  if (r_info.type() == 1):
    print("1---")
  elif (r_info.type() == -1):
    print("%d--%s" % (
      r_info.type(),
      str(t_info.origin_shift())))
  elif (abs(r_info.type()) == 2):
    print("%d%s%s%s" % (
      r_info.type(),
      str_ev(r_info.ev()),
      str(t_info.intrinsic_part()),
      str(t_info.origin_shift())))
  else:
    print("%d^%d%s%s%s" % (
       r_info.type(),
       r_info.sense(),
       str_ev(r_info.ev()),
       str(t_info.intrinsic_part()),
       str(t_info.origin_shift())))
  print("
")

def show_group_generic(sg_type, status):
  sg = sg_type.group()
  print("Number of lattice translations:", sg.n_ltr())
  if (sg.is_centric()):
    print("Space group is centric.")
  else:
    print("Space group is acentric.")
  if (sg.is_chiral()):
    print("Space group is chiral.")
  if (sg_type.is_enantiomorphic()):
    print("Space group is enantiomorphic.")
  print("Number of representative symmetry operations:", sg.n_smx())
  print("Total number of symmetry operations:", sg.order_z())
  print()
  print("Parallelepiped containing an asymmetric unit:")
  try: brick = sgtbx.brick(sg_type)
  except RuntimeError as e:
    print(" ", e)
  else:
    print(" ", str(brick).replace("<", "<").replace(">", ">"))
  print()
  print("List of symmetry operations:")
  print("

")
  status.in_table = True
  rt_mx_analysis_header()
  for s in sg: rt_mx_analysis(s)
  print("

")
  status.in_table = False
  print()

def show_symbols(symbols):
  print("  Space group number:", symbols.number())
  print("  Schoenflies symbol:", symbols.schoenflies())
  print("  Hermann-Mauguin symbol:", symbols.hermann_mauguin())
  e = symbols.extension()
  if (e != "\0"):
    if (e in "12"):
      print("  Origin choice:", e)
    elif (e == "H"):
      print("  Trigonal using hexagonal axes")
    elif (e == "R"):
      print("  Trigonal using rhombohedral axes")
    else:
      raise RuntimeError("Internal error")
  q = symbols.qualifier()
  if (q != ""):
    if (symbols.number() < 16):
      if (q[-1] in "123"):
        unique_axis = q[:-1]
        cell_choice = q[-1]
      else:
        unique_axis = q
        cell_choice = ""
      print("  Unique axis:", unique_axis)
      if (cell_choice != ""):
        print("  Cell choice:", cell_choice)
    else:
      print("  Relation to standard setting:", q)
  print("  Hall symbol:", symbols.hall().strip())

def expand_shelx_latt(sg, n_fld):
  z_dict = {
    "P": 1,
    "I": 2,
    "R": 3,
    "F": 4,
    "A": 5,
    "B": 6,
    "C": 7,
  }
  n_dict = {}
  for z in z_dict.keys(): n_dict[z_dict[z]] = z
  try:
    n = int(n_fld)
    z = n_dict[abs(n)]
  except Exception:
    raise RuntimeError("Format Error: LATT " + str(n_fld))
  print("Addition of SHELX LATT " + str(n) + ":")
  if (n > 0):
    print("  Addition of centre of inversion at the origin.")
    sg.expand_smx(sgtbx.rt_mx("-x,-y,-z"))
  print("  Addition of lattice translations for centring type " + str(z) + ".")
  sg.expand_conventional_centring_type(z)
  print()

def run(server_info, inp, status):
  print("
")

  symbols_inp = None
  lookup_symbol = inp.sgsymbol
  if (lookup_symbol == ""): lookup_symbol = "P 1"
  if (inp.convention == "Hall"):
    hall_symbol = lookup_symbol
  else:
    symbols_inp = sgtbx.space_group_symbols(lookup_symbol, inp.convention)
    hall_symbol = symbols_inp.hall()
    if (symbols_inp.number() == 0):
      symbols_inp = None
      inp.convention = "Hall"
    else:
      print("Result of symbol lookup:")
      show_symbols(symbols_inp)
      print()

  try:
    ps = sgtbx.parse_string(hall_symbol)
    sg = sgtbx.space_group(ps)
  except RuntimeError as e:
    print("-->" + ps.string() + "<--")
    print(("-" * (ps.where() + 3)) + "^")
    raise

  io_utils.show_input_symbol(inp.sgsymbol, inp.convention)
  if (len(inp.shelx_latt) != 0):
    for n_fld in inp.shelx_latt:
      expand_shelx_latt(sg, n_fld)

  if (len(inp.symxyz) != 0):
    print("Addition of symmetry operations:")
    print("

")
    status.in_table = True
    rt_mx_analysis_header()
    for s in inp.symxyz:
      ps = sgtbx.parse_string(s)
      try:
        s = sgtbx.rt_mx(ps)
      except RuntimeError as e:
        print("

")
        status.in_table = False
        print("-->" + ps.string() + "<--")
        print(("-" * (ps.where() + 3)) + "^")
        raise
      rt_mx_analysis(s)
      sg.expand_smx(s)
    print("

")
    status.in_table = False
    print()

  sg_type = sg.type()
  show_group_generic(sg_type, status)

  if (   inp.convention == "Hall"
      or len(inp.shelx_latt) != 0
      or len(inp.symxyz) != 0):
    symbols_match = sg.match_tabulated_settings()
    if (symbols_match.number() != 0):
      if (   symbols_inp is None
          or    symbols_inp.universal_hermann_mauguin()
             != symbols_match.universal_hermann_mauguin()):
        print("Symmetry operations match:")
        show_symbols(symbols_match)
        print()
      else:
        print("Additional symmetry operations are redundant.")
        print()
    else:
      print("Space group number:", sg_type.number())
      print("Conventional Hermann-Mauguin symbol:", \
        sgtbx.space_group_symbols(sg_type.number()) \
        .universal_hermann_mauguin())
      print("Universal    Hermann-Mauguin symbol:", \
        sg_type.universal_hermann_mauguin_symbol())
      print("Hall symbol:", sg_type.hall_symbol())
      print("Change-of-basis matrix:", sg_type.cb_op().c())
      print("               Inverse:", sg_type.cb_op().c_inv())
      print()

  wyckoff_table = sgtbx.wyckoff_table(sg_type)
  print("List of Wyckoff positions:")
  print("

")
  status.in_table = True
  print("
")
  print("Wyckoff letter")
  print("Multiplicity")
  print("Site symmetry
point group type")
  print("Representative special position operator")
  print("
")
  for i_position in range(wyckoff_table.size()):
    position = wyckoff_table.position(i_position)
    print("
")
    print("%s%d%s<tt>%s</tt>" % (
      position.letter(),
      position.multiplicity(),
      position.point_group_type(),
      str(position.special_op_simplified())))
    print("
")
  print("

")
  status.in_table = False
  print()

  print("Harker planes:")
  print("

")
  status.in_table = True
  print("
")
  print("Algebraic")
  print("Normal vector")
  print("A point in the plane")
  print("
")
  planes = harker.planes_fractional(sg)
  for plane in planes.list:
    print("
")
    print("<tt>%s</tt>%s%s" % (
      plane.algebraic(), str_ev(plane.n), str(plane.p)))
    print("
")
  print("

")
  status.in_table = False
  print()

  print("Additional generators of Euclidean normalizer:")
  ss = sgtbx.structure_seminvariants(sg)
  ss_vm = ss.vectors_and_moduli()
  print("  Number of structure-seminvariant vectors and moduli:", len(ss_vm))
  if (len(ss_vm)):
    print("    Vector    Modulus")
    for vm in ss_vm: print("   ", vm.v, vm.m)
  k2l = sg_type.addl_generators_of_euclidean_normalizer(True, False)
  l2n = sg_type.addl_generators_of_euclidean_normalizer(False, True)
  if (len(k2l)):
    print("  Inversion through a centre at:", end=' ')
    assert len(k2l) == 1
    print(sgtbx.translation_part_info(k2l[0]).origin_shift())
  if (len(l2n)):
    print("  Further generators:")
    print("

")
    status.in_table = True
    rt_mx_analysis_header()
    for s in l2n: rt_mx_analysis(s)
    print("

")
    status.in_table = False
  print()

  print("Grid factors implied by symmetries:")
  grid_sg = sg.gridding()
  grid_ss = ss.gridding()
  eucl_sg = sg_type.expand_addl_generators_of_euclidean_normalizer(True,True)
  grid_eucl = eucl_sg.refine_gridding(grid_ss)
  print("  Space group:", grid_sg)
  print("  Structure-seminvariant vectors and moduli:", grid_ss)
  print("  Euclidean normalizer:", grid_eucl)
  print()
  print("  All points of a grid over the unit cell are mapped")
  print("  exactly onto other grid points only if the factors")
  print("  shown above are factors of the grid.")
  print()

  print("
")


# Given an array of positive integers nums and an integer k,
# find the length of the longest subarray whose sum is less than or equal to k.

def find_length(nums, k):
    # left boundary pointer of subarray, current sum of subarray, max length of subarray thus far
    left = curr = ans = 0
    # iterate over nums array with right boundary pointer
    for right in range(len(nums)):
        curr += nums[right]
        # while current sum is more than k (we need it less than or equal to k)
        while curr > k:
            # subtract value at left boundary pointer from current sum of current subarray
            curr -= nums[left]
            left += 1
        # maintain length of largest subarray (plus one due to zero index)
        ans = max(ans, right - left + 1)

    return ans

nums = [3, 1, 2, 7, 4, 2, 1, 1, 5]
k = 8
# Output: 4

print(find_length(nums, k))


import unittest
from money_tracker.daos.sql_generic.dao import (
    GenericSQLAccountDAO,
    GenericSQLCategoryDAO,
    GenericSQLTransactionDAO,
)
from money_tracker.daos.sql_generic import SQLiteDAOFactory

class SqliteDAOFactoryTest(unittest.TestCase):
    def test_get_account_dao(self):
        factory = SQLiteDAOFactory("test.db")

        dao = factory.get_account_dao()

        self.assertIsInstance(dao, GenericSQLAccountDAO)

    def test_get_category_dao(self):
        factory = SQLiteDAOFactory("test.db")

        dao = factory.get_category_dao()

        self.assertIsInstance(dao, GenericSQLCategoryDAO)

    def test_get_category_dao(self):
        factory = SQLiteDAOFactory("test.db")

        dao = factory.get_transaction_dao()

        self.assertIsInstance(dao, GenericSQLTransactionDAO)


import torch
from torch.autograd import Function

import torch
import torch.nn as nn
import torch.nn.functional as F

class DiceCoeff(Function):
    """Dice coeff for individual examples"""

    def forward(self, input, target):
        self.save_for_backward(input, target)
        eps = 0.0001
        self.inter = torch.dot(input.view(-1), target.view(-1))
        self.union = torch.sum(input) + torch.sum(target) + eps

        t = (2 * self.inter.float() + eps) / self.union.float()
        return t

    # This function has only a single output, so it gets only one gradient
    def backward(self, grad_output):

        input, target = self.saved_variables
        grad_input = grad_target = None

        if self.needs_input_grad[0]:
            grad_input = grad_output * 2 * (target * self.union - self.inter) \
                         / (self.union * self.union)
        if self.needs_input_grad[1]:
            grad_target = None

        return grad_input, grad_target

def dice_coeff(input_, target):
    """Dice coeff for batches"""
    if input_.is_cuda:
        s = torch.FloatTensor(1).cuda().zero_()
    else:
        s = torch.FloatTensor(1).zero_()

    for i, c in enumerate(zip(input_, target)):
        s = s + DiceCoeff().forward(c[0], c[1])

    return s / (i + 1)

class DiceLoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(DiceLoss, self).__init__()

    def forward(self, inputs, targets, smooth=1):
        # smooth = 1e7

        #comment out if your model contains a sigmoid or equivalent activation layer
        # inputs = F.sigmoid(inputs)

        #flatten label and prediction tensors
        inputs = inputs.view(-1)
        targets = targets.view(-1)

        intersection = (inputs * targets).sum()
        dice = (2.*intersection + smooth)/(inputs.sum() + targets.sum() + smooth)

        return 1 - dice

class DiceBCELoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(DiceBCELoss, self).__init__()

    def forward(self, inputs, targets, smooth=1):

        #comment out if your model contains a sigmoid or equivalent activation layer
        # inputs = F.sigmoid(inputs)

        #flatten label and prediction tensors
        inputs = inputs.view(-1)
        targets = targets.view(-1)

        intersection = (inputs * targets).sum()
        dice_loss = 1 - (2.*intersection + smooth)/(inputs.sum() + targets.sum() + smooth)
        BCE = F.binary_cross_entropy(inputs, targets, reduction='mean')
        Dice_BCE = BCE + dice_loss

        return Dice_BCE

class FocalLoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(FocalLoss, self).__init__()

    def forward(self, inputs, targets, alpha=0.8, gamma=2, smooth=1):

        #comment out if your model contains a sigmoid or equivalent activation layer
        # inputs = F.sigmoid(inputs)

        #flatten label and prediction tensors
        inputs = inputs.view(-1)
        targets = targets.view(-1)

        #first compute binary cross-entropy
        BCE = F.binary_cross_entropy(inputs, targets, reduction='mean')
        BCE_EXP = torch.exp(-BCE)
        focal_loss = alpha * (1-BCE_EXP)**gamma * BCE

        return focal_loss

class BCEFocalLoss(nn.Module):
    def __init__(self, alpha=1, gamma=2, logits=False, reduce=True):
        super(BCEFocalLoss, self).__init__()
        self.alpha = alpha
        self.gamma = gamma
        self.logits = logits
        self.reduce = reduce

    def forward(self, inputs, targets):
        if self.logits:
            BCE_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduce=False)
        else:
            BCE_loss = F.binary_cross_entropy(inputs, targets, reduce=False)
        pt = torch.exp(-BCE_loss)
        F_loss = self.alpha * (1-pt)**self.gamma * BCE_loss

        if self.reduce:
            return torch.mean(F_loss)
        else:
            return F_loss

class TverskyLoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(TverskyLoss, self).__init__()

    def forward(self, inputs, targets, smooth=1, alpha=0.5, beta=0.5):

        #comment out if your model contains a sigmoid or equivalent activation layer
        # inputs = F.sigmoid(inputs)

        #flatten label and prediction tensors
        inputs = inputs.view(-1)
        targets = targets.view(-1)

        #True Positives, False Positives & False Negatives
        TP = (inputs * targets).sum()
        FP = ((1-targets) * inputs).sum()
        FN = (targets * (1-inputs)).sum()

        Tversky = (TP + smooth) / (TP + alpha*FP + beta*FN + smooth)

        return 1 - Tversky

class FocalTverskyLoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(FocalTverskyLoss, self).__init__()

    def forward(self, inputs, targets, smooth=1, alpha=0.5, beta=0.5, gamma=1):

        #comment out if your model contains a sigmoid or equivalent activation layer
        # inputs = F.sigmoid(inputs)

        #flatten label and prediction tensors
        inputs = inputs.view(-1)
        targets = targets.view(-1)

        #True Positives, False Positives & False Negatives
        TP = (inputs * targets).sum()
        FP = ((1-targets) * inputs).sum()
        FN = (targets * (1-inputs)).sum()

        Tversky = (TP + smooth) / (TP + alpha*FP + beta*FN + smooth)
        FocalTversky = (1 - Tversky)**gamma

        return FocalTversky

if __name__ == "__main__":
    import torch
    a = torch.randint(0, 1, (1, 1, 3, 3), dtype=torch.float32)
    c = torch.rand((1, 1, 3, 3), dtype=torch.float32)
    b = torch.randint(0, 2, (1, 1, 3, 3), dtype=torch.float32)
    print(a, b, c)

    loss = BCEFocalLoss()
    print(loss(b, a))
    print(loss(c, a))


# Implementation of algorithm from https://stackoverflow.com/a/22640362/6029703
import numpy as np
import h5py
import os
import argparse
from shutil import copyfile

def thresholding_algo(y, lag):
    min_length = 5000
    signals = np.zeros(len(y))
    blockage = np.zeros(len(y))
    avg = [0]*len(y)
    std = [0]*len(y)
    avg[lag - 1] = np.mean(y[0:lag])
    std[lag - 1] = np.std(y[0:lag])
    current = 0
    first_occurence = 0
    for i in range(lag, len(y)):
        avg[i] = np.mean(y[(i-lag+1):i+1])
        std[i] = np.std(y[(i-lag+1):i+1])
        if abs(avg[i]-avg[i-100]) < 0.015*avg[i]:
            signals[i] = 1
            current += 1
            if current>min_length:
                blockage[i-min_length:i] = 1
                if first_occurence==0:
                    first_occurence = i-min_length
                    print("std:", std[i])
        else:
            current = 0

    return dict(signals = np.asarray(signals),
                blockage = np.asarray(blockage),
                avg = np.asarray(avg),
                first_occurence = first_occurence)

def locate_blk(fast5):
    lag = 400

    for key in fast5['Raw']['Reads'].keys():
        y = fast5['Raw']['Reads'][key]['Signal'][()]
        y = y.astype(np.int16)
    result = thresholding_algo(y, lag=lag)

    return result["first_occurence"]

def find_read(name):
    if 'Read_' in name:
        return name

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True,
    help="path to fast5 files")
ap.add_argument("-b", "--blk", required=True,
    help="path to blk savedir")
ap.add_argument("-n", "--norm", required=True,
    help="path to norm savedir")
args = vars(ap.parse_args())

files = os.listdir(args["input"])
k = 0

for file in files:

    if file.endswith("fast5"):

        fast5 = h5py.File(os.path.join(args["input"], file), 'r')
        k += 1
        CUT = locate_blk(fast5)

        for key in fast5['Raw']['Reads'].keys():
            signal = fast5['Raw']['Reads'][key]['Signal'][()]
            signal = signal.astype(np.int16)
            key_str = fast5['Raw']['Reads'].visit(find_read)

        if CUT>5000:
            print(file)
            copyfile(os.path.join(args["input"], file), os.path.join(args["blk"], file))
        else:
            copyfile(os.path.join(args["input"], file), os.path.join(args["norm"], file))

        if k>4000:
            break


from django.urls import path
from order import views

app_name = 'order'

urlpatterns = [
    #product
    path('product/create', views.Create.as_view(), name='product-create'),
    path('product/get/<int:pk>', views.Get.as_view(), name='product-get'),
    path('product/list', views.List.as_view(), name='product-list'),
    path('product/update/<int:pk>', views.Update.as_view(), name='product-update'),
    path('product/delete/<int:pk>', views.DeleteOne.as_view(), name='product-delete'),

    #order
    path('order/create', views.CreateOrder.as_view(), name='create'),
    path('order/get/<int:pk>', views.GetOrder.as_view(), name='get'),
    path('order/list', views.ListOrder.as_view(), name='list'),
    path('order/update/<int:pk>', views.UpdateOrder.as_view(), name='update'),
    path('order/delete/<int:pk>', views.DeleteOneOrder.as_view(), name='delete')
]


# -*- coding: utf-8 -*-
"""
Created on Wed Jan 26 11:30:22 2022

@author: CPEGM

Sujet n°20

"""

# Exercice 1
def xor(L1, L2):
    T = []
    for k in range(len(L1)):
        if L1[k] == L2[k]:
            T.append(0)
        else:
            T.append(1)
    return T

a = [1, 0, 1, 0, 1, 1, 0, 1]
b = [0, 1, 1, 1, 0, 1, 0, 0]
c = [1, 1, 0, 1]
d = [0, 0, 1, 1]
assert(xor(a, b) == [1, 1, 0, 1, 1, 0, 0, 1])
assert(xor(c, d) == [1, 1, 1, 0])

# Exercice 2
class Carre:
    def __init__(self, tableau = [[]]):
        self.ordre = len(tableau)
        self.valeurs = tableau

    def affiche(self):
        '''Affiche un carré'''
        for i in range(self.ordre):
            print(self.valeurs[i])

    def somme_ligne(self, i):
        '''Calcule la somme des valeurs de la ligne i'''
        return sum(self.valeurs[i])

    def somme_col(self, j):
        '''calcule la somme des valeurs de la colonne j'''
        return sum([self.valeurs[i][j] for i in range(self.ordre)])

def est_magique(carre):
    n = carre.ordre
    s = carre.somme_ligne(0)

    #test de la somme de chaque ligne
    for i in range(0, n):
        if carre.somme_ligne(i) != s:
            return False

    #test de la somme de chaque colonne
    for j in range(n):
        if carre.somme_col(j) != s:
            return False

    #test de la somme de chaque diagonale
    if sum([carre.valeurs[k][k] for k in range(n)]) != s:
            return False
    if sum([carre.valeurs[k][n-1-k] for k in range(n)]) != s:
            return False

    return True

c2 = Carre([[1,1],[1,1]])
c3 = Carre([[2,9,4],[7,5,3],[6,1,8]])
c4 = Carre([[4,5,16,9],[14,7,2,11],[3,10,15,6],[13,12,8,1]])

print("c2 magique?", est_magique(c2))
print("c3 magique?", est_magique(c3))
print("c4 magique?", est_magique(c4))