import numpy as np
from sklearn.dummy import DummyRegressor
import sys
import os

SEP = '.' * 100
LINE = '=' * 100

def testDummyRegressor(case, desc, const, X, y):
    '''
    [Issue #22478]
    Some parameters passed into DummyRegressor are erroneously converted
    into Numpy formart after the fit() method is invoked.
    Source: https://github.com/scikit-learn/scikit-learn/issues/22478
    '''
    print(LINE)
    print(case, ":", desc)
    print(LINE)

    print("Creating a DummyRegressor...")
    regressor = DummyRegressor(constant=const, strategy="constant")
    params = regressor.get_params()
    print("Before fit() Method Invocation:")
    print(" " * 4, "params =", params)
    print(" " * 4, "X =", X)
    print(" " * 4, "y =", y)
    print(SEP)

    regressor.fit(X=X, y=y)
    result = regressor.get_params()
    print("After fit() Method Invocation:")

    print("    Expected:", params)
    print("    Actual:  ", result)
    print(SEP)

    print("Test Results:")

    try:
        assert type(result['constant']) == type(const)
        assert type(result['constant']) != np.ndarray
        print("    [PASS] Test 1: constant is of the expected type.")
    except:
        print("    [FAIL] Test 1: constant should be", type(const), "not", type(result['constant']))

    try:
        assert result == params
        assert result['constant'] == const
        print("    [PASS] Test 2: constant holds the expected value.")
    except:
        print("    [FAIL] Test 2: incorrect value of constant received.")

    print(LINE, '\n' * 2)

def testAll(cases):
    os.system('cls' if os.name == 'nt' else 'clear')
    for case in cases.keys():
        testCase = cases[case]
        desc = testCase['desc']
        const = testCase['args'][0]
        X = testCase['args'][1]
        y = testCase['args'][2]
        testDummyRegressor(case, desc, const, X, y)

testCases = {
    'Test Set 1: 0 Float Constant' : {
        'desc': 'strategy = constant; constant = 0.0',
        'args': [0.0, [[1,1], [2,2], [3,3]], [[0], [0], [0]]]
        },
    'Test Set 2: 0 Integer Constant' : {
        'desc': 'strategy = constant; constant = 0',
        'args': [0, [[1,1], [2,2], [3,3]], [[0], [0], [0]]]
        },
    'Test Set 3: Postive Integer Constant' : {
        'desc': 'strategy = constant; constant = 2',
        'args': [2, [[1,1], [2,2], [3,3]], [[0], [0], [0]]]
        },
    'Test Set 4: Negative Integer Constant' : {
        'desc': 'strategy = constant; constant = -2',
        'args': [-2, [[1,1], [2,2], [3,3]], [[0], [0], [0]]]
        },
    'Test Set 5: Negative Float Constant Part 1' : {
        'desc': 'strategy = constant; constant = -3.14',
        'args': [-3.14, [[1,1], [2,2], [3,3]], [[0], [0], [0]]]
        },
    'Test Set 6: Negative Float Constant Part 2' : {
        'desc': 'strategy = constant; constant = -3.14',
        'args': [-3.14, [[1,2], [2,1], [3,1]], [[3], [1], [4]]]
        },
    'Test Set 7: Large Positive Float Constant' : {
        'desc': 'strategy = constant; constant = sys.float_info.max',
        'args': [sys.float_info.max, [[1,2], [2,1], [3,1]], [[3], [1], [4]]]
        },
    'Test Set 8: Large Negative Float Constant' : {
        'desc': 'strategy = constant; constant = -sys.float_info.max',
        'args': [-sys.float_info.max, [[1,2], [2,1], [3,1]], [[3], [1], [4]]]
        },
    'Test Set 9: Small Positive Float Constant' : {
        'desc': 'strategy = constant; constant = sys.float_info.min',
        'args': [sys.float_info.min, [[1,2], [2,1], [3,1]], [[3], [1], [4]]]
        },
    'Test Set 10: Small Negative Float Constant' : {
        'desc': 'strategy = constant; constant = -sys.float_info.min',
        'args': [-sys.float_info.min, [[1,2], [2,1], [3,1]], [[3], [1], [4]]]
        }
}

testAll(testCases)


import os
import argparse
from fm_index import FMIndex
from util import save_pickle, load_pickle, load_files, get_file_name_via_index
from flask import Flask, render_template, request, redirect, url_for

parser = argparse.ArgumentParser()
parser.add_argument('--f', type=str, metavar='PATH', help='text file')
parser.add_argument('--dir', type=str, metavar='PATH', help='text dir')
parser.add_argument('--dict', type=str, metavar='PATH', help='dict file')
parser.add_argument('--t', type=str, help='raw text')
parser.add_argument('--s', type=str, help='search text')
parser.add_argument('--d', type=str, metavar='PATH', help='dict file')
args = parser.parse_args()
app = Flask(__name__)

T, fmi, db = None, None, None

@app.route('/', methods=['GET'])
def index():
    if request.method == 'GET':
        # message = 'hi'
        pat = request.args.get('keyword')
        # request.form['keyword'])
        # return render_template('index.html', message=message)

        if pat:
            # pat = request.form['keyword']
            # pat = '日本の'
            match = fmi.search(pat)
            print('Results of search("{}")'.format(pat))
            print('match', match)
            rng = 15
            results = []
            for i, m in enumerate(match):
                beg = m[0]
                end = m[1]
                # print('(beg, end) = ({}, {})'.format(beg, end))
                f_name = get_file_name_via_index(db, beg)
                print('{} [{}]: ({}, {})'.format(i, f_name, beg, end))
                # print('---{}"{}"{}---'.format(dec[beg-rng: beg], dec[beg:end], dec[end:end+rng]))
                print('---{}"{}"{}---'.format(T[beg-rng: beg], T[beg:end], T[end:end+rng]))
                v = '{}{}{}'.format(T[beg-rng: beg], T[beg:end], T[end:end+rng])
                results.append((f_name, v))
                # print(decoded[m[0]:])
            return render_template('index.html', results=results)
        else:
            return render_template('index.html')
    else:
        # エラーなどでリダイレクトしたい場合はこんな感じで
        return redirect(url_for('index'))

def load_database():
    global T, fmi, db
    pat = args.s
    if args.dir is not None:
        T, db = load_files(args.dir)
        print('db', db)
        # print(T[:1000])
    elif args.f is not None:
        db = []
        with open(args.f, 'r') as f:
            T = ''.join(f.readlines())
            db.append((args.f, len(T)))
    else:
        T = args.t

    fmi = FMIndex()
    if args.dict and os.path.isfile(args.dict):
        saved_data = load_pickle(args.dict)
        bw = saved_data['bwt']
        fmi.set_dict(saved_data)
    else:
        print('encode text...')
        bw, sa = fmi.encode(T)
        ranks, ch_count = fmi.rank_bwt(bw)
        save_pickle({'bwt': bw, 'sa': sa, 'text_len': len(T), 'ch_count': ch_count}, 'index.dict')
        fmi.ch_count = ch_count
        print('encode done!')
    return
    # return T, fmi
    # print('decoding...')
    # dec = fmi.decode(bw)
    # print('decoding done')
    match = fmi.search(pat)
    print('Results of search("{}")'.format(pat))
    print('match', match)
    rng = 5
    for i, m in enumerate(match):
        beg = m[0]
        end = m[1]
        # print('(beg, end) = ({}, {})'.format(beg, end))
        f_name = get_file_name_via_index(db, beg)
        print('{} [{}]: ({}, {})'.format(i, f_name, beg, end))
        # print('---{}"{}"{}---'.format(dec[beg-rng: beg], dec[beg:end], dec[end:end+rng]))
        print('---{}"{}"{}---'.format(T[beg-rng: beg], T[beg:end], T[end:end+rng]))
        # print(decoded[m[0]:])

if __name__ == '__main__':
    load_database()
    app.debug = True
    app.run(host='0.0.0.0')


import discord
from data import settings
from discord.ext import commands
from datetime import datetime
from modules.storage import info, cargos

class Info(commands.Cog, name='Informativo', description='''Comandos de informações gerais sobre o nosso servidor.'''):

    def __init__(self, client):
        self.client = client

    @commands.command(aliases=['servidor'], help='Exibe informações sobre o servidor do Discord.', usage=f'{settings.bot_prefix}server')
    @commands.guild_only()
    async def server(self, ctx):
        embed=discord.Embed(color=info.welcome_colour, description='Informações sobre este servidor:')
        embed.set_author(name=ctx.guild.name, url=settings.url, icon_url=ctx.guild.icon.url)
        embed.set_footer(text=f'Informações requisitadas por {ctx.author}. | Data: {datetime.now().strftime("às %H:%M:%S em %d/%m/%Y")}', icon_url=ctx.author.avatar.url)
        if ctx.guild.banner:
            embed.set_thumbnail(ctx.guild.banner.url)
        embed.add_field(name='Dono do servidor:', value=ctx.guild.owner, inline=False)
        embed.add_field(name='Data de criação do servidor:', value=ctx.guild.created_at.__format__("às %H:%M:%S em %d/%m/%Y"), inline=False)
        embed.add_field(name='Contagem de membros:', value=ctx.guild.member_count, inline=False)
        embed.add_field(name='Região do servidor:', value=ctx.guild.region, inline=False)
        embed.add_field(name='Canal de regras:', value=ctx.guild.rules_channel.mention, inline=False)
        embed.add_field(name='Canal de avisos públicos:', value=ctx.guild.public_updates_channel.mention, inline=False)
        embed.add_field(name='Contagem de boosts:', value=len(ctx.guild.premium_subscribers), inline=False)
        embed.add_field(name='Cargo intrínseco ao bot:', value=ctx.guild.self_role.mention, inline=False)
        #embed.add_field(name=':', value=ctx.guild., inline=False)
        #embed.add_field(name=':', value=ctx.guild., inline=False)
        await ctx.send(embed=embed)

    @commands.command(aliases=['pfp', 'foto'], help='Envia a foto de perfil de um usuário.', usage=f'{settings.bot_prefix}avatar *@membro*')
    @commands.guild_only()
    @commands.has_any_role(cargos.member_role_id)
    async def avatar(self, ctx, member:discord.Member=None):
        if not member:
            member = ctx.author
        user = await self.client.fetch_user(member.id)
        if user.accent_color:
            embed=discord.Embed(color=user.accent_color.value, description=f'Comando de avatar requisitado por {ctx.author.mention}')
        else:
            embed=discord.Embed(color=info.welcome_colour, description=f'Comando de avatar requisitado por {ctx.author.mention}')
        embed.set_author(name=f'Avatar de {user}', url=ctx.author.avatar.url)
        embed.set_image(url=user.avatar.url)
        embed.set_footer(text=ctx.guild.name, icon_url=ctx.guild.icon.url)
        await ctx.reply(embed=embed)

    @commands.command(aliases=['perfil', 'conta', 'sobre'], help='Exibe informações gerais sobre o membro mencionado.', usage=f'{settings.bot_prefix}')
    @commands.guild_only()
    @commands.has_any_role(cargos.member_role_id)
    async def profile(self, ctx, member:discord.Member=None):
        if not member:
            member = ctx.author
        user = await self.client.fetch_user(member.id)
        if user.accent_color:
            embed=discord.Embed(color=user.accent_color.value, description=f'Comando requisitado por {ctx.author.mention}:')
        else:
            embed=discord.Embed(color=info.rules_colour, description='Comando de informação de usuários:')
        embed.set_author(name=f'Dados da conta do Discord de {user}', url=settings.url, icon_url=member.avatar.url)
        embed.set_thumbnail(url=user.avatar.url)
        if user.banner:
            embed.set_image(url=user.banner.url)
        embed.set_footer(text=ctx.guild.name, icon_url=ctx.author.avatar.url)
        embed.add_field(name='Nome e discriminador:', value=user, inline=False)
        embed.add_field(name='ID da conta:', value=user.id, inline=False)
        embed.add_field(name='Data de criação da conta:', value=user.created_at.strftime("às %H:%M:%S em %d/%m/%Y"), inline=False)
        embed.add_field(name='Data de entrada neste servidor:', value=member.joined_at.strftime("às %H:%M:%S em %d/%m/%Y"), inline=False)
        isbot = 'Não'
        if user.bot:
            isbot = 'Sim'
        embed.add_field(name='É um bot?', value=isbot)
        embed.add_field(name='Cargos:', value=', '.join(map(str,member.roles)), inline=False)
        embed.add_field(name='Cargo mais alto na hierarquia:', value=member.top_role.mention)
        if member.premium_since:
            embed.add_field(name='Dá boost no servidor desde:', value=member.premium_since.strftime("às %H:%M:%S em %d/%m/%Y"))
        await ctx.send(embed=embed)

def setup(client):
    client.add_cog(Info(client))


from tkinter import Tk, StringVar, Spinbox

class EntryWidgets:

    def __init__(self, master):

        self.master = master
        master.title("Entering single-line text with the Entry Widget")

        self.month = StringVar()
        self.combobox = Combobox(master, textvariable= self.month)
        self.combobox.pack()

root = Tk()
my_gui = EntryWidgets(root)
root.mainloop()


import numpy as np

from ..util import exec_model_test

# 紧凑关联识别
def recog_compact(X, y, features_rank, model, n_features_lst, S_pre: set, metric: str="r2",
                  rounds: int=3):
    """从CMIM-GIEF所得features_rank中识别出y的紧凑关联变量, 返回其在X中的编号表

    :param X: X数组, np.ndarray
    :param y: y数组, np.ndarray
    :param features_rank: CMIM-GIEF所得特征排序表, list
    :param model: 用于进行FIMT测试的机器学习模型
    :param n_features_lst: 用于FIMT测试的特征数列表
    :param S_pre: 在X中已被事先选中的特征集, set
    :param metric: 模型评估指标, str, defaults to "r2"
    :param rounds: 每个特征集合上重复评估的轮数, defaults to 3
    """

    # 当前仅支持基于决定系数的判断
    if metric != "r2":
        raise ValueError(f"unsupported metric {metric}")

    if S_pre:
        init_value = exec_model_test(X[:, list(S_pre)], y, model, metric=metric, rounds=rounds)[0]
    else:
        init_value = 0.0  # 仅考虑已选特征所得模型分数

    # FIMT测试
    fimt_values = []
    for n_features in n_features_lst:
        S = list(S_pre) + features_rank[:n_features]
        fimt_values.append(exec_model_test(X[:, S], y, model, metric=metric, rounds=rounds)[0])

    # 截断点判断
    max_value = np.max(fimt_values)

    # 如果FIMT测试最大值不高于已选特征集对应的初始值, 则不新选入
    best_n_features = 0
    if max_value - init_value >= 0.01:
        for i, n_features in enumerate(n_features_lst):
            if fimt_values[i] > max_value - 0.01:
                best_n_features = n_features
                break

    # 新识别出的紧凑变量在X所有特征中的序号
    features_compact = features_rank[:best_n_features]
    return features_compact, fimt_values


import os
import sys
import re
import random
sys.path.append("../xre")
import xre

class ko_chat_style_transfer():

    def __init__(self, lex_dict, xre_dict, verbose):
        self.lex_dict = {}
        self.xre_dict = xre.read(xre_dict)
        self.verbose = verbose

        self.re_token = re.compile("[가-힣]+")

    def transfer(self, line):
        k = 0
        ls = []
        out = line

        for m in self.re_token.finditer(line):
            w, i, j = m.group(), m.start(), m.end()
            cands = [(w, [])]

            if w in self.lex_dict:
                for y, r in self.lex_dict[w]:
                    cands.append((y, [r]))

            for pt in self.xre_dict:
                for x, rs in list(cands):
                    if not pt.search(x):
                        continue
                    for y, r in self.xre_dict[pt]:
                        cands.append((xre.sub(pt, y, x), rs + [r]))

            if len(cands) > 1:
                ys = [y for y, _ in cands]
                y, rs = random.choice(cands[1:])
                ls.append((w, y, rs, ys))
                out = out[:i + k] + y + out[j + k:]
                k += len(y) - (j - i)

        return line, out, ls

    def print(self, line, out, ls, op):

        if op == "all" \
        or op == "diff" and line != out \
        or op == "same" and line == out:
            print(out, end = "")

        if self.verbose:
            i = 0
            for w, y, rs, ys in ls:
                if w == y:
                    continue
                print(f"[{i}]", ys)
                print("->", (w, y))
                for j, r in enumerate(rs):
                    print(f"   [{j}]", *r.split("\t"))
                print()
                i += 1

if __name__ == "__main__":

    if len(sys.argv) not in (2, 3):
        sys.exit("Usage: %s all|diff|same [-v] < txt" % sys.argv[0])

    op = sys.argv[1]
    path = (os.path.dirname(__file__) or ".") + "/"
    tst = ko_chat_style_transfer(
        lex_dict = "",
        xre_dict = path + "ko_chat_style_transfer.xre",
        verbose = (len(sys.argv) == 3 and sys.argv[2] == "-v")
    )

    for line in sys.stdin:
        tst.print(*tst.transfer(line), op)


from evolucao import Evolucao
from matplotlib import pyplot as plt

geracoes = 70
volume_maximo = 3
taxa_mutacao = 0.05
numero_de_cromossomos = 112
volumes_e_precos = [
    [0.635, 849],
    [0.527, 3999],
    [0.751, 999.9],
    [0.00350, 2499],
    [0.496, 199.90],
    [0.0319, 299.29],
    [0.400, 4346.99],
    [0.290, 3999.90],
    [0.200, 2999.90],
    [0.0424, 308.66],
    [0.0544, 429.90],
    [0.870, 1199.89],
    [0.498, 1999.90],
    [0.0000899, 2199.12],
]

evolucao = Evolucao(
    geracoes=geracoes,
    volume_maximo=volume_maximo,
    taxa_mutacao=taxa_mutacao,
    volumes_e_precos=volumes_e_precos,
    numero_de_cromossomos=numero_de_cromossomos,
)

populacao = evolucao.criar_populacao()
historico_de_fitness = [evolucao.media_fitness(populacao)]

for _ in range(geracoes):
    populacao = evolucao.evoluir(
        populacao,
    )
    historico_de_fitness.append(evolucao.media_fitness(populacao))

print("\nSuguestões de boas soluções:")
for index in range(5):
    print(populacao[index])

plt.plot(range(len(historico_de_fitness)), historico_de_fitness)
plt.grid(True, zorder=0)
plt.xlabel("Gerações")
plt.ylabel("Preços médios do caminhão")
plt.show()


#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author : haymai

"""
 你想在类被定义的时候就初始化一部分类的成员，而不是要等到实例被创建后。

"""

# 在类定义时就执行初始化或设置操作是元类的一个典型应用场景。本质上讲，一个
# 元类会在定义时被触发，这时候你可以执行一些额外的操作。

import operator

class StructTupleMeta(type):
    def __init__(cls, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for n, name in enumerate(cls._fields):
            setattr(cls, name, property(operator.itemgetter(n)))

class StructTuple(tuple, metaclass=StructTupleMeta):
    _fields = []

    def __new__(cls, *args):
        if len(args) != len(cls._fields):
            raise ValueError('{} arguments required'.format(len(cls._fields)))
        return super().__new__(cls, args)

# 这段代码可以用来定义简单的基于元组的数据结构，如下所示：

class Stock(StructTuple):
    _fields = ['name', 'shares', 'price']

class Point(StructTuple):
    _fields = ['x', 'y']

if __name__ == '__main__':
    s = Stock('ACME', 50, 91.1)
    print(s)

    print(s[0])
    print(s.name)
    print(s.shares * s.price)
    # s.shares = 23


import gym
import time
import numpy as np
import sklearn.neural_network as nn

class Agent(object):
    '''
    '''
    def __init__(self, env=None, hidden_sizes=[20, 20]):
        '''
        '''
        self.env = env
        self.hidden_sizes = hidden_sizes
        self.n_actions = env.action_space.n
        self.actions = range(env.action_space.n)
        self.policy = self.init_policy()

    def init_policy(self, ):
        '''
        '''
        policy = nn.MLPClassifier(hidden_layer_sizes=self.hidden_sizes, activation='tanh')
        policy.partial_fit([self.env.reset()] * self.n_actions, range(self.n_actions), range(self.n_actions))
        print('---init MLP done---')
        return policy

    def action(self, state):
        '''
        '''
        probs = self.policy.predict_proba(state)
        a = np.random.choice(self.actions, p=probs[0])

        return probs

    def action_probs(self, state):
        '''
        '''
        probs = self.policy.predict_proba(state)
        return probs

class Solver(object):
    '''
    '''
    def __init__(self, env, agent, batches=100, epoches=10, percentile=50):
        '''
        '''
        self.env = env
        self.agent = agent
        self.batches = batches
        self.epoches = epoches
        self.percentile = percentile
        self.actions = range(self.env.action_space.n)

    def train(self, ):
        '''
        '''
        tic = time.time()
        for _ in range(self.epoches):
            states, actions, _rewards = self.generate_train_data(batches=self.batches)
            self.agent.policy.partial_fit(states, actions, self.actions)

            print(np.mean(_rewards))

            if np.mean(_rewards) > 200:
                print('---Done--Using {} s-'.format(time.time() - tic))
                break

        return self.agent.policy

    def generate_session(self, t_max=1000):
        '''
        '''
        states = []
        actions = []
        rewards = 0.

        s = env.reset()

        for _ in range(t_max):

            probs = self.agent.action_probs([s, ])[0]
            a = np.random.choice(self.actions, p=probs)
            s_next, r, done, _ = self.env.step(a)

            states.append(s)
            actions.append(a)
            rewards += r

            s = s_next

            if done:
                break

        return states, actions, rewards

    def select_elites(self, states, actions, rewards):
        '''
        '''
        # states, actions, rewards = map(np.array, [states, actions, rewards])
        # print(states.shape)
        # print(actions.shape)
        r_threshold = np.percentile(rewards, q=self.percentile)
        idx = (np.array(rewards) >= r_threshold).nonzero()[0]
        elite_states = [s for i in idx for s in states[i]]
        elite_actions = [a for i in idx for a in actions[i]]

        return np.array(elite_states), np.array(elite_actions), np.array(rewards)

    def generate_train_data(self, batches=1):
        '''
        '''
        states, actions, rewards = zip(*[self.generate_session() for _ in range(batches)])
        states, actions, _rewards = self.select_elites(states, actions, rewards)

        return states, actions, _rewards

if __name__ == '__main__':

    env = gym.make('CartPole-v0').env
    # obs0 = env.reset()
    # print(env.action_space.n)
    # print(env.observation_space.shape)
    # print(type(obs0), obs0.shape)

    agent = Agent(env=env)
    # probs = agent.action([obs0, env.reset()])
    # print(probs.shape)
    # print(probs.dtype)
    # print(probs[0])

    solver = Solver(env, agent, percentile=50, epoches=100)
    # sss, ass, rss = solver.generate_train_data(batches=10)
    # print(sss.shape, sss.dtype)
    # print(ass.shape, ass.dtype)
    # print(rss.shape, rss.dtype)

    solver.train()


import wave, struct, math, subprocess, platform
import matplotlib.pyplot as plot

# print params of a .wav file
def show_info(fname):
    obj = wave.open(fname)
    print( "Number of channels",obj.getnchannels())
    print ( "Sample width",obj.getsampwidth())
    print ( "Frame rate.",obj.getframerate())
    print ("Number of frames",obj.getnframes())
    print ( "parameters:",obj.getparams())
    obj.close()

def nframes(fname):
    obj = wave.open(fname)
    return obj.getnframes()

# draw a graph of the first N frames of a .wav file
def graph_wav(fname, nframes):
    obj = wave.open(fname)
    x = obj.readframes(nframes)
    obj.close()
    #print(len(x))
    y = struct.unpack("%dh"%(nframes*2), x)
    y1 = [0]*nframes
    y2 = [0]*nframes
    for i in range(nframes):
        y1[i] = y[i*2]
        y2[i] = y[i*2+1]
    plot.rcParams['figure.figsize'] = (12,8)
    plot.plot(range(nframes), y1, label='L')
    plot.plot(range(nframes), y2, label='R')
    plot.show()

# graph a position array
def graph_pos(pos_array):
    nframes = len(pos_array)
    plot.rcParams['figure.figsize'] = (12,8)
    plot.plot(range(nframes), pos_array)
    plot.show()

# read .wav file as array of floats
def read_wav(fname):
    f = wave.open(fname)
    nsamples = f.getnframes()*2
    samples = [0.]*nsamples
    buf_frames = 10000
    ns = 0
    while True:
        x = f.readframes(buf_frames)
        nbytes = len(x)
        if nbytes == 0: break
        buf_nsamples = nbytes//2
        s = struct.unpack("%dh"%(buf_nsamples), x)
        for i in range(buf_nsamples):
            a = float(s[i])
            samples[ns] = a
            ns += 1
    print('read',nsamples//2,'frames from', fname)
    return samples

# write array of floats as .wav file
def write_wav(fname, samples):
    f = wave.open(fname, 'wb')
    f.setnchannels(2)
    f.setsampwidth(2)
    f.setframerate(44100)
    buf_nsamples = 10000
    nsamples = len(samples)
    nwritten = 0
    while nwritten < nsamples:
        ns = buf_nsamples
        if nwritten + ns > nsamples:
            ns = nsamples-nwritten
        isamples = [0]*ns
        for i in range(ns):
            isamples[i] = int(samples[nwritten+i])
        x = struct.pack("%dh"%(ns), *isamples)
        f.writeframes(x)
        nwritten += ns
    print('wrote',nsamples//2,'frames to',fname)

# create a zero signal of given length
def zero_signal_t(dur, framerate):
    nsamples = math.ceil(2*dur*framerate)
    return [0]*nsamples

def zero_signal_ns(nsamples):
    return [0]*nsamples

# scale signal
def scale(samples, gain):
    for i in range(len(samples)):
        samples[i] *= gain

# add the input signal "isig" to the output signal "osig",
# panning it according to the array pos: 0..1
# "ang" is the separation (0..1) between the input chans.
# if 0, the channels are summed (mono)
def pan_signal(isig, framerate, ang, pos_array, osig):
    inframes = len(isig)//2
    pnframes = len(pos_array)
    print('pan_signal; input %d frames, pos_array %d frames'%(inframes, pnframes))
    for i in range(inframes):
        a = isig[i*2]
        b = isig[i*2+1]
        if i < pnframes:
            p = pos_array[i]
        else:
            p = pos_array[pnframes-1]
        if ang == 0:
            avg = (a+b)/2
            pp = p*math.pi/2
            osig[i*2] += avg*math.cos(pp)
            osig[i*2+1] += avg*math.sin(pp)
        else:
            p0 = max(p-ang, 0)*math.pi/2
            p1 = min(p+ang, 1)*math.pi/2
            osig[i*2] += a*math.cos(p0)
            osig[i*2+1] += a*math.sin(p0)
            osig[i*2] += b*math.cos(p1)
            osig[i*2+1] += b*math.sin(p1)

def play_wav(fname):
    s = platform.system()
    if s == 'Windows':
        prog = "C:\Program Files (x86)\Windows Media Player/wmplayer.exe"
        cmd = '"%s" %%cd%%/%s'%(prog, fname)
            # wmplayer requires full path
    else:
        raise Exception("OS not supported")

    print(cmd)
    subprocess.call(cmd, shell=True)

play_wav("data/pan_test.wav")


from expert.models import Region, Area, City
from django.core.management.base import BaseCommand, CommandParser
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
import ast
from django.db.models import Q
from Levenshtein import distance

class Command(BaseCommand):
    help = "Команда для добавления населённых пунтов в базу данных"

    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument(
            "filepath",
            type=str,
            help="Путь к файлу"
        )

    def handle(self, *args, **options):
        path = options["filepath"]
        with open(f'{path}') as file:
            citys = file.readlines()[0]
        locations = ast.literal_eval("[" + citys + "]")[0]
        trable = []
        for location in locations:
            try:
                regions = Region.objects.filter(name__icontains=location[0])
                if len(regions)>1:
                    region = min(regions, key=lambda r: distance(location[0], r.name), default=None)
                else:
                    region = regions.first()

                areas = Area.objects.filter(Q(name__icontains=location[1]) & Q(region=region))
                if len(areas)>1:
                    area = min(areas, key=lambda area: abs(len(area.name) - len(location[1])), default=None)
                else:
                    area = areas.first()

                City.objects.get_or_create(
                    name=location[2],
                    region=region,
                    area=area
                )

            except (ObjectDoesNotExist, MultipleObjectsReturned, IndexError) as e:
                try:
                    print(region, area, location[2])
                    trable.append([location[0], location[1], location[2]])
                except:
                    pass

        with open('trable.txt', 'w') as file:
            file.write(str(trable))


"""
"Adaptive Binning" algorithm by Nguyen and O'Connor
(Algorithm 1)  https://arxiv.org/pdf/1508.05154.pdf

Author: Katie Keith
2020-09-13
"""
import numpy as np
from collections import defaultdict, Counter

def sort_pairs(pred_label_pairs):
    """
    Input
        pred_label_pairs: list of tuples

    Sorts by first element of the tuple, returns in assending order
    """
    return sorted(pred_label_pairs, key=lambda x: x[0])

def assign_bin_labels(sorted_pred_label_pairs, beta):
    """
    b_k = floor((k-1)/beta)+ 1
    """

    #k = pair label
    pair_label2bin_label = {}
    for pair_label, _ in enumerate(sorted_pred_label_pairs):
        k = pair_label + 1 #their k starts at 1
        bin_label = np.floor((k-1)/beta)+ 1
        pair_label2bin_label[pair_label] = int(bin_label)

    return pair_label2bin_label

def define_bins(pair_label2bin_label, beta):
    bin2pairs = defaultdict(list)
    for pair_label, bin_label in pair_label2bin_label.items():
        bin2pairs[bin_label].append(pair_label)

    #from algorithm: If the last bin has size less than β, merge it with the second-to-last bin (if one exists).
    bin2pairs = dict(bin2pairs)
    last_bin = len(bin2pairs)
    last_bin_pairs = bin2pairs[last_bin]
    len_last_bin = len(last_bin_pairs)
    if bin2pairs.get(last_bin-1) != None:
        if len_last_bin < beta:
            bin2pairs[last_bin-1] = bin2pairs[last_bin-1] + last_bin_pairs
            del bin2pairs[last_bin]
    return bin2pairs

def calc_per_bin_probs(bin2pairs, sorted_pred_label_pairs):
    q_i_hat_list = []
    p_i_hat_list = []

    for bbin, pairs in bin2pairs.items():
        p_list = []
        q_list = []
        for pair_indx in pairs:
            q, p = sorted_pred_label_pairs[pair_indx]
            q_list.append(q)
            p_list.append(p)

        #calculate hat_{q_i}
        q_hat = np.mean(np.array(q_list))
        q_i_hat_list.append(q_hat)

        #calculate \hat_{p_i}
        p_hat = np.mean(np.array(p_list))
        p_i_hat_list.append(p_hat)
    return q_i_hat_list, p_i_hat_list

def calc_calib_error(q_i_hat_list, p_i_hat_list, bin2pairs, N):
    assert len(q_i_hat_list) == len(p_i_hat_list) == len(bin2pairs)

    ssum = 0
    for i, (q_i, p_i) in enumerate(zip(q_i_hat_list, p_i_hat_list)):
        len_b_i = len(bin2pairs[i+1])
        squared_term = (q_i - p_i)**2
        ssum+= len_b_i * squared_term

    calib_error = np.sqrt(1/N*ssum)
    return calib_error

def graph_calibration_curve(q_i_hat_list, p_i_hat_list):
	import matplotlib.pyplot as plt
	fig, ax = plt.subplots()
	plt.plot(p_i_hat_list, q_i_hat_list)
	plt.scatter(p_i_hat_list, q_i_hat_list)
	plt.xlim(0, 1)
	plt.ylim(0, 1)
	plt.xlabel('Prediction Strength')
	plt.ylabel('Empirical Frequency')
	plt.title("Calibration curve")

	#plot y=x line
	lims = [
	    np.min([ax.get_xlim(), ax.get_ylim()]),  # min of both axes
	    np.max([ax.get_xlim(), ax.get_ylim()]),  # max of both axes
	]
	ax.plot(lims, lims, 'k-', alpha=0.75, zorder=0)
	ax.set_aspect('equal')

	plt.show()
	return plt

def create_pred_label_pairs(q_list, y_list):
    """
    - Use the model to predict given the docids

    Returns:
     [(q_i, y_i), ...]
         - where q_i = probability out of logreg
         - y_i = "true" label averaged over multiple annotators
    """
    pred_label_pairs = [(q, y) for q, y in zip(q_list, y_list)]
    return pred_label_pairs

def mean_calib_error_over_bins(q_list, y_list, calib_bin_range):
	pred_label_pairs = create_pred_label_pairs(q_list, y_list)

	all_calib_error = []
	print("num_bins", "beta", "calib_error")
	print("==="*10)
	for num_bins in calib_bin_range: #TODO, automate this list
	    beta = int(np.round(len(y_list)/num_bins))
	    calib_error = adaptive_binning_algo(list(pred_label_pairs), beta, output_q_y_est=False)
	    print(num_bins, beta, calib_error)
	    all_calib_error.append(calib_error)
	all_calib_error = np.array(all_calib_error)
	print()
	mn = np.mean(all_calib_error)
	print('mean calib error=', mn)
	print('std calib error=', np.std(all_calib_error))
	return mn

def adaptive_binning_algo(pred_label_pairs, beta, output_q_y_est=True):
    """
    Inputs:
    	pred_label_pairs: (list of tuples)

    		Example:
    			[(q_1, y_1), (q_2, y_2), ... (q_n, y_n)]
    		Where q is the predicted probability and y is the label

    	beta : (int) target bin size (i.e. number of documents in a bin)

    Output:
    	q_i_hat_list : (list of floats) each entry is the average predicted probabilities per bin
    		length = number of bins

    	p_i_hat_list : (list of floats) each entry is the average empirical probabilites per bin
    		length = number of bins

    	calib_error : (float) The calibration error (root mean squared error per bin)
    	len_B_i     : (list of floats) each entry is the number of samples in a bin
    		length = number of bins

    """
    N = len(pred_label_pairs)

    #Step 1: Sort pairs by prediction values qk in ascending order
    sorted_pred_label_pairs = sort_pairs(pred_label_pairs)

    #Step 2: For each, asign bin label
    pair_label2bin_label = assign_bin_labels(sorted_pred_label_pairs, beta)

    #Step 3: Define bins
    bin2pairs = define_bins(pair_label2bin_label, beta)

    #Step 4: Calculate the empirical and predicted probabilities per bin
    q_i_hat_list, p_i_hat_list = calc_per_bin_probs(bin2pairs, sorted_pred_label_pairs)

    #Step 5: Calculate calibration error
    calib_error = calc_calib_error(q_i_hat_list, p_i_hat_list, bin2pairs, N)
    len_B_i = [len(bin2pairs[i+1]) for i in range(len(q_i_hat_list))]

    if output_q_y_est:
    	return q_i_hat_list, p_i_hat_list, len_B_i, calib_error
    else:
    	return calib_error, len_B_i

def calib_error_score(y_true, y_pred, NUM_BINS=10, output_q_y_est=False):
	"""
	Scorer for sklearn
		See https://scikit-learn.org/stable/modules/model_evaluation.html#scoring
	"""
	pred_label_pairs = create_pred_label_pairs(y_pred, y_true)
	beta = np.round(len(y_true)/NUM_BINS)
	return adaptive_binning_algo(pred_label_pairs, beta, output_q_y_est)

def draw_samples_for_caliberation(NUM_BINS, NUM_SAMPLES, p_i_hat_list, q_i_hat_list, sigma_hat_list):
    '''Estimate caliberation error with 95% confidence interval'''
    CalibErr = []
    for s in range(NUM_SAMPLES):
        s_i_hat_list = []
        for j in range(NUM_BINS):
            p_s = np.random.normal(p_i_hat_list[j], np.sqrt(sigma_hat_list[j]))
            p_s = min(1, max(0, p_s))
            s_i_hat_list.append(p_s)
        calib_error, len_B_i = calib_error_score(s_i_hat_list, q_i_hat_list, NUM_BINS=NUM_BINS, output_q_y_est=False)
        CalibErr.append(calib_error)
    return CalibErr


from telegram import (
    InlineKeyboardButton,
    InlineKeyboardMarkup,
    ReplyKeyboardMarkup,
    ParseMode
)

from db import get_menu, get_dish

from glob import glob

FIRST, SECOND, THIRD, FOURTH = range(4)

MENU = ['hot_dishes', 'soup', 'pizza', 'drinks']

HOT_DISHES, SOUP, PIZZA, DRINKS = (
    'Горячие блюда',
    'Супы',
    'Пицца',
    'Напитки'
)

BACK, ADD_TO_SHOPPING_CART, REMOVE_FROM_SHOPPING_CART, MY_SHOPPING_CART, MAKE_ORDER = (
    'Назад',
    'Добавить в корзину',
    'Удалить',
    'Моя корзина',
    'Оформить заказ'
    )

INCREASE, DECREASE = (
    '▲',
    '▼'
)

KEYBOARD_NAVIGATION = [
    # [InlineKeyboardButton("Показать еще", callback_data=str(PIZZA))],
    [InlineKeyboardButton("Моя корзина", callback_data=str(MY_SHOPPING_CART))],
    # [InlineKeyboardButton("Оформить заказ", callback_data=str(DRINKS))],
    [InlineKeyboardButton("Назад", callback_data=str(BACK))]
]

KEYBOARD_MY_SHOPPING_CART = [
    [
        InlineKeyboardButton("Оформить заказ", callback_data=str(MAKE_ORDER)),
        InlineKeyboardButton("Назад", callback_data=str(BACK)),
    ]
]

KEYBOARD_MENU = [
    [
        InlineKeyboardButton("Горячие блюда", callback_data=str(HOT_DISHES)),
        InlineKeyboardButton("Супы", callback_data=str(SOUP))
    ],
    [
        InlineKeyboardButton("Пицца", callback_data=str(PIZZA)),
        InlineKeyboardButton("Напитки", callback_data=str(DRINKS))
    ],
    [InlineKeyboardButton("Моя корзина", callback_data=str(MY_SHOPPING_CART))]
]

KEYBOARD_SHOPPING_CART = [
    [
        InlineKeyboardButton("Добавить в корзину", callback_data=str(ADD_TO_SHOPPING_CART)),
    ]
]

KEYBOARD_SET_PORTION = [
    [
        InlineKeyboardButton('▼', callback_data=str(DECREASE)),
        InlineKeyboardButton(str(1), callback_data=str(1)), #Надо вставить переменную для указания количества добавленных порций.
        InlineKeyboardButton('▲', callback_data=str(INCREASE))
    ],
    [
        InlineKeyboardButton('Удалить', callback_data=str(REMOVE_FROM_SHOPPING_CART))
    ]
]

KEYBOARD_REMOVE_FROM_SHOPPING_CART = [
    [
        InlineKeyboardButton('Удалить', callback_data=str(REMOVE_FROM_SHOPPING_CART))
    ]
]

def order_keyboard():
    return ReplyKeyboardMarkup([
        ['Заказать', 'Отменить']
    ])

def main_keyboard():
    return ReplyKeyboardMarkup([
        ["Меню", "Заказать"]
    ])

def save_message_id(context, message_id):
        context.user_data['message_ids'].append(message_id['message_id'])

def delete_message_one(context, chat_id, message_id):
    context.bot.deleteMessage(
            chat_id=chat_id,
            message_id=message_id
        )
    context.user_data['message_ids'].remove(message_id)

def delete_message_all(context, chat_id):
    for message_id in context.user_data['message_ids']:
        context.bot.deleteMessage(
            chat_id=chat_id,
            message_id=message_id
        )
    context.user_data['message_ids'].clear()

def send_message(context, chat_id, menu, menu_type):
    for item in menu:
        message_id = context.bot.send_photo(
            chat_id=chat_id,
            photo=open(f"menu_imgs/{menu_type}/{item['id']}.png", 'rb'),
            caption=f"""
            Название: {item['name']}
Цена: {item['price']}
Описание: {item['description']}
ID: {menu_type}.{item['id']}
            """,
            reply_markup=InlineKeyboardMarkup(KEYBOARD_SHOPPING_CART),
            parse_mode = ParseMode.HTML
        )
        save_message_id(context, message_id)
    message_id = context.bot.send_message(
        chat_id=chat_id,
        text="Для оформления заказа выбирите интересующее блюдо и перейдите в корзину.",
        reply_markup=InlineKeyboardMarkup(KEYBOARD_NAVIGATION)
    )
    save_message_id(context, message_id)

def create_menu_list(context, menu_type):
    if not context.user_data.get(menu_type):
        context.user_data[menu_type] = []

def edit_message_reply_markup(context, dish_count, message_id, chat_id):
    context.bot.edit_message_reply_markup(
        message_id=message_id,
        chat_id=chat_id,
        reply_markup = InlineKeyboardMarkup(
            [[
                InlineKeyboardButton('▼', callback_data=str(DECREASE)),
                InlineKeyboardButton(str(dish_count), callback_data=str(dish_count)), #Надо вставить переменную для указания количества добавленных порций.
                InlineKeyboardButton('▲', callback_data=str(INCREASE))
            ],
            [
                InlineKeyboardButton('Удалить', callback_data=str(REMOVE_FROM_SHOPPING_CART))
            ]]
        )
    )

def show_my_shopping_cart(context, chat_id):
    total_price = 0
    for key, value in context.user_data.items():
        if key in MENU:
            for dish_dict in value:
                dish = get_dish(key, next(iter(dish_dict.keys())))
                dish_position_price = dish['price']*int(next(iter(dish_dict.values())))
                total_price += dish_position_price
                message_id = context.bot.send_photo(
                    chat_id=chat_id,
                    photo=open(f"menu_imgs/{key}/{dish['id']}.png", 'rb'),
                    caption=f"Блюдо: {dish['name']}\nЦена: {dish['price']}\nКоличество порций: {next(iter(dish_dict.values()))}\nСтоимость: {dish_position_price}\nID: {key}.{dish['id']}",
                    reply_markup=InlineKeyboardMarkup(KEYBOARD_REMOVE_FROM_SHOPPING_CART),
                    parse_mode = ParseMode.HTML
                )
                save_message_id(context, message_id)
    message_id = context.bot.send_message(
        chat_id=chat_id,
        text=f"К оплате: {total_price}",
        reply_markup=InlineKeyboardMarkup(KEYBOARD_MY_SHOPPING_CART)
    )
    save_message_id(context, message_id)
    context.user_data['total_price'] = total_price

def refresh_total_price(context, chat_id, message):
    message_id = context.user_data['message_ids'][-1]
    dish_price = message['caption'].split('\n')[3].split()[-1]
    total_price = context.user_data['total_price']
    refreshed_price = total_price - int(dish_price)
    context.user_data['total_price'] = refreshed_price
    context.bot.edit_message_text(
        message_id=message_id,
        chat_id=chat_id,
        text=f'К оплате: {refreshed_price}',
        reply_markup=InlineKeyboardMarkup(KEYBOARD_MY_SHOPPING_CART)
    )

def delete_dish(context, chat_id, message_id, message=0, flag=0):
    if flag == 'menu':
        message = context.bot.edit_message_reply_markup(
            message_id=message_id,
            chat_id=chat_id,
            reply_markup=InlineKeyboardMarkup(KEYBOARD_SHOPPING_CART)
        )
    else:
        delete_message_one(context, chat_id,  message_id)
        refresh_total_price(context, chat_id, message)
    print(message['caption'])
    dish_type = message['caption'].split()[-1].split('.')[0]
    dish_id = message['caption'].split()[-1].split('.')[-1]
    for dish in context.user_data[dish_type]:
        if dish.get(dish_id, False):
            context.user_data[dish_type].remove(dish)
            break
    print(context.user_data)


def quick_sort(alist, fst, lst):
    """
    快速排序
    1. 确定终止条件，起始大于等于终止；
    2. 起始fst和终止lst的位置，枢轴值pivot是第1个值；
    3. 遍历i和j，i是第2个，j是最后一个；
    4. 循环交换，直到i和j交叉；
    5. 枢轴索引取i和j最小的1个；
    6. 交换枢轴位置的值与起始位置的值；
    7. 递归调用左右两部分；
    8. 16行
    :param alist: 待排序列表
    :param fst: 起始idx
    :param lst: 终止idx
    :return: None
    """
    if fst >= lst:
        return
    pivot = alist[fst]
    i, j = fst + 1, lst
    while i <= j:  # 增加等号，用于移动中心轴位置，最后交换使用
        while alist[i] < pivot:
            i += 1
        while alist[j] > pivot:
            j -= 1
        if i < j:
            alist[i], alist[j] = alist[j], alist[i]
            i, j = i + 1, j - 1
    p_idx = min(i, j)  # 枢轴索引
    alist[fst], alist[p_idx] = alist[p_idx], alist[fst]
    quick_sort(alist, fst, p_idx - 1)
    quick_sort(alist, p_idx + 1, lst)

def quick_sort_v2(alist):
    """
    快速排序，需要额外空间
    :param alist: 待排序列表
    :return: 排序列表
    """
    if len(alist) <= 1:
        return alist
    pivot = alist[0]
    small = [i for i in alist if i < pivot]
    mid = [i for i in alist if i == pivot]
    large = [i for i in alist if i > pivot]
    return quick_sort_v2(small) + mid + quick_sort_v2(large)

def test_of_quick_sort():
    # alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
    alist = [54, 26, 93, 17, 77, 56, 26, 55, 20]
    quick_sort(alist, 0, len(alist) - 1)
    print(alist)
    # alist = quick_sort_v2(alist)
    # print(alist)

if __name__ == '__main__':
    test_of_quick_sort()


import csv
import tqdm
import random
import logging
import numpy as np
import pandas as pd
from os import path
from datetime import datetime

import chainer
import chainerrl
import chainer.links as L
from chainerrl import misc
import chainer.functions as F
from chainer import serializers
from chainerrl.agents import PPO
from chainer.backends import cuda
from chainerrl import experiments
from chainer.backends import cuda

from src.abstract.agent import Agent
from src.visualise.visualise import visualise_agent
from src.supervisor.supervisor_agent_environment import SupervisorEnvironment
from src.supervisor.supervisor_agent_two_finger_env import SupervisorEnvironment_

class SupervisorAgent(Agent):

    def __init__(self, layout_config, agent_params, train, finger_two, verbose=False):
        self.logger = logging.getLogger(__name__)

        self.layout_config = layout_config
        self.agent_params = agent_params
        self.train_model = train
        self.finger_two = finger_two
        self.verbose = verbose

        if finger_two:
            self.env = SupervisorEnvironment_(self.layout_config, self.agent_params, self.train_model)
        else:
            self.env = SupervisorEnvironment(self.layout_config, self.agent_params, self.train_model)

        optimizer_name = 'Adam' if agent_params is None else agent_params['supervisor']['optimizer_name']
        lr = 0.001 if agent_params is None else agent_params['supervisor']['learning_rate']
        n_units = 512 if agent_params is None else int(agent_params['supervisor']['n_units'])
        device_id = 0 if agent_params is None else int(agent_params['supervisor']['device_id'])
        pre_load = False if agent_params is None else bool(agent_params['supervisor']['pre_load'])
        self.gpu = True if agent_params is None else bool(agent_params['supervisor']['gpu'])
        self.save_path = path.join('data', 'models', 'supervisor') if agent_params is None \
            else agent_params['supervisor']['save_path']
        self.episodes = 1000000 if agent_params is None else int(agent_params['supervisor']['episodes'])
        self.log_interval = 1000 if agent_params is None else int(agent_params['supervisor']['log_interval'])
        self.log_filename = agent_params['supervisor']['log_file']

        winit_last = chainer.initializers.LeCunNormal(1e-2)

        self.model = chainer.Sequential(
            L.Linear(None, n_units),
            F.relu,
            L.Linear(None, n_units),
            F.relu,
            chainerrl.links.Branched(
                chainer.Sequential(
                    L.Linear(None, self.env.action_space.n, initialW=winit_last),
                    chainerrl.distribution.SoftmaxDistribution,
                ),
                L.Linear(None, 1)
            )
        )

        if pre_load:
            serializers.load_npz(path.join(self.save_path, 'best', 'model.npz'), self.model)

        if self.gpu:
            self.model.to_gpu(device_id)

        if optimizer_name == 'Adam':
            self.optimizer = chainer.optimizers.Adam(alpha=lr)
        elif optimizer_name == 'RMSprop':
            self.optimizer = chainer.optimizers.RMSprop(lr=lr)
        else:
            self.optimizer = chainer.optimizers.MomentumSGD(lr=lr)

        self.optimizer.setup(self.model)

        self.optimizer.add_hook(chainer.optimizer.GradientClipping(1.0))

        phi = lambda x: x.astype(np.float32, copy=False)

        self.agent = PPO(
            self.model,
            self.optimizer,
            phi=phi,
            update_interval=1000,
            standardize_advantages=True,
            entropy_coef=1e-2,
            recurrent=False,
        )

        if train:
            chainer.config.train = True
            if self.verbose:
                self.pbar = tqdm.tqdm(total=self.episodes, ascii=True, bar_format='{l_bar}{n}, {remaining}\n')
            else:
                self.pbar = tqdm.tqdm(total=self.episodes)
        else:
            chainer.config.train = False
            self.agent.act_deterministically = False

    def train(self, episodes):
        """
        Trains the model for given number of episodes.
        """

        progress_bar = ProgressBar(self.pbar, episodes)

        experiments.train_agent_with_evaluation(
            self.agent, self.env,
            steps=episodes,  # Train the agent for 2000 steps
            eval_n_steps=None,  # We evaluate for episodes, not time
            eval_n_episodes=10,  # 10 episodes are sampled for each evaluation
            train_max_episode_len=100,  # Maximum length of each episode
            eval_interval=self.log_interval,  # Evaluate the agent after every 1000 steps
            step_hooks=[progress_bar],  # add hooks
            logger=self.logger,
            outdir=self.save_path)  # Save everything to 'supervisor' directory

    def evaluate(self, sentence, batch, n_users, **kwargs):
        """
        Function to evaluate trained agent.
        :param sentence: sentence to type.
        :param batch: run evaluation in batch mode.
        :param n_users: number of users to simulate.
        """

        done = False
        if not (sentence == "" or sentence is None):
            self.env.sentences = [sentence]
            self.env.sentences_bkp = [sentence]

        if batch:
            sentence_agg_data = [["sentence.id", "agent.id", "target.sentence", "wpm", "lev.distance",
                                  "gaze.shift", "bs", "immediate.bs", "delayed.bs",
                                  "gaze.keyboard.ratio", "fix.count", "finger.travel", "iki", "correct.error",
                                  "uncorrected.error", "fix.duration", "chunk.length"]]
            if self.verbose:
                iter = tqdm.tqdm(iterable=range(n_users), ascii=True,
                                 bar_format='{l_bar}{n}, {remaining}\n')
            else:
                iter = tqdm.tqdm(range(n_users))
            for i in iter:

                if self.finger_two:
                    self.env = SupervisorEnvironment_(self.layout_config, self.agent_params, self.train_model)
                else:
                    self.env = SupervisorEnvironment(self.layout_config, self.agent_params, self.train_model)
                self.env.agent_id = i

                # reinitialise random seed.
                np.random.seed(datetime.now().microsecond)
                random.seed(datetime.now().microsecond)

                while len(self.env.sentences) > 0:
                    state = self.env.reset()
                    done = False
                    while not done:
                        action = self.agent.act(state)
                        state, reward, done, info = self.env.step(action)

                sentence_agg_data += self.env.sentence_test_data

            with open(path.join("data", "output", "SupervisorAgent_sentence_test.csv"), "w", newline="",
                      encoding='utf-8') as f:
                writer = csv.writer(f)
                writer.writerows(sentence_agg_data)

            if not self.finger_two:
                with open(path.join("data", "output", "SupervisorAgent_Vision_Viz.csv"), "w", newline="") as f:
                    writer = csv.writer(f)
                    writer.writerows(self.env.eye_viz_log)

                with open(path.join("data", "output", "SupervisorAgent_Finger_Viz.csv"), "w", newline="") as f:
                    writer = csv.writer(f)
                    writer.writerows(self.env.finger_viz_log)

                with open(path.join("data", "output", "SupervisorAgent_Typing_Viz.csv"), "w", newline="") as f:
                    writer = csv.writer(f)
                    writer.writerows(self.env.typing_viz_log)

        else:
            self.env.sentence_test_data.append(["sentence.id", "agent.id", "target.sentence", "wpm", "lev.distance",
                                                "gaze.shift", "bs", "immediate.bs", "delayed.bs",
                                                "gaze.keyboard.ratio", "fix.count", "finger.travel", "iki",
                                                "correct.error",
                                                "uncorrected.error", "fix.duration", "chunk.length"])
            state = self.env.reset()
            while not done:
                action = self.agent.act(state)
                state, reward, done, info = self.env.step(action)

            with open(path.join("data", "output", "SupervisorAgent_vision_test.csv"), "w", newline="") as f:
                writer = csv.writer(f)
                writer.writerows(self.env.eye_test_data)

            with open(path.join("data", "output", "SupervisorAgent_finger_test.csv"), "w", newline="") as f:
                writer = csv.writer(f)
                writer.writerows(self.env.finger_test_data)

            with open(path.join("data", "output", "SupervisorAgent_sentence_test.csv"), "w", newline="",
                      encoding='utf-8') as f:
                writer = csv.writer(f)
                writer.writerows(self.env.sentence_test_data)

            # TODO: This is from legacy code. Need to update.
            visualise_agent(True, True, path.join("data", "output", "SupervisorAgent_vision_test.csv"),
                            path.join("data", "output", "SupervisorAgent_finger_test.csv"),
                            path.join("data", "output", "SupervisorAgent.mp4"))

        self.save_senetence_agg_data(path.join("data", "output", "SupervisorAgent_sentence_test.csv"))
        self.save_user_agg_data(path.join("data", "output", "SupervisorAgent_sentence_test.csv"))

    def save_senetence_agg_data(self, filename):
        """
        generates sentence level aggregate data.
        :param filename: raw data file path.
        """
        data = pd.read_csv(filename, sep=',', encoding='utf-8')
        data = data.groupby("target.sentence").agg(['mean', 'std'])
        data.to_csv(path.join("data", "output", "SupervisorAgent_sentence_aggregate.csv"), encoding='utf-8')

    def save_user_agg_data(self, filename):
        """
        generates user level aggregate data.
        :param filename: raw data file path.
        """
        data = pd.read_csv(filename, sep=',', encoding='utf-8')
        data = data.groupby("agent.id").agg(['mean', 'std'])
        data.to_csv(path.join("data", "output", "SupervisorAgent_user_aggregate.csv"), encoding='utf-8')

class ProgressBar(chainerrl.experiments.hooks.StepHook):
    """
    Hook class to update progress bar.
    """

    def __init__(self, pbar, max_length):
        self.pbar = pbar
        self.max = max_length

    def __call__(self, env, agent, step):
        self.pbar.update()
        if self.max <= step:
            self.pbar.close()


import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn.cluster import AffinityPropagation
from sklearn import preprocessing
import pandas as pd
import matplotlib.pyplot as plt
import pickle

#df = getdata
class Clustering():

	def train_affinity_propogation_model(self, X, savePickle = True):
		clf = AffinityPropagation(preference=-50).fit(X)
		cluster_centers_indices = clf.cluster_centers_indices_

		if savePickle:
			with open('affinity_propagation.pickle','wb') as f:
				pickle.dump(clf, f)

		return clf

	def load_affinity_propogation_model_pickle(self):
		pickle_in = open('affinity_propagation.pickle', 'rb')
		clf = pickle.load(pickle_in)

		return clf

	def train_mean_shift_model(self, X, savePickle = True):
		X = preprocessing.scale(X)

		bandwidth = estimate_bandwidth(X, quantile=0.1, n_samples=500)

		clf = MeanShift(bandwidth=bandwidth, bin_seeding=True)
		clf.fit(X)
		if savePickle:
			with open('meanshift.pickle','wb') as f:
				pickle.dump(clf, f)

		return clf

	def load_mean_shift_model_pickle(self):
		pickle_in = open('meanshift.pickle', 'rb')
		clf = pickle.load(pickle_in)

		return clf


#!/usr/bin/env python
# general_plotter for quick plotting

import argparse
# parse first since matplotlib takes a long time to load
parser = argparse.ArgumentParser()
parser.add_argument('column', nargs='+')
parser.add_argument('--string-data', '-s', nargs='+')
parser.add_argument('--xaxis', '-a', nargs='+')
parser.add_argument('--xlabel', '-x', type=str)
parser.add_argument('--ylabel', '-y', type=str)
parser.add_argument('--xtics-column', 't')
#parser.add_argument('--title', type=str)
arg = parser.parse_args()

import matplotlib
gui_envs = ['GTKAgg','TKAgg','Qt4Agg','WXAgg']
for gui in gui_envs:
    try:
        matplotlib.use(gui,warn=False, force=True)
        from matplotlib import pyplot as plt
        break
    except:
        continue

# list of fonts
#flist = matplotlib.font_manager.get_fontconfig_fonts()
#for fname in flist:
#    print(fname)
#    if not '/Library/Fonts/NISC18030.ttf' in fname:
#        matplotlib.font_manager.FontProperties(fname=fname).get_name()
import numpy as np
font = {'family': 'sans-serif',
        #'sans-serif': '/System/Library/Fonts/Helvetica.ttc'}
        'sans-serif': '/Library/Fonts/Skia.ttf'}
#font = fm.FontProperties(fname='/System/Library/Fonts/Helvetica.ttc')
#plt.rcParams['font.family'] = 'cursive'
plt.rc('font', **font)

def plot_single(data_file, xc):
    # load
    if arg.string_data:
        #str_data = np.loadtxt(data_file, usecols=(0, 1), dtype=str)
        str_data = np.loadtxt(data_file, usecols=arg.string_data, dtype=str)
    num_data = np.loadtxt(data_file, usecols=(2,3,4,5,6))

    if str_data:
        str_data = np.array([ x for x in sorted(str_data,
            key=lambda x: x[XC_COLUMN]) if x[XC_COLUMN] == xc ])
    num_data = np.array([ x  for _,x in sorted(zip(str_data[:, XC_COLUMN], num_data),
        key=lambda x: x[0]) if _ == xc ])

    if arg.xaxis:
        t = num_data
    else:
        t = np.arange(0, np.shape(num_data)[0])
    for column in arg.column:
        plt.plot(t, num_data[:, column])

    if str_data and arg.xtics_column:
        plt.xtics(t, str_data[:, arg.xtics_column])
    #plt.xticks(x, str_data[:, POS_COLUMN], **font)
    #plt.title(xc, **font)
    #plt.xticks(x, str_data[:, POS_COLUMN], fontproperties=font)
    #plt.title(xc, fontproperties=font)
    #plt.xticks(x, str_data[:, POS_COLUMN])
    #plt.title(xc)
    #plt.plot(x, num_data[:, E_COLUMN])

if __name__ == '__main__':
    #plt.subplot(2,1,1)
    plot_single(arg.files[0], 'pbe')
    #plt.subplot(2,1,2)
    #plot_single(arg.files[0], 'pz')
    plt.show()


# -*- coding: utf-8 -*-
import numpy as np
import cv2
import os
import json
from multiprocessing import Pool
from urllib.request import urlopen
# URL到图片
def url_to_image(url):
    # download the image, convert it to a NumPy array, and then read
    # it into OpenCV format
    resp = urlopen(url)
    # bytearray将数据转换成（返回）一个新的字节数组
    # asarray 复制数据，将结构化数据转换成ndarray
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    # cv2.imdecode()函数将数据解码成Opencv图像格式
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    # return the image
    return image

data_path = r'D:\data\logo\qingxi\爬取\logo'
listdir = os.listdir(data_path)
threads = 4

def down_img(label_file):
        txt = open(os.path.join(data_path, label_file), encoding='utf-8')
        json_txt = json.load(txt)
        for file_path in json_txt:
            path_list = file_path['pic_list'].split('|')
            for i in range(1,int(path_list[1])):
                url = 'http://oss-saas-1.oss-cn-beijing.aliyuncs.com/saas/'+path_list[0]+'/thumb/'+str(i)+'.jpg'
                print(url)
                try:
                    image = url_to_image(url)
                    sava_path = os.path.join(r'E:\huangxin\oss',label_file,
                                             path_list[0].split('/')[-1] + '_' + str(i) + '.jpg')
                    cv2.imwrite(sava_path,image)
                except Exception as e:
                    print(e)
                    print(url)

# down_img('qinghai')

if __name__ == "__main__":
    with Pool(processes=threads) as p:
        p.map(down_img, listdir)
    # check_image_opencv()


import xml.etree.ElementTree as ET

COMPARE_KEY_X = 1
COMPARE_KEY_Y = 2
COMPARE_KEY_WIDTH = 3
COMPARE_KEY_HEIGHT = 4
COMPARE_KEY_ROW = 5
COMPARE_KEY_COLUMN = 6

class HtmlTree:
    def __init__(self):
        self.root = ET.Element('div')
        self.root.set('class', 'container_main')
        self.root.set('name', 'main')
        self.tree = ET.ElementTree(self.root)
        self.current_node = self.root
    def add_node(self, node, parent=None):
        if parent:
            parent.append(node)
        else:
            self.root.append(node)

    def create_node(self,node_name, parent=None):
        self.current_node = ET.SubElement(parent,str(node_name))
        return self.current_node

    def add_attribute(self,node,**kwargs):

        for k,v in kwargs.items():
            node.set(k,v)

    def add_text(self,node,text):
        node.text = str(text)

html = HtmlTree()

class plugins:
    def __init__(self, left,top,width,height):
        self.x = left
        self.y = top
        self.width = width
        self.height = height
        self.option  = {COMPARE_KEY_X: self.compare_x,
                        COMPARE_KEY_Y: self.compare_y,
                        COMPARE_KEY_WIDTH: self.compare_width,
                        COMPARE_KEY_HEIGHT: self.compare_height,
                        COMPARE_KEY_ROW: self.compare_row,
                        COMPARE_KEY_COLUMN: self.compare_column
                        }

    def is_less(self,obj):
        if(self.x < obj.x and self.y < obj.y):
            return True
        else:
            return False
    def print_node(self):
        print(("( "+ str(self.x) + " - "+ str(self.y) +", "+ str(self.width) +", "+ str(self.height) + ")"))

    def node_str(self):
        return str("( "+ str(self.x) + " - "+ str(self.y) +", "+ str(self.width) +", "+ str(self.height) + ")")

    def compare(self,obj,key=COMPARE_KEY_X):
        return self.option[key](obj)

    def compare_x(self,obj):
        if self.x > obj.x:
            return 1
        elif obj.x > self.x:
            return -1
        else:
            return 0

    def compare_y(self,obj):
        if self.y > obj.y:
            return 1
        elif obj.y > self.y:
            return -1
        else:
            return 0

    def compare_width(self,obj):
        if self.width > obj.width:
            return 1
        elif obj.width > self.width:
            return -1
        else:
            return 0

    def compare_height(self,obj):
        if self.height > obj.height:
            return 1
        elif obj.height > self.height:
            return -1
        else:
            return 0

    def compare_row(self,obj):
        if self.x > obj.x:
            if self.y > obj.y:
                return 1
            elif self.y < obj.y:
                return -1
            else:
                return 1
        elif self.x < obj.x:
            if self.y < obj.y:
                return -1
            elif self.y > obj.y:
                return 1
            else:
                return -1
        else:
            if self.y < obj.y:
                return -1
            elif self.y > obj.y:
                return 1
            else:
                return 0

    def compare_column(self,obj):
        if self.y > obj.y:
            if self.x > obj.x:
                return 1
            elif self.x < obj.x:
                return -1
            else:
                return 1
        elif self.y < obj.y:
            if self.x < obj.x:
                return -1
            elif self.x > obj.x:
                return 1
            else:
                return -1
        else:
            if self.x < obj.x:
                return -1
            elif self.x > obj.x:
                return 1
            else:
                return 0

def insert_sort(obj_list,key):
    for i in range(len(obj_list)):
        for j in range(i,0,-1):
            if obj_list[j].compare(obj_list[j-1],key) <= 0:
                tmp = obj_list[j-1]
                obj_list[j-1] = obj_list[j]
                obj_list[j] = tmp
            else:
                break

    return obj_list

def create_row(obj_list,root):
    """
    1. Pop first object from the list.
    2. Set MAX_HEIGHT to obj.y + obj.height
    3. for all other objects do following:
        a. if obj.y  < MAX_HEIGHT the add it to temp list and pop it from original list.
        b. if obj.y + obj.height > MAX_HEIGHT then change it to obj.y + obj.height.
    4. Open the ROW div.
    5. Call the create_column(temp_list).
    6. close the ROW div
    """
    if len(obj_list) == 0:
        return

    #sort the list accordingly
    obj_list = insert_sort(obj_list,COMPARE_KEY_ROW)

#     print "create_row called with list"
#
#     for elem in obj_list:
#         elem.print_node()

    # Pop first element and set max HEIGHT
    obj = obj_list.pop(0)
    MAX_HEIGHT = obj.y + obj.height
    row_list = [obj]

    # create the row list to be passed to the column function

    i = 0
    n = len(obj_list)
    while i < n:
        element = obj_list[i]
        if element.y < MAX_HEIGHT:
            row_list.append(element)
            if element.y + element.height > MAX_HEIGHT:
                MAX_HEIGHT = element.y + element.height
            del obj_list[i]
            n = n - 1
        else:
            i = i + 1

    tmp = html.create_node('div',root)
    kwargs = {"name":'row',"class":'ROW'}
    html.add_attribute(tmp,**kwargs)
#     print("
")
    create_column(row_list,tmp)
#     print("
 !< ROW !>")

    if len(obj_list) == 0:
        return
    create_row(obj_list,root)

def create_column(obj_list,root):
    """
    1. Pop first object from the list.
    2. Set MAX_WIDTH to obj.x + obj.width
    3. for all other objects do following:
        a. if obj.x  < MAX_WIDTH the add it to temp list and pop it from original list.
        b. if obj.x + obj.width > MAX_WIDTH then change it to obj.x + obj.width.
    4. Open the COLUMN div.
    5. Call the create_row(temp_list).
    6. close the COLUMN div
    """
    if len(obj_list) == 0:
        return
    #sort the list accordingly
    obj_list = insert_sort(obj_list,COMPARE_KEY_COLUMN)

#     print "create_column called with list"
#
#     for elem in obj_list:
#         elem.print_node()

    # Pop first element and set max HEIGHT
    obj = obj_list.pop(0)
    MAX_WIDTH = obj.x + obj.width
    column_list = [obj]

    if len(obj_list) == 0:
        tmp = html.create_node('div',root)
        kwargs = {"name":'column',"class":'COLUMN'}
        html.add_attribute(tmp,**kwargs)
        html.add_text(tmp,obj.node_str())

#         print("
")
#         obj.print_node()
#         print("
 !< COLUMN !>")
        return

    # create the column list to be passed to the row function
    i = 0
    n = len(obj_list)
    while i < n:
        element = obj_list[i]
        if element.x < MAX_WIDTH:
            column_list.append(element)
            if element.x + element.width > MAX_WIDTH:
                MAX_WIDTH = element.x + element.width
            del obj_list[i]
            n = n - 1
        else:
            i = i + 1

    # pass to create row only if it contains more than 1 items
    tmp = html.create_node('div',root)
    kwargs = {"name":'column',"class":'COLUMN'}
    html.add_attribute(tmp,**kwargs)
#     print("
")
    if len(column_list) > 1:
        create_row(column_list,tmp)
    else:
        html.add_text(tmp,obj.node_str())
#         column_list[0].print_node()
#     print("
 !< COLUMN !>")
    create_column(obj_list,root)

def create_array(object_list):
#     obj_list = [plugins(0,0,10,15),plugins(12,17,5,10),plugins(20,30,8,12),plugins(0,45,10,15),plugins(12,45,10,15),plugins(24,45,5,10)]
#     obj_list = [plugins(0,0,10,15),plugins(12,0,5,10),plugins(20,0,8,12)]

#     for elem in  obj_list:
#         elem.print_node()
#     print "after sorting the array in row"
#     obj_list = insert_sort(obj_list, COMPARE_KEY_ROW)
#     for elem in  obj_list:
#         elem.print_node()
#
#     print "after sorting the array in column"
#     obj_list = insert_sort(obj_list, COMPARE_KEY_COLUMN)
#     for elem in  obj_list:
#         elem.print_node()

    create_row(object_list,html.root)

    print("\n\n\n Printing the Tree \n\n\n")

    ET.dump(html.root)

if __name__ == "__main__":
    create_array()


from django.urls import path
from .import views

app_name = 'cart'

urlpatterns = [
    path('', views.cartView, name='cart'),
    path("checkout/", views.checkout, name='checkout'),
    path('add/', views.addToCart , name='add'),
    path('remove/', views.removeCartItems , name='removeAllItems'),
    path('<int:product_id>/<int:qty>/delete', views.deleteCartItem , name='delete'),
    ]


"""Methods for plotting binned data per-month."""
import calendar  # pylint: disable=E0401

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import pandas as pd

from ..bhom.analytics import bhom_analytics
from ..helpers import validate_timeseries
from .utilities import contrasting_color

@bhom_analytics()
def monthly_histogram_proportion(
    series: pd.Series,
    bins: list[float],
    ax: plt.Axes = None,
    labels: list[str] = None,
    show_year_in_label: bool = False,
    show_labels: bool = False,
    show_legend: bool = False,
    **kwargs,
) -> plt.Axes:
    """Create a monthly histogram of a pandas Series.

    Args:
        series (pd.Series):
            The pandas Series to plot. Must have a datetime index.
        bins (list[float]):
            The bins to use for the histogram.
        ax (plt.Axes, optional):
            An optional plt.Axes object to populate. Defaults to None, which creates a new plt.Axes object.
        labels (list[str], optional):
            The labels to use for the histogram. Defaults to None, which uses the bin edges.
        show_year_in_label (bool, optional):
            Whether to show the year in the x-axis label. Defaults to False.
        show_labels (bool, optional):
            Whether to show the labels on the bars. Defaults to False.
        show_legend (bool, optional):
            Whether to show the legend. Defaults to False.
        **kwargs:
            Additional keyword arguments to pass to plt.bar.

    Returns:
        plt.Axes:
            The populated plt.Axes object.
    """

    validate_timeseries(series)

    if ax is None:
        ax = plt.gca()

    t = pd.cut(series, bins=bins, labels=labels)
    t = t.groupby([t.index.year, t.index.month, t], observed=True).count().unstack().T
    t = t / t.sum()

    # adjust column labels
    if show_year_in_label:
        t.columns = [
            f"{year}\n{calendar.month_abbr[month]}" for year, month in t.columns.values
        ]
    else:
        t.columns = [f"{calendar.month_abbr[month]}" for _, month in t.columns.values]

    t.T.plot.bar(
        ax=ax,
        stacked=True,
        legend=False,
        width=1,
        **kwargs,
    )
    ax.set_xlim(-0.5, len(t.columns) - 0.5)
    ax.set_ylim(0, 1)
    plt.setp(ax.get_xticklabels(), ha="center", rotation=0)
    for spine in ["top", "right", "left", "bottom"]:
        ax.spines[spine].set_visible(False)
    ax.yaxis.set_major_formatter(mticker.PercentFormatter(1))

    if show_legend:
        ax.legend(
            bbox_to_anchor=(1, 1),
            loc="upper left",
            borderaxespad=0.0,
            frameon=False,
        )

    if show_labels:
        for i, c in enumerate(ax.containers):
            label_colors = [contrasting_color(i.get_facecolor()) for i in c.patches]
            labels = [
                f"{v.get_height():0.1%}" if v.get_height() > 0.1 else "" for v in c
            ]
            ax.bar_label(
                c,
                labels=labels,
                label_type="center",
                color=label_colors[i],
                fontsize="x-small",
            )

    return ax


from appdirs import AppDirs
from yaml import safe_load, safe_dump
from os import mkdir
from os.path import dirname, isdir
from platform import system
from PySide6.QtCore import QTime
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QApplication

app = QApplication()
path = dirname(__file__)

CONFIG_FILE = "AwakeGuardian"
CONFIG_FILE_EXT = ".conf"

D = "DEFAULT"
LHT = "last_hold_time"
P = "profile"
R = "remind"
N = "nag"
TTRM = "time_to_remind_m"
TTRS = "time_to_remind_s"
TTNM = "time_to_nag_m"
TTNS = "time_to_nag_s"
PM = "power_management"
PMA = "power_management_action"
TTEM = "time_to_event_m"
TTES = "time_to_event_s"
IVR = "increase_volume_remind"
IVN = "increase_volume_nag"
TR = "time_range_active"  # FUTURE: this should be just "time_range" in v2.x, kept for backward compatibility
TRF = "time_range_from"
TRT = "time_range_to"
GS = "geometry_settings"
GH = "geometry_hold"

def defaults(key):
    d = {
        LHT: 15,
        P: 0,
        R: 1,
        N: 1,
        TTRM: 10,
        TTRS: 0,
        TTNM: 15,
        TTNS: 0,
        PM: 0,
        PMA: 1,
        TTEM: 20,
        TTES: 0,
        IVR: 0,
        IVN: 1,
        TR: 1,
        TRF: "20:00:00",
        TRT: "08:00:00",
        GH: None,
        GS: None,
    }
    return key, d[key]

class Icon:
    beep = QIcon(f"{path}/images/beep.png")
    clock = QIcon(f"{path}/images/clock.png")
    exit = QIcon(f"{path}/images/exit.png")
    eyes = QIcon(f"{path}/images/eyes.png")
    inactive = QIcon(f"{path}/images/inactive.png")
    settings = QIcon(f"{path}/images/settings.png")
    shout = QIcon(f"{path}/images/shout.png")

class Audio:
    coin = f"{path}/audio/coin.mp3"
    wilhelm = f"{path}/audio/wilhelm.mp3"

class Config:
    def __init__(self):
        self.config_file = self.setup_config_file()
        self.load_config()

    def setup_config_file(self):
        dirs = AppDirs(CONFIG_FILE)
        config_dir = dirname(dirs.user_config_dir)
        if not isdir(config_dir):
            try:
                mkdir(config_dir)
            except Exception as e:
                raise e
        return f"{dirs.user_config_dir}{CONFIG_FILE_EXT}"

    def set_hold_time(self, minutes):
        self.last_hold_time = minutes
        self.save_config()

    def set_time_to_remind(self, minutes, seconds):
        if minutes is not None:
            self.t_to_remind_m = minutes
        if seconds is not None:
            self.t_to_remind_s = seconds
        self.save_config()

    def set_time_to_nag(self, minutes, seconds):
        if minutes is not None:
            self.t_to_nag_m = minutes
        if seconds is not None:
            self.t_to_nag_s = seconds
        self.save_config()

    def set_time_to_event(self, minutes, seconds):
        if minutes is not None:
            self.t_to_event_m = minutes
        if seconds is not None:
            self.t_to_event_s = seconds
        self.save_config()

    def set_remind(self, value):
        self.remind = int(value)
        self.save_config()

    def set_nag(self, value):
        self.nag = int(value)
        self.save_config()

    def set_power_management(self, value):
        self.power_management = int(value)
        self.save_config()

    def set_power_management_action(self, value):
        self.power_management_action = int(value)
        self.save_config()

    def set_inc_volume_remind(self, value):
        self.inc_volume_remind = value
        self.save_config()

    def set_inc_volume_nag(self, value):
        self.inc_volume_nag = value
        self.save_config()

    def set_time_range(self, value):
        self.t_range = int(value)
        self.save_config()

    def set_time_range_from(self, time):
        self.t_range_f = time
        self.save_config()

    def set_time_range_to(self, time):
        self.t_range_t = time
        self.save_config()

    def set_geometry_settings(self, geometry):
        x = geometry.x()
        y = geometry.y()
        w = geometry.width()
        h = geometry.height()
        self.geometry_settings = f"{x} {y} {w} {h}"
        self.save_config()

    def set_geometry_hold(self, geometry):
        x = geometry.x()
        y = geometry.y()
        w = geometry.width()
        h = geometry.height()
        self.geometry_hold = f"{x} {y} {w} {h}"
        self.save_config()

    def save_config(self):
        settings = {
            P: self.profile,
            R: self.remind,
            N: self.nag,
            TTRM: self.t_to_remind_m,
            TTRS: self.t_to_remind_s,
            TTNM: self.t_to_nag_m,
            TTNS: self.t_to_nag_s,
            IVR: self.inc_volume_remind,
            IVN: self.inc_volume_nag,
            PM: self.power_management,
            PMA: self.power_management_action,
            TTEM: self.t_to_event_m,
            TTES: self.t_to_event_s,
            LHT: self.last_hold_time,
            TR: self.t_range,
            TRF: self.t_range_f.toString(),
            TRT: self.t_range_t.toString(),
            GH: "" if self.geometry_hold is None else self.geometry_hold,
            GS: "" if self.geometry_settings is None else self.geometry_settings,
        }
        with open(self.config_file, "w") as conf_file:
            conf_file.write(safe_dump(settings))

    def clear_config(self):
        open(self.config_file, "w")

    def load_config(self):
        cfg = {}
        try:
            loaded = safe_load(open(self.config_file))
            if loaded:
                cfg = loaded
        except:
            pass

        self.profile = int(cfg.get(*defaults(P)))
        self.remind = int(cfg.get(*defaults(R)))
        self.nag = int(cfg.get(*defaults(N)))

        self.last_hold_time = int(cfg.get(*defaults(LHT)))
        self.t_to_remind_m = int(cfg.get(*defaults(TTRM)))
        self.t_to_remind_s = int(cfg.get(*defaults(TTRS)))
        self.t_to_nag_m = int(cfg.get(*defaults(TTNM)))
        self.t_to_nag_s = int(cfg.get(*defaults(TTNS)))

        self.inc_volume_remind = int(cfg.get(*defaults(IVR)))
        self.inc_volume_nag = int(cfg.get(*defaults(IVN)))
        self.volume = None

        self.power_management = int(cfg.get(*defaults(PM)))
        self.power_management_action = int(cfg.get(*defaults(PMA)))
        self.t_to_event_m = int(cfg.get(*defaults(TTEM)))
        self.t_to_event_s = int(cfg.get(*defaults(TTES)))

        self.t_range = int(cfg.get(*defaults(TR)))
        self.t_range_f = QTime.fromString(cfg.get(*defaults(TRF)))
        self.t_range_t = QTime.fromString(cfg.get(*defaults(TRT)))

        self.geometry_hold = cfg.get(*defaults(GH))
        self.geometry_settings = cfg.get(*defaults(GS))

    def restore_defaults(self):
        self.clear_config()
        self.load_config()
        self.save_config()


#!/usr/bin/env python

from __future__ import print_function
import numpy as np
from astropy.io import fits

def loadspec(specfile, i):

    # log_10 of starting wavelength in Angstroms
    lam0 = 10**fits.open(specfile)[2].data[i]

    # flux density
    flambda = fits.open(specfile)[0].data[i]

    # inverse variance
    ivar = fits.open(specfile)[1].data[i]

    # Definition of the wavelength array: 1e-4 spacing in log_10(lambda)
    lam = lam0*10**(1e-4*np.arange(len(ivar)))

    return [lam, flambda, ivar]

def savespec(lam, flambda, ivar, outfile=None):

    specarr = np.zeros((len(lam), 3))
    specarr[:, 0] = lam
    specarr[:, 1] = flambda
    specarr[:, 2] = ivar

    if outfile is None:
        return specarr
    else:
        np.savetxt(outfile, specarr, fmt="%.5g")
        return

if __name__ == "__main__":

    specfile = 'skyfibers_nativelam.fits'

    # Save the 101st spectrum (index 100 from 0) as an example
    i = 100
    lam, flambda, ivar = loadspec(specfile, i)
    savespec(lam, flambda, ivar, 'spec_%06d.dat' % (i))

    # flambda is the excess sky spectrum-it should be nearly zero
    # apart from measurement errors.  Quantify this with chi squared:

    chisq_dof = np.sum(flambda**2*ivar)/len(lam)
    print('chi2 per degree of freedom of the sky spectrum: %.2f' % chisq_dof)


from talon.voice import Context, Key, press
from ..misc.utils import text, parse_words, insert, is_filetype, CursorText
# Some of these are going to tightly couple to my VSCode implementation because that's where I
# write javascript for the most part
from ..apps.vscode import VSCodeTabComplete

JS_EXTENSIONS = (".js", ".jsx", ".ts", ".tsx")

context = Context("javascript", func=is_filetype(JS_EXTENSIONS))

def remove_spaces_around_dashes(m):
    words = parse_words(m)
    s = " ".join(words)
    s = s.replace(" – ", "-")
    insert(s)

context.keymap(
    {
        # All reserved words that we actually use
        "arguments": "arguments",
        "asink | async": "async ",
        "await": "await ",
        "boolean": "boolean",
        "break": "break;",
        "case": "case",
        "catch": "catch(e){",
        "class": "class ",
        "const": "const ",
        "continue": "continue; ",
        "debugger": "debugger; ",
        "default": "default ",
        "obj delete": "delete",
        "do": "do",
        "elsy": VSCodeTabComplete(["else"]),
        "else if": VSCodeTabComplete(["else if"]),
        "export": "export ",
        "extends": "extends ",
        "false": "false",
        "finally": ["finally{}", Key("left")],
        "for loop": VSCodeTabComplete(["for"]),
        "goto": "goto",
        "iffy": VSCodeTabComplete(["if"]),
        "import": "import",
        "obj in": "in ",
        "instance of": "instanceof",
        "let": "let ",
        "new": "new ",
        "null": "null",
        "return": "return ",
        "super": CursorText("super({.})"),
        "switch": VSCodeTabComplete(["switch"]),
        "this": "this",
        "throw": ["throw new Error();", Key('Left'), Key('Left')],
        "true": "true",
        "try": VSCodeTabComplete(["trycatch"]),
        "typeof": "typeof ",
        "var": "var ",
        "while": VSCodeTabComplete(["while"]),
        "with": "with ",
        "yield": "yield ",

        # Global values
        "infinity": "Infinity",
        "Nan": "NaN",
        "undefined": "undefined",
        "null": "null",

        # Function Properties
        "eval": CursorText("eval({.})"),
        "is finite": CursorText("isFinite({.})"),
        "is Nan": CursorText("isNaN({.})"),
        "parse float": CursorText("parseFloat({.})"),
        "parse int": CursorText("parseInt({.})"),
        "decode you are eye": CursorText("decodeURI({.})"),
        "decode you are eye component": CursorText("decodeURIComponent({.})"),
        "encode you are eye": CursorText("encodeURI({.})"),
        "encode you are eye component": CursorText("encodeURIComponent({.})"),

        # FUNDAMENTAL OBJECTS
        "[new] error": CursorText("new Error({.})"),
        "[new] symbol": CursorText("Symbol({.})"),
        "new Reg ex": ["new RegExp()"],
        "Reg ex": ["//", Key("left")],

        # NUMBERS AND DATES
        # Dates
        "new date": CursorText("new Date({.})"),
        "date dot now": "Date.now()",
        "date dot UTC": CursorText("Date.UTC({.})"),
        # Date Getters
        "Date dot get date": ".getDate()",
        "Date dot get day": ".getDay()",
        "Date dot get full year": ".getFullYear()",
        "Date dot get hours": ".getHours()",
        "Date dot get milliseconds": ".getMilliseconds()",
        "Date dot get minutes": ".getMinutes()",
        "Date dot get month": ".getMonth()",
        "Date dot get seconds": ".getSeconds()",
        "Date dot get time": ".getTime()",
        "Date dot get timezone offset": ".getTimezoneOffset()",
        "Date dot get UTC date": ".getUTCDate()",
        "Date dot get UTC day": ".getUTCDay()",
        "Date dot get UTC full year": ".getUTCFullYear()",
        "Date dot get UTC hours": ".getUTCHours()",
        "Date dot get UTC milliseconds": ".getUTCMilliseconds()",
        "Date dot get UTC minutes": ".getUTCMinutes()",
        "Date dot get UTC month": ".getUTCMonth()",
        # Date setters
        "Date dot get UTC seconds": ".getUTCSeconds()",
        "Date dot setDate": ".setDate()",
        "Date dot set full year": ".setFullYear()",
        "Date dot setHours": ".setHours()",
        "Date dot set milliseconds": ".setMilliseconds()",
        "Date dot set minutes": ".setMinutes()",
        "Date dot set month": ".setMonth()",
        "Date dot set seconds": ".setSeconds()",
        "Date dot set time": ".setTime()",
        "Date dot set UTC date": ".setUTCDate()",
        "Date dot set UTC full year": ".setUTCFullYear()",
        "Date dot set UTC hours": ".setUTCHours()",
        "Date dot set UTC milliseconds": ".setUTCMilliseconds()",
        "Date dot set UTC minutes": ".setUTCMinutes()",
        "Date dot set UTC month": ".setUTCMonth()",
        "Date dot set UTC seconds": ".setUTCSeconds()",
        # Date Conversion Getters
        "Date dot to date string": ".toDateString()",
        "Date dot to iso string": ".toISOString()",
        "Date dot to json": ".toJSON()",
        "Date dot to locale date string": ".toLocaleDateString()",
        "Date dot to locale string": ".toLocaleString()",
        "Date dot to locale time string": ".toLocaleTimeString()",
        "Date dot to string": ".toString()",
        "Date dot to time string": ".toTimeString()",
        "Date dot to UTC string": ".toUTCString()",

        # Numbers
        "Number dot epsilon": "Number.EPSILON",
        "Number dot Max safe integer": "Number.MAX_SAFE_INTEGER",
        "Number dot Max value": "Number.MAX_VALUE",
        "Number dot Min safe intiger": "Number.MIN_SAFE_INTEGER",
        "Number dot Min value": "Number.MIN_VALUE",
        "Number dot Nan": "Number.NaN",
        "Number dot negative infinity": "Number.NEGATIVE_INFINITY",
        "Number dot positive infinity": "Number.POSITIVE_INFINITY",
        "Number dot is Nan": CursorText("Number.isNaN({.})"),
        "Number dot is finite": CursorText("Number.isFinite({.})"),
        "Number dot is integer": CursorText("Number.isInteger({.})"),
        "Number dot is safe integer": CursorText("Number.isSafeInteger({.})"),
        "Number dot to integer": CursorText("Number.toInteger({.})"),
        "Number dot parse float": CursorText("Number.parseFloat({.})"),
        "Number dot parse int": CursorText("Number.parseInt({.})"),
        "Number dot to fixed": CursorText("Number.prototype.toFixed({.})"),
        "Number dot to locale string": CursorText("Number.prototype.toLocaleString({.})"),
        "Number dot to precision": CursorText("Number.prototype.toPrecision({.})"),
        "Number dot to string": CursorText("Number.prototype.toString({.})"),

        # Math
        "Math dot (abs | absolute)": CursorText("Math.abs({.})"),
        "Math dot (ceil | ceiling)": CursorText("Math.ceil({.})"),
        "Math dot floor": CursorText("Math.floor({.})"),
        "Math dot max": CursorText("Math.max({.})"),
        "Math dot min": CursorText("Math.min({.})"),
        "Math dot pow": CursorText("Math.pow({.})"),
        "Math dot random": "Math.random()",
        "Math dot round": CursorText("Math.round({.})"),
        "Math dot (trunk | truncate)": CursorText("Math.trunc({.})"),

        # Strings
        "string dot from char code": CursorText("String.fromCharCode({.})"),
        "string dot from code point": CursorText("String.fromCodePoint({.})"),
        "string dot length": ".length",

        "string dot char at": CursorText(".charAt({.})"),
        "string dot char code at": CursorText(".charCodeAt({.})"),
        "string dot code point at": CursorText(".codePointAt({.})"),
        "string dot concat": CursorText(".concat({.})"),
        "string dot includes": CursorText(".includes({.})"),
        "string dot ends with": CursorText(".endsWith({.})"),
        "string dot index of": CursorText(".indexOf({.})"),
        "string dot last index of": CursorText(".lastIndexOf({.})"),
        "string dot locale compare": CursorText(".localeCompare({.})"),
        "string dot match": CursorText(".match({.})"),
        "string dot match all": CursorText(".matchAll({.})"),
        "string dot normalize": CursorText(".normalize({.})"),
        "string dot pad end": CursorText(".padEnd({.})"),
        "string dot pad start": CursorText(".padStart({.})"),
        "string dot repeat": CursorText(".repeat({.})"),
        "string dot replace": CursorText(".replace({.})"),
        "string dot search": CursorText(".search({.})"),
        "string dot slice": CursorText(".slice({.})"),
        "string dot split": CursorText(".split({.})"),
        "string dot starts with": CursorText(".startsWith({.})"),
        "string dot sub string": CursorText(".substring({.})"),
        "string dot to locale lower case": CursorText(".toLocaleLowerCase({.})"),
        "string dot to locale upper case": CursorText(".toLocaleUpperCase({.})"),
        "string dot to lower case": CursorText(".toLowerCase({.})"),
        "string dot to string": CursorText(".toString({.})"),
        "string dot to upper case": CursorText(".toUpperCase({.})"),
        "string dot trim": CursorText(".trim({.})"),
        "string dot trim start": CursorText(".trimStart({.})"),
        "string dot trim left": CursorText(".trimLeft({.})"),
        "string dot trim end": CursorText(".trimEnd({.})"),
        "string dot trim right": CursorText(".trimRight({.})"),
        "string dot value of": CursorText(".valueOf({.})"),

        # Regex
        "Reg ex dot exec": CursorText(".exec({.})"),
        "Reg ex dot test": CursorText(".test({.})"),
        "Reg ex dot to string": CursorText(".toString({.})"),

        # Functions
        "(function | funk)": VSCodeTabComplete(["function"]),
        "anon [funk]": VSCodeTabComplete(["anon"]),

        # Array methods
        "array dot is array": CursorText("Array.isArray({.})"),
        "array dot from": CursorText("Array.from({.})"),
        "array dot of": CursorText("Array.of({.})"),

        "array dot con cat": CursorText(".concat({.})"),
        "array dot every": CursorText(".every({.})"),
        "array dot fill": CursorText(".fill({.})"),
        "array dot filter": CursorText(".filter({.})"),
        "array dot find": CursorText(".find({.})"),
        "array dot find index": CursorText(".findIndex({.})"),
        "array dot flat": CursorText(".flat({.})"),
        "array dot flat map": CursorText(".flatMap({.})"),
        "array dot for each": CursorText(".forEach({.})"),
        "array dot includes": CursorText(".includes({.})"),
        "array dot index of": CursorText(".indexOf({.})"),
        "array dot join": CursorText(".join({.})"),
        "array dot length": ".length",
        "array dot map": CursorText(".map({.})"),
        "array dot pop": ".pop()",
        "array dot push": CursorText(".push({.})"),
        "array dot reduce": CursorText(".reduce({.})"),
        "array dot reduceRight": CursorText(".reduceRight({.})"),
        "array dot reverse": ".reverse()",
        "array dot shift": ".shift()",
        "array dot slice": CursorText(".slice({.})"),
        "array dot some": CursorText(".some({.})"),
        "array dot sort": CursorText(".sort({.})"),
        "array dot splice": CursorText(".splice({.})"),
        "array dot unshift": CursorText(".unshift({.})"),

        # Object methods
        "Object dot assign": CursorText("Object.assign({.})"),
        "Object dot create": CursorText("Object.create({.})"),
        "Object dot define property": CursorText("Object.defineProperty({.})"),
        "Object dot define properties": CursorText("Object.defineProperties({.})"),
        "Object dot entries": CursorText("Object.entries({.})"),
        "Object dot freeze": CursorText("Object.freeze({.})"),
        "Object dot from entries": CursorText("Object.fromEntries({.})"),
        "Object dot get own property descriptor": CursorText("Object.getOwnPropertyDescriptor({.})"),
        "Object dot get own property descriptors": CursorText("Object.getOwnPropertyDescriptors({.})"),
        "Object dot get own property names": CursorText("Object.getOwnPropertyNames({.})"),
        "Object dot get own property symbols": CursorText("Object.getOwnPropertySymbols({.})"),
        "Object dot get prototype of": CursorText("Object.getPrototypeOf({.})"),
        "Object dot is": CursorText("Object.is({.})"),
        "Object dot is extensible": CursorText("Object.isExtensible({.})"),
        "Object dot is frozen": CursorText("Object.isFrozen({.})"),
        "Object dot is sealed": CursorText("Object.isSealed({.})"),
        "Object dot keys": CursorText("Object.keys({.})"),
        "Object dot prevent extensions": CursorText("Object.preventExtensions({.})"),
        "Object dot seal": CursorText("Object.seal({.})"),
        "Object dot set prototype of": CursorText("Object.setPrototypeOf({.})"),
        "Object dot values": CursorText("Object.values({.})"),

        "const [<dgndictation>]": ["const ", text],
        "let [<dgndictation>]": ["let ", text],
        "args": CursorText("({.})"),
        "index": ["[]", Key("left")],
        "block": [" {}", Key("left enter enter up tab")],
        "empty array": "[]",
        "empty object": "{}",
        "call": "()",
        "state func": "function ",
        "state return": "return ",
        "state constructor": "constructor ",
        "state if": CursorText("if ({.})"),
        "state else": " else ",
        "state else if": CursorText(" else if ({.})"),
        "state while": CursorText("while ({.})"),
        "state for": CursorText("for ({.})"),
        "state switch": CursorText("switch ({.})"),
        "state case": ["case \nbreak;", Key("up")],
        "state goto": "goto ",
        "state important": "import ",
        "state class": "class ",
        "state extends": "extends ",
        "state super": "super",
        "comment js": "// ",
        "word no": "null",
        "arrow": " => ",
        "assign": " = ",
        "op (minus | subtract)": " - ",
        "op (plus | add)": " + ",
        "op (times | multiply)": " * ",
        "op divide": " / ",
        "op mod": " % ",
        "[op] (minus | subtract) equals": " -= ",
        "[op] (plus | add) equals": " += ",
        "[op] (times | multiply) equals": " *= ",
        "[op] divide equals": " /= ",
        "[op] mod equals": " %= ",
        "(op | is) greater [than]": " > ",
        "(op | is) less [than]": " < ",
        "(op | is) equal": " === ",
        "(op | is) not equal": " !== ",
        "(op | is) greater [than] or equal": " >= ",
        "(op | is) less [than] or equal": " <= ",
        "(op (power | exponent) | to the power [of])": " ** ",
        "op and": " && ",
        "op or": " || ",

        # commands for react-redux
        "combo provider": "ImportProvider",
    }
)


#!/usr/bin/python

with open("input.txt", "r") as f:
    d = {}

    for line in f:
        n1 = int(line)

        for n2 in d.keys():
            n3 = 2020 - n2 - n1
            if n3 != n2 and n3 in d:
                print("%d+%d+%d == %d, %d*%d*%d=%d" % (n1, n2, n3, n1+n2+n3, n1, n2, n3, n1*n2*n3))

        d[n1] = 1


#line problem
#exam 2 question 2
#Codey Sivley
#OOP Fall 2021
import csv
from csv import reader

def readAnimalRange(csvFile):
    formattedData = []

    with open(csvFile, newline='') as animalData:
        rawData = csv.reader(animalData)
        for i in list(rawData):
            formattedData = formattedData + [tuple(i)]

    return formattedData

print(readAnimalRange('e2p2data.csv'))


from numpy import random
import matplotlib.pyplot as plt

N=10 # 100, 1000
K=[i+1 for i in range(N)] # Total number of arms
R = {}  # Reward corresponding to each arm
for i in range(N):
    R[i+1]=1
prob = {}  # Probability corresponding to each arm
equi_space=1/N
prob_start=round(1/N-1/(N*10),6)
for i in range(N):
    prob[i + 1] = prob_start
    prob_start = round(prob_start + equi_space, 6)
T = 10000
eplison = 1
count = dict(zip(list(range(1, N+1)), [0] * N))  # Record the times of each arm
u={}
for i in range(N):
    u[i+1]=R[i+1]*prob[i+1]
u=sorted(u.items(), key=lambda d:d[1], reverse = True)
best_k=u[0][0]
best_u=u[0][1]

Q = dict(zip(list(range(1, N+1)), [0] * N))
r = 0
c=0.5
d_list=[]
u_list=[]
for i in range(T):
    if random.random() < eplison:
        k = random.choice(K)
    else:
        k = max(Q, key=Q.get)
    v = random.choice([R[k], 0], p=[prob[k], 1 - prob[k]])
    r += v*prob[k]
    Q[k] = (Q[k] * count[k] + v*prob[k]) / (count[k] + 1)
    temp_u=round(best_u*(i+1)-r,2)
    u_list.append(temp_u)
    count[k] = count[k] + 1
    d=best_u-prob[k]*v
    if d!=0:
        d_list.append(d)
    d = min(d_list)
    eplison=min(1,c*(N)/((i+1)*(d**2)))

print('eplision: ',eplison)
print("The total reward is {}".format(r))
plt.plot(list(range(T)),u_list)
plt.xlabel('turn')
plt.ylabel('regret')
print('Number of times each slot machine is selected: ',count)
print('The best slot machine to choose: ',best_k)
plt.show()


f=lambda x:x*x
value=f(5)
print("Square value =",value)

x = lambda a,b:a+b
res=x(5,6)
print("sum is %d" % res)

func=lambda x:'yes' if x%2==0 else 'no'
res = func(34)
print(res)


from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse

#  밑줄 그을 텍스트
def index1(request) :
    return HttpResponse("Hello...")

#
문단

def index2(request) :
    return HttpResponse("
index2 함수 호출</>")

#  볼드체
def home(request) :
    return HttpResponse("Home")

def main(request) :
    return HttpResponse("Main")

# 데이터 입력
from .models import Curriculum

def insert(request) :
    msg = ""
    # 1) linux 입력
    Curriculum.objects.create(name='linux')
    msg += '1) linux 입력 성공
'
    # 2) python 입력
    c = Curriculum(name='python')
    c.save()
    msg += '2) python 입력 성공
'
    # 3) html/css/js 입력
    Curriculum(name='html/css/js').save()
    msg += '3) html/css/js 입력 성공
'
    # 4) django 입력
    Curriculum(name='django')
    msg += '4) django 입력 성공
'
    return HttpResponse(msg)

# 전체 데이터 조회
def show(request) :
    data = Curriculum.objects.all()

    msg = ''
    for dt in data :
        msg += dt.name + '
'

    return HttpResponse(msg)

# 한건 조회
def oneshow(request) :
    onedata = Curriculum.objects.get(pk=4)
    return HttpResponse(onedata.name)

def show2(request) :
    return render(
        request,
        # templates 폴더 내 경로만 작성
        "firstapp/show2.html",
        {}
    )

def show3(request) :
    data = Curriculum.objects.all()

    return render(
        request,
        # templates 폴더 내 경로만 작성
        "firstapp/show3.html",
        {'data' : data}
    )

def show4(request) :
    data = Curriculum.objects.all()

    return render(
        request,
        # templates 폴더 내 경로만 작성
        "firstapp/show4.html",
        {'data' : data}
    )

# 수정하기
def update(request) :
    data = Curriculum.objects.get(pk=1)
    data.name = 'linux_update'
    data.save()
    return HttpResponse('수정 성공')

# 삭제하기
def delete(request) :
    data1 = Curriculum.objects.get(pk=1)
    data1.delete()
    data2 = Curriculum.objects.get(pk=2)
    data2.delete()
    return HttpResponse('삭제 성공')