from django.db import connections
from django.http import JsonResponse
from base.models import Institucion, Respuesta
from django.db.models import Sum

from datetime import datetime

def informe(request, codigo_dipres):
    return JsonResponse({'url': 'asd'})

def canal_preferencia(request, pk=None):

    respuestas = Respuesta.objects.all()
    anio = 2020

    if pk:
        institucion = Institucion.objects.get(pk=pk)
        respuestas = respuestas.filter(institucion=institucion)
        anio = institucion.datos.get("anios")[-1]

    # labels = ['pec_canal_telefono', 'pec_canal_web', 'pec_canal_presencial']
    # MK recomendó ocupar pec_Eval los que tengan dato en vez que pec_Canal
    labels = ['pec_eval_telefono', 'pec_eval_web', 'pec_eval_presencial']

    data = []
    labels_with_data = []
    resp_anio = respuestas.filter(anio=anio)
    total = resp_anio.count()
    for label in labels:
        porcentaje = round(resp_anio.filter(**{label + '__isnull': False}).count() / total * 100, 0)
        if porcentaje > 0:
            labels_with_data.append(label)
            data.append(porcentaje)

    return JsonResponse({'labels': labels_with_data, 'data': data}, safe=False)

def canal_evaluacion(request, pk=None):

    respuestas = Respuesta.objects.all()
    anio = 2020

    if pk:
        institucion = Institucion.objects.get(pk=pk)
        respuestas = respuestas.filter(institucion=institucion)
        anio = institucion.datos.get("anios")[-1]

    labels = ['pec_eval_telefono', 'pec_eval_web', 'pec_eval_presencial']
    # labels = ['pec_eval_telefono']

    data = {
        'insatisfecho': [],
        'neutro': [],
        'satisfecho': []
    }

    anios = ["2016", "2017", "2018", "2019", "2020"]

    datasets = []
    for anio in anios:
        resp_anio = respuestas.filter(anio=anio)
        if resp_anio.count() == 0:
            continue

        datasets.append({'label': 'Satisfecho', 'data': [], 'stack': anio, 'backgroundColor': '#00d1b2', })
        datasets.append({'label': 'Neutro', 'data': [], 'stack': anio, 'backgroundColor': '#FBD561', })
        datasets.append({'label': 'Insatisfecho', 'data': [], 'stack': anio, 'backgroundColor': '#F08289', })

        for label in labels:
            insatisfecho_sum = resp_anio.filter(**{label + '__in': [1, 2, 3, 4]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0
            neutro_sum = resp_anio.filter(**{label + '__in': [5]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0
            satisfecho_sum = resp_anio.filter(**{label + '__in': [6, 7]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0

            total = insatisfecho_sum + neutro_sum + satisfecho_sum
            # if total and total >= 0:
            #     labels_with_data.append(label)
            for dataset in datasets:
                if dataset.get("label") == 'Satisfecho' and dataset.get("stack") == anio:
                    dataset["data"].append(round(satisfecho_sum / total * 100))

            for dataset in datasets:
                if dataset.get("label") == 'Neutro' and dataset.get("stack") == anio:
                    dataset["data"].append(round(neutro_sum / total * 100))

            for dataset in datasets:
                if dataset.get("label") == 'Insatisfecho' and dataset.get("stack") == anio:
                    dataset["data"].append(round(insatisfecho_sum / total * 100))

        print(datasets)

    if len(datasets) > 6:
        datasets = datasets[-6:]

    return JsonResponse({'labels': labels, 'datasets': datasets}, safe=False)

def data_atributos(request, pk=None):
    print(datetime.now())
    respuestas = Respuesta.objects.all()
    anio = 2020

    if pk:
        institucion = Institucion.objects.get(pk=pk)
        respuestas = respuestas.filter(institucion=institucion)
        anio = institucion.datos.get("anios")[-1]

    labels = ['pev_tram_facil', 'pev_tram_tiempo', 'pev_tram_claridad_pasos', 'pev_tram_info_compr',
              'pev_tram_info_util', 'pev_tram_resp_util', 'pev_tram_resp_compl', 'pev_tram_resp_clara', 'pev_tram_acogido', ]

    data = {
        'insatisfecho': [],
        'neutro': [],
        'satisfecho': []
    }

    efectivo_para_ordenar = []
    labels_with_data = []
    resp_anio = respuestas.filter(anio=anio)
    for label in labels:
        insatisfecho_sum = resp_anio.filter(**{label + '__in': [1, 2, 3, 4]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0
        neutro_sum = resp_anio.filter(**{label + '__in': [5]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0
        satisfecho_sum = resp_anio.filter(**{label + '__in': [6, 7]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0

        total = insatisfecho_sum + neutro_sum + satisfecho_sum
        if total and total >= 0:
            labels_with_data.append(label)
            data["insatisfecho"].append(round(insatisfecho_sum / total * 100))
            data["neutro"].append(round(neutro_sum / total * 100))
            data["satisfecho"].append(round(satisfecho_sum / total * 100))
            efectivo_para_ordenar.append(round(satisfecho_sum / total * 100) - round(insatisfecho_sum / total * 100))

    ordenado = sorted(range(len(efectivo_para_ordenar)), key=lambda k: efectivo_para_ordenar[k])
    labels_with_data = ordenar(labels_with_data, ordenado)
    data["insatisfecho"] = ordenar(data["insatisfecho"], ordenado)
    data["neutro"] = ordenar(data["neutro"], ordenado)
    data["satisfecho"] = ordenar(data["satisfecho"], ordenado)

    return JsonResponse({'labels': labels_with_data, 'data': data}, safe=False)

import copy

def ordenar(arreglo, ordenado):
    temp = copy.deepcopy(arreglo)
    for (i, v) in enumerate(ordenado):
        temp[i] = arreglo[v]

    return temp

def data_imagen(request, pk=None):
    respuestas = Respuesta.objects.all()
    anio = 2020

    if pk:
        institucion = Institucion.objects.get(pk=pk)
        respuestas = respuestas.filter(institucion=institucion)
        anio = institucion.datos.get("anios")[-1]

    labels = ['pi_imagen_transp', 'pi_imagen_preocupa', 'pi_imagen_actual', 'pi_imagen_funcion', 'pi_imagen_satisface']

    data = {
        'insatisfecho': [],
        'neutro': [],
        'satisfecho': []
    }

    resp_anio = respuestas.filter(anio=anio)
    labels_with_data = []
    efectivo_para_ordenar = []
    for label in labels:
        insatisfecho_sum = resp_anio.filter(**{label + '__in': [1, 2, 3, 4]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0
        neutro_sum = resp_anio.filter(**{label + '__in': [5]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0
        satisfecho_sum = resp_anio.filter(**{label + '__in': [6, 7]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0

        total = insatisfecho_sum + neutro_sum + satisfecho_sum
        if total and total >= 0:
            labels_with_data.append(label)
            data["insatisfecho"].append(round(insatisfecho_sum / total * 100))
            data["neutro"].append(round(neutro_sum / total * 100))
            data["satisfecho"].append(round(satisfecho_sum / total * 100))
            efectivo_para_ordenar.append(round(satisfecho_sum / total * 100) - round(insatisfecho_sum / total * 100))

    ordenado = sorted(range(len(efectivo_para_ordenar)), key=lambda k: efectivo_para_ordenar[k])
    labels_with_data = ordenar(labels_with_data, ordenado)
    data["insatisfecho"] = ordenar(data["insatisfecho"], ordenado)
    data["neutro"] = ordenar(data["neutro"], ordenado)
    data["satisfecho"] = ordenar(data["satisfecho"], ordenado)

    return JsonResponse({'labels': labels_with_data, 'data': data}, safe=False)

def data_dimension(request, pk=None):
    respuestas = Respuesta.objects.all()

    if pk:
        institucion = Institucion.objects.get(pk=pk)
        respuestas = respuestas.filter(institucion=institucion)

    medicion = request.GET.get("medicion", 'experiencia')

    # esto debería salir
    if medicion == 'tipo_tramite':
        medicion = 'experiencia'

    dimension = request.GET.get("dimension", 'anio')
    labels = [d[dimension] for d in respuestas.values(dimension).distinct(dimension) if d[dimension]]
    if dimension == 'tipo_tramite':
        labels = [l for l in labels if l != 'Otros']

    labels.append('Todos')

    if request.GET.get("edad"):
        respuestas = respuestas.filter(edad=request.GET.get("edad").replace("_", " "))

    if request.GET.get("sexo"):
        respuestas = respuestas.filter(sexo=request.GET.get("sexo"))

    if request.GET.get("educacion"):
        respuestas = respuestas.filter(educacion=request.GET.get("educacion"))

    if request.GET.get("habilitado"):
        respuestas = respuestas.filter(habilitado=request.GET.get("habilitado"))

    if request.GET.get("anio"):
        respuestas = respuestas.filter(anio=request.GET.get("anio"))

    data = {
        'insatisfecho': [],
        'neutro': [],
        'satisfecho': []
    }
    labels_with_data = []

    for label in labels:
        if label == 'Todos':
            resp_anio = respuestas
        else:
            resp_anio = respuestas.filter(**{dimension: label})

        insatisfecho_sum = resp_anio.filter(**{medicion + '__in': [1, 2, 3, 4]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0
        neutro_sum = resp_anio.filter(**{medicion + '__in': [5]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0
        satisfecho_sum = resp_anio.filter(**{medicion + '__in': [6, 7]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0

        total = insatisfecho_sum + neutro_sum + satisfecho_sum
        if total > 0:
            labels_with_data.append(label)

            data["insatisfecho"].append(round(insatisfecho_sum / total * 100))
            data["neutro"].append(round(neutro_sum / total * 100))
            data["satisfecho"].append(round(satisfecho_sum / total * 100))

    return JsonResponse({'labels': labels_with_data, 'data': data}, safe=False)

def data_grafica(request, pk=None):
    print(datetime.now())
    respuestas = Respuesta.objects.all()
    anios = [2016, 2017, 2018, 2019, 2020]

    if pk:
        institucion = Institucion.objects.get(pk=pk)
        respuestas = respuestas.filter(institucion=institucion)
        anios = institucion.datos.get("anios")

    medicion = request.GET.get("medicion", 'experiencia')

    if request.GET.get("edad"):
        respuestas = respuestas.filter(edad=request.GET.get("edad").replace("_", " "))

    if request.GET.get("sexo"):
        respuestas = respuestas.filter(sexo=request.GET.get("sexo"))

    if request.GET.get("educacion"):
        respuestas = respuestas.filter(educacion=request.GET.get("educacion"))

    if request.GET.get("habilitado"):
        respuestas = respuestas.filter(habilitado=request.GET.get("habilitado"))

    data = {
        'insatisfecho': [],
        'neutro': [],
        'satisfecho': []
    }

    for anio in anios:
        # if anio == 2019:
        #     import ipdb
        #     ipdb.set_trace()
        resp_anio = respuestas.filter(anio=anio)
        insatisfecho_sum = resp_anio.filter(**{medicion + '__in': [1, 2, 3, 4]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0
        neutro_sum = resp_anio.filter(**{medicion + '__in': [5]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0
        satisfecho_sum = resp_anio.filter(**{medicion + '__in': [6, 7]}).aggregate(Sum('f_pond'))["f_pond__sum"] or 0

        total = insatisfecho_sum + neutro_sum + satisfecho_sum
        if total == 0:
            data["insatisfecho"].append(None)
            data["neutro"].append(None)
            data["satisfecho"].append(None)
        else:
            data["insatisfecho"].append(round(insatisfecho_sum / total * 100))
            data["neutro"].append(round(neutro_sum / total * 100))
            data["satisfecho"].append(round(satisfecho_sum / total * 100))

    print(datetime.now())
    return JsonResponse({'labels': anios, 'data': data}, safe=False)

def resumen(request):
    datos = []
    for institucion in Institucion.objects.all():
        dato = {'nombre': institucion.nombre or institucion.datos.get("codigo")}
        for anio in [2015, 2016, 2017, 2018, 2019, 2020]:
            respuestas = Respuesta.objects.filter(anio=anio, institucion=institucion)
            if respuestas.count() == 0:
                continue

            dato[anio] = get_valores(respuestas, 'eval_inst')["neta"]
        datos.append(dato)

    return JsonResponse(datos, safe=False)

def get_valores(respuestas, medicion):
    negativo_suma = respuestas.filter(**{'{}__in'.format(medicion): [1, 2, 3, 4]}).aggregate(suma=Sum('f_pond'))["suma"] or 0
    positivo_suma = respuestas.filter(**{'{}__in'.format(medicion): [6, 7]}).aggregate(suma=Sum('f_pond'))["suma"] or 0
    neutro_suma = respuestas.filter(**{'{}__in'.format(medicion): [5]}).aggregate(suma=Sum('f_pond'))["suma"] or 0
    suma = respuestas.filter(**{'{}__in'.format(medicion): [1, 2, 3, 4, 5, 6, 7]}).aggregate(suma=Sum('f_pond'))["suma"] or 0

    if suma is not None and suma > 0:
        positivo = round((positivo_suma) / suma * 100, 0)
        negativo = round((negativo_suma) / suma * 100, 0)
        neutro = round((neutro_suma) / suma * 100, 0)
    else:
        positivo = 0
        negativo = 0
        neutro = 0

    neta = positivo - negativo
    return {
        'negativo_suma': negativo_suma,
        'negativo_suma': negativo_suma,
        'neutro_suma': neutro_suma,
        'suma': suma,
        'neta': neta,
        'positivo': positivo,
        'negativo': negativo,
        'neutro': neutro,

    }


'''
백준 1300
k번째 수

문제에서 나온대로 곧이곧대로 만들면 시간 초과, 배열이 너무 커져서 메모리 부족
그래서 이진 탐색으로 풀기로 한다.

이진탐색을 위해 왼쪽, 즉 시작점이랑 오른쪽, 즉 끝쪽을 초기화한다.
끝을 k로 두는 이유는 정렬했을때 k번째 수를 알고 싶으니까.

그리고 시작점이 끝점 이하일 동안
반복해서 이진탐색을 하는데,

중앙값mid는 시작, 끝을 더해서 2로 나눠두고 시작한다
이건 그냥 임의의 수를 구한 것이다
아무래도 중간부터 하는게 맨앞이나 맨끝보다 효율적이니까 이렇게 둔다

그리고 문제의 N바이 N 배열안의 원소가
N바이 N 배열이 i행 j열이라고 할때
i행 j열의 요소가 i*j니까

임의의 수 mid에 대해 요소 i*j가 몇개나 작거나 같은지 찾고 싶은 것이다.
그런데 i는 행이 1~N개 있으니까 그건 고정돼 있고,
j를 구하려면 i를 이항해서 mid/i 이하인 것을 찾으면 된다

그걸 찾기 위해 for문에서 i행을 (1부터 N까지) 돈다.
j가 N보다 커진다는 건 그냥 전부 다 해당된다는 거라서
N개 모두가 mid보다 작다고 봐주면 되므로
mid보다 작은 수의 개수를 세는 cnt에 그만큼 더해준다.
N보다 j가 작으면 N개 전부다 작은게 아니라
j개만큼 작은거니까 그만큼 더해준다.

그 도는게 끝나고 나서
k보다 cnt가 작다는 건 임의의 수 mid가 k보다 앞에 있다는 거고
이게 파라메트릭 서치 개념이다.
그럼 시작점을 mid다음으로 옮겨준다.

그리고 cnt가 K이상이면
답, 그러니까 자기보다 작거나 같은 수를 k개 갖고 있는 수는 임의의 수였던 mid가 된다.
while문을 종료시키기 위해 right에 mid-1을 해준다.

'''
import sys
input = sys.stdin.readline

N = int(input())
k = int(input())

left=1
right=k
ans = 0
mid = 0

while left <= right:
    mid = (left+right)/2
    cnt=0
    for i in range(1, N+1):
        cnt += min(mid/i, N)
    if cnt < k:
        left = mid+1
    else:
        ans=mid
        right=mid-1
    print(int(left), int(right), int(mid), int(ans))

print(int(ans))


""" 15. Haz un subprograma que calcule cuantas de las piezas del Sistema Monetario de España
son múltiplos exactos del valor de una determinada, conocido su orden en la edición.
Tomaremos ventaja de saber que los valores de las piezas están dados en orden descendente.

Ejemplo: Múltiplos de la cuarta (cuyo valor es 20.0) están, 500.0,200.0 y 100.0, por tanto, debe contestar 3 piezas."""

piezas = [1, 2, 5, 10, 20, 50, 100, 200, 500]

def contar_multiplos(lista, valor):
    # DEVUELVE CUANTOS VALORES DE UNA LISTA SON MULTIPLOS DE UN VALOR DETERMINADO.
    total = 0
    for i in lista:
        if i % valor == 0:
            total += 1
    return total

print(contar_multiplos(piezas, 50))


import shogi

UCT_HASH_SIZE = 2 ** 12
UCT_HASH_LIMIT = UCT_HASH_SIZE * 9 / 10
NOT_EXPANDED = -1

def hash_to_index(hash):
    """hash を index に変換する

    zobrist_hash を UCT_HASH_SIZE 未満の値に変換する

    Args:
        hash (int): hash

    Returns:
        int: index

    """
    return ((hash & 0xffffffff) ^ ((hash >> 32) & 0xffffffff)) & (UCT_HASH_SIZE - 1)

class NodeHashEntry:
    """ノード衝突情報

    Attributes:
        hash (int): zobrist_hash
        color (int in range(1)): 手番
        moves (int): 手数
        flag (bool): 使用中かどうか

    """
    def __init__(self):
        self.hash = 0
        self.color = 0
        self.moves = 0
        self.flag = False

class NodeHash:
    """ノード衝突情報管理

    Attributes:
        used (int): 使用中のノード数
        enough_size (bool): used が UCT_HASH_LIMIT を超えたかどうか
        node_hash (list of NodeHashEntry): ノード一覧

    """
    def __init__(self):
        self.used = 0
        self.enough_size = True
        self.node_hash = None

    def initialize(self):
        self.used = 0
        self.enough_size = True
        if self.node_hash is None:
            self.node_hash = [NodeHashEntry() for _ in range(UCT_HASH_SIZE)]
        else:
            for i in range(UCT_HASH_SIZE):
                self.node_hash[i].hash = 0
                self.node_hash[i].color = 0
                self.node_hash[i].moves = 0
                self.node_hash[i].flag = False

    def __getitem__(self, i):
        return self.node_hash[i]

    def search_empty_index(self, hash, color, moves):
        """未使用のノードを探す

        未使用のノードがあれば、衝突情報を書き込んで該当ノードの index を返す
        全てのノードが使用中の場合は UCT_HASH_SIZE を返す

        Args:
            hash (int): hash
            color (int in range(1)): 手番
            moves (int): 手数

        Returns:
            int: index

        """
        key = hash_to_index(hash)
        i = key

        while True:
            if not self.node_hash[i].flag:
                self.node_hash[i].hash = hash
                self.node_hash[i].color = color
                self.node_hash[i].moves = moves
                self.node_hash[i].flag = True
                self.used += 1
                if self.used > UCT_HASH_LIMIT:
                    self.enough_size = False
                return i
            i += 1
            if i >= UCT_HASH_SIZE:
                i = 0
            if i == key:
                return UCT_HASH_SIZE

    def find_same_hash_index(self, hash, color, moves):
        """hash に対応するノードを探す

        対応するノードがあれば、該当ノードの index を返す
        なければ UCT_HASH_SIZE を返す

        Args:
            hash (int): hash
            color (int in range(1)): 手番
            moves (int): 手数

        Returns:
            int: index

        """
        key = hash_to_index(hash)
        i = key

        while True:
            if not self.node_hash[i].flag:
                return UCT_HASH_SIZE
            elif self.node_hash[i] == hash and self.node_hash[i].color == color and self.node_hash[i].moves == moves:
                return i
            i += 1
            if i >= UCT_HASH_SIZE:
                i = 0
            if i == key:
                return UCT_HASH_SIZE

    def save_used_hash(self, board, uct_node, index):
        """uct_node[index] と展開済みの子孫を使用中にする

        Args:
            board (shogi.Board): 盤面
            uct_node (list of UctNode): ノード情報
            index (int): 使用中にする index

        Returns:
            int: index

        Todo:
            board unnecessary?

        """
        self.node_hash[index].flag = True
        self.used += 1

        current_node = uct_node[index]
        child_index = current_node.child_index
        child_move = current_node.child_move
        child_num = current_node.child_num
        for i in range(child_num):
            if child_index[i] != NOT_EXPANDED and self.node_hash[child_index[i]].flag == False:
                board.push(child_move[i])
                self.save_used_hash(board, uct_node, child_index[i])
                board.pop()

    def delete_old_hash(self, board, uct_node):
        """盤面と展開済みの子孫以外のノードを未使用にする

        Args:
            board (shogi.Board): 盤面
            uct_node (list of UctNode): ノード情報

        """
        root = self.find_same_hash_index(board.zobrist_hash(), board.turn, board.move_number)
        self.used = 0
        for i in range(UCT_HASH_SIZE):
            self.node_hash[i].flag = False
        if root != UCT_HASH_SIZE:
            self.save_used_hash(board, uct_node, root)

        self.enough_size = True

    def get_usage_rate(self):
        """ノード衝突情報使用率

        Returns:
            ノード衝突情報使用率

        """
        return self.used / UCT_HASH_SIZE

class UctNode:
    """ノード情報

    Attributes:
        move_count (int): 訪問回数
        win (float in [0.0, 1.0]): 合計勝率
        child_num (int): 子ノードの数
        child_move (list of int): 子ノードの指し手
        child_index (list of int): 子ノードの index
        child_move_count (list of int): 子ノードの訪問回数
        child_win (list of float): 子ノードの合計勝率
        nnrate (list of float): policy network の予測確率
        value_win (int): value network の予測勝率
        evaled (bool): 評価済みフラグ

    """
    def __init__(self):
        self.move_count = 0
        self.win = 0.0
        self.child_num = 0
        self.child_move = None
        self.child_index = None
        self.child_move_count = None
        self.child_win = None
        self.nnrate = None
        self.value_win = 0.0
        self.evaled = False


class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """

        #一次循环解决，把旋转的4个坐标计算出来，对4个元素进行替换既可。
        n = len(matrix[0])
        for i in range(n // 2 + n % 2):
            for j in range(n // 2):
                tmp = matrix[n - 1 - j][i]
                matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1]
                matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 -i]
                matrix[j][n - 1 - i] = matrix[i][j]
                matrix[i][j] = tmp

        #好理解的想法，先转置再镜像
        n = len(matrix[0])
        # transpose matrix
        for i in range(n):
            for j in range(i, n):
                matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i]

        # reverse each row
        for i in range(n):
            matrix[i].reverse()


'''
	删除《2号机》每个文件中的无用数据（前43行和前两列后三列）
'''
import os
import pandas as pd
import numpy as np

res=r'G:\\Desktop\\风机\\code\\2号机\\'          		#处理前原始所有dat文件所在的文件夹
list = r'G:\\Desktop\\风机\\code\\1_datalist.txt' 		 #dat数据名字汇总txt
savePath=r'G:\\Desktop\\风机\\code\\1_datasorting_allfiles\\'  		 #处理后保存所有dat文件所在的文件夹

f = open(list,'r')							#从汇总txt逐个读取原始文件
lines = f.readlines()
for line in lines[:]:
	name = line.strip()
	resfile=res+name 				  			#每次要处理的dat文件路径
	openFileHandle=open(resfile,'r')
	savefile=savePath+name[:-4]+'.txt'			#每次处理后的txt文件保存路径
	writeFileHandle=open(savefile,'w')

	for line in openFileHandle.readlines()[43:]: #删去原始文件中无用的前42行
  		writeFileHandle.write(line)

openFileHandle.close()
writeFileHandle.close()

for line in lines[:]:						#从汇总txt逐个读取处理后的文件
	name = line.strip()
	savefile=savePath+name[:-4]+'.txt'
	a=np.loadtxt(savefile) 						 #删去原始文件中无用的列(前两列和后两列)
	a=np.around(a[:,2:-3],decimals=2)
	np.savetxt(savefile,a,fmt="%.2f")


recem_nascido = {
    'nome' : '',
    'data_nascimento' : '',
    'peso_nascimento' : 0,
    'altura' : 0,
    'mae_bebe' : '',
    'medico_parto' : '',
    }

mae  = {
    'nome' : '',
    'endereco' : '',
    'telefone' : 0,
    'data_nascimento' : ''
}

medico = {
    'nome' : '',
    'crm' : 0,
    'telefone' : 0,
    'especialidade' : ''
}

print('DIGITE OS DADOS DO RECÉM NASCIDO')
print(50 * '-')
recem_nascido['nome'] = str(input('Digite o nome do recém nascido: '))
recem_nascido['data_nascimento'] = str(input('Digite a data de nascimento: '))
recem_nascido['peso_nascimento'] = float(input('Digite o peso do nascimento em Kg: '))
recem_nascido['altura'] = int(input('Digite a altura do recém nascido em cm: '))
recem_nascido['mae_bebe'] = str(input('Digite o nome da mãe do recém nascido: '))
recem_nascido['medico'] = str(input('Digite o médico responsável pelo parto: '))

print(50 * '-')
print('DIGITE OS DADOS DA MÃE')
mae['nome'] = str(input('Digite o nome da mãe: '))
mae['endereco'] = str(input('Digite o endereço (RUA): '))
mae['telefone'] = (input('Digite o número de telefone: '))
mae['data_nascimento'] = str(input('Digite a data de nascimento da mãe: '))

print(50 * '-')
print('DIGITE OS DADOS DO MÉDICO')
medico['nome'] = str(input('Digite o nome do médico: '))
medico['crm'] = int(input('Digite o CRM do médico: '))
medico['telefone'] = int(input('Digite o número de telefone do médico: '))
medico['especialidade'] = str(input('Digite a especialidade do médico: '))

print(recem_nascido)
print(mae)
print(medico)


# -*- coding: cp950 -*-

# 寄售形象選擇界面
CommissionSale = {
	'stClew'		 : { 'color' : (1.0, 255.0, 216.0), 'text' : "請左鍵點擊選擇你喜歡的寄售NPC形象。" },	# "commissionsale:CommissionSale", "stClew"
	'btnCommiss'	 : { 'color' : (255.0, 248.0, 158.0), 'text' : "開始寄售" },	# "commissionsale:CommissionSale", "btnCommiss"
	'lbTitle'		 : { 'color' : (239.0, 231.0, 110.0), 'text' : "形象選擇" },	# "commissionsale:CommissionSale", "lbTitle"
	'shopName'		 : { 'text'	 : "的店鋪" },	# "commissionsale:CommissionSale", "shopName"
}

# 店鋪查詢主界面
CommissionViewer = {
	'tb_merchant'	 : { 'text' : "店主查詢" },	# "commissionsale:CommissionViewer", "tb_merchant"
	'tb_pet'		 : { 'text' : "寵物查詢" },	# "commissionsale:CommissionViewer", "tb_pet"
	'tb_goods'		 : { 'text' : "物品查詢" },	# "commissionsale:CommissionViewer", "tb_goods"
	'lbTitle'		 : { 'color' : (241.0, 232.0, 110.0), 'text' : "店鋪查詢" },	# "commissionsale:CommissionViewer", "lbTitle"
}

# 店主查詢面板
MerchantPanel = {
	'stClewCondition'		 : { 'color' : (0.0, 255.0, 0.0), 'text' : "請確定查詢條件後點擊“查找”按鈕進行查找！" },	# "commissionsale:MerchantPanel", "stClewCondition"
	'stClewSearching'		 : { 'color' : (0.0, 255.0, 0.0), 'text' : "正在查找..." },	# "commissionsale:MerchantPanel", "stClewSearching"
	'stClewNotFound'		 : { 'color' : (0.0, 255.0, 0.0), 'text' : "未找到相關數據" },	# "commissionsale:MerchantPanel", "stClewNotFound"
	'taxisBtn_0'	 : { 'text' : "店鋪名稱" },	# "commissionsale:MerchantPanel", "taxisBtn_0"
	'taxisBtn_1'	 : { 'text' : "店主名" },	# "commissionsale:MerchantPanel", "taxisBtn_1"
	'btnSearch'		 : { 'text' : "查 找" },	# "commissionsale:MerchantPanel", "btnSearch"
	'stKeyWord'		 : { 'color' : (6.0, 243.0, 204.0), 'text' : "按店主名查找" },	# "commissionsale:MerchantPanel", "stKeyWord"
}

# 物品查詢面板
GoodsPanel = {
	# .dirText
	'stClewCondition'		 : { 'color' : (0.0, 255.0, 0.0), 'text' : "請確定查詢條件後點擊“查找”按鈕進行查找！" },	# "commissionsale:GoodsPanel", "stClewCondition"
	'stClewSearching'		 : { 'color' : (0.0, 255.0, 0.0), 'text' : "正在查找..." },	# "commissionsale:GoodsPanel", "stClewSearching"
	'stClewNotFound'		 : { 'color' : (0.0, 255.0, 0.0), 'text' : "未找到相關數據" },	# "commissionsale:GoodsPanel", "stClewNotFound"
	# .cbMR
	'cbMR_All'		 : { 'text' : "全部職業" },	# "commissionsale:GoodsPanel", "cbMR_All"
	'cbMR_Warrior'	 : { 'text' : "戰士" },	# "commissionsale:GoodsPanel", "cbMR_Warrior"
	'cbMR_Swordman'	 : { 'text' : "劍客" },	# "commissionsale:GoodsPanel", "cbMR_Swordman"
	'cbMR_Archer'	 : { 'text' : "射手" },	# "commissionsale:GoodsPanel", "cbMR_Archer"
	'cbMR_Magician'	 : { 'text' : "法師" },	# "commissionsale:GoodsPanel", "cbMR_Magician"
	# .cbTY
	'cbTY_All'		 : { 'text' : "全部類型" },	# "commissionsale:GoodsPanel", "cbTY_All"
	'cbTY_Weapon'	 : { 'text' : "武器" },	# "commissionsale:GoodsPanel", "cbTY_Weapon"
	'cbTY_Armour'	 : { 'text' : "防具" },	# "commissionsale:GoodsPanel", "cbTY_Armour"
	'cbTY_Material'	 : { 'text' : "材料" },	# "commissionsale:GoodsPanel", "cbTY_Material"
	'cbTY_Other'	 : { 'text' : "其他" },	# "commissionsale:GoodsPanel", "cbTY_Other"
	# .cbQA
	'cbQA_All'		 : { 'text' : "全部品質" },	# "commissionsale:GoodsPanel", "cbQA_All"
	'cbQA_White'	 : { 'text' : "白色" },	# "commissionsale:GoodsPanel", "cbQA_White"
	'cbQA_Blue'		 : { 'text' : "藍色" },	# "commissionsale:GoodsPanel", "cbQA_Blue"
	'cbQA_Yellow'	 : { 'text' : "黃色" },	# "commissionsale:GoodsPanel", "cbQA_Yellow"
	'cbQA_Pink'		 : { 'text' : "粉色" },	# "commissionsale:GoodsPanel", "cbQA_Pink"
	'cbQA_Green'	 : { 'text' : "綠色" },	# "commissionsale:GoodsPanel", "cbQA_Green"
	'cbQA_Orange'	 : { 'text' : "橘色" },
	'cbQA_Purple'	 : { 'text' : "紫色" },
	# btn
	'btnSearch'		 : { 'text' : "查找" },	# "commissionsale:GoodsPanel", "btnSearch"
	'btnBuy'		 : { 'text' : "購 買" },	# "commissionsale:GoodsPanel", "btnBuy"
	# taxisBtn
	'taxisBtn_4'		 : { 'text' : "品質" },	# "commissionsale:GoodsPanel", "taxisBtn_4"
	'taxisBtn_3'		 : { 'text' : "價格" },	# "commissionsale:GoodsPanel", "taxisBtn_3"
	'taxisBtn_2'		 : { 'text' : "店主名" },	# "commissionsale:GoodsPanel", "taxisBtn_2"
	'taxisBtn_1'		 : { 'text' : "等級" },	# "commissionsale:GoodsPanel", "taxisBtn_1"
	# stext
	'stLVRange'		 : { 'color' : (6.0, 243.0, 204.0), 'text' : "等級範圍" },	# "commissionsale:GoodsPanel", "stLVRange"
	'stSplit'		 : { 'color' : (6.0, 243.0, 204.0), 'text' : "-" },	# "commissionsale:GoodsPanel", "stSplit"
	'stOwnMoney'		 : { 'color' : (6.0, 243.0, 204.0), 'text' : "您的金錢" },	# "commissionsale:GoodsPanel", "stOwnMoney"
}

# 顯示金錢的列項
MoneyCol = {
	"gold"		: { 'text' : "金" },		# "commissionsale:MoneyCol", "gold"
	"silver"	: { 'text' : "銀" },		# "commissionsale:MoneyCol", "silver"
	"coin"		: { 'text' : "銅" },		# "commissionsale:MoneyCol", "coin"
}

# 寵物查詢面板
PetPanel = {
	# .dirText
	'stClewCondition'		 : { 'color' : (0.0, 255.0, 0.0), 'text' : "請確定查詢條件後點擊“查找”按鈕進行查找！" },	# "commissionsale:PetPanel", "stClewCondition"
	'stClewSearching'		 : { 'color' : (0.0, 255.0, 0.0), 'text' : "正在查找..." },	# "commissionsale:PetPanel", "stClewSearching"
	'stClewNotFound'		 : { 'color' : (0.0, 255.0, 0.0), 'text' : "未找到相關數據" },	# "commissionsale:PetPanel", "stClewNotFound"
	# .cbGender
	'cbGender_All'		 : { 'text' : "全部性別" },	# "commissionsale:PetPanel", "cbGender_All"
	'cbGender_Male'		 : { 'text' : "雄性" },	# "commissionsale:PetPanel", "cbGender_Male"
	'cbGender_Female'	 : { 'text' : "雌性" },	# "commissionsale:PetPanel", "cbGender_Female"
	# .cbBreed
	'cbBreed_All'		 : { 'text' : "繁殖狀況" },	# "commissionsale:PetPanel", "cbBreed_All"
	'cbBreed_Progenitive'		 : { 'text' : "未繁殖" },	# "commissionsale:PetPanel", "cbBreed_Progenitive"
	'cbBreed_Irreproducible'	 : { 'text' : "已繁殖" },	# "commissionsale:PetPanel", "cbBreed_Irreproducible"
	# .cbMR
	'cbMR_All'			 : { 'text' : "全部類型" },	# "commissionsale:PetPanel", "cbMR_All"
	'cbMR_Balanced'		 : { 'text' : "均衡型" },	# "commissionsale:PetPanel", "cbMR_Balanced"
	'cbMR_Nimble'		 : { 'text' : "敏捷型" },	# "commissionsale:PetPanel", "cbMR_Nimble"
	'cbMR_Intellective'	 : { 'text' : "智力型" },	# "commissionsale:PetPanel", "cbMR_Intellective"
	'cbMR_Potent'		 : { 'text' : "力量型" },	# "commissionsale:PetPanel", "cbMR_Potent"
	# .cbEra
	'cbEra_All'			 : { 'text' : "全部規格" },	# "commissionsale:PetPanel", "cbEra_All"
	'cbEra_Grown'		 : { 'text' : "成年寵物" },	# "commissionsale:PetPanel", "cbEra_Grown"
	'cbEra_Era1'		 : { 'text' : "一代寶寶" },	# "commissionsale:PetPanel", "cbEra_Era1"
	'cbEra_Era2'		 : { 'text' : "二代寶寶" },	# "commissionsale:PetPanel", "cbEra_Era2"
	# taxisBtns
	'taxisBtn_7'		 : { 'text' : "價格" },	# "commissionsale:PetPanel", "taxisBtn_7"
	'taxisBtn_6'		 : { 'text' : "店主名" },	# "commissionsale:PetPanel", "taxisBtn_6"
	'taxisBtn_5'		 : { 'text' : "等級" },	# "commissionsale:PetPanel", "taxisBtn_5"
	'taxisBtn_4'		 : { 'text' : "繁殖" },	# "commissionsale:PetPanel", "taxisBtn_4"
	'taxisBtn_3'		 : { 'text' : "性別" },	# "commissionsale:PetPanel", "taxisBtn_3"
	'taxisBtn_2'		 : { 'text' : "類型" },	# "commissionsale:PetPanel", "taxisBtn_2"
	'taxisBtn_1'		 : { 'text' : "規格" },	# "commissionsale:PetPanel", "taxisBtn_1"
	'taxisBtn_0'		 : { 'text' : "名稱" },	# "commissionsale:PetPanel", "taxisBtn_0"
	# btns
	'btnProperty'		 : { 'text' : "查看屬性" },	# "commissionsale:PetPanel", "btnProperty"
	'btnSearch'		 : { 'text' : "查找" },	# "commissionsale:PetPanel", "btnSearch"
	'btnBuy'		 : { 'text' : "購 買" },	# "commissionsale:PetPanel", "btnBuy"
	# stext
	'stLVRange'		 : { 'color' : (6.0, 243.0, 204.0), 'text' : "等級範圍" },	# "commissionsale:PetPanel", "stLVRange"
	'stSplit'		 : { 'color' : (6.0, 243.0, 204.0), 'text' : "-" },	# "commissionsale:PetPanel", "stSplit"
	'stOwnMoney'		 : { 'color' : (6.0, 243.0, 204.0), 'text' : "您的金錢" },	# "commissionsale:PetPanel", "stOwnMoney"
	# 以下是為了以後需要到而作的記錄，例如可能會修改字體
	# .coinBox.lbText
	'textBox_Coin'		 : { 'color' : (6.0, 243.0, 204.0), 'text' : "99" },	# "commissionsale:PetPanel", "textBox_Coin"
	# .silverBox.lbText
	'textBox_Silver'	 : { 'color' : (6.0, 243.0, 204.0), 'text' : "99" },	# "commissionsale:PetPanel", "textBox_Silver"
	# .goldBox.lbText
	'textBox_Gold'		 : { 'color' : (6.0, 243.0, 204.0), 'text' : "99999999" },	# "commissionsale:PetPanel", "textBox_Gold"
	# .idxCtrl.stPgIndex
	'stPgIndex'		 : { 'text' : "5" },	# "commissionsale:PetPanel", "stPgIndex"
}

# PCBuyWindow
PCBuyWindow = {
	# .cb_3000.stext
	'cb3000'		 : { 'text' : "XXXX" },	# "commissionsale:PCBuyWindow", "cb3000"
	# .cb_1000.stext
	'cb1000'		 : { 'text' : "XXXX" },	# "commissionsale:PCBuyWindow", "cb1000"
	'btnCancel'		 : { 'text' : "取 消" },	# "commissionsale:PCBuyWindow", "btnCancel"
	'stChoose'		 : { 'text' : "面額選擇:" },	# "commissionsale:PCBuyWindow", "stChoose"
	'btnBuy'		 : { 'text' : "購 買" },	# "commissionsale:PCBuyWindow", "btnBuy"
	'taxisBtn_3'	 : { 'text' : "剩餘時間" },	# "commissionsale:PCBuyWindow", "taxisBtn_3"
	'taxisBtn_2'	 : { 'text' : "售價" },	# "commissionsale:PCBuyWindow", "taxisBtn_2"
	'taxisBtn_1'	 : { 'text' : "面額" },	# "commissionsale:PCBuyWindow", "taxisBtn_1"
	'lbTitle'		 : { 'color' : (241.0, 232.0, 110.0), 'text' : "購買點卡" },	# "commissionsale:PCBuyWindow", "lbTitle"
}

# 點卡購買窗口的時間列項
TimeCol = {
	'leaveTime_second'	: { 'text' : "%d秒" },	# "commissionsale:TimeCol", "leaveTime_second"
	'leaveTime_hour'	: { 'text' : "%d時" },	# "commissionsale:TimeCol", "leaveTime_hour"
	'leaveTime_minute'	: { 'text' : "%d分" },	# "commissionsale:TimeCol", "leaveTime_minute"
	'leaveTime_end'		: { 'text' : "寄售結束！" },	# "commissionsale:TimeCol", "leaveTime_end"
}

# 點卡出售窗口
PCSellWindow = {
	# clewText
	'explanation'	 : { 'text' : "1、寄售點卡需要支付押金，10元卡需要5金，@S{4}30元卡需要10金，押金在成功售出後退還。@S{3}若寄售點卡為無效點卡，押金將被沒收。@B{2}2、寄售點卡在24小時內無人購買，點卡將退回，@S{3}而押金將被沒收。"},	# "commissionsale:PCSellWindow", "explanation"
	'prompt'		 : { 'text' : "請輸入寄售點卡的卡號，密碼和寄售價格@F{fc=(211,175,9,255)}(請注意您的點卡不一定有人購買，所以請繼續保管好您的卡號和密碼)@D" },	# "commissionsale:PCSellWindow", "prompt"
	# btns
	'btnOK'			 : { 'text' : "確 定" },	# "commissionsale:PCSellWindow", "btnOK"
	'btnCancel'		 : { 'text' : "取 消" },	# "commissionsale:PCSellWindow", "btnCancel"
	# stText
	'lbTitle'		 : { 'color' : (241.0, 232.0, 110.0), 'text' : "寄售點卡" },	# "commissionsale:PCSellWindow", "lbTitle"
	'stResume'		 : { 'color' : (21.0, 195.0, 161.0), 'text' : "寄售說明" },	# "commissionsale:PCSellWindow", "stResume"
	'stInputTitle'	 : { 'color' : (21.0, 195.0, 161.0), 'text' : "點卡輸入" },	# "commissionsale:PCSellWindow", "stInputTitle"
	'stCardNo'		 : { 'text' : "卡    號：" },	# "commissionsale:PCSellWindow", "stCardNo"
	'stCardPsw'		 : { 'text' : "密    碼：" },	# "commissionsale:PCSellWindow", "stCardPsw"
	'stCardPrice'	 : { 'text' : "寄售價格：" },	# "commissionsale:PCSellWindow", "stCardPrice"
	'serverName'	 : { 'text' : "永�琱坏�" },	# "commissionsale:PCSellWindow", "serverName"
}

# TiShouSellPanel
TiShouSellPanel = {
	# 攤位形象選擇框
	'stallModel'		 : { 'text' : "攤位形象" },	# "commissionsale:TiShouSellPanel", "stallModel"
	'colouredGlazeFox'	 : { 'text' : "琉璃狐" },	# "commissionsale:TiShouSellPanel", "colouredGlazeFox"
	'blueTiger'			 : { 'text' : "藍色老虎" },	# "commissionsale:TiShouSellPanel", "blueTiger"
	'yellowTiger'		 : { 'text' : "黃色老虎" },	# "commissionsale:TiShouSellPanel", "yellowTiger"
	'lightningDog'		 : { 'text' : "閃電狗" },	# "commissionsale:TiShouSellPanel", "lightningDog"
	'bigHeadRacoon'		 : { 'text' : "大頭浣熊" },	# "commissionsale:TiShouSellPanel", "bigHeadRacoon"
	'blueMandarinDuck'	 : { 'text' : "藍色鴛鴦" },	# "commissionsale:TiShouSellPanel", "blueMandarinDuck"
	'fortunatePig'		 : { 'text' : "發財豬" },	# "commissionsale:TiShouSellPanel", "fortunatePig"
	# 剩餘時間提示
	'stRemainTime'		 : { 'color' : (6.0, 228.0, 192.0), 'text' : "寄售剩餘時間：" },	# "commissionsale:TiShouSellPanel", "stRemainTime"
	'stHour'		 : { 'color' : (6.0, 228.0, 192.0), 'text' : "%d小時" },	# "commissionsale:TiShouSellPanel", "stHour"
	'stMinute'		 : { 'color' : (6.0, 228.0, 192.0), 'text' : "%d分鐘" },	# "commissionsale:TiShouSellPanel", "stMinute"
	'stSecond'		 : { 'color' : (6.0, 228.0, 192.0), 'text' : "%d秒" },	# "commissionsale:TiShouSellPanel", "stSecond"
	# 攤主名
	'stOwnerName'	 : { 'text' : "店主：" },	# "commissionsale:TiShouSellPanel", "stOwnerName"
}

# TiShouGoodsPanel
TiShouGoodsPanel = {
	'ipBoxPrice'	 : { 'text' : "請輸入商品售價" },	# "commissionsale:TiShouGoodsPanel", "ipBoxPrice"
	'ipBoxNewPrice'	 : { 'text' : "請輸入新價格" },	# "commissionsale:TiShouGoodsPanel", "ipBoxNewPrice"
}

# TiShouPetsPanel
TiShouPetsPanel = {
	'ipBoxPrice'	 : { 'text' : "請輸入出售價格" },	# "commissionsale:TiShouPetsPanel", "ipBoxPrice"
	'ipBoxNewPrice'	 : { 'text' : "請輸入新價格" },	# "commissionsale:TiShouPetsPanel", "ipBoxNewPrice"
}

# 擺攤收購面板
TiShouPurchasePanel = {
	'ipBoxPrice'		 : { 'text' : "輸入單價" },	# "commissionsale:TiShouPurchasePanel", "ipBoxPrice"
	'ipBoxPurchaseAmount'	 : { 'text' : "收購數量" },	# "commissionsale:TiShouPurchasePanel", "ipBoxPurchaseAmount"
	'ipBoxTotalPrice'	 : { 'text' : "收購總額" },	# "commissionsale:TiShouPurchasePanel", "ipBoxTotalPrice"
	'ipBoxPurchaseSetting'	 : { 'text' : "收購設置" },	# "commissionsale:TiShouPurchasePanel", "ipBoxPurchaseSetting"
	'ipBoxNewPrice'		 : { 'text' : "請輸入新價格" },	# "commissionsale:TiShouPurchasePanel", "ipBoxNewPrice"
}

TSBuyPurchasePenel = {
	'ipBoxPrice'		 : { 'text' : "收購單價:" },	# "commissionsale:TSBuyPurchasePenel", "ipBoxPrice"
	'ipBoxPurchaseAmount'		 : { 'text' : "出售數量:" },	# "commissionsale:TSBuyPurchasePenel", "ipBoxPurchaseAmount"
	'ipBoxTotalPrice'		 : { 'text' : "收入總額:" },	# "commissionsale:TSBuyPurchasePenel", "ipBoxTotalPrice"
	'ipBoxPurchaseSetting'		 : { 'text' : "出售設置:" },	# "commissionsale:TSBuyPurchasePenel", "ipBoxPurchaseSetting"
}

TSSellWindow = {
	'shopName'		 : { 'text' : "%s的店鋪" },	# "commissionsale:TSSellWindow", "shopName"
}


import os

import click
from control import explorer_path, get_parent_directory, handle_control_keys, tools_path
from pyfzf.pyfzf import FzfPrompt
from state import MODES, Combination, Processedpath, State
from view import get_output_string

home = os.path.expanduser("~")
history_file = f"{explorer_path}/history"
state = State(os.getcwd(), [], "", MODES.OPEN, "", [])

def assign_combinations(subpaths, state):
    starting_char = []
    starting_charpairs = []

    identifier_chars = [x for x in "asdfjkl;qweruiopzsxcvnm,."]
    processed_paths = []

    for path in subpaths:
        full_path = f"{state.current_folder}/{path}"
        if path.endswith("/"):
            path = path[:-1]
        if len(path) < 2:
            continue
        path = path.split("/")[-1].replace("\n", "")
        processed_paths.append(Processedpath(full_path, path))
        starting_char.append(path[0])
        starting_charpairs.append(path[:2])

    final_keybind_char_lookup = {
        charpair: identifier_chars.copy() for charpair in starting_charpairs
    }
    # Get combinations

    combinations = []
    for path in processed_paths:
        c1, c2 = path.shorthand[:2]
        if len([x for x in starting_char if x == c1]) == 1:  # unique starting char
            combination = Combination(path, c1)
            combinations.append(combination)
        elif (
            len([x for x in starting_charpairs if x == c1 + c2]) == 1
        ):  # unique starting char
            combinations.append(Combination(path, c1 + c2))
        else:
            identifier_list = final_keybind_char_lookup[path.shorthand[:2]]
            if len(identifier_list) == 0:
                continue
            identifier = identifier_list.pop(0)
            combinations.append(Combination(path, c1 + c2 + identifier))
    state.combinations = combinations
    return state

def add_to_history_file(full_path):
    HISTORY_LEN = 100
    history_file = f"{explorer_path}/history"
    with open(history_file, "r") as f:
        paths = f.read().split("\n")[-HISTORY_LEN:]
    if full_path not in paths:
        paths.append(full_path)
        with open(history_file, "w") as f:
            f.write("\n".join(paths))

while True:
    if state.current_folder.startswith("//"):
        state.current_folder = state.current_folder[1:]
    ## Prepare keybinds
    subpaths = os.listdir(state.current_folder)

    if state.mode == MODES.BOOKMARK:
        with open(f"{explorer_path}/bookmarks", "r") as f:
            subpaths = f.read().split("\n")
    elif state.mode == MODES.HISTORY:
        with open(f"{explorer_path}/history", "r") as f:
            subpaths = f.read().split("\n")

    subpaths.sort()
    if state.mode in [MODES.SEARCH, MODES.HISTORY]:
        print(state.current_folder)
        prompt = FzfPrompt()
        selected_path = prompt.prompt(subpaths)
        if len(selected_path) == 0:
            state.mode = MODES.OPEN
            continue
        path = os.path.join(state.current_folder, selected_path[0])
        final_result = True
        if state.mode == MODES.HISTORY:
            state.mode = MODES.OPEN
    else:
        state = assign_combinations(subpaths, state)
        # UI loop
        get_output_string(state)
        final_result = False
        state.cur_selection = []
        state.curkey = ""
        while True:
            char = click.getchar()
            # input(f"u pressed {char} with {len(char)}")
            if char == " " and handle_control_keys(state):
                break

            elif char == "\x1b":
                state.current_folder = get_parent_directory(state.current_folder)
                os.system("clear")
                break

            os.system("clear")
            state.curkey += char
            state.cur_selection = [
                x for x in state.combinations if x.keybind.startswith(state.curkey)
            ]
            if len(state.cur_selection) == 1:
                path = state.cur_selection[0].path.full_path
                if state.mode == MODES.BOOKMARK:
                    path = path.replace(state.current_folder, "")
                    state.mode = MODES.OPEN
                final_result = True
                break
            elif len(state.cur_selection) == 0:
                state.cur_selection = state.combinations
                state.curkey = ""
            get_output_string(state)

    if final_result:
        add_to_history_file(path)
        if os.path.isfile(path):
            if state.mode in [MODES.OPEN, MODES.SEARCH]:
                if path.split(".")[-1] in ["xlsx", "csv", "pkl"]:
                    os.system(f'python3 {tools_path}/csv_master/csv_master.py "{path}"')
                else:
                    os.system(f'xdg-open "{path}" &')
            elif state.mode == MODES.COPY or state.mode == MODES.MOVE:
                # os.system(f'clip.exe "{filepath}"')
                state.path_to_copy = path
                state.curkey = ""
            elif state.mode == MODES.DELETE:
                os.system(f"rm {path}")
                # state.current_folder = path
        else:
            state.curkey = ""
            state.current_folder = path


from itertools import compress, count
num = count()
even = [True,False]*10
odd = [False, True]*10
even = compress(num,even)
num=count()
odd = compress(num,odd)
print(odd)
print("The first 10 even numbers: ")
for n in even:
    print(n,end=",")
print()
print("First 10 odd numbers: ")
for x in odd:
    print(x,end=",")


import pathlib
from setuptools import setup, find_packages

__dir__ = pathlib.Path(__file__).resolve().parent

def get_file(file: pathlib.Path) -> str:
    """Extract all lines from a file."""
    with open(file, "r") as f:
        return f.read()

setup(
    name="sepaq_crawler",
    author="Antoine Prouvost",
    description="Utility to crawl the SEPAQ API.",
    long_description=get_file(__dir__ / "README.md"),
    license="MIT",
    url="https://github.com/AntoinePrv/Sepaq-Crawler",
    version="0.1.0",
    packages=find_packages(where="src"),
    package_dir={"": "src"},
    install_requires=["requests", "click", "geopy", "notify-py"],
)


import math
import tkinter as tk
from tkinter import messagebox
from tkinter import *
import os

def  screen():
    global main_screen
    global no,o,op

    main_screen= Tk ()
    main_screen.geometry("300x250")
    main_screen.title("Graphical Calculator")
    main_screen['bg']='green'

    no = IntVar()
    o = IntVar()

    op=StringVar()
    d=DoubleVar()

    Label(main_screen,text="enter first no.", bg="blue", width="300", height="2", font=("Calibri", 24)).pack()
    first_entry = Entry(main_screen,font=('calibri',24),bg="maroon" , textvariable=no).pack()
    Label(main_screen,text="enter second no.", bg="blue", width="300", height="2", font=("Calibri",24)).pack()

    second_entry = Entry(main_screen,font=('calibri',24),bg="maroon" ,textvariable=o).pack()
    Label(main_screen,text="enter operator", bg="blue", width="300", height="2", font=("Calibri",24)).pack()
    opt = Entry(main_screen,font=('calibri',24),bg="maroon", textvariable=op).pack()
    Button(main_screen,text="calculate", height="2",bg="aqua",width="30",font=("calibri",24), command = calculation ).pack()
    Button(main_screen,text="exit the pages", height="2",bg="aqua",width="30",font=("calibri",24), command =ExitApplication1 ).pack()

    Label(main_screen,text="", bg="red", width="300", height="2", font=("Calibri", 24)).pack()
    Label(main_screen,text="", bg="red", width="300", height="2", font=("Calibri", 24)).pack()
    Label(main_screen,text="", bg="red", width="300", height="2", font=("Calibri", 24)).pack()

    main_screen.mainloop()

def calcu(a,b,opt):

    if opt=="*" :
        d=a*b
    elif opt == "/":
        d=a/b
    elif opt == "+":
        d=a+b

    elif opt == "-":
        d=a-b
    elif opt == 'square of a':
        d=a*a
    elif opt == 'square of b':
        d=b*b
    elif opt == 'cube of a':
        d=a*a*a

    elif opt == 'cube of b':
        d=b*b*b
    elif opt == 'a sq - b sq':
        d=(a*a)-(b*b)
    elif opt == '(a+b)sq':
        d=(a+b)*(a+b)
    elif opt == '(a+b)sq':
        d=(a-b)*(a-b)

    elif opt == 'a sq + b sq':
        d=(a*a)+(b*b)
    elif opt == 'a cube - b cube':
        d=(a*a*a)-(b*b*b)
    elif opt == 'a cube + b cube':
        d=(a*a*a)+(b*b*b)
    elif opt == '(a+b) cube':
        d=(a+b)*(a+b)*(a+b)

    elif opt == '(a-b) cube':
        d=(a-b)*(a-b)*(a-b)
    elif opt == 'sq rt of a':
        d=math.sqrt(a)
    elif opt == 'sq rt of b':
        d=math.sqrt(b)
    elif opt == 'cube rt of a':
        d=a**(1/3)

    elif opt == 'cube rt of b':
        d=b**(1/3)
    elif opt=='check remainder of a/b' or 'mod of a/b' or 'mod a/b' :
        d=a % b
    elif opt=='check remainder of b/a' or 'mod of b/a' or 'mod b/a' :
        d=b % a
    return d

def ExitApplication1():
    MsgBox = tk.messagebox.askquestion ('Exit Application','Are you sure you want to exit the application',icon = 'warning')

    if MsgBox == 'yes':

       exit()

    else:
        tk.messagebox.showinfo('Return','You will now return to the application screen')

def calculation():

    no1=(no.get())
    no2=(o.get())
    oprt=op.get()

    global d
    d=calcu(no1,no2,oprt)

    global calculator
    calculator = Toplevel (main_screen)
    calculator.geometry("300x250")
    calculator.title("result")
    calculator['bg']='red'

    Label(calculator,text=('result page'), bg="Green", width="300", height="1", font=("Calibri", 36)).pack()
    Label(calculator,text="", bg="red", width="300", height="1", font=("Calibri",24)).pack()
    Label(calculator,text='The result is', bg="blue", width="300", height="1", font=("Calibri", 36)).pack()

    Label(calculator,text="", bg="red", width="300", height="1", font=("Calibri", 24)).pack()
    Label(calculator,text=d, bg="blue", width="300", height="1", font=("Calibri", 24)).pack()
    Button(calculator,text="exit the pages", height="2",bg="aqua",width="30",font=("calibri",24), command =ExitApplication1).pack()

if __name__ == "__main__":
    screen()


from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

from .models import Review

@receiver(post_save, sender=Review)
def update_on_save(sender, instance, created, **kwargs):
    """
    Update a product's average rating when update/create
    """
    instance.product.calculate_rating()

@receiver(post_delete, sender=Review)
def update_on_delete(sender, instance, **kwargs):
    """
    Update a product's average rating when delete
    """
    if instance.product:
        instance.product.calculate_rating()


class Node:
    def __init__(self,value):
        self.value = value
        self.next = None

class Stack:
    def __init__(self,value):
        new_node = Node(value)
        self.top = new_node
        self.lenght = 1

    def push(self,value):#prependmethod
        new_node = Node(value)
        if self.lenght == 0:
            self.top = new_node

        else:
            new_node.next = self.top
            self.top = new_node
        self.lenght +=1
        return True

    def printstack(self):
        temp = self.top
        while temp:
            print(temp.value)
            temp = temp.next
stack = Stack(5)
stack.push(4)
stack.printstack()


'''
Created on 12 Feb 2018

@author: Bryan
'''
from .clique import Clique
from ..clique_potential import CliquePotential, MixedCliquePotential
from ..message import Message
from pyltm.model.potential.cgpotential import CGPotential
from pyltm.reasoner.clique_potential.discrete_clique_potential import DiscreteCliquePotential
from pyltm.model.potential.cptpotential import CPTPotential

class MixedClique(Clique):
    '''
    classdocs
    '''

    def __init__(self, tree, name, jointVar, discreteVar):
        '''
        Constructor
        '''
        super().__init__(tree, name)
        self._jointVariable = jointVar
        self._discreteVariable = discreteVar

    @property
    def discreteVariable(self):
        return self._discreteVariable

    @property
    def jointVariable(self):
        return self._jointVariable

    @property
    def discreteVariables(self):
        return [self._discreteVariable]

    @property
    def potential(self):
        return self._potential

    def logNormalization(self):
        return self._potential.logNormalization

    def contains(self, variable):
        return self._discreteVariable is variable or self._jointVariable is variable or \
            variable in self._jointVariable.variables

    def assign(self, potential):
        """
        potential: CGPotential
        """
        self._potential = MixedCliquePotential(potential)

    def absorbEvidence(self, variable, value):
        self._potential.absorbEvidence(variable, value)

    def computeMessage(self, separator, multiplier=None, retainingVariables=None):
        """
        Should only contain discrete variable of the separator
        Always retain the discrete variable and marginalize out continuous
        """
        discreteCliquePotential = self._potential.marginalize(separator.variable)
        message = Message(discreteCliquePotential)
        return message.times(multiplier) if multiplier is not None else message

    def reset(self):
        self._potential = None

    def combine(self, other, logNormalization=0):
        """
        other: Potential
        """
        if isinstance(other, Message):
            self.combine(other.function())
            return
        elif isinstance(other, CGPotential):
            if self._potential is None:
                self._potential = MixedCliquePotential(other.clone(), logNormalization)
            else:
                other = MixedCliquePotential(other, logNormalization)
                self._potential.combine(other)
        elif isinstance(other, CPTPotential):
            # other is CPTPotential
            other = other.function()
            if self._potential is None:
                cgpotential = CGPotential(self._jointVariable, self._discreteVariable)
                self._potential = MixedCliquePotential(cgpotential, logNormalization)
            other = DiscreteCliquePotential(other, logNormalization)
            self._potential.multiply(other)
        elif isinstance(other, DiscreteCliquePotential):
            self._potential.multiply(other)
        else:
            raise Exception("Invalid potential type!")

        if self.pivot:
            self.normalize()

    def variables(self):
        variables = self._jointVariable.variables() + [self._discreteVariable]
        return variables

    def __str__(self):
        toStr = "" + self.__class__.__name__ + ": "
        toStr += " ".join([v.name for v in self._jointVariable.variables])
        toStr += " " + self._discreteVariable.name + "\n"
        toStr += "neighbors={ " + " ".join([n.name for n in self.getNeighbors()]) + " }\n"

        if self.potential is not None:
            toStr += str(self.potential)
            toStr += "\n"
        else:
            toStr += "potential: None\n"
        toStr += "}\n"

        return toStr


# 3a. Даны списки my_list_1 и my_list_2.
# Создать список my_result в который вначале поместить
# элементы на четных местах из my_list_1, а потом все элементы на нечетных местах из my_list_2.
#
# 3b. Даны списки my_list_1 и my_list_2. Создать список my_result в который
# вначале поместить четные элементы (ИМЕННО ЭЛЕМЕНТЫ) из my_list_1 и потом нечетные элементы из my_list_2.
# my_list_1 = [1,2,3,4,5], my_list_2 = [10, 15, 20, 25] -> my_result [2, 4, 15, 25]
#
# my_list_1 = ["q", "w", "e", "r"]
# my_list_2 = [1, 2, 3, 4]
my_list_1 = [1, 2, 3, 4, 5]
my_list_2 = [10, 15, 20, 25, 33]
my_result = []
for i in my_list_1:
    if not i % 2:
        my_result.append(i)

for i in my_list_2:
    if i % 2:
        my_result.append(i)

print(my_result)

# 4. Дан список my_list. СОЗДАТЬ НОВЫЙ список new_list у которого первый элемент из my_list
# стоит на последнем месте. Если my_list [1,2,3,4], то new_list [2,3,4,1]
my_list4 = [1,2,3,4]
new_list = my_list4.copy()
new_list.append(new_list[0])
new_list.remove(new_list[0])
print(new_list)

# 5.Дан список my_list. В ЭТОМ списке первый элемент переставить на последнее место.
# [1,2,3,4] -> [2,3,4,1]. Пересоздавать список нельзя! (используйте метод pop)
mylist5 = [8, 1, 2, 3, 4, 5, 6]
mylist5.append(mylist5.pop(0))
print(mylist5)

# 6. Дана строка в которой есть числа (разделяются пробелами).
# Например "43 больше чем 34 но меньше чем 56". Найти сумму ВСЕХ ЧИСЕЛ (А НЕ ЦИФР) в этой строке.
# Для данного примера ответ - 133.

my_str6 = "43 больше чем 34 но меньше чем 56"

word_list = my_str6.split()
num_list = []
number_last = 0
for word in word_list:
    if word.isnumeric():
        num_list.append(int(word))

for value in num_list:
    number_last += value
print(number_last)

my_str7 = 'gfdsqgzer'
if len(my_str7) % 2:
    my_str7 += "_"
print([my_str7[index:index + 2] for index in range(0, len(my_str7), 2)])

# 8. Дана строка my_str в которой символы не повторяются и два символа l_limit, r_limit,
# которые точно находятся в этой строке. Причем l_limit левее чем r_limit.
# В переменную sub_str поместить часть строки между этими символами.
# my_str = "My_long str", l_limit = "o", r_limit = "t" -> sub_str = "ng s"
my_str8 = "My_long str"
l_limit = "o"
r_limit = "t"

mystr_test = list(my_str8)
mysubstr = "".join(mystr_test[mystr_test.index(l_limit) + 1:mystr_test.index(r_limit)])

print(mysubstr)

# 9. Дана строка my_str в которой символы МОГУТ повторяться и два символа l_limit, r_limit,
# которые точно находятся в этой строке. Причем l_limit левее чем r_limit.
# В переменную sub_str поместить НАИБОЛЬШУЮ часть строки между этими символами.
# my_str = "My long string", l_limit = "o", r_limit = "g" -> sub_str = "ng strin".
my_str9 = "My long string"
l_limit9 = "o"
r_limit9 = "g"

_ = list(my_str9)
_2 = _.copy()
_2.reverse()
indexofr_imit = len(_2) - _2.index(r_limit9) - 1
print(indexofr_imit)

splitstr9 = "".join(_[_.index(l_limit) + 1:indexofr_imit])
print(splitstr9)

# 10. Дан список чисел. Определите, сколько в этом списке элементов,
# которые больше суммы двух своих соседей (слева и справа), и НАПЕЧАТАЙТЕ КОЛИЧЕСТВО таких элементов.
# Крайние элементы списка никогда не учитываются, поскольку у них недостаточно соседей.
# Для списка [2,4,1,5,3,9,0,7] ответом будет 3 потому что 4 > 2+1, 5 > 1+3, 9>3+0.

list10 = [2, 4, 1, 5, 3, 9, 0, 7, 2, 0]
new_list = []
for i,value in enumerate(list10):
    if i == 0 or i == len(list10) - 1:
        continue
    elif value > list10[i - 1] + list10[i + 1]:
        new_list.append(value)

print(len(new_list))


import logging

try:
    import tkMessageBox
except:
    tkMessageBox = None

class MessageBoxHandler(logging.Handler):
    def __init__(self):
        logging.Handler.__init__(self)

    def emit(self, record):
        if tkMessageBox:
            msg = self.format(record)
            tkMessageBox.showinfo('info1', msg)


import os
import pickle

curr_path = os.path.dirname(os.path.abspath(__file__))
model_dir = os.path.abspath(os.path.join(
    curr_path, '..', 'saved_models', 'spam_classifier'
))

model_path = os.path.join(model_dir, "model.pickel")
vector_path = os.path.join(model_dir, "vector.pickel")

cv = pickle.load(open(vector_path, "rb"))
model = pickle.load(open(model_path, "rb"))

def predict(text):
    text = cv.transform([text]).toarray()

    y = model.predict(text)

    return y[0]


def main():
    print("This program calculates the future value\n", "of a 10-year investment.")
    #principal = eval(input("Enter the initial principal: "))
    #apr = eval(input("Enter the annual interest rate: "))

    principal = 900
    apr = 5

    print("{0:<} {1:>10}".format("Year", "Value"))
    print("----------------")

    for i in range (10):
        principal = principal * (1 + .01 * apr)

        print("{0:>2}      ${1:<}.{2:0^2}".format(i+1, int(principal), int(principal%1 * 100)))

main()


import requests
import re
import time
from bs4 import BeautifulSoup

header_str = '''
Cookie: bid=qslPNVL8KVE; __yadk_uid=x6rMxdAg7B0u2dVOsdLMtrQWTQ4ifElh; _vwo_uuid_v2=D152A61B581FDD37976848D468E756774|92395dde9e00d52279fb0d6e8f46e567; viewed="1438874"; push_doumail_num=0; push_noty_num=0; ll="128485"; ct=y; __gads=ID=2381e087574308dd-22faeeedfac4000c:T=1606906591:RT=1606906591:S=ALNI_MZN8RV6NZxXEseTX8j_n-oYemM5eg; __utmv=30149280.22572; __utmz=30149280.1606971052.4.3.utmcsr=baidu|utmccn=(organic)|utmcmd=organic; __utmz=223695111.1606971059.39.27.utmcsr=douban.com|utmccn=(referral)|utmcmd=referral|utmcct=/; __utmc=30149280; __utma=30149280.299413206.1606906666.1606971052.1606982674.5; __utma=223695111.307071430.1600620354.1606971059.1606982674.40; __utmc=223695111; ap_v=0,6.0; _pk_ref.100001.4cf6=%5B%22%22%2C%22%22%2C1606982675%2C%22https%3A%2F%2Fwww.douban.com%2F%22%5D; _pk_id.100001.4cf6=b17b83d1d584e666.1600620354.40.1606982815.1606976799.; dbcl2="225727052:1gGWd0LJtrc"; ck=wAAo
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36
'''

def str_to_dict(s, s1=';', s2='='):
    li = s.split(s1)
    res = {}
    for kv in li:
        li2 = kv.split(s2)
        if len(li2) > 1:
            li2[0] = li2[0].replace(':', '')
            res[li2[0]] = li2[1]
    return res

my_headers = str_to_dict(header_str, '\n', ': ')
my_headers['Accept-Encoding'] = 'gzip'

film_id = {
           '电话': '30346025',
           '姜子牙': '25907124',
           '我想藏起来': '30170195',
           '银河守门员': '30306050',
           '最幸福的季节': '30389671',
           '夺冠': '30128916',
           '末日逃生': '30220799',
           '逃跑': '30243396',
           '无声': '33591810',
           '八佰': '26754233'}

R = [[]]
tempScore = []

def transform(input):
    if input == "rating1-t":
        return 1
    elif input == "rating2-t":
        return 2
    elif input == "rating3-t":
        return 3
    elif input == "rating4-t":
        return 4
    elif input == "rating5-t":
        return 5

def collect(all_user_id):
    for indexofuser, user in enumerate(all_user_id):
        movie_id = []
        R.append([])
        tempScore.append({})
        r = requests.get("https://movie.douban.com/people/"+user+"/collect?sort=time&filter=schedule", headers=my_headers)
        soup = BeautifulSoup(r.text, 'html.parser')

        all_movie = soup.find_all('div', 'info', title=False)
        score = re.compile(r'rating\d-t').findall(str(all_movie))
        t = re.compile(r'https://movie.douban.com/subject/\d+').findall(str(all_movie))

        for x in t:
            movie_id.append(x[33:])
        for i, each_movie in enumerate(movie_id):
            if i < len(score):
                if each_movie not in R[0]:
                    R[0].append(each_movie)
                tempScore[indexofuser][each_movie] = score[i]

        print(indexofuser)
        time.sleep(2)
    for i in range(len(R[0])):
        for j in range(1, len(R)):
            R[j].append(0)
    for indexofuser, user in enumerate(all_user_id):
        for i in tempScore[indexofuser]:
            col = R[0].index(i)
            R[indexofuser+1][col] = transform(tempScore[indexofuser][i])
    with open("info.txt", 'w') as f:
        for t in R:
            f.write(str(t))
            f.write(",\n")

try:
    all_user_id = []
    for movie in film_id:  # 10部电影
        print("正在爬取" + movie)
        r = requests.get("https://movie.douban.com/subject/" + film_id[movie] + "/comments", headers=my_headers)
        soup = BeautifulSoup(r.text, 'html.parser')
        all_user = soup.find_all('a', href=re.compile(r'https://www.douban.com/people/\S+/'), title=False)
        all_user_href = re.compile(r'https://www.douban.com/people/.*?/').findall(str(all_user))
        for user in all_user_href:
           all_user_id.append(user[30:-1])
        time.sleep(2)
    print("共有", len(all_user_id), "个用户")
    collect(all_user_id[:100])
except:
    print('爬取失败')


import pygame as pg

#always start line with the left most point
class Line(pg.sprite.Sprite):
    # OBJECTIVE 1.3 - CREATING CLASSES FOR ENTITIES IN THE GAME
    # line is a rectangle with a width of 8, and a height of the distance between the start and end points
    # it can collide with the ball and the player
    def __init__(self,surface,collidesWithPlayer,collidesWithBall,startPosition,endPosition,colour = (255,255,255)):
        super().__init__()
        self.surface = surface
        self.startPosition =  pg.math.Vector2(startPosition)
        self.endPosition =  pg.math.Vector2(endPosition)
        self.position =  pg.math.Vector2(endPosition[0]-startPosition[0],endPosition[1]-startPosition[1])
        self.colour = colour

        self.w= 8
        self.h = pg.math.Vector2.magnitude(pg.math.Vector2(endPosition[0]-startPosition[0],endPosition[1]-startPosition[1]))

        self.bounds = {
            "x1":self.startPosition[0],
            "y1" :self.startPosition[1],

            "x2":self.endPosition[0],
            "y2":self.endPosition[1],
        }

        self.size = (endPosition[0]-startPosition[0],endPosition[1]-startPosition[1])

        #PHYSICS
        self.staticValue = False
        # determines if the object is static or not
        self.collidesWith = {"player":collidesWithPlayer,"ball":collidesWithBall}
        # determines what the object collides with
        self.velocity = pg.math.Vector2(0,0)
        self.mass = 4
        self.inverseMass = 1/self.mass
        self.restitution = 0.99
        self.damping = 0

        self.image = pg.Surface((self.size[0],self.size[1]),pg.SRCALPHA)
        self.rect = self.image.get_rect(topleft = (self.startPosition[0],self.startPosition[1]))
        self.renderGraphics()
        self.mask = pg.mask.from_surface(self.image)

    def render(self):
        self.rect = self.image.get_rect(topleft = (self.startPosition[0],self.startPosition[1]))

        self.renderGraphics()
        self.mask = pg.mask.from_surface(self.image)

        self.surface.blit(self.image,(self.startPosition[0],self.startPosition[1]))

    def renderGraphics(self):
        pg.draw.rect(self.image,self.colour,(0,0,self.size[0],self.size[1]))

    def updatePhysics(self):
        if self.Static:
            self.bounds = {
                "x1":self.startPosition[0],
                "y1" :self.startPosition[1],

                "x2":self.endPosition[0],
                "y2":self.endPosition[1],
            }


import tkinter as tk

root = tk.Tk()
root.title("GuiPracticeCanvas.py")
root.maxsize
root.minsize(1,1)
canvas1 = tk.Canvas(root, width = 1920, height = 1080, background = "navy blue")

canvas1.pack();

root.mainloop()


'''

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

'''

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        max_len = i = 0
        d = dict()
        for j in range(len(s)):
            if s[j] in d:
                i = max(i, d[s[j]] + 1)
            d[s[j]] = j
            max_len = max(max_len, j - i + 1)

        return max_len


from flask import Flask, render_template
from flask_login import LoginManager, login_required, current_user
from dotenv import load_dotenv
from init_db import db
from model.Models import User
from init_bycrypt import bcrypt
from authentication.routes import authentication
from following.routes import following
from search.routes import search
import sqlite3
import os
import requests

load_dotenv()
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv("DATABASE_URI")
app.config['SECRET_KEY'] = os.getenv("SECRET_KEY")
db.init_app(app)
bcrypt.init_app(app)

app.register_blueprint(authentication)
app.register_blueprint(following)
app.register_blueprint(search)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@app.route('/dashboard', methods=['GET', 'POST'])
@login_required
def dashboard():
    con = sqlite3.connect("instance/database.db")
    cur = con.cursor()
    res = cur.execute(f"SELECT company_no FROM Following WHERE user_id={current_user.id}")
    followed_companies = res.fetchall()
    res.close()
    followed_companies_dict = {}
    for f in followed_companies:
        data = requests.get(f"https://api.company-information.service.gov.uk/company/{f[0]}", auth=(os.getenv("API_KEY"),
                                                                                ""), params={
            "company_number": f[0]
        })
        followed_companies_dict[f[0]] = data.json()['company_name']

    print(followed_companies_dict)
    return render_template('dashboard.html', user=current_user, followers=followed_companies_dict)

if __name__ == '__main__':
    app.run()


#Даны два массива чисел. Требуется вывести те элементы первого массива (в том порядке, в каком они идут в первом массиве),
#которых нет во втором массиве. Пользователь вводит число N - количество элементов в первом массиве, затем N чисел - элементы массива.
#Затем число M - количество элементов во втором массиве. Затем элементы второго массива.

# from random import randint # выводим библиотеку
# array=[]
# n= int(input('введите длинну массива:'))
# for i in range(0,n):
#     array.append(randint(0,10))
# print(array)
# array2=[]
# for i in range(0,n):
#     array2.append(randint(0,10))
# print(array2)
# for i in array:
#     for j in array2:
#         if i==j:
#             break
#     else:
#           print(i, end =' ')

# for i in array:
#     if i not in array2:
#         print(i, end =' ')

def input_array(size):
    array=[]
    for i in range(size):
        array.append(int(input()))
    return array

n= int(input('введите длинну первого массива:'))
array1 = input_array(n)
m= int(input('введите длинну второго массива:'))
array2 = input_array(m)

print(array1)
print(array2)
print([i for i in array1 if i not in array2])


import os
import pandas as pd

execfile('inputs.py')

# convert csv into hdf5 using US2
store = pd.HDFStore(output_file)
for table, tid in tables.iteritems():
    f = os.path.join(out_directory, table + ".csv")
    ds = pd.read_csv(f, index_col=tid)
    store[table] = ds
store.close()


import logging
from logging.handlers import RotatingFileHandler
from os.path import dirname, join

from disnake import Intents
from disnake.ext import commands
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, declarative_base

from config import BOT_CONFIG, LOG_NAME

intents = Intents.all()
this_dir = dirname(__file__)

logger = logging.getLogger(LOG_NAME)
logger.setLevel(logging.DEBUG)
if not len(logger.handlers):
    handler = RotatingFileHandler(filename=join(this_dir, 'logs/tea.log'), encoding='utf-8', mode='w', maxBytes=50000,
                                  backupCount=5)
    handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
    logger.addHandler(handler)

bot = commands.Bot(description="Tyrian Education Association Discord Bot", command_prefix='!', sync_commands_debug=True,
                   intents=intents)

db_engine = create_engine(f"sqlite:///{join(this_dir, 'guild_members.db')}")
db_base = declarative_base()
db_session = Session(db_engine)

@bot.event
async def on_ready():
    logger.info(f'Logged in as {bot.user.name}#{bot.user.discriminator} [{bot.user.id}]')

if __name__ == '__main__':
    bot.load_extension('cogs.support')
    bot.load_extension('cogs.member_role_manager')
    bot.load_extension('cogs.roster_reports')
    bot.load_extension('cogs.visitor_manager')
    bot.load_extension('cogs.react_roles')
    bot.load_extension('cogs.daily_achievements')
    bot.load_extension('cogs.query')
    bot.load_extension('cogs.hirdy')
    bot.load_extension('cogs.membership')
    bot.run(BOT_CONFIG['BOT_TOKEN'])


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

"""
Conway's Game of life
"""

import pygame, random
from optparse import OptionParser
from sprites.boxes import Box
from pygame.locals import *

VERSION = "%prog 1.0"
DESCRIPTION = "Conway's Game of life"

DEFAULT_HEIGHT = 40
DEFAULT_WIDTH = 80
DEFAULT_SIZE = 10
DEFAULT_DELAY = 10
CELL_DEAD = '.'
CELL_LIVE = 'o'

# colors
black = (0, 0, 0)
white = (255, 255, 255)

def init_screen(width, height, size):
    """
    Initialize pygame screen
    """
    pygame.init()
    pygame.display.set_caption(DESCRIPTION)
    screen = pygame.display.set_mode([width * size, height * size])
    return screen

def update_display(screen, board, boxes, options, rand_col = False, keep_background = False):
    """
    Updating display
    """
    for dy in range(options.height):
        for dx in range(options.width):
            if board[dx][dy] == CELL_LIVE:
                if rand_col:
                    boxes[dx][dy] = Box([random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)], [dx * options.size, dy * options.size], options.size)
                else:
                    boxes[dx][dy] = Box(white, [dx * options.size, dy * options.size], options.size)
            elif not keep_background:
                boxes[dx][dy] = Box(black, [dx * options.size, dy * options.size], options.size)

            screen.blit(boxes[dx][dy].image, boxes[dx][dy].rect)

    pygame.display.update()

def borderless(pos, max):
    if pos < 0:
        pos = max + pos
    elif pos >= max:
        pos = abs(pos) % max
    return pos

def rules_of_life(board, options):
    """
    Rules of the games
    """
    total_pop = 0
    pop_list = [['0' for i in range(options.height)] for j in range(options.width)]

    for y in range(options.height):
        for x in range(options.width):
            pop = 0
            buf = []

            # bottom row
            if board[borderless(x - 1, options.width)][borderless(y - 1, options.height)] == CELL_LIVE:
                pop += 1
            if board[borderless(x, options.width)][borderless(y - 1, options.height)] == CELL_LIVE:
                pop += 1
            if board[borderless(x + 1, options.width)][borderless(y - 1, options.height)] == CELL_LIVE:
                pop += 1

            # middle row
            if board[borderless(x - 1, options.width)][borderless(y, options.height)] == CELL_LIVE:
                pop += 1
            if board[borderless(x + 1, options.width)][borderless(y, options.height)] == CELL_LIVE:
                pop += 1

            # upper row
            if board[borderless(x - 1, options.width)][borderless(y + 1, options.height)] == CELL_LIVE:
                pop += 1
            if board[borderless(x, options.width)][borderless(y + 1, options.height)] == CELL_LIVE:
                pop += 1
            if board[borderless(x + 1, options.width)][borderless(y + 1, options.height)] == CELL_LIVE:
                pop += 1

            total_pop += pop
            pop_list[x][y] = pop

    # apply rules
    for y in range(options.height):
        for x in range(options.width):
            if board[x][y] == CELL_LIVE and (pop_list[x][y] < 2 or pop_list[x][y] > 3):
                board[x][y] = CELL_DEAD
            elif board[x][y] == CELL_DEAD and pop_list[x][y] == 3:
                board[x][y] = CELL_LIVE

    return board

def main(options, args):
    # prepare boxes
    boxes = [['' for i in range(options.height)] for j in range(options.width)]

    # fill board with dead cells
    board = [[CELL_DEAD for i in range(options.height)] for j in range(options.width)]

    # set screen params
    screen = init_screen(options.width, options.height, options.size)

    running = True
    button_down = False
    keep_background = False
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

            if event.type == KEYDOWN and event.key == K_ESCAPE:
                exit()
            if event.type == KEYDOWN and event.key == K_RETURN:
                running = False

            # set random glyders
            if event.type == KEYDOWN and event.key == K_r:
                for i in range(random.randint(10, 20)):
                    sx = random.randint(0, options.width)
                    sy = random.randint(0, options.height)

                    if random.randint(0, 1) == 1:
                        board[borderless(sx + 1, options.width)][borderless(sy + 0, options.height)] = CELL_LIVE
                        board[borderless(sx + 2, options.width)][borderless(sy + 1, options.height)] = CELL_LIVE
                        board[borderless(sx + 0, options.width)][borderless(sy + 2, options.height)] = CELL_LIVE
                        board[borderless(sx + 1, options.width)][borderless(sy + 2, options.height)] = CELL_LIVE
                        board[borderless(sx + 2, options.width)][borderless(sy + 2, options.height)] = CELL_LIVE
                    else:
                        board[borderless(sx + 1, options.width)][borderless(sy + 0, options.height)] = CELL_LIVE
                        board[borderless(sx + 0, options.width)][borderless(sy + 1, options.height)] = CELL_LIVE
                        board[borderless(sx + 0, options.width)][borderless(sy + 2, options.height)] = CELL_LIVE
                        board[borderless(sx + 1, options.width)][borderless(sy + 2, options.height)] = CELL_LIVE
                        board[borderless(sx + 2, options.width)][borderless(sy + 2, options.height)] = CELL_LIVE

                update_display(screen, board, boxes, options)

            if event.type == pygame.MOUSEBUTTONDOWN:
                button_down = True
                button_type = event.button

            if event.type == MOUSEBUTTONUP:
                button_down = False

            if button_down:
                mouse_x, mouse_y = pygame.mouse.get_pos()
                sp_x = mouse_x / options.size
                sp_y = mouse_y / options.size

                if button_type == 1:
                    board[sp_x][sp_y] = CELL_LIVE
                elif button_type == 3:
                    board[sp_x][sp_y] = CELL_DEAD

                update_display(screen, board, boxes, options)

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == KEYDOWN and event.key == K_ESCAPE:
                running = False
            if event.type == KEYDOWN and event.key == K_b:
                if not keep_background:
                    keep_background = True
                else:
                    keep_background = False

        update_display(screen, board, boxes, options, rand_col=True, keep_background=keep_background)
        board = rules_of_life(board, options)
        pygame.time.delay(options.delay)

if __name__ == "__main__":
    parser = OptionParser(version=VERSION, description=DESCRIPTION)
    parser.add_option("--width", type="int", dest="width", default=DEFAULT_WIDTH, help="Field width")
    parser.add_option("--height", type="int", dest="height", default=DEFAULT_HEIGHT, help="Field height")
    parser.add_option("--size", type="int", dest="size", default=DEFAULT_SIZE, help="Cell size")
    parser.add_option("--delay", type="int", dest="delay", default=DEFAULT_DELAY, help="Update delay")
    parser.add_option("--debug", action="store_true", dest="debug", help="Debug flag", default=False)

    (options, args) = parser.parse_args()
    main(options, args)
    pygame.quit()


from parsers.hardware_objs import HardwareUnit, CFGU, ManycoreUnit, Tile
from parsers.equation_parse import eq_to_cfg
from parsers.cfg_compiler import cfg_to_pipeline
from simulators.simulators import pipeline_eumulator, simulate_system
from simulators.asip_emulator import emulate_core
import numpy as np

def oregonator_model():

    test_equ = """
    dx/dt = x * (1 - x) + f * ((q - x) / (q + x)) * y
    dy/dt = x - y
    """

    init_state = {
        "x": 30,
        "y": 16
    }

    args = {
        "f": 0.0001,
        "q": 10.0 ** -4
    }

    return test_equ, args, init_state

def hodgkin_huxley():

    test_equ = """
    dv/dt = -(I_K + I_Na + I_L - I_in) / Cm
    dn/dt = a_n * (1 - n) - b_n * n
    dm/dt = a_m * (1 - m) - b_m * m
    dh/dt = a_h * (1 - h) - b_h * h

    I_K = g_K * (n ^ 4) * (v - V_K)
    I_Na = g_Na * (m ^ 3) * h * (v - V_Na)
    I_L = g_L * (v - V_L)

    a_n = 0.01 * (10 - v) / (e ^ (1 - 0.1 * v) - 1)
    b_n = 0.125 * e ^ (-v / 80)

    a_m = 0.1 * (25 - v) / (e ^ (2.5 - 0.1 * v) - 1)
    b_m = 4 * e ^ (-v / 18)

    a_h = 0.07 * (e ^ (-v / 20))
    b_h = 1 / (e ^ (3 - 0.1 * v) + 1)
    """

    args = {
        "g_K": 36.0,
        "g_Na": 120.0,
        "g_L": 0.3,
        "V_K": -12.0,
        "V_Na": 115.0,
        "V_L": 10.613,
        "Cm": 1.0,
        "I_in": 10
    }

    init_state = {
        "v": 0.0,
        "n": 0.31767691,
        "m": 0.05293249,
        "h": 0.59612075
    }

    instances = 10
    sys_data = {
        "g_K": 36.0,
        "g_Na": 120.0,
        "g_L": 0.3,
        "V_K": -12.0,
        "V_Na": 115.0,
        "V_L": 10.613,
        "Cm": 1.0,
        "I_in": 40,

        "v": 0.0,
        "n": 0.31767691,
        "m": 0.05293249,
        "h": 0.59612075,

        "dt": 1.0/128.0
    }

    return test_equ, args, init_state, sys_data, instances

def lorenz_attractor():

    test_equ = """
    dx/dt = sigma * (y - x)
    dy/dt = x * (rho - z) - y
    dz/dt = x * y - b * z
    """
    args = {
        "b": 8.0/3.0,
        "sigma": 10,
        "rho": 10
    }

    init_state = {
        "x": 1.0,
        "y": 0,
        "z": 0
    }

    instances = 10
    sys_data = {
        "x": 1.0,
        "y": 0.0,
        "z": 0.0,
        "b": 8.0/3.0, # np.random.uniform(4.0/3.0, 16.0/3.0, instances),
        "sigma": 10.0, # np.random.uniform(5, 50, instances),
        "rho": 10.0, #np.random.uniform(5, 50, instances),
        "dt": 1.0/128.0
    }

    return test_equ, args, init_state, sys_data, instances

def cicr():

    test_equ = """
        dx/dt = z_0 - z_2 + z_3 + k_f * y - k * x + z_1 * b
        dy/dt = z_2 - z_3 - k_f * y

        n = 2
        m = 2
        p = 2
        z_0 = 1
        z_1 = 6
        z_2 = v_m_2 * ((x ** n) / (k_2 ** n + x ** n))
        z_3 = v_m_3 * ((y ** m) / (k_r ** m + y ** m)) * ((x ** p) / (k_a ** p + x ** p))
    """

    args = {
        "v_m_2": 100.0,
        "v_m_3": 700.0,
        "k_2": 1.0,
        "k_r": 15.0,
        "k_a": 2.5,
        "k_f": 0,
        "k": 8.0,
        "b": 1.0
    }

    init_state = {
        "x": 16,
        "y": 16
    }

    instances = 10
    sys_data = {
        "v_m_2": 100.0,
        "v_m_3": 700.0,
        "k_2": 1.0,
        "k_r": 15.0,
        "k_a": 2.5,
        "k_f": 0,
        "k": 8.0,
        "b": 1.0,
        "x": np.random.uniform(10.0, 20.0, instances),
        "y": np.random.uniform(10.0, 20.0, instances)
    }

    return test_equ, args, init_state, sys_data, instances

def duplicate_test():

    test_equ = """
        dx/dt = (x + y) * 0.5
        dy/dt = (x - y)
    """

    args = {

    }

    init_state = {
        "x": 0.5,
        "y": 0.6
    }

    return test_equ, args, init_state

if __name__ == "__main__":

    np.random.seed(0)
    test_equ, args, init_state, sys_data, instances = cicr()

    dt = 1.0/128.0
    compiled_cfg = eq_to_cfg(test_equ)
    pipelined_cfg = cfg_to_pipeline(compiled_cfg)

    hardware_unit = ManycoreUnit(pipelined_cfg, args, init_state, dt=dt)

    tile = Tile(
        hardware_unit,
        instances,
        sys_data,
        init_state.keys()
    )

    emulate_core()

    simulate_system(
        test_equ, sys_data, sim_time=20, dt=1.0/128.0
    )


from adafruit_binascii import hexlify, unhexlify, a2b_base64, b2a_base64
from digitalio import DigitalInOut, Direction, Pull
from adafruit_debouncer import Debouncer
import busio
import board
import keypad
import time

class SlaveKeypad:
    """
    SlaveKeypad reads button states from the second half of my diy split keyboard.
    """
    def __init__(self):
        super().__init__()
        self.key_pins = (board.GP2,
                         board.GP3,
                         board.GP4,
                         board.GP5,
                         board.GP6,
                         board.GP7,
                         board.GP8,
                         board.GP9,
                         board.GP10,
                         board.GP11,
                         board.GP12,
                         board.GP13,
                         board.GP14,
                         board.GP15,
                         board.GP16,
                         board.GP17,
                         board.GP18,
                         board.GP19,
                         board.GP20,
                         board.GP21)
        self.keys = keypad.Keys(self.key_pins, value_when_pressed=False, pull=True)
        self.states = [False] * self.keys.key_count

    def value(self):
        value = 0
        for i in range(0, self.keys.key_count):
            if self.states[i]:
                value += 1 << i
        return value

    def update(self):
        event = self.keys.events.get()
        if event:
            self.states[event.key_number] = event.pressed
            return True
        return False

class SlaveKeyboard:
    """
    SlaveKeyboard runs the main loop. It reads button states from the keypad and sends them
    over a serial connection to the master keyboard.
    """
    def __init__(self, keypad):
        self.keypad = keypad
        self.isRunning = False
        self.uart = busio.UART(board.GP0, board.GP1, baudrate=256000)

    def start(self):
        if not self.isRunning:
            self.isRunning = True
            keypad = self.keypad

            while self.isRunning:
                if keypad.update():
                    self.send_keys(keypad.value())

    def stop(self):
        self.isRunning = False

    def send_keys(self, value):
        """
        Keys are sent as a base64 encoded integer to the master keyboard.
        """
        # print("keys: ", value)
        self.uart.write(b2a_base64(value.to_bytes(3, "little", signed=False)))

# Create the keyboard
keyboard = SlaveKeyboard(keypad=SlaveKeypad())

# Start the main loop
keyboard.start()