import pymongo
from pymongo import MongoClient

mongo_client = MongoClient()
leap = mongo_client['leap']
employees = leap['employees']
projects = leap['projects']
messages = leap['messages']
sentiment_ts = leap['sentiments_ts']
turnover_ts = leap['turnover_ts']

employees.create_index(("id"), unique=True)
projects.create_index(("id"), unique=True)


import gc
import re
import torch
import os
from models.models import create_pipeline, current_model_is_in_painting, models_memory_checker
from images.latents import create_latents_noise, latents_to_pil
from exceptions.exceptions import CancelException
from utils.settings import get_setting
from utils.images import pil_as_dict, pil_from_dict, inpaint_fill_image
from models.my_gfpgan import gfpgan_dwonload_model, gfpgan_restore_faces
from models.paths import LORA_DIR

from dexpert import progress, progress_canceled, progress_title

REPORT_PREFIX = 'Text To Image'
REPORT_PREFIXES = {
    'txt2img': 'Text to Image',
    'inpaint2img': 'Inpaint',
    'img2img': 'Image to Image',
}

def set_prefix(text):
    global REPORT_PREFIX
    REPORT_PREFIX = text

def report(message):
    progress_title(f'[{REPORT_PREFIX}] - {message}')

def get_lora_path(lora: str) -> str:
    for d in (LORA_DIR, get_setting('add_lora_dir', '')):
        for e in ('.safetensors', '.ckpt'):
            filepath = os.path.join(d, f'{lora}{e}')
            if os.path.exists(filepath):
                return filepath
    return None

def parse_prompt_loras(prompt: str):
    lora_re = re.compile('<lora:[^:]+:[^>]+>')
    lora_list = re.findall(lora_re, prompt)

    lora_items = []
    for lora in lora_list:
        lora = lora.replace('<', '').replace('>', '')
        p = lora.split(':')
        if len(p) != 3:
            continue
        p = [p[1], p[2]]
        try:
            weight = float(p[1])
        except Exception:
            report(f"Invalid lora weigth {p[1]}")
            continue
        filepath = get_lora_path(p[0])
        if not filepath:
            report(f"Lora not found: {p[0]}")
            continue
        lora_items.append([filepath, weight])
    return re.sub(lora_re, '', prompt), lora_items

@torch.no_grad()
def _run_pipeline(pipeline_type, params):
    device = get_setting('device', 'cuda')
    restore_faces = params.get('restore_faces')
    if restore_faces:
        gfpgan_dwonload_model()
        restore_faces = True

    prompt, lora_list = parse_prompt_loras(params['prompt'])
    negative = params['negative']

    if len(negative or '') < 2:
        negative = None

    seed = params['seed']
    model = params["model"]
    cfg = params["cfg"]
    steps = params["steps"]
    width = params["width"]
    height = params["height"]
    reload_model = params.get("reload_model", False)
    input_image = params.get("image")
    input_mask = params.get("mask")
    inpaint_mode = params.get("inpaint_mode", "original")
    controlnets = params.get("controlnets", [])

    if width % 8 != 0:
        width += 8 - width % 8

    if height % 8 != 0:
        height += 8 - height % 8

    variation_enabled = params.get('var_stren', 0) > 0
    var_stren = params.get("var_stren", 0)
    subseed = params['variation'] if variation_enabled else None

    shape = (4, height // 8, width // 8 )
    latents_noise = create_latents_noise(shape, seed, subseed, var_stren)

    generator = None if seed == -1  else torch.Generator(device=device).manual_seed(seed)

    if pipeline_type == 'img2img' and input_mask is not None:
        pipeline_type = 'inpaint2img'

    set_prefix(REPORT_PREFIXES.get(pipeline_type, "Text to Image"))

    report("started")

    report("creating the pipeline")
    pipeline = create_pipeline(pipeline_type, model, controlnets=controlnets, lora_list=lora_list, reload_model=reload_model)
    report("pipeline created")

    if pipeline_type == 'inpaint2img':
        if not current_model_is_in_painting():
            return {
                "error": "The current model is not for inpainting"
            }
    elif current_model_is_in_painting():
        return {
            "error": "The current model is a inpainting model"
        }

    def progress_preview(step, timestep, latents):
        progress(step, steps, latents_to_pil(step, pipeline.vae, latents))
        if progress_canceled():
            raise CancelException()

    additional_args = {}
    if pipeline_type == 'txt2img':
        additional_args = {
            'width': width,
            'height': height,
            'latents': latents_noise,
        }
        if len(controlnets):
            images = []
            conds = []
            for c in controlnets:
                if c['strength'] < 0:
                    c['strength'] = 0
                if c['strength'] > 2.0:
                    c['strength'] = 2.0
                images.append(pil_from_dict(c['image']))
                conds.append(c['strength'])
            if len(images) == 1:
                images = images[0]
            if len(conds) == 1:
                conds = conds[0]
            additional_args['image'] = images
            additional_args['controlnet_conditioning_scale'] = conds
    elif pipeline_type == 'img2img':
        additional_args = {
            'image': pil_from_dict(input_image),
            'strength': params['strength'],
        }
        if len(controlnets):
            additional_args['width'] = width
            additional_args['height'] = height
            images = []
            conds = []
            for c in controlnets:
                if c['strength'] < 0:
                    c['strength'] = 0
                if c['strength'] > 2.0:
                    c['strength'] = 2.0
                images.append(pil_from_dict(c['image']))
                conds.append(c['strength'])
            if len(images) == 1:
                images = images[0]
            if len(conds) == 1:
                conds = conds[0]
            additional_args['controlnet_conditioning_image'] = images
            additional_args['controlnet_conditioning_scale'] = conds
    elif pipeline_type == 'inpaint2img':
        if not current_model_is_in_painting():
            return {
                "error": "The current model is not for in painting"
            }
        image = pil_from_dict(input_image)
        mask = pil_from_dict(input_mask)

        if inpaint_mode != 'original':
            image = inpaint_fill_image(image, mask)

        additional_args = {
            'image': image,
            'mask_image': mask,
            'width': width,
            'height': height,
            'latents': latents_noise,
        }
        if len(controlnets):
            images = []
            conds = []
            for c in controlnets:
                if c['strength'] < 0:
                    c['strength'] = 0
                if c['strength'] > 2.0:
                    c['strength'] = 2.0
                images.append(pil_from_dict(c['image']))
                conds.append(c['strength'])
            if len(images) == 1:
                images = images[0]
            if len(conds) == 1:
                conds = conds[0]
            additional_args['controlnet_conditioning_image'] = images
            additional_args['controlnet_conditioning_scale'] = conds

    pipeline.to(device)
    latents_noise.to(device)
    report("generating the variation" if variation_enabled else "generating the image")
    with torch.inference_mode(), torch.autocast(device):
        result = pipeline(
            prompt,
            negative_prompt=negative,
            guidance_scale=cfg,
            num_inference_steps=steps,
            generator=generator,
            callback=progress_preview,
            **additional_args,
        ).images[0]

    if restore_faces:
        progress(99, 100, pil_as_dict(result))
        result = gfpgan_restore_faces(result)

    report("image generated")
    return pil_as_dict(result)

def run_pipeline(mode: str, params: dict):
    progress(0, 100, {})

    try:
        data = _run_pipeline(mode, params)
    except CancelException:
        print("Image generation canceled")
        data = {"error": "Operation canceled by the user"}
    gc.collect()

    progress(100, 100, {})

    return data


import torch
import torch.nn as nn
import pytest

from kgcn_torch.nn.util_modules import Concatenate

@pytest.mark.parametrize('axis, expected', [
    (0, [10, 4, 3, 2]),
    (1, [5, 8, 3, 2]),
    (2, [5, 4, 6, 2]),
    (3, [5, 4, 3, 4]),
])
def test_concatenate(axis, expected):
    a = torch.randn(5, 4, 3, 2)
    b = torch.randn(5, 4, 3, 2)
    net = Concatenate(axis)
    c = net(a, b)
    assert list(c.shape) == expected


import string

class Vertex:
    def __init__(self, id):
        self.id = id
        self.name = string.ascii_uppercase[id]
        self.degree = 0
        self.neighbours = []

    def addNeighbour(self, id):
        if id not in self.neighbours:
            self.neighbours.append(id)
            self.degree+=1

class Graph:
    def __init__(self, fileName):
        self.fileName = fileName
        self.tab = []
        with open (self.fileName, 'r') as file:
            for i in file:
                tab = []
                for j in i:
                    if j == '0' or j == '1':
                        tab.append(int(j))
                self.tab.append(tab)
        self.vertices = []
        for x in range(0, len(self.tab[0])):
            self.vertices.append(Vertex(x))
        for i in range(0,len(self.tab)):
            for j in range(0, len(self.tab[i])):
                if self.tab[i][j] == 1:
                    self.vertices[i].addNeighbour(j)
        self.edges = []
        for v in self.vertices:
            for e in v.neighbours:
                a = v.id
                b = e
                if a > b:
                    c = a
                    a = b
                    b = c
                if not((a, b) in self.edges):
                    self.edges.append((a,b))
        self.incident = [[0 for col in range(len(self.edges))] for row in range(len(self.vertices))]
        for i in range(0, len(self.edges)):
            e = self.edges[i]
            self.incident[e[0]][i]+=1
            self.incident[e[1]][i]+=1

    def tupleIdToName(self, t):
        return (self.vertices[t[0]].name, self.vertices[t[1]].name)

    def printIncidentMatrix(self):
        print("Macierz incydencji: ")
        for i in self.incident:
            print(i)

    def printEdgesNames(self):
        print("Krawędzie w grafie: ")
        for i in self.edges:
            print(self.tupleIdToName(i))

    def printVerticesDegrees(self):
        print("Stopnie wierzchołków:")
        for i in self.vertices:
            print("* " + i.name + ": " + str(i.degree))

    def neighboursIdToName(self, v):
        tab = []
        for x in v.neighbours:
            tab.append(self.vertices[x].name)
        return tab

    def printMaxVertexDegreeNeighbours(self):
        v = None
        for i in self.vertices:
            if v is None or i.degree > v.degree:
                v = i
        print("Wierzchołek o największym stopniu (" + str(v.degree) + ") to " + v.name + " z somsiadami:")
        print(self.neighboursIdToName(v))

    def printAllNeighbours(self):
        print("Lista następników: ")
        for i in self.vertices:
            print(i.name, self.neighboursIdToName(i))
    def printConsistentComponents(self):
        n = len(self.vertices)
        C = [0] * n
        cn = 0
        S = []
        vOrder = []
        skladowe = []
        print(str(n))
        for i in range(n):
            if C[i] > 0:
                continue
            cn+=1
            skladowe.append([])
            S.append(i)
            skladowe[cn-1].append(i)
            vOrder.append(i)
            C[i] = cn
            vx = S[-1]
            while len(S):
                v = self.vertices[vx]
                vN = len(v.neighbours)
                vV = 0
                for x in v.neighbours:
                    if C[x] > 0:
                        vV+=1
                if vN == vV:
                    S.pop()
                    if len(S) == 0:
                        break
                    vx = S[-1]
                    continue
                for u in v.neighbours:
                    if C[u] > 0:
                        continue
                    else:
                        S.append(u)
                        vx = S[-1]
                        skladowe[cn-1].append(u)
                        vOrder.append(u)
                        C[u] = cn
                        break
        print(vOrder)
        print("Spójne składowe: " + str(cn))
        for i in range(1,cn+1):
            print("*składowa: " + str(i))
            print(skladowe[i-1])

plik = input("Podaj nazwę pliku: ")
graf = Graph(plik)
graf.printConsistentComponents()


import xlwings

def code(path):  # 主功能代码
    app = xlwings.App(visible=True, add_book=False)
    file1 = app.books.open(path)
    len_org = len(file1.sheets)  # 初始的sheet数量
    file1.sheets.add(after=file1.sheets[-1])  # 添加一个sheet放最后
    sht_last = file1.sheets[-1]
    try:
        index_options = file1.sheets[
                            'Options'].index - 1  # sheet<Options>（已被隐藏）的索引，为了处理在前面添加过sheet导致的错误，xlwings的索引从1开始，所以-1和list保持一致
    except:
        index_options = 0
    rng = file1.sheets[index_options + 1].range('a16').expand()  # 从a16展开，为了获取行数和列数
    rng_rows = rng.rows.count  # 统计行数
    # rng_cols=rng.columns.count#统计列数
    sht_last[1, 2].options(transpose=True).value = file1.sheets[index_options + 1].range(
        'a16:a{}'.format(rng_rows + 16)).value  # 导出化合物名称到第3列
    sht_last[0, 2].value = '化合物'
    count_0 = 0
    for i in range(index_options + 1, len_org - 1):
        if str(file1.sheets[i].name)[0:-2] == str(file1.sheets[i].range('d7').value)[0:-2]:  # 自行添加的sheet不导出数据
            sht_last[0, i + 2 - index_options - count_0].value = file1.sheets[i].name  # 导出sheet名称（样品编号）到第一行
            sht_last[1, i + 2 - index_options - count_0].options(transpose=True).value = file1.sheets[i].range(
                'f16:f{}'.format(rng_rows + 16)).value  # 导出对应的数据
        else:
            count_0 += 1  # 修正

    table = sht_last.range('c1').expand()  # 统计要删除第几行
    table_rows = table.rows.count
    delete_rows = []
    for i in range(table_rows - 1):
        if sht_last[i, 2].value in ['Compound', '4-溴氟苯(surr)']:
            delete_rows.append(i + 1)
    count_1 = 0
    for i in delete_rows:
        sht_last.api.rows('{}'.format(i - count_1)).delete  # 调用excel的API完成
        count_1 += 1  # 每删除1行后面的所有行会向上，所以-count来修正

    rows_final = table_rows - len(delete_rows)  # 删除不需要的行后最终的行数
    list_unsorted = sht_last.range('c2:c{}'.format(rows_final)).value
    if list_unsorted[0] in content_sort.get('1.0', 'end'):
        list_manual_sort = content_sort.get('1.0', 'end').splitlines()
    else:
        list_manual_sort = list_unsorted
    for i in range(len(list_unsorted)):
        sht_last.range('a{}'.format(i + 2)).value = list_manual_sort.index(list_unsorted[i]) + 1  # 查找a列表中的项在b列表的索引
    sht_last.range('b1').value = '原始排序'
    sht_last.range('b2').options(transpose=True).value = [i for i in range(1, rows_final)]  # 按顺序添加第一列序号
    sht_last.range('a1').value = 0
    sht_last.range('a1').api.Sort(Key1=sht_last.range('a1').api, Order1=1)  # 调用api，按照a列排序，Order1=1升序，=2降序
    sht_last.range('a1').value = '自定义排序'

# 以下部分为gui
import tkinter
import tkinter.filedialog
import tkinter.scrolledtext
import time

window = tkinter.Tk()  # 初始化
window.title('MassHunter报告数据汇总')  # 标题
window.geometry()  # 窗口范围

string1 = tkinter.StringVar()  # 文本，用于显示在label等控件上
string1.set('输入or选择路径')  # 设置string的值
content_log = tkinter.scrolledtext.ScrolledText(font=('None', 14), height=15)
content_log.pack(side='bottom', expand=True, fill='both')
content_log.insert('1.0', '文件浏览记录:\n')
content_sort = tkinter.scrolledtext.ScrolledText(font=('None', 14), height=15)
content_sort.pack(side='bottom', expand=True, fill='both')
content_sort.insert('1.0', '自定义排序请将模板黏贴此处（beta）')
label = tkinter.Label(window, text='目标路径:', font=('None', 14))  # label控件
label.pack(side='left')  # 放置控件
ety_path = tkinter.Entry(window, textvariable=string1, font=('None', 14))  # 输入框，可用Entry.get()取得输入的值
ety_path.pack(side='left', fill='x', expand=True)

def select():
    filepath = tkinter.filedialog.askopenfilename()  # 选择一个文件，取得他的绝对路径
    # Folderpath = tkinter.filedialog.askdirectory()  # 获得文件夹路径
    string1.set(filepath)
    content_log.insert('end', '[{}] {}\n'.format(time.strftime('%H:%M:%S'), filepath))

button_select = tkinter.Button(window, text='选择', font=('None', 12), width=10, height=1,
                               command=select)  # 注：command后的函数不可传入参数
button_select.pack(side='left')

def run():
    code(path=ety_path.get())

button_run = tkinter.Button(window, text='处理', font=('None', 12), width=10, height=1, command=run)
button_run.pack(side='left')

menubar = tkinter.Menu(window)  # 以下部分为添加菜单栏，保留功能扩展
menu_first = tkinter.Menu(menubar)
menu_second = tkinter.Menu(menu_first)
menu_third = tkinter.Menu(menu_second)
menubar.add_cascade(label='一级菜单示例', menu=menu_first)
menu_first.add_cascade(label='二级菜单示例', menu=menu_second, underline=0)
menu_first.add_separator()
menu_first.add_command(label='打开', command=None)
menu_first.add_command(label='保存', command=None)
menu_first.add_separator()
menu_first.add_command(label='退出', command=window.quit)
menu_second.add_cascade(label='三级菜单示例', menu=menu_third)
menu_second.add_separator()
menu_second.add_command(label='打开', command=None)
menu_third.add_command(label='打开', command=None)
window.config(menu=menubar)

window.mainloop()


import argparse
import logging
from tools import *
from main import get_best_tpn
import datetime

def run(args):
    """collect parameters"""
    try:  # for split domains
        test = int(args.d.split('/')[-2])
        args.d_name = args.d.split('/')[-3]
    except:
        args.d_name = args.d.split('/')[-2]
    args.p_name = args.p.split('/')[-1].split('.')[0]
    args.d = os.path.join(os.getcwd(), 'benchmarks', args.d)
    args.p = os.path.join(os.getcwd(), 'benchmarks', args.p)
    args.n = int(args.n)
    params = [args.p_type, args.d, args.p, args.d_name, args.p_name, args.n, args.n, 'Python', 'C0', 'K-First',
              [None, None], args.planner, args.verbose, args.timeout, ['Full', 'Semi'], ['Strict', 'Loose'],
              args.ground, 'Gecode']
    method_list = []

    """OUTPUT DIR"""
    DIRECTORIES["PLAN_OUTPUT_DIR"] = os.path.join(os.getcwd(), 'output/planner_output', args.p_type, args.d_name,
                                                  args.p_name, str(args.n))
    if not os.path.exists(DIRECTORIES["PLAN_OUTPUT_DIR"]):
        os.makedirs(DIRECTORIES["PLAN_OUTPUT_DIR"])

    """RUN"""
    name = '_'.join([args.p_type, str(args.n), args.d_name, args.p_name])
    log_name = 'logs/' + '_'.join([name, datetime.datetime.now().strftime("%d-%m %H:%M").replace(' ', '_')])
    logging.basicConfig(filename=log_name + '.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s',
                        level=logging.INFO)
    tpns, msg, naive_tpn = get_best_tpn(params)
    if tpns:
        for regime_method in tpns:
            tpn_name = '_'.join([name, regime_method])
            if tpns[regime_method]:
                tpns[regime_method].name = name
                save_object(tpns[regime_method], tpn_name, DIRECTORIES['TPN_DIR'])
                method_list.append([tpn_name, 'TPN generated'])
            else:
                save_object(naive_tpn, tpn_name, DIRECTORIES['TPN_DIR'])
                method_list.append([tpn_name, 'Time limit reached'])
    else:
        name = '_'.join([name, msg.upper()])
        save_object(naive_tpn, name, DIRECTORIES['TPN_DIR'])
        method_list.append([name, msg])

    return method_list

def get_prob_name(problem):
    if problem[-5:] == '.pddl':
        return problem[:-5]  # remove pddl extension
    else:
        return problem

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Automatically generate a TPN for input temporal planning problem.')
    parser.add_argument("-p_type", help="PDDL problem type", default='Temporal')
    parser.add_argument("-d", help="PDDL domain file path from benchmarks folder", default=None)
    parser.add_argument('-p', type=str, help='problem file path from benchmarks folder')
    parser.add_argument("-n", help="number of plans", default=None)
    parser.add_argument("-ground", help="grounded domain", default=False)
    parser.add_argument('-planner', type=str, help='which planner to use', default='optic_plus')
    parser.add_argument('-verbose', type=bool, help='verbose for planner', default=False)
    parser.add_argument('-timeout', type=int, help='COP timeout (sec), default is 5 min (300 sec)', default=30 * 60)
    args = parser.parse_args()

    run(args)

    # -p_type Classical -d Classical/driverlog/domain.pddl -n 2 -p Classical/driverlog/p01.pddl
    # -p_type Temporal -d Temporal/parking/domain.pddl -n 2 -p Temporal/parking/p15-9-3.pddl
    # -p_type Temporal -d Temporal/quantum_circuit/quantum_circuit_01/domain.pddl -n 2 -p Temporal/quantum_circuit/quantum_circuit_01/problem_n4_i1_u1.0_P1_V2.pddl


# -*- coding:utf-8 -*-
import streamlit as st
import matplotlib.pyplot as plt
def main():
    value1 = st.sidebar.slider('Select a Value object notation', 0, 100)
    st.sidebar.write(value1)

    with st.sidebar:
        value2 = st.slider('Select a Value with notation', 0, 100)
        st.write(value2)
    value3 = st.slider('Select a Value just slider, 0, 100')
    st.write(value3)

    with st.sidebar:
        st.markdown('### Matplotlib Added on Sidebar')
        fig, ax = plt.subplots()
        ax.plot([1, 2, 3])
        st.pyplot(fig)

if __name__ == "__main__":
    main()


#relative module with python
#剛剛是自訂函數來enqueue/dequeue data,利用list模擬queue
#python 有內建的enqueue/dequeue function->put(data),get()
from queue import*
#利用Queue() 可以直接建立一個空的queue  queue=[]
q=Queue()
q.put('Grape')  #enqueue data 'grape'
q.put('Mango')
q.put('Apple')
#print("the len of queue",len()
print(q.empty())
while not q.empty():   #while True    not False == True
    print(q.get())  #use loop to dequeue(read) the data  using get()


import numpy as np
import pandas as pd
from krwordrank.word import KRWordRank
from soynlp.noun import LRNounExtractor_v2
from konlpy.tag import Okt
from collections import Counter
import copy

# 영어 숫자를 제외한 한국어 댓글를 통해 키워드를 추출
# soynlp, krwordsrank는 비지도 학습이므로 댓글 수가 적으면 정확한 키워드 추출이 안될 수 있다(댓글 50개이하..?)
# 댓글 적은거는 분석 안해주기로

class keywordExtractor: # 키워드 추출 클래스

  def __init__(self, common_words=[]):
    self.common_words = common_words

  def set_common_words(self, common_words):
    self.common_words = common_words

  def get_comments_from_excel(self,link):
    data = pd.read_excel(link)  # 엑셀 파일 읽기
    self.data = copy.deepcopy(data)   # 깊은 복사
    data['comment'] = data['comment'].str.replace('[^ㄱ-ㅎㅏ-ㅣ가-힣 ]','', regex=True)   # 한국어를 제외한 문자 제거(숫자, 영어도 모두 제거)
    data['comment'] = data['comment'].str.replace('^ +','', regex=True)
    data['comment'].replace('',np.nan, inplace=True)
    data = data.dropna(how='any')
    self.comments = data['comment'].values.tolist() # df to list
    return self

  def keywords_from_krwordsrank(self):
    # krwordsrank를 통한 키워드 추출
    wordrank_extractor = KRWordRank()
    # 영어 포함 시 normalize 해주어야함
    keywords, rank, graph = wordrank_extractor.extract(self.comments)
    return keywords

  def keywords_from_soynlp(self):
    # soynlp를 통한 키워드 추출
    # verbose : 함수 실행시 상세 정보를 출력할 것인지
    noun_extractor = LRNounExtractor_v2(verbose=False, extract_compound=True)
    keywords = noun_extractor.train_extract(self.comments)
    keywords = sorted(keywords.items(), reverse=True, key= lambda x : x[1])   # 빈도수 순으로 정렬(빈도수 높은 순으로)
    keywords = dict(((key, value) for key, value in keywords))
    # 딕셔너리로 변환
    # 반환값 : 빈도수 순으로 정렬된 키워드 딕셔너리(키워드 : 빈도수)
    return keywords

  def keywords_from_konlpy(self):
    # konlpy를 통한 키워드 추출
    data = copy.deepcopy(self.comments)   # 깊은 복사
    okt = Okt()
    for i in range(len(data)):   # 토큰화 n번
      data[i] = okt.nouns(data[i])  #명사 추출
    data = sum(data,[])  # 리스트 합치기(2차원 -> 1차원)
    keywords = dict(Counter(data))  #토큰 빈도수 계산
    keywords = sorted(keywords.items(), reverse=True, key= lambda x : x[1]) # 빈도수 순으로 정렬(빈도수 높은 순으로)
    keywords = dict(((key, value) for key, value in keywords))
    # 딕셔너리로 변환
    # 반환값 : 빈도수 순으로 정렬된 키워드 딕셔너리(키워드 : 빈도수)
    return keywords

  def get_best5_keywords(self, keywords, one=False):
    # best 5 키워드 뽑기
    # common_words나 한글자 단어는 키워드에서 제외
    # 파라미터 one은 한글자 단어를 제외시킬건지(True:제외, False:제외x)
    # 한글자 단어를 제외시키면 real 한글자 키워드를 뽑지 못하는 issue(ex : 깡, 진)
    keywords = [*keywords]
    # 딕셔너리의 인덱스값만을 뽑아 배열로 만듬
    if(one == True):
      keywords = [word for word in keywords if len(word)!=1]
      # 한글자 단어 키워드에서 제외
    best_5_keywords = [word for word in keywords if not word in self.common_words][:5]
    # common_words 제외 & 상위 5개 키워드 추출
    # 반환값 : 상위 5개 키워드
    return best_5_keywords

  def get_comments_related_to_keyword(self,keyword, n=None):
    # 키워드에 대한 관련 댓글 추출
    data = self.data.sort_values(by='num_likes', ascending=False)
    # 좋아요 순으로 정렬
    comments = data['comment'].values.tolist()
    related_comments = [] #관련 댓글
    for i in range(len(comments)):
      if(len(related_comments) == n):
        break
      else:
        if(comments[i].find(keyword)!=-1):
          markedword = "<mark>"+keyword+"</mark>"
          comments[i] =comments[i].replace(keyword, markedword)
          related_comments.append(comments[i])
    return related_comments

  def method_comparison(self, link):
    # soynlp, krwordsrank, konlpy 결과 비교
    self.get_comments_from_excel(link)
    keywords = [self.keywords_from_konlpy(), self.keywords_from_soynlp(), self.keywords_from_krwordsrank()]
    print('konlpy best 5 :'+', '.join(self.get_best5_keywords(keywords[0],True)))
    print('soynlp best 5 :'+', '.join(self.get_best5_keywords(keywords[1],True)))
    print('krwordsrank best 5 :'+', '.join(self.get_best5_keywords(keywords[2],False)))

  def get_comments_related_to_best5keywords(self, func, one=True, n=10):
    # best5 키워드를 추출하고 그에 관한 관련댓글 추출
    # 파라미터 func 사용할 키워드 추출 함수 설정
    if(func == self.keywords_from_krwordsrank):
      # func가 krwordsrank를 통한 키워드 추출일 경우 one 파라미터를 False로 수정한다
      one = False
    comments = []  #best5 키워드의 관련 댓글들 n개*5가 담길 리스트
    best_5_keywords = self.get_best5_keywords(func(),one) #best5 키워드
    for i in best_5_keywords:
      comments.append(self.get_comments_related_to_keyword(i,n))
    # best5 키워드와 관련 댓글들을 반환
    return best_5_keywords, comments


import time
import pandas as pd
import numpy as np
from os import path, listdir

def read_vdj(filename=None):
    if filename is None:
        filename = 'vdjdb_full.txt'
        # filename = 'vdjdb.slim.txt'
    file = path.abspath(
        path.join(__file__, '../../../data/vdjdb-2023-06-01/'+filename))
    df = pd.read_csv(file, sep='\t', keep_default_na=False)

    filter1 = df['species'] == 'HomoSapiens'
    filter2 = df['cdr3.beta'].str.match(r'^C[ACDEFGHIKLMNPQRSTVWY]{9,15}[FW]$')
    filter3 = df['v.beta'] != ''
    filter4 = df['antigen.epitope'] != ''
    all_filter = np.all((filter1, filter2, filter3, filter4), axis=0)
    df2 = df[all_filter].reset_index(drop=True)

    filter1 = df2['vdjdb.score'] != 0
    filter2 = df2['reference.id'] != 'PMID:28636592'
    df2_test = np.all((filter1, filter2), axis=0)
    df2_validation = ~df2_test

    fieldmap = {'v.beta': 'vb', 'cdr3.beta': 'cdr3b',
                'antigen.epitope': 'epitope'}
    df3 = df2.rename(columns=fieldmap)[fieldmap.values()]
    return df3[df2_test].reset_index(drop=True), df3[
        df2_validation].reset_index(drop=True)

def read_emerson(single_file=False):
    folder = path.abspath(path.join(__file__, '../../../data/emerson'))
    ans = None
    for i, file in enumerate(listdir(folder)):
        df = pd.read_csv(path.abspath(path.join(folder, file)),
                         sep='\t', usecols=['amino_acid', 'v_gene'])
        df.dropna(inplace=True)
        df = df[df['amino_acid'].str.match(
            r'^C[ACDEFGHIKLMNPQRSTVWY]{9,15}[FW]$')]
        df = df[df['v_gene'].str.contains(r'\-\d\d$')]
        df['file'] = i
        if ans is None:
            ans = df[['amino_acid', 'file', 'v_gene']].reset_index(drop=True)
        else:
            ans = pd.concat([ans, df], copy=False, ignore_index=True)
        if single_file:
            break
    fieldmap = {'v_gene': 'vb', 'amino_acid': 'cdr3b', 'file': 'file'}
    return ans.rename(columns=fieldmap)[fieldmap.values()]

def read_template():
    _file = path.abspath(path.join(__file__, '../../../data/templategt9.csv'))
    return pd.read_csv(_file, index_col=False)

def print_count(arr):
    u, c = np.unique(arr, return_counts=True)
    for i in range(len(u)):
        print(u[i], c[i])

def read_emerson_healthy(single_file=False):
    folder = path.abspath(path.join(__file__, '../../../../msc_proj/data/emerson'))
    ans = None
    files = listdir(folder)
    total_tcr = 0
    for i, file in enumerate(files):
        print(i/len(files))
        df = pd.read_csv(path.abspath(path.join(folder, file)),
                         sep='\t', usecols=['amino_acid','templates'])
        df['templates'].fillna(1,inplace=True)
        df.dropna(inplace=True)
        total_tcr += len(df)
        if len(df)==0:
            continue
        df = df[df['amino_acid'].str.match(
            r'^C[ACDEFGHIKLMNPQRSTVWY]{9,15}[FW]$')].reset_index(drop=True)

        df = df.groupby('amino_acid')['templates'].sum().reset_index()
        df['file'] = i
        filter1 = df['templates'] > 7
        filter2 = np.all((df['amino_acid'].str.len()==14,df['templates'] > 5),axis=0)
        filter3 = np.all((df['amino_acid'].str.len()==15,df['templates'] > 4),axis=0)
        filter4 = np.all((df['amino_acid'].str.len()==16,df['templates'] > 2),axis=0)
        filter5 = np.all((df['amino_acid'].str.len()>16,df['templates'] > 1),axis=0)
        df = df[np.any((filter1,filter2,filter3,filter4,filter5),axis=0)]
        if ans is None:
            ans = df[['amino_acid', 'file']].reset_index(drop=True)
        else:
            ans = pd.concat([ans, df], copy=False, ignore_index=True)
        if single_file:
            break
    print('total_tcr:',total_tcr)
    fieldmap = {'amino_acid': 'cdr3b', 'file': 'file'}
    return ans.rename(columns=fieldmap)[fieldmap.values()]

def read_emerson_negative():
    folder = path.abspath(path.join(__file__, '../../../../msc_proj/data/emerson'))
    ans = None
    files = listdir(folder)[:20]
    total_tcr = 0
    for i, file in enumerate(files):
        print(i/len(files))
        df = pd.read_csv(path.abspath(path.join(folder, file)),
                         sep='\t', usecols=['amino_acid','templates'])
        df['templates'].fillna(1,inplace=True)
        df.dropna(inplace=True)
        total_tcr += len(df)
        if len(df)==0:
            continue
        df = df[df['amino_acid'].str.match(
            r'^C[ACDEFGHIKLMNPQRSTVWY]{9,15}[FW]$')].reset_index(drop=True)

        df = df.groupby('amino_acid')['templates'].sum().reset_index()
        df['file'] = i
        df = df[df['templates'] == 1]
        if ans is None:
            ans = df[['amino_acid', 'file']].reset_index(drop=True)
        else:
            ans = pd.concat([ans, df], copy=False, ignore_index=True)
    print('total_tcr:',total_tcr)
    fieldmap = {'amino_acid': 'cdr3b', 'file': 'file'}
    return ans.rename(columns=fieldmap)[fieldmap.values()]

def save_np(np_arr, filename):
    file = path.abspath(
        path.join(__file__, '../../../data/'+filename))
    np.save(file, np_arr)

def load_np(filename):
    file = path.abspath(
        path.join(__file__, '../../../data/'+filename))
    return np.load(file)

def save_pd(df, filename):
    file = path.abspath(
        path.join(__file__, '../../../data/'+filename))
    df.to_csv(file, index=False)

def load_pd(filename):
    file = path.abspath(
        path.join(__file__, '../../../data/'+filename))
    return pd.read_csv(file, index_col=False)


from django.urls import path
from . import views

app_name = 'devices'

urlpatterns = [
    path('list', views.DeviceListView.as_view(), name="list"),
    path('create/', views.DeviceCreateView.as_view(), name="device_create"),
    path('create/<str:id>', views.DeviceCreateView.as_view(), name="device_created"),
    path('delete/', views.delete_device_view, name="delete"),
    path('device-update/', views.update_device, name="update"),
    path('device-update/', views.update_device, name="update"),
]


from typing import Tuple, Optional, Union
from packaging import version

from torch import Tensor
from torch.nn import functional as F
from torch.nn import Module

from brevitas import torch_version
from brevitas.quant_tensor import QuantTensor
from brevitas.export.onnx.manager import ONNXBaseManager
from brevitas.export.manager import _set_layer_export_handler, _set_layer_export_mode

from .handler.base import StdQOpONNXQuantLayerHandler
from .handler.parameter import StdQOpONNXQuantConv2dHandler
from .handler.parameter import StdQOpONNXQuantAdd2dHandler
from .handler.parameter import StdQOpONNXQuantConv1dHandler
from .handler.parameter import StdQOpONNXQuantLinearHandler
from .handler.act import StdQOpONNXQuantReLUHandler
from .handler.act import StdQOpONNXQuantHardTanhHandler
from .handler.act import StdQOpONNXQuantIdentityHandler
from .handler.act import StdQOpONNXQuantTanhHandler
from .handler.act import StdQOpONNXQuantSigmoidHandler
from .handler.pool import StdQOpONNXQuantMaxPool1d
from .handler.pool import StdQOpONNXQuantMaxPool2d
from .. import OPSET
from ..function import QuantizeLinearFn, DequantizeLinearFn

class StdQOpONNXManager(ONNXBaseManager):
    target_name = 'StdQOpONNX'

    _fn_to_cache = [
        F.relu,
        F.relu6,
        F.hardtanh,
        F.max_pool1d,
        F.max_pool2d,
        F.max_pool3d,
        F.adaptive_max_pool1d,
        F.adaptive_max_pool2d,
        F.adaptive_max_pool3d,
    ]

    handlers = [
        StdQOpONNXQuantConv1dHandler,
        StdQOpONNXQuantConv2dHandler,
        StdQOpONNXQuantAdd2dHandler,
        StdQOpONNXQuantLinearHandler,
        StdQOpONNXQuantReLUHandler,
        StdQOpONNXQuantHardTanhHandler,
        StdQOpONNXQuantIdentityHandler,
        StdQOpONNXQuantTanhHandler,
        StdQOpONNXQuantSigmoidHandler,
        StdQOpONNXQuantMaxPool1d,
        StdQOpONNXQuantMaxPool2d]

    onnx_passes = [
        # remove unused graph inputs & initializers
        "eliminate_unused_initializer"]

    @classmethod
    def solve_enable_onnx_checker(cls, export_kwargs):
        if torch_version >= version.parse('1.5.0'):
            export_kwargs['enable_onnx_checker'] = True

    @classmethod
    def _trace_fn_dispatcher(cls, fn, input, *args, **kwargs):
        cached_io = cls._fn_cache.pop(0)
        if cached_io is not None:
            cached_inp, cached_out = cached_io
            if cached_inp is not None:
                deq_kwargs = StdQOpONNXQuantLayerHandler.dequant_symbolic_kwargs_from_cached_io(
                    cached_inp)
                input = DequantizeLinearFn.apply(input, *deq_kwargs.values())
            output = fn(input, *args, **kwargs)
            if cached_out is not None:
                q_kwargs = StdQOpONNXQuantLayerHandler.quant_symbolic_kwargs_from_cached_io(
                    cached_out)
                output = QuantizeLinearFn.apply(output, *q_kwargs.values())
        else:
            output = fn(input, *args, **kwargs)
        return output

    @classmethod
    def set_export_mode(cls, module: Module, enabled: bool):
        _set_layer_export_mode(module, enabled)

    @classmethod
    def set_export_handler(cls, module: Module):
        _set_layer_export_handler(cls, module)

    @classmethod
    def export_onnx(
            cls,
            module: Module,
            input_shape: Tuple[int, ...] = None,
            export_path: Optional[str] = None,
            input_t: Optional[Union[Tensor, QuantTensor]] = None,
            disable_warnings=True,
            **kwargs):
        output = super().export_onnx(
            module, input_shape, export_path, input_t,
            disable_warnings=disable_warnings, opset_version=OPSET, **kwargs)
        return output


# -*- coding: utf-8 -*-
# @Project: Spider_Hero
# @Author: little fly
# @File name: 6.多协程2
# @Create time: 2020/8/15 0:02
import requests
import asyncio
import time
import aiohttp

async def get_page(url):
    async with aiohttp.ClientSession() as session:
        # get()、post():
        # headers,params/data,proxy='http://ip:port'
        async with await session.get(url) as response:
            # text()返回字符串形式的响应数据
            # read()返回的二进制形式的响应数据
            # json()返回的就是json对象
            # 注意：获取响应数据操作之前一定要使用await进行手动挂起
            page_text = await response.text()
            print(page_text)

if __name__ == '__main__':
    urls = [
        'http://127.0.0.1:5000/zhx',
        'http://127.0.0.1:5000/lst',
        'http://127.0.0.1:5000/zxy'
    ]
    start_time = time.time()
    tasks = []
    for url in urls:
        c = get_page(url)
        task = asyncio.ensure_future(c)
        tasks.append(task)
    loop = asyncio.get_event_loop()
    # 需要将任务列表封装到wait中
    loop.run_until_complete(asyncio.wait(tasks))
    print('all_time:', time.time() - start_time)


from tkinter import*
import os
import random
import pickle
import time
import math
import projet
import module_scores

#fonctions commandees par bouttons

def regles():
    fenetre2=Toplevel() # ouverture d'une nouvelle fenetre
    fenetre2.title("R\xE8gles du Jeu") #titre de la fenetre = Regles du Jeu
    fenetre2.resizable(width=False, height=False) # ne peut pas changer la taille de la fenetre

    can2=Canvas(fenetre2,height=500,width=325) # dimension de la fenetre graphique (avec height=hauteur, width=largeur)
    photo2=PhotoImage(file="regles_du_jeu.gif") #insertion de l'image des regles
    item=can2.create_image(160,250,image=photo2) #placement de l'image aux pixels...
    can2.grid()  # composition de la fenetre graphique d'une grille par defaut
    fenetre2.mainloop() # lancement de la fenetre

def jouer():
    projet.show_jeu(True)
    # programme Tanguy + Valentin

#----------fenetre principale
fenetre=Tk()
fenetre.resizable(width=False, height=False)
fenetre.title("Menu Principal")

#-------------fond menu
can=Canvas(fenetre,height=500,width=300)
photo=PhotoImage(file="imagetest3.gif")# image qui est dans le meme repertoire que le script Python
item=can.create_image(150,250,image=photo) # placement de l'image aux pixels 150,250
can.grid(row=0,rowspan=1000,column=0) # grille de la fenetre graphique (avec row=ligne, rowspan=nb de lignes totales, column=colonne)

#-------widget button''let's go''
image_go=PhotoImage(file="go_button.gif")
but1=Button(fenetre,image=image_go,command=jouer) #va permettre de lancer le jeu
but1.grid(row=467,column=0)

#---------widget button "regles du jeu"
image_regles=PhotoImage(file="regles_button.gif")
but2=Button(fenetre,image=image_regles,command=regles) #va faire apparaitre une autre fenetre qui contient regles du jeu
but2.grid(row=598,column=0)

#-------widget button"scores"
image_scores=PhotoImage(file="scores_button.gif")
but3=Button(fenetre,text='Scores',image=image_scores,command=module_scores.affich_scores) #permet d'afficher les scores obtenus
but3.grid(row=737,column=0)

#------------creation widget "quitter"
image_quitter=PhotoImage(file="quitter_button.gif")
but4=Button(fenetre,text="Quitter",image=image_quitter,command=fenetre.destroy) #permet de fermer la fenetre
but4.grid()

#---------on lance le programme
fenetre.mainloop()


from __future__ import absolute_import

import collections
import uuid

from dolfin import Expression, Constant, FunctionSpace, VectorFunctionSpace, \
    interpolate
from . import Material

__all__ = ["CompositeMaterial"]

class CellExpr(Expression):
  def __init__(self, attr, domains, base_material, materials):
    self._attr          = attr
    self._domains       = domains
    self._base_material = base_material
    self._materials     = materials

  def eval_cell(self, result, x, cell):
    try:
      material = self._materials[self._domains[cell.index]]
    except KeyError:
      material = self._base_material

    try:
      result[0] = getattr(material, self._attr)
    except AttributeError:
      result[0] = 0.0

class VectorCellExpr(Expression):
  def __init__(self, attr, domains, base_material, materials):
    self._attr          = attr
    self._domains       = domains
    self._base_material = base_material
    self._materials     = materials

  def eval_cell(self, result, x, cell):
    try:
      material = self._materials[self._domains[cell.index]]
    except KeyError:
      material = self._base_material

    try:
      values = getattr(material, self._attr)
      result[0] = values[0]
      result[1] = values[1]
      result[2] = values[2]
    except (AttributeError, TypeError):
      result[0] = 0.0
      result[1] = 0.0
      result[2] = 0.0
  def value_shape(self):
    return (3,)

class CompositeMaterial(object):
  def __init__(self, state, base_material = Material()):
    self._state         = state
    self._base_material = base_material
    self._cache         = {}
    self._materials     = collections.OrderedDict()
    self.uuid           = uuid.uuid4()

  def __setitem__(self, index, value):
    self._materials[index] = value
    self._cache = {}
    self.uuid = uuid.uuid4()
    return value

  def __getitem__(self, index):
    return self._materials[index]

  def __delitem__(self, index):
    del self._materials[index]
    self._cache = {}
    self.uuid = uuid.uuid4()

  def __setattr__(self, attr, value):
    if attr[0] == '_' or attr == 'uuid':
      return super(CompositeMaterial, self).__setattr__(attr, value)
    else:
      self._cache = {}
      self.uuid = uuid.uuid4()
      return setattr(self._base_material, attr, value)

  def __getattr__(self, attr):
    if attr in self._cache:
      return self._cache[attr]

    materials = {}
    for domain, material in self._materials.items():
      ids = self._state.domain_ids(domain)
      for id in ids:
        if materials.has_key(id):
          materials[id] = Material(materials[id], material)
        else:
          materials[id] = material

    # scalar or vector parameter
    V    = None
    expr = None
    if len(self._materials) == 0:
      self._cache[attr] = Constant(getattr(self._base_material, attr))
    else:
      for material in [self._base_material] + self._materials.values():
        try:
          value = getattr(material, attr)
          if isinstance(value, tuple) or isinstance(value, list):
            assert len(value) == 3
            V    = VectorFunctionSpace(self._state.mesh, 'DG', 0)
            expr = VectorCellExpr(attr, self._state.cell_domains, self._base_material, materials)
          else:
            V    = FunctionSpace(self._state.mesh, 'DG', 0)
            expr = CellExpr(attr, self._state.cell_domains, self._base_material, materials)
          break
        except AttributeError:
          continue

      self._cache[attr] = interpolate(expr, V)

    return self._cache[attr]


import random
import argparse
import time
import os
from collections import Iterator

class RowsIterator(Iterator):

    def __init__(self, number_rows, step, start_time, number_devices, number_errors):
        self.__number_rows = number_rows
        self.__step = step
        self.__start_time = start_time
        self.__number_devices = number_devices
        self.__number_errors = number_errors
        self.__cur_row = start_time
        self.__cur_pos = 0
        self.__errors_pos = [random.randint(0, number_rows - 1) for _ in range(number_errors)]

    def __next__(self):
        if self.__cur_pos + 1 > self.__number_rows:
            raise StopIteration
        self.__cur_pos += 1
        if self.__cur_pos in self.__errors_pos:
            return get_errors_row()
        self.__cur_row += step
        return f"{random.randint(1, self.__number_devices)},{self.__cur_row},{random.randint(1, 100)}"

def current_milli_time():
    return round(time.time() * 1000)

def get_start_time(number_rows, step):
     # return random.randint(0, current_milli_time()-number_rows*step)
     return current_milli_time()

def get_number_rows():
    return random.randint(10000, 1000000)

def get_step():
    return random.randint(1, 1000*60*60*24)

def get_number_devices():
    return random.randint(2, 10)

def get_number_errors(number_rows):
    return random.randint(0, number_rows//10)

def get_errors_row():
    number_args = random.randint(1, 3)
    if number_args == 1:
        return f"{random.randint(0, 777)}"
    elif number_args == 2:
        return ",".join([str(random.randint(0, 777)), random.choice("pshepshe, rirva, pipidol")])
    return ",".join([str(random.randint(0, 777)),
                     str(random.choice("pshepshe, rirva, pipidol")),
                     str(random.randint(0, 100))])

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--start_time', type=int,
                        help='start time')
    parser.add_argument('-n', '--number_rows', type=int,
                        help='number rows')
    parser.add_argument('-t', '--step', type=int,
                        help='step')
    parser.add_argument('-d', '--number_devices', type=int,
                        help='number devices')
    parser.add_argument('-e', '--errors', type=int,
                        help='invalid rows count')

    args = parser.parse_args()
    if not args.number_rows:
        number_rows = get_number_rows()
    else:
        number_rows = args.number_rows
    if not args.step:
        step = get_step()
    else:
        step = args.step
    if not args.start_time:
        start_time = get_start_time(number_rows, step)
    else:
        start_time = args.start_time
    if not args.number_devices:
        number_devices = get_number_devices()
    else:
        number_devices = args.number_devices
    if not args.errors:
        number_errors = get_number_errors(number_rows)
    else:
        number_errors = args.errors

    genius_iterator = RowsIterator(number_rows, step, start_time, number_devices, number_errors)
    if not os.path.isdir("input"):
        os.mkdir("input")

    if not os.path.isdir("resolver"):
            os.mkdir("resolver")
    os.chdir("input")
    with open("output_data", 'w') as output_file:
        for row in genius_iterator:
            output_file.write(row + '\n')
    os.chdir("../resolver")
    with open("metric_resolver", 'w') as metric_resolver:
        for item in range(1, number_devices):
            metric_resolver.write(f"{item},device_{item}" + '\n')


def solution(A):
    lA=len(A)
    mA=max(A)
    repeats=[0]*mA
    divisors=[[1]]

    for x in range(1,mA): divisors.append([1,x+1])
    for x in A: repeats[x-1] +=1

    x=2
    while (x*x<=mA):
        for y in range (x, (mA//x)+1):
            tmp=divisors[(y*x)-1]
            tmp.append(x)
            if (y!=x) : tmp.append(y)
            divisors[(y*x)-1]=tmp
        x += 1

    r=[]

    for y in A:
        sum=0
        for x in divisors[y-1]: sum+=repeats[x-1]
        r.append(lA-sum)

    return(r)


#! /usr/bin/python3

code = '#ifndef CVVK_GLSLSTYLE_HPP\n#define CVVK_GLSLSTYLE_HPP\n#include "glm/glm.hpp" // IWYU pragma: keep\n'

def app(s):
    global code
    code += '\n'
    code += s

def toN(nu, n, l, sw):
    coms = ['xyzw', 'rgba']
    s = ''
    for i in range(l):
        s = coms[sw][nu % n] + s
        nu //= n
    return s

def combine(name, s):
    return ', '.join([ '{}.{}'.format(name, i) for i in s ])

def toVecN(n, name, sg):
    if n == 1:
        return sg
    return 'glm::{}{}'.format(name, n)

app('namespace mltsg\n{\n')

app('\n\n'.join([ (
        '\n'.join([ (
            '\n'.join([ (
                '\n'.join([ (

                    'inline {3} _{1}(const {0}& v) {{ return {3}({2}); }}'.format(
                        toVecN(i, 'vec', 'float'), toN(b, i, j, sw), combine('v', toN(b, i, j, sw)), toVecN(j, 'vec', 'float'))

                ) for sw in range(2) ])
            ) for b in range(pow(i, j)) ])
        ) for j in range(1, i + 1) ])
    ) for i in range(2, 5) ]))

app('\n\n'.join([ (
        '\n'.join([ (
            '\n'.join([ (
                '\n'.join([ (

                    'inline {3} _{1}(const {0}& v) {{ return {3}({2}); }}'.format(
                        toVecN(i, 'ivec', 'int'), toN(b, i, j, sw), combine('v', toN(b, i, j, sw)), toVecN(j, 'ivec', 'int'))

                ) for sw in range(2) ])
            ) for b in range(pow(i, j)) ])
        ) for j in range(1, i + 1) ])
    ) for i in range(2, 5) ]))

app('\n}\n')
app("#endif")

with open('./glslStyle.hpp', 'w') as f:
    f.write(code)


#1.
for i in range(2000,3201):
    if(i%7==0 and i%5!=0):
        print(i,end=',')

#2.
s=str(input())
print(s[::-1])

#3.
from math import pi
r=6
v=4*pi*(r**3)/3
print(v)


import sys

def countingSort(A,k):
    C=[0 for _ in range(k+1)]
    B=[0 for _ in range(len(A))]
    for i in range(0,len(A)):
        C[A[i]]=(C[A[i]])+1
    for i in range (1,k+1):
        C[i]=C[i]+C[i-1]
    C[:] = [x - 1 for x in C]
    for i in range(len(A)-1,-1,-1):
        B[C[A[i]]]=A[i]
        C[A[i]]=(C[A[i]])-1
    return B

N = int(sys.stdin.readline().strip())
array=[]
for i in range(N):
    x = int ((float(sys.stdin.readline().strip()))*100)
    array.append(x)
G = int(sys.stdin.readline().strip())

print(format(((countingSort(array,100)[G])/100),'.2f'))


#!/usr/bin/env python3

"""The setup script."""

from setuptools import setup, find_packages

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read()

requirements = [ ]

test_requirements = ['pytest>=3', ]

setup(
    author="Jonathan Velasco",
    author_email='velasco_jonathan@hotmail.com',
    maintainer="CSC - IT Center for Science :  ElmerFEM Developers",
    python_requires='>=3.7',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
        'Natural Language :: English',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
    ],
    description="Python module for creating the circuit simulation definitions for Elmer FEM. The circuit definitions enable easy setup of coils (e.g. massive, stranded, and foil) in 2D and 3D for magnetodynamics applications.",
    install_requires=requirements,
    license="GNU Lesser General Public License v3",
    long_description=readme + '\n\n' + history,
    include_package_data=True,
    keywords='elmer_circuitbuilder',
    name='elmer_circuitbuilder',
    #packages=find_packages(include=['elmer_circuitbuilder', 'elmer_circuitbuilder.*']),
    test_suite='tests',
    tests_require=test_requirements,
    url='https://github.com/ElmerCSC/elmer_circuitbuilder.git',
    version='v1.0.0',
    zip_safe=False,
    extras_require={"dev":["pytest>=3.7"], },
    py_modules=["elmer_circuitbuilder"],
    package_dir={'': 'elmer_circuitbuilder'},

)


from PygameWidgets.Widgets.UpdateWidget import UpdateWidget
import pygame
from .UpdateWidget import UpdateWidget
from pygame import Rect

class ProgressBar(UpdateWidget):

    def __init__(this, window, x, y, w, h, backgroundColor, foregroundColor, valuePointer, packetreader):
        super().__init__(window, x, y, w, h, backgroundColor, valuePointer, packetreader)
        this.foregroundColor = foregroundColor

    def draw(this):
        super().draw()

        # Draw Border
        x, y = this.x - this.w//2, this.y - this.h//2
        w, h = this.w, this.h
        borderRect = Rect(x, y, w, h)
        pygame.draw.rect(this.window, this.foregroundColor, borderRect, 2, 10)

        # Draw Progress
        x, y = this.x - this.w//2, this.y - this.h//2
        w, h = this.w/100 * this.value//40000, this.h
        progressRect = Rect(x, y, w, h)
        pygame.draw.rect(this.window, this.foregroundColor, progressRect, 0, 10)

        return (this.x, this.y, this.w, this.h)


'''
    Commands examples:
    python3 main.py -t (Scan all files in assets/text/*)
    python3 main.py -t -p assets/text/a.txt (Scan file of assets/text/a.txt)
'''
import json
import os
import requests
from com_function.get_local_storage import get_token

class Type():
    text = "text"

# API of Text Audit
url_list = {
    Type.text: 'https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token='
}

# Check text audit

def cli_text_audit(args):
    if args.path:
        path = args.path
        output_result_tojson(path, Type.text)

    else:
        for file_path in os.listdir('assets/text'):
            path = 'assets/text/' + file_path
            output_result_tojson(path, Type.text)

# Output json result to json file
def output_result_tojson(path, type: Type):
    token = get_token('Auth')
    url = url_list[type] + token
    file_handler = open(path, 'r')
    list_of_lines = file_handler.readlines()
    resultDict = {}
    for index, line in enumerate(list_of_lines):
        meta_data = line.strip()
        para = {"text": meta_data}
        r = requests.post(url, data=para)
        resultDict[meta_data] = r.json()
        print('all %s, current' % len(list_of_lines), index+1)
    with open('output/%s-result.json' % path[12:], "w", encoding='utf-8') as outfile:
        outfile.write(json.dumps(resultDict, ensure_ascii=False, indent=4))

    print('Done. Please check jason file!')


#MergeSort takes an unstorted list and sorts it increasingly

def MergeSort(list, left, right):
    if(left < right):
        middle = (left+right)/2
        MergeSort(list, left, middle)
        MergeSort(list, middle, right)
        print(list)
        Merge(list, left, middle, right)

def Merge(list, left, middle, right):
    s1 = middle - left + 1
    s2 = right - middle

    leftArray = []
    rightArray = []

    i = 0

    while i < s1:
        leftArray[i] = list[left + i]
        i += 1

    i = 0

    while i < s2:
        rightArray[i] = list[middle + 1 + i]
        i += 1
    i = 0
    j = 0

    k = left

    while i < s1 and j < s2:
        if leftArray[i] < rightArray[j]:
            list[k] = leftArray[i]
            k += 1
            i += 1
        else:
            list[k] = rightArray[j]
            k += 1
            j += 1

    while i < s1:
        list[k] = leftArray[i]
        k += 1
        i += 1

    while j < s2:
        list[k] = rightArray[j]
        k += 1
        j += 1

list = [1,6,0,8,12,22,45,7,99,100,11,10,20,26,38,201,13,4,3]
MergeSort(list, 0, len(list) - 1)
print(list)


from flask import Blueprint, jsonify, request, redirect, make_response

from libs.tools import cheap_hash
from libs.auth import token_required
from models import db, Url

shortener = Blueprint("shorten", __name__)

@shortener.route("/shorten", methods=["POST"])
@token_required
def encode(current_user):
    print(type(current_user))
    url = request.json.get("url")
    new_url = Url(url=url, short_url=cheap_hash(url), user_id=current_user.id)
    new_url.save()
    return jsonify({"full_url": url, "short_url": new_url.short_url})

@shortener.route("/s/<short_url>", methods=["GET"])
def get_full_url(short_url):
    url = Url.query.filter_by(short_url=short_url).first()

    # log & monitor click
    url.click += 1
    url.save()

    return redirect(url.url)

@shortener.route("/s/<short_url>/info", methods=["GET"])
@token_required
def get_url_info(current_user, short_url):
    url = Url.query.filter_by(short_url=short_url, user_id=current_user.id).first()
    if not url:
        return make_response(jsonify(message="forbidden url"), 403)
    return jsonify(url.json())


from sockjs.tornado import SockJSConnection
import json
import tornado.web
import tornado.gen
from .utils import get_redis

class Connection(SockJSConnection):
    clients = set()
    available_experiments = {}
    def send_error(self, message, error_type=None):
        """
        Standard format for all errors
        """
        return self.send(json.dumps({
            'type': 'error' if not error_type else '%s_error' % error_type,
            'data': {
                'message': message
            }
        }))

    def send_message(self, message, data_type):
        """
        Standard format for all messages
        """
        return self.send(json.dumps({
            'type': data_type,
            'data': message
        }))

    def on_experiments_updated(self):
        self.send_message(
            {
                "available_experiments": Connection.available_experiments
            },
            'experiments_list_update' # what to name the channel
        )

    @tornado.gen.coroutine
    def on_open(self, request):
        """
        Choose what model updates to listen to in visualizer:
        """
        self.authenticated = True
        self.experiment_uuid = None
        # choose the channel
        self.on_experiments_updated()
        self.clients.add(self)

    def on_message(self, msg):
        # For every incoming message, broadcast it to all clients
        # self.broadcast(self.clients, msg)
        if len(msg) > 2:
            try:
                json_msg = json.loads(msg)
            except Exception as e:
                print ("Error parsing JSON from client: " + e)
                return
            if "experiment_uuid" in json_msg:
                # new participant to this channel:
                self.experiment_uuid = json_msg["experiment_uuid"]
        else:
            pass

    def on_close(self):
        # If client disconnects, remove him from the clients list
        self.clients.remove(self)

    @classmethod
    def announce_new_experiments(cls, experiments):
        Connection.available_experiments = experiments
        for client in cls.clients:
            if client.authenticated:
                client.on_experiments_updated()

    @classmethod
    def pubsub_message(cls, msg):
        PREFIX = 'updates_'
        if not msg.channel.startswith(PREFIX) or msg.kind == 'psubscribe':
            return
        try:
            experiment_uuid = msg.channel[len(PREFIX):]
            data = json.loads(msg.body)
            data_type = data["type"]
        except Exception as e:
            print('WARNING: exception JSON parsing incoming update: ', e)
            return

        if data_type == 'heartbeat':
            # only used by server - do not pass to website
            return

        for client in cls.clients:
            if client.authenticated and client.experiment_uuid == experiment_uuid:
                # here is what redis sends
                client.send(msg.body)


import pandas as pd
from yelpapi import YelpAPI

from config import api_key

class YelpBusinessResults:

    default_api_key = api_key

    def __init__(
        self,
        search_term,
        location,
        business_types,
        key=None
        ):
        self.search_term = search_term
        self.location = location
        self.business_types = business_types
        if key is None:
            key = self.default_api_key
        self.key = key

        self.output_list = []

        # call the `_get_businesses()` method to fill in the above `output_list`
        self._get_businesses()

    def _get_businesses(self):

        limit = 50

        with YelpAPI(self.key) as yelp_api:

            # grab the first page of results, also use this to get the total number of results
            city_data = yelp_api.search_query(
                term=self.search_term,
                location=self.location,
                limit=limit # look at adding the business_types to this initial request
                )

            num_results = city_data['total']
            pages = (num_results // limit) + 1

            self._parse_response(city_data['businesses'])

            # pull the remaining pages of data, not past 1000 results (this is the Yelp-imposed max number of results)
            for n in range(1, pages):
                offset = limit * n
                if offset < 1000:
                    city_data = yelp_api.search_query(
                        term=self.search_term,
                        location=self.location,
                        limit=limit,
                        offset=offset
                        )
                    self._parse_response(city_data['businesses'])

    def _parse_response(self, businesses_list):
        for i,c in enumerate(businesses_list):
            try:
                country = businesses_list[i]['location']['country']
                business_type = businesses_list[i]['categories'][0]['alias']
                original_search_city = self.location.split(',')[0]

                if country == 'US' and business_type in self.business_types:
                    yelp_id = businesses_list[i]['id']
                    name = businesses_list[i]['name']
                    lat = businesses_list[i]['coordinates']['latitude']
                    long = businesses_list[i]['coordinates']['longitude']
                    yelp_city = businesses_list[i]['location']['city']
                    is_closed = businesses_list[i]['is_closed']
                    rating = businesses_list[i]['rating']
                    zip_code = businesses_list[i]['location']['zip_code']
                    state = businesses_list[i]['location']['state']

                    response_data = {
                        'yelp_id':yelp_id,
                        'name':name,
                        'lat':lat,
                        'lng': long,
                        'original_search_city':original_search_city,
                        'yelp_city':yelp_city,
                        'business`_type':business_type,
                        'is_closed':is_closed,
                        'rating':rating,
                        'zip_code':zip_code,
                        'state':state
                        }
                    self.output_list.append(response_data)
            except IndexError:
                print(i, c)


import sys
sys.stdin = open("B7_N QUEEN_input.txt")

# 우선은 행마다 하나씩 퀸을 놓아보자 - 어디에 놓을 수 있는가?(순열)
# 그 다음에 겹치는지를 체크
# N행에 도달하면 종료된다
# N열에 도달할 때까지 종료된다

# depth = 0행부터 행 개수를 추가한다
# check 함수에 행과 열을 인자로 넣어준다 -> 그러나 n^2만큼 체크하므로 속도 저하 발생
# check 함수로 체크할 대상은 놓을 위치의 위쪽, 왼쪽 대각선, 오른쪽 대각선을 확인하면 된다

# check 개선 방향(전체 2배 길이로 만든다)
# 1차원 배열을 3개를 만들어 어떤 열에 놓았는지 확인(for문 필요 없이 if문으로 체크)
# 직선의 경우 1차원 리스트 N개를 만듦
# 우상향 대각선의 경우 N = 4인 경우 7개 리스트로 만들어서 체크(행+열 인덱스를 더하면 1차원 배열의 인덱스가 나옴)
# 좌상향 대각선도 7개 리스트로 만들어서 열에 놓았는지 체크((N-1)-(r-c))의 규칙

# 말을 놓고 check를 한 다음에, 모두 0인 지점에 말을 놓을 수 있다

# 현재 좌표에 퀸을 놓을 수 있는지 여부 체크
def check(x, y):

    dx = [-1, -1, -1]
    dy = [-1, 0, 1]   # 각각 좌상단, 위쪽, 우상단을 체크함

    for i in range(3):
        for k in range(1, N):   # 현재 check 지점에서 0행/0열/N행/N열까지 체크
            new_x = x + dx[i]*k
            new_y = y + dy[i]*k
            if new_x < 0 or new_x >= N or new_y < 0 or new_y >= N:
                break
            if pan[new_x][new_y] == 1:
                return 0   # 이미 퀸이 놓아져 있어 불가

    return 1   # 퀸을 놓을 수 있다

# 현재 행에서 모든 열에 퀸을 놓는 경우
def DFS(depth):

    global sol, N

    if depth >= N:  # N행이 되면 멈춘다
        sol += 1
        return

    # 기본 check 함수 사용한 for문
    # for i in range(N):  # i는 열에 해당한다
    #     if check(depth, i):   # 현재 행과 열을 check함수로 넘긴다
    #         pan[depth][i] = 1  # 퀸 놓기
    #         DFS(depth+1)   # 다음 행으로 넘어가기
    #         pan[depth][i] = 0  # 아니면 퀸을 빼기

    for i in range(N):
        if chk1[i]:  # 세로 방향 체크
            continue
        if chk2[depth+i]:  # 오른쪽 대각선 방향 체크
            continue
        if chk3[(N-1)-(depth-i)]:  # 왼쪽 대각선 방향 체크
            continue

        chk1[i] = chk2[depth+i] = chk3[(N-1)-(depth-i)] = 1
        DFS(depth+1)
        chk1[i] = chk2[depth+i] = chk3[(N-1)-(depth-i)] = 0

# 백트래킹 - 모든 경우의 수를 구해야 하므로 가지치기가 필요하다
N = int(input())

pan = [[0 for _ in range(N)] for _ in range(N)]

sol = 0

# 개선된 백트래킹 - depth를 찾고 어떤 것을 반복시킬지 고민할 것
chk1 = [0] * N
chk2 = [0] * (2*N)
chk3 = [0] * (2*N)

DFS(0)   # 0행부터 시작

print(sol)


# -*- coding: utf-8 -*-
"""
Created on Mon Aug  5 10:25:02 2019

@author: 10539
"""
'''array'''
def mergelist(l1,l2):
    l1[len(l1):len(l1)+len(l2)]=l2
    return l1.sort()
'''singlelist'''
class Node:
    def __init__(self,val):
        self.val=val
        self.next=None
class singlelist:
    def __init__(self,node=None):
        self._head=node
    def is_empty(self):
        return self._head==None
    def insert(self,pos,elem):
        node=Node(elem)
        if pos<0:
            print("errro")
            return False
        else:
            index=0
            pre=self._head
            while index <(pos-1) and pre!=None:
                pre=pre.next
                index+=1
            node.next=pre.next
            pre.next=node
    def remove(self,elem):
        curr=self._head
        pre=None
        while curr!=None:
            if curr.val==elem:
                if curr==self._head:
                    self._head=curr.next
                else:
                    pre.next=curr.next
                break
            else:
                pre=curr
                curr=curr.next
    def index(self,pos):
        if pos<0:
            print("errro")
            return False
        else:
            index=1
            curr=self._head
            while index <(pos):
                if curr.next!=None:
                    curr=curr.next
                    index+=1
                else:
                    print("over range")
                    return False
        return curr.val
    def inverse(self):
        wareh=list()
        pre=self._head
        while pre!=None:
            wareh.append(pre)
            pre=pre.next
        wareh.reverse()
        i=1
        while i<len(wareh):
            now=wareh(i)
            now.next=wareh(i+1)
        self._head=wareh(1)

'''combine up以单向链表为例,
循环列表记录head作为停止循环条件'''
def merge(l1,l2):
    res=singlelist()
    pre=res._head
    if l1 is None:
        res._head=l2._head
    if l2 is None:
        res._head=l1._head
    curl1=l1._head
    curl2=l2._head
    if curl1.val<curl2.val:
        pre=curl1
        curl1=curl1.next
    else:
        pre=curl2
        curl2=curl2.next
    while curl1!=None and curl2!=None:
        if curl1.val<curl2.val:
            pre.next=curl1
            curl1=curl1.next
        else:
            pre.next=curl2
            curl2=curl2.next
'''circle'''
class circlelist:
    def __init__(self,node=None):
        self._head=node
        if node:
            node.next=node
    def is_empty(self):
        return self._head==None
    def insert(self,pos,elem):
        node=Node(elem)
        if pos<0:
            print("errro")
            return False
        else:
            index=0
            pre=self._head
            while index <(pos-1):
                pre=pre.next
                index+=1
            node.next=pre.next
            pre.next=node
    def remove(self,elem):
        if self.is_empty():
            return
        curr=self._head
        pre=None
        while curr.next!=self._head:
            if curr.val==elem:
                if curr==self._head:
                    rear=self._head
                    while rear.next!=self._head:
                        rear=rear.next
                    self._head=curr.next
                    rear.next=self._head
                else:
                    pre.next=curr.next
                return
            else:
                pre=curr
                curr=curr.next
        if curr.val==elem:
            if curr==self._head:
                self._head=None
            else:
                pre.next=curr.next
    def index(self,pos):
        if pos<0:
            print("errro")
            return False
        else:
            index=1
            curr=self._head
            while index <(pos):
                if curr.next!=self._head:
                    curr=curr.next
                    index+=1
                else:
                    print("over range")
                    return False
        return curr.val


from setuptools import setup, find_packages

def read(filename):
    return [requirement.strip() for requirement in open(filename).readlines()]

setup(
    name="school-system",
    version="0.1.0", # major, minor, patch
    description="a school system API",
    packages=find_packages(),
    include_package_data=True,
    install_requires=read("requirements.txt"),
    extras_require={"dev": read("requirements-dev.txt")}
    )


"""
This exercise stub and the test suite contain several enumerated constants.

Since Python 2 does not have the enum module, the idiomatic way to write
enumerated constants has traditionally been a NAME assigned to an arbitrary,
but unique value. An integer is traditionally used because it’s memory
efficient.
It is a common practice to export both constants and functions that work with
those constants (ex. the constants in the os, subprocess and re modules).

You can learn more here: https://en.wikipedia.org/wiki/Enumerated_type
"""

# Possible sublist categories.
# Change the values as you see fit.
SUBLIST = 1
SUPERLIST = 2
EQUAL = 3
UNEQUAL = 4

def sublist(primera_lista, segunda_lista):
    if len(primera_lista) > len(segunda_lista): return False
    for i in range(len(segunda_lista) - len(primera_lista) + 1):
        if primera_lista == segunda_lista[i:i + len(primera_lista)]:
            return True
    return False

def check_lists(primera_lista, segunda_lista):
    if primera_lista == segunda_lista: return EQUAL
    if sublist(primera_lista, segunda_lista): return SUBLIST
    if sublist(segunda_lista, primera_lista): return SUPERLIST
    return UNEQUAL


"""
CCC '15 J3 - Rövarspråket
Find this problem at:
https://dmoj.ca/problem/ccc15j3
"""

import string

vowels = {'a', 'e', 'i', 'o', 'u'}
alphabet = string.ascii_lowercase
word = list(input())

for idx in range(len(word)):
    if word[idx] not in vowels:
        i = j = alph_num = ord(word[idx]) - 97
        # Get closest vowel
        while True:
            i -= 1
            j += 1
            t = alphabet[i]
            if alphabet[i] in vowels:
                word[idx] += alphabet[i]
                break
            elif j < len(alphabet) and alphabet[j] in vowels:
                word[idx] += alphabet[j]
                break
        # Get next consonant
        if alph_num == len(alphabet) - 1:
            word[idx] += 'z'
        else:
            i = alph_num + 1
            while alphabet[i] in vowels:
                i += 1
            word[idx] += alphabet[i]

print(''.join(word))


class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        stack = []
        for i in range(min(len(word1),len(word2))):
            stack.append(word1[i])
            stack.append(word2[i])

        stack.extend(word1[i+1:])
        stack.extend(word2[i+1:])

        return "".join(stack)


from tkinter import *
from tkinter import ttk
import numpy as np

class Simon(Canvas):

    def homogenize(self,coords: list):
        for i in range(len(coords)):
            coords[i].append(1)
        return coords

    def homogenize2(self, coords: list):
        for i in range(len(coords)):
            coords[i].append(1)

    def dehomogenize(self, coords: list):
        for i in range(len(coords)):
            coords[i][0] = coords[i][0] / coords[i][2]
            coords[i][1] = coords[i][1] / coords[i][2]
            del coords[i][2]

    def gettranslation(self, tx: float, ty: float) -> list:
        return [[1, 0, 0], [0, 1, 0], [tx, ty, 1]]

    def getrotation(self, deg: float) -> list:
        rad = np.radians(deg)
        return [[np.cos(rad), np.sin(rad), 0], [-np.sin(rad), np.cos(rad), 0], [0, 0, 1]]

    def getscaled(self, xscl:float, yscl:float) -> list:
        return [[xscl, 0, 0], [0, yscl, 0], [0, 0, 1]]

    def incresure(self):
        num = int(self.var.get())
        self.var.set(str(num + 10))

    def reset(self):
        self.var.set(0)

    def __init__(self, master=None, **options):
        super().__init__(master, options)
        self.w0 = 350
        self.h0 = 350

        self.lastneedle = None

        self.w = int(self.cget('width'))
        self.h = int(self.cget('height'))

        self.xscl = self.w / self.w0
        self.yscl = self.h / self.h0

        self.scale = self.getscaled(self.xscl, self.yscl)

        biggest_circle = [[5, 5], [345, 345]]
        self.homogenize(biggest_circle)
        biggest_circle=np.dot(biggest_circle,self.scale).tolist()
        self.dehomogenize(biggest_circle)
        self.create_oval(biggest_circle, fill='grey')

        medium_circle = [[10, 10], [340, 340]]
        self.homogenize(medium_circle)
        medium_circle=np.dot(medium_circle,self.scale).tolist()
        self.dehomogenize(medium_circle)
        self.create_oval(medium_circle, fill='black')

        smallest_circle = [[110, 110], [240, 240]]
        self.homogenize(smallest_circle)
        smallest_circle=np.dot(smallest_circle,self.scale).tolist()
        self.dehomogenize(smallest_circle)
        self.create_oval(smallest_circle, fill='silver')

    # Small_concentric_circles

        biggest_concentric_circle1 = [[165, 180], [185, 200]]
        self.homogenize(biggest_concentric_circle1)
        biggest_concentric_circle1=np.dot(biggest_concentric_circle1,self.scale).tolist()
        self.dehomogenize(biggest_concentric_circle1)
        self.create_oval(biggest_concentric_circle1, fill='black')

        smallest_concentric_circle1 = [[167, 182], [183, 198]]
        self.homogenize(smallest_concentric_circle1)
        smallest_concentric_circle1=np.dot(smallest_concentric_circle1,self.scale).tolist()
        self.dehomogenize(smallest_concentric_circle1)
        smallest_concentric_circle1=self.create_oval(smallest_concentric_circle1, fill='red')
        self.tag_bind(smallest_concentric_circle1, "<Button-1>", lambda e: self.reset())

        biggest_concentric_circle2 = [[165 - 35, 180], [185 - 35, 200]]
        self.homogenize(biggest_concentric_circle2)
        biggest_concentric_circle2=np.dot(biggest_concentric_circle2,self.scale).tolist()
        self.dehomogenize(biggest_concentric_circle2)
        self.create_oval(biggest_concentric_circle2, fill='black')

        smallest_concentric_circle2 = [[167 - 35, 182], [183 - 35, 198]]
        self.homogenize(smallest_concentric_circle2)
        smallest_concentric_circle2=np.dot(smallest_concentric_circle2,self.scale).tolist()
        self.dehomogenize(smallest_concentric_circle2)
        self.create_oval(smallest_concentric_circle2, fill='yellow')

        biggest_concentric_circle3 = [[165 + 35, 180], [185 + 35, 200]]
        self.homogenize(biggest_concentric_circle3)
        biggest_concentric_circle3 = np.dot(biggest_concentric_circle3, self.scale).tolist()
        self.dehomogenize(biggest_concentric_circle3)
        self.create_oval(biggest_concentric_circle3, fill='black')

        smallest_concentric_circle3 = [[167 + 35, 182], [183 + 35, 198]]
        self.homogenize(smallest_concentric_circle3)
        smallest_concentric_circle3=np.dot(smallest_concentric_circle3,self.scale).tolist()
        self.dehomogenize(smallest_concentric_circle3)
        self.create_oval(smallest_concentric_circle3, fill='lightblue')

    # Texts
        texto1=[[175, 175]]
        self.homogenize(texto1)
        sca=np.dot(texto1,self.scale).tolist()
        self.dehomogenize(sca)
        self.create_text(sca, text='prefs', font="arial 8")

        texto2 = [[175 - 35, 175]]
        self.homogenize(texto2)
        sca = np.dot(texto2, self.scale).tolist()
        self.dehomogenize(sca)
        self.create_text(sca, text='new', font="arial 8")

        texto3=[[175 + 35, 175]]
        self.homogenize(texto3)
        sca = np.dot(texto3, self.scale).tolist()
        self.dehomogenize(sca)
        self.create_text(sca,text='scores', font="arial 8")

        texto4=[[175, 150]]
        self.homogenize(texto4)
        sca = np.dot(texto4,self.scale).tolist()
        self.dehomogenize(sca)
        self.create_text(sca, text='SIMÓN', font='Arial 23 bold')

    # Diamonds(poligonos)

        points_dia = [[-70, -10], [-150, -10], [-150, -60], [-60, -150], [-10, -150], [-10, -70], [-30, -70], [-70, -30]]
        self.homogenize(points_dia)
        colors = (('green4', 'green3'), ('cyan4', 'cyan3'), ('red4', 'red3'), ('yellow4', 'yellow3'))

        trans = self.gettranslation(175, 175)
        contador = 0

        for rot in range(0, 360, 90):
            rotation = self.getrotation(rot)
            transform = np.dot(rotation, trans).tolist()
            temp = list()
            for i in range(len(points_dia)):
                temp.append(np.dot(points_dia[i], transform).tolist())
                sca = np.dot(temp,self.scale).tolist()
                self.dehomogenize(sca)
            self.dehomogenize(temp)
            dia1 = self.create_polygon(sca, fill=colors[contador][0], activefill=colors[contador][1])
            self.tag_bind(dia1, "<Enter>", lambda e: self.incresure())

            contador += 1

        # Label
        window = [[175, 220]]
        self.homogenize(window)
        sca = np.dot(window,self.scale).tolist()
        self.dehomogenize(sca)
        self.var = IntVar()
        label_score = Label(self, relief='groove', background="black", textvariable=self.var, foreground="red", anchor='e')
        self.create_window(sca, width=60, height=20, window=label_score)

    # funtions


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

import os
import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

MAX_LENGTH = 3
#COLORS = ['magenta', 'red', 'blue', 'yellow', 'cyan', 'green']
#COLORS = ['red', 'blue', 'cyan', 'green']
COLORS = ['red', 'blue', 'green']

class Square(object):
    def __init__(self):
        self.width  = np.random.randint(1, MAX_LENGTH + 1)
        self.height = np.random.randint(1, MAX_LENGTH + 1)
        self.color_id = np.random.choice([_ for _ in range(len(COLORS))])

        self.x = None
        self.y = None

    def set_xy(self, x, y):
        self.x = x; self.y = y

    def add_rectangle_to_ax(self, ax):
        r = patches.Rectangle(xy = (self.x, self.y),
                              width = self.width, height = self.height,
                              edgecolor = 'black',
                              facecolor = COLORS[self.color_id]
                              )
        ax.add_patch(r)

class Squares(object):
    def __init__(self):
        self.__data = []

    def add_square(self):
        self.__data.append(Square())

    def set_xys(self, xys):
        # xys = [(x, y), ....]
        assert(len(xys) == len(self.__data))
        for xy, square in zip(xys, self.__data):
            square.set_xy(xy[0], xy[1])

    def add_rectangles_to_ax(self, ax):
        for square in self.__data:
            square.add_rectangle_to_ax(ax)

    def get_s_id_list_with_c_id(self, c_id):
        ret = []
        for s_id, square in enumerate(self.__data):
            if square.color_id == c_id:
                ret.append(s_id)
        return ret

    def __iter__(self):
        return self.__data.__iter__()

    def __getitem__(self, idx):
        return self.__data[idx]

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

if __name__ == '__main__':

    ss = Squares()
    for _ in range(2):
        ss.add_square()
    ss.set_xys([(10, 10), (20, 20)])

    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)
    ax.set_xlim([-1, 51])
    ax.set_ylim([-1, 51])
    r = patches.Rectangle(xy = (0, 0),
                          width = 50, height = 50,
                          edgecolor = 'black',
                          facecolor = 'white'
    )
    ax.add_patch(r)
    ss.add_rectangles_to_ax(ax)
    plt.savefig('test.png')


from __future__ import print_function, division

from keras.layers import Input, Dense, Flatten, Dropout, Reshape
from keras.layers import BatchNormalization, Activation, Conv2D, Conv2DTranspose
from keras.layers.advanced_activations import LeakyReLU
from keras.models import Model
from keras.optimizers import Adam

from keras.datasets import cifar10
import keras.backend as K

import matplotlib.pyplot as plt
import cv2
import sys
import numpy as np
import os
from sklearn.model_selection import train_test_split

img_data_list=[]
def get_generator(input_layer):

    hid = Dense(128 * 16 * 16, activation='relu')(input_layer)
    hid = BatchNormalization(momentum=0.9)(hid)
    hid = LeakyReLU(alpha=0.1)(hid)
    hid = Reshape((16, 16, 128))(hid)

    hid = Conv2D(128, kernel_size=5, strides=1,padding='same')(hid)
    hid = BatchNormalization(momentum=0.9)(hid)
    #hid = Dropout(0.5)(hid)
    hid = LeakyReLU(alpha=0.1)(hid)

    hid = Conv2DTranspose(128, 4, strides=2, padding='same')(hid)
    hid = BatchNormalization(momentum=0.9)(hid)
    hid = LeakyReLU(alpha=0.1)(hid)

    hid = Conv2D(128, kernel_size=5, strides=1, padding='same')(hid)
    hid = BatchNormalization(momentum=0.9)(hid)
    #hid = Dropout(0.5)(hid)
    hid = LeakyReLU(alpha=0.1)(hid)

    hid = Conv2D(128, kernel_size=5, strides=1, padding='same')(hid)
    hid = BatchNormalization(momentum=0.9)(hid)
    hid = LeakyReLU(alpha=0.1)(hid)

    hid = Conv2D(3, kernel_size=5, strides=1, padding="same")(hid)
    out = Activation("tanh")(hid)

    model = Model(input_layer, out)
    model.summary()

    return model, out

def get_discriminator(input_layer):

#Requires the input layer as input, outputs the model and the final layer

    hid = Conv2D(128, kernel_size=1, strides=1, padding='same')(input_layer)
    hid = BatchNormalization(momentum=0.9)(hid)
    hid = LeakyReLU(alpha=0.1)(hid)

    hid = Conv2D(128, kernel_size=2, strides=2, padding='same')(hid)
    hid = BatchNormalization(momentum=0.9)(hid)
    hid = LeakyReLU(alpha=0.1)(hid)

    hid = Conv2D(128, kernel_size=2, strides=2, padding='same')(hid)
    hid = BatchNormalization(momentum=0.9)(hid)
    hid = LeakyReLU(alpha=0.1)(hid)

    hid = Conv2D(128, kernel_size=2, strides=2, padding='same')(hid)
    hid = BatchNormalization(momentum=0.9)(hid)
    hid = LeakyReLU(alpha=0.1)(hid)

    hid = Flatten()(hid)
    hid = Dropout(0.4)(hid)
    out = Dense(1, activation='sigmoid')(hid)

    model = Model(input_layer, out)

    model.summary()

    return model, out

from keras.preprocessing import image

def load_lfw():
        data_path = './lfw/'
        data_dir_list = os.listdir(data_path)
        label_list_name=[]
        for dataset in data_dir_list:
            img_list = os.listdir(data_path+'/'+ dataset)
            for img in img_list:
                label_list_name.append(dataset)
                input_img=cv2.imread(data_path + '/'+ dataset + '/'+ img )
                input_img_resize=cv2.resize(input_img,(256,256))
                img_data_list.append(input_img_resize)

        img_data = np.asarray(img_data_list)
        img_data = img_data.astype('float32')
        img_data = np.expand_dims(img_data, -1)
        img_data.shape
        return img_data, label_list_name

def load_jaffe():
        data_path = './jaffe/'
        data_dir_list = os.listdir(data_path)
        for dataset in data_dir_list:
            img_list=os.listdir(data_path+'/'+ dataset)
            print ('Loaded the images of dataset-'+'{}\n'.format(dataset))
            for img in img_list:
                input_img=cv2.imread(data_path + '/'+ dataset + '/'+ img )
                input_img=cv2.cvtColor(input_img, cv2.COLOR_BGR2GRAY)
                input_img_resize=cv2.resize(input_img,(256,256))
                img_data_list.append(input_img_resize)

        img_data = np.asarray(img_data_list)
        img_data = img_data.astype('float32')
        img_data = np.expand_dims(img_data, -1)
        img_data.shape

        num_of_samples = img_data.shape[0]
        labels = np.ones((num_of_samples,),dtype='int64')

        labels[0:29]=0 #30
        labels[30:58]=1 #29
        labels[59:90]=2 #32
        labels[91:121]=3 #31
        labels[122:151]=4 #30
        labels[152:182]=5 #31
        labels[183:]=6 #30

        names = ['ANGRY','DISGUST','FEAR','HAPPY','NEUTRAL','SAD','SURPRISE']
        return img_data, labels

def generate_noise(n_samples, noise_dim):
  X = np.random.normal(0, 1, size=(n_samples, noise_dim))
  return X

def show_imgs(batchidx):
  noise = generate_noise(9, 100)
  gen_imgs = generator.predict(noise)

  fig, axs = plt.subplots(3, 3)
  count = 0
  for i in range(3):
    for j in range(3):
      # Dont scale the images back, let keras handle it
      img = image.array_to_img(gen_imgs[count], scale=True)
      axs[i,j].imshow(img)
      axs[i,j].axis('off')
      count += 1
  plt.show()
  plt.close()

# GAN creation
img_input = Input(shape=(256,256,3))
discriminator, disc_out = get_discriminator(img_input)
discriminator.compile(optimizer=Adam(0.0002, 0.5), loss='binary_crossentropy', metrics=['accuracy'])

discriminator.trainable = False

noise_input = Input(shape=(100,))
generator, gen_out = get_generator(noise_input)

gan_input = Input(shape=(100,))
x = generator(gan_input)
gan_out = discriminator(x)
gan = Model(gan_input, gan_out)
gan.summary()

gan.compile(optimizer=Adam(0.0002, 0.5), loss='binary_crossentropy')

BATCH_SIZE = 16

# # Get training images
faces, labels = load_lfw()

X_train, xtest,ytrain,ytest = train_test_split(faces, labels, test_size=0.2,shuffle=True)

X_train = (X_train.astype(np.float32) - 127.5) / 127.5

num_batches = int(BATCH_SIZE / 2)

N_EPOCHS = 50
for epoch in range(N_EPOCHS):

  cum_d_loss = 0.
  cum_g_loss = 0.

  for batch_idx in range(num_batches):
    # Get the next set of real images to be used in this iteration
    images = X_train[batch_idx*BATCH_SIZE : (batch_idx+1)*BATCH_SIZE]

    noise_data = generate_noise(BATCH_SIZE, 100)
    generated_images = generator.predict(noise_data)

    # Train on soft labels (add noise to labels as well)
    noise_prop = 0.05 # Randomly flip 5% of labels

    # Prepare labels for real data
    true_labels = np.zeros((BATCH_SIZE, 1)) + np.random.uniform(low=0.0, high=0.1, size=(BATCH_SIZE, 1))
    flipped_idx = np.random.choice(np.arange(len(true_labels)), size=int(noise_prop*len(true_labels)))
    true_labels[flipped_idx] = 1 - true_labels[flipped_idx]

    # Train discriminator on real data
    d_loss_true = discriminator.train_on_batch(images, true_labels)

    # Prepare labels for generated data
    gene_labels = np.ones((BATCH_SIZE, 1)) - np.random.uniform(low=0.0, high=0.1, size=(BATCH_SIZE, 1))
    flipped_idx = np.random.choice(np.arange(len(gene_labels)), size=int(noise_prop*len(gene_labels)))
    gene_labels[flipped_idx] = 1 - gene_labels[flipped_idx]

    # Train discriminator on generated data
    d_loss_gene = discriminator.train_on_batch(generated_images, gene_labels)

    d_loss = 0.5 * np.add(d_loss_true, d_loss_gene)
    cum_d_loss += d_loss

    # Train generator
    noise_data = generate_noise(BATCH_SIZE, 100)
    g_loss = gan.train_on_batch(noise_data, np.zeros((BATCH_SIZE, 1)))
    cum_g_loss += g_loss

  print('  Epoch: {}, Generator Loss: {}, Discriminator Loss: {}'.format(epoch+1, cum_g_loss/num_batches, cum_d_loss/num_batches))
  show_imgs("epoch" + str(epoch))


'''
============================================================
In computer science, a stack is a particular kind of data type or collection in which the principal operations in the collection are the addition of an entity to the collection (also known as push) and the removal of an entity (also known as pop). The relation between the push and pop operations is such that the stack is a Last-In-First-Out (LIFO) data structure. In a LIFO data structure, the last element added to the structure must be the first one to be removed. Often a peek, or top operation is also implemented, returning the value of the top element without removing it.
We will emulate the stack process with Python. You are given a sequence of commands:
- 'PUSH X' -- add X in the stack, where X is a digit.
- 'POP' -- look and remove the top position. If the stack is empty, then it returns 0 (zero) and does nothing.
- 'PEEK' -- look at the top position. If the stack is empty, then it returns 0 (zero).
The stack can only contain digits.
You should process all commands and sum all digits which were taken from the stack ('PEEK' or 'POP'). Initial value of the sum is 0 (zero).
Let's look at an example, here's the sequence of commands:
['PUSH 3', 'POP', 'POP', 'PUSH 4', 'PEEK', 'PUSH 9', 'PUSH 0', 'PEEK', 'POP', 'PUSH 1', 'PEEK']
Command    Stack    Sum
PUSH 3    3    0
POP        0+3
POP        3+0
PUSH 4    4    3
PEEK    4    3+4
PUSH 9    4,9    7
PUSH 0    4,9,0    7
PEEK    4,9,0    7+0
POP    4,9    7+0
PUSH 1    4,9,1    7
PEEK    4,9,1    7+1=8
Input: A sequence of commands as a list of strings.
Output: The sum of the taken digits as an integer.
Precondition:
0 <= len(commands) <= 20;
all(re.match('\APUSH \d\Z', c) or c == 'POP' or c == 'PEEK' for c in commands)

http://www.checkio.org/mission/digit-stack/

Created on Apr 5, 2015
@author: Oren Livne <livne@uchicago.edu>
============================================================
'''
def digit_stack(commands):
    total, s = 0, []
    for command in commands:
        if command.startswith('PUSH'): s.append(int(command[5:]))
        elif command == 'POP':
            if s: total += s.pop()
        elif command == 'PEEK':
            if s: total += s[-1]
        else: raise ValueError('Unrecognized command: ' % s (command,))
    return total

if __name__ == '__main__':
    # These 'asserts' using only for self-checking and not necessary for auto-testing
    assert digit_stack(['PUSH 3', 'POP', 'POP', 'PUSH 4', 'PEEK',
                        'PUSH 9', 'PUSH 0', 'PEEK', 'POP', 'PUSH 1', 'PEEK']) == 8, 'Example'
    assert digit_stack(['POP', 'POP']) == 0, 'pop, pop, zero'
    assert digit_stack(['PUSH 9', 'PUSH 9', 'POP']) == 9, 'Push the button'
    assert digit_stack([]) == 0, 'Nothing'


from django import forms

class KelasForm(forms.Form):
    nama = forms.CharField(max_length=100)

class MuridForm(forms.Form):
    namadepan = forms.CharField(max_length=100)
    namabelakang = forms.CharField(max_length=100)

class BaseMuridFormSet(forms.formsets.BaseFormSet):

    def clean(self):

        if any(self.errors):
            return

        namadepans = []
        namabelakangs = []
        duplikat = False

        for form in self.forms:
            if form.cleaned_data:
                namadepan = form.cleaned_data['namadepan']
                namabelakang = form.cleaned_data['namabelakang']

                if namadepan:
                    if namadepan in namadepans:
                        duplikat = True
                    namadepans.append(namadepan) #ingat, namadepan untuk satu objek,
                                                                             # namadepans untuk list
                    if namabelakang in namabelakangs:
                        duplikat = True
                    namabelakangs.append(namabelakang)

                if duplikat:
                    raise forms.ValidationError("Nama depan atau belakang terduplikasi",
                                                code="duplikat")

MuridFormSet = forms.formset_factory(MuridForm,
                                     formset  = BaseMuridFormSet)