import numpy as np
import cv2
import colorsys
# import copy
from help import NMS

def _create_unique_color_float(tag, hue_step=0.41):
    h, v = (tag * hue_step) % 1, 1. - (int(tag * hue_step) % 4) / 5.
    r, g, b = colorsys.hsv_to_rgb(h, 1., v)
    return r, g, b

def _create_unique_color_uchar(tag, hue_step=0.41):
    r, g, b = _create_unique_color_float(tag, hue_step)
    return int(255 * r), int(255 * g), int(255 * b)

def recoverBBox(x, y, w, h, dsr_x, dsr_y):
    x = x * dsr_x
    y = y * dsr_y
    w = w * dsr_x
    h = h * dsr_y
    return x, y, w, h

def drawBBoxes(img, bboxes, dsr_x, dsr_y, color_index=0, threshold=1):
    for i in range(len(bboxes)):
        if bboxes[i][2] > threshold and bboxes[i][3] > threshold:
            x, y, w, h = recoverBBox(bboxes[i][0], bboxes[i][1], bboxes[i][2], bboxes[i][3], dsr_x, dsr_y)
            color = _create_unique_color_uchar(color_index)
            cv2.rectangle(img, (x, y), (x + w - 1, y + h - 1), color, 2)
    return img

def getBoundingRect(contours, threshold=1):
    bboxes = []
    for i in range(len(contours)):
        x, y, w, h = cv2.boundingRect(contours[i])
        if h > threshold and w > threshold:
            bboxes.append([x, y, w, h])
    return bboxes

def drawBoundingRect(img, contours, dsr_x, dsr_y, color_index=0, threshold=1):
    for i in range(len(contours)):
        # print(cv2.minAreaRect(contours[i]))
        x, y, w, h = cv2.boundingRect(contours[i])
        if h > threshold and w > threshold:
            x, y, w, h = recoverBBox(x, y, w, h, dsr_x, dsr_y)
            color = _create_unique_color_uchar(color_index)
            cv2.rectangle(img, (x, y), (x + w - 1, y + h - 1), color, 2)
    return img

def findContours(img):
    _, contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    return contours

def includeBoxes(big_box, small_box):
    big_x1 = big_box[0]
    big_x2 = big_box[0] + big_box[2] - 1
    big_y1 = big_box[1]
    big_y2 = big_box[1] + big_box[3] - 1
    inc_box = []
    # rem_box = copy.deepcopy(small_box)
    for i in range(len(small_box)):
        center_x = small_box[i][0] + (small_box[i][2] - 1) / 2
        center_y = small_box[i][1] + (small_box[i][3] - 1) / 2
        if center_x > big_x1 and center_x < big_x2 and center_y > big_y1 and center_y < big_y2:
            inc_box.append(small_box[i])
            # rem_box.remove(small_box[i])
    return inc_box  # , rem_box

def filterBBox(bboxes):
    for i in range(len(bboxes)):
        bboxes[i].append(bboxes[i][2] * bboxes[i][3])
    return NMS.IoM_suppression_fast(bboxes)

def isLeftRightTouched(bbox1, bbox2, offset=1):
    condition1 = bbox1[0] + bbox1[2] + offset > bbox2[0]
    condition2 = bbox1[0] < bbox2[0]
    condition3 = bbox1[0] + bbox1[2] - 1 < bbox2[0] + bbox2[2] - 1
    condition4 = bbox1[1] <= bbox2[1] + bbox2[3] - 1
    condition5 = bbox1[1] + bbox1[3] - 1 >= bbox2[1]
    if condition1 and condition2 and condition3 and condition4 and condition5:
        return True
    else:
        return False

def isUpDownTouched(bbox1, bbox2, offset=1):
    condition1 = bbox1[1] + bbox1[3] + offset > bbox2[1]
    condition2 = bbox1[1] < bbox2[1]
    condition3 = bbox1[1] + bbox1[3] - 1 < bbox2[1] + bbox2[3] - 1
    condition4 = bbox1[0] <= bbox2[0] + bbox2[2] - 1
    condition5 = bbox1[0] + bbox1[2] - 1 >= bbox2[0]
    if condition1 and condition2 and condition3 and condition4 and condition5:
        return True
    else:
        return False

def isMatchPairLR(j, bboxes1, bboxes2):
    index1 = []
    area = 0
    for k in range(len(bboxes2)):
        if isLeftRightTouched(bboxes1[j], bboxes2[k]):
            if bboxes2[k][2] * bboxes2[k][3] > area:
                area = bboxes2[k][2] * bboxes2[k][3]
                index1 = [j, k]
    if index1:
        index2 = []
        area = 0
        for l in range(len(bboxes1)):
            if isLeftRightTouched(bboxes1[l], bboxes2[index1[1]]):
                if bboxes1[l][2] * bboxes1[l][3] > area:
                    area = bboxes1[l][2] * bboxes1[l][3]
                    index2 = [l, index1[1]]
    else:
        return False, index1

    if index1 == index2:
        return True, index1
    else:
        return False, index1

def isMatchPairRL(j, bboxes1, bboxes2):
    index1 = []
    area = 0
    for k in range(len(bboxes2)):
        if isLeftRightTouched(bboxes2[k], bboxes1[j]):
            if bboxes2[k][2] * bboxes2[k][3] > area:
                area = bboxes2[k][2] * bboxes2[k][3]
                index1 = [j, k]
    if index1:
        index2 = []
        area = 0
        for l in range(len(bboxes1)):
            if isLeftRightTouched(bboxes2[index1[1]], bboxes1[l]):
                if bboxes1[l][2] * bboxes1[l][3] > area:
                    area = bboxes1[l][2] * bboxes1[l][3]
                    index2 = [l, index1[1]]
    else:
        return False, index1

    if index1 == index2:
        return True, index1
    else:
        return False, index1

def isMatchPairUD(j, bboxes1, bboxes2):
    index1 = []
    area = 0
    for k in range(len(bboxes2)):
        if isUpDownTouched(bboxes1[j], bboxes2[k]):
            if bboxes2[k][2] * bboxes2[k][3] > area:
                area = bboxes2[k][2] * bboxes2[k][3]
                index1 = [j, k]
    if index1:
        index2 = []
        area = 0
        for l in range(len(bboxes1)):
            if isUpDownTouched(bboxes1[l], bboxes2[index1[1]]):
                if bboxes1[l][2] * bboxes1[l][3] > area:
                    area = bboxes1[l][2] * bboxes1[l][3]
                    index2 = [l, index1[1]]
    else:
        return False, index1

    if index1 == index2:
        return True, index1
    else:
        return False, index1

def isMatchPairDU(j, bboxes1, bboxes2):
    index1 = []
    area = 0
    for k in range(len(bboxes2)):
        if isUpDownTouched(bboxes2[k], bboxes1[j]):
            if bboxes2[k][2] * bboxes2[k][3] > area:
                area = bboxes2[k][2] * bboxes2[k][3]
                index1 = [j, k]
    if index1:
        index2 = []
        area = 0
        for l in range(len(bboxes1)):
            if isUpDownTouched(bboxes2[index1[1]], bboxes1[l]):
                if bboxes1[l][2] * bboxes1[l][3] > area:
                    area = bboxes1[l][2] * bboxes1[l][3]
                    index2 = [l, index1[1]]
    else:
        return False, index1

    if index1 == index2:
        return True, index1
    else:
        return False, index1

def segmentConnectedText(bbox_all, bbox_up_left, bbox_up_right, bbox_down_left, bbox_down_right):
    seg_checked_bbox = []
    for i in range(len(bbox_all)):
        up_left = includeBoxes(bbox_all[i], bbox_up_left)
        if len(up_left) <= 1:
            seg_checked_bbox.append(bbox_all[i])
            continue
        else:
            up_right = includeBoxes(bbox_all[i], bbox_up_right)
            if len(up_right) <= 1:
                seg_checked_bbox.append(bbox_all[i])
                continue
            else:
                down_right = includeBoxes(bbox_all[i], bbox_down_right)
                if len(down_right) <= 1:
                    seg_checked_bbox.append(bbox_all[i])
                    continue
                else:
                    down_left = includeBoxes(bbox_all[i], bbox_down_left)
                    if len(down_left) <= 1:
                        seg_checked_bbox.append(bbox_all[i])
                        continue
                    else:
                        final_index = []
                        for j in range(len(up_left)):
                            match_index = []
                            flag1, index1 = isMatchPairLR(j, up_left, up_right)
                            if flag1:
                                match_index.extend(index1)
                                flag2, index2 = isMatchPairUD(index1[1], up_right, down_right)
                                if flag2:
                                    match_index.append(index2[1])
                                    flag3, index3 = isMatchPairRL(index2[1], down_right, down_left)
                                    if flag3:
                                        match_index.append(index3[1])
                                        flag4, index4 = isMatchPairDU(index3[1], down_left, up_left)
                                        if flag4:
                                            # Got a group
                                            final_index.append(match_index)

                        if len(final_index) > 1:
                            for l in range(len(final_index)):
                                x1 = min(up_left[final_index[l][0]][0], up_right[final_index[l][1]][0],
                                         down_right[final_index[l][2]][0], down_left[final_index[l][3]][0])
                                y1 = min(up_left[final_index[l][0]][1], up_right[final_index[l][1]][1],
                                         down_right[final_index[l][2]][1], down_left[final_index[l][3]][1])
                                x2 = max(up_left[final_index[l][0]][0] + up_left[final_index[l][0]][2] - 1,
                                         up_right[final_index[l][1]][0] + up_right[final_index[l][1]][2] - 1,
                                         down_right[final_index[l][2]][0] + down_right[final_index[l][2]][2] - 1,
                                         down_left[final_index[l][3]][0] + down_left[final_index[l][3]][2] - 1)
                                y2 = max(up_left[final_index[l][0]][1] + up_left[final_index[l][0]][3] - 1,
                                         up_right[final_index[l][1]][1] + up_right[final_index[l][1]][3] - 1,
                                         down_right[final_index[l][2]][1] + down_right[final_index[l][2]][3] - 1,
                                         down_left[final_index[l][3]][1] + down_left[final_index[l][3]][3] - 1)
                                seg_checked_bbox.append([x1, y1, x2 - x1 + 1, y2 - y1 + 1])
                                bbox_up_left.remove(up_left[final_index[l][0]])
                                bbox_up_right.remove(up_right[final_index[l][1]])
                                bbox_down_right.remove(down_right[final_index[l][2]])
                                bbox_down_left.remove(down_left[final_index[l][3]])
                        else:
                            seg_checked_bbox.append(bbox_all[i])
    return seg_checked_bbox

def processLocation(img, cls_image=None, locations=None, dsr_x=4, dsr_y=4, drawBBox=False, filterBox=True):
    for i in range(cls_image.shape[0]):
        for j in range(cls_image.shape[1]):
            if cls_image[i, j, 0] < 0.5:
                cls_image[i, j, 0] = 255
            else:
                cls_image[i, j, 0] = 0
            loc = locations[i, j, :].tolist()
            loc = loc.index(max(loc))
            locations[i, j, :] = 0
            locations[i, j, loc] = 255

    cls_image = np.array(cls_image, np.uint8)
    up_left = np.array(locations[:, :, 1], np.uint8)
    up_right = np.array(locations[:, :, 2], np.uint8)
    down_left = np.array(locations[:, :, 3], np.uint8)
    down_right = np.array(locations[:, :, 4], np.uint8)
    # img_color = cv2.cvtColor(cls_image, cv2.COLOR_GRAY2RGB)
    # img = cv2.imread('test.jpg')
    # imgray = cv2.cvtColor(classes, cv2.COLOR_BGR2GRAY)  # 彩色转灰度
    # ret, thresh = cv2.threshold(img, 127, 255, 0)  # 进行二值化
    # print(thresh)
    contours = findContours(cls_image)
    bbox_all = getBoundingRect(contours)
    contours_up_left = findContours(up_left)
    bbox_up_left = getBoundingRect(contours_up_left)
    contours_up_right = findContours(up_right)
    bbox_up_right = getBoundingRect(contours_up_right)
    contours_down_left = findContours(down_left)
    bbox_down_left = getBoundingRect(contours_down_left)
    contours_down_right = findContours(down_right)
    bbox_down_right = getBoundingRect(contours_down_right)

    bbox_all = segmentConnectedText(bbox_all, bbox_up_left, bbox_up_right, bbox_down_left, bbox_down_right)

    # 检索模式为树形cv2.RETR_TREE，
    # 轮廓存储模式为简单模式cv2.CHAIN_APPROX_SIMPLE，如果设置为 cv2.CHAIN_APPROX_NONE，所有的边界点都会被存储。
    # img = cv2.drawContour(img, contours, -1, (0, 255, 0), 3)  # 此时是将轮廓绘制到了原始图像上
    # 第三个参数是轮廓的索引（在绘制独立轮廓是很有用，当设置为 -1 时绘制所有轮廓）。接下来的参数是轮廓的颜色和厚度等

    # img = drawBoundingRect(img, contours, dsr_x, dsr_y, color_index=0)
    # img = drawBoundingRect(img, contours_up_left, dsr_x, dsr_y, color_index=1)
    # img = drawBoundingRect(img, contours_up_right, dsr_x, dsr_y, color_index=2)
    # img = drawBoundingRect(img, contours_down_left, dsr_x, dsr_y, color_index=3)
    # img = drawBoundingRect(img, contours_down_right, dsr_x, dsr_y, color_index=4)
    if filterBox:
        bbox_all = filterBBox(bbox_all)
    if drawBBox:
        img = drawBBoxes(img, bbox_all, dsr_x, dsr_y, color_index=0)
        return img
    else:
        for i in range(len(bbox_all)):
            bbox_all[i][0] *= dsr_x
            bbox_all[i][1] *= dsr_y
            bbox_all[i][2] *= dsr_x
            bbox_all[i][3] *= dsr_y
        return bbox_all

    # img2 = cv2.drawContours(img_color, contours, -1, (0, 255, 0), 1)
    # cv2.imshow('img', img)  # 显示原始图像
    # cv2.waitKey()  # 窗口等待按键，无此代码，窗口闪一下就消失

    # ret, binary = cv2.threshold(classes, 127, 255, cv2.THRESH_BINARY)
    # binary = classes.reshape((classes.shape[0], classes.shape[1], 1))

    # _, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    # gray = classes.reshape((classes.shape[0], classes.shape[1], 1))
    # # gray = cv2.cvtColor(classes, cv2.COLOR_BGR2GRAY)
    # mser = cv2.MSER_create()
    # contours, regions = mser.detectRegions(gray)
    # hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions]
    # cv2.polylines(classes, hulls, 1, (0, 255, 0))
    # cv2.imshow('img', cls_image)

    # cv2.imshow('pic', classes)
    # cv2.waitKey(0)
#
#
# def main():
#     classes = np.ones((ResizeH // 4, ResizeW // 4, 1))
#     for i in range(50, 80):
#         for j in range(60, 100):
#             classes[i, j, 0] = 0
#     for i in range(60, 90):
#         for j in range(65, 120):
#             classes[i, j, 0] = 0
#     processLocation(cls_image=classes)
#
#
# if __name__ == '__main__':
#     ResizeH = 608
#     ResizeW = 800
#     main()


import os
import pandas as pd
import numpy as np
from upsetplot import from_contents, plot
import matplotlib.pyplot as plt

from GEN_Utils import FileHandling
from loguru import logger

logger.info('Import OK')

input_folder = 'results/tpemi_proteomics/peptide_summary/'
output_folder = 'results/tpemi_proteomics/intersections/'

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

# Read in raw data
cys_peptides = pd.read_excel(f'{input_folder}peptide_summary.xlsx', sheet_name=None)
peptides = cys_peptides['summary'].copy()
peptides.drop([col for col in peptides.columns.tolist() if 'Unnamed: ' in col], axis=1, inplace=True)

treatments = ['Celastrol', 'Novobiocin', 'MG132', 'Ver155008', 'Staurosporine']
proteins = pd.pivot_table(peptides.copy(), index=['Proteins'], columns='treatment', values='log2_thresh_pval_ratio')
proteins = proteins[treatments].dropna() # select only proteins quantified in all treatments
proteins_all_quant = pd.melt(proteins.reset_index(), id_vars='Proteins', value_vars=treatments, var_name='treatment', value_name='log2_thresh_pval_ratio')
proteins_all_quant_one_change = pd.melt(proteins.replace(0, np.nan).dropna(how='all').replace(np.nan, 0).reset_index(), id_vars='Proteins', value_vars=treatments, var_name='treatment', value_name='log2_thresh_pval_ratio')

peptide_quant = pd.pivot_table(peptides.copy(), index=[
                          'Proteins', 'Sequence'], columns='treatment', values='log2_thresh_pval_ratio')
# select only proteins quantified in all treatments
peptide_quant = peptide_quant[treatments].dropna()
peptides_all_quant = pd.melt(peptide_quant.reset_index(), id_vars=['Proteins', 'Sequence'], value_vars=treatments,var_name='treatment', value_name='log2_thresh_pval_ratio')
peptides_all_quant_one_change = pd.melt(peptide_quant.replace(0, np.nan).dropna(how='all').replace(np.nan, 0).reset_index(), id_vars=['Proteins', 'Sequence'], value_vars=treatments, var_name='treatment', value_name='log2_thresh_pval_ratio')
# -----------------------------------UpSet plotting-----------------------------------
# Generate UpSet figure for significant proteins i.e. any protein that had at least one significant change
# turn into dictionary to feed to pyupset
changed_prots = {df_name: df.replace(0, np.nan).dropna(subset=['log2_thresh_pval_ratio'])[
    'Proteins'].unique().tolist() for df_name, df in proteins_all_quant_one_change.groupby('treatment')}
changed_prots = from_contents(changed_prots)

fig = plot(changed_prots, sort_by='degree', show_counts=True)
plt.savefig(f'{output_folder}protein_upset.svg')

# Generate UpSet figure for significant peptides
changed_peps = {df_name: df.replace(0, np.nan).dropna(subset=['log2_thresh_pval_ratio'])[
    'Sequence'].unique().tolist() for df_name, df in peptides_all_quant_one_change.groupby('treatment')}
changed_peps = from_contents(changed_peps)

fig = plot(changed_peps, sort_by='degree', show_counts=True)

#-------------------Generating degree count results-----
degree_peps = changed_peps.reset_index().set_index('id').sum(axis=1).reset_index()
degree_peps.columns = ['Sequence', 'Degree']
degree_peps['Proteins'] = degree_peps['Sequence'].map(dict(peptides[['Sequence', 'Proteins']].values))
peps_summary = pd.merge(changed_peps.reset_index().rename(columns={'id': 'Sequence'}), degree_peps, on=['Sequence'])

degree_prots = changed_prots.reset_index().set_index('id').sum(axis=1).reset_index()
degree_prots.columns = ['Proteins', 'Degree']
prots_summary = pd.merge(changed_prots.reset_index().rename(
    columns={'id': 'Proteins'}), degree_prots, on=['Proteins'])

# Save summary info
peps_summary.to_csv(f'{output_folder}peptide_intersection_degree.csv')
prots_summary.to_csv(f'{output_folder}protein_intersection_degree.csv')


# print("구구단 몇 단을 계산할까?")
# user_input = input()
# print("구구단", user_input, "단을 계산한다.")
# int_input = int(user_input)
# for i in range(1, 10):
#     result = int_input*i
#     print(user_input, "X", i, "=", result)

# import random
# import time

# def game_gugudan(dans, game_time):
#     print(f'\n{"="*10} 구구단 게임 {"="*10}\n')
#     games = int(input('\n 몇 게임 할까요? : '))  # input 안에서 바로 int 변환

#     games_cnt = 0  # 진행 게임수
#     correct_cnt = 0  # 맞은 게임수
#     incorrect_cnt = 0  # 틀린 게임수
#     g_time = game_time  # 제한시간(초) 설정

#     while games_cnt < games:  # games_cnt가 games보다 작을 때까지 반복
#         dan = random.randint(2, dans)
#         number = random.randint(2, 9)

#         start = time.time()
#         answer = input(f'\n#{games_cnt + 1} 게임: {dan} X {number} = ')
#         end = time.time()

#         if not answer.isdigit():
#             incorrect_cnt += 1
#             print('오입력, 틀렸습니다!')
#         elif (end - start) > g_time:
#             incorrect_cnt += 1
#             print(f'입력 시간 {g_time}초 경과로 오답 처리합니다.')
#         elif int(answer) == (dan * number):
#             correct_cnt += 1
#             print('맞았습니다!')
#         else:
#             incorrect_cnt += 1
#             print('틀렸습니다!')

#         games_cnt += 1

#     print(
#         f'\n총 {games}게임 중\n맞은 게임수: {correct_cnt}\n틀린 게임수: {incorrect_cnt}\n정확도: {(correct_cnt/games)*100:.1f}%')

# dans = 9  # 단수 (9~19)
# game_time = 5  # 응답 시간 제한(초)
# game_gugudan(dans, game_time)

import tkinter as tk
from tkinter import simpledialog
import random
import time

class GugudanGameGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("구구단 게임")
        self.root.geometry("400x300")

        self.dans = 9
        self.game_time = 5

        self.start_button = tk.Button(
            root, text="게임 시작", command=self.start_game)
        self.start_button.pack(pady=20)

        self.question_label = tk.Label(root, text="", font=("Helvetica", 24))
        self.question_label.pack()

        self.result_label = tk.Label(root, text="")
        self.result_label.pack()

    def start_game(self):
        games = simpledialog.askinteger("게임 설정", "몇 게임 할까요?")
        if games is not None:  # 사용자가 창을 닫을 때 예외 처리
            correct_cnt, incorrect_cnt = self.play_games(games)
            accuracy = (correct_cnt / games) * 100
            result_text = f"총 {games}게임 중\n맞은 게임수: {correct_cnt}\n틀린 게임수: {incorrect_cnt}\n정확도: {accuracy:.1f}%"
            self.result_label.config(text=result_text)

    def play_games(self, games):
        games_cnt = 0
        correct_cnt = 0
        incorrect_cnt = 0
        g_time = self.game_time

        while games_cnt < games:
            dan = random.randint(2, self.dans)
            number = random.randint(2, 9)

            self.question_label.config(text=f"{dan} X {number} = ")

            start = time.time()

            answer = self.show_question(dan, number)

            end = time.time()

            if answer is None:
                break  # 사용자가 대화상자를 닫았을 때

            if not answer.isdigit():
                incorrect_cnt += 1
            elif (end - start) > g_time:
                incorrect_cnt += 1
            elif int(answer) == (dan * number):
                correct_cnt += 1
            else:
                incorrect_cnt += 1

            games_cnt += 1

        self.question_label.config(text="")  # 문제 표시 레이블 초기화
        return correct_cnt, incorrect_cnt

    def show_question(self, dan, number):
        question = f"{dan} X {number} = "
        answer = simpledialog.askstring("구구단 문제", question)
        return answer

if __name__ == "__main__":
    root = tk.Tk()
    app = GugudanGameGUI(root)
    root.mainloop()


# author: choi sugil
# date: 2023.10.25 version: 1.0.0 license: MIT brief: keyward
# description: 데이터클래스 와 클래스를 연동하는 프로그램 sqlite로 데이터를 읽어옴
from dataclasses import dataclass, field
import sqlite3

@dataclass
class StudentArg:
    name: str
    korean: int = 0
    math: int = 0
    english: int = 0
    science: int = 0
    score_set: list = field(default_factory=list)

    def __post_init__(self):
        self.score_set = [self.korean, self.math, self.english, self.science]

class Student:
    def __init__(self, arg: StudentArg):
        """student class
        Args:
            args (StudentArg): Student dataclass

        Attributes:
            name: str
            korean: int
            math: int
            english: int
            science: int
            score_set: list
        """
        self.name = arg.name
        self.korean = arg.korean
        self.math = arg.math
        self.english = arg.english
        self.science = arg.science
        self.score_set = arg.score_set

    def get_sum(self):
        return sum(self.score_set)

    def get_average(self):
        return self.get_sum() / 4

    def __str__(self):
        return f"{self.name}\t{self.get_sum()}\t{self.get_average():.2f}"

def main():
    students = []
    conn = sqlite3.connect("C:\chungnam_chatbot\python\example.db")
    c = conn.cursor()
    c.execute("SELECT * FROM students;")
    rows = c.fetchall()
    for row in rows:
        arg = StudentArg(*row)
        students.append(Student(arg))
        print(f"{students[-1].name} : {students[-1].score_set}")
    conn.close()

    print("이름\t총점\t평균")
    for student in students:
        print(student)

if __name__ == "__main__":
    main()


import torch
from torch.autograd import Variable
import numpy as np

def subsequent_mask(size):
    "Mask out subsequent positions."
    attn_shape = (1, size, size)
    subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')
    return torch.from_numpy(subsequent_mask) == 0

def make_std_mask(tgt, pad):
    "Create a mask to hide padding and future words."
    tgt_mask = (tgt != pad).unsqueeze(-2)
    tgt_mask = tgt_mask & Variable(subsequent_mask(tgt.size(-1)).type_as(tgt_mask.data))
    return tgt_mask

scores = torch.tensor([0.1, 0.3, 0.3, 0.1, 0.1, 0.03, 0.05, 0.02])
target = torch.tensor([48, 45, 67, 36, 49, 34, 23, 32])
print("Target: ", target)
look_ahead_mask = make_std_mask(target, 0)
print("Attn Mask: ", look_ahead_mask)

print("Attn Scores: ", scores)
print("After applying attn mask:")
scores = scores.masked_fill(look_ahead_mask == 0, -1e9)
print(scores.numpy())


from django.shortcuts import render, get_object_or_404,HttpResponseRedirect
from .models import Category, Product
from cart.forms import CartAddProductForm

def product_list(request, category_slug=None):
    category = None
    categories = Category.objects.all()
    products = Product.objects.filter()
    cart_product_form = CartAddProductForm()

    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        products = products.filter(category=category)

    return render(request,
                  'orders/product/list.html',
                  {'category': category,
                   'categories': categories,
                   'products': products,
                   'cart_product_form': cart_product_form})

def product_detail(request, id, slug):
    product = get_object_or_404(Product,
                                id=id,
                                slug=slug)
    cart_product_form = CartAddProductForm()
    products = Product.objects.filter()
    categories = Category.objects.first()

    return render(request,
                  'orders/product/detail.html',
                  {'product': product,'products':products,'categories':categories,
                   'cart_product_form': cart_product_form})


import threading
import pickle
import socket

class Receiver(threading.Thread):
    def __init__(self, client_socket):
        threading.Thread.__init__(self)

        self.client_socket = client_socket

        self.quit = False

        self.resign_white = False
        self.resign_black = False
        self.offer_draw_white = False
        self.offer_draw_black = False
        self.draw = False
        self.aborted_white = False
        self.aborted_black = False

        self.move = None
        self.time = None

    def kill(self):
        self.quit = True

    def run(self):
        while not self.quit:
            self.client_socket.settimeout(1)
            try:
                self.move = pickle.loads(self.client_socket.recv(1024))

                if self.move == "resign_b":
                    self.resign_black = True
                elif self.move == "resign_w":
                    self.resign_white = True
                elif self.move == "draw_offer_b":
                    self.offer_draw_black = True
                    if self.offer_draw_white:
                        self.draw = True
                        self.quit = True
                elif self.move == "draw_offer_w":
                    self.offer_draw_white = True
                    if self.offer_draw_black:
                        self.draw = True
                        self.quit = True
                elif self.move == "abort_w":
                    self.aborted_white = True
                elif self.move == "abort_b":
                    self.aborted_black = True

                print(self.move)
            except:
                continue


from confluent_kafka import Consumer, KafkaException, Producer, KafkaError
import json
import threading
import time

KAFKA_BROKER_URL = 'localhost:9092'
KAFKA_TOPIC = 'sms-messages'
STATUS_TOPIC = 'sender-status-updates'
GROUP_ID = 'sms-sender-group'

class Sender(threading.Thread):

    def __init__(self, sender_id, error_rate, processing_time):
        super().__init__()
        self.sender_id = sender_id
        self.consumer = Consumer({
            'bootstrap.servers': KAFKA_BROKER_URL,
            'group.id': GROUP_ID,
            'auto.offset.reset': 'earliest',
        })
        self.producer = Producer({'bootstrap.servers': KAFKA_BROKER_URL})
        self.success_count = 0
        self.total_msgs = 0
        self.failed_count = 0
        self.error_rate = error_rate
        self.fail_after_msgs = 100/error_rate
        self.processing_time = processing_time

    def run(self):
        self.poll_messages()

    def poll_messages(self):
        self.consumer.subscribe([KAFKA_TOPIC])
        print("processing messages")
        try:
            while True:
                msg = self.consumer.poll(1.0)
                if msg is None:
                    continue
                if msg.error():
                    if msg.error().code() == KafkaError._PARTITION_EOF:
                        continue
                    else:
                        print(msg.error())
                        break
                self.total_msgs += 1
                start_time = time.time()
                time.sleep(self.processing_time)
                end_time = time.time()
                if(self.total_msgs % self.fail_after_msgs == 0):
                    self.failed_count +=1
                else:
                    self.success_count += 1
                processing_time = end_time - start_time
                status_update = {
                    'sender_id': self.sender_id,
                    'success_count': self.success_count,
                    'failed_count': self.failed_count,
                    'total_processing_time': processing_time*(self.success_count+self.failed_count)
                }
                print("Sending messages to the status producer")
                self.producer.produce(STATUS_TOPIC, key=str(self.sender_id), value=json.dumps(status_update))
        except KeyboardInterrupt:
            pass
        finally:
            self.consumer.close()

def main():
    num_senders = 2
    senders = []
    settings = [[10, 2], [20, 1]] # Setting of the error rate and processing times for each sender.
    index = 0
    for i in range(num_senders):
        sender = Sender(sender_id=f'sender_{i}', error_rate=settings[index][0], processing_time=settings[index][1])
        sender.start()
        senders.append(sender)
        index += 1

    for sender in senders:
        sender.join()

if __name__ == '__main__':
    main()


from datetime import date, datetime, timedelta

from django.conf import settings
from django.core.management.base import BaseCommand

from kitsune.kpi.management import utils
from kitsune.kpi.models import (
    SEARCH_CLICKS_METRIC_CODE,
    SEARCH_SEARCHES_METRIC_CODE,
    Metric,
    MetricKind,
)
from kitsune.sumo import googleanalytics

class Command(BaseCommand):
    help = "Get new search CTR data from Google Analytics and save."

    def handle(self, **options):
        if settings.STAGE:
            # Let's be nice to GA and skip on stage.
            return

        # Start updating the day after the last updated.
        latest_metric = utils._get_latest_metric(SEARCH_CLICKS_METRIC_CODE)
        if latest_metric is not None:
            latest_metric_date = latest_metric.start
        else:
            latest_metric_date = date(2011, 1, 1)
        start = latest_metric_date + timedelta(days=1)

        # Collect up until yesterday
        end = date.today() - timedelta(days=1)

        # Get the CTR data from Google Analytics.
        ctr_data = googleanalytics.search_ctr(start, end)

        # Create the metrics.
        clicks_kind = MetricKind.objects.get_or_create(code=SEARCH_CLICKS_METRIC_CODE)[0]
        searches_kind = MetricKind.objects.get_or_create(code=SEARCH_SEARCHES_METRIC_CODE)[0]
        for date_str, ctr in list(ctr_data.items()):
            day = datetime.strptime(date_str, "%Y-%m-%d").date()

            # Note: we've been storing our search data as total number of
            # searches and clicks. Google Analytics only gives us the rate,
            # so I am normalizing to 1000 searches (multiplying the % by 10).
            # I didn't switch everything to a rate because I don't want to
            # throw away the historic data.
            Metric.objects.create(
                kind=searches_kind, start=day, end=day + timedelta(days=1), value=1000
            )
            Metric.objects.create(
                kind=clicks_kind,
                start=day,
                end=day + timedelta(days=1),
                value=round(ctr, 1) * 10,
            )


#!/usr/bin/env python3

import os
import re
import time
import pytest
import shutil
import hashlib
import platform
from pathlib import Path
import threading
import subprocess
import random
import string
import tempfile

from refuse.high import fuse_exit

import autoortho_fuse
import aostats
from aoconfig import CFG

import logging
#logging.basicConfig()
log = logging.getLogger('log')
#log.setLevel(logging.DEBUG)
log.setLevel(logging.INFO)

ao = None

def runmount(mountdir, cachedir):
    global ao
    #ao = autoortho.AutoOrtho('./testfiles', cachedir)
    #autoortho.run(ao, mountdir, True)

    ao = autoortho_fuse.AutoOrtho('./testfiles', cachedir)
    autoortho_fuse.run(ao, mountdir)
    print("Exiting FUSE mount")

    #if os.path.isdir(ao.cache_dir):
    #    print("Removing cache dir")
    #    shutil.rmtree(ao.cache_dir)
    #shutil.rmtree(ao.cache_dir)
    #ao.cache_dir = os.path.join(mountdir, "cache")
    #autoortho.FUSE(ao, mountdir, nothreads=True, foreground=True, allow_other=True, max_readahead=0)

    print("Shutting down mount fixture")
    #if os.path.isdir(ao.cache_dir):
    #    print("Removing cache dir")
    #    shutil.rmtree(ao.cache_dir)

@pytest.fixture(scope="module")
def mount():

    tmpname = ''.join(random.choice(string.ascii_lowercase) for x in range(8))

    print(f"TMPNAME: {tmpname}")

    tmpdir = os.path.join(tempfile.gettempdir(), f"atest_{tmpname}")
    os.makedirs(tmpdir)

    #tmpdir = tempfile.mkdtemp()
    mountdir = str(os.path.join(tmpdir, 'mount'))

    if platform.system() != "Windows":
        os.makedirs(mountdir)
        print(os.listdir(mountdir))

    #cachedir = os.path.join(tmpdir, 'cache')
    cachedir = "./cache"

    try:
        stats = aostats.AOStats()
        stats.start()
        t = threading.Thread(daemon=True, target=runmount, args=(mountdir, cachedir))
        t.start()
        time.sleep(1)
        #print(os.listdir(mountdir))

        yield mountdir

    finally:
        stats.stop()
        #files = os.listdir(mountdir)
        #print(files)
        if platform.system() != "Windows":
            subprocess.check_call(f"umount {mountdir}", shell=True)
            subprocess.call(f"umount -f AutoOrtho", shell=True)
        time.sleep(1)
        shutil.rmtree(tmpdir)

def _test_stuff():
    assert 1 == 1

def _test_read_dsf(mount):
    dsf_file = './testfiles/dsftest/+00-051.dsf'
    ter_dir = './testfiles/dsftest/'

    with open(dsf_file, encoding='utf-8', errors='ignore') as h:
        ter_files = re.findall("terrain\W?\d+[-_]\d+[-_]\D*\d+\w*\.ter", h.read())

    dds_full_paths = set()
    log.info(f"DSF: found {len(ter_files)} terrain files.  Parsing ...")
    for t in ter_files:
        ter_path = os.path.join(ter_dir, t)
        #log.debug(f"Checking {ter_path}...")
        with open(ter_path) as h:
            dds_files = re.findall("\S*/\d+[-_]\d+[-_]\D*\d+.dds", h.read())
            log.info(f"Found: {dds_files}")
            for dds in dds_files:
                dds_full_paths.add(
                    os.path.join(mount, os.path.basename(dds))
                )

    print(dds_full_paths)
    print(len(dds_full_paths))

    #CFG.pydds.compressor = "STB"
    for dds in dds_full_paths:
        rc = subprocess.call(
            f"identify {dds}",
            shell=True
        )

    log.info(f"FINAL STATS: ID: {aostats.STATS}")
    #assert True == False

def test_autoortho(mount):
    print(mount)

    things = os.listdir(mount)
    print(things)

    rc = subprocess.call(
        f"identify {mount}/3232_2176_Null13.dds",
        shell=True
    )

    assert rc == 0

def test_read_header(mount):
    things = os.listdir(mount)

    testfile = f"{mount}/24832_12416_BI16.dds"

    stat = os.stat(testfile)
    size = stat.st_size

    blocksize = 16384

    blocks = size//blocksize
    remainder = size%blocksize

    with open(testfile, "rb") as h:
        header = h.read(blocksize)

    rc = subprocess.call(
        f"identify {testfile}",
        shell=True
    )

    assert rc == 0

def test_read_mip0(mount):
    things = os.listdir(mount)

    testfile = f"{mount}/24832_12416_BI16.dds"

    stat = os.stat(testfile)
    size = stat.st_size

    blocksize = 16384

    blocks = size//blocksize
    remainder = size%blocksize

    with open(testfile, "rb") as h:
        data = h.read(blocksize)
        data = h.read(blocksize)

    #assert True == False

    rc = subprocess.call(
        f"identify {testfile}",
        shell=True
    )

    assert rc == 0

def test_read_mip1(mount, tmpdir):
    things = os.listdir(mount)

    testfile = f"{mount}/24832_12416_BI16.dds"

    stat = os.stat(testfile)
    size = stat.st_size

    blocksize = 4096

    blocks = size//blocksize
    remainder = size%blocksize

    mipmapsize = 4194304

    with open(testfile, "rb") as h:
        data = h.read(128)
        print(data)
        print(f"DATA LEN: {len(data)}")
        h.seek(16777344)
        data = h.read(mipmapsize)
        print(f"DATA LEN: {len(data)}")

    with open(testfile, "rb") as read_h:
        with open(f"{tmpdir}/testmip1.dds", 'wb') as write_h:
            write_h.write(read_h.read(128))
            read_h.seek(16777344)
            write_h.seek(16777344)
            write_h.write(read_h.read(mipmapsize))
            write_h.seek(22369870)
            write_h.write(b'x\00')

    rc = subprocess.call(
        f"identify -verbose {testfile}",
        shell=True
    )
    assert rc == 0

    rc = subprocess.call(
        f"identify {tmpdir}/testmip1.dds",
        shell=True
    )
    assert rc == 0

    #assert True == False

def _test_mip_4_read(mount, tmpdir):
    global ao
    testfile = os.path.join(mount, "24832_12416_BI16.dds")
    with open(testfile, "rb") as h:
        time.sleep(0.5)
        log.info("-"*32)
        log.info("First read the header:")
        header = h.read(128)

        time.sleep(0.5)
        log.info("-"*32)
        log.info("Now seek to mipmap4")
        h.seek(22282368)
        time.sleep(1)
        log.info("-"*32)
        log.info("Tell:")
        pos = h.tell()
        log.debug(f"TEST TELL(): {pos}")
        time.sleep(1)
        log.info("-"*32)
        log.info("Read mipmap 4")
        data1 = h.read(65536)
        print(data1[0:20])
        time.sleep(0.5)
        log.info("-"*32)
        log.info("Close")
        time.sleep(0.5)

    log.info(f"Tiles: {len(ao.tc.tiles)}")
    for k,v in ao.tc.tiles.items():
        log.info(f"{k} {v}")
        log.info(f"Chunks: {len(v.chunks)}")
        log.info(v.dds.mipmap_list)

#     with open(testfile, "rb") as h:
#         data = h.read(101000)
#         print(data[100000:20])
#         print(data[129:149])
#
#     assert len(testdata) == len(data)
#     assert testdata[100000:100020] == data[100000:100020]
#     assert testdata[0:128] == data[0:128]
#     assert testdata[128:150] == data[128:150]
#
#     assert hashlib.md5(testdata).hexdigest() == hashlib.md5(data).hexdigest()
    #assert True == False

def test_middle_read(mount, tmpdir):
    testfile = os.path.join(mount, "24832_12416_BI16.dds")
    # rc = subprocess.call(
    #     f"identify -verbose {testfile}",
    #     shell=True
    # )
    # assert rc == 0

    #with open(testfile, "rb") as h:
    #    header = h.read(128)
    #    data = h.read(1000)

    with open(testfile, "rb") as h:
        header = h.read(128)
        h.seek(100000)
        log.debug(f"TEST TELL(): {h.tell()}")
        data1 = h.read(1000)
        print(data1[0:20])
        log.debug("TEST MIDDLE: SEEK(128)")
        h.seek(128)
        log.debug(f"TEST TELL(): {h.tell()}")
        data0 = h.read(99872)
        print(data0[0:20])

    testdata = header + data0 + data1

    with open(testfile, "rb") as h:
        data = h.read(101000)
        print(data[100000:20])
        print(data[129:149])

    assert len(testdata) == len(data)
    assert testdata[100000:100020] == data[100000:100020]
    assert testdata[0:128] == data[0:128]
    assert testdata[128:150] == data[128:150]

    assert hashlib.md5(testdata).hexdigest() == hashlib.md5(data).hexdigest()
    #assert True == False

def test_multi_read(mount, tmpdir):
    testfile = f"{mount}/24832_12416_BI16.dds"
    header1 = "aaa"
    header2 = "zzz"
    with open(testfile, "rb") as h:
        header1 = h.read(128)
        print(header1)

        with open(testfile, "rb") as h2:
            header2 = h2.read(128)
            print(header2)

    assert header1 == header2
    #assert True == False


from flask_app import app
from flask import render_template,redirect,request,session,flash
from flask_app.models import recipe, user

@app.route('/create/recipe')
def create_recipe():
    if 'user_id' in session:
        return render_template('createRecipe.html')
    return redirect('/home')

@app.route('/save/recipe', methods= ['post'])
def save_recipe():
    if 'user_id' in session:
        if recipe.Recipe.validate_post(request.form):
            data ={
                'name': request.form['name'],
                'description': request.form['description'],
                'instructions': request.form['instructions'],
                'date': request.form['date'],
                'under_30': request.form['under_30'],
                'user_id':session['user_id'],
            }
            recipe.Recipe.save(data)
            return redirect('/dashboard')
    return redirect('/home')

@app.route('/delete/recipe/<int:id>')
def delete_recipe(id):
    if 'user_id' in session:
        recipe.Recipe.delete({'id': id})
        return redirect('/dashboard')
    return redirect('/home')

@app.route('/update/recipe/<int:id>')
def update_recipe(id):
    if 'user_id' in session:
        r = recipe.Recipe.get_by_id({'id': id})
        print(r)
        return render_template('updateRecipe.html' ,r=r)
    return redirect('/home')

@app.route('/save/recipe/<int:id>', methods= {'post'})
def save_update(id):
    if 'user_id' in session:
        if recipe.Recipe.validate_post(request.form):
            data ={
                'name': request.form['name'],
                'description': request.form['description'],
                'instructions': request.form['instructions'],
                'date': request.form['date'],
                'under_30': request.form['under_30'],
                'id':id,
            }
            recipe.Recipe.save_update(data)
            return redirect(f'/update/recipe/{id}')
        return redirect(f'/update/recipe/{id}')
    return redirect('/home')

@app.route('/show/recipe/<int:id>')
def show_recipe(id):
    if 'user_id' in session:
        r = recipe.Recipe.get_by_id({'id': id})
        current_user =user.User.get_by_id({'id':session['user_id']})
        return render_template('viewRecipe.html' ,r=r, current_user=current_user)
    return redirect('/home')


import blenderbim.bim.helper
from bpy.types import Panel, UIList
from blenderbim.bim.ifc import IfcStore
from blenderbim.bim.module.resource.data import ResourceData

class BIM_PT_resources(Panel):
    bl_label = "Resources"
    bl_idname = "BIM_PT_resources"
    bl_space_type = "PROPERTIES"
    bl_region_type = "WINDOW"
    bl_context = "scene"
    bl_parent_id = "BIM_PT_tab_resources"
    bl_options = {"HIDE_HEADER"}

    @classmethod
    def poll(cls, context):
        file = IfcStore.get_file()
        return file and hasattr(file, "schema") and file.schema != "IFC2X3"

    def draw(self, context):
        self.props = context.scene.BIMResourceProperties
        self.tprops = context.scene.BIMResourceTreeProperties
        if not ResourceData.is_loaded:
            ResourceData.load()

        row = self.layout.row(align=True)
        if ResourceData.data["total_resources"]:
            row.label(text=f"{ResourceData.data['total_resources']} Resources Found", icon="TEXT")
        else:
            row.label(text="No Resources found.", icon="COMMUNITY")
        if self.props.is_editing:
            row.operator("bim.disable_resource_editing_ui", text="", icon="CANCEL")
        else:
            row.operator("bim.load_resources", text="", icon="GREASEPENCIL")
            row.operator("import_resources.bim", text="", icon="IMPORT")
        if not self.props.is_editing:
            return

        self.draw_resource_operators()

        self.layout.template_list(
            "BIM_UL_resources",
            "",
            self.tprops,
            "resources",
            self.props,
            "active_resource_index",
        )

        if self.props.active_resource_id:
            if self.props.editing_resource_type == "ATTRIBUTES":
                self.draw_editable_resource_attributes_ui()
            elif self.props.active_resource_id and self.props.editing_resource_type == "QUANTITY":
                self.draw_editable_resource_quantity_ui()
            elif self.props.active_resource_id and self.props.editing_resource_type == "COSTS":
                self.draw_editable_resource_costs_ui()
            elif self.props.active_resource_id and self.props.editing_resource_type == "USAGE":
                self.draw_editable_resource_time_attributes_ui()
        self.draw_productivity_ui(context)

    def draw_productivity_ui(self, context):
        row = self.layout.row(align=True)
        row.alignment = "RIGHT"
        row.prop(self.props, "should_show_resource_tools", text="Resource Tools", icon="RECOVER_LAST")
        if self.props.should_show_resource_tools:
            total_resources = len(self.tprops.resources)
            if not total_resources or self.props.active_resource_index >= total_resources:
                return

            ifc_definition_id = self.tprops.resources[self.props.active_resource_index].ifc_definition_id
            resource = ResourceData.data["resources"][ifc_definition_id]

            if not resource["type"] in ["IfcConstructionEquipmentResource", "IfcLaborResource"]:
                row = self.layout.row(align=True)
                row.label(text="Resource type cannot have productivity data", icon="ERROR")
            else:
                is_usage_locked = False
                is_work_locked = False
                for constraint in resource["Benchmarks"] or []:
                    for metric in constraint["metrics"] or []:
                        if (
                            metric["ConstraintGrade"] == "HARD"
                            and metric["reference"]
                            and metric["reference"] == "Usage.ScheduleUsage"
                        ):
                            is_usage_locked = True
                        elif (
                            metric["ConstraintGrade"] == "HARD"
                            and metric["reference"]
                            and metric["reference"] == "Usage.ScheduleWork"
                        ):
                            is_work_locked = True
                grid = self.layout.grid_flow(columns=3, even_columns=False, even_rows=False, align=False)

                col1 = grid.column(align=True)
                col2 = grid.column(align=False)
                col3 = grid.column(align=True)
                col1.ui_units_x = 1
                col2.ui_units_x = 1
                col3.ui_units_x = 2

                row1_col1 = col1.row()
                row1_col1.label(text="Schedule Work")
                row1col2 = col2.row()
                schedule_work = resource.get("ScheduleWork", None)
                derived_schedule_work = resource.get("DerivedScheduleWork", None)
                row1col2.label(
                    text="{}".format(schedule_work) if schedule_work else "{} h*".format(derived_schedule_work),
                    icon="TIME",
                )

                row1col3 = col3.row()
                row1col3.operator("bim.calculate_resource_work", text="", icon="TEMP").resource = ifc_definition_id
                op = row1col3.operator(
                    "bim.add_usage_constraint" if not is_work_locked else "bim.remove_usage_constraint",
                    text="",
                    icon="LOCKED" if is_work_locked else "UNLOCKED",
                )
                op.resource = ifc_definition_id
                op.attribute = "Usage.ScheduleWork"
                row2_col1 = col1.row()
                row2_col1.label(text="Schedule Usage")
                row2col2 = col2.row()
                row2col2.prop(self.tprops.resources[self.props.active_resource_index], "schedule_usage", text="")
                row2col3 = col3.row()
                row2col3.operator("bim.calculate_resource_usage", text="", icon="TEMP")
                op = row2col3.operator(
                    "bim.add_usage_constraint" if not is_usage_locked else "bim.remove_usage_constraint",
                    text="",
                    icon="LOCKED" if is_usage_locked else "UNLOCKED",
                )
                op.resource = ifc_definition_id
                op.attribute = "Usage.ScheduleUsage"

                productivity = resource["Productivity"]
                parent_productivity = resource["InheritedProductivity"]
                row = self.layout.row()
                if productivity:
                    produtivitiy_rate_message = "Current Productivity Rate: {} {} / {}".format(
                        productivity["QuantityProduced"],
                        productivity["QuantityProducedName"],
                        productivity["TimeConsumed"],
                    )
                    row.alignment = "LEFT"
                    row.label(text=produtivitiy_rate_message, icon="ARMATURE_DATA")
                    row.operator("bim.edit_productivity_data", text="", icon="GREASEPENCIL")
                    op = row.operator("bim.remove_pset", text="", icon="X")
                    op.pset_id = productivity["id"]
                    op.obj_type = "Resource"
                    op.obj = ""

                elif parent_productivity:
                    produtivitiy_rate_message = "Inherited Productivity Rate: {} {} / {}*".format(
                        parent_productivity["QuantityProduced"],
                        parent_productivity["QuantityProducedName"],
                        parent_productivity["TimeConsumed"],
                    )
                    row.alignment = "LEFT"
                    row.label(text="{}".format(produtivitiy_rate_message), icon="ARMATURE_DATA")
                    row.operator("bim.add_productivity_data", text="", icon="ADD")
                else:
                    row = self.layout.row(align=True)
                    row.alignment = "LEFT"
                    produtivitiy_rate_message = "No productivity data found"
                    row.label(text="{}".format(produtivitiy_rate_message), icon="ARMATURE_DATA")
                    row.operator("bim.add_productivity_data", text="", icon="ADD")

    def draw_resource_operators(self):
        row = self.layout.row(align=True)
        op = row.operator("bim.add_resource", text="Add SubContract", icon="TEXT")
        op.ifc_class = "IfcSubContractResource"
        op.parent_resource = 0
        op = row.operator("bim.add_resource", text="Add Crew", icon="COMMUNITY")
        op.ifc_class = "IfcCrewResource"
        op.parent_resource = 0

        total_resources = len(self.tprops.resources)
        if not total_resources or self.props.active_resource_index >= total_resources:
            return

        ifc_definition_id = self.tprops.resources[self.props.active_resource_index].ifc_definition_id
        resource = ResourceData.data["resources"][ifc_definition_id]

        if resource["type"] != "IfcSubContractResource":
            icon_map = {
                "IfcSubContractResource": "TEXT",
                "IfcConstructionEquipmentResource": "TOOL_SETTINGS",
                "IfcLaborResource": "OUTLINER_OB_ARMATURE",
                "IfcConstructionMaterialResource": "MATERIAL",
                "IfcConstructionProductResource": "PACKAGE",
            }
            row = self.layout.row(align=True)
            for ifc_class, icon in icon_map.items():
                label = ifc_class.replace("Ifc", "").replace("Construction", "").replace("Resource", "")
                op = row.operator("bim.add_resource", text=label, icon=icon)
                op.parent_resource = ifc_definition_id
                op.ifc_class = ifc_class

        row = self.layout.row(align=True)
        row.alignment = "RIGHT"

        if not self.props.active_resource_id:
            if resource["type"] in ["IfcLaborResource", "IfcConstructionEquipmentResource"]:
                row.operator("bim.enable_editing_resource_time", text="", icon="TIME").resource = ifc_definition_id
            op = row.operator("bim.enable_editing_resource_base_quantity", text="", icon="PROPERTIES")
            op.resource = ifc_definition_id
            op = row.operator("bim.enable_editing_resource_costs", text="", icon="DISC")
            op.resource = ifc_definition_id
            row.operator("bim.enable_editing_resource", text="", icon="GREASEPENCIL").resource = ifc_definition_id
            row.operator("bim.remove_resource", text="", icon="X").resource = ifc_definition_id
        else:
            if self.props.editing_resource_type == "ATTRIBUTES":
                row.operator("bim.edit_resource", text="", icon="CHECKMARK")
            elif self.props.editing_resource_type == "USAGE":
                row.operator("bim.edit_resource_time", text="", icon="CHECKMARK")
            row.operator("bim.disable_editing_resource", text="", icon="CANCEL")

    def draw_editable_resource_attributes_ui(self):
        blenderbim.bim.helper.draw_attributes(self.props.resource_attributes, self.layout)

    def draw_editable_resource_time_attributes_ui(self):
        blenderbim.bim.helper.draw_attributes(self.props.resource_time_attributes, self.layout)

    def draw_editable_resource_quantity_ui(self):
        resource = ResourceData.data["resources"][self.props.active_resource_id]

        if resource["BaseQuantity"]:
            quantity = resource["BaseQuantity"]
            value = quantity[[k for k in quantity.keys() if "Value" in k][0]]
            row = self.layout.row(align=True)
            row.label(text=quantity["Name"])
            row.label(text="{0:.2f}".format(value))
            if self.props.is_editing_quantity:
                op = row.operator("bim.edit_resource_quantity", text="", icon="CHECKMARK")
                op.physical_quantity = quantity["id"]
                row.operator("bim.disable_editing_resource_quantity", text="", icon="CANCEL")
            else:
                op = row.operator("bim.enable_editing_resource_quantity", text="", icon="GREASEPENCIL")
                op.resource = self.props.active_resource_id
                op = row.operator("bim.remove_resource_quantity", text="", icon="X")
                op.resource = self.props.active_resource_id

            if self.props.is_editing_quantity:
                box = self.layout.box()
                blenderbim.bim.helper.draw_attributes(self.props.quantity_attributes, box)
        else:
            row = self.layout.row(align=True)
            row.prop(self.props, "quantity_types", text="")
            op = row.operator("bim.add_resource_quantity", text="", icon="ADD")
            op.resource = self.props.active_resource_id
            op.ifc_class = self.props.quantity_types

    def draw_editable_resource_costs_ui(self):
        row = self.layout.row(align=True)
        row.prop(self.props, "cost_types", text="")
        if self.props.cost_types == "CATEGORY":
            row.prop(self.props, "cost_category", text="")
        op = row.operator("bim.add_cost_value", text="", icon="ADD")
        op.parent = self.props.active_resource_id
        op.cost_type = self.props.cost_types
        if self.props.cost_types == "CATEGORY":
            op.cost_category = self.props.cost_category

        for cost_value in ResourceData.data["cost_values"]:
            row = self.layout.row(align=True)
            self.draw_readonly_cost_value_ui(row, cost_value)

        if self.props.cost_value_editing_type == "ATTRIBUTES":
            blenderbim.bim.helper.draw_attributes(self.props.cost_value_attributes, self.layout.box())

    def draw_readonly_cost_value_ui(self, layout, cost_value):
        if self.props.active_cost_value_id == cost_value["id"] and self.props.cost_value_editing_type == "FORMULA":
            layout.prop(self.props, "cost_value_formula", text="")
        else:
            layout.label(text=cost_value["label"], icon="DISC")

        self.draw_cost_value_operator_ui(layout, cost_value["id"], self.props.active_resource_id)

    def draw_cost_value_operator_ui(self, layout, cost_value_id, parent_id):
        if self.props.active_cost_value_id and self.props.active_cost_value_id == cost_value_id:
            if self.props.cost_value_editing_type == "ATTRIBUTES":
                op = layout.operator("bim.edit_resource_cost_value", text="", icon="CHECKMARK")
                op.cost_value = cost_value_id
            elif self.props.cost_value_editing_type == "FORMULA":
                op = layout.operator("bim.edit_resource_cost_value_formula", text="", icon="CHECKMARK")
                op.cost_value = cost_value_id
            layout.operator("bim.disable_editing_resource_cost_value", text="", icon="CANCEL")
        elif self.props.active_cost_value_id:
            op = layout.operator("bim.remove_cost_value", text="", icon="X")
            op.parent = parent_id
            op.cost_value = cost_value_id
        else:
            op = layout.operator("bim.enable_editing_resource_cost_value_formula", text="", icon="CON_TRANSLIKE")
            op.cost_value = cost_value_id
            op = layout.operator("bim.enable_editing_resource_cost_value", text="", icon="GREASEPENCIL")
            op.cost_value = cost_value_id
            op = layout.operator("bim.remove_cost_value", text="", icon="X")
            op.parent = parent_id
            op.cost_value = cost_value_id

    def draw_duration_property(self, duration_props, layout):
        for duration_prop in duration_props:
            if duration_prop.name == "BaseQuantityConsumed":
                layout.prop(duration_prop, "years", text="Y")
                layout.prop(duration_prop, "months", text="M")
                layout.prop(duration_prop, "days", text="D")
                layout.prop(duration_prop, "hours", text="H")
                layout.prop(duration_prop, "minutes", text="Min")
                layout.prop(duration_prop, "seconds", text="S")

class BIM_UL_resources(UIList):
    def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
        icon_map = {
            "IfcSubContractResource": "TEXT",
            "IfcCrewResource": "COMMUNITY",
            "IfcConstructionEquipmentResource": "TOOL_SETTINGS",
            "IfcLaborResource": "OUTLINER_OB_ARMATURE",
            "IfcConstructionMaterialResource": "MATERIAL",
            "IfcConstructionProductResource": "PACKAGE",
        }
        if item:
            resource = ResourceData.data["resources"][item.ifc_definition_id]
            props = context.scene.BIMResourceProperties
            row = layout.row(align=True)
            for i in range(0, item.level_index):
                row.label(text="", icon="BLANK1")
            if item.has_children:
                if item.is_expanded:
                    row.operator(
                        "bim.contract_resource", text="", emboss=False, icon="DISCLOSURE_TRI_DOWN"
                    ).resource = item.ifc_definition_id
                else:
                    row.operator(
                        "bim.expand_resource", text="", emboss=False, icon="DISCLOSURE_TRI_RIGHT"
                    ).resource = item.ifc_definition_id
            else:
                row.label(text="", icon="DOT")
            row.prop(item, "name", emboss=False, text="", icon=icon_map[resource["type"]])
            row.prop(item, "schedule_usage", text="", emboss=False) if item.schedule_usage else None
            if context.active_object and not props.active_resource_id:
                row = layout.row(align=True)
                if item.ifc_definition_id in ResourceData.data["active_resource_ids"]:
                    op = row.operator("bim.unassign_resource", text="", icon="KEYFRAME_HLT", emboss=False)
                    op.resource = item.ifc_definition_id
                else:
                    op = row.operator("bim.assign_resource", text="", icon="KEYFRAME", emboss=False)
                    op.resource = item.ifc_definition_id

            if props.active_resource_id == item.ifc_definition_id:
                if props.editing_resource_type == "ATTRIBUTES":
                    row.operator("bim.edit_resource", text="", icon="CHECKMARK")
                elif props.editing_resource_type == "USAGE":
                    row.operator("bim.edit_resource_time", text="", icon="CHECKMARK")
                row.operator("bim.disable_editing_resource", text="", icon="CANCEL")

def draw_productivity_ui(self, context):
    def draw_duration_property(duration_props, layout):
        for duration_prop in duration_props:
            if duration_prop.name == "BaseQuantityConsumed":
                layout.prop(duration_prop, "years", text="Y")
                layout.prop(duration_prop, "months", text="M")
                layout.prop(duration_prop, "days", text="D")
                layout.prop(duration_prop, "hours", text="H")
                layout.prop(duration_prop, "minutes", text="Min")
                layout.prop(duration_prop, "seconds", text="S")

    productivity_props = context.scene.BIMResourceProductivity
    grid = self.layout.grid_flow(columns=2, even_columns=False, even_rows=False, align=False)
    col1 = grid.column(align=False)
    col2 = grid.column(align=False)
    row1_col1 = col1.row()
    row1_col1.label(text="Quantity")
    row1_col2 = col2.row()
    row1_col2.prop(productivity_props, "quantity_produced", text="")
    row1_col2.prop(productivity_props, "quantity_produced_name", text="")
    row2_col1 = col1.row()
    row2_col1.label(text="Time")
    row2_col2 = col2.row()
    draw_duration_property(productivity_props.quantity_consumed, row2_col2)


import yaml, random, time, os
import numpy as np
import pandas as pd
import torch
import torch.optim as optim
from dataloader import get_dataloader_bert
from transformers import BertForSequenceClassification, BertTokenizer, AdamW, get_linear_schedule_with_warmup

if torch.cuda.is_available():
  torch.backends.cudnn.deterministic = True
  DEVICE='cuda:0'
else:
  DEVICE='cpu'

def set_seed(seed):
    random.seed(seed)
    np.random.seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.manual_seed(seed)

# Function to write predictions to output file
def write_predictions(predictions, test_data_frame, out_loc):
    test_data_frame['pred'] = predictions
    output = test_data_frame[['id','pred']]
    output.to_csv(out_loc, index=False)

    print('Output file created:\n\t- '+os.path.abspath(out_loc))

# function to get RMSE score based on ground truth and predictions
def score(truth_loc, prediction_loc):
    truth = pd.read_csv(truth_loc, usecols=['id','meanGrade'])
    pred = pd.read_csv(prediction_loc, usecols=['id','pred'])

    assert(sorted(truth.id) == sorted(pred.id)),"ID mismatch between ground truth and prediction!"

    data = pd.merge(truth,pred)
    rmse = np.sqrt(np.mean((data['meanGrade'] - data['pred'])**2))

    print("RMSE = %.6f" % rmse)

# Function for evaluation.
# Get predictions in eval() mode and return the loss
def evaluate(model, valid_dataloader):
    epoch_loss = 0
    model.eval()
    with torch.no_grad():
        for input_ids_batch, attention_mask_batch, token_type_ids_batch, labels in valid_dataloader:

            outputs = model(input_ids_batch,
                            attention_mask=attention_mask_batch,
                            token_type_ids=token_type_ids_batch)
            predictions = outputs[0].squeeze(1)
            loss = torch.sqrt(((predictions - labels)**2).mean())
            epoch_loss += loss.item()

    return epoch_loss / len(valid_dataloader)

def main(params, train_dataloader, valid_dataloader, optimizer, scheduler, model):

    for epoch in range(params['hyperparameters']['epochs']):
        start_time = time.time()
        # model training
        model.train()
        epoch_loss = 0

        for input_ids_batch, attention_mask_batch, token_type_ids_batch, labels in train_dataloader:
            # Zero the gradients
            optimizer.zero_grad()
            # Get predictions after forward pass of the model
            outputs = model(input_ids_batch,
                            attention_mask=attention_mask_batch,
                            token_type_ids=token_type_ids_batch)
            predictions = outputs[0].squeeze(1)
            # compute the loss
            loss = torch.sqrt(((predictions - labels)**2).mean())

            # Gradients are calculated for each parameter
            # Parameters are updated using the gradients and optimizer algorithm
            # Learning rate is updated
            loss.backward()
            optimizer.step()
            scheduler.step()
            epoch_loss += loss.item()

        average_epoch_loss = epoch_loss / len(train_dataloader)

        end_time = time.time()

        average_epoch_valid_loss = evaluate(model, valid_dataloader)

        print(f'Epoch: {epoch+1:02} | Epoch Time: {end_time-start_time}')
        print(f'\tTrain Loss: {average_epoch_loss:.3f} | Val. Loss: {average_epoch_valid_loss:.3f} ')

    return model

def test_predictions(model, test_dataloader):
    test_loss = 0
    test_predictions = []

    model.eval()

    with torch.no_grad():

        for input_ids_batch, attention_mask_batch, token_type_ids_batch, labels in test_dataloader:

            predictions__batch = model(input_ids_batch,
                           attention_mask=attention_mask_batch,
                           token_type_ids=token_type_ids_batch)[0].squeeze(1)
            test_predictions += predictions__batch.tolist()
            loss = torch.sqrt(((predictions__batch - labels)**2).mean())
            test_loss += loss.item()

        average_test_loss = test_loss / len(test_dataloader)

    print(f'| Test Loss: {average_test_loss:.6f} |')

    out_loc = 'task-1-output.csv'
    test = pd.read_csv(params['dataset']['data_dir']+'test.csv')
    write_predictions(test_predictions, test, out_loc)

    truth_loc = params['dataset']['data_dir']+'test.csv'
    prediction_loc = 'task-1-output.csv'
    score(truth_loc, prediction_loc)

if __name__=="__main__":
    set_seed(234)
    # the arguments are given from a config file
    with open("/content/drive/MyDrive/Funniness_estimation/bert_config.yaml") as file:
        params = yaml.safe_load(file)

    # Bert tokenizer
    tokenizer = BertTokenizer.from_pretrained(params['model']['name'],do_lower_case=True)
    # dataloader for bert model
    train_dataloader, valid_dataloader, test_dataloader = get_dataloader_bert(params, DEVICE, tokenizer)
    # Construct the model
    # Load the BertForSequenceClassification model
    model = BertForSequenceClassification.from_pretrained("bert-base-uncased",
                                                        num_labels = 1,
                                                        output_attentions = False,
                                                        output_hidden_states = False)

    TOTSTEPS = len(train_dataloader) * params['hyperparameters']['epochs'] * 2
    WUSTEPS = int(TOTSTEPS * float(params['hyperparameters']['WU']))
    # Apply weight decay to all parameters other than bias and layer normalization terms
    no_decay = ['bias', 'LayerNorm.weight']
    optimizer_grouped_parameters = [
        {'params': [p for n, p in model.named_parameters() if "bert" not in n], 'lr': float(params['hyperparameters']['LRATE']), 'weight_decay': float(params['hyperparameters']['WDECAY'])},
        {'params': [p for n, p in model.named_parameters() if "bert" in n], 'weight_decay':  float(params['hyperparameters']['WDECAY'])}
    ]
    # define optimizer and scheduler
    optimizer = AdamW(optimizer_grouped_parameters, lr=float(params['hyperparameters']['FRATE']), eps = float(params['hyperparameters']['EPS']))
    scheduler = get_linear_schedule_with_warmup(optimizer,
                                            num_warmup_steps = WUSTEPS,
                                            num_training_steps = TOTSTEPS)

    model = model.to(DEVICE)
    model = main(params, train_dataloader, valid_dataloader, optimizer, scheduler, model)
    test_predictions(model, test_dataloader)


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

# file:do_list2.py
# author:Asus
# datetime:2021/3/8 15:01
# software: PyCharm
'''
this is functiondescription
'''
# import module your need

import random

score = [random.randint(60, 100) for _ in range(10)]

Max1 = max(score);
Min1 = min(score);
Sum = sum(score)

avg = Sum / len(score)
print(f'{score}\n最高分：{Max1}\n最低分：{Min1}\n总分：{Sum}\n平均分：{avg}')


from flask import abort, jsonify

def gcd_euclides(a, b):
    try:
        conversionA = int(a)
        conversionB = int(b)
    except ValueError:
        return abort(400, "Error! los valores deben ser enteros")

    if type(conversionA) == int and type(conversionB) == int:
        if conversionB == 0:
            return conversionA
        else:
            return gcd_euclides(conversionB, conversionA % conversionB)
    else:
        return abort(400, "Error! los valores deben ser enteros")


from cr_network import CRNetwork

__author__ = 'jdr'
from cr_network import Link

class TrafficState(object):
    """base state"""
    pass

class TrafficLink(Link):

    def get_state(self):
        raise NotImplementedError("abstract")

    def travel_time(self, state=None):
        raise NotImplementedError("abstract")

    def total_travel_time(self, state=None):
        raise NotImplementedError("abstract")

class TrafficNetwork(CRNetwork):

    link_class = TrafficLink

    def total_travel_time(self):
        return sum(
            link.total_travel_time()
                for link in self.get_links()
        )

    def route_travel_time(self, route):
        if isinstance(route, list):
            route = self.route_by_names(route)
        return sum(
            link.travel_time()
                for link in route.links
        )


from __future__ import annotations

import dataclasses
import gzip
import json
from dataclasses import dataclass
from datetime import date, datetime
from typing import (
    Any,
    Type,
    TypeVar,
    Union,
    get_args,
    get_origin,
    get_type_hints,
)

T = TypeVar("T", bound="Deserializable")

@dataclass
class Deserializable:
    """实现递归的从 JSON 对象构建（仅针对 dataclass 及基础类型）"""

    @staticmethod
    def deserialize_object(ty: type, obj: Any) -> Any:
        """读取对象并转化为指定的类型"""
        if get_origin(ty) is Union:
            # 应为 Optional
            assert get_args(ty)[1] is type(None)
            if obj is None:
                return None
            ty = get_args(ty)[0]
            return Deserializable.deserialize_object(ty, obj)
        if get_origin(ty) is list:
            ty = get_args(ty)[0]
            return [Deserializable.deserialize_object(ty, item) for item in obj]
        if get_origin(ty) is tuple:
            return [
                Deserializable.deserialize_object(t, item)
                for (t, item) in zip(get_origin(ty), obj)
            ]
        if get_origin(ty) is dict:
            key_type, value_type = get_args(ty)
            return {
                Deserializable.deserialize_object(
                    key_type, key
                ): Deserializable.deserialize_object(value_type, value)
                for key, value in obj.items()
            }
        if issubclass(ty, Deserializable):
            return ty.deserialize(obj)
        if issubclass(ty, datetime):
            return datetime.fromisoformat(obj)
        return ty(obj)

    @classmethod
    def deserialize(cls: Type[T], obj: dict) -> T:
        """读取对象并转化为当前类型"""
        kwargs = {}
        type_hints = get_type_hints(cls)
        for field in dataclasses.fields(cls):
            if not field.repr:
                continue
            name = field.name
            if name not in obj:
                continue
            if obj[name] is None:
                kwargs[name] = None
                continue
            kwargs[name] = cls.deserialize_object(type_hints[name], obj[name])
        return cls(**kwargs)

    @classmethod
    def read_compressed_file(cls: Type[T], path: str) -> T:
        """从指定的文件中读取对象"""
        with gzip.open(path, "rt") as file:
            obj = json.load(file)
            return cls.deserialize(obj)

    @staticmethod
    def serialize_object(obj: Any, exclude_non_repr: bool = True) -> Any:
        """递归地转化为可以 JSON 序列化的字典对象"""
        if isinstance(obj, Deserializable):
            return obj.serialize(exclude_non_repr=exclude_non_repr)
        if isinstance(obj, (list, tuple)):
            return [
                Deserializable.serialize_object(item, exclude_non_repr=exclude_non_repr)
                for item in obj
            ]
        if isinstance(obj, dict):
            return {
                Deserializable.serialize_object(
                    key, exclude_non_repr=exclude_non_repr
                ): Deserializable.serialize_object(
                    value, exclude_non_repr=exclude_non_repr
                )
                for key, value in obj.items()
            }
        if isinstance(obj, (datetime, date)):
            return obj.isoformat()
        return obj

    def serialize(self, exclude_non_repr: bool = True) -> dict:
        """递归地转化为可以 JSON 序列化的字典对象

        如果 exclude_repr，则不序列化其中 repr 为 False 的字段
        （保存数据时应为 True，向前端发送数据时应为 False）

        date 和 datetime 会转换为 isoformat 字符串"""
        result = {}
        for field in dataclasses.fields(self):
            if exclude_non_repr and not field.repr:
                continue
            result[field.name] = self.serialize_object(
                getattr(self, field.name), exclude_non_repr=exclude_non_repr
            )
        return result

    def write_compressed_data(self, path: str) -> None:
        """将当前对象压缩保存于指定文件"""
        with gzip.open(path, "wt") as file:
            json.dump(self.serialize(), file)


from tkinter import *
import tkinter as tk
from tkinter import ttk
import doctors_page
import layout

from PIL import Image, ImageTk

from threading import Timer

class main_page_layout(layout.main_layout):
    def __init__(self):
        super().__init__()
        self.top_mainpage_frame=Frame(self.top_overlay_frame, bg='black', width = self.top_overlay_width, height = self.top_overlay_height)
        self.side_mainpage_frame=Frame(self.side_overlay_frame, bg='white', width = self.side_overlay_width, height = self.side_overlay_height)
        self.center_mainpage_frame=Frame(self.center_overlay_frame, bg='white', width = self.center_overlay_width, height = self.center_overlay_height)

        self.top_mainpage_frame.place(x=0,y=0)
        self.side_mainpage_frame.place(x=0,y=0)
        self.center_mainpage_frame.place(x=0,y=0)

        self.update()

        self.side_width=self.side_mainpage_frame.winfo_width()
        self.side_height=self.side_mainpage_frame.winfo_height()

        self.top_width=self.top_mainpage_frame.winfo_width()
        self.top_height=self.top_mainpage_frame.winfo_height()

        self.center_width=self.center_mainpage_frame.winfo_width()
        self.center_height=self.center_mainpage_frame.winfo_height()

class main_page_display(main_page_layout):
    def __init__(self):
        #it will call parent class again so it will make another window, so either call this class at bottom(can use super() then) or dont call super()
        super().__init__()

        display_image(self.side_mainpage_frame,self.side_width, self.side_height, "C:/Users/91807/Downloads/kona/project/res/admin.jpg")

        self.front_frame=Frame(self.center_mainpage_frame,bg='grey')
        self.lb_admin = Frame(self.front_frame, bg='yellow')
        self.lb_doctor = Frame(self.front_frame, bg="red")
        self.lb_receptionist = Frame(self.front_frame, bg="blue")

        self.front_frame.place(x=0,y=0,width=self.center_width,height=self.center_height,anchor='nw')
        self.front_frame.columnconfigure(0,weight=1)
        self.front_frame.columnconfigure(1,weight=1)
        self.front_frame.columnconfigure(2,weight=1)
        self.front_frame.columnconfigure(3,weight=1)
        self.front_frame.columnconfigure(4,weight=1)
        self.front_frame.columnconfigure(5,weight=1)
        self.front_frame.columnconfigure(6,weight=1)
        self.front_frame.columnconfigure(7,weight=1)
        self.front_frame.columnconfigure(8,weight=1)
        self.front_frame.columnconfigure(9,weight=1)

        self.front_frame.rowconfigure(0,weight=1)
        self.front_frame.rowconfigure(1,weight=1)
        self.front_frame.rowconfigure(2,weight=1)
        self.front_frame.rowconfigure(3,weight=1)
        self.front_frame.rowconfigure(4,weight=1)
        self.front_frame.rowconfigure(5,weight=1)
        self.front_frame.rowconfigure(6,weight=1)
        self.front_frame.rowconfigure(7,weight=1)
        self.front_frame.rowconfigure(8,weight=1)

        self.lb_admin.grid(column=1,row=3, columnspan=2, rowspan=2, sticky=NSEW)
        self.lb_doctor.grid(column=4,row=3, columnspan=2, rowspan=2, sticky=NSEW)
        self.lb_receptionist.grid(column=7,row=3, columnspan=2, rowspan=2, sticky=NSEW)

        self.update()

        self.admin_width = self.lb_admin.winfo_width()
        self.admin_height = self.lb_admin.winfo_height()

        display_image(self.lb_admin, self.admin_width, self.admin_height, "C:/Users/91807/Downloads/kona/project/res/adm.jpg")
        display_image(self.lb_doctor, self.admin_width, self.admin_height, "C:/Users/91807/Downloads/kona/project/res/doc.jpg", self.change_page)
        display_image(self.lb_receptionist, self.admin_width, self.admin_height, "C:/Users/91807/Downloads/kona/project/res/recep.jpg")

    def change_page(self):
        for widgets in self.center_mainpage_frame.winfo_children():
            widgets.destroy()
        for widgets in self.side_mainpage_frame.winfo_children():
            widgets.destroy()
        doctors_page.show_top_frame(self,self.top_mainpage_frame, self.rwidth, self.rheight)
        doctors_page.show_side_frame(self,self.side_mainpage_frame, self.rwidth, self.rheight, self.side_width,self.side_height)
        doctors_page.show_center_frame(self,self.center_mainpage_frame, self.rwidth, self.rheight)

    def run(self):
        self.mainloop()

class display_image(ttk.Button):
    def __init__(self, container, side_width, side_height, url, command=""):
        #this is important using super() otherwise show_img wont work
        super().__init__()
        self.side_width = side_width
        self.side_height = side_height
        self.url = url
        self.command=command
        self.show_img(container)

    def get_img(self):
        img_file=Image.open(self.url)
        #size_fit=(int((self.rwidth/4)-8), int(self.rheight-93))
        size_fit=(self.side_width, self.side_height)
        resized_img_file=img_file.resize(size_fit ,Image.ANTIALIAS)
        self.img=ImageTk.PhotoImage(resized_img_file)
        return self.img

    #def show_img(self):
    def show_img(self, container):
        img = self.get_img()
        # print(self.side_width)
        btn=Button(container,image=self.img, width=self.side_width, height=self.side_height, command=self.command)
        btn.place(x=0,y=0)

if __name__ == "__main__":
    #this should be the entry of this program.
    app = main_page_display()
    app.run()


from collections import defaultdict

from odoo import models

class EventRegistration(models.Model):
    _inherit = 'event.registration'

    def _get_lead_grouping(self, rules, rule_to_new_regs):
        """ Override to support sale-order based grouping and update.

        When checking for groups for rules, we search for existing leads linked
        to same group (based on sale_order_id) and rule. Each rule can therefore
        update an existing lead or create a new one, for each sale order that
        makes the group. """
        so_registrations = self.filtered(lambda reg: reg.sale_order_id)
        grouping_res = super(EventRegistration, self - so_registrations)._get_lead_grouping(rules, rule_to_new_regs)

        if so_registrations:
            # find existing leads in batch to put them in cache and avoid multiple search / queries
            related_registrations = self.env['event.registration'].search([
                ('sale_order_id', 'in', so_registrations.sale_order_id.ids)
            ])
            related_leads = self.env['crm.lead'].search([
                ('event_lead_rule_id', 'in', rules.ids),
                ('registration_ids', 'in', related_registrations.ids)
            ])

            for rule in rules:
                rule_new_regs = rule_to_new_regs[rule]

                # for each group (sale_order), find its linked registrations
                so_to_regs = defaultdict(lambda: self.env['event.registration'])
                for registration in rule_new_regs & so_registrations:
                    so_to_regs[registration.sale_order_id] |= registration

                # for each grouped registrations, prepare result with group and existing lead
                so_res = []
                for sale_order, registrations in so_to_regs.items():
                    registrations = registrations.sorted('id')  # as an OR was used, re-ensure order
                    leads = related_leads.filtered(lambda lead: lead.event_lead_rule_id == rule and lead.registration_ids.sale_order_id == sale_order)
                    so_res.append((leads, sale_order, registrations))
                if so_res:
                    grouping_res[rule] = grouping_res.get(rule, list()) + so_res

        return grouping_res


import numpy as np
import scipy.misc
from keras.models import model_from_json
from matplotlib import pyplot as plt
import os
import subprocess
import time

class CNN_Model:
   '''Creates an instance of Convolution Neutral Network classification model'''
   def __init__(self):
      self.num_to_abc = {0: 'A', 1:'B', 2:'C',3:'D',4:'E',5:'F',6:'G',7:'H',8:'I',9:'J',10:'K',11:'L',12:'M' \
                        ,13:'N',14:'O',15:'P',16:'Q',17:'R',18:'S',19:'T',20:'U',21:'V',22:'W',23:'X',24:'Y',25:'Z'}
      self.model = self.load_model('char74k_architecture.json', 'char74k_weights.h5')

   def load_model(self, model_def_fname, model_weight_fname):
      model = model_from_json(open(model_def_fname).read())
      model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
      model.load_weights(model_weight_fname)
      return model

   def scale_img(self, i):
      scaled_img = np.transpose(scipy.misc.imresize(i, (32, 32)),
                  (2, 0, 1)).astype('float32')
      scaled_img = np.array(scaled_img) / 255
      return scaled_img.reshape(1,3,32,32)

   def classify(self,img):
      # load image and rescale it
      scaled_img = self.scale_img(img)
      prediction = self.model.predict_classes(scaled_img)[0]
      return self.num_to_abc[prediction]


import os
import numpy as np
from sklearn.neighbors import NearestNeighbors
import csv

class Searcher:
    def __init__(self, index_path):
        self.index_path = index_path

    def search(self, query_features, neighbors):
        results = {}
        feature_list = []
        img_ids_all = []

        with open(self.index_path) as index_file:
            reader = csv.reader(index_file)

            for row in reader:
                feature = [float(x) for x in row[1:]]
                img_ids_all.append(row[0])
                feature_list.append(feature)

            feature_array = np.array(feature_list)

            neighbor_model = NearestNeighbors(n_neighbors = neighbors)
            neighbor_model.fit(feature_array)

            dist, results = neighbor_model.kneighbors([query_features])

        index_file.close()
        img_ids = []

        for result in results[0]:
            img_ids.append(img_ids_all[result])

        return dist[0], img_ids


def prepare_shingles_char(text, l):

    shingles = set([])
    for i in range(len(text)):
        shingles.add(text[i: i+l])

    return shingles

def prepare_shingles_word(text, l):

    text = text.split()
    shingles = set([])

    for i in range(len(text)):
        shitext = ""
        for j in text[i:i+l]:
            shitext+=j

        shingles.add(shitext)

    return shingles

def prep_text(text):

    cleantext = ""
    for c in text:
        if c.isalpha() or c == " ":
            cleantext+=c.lower()

    return cleantext

def similarity(shingle1, shingle2):

    common = shingle1.intersection(shingle2)
    shingle1.update(shingle2)

    return len(common)/len(shingle1)*100

file1 = open("AI/13chil.txt", "r")
text1 = file1.read()
file2 = open("AI/3wishes.txt", "r")
text2 = file2.read()

text1 = prep_text(text1)
text1 = prep_text(text2)

shi1 = prepare_shingles_char(text1, 5)
shi2 = prepare_shingles_char(text2, 5)

print(f"{similarity(shi1, shi2)}%")


import xgboost as xgb

def execute_shallow_model(model=None, x_train=None, y_train=None, x_test=None,model_params=None):
    if model_params['model_name'] == 'XGB':
        model.fit(x_train, y_train, eval_metric='error')
    else:
        model.fit(x_train, y_train)

    best_params = model.best_params_
    best_estimator = model.best_estimator_

    y_pred = best_estimator.predict(x_test)  # test data
    x_pred = best_estimator.predict(x_train)  # training data

    return x_pred, y_pred, best_estimator, best_params


import json

# Load the original JSON data from "pos_0.png.json"
with open('pos_0.png.json', 'r') as json_file:
    original_data = json.load(json_file)

# Initialize dictionaries to store the formatted data
annotation_objects = {}
annotation_attributes = {}

# Loop through objects in the original data
for obj in original_data['objects']:
    annotation_type = obj['classTitle'].lower()
    annotation_type = annotation_type.replace(" ", "_")
    bbox = obj['points']['exterior']

    # Create a dictionary for annotation_objects
    annotation_objects[annotation_type] = {
        "presence": 1,
        "bbox": [bbox[0][0], bbox[0][1], bbox[1][0], bbox[1][1]]
    }

    # Create a dictionary for annotation_attributes
    annotation_attributes[annotation_type] = {}

    # Extract attributes from tags
    for tag in obj['tags']:
        attribute_name = tag['name']
        attribute_value = tag['value']

        if attribute_name == "Difficulty Score":
            attribute_value = int(attribute_value)

        annotation_attributes[annotation_type][attribute_name] = attribute_value

# Add "Occlusion" attribute to "license_plate" if it's missing
if "license_plate" in annotation_attributes and "Occlusion" not in annotation_attributes["license_plate"]:
    annotation_attributes["license_plate"]["Occlusion"] = 0

# Create the final formatted data
formatted_data = [{
    "dataset_name": "pos_0.png.json",
    "image_link": "",
    "annotation_type": "image",
    "annotation_objects": annotation_objects,
    "annotation_attributes": annotation_attributes
}]

# Save the formatted data to "formatted_pos_0.png.json"
with open('new_formatted_pos_0.png.json', 'w') as formatted_file:
    json.dump(formatted_data, formatted_file, indent=4)

print("Conversion completed. Formatted data saved to formatted_pos_0.png.json.")


'''
a) Опишите класс Книга: Автор, название, год, цена.
Создайте класс Библиотека.
Класс предназначен для хранения информации о библиотеке:
название, адрес, книги.

b) Реализуйте необходимые для класса методы.
Используя перегрузку операторов реализуйте
для него следующие арифметические операции:
+ добавляет к количеству книг указанное значение;
- вычитает из количества книг указанное значение;
+= добавляет к количеству книг указанное значение;
-= вычитает из количества книг указанное значение;
Используя перегрузку операторов реализуйте
(сравнение по количеству книг):<;>;<=;>=;==;!=
__len__, __getitem__, ....
'''
from random import random
from random import randint
from random import choice

authName = ['Jho', 'Mike', 'Pushkin', 'Eminame']

class Book(object):
    __author = ''
    __name = ''
    __year = 0
    __price = ''

    def __init__(self, author, name):
        self.__author = author
        self.__name = name

    def __init__(self, a, n, y, p):
        self.__author = a
        self.__name = n
        self.__year = y
        self.__price = p

    def __init__(self) -> None:
        pass

    # def __init__(self, *args, **kwarg):
    #  pass
    @property
    def Author(self):
        return self.__author

    @property
    def Name(self):
        return self.__name

    @property
    def Year(self):
        return self.__year

    @property
    def Price(self):
        return self.__price

    @Author.setter
    def Author(self, val):
        self.__author = val

    @Name.setter
    def Name(self, val):
        self.__name = val

    @Year.setter
    def Year(self, val):
        self.__year = val

    @Price.setter
    def Price(self, val):
        self.__price = val

    @property
    def rand(self):
        self.Author = choice(authName)
        size = randint(3, 10)
        self.Name = ''.join(chr(randint(ord('A'), ord('Z'))) \
                            for a in range(size))
        self.Year = randint(1600, 2023)
        self.Price = randint(100, 1000)
        return self

    def __ne__(self, right) -> bool:
        if self.Author != right.Author or \
                self.Name != right.Name or \
                self.Year != right.Year or \
                self.Price != right.Price:
            return True

        return False

    def __eq__(self, right) -> bool:
        if self.Author == right.Author and \
                self.Name == right.Name and \
                self.Year == right.Year and \
                self.Price == right.Price:
            return True

        return False

    def __str__(self) -> str:
        # return '\t'.join(str(a) for a in \
        # (self.__name ,self.__author,\
        #  self.__year,self.__price ))
        s = ''
        s += '{:>11}'.format(self.Name)
        s += '{:^12}'.format(self.Author)
        s += '{:5}'.format(self.Year)
        s += '{:6}'.format(self.Price)
        return s

class Library(object):
    __books = []
    __addr = ''
    __name = ''

    def __init__(self) -> None:
        pass

    def __init__(self, count: int):
        for x in range(count):
            temp = Book()
            temp.rand
            self.__books.append(temp)

    @property
    def Addr(self):
        return self.__addr

    @property
    def Name(self):
        return self.__name

    @property
    def Books(self):
        return self.__books

    @Books.setter
    def Books(self, val):
        self.__books = val.copy()

    @Name.setter
    def Name(self, val):
        self.__name = val

    @Addr.setter
    def Addr(self, val):
        self.__addr = val

    def __str__(self):
        s = ''
        s += self.Addr + '\n'
        s += self.Name + '\n'
        for b in self.Books:
            s += str(b) + ' \n'

        return s;

    def copy(self):
        l = Library(0)
        l.Name = self.Name
        l.Addr = self.Addr
        l.Books = self.Books.copy()
        return l

    def __add__(self, val):
        if type(val) == type(Book()):
            l = self.copy()
            l.Books.append(val)
            return l
        elif type(val) == type(int()):
            # b = Book()
            l = self.copy()
            for x in range(val):
                # l.Books.append(b.rand)
                l.Books.append(Book().rand)
            return l
        return None

    def __sub__(self, val):
        if type(val) != type(Book()):
            return None
        # assert type(val) == type(Book()) return None
        l = self.copy()
        l.Books = [b for b in l.Books if b != val]
        return l

def task1():
    l = Library(5)
    print('\nOriginal list from library:', l)

    r = Book()  # 'Ronaldo', 'Goal')#,2023,255)
    r.Author = 'Ronaldo'
    r.Name = 'Goal'
    r.Year = 2023
    r.Price = 500

    l2 = l + r
    print(f'\nCopy list from library with added new book {r}:', l2)
    print()
    print('\nOriginal list from library:', l)
    l2 = l2 + 4
    print(f'\nCopy list from library with added 4 new book:', l2)

    # Ошибка в работе - неверно удаляет книгу из библиотеки
    l2 = l2 - r
    print('\nCopy list from library with deleted new book:')
    print(f'\nудаляем книгу {r} из библиотеки:', l2)

    m = Book()  # 'Ronaldo', 'Goal')#,2023,255)
    m.Author = 'Messi'
    m.Name = 'Leonel'
    m.Year = 1988
    m.Price = 5000

    l2 = l2 + m
    print(f'\nCopy list from library with added new book {m}:', l2)

    l2 = l2 - m
    print(f'\nCopy list from library with deleted new book {m}:')
    print(f'\nудаляем книгу {m} из библиотеки:', l2)