import numpy as np

def get_ap(ap, dim0, dim1):
    if ap == 'PCA':
        a = np.identity(dim0)
        return np.pad(a, ((0, 0), (0, dim1 - dim0)))
    elif ap == 'RP':
        return np.random.random((dim0, dim1))
    elif ap == 'WPCA':
        feature = np.load("/home/chenzhentao/fgfv_data/LBP_pca_feature_500.npz", allow_pickle=True)['feature'].item()
        f_v = feature['feature_value'][:dim0]
        f_v = np.sqrt(f_v)
        a = np.diag(f_v)
        return np.pad(a, ((0, 0), (0, dim1 - dim0)))
    else:
        return np.ones((dim0, dim1))


import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
# Function: K Means
# -------------
# K-Means is an algorithm that takes in a dataset and a constant
# k and returns k centroids (which define clusters of data in the
# dataset which are similar to one another).
# maxIt最大的迭代次数
def kmeans(X, k, maxIt):

    # 得到 行、列 数
    numPoints, numDim = X.shape
    # 矩阵多加一列，并且全部赋值为0
    dataSet = np.zeros((numPoints, numDim + 1))
    # 把原始数据集赋值给新的数组dataSet,其中最后一列为0
    dataSet[:, :-1] = X

    # Initialize centroids randomly
    # 从矩阵每行中随机选取K行  也就是说 选k个中心点
    centroids = dataSet[np.random.randint(numPoints, size=k), :]
    # centroids = dataSet[0:2, :]
    # Randomly assign labels to initial centorid
    # 对k行的最后一列 赋值 k种类别
    centroids[:, -1] = range(1, k + 1)

    # Initialize book keeping vars.
    iterations = 0
    oldCentroids = None

    # Run the main k-means algorithm
    # shouldStop（）计算迭代停止 条件
    while not shouldStop(oldCentroids, centroids, iterations, maxIt):
        print("iteration: \n", iterations)
        print("dataSet: \n", dataSet)
        print("centroids: \n", centroids)

        # Save old centroids for convergence test. Book keeping.
        # numpy复制数组
        oldCentroids = np.copy(centroids)
        iterations += 1

        # Assign labels to each datapoint based on centroids
        # 对每行数据 更新类别数据 所属的类别需要不断的更新
        updateLabels(dataSet, centroids)

        # Assign centroids based on datapoint labels
        # 重新获取中心点 计算平均值
        centroids = getCentroids(dataSet, k)

    # We can get the labels too by calling getLabels(dataSet, centroids)
    return dataSet

# Function: Should Stop
# -------------
# Returns True or False if k-means is done. K-means terminates either
# because it has run a maximum number of iterations OR the centroids
# stop changing.
def shouldStop(oldCentroids, centroids, iterations, maxIt):
    if iterations > maxIt:
        return True
    # 注意数组的比较 使用numpy的array_equal函数
    return np.array_equal(oldCentroids, centroids)

# Function: Get Labels
# -------------
# Update a label for each piece of data in the dataset.
def updateLabels(dataSet, centroids):
    # For each element in the dataset, chose the closest centroid.
    # Make that centroid the element's label.
    numPoints, numDim = dataSet.shape
    for i in range(0, numPoints):
        dataSet[i, -1] = getLabelFromClosestCentroid(dataSet[i, :-1], centroids)

def getLabelFromClosestCentroid(dataSetRow, centroids):
    label = centroids[0, -1]
    #norm 表示范数 默认为L2  这里算出了两个向量之间的距离
    minDist = np.linalg.norm(dataSetRow - centroids[0, :-1])
    for i in range(1, centroids.shape[0]):
        dist = np.linalg.norm(dataSetRow - centroids[i, :-1])
        if dist < minDist:
            minDist = dist
            # 更新距离相近的点 的类别
            label = centroids[i, -1]
    print("minDist:", minDist)
    return label

# Function: Get Centroids
# -------------
# Returns k random centroids, each of dimension n.
def getCentroids(dataSet, k):
    # Each centroid is the geometric mean of the points that
    # have that centroid's label. Important: If a centroid is empty (no points have
    # that centroid's label) you should randomly re-initialize it.
    result = np.zeros((k, dataSet.shape[1]))
    for i in range(1, k + 1):
        oneCluster = dataSet[dataSet[:, -1] == i, :-1]
        # 对两个点之间计算平均值，更新中心点的位置
        result[i - 1, :-1] = np.mean(oneCluster, axis=0)
        result[i - 1, -1] = i

    return result

# 准备数据集
x1 = np.array([1, 1])
x2 = np.array([2, 1])
x3 = np.array([4, 3])
x4 = np.array([5, 4])
x5=np.array([6,3])
x6=np.array([1,1.5])

# 合并为一个矩阵
# testX = np.vstack((x1, x2, x3, x4,x5,x6))
# testX=np.random.randint(1,100,size=[100,5])
testX, y = make_blobs(n_samples=1500, random_state=150)

#自己实现kmeans testx:数据集 3：K值 15：最大迭代次数
result = kmeans(testX, 3, 15)

# 绘制散点图
plt.figure(figsize=(10, 10))
# plt.subplot(221)
plt.scatter(result[:,0],result[:,1],result[:,2],c=result[:,-1])
plt.show()

print("final result:\n",result)


from Block import *

# Define an entity in the game with unique behaviors
class Agent:
    def __init__(self, uid, environment, layers, sight, color, width, height):
        self.uid = uid  # Unique ID
        self.environment = environment  # environment the agent is inside of (reference)
        self.sight = 1  # how far the agent can "see"
        self.path = None  # trajectory
        self.block = Block(color, width, height)  # Block sprite


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

#Venn diagrams
import pandas as pd
ibd_data = pd.read_pickle("datasetspandas/dutch_export_transposed_ibd_binary.pkl")
ibd_data.rename(columns={'Unnamed: 0': 'sample_id'}, inplace=True)
ibd_data.index.name = 'sample_id'

#Fetch cohort ID
covariates = pd.read_excel("Covariates/CDvsUC analysis covariates.xlsx")
covariates = covariates.set_index('sample_id')
del covariates['Plate_id']
del covariates['Age']
del covariates['Gender']

#Define groups
df_CD = covariates.loc[covariates['IBD type'] == 1]
df_UC = covariates.loc[covariates['IBD type'] == 0]
df_IBD = covariates.merge(ibd_data, on=["sample_id"])
cd_data = df_CD.merge(ibd_data, on=["sample_id"])
del cd_data['IBD type']
uc_data = df_UC.merge(ibd_data, on=["sample_id"])
del uc_data['IBD type']
del df_IBD['IBD type']

#CD feature selection (5% threshold)
def Prevalence(Series):
    Prev = Series.sum()/Series.count()
    return(Prev)
Prev_thresh = 0.05
print("Computing antibody prevalence")
Prevalences = df_IBD.apply(Prevalence, axis=0)
Vector_keep = Prevalences > Prev_thresh #True/False vector of the features with prevalence > 5%
df_IBD_f = df_IBD[Vector_keep.index[Vector_keep]] #Removal of columns that do not pass the prevalence threshold

#UC feature selection (5% threshold)
def Prevalence(Series):
    Prev = Series.sum()/Series.count()
    return(Prev)
Prev_thresh = 0.05
print("Computing antibody prevalence")
Prevalences = uc_data.apply(Prevalence, axis=0)
Vector_keep = Prevalences > Prev_thresh #True/False vector of the features with prevalence > 5%
uc_data_f = uc_data[Vector_keep.index[Vector_keep]] #Removal of columns that do not pass the prevalence threshold

cd_unique = cd_data_f.T
uc_unique = uc_data_f.T
cd_unique.to_excel("datasetspandas/cd_unique_features.xlsx")
uc_unique.to_excel("datasetspandas/uc_unique_features.xlsx")

df_IBD_f
ibd_unique = df_IBD_f.T
ibd_unique.to_excel("datasetspandas/ibd_unique_features.xlsx")

##Hereafter, random peptide selection exclusion and >95% exclusion was performed manually to compute overlapping numbers

#Figures
from matplotlib_venn import venn3, venn3_circles, venn3_unweighted
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
fig = plt.figure()

#Custom it
sns.set(rc={"figure.dpi":600, 'savefig.dpi':600})
sns.set(rc={'figure.figsize':(7,7)}, font_scale = 1.5)
sns.set_style("white")
c = venn3_unweighted(subsets=(281, 243, "", "", 227, 122, 1974), set_labels = ('CD', 'UC', 'IBD'), alpha=1)

#Add title and annotation
c.get_patch_by_id('100')
c.get_patch_by_id('010')
c.get_patch_by_id('001')
plt.title("Prevalence of antibody probes (≥5%)", fontsize=18)
plt.savefig("datasetspandas/VennDiagramPrevalence-updatedsep2021.jpg", bbox_inches='tight', dpi=600)

from matplotlib_venn import venn2, venn2_circles, venn2_unweighted
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

#Custom it
sns.set(rc={"figure.dpi":600, 'savefig.dpi':600})
sns.set(rc={'figure.figsize':(7,7)}, font_scale = 1.5)
sns.set_style("white")
c2 = venn2_unweighted(subsets = ('205', '104', '64'), set_labels = ('CD', 'UC'), alpha=0.5)

#Add title and annotation
c2.get_patch_by_id('10').set_color('deepskyblue')
c2.get_patch_by_id('01').set_color('lightblue')
c2.get_patch_by_id('11').set_color('darkblue')
c2.get_label_by_id('10').set_fontsize(18)
c2.get_label_by_id('01').set_fontsize(18)
c2.get_label_by_id('11').set_fontsize(18)
plt.title("Differentially abundant peptides", fontstyle="italic")
plt.suptitle("Total: 373 peptides (FDR≤0.05)", fontstyle="italic", x=0.52, y=0.78, fontsize=10)
plt.savefig("datasetspandas/VennDiagramCC-analysis-total_updatedaug2021.jpg", bbox_inches='tight', dpi=600)


from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import time

# Signup
class Quantibly():
    def test_signup_valid(self):
        base_url = 'https://app.quantibly.com/register/'
        driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
        driver.maximize_window()
        driver.get(base_url)

        # Find Elements
        organization_name = driver.find_element(By.XPATH, '//*[@id="app"]/div/div/div/div/div/div[2]/div/div/form/section/div[1]/div/input')
        email_address = driver.find_element(By.XPATH, '//*[@id="app"]/div/div/div/div/div/div[2]/div/div/form/section/div[2]/div/input')
        get_started = driver.find_element(By.XPATH, '//*[@id="app"]/div/div/div/div/div/div[2]/div/div/form/button/span[1]')

        # Signup Action
        organization_name.clear()
        organization_name.send_keys('iQuantile')
        time.sleep(1)

        email_address.clear()
        email_address.send_keys('shuvo.bandahajir@gmail.com')
        time.sleep(1)

        get_started.click()
        time.sleep(3)

        # Email Verification Code
        verification_code = driver.find_element(By.ID, '1')
        verification_code.clear()
        verification_code.send_keys('5')

        verification_code = driver.find_element(By.ID, '2')
        verification_code.clear()
        verification_code.send_keys('6')

        verification_code = driver.find_element(By.ID, '3')
        verification_code.clear()
        verification_code.send_keys('2')

        verification_code = driver.find_element(By.ID, '4')
        verification_code.clear()
        verification_code.send_keys('5')

        verification_code = driver.find_element(By.ID, '5')
        verification_code.clear()
        verification_code.send_keys('8')

        verification_code = driver.find_element(By.ID, '6')
        verification_code.clear()
        verification_code.send_keys('0')

        # Verify Token
        verify_token = driver.find_element(By.XPATH, '//*[@id="app"]/div/div/div/div/div/div[2]/div/div/form/button')
        verify_token.click()
        time.sleep(2)

test_obj = Quantibly()
test_obj.test_signup_valid()


import serial
import re
import math
from openpyxl import *

# To get the relative data from the data

def get_data(getdata_data,baseline):
    getdata_result = [0] * 9
    for i in range(9):
        getdata_result[i] = abs(float(getdata_data[i]) - float(baseline[i])) / float(baseline[i])
    return getdata_result

#  To know whether the pad is touched

def whether_touched(touched_data):

    touched_result = False
    for i in range(len(touched_data)):
        if touched_data[i] > 0.02:
            touched_result = True
            break
    return touched_result

# To get the position of the touch point

def get_position(rawdata, baseline):

    #  Get the initial data
    data = [0] * 9
    for i in range(9):
        data[i] = abs(float(rawdata[i]) - float(baseline[i])) / float(baseline[i])

    '''
    Get the position of the touch
    If it is not touched, give it [11,11]
    If it is touched by two finger, give it [0,0]
    '''
    position = [11, 11]

    if whether_touched(data) is False:
        return position

    costx = 0
    costy = 0
    mincostx = 10000
    mincosty = 10000
    x = 0.0
    y = 0.0

    while x <= 10:
          costx = data[8] * pow(0.0 - x, 2) + \
                data[7] * pow(3.3 - x, 2) + \
                data[6] * pow(6.6 - x, 2) + \
                data[5] * pow(10.0 - x, 2)

          if costx < mincostx:
              mincostx = costx
              position[0] = x
          x = x + 0.02

    while y <= 10:
        costy = data[4] * pow(0.0 - y, 2) + \
                data[3] * pow(2.5 - y, 2) + \
                data[2] * pow(5.0 - y, 2) + \
                data[1] * pow(7.5 - y, 2) + \
                data[0] * pow(10.0 - y, 2)
        if costy < mincosty:
            mincosty = costy
            position[1] = y
        y = y + 0.02

    return position

#  Gesture Recognition

def gesture_recognition(gesturerecognition_data):
    xMax = 0
    xMin = 10
    yMax = 0
    yMin = 10
    for i in range(len(gesturerecognition_data)):
        xMax = max(xMax, gesturerecognition_data[i][0])
        xMin = min(xMin, gesturerecognition_data[i][0])
        yMax = max(yMax, gesturerecognition_data[i][1])
        yMin = min(yMin, gesturerecognition_data[i][1])
    xDis = xMax - xMin
    yDis = yMax - yMin

    '''
    Gesture protocal
    1---up
    2---down
    3---left
    4---right
    5---up-right
    6---down-right
    7---up-down
    8---down-up
    9---circle
    '''
    vertical_sum1 = 0
    vertical_sum2 = 0
    vertical_sum3 = 0
    vertical_sum4 = 0
    vertical_sum5 = 0

    horizontal_sum1 = 0
    horizontal_sum2 = 0
    horizontal_sum3 = 0
    horizontal_sum4 = 0
    horizontal_sum5 = 0

    up_right_sum = 0
    down_right_sum = 0
    circle_sum = 0

    for single_position in gesturerecognition_data:

        vertical_sum1 = vertical_sum1 + pow(single_position[0] - 1, 2)
        vertical_sum2 = vertical_sum2 + pow(single_position[0] - 3, 2)
        vertical_sum3 = vertical_sum3 + pow(single_position[0] - 5, 2)
        vertical_sum4 = vertical_sum4 + pow(single_position[0] - 7, 2)
        vertical_sum5 = vertical_sum5 + pow(single_position[0] - 9, 2)

        horizontal_sum1 = horizontal_sum1 + pow(single_position[1] - 1, 2)
        horizontal_sum2 = horizontal_sum2 + pow(single_position[1] - 3, 2)
        horizontal_sum3 = horizontal_sum3 + pow(single_position[1] - 5, 2)
        horizontal_sum4 = horizontal_sum4 + pow(single_position[1] - 7, 2)
        horizontal_sum5 = horizontal_sum5 + pow(single_position[1] - 9, 2)

        up_right_sum = up_right_sum + pow(single_position[0] - single_position[1], 2) / 2
        down_right_sum = down_right_sum + pow(single_position[0] + single_position[1] - 10, 2) / 2

        circle_sum = circle_sum + pow(math.sqrt(pow(single_position[0] - 5, 2)
                                                + pow(single_position[1] - 5, 2)) - 2.5, 2)

    threshold = 5

    if xDis < threshold and yDis < threshold:
        return 0

    if xDis < threshold or yDis < threshold:

        min_sum = min(vertical_sum1, vertical_sum2, vertical_sum3, vertical_sum4, vertical_sum5,
                  horizontal_sum1, horizontal_sum2, horizontal_sum3, horizontal_sum4, horizontal_sum5)

        if min_sum == vertical_sum1 or min_sum == vertical_sum2 or min_sum == vertical_sum3 or \
                        min_sum == vertical_sum4 or min_sum == vertical_sum5:

            if gesturerecognition_data[0][1] < threshold and gesturerecognition_data[-1][1] < threshold and \
                    gesturerecognition_data[int(len(gesturerecognition_data)/2)][1] > 7:
                return 7
            elif gesturerecognition_data[0][1] > threshold and gesturerecognition_data[-1][1] > threshold and \
                    gesturerecognition_data[int(len(gesturerecognition_data)/2)][1] < 3:
                return 8
            elif gesturerecognition_data[0][1] < gesturerecognition_data[-1][1]:
                return 1
            elif gesturerecognition_data[0][1] > gesturerecognition_data[-1][1]:
                return 2

        if min_sum == horizontal_sum1 or min_sum == horizontal_sum2 or min_sum == horizontal_sum3 or \
                        min_sum == horizontal_sum4 or min_sum == horizontal_sum5:
            if gesturerecognition_data[0][0] < gesturerecognition_data[-1][0]:
                return 4
            if gesturerecognition_data[0][0] > gesturerecognition_data[-1][0]:
                return 3
    else:
        min_sum = min(up_right_sum, down_right_sum, circle_sum)
        if min_sum == up_right_sum:
            if gesturerecognition_data[0][0] < gesturerecognition_data[-1][0]:
                return 5
        if min_sum == down_right_sum:
            if gesturerecognition_data[0][0] < gesturerecognition_data[-1][0]:
                return 6
        if min_sum == circle_sum:
            return 9

    return 0
    '''
    Gesture recognition algorithm with the data feature
    '''
    # if abs(gesturerecognition_data[0][0] - gesturerecognition_data[-1][0]) < 5:
    #     if abs(gesturerecognition_data[0][1] - gesturerecognition_data[-1][1]) < 5:
    #         if xDis > 5 and yDis > 5:
    #             return 9
    #
    # if gesturerecognition_data[0][1] < 5 and gesturerecognition_data[-1][1] < 5:
    #     if gesturerecognition_data[int(len(gesturerecognition_data)/2)][1] - gesturerecognition_data[0][1] > 5:
    #         return 7
    #
    # if gesturerecognition_data[0][1] > 5 and gesturerecognition_data[-1][1] > 5:
    #     if gesturerecognition_data[0][1] - gesturerecognition_data[int(len(gesturerecognition_data)/2)][1] > 5:
    #         return 8
    #
    # if xDis < 5:
    #     if yDis > 5:
    #         if gesturerecognition_data[-1][1] > gesturerecognition_data[0][1]:
    #             return 1
    #         if gesturerecognition_data[-1][1] < gesturerecognition_data[0][1]:
    #             return 2
    # if xDis > 5:
    #     if yDis < 5:
    #         if gesturerecognition_data[-1][0] > gesturerecognition_data[0][0]:
    #             return 4
    #         if gesturerecognition_data[-1][0] < gesturerecognition_data[0][0]:
    #             return 3
    #     if yDis > 5:
    #         if gesturerecognition_data[-1][1] > gesturerecognition_data[0][1]:
    #             return 5
    #         if gesturerecognition_data[-1][1] < gesturerecognition_data[0][1]:
    #             return 6
    # return 0

# Communication info
SERIAL_PORT = '/dev/cu.usbmodem1421'
COMMUNICATION_RATE = 115200
ser = serial.Serial(SERIAL_PORT, COMMUNICATION_RATE)

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip = '127.0.0.1'
port = 33335

sock_receive = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock_receive.setblocking(0)
port_receive = 33336
sock_receive.bind((ip, port_receive))

# find the baseline for all the keys
key_dic = {'a': 0, 'b': 11, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9,
           'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18,
           't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25, 'delete': 51, 'fn': 63}

all_key = ['0', '11', '8', '2', '14', '3', '5', '4', '34', '38', '40', '37', '46',
           '45', '31', '35', '12', '15', '1', '17', '32', '9', '13', '7', '16', '6', '51', '63']

# all_key = ['12','0','6']

base_array = []

# for scan_key in all_key:
#     ser.write(scan_key.encode('UTF-8'))
#     for i in range(10):
#         ser.readline()
#     baseline = re.findall(r"\d+", str(ser.readline(), encoding="utf-8"))
#     base_array.append(baseline)
#
# print("Baseline reading finished, data is as following:")
# for base_data in base_array:
#     print(base_data)

touched = False
previous_touched = False
read = True
data_list = []
gesture = 0
keyData = ''
baseline = [380, 360, 320, 370, 400, 405, 410, 420, 413]
status = False
previous_status = False
last_key = "NULL"
pressed = False
# Start the the data reading part
print("Please do gesture")

while True:

    # Get the original data
    try:
        raw_data_str = str(ser.readline(), encoding="utf-8")
        raw_data_array = re.findall(r"\d+", raw_data_str)
        # Get the touch position
        data = get_data(raw_data_array, baseline)
        position = get_position(raw_data_array, baseline)

        # Check whether the data should be added
        if pressed:
            if position != [11, 11]:
                data_list.append(position)
    except:
        continue

    try:
        if pressed == False:
            data_list = []

        keyData = sock_receive.recvfrom(4096)
        key = keyData[0].decode('UTF-8')

        if key == "-1":
            continue

        print(key)

        if key == "STOP":
            read = False
            continue
        elif key == "START":
            read = True
            continue

        if read is False:
            continue

        bkey = key.encode('UTF-8')
        # ser.flushInput()
        # ser.flushOutput()
        # print(key)
        # print(last_key)
        if last_key == "NULL":
            pressed = True
            ser.write(bkey)
            last_key = key

        elif last_key == key:
            last_key = "NULL"
            # print("pressed")
            pressed = False
            if len(data_list) > 2:
                print("--------------NEW GESTURE---------------")
                print("KEY NUM ---"+key)
                del data_list[0]
                del data_list[0]
                del data_list[0]
                del data_list[0]
                gesture = gesture_recognition(data_list)
                print("GESTURE ---" + str(gesture))
                try:
                    sock.sendto(bytes(int(gesture)), (ip, port))
                except:
                    print("error")
            # print(data_list)
            data_list = []
    except socket.error:
        continue


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

from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError
import odoo.addons.decimal_precision as dp
from datetime import datetime
from dateutil.relativedelta import relativedelta
import math
import logging
EPS = 0.00001

_logger = logging.getLogger(__name__)
DF = "%Y-%m-%d"

class Deductions(models.Model):
    _inherit = "wc.loan.deduction"

    is_created_by_manual = fields.Boolean('')

    #b589
    @api.onchange('code')
    def on_change_ded_code(self):
        self.ensure_one()

        member_id = self.loan_id.member_id.id
        domain_str="""
           ['|',('account_type','=','%s'),('account_type','=','%s'),'|'
           ,('member_id','=',%s),('other_member_ids','in',%s),('state','=','open')]
           """
        if self.code and self.code.upper() == "SA" and member_id:
            domain_str = domain_str % ('sa','SA',member_id,member_id)
        elif self.code and self.code.upper() == "CBU" and member_id:
            domain_str = domain_str % ('cbu','CBU',member_id,member_id)
        else:
            domain_str = "[('member_id','=',False)]"

        return {'domain':{'deposit_account_id':domain_str}}

    #b563
    @api.constrains('is_created_by_manual','code')
    def validate_for_manual_input(self):
        self.ensure_one()
        if self.is_created_by_manual:
            if self.code.upper() in ['INT','PCP','PEN','ADV-INT']:
                raise UserError(_("Cannot use reserved deduction code [%s].") % (self.code))


#!/bin/env python
import csv
import requests
from io import StringIO
import difflib

url = 'https://docs.google.com/spreadsheet/ccc?key='\
      '1H77kqiz1R7xVBRXxjjMCqk_3AMF6P6qIMi6p2FEL_us&output=csv'

response = requests.get(url)
assert response.status_code == 200, 'Wrong status code'
buff = StringIO(response.content.decode("utf-8"))

classes = {}

reader = csv.reader(buff)

rows = list(reader)
del rows[0]

bros = [row[1] for row in rows]
bigs = [row[3] for row in rows]
big_years = [row[2] for row in rows]

for ind, big in enumerate(bigs):
    if big in bros or big == '':
        continue
    print("Big %s for %s: %s" % (big, big_years[ind],
                                 difflib.get_close_matches(big, bros)))


import logging
from . import epdconfig

# Display resolution
EPD_WIDTH       = 640
EPD_HEIGHT      = 400

logger = logging.getLogger(__name__)

class EPD:
    def __init__(self):
        self.reset_pin = epdconfig.RST_PIN
        self.dc_pin = epdconfig.DC_PIN
        self.busy_pin = epdconfig.BUSY_PIN
        self.cs_pin = epdconfig.CS_PIN
        self.width = EPD_WIDTH
        self.height = EPD_HEIGHT
        self.BLACK  = 0x000000   #   0000  BGR
        self.WHITE  = 0xffffff   #   0001
        self.GREEN  = 0x00ff00   #   0010
        self.BLUE   = 0xff0000   #   0011
        self.RED    = 0x0000ff   #   0100
        self.YELLOW = 0x00ffff   #   0101
        self.ORANGE = 0x0080ff   #   0110

    # Hardware reset
    def reset(self):
        epdconfig.digital_write(self.reset_pin, 1)
        epdconfig.delay_ms(200)
        epdconfig.digital_write(self.reset_pin, 0)
        epdconfig.delay_ms(1)
        epdconfig.digital_write(self.reset_pin, 1)
        epdconfig.delay_ms(200)

    def send_command(self, command):
        epdconfig.digital_write(self.dc_pin, 0)
        epdconfig.digital_write(self.cs_pin, 0)
        epdconfig.spi_writebyte([command])
        epdconfig.digital_write(self.cs_pin, 1)

    def send_data(self, data):
        epdconfig.digital_write(self.dc_pin, 1)
        epdconfig.digital_write(self.cs_pin, 0)
        epdconfig.spi_writebyte([data])
        epdconfig.digital_write(self.cs_pin, 1)

    # send a lot of data
    def send_data2(self, data):
        epdconfig.digital_write(self.dc_pin, 1)
        epdconfig.digital_write(self.cs_pin, 0)
        epdconfig.spi_writebyte2(data)
        epdconfig.digital_write(self.cs_pin, 1)

    def ReadBusyHigh(self):
        logger.debug("e-Paper busy")
        while(epdconfig.digital_read(self.busy_pin) == 0):      # 0: idle, 1: busy
            epdconfig.delay_ms(10)
        logger.debug("e-Paper busy release")

    def ReadBusyLow(self):
        logger.debug("e-Paper busy")
        while(epdconfig.digital_read(self.busy_pin) == 1):      # 0: idle, 1: busy
            epdconfig.delay_ms(10)
        logger.debug("e-Paper busy release")

    def init(self):
        if (epdconfig.module_init() != 0):
            return -1
        # EPD hardware init start
        self.reset()

        self.ReadBusyHigh()
        self.send_command(0x00)
        self.send_data(0x2f)
        self.send_data(0x00)
        self.send_command(0x01)
        self.send_data(0x37)
        self.send_data(0x00)
        self.send_data(0x05)
        self.send_data(0x05)
        self.send_command(0x03)
        self.send_data(0x00)
        self.send_command(0x06)
        self.send_data(0xC7)
        self.send_data(0xC7)
        self.send_data(0x1D)
        self.send_command(0x41)
        self.send_data(0x00)
        self.send_command(0x50)
        self.send_data(0x37)
        self.send_command(0x60)
        self.send_data(0x22)
        self.send_command(0x61)
        self.send_data(0x02)
        self.send_data(0x80)
        self.send_data(0x01)
        self.send_data(0x90)
        self.send_command(0xE3)
        self.send_data(0xAA)

        # EPD hardware init end
        return 0

    def getbuffer(self, image):
        buf = [0x00] * int(self.width * self.height / 2)
        image_monocolor = image.convert('RGB')#Picture mode conversion
        imwidth, imheight = image_monocolor.size
        pixels = image_monocolor.load()
        logger.debug('imwidth = %d  imheight =  %d ',imwidth, imheight)
        if(imwidth == self.width and imheight == self.height):
            for y in range(imheight):
                for x in range(imwidth):
                    # Set the bits for the column of pixels at the current position.
                    Add = int((x + y * self.width) / 2)
                    Color = 0;
                    if (pixels[x, y][0] == 0 and  pixels[x, y][1] == 0 and pixels[x, y][2] == 0):
                        Color = 0
                    elif (pixels[x, y][0] == 255 and  pixels[x, y][1] == 255 and pixels[x, y][2] == 255):
                        Color = 1
                    elif (pixels[x, y][0] == 0 and  pixels[x, y][1] == 255 and pixels[x, y][2] == 0):
                        Color = 2
                    elif (pixels[x, y][0] == 0 and  pixels[x, y][1] == 0 and pixels[x, y][2] == 255):
                        Color = 3
                    elif (pixels[x, y][0] == 255 and  pixels[x, y][1] == 0 and pixels[x, y][2] == 0):
                        Color = 4
                    elif (pixels[x, y][0] == 255 and  pixels[x, y][1] == 255 and pixels[x, y][2] == 0):
                        Color = 5
                    elif (pixels[x, y][0] == 255 and  pixels[x, y][1] == 128 and pixels[x, y][2] == 0):
                        Color = 6

                    data_t = buf[Add]&(~(0xF0 >> ((x % 2)*4)))
                    buf[Add] = data_t | ((Color << 4) >> ((x % 2)*4));

        elif(imwidth == self.height and imheight == self.width):
            for y in range(imheight):
                for x in range(imwidth):
                    newx = y
                    newy = self.height - x - 1
                    Add = int((newx + newy*self.width) / 2)
                    Color = 0;
                    if (pixels[x, y][0] == 0 and  pixels[x, y][1] == 0 and pixels[x, y][2] == 0):
                        Color = 0
                    elif (pixels[x, y][0] == 255 and  pixels[x, y][1] == 255 and pixels[x, y][2] == 255):
                        Color = 1
                    elif (pixels[x, y][0] == 0 and  pixels[x, y][1] == 255 and pixels[x, y][2] == 0):
                        Color = 2
                    elif (pixels[x, y][0] == 0 and  pixels[x, y][1] == 0 and pixels[x, y][2] == 255):
                        Color = 3
                    elif (pixels[x, y][0] == 255 and  pixels[x, y][1] == 0 and pixels[x, y][2] == 0):
                        Color = 4
                    elif (pixels[x, y][0] == 255 and  pixels[x, y][1] == 255 and pixels[x, y][2] == 0):
                        Color = 5
                    elif (pixels[x, y][0] == 255 and  pixels[x, y][1] == 128 and pixels[x, y][2] == 0):
                        Color = 6

                    data_t = buf[Add]&(~(0xF0 >> ((newx % 2)*4)))
                    buf[Add] = data_t | ((Color << 4) >> ((newx % 2)*4));
        return buf

    def display(self,image):
        self.send_command(0x61)#Set Resolution setting
        self.send_data(0x02)
        self.send_data(0x80)
        self.send_data(0x01)
        self.send_data(0x90)
        self.send_command(0x10)
        self.send_data2(image)
        self.send_command(0x04)#0x04
        self.ReadBusyHigh()
        self.send_command(0x12)#0x12
        self.ReadBusyHigh()
        self.send_command(0x02)  #0x02
        self.ReadBusyLow()
        # epdconfig.delay_ms(500)

    def Clear(self):
        self.send_command(0x61)#Set Resolution setting
        self.send_data(0x02)
        self.send_data(0x80)
        self.send_data(0x01)
        self.send_data(0x90)
        self.send_command(0x10)
        self.send_data2([0x11] * int(EPD_HEIGHT) * int(EPD_WIDTH/2))
        #BLACK   0x00    /// 0000
        #WHITE   0x11    /// 0001
        #GREEN   0x22    /// 0010
        #BLUE    0x33    /// 0011
        #RED     0x44    /// 0100
        #YELLOW  0x55    /// 0101
        #ORANGE  0x66    /// 0110
        #CLEAN   0x77    /// 0111   unavailable  Afterimage
        self.send_command(0x04)#0x04
        self.ReadBusyHigh()
        self.send_command(0x12)#0x12
        self.ReadBusyHigh()
        self.send_command(0x02)  #0x02
        self.ReadBusyLow()
        # epdconfig.delay_ms(500)

    def sleep(self):
        # epdconfig.delay_ms(500)
        self.send_command(0x07) # DEEP_SLEEP
        self.send_data(0XA5)

        epdconfig.delay_ms(2000)
        epdconfig.module_exit()


import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

fileWithIps = open("ipList.txt", "r")

def getIpList(file):
    clients = []
    servers = []
    routers = []
    connections = []
    for line in file:
        if line[0:1] == "0" and line[1] == ":":
            nonZeroLine = line.split(":")
            nonZeroLine.pop(0)
            nonZeroLine = str(nonZeroLine)
            zeroLine = nonZeroLine.split(".")
            zeroLine[0] = zeroLine[0][2:]
            zeroLine[3] = zeroLine[3][:-4]

            x = zeroLine[3].find("-")

            if x != -1:
                lastIpNumbers = zeroLine[3].split("-")
                for i in range(int(lastIpNumbers[0]), int(lastIpNumbers[1]) + 1):
                    ip_i = str(zeroLine[0] + "." + zeroLine[1] + "." + zeroLine[2] + "." + str(i))
                    clients.append(ip_i)
            else:
                s = ".".join(zeroLine)
                clients.append(s)

        if line[0] == "1" and line[1] == ":":
            nonZeroLine = line.split(":")
            nonZeroLine.pop(0)
            nonZeroLine = str(nonZeroLine)
            zeroLine = nonZeroLine.split(".")
            zeroLine[0] = zeroLine[0][2:]
            zeroLine[3] = zeroLine[3][:-4]

            x = zeroLine[3].find("-")

            if x != -1:
                lastIpNumbers = zeroLine[3].split("-")
                for i in range(int(lastIpNumbers[0]), int(lastIpNumbers[1]) + 1):
                    ip_i = str(zeroLine[0] + "." + zeroLine[1] + "." + zeroLine[2] + "." + str(i))
                    servers.append(ip_i)
            else:
                s = ".".join(zeroLine)
                servers.append(s)

        if line[0] == "2" and line[1] == ":":
            nonZeroLine = line.split(":")
            nonZeroLine.pop(0)
            nonZeroLine = str(nonZeroLine)
            zeroLine = nonZeroLine.split(".")
            zeroLine[0] = zeroLine[0][2:]
            zeroLine[3] = zeroLine[3][:-4]

            x = zeroLine[3].find("-")

            if x != -1:
                lastIpNumbers = zeroLine[3].split("-")
                for i in range(int(lastIpNumbers[0]), int(lastIpNumbers[1]) + 1):
                    ip_i = str(zeroLine[0] + "." + zeroLine[1] + "." + zeroLine[2] + "." + str(i))
                    routers.append(ip_i)
            else:
                s = ".".join(zeroLine)
                routers.append(s)

        isConn = line.find("--")
        if isConn > 0:
            connectionLine = line.split("--")
            connectionLine[1] = connectionLine[1][:-2]
            connections.append((connectionLine[0], connectionLine[1]))

    return clients, servers, routers, connections

def buildGraph(mainArray):
    pc = mpimg.imread('pc.png')
    router = mpimg.imread("router.jpg")
    server = mpimg.imread("server.png")

    G = nx.Graph
    for router in range(len(mainArray[2])):
        routerIP = mainArray[2][router].split(".")
        print(routerIP)
        for j in range(len(mainArray[0])):
            clientIP = mainArray[0][j].split(".")
            if clientIP[0] == routerIP[0] and clientIP[1] == routerIP[1] and clientIP[2] == routerIP[2]:
                clientIPstr = ".".join(clientIP)
                routerIPstr = ".".join(routerIP)
                G.add_edge("192.168.11.10", "192.168.11.1", image=pc, size=0.1)

    pos = nx.spring_layout(G)
    nx.draw(G, pos, with_labels=True)

    # add images on edges
    ax = plt.gca()
    fig = plt.gcf()
    label_pos = 0  # middle of edge, halfway between nodes
    trans = ax.transData.transform
    trans2 = fig.transFigure.inverted().transform
    imsize = 0.2  # this is the image size
    for (n1, n2) in G.edges():
        (x1, y1) = pos[n1]
        (x2, y2) = pos[n2]
        (x, y) = (x1 * label_pos + x2 * (1.0 - label_pos),
                  y1 * label_pos + y2 * (1.0 - label_pos))
        xx, yy = trans((x, y))  # figure coordinates
        xa, ya = trans2((xx, yy))  # axes coordinates
        imsize = G[n1][n2]['size']
        img = G[n1][n2]['image']
        a = plt.axes([xa - imsize / 2.0, ya - imsize / 2.0, imsize, imsize])
        a.imshow(img)
        a.set_aspect('equal')
        a.axis('off')
    plt.savefig('save.png')
    plt.axis('off')
    plt.show()

buildGraph(getIpList(fileWithIps))


import logging
from datetime import timedelta
from pathlib import Path

logging.basicConfig(filename="telescreen.log", level=logging.DEBUG)

# -----------Slide Sources-----------
# page which lists all the slide-urls
wikipedia_list_page = "Benutzer:Meisam/test"
wikipedia_lang = "de"

# list of the users who are allowed to edit the wikipedia page
whitelist_users = ["Meisam"]

working_directory = Path(".")

# images will be cached here
cache_folder = Path(".")

# the images included in the wikipedia page will be cached here
# the files in this directory will be completely wiped each time the wikipedia page is updated
wikipedia_list_cache = Path(".")

# the images included in the local list files will be cached here
# directory will be completely wiped each time the slides list is updated
local_lists_cache = Path(".")

# will try to download these types if found in a URL
img_extensions = ("jpeg", "jpg", "png", "gif")
# these types be shown directly
web_extensions = ("htm", "html")
# list files be parsed line-by-line
list_extensions = ("txt",)

# -----------Slide configs-----------
# Update the slides list every ***
cache_lifetime = timedelta(hours=1)

# show each slide for *** seconds
slides_refresh_time = 30


import sys

# iterate through each line provided via standard input
for line in sys.stdin:
  datalist = line.strip().split(",")
  if (len(datalist) == 7) :
    CourseName,University,DifficultyLevel,CourseRating,CourseURL,CourseDescription,Skills= datalist

    # print intermediate key-value pairs to standard output
    print(DifficultyLevel,"\t",1)


from datetime import datetime

from app.baseModel import fields, pydantic_model_creator, BaseModel

class WeeklyConfigModel(BaseModel):
    name = fields.TextField(description="名字")
    parent = fields.IntField(null=True, default=None, description="上一级的id，有上一级则为项目，否则为产品")
    desc = fields.TextField(description="备注")

    class Meta:
        table = "test_work_weekly_config"
        table_description = "周报配置表"

    @classmethod
    async def get_data_dict(cls):
        """ 获取产品、项目数据
        {
            "id": {
                "total": 0,  # 产品下的项目数
                "name": "产品名",
                "project": {
                    "id": {
                        "total": 0,  # 项目下的版本数
                        "name": "项目名",
                        "version": {
                            "version1": {
                                "total": 0,  # 版本下的日报条数
                                "item": [],  # 版本下的日报数据
                            },
                            "version2": {
                                "total": 0,
                                "item": []
                            }
                        }
                    }
                }
            }
        }
        """
        container = {}
        product_list = [dict(data) for data in await WeeklyConfigModel.all()]

        # 获取所有产品
        for index, data in enumerate(product_list):
            if not data["parent"]:
                cls.build_project_product(container, data)
                cls.build_project_container(container[data["id"]], data)

        # 根据产品id获取所有项目
        for product_id, product_data in container.items():
            for index, data in enumerate(product_list):
                if data["parent"] == product_id:
                    cls.build_project_container(product_data, data)

        return container

    @classmethod
    def build_project_product(cls, container, data):
        """ 插入项目 """
        container[data["id"]] = {
            "total": 0,
            "name": data["name"],
            "project": {}
        }

    @classmethod
    def build_project_container(cls, container, data):
        """ 插入项目 """
        container["project"][data["id"]] = {
            "name": data["name"],
            "total": 0,
            "version": {}
        }
        container["total"] += 1

class WeeklyModel(BaseModel):
    product_id = fields.IntField(description="产品id")
    project_id = fields.IntField(description="项目id")
    version = fields.CharField(255, description="版本号")
    task_item = fields.TextField(description="任务明细和进度")
    start_time = fields.DatetimeField(default=datetime.now, description="开始时间")
    end_time = fields.DatetimeField(default=datetime.now, onupdate=datetime.now, description="结束时间")
    desc = fields.TextField(description="备注")

    class Meta:
        table = "test_work_weekly"
        table_description = "周报明细表"

WeeklyConfigModelPydantic = pydantic_model_creator(WeeklyConfigModel, name="WeeklyConfigModel")
WeeklyModelPydantic = pydantic_model_creator(WeeklyModel, name="WeeklyModel")


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/4/21 23:57
# @Author  : cap669
# @File    : XJob.py
# @Software: PyCharm
import datetime
import traceback
from peewee import Model
from peewee import fn
from playhouse.pool import PooledPostgresqlDatabase
from root.base.wrapper.EvsWrapper import EvsWrapper
from root.utils.StateUtils import StateUtils
from root.utils.Utils import Utils
from typing import Any, List
from pydantic import BaseModel

class Job0Model(BaseModel):
    uid: str
    info: str
    ctime: datetime.datetime

class Job1Model(Job0Model):
    an: int
    en: int

class XHis0:
    def __init__(self, cur: Model, safe_table: bool, clear_table: bool, func):
        if safe_table:
            if cur.table_exists():
                if clear_table:
                    cur.truncate_table()
            else:
                cur.create_table()
        if func:
            func()
        self.cur = cur

class XJob0(XHis0):
    def __init__(self, cur: Model, db: PooledPostgresqlDatabase, safe_table: bool = True, clear_table: bool = False,
                 func: Any = None):
        XHis0.__init__(self, cur, safe_table, clear_table, func)
        self.db = db

    def adds(self, info: str, state: StateUtils):
        d0 = Job0Model(uid=Utils.f1(), info=info, ctime=Utils.u0())
        d1 = d0.dict()
        with self.db.atomic():
            e0 = self.cur.insert_many(d1).execute()
            if e0:
                state.succ(1)
            else:
                state.errn()
        return state

    def addc(self, data: List[Any], func: Any, state: StateUtils):
        ctime = Utils.u0()
        with self.db.atomic():
            try:
                d0 = [Job0Model(uid=Utils.f1(), ctime=ctime, info=func(d0)).dict() for d0 in data]
                self.cur.insert_many(d0) \
                    .on_conflict_ignore() \
                    .execute()
                state.succ(1, '')
            except:
                state.errn('')
        return state

    def comp(self, func, uid: str, state: StateUtils, msg: str = 'nuxx'):
        try:
            with self.db.manual_commit():
                d0 = self.cur.select().where(self.cur.uid == uid).for_update().get()
                sta: StateUtils = func()
                if sta.code == 1:
                    d0.fnsh = 4
                else:
                    d0.fnsh = 3
                d0.msg = msg
                d0.stime = Utils.u0()
                if d0.save():
                    state.succ(1, )
        except self.cur.DoesNotExist:
            state.errn('')
        return state

    def gets(self, aka: str, state: StateUtils, msg: str = 'nuxx'):
        uid, info = '', ''
        with self.db.atomic():
            try:
                d0 = self.cur.select().where(self.cur.fnsh == 1).limit(1).for_update().get()
                d0.rtime = Utils.u0()
                d0.fnsh = 2
                d0.msg = msg
                d0.aka = aka
                if d0.save():
                    state.succ(1)
                    uid = d0.uid
                    info = d0.info
                else:
                    state.errn()
            except self.cur.DoesNotExist:
                state.errn()

        return uid, info

    def outs(self, aka: str, state: StateUtils, msg: str = 'nuxx'):
        with self.db.atomic():
            try:
                d0 = self.cur.select().where((self.cur.fnsh == 2) & (self.cur.aka == aka)).for_update().get()
                d0.rtime = Utils.u0()
                d0.fnsh = 1
                if msg == 'nuxx':
                    msg = f'cur:{aka}'
                d0.msg = msg
                d0.aka = 'nuxx'
                if d0.save():
                    state.succ(1)
                else:
                    state.errn('')
            except self.cur.DoesNotExist:
                state.errn()

    def show(self):
        d0 = self.cur.select()
        bag = []
        if d0:
            for d1 in d0:
                d3 = d1.__data__
                bag.append(d3)
        return bag

class XJob1(XHis0):
    def __init__(self, cur: Model, db: PooledPostgresqlDatabase, safe_table: bool = True, clear_table: bool = False,
                 func: Any = None):
        XHis0.__init__(self, cur, safe_table, clear_table, func)
        self.db = db

    def adds(self, info: str, state: StateUtils, an: int = 0, en: int = 0):
        if an >= en:
            d0 = Job1Model(uid=Utils.f1(), info=info, an=an, en=en, ctime=Utils.u0())
            d1 = d0.dict()
            with self.db.atomic():
                e0 = self.cur.insert_many(d1).execute()
                if e0:
                    state.succ(1)
                else:
                    state.errn()
        else:
            state.errn()
        return state

    def comp(self, uid,func, state: StateUtils):
        with self.db.atomic():
            try:
                d0 = self.cur.select().where((self.cur.fnsh == 2) & (self.cur.uid == uid)).for_update().get()
                if d0.an > d0.en:
                    sta:StateUtils = func()
                    if sta.code == 1:
                        d0.rtime = Utils.u0()
                        d0.en = d0.en + 1
                        if d0.save():
                            state.succ(1)
                            if d0.an == d0.en:
                                d0.fnsh = 4
                                if d0.save():
                                    state.succ(2)
                                else:
                                    state.errn('')
                        else:
                            state.errn()
                    else:
                        state.errn('')
                else:
                    state.errn('')
            except:
                state.errn()

    def outs(self,aka:str,state:StateUtils,msg:str = 'nuxx'):
        with self.db.atomic():
            try:
                d0 = self.cur.select().where((self.cur.fnsh == 2) & (self.cur.aka == aka)).for_update().get()
                d0.rtime = Utils.u0()
                d0.fnsh = 1
                if msg == 'nuxx':
                    msg = f'cur:{aka}'
                d0.msg = msg
                d0.aka = 'nuxx'
                if d0.save():
                    state.succ(1)
                else:
                    state.errn('')
            except self.cur.DoesNotExist:
                state.errn()

    def gets(self, aka: str, state: StateUtils, msg: str = 'nuxx'):
        uid, info = '', ''
        with self.db.atomic():
            if aka:
                try:
                    d0 = self.cur.select().where((self.cur.fnsh == 2) & (self.cur.aka == aka)).for_update().get()
                    d0.rtime = Utils.u0()
                    d0.fnsh = 2
                    d0.msg = msg
                    d0.aka = aka
                    d0.save()
                    state.succ(1, '更具aka寻找任务')
                    uid = d0.uid
                    info = d0.info
                except self.cur.DoesNotExist:
                    state.errn()
            if state.code == 1:
                pass
            else:
                try:
                    d0 = self.cur.select().where(self.cur.fnsh == 1).for_update().get()
                    d0.rtime = Utils.u0()
                    d0.fnsh = 2
                    d0.msg = msg
                    d0.aka = aka
                    if d0.save():
                        state.succ(1, '新任务')
                        uid = d0.uid
                        info = d0.info
                    else:
                        state.errn()
                except:
                    state.errn()
        return uid, info

    def show(self):
        pass

class XJob2(XHis0):
    def __init__(self, cur: Model, db: PooledPostgresqlDatabase, safe_table: bool = True, clear_table: bool = False,
                 func: Any = None):
        XHis0.__init__(self, cur, safe_table, clear_table, func)
        self.db = db

    @EvsWrapper()
    def adds(self, info, state: StateUtils):
        d0 = dict(
            uid=Utils.f1(),
            info=info,
            ctime=Utils.u0()
        )
        with self.db.atomic():
            e0 = self.cur.insert_many(d0).execute()
            if e0:
                state.succ(1)
            else:
                state.errn()
        return state

    def addc(self):
        pass

    @EvsWrapper()
    def comp(self, func: Any, uid: str, diff: int, state: StateUtils, msg: str = 'nuxx'):
        with self.db.atomic():
            d0 = self.cur.select().where(self.cur.uid == uid).for_update().get()
            state0: StateUtils = func()
            if state0.code == 1:
                d0.diff = diff
                d0.stime = Utils.u0()
                d0.msg = msg
                d0.aka = 'nuxx'
                d0.save()
                state.succ(1)
            else:
                state.errn()

    def outs(self, aka: str):
        pass

    @EvsWrapper()
    def gets(self, aka: str, info: str, diff: int, state: StateUtils, msg: str = 'nuxx'):
        uid = ''
        with self.db.atomic():
            try:
                d0 = self.cur.select().where((self.cur.diff != diff) & (self.cur.info == info)).order_by(
                    fn.Random()).limit(1).for_update().get()
                d0.rtime = Utils.u0()
                d0.msg = msg
                d0.aka = aka
                d0.save()
                state.succ(1)
                uid = d0.uid
            except self.cur.DoesNotExist:
                state.errn()
        return state, uid

    def show(self):
        pass

# Tips     :XJob0,XJob1 可以执行分布式运算 XJob2 只能同步运算


import time
import datetime
import numpy as np
from app.utils import utils
from app.utils.portfolio import Portfolio
from app.usecases.get_recommended_weights import get_recommended_weights
from app.usecases.get_simulation_hull import get_simulation_hull
from app.models.sector import GICS_DATA
from dateutil.relativedelta import relativedelta

def portfolio_response(p, f=None, t=None):
    (asset, amount, weight, recommended_weight, capital_gain, dividends) = p

    today_date = datetime.datetime.today()
    today_year = today_date.year
    today_date = today_date.date().isoformat()
    back_date = datetime.datetime.today() + relativedelta(years=-3)
    back_year = back_date.year
    back_date = back_date.date().isoformat()

    return {
        'asset_id': int(asset.id),
        'asset_type': asset.asset_type,
        'ticker': asset.ticker,
        'amount': int(amount),
        'ch': asset.ch(today_year, today_year),
        'ry': [0, asset.ry(back_date, today_date), 0],
        'dy': [0, asset.dy(back_date, today_date), 0],
        'yy': asset.yy(back_year, today_year),
        'tv': int(amount) * asset.adjusted_close_price(),
        'p': asset.adjusted_close_price(),
        'cg': capital_gain,
        'divs': dividends,
        'tr': capital_gain + dividends,
        'country': asset.country,
        'sector': asset.sector,
        'weight': weight,
        'recommended_weight': recommended_weight,
        'updated_at': asset.updated_at,
    }

def get_portfolio(account_id, portfolio_id, f=None, t=None):
    assets, quantities = utils.get_portfolio_asset_quantities(account_id, portfolio_id)

    portfolio_data = utils.get_portfolio_data(account_id, portfolio_id)
    weights = utils.weights(assets, quantities)

    # gics
    gics = [asset.sector for asset in assets if asset._asset_type == 'stock']
    gics_aggs = {k: 0.0 for k in GICS_DATA.keys()}
    for (gics, weight) in list(zip(gics, weights)):
        if gics in GICS_DATA.keys():
            gics_aggs[gics] += weight

    # gics_aggs = sorted(gics_aggs.items(), key=lambda x: -x[1])
    gics_aggs = list(gics_aggs.items())

    # benchmarks
    voo = utils.get_asset('VOO')
    vt = utils.get_asset('VT')
    imoex = utils.get_asset('IMOEX')

    portfolio = Portfolio(assets, weights)

    recommended_weights = get_recommended_weights(assets)
    # target = Portfolio(assets, recommended_weights)

    portfolio_actions = utils.get_portfolio_actions(account_id, portfolio_id)
    portfolio_actions = sorted(portfolio_actions, key=lambda item: item['action_date'])

    capital_gain = utils.get_portfolio_capital_gain(account_id, portfolio_id)
    dividends = utils.get_portfolio_dividends(account_id, portfolio_id)

    assets_data = list(zip(
        assets, quantities, weights, recommended_weights, capital_gain, dividends
    ))
    assets_data_response = list(map(portfolio_response, assets_data))

    today_date = datetime.datetime.today()
    today_year = today_date.year
    today_date = today_date.date().isoformat()
    back_date = datetime.datetime.today() + relativedelta(years=-3)
    back_year = back_date.year
    back_date = back_date.date().isoformat()

    return {
        'portfolioData': {
            'name': portfolio_data.name,
            'ch': portfolio.ch(today_year),
            'r': portfolio.ry(back_date, today_date),
            'd': portfolio.dy(back_date, today_date),
            'y': portfolio.yy(back_year, today_year),
            'u': utils.utility(assets, weights),
            'or': utils.total_return(assets, recommended_weights),
            'od': utils.stdev(assets, recommended_weights),
            'oy': utils.total_yield(assets, recommended_weights),
            'ou': utils.utility(assets, recommended_weights),
            'tv': utils.total_value(assets, quantities),
            'tcg': int(np.sum(list(capital_gain))),
            'td': int(np.sum(list(dividends))),
            'gics_data': gics_aggs,  # TODO: maybe extract
            'simulation_hull': get_simulation_hull(assets),  # TODO: extract
        },
        'assetData': assets_data_response,
    }


# from os.path import dirname
import urllib.request
import base64
import argparse
import os.path

key = "<your api key>"

parser = argparse.ArgumentParser(description="Shrink PNGs with TinyPNG")
parser.add_argument("input", type=argparse.FileType("rb"), help="input PNG")
args = parser.parse_args()

request = urllib.request.Request("https://api.tinypng.com/shrink", args.input.read())

cafile = None
# Uncomment below if you have trouble validating our SSL certificate.
# Download cacert.pem from: http://curl.haxx.se/ca/cacert.pem
# cafile = dirname(__file__) + "/cacert.pem"

auth = base64.b64encode(bytes("api:" + key, "ascii")).decode("ascii")
request.add_header("Authorization", "Basic %s" % auth)

response = urllib.request.urlopen(request, cafile = cafile)
if response.status == 201:
  # Compression was successful, retrieve output from Location header.
  result = urllib.request.urlopen(response.getheader("Location"), cafile = cafile).read()

  # Rename original file
  orig_path = args.input.name
  rename_path = orig_path
  args.input.close()

  while True:
    try:
      rename_path_split = os.path.splitext(rename_path)
      rename_path = rename_path_split[0] + "_orig" + rename_path_split[1]
      os.rename(orig_path, rename_path)
      break
    except FileExistsError:
      print("File exist")

  # Name the new one as the original
  open(orig_path, "wb").write(result)

else:
  # Something went wrong! You can parse the JSON body for details.
  print("Compression failed")
  input("Press enter to continue")


from turtle import pd
import numpy as np
import matplotlib.pyplot as plt
import  pandas as pd
# Import the MarkovChain class from markovchain.py
from markovchain import MarkovChain
import random as random

# P = np.array([[0.8, 0.2], [0.1, 0.9]]) # Transition matrix
# mc = MarkovChain(P, ['1', '2'])
# mc.draw()

# Gambling simulation
def gamblers_ruin():
    gambling_money = 50
    gambling_goal = 100
    gambling_simulations = []

    while gambling_money in range(1,gambling_goal):
        bet_size = 1
        w_or_l = random.randrange(-1,2,2)
        gambling_money+= bet_size * w_or_l
        gambling_simulations.append(gambling_money)
    return gambling_simulations

# Plotting Gambling Simulation
plt.plot(gamblers_ruin())
plt.yticks(np.arange(-20,120,10))
plt.axhline(y=0,color="red",linestyle ="-")
plt.axhline(y=100,color="black",linestyle ="-")
plt.xlabel("Numer of bets")
plt.ylabel("Winnings")
plt.title("Gambling Simulation")

# Probability of Ruin
def prob_of_ruin(gambling_goal, initial_gambling_money):
    return (gambling_goal - initial_gambling_money)/gambling_goal

prob_of_ruin(100,50)

sim_list = []
while len(sim_list) < 500:
    sim_list.append(gamblers_ruin()[-1])
np.mean(sim_list)

# Markov Chain Simulation
example = {
    "NYC":    [.25,0,.75,1],
    "Paris" : [.25,.25,0,0],
    "Cairo" : [.25,.25,.25,0],
    "Seoul" : [.25,.50,0,0]
}

markov_chain = pd.DataFrame(data=example,index = ["NYC","Paris","Cairo","Seoul"])
markov_chain

markov_chain_image  =  MarkovChain(markov_chain.to_numpy(), markov_chain.columns.tolist() )
# markov_chain_image.draw("./markov_chain.png")

# simulation for 25 times
travel_sim = []
travel_sim.append(markov_chain.iloc[0].index[0])
city = np.random.choice(markov_chain.iloc[0].index,p=markov_chain.iloc[0])
travel_sim.append(city)

while len(travel_sim) < 25:
    city = np.random.choice(markov_chain.iloc[markov_chain.index.get_loc(city)].index,p=markov_chain.iloc[markov_chain.index.get_loc(city)])
    travel_sim.append(city)

travel_sim

# n Step Transition Matrix

markov_chain.to_numpy();
def matrix_power(matrix,power):
    if power == 0:
        return np.identity(len(matrix))
    elif power == 1:
        return matrix
    else:
        return np.dot(matrix,matrix_power(matrix,power-1))

matrix_power(markov_chain,3)

# steady State Matrix

for i in range (1,10,1):
    print(f'n step transition matrix at the nth power {i}\n',matrix_power(markov_chain,i),'\n')

# starting from a state where will it be in the next n steps

initial_dist = np.asarray([1,0,0,0])
mcp2 = matrix_power(markov_chain.to_numpy(),2)
np.dot(initial_dist,mcp2)


# You are given a block of text with different words. These words are
# separated by white-spaces and punctuation marks. Numbers are not
# considered words in this mission (a mix of letters and digits is not a
# word either). You should count the number of words (striped words)
# where the vowels with consonants are alternating, that is; words that
# you count cannot have two consecutive vowels or consonants. The words
# consisting of a single letter are not striped -- do not count
# those. Casing is not significant for this mission.
# Input: A text as a string (unicode)
# Output: A quantity of striped words as an integer.
# Precondition:The text contains only ASCII symbols.
# 0 < len(text) < 105

import re

VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"

def checkio(text):
    words = re.split('\W+', text)
    striped_words = 0
    for word in words:
        striped_words += isStriped(word.upper())
    return striped_words

def isStriped(word):
    # Exclude words without at least one vowel and one consonant
    if len([c for c in word if c in VOWELS]) + len([c for c in word if c in CONSONANTS]) < 2:
        return False

    # Exclude words containing numbers
    if len([c for c in word if c.isdigit()]) > 0:
        return False

    # Compare each letter to the previous
    prev_char = ''
    for c in word:
        if prev_char:
            if (prev_char in VOWELS and c in VOWELS) or (prev_char in CONSONANTS and c in CONSONANTS):
                return False
        if c in VOWELS or c in CONSONANTS:
            prev_char = c

    return True

#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio(u"My name is ...") == 3, "All words are striped"
    assert checkio(u"Hello world") == 0, "No one"
    assert checkio(u"A quantity of striped words.") == 1, "Only of"
    assert checkio(u"Dog,cat,mouse,bird.Human.") == 3, "Dog, cat and human"


import math
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Callable

def print_header():
    print("Задание #4_2. Приближённое вычисление интеграла по квадратурным формулам\n")

def get_input(value_name: str, msg: str, default_value: float) -> float:
    try:
        value = float(input(f">>> Введите {msg} {value_name}="))
    except ValueError:
        value: float = default_value
        print(f"Оставлено значение {value_name} по умолчанию;   {value_name}={default_value}")
    return value

@dataclass
class Method(ABC):
    name: str

    @staticmethod
    @abstractmethod
    def calculate(f: Callable, a: float, b: float) -> float:
        pass

@dataclass
class LeftRectangle(Method):
    name: str = "КФ левого прямоугольника"

    @staticmethod
    def calculate(f: Callable, a: float, b: float) -> float:
        return (b - a) * f(a)

@dataclass
class RightRectangle(Method):
    name: str = "КФ правого прямоугольника"

    @staticmethod
    def calculate(f: Callable, a: float, b: float) -> float:
        return (b - a) * f(b)

@dataclass
class MiddleRectangle(Method):
    name: str = "КФ среднего прямоугольника"

    @staticmethod
    def calculate(f: Callable, a: float, b: float) -> float:
        return (b - a) * f((a + b) / 2)

@dataclass
class Trapeze(Method):
    name: str = "КФ трапеции"

    @staticmethod
    def calculate(f: Callable, a: float, b: float) -> float:
        return ((b - a) / 2) * (f(a) + f(b))

@dataclass
class Simpson(Method):
    name: str = "КФ Симпсона"

    @staticmethod
    def calculate(f: Callable, a: float, b: float) -> float:
        return ((b - a) / 6) * (f(a) + 4 * f((a + b) / 2) + f(b))

@dataclass
class ThreeEighths(Method):
    name: str = "КФ 3/8"

    @staticmethod
    def calculate(f: Callable, a: float, b: float) -> float:
        h = (b - a) / 3
        return (b - a) * (f(a) + 3 * f(a + h) + 3 * f(a + 2 * h) + f(b)) / 8

def print_results(a: float, b: float, functions: [Callable, Callable, str], polynomials: [Callable, Callable, str]):
    print("――――――――――――――――――――――――――――――――――――――――――――――――")
    for function, integral, formula in polynomials + functions:
        print(f" Функция f(x) = {formula}")
        value_of_integral = integral(b) - integral(a)
        print(f" Точное значение интеграла: {value_of_integral:.8f}\n")
        for method in [LeftRectangle, RightRectangle, MiddleRectangle, Trapeze, Simpson, ThreeEighths]:
            print(f"   Метод: {method.name}")
            result = method.calculate(function, a, b)
            print(f"    Результат метода: {result:.8f}")
            print(f"    Абсолютная фактическая погрешность: {abs(value_of_integral - result):.8f}\n")
        print("――――――――――――――――――――――――――――――――――――――――――――――――")

def main():
    print_header()
    functions = [
        (lambda x: math.cos(x) * math.exp(math.sin(x)), lambda x: math.exp(math.sin(x)), 'cos(x) * e^(sin(x))'),
    ]
    polynomials = [
        (lambda x: 10, lambda x: 10 * x, '10'),
        (lambda x: 8.8 * x - 10, lambda x: 4.4 * x ** 2 - 10 * x, '8.8 * x - 10'),
        (lambda x: 3 * x ** 2 + 8.8 * x - 10, lambda x: x ** 3 + 4.4 * x ** 2 - 10 * x, '3 * x² + 8.8 * x - 10'),
        (
            lambda x: 16 * x ** 3 - 3 * x ** 2 + 8.8 * x - 10,
            lambda x: 4 * x ** 4 - x ** 3 + 4.4 * x ** 2 - 10 * x,
            '16 * x³ - 3 * x² + 8.8 * x - 10'
        ),
    ]
    a = get_input('A', 'нижний предел интегрирования', 0)
    b = get_input('B', 'верхний предел интегрирования', 1)
    print_results(a, b, functions, polynomials)
    try:
        while True:
            choice = input(">>> Напишите \"1\", если хотите ввести новые значения:   ")
            if choice == '1':
                a = get_input('A', 'нижний предел интегрирования', 0)
                b = get_input('B', 'верхний предел интегрирования', 1)
                print_results(a, b, functions, polynomials)
            else:
                print(f"Выход из программы...")
                break
    except Exception:
        print(f"Ошибка!\nВыход из программы...")
        return

if __name__ == '__main__':
    main()


from __future__ import annotations

import os
from enum import Enum, auto
from typing import List, Optional

from skytemple_files.common.types.data_handler import DataHandler
from skytemple_files.common.util import OptionalKwargs, read_bytes
from skytemple_files.compression_container.at3px.handler import At3pxHandler
from skytemple_files.compression_container.at4pn.handler import At4pnHandler
from skytemple_files.compression_container.at4px.handler import At4pxHandler
from skytemple_files.compression_container.atupx.handler import AtupxHandler
from skytemple_files.compression_container.base_handler import (
    CompressionContainerHandler,
)
from skytemple_files.compression_container.pkdpx.handler import PkdpxHandler
from skytemple_files.compression_container.protocol import CompressionContainerProtocol

class CommonAtType(Enum):
    AT4PN = auto(), At4pnHandler, True
    AT3PX = auto(), At3pxHandler, True
    AT4PX = auto(), At4pxHandler, True
    ATUPX = auto(), AtupxHandler, False
    PKDPX = auto(), PkdpxHandler, True

    def __new__(cls, *args, **kwargs):  # type: ignore
        obj = object.__new__(cls)
        obj._value_ = args[0]
        return obj

    # ignore the first param since it's already set by __new__
    def __init__(
        self, _: int, handler: CompressionContainerHandler, auto_allowed: bool
    ):
        self.handler = handler
        self.auto_allowed = auto_allowed

# Pre-built lists for compression
COMMON_AT_BEST_3 = [
    CommonAtType.AT4PN,
    CommonAtType.ATUPX,
    CommonAtType.AT3PX,
    CommonAtType.PKDPX,
]
COMMON_AT_BEST_4 = [
    CommonAtType.AT4PN,
    CommonAtType.ATUPX,
    CommonAtType.AT4PX,
    CommonAtType.PKDPX,
]
COMMON_AT_MUST_COMPRESS_3 = [CommonAtType.ATUPX, CommonAtType.AT3PX, CommonAtType.PKDPX]
COMMON_AT_MUST_COMPRESS_4 = [CommonAtType.ATUPX, CommonAtType.AT4PX, CommonAtType.PKDPX]
COMMON_AT_PKD = [CommonAtType.PKDPX]

DEBUG = False

class CommonAtHandler(DataHandler[CompressionContainerProtocol]):
    allowed_types = set()
    for t in CommonAtType:
        if t.auto_allowed:
            if t == CommonAtType.ATUPX:
                # For native handler:
                os.environ["SKYTEMPLE_ALLOW_ATUPX"] = "1"
            allowed_types.add(t)

    @classmethod
    def allow(cls, compression_type: CommonAtType):
        if compression_type == CommonAtType.ATUPX:
            # For native handler:
            os.environ["SKYTEMPLE_ALLOW_ATUPX"] = "1"
        cls.allowed_types.add(compression_type)
        if DEBUG:
            print("*** COMMON AT DEBUG: Allowed types =", cls.allowed_types)

    @classmethod
    def disallow(cls, compression_type: CommonAtType):
        try:
            # For native handler:
            cls.allowed_types.remove(compression_type)
            del os.environ["SKYTEMPLE_ALLOW_ATUPX"]
        except KeyError as ke:
            pass  # TODO, add warning
        if DEBUG:
            print("*** COMMON AT DEBUG: Allowed types =", cls.allowed_types)

    @classmethod
    def deserialize(
        cls, data: bytes, **kwargs: OptionalKwargs
    ) -> CompressionContainerProtocol:
        """Load a Common At container into a high-level representation"""
        for t in CommonAtType:
            if t.handler is not None:
                if t.handler.matches(data):
                    if DEBUG:
                        print("*** COMMON AT DEBUG: Opened =", t)
                    return t.handler.deserialize(data, **kwargs)
        raise ValueError(f"The provided data is not an AT container ({read_bytes(data, 0, 5)}).")  # type: ignore

    @classmethod
    def serialize(
        cls, data: CompressionContainerProtocol, **kwargs: OptionalKwargs
    ) -> bytes:
        """Convert the high-level AT representation back into a BitStream."""
        return data.to_bytes()

    @classmethod
    def compress(
        cls, data: bytes, compression_type: Optional[List[CommonAtType]] = None
    ) -> CompressionContainerProtocol:
        """Turn uncompressed data into a new AT container"""
        if compression_type is None:
            compression_type = COMMON_AT_BEST_4
        new_data: Optional[CompressionContainerProtocol] = None
        new_size = -1
        if DEBUG:
            print("*** COMMON AT DEBUG: Compress Start")
        for t in compression_type:
            if t in CommonAtHandler.allowed_types:
                try:
                    cont = t.handler.compress(data)  # pylint: disable=no-member
                    size = len(cont.to_bytes())
                    if DEBUG:
                        print("*** COMMON AT DEBUG: Compress", t, "size", size)
                    if new_data is None or size < new_size:
                        new_data = cont
                        new_size = size
                except:
                    pass
        if DEBUG:
            print("*** COMMON AT DEBUG: Compress End")
        if new_data is None:
            raise ValueError("No useable compression algorithm.")
        return new_data

    @classmethod
    def cont_size(cls, data: bytes, byte_offset=0):
        for t in CommonAtType:
            if t.handler.matches(data, byte_offset):
                return t.handler.cont_size(data, byte_offset)
        raise ValueError("The provided data is not an AT container.")

    @classmethod
    def matches(cls, data: bytes, byte_offset=0):
        """Check if the given data stream is an AT container"""
        for t in CommonAtType:
            if t.handler.matches(data, byte_offset):
                return True
        return False


import asyncio
try:
    import uvloop
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
    pass
import aiohttp
import concurrent.futures
from concurrent.futures import CancelledError, TimeoutError
import threading

import numpy as np

from tempfile import NamedTemporaryFile
from itertools import chain
import os
import sys
import functools
import json
import collections
import logging
import logging.handlers
import inspect

from pyveda.io.utils import write_trace_profile
from pyveda.vedaset.interface import OpRegister
from pyveda.config import VedaConfig
from pyveda.utils import tail

has_tqdm = False
try:
    from tqdm import trange, tqdm, tqdm_notebook, tnrange
    has_tqdm = True
except ImportError:
    pass

log_fh = ".{}.log".format(__name__)
logger = logging.getLogger(__name__)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(
            log_fh, mode="w", maxBytes=10485760, backupCount=1)
handler.setFormatter(formatter)
logger.addHandler(handler)

cfg = VedaConfig()

class ThreadedAsyncioRunner(object):
    def __init__(self, run_method, call_method, loop=None):
        if not loop:
            loop = asyncio.new_event_loop()
        self._loop = loop
        self._method = call_method
        self._thread = threading.Thread(target=functools.partial(run_method, loop=loop))
        self._thread.start()

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self._loop.call_soon_threadsafe(self._loop.stop)
        self._thread.join()
        self._loop.close()

    def __call__(self, *args, **kwargs):
        f = asyncio.run_coroutine_threadsafe(self._method(*args, **kwargs), self._loop)
        return f.result()

class PhaseBuffer(object):
    def __init__(self, period=1, maxlen=None):
        self.period = period
        self._count = 0
        self._cycle_num = 1
        self._full_cycles = 0
        self._phased = False
        self._ibuf = collections.deque(maxlen=maxlen)

    @property
    def count(self):
        return self._count

    @property
    def phased(self):
        return self._phased

    @phased.setter
    def phased(self, v):
        self._phased = v
        if v:
            self._full_cycles = self._cycle_num
            self._cycle_num += 1

    @property
    def k(self):
        return self.count % self.period

    @property
    def full_cycles(self):
        return self._full_cycles

    @property
    def cycle_number(self):
        return self.full_cycles + 1

    @property
    def current_sample(self):
        n = self.k
        if self.phased:
            n = self.period
        return list(tail(n, self.view))

    def append(self, obj):
        self._phased = False
        self._ibuf.append(obj)
        self._count += 1
        if self.k == 0:
            self.phased = True

    @property
    def view(self):
        return self._ibuf.copy()

class HTTPClientTracer(object):
    """
    A mixin class that can be used to record infomation about
    aiohttp request lifecycles.
    """

    def __init__(self, cache=None):
        if not cache:
            cache = collections.defaultdict(list)
        self._trace_cache = cache

    async def on_request_exception(self, session, context, params):
        pass

    async def on_connection_queued_start(self, session, context, params):
        pass

    async def on_connection_queued_end(self, session, context, params):
        pass

    async def on_dns_resolvehost_start(self, session, context, params):
        context.start = session.loop.time()

    async def on_dns_resolvehost_end(self, session, context, params):
        elapsed = session.loop.time() - context.start
        self._trace_cache["dns_resolution_time"].append(elapsed)

    async def on_request_start(self, session, context, params):
        context.start = session.loop.time()

    async def on_request_end(self, session, context, params):
        elapsed = session.loop.time() - context.start
        self._trace_cache["request_times"].append(elapsed)

    async def on_connection_create_start(self, session, context, params):
        context.start = session.loop.time()

    async def on_connection_create_end(self, session, context, params):
        elapsed = session.loop.time() - context.start
        self._trace_cache["connection_lifetimes"].append(elapsed)

    def _configure_tracer(self):
        trace_config = aiohttp.TraceConfig()
        trace_config.on_dns_resolvehost_start.append(self.on_dns_resolvehost_start)
        trace_config.on_dns_resolvehost_end.append(self.on_dns_resolvehost_end)
        trace_config.on_request_start.append(self.on_request_start)
        trace_config.on_request_end.append(self.on_request_end)
        trace_config.on_request_exception.append(self.on_request_exception)
        trace_config.on_connection_queued_start.append(self.on_connection_queued_start)
        trace_config.on_connection_queued_end.append(self.on_connection_queued_end)
        trace_config.on_connection_create_start.append(self.on_connection_create_start)
        trace_config.on_connection_create_end.append(self.on_connection_create_end)
        return trace_config

idfn = lambda x: x

class HTTPDataClient(HTTPClientTracer):
    def __init__(self,
                 total_count=100,
                 session=None,
                 token=None,
                 max_retries=5,
                 timeout=20,
                 session_limit=30,
                 max_concurrent_requests=200,
                 max_memarrays=100,
                 batch_size=100,
                 suppress_callback_errors = True,
                 suppress_http_errors = True,
                 on_data=idfn,
                 num_write_workers=1,
                 num_write_threads=1,
                 lbl_payload_handler=idfn,
                 img_payload_handler=idfn,
                 img_batch_transform=idfn,
                 lbl_batch_transform=idfn,
                 num_lbl_payload_threads=10,
                 num_img_payload_threads=10,
                 lbl_payload_executor=concurrent.futures.ThreadPoolExecutor,
                 img_payload_executor=concurrent.futures.ThreadPoolExecutor,
                 write_executor=concurrent.futures.ThreadPoolExecutor,
                 connector=aiohttp.TCPConnector,
                 run_tracer=False,
                 buf=None,
                 loop=None,
                 *args, **kwargs):

        self.max_concurrent_reqs = min(total_count, max_concurrent_requests)
        self.suppress_cb_errs = suppress_callback_errors
        self.suppress_http_errs = suppress_http_errors
        self.max_retries = max_retries
        self.timeout = timeout
        self.session = session
        self._token = token
        self._session_limit = session_limit
        self._connector = connector
        self._trace_configs = []
        self._run_tracer = run_tracer
        if run_tracer:
            trace_config = self._configure_tracer()
            self._trace_configs.append(trace_config)

        self.on_data = on_data
        self.max_memarrs = max_memarrays
        self._lbl_batch_transform = lbl_batch_transform
        self._img_batch_transform = img_batch_transform
        self._n_lbl_payload_threads = num_lbl_payload_threads
        self._n_img_payload_threads = num_img_payload_threads
        self._n_write_workers = num_write_workers
        self._n_write_threads = num_write_threads
        self._io_executor = write_executor(max_workers=num_write_threads)
        self._lbl_payload_executor = lbl_payload_executor(max_workers=num_lbl_payload_threads)
        self._img_payload_executor = img_payload_executor(max_workers=num_img_payload_threads)

        self.lbl_payload_handler = functools.partial(self._payload_handler,
                                                     executor=self._lbl_payload_executor,
                                                     fn=lbl_payload_handler)
        self.img_payload_handler = functools.partial(self._payload_handler,
                                                     executor=self._img_payload_executor,
                                                     fn=img_payload_handler)
        if not buf:
            batch_size = min(batch_size, max_memarrays)
            buf = PhaseBuffer(period=batch_size, maxlen=max_memarrays)
        self.data_buf = buf

        self.io_callbacks = OpRegister()
        self.cpu_callbacks = OpRegister()
        self.filters = OpRegister()

        self._loop = None
        if loop:
            self.set_loop(loop)
        self._logger = logger

    @property
    def loop(self):
        return self._loop

    @loop.setter
    def loop(self, loop):
        raise AttributeError(
            "Access denied; for loop assignment, call {}.set_loop".format(type(self)))

    def set_loop(self, loop, force=False):
        if self.loop and not force:
            return False
        self._loop = loop
        asyncio.set_event_loop(loop)
        return True

    @property
    def headers(self):
        return {"Authorization": "Bearer {}".format(self._token)}

    async def _payload_handler(self, payload, executor=None, fn=lambda x: x):
        processed_data = await self.loop.run_in_executor(executor, fn, payload)
        return processed_data

    async def fetch_with_retries(self, url, json=True, callback=None, **kwargs):
        await asyncio.sleep(0.0)
        data = None
        retries = self.max_retries
        while retries:
            try:
                async with self.session.get(url) as response:
                    response.raise_for_status()
                    logger.info("  URL READ SUCCESS: {}".format(url))
                    if json:
                        data = await response.json()
                    else:
                        data = await response.read()
                    await response.release()
                if callback:
                    try:
                        data = await callback(data, **kwargs)
                    except Exception as e:
                        logger.info(e)
                        if not self.suppress_cb_errs:
                            raise
                return data
            except CancelledError:
                break
            except Exception as e: # TODO: catch appr aiohttp exceptions here
                logger.info(e)
                logger.info("    URL READ ERROR: {}".format(url))
                retries -= 1
                if not retries and not self.suppress_http_errs:
                    raise
        return data

    async def start_fetch(self, reqs=[], **kwargs):
        assert self.loop.is_running()
        async with aiohttp.ClientSession(loop=self.loop,
                                         connector=self._connector(limit=self._session_limit),
                                         headers=self.headers,
                                         trace_configs=self._trace_configs) as session:
            self.session = session
            logger.info("BATCH FETCH START")
            results = await self.drive_fetch(reqs=reqs, **kwargs)
            logger.info("BATCH FETCH COMPLETE")
            return results

    async def consume_reqs(self):
        while True:
            try:
                label_url, image_url, _id = await self._qreq.get()
                flbl = asyncio.ensure_future(self.fetch_with_retries(
                    label_url, callback=self.lbl_payload_handler))
                fimg = asyncio.ensure_future(self.fetch_with_retries(
                    image_url, json=False, callback=self.img_payload_handler))
                label, image = await asyncio.gather(flbl, fimg)
                await self._qwrite.put([label, image, _id])
            except CancelledError:
                break

    def _configure(self, loop):
        self._kill_trigger = asyncio.Event(loop=loop)
        self._qreq = asyncio.Queue(maxsize=self.max_concurrent_reqs, loop=loop)
        self._qwrite = asyncio.Queue(loop=loop)
        self._data_lock = asyncio.Lock(loop=loop)
        self._consumers = [asyncio.ensure_future(self.consume_reqs(), loop=loop)
                           for _ in range(self.max_concurrent_reqs)]
        self._writers = [asyncio.ensure_future(self.process_data(), loop=loop)
                         for _ in range(self._n_write_workers)]

    def register_filter(self, fn, run_in_executor=False, executor=None):
        if not executor:
            executor = self._cpu_executor

        def wrap(fn):
            async def wrapped(*args, **kwargs):
                await asyncio.sleep(0.0)
                if run_in_executor:
                    return await self.loop.run_in_executor(executor, fn, *args)
                return fn(*args, **kwargs)
            return wrapped

        self.filters.register(wrap(fn))

    def register_io_callback(self, fn, executor=None, use_lock=False, lock=None):
        if not executor:
            executor = self._io_executor
        if use_lock:
            if not lock:
                lock = asyncio.Lock(loop=self.loop)

        def wrap(fn):
            if lock:
                async def wrapped(*args, **kwargs):
                    async with lock:
                        return await self.loop.run_in_executor(executor, fn, *args)
            else:
                async def wrapped(*args, **kwargs):
                    return await self.loop.run_in_executor(executor, fn, *args)
            return wrapped

        self.io_callbacks.register(wrap(fn))

    def register_cpu_callback(self, fn, executor=None, use_lock=False, lock=None):
        if not executor:
            executor = self._cpu_executor
        if use_lock:
            if not lock:
                lock = asyncio.Lock(loop=self.loop)

        def wrap(fn):
            if lock:
                async def wrapped(*args, **kwargs):
                    async with lock:
                        return await self.loop.run_in_executor(executor, fn, *args)
            else:
                async def wrapped(*args, **kwargs):
                    return await self.loop.run_in_executor(executor, fn, *args)
            return wrapped

        self.cpu_callbacks.register(wrap(fn))

    async def kill_workers(self, no_wait=False):
        if not no_wait:
            await self._qreq.join()
            await self._qwrite.join()
        # Next line runs io on any remaining data in the buffer
        if not self.data_buf.phased:
            await self.run_io_callbacks(self.data_buf.current_sample)
        for fut in self._consumers:
            fut.cancel()
        for fut in self._writers:
            fut.cancel()
        done, pending = await asyncio.wait(self._writers)
        logger.info("Shutdown successful")
        return True

    def run_loop(self, loop=None):
        if not loop and not self.loop:
            loop = asyncio.get_event_loop()
        self.set_loop(loop)
        if not self.loop.is_running():
            self.loop.run_forever()

    async def drive_fetch(self, reqs=[], **kwargs):
        self._configure(self.loop)
        if reqs:
            await self.produce_reqs(reqs=reqs, **kwargs)
        await self._kill_trigger.wait()
        res = await self.kill_workers()

    async def process_data(self):
        while True:
            try:
                data = await self._qwrite.get()
                self._qreq.task_done()

                data = await self.filter_data(data)
                if not data:
                    self._qwrite.task_done()
                    continue

                dstack = None
                async with self._data_lock:
                    self.data_buf.append(data)
                    self.on_data(data)
                    if self.data_buf.phased: # Get the view, release the lock
                        dstack = self.data_buf.current_sample
                if dstack:
                    await self.run_io_callbacks(dstack)
                self._qwrite.task_done()

            except CancelledError as ce:
                break
        return True

    async def run_io_callbacks(self, dstack):
        for cb in self.io_callbacks:
            try:
                await cb(dstack)
            except Exception as e:
                logger.info(
                    "User exception in io callback: {}".format(e))
                if not self.suppress_cb_errs:
                    raise

    async def filter_data(self, data):
        for cb in self.filters:
            result = await cb(data)
            if not result:
                return False
        return data

    async def produce_reqs(self, reqs=[], shutdown=False, **kwargs):
        for req in reqs:
            await asyncio.sleep(0.0)
            if req is None:
                self._kill_trigger.set()
                return True
            await self._qreq.put(req)
        if shutdown:
            self._kill_trigger.set()
        return True

class HTTPVedaClient(HTTPDataClient):
    def __init__(self, **kwargs):
        super(HTTPVedaClient, self).__init__(**kwargs)
        if self._token is None:
            self._token = cfg.conn.access_token


# Create functions that will check if a number is prime

def is_prime(n):
    if n == 1:
        return False
    elif n == 2:
        return True
    else:
        for i in range(2, n):
            if n % i == 0:
                return False
        return True

# Create a loop that steps by 1 and checks if the number is prime. If it is, add it to a list. When the list is 10001 items long, print the last item in the list.

def prime_list():
    prime_list = []
    i = 1
    while len(prime_list) < 10001:
        if is_prime(i) == True:
            prime_list.append(i)
        i += 1
    return prime_list

# Print the last item in the list.

print(prime_list()[-1])


def Wrapper(i):

    for _ in range(i):
        dataDict = init()
        returnValue = solution(dataDict)
        print(f'returnValue : {returnValue}')

def init():
    n = int(input().strip())
    dataDict = {}
    for _ in range(n**2):
        s, l1, l2, l3, l4 = list(map(int, input().split(' ')))
        dataDict[s] = [l1, l2, l3, l4]

    return dataDict

def solution(dataDict):
    pass

def returnCloseAbs(pos1, pos2): # y, x

    return abs(pos1[0]-pos2[0]), abs(pos1[1]-pos2[1])

if __name__ == '__main__':

    import sys
    sys.stdin = open('sample_input.txt', 'r')

    T = 2
    Wrapper(T)


from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QFileDialog
from os import getcwd

class OptionsDialogFunctions(QObject):
    saveSettingsRequest = pyqtSignal(dict)

    def __init__(self, widget, ui, settings):
        super(OptionsDialogFunctions, self).__init__(widget.parent())
        self.ui = ui
        self.widget = widget
        self.settings = settings

    def showOptionsDialog(self):
        self.init()
        self.widget.exec_()

    def init(self):
        self.setupConnections()
        self.applySettingsToUi()

    def setupConnections(self):
        self.ui.mainButtonBox.clicked["QAbstractButton*"].connect(self.mainButtonBoxClick)
        self.ui.addFolderButton.clicked.connect(self.addFolderButtonClicked)
        self.ui.deleteFolderButton.clicked.connect(self.deleteFolderButtonClicked)

    def applySettingsToUi(self):
        self.ui.maxThreadsSpinBox.setValue(int(self.settings["threads"]))
        if "library" in self.settings and self.settings["library"] is not None:
            self.ui.folderListWidget.addItems(self.settings["library"])

    def saveNewSettings(self):
        self.settings["threads"] = self.ui.maxThreadsSpinBox.value()
        self.settings["library"] = []
        for x in range(self.ui.folderListWidget.count()):
            self.settings["library"].append(self.ui.folderListWidget.item(x).text())
        self.saveSettingsRequest.emit(self.settings)

    def mainButtonBoxClick(self, button):
        if button.text() == "Save":
            self.saveNewSettings()
            self.widget.accept()
        elif button.text() == "Cancel":
            self.widget.close()
        elif button.text() == "Restore Defaults":
            pass

    def addFolderButtonClicked(self):
        filedialog = QFileDialog()
        filedialog.setAcceptMode(QFileDialog.AcceptOpen)
        filedialog.setFileMode(QFileDialog.DirectoryOnly)
        filedialog.setViewMode(QFileDialog.Detail)
        parent = self.widget
        caption = "Select directory to scan for movies in..."
        startdir = getcwd()
        options = QFileDialog.ShowDirsOnly
        selecteddir = filedialog.getExistingDirectory(parent, caption, startdir, options)
        self.ui.folderListWidget.addItem(selecteddir)

    def deleteFolderButtonClicked(self):
        selected_folder_index = self.ui.folderListWidget.currentRow()
        self.ui.folderListWidget.takeItem(selected_folder_index)


from unittest import TestCase, main

from project.team import Team

class TestTeam(TestCase):
    valid_name = 'Cherry'
    invalid_name = 'Cherry101'
    player1 = 'Gosho'
    player1_age = 20
    player2 = 'Pesho'
    player2_age = 22

    def test_init__with_valid_name__should_create_instance(self):
        team = Team(self.valid_name)

        self.assertEqual(self.valid_name, team.name)
        self.assertEqual({}, team.members)

    def test_init__when_name_contains_numbers__should_raise(self):
        with self.assertRaises(ValueError) as context:
            team = Team(self.invalid_name)

        expected = 'Team Name can contain only letters!'
        actual = str(context.exception)

        self.assertEqual(expected, actual)

    def test_add_member_when_all_names_does_not_exists_in_members__should_add(self):
        team = Team(self.valid_name)
        players = {self.player1: self.player1_age, self.player2: self.player2_age}

        actual = team.add_member(**players)
        expected = f"Successfully added: {', '.join([f'{self.player1}, {self.player2}'])}"

        self.assertEqual(expected, actual)
        self.assertIn(self.player1, team.members)
        self.assertIn(self.player2, team.members)
        self.assertEqual(self.player1_age, team.members[self.player1])
        self.assertEqual(self.player2_age, team.members[self.player2])

    def test_add_member_when_one_name_exist_in_members__should_ignore(self):
        team = Team(self.valid_name)
        test_player = {self.player1: self.player1_age}
        team.add_member(**test_player)

        players = {self.player1: self.player1_age, self.player2: self.player2_age}

        actual = team.add_member(**players)
        expected = f"Successfully added: {', '.join([f'{self.player2}'])}"

        self.assertEqual(expected, actual)
        self.assertIn(self.player1, team.members)
        self.assertIn(self.player2, team.members)
        self.assertEqual(self.player1_age, team.members[self.player1])
        self.assertEqual(self.player2_age, team.members[self.player2])

    def test_remove_member__when_name_not_exists(self):
        team = Team(self.valid_name)

        actual = team.remove_member(self.player1)
        expected = f"Member with name {self.player1} does not exist"

        self.assertEqual(expected, actual)
        self.assertDictEqual({}, team.members)

    def test_remove_member__when_name_exists(self):
        team = Team(self.valid_name)
        test_player = {self.player1: self.player1_age}
        team.add_member(**test_player)

        actual = team.remove_member(self.player1)
        expected = f"Member {self.player1} removed"

        self.assertEqual(expected, actual)
        self.assertDictEqual({}, team.members)

    def test__gt__when_is_bigger(self):
        team = Team(self.valid_name)
        other_team = Team('Strawberry')

        test_player = {self.player1: self.player1_age}
        team.add_member(**test_player)

        self.assertEqual(True, team > other_team)

    def test__gt__when_is_less(self):
        team = Team(self.valid_name)
        other_team = Team('Strawberry')

        test_player = {self.player1: self.player1_age}
        team.add_member(**test_player)

        self.assertEqual(False, team < other_team)

    def test__gt__when_is_equal(self):
        team = Team(self.valid_name)
        other_team = Team('Strawberry')

        test_player = {self.player1: self.player1_age}
        team.add_member(**test_player)

        self.assertEqual(False, team == other_team)

    def test__len__should_return_count_of_members(self):
        team = Team(self.valid_name)
        test_player = {self.player1: self.player1_age}
        team.add_member(**test_player)

        self.assertEqual(1, len(team))

    def test__add__should_concatenate_name_and_add_other_members(self):
        team = Team(self.valid_name)
        test_player = {self.player1: self.player1_age}
        team.add_member(**test_player)

        other_team = Team('Strawberry')
        test_player2 = {self.player2: self.player2_age}
        other_team.add_member(**test_player2)

        new_team = team + other_team

        self.assertEqual(team.name + other_team.name, new_team.name)
        self.assertIn(self.player1, new_team.members)
        self.assertIn(self.player2, new_team.members)
        self.assertEqual(self.player1_age, new_team.members[self.player1])
        self.assertEqual(self.player2_age, new_team.members[self.player2])

    def test__str__should_return_proper_string(self):
        team = Team(self.valid_name)
        players = {self.player1: self.player1_age, self.player2: self.player2_age}
        team.add_member(**players)

        actual = str(team)
        expected = f"Team name: {team.name}" + '\n' + f"Member: {self.player2} - {self.player2_age}-years old" + "\n" + \
                   f"Member: {self.player1} - {self.player1_age}-years old"

        self.assertEqual(expected,  actual)

    def test__str__when_empty_should_return_proper_string(self):
        team = Team(self.valid_name)

        actual = str(team)
        expected = f"Team name: {team.name}"

        self.assertEqual(expected, actual)

if __name__ == '__main__':
    main()

Python OOP Exam - 11 December 2021/tests/test/test.py


# -*- coding:utf-8 -*-
import math
N = int(input())
A = list(map(int, input().split()))
ans = 0
for tmp in range(N):
    if A[tmp] != 0:
        ans += A[tmp]
ans /= N - A.count(0)
print(int(math.ceil(ans)))


import unittest
import torch

from utils import read_py_config, build_model, check_file_exist

class ExportError(Exception):
    pass

class TestONNXExport(unittest.TestCase):
    def setUp(self):
        config = read_py_config('./configs/config.py')
        self.config = config
        self.model = build_model(config, device='cpu', strict=True, mode='convert')
        self.img_size = tuple(map(int, config.resize.values()))
    def test_export(self):
        try:
            # input to inference model
            dummy_input = torch.rand(size=(1, 3, *(self.img_size)), device='cpu')
            self.model.eval()
            torch.onnx.export(self.model, dummy_input, './mobilenetv3.onnx', verbose=False)
            check_file_exist('./mobilenetv3.onnx')
        except ExportError:
            self.fail("Exception raised while exporting to ONNX")

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


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

import json, random
from flask import Flask, render_template, request

from . import constant as const
from gpbapp.classes import LocationSearch, Parser
from gpbapp.function import infos_wikipedia

app = Flask(__name__)

@app.route('/')
@app.route('/index/')
def index():
    return render_template('index.html', API_KEY=const.API_KEY)

@app.route('/search', methods=['GET'])
def search():
    phrase = request.args.get('phrase')

    data = Parser()
    geolocation = LocationSearch(const.API_KEY)

    # cuts the sentence into words
    data_user = data.split_word(phrase)
    phrase_parser = data.util_word(data_user)
    complete_string = " ".join(phrase_parser)

    # Look for the place
    prediction = geolocation.place_prediction(complete_string)

    if not prediction:
        details = "Lieu non trouver"
        history = "La page n'existe pas"
    else:
        details = geolocation.places_search(prediction['description'])

        if not infos_wikipedia(complete_string):
            address_for_wiki = data.address(details['formatted_address'])

            if not infos_wikipedia(address_for_wiki):
                history = "La page n'existe pas"

            else:
                history = infos_wikipedia(address_for_wiki)

        else:
            history = infos_wikipedia(complete_string)

    return json.dumps({
        'status': 'OK',
        'result': details,
        'history': history,
        'story': random.choice(const.STORY)
        })

if __name__ == "__main__":
    app.run()