from datetime import datetime
import winsound

def inc_time(time):
    if time[-1:] == '9':
        tenth_min = int(time[-2:-1])
        if tenth_min == 5:
            tenth_min = 0
        else:
            tenth_min = tenth_min + 1
        time = time[:-2] + str(tenth_min) + '0'
    else:
        mins = int(time[-1:])
        mins += 1
        time = time[:-1] + str(mins)
    return time

def current_time():
    current = str(datetime.now())
    current = current[11:-10]
    current = current.strip()
    print(current)
    return current

if __name__ == "__main__":
    time = current_time()
    new_time = inc_time(time)
    while True:
        if new_time == current_time():
            frequency = 5000  # Set Frequency To 2500 Hertz
            duration = 3000  # Set Duration To 1000 ms == 1 second
            winsound.Beep(frequency, duration)
            break


''' Chapter 13.2 '''

def main():
    filename = input("Enter a filename: ")
    fileInput = open(filename)
    characterCount = 0
    wordCount = 0
    lineCount = 0

    for line in fileInput:
        for i in line:
            if(i == " "):
                wordCount += 1
            else:
                characterCount += 1
        if(not line.endswith(" ")):
            characterCount += 1
        lineCount += 1

    print(characterCount,"characters")
    print(wordCount,"words")
    print(lineCount,"lines")

    fileInput.close()

if __name__ == "__main__":
    main()


import cv2
import numpy as np

class ForegroundEstimator:
    def __init__(self, width, height, speaker_exp_factor, min_mask_frames, mask_exp_radius):
        self.width = width
        self.height = height
        self.speaker_exp_factor = speaker_exp_factor
        self.min_mask_frames = min_mask_frames
        self.mask_exp_radius = mask_exp_radius

    def recover_missing_bboxes(self, frames, bboxes):
        rec_bboxes = bboxes.copy()

        main_pos = 0
        while main_pos < bboxes.shape[0]:
            x1, y1, x2, y2 = bboxes[main_pos]
            if x1 < 0:
                # missing bbox identified ...
                # find the next good bbox ...
                second_pos = main_pos + 1
                while second_pos < bboxes.shape[0] and bboxes[second_pos][0] < 0:
                    second_pos += 1

                # check if
                #  - it didn't reach the end ...
                #  - and is not a gap at the beginning
                #  - and if the gap is contiguous
                if ((second_pos < bboxes.shape[0]) and (main_pos > 0) and
                    (second_pos - main_pos + 1 == frames[second_pos] - frames[main_pos - 1])):
                    # interpolate between last known box and next known box ...
                    prev_bbox = bboxes[main_pos - 1]
                    next_bbox = bboxes[second_pos]
                    # print((main_pos, second_pos, frames[main_pos - 1:second_pos + 1], bboxes[second_pos]))
                    for inner_frame_idx in range(main_pos, second_pos):
                        w = (inner_frame_idx - main_pos + 1.0) / (second_pos - main_pos + 1.0)

                        current_box = next_bbox * w + prev_bbox * (1.0 - w)
                        rec_bboxes[inner_frame_idx] = current_box

                    pass

                main_pos = second_pos + 1
            else:
                # just keep moving ...
                main_pos += 1

        return rec_bboxes

    def get_bboxes_heat_map(self, bboxes):
        heat_map = np.zeros((self.height, self.width), np.float64)
        count = 0
        for x1, y1, x2, y2 in bboxes:
            if x1 < 0:
                # skip this bbox
                count += 1
                continue

            box_w = x2 - x1
            box_h = y2 - y1
            exp_w = (box_w * (self.speaker_exp_factor - 1)) / 2.0
            exp_h = (box_h * (self.speaker_exp_factor - 1)) / 2.0

            # convert to valid boundaries ....
            x1 = max(0, int(x1 - exp_w))
            y1 = max(0, int(y1 - exp_h))
            x2 = min(self.width, int(x2 + 1 + exp_w))
            y2 = min(self.height, int(y2 + 1 + exp_h))

            heat_map[y1:y2, x1:x2] += 1

        print(" - Boxes ommited: {0:.2f} ({1:d} of {2:d})".format(count * 100.0 / bboxes.shape[0], count,
                                                                  bboxes.shape[0]))

        return heat_map

    def get_action_mask(self, frame_idxs, actions, body_bboxes, right_hand_bboxes, action_name):
        relevant_idx = np.nonzero(actions == action_name)[0]

        # interpolate missing boxes on contiguous segments ...
        action_frame_idxs = frame_idxs[relevant_idx]
        action_rh_bboxes = right_hand_bboxes[relevant_idx]
        action_rh_bboxes = self.recover_missing_bboxes(action_frame_idxs, action_rh_bboxes)

        body_heat_map = self.get_bboxes_heat_map(body_bboxes[relevant_idx])
        hand_heat_map = self.get_bboxes_heat_map(action_rh_bboxes)
        # visualize_heat_map(body_heat_map, "body " + action_name, (960, 540))
        # visualize_heat_map(hand_heat_map, "right hand " + action_name, (960, 540))

        return body_heat_map, hand_heat_map

    def visualize_heat_map(self, heat_map, window_name, window_size):
        vis_heat_map = ((heat_map / heat_map.max()) * 255).astype(np.uint8)
        cv2.imshow(window_name, cv2.resize(vis_heat_map, window_size))
        # cv2.imwrite(window_name + ".png", vis_heat_map)

    def expand_mask(self, bin_image, close_radius):
        struct_elem = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, ksize=(close_radius, close_radius))
        # return cv2.morphologyEx(bin_image, cv2.MORPH_CLOSE, struct_elem)
        return cv2.morphologyEx(bin_image, cv2.MORPH_DILATE, struct_elem)

    def get_mask(self, frame_idxs, actions, body_bboxes, right_hand_bboxes, debug_name=None):
        # 'write', 'erase'
        w_body_map, w_hand_map = self.get_action_mask(frame_idxs, actions, body_bboxes, right_hand_bboxes, 'write')
        e_body_map, e_hand_map = self.get_action_mask(frame_idxs, actions, body_bboxes, right_hand_bboxes, 'erase')

        if debug_name is not None:
            self.visualize_heat_map(w_hand_map, debug_name, (int(self.width / 2), int(self.height / 2)))

        # combined_hand_map = write_hand_map + erase_hand_map
        # combined_hand_map = (write_hand_map > 5)
        combined_hand_map = (w_hand_map + e_hand_map > self.min_mask_frames).astype(np.uint8) * 255
        combined_hand_map = self.expand_mask(combined_hand_map, self.mask_exp_radius)

        return combined_hand_map


import logging as log
from common.config import DEFAULT_TABLE
from indexer.index import milvus_client, create_table, insert_vectors, create_index, has_table
from indexer.tools import connect_mysql, create_table_mysql, search_by_image_id, load_data_to_mysql
import datetime
import time
from indexer.logs import write_log
import uuid
import os

def get_img_ids(conn, cursor, ids_image, img, table_name):
    img_list = []
    ids_img = []
    info = []

    for i in range(len(ids_image)):
        has_id = search_by_image_id(conn, cursor, ids_image[i], table_name)
        if has_id:
            print("The id of image has exists:", ids_image[i])
            info.append(ids_image[i])
            continue
        else:
            img_list.append(img[i])
            ids_img.append(ids_image[i])

    return img_list, ids_img, info

def get_ids_file(ids_milvus, ids_image, file_name):
    with open(file_name,'w') as f:
        for i in range(len(ids_image)):
            line = str(ids_milvus[i]) + "," + ids_image[i] + '\n'
            f.write(line)

def init_table(index_client, conn, cursor, table_name):
    status, ok = has_table(index_client, table_name)
    print("has_table:", status, ok)
    if not ok:
        print("create table.")
        create_table(index_client, table_name)
        create_index(index_client, table_name)
        create_table_mysql(conn, cursor, table_name)

def insert_img(index_client, conn, cursor, img_to_vec, insert_img_list, insert_ids_img, table_name):
    vectors_img = img_to_vec(insert_img_list)
    # print(len(insert_img_list),len(insert_ids_img))
    status, ids_milvus = insert_vectors(index_client, table_name, vectors_img)

    file_name = str(uuid.uuid1()) + ".csv"
    get_ids_file(ids_milvus, insert_ids_img, file_name)
    print("load data to mysql:", file_name)
    load_data_to_mysql(conn, cursor, table_name, file_name)
    if os.path.exists(file_name):
        os.remove(file_name)
    return status

def do_insert(index_client, conn, cursor, img_to_vec, ids_image, img, size, table_name):
    if not table_name:
        table_name = DEFAULT_TABLE
    if not size:
        size = 200
    print("table_name:", table_name, ", num of orgin ids:", len(ids_image),", num of orgin img:", len(img))

    if len(ids_image)!= len(img):
        return "The number of pictures is not consistent with the ID number, please check!", None

    init_table(index_client, conn, cursor, table_name)
    img_list, ids_img, info = get_img_ids(conn, cursor, ids_image, img, table_name)
    print("num of the insert images:", len(img_list))
    if not img_list:
        return None, "All the image id exists!"
    try:
        i = 0
        while i+size<len(ids_img):
            insert_img_list = img_list[i:i+size]
            insert_ids_img = ids_img[i:i+size]
            i = i+size
            print("doing insert, size:", size, "the num of insert vectors:", len(insert_img_list))
            status = insert_img(index_client, conn, cursor, img_to_vec, insert_img_list, insert_ids_img, table_name)
        else:
            insert_img_list = img_list[i:len(ids_image)]
            insert_ids_img = ids_img[i:len(ids_image)]
            print("doing insert, size:", size, ",the num of insert vectors:", len(insert_img_list))
            status = insert_img(index_client, conn, cursor, img_to_vec, insert_img_list, insert_ids_img, table_name)

        return status, info
    except Exception as e:
        # log.error(e)
        write_log(e, 1)
        return None, "Error with {}".format(e)


#!/usr/bin/env python3

from functools import reduce
from PIL import Image
from typing import List, Tuple
import sys
from math import floor
from itertools import chain
import numpy as np

def read_barcode_info(path: str) -> List[bool]:
  img = Image.open(path)
  img = img.resize((256, img.height)).convert('L')
  return list(map(lambda x: img.getpixel((x, 0)) < 128, range(256)))

def read_ref_img_info(path: str) -> Tuple[Image.Image, int]:
  img = Image.open(path).convert('1')
  return (img, np.sum(np.array(img) == 0))

def get_image(info: List[bool], ref: Image.Image, black_count: int) -> Image.Image:
  expected = ref.width * ref.height
  total = sum(info)
  count = floor(expected / total)
  last = expected - ((total - 1) * count)
  pixels = list(map(lambda x: x[0], filter(lambda x: x[1], enumerate(info))))
  data = chain(map(lambda x: [x] * count, pixels[:-1]), [[pixels[-1]] * last])
  data = list(reduce(lambda l0, l1: l0 + l1, data))
  img = Image.new('L', (ref.width, ref.height))
  black_index, white_index = 0, black_count
  for y in range(ref.height):
    for x in range(ref.width):
      if ref.getpixel((x, y)):
        img.putpixel((x, y), data[white_index])
        white_index += 1
      else:
        img.putpixel((x, y), data[black_index])
        black_index += 1
  return img

if __name__ == '__main__':
  if len(sys.argv) < 4:
    print(f'usage: {sys.argv[0]} BARCODE_IMG REF_IMG OUTPUT')
    exit(1)

  info = read_barcode_info(sys.argv[1])
  (ref, black_count) = read_ref_img_info(sys.argv[2])
  img = get_image(info, ref, black_count)
  img.save(sys.argv[3])


#!/usr/bin/env python
import serial
import keyboard

ser = serial.Serial('/dev/ttyUSB0', 115200)
izq=False
dch=False
nad=False
prevIzq=False
prevDch=False

while 1:
    lectura = ser.readline()
    print(lectura)
    pos = lectura[:3]
    if pos == 'izq':
        print("Izquierda")
        izq=True
        dch=False
    elif pos == 'dch':
        print("Derecha")
        dch=True
        izq=False
    elif pos == 'nad':
        print("Nada")
        dch=False
        izq=False
        nad=True
    if izq and not prevIzq:
        keyboard.press('i')
    if dch and not prevDch:
        keyboard.press('d')
    if nad:
        if prevIzq:
            keyboard.release('i')
        if prevDch:
            keyboard.release('d')
    prevIzq=izq
    prevDch=dch
ser.close()


from torch.utils.data import Dataset
import numpy as np
# import main as env
import math
import pandas as pd
from sklearn.model_selection import train_test_split
import torch

from imblearn.over_sampling import SMOTE
from imblearn.combine import SMOTETomek

class SmartHomeDataset(Dataset):
    def __init__(self, filename, random_state = 10, rawdata = None, classes = None, permu_task_order=False):
        if rawdata is None:
            self.pddata = pd.read_csv(filename).dropna()
        else:
            self.pddata = rawdata

        self.classes = classes
        if permu_task_order:
            lst = np.random.permutation(classes)
            self.classes = lst[0:10]

        # print("Task order: ", self.classes)

        self.pddata = self.pddata[self.pddata['ActivityName'].isin(self.classes)]
        self.labels = self.pddata["ActivityName"].values
        self.arr = self.pddata.drop('ActivityName', 1).values

        self.random_state = random_state

        self.config = {
            'feature': len(self.pddata.columns) - 1,
            'classes': len(self.classes)
        }

        self.target_tranform = None

    def train_test_split(self):
        traindata, testdata = train_test_split(self.pddata, test_size=0.2, random_state=self.random_state)

        traindata = SmartHomeDataset("", rawdata=traindata, classes=self.classes)
        testdata = SmartHomeDataset("", rawdata=testdata, classes=self.classes)

        return (traindata, testdata)

    def set_target_tranform(self, transform):
        self.target_tranform = transform

    def __len__(self):
        return len(self.pddata)

    def __getitem__(self, idx):
        if self.target_tranform is not None:
            return torch.FloatTensor(list(self.arr[idx])), self.target_tranform(self.labels[idx])

        raise Exception("No key `"+self.labels[idx]+"` in classmap")
        # return torch.FloatTensor(list(self.arr[idx])), self.labels[idx]

    def __str__(self):
        return "Smart Home dataset"

    def resampling(self):

        # SMOTE
        # It will synthesize a new data for the minority class, based on those that already exist.

        # Tomek links
        # It pairs an instance with another instance but of opposite classes
        # and then remove the instances of the bigger class of each pair.

        smote = SMOTE(random_state=self.random_state)

        classes = self.classes
        mapping = dict(zip(classes, range(len(classes))))

        pddata = self.pddata.replace({'ActivityName': mapping})
        labels = pddata["ActivityName"]

        pddata = pddata.drop('ActivityName', 1)
        columns = pddata.columns

        X_sm, y_sm = smote.fit_sample(pddata, labels)

        # convert the output back to pandas
        X_sm = pd.DataFrame(data=X_sm, columns=columns)
        rmapping = dict(zip(range(len(classes)), classes))
        X_sm["ActivityName"] = y_sm
        X_sm = X_sm.replace({'ActivityName': rmapping})

        return SmartHomeDataset("", rawdata=X_sm, classes=self.classes)

    def split(self, tasks=5):

        classes_per_task = int(np.floor(len(self.classes) / tasks))
        datasets = []

        labels_per_task = [
            list(np.array(range(classes_per_task)) + classes_per_task * task_id) for task_id in range(tasks)
        ]

        # split them up into sub-tasks
        datasets = []
        for labels in labels_per_task:
            datasets.append(self.filter(labels))

        return datasets, self.config, classes_per_task

    def filter(self, labels):
        classes = [self.classes[l] for l in labels]
        filtered = self.pddata[self.pddata["ActivityName"].isin(classes)]

        return SmartHomeDataset("", rawdata=filtered, classes=classes)

    def merge(self, dataset):
        dataset.pddata.columns = self.pddata.columns
        mpddata = pd.concat([self.pddata, dataset.pddata], axis=0, ignore_index=True)

        mpddata = mpddata.sample(frac=1).reset_index(drop=True)
        classes = self.classes + dataset.classes
        return SmartHomeDataset("", rawdata=mpddata, classes=classes)

    def detail(classes, train_datasets, test_datasets):
        print ("===== Smart Home dataset ======")
        d = {'Activity Name': [], '#Train': [], "#Test": [], "Total":[]}

        cid = {}
        i = 0
        for c in classes:
            d["Activity Name"].append(c)
            d["#Train"].append(0)
            d["#Test"].append(0)
            d["Total"].append(0)

            cid[c] = i
            i += 1

        for dataset in train_datasets:
            data = dataset.pddata
            for c in classes:
                tr = data[data["ActivityName"] == c]
                d["#Train"][cid[c]] += len(tr)

                d["Total"][cid[c]] += len(tr)

        for dataset in test_datasets:
            data = dataset.pddata
            for c in classes:
                tr = data[data["ActivityName"] == c]
                d["#Test"][cid[c]] += len(tr)
                d["Total"][cid[c]] += len(tr)

        df = pd.DataFrame(data=d)
        print (df)


######################
#感知机MNIST数据集测试
#不同于tensor,Variable的值会一直保留下来
######################

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#导入mnist数据集
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)

#注册为默认的session，之后的运算也默认跑在这个session里，不同session的数据和运算应该是独立的
sess = tf.InteractiveSession()
#定义输入数据，第二个参数为数据尺寸，None表示不限条数的输入，784代表每条输入是一个784维向量
x = tf.placeholder(tf.float32,[None,784])
#不同于tensor,Variable的值会一直保留下来
W = tf.Variable(tf.zeros([784,10]))
#因为最后是分成十类
b = tf.Variable(tf.zeros([10]))
#网络计算得出的值
y = tf.nn.softmax(tf.matmul(x,W)+ b )
#真实标签，[0...1..0]的形式
y_ = tf.placeholder(tf.float32,[None,10])
#定义损失函数,reduction_indices意思是将矩阵的维度进行压缩
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))
#定义学习率和损失函数
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
#全局参数初始化器
tf.global_variables_initializer().run()
#使用mini_batch对样本随机梯度下降
for i in range(1000):
    #取出数据，100项为1组
    batch_xs,batch_ys = mnist.train.next_batch(100)
    train_step.run({x:batch_xs,y_:batch_ys})

    #完成训练，开始验证,argmax()表示返回最大值下标，1代表的是行内比较，0代表列内比较
    correct_prediction = tf.equal(tf.argmax(y,1),tf.arg_max(y_,1))
    #统计全部样本预测的arruracy,先用tf.cast将之前correct_prediction输出的bool值转换为float32
    accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
    #eval()函数用于启动计算，用测试集数据做检测
    print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels}))


# Definition for a binary tree node.

from typing import Optional

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def recoverTree(self, root: Optional[TreeNode]) -> None:
        if not root:
            return root

        values = []

        def inorder(node, replace):
            if node.left:
                inorder(node.left, replace)

            if replace == True:
                node.val = values.pop()
            elif replace == False:
                values.append(node.val)

            if node.right:
                inorder(node.right, replace)

        inorder(root, False)

        values.sort(reverse=True)

        inorder(root, True)

        return root


#nome = str(input('Qual é o seu nome? '))
#print('Prazer em te conhecer {:=^20}!'.format(nome))

x = int(input('Digite um Valor: '))
y = int(input('Outro Valor: '))
soma = x + y
multiplicacao = x * y
subtracacao = x - y
divisao = x / y
exponciacao = x ** y
divireal = x // y
resto = x % y
print('A soma vale {} '
      '\n) produto é {} \n'
      'e a divisão é {}'.format(soma, multiplicacao, divisao), end=' ')
print(' Divisão inteira {} e a potência {}'.format(divireal, exponciacao))


import turtle

def seq3np1(n):
    """
        Print the 3n+1 sequence from n, terminating when it reaches 1.
        args: n (int) starting value for 3n+1 sequence
        return: None
    """
    count = 0

    while(n != 1):

        if(n % 2) == 0:        # n is even
            n = n // 2
            count += 1
        else:                 # n is odd
            n = n * 3 + 1
            count += 1

    return count

def Graph(upper):
    writer = turtle.Turtle()
    grapher = turtle.Turtle()

    window = turtle.Screen()
    window.reset()
    window.setworldcoordinates(0, 0, 10, 10)

    max_so_far = 0

    for i in range(1, upper + 1):
        result = seq3np1(i)

        if result > max_so_far:
            max_so_far = result

        window.setworldcoordinates(0, 0, i + 10, max_so_far + 10)

        writer.clear()
        writer.up()
        writer.goto(0, max_so_far)
        writer.down()
        writer.hideturtle()

        writer.write(f"Maximum so far: {i}, {max_so_far}", font = ('Arial', 12, 'normal'))
        grapher.goto(i, max_so_far)
        grapher.dot()

    window.exitonclick()

def main():
    start = int(input("What is the upper bound? "))

    if start < 0:
        quit()

    else:
        for i in range(1, start + 1):         #Part A
            print("Iteration:", i)
            print("Count:", seq3np1(i))

        Graph(start)                          #Part B

main()


'''
Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.

Example 1:

Input: root = [4,2,6,1,3]
Output: 1
Example 2:

Input: root = [1,0,48,null,null,12,49]
Output: 1

Constraints:

The number of nodes in the tree is in the range [2, 100].
0 <= Node.val <= 105
'''

class Solution:
    def minDiffInBST(self, root: TreeNode) -> int:
        stack = []

        def findLeast(node):
            while node:
                stack.append(node)
                node = node.left
            return node

        findLeast(root)
        low = stack.pop()   # get the lowest node
        if low.right: findLeast(low.right)

        diff = None
        while stack:
            top = stack.pop()
            if not diff or diff > top.val - low.val:
                diff = top.val - low.val
            if top.right:
                findLeast(top.right)
            low = top
        return diff


__author__ = 'Huang'

import numpy as np
import pandas as pd
def loadData(fileName):
    dataSet=pd.read_table(fileName,header=None).values
    dataArr=dataSet[:,:-1]
    labelArr=dataSet[:,-1]
    return dataArr,labelArr

#感知机原始形式求超平面参数,损失函数选误分类到超平面的距离
def calPar(dataArr,labelArr):
    dataMat=np.mat(dataArr);labelMat=np.mat(labelArr).transpose()
    m,n=np.shape(dataArr)
    # 学习率
    alpha=1
    w=np.mat(np.zeros((n,1)))
    b=0
    ErrorCount=1
    while(ErrorCount>0):
        ErrorCount=0
        for i in range(m):
            if labelMat[i]*(w.T*dataMat[i,:].T+b)<=0:
                w+=np.multiply(alpha*labelMat[i],dataMat[i,:].T)
                b+=alpha*labelMat[i]
                ErrorCount+=1
    return w,b

#感知机的对偶形式
def dualCalPar(dataArr,labelArr):
    dataMat=np.mat(dataArr)
    labelMat=np.mat(labelArr).transpose()
    m,n=np.shape(dataArr)
    #求训练集的Gram矩阵
    gramMat=dataMat*dataMat.T
    alpha=np.mat(np.zeros((m,1)))
    b=0
    eta=1
    errCount=1
    while errCount>0:
        errCount=0
        for i in range(m):
            if labelMat[i]*(np.multiply(alpha,labelMat).T*gramMat[:,i]+alpha.T*labelMat)<=0:
                errCount+=1
                alpha[i]+=eta
                b+=eta*labelMat[i]
    w=dataMat.T*np.multiply(alpha,labelMat)
    return w,b

def main():
    dataArr,labelArr=loadData(r'test_import.txt')
    w,b=calPar(dataArr,labelArr)
    w1,b1=dualCalPar(dataArr,dataArr)
    print(w)
    print(b)
    print(w1)
    print(b1)

if __name__=='__main__':
    #main()
    a=np.mat(np.arange(12).reshape(3,4))
    b=np.mat(np.array([1,2,3])).transpose()
    c=np.mat(np.array([1,2,3,4]))
    print(a+b)
    print(a+c)


"""
deviceinfo.py
A simple Device Information service

Device information is stored in files named <devicename>.py in the devices sub-folder
Each device file contains a dict of values
These device files are [ideally] generated from DFP information by [running generate_device_info.py | hand]
"""
# Python 3 compatibility for Python 2
from __future__ import print_function

import os
import importlib

from logging import getLogger

from pymcuprog.pymcuprog_errors import PymcuprogError
from .memorynames import MemoryNames
from .deviceinfokeys import DeviceMemoryInfoKeys, DeviceInfoKeys, DeviceInfoKeysPic

def getdeviceinfo(devicename):
    """
    Looks up device info for a given part

    :param devicename: device to look up
    :return: device information dict
    """
    logger = getLogger(__name__)
    logger.info("Looking for device %s", devicename)

    devicename = devicename.lower()

    try:
        device_module = importlib.import_module("deviceinfo.devices.{}".format(devicename))
    except ImportError:
        try:
            # When pymcuprog is used as a package in other scripts
            # the deviceinfo module is part of the pymcuprog package
            device_module = importlib.import_module("pymcuprog.deviceinfo.devices.{}".format(devicename))
        except ImportError:
            device_module = importlib.import_module("{}".format(devicename))

    device_info = getattr(device_module, "DEVICE_INFO")

    # For PIC devices there will be a default_bulk_erase_address outside any memory information
    # This address needs to be converted to byte address
    default_bulk_erase_address_byte = None
    for param in device_info:
        if param.startswith(DeviceInfoKeysPic.DEFAULT_BULK_ERASE_ADDRESS):
            # Check if it's word or byte oriented data
            mul = DeviceMemoryInfo.bytes_or_words(param)
            if mul is not None:
                default_bulk_erase_address_byte = int(device_info[param] * mul)
            else:
                default_bulk_erase_address_byte = device_info[param]

    if default_bulk_erase_address_byte is not None:
        device_info[DeviceInfoKeysPic.DEFAULT_BULK_ERASE_ADDRESS] = default_bulk_erase_address_byte

    return device_info

def get_supported_devices():
    """
    Return a list of all supported devices

    A device is supported if it has a device model file in the devices folder
    """
    root_folder = os.path.dirname(os.path.abspath(__file__))
    dir_list = os.listdir(root_folder + "//devices")
    ignore_list = ['__init__.py']
    device_list = []
    for devicefile in dir_list:
        if devicefile.endswith(".py") and devicefile not in ignore_list:
            devicename = devicefile.split('.')[0]
            device_list.append(devicename)

    return device_list

class DeviceMemoryInfo:
    """
    API to fetch information about device memory segments
    """
    def __init__(self, device_info):
        self.device = device_info
        self.memtypes = MemoryNames.get_all()

        # hexfile_address is the start address for the memory segment in hex files.
        # PIC and ARM devices usually does not need the parameter as all locations are mapped in a single address space.
        # AVR8 devices does not map all memory types in a single address space.
        # Memory types have defined offsets in hex files as defined below
        self.avr8_hex_file_offsets = {
            MemoryNames.FLASH: 0x000000,
            MemoryNames.EEPROM: 0x810000,
            MemoryNames.FUSES: 0x820000,
            MemoryNames.LOCKBITS: 0x830000,
            MemoryNames.SIGNATURES: 0x840000,
            MemoryNames.USER_ROW: 0x850000
        }

        # erase_address is the address for the erase of the memory.
        # Note that for PIC devices other memories might be erased in the same operation depending on the target,
        # see the programming spec for the target device.

        # erase_address, hexfile_address, hexfile_size and verify mask are optional in the device models.
        #   erase_address will be set to the memory address if it's missing.
        # Hex file address will be set to the memory address if it's missing, unless it's an AVR device where
        #   the hex file offset is used instead.
        # Hex file size will be set to the memory size if it's missing except for EEPROM on PIC16 devices where
        #   the hex file will contain phantom bytes so the hex file will contain twice as many EEPROM bytes as
        #   the actual EEPROM in the device
        # verify_mask is set based on architecture
        self.paramtypes = [DeviceMemoryInfoKeys.ADDRESS,
                           DeviceMemoryInfoKeys.SIZE,
                           DeviceMemoryInfoKeys.PAGE_SIZE,
                           DeviceMemoryInfoKeys.WRITE_SIZE,
                           DeviceMemoryInfoKeys.READ_SIZE,
                           DeviceMemoryInfoKeys.VERIFY_MASK,
                           DeviceMemoryInfoKeys.ERASE_ADDRESS,
                           DeviceMemoryInfoKeys.HEXFILE_ADDRESS,
                           DeviceMemoryInfoKeys.HEXFILE_SIZE,
                           DeviceMemoryInfoKeys.CHIPERASE_EFFECT,
                           DeviceMemoryInfoKeys.ISOLATED_ERASE]

        self.mem_by_name = {}

        # Find information about memory segments
        for param in self.device:
            for mtype in self.memtypes:
                # Does this line describe a memory location?
                if param.startswith(mtype):
                    self._configure_memory_param(mtype, param)

        # erase_address and hexfile_address are optional and should default to the value of the address parameter
        optional_params = [DeviceMemoryInfoKeys.VERIFY_MASK,
                           DeviceMemoryInfoKeys.HEXFILE_ADDRESS,
                           DeviceMemoryInfoKeys.ERASE_ADDRESS,
                           DeviceMemoryInfoKeys.HEXFILE_SIZE]
        for optional_param in optional_params:
            for memtype in self.mem_by_name:
                if optional_param not in self.mem_by_name[memtype]:
                    # Set the verify mask based on architecture
                    if optional_param == DeviceMemoryInfoKeys.VERIFY_MASK:
                        verify_mask = self._get_verify_mask(self.device[DeviceInfoKeys.ARCHITECTURE], memtype)
                        self.mem_by_name[memtype][optional_param] = verify_mask
                    # Set the hexfile_address
                    elif optional_param == DeviceMemoryInfoKeys.HEXFILE_ADDRESS:
                        self._add_hexfile_address(memtype, optional_param)
                    # Set the hexfile_size
                    elif optional_param == DeviceMemoryInfoKeys.HEXFILE_SIZE:
                        self._add_hexfile_size(memtype, optional_param)
                    # Set the erase_address
                    elif optional_param == DeviceMemoryInfoKeys.ERASE_ADDRESS:
                        # By default the erase_address is the same as the address of the memory
                        address = self.mem_by_name[memtype][DeviceMemoryInfoKeys.ADDRESS]
                        self.mem_by_name[memtype][optional_param] = address

    def _configure_memory_param(self, memorytype, param):
        # Check if it's word or byte oriented data
        mul = self.bytes_or_words(param)
        # Create a dict for the memory type if it does not exist
        if not self.mem_by_name.get(memorytype):
            self.mem_by_name[memorytype] = {DeviceMemoryInfoKeys.NAME: memorytype}
        # Parse and store parameter
        for ptype in self.paramtypes:
            if param.startswith("{}_{}".format(memorytype, ptype)):
                if mul is not None:
                    self.mem_by_name[memorytype][ptype] = int(self.device[param] * mul)
                else:
                    self.mem_by_name[memorytype][ptype] = self.device[param]

    def _add_hexfile_address(self, memorytype, paramname):
        # Inject hex file addresses for AVR memory areas
        if self.device[DeviceInfoKeys.ARCHITECTURE].startswith('avr8'):
            if memorytype in self.avr8_hex_file_offsets:
                self.mem_by_name[memorytype][paramname] = self.avr8_hex_file_offsets[memorytype]
            else:
                # The hexfile_address for memory types that doesn't make sense in a hex file like SRAM
                # and regular I/O space is defined to an address the other memory types will not reach
                self.mem_by_name[memorytype][paramname] = 0xFFFFFF
        # All other memory types are mapped 1 to 1 in the hex file
        else:
            self.mem_by_name[memorytype][paramname] = self.mem_by_name[memorytype][DeviceMemoryInfoKeys.ADDRESS]

    def _add_hexfile_size(self, memorytype, paramname):
        if self.device[DeviceInfoKeys.ARCHITECTURE].startswith('PIC16') and memorytype == MemoryNames.EEPROM:
            # For PIC16 devices there will be one phantom byte in the hex file for each EEPROM byte, so
            # the size of EEPROM in a hex file will be twice the size of the actual EEPROM memory
            self.mem_by_name[memorytype][paramname] = self.mem_by_name[memorytype][DeviceMemoryInfoKeys.SIZE] * 2
        else:
            self.mem_by_name[memorytype][paramname] = self.mem_by_name[memorytype][DeviceMemoryInfoKeys.SIZE]

    @staticmethod
    def _get_verify_mask(architecture, memtype):
        # byte oriented memory
        mask = [0xFF]

        # PIC16 is word addressed and has 14-bit flash, except EEPROM which is byte oriented
        if architecture == 'PIC16' and memtype not in [MemoryNames.EEPROM]:
            mask = [0xFF, 0x3F]

        # PIC18 is word addressed and has 16-bit flash, except EEPROM which is byte oriented
        elif architecture == 'PIC18' and memtype not in [MemoryNames.EEPROM]:
            mask = [0xFF, 0xFF]

        # PIC24 is word addressed and has 24-bit flash, except EEPROM which is word oriented
        elif architecture == 'PIC24':
            if memtype in [MemoryNames.EEPROM]:
                mask = [0xFF, 0xFF]
            else:
                mask = [0xFF, 0xFF, 0xFF, 0x00]

        return mask

    @staticmethod
    def bytes_or_words(address_param):
        """
        Return multiplier for address parameter

        The returned multiplier can be used to convert the address parameter to byte address
        :param address_param: Address parameter (used as key in device info dict)
        :return: Multiplier to convert the address to byte address
        """
        if address_param.endswith("_byte") or address_param.endswith("_bytes"):
            mul = 1
        elif address_param.endswith("_word") or address_param.endswith("_words"):
            mul = 2
        else:
            mul = None
        return mul

    def memory_info_by_address_range(self,
                                     start,
                                     stop,
                                     address_type=DeviceMemoryInfoKeys.ADDRESS,
                                     size_type=DeviceMemoryInfoKeys.SIZE):
        """
        Returns a list of all memories applicable for the address range(start, stop)

        :param start: Start address (byte)
        :param stop: End address (byte)
        :param address_type: Selects between normal addresses and addresses used in hex files
            (address vs hexfile_address)
        :param size_type: Selects between normal size and size used in hexfiles (size vs hexfile_size)
        """
        # We do not support negative memory ranges
        if start > stop:
            raise PymcuprogError("Cannot parse reverse memory range {} to {}".format(start, stop))

        memtypes = []

        # Loop through all known memory types for this device
        for memtype in self.mem_by_name:
            address = self.mem_by_name[memtype][address_type]
            size = self.mem_by_name[memtype][size_type]

            # Check if any of the addresses between start and stop is within the memory type range
            if start < address+size and stop > address:
                memtypes.append(self.mem_by_name[memtype])
        return memtypes

    def memory_info_by_address(self,
                               byte_address,
                               address_type=DeviceMemoryInfoKeys.ADDRESS,
                               size_type=DeviceMemoryInfoKeys.SIZE):
        """
        Returns information about the memory type for a given byte address

        :param byte_address: Memory address to check
        :param address_type: Selects between normal addresses and addresses used in hex files
            (ADDRESS vs HEXFILE_ADDRESS)
        :param size_type: Selects between normal size and size used in hexfiles (size vs hexfile_size)
       """
        memtype = None
        for memory in self.mem_by_name:
            if self.mem_by_name[memory][address_type] <= byte_address < \
                    self.mem_by_name[memory][address_type] + self.mem_by_name[memory][size_type]:
                if memtype is not None:
                    raise PymcuprogError("Duplicate memory area found for byte address '{}'".format(byte_address))
                memtype = self.mem_by_name[memory]
        return memtype

    def memory_info_by_name(self, name):
        """
        Returns information about the requested memory
        """
        memory = self.mem_by_name.get(name)
        if not memory:
            message = "Memory type '{}' not defined for device '{}'".format(name, self.device[DeviceInfoKeys.NAME])
            raise ValueError(message)
        return memory


"""
Module - measurements.single

Modulo di misurazione dei dataset con output del tempo di esecuzione dei singoli

"""

from random import randint
import gc
# import matplotlib.pyplot as plt
from data_structures.heap import Heap, Node
from data_structures.tsp import TSP
from data_structures.disjoint_set import DisjointSet
from algorithms.utils import populateTSPFromFile as populate
from algorithms.utils import loadFromFolder
from algorithms.utils import loadFromFile
from algorithms.utils import bcolors as col
from algorithms.hk import HeldKarp
from algorithms.nearestneighbor import NearestNeighbor
from algorithms.two_approximation import TwoApproximation
from os import walk, path
import time

"""
Esecuzione degli algoritmi in tutti i dataset

    graphs      =   grafi dei dataset da eseguire
    lock        =   accesso condiviso dei threads per la scrittura in append dei file (eventuale implementazione)

"""
def executeTheSuperFancyFunctionToCalculateMegaComplexTSPs(tsps, lock):
    outputfilePostfix = time.strftime('%Y-%m-%d_%H-%M-%S', time.gmtime()) + '.csv'

    #======= 2 approx =======
    print('Executing 2 approximation...')
    datasetNumber = 1
    output = './output_2approx_' + outputfilePostfix

    for tsp in tsps:
        executeSingleGraphCalculus(output, '2ap' , tsp, datasetNumber, lock)
        datasetNumber+=1

    #======= Nearest Neighbors =======
    print('Executing Nearest Neighbors...')
    datasetNumber = 1
    output = './output_nearest_neighbor' + outputfilePostfix

    for tsp in tsps:
        executeSingleGraphCalculus(output, 'nn', tsp, datasetNumber, lock)
        datasetNumber+=1

    #======= Held and Karp =======
    print('Executing Held and Karp...')
    datasetNumber = 1
    output = './output_heldkarp_' + outputfilePostfix

    for tsp in tsps:
        executeSingleGraphCalculus(output, 'hk', tsp, datasetNumber, lock)
        datasetNumber+=1

"""
Esecuzione di un singolo grafo

    outputfile      =   file di salvataggio dei risultati
    algoname        =   tipo algoritmo da eseguire
    graph           =   grafo di partenza in input
    filenumber      =   numero del dataset
    fileResultLock  =   accesso condiviso dei threads per la scrittura in append dei file (eventuale implementazione)

"""
def executeSingleGraphCalculus(outputfile, algoname, tsp, filenumber, fileResultLock):
    executionTimes = 1

    localStartTime = time.perf_counter_ns()
    gc.disable()

    if algoname == '2ap':
        final = TwoApproximation()
        res = final.algorithm(tsp)

    elif algoname == 'nn':
        res = NearestNeighbor().algorithm(tsp)

    elif algoname == 'hk':
        hk = HeldKarp()
        res = hk.hk_init(tsp)

    else:
        pass

    gc.enable()
    localEndTime = time.perf_counter_ns() - localStartTime

    # Se il tempo di esecuzione è minore di 1 secondo, lo eseguo n volte
    # tale da avvicinarmi a 1 secondo
    # e ne faccio la media

    if localEndTime <= 1000000000:
        numCalls = 1000000000//localEndTime
        loopStartTime = time.perf_counter_ns()
        gc.disable()
        for i in range(0, numCalls):

            if algoname == '2ap':
                final = TwoApproximation()
                res = final.algorithm(tsp)

            elif algoname == 'nn':
                res = NearestNeighbor().algorithm(tsp)

            elif algoname == 'hk':
                hk = HeldKarp()
                res = hk.hk_init(tsp)

        gc.enable()
        loopEndTime = time.perf_counter_ns() - loopStartTime
        rightTime = loopEndTime/numCalls
        executionTimes = numCalls
    else:
        rightTime = localEndTime

    # OUTPUT
    # ======================================================================
    # dataset name | tsp result | nano seconds time | seconds time | exe times
    # ======================================================================

    with fileResultLock:
        file_object = open(outputfile, 'a')
        file_object.write("{:<15}{:<12}{:<20}{:<20}{:<20}".format(tsp.name, str(int(res)), str(rightTime), '{:.7f}'.format(rightTime/1000000000), str(executionTimes)))
        file_object.write('\n')
        file_object.close()


fn = "input.txt"
fn = "test.txt"
from math      import prod
from itertools import product

def solve(data, n, label):
    for group in product(*(data,)*n):
        if sum(group) == 2020:
            print(f'{label}: {prod(group)}')
            return

data = list(map(int, open(fn).readlines()))
solve(data, 2, 'Part 1')
solve(data, 3, 'Part 2')


import os
import msgspec
msgspec_encoders = {".json": msgspec.json.Encoder(), ".msgpack": msgspec.msgpack.Encoder(), ".toml": msgspec.toml, ".yaml": msgspec.yaml}
msgspec_decoders = {".json": msgspec.json.Decoder(), ".msgpack": msgspec.msgpack.Decoder(), ".toml": msgspec.toml, ".yaml": msgspec.yaml}

import gradio as gr

from modules import shared, processing, devices
from modules.scripts import basedir
from modules.sd_samplers import samplers

# __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
__location__ = basedir()
payloads_path = os.path.join(__location__, "payloads")

#payload function with ext
def refresh_payloads():
    global discovered_payloads
    discovered_payloads = []
    for _, _, files in os.walk(payloads_path):
        for f in files:
            if os.path.splitext(f)[1] in [".json", ".msgpack", ".toml", ".yaml"]:
                discovered_payloads.append(f)
    discovered_payloads = [*set(discovered_payloads)]
    print("autoMBW [info]: discovered " + str(len(discovered_payloads)) + " payloads.")
    return gr.update(choices=discovered_payloads)

refresh_payloads()

def on_ui_tabs(main_block):
    def create_sampler_and_steps_selection(choices, tabname):
        with gr.Row(elem_id=f"sampler_selection_{tabname}"):
            sampler = gr.Dropdown(label='Sampling method', elem_id=f"{tabname}_sampling", choices=[x.name for x in choices], value=choices[0].name)
            steps = gr.Slider(minimum=1, maximum=150, step=1, elem_id=f"{tabname}_steps", label="Sampling steps", value=20)
        return steps, sampler
    with gr.Row():
        with gr.Column(variant="panel"):
            radio_wildcard_type = gr.Radio(label="Wildcards Type", choices=["none", "random", "combinatorial", "jinja2", "lucky"], value="random")
            positive_prompt = gr.Text(label="Positive Prompt", elem_id="autombw_positive_prompt", lines=4, placeholder="Positive prompt here")
            negative_prompt = gr.Text(label="Negative Prompt", elem_id="autombw_negative_prompt", lines=4, placeholder="Negative prompt here")
            with gr.Row():
                steps, sampler = create_sampler_and_steps_selection(samplers, "autombw")
            with gr.Row():
                with gr.Column(elem_id="autombw_column_size", scale=4):
                    width = gr.Slider(minimum=64, maximum=2048, step=64, label="Width", value=512, elem_id="autombw_width")
                    height = gr.Slider(minimum=64, maximum=2048, step=64, label="Height", value=512, elem_id="autombw_height")
                with gr.Column(elem_id="autombw_column_batch"):
                    batch_count = gr.Slider(minimum=1, step=1, label='Batch count (Wildcards)', value=1, elem_id="autombw_batch_count")
                    batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1, elem_id="autombw_batch_size")
            cfg_scale = gr.Slider(minimum=1.0, maximum=30.0, step=0.5, label='CFG Scale', value=7.0, elem_id="autombw_cfg_scale")
            seed = gr.Number(label="Seed", value=1, precision=0)
            with gr.Row(elem_id="autombw_checkboxes"):
                with gr.Column(scale=3):
                    with gr.Row():
                        restore_faces = gr.Checkbox(label='Restore faces', value=False, visible=len(shared.face_restorers) > 1, elem_id="autombw_restore_faces")
                        tiling = gr.Checkbox(label='Tiling', value=False, elem_id="autombw_tiling")
                        enable_hr = gr.Checkbox(label='Hires. fix', value=False, elem_id="autombw_enable_hr")
                        reverse_scoring = gr.Checkbox(label='reverse_scoring', value=False)
                with gr.Column(scale=1, min_width=150):
                    with gr.Row():
                        hr_final_resolution = gr.HTML(value="", elem_id="txtimg_hr_finalres", label="Upscaled resolution", interactive=False, visible=False)
            with gr.Row(elem_id="autombw_hires_fix_row1"):
                hr_upscaler = gr.Dropdown(label="Upscaler", elem_id="autombw_hr_upscaler", choices=[*shared.latent_upscale_modes, *[x.name for x in shared.sd_upscalers]], value=shared.latent_upscale_default_mode, visible=False)
                hr_second_pass_steps = gr.Slider(minimum=0, maximum=150, step=1, label='Hires steps', value=0, elem_id="autombw_hires_steps", visible=False)
                denoising_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Denoising strength', value=0.7, elem_id="autombw_denoising_strength", visible=False)
            with gr.Row(elem_id="autombw_hires_fix_row2"):
                hr_scale = gr.Slider(minimum=1.0, maximum=4.0, step=0.05, label="Upscale by", value=2.0, elem_id="autombw_hr_scale", visible=False)
                hr_resize_x = gr.Slider(minimum=0, maximum=2048, step=64, label="Resize width to", value=0, elem_id="autombw_hr_resize_x", visible=False)
                hr_resize_y = gr.Slider(minimum=0, maximum=2048, step=64, label="Resize height to", value=0, elem_id="autombw_hr_resize_y", visible=False)
        with gr.Column(variant="panel"):
            btn_create_payload = gr.Button(value="Create Payload", variant="primary")
            filename = gr.Text(label="Filename")
            radio_ext = gr.Radio(label="Format", choices=[".json", ".msgpack", ".toml", ".yaml"], value=".json")
            chk_overwrite = gr.Checkbox(label="Allow Overwrite", value=False)
            with gr.Row():
                btn_load_payload = gr.Button(value="Load Payload", variant="primary")
                btn_reload_payloads= gr.Button(value="Reload Payloads")
            dropdown_payloads = gr.Dropdown(label="Payload", choices=discovered_payloads)
            html_output_info = gr.HTML()

    def create_payload(args):
        payload = {
            "enable_hr": args[enable_hr],
            "denoising_strength": args[denoising_strength],
            "firstphase_width": 0,
            "firstphase_height": 0,
            "hr_scale": args[hr_scale],
            "hr_upscaler": args[hr_upscaler],
            "hr_second_pass_steps": args[hr_second_pass_steps],
            "hr_resize_x": args[hr_resize_x],
            "hr_resize_y": args[hr_resize_y],
            "prompt": args[positive_prompt],
            "seed": args[seed],
            "sampler_name": args[sampler],
            "batch_size": args[batch_size],
            "n_iter": args[batch_count],
            "steps": args[steps],
            "cfg_scale": args[cfg_scale],
            "width": args[width],
            "height": args[height],
            "restore_faces": args[restore_faces],
            "tiling": args[tiling],
            "negative_prompt": args[negative_prompt],
            "wildcard_type": args[radio_wildcard_type],
            "reverse_scoring": args[reverse_scoring]
        }
        payload = msgspec_encoders[args[radio_ext]].encode(payload)
        payload_path = os.path.join(__location__, "payloads", args[filename] + args[radio_ext])
        if not os.path.exists(payload_path) or args[chk_overwrite]:
            with open(payload_path, "wb") as f:
                f.write(payload)
            if args[chk_overwrite]:
                print("warning [overwrite]: file already exists")
                return f"success: file overwritten [{payload_path}].
"
        else:
            print("error: file already exists")
            return "error: file already exists.
"
        return f"success: file created [{payload_path}].
"

    payload_args = {
        "enable_hr": enable_hr,
        "denoising_strength": denoising_strength,
        "hr_scale": hr_scale,
        "hr_upscaler": hr_upscaler,
        "hr_second_pass_steps": hr_second_pass_steps,
        "hr_resize_x": hr_resize_x,
        "hr_resize_y": hr_resize_y,
        "prompt": positive_prompt,
        "seed": seed,
        "sampler_name": sampler,
        "batch_size": batch_size,
        "n_iter": batch_count,
        "steps": steps,
        "cfg_scale": cfg_scale,
        "width": width,
        "height": height,
        "restore_faces": restore_faces,
        "tiling": tiling,
        "negative_prompt": negative_prompt,
        "wildcard_type": radio_wildcard_type,
        "reverse_scoring": reverse_scoring
    }
    # payload_args = [enable_hr, denoising_strength, hr_scale, hr_upscaler, hr_second_pass_steps, hr_resize_x, hr_resize_y,
    #     positive_prompt, seed, sampler, batch_size, batch_count, steps, cfg_scale, width, height, restore_faces, tiling, negative_prompt]

    btn_create_payload.click(
        fn=create_payload,
        inputs={filename, chk_overwrite, radio_ext, *[*payload_args.values()]},
        outputs=[html_output_info]
    )

    payload_keys = [*payload_args.keys()]
    def load_payload(payload):
        payload_path = os.path.join(payloads_path, payload)
        if os.path.isfile(payload_path):
            payload = msgspec_decoders[os.path.splitext(payload_path)[1]].decode(open(payload_path, "rb").read())
        else:
            return f"error: file not found [{payload_path}].
"
        return_list = []
        for key in payload_keys:
            try:
                return_list.append(gr.update(value=payload[key]))
            except KeyError:
                return_list.append(gr.update())
        return [f"success: file loaded [{payload_path}].
"] + return_list

    btn_load_payload.click(
        fn=load_payload,
        inputs=[dropdown_payloads],
        outputs=[html_output_info] + [payload_args[key] for key in payload_keys]
    )

    btn_reload_payloads.click(
        fn=refresh_payloads,
        inputs=[],
        outputs=[dropdown_payloads]
    )

    def calc_resolution_hires(enable, width, height, hr_scale, hr_resize_x, hr_resize_y):
        if not enable:
            return ""
        p = processing.StableDiffusionProcessingTxt2Img(width=width, height=height, enable_hr=True, hr_scale=hr_scale, hr_resize_x=hr_resize_x, hr_resize_y=hr_resize_y)
        with devices.autocast():
            p.init([""], [0], [0])
        return f"resize: from {p.width}x{p.height} to {p.hr_resize_x or p.hr_upscale_to_x}x{p.hr_resize_y or p.hr_upscale_to_y}"

    hr_resolution_preview_inputs = [enable_hr, width, height, hr_scale, hr_resize_x, hr_resize_y]
    for input in hr_resolution_preview_inputs:
        input.change(
            fn=calc_resolution_hires,
            inputs=hr_resolution_preview_inputs,
            outputs=[hr_final_resolution],
            show_progress=False,
        )
        input.change(
            None,
            _js="onCalcResolutionHires",
            inputs=hr_resolution_preview_inputs,
            outputs=[],
            show_progress=False,
        )

    def gr_show(visible_flag):
        if visible_flag:
            return gr.update(visible=True)
        else:
            return gr.update(visible=False)

    hr_options = [hr_final_resolution, hr_upscaler, hr_second_pass_steps, denoising_strength, hr_scale, hr_resize_x, hr_resize_y]
    enable_hr.change(
    fn=lambda x: [gr_show(x) for _ in range(len(hr_options))],
    inputs=[enable_hr],
    outputs=hr_options
    )


import sys
sys.stdin = open("input.txt")

def get_score(lst):
    cnt_max = 0
    score = 0
    for i in range(100, -1, -1):
        cnt = lst.count(i)
        if cnt_max < cnt:
            cnt_max = cnt
            score = i

    return score

T = int(input())

for tc in range(1, T+1):
    t = int(input())
    lst = list(map(int, input().split()))

    print(f'#{tc} {get_score(lst)}')


import sys
def analyze_text(text):
    # Your code here
    """ Count the alphabetical characters; also, the letters 'e'. Return a ratio. """

def answer(nums_alpha, nums_e, quotient):
    print("The text contains " + nums_alpha + " alphabetic characters, of which " +
            nums_e + " (" + quotient + "%) are 'e'.")

def main():
    nums = ["squat", "bench", "deadlift"]
    for lift in lifts:
        keep_lifting = "yes"
        weight = 0
        input_prompt = "Keep doing the " + lift + "? Enter yes for the next set."
        while keep_lifting == "yes":
            weight = weight + 10
            if lift == "bench" and weight > 200:
                break
            else:
                workout_coach(lift, weight)
            keep_lifting = input(input_prompt)

if __name__ == "__main__":
    main()


import mock
import unittest
import uuid
import sys
import subprocess
import pdb

from stats_daemon.storage_nodemgr import EventManager
from pysandesh.sandesh_base import *

class EventManagerTest(unittest.TestCase):
    def setUp(self):
        self._api = EventManager("storage-compute")

    def mocked_pool_subprocess_call(self, arg1, stderr, shell):
        if arg1 == '/usr/bin/rados df':
            return "pool name       category                 KB      " + \
                   "objects       clones     degraded      unfound   " + \
                   "        rd        rd KB           wr        wr KB\n" + \
                   "images          -                  431045012     " + \
                   "   24144            0            0           0   " + \
                   "         0            0        61764    220548992\n" + \
                   "volumes         -                  431072528      " + \
                   "  24145            0            0           0     " + \
                   "       0            0        60484    215975742"

    def test_create_and_send_pool_stats(self):
        subprocess.check_output = self.mocked_pool_subprocess_call
        SandeshUVE.send = mock.MagicMock(return_value=1)
        self._api.create_and_send_pool_stats()
        SandeshUVE.send.assert_called_with()

    def mocked_osd_subprocess_call(self, arg1, stderr, shell):
        if arg1.find('ls /var/lib/ceph/osd') != -1:
            return "ceph-0\nceph-1"
        if arg1.find('cat /var/lib/ceph/osd') != -1:
            return "ok\n"
        if arg1.find('ceph osd dump | grep') != -1:
            return "abcdefghuuiduuid\n"
        if arg1.find('subop_r_out_bytes') != -1:
            return   "subop_r_out_bytes : 100000\n" + \
                     "op_r_out_bytes : 1200000\n" + \
                     "subop_w_in_bytes : 10000000\n" + \
                     "op_w_in_bytes : 10000000\n" + \
                     "subop_r : 1000000\n" + \
                     "op_r : 10000000\n" + \
                     "subop_w : 1000000\n" + \
                     "op_w : 10000000\n"
        if arg1.find('subop_r_latency') != -1:
            return   "op_w_latency : { avgcount: 259289,\n" + \
                     "sum: 101967.951216000}, \n" + \
                     "op_r_latency: { avgcount: 659289,\n" + \
                     "sum: 151967.15}, \n" + \
                     "subop_w_latency: { avgcount: 9289,\n" + \
                     "sum: 1767.95}, \n" + \
                     "subop_r_latency: { avgcount: 659,\n" + \
                     "sum: 1544.15},"

    def test_create_and_send_osd_stats(self):
        subprocess.check_output = self.mocked_osd_subprocess_call
        SandeshUVE.send = mock.MagicMock(return_value=1)
        self._api.create_and_send_osd_stats()
        SandeshUVE.send.assert_called_with()

    def mocked_diskstats_subprocess_call(self, arg1, stderr, shell):
        if arg1.find('iostat') != -1:
            return  "sda               4         432        94 " + \
                    "    785643   17196348\n" + \
                    "sdb              13         186      5108 " + \
                    "    331088  929245099\n" + \
                    "sdc              94      108048       383 " + \
                    "196540614   69852410\n" + \
                    "sdd              11         159      4413 " + \
                    "   283430  802800232\n"
        if arg1.find('cat /sys/block') != -1:
            return "10 20 30 40 50 60 70 80 90 100\n" + \
                   "11 21 31 41 51 61 71 81 91 101\n" + \
                   "12 22 32 42 52 62 72 82 92 102\n" + \
                   "13 23 33 43 53 63 73 83 93 103\n"

        if arg1.find('disk list') != -1:
            return "esbu-mflab-lnx-c02][INFO  ] /dev/sda :\n" + \
                   "[esbu-mflab-lnx-c02][INFO  ]  /dev/sda1 other, ext4, mounted on /\n" + \
                   "[esbu-mflab-lnx-c02][INFO  ]  /dev/sdb1 ceph data, active, cluster ceph, osd.0, journal /dev/sdb2\n" + \
                   "[esbu-mflab-lnx-c02][INFO  ]  /dev/sdd1 ceph data, active, cluster ceph, osd.1, journal /dev/sdd2\n" + \
                   "[esbu-mflab-lnx-c02][INFO  ]  /dev/sdd2 ceph journal, for /dev/sdd1\n"
        if arg1.find('df -h') != -1:
            return "Filesystem      Size  Used Avail Use% Mounted on\n" + \
                   "/dev/sda1       215G  2.7G  201G   2% /\n" + \
                   "/dev/sdb1       465G  442G   24G  96% /var/lib/ceph/osd/ceph-0\n" + \
                   "/dev/sdd1       465G  382G   84G  83% /var/lib/ceph/osd/ceph-1\n"

        if arg1.find('by-id') != -1:
            return "lrwxrwxrwx 1 root root  9 Jul 23 14:55 ata-INTEL_SSDSC2BA200G3_BTTV33450B3K200GGN -> ../../sdc\n" + \
                   "lrwxrwxrwx 1 root root 10 Jul 20 22:00 ata-INTEL_SSDSC2BA200G3_BTTV33450B3K200GGN-part1 -> ../../sdc1\n" + \
                   "lrwxrwxrwx 1 root root 10 Jul 20 22:00 ata-INTEL_SSDSC2BA200G3_BTTV33450B3K200GGN-part2 -> ../../sdc2\n" + \
                   "lrwxrwxrwx 1 root root  9 Jul 23 14:55 ata-WDC_WD2503ABYX-01WERA1_WD-WMAYP3911052 -> ../../sda\n" + \
                   "lrwxrwxrwx 1 root root 10 Jul 20 22:00 ata-WDC_WD2503ABYX-01WERA1_WD-WMAYP3911052-part1 -> ../../sda1\n" + \
                   "lrwxrwxrwx 1 root root 10 Jul 20 22:00 ata-WDC_WD2503ABYX-01WERA1_WD-WMAYP3911052-part2 -> ../../sda2\n" + \
                   "lrwxrwxrwx 1 root root 10 Jul 20 22:00 ata-WDC_WD2503ABYX-01WERA1_WD-WMAYP3911052-part5 -> ../../sda5\n" + \
                   "lrwxrwxrwx 1 root root  9 Jul 23 14:55 ata-WDC_WD5000HHTZ-04N21V0_WD-WXA1E63CYSX7 -> ../../sdb\n" + \
                   "lrwxrwxrwx 1 root root 10 Jul 20 22:00 ata-WDC_WD5000HHTZ-04N21V0_WD-WXA1E63CYSX7-part1 -> ../../sdb1\n" + \
                   "lrwxrwxrwx 1 root root 10 Jul 20 22:00 ata-WDC_WD5000HHTZ-04N21V0_WD-WXA1E63CYSX7-part2 -> ../../sdb2\n" + \
                   "lrwxrwxrwx 1 root root  9 Jul 23 14:55 ata-WDC_WD5000HHTZ-04N21V0_WD-WXH1E33XJHM1 -> ../../sdd\n" + \
                   "lrwxrwxrwx 1 root root 10 Jul 20 22:00 ata-WDC_WD5000HHTZ-04N21V0_WD-WXH1E33XJHM1-part1 -> ../../sdd1\n" + \
                   "lrwxrwxrwx 1 root root 10 Jul 20 22:00 ata-WDC_WD5000HHTZ-04N21V0_WD-WXH1E33XJHM1-part2 -> ../../sdd2\n"

    def test_create_and_send_disk_stats(self):
        subprocess.check_output = self.mocked_diskstats_subprocess_call
        SandeshUVE.send = mock.MagicMock(return_value=1)
        self._api.create_and_send_disk_stats()
        SandeshUVE.send.assert_called_with()


# Даны целочисленные координаты точки на плоскости. Если точка совпадает с началом координат, то вывести 0.
# Если точка не совпадает с началом координат, но лежит на оси OX или OY, то вывести соответственно 1 или 2.
# Если точка не лежит на координатных осях, то вывести 3.

def do_it():
    x = input("Введите X:\n")
    y = input("Введите Y:\n")
    while type(x) != int:  # обработка исключений X
        try:
            x = int(x)
        except ValueError:
            print('Введите число заново!')
            x = input('Введите число X:\n')
    while type(y) != int:  # обработка исключений Y
        try:
            y = int(y)
        except ValueError:
            print('Введите число заново!')
            y = input('Введите число Y:\n')
    if x == 0 and y == 0:                               # Начало проверок и вывод
        print(0)
    elif x != 0 and y == 0:
        print(1)
    elif y != 0 and x == 0:
        print(2)
    elif y != 0 and x != 0:
        print(3)
    else:
        print("Ошибка!")


import tkinter as tk
from tkinter import ttk
import os
from twisted.internet import tksupport, reactor
from autobahn.twisted.component import Component
from twisted.internet.defer import inlineCallbacks
import pickle
from pathlib import Path
from googleapiclient.discovery import build
import pandas as pd
from itertools import zip_longest
from functools import partial
from datetime import datetime

# TODO Server GUI rows are too long. Only extends to 'Add ' comment on vertical monitor
# TODO If booth closes, clear server's rat selection

class Server(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.computer = os.environ["COMPUTERNAME"]
        self.parent = parent
        self.parent.geometry("400x300")
        self.parent.columnconfigure(0, weight=1)
        self.parent.rowconfigure(0, weight=1)
        self.frame = ttk.Frame(self.parent, padding=[3, 3, 3, 3])
        self.frame.grid(column=0, row=0, sticky=(tk.N, tk.W, tk.S))
        self.frame.columnconfigure(0, weight=1)
        self.frame.rowconfigure(0, weight=1)
        self.parent.title(f"Server {self.computer}")

        path = Path(__file__).parent / "../../resources/credentials/token.pickle"
        with path.open("rb") as token:
            sheets_creds = pickle.load(token)
        sheets_service = build('sheets', 'v4', credentials=sheets_creds)
        self._sheets = sheets_service.spreadsheets()

        server_info = pd.read_csv(Path(__file__).parent / "../../resources/credentials/server_info.csv")
        host, port, realm = server_info.iloc[0].values
        self.router_session = None
        self.component = Component(transports=f"ws://{host}:{port}", realm=realm)
        self.component.on_join(self.__joined)
        self.component.on_leave(self.__left)
        self.component.start(reactor)

        df = pd.read_csv(Path(__file__).parent / "../../resources/credentials/sheet_ids.csv")
        self.sheets_ids = {val.Name: val.ID for idx, val in df.iterrows()}

        # Get session running orders
        sess_info = self._sheets.values().get(spreadsheetId=self.sheets_ids["ATAT Behavior"],
                                              range="Sessions!A:Z", majorDimension="COLUMNS").execute()['values']
        session_dicts = []
        for session in range(1, len(sess_info)):
            rat_list = [rat if rat else None for rat in sess_info[session][1:]]
            session_dicts.extend([{"Booth": int(booth), "Session": int(session), "Rat": rat} for booth, rat in
                                  zip_longest(sess_info[0][1:], rat_list)])
        self.sessions = pd.DataFrame(session_dicts)

        # Get parameters for active rats
        parameters_info = self._sheets.values().get(spreadsheetId=self.sheets_ids["ATAT Behavior"],
                                                    range="Parameters!A:Z").execute()['values']
        self.parameters_info = pd.DataFrame(parameters_info[1:], columns=parameters_info[0])
        self.rat_list_values = self.parameters_info["Rat"].values.tolist()

        # Super control widgets
        self.control_frame = ttk.LabelFrame(self.frame, text="Controls", padding=[1, 1, 1, 1])
        self.booth_control_frame = ttk.LabelFrame(self.frame, text="Booths", padding=[1, 1, 1, 1])
        self.control_frame.pack()
        self.booth_control_frame.pack()
        self.refresh_parameters_button = ttk.Button(self.control_frame, text="Refresh parameters",
                                                    command=self.refresh_parameters)
        self.start_all_button = ttk.Button(self.control_frame, text="Start All", command=self.start_all_booths)
        self.stop_all_button = ttk.Button(self.control_frame, text="Stop and Save All", command=self.stop_all_booths)
        self.session_label = ttk.Label(self.control_frame, text="Select Session: ")
        self.session_selection = ttk.Combobox(self.control_frame, state="readonly",
                                              values=self.sessions["Session"].unique().tolist())
        self.session_selection.bind("<<ComboboxSelected>>", self.select_session)
        self.refresh_parameters_button.pack(side="left")
        self.start_all_button.pack(side="left")
        self.stop_all_button.pack(side="left")
        self.session_label.pack(side="left")
        self.session_selection.pack(side="left")

        # Iterate booth widgets
        self.booth_frames = {}
        self.booth_labels = {}
        self.booth_refresh_buttons = {}
        self.booth_open_buttons = {}
        self.booth_close_buttons = {}
        self.booth_rat_selecions = {}
        self.booth_status_labels = {}
        self.booth_time_labels = {}
        self.booth_trial_labels = {}
        self.booth_pellet_labels = {}
        self.booth_sound_labels = {}
        self.booth_percent_labels = {}
        self.booth_daily_labels = {}
        self.booth_attempt_labels = {}
        self.booth_start_buttons = {}
        self.booth_stop_buttons = {}
        self.booth_pause_buttons = {}
        self.booth_comment_buttons = {}
        self.booth_last_activity_labels = {}
        self.booth_test_func_buttons = {}
        self.booth_weight_labels = {}  # TODO
        for idx, booth in enumerate(self.sessions["Booth"].unique()):
            booth = int(booth)
            self.booth_frames[booth] = ttk.Frame(self.booth_control_frame, padding=[1, 1, 1, 1])
            self.booth_frames[booth].pack(fill="y", expand=True)
            self.booth_labels[booth] = ttk.Label(self.booth_frames[booth], text=f"Booth {booth}")
            self.booth_refresh_buttons[booth] = ttk.Button(self.booth_frames[booth], text="Refresh",
                                                           command=partial(self.refresh_booth, booth))
            self.booth_open_buttons[booth] = ttk.Button(self.booth_frames[booth], text="Open",
                                                        command=partial(self.open_booth, booth))
            self.booth_close_buttons[booth] = ttk.Button(self.booth_frames[booth], text="Close",
                                                         command=partial(self.close_booth, booth))
            self.booth_rat_selecions[booth] = ttk.Combobox(self.booth_frames[booth], justify="right", state="readonly",
                                                           values=self.rat_list_values + [""])
            self.booth_rat_selecions[booth].bind("<<ComboboxSelected>>", partial(self.select_rat, booth))
            self.booth_status_labels[booth] = ttk.Label(self.booth_frames[booth], text="Disconnected")
            self.booth_time_labels[booth] = ttk.Label(self.booth_frames[booth], text="--:--")
            self.booth_trial_labels[booth] = ttk.Label(self.booth_frames[booth], text="Trial: -")
            self.booth_pellet_labels[booth] = ttk.Label(self.booth_frames[booth], text="Pellets: -")
            self.booth_sound_labels[booth] = ttk.Label(self.booth_frames[booth], text="Sound:")
            self.booth_percent_labels[booth] = ttk.Label(self.booth_frames[booth], text="-% correct")
            self.booth_daily_labels[booth] = ttk.Label(self.booth_frames[booth], text="Session: -")
            self.booth_attempt_labels[booth] = ttk.Label(self.booth_frames[booth], text="Attempt: -")
            self.booth_start_buttons[booth] = ttk.Button(self.booth_frames[booth], text="Start",
                                                         command=partial(self.start_booth, booth))
            self.booth_stop_buttons[booth] = ttk.Button(self.booth_frames[booth], text="Stop/Save", state="disabled",
                                                        command=partial(self.stop_booth, booth))
            self.booth_pause_buttons[booth] = tk.Button(self.booth_frames[booth], text="Pause", state="disabled",
                                                        command=partial(self.pause_booth, booth))
            self.booth_comment_buttons[booth] = ttk.Button(self.booth_frames[booth], text="Add comment",
                                                           state="disabled", command=partial(self.add_comment, booth))
            self.booth_last_activity_labels[booth] = ttk.Label(self.booth_frames[booth], text="Last update: --:--")
            self.booth_test_func_buttons[booth] = ttk.Button(self.booth_frames[booth], text="Test func",
                                                             command=partial(self.test_func, booth))
            self.booth_labels[booth].pack(side="left")
            self.booth_refresh_buttons[booth].pack(side="left")
            self.booth_open_buttons[booth].pack(side="left")
            self.booth_close_buttons[booth].pack(side="left")
            self.booth_rat_selecions[booth].pack(side="left")
            self.booth_status_labels[booth].pack(side="left")
            self.booth_time_labels[booth].pack(side="left")
            self.booth_trial_labels[booth].pack(side="left")
            self.booth_pellet_labels[booth].pack(side="left")
            self.booth_sound_labels[booth].pack(side="left")
            self.booth_percent_labels[booth].pack(side="left")
            self.booth_daily_labels[booth].pack(side="left")
            self.booth_attempt_labels[booth].pack(side="left")
            self.booth_start_buttons[booth].pack(side="left")
            self.booth_stop_buttons[booth].pack(side="left")
            self.booth_pause_buttons[booth].pack(side="left")
            self.booth_comment_buttons[booth].pack(side="left")
            self.booth_last_activity_labels[booth].pack(side="left")
            self.booth_test_func_buttons[booth].pack(side="left")

    @inlineCallbacks
    def __joined(self, session, _details):
        print("Server joined session!")
        self.router_session = session
        yield self.router_session.subscribe(self.session_status, "server.session_status")
        yield self.router_session.subscribe(self.update_pause, "server.pause_booth")
        yield self.router_session.subscribe(self.update_rat, "server.select_rat")
        yield self.router_session.subscribe(self.update_booth, "server.refresh_booth")
        yield self.router_session.subscribe(self.update_running, "server.running_status")

    @inlineCallbacks
    def __left(self, _details, _was_clean):
        print("Server left session!")

    def test_func(self, booth_num):
        self.router_session.publish("test.test_func", booth_num)

    def refresh_parameters(self):
        # Update session running orders
        sess_info = self._sheets.values().get(spreadsheetId=self.sheets_ids["ATAT Behavior"],
                                              range="Sessions!A:Z", majorDimension="COLUMNS").execute()['values']
        session_dicts = []
        for session in range(1, len(sess_info)):
            rat_list = [rat if rat else None for rat in sess_info[session][1:]]
            session_dicts.extend([{"Booth": int(booth), "Session": int(session), "Rat": rat} for booth, rat in
                                  zip_longest(sess_info[0][1:], rat_list)])
        self.sessions = pd.DataFrame(session_dicts)
        self.session_selection["values"] = self.sessions["Session"].unique().tolist()

        # Update rat parameters
        parameters_info = self._sheets.values().get(spreadsheetId=self.sheets_ids["ATAT Behavior"],
                                                    range="Parameters!A:Z").execute()['values']
        self.parameters_info = pd.DataFrame(parameters_info[1:], columns=parameters_info[0])
        self.rat_list_values = self.parameters_info["Rat"].values.tolist()
        for booth in self.booth_rat_selecions.values():
            booth["values"] = self.rat_list_values + [""]

    def select_session(self, event):
        session_num = int(event.widget.get())
        session = self.sessions[self.sessions["Session"] == session_num]
        for idx, row in session.iterrows():
            if row["Rat"]:
                self.booth_rat_selecions[row["Booth"]].set(row["Rat"])
                self.router_session.publish("client.select_rat", row["Booth"], row["Rat"])
            else:
                self.booth_rat_selecions[row["Booth"]].set("")
                self.router_session.publish("client.select_rat", row["Booth"], "")

    def open_booth(self, booth_num):
        self.router_session.publish("client.open_booth", booth_num)

    def refresh_booth(self, booth_num):
        self.router_session.publish("client.refresh_booth", booth_num)

    def close_booth(self, booth_num):
        self.router_session.publish("client.close_booth", booth_num)

    def start_booth(self, booth_num):
        self.router_session.publish("client.start_booth", booth_num)

    def start_all_booths(self):
        for booth_num, booth_obj in self.booth_rat_selecions.items():
            if booth_obj["state"] == "normal" and booth_obj.get():
                self.start_booth(booth_num)

    def stop_booth(self, booth_num):
        self.router_session.publish("client.stop_booth", booth_num)

    def stop_all_booths(self):
        for booth_num, booth_obj in self.booth_stop_buttons.items():
            if booth_obj["state"] == "normal":
                self.stop_booth(booth_num)

    def pause_booth(self, booth_num):
        if self.booth_status_labels[booth_num]["text"] == "Paused":
            self.router_session.publish("client.pause_booth", booth_num, False)
        else:
            self.router_session.publish("client.pause_booth", booth_num, True)

    def update_pause(self, booth_num, pause):
        if pause:
            self.booth_pause_buttons[booth_num].configure(relief="sunken")
            self.booth_status_labels[booth_num].configure(text="Paused")
        else:
            self.booth_pause_buttons[booth_num].configure(relief="raised")
            self.booth_status_labels[booth_num].configure(text="Other")  # TODO fix this

    def update_rat(self, booth_num, rat):
        self.booth_start_buttons[booth_num]["state"] = "normal"
        self.booth_rat_selecions[booth_num].set(rat)

    def update_running(self, booth_num, running):
        if running:
            self.booth_pause_buttons[booth_num]["state"] = "normal"
            self.booth_stop_buttons[booth_num]["state"] = "normal"
            self.booth_comment_buttons[booth_num]["state"] = "normal"
            self.booth_start_buttons[booth_num]["state"] = "disabled"
            self.booth_close_buttons[booth_num]["state"] = "disabled"
            self.booth_rat_selecions[booth_num]["state"] = "disabled"
        else:
            self.booth_pause_buttons[booth_num]["state"] = "disabled"
            self.booth_stop_buttons[booth_num]["state"] = "disabled"
            self.booth_comment_buttons[booth_num]["state"] = "disabled"
            self.booth_close_buttons[booth_num]["state"] = "normal"
            self.booth_rat_selecions[booth_num]["state"] = "readonly"

    def update_booth(self, booth_info):
        # TODO
        booth_num = booth_info["Number"]

    def add_comment(self, booth_num):
        self.router_session.publish("client.add_comment", booth_num)

    def select_rat(self, booth_num, event):
        self.booth_start_buttons[booth_num]["state"] = "normal"
        self.router_session.publish("client.select_rat", booth_num, event.widget.get())

    def session_status(self, status_dict, booth_num):
        self.booth_status_labels[booth_num].configure(text=status_dict["Status"])
        self.booth_time_labels[booth_num].configure(text=f"{status_dict['Time'][0]}:{status_dict['Time'][1]}")
        self.booth_trial_labels[booth_num].configure(text=f"Trial: {status_dict['Trial']}")
        self.booth_pellet_labels[booth_num].configure(text=f"Pellet: {status_dict['Pellet']}")
        self.booth_sound_labels[booth_num].configure(text=f"Sound: {status_dict['Sound']}")
        self.booth_percent_labels[booth_num].configure(text=f"{status_dict['Percent']:.1f}% correct")
        self.booth_attempt_labels[booth_num].configure(text=f"Attempt: {status_dict['Attempt']}")
        self.booth_daily_labels[booth_num].configure(text=f"Session: {status_dict['Session']}")
        self.update_last_active(booth_num)

    def update_last_active(self, booth_num):
        last_active = datetime.now().strftime("%H:%M")
        self.booth_last_activity_labels[booth_num].configure(text=f"Last active: {last_active}")

    def quit(self):
        reactor.stop()

def create_gui():
    root = tk.Tk()
    tksupport.install(root)
    server = Server(root)
    root.protocol("WM_DELETE_WINDOW", server.quit)
    return server

if __name__ == "__main__":
    server_gui = create_gui()
    reactor.run()


import csv

# Load files
file_load = "/Users/petr/Desktop/Data_School/python/python-challenge/PyPoll/Resources/03-Python_HW_Instructions_PyPoll_Resources_election_data.csv"
poll_analysis = "/Users/petr/Desktop/Data_School/python/python-challenge/PyPoll/Analysis/poll_analysis.txt"

# Set variables
votes = 0
winner_votes = 0
total_candidates = 0
greatest_votes = ["", 0]
candidate_options = []
candidate_votes = {}

#read file
with open(file_load,'r') as csvfile:
    csvreader = csv.reader(csvfile)

    csv_header = next(csvreader)

    candidate_map = {}

# Loop through all the rows of data collected
    for row in csvreader:

         # Set Variable + Calculate votes
        candidatespoll = row[2]
        votes += 1
        total_candidates = candidatespoll
        # candidate_map[candidatespoll] = candidate_map[candidatespoll] + 1 or 1
        # if candidate_map.get(candidatespoll) is not none:
            # candidate_map[candidatespoll] +=1
        # else:
        #     candidate_map.get(candidatespoll,1)

        if candidatespoll not in candidate_options:

            candidate_options.append(candidatespoll)

            candidate_votes[candidatespoll] = 1

        else:
            candidate_votes[candidatespoll] = candidate_votes[candidatespoll] + 1

    print()
    print()
    print()
    print("Election Results")
    print("-------------------------")
    print("Total Votes " + str(votes))
    print("-------------------------")

# Show Results in Text
with open(poll_analysis, "w") as txt_file:

    txt_file.write("Election Results")
    txt_file.write("\n")
    txt_file.write("-------------------------")
    txt_file.write("\n")
    txt_file.write("Total Votes " + str(votes))


import os
import csv
from innostock import settings
from stockkdata.models import ListOfCompanies
from django.core.management.base import  BaseCommand,CommandError

DIR_PATH=os.path.dirname(__file__)

class Command(BaseCommand):
    help='Add company data'
    def handle(self, *args, **options):
        with open(str(DIR_PATH+'/ListOfScrips.csv'),'r') as csvfile:
            reader=csv.reader(csvfile)
            # company = ListOfCompanies.objects.get(company_id='Security Code').delete()
            for row in reader:
                if(row[0]=='Security Code' or int(row[0])<=500458):
                    continue
                url="https://www.bseindia.com/corporates/ann.aspx?scrip={}%20&dur=A".format(row[0])
                company=ListOfCompanies(company_id=row[0],security_id=row[1],security_name=row[2],status=row[3],url=url)
                company.save()


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the arrayManipulation function below.

def arrayManipulation(n, queries):
    arr = [0]*(n+1)
    for q in queries:
        arr[q[0]-1] += q[2]
        arr[q[1]] -= q[2]
    answer = 0
    cumulative_sum = 0
    for value in arr:
        cumulative_sum += value
        answer = max(answer, cumulative_sum)
    return answer

nm = input().split()
n = int(nm[0])
m = int(nm[1])
queries = []
for _ in range(m):
    queries.append(list(map(int, input().rstrip().split())))
result = arrayManipulation(n, queries)

print(result)


class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums) == 0 or nums[0] > target or nums[-1] < target: return [-1, -1]
        local_min, local_max = 0, len(nums)
        idx = (local_min + local_max)//2
        prev_result, cur_result, prev_idx = 0,0,-1

        while nums[idx] != target:
            if nums[idx] > target:
                local_max = idx
                cur_result = 1
            else:
                local_min = idx
                cur_result = 0
            if abs(idx - prev_idx) == 1 and (cur_result ^ prev_result) == 1: return [-1, -1]
            prev_result, prev_idx = cur_result, idx
            idx = (local_min + local_max)//2

        l_ans = [idx, idx]
        tmp = idx
        while tmp >= 0 and nums[tmp] == target:
            l_ans[0] = tmp
            tmp -= 1
        for i in range(idx, len(nums), 1): #right
            if nums[i] == target: l_ans[1] = i
            else: break

        return l_ans


from schema import And, Optional, Or, Schema

_DATA_TYPES = Or(
    "binary",
    "text",
    "number",
    "date",
    "image",
    "audio",
    "video",
    "list",
    "single_selection",
    "multiple_selection",
    "form_sequence",
    "email",
    "link",
    "pdf",
    "embed",
    "named_entity_recognition",
    "rich_text",
    "bounding_boxes",
    "text_sequence",
)
DATA_SCHEMA = Schema(
    [
        {
            "id": Or(And(str, len), int),
            Optional("_id"): Or(And(str, len), int),
            "name": And(str, len),
            "type": _DATA_TYPES,
            Optional("layout"): dict,
            _DATA_TYPES: {
                Optional("placeholder"): Or(str, float, int, bool, list, None),
                Optional("read_only"): bool,
                Optional("use_placeholder"): bool,
                Optional("is_required"): bool,
                Optional("subtype"): And(str, len),
                Optional("value"): Or(bool, str, list, float, int, dict, None),
                Optional("entities"): Or(list, None),
                Optional("options"): list,
                Optional("data"): list,
                Optional("history"): list,
                Optional("format"): str,
                Optional("delete_disabled"): bool,
                Optional("edit_disabled"): bool,
                Optional("ordering_disabled"): bool,
                Optional("allow_edits"): bool,
            },
            Optional("logic_jump"): dict,
        }
    ],
    ignore_extra_keys=True,
)


Import('BuildEnv')
import os
import sys

env = BuildEnv.Clone()

env.Append(CPPPATH = [env['TOP'],
                      env['TOP'] + '/base',
                      env['TOP'] + '/io',
                      env['TOP'] + '/bfd',
                     ])
env.Append(LIBPATH = ['#/' + Dir('..').path,
                      '../../base',
                      '../../io',
                      '.'
                     ])

env.Prepend(LIBS = ['bfd', 'gunit', 'io', 'sandesh', 'io', 'sandeshvns', 'process_info', 'base', 'http',
                    'http_parser', 'curl', 'pugixml', 'boost_program_options', 'boost_thread'])

if sys.platform != 'darwin':
    env.Append(LIBS=['rt'])

except_env = env.Clone()
except_env.CppEnableExceptions()

config_test_env = env.Clone()
# config_test_env.Append(LIBPATH = ['../../ifmap/test'])
# config_test_env.Prepend(LIBS = ['ifmap_test_util'])

bfd_parser_test = env.UnitTest('bfd_parser_test',
                            ['bfd_parser_test.cc'])
env.Alias('src/bfd:bfd_parser_test', bfd_parser_test)

bfd_udp_connection_test = env.UnitTest('bfd_udp_connection_test',
                            ['bfd_udp_connection_test.cc'])
env.Alias('src/bfd:bfd_udp_connection_test', bfd_udp_connection_test)

bfd_state_machine_test = env.UnitTest('bfd_state_machine_test',
                            ['bfd_state_machine_test.cc'])
env.Alias('src/bfd:bfd_state_machine_test', bfd_state_machine_test)

bfd_server_test = env.UnitTest('bfd_server_test',
                            ['bfd_server_test.cc'])
env.Alias('src/bfd:bfd_server_test', bfd_server_test)

bfd_session_test = env.UnitTest('bfd_session_test',
                            ['bfd_session_test.cc'])
env.Alias('src/bfd:bfd_session_test', bfd_session_test)

bfd_external_test = env.UnitTest('bfd_external_test',
                            ['bfd_external_test.cc'])
env.Alias('src/bfd:bfd_external_test', bfd_external_test)

# All Tests
test_suite = [
    bfd_parser_test,
    bfd_udp_connection_test,
    bfd_state_machine_test,
    bfd_session_test,
]

flaky_test_suite = [
    bfd_server_test,
#   bfd_external_test,
]

test = env.TestSuite('bfd-test', test_suite)
env.Alias('controller/src/bfd:test', test)

flaky_test = env.TestSuite('bfd-flaky-test', flaky_test_suite)
env.Alias('controller/src/bfd:flaky-test', flaky_test)

Return('test_suite')


import sys
sys.setrecursionlimit(10**9)
N = int(input())

arr = [[] * (N+1) for _ in range(N+1)]

for i in range(N-1):
    a, b = map(int, input().split())
    arr[a].append(b)
    arr[b].append(a)

# print(arr)

visited = [0] * (N+1)
ans = [0] * (N+1)

def dfs(x):
    visited[x] = 1
    # print(x)
    if 0 not in visited:
        return
    else:
        for i in arr[x]:
            # print('a', i)
            if visited[i] == 0:
                ans[i] = x
                dfs(i)
    return

dfs(1)
# print()
for i in range(2, N+1):
    print(ans[i])

기웅스터디/트리/11725. 트리의 부모 찾기.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: Wenxuan Wu, Zhongang Qi, Li Fuxin.
@Contact: wuwen@oregonstate.edu
@File: eval_cls_conv.py

Modified by
@Author: Jiawei Chen, Linlin Li
@Contact: jc762@duke.edu
@File: k_eval_cls_conv.py
"""

import argparse
import os
import sys
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix
import torch
import torch.nn.parallel
import torch.utils.data
import torch.nn.functional as F
from data_utils.ModelNetDataLoader import ModelNetDataLoader, load_data
import datetime
import logging
from pathlib import Path
from tqdm import tqdm
from utils.utils import test, save_checkpoint
from model.pointconv import PointConvDensityClsSsg as PointConvClsSsg

def parse_args():
    '''PARAMETERS'''
    parser = argparse.ArgumentParser('PointConv')
    parser.add_argument('--batchsize', type=int, default=16, help='batch size')
    parser.add_argument('--gpu', type=str, default='0', help='specify gpu device')
    parser.add_argument('--kb1checkpoint', type=str, default=None, help='k but 1 checkpoint')
    parser.add_argument('--binarycheckpoint', type=str, default=None, help='binary checkpoint')
    parser.add_argument('--num_view', type=int, default=3, help='num of view')
    parser.add_argument('--model_name', default='my_pointconv', help='model name')
    return parser.parse_args()

def main(args):
    '''HYPER PARAMETER'''
    os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu
    datapath = './data/ModelNet/'

    '''CREATE DIR'''
    experiment_dir = Path('./eval_experiment/')
    experiment_dir.mkdir(exist_ok=True)
    file_dir = Path(str(experiment_dir) + '/%sModelNet40-'%args.model_name + str(datetime.datetime.now().strftime('%Y-%m-%d_%H-%M')))
    file_dir.mkdir(exist_ok=True)
    checkpoints_dir = file_dir.joinpath('checkpoints/')
    checkpoints_dir.mkdir(exist_ok=True)
    os.system('cp %s %s' % (args.kb1checkpoint, checkpoints_dir))
    log_dir = file_dir.joinpath('logs/')
    log_dir.mkdir(exist_ok=True)

    '''LOG'''
    args = parse_args()
    logger = logging.getLogger(args.model_name)
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler = logging.FileHandler(str(log_dir) + 'eval_%s_cls.txt'%args.model_name)
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    logger.info('---------------------------------------------------EVAL---------------------------------------------------')
    logger.info('PARAMETER ...')
    logger.info(args)

    '''DATA LOADING'''
    logger.info('Load dataset ...')
    train_data, train_label, test_data, test_label = load_data(datapath, classification=True)
    logger.info("The number of training data is: %d",train_data.shape[0])
    logger.info("The number of test data is: %d", test_data.shape[0])
    testDataset = ModelNetDataLoader(test_data, test_label)
    testDataLoader = torch.utils.data.DataLoader(testDataset, batch_size=args.batchsize, shuffle=False)

    '''MODEL LOADING'''
    num_class = 39
    kb1classifier = PointConvClsSsg(num_class).cuda()
    if args.kb1checkpoint is not None:
        print('Load k but 1 CheckPoint...')
        logger.info('Load k but 1 CheckPoint')
        kb1checkpoint = torch.load(args.kb1checkpoint)
        start_epoch = kb1checkpoint['epoch']
        kb1classifier.load_state_dict(kb1checkpoint['model_state_dict'])
    else:
        print('Please load k but 1 Checkpoint to eval...')
        sys.exit(0)
        start_epoch = 0

    num_class1 = 2
    binaryclassifier = PointConvClsSsg(num_class1).cuda()
    if args.binarycheckpoint is not None:
        print('Load binary CheckPoint...')
        logger.info('Load binary CheckPoint')
        binarycheckpoint = torch.load(args.binarycheckpoint)
        start_epoch = binarycheckpoint['epoch']
        binaryclassifier.load_state_dict(binarycheckpoint['model_state_dict'])
    else:
        print('Please load binary Checkpoint to eval...')
        sys.exit(0)
        start_epoch2 = 0

    blue = lambda x: '\033[94m' + x + '\033[0m'

    '''EVAL'''
    logger.info('Start evaluating...')
    print('Start evaluating...')

    total_correct = 0
    total_seen = 0
    preds = []
    for batch_id, data in tqdm(enumerate(testDataLoader, 0), total=len(testDataLoader), smoothing=0.9):
        pointcloud, target = data
        target = target[:, 0]
        #import ipdb; ipdb.set_trace()
        pred_view = torch.zeros(pointcloud.shape[0], num_class).cuda()
        binary_view = torch.zeros(pointcloud.shape[0], num_class1).cuda()

        for _ in range(args.num_view):
            pointcloud = generate_new_view(pointcloud)
            #import ipdb; ipdb.set_trace()
            #points = torch.from_numpy(pointcloud).permute(0, 2, 1)
            points = pointcloud.permute(0, 2, 1)
            points, target = points.cuda(), target.cuda()
            kb1classifier = kb1classifier.eval()
            binaryclassifier = binaryclassifier.eval()
            with torch.no_grad():
                pred = kb1classifier(points)
                pred_binary = binaryclassifier(points)
            pred_view += pred
            binary_view += pred_binary

        kb1_logprob = pred_view.data
        binary_logprob = binary_view.data
        ## since we assigned the composite class the largest label, we will split the log-probability for the last label to two part, one for binary 0 and one for binary 1.
        binary_pred_logprob = kb1_logprob[:,-1].reshape(1,len(kb1_logprob[:,-1])).transpose(0,1).repeat(1,2).view(-1, 2) + binary_logprob
        ## concatenate to get log-probability for all (40) classes
        pred_logprob = torch.from_numpy(np.c_[kb1_logprob[:,0:-1].cpu().detach().numpy(), binary_pred_logprob.cpu().detach().numpy()]).to('cuda')
        pred_choices = pred_logprob.max(1)[1]

        ## reset labels
        mapper_dict = {**{key: key + 1 for key in range(12, 32)}, **{key: key + 2 for key in range(32, 38)}, **{38: 33, 39: 12}}

        def mp(entry):
            return mapper_dict[entry] if entry in mapper_dict else entry
        mp = np.vectorize(mp)

        pred_choice = torch.from_numpy(np.array(mp(pred_choices.cpu().detach().numpy()))).to('cuda')
        preds.append(pred_choice.cpu().detach().numpy())
        correct = pred_choice.eq(target.long().data).cpu().detach().numpy().sum()
        total_correct += correct.item()
        total_seen += float(points.size()[0])

    accuracy = total_correct / total_seen
    ## confusion matrix
    cm = confusion_matrix(test_label.ravel(), np.concatenate(preds).ravel())
    cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    t = pd.read_table('data/ModelNet/shape_names.txt', names = ['label'])
    d = {key:val for key,val in zip(t.label, cm.diagonal())}
    print('Total Accuracy: %f'%accuracy)
    print('Accuracy per class:', d)

    logger.info('Total Accuracy: %f'%accuracy)
    logger.info('End of evaluation...')

def generate_new_view(points):
    points_idx = np.arange(points.shape[1])
    np.random.shuffle(points_idx)

    points = points[:, points_idx, :]
    return points

def rotate_point_cloud_by_angle(data, rotation_angle):
    """
    Rotate the point cloud along up direction with certain angle.
    :param batch_data: Nx3 array, original batch of point clouds
    :param rotation_angle: range of rotation
    :return:  Nx3 array, rotated batch of point clouds
    """
    cosval = np.cos(rotation_angle)
    sinval = np.sin(rotation_angle)
    rotation_matrix = np.array([[cosval, 0, sinval],
                                [0, 1, 0],
                                [-sinval, 0, cosval]], dtype=np.float32)
    rotated_data = np.dot(data, rotation_matrix)

    return rotated_data

if __name__ == '__main__':
    args = parse_args()
    main(args)