"""
@author: Elias Raninen www.github.com/EliasRaninen

This version: March 2022
"""
import numpy as np
import pandas as pd
import multiclass_rscm as pool
np.random.seed(42)

# Define simulation setup

nmc = 4000  # number of Monte Carlo trials

SETUP = 'C'  # choose 'A', 'B', or 'C'

if SETUP == 'A':
    # Setup A: AR(1) covariance matrices
    p = 200  # dimension
    n = [25, 50, 75, 100]  # number of samples
    K = 4  # number of classes
    df = [8, 8, 8, 8]  # degrees of freedom of multivariate t
    rho = [0.2, 0.3, 0.4, 0.5]
    C = [pool.ARcov(rho[0], p),  # covariance matrices
         pool.ARcov(rho[1], p),
         pool.ARcov(rho[2], p),
         pool.ARcov(rho[3], p)]
elif SETUP == 'B':
    # Setup B: compound symmetry
    p = 200  # dimension
    K = 4  # number of classes
    n = [25, 50, 75, 100]  # number of samples
    df = [8, 8, 8, 8]  # degrees of freedom of multivariate t
    rho = [0.2, 0.3, 0.4, 0.5]
    C = [pool.CScov(rho[0], p),  # covariance matrices
         pool.CScov(rho[1], p),
         pool.CScov(rho[2], p),
         pool.CScov(rho[3], p)]
elif SETUP == 'C':
    # Setup C: mixed case
    p = 200  # dimension
    n = [100, 100, 100, 100]  # number of samples
    K = 4  # number of classes
    df = [12, 8, 12, 8]  # degrees of freedom of multivariate t
    rho = [0.6, 0.6, 0.1, 0.1]
    C = [pool.ARcov(rho[0], p),
         pool.ARcov(rho[1], p),
         pool.CScov(rho[2], p),
         pool.CScov(rho[3], p)]
else:
    print("SETUP must be either 'A', 'B', or 'C'")

# Run simulation

print('Running simulation: SETUP ' + SETUP + ', averaging over '
      + str(nmc) + ' Monte Carlo trials.')

# class means
mu = [np.random.normal(0, 1, p),
      np.random.normal(0, 1, p),
      np.random.normal(0, 1, p),
      np.random.normal(0, 1, p)]

mse_mc = dict()
mse_mc['poly'] = np.zeros((nmc, K))
mse_mc['polyave'] = np.zeros((nmc, K))
mse_mc['polys'] = np.zeros((nmc, K))
mse_mc['polysave'] = np.zeros((nmc, K))
mse_mc['lin2'] = np.zeros((nmc, K))
for mc in range(nmc):
    if mc % 50 == 0:
        print(mc, '/', nmc)
    dataset = pool.generate_dataset(mu, C, df, n, p, K)
    params = pool.estimate_parameters(dataset)

    # LINPOOL2
    out = pool.linpool(params, 'LIN2')
    LIN2 = out['Sigmas']

    # POLY
    out = pool.rscmpool(params, averaging=False, compute_inverse=False)
    POLY = out['Sigmas']

    # POLY-Ave
    out = pool.rscmpool(params, averaging=True, compute_inverse=False)
    POLYAve = out['Sigmas']

    # POLYs
    out = pool.rscmpools(params, T='Sp', averaging=False, compute_inverse=False)
    POLYs = out['Sigmas']

    # POLYs-Ave
    out = pool.rscmpools(params, T='Sp', averaging=True, compute_inverse=False)
    POLYsAve = out['Sigmas']

    for k in range(K):
        mse_mc['poly'][mc, k] = pool.NSE(POLY[k], C[k])
        mse_mc['polyave'][mc, k] = pool.NSE(POLYAve[k], C[k])
        mse_mc['polys'][mc, k] = pool.NSE(POLYs[k], C[k])
        mse_mc['polysave'][mc, k] = pool.NSE(POLYsAve[k], C[k])
        mse_mc['lin2'][mc, k] = pool.NSE(LIN2[k], C[k])

# Print results

def meanmse(a):
    """ function for returning mean of normalized squared error (x10) and their sum """
    return np.append(a.mean(axis=0), a.sum(axis=1).mean())*10

def stdmse(a):
    """ function for returning std of normalized squared error (x10) and their sum """
    return np.append(a.std(axis=0), a.sum(axis=1).std())*10

mse = dict()
mse['lin2'] = meanmse(mse_mc['lin2'])
mse['poly'] = meanmse(mse_mc['poly'])
mse['polys'] = meanmse(mse_mc['polys'])
mse['polyave'] = meanmse(mse_mc['polyave'])
mse['polysave'] = meanmse(mse_mc['polysave'])

std = dict()
std['lin2'] = stdmse(mse_mc['lin2'])
std['poly'] = stdmse(mse_mc['poly'])
std['polys'] = stdmse(mse_mc['polys'])
std['polyave'] = stdmse(mse_mc['polyave'])
std['polysave'] = stdmse(mse_mc['polysave'])

# print results
print('MSE (x10):')
print(pd.DataFrame(mse, index=['Class 1', 'Class 2',
                               'Class 3', 'Class 4', 'Sum']).T.round(1))
print('')
print('Standard deviation (x10):')
print(pd.DataFrame(std, index=['Class 1', 'Class 2',
                               'Class 3', 'Class 4', 'Sum']).T.round(1))


def extractSultricWordpressCom(item):
	'''
	Parser for 'sultric.wordpress.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('Sy',                                            'seducing you',                      'translated'),
		('seducing you',                                  'seducing you',                      'translated'),
		('bpetit',                                        'being papa\'d every time i transmigrate',                      'translated'),
		('being papa\'d every time i transmigrate',       'being papa\'d every time i transmigrate',                      'translated'),
		('PRC',       'PRC',                      'translated'),
		('Loiterous', 'Loiterous',                'oel'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


aylar = [31, 28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31]
def artıkyıl(d):
    years = d.y
    if (d.m <= 2):
        years = years- 1
    ans = int(years / 4)
    ans -= int(years / 100)
    ans += int(years / 400)
    return ans
def getDifference(dt1, dt2):
    n1 = dt1.y * 365 + dt1.d
    for i in range(0, dt1.m - 1):
        n1 += aylar[i]
    n1 += artıkyıl(dt1)
    n2 = dt2.y * 365 + dt2.d
    for i in range(0, dt2.m - 1):
        n2 += aylar[i]
    n2 += artıkyıl(dt2)
    return (n2 - n1)
class tarih:
   def __init__(self, d, m, y,s):
     self.d = d
     self.m = m
     self.y = y
     self.s = s
tarih_1 = tarih(1, 9, 2020,22)
tarih_2 = tarih(3, 9, 2020,22)
farkgun=getDifference(tarih_1,tarih_2)
if(tarih_1.s>tarih_2.s):
    farkgun=farkgun-1
    tarih_2.s=tarih_2.s+24
print("Iki tarih arasindaki saat: ",(farkgun*24)+(tarih_2.s-tarih_1.s),"saat.")


# Simon Game on BBC micro:bit V2
# by Alan Wang

"""
How to play:

1) Upload the script as main.py or in the form of .hex file.
2) After the welcome effects, press A + B to start.
3) Memorize the Simon sequence in each turn.
4) Tilt the board toward indicated directions to match the sequence.
5) After each tilting gesture, you have to return it to horizontal position.
6) Game will end when you failed.
7) There is no limit how long the Simon sequence can go.
"""

# import modules

from microbit import display, Image, Sound, sleep
from microbit import button_a, button_b, accelerometer
import random, music, audio, speech

# prepare data

"""
Note: the indexes of the following tuple represent
0 = toward up/north
1 = toward left/west
2 = toward right/east
3 = toward down/south

Since gesture "up" in micro:bit means "north side up",
I inverted the direction here.
But you can change the items of gestures, images and notes
to customize what would be shown and play on micro:bit.
"""

gestures = ('down', 'left', 'right', 'up')
images = (Image('69996:06960:00600:00000:00000:'),
          Image('60000:96000:99600:96000:60000:'),
          Image('00006:00069:00699:00069:00006:'),
          Image('00000:00000:00600:06960:69996:'),
          Image('30003:60006:90009:60006:30003:'))
notes = (262, 330, 392, 523)
simon = []
guess = []

# start up effects

display.clear()
audio.play(Sound.GIGGLE)
sleep(1000)
display.show(Image.FABULOUS)
speech.say('Simon says', speed=150, pitch=50, throat=100, mouth=50)
sleep(500)

# wait for the user to press A + B

display_flag = True
while not (button_a.is_pressed() and button_b.is_pressed()):
    if display_flag:
        display.show(images[4])
    else:
        display.clear()
    sleep(200)
    display_flag = not display_flag

for i in range(4):
    music.pitch(notes[i])
    display.show(images[i])
    sleep(100)

display.clear()
sleep(400)
music.stop()
sleep(1000)

# start game

while True:
    guess.clear()
    simon.append(random.randrange(4))  # add a random number to sequence

    for n in simon:
        music.pitch(notes[n])
        display.show(images[n])
        sleep(500)
        music.stop()
        display.clear()
        sleep(250)

    sleep(500)

    # game loop
    # the loop will end when user matched the whole sequence
    while len(guess) < len(simon):
        gesture = None
        display.show('?')

        # record user's tilting gestures
        for i in range(4):
            if accelerometer.was_gesture(gestures[i]):
                gesture = i
                break
        if gesture == None:
            continue
        guess.append(gesture)
        display.show(images[gesture])
        music.pitch(notes[gesture])
        sleep(250)
        music.stop()
        display.clear()
        sleep(100)

        # if the gesture don't match, exit the game loop
        if guess != simon[:len(guess)]:
            break

    else:
        # sequence successfully matched, go to next round
        display.show(Image.YES)
        music.play(music.POWER_UP)
        sleep(500)
        display.clear()
        sleep(500)
        continue

    # failed to match sequence
    sleep(100)
    display.show(Image.NO)
    music.play(music.WAWAWAWAA)
    break

# display final score

sleep(1000)
audio.play(Sound.HAPPY)

while True:
    display.scroll('SCORE: {}'.format(len(simon) - 1))
    sleep(1000)


from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
import numpy as np
import matplotlib.pyplot as plt

a ="./GAN/runs/Oct12_12-02-34_isys313/events.out.tfevents.1665543754.isys313.2464797.0"
event_acc = EventAccumulator(a)
event_acc.Reload()

loss_G_GAN = np.array([[s.step, s.value] for s in event_acc.Scalars('loss_G_GAN')])
loss_G_recon = np.array([[s.step, s.value] for s in event_acc.Scalars('loss_G_recon')])
loss_D =np.array([[s.step, s.value] for s in event_acc.Scalars('loss_D')])

plt.subplot(131)
plt.title("loss_G_GAN")
plt.plot(loss_G_GAN[:, 0], loss_G_GAN[:, 1])
plt.subplot(132)
plt.title("loss_G_recon")
plt.plot(loss_G_recon[:, 0], loss_G_recon[:, 1])
plt.subplot(133)
plt.title("loss_D")
plt.plot(loss_D[:, 0], loss_D[:, 1])
plt.show()


from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .forms import AnalisisForm, EvaluacionForm, ProcesoAfectadoForm, ReporteIncidenteForm, SolucionForm
from .models import ReporteIncidente

# Create your views here.
def index(request):
    reports = ReporteIncidente.objects.all()
    context = {'reports': reports}
    return render(request, 'reports/index.html', context)

def create(request):
    if request.method == 'POST':
        reportForm = ReporteIncidenteForm(request.POST)
        checkForm = EvaluacionForm(request.POST)
        if reportForm.is_valid() and checkForm.is_valid():
            print(request.POST)
            check = checkForm.save()
            report = reportForm.save(commit=False)
            report.evaluacion = check
            report.save()
    else:
        checkForm = EvaluacionForm()
        reportForm = ReporteIncidenteForm()
    context = {
        'report': reportForm,
        'check': checkForm
    }
    return render(request, 'reports/create.html', context)

def browse(request, id):
    report = get_object_or_404(ReporteIncidente, pk=id)
    context = {
        'report': report
    }
    return render(request, 'reports/details.html', context)

def update(request, id):
    report = get_object_or_404(ReporteIncidente, pk=id)
    if request.method == 'POST':
        reportForm = ReporteIncidenteForm(request.POST, instance=report)
        if reportForm.is_valid():
            report = reportForm.save()
    else:
        reportForm = ReporteIncidenteForm(instance=report)
    context = {
        'form': reportForm
    }
    return render(request, 'reports/update.html', context)

def analyze(request, id):
    if request.method == 'POST':
        analysisForm = AnalisisForm(request.POST)
        if analysisForm.is_valid():
            report = get_object_or_404(ReporteIncidente, pk=id)
            analysis = analysisForm.save()
            report.analisis = analysis
            report.save()
            return HttpResponseRedirect(reverse('reports:update', args=(id,)))
    else:
        analysisForm = AnalisisForm()
    context = {
        'analysis': analysisForm
    }
    return render(request, 'reports/analyze.html', context)

def solve(request, id):
    if request.method == 'POST':
        solutionForm = SolucionForm(request.POST)
        if solutionForm.is_valid():
            report = get_object_or_404(ReporteIncidente, pk=id)
            solution = solutionForm.save()
            report.solucion = solution
            report.save()
            return HttpResponseRedirect(reverse('reports:update', args=(id,)))
    else:
        solutionForm = SolucionForm()
    context = {
        'solution': solutionForm
    }
    return render(request, 'reports/solve.html', context)


# coding:utf-8

import pinyin
from my_widget.my_grid_layout import GridLayout
from my_widget.my_groupBox import GroupBox
from my_widget.my_scrollArea import ScrollArea
from PyQt5.QtCore import (QParallelAnimationGroup, QPoint, QPropertyAnimation,
                          Qt, pyqtSignal)
from PyQt5.QtWidgets import QApplication, QGroupBox, QLabel, QVBoxLayout, QWidget

from .album_blur_background import AlbumBlurBackground
from .album_card import AlbumCard
from my_dialog_box.delete_card_panel import DeleteCardPanel

class AlbumCardViewer(QWidget):
    """ 定义一个专辑卡视图 """

    playSignal = pyqtSignal(list)
    nextPlaySignal = pyqtSignal(list)
    albumNumChanged = pyqtSignal(int)
    saveAlbumInfoSig = pyqtSignal(dict, dict)
    addAlbumToPlayingSignal = pyqtSignal(list)            # 将专辑添加到正在播放
    switchToAlbumInterfaceSig = pyqtSignal(dict)
    selectionModeStateChanged = pyqtSignal(bool)
    checkedAlbumCardNumChanged = pyqtSignal(int)
    addAlbumToNewCustomPlaylistSig = pyqtSignal(list)     # 将专辑添加到新建的播放列表
    addAlbumToCustomPlaylistSig = pyqtSignal(str, list)   # 将专辑添加到已存在的自定义播放列表

    def __init__(self, albumInfo_list: list, parent=None):
        super().__init__(parent)
        self.albumInfo_list = albumInfo_list
        # 初始化网格的列数
        self.columnNum = 1
        self.albumCardDict_list = []
        self.albumCard_list = []
        self.checkedAlbumCard_list = []
        self.currentGroupDict_list = []
        # 初始化标志位
        self.isInSelectionMode = False
        self.isAllAlbumCardsChecked = False
        # 设置当前排序方式
        self.sortMode = '添加时间'
        # 实例化滚动部件的竖直布局
        self.scrollWidgetVBoxLayout = QVBoxLayout()
        # 实例化滚动区域和滚动区域的窗口
        self.__createGuideLabel()
        self.scrollArea = ScrollArea(self)
        self.scrollWidget = QWidget()
        self.albumBlurBackground = AlbumBlurBackground(self.scrollWidget)
        # 创建专辑卡并将其添加到布局中
        self.__createAlbumCards()
        # 初始化小部件
        self.__initWidget()

    def __initWidget(self):
        """ 初始化小部件 """
        self.resize(1270, 760)
        # 隐藏磨砂背景
        self.albumBlurBackground.hide()
        # 设置导航标签的可见性
        self.guideLabel.raise_()
        self.guideLabel.setHidden(bool(self.albumCard_list))
        # 初始化滚动条
        self.scrollArea.setHorizontalScrollBarPolicy(
            Qt.ScrollBarAlwaysOff)
        self.scrollWidget.setObjectName('scrollWidget')
        self.__connectSignalToSlot()
        self.__initLayout()
        self.__setQss()

    def __createGuideLabel(self):
        """ 创建导航标签 """
        self.guideLabel = QLabel('这里没有可显示的内容。请尝试其他筛选器。', self)
        self.guideLabel.setStyleSheet(
            "color: black; font: 25px 'Microsoft YaHei'")
        self.guideLabel.resize(500, 26)
        self.guideLabel.move(35, 286)

    def __createAlbumCards(self):
        """ 将专辑卡添加到窗口中 """
        # 创建并行动画组
        self.hideCheckBoxAniGroup = QParallelAnimationGroup(self)
        self.hideCheckBoxAni_list = []
        for albumInfo in self.albumInfo_list:
            self.__createOneAlbumCard(albumInfo)

    def __createOneAlbumCard(self, albumInfo: dict):
        """ 创建一个专辑卡 """
        # 实例化专辑卡和动画
        albumCard = AlbumCard(albumInfo, self)
        # 创建动画
        hideCheckBoxAni = QPropertyAnimation(
            albumCard.checkBoxOpacityEffect, b'opacity')
        self.hideCheckBoxAniGroup.addAnimation(hideCheckBoxAni)
        self.hideCheckBoxAni_list.append(hideCheckBoxAni)
        # 将含有专辑卡及其信息的字典插入列表
        album = albumInfo['album']
        self.albumCard_list.append(albumCard)
        self.albumCardDict_list.append({'albumCard': albumCard,
                                        'albumName': album,
                                        'year': albumInfo['year'][:4],
                                        'songer': albumInfo['songer'],
                                        'firstLetter': pinyin.get_initial(album[0])[0].upper()})
        # 专辑卡信号连接到槽函数
        albumCard.playSignal.connect(self.playSignal)
        albumCard.nextPlaySignal.connect(self.nextPlaySignal)
        albumCard.saveAlbumInfoSig.connect(self.saveAlbumInfoSig)
        albumCard.deleteCardSig.connect(self.showDeleteOneCardPanel)
        albumCard.addToPlayingSignal.connect(
            self.addAlbumToPlayingSignal)
        albumCard.switchToAlbumInterfaceSig.connect(
            self.switchToAlbumInterfaceSig)
        albumCard.checkedStateChanged.connect(
            self.__albumCardCheckedStateChangedSlot)
        albumCard.showBlurAlbumBackgroundSig.connect(
            self.__showBlurAlbumBackground)
        albumCard.hideBlurAlbumBackgroundSig.connect(
            self.albumBlurBackground.hide)
        albumCard.addAlbumToCustomPlaylistSig.connect(
            self.addAlbumToCustomPlaylistSig)
        albumCard.addAlbumToNewCustomPlaylistSig.connect(
            self.addAlbumToNewCustomPlaylistSig)

    def __connectSignalToSlot(self):
        """ 将信号连接到槽函数 """
        # 动画完成隐藏复选框
        self.hideCheckBoxAniGroup.finished.connect(self.__hideAllCheckBox)

    def __initLayout(self):
        """ 初始化布局 """
        # 按照添加时间分组
        self.sortByAddTime()
        self.scrollWidgetVBoxLayout.setSpacing(30)
        self.scrollWidgetVBoxLayout.setContentsMargins(10, 245, 0, 120)
        self.scrollWidget.setLayout(self.scrollWidgetVBoxLayout)
        self.scrollArea.setWidget(self.scrollWidget)

    def resizeEvent(self, event):
        """ 根据宽度调整网格的列数 """
        super().resizeEvent(event)
        self.scrollArea.resize(self.size())
        # 如果第一次超过1337就调整网格的列数
        if self.width() >= 1790 and self.columnNum != 8:
            self.__updateColumnNum(8)
        if 1570 <= self.width() < 1790 and self.columnNum != 7:
            self.__updateColumnNum(7)
        elif 1350 <= self.width() < 1570 and self.columnNum != 6:
            self.__updateColumnNum(6)
        elif 1130 < self.width() < 1350 and self.columnNum != 5:
            self.__updateColumnNum(5)
        elif 910 < self.width() <= 1130 and self.columnNum != 4:
            self.__updateColumnNum(4)
        elif 690 < self.width() <= 910:
            self.__updateColumnNum(3)
        elif self.width() <= 690:
            self.__updateColumnNum(2)
        # 调整滚动条
        self.scrollArea.verticalScrollBar().move(-1, 40)
        self.scrollArea.verticalScrollBar().resize(
            self.scrollArea.verticalScrollBar().width(), self.height() - 156)

    def __updateColumnNum(self, columnNum: int):
        """ 更新网格列数 """
        self.columnNum = columnNum
        for currentGroup_dict in self.currentGroupDict_list:
            gridLayout = currentGroup_dict['gridLayout']  # type:GridLayout
            gridLayout.updateColumnNum(columnNum, 210, 290)
        self.__adjustScrollWidgetSize()

    def __adjustScrollWidgetSize(self):
        """ 调整滚动部件的高度 """
        rowCount = sum([currentGroup_dict['gridLayout'].rowCount()
                        for currentGroup_dict in self.currentGroupDict_list])
        containerCount = len(self.currentGroupDict_list)
        self.scrollWidget.resize(
            self.width(), 310 * rowCount + 60 * containerCount * (self.sortMode != '添加日期') + 120 + 245)

    def __removeContainerFromVBoxLayout(self):
        """ 从竖直布局中移除专辑卡容器 """
        for currentGroup_dict in self.currentGroupDict_list:
            # 将专辑卡从每个网格布局中移除
            currentGroup_dict['gridLayout'].removeAllWidgets()
            self.scrollWidgetVBoxLayout.removeWidget(
                currentGroup_dict['container'])
            currentGroup_dict['container'].deleteLater()
            currentGroup_dict['gridLayout'].deleteLater()
        self.currentGroupDict_list = []

    def __addContainterToVBoxLayout(self):
        """ 将当前的分组添加到箱式布局中 """
        for currentGroup_dict in self.currentGroupDict_list:
            self.scrollWidgetVBoxLayout.addWidget(
                currentGroup_dict['container'], 0, Qt.AlignTop)

    def __addAlbumCardToGridLayout(self):
        """ 将专辑卡添加到每一个网格布局中 """
        for currentGroup_dict in self.currentGroupDict_list:
            for index, albumCard in enumerate(currentGroup_dict['albumCard_list']):
                row = index // self.columnNum
                column = index - row * self.columnNum
                currentGroup_dict['gridLayout'].addWidget(
                    albumCard, row, column)
            currentGroup_dict['gridLayout'].setAlignment(Qt.AlignLeft)

    def sortByAddTime(self):
        """ 按照添加时间分组 """
        self.sortMode = '添加时间'
        # 创建一个包含所有歌曲卡的网格布局
        container = QWidget()
        gridLayout = GridLayout()
        gridLayout.setVerticalSpacing(20)
        gridLayout.setHorizontalSpacing(10)
        container.setLayout(gridLayout)
        # 从竖直布局中移除小部件
        self.__removeContainerFromVBoxLayout()
        # 构造一个包含布局和小部件列表字典的列表
        self.addTimeGroup_list = [
            {'container': container,
             'gridLayout': gridLayout,
             'albumCard_list': self.albumCard_list}]
        # 创建一个对当前分组列表引用的列表
        self.currentGroupDict_list = self.addTimeGroup_list
        # 将专辑卡添加到布局中
        self.__addAlbumCardToGridLayout()
        self.__addContainterToVBoxLayout()
        self.__adjustScrollWidgetSize()

    def sortByFirstLetter(self):
        """ 按照专辑名的首字母进行分组排序 """
        self.sortMode = 'A到Z'
        # 将专辑卡从旧布局中移除
        self.__removeContainerFromVBoxLayout()
        # 创建分组
        firstLetter_list = []
        self.firsetLetterGroupDict_list = []
        # 将专辑卡添加到分组中
        for albumCard_dict in self.albumCardDict_list:
            # 获取专辑卡的专辑名首字母(有可能不是字母)
            firstLetter = albumCard_dict['firstLetter']
            firstLetter = firstLetter if 65 <= ord(
                firstLetter) <= 90 else '...'
            # 如果首字母属于不在列表中就将创建分组(仅限于A-Z和...)
            if firstLetter not in firstLetter_list:
                # firstLetter_list的首字母顺序和firsetLetterGroupDict_list保持一致
                firstLetter_list.append(firstLetter)
                group = GroupBox(firstLetter)
                gridLayout = GridLayout()
                group.setLayout(gridLayout)
                gridLayout.setVerticalSpacing(20)
                gridLayout.setHorizontalSpacing(10)
                self.firsetLetterGroupDict_list.append(
                    {'container': group, 'firstLetter': firstLetter,
                     'gridLayout': gridLayout, 'albumCard_list': []})
            # 将专辑卡添加到分组中
            index = firstLetter_list.index(firstLetter)
            self.firsetLetterGroupDict_list[index]['albumCard_list'].append(
                albumCard_dict['albumCard'])
        # 排序列表
        self.firsetLetterGroupDict_list.sort(
            key=lambda item: item['firstLetter'])
        # 将...分组移到最后
        if '...' in firstLetter_list:
            unique_group = self.firsetLetterGroupDict_list.pop(0)
            self.firsetLetterGroupDict_list.append(unique_group)
        # 将专辑加到分组的网格布局中
        self.currentGroupDict_list = self.firsetLetterGroupDict_list
        # 将专辑卡添加到网格布局中并将容器添加到竖直布局中
        self.__addAlbumCardToGridLayout()
        self.__addContainterToVBoxLayout()
        self.__adjustScrollWidgetSize()

    def sortByYear(self):
        """ 按照专辑的年份进行分组排序 """
        self.sortMode = '发行年份'
        # 将专辑卡从旧布局中移除
        self.__removeContainerFromVBoxLayout()
        # 创建分组
        year_list = []
        self.yearGroupDict_list = []
        # 将专辑加到分组中
        for albumCard_dict in self.albumCardDict_list:
            year = albumCard_dict['year']
            year = '未知' if year == '未知年份' else year
            # 如果年份不在年份列表中就创建分组
            if year not in year_list:
                year_list.append(year)
                # 实例化分组和网格布局
                group = GroupBox(year)
                gridLayout = GridLayout()
                group.setLayout(gridLayout)
                gridLayout.setVerticalSpacing(20)
                gridLayout.setHorizontalSpacing(10)
                self.yearGroupDict_list.append(
                    {'container': group, 'year': year,
                     'gridLayout': gridLayout, 'albumCard_list': []})
            # 将专辑卡添加到分组中
            index = year_list.index(year)
            self.yearGroupDict_list[index]['albumCard_list'].append(
                albumCard_dict['albumCard'])
        # 按照年份从进到远排序
        self.yearGroupDict_list.sort(
            key=lambda item: item['year'], reverse=True)
        # 检测是否含有未知分组,有的话将其移到最后一个
        if '未知' in year_list:
            unique_group = self.yearGroupDict_list.pop(0)
            self.yearGroupDict_list.append(unique_group)
        # 将专辑加到分组的网格布局中
        self.currentGroupDict_list = self.yearGroupDict_list
        self.__addAlbumCardToGridLayout()
        self.__addContainterToVBoxLayout()
        self.__adjustScrollWidgetSize()

    def sortBySonger(self):
        """ 按照专辑的专辑进行分组排序 """
        self.sortMode = '歌手'
        # 将专辑卡从旧布局中移除
        self.__removeContainerFromVBoxLayout()
        # 创建列表
        songer_list = []
        self.songerGroupDict_list = []
        # 将专辑加到分组中
        for albumCard_dict in self.albumCardDict_list:
            songer = albumCard_dict['songer']
            if songer not in songer_list:
                songer_list.append(songer)
                group = GroupBox(songer)
                gridLayout = GridLayout()
                group.setLayout(gridLayout)
                gridLayout.setVerticalSpacing(20)
                gridLayout.setHorizontalSpacing(10)
                self.songerGroupDict_list.append(
                    {'container': group, 'songer': songer,
                     'gridLayout': gridLayout, 'albumCard_list': []})
            # 将专辑卡添加到分组中
            index = songer_list.index(songer)
            self.songerGroupDict_list[index]['albumCard_list'].append(
                albumCard_dict['albumCard'])
        # 排序列表
        self.songerGroupDict_list.sort(key=lambda item: item['songer'].lower())
        # 将专辑加到分组的网格布局中
        self.currentGroupDict_list = self.songerGroupDict_list
        self.__addAlbumCardToGridLayout()
        self.__addContainterToVBoxLayout()
        self.__adjustScrollWidgetSize()

    def __setQss(self):
        """ 设置层叠样式 """
        with open('resource\\css\\albumCardViewer.qss', encoding='utf-8') as f:
            self.setStyleSheet(f.read())

    def findAlbumCardByAlbumInfo(self, albumInfo: dict) -> AlbumCard:
        """ 通过albumInfo获取对AlbumCard实例的引用 """
        for albumCard in self.albumCard_list:
            if albumCard.albumInfo == albumInfo:
                return albumCard
        return None

    def findAlbumCardByName(self, albumName: str, songerName: str) -> AlbumCard:
        """ 通过名字查找专辑卡 """
        for albumCard in self.albumCard_list:
            if albumCard.albumInfo['album'] == albumName:
                # 如果歌手名也相同就直接返回，否则在歌曲列表中寻找
                if albumCard.albumInfo['songer'] == songerName:
                    return albumCard
                else:
                    for songInfo in albumCard.albumInfo['songInfo_list']:
                        if songInfo['songer'] == songerName:
                            return albumCard
        return None

    def __albumCardCheckedStateChangedSlot(self, albumCard: AlbumCard, isChecked: bool):
        """ 专辑卡选中状态改变对应的槽函数 """
        # 如果专辑信息不在选中的专辑信息列表中且对应的专辑卡变为选中状态就将专辑信息添加到列表中
        if albumCard not in self.checkedAlbumCard_list and isChecked:
            self.checkedAlbumCard_list.append(albumCard)
            self.checkedAlbumCardNumChanged.emit(
                len(self.checkedAlbumCard_list))
        # 如果专辑信息已经在列表中且该专辑卡变为非选中状态就弹出该专辑信息
        elif albumCard in self.checkedAlbumCard_list and not isChecked:
            self.checkedAlbumCard_list.pop(
                self.checkedAlbumCard_list.index(albumCard))
            self.checkedAlbumCardNumChanged.emit(
                len(self.checkedAlbumCard_list))
        # 如果先前不处于选择模式那么这次发生选中状态改变就进入选择模式
        if not self.isInSelectionMode:
            # 所有专辑卡进入选择模式
            self.__setAllAlbumCardSelectionModeOpen(True)
            # 发送信号要求主窗口隐藏播放栏
            self.selectionModeStateChanged.emit(True)
            # 更新标志位
            self.isInSelectionMode = True
        else:
            if not self.checkedAlbumCard_list:
                # 所有专辑卡退出选择模式
                self.__setAllAlbumCardSelectionModeOpen(False)
                # 发送信号要求主窗口显示播放栏
                self.selectionModeStateChanged.emit(False)
                # 更新标志位
                self.isInSelectionMode = False

    def __setAllAlbumCardSelectionModeOpen(self, isOpenSelectionMode: bool):
        """ 设置所有专辑卡是否进入选择模式 """
        for albumCard in self.albumCard_list:
            albumCard.setSelectionModeOpen(isOpenSelectionMode)
        # 退出选择模式时开启隐藏所有复选框的动画
        if not isOpenSelectionMode:
            self.__startHideCheckBoxAni()

    def __startHideCheckBoxAni(self):
        """ 开始隐藏复选框动画 """
        for ani in self.hideCheckBoxAni_list:
            ani.setStartValue(1)
            ani.setEndValue(0)
            ani.setDuration(140)
        self.hideCheckBoxAniGroup.start()

    def __hideAllCheckBox(self):
        """ 隐藏所有复选框 """
        for albumCard in self.albumCard_list:
            albumCard.checkBox.hide()

    def unCheckAlbumCards(self):
        """ 取消所有已处于选中状态的专辑卡的选中状态 """
        checkedAlbumCard_list_copy = self.checkedAlbumCard_list.copy()
        for albumCard in checkedAlbumCard_list_copy:
            albumCard.setChecked(False)

    def setAllAlbumCardCheckedState(self, isAllChecked: bool):
        """ 设置所有的专辑卡checked状态 """
        if self.isAllAlbumCardsChecked == isAllChecked:
            return
        self.isAllAlbumCardsChecked = isAllChecked
        for albumCard in self.albumCard_list:
            albumCard.setChecked(isAllChecked)

    def __showBlurAlbumBackground(self, pos: QPoint, picPath: str):
        """ 显示磨砂背景 """
        # 将全局坐标转为窗口坐标
        pos = self.scrollWidget.mapFromGlobal(pos)
        self.albumBlurBackground.setBlurAlbum(picPath)
        self.albumBlurBackground.move(pos.x() - 31, pos.y() - 16)
        self.albumBlurBackground.show()

    def updateOneAlbumCardSongInfo(self, newSongInfo: dict):
        """ 更新一个专辑卡的一首歌的信息 """
        for albumCard in self.albumCard_list:
            albumInfo = albumCard.albumInfo
            if albumInfo['album'] == newSongInfo['album'] and albumInfo['songer'] == newSongInfo['songer']:
                for i, songInfo in enumerate(albumInfo['songInfo_list']):
                    if songInfo['songPath'] == newSongInfo['songPath']:
                        albumInfo['songInfo_list'][i] = newSongInfo.copy()
                        return albumInfo
        return {}

    def updateAllAlbumCards(self, albumInfo_list: list):
        """ 更新所有专辑卡 """
        oldAlbumInfo_list = [
            albumCard.albumInfo for albumCard in self.albumCard_list]
        if albumInfo_list == oldAlbumInfo_list:
            return
        # 将专辑卡从布局中移除
        self.__removeContainerFromVBoxLayout()
        # 根据具体情况增减专辑卡
        newCardNum = len(albumInfo_list)
        oldCardNum = len(self.albumCard_list)
        deltaNum = newCardNum - oldCardNum
        if deltaNum < 0:
            for i in range(oldCardNum - 1, newCardNum - 1, -1):
                albumCard = self.albumCard_list.pop()
                self.hideCheckBoxAni_list.pop()
                self.albumCardDict_list.pop()
                self.hideCheckBoxAniGroup.takeAnimation(i)
                albumCard.deleteLater()
        elif deltaNum > 0:
            for albumInfo in albumInfo_list[oldCardNum:]:
                self.__createOneAlbumCard(albumInfo)
                QApplication.processEvents()
        # 更新部分专辑卡
        self.albumInfo_list = albumInfo_list
        iterRange = range(oldCardNum) if deltaNum > 0 else range(newCardNum)
        for i in iterRange:
            albumInfo = albumInfo_list[i]
            album = albumInfo['album']
            self.albumCard_list[i].updateWindow(albumInfo)
            QApplication.processEvents()
            self.albumCardDict_list[i] = {'albumCard': self.albumCard_list[i],
                                          'albumName': album,
                                          'year': albumInfo['year'][:4],
                                          'songer': albumInfo['songer'],
                                          'firstLetter': pinyin.get_initial(album)[0].upper()}
        # 重新排序专辑卡
        self.setSortMode(self.sortMode)
        # 根据当前专辑卡数决定是否显示导航标签
        self.guideLabel.setHidden(bool(albumInfo_list))
        if deltaNum != 0:
            self.albumNumChanged.emit(newCardNum)

    def setSortMode(self, sortMode: str):
        """ 排序专辑卡 """
        self.sortMode = sortMode
        if sortMode == '添加时间':
            self.sortByAddTime()
        elif sortMode == 'A到Z':
            self.sortByFirstLetter()
        elif sortMode == '发行年份':
            self.sortByYear()
        elif sortMode == '歌手':
            self.sortBySonger()
        else:
            raise Exception(f'排序依据"{sortMode}"不存在')

    def showDeleteOneCardPanel(self, albumInfo: dict):
        """ 显示删除一个专辑卡的对话框 """
        title = '是否确定要删除此项？'
        content = f"""如果删除"{albumInfo['album']}"，它将不再位于此设备上。"""
        deleteCardPanel = DeleteCardPanel(title, content, self.window())
        deleteCardPanel.deleteCardSig.connect(
            lambda: self.__deleteAlbumCards([albumInfo]))
        deleteCardPanel.exec_()

    def showDeleteMultiAlbumCardPanel(self, albumInfo_list: list):
        """ 显示删除多个专辑卡的对话框 """
        title = '确定要删除这些项？'
        content = "如果你删除这些专辑，它们将不再位于此设备上。"
        deleteCardPanel = DeleteCardPanel(title, content, self.window())
        deleteCardPanel.deleteCardSig.connect(
            lambda: self.__deleteAlbumCards(albumInfo_list))
        deleteCardPanel.exec()

    def __deleteAlbumCards(self, albumInfo_list: list):
        """ 删除一个专辑卡 """
        for albumInfo in albumInfo_list:
            self.albumInfo_list.remove(albumInfo)
        self.updateAllAlbumCards(self.albumInfo_list)


from bootstrap_italia_template.widgets import BootstrapItaliaDateWidget

from ckeditor.widgets import CKEditorWidget

from django import forms
from django.utils.translation import gettext_lazy as _
from django.conf import settings

from ricerca_app.models import (RicercaDocenteLineaBase,
                                RicercaLineaApplicata,
                                RicercaLineaBase)

from .. utils.settings import CMS_STORAGE_ROOT_API
from .. utils.utils import _clean_teacher_dates

CMS_STORAGE_ROOT_API = getattr(
    settings, 'CMS_STORAGE_ROOT_API', CMS_STORAGE_ROOT_API)

class RicercaLineaApplicataForm(forms.ModelForm):
    class Meta:
        model = RicercaLineaApplicata
        fields = ['descrizione', 'descr_pubblicaz_prog_brevetto',
                  'anno', 'ricerca_aster2', 'visibile']
        labels = {
            'descrizione': _('Denomination'),
            'descr_pubblicaz_prog_brevetto': _('Patent project description'),
            'anno': _('Year'),
            'ricerca_aster2': _('ASTER2'),
        }
        widgets = {'descr_pubblicaz_prog_brevetto': CKEditorWidget()}

    class Media:
        js = ('js/textarea-autosize.js',)

class RicercaLineaBaseForm(forms.ModelForm):
    class Meta:
        model = RicercaLineaBase
        fields = ['descrizione', 'descr_pubblicaz_prog_brevetto',
                  'anno', 'ricerca_erc2', 'visibile']
        labels = {
            'descrizione': _('Denomination'),
            'descr_pubblicaz_prog_brevetto': _('Patent project description'),
            'anno': _('Year'),
            'ricerca_erc2': _('ERC2'),
        }
        widgets = {'descr_pubblicaz_prog_brevetto': CKEditorWidget()}

    class Media:
        js = ('js/textarea-autosize.js',)

class RicercaDocenteLineaBaseForm(forms.ModelForm):
    choosen_person = forms.CharField(label=_('Teacher'),
                                     widget=forms.HiddenInput(),
                                     required=True)

    def clean(self):
        cleaned_data = super().clean()
        _clean_teacher_dates(self, cleaned_data)

    class Meta:
        model = RicercaDocenteLineaBase
        fields = ['dt_inizio', 'dt_fine']
        labels = {
            'dt_inizio': _('From'),
            'dt_fine': _('To'),
        }
        widgets = {'dt_inizio': BootstrapItaliaDateWidget,
                   'dt_fine': BootstrapItaliaDateWidget, }

class RicercaDocenteLineaApplicataForm(forms.ModelForm):
    choosen_person = forms.CharField(label=_('Person'),
                                     widget=forms.HiddenInput(),
                                     required=True)

    def clean(self):
        cleaned_data = super().clean()
        _clean_teacher_dates(self, cleaned_data)

    class Meta:
        model = RicercaDocenteLineaBase
        fields = ['dt_inizio', 'dt_fine']
        labels = {
            'dt_inizio': _('From'),
            'dt_fine': _('To'),
        }
        widgets = {'dt_inizio': BootstrapItaliaDateWidget,
                   'dt_fine': BootstrapItaliaDateWidget, }


import numpy as np
from scipy.sparse import csr_matrix, lil_matrix, diags

class Bus():
	"""Electrical network bus """

	def __init__(self, bus_id, name, bus_type, init_voltage, final_voltage,
	                   base_voltage, angle, load, generation, Q_min, Q_max,
	                   P_min, P_max, sh_conductance, sh_susceptance):

		self.bus_id = bus_id #Int
		self.name = name #String
		self.bus_type = bus_type # 0:PQ, 1:Q \theta, 2: PV, 3: V\theta
		self.init_voltage = init_voltage #Float
		self.final_voltage = final_voltage #Float
		self.base_voltage = base_voltage # base voltage in KV
		self.angle = angle #Float
		self.load = load #Complex
		self.generation = generation #Complex
		self.Q_min = Q_min #Float
		self.Q_max = Q_max #Float
		self.P_min = P_min #Float
		self.P_max = P_max #Float
		self.sh_conductance = sh_conductance #Float
		self.sh_susceptance = sh_susceptance #Float

class Line():
	"""Electrical line"""

	def __init__(self, line_id, source, target, status, admittance,
	                   sh_susceptance, line_type, s_ratio, t_ratio,
	                   phase_shift):

		self.line_id = line_id #Int
		self.source = source #Bus
		self.target = target #Bus
		self.status = status #Bool
		self.admittance = admittance #Complex Y = 1/Z  for Z = R + iX
		self.sh_susceptance = sh_susceptance #Float
		self.line_type = line_type
		self.s_ratio = s_ratio #Complex
		self.t_ratio = t_ratio #Complex
		self.phase_shift = phase_shift #In radians

class Electrical_network():
	"""Electrical Network: array of lines, array of busses, adjacency and admittance matrices"""

	def __init__(self, busses, lines, S_BASE):

		self.busses = busses
		self.lines = lines
		self.S_BASE = S_BASE
		self.Y = self.__YMatrix()
		self.A = self.__Get_Adjacency_matrix()
		self.L = self.__Get_Laplacian_matrix()

	def YMatrix(self):

		n = len(self.busses)
		Y = lil_matrix((n,n), dtype=complex)

		for l in self.lines:
			if l.status == True:
				y = l.admittance
				y_sh = l.sh_susceptance*1j
				Y[l.source.bus_id, l.source.bus_id] += pow(abs(l.s_ratio),2)*(y + y_sh/2)
				Y[l.target.bus_id, l.target.bus_id] += pow(abs(l.t_ratio),2)*(y + y_sh/2)
				Y[l.source.bus_id, l.target.bus_id] += -y*np.conjugate(l.s_ratio)*l.t_ratio
				Y[l.target.bus_id, l.source.bus_id] += -y*np.conjugate(l.t_ratio)*l.s_ratio

		# add shunt susceptance to each node
		Y = Y.tocsr() + diags(np.array([bus.sh_conductance + bus.sh_susceptance*1j for bus in self.busses]))

		return Y

	__YMatrix = YMatrix

	def Get_Adjacency_matrix(self):

		n = len(self.busses)
		Y = (self.Y).copy()
		Y -= diags(Y.diagonal())
		row, col = Y.nonzero()
		A = csr_matrix((np.ones(len(row)),(row,col)), shape=(n,n))

		return A

	__Get_Adjacency_matrix = Get_Adjacency_matrix

	def Get_Laplacian_matrix(self):

		return diags(np.squeeze(np.asarray((self.A).sum(axis=0)))) - self.A

	__Get_Laplacian_matrix = Get_Laplacian_matrix

	def Get_power(self):

		S = np.array([-b.load + b.generation for b in self.busses])
		return S.real, S.imag

	def YMatrix_DC(self):
		# Same approximations as in the Matpower DC power flow

		n = len(self.busses)
		B_DC, G_DC = lil_matrix((n,n), dtype=complex), lil_matrix((n,n), dtype=complex)

		for l in self.lines:
			if l.status == True:
				# Only the reactance of the line is included y = 1/z for z = 1j*x, neglect r
				b = 1./(1j*((1./l.admittance).imag)) #

				#cos(phase shift)  \approx 1
				B_DC[l.source.bus_id, l.target.bus_id] += -b*abs(np.conjugate(l.s_ratio)*l.t_ratio)
				B_DC[l.target.bus_id, l.source.bus_id] += -b*abs(np.conjugate(l.t_ratio)*l.s_ratio)

				# 1j* sin(phase shift)  \approx 1j* sin(phase shift)
				G_DC[l.source.bus_id, l.target.bus_id] += -b*abs(np.conjugate(l.s_ratio)*l.t_ratio)*(l.phase_shift)*1j
				G_DC[l.target.bus_id, l.source.bus_id] += -b*abs(np.conjugate(l.t_ratio)*l.s_ratio)*(-l.phase_shift)*1j

		# B_DC includes tap ratios, line shunt_susceptances are neglected
		# B_DC is really a weighted Laplacian matrix
		B_DC = B_DC.tocsr()
		B_DC = B_DC.imag
		B_DC = B_DC - diags( np.squeeze(np.asarray(B_DC.sum(axis=1))) )

		# dP is the adjustment to power injections which is due to phase shifters and real shunts
		G_DC = G_DC.real
		dP = np.squeeze(np.asarray(G_DC.sum(axis=1))) + np.array([bus.sh_conductance for bus in self.busses])
		return B_DC, dP


from tools import Parser
import sys
import time

in_file = sys.argv[1]
out_file = sys.argv[2]
myParser = Parser(in_file)
P_lst = myParser.queryList()
size = len(P_lst)

def larger(str1, str2):
    if str2 == float("inf") and not str1 == float("inf"):
        return False
    if str1 == float("inf"):
        return True
    asc_lst_1 = [ord(x) for x in str1]
    asc_lst_2 = [ord(x) for x in str2]
    if(len(asc_lst_1) < len(asc_lst_2)):
        for idx in range(len(asc_lst_1)):
            if asc_lst_1[idx] < asc_lst_2[idx]:
                return False
            elif asc_lst_1[idx] > asc_lst_2[idx]:
                return True
            else:
                continue
        return False
    else:
        for idx in range(len(asc_lst_2)):
            if asc_lst_1[idx] < asc_lst_2[idx]:
                return False
            elif asc_lst_1[idx] > asc_lst_2[idx]:
                return True
            else:
                continue
        return True

def Merge(P_lst, head, m1, m2, tail):
    l_lst = P_lst[head:m1]
    m_lst = P_lst[m1:m2]
    r_lst = P_lst[m2:tail]
    l = 0
    m = 0
    r = 0
    l_lst.append(float("inf"))
    m_lst.append(float("inf"))
    r_lst.append(float("inf"))
    for i in range(head,tail):
        if larger(m_lst[m], l_lst[l]) and larger(r_lst[r], l_lst[l]):
            P_lst[i] = l_lst[l]
            l+=1
        elif larger(l_lst[l], m_lst[m]) and larger(r_lst[r], m_lst[m]):
            P_lst[i] = m_lst[m]
            m+=1
        elif larger(l_lst[l], r_lst[r]) and larger(m_lst[m], r_lst[r]):
            P_lst[i] = r_lst[r]
            r+=1
'''
        if l_lst[l] <= m_lst[m] and l_lst[l] <= r_lst[r]:
            P_lst[i] = l_lst[l]
            l+=1
        elif m_lst[m] <= l_lst[l] and m_lst[m] <= r_lst[r]:
            P_lst[i] = m_lst[m]
            m+=1
        elif r_lst[r] <= l_lst[l] and r_lst[r] <= m_lst[m]:
            P_lst[i] = r_lst[r]
            r+=1
'''

def MergeSort(P_lst, head, tail):
    if((tail-head) < 2):
        return
    m1 = head+ int((tail-head)/3)
    if((tail-head)%3!=0):
        m1+=1
    m2 = m1 + int((tail-head)/3)
    if((tail-head)%3==2):
        m2+=1
    MergeSort(P_lst, head, m1)
    MergeSort(P_lst, m1, m2)
    MergeSort(P_lst, m2, tail)
    Merge(P_lst, head, m1, m2, tail)

t0 = time.time()
MergeSort(P_lst, 0, size)
t1 = time.time()

run_time = t1-t0

with open(out_file, 'w') as f:
    for i, x in enumerate(P_lst):
        if i == size-1:
            f.write(x)
        else:
            f.write(x+'\n')
    #f.write("input_size: "+str(size)+'\n')
    #f.write("run_time: "+str(run_time)+'\n')

'''
lst = [1000, 999, 43, 22, 1, 0]
print(lst)
MergeSort(lst, 0, len(lst))
print(lst)
'''


__author__ = 'student'
import numpy as np

def get_percentile_number(value, percentiles):
    k = 0
    if value <= percentiles[0]:
        k = 0
    elif value >= percentiles[len(percentiles)-1]:
        k = len(percentiles)
    else:
        for i in range(len(percentiles) - 1, 0, -1):
            if percentiles[i] <= value:
                k = i
                break

    return k

def get_percentile(values, n):
    k = 100 / n
    a = 0
    t = []
    while a != 100:
        t.append(np.percentile(values,a))
        a += k
    if min (values) >= 0:
        t[0] = 0.0
    return t

#def  value_equalization(value, percentiles):

l = []
values = [3, 4, 1, 2, 5, 6, 7, 8, 9, 10]
n = int (input())
l = get_percentile(values, n)
print(' '.join(map(str, l)))
a = int(input())
print(get_percentile_number(a, l))


# File : blink.py
# Simple program to blink a led 10 times
# https://docs.micropython.org/en/latest/library/machine.Pin.html
# joao.galhardocarraca@student.hepl.be
# 13/2/2023

#Import of libraries
from machine import Pin
import utime

#Led pin configuration
led = Pin(16, Pin.OUT)

#For statement to 10 togles of the led
for i in range (10):
    led.value(1)	#Led on
    sleep(1)	#Wait for 1 second
    led.value(0)	#Led off
    sleep(1)


"""Provide tests for cli."""

# Authors: Federico Raimondo <f.raimondo@fz-juelich.de>
#          Synchon Mandal <s.mandal@fz-juelich.de>
# License: AGPL

from pathlib import Path
from typing import List, Tuple

import pytest
from click.testing import CliRunner
from ruamel.yaml import YAML

from junifer.api.cli import _parse_elements_file, collect, run, selftest, wtf

# Configure YAML class
yaml = YAML()
yaml.default_flow_style = False
yaml.allow_unicode = True
yaml.indent(mapping=2, sequence=4, offset=2)

# Create click test runner
runner = CliRunner()

# TODO: adapt elements to take arrays
@pytest.mark.parametrize(
    "elements",
    [
        ("sub-01", "sub-02", "sub-03"),
        ("sub-01", "sub-02", "sub-04"),
    ],
)
def test_run_and_collect_commands(
    tmp_path: Path, elements: Tuple[str, ...]
) -> None:
    """Test run and collect commands.

    Parameters
    ----------
    tmp_path : pathlib.Path
        The path to the test directory.
    elements : tuple of str
        The parametrized elements to operate on.

    """
    # Get test config
    infile = Path(__file__).parent / "data" / "gmd_mean.yaml"
    # Read test config
    contents = yaml.load(infile)
    # Working directory
    workdir = tmp_path / "workdir"
    contents["workdir"] = str(workdir.resolve())
    # Output directory
    outdir = tmp_path / "outdir"
    # Storage
    contents["storage"]["uri"] = str(outdir.resolve())
    # Write new test config
    outfile = tmp_path / "in.yaml"
    yaml.dump(contents, stream=outfile)
    # Run command arguments
    run_args = [
        str(outfile.absolute()),
        "--verbose",
        "debug",
        "--element",
        elements[0],
        "--element",
        elements[1],
        "--element",
        elements[2],
    ]
    # Invoke run command
    run_result = runner.invoke(run, run_args)
    # Check
    assert run_result.exit_code == 0
    # Collect command arguments
    collect_args = [str(outfile.absolute()), "--verbose", "debug"]
    # Invoke collect command
    collect_result = runner.invoke(collect, collect_args)
    # Check
    assert collect_result.exit_code == 0

@pytest.mark.parametrize(
    "elements",
    [
        "sub-01",
        "sub-01\nsub-02",
        "    sub-01    ",
        "sub-01\n    sub-02",
    ],
)
def test_run_using_element_file(tmp_path: Path, elements: str) -> None:
    """Test run command using element file.

    Parameters
    ----------
    tmp_path : pathlib.Path
        The path to the test directory.
    elements : str
        The parametrized elements to write to the element file.

    """
    # Create test file
    test_file_path = tmp_path / "elements.txt"
    with open(test_file_path, "w") as f:
        f.write(elements)

    # Get test config
    infile = Path(__file__).parent / "data" / "gmd_mean.yaml"
    # Read test config
    contents = yaml.load(infile)
    # Working directory
    workdir = tmp_path / "workdir"
    contents["workdir"] = str(workdir.resolve())
    # Output directory
    outdir = tmp_path / "outdir"
    # Storage
    contents["storage"]["uri"] = str(outdir.resolve())
    # Write new test config
    outfile = tmp_path / "in.yaml"
    yaml.dump(contents, stream=outfile)
    # Run command arguments
    run_args = [
        str(outfile.absolute()),
        "--verbose",
        "debug",
        "--element",
        str(test_file_path.resolve()),
    ]
    # Invoke run command
    run_result = runner.invoke(run, run_args)
    # Check
    assert run_result.exit_code == 0

@pytest.mark.parametrize(
    "elements, expected_list",
    [
        ("sub-01,ses-01", [("sub-01", "ses-01")]),
        (
            "sub-01,ses-01\nsub-02,ses-01",
            [("sub-01", "ses-01"), ("sub-02", "ses-01")],
        ),
        ("sub-01, ses-01", [("sub-01", "ses-01")]),
        (
            "sub-01, ses-01\nsub-02, ses-01",
            [("sub-01", "ses-01"), ("sub-02", "ses-01")],
        ),
        (" sub-01 , ses-01 ", [("sub-01", "ses-01")]),
        (
            " sub-01 , ses-01 \n sub-02, ses-01 ",
            [("sub-01", "ses-01"), ("sub-02", "ses-01")],
        ),
    ],
)
def test_multi_element_access(
    tmp_path: Path, elements: str, expected_list: List[Tuple[str, ...]]
) -> None:
    """Test mulit-element parsing.

    Parameters
    ----------
    tmp_path : pathlib.Path
        The path to the test directory.
    elements : str
        The parametrized elements to write to the element file.
    expected_list : list of tuple of str
        The parametrized list of element tuples to expect.

    """
    # Create test file
    test_file_path = tmp_path / "elements_multi.txt"
    with open(test_file_path, "w") as f:
        f.write(elements)
    # Load element file
    read_elements = _parse_elements_file(test_file_path)
    # Check
    assert read_elements == expected_list

def test_wtf_short() -> None:
    """Test short version of wtf command."""
    # Invoke wtf command
    wtf_result = runner.invoke(wtf)
    # Check
    assert wtf_result.exit_code == 0

def test_wtf_long() -> None:
    """Test long version of wtf command."""
    # Invoke wtf command
    wtf_result = runner.invoke(wtf, "--long")
    # Check
    assert wtf_result.exit_code == 0

def test_selftest_invalid_arg() -> None:
    """Test selftest failure for invalid argument value."""
    # Invoke selftest command
    selftest_result = runner.invoke(selftest, "abyss")
    # Check
    assert selftest_result.exit_code == 2

def test_selftest() -> None:
    """Test selftest."""
    # Invoke selftest command
    selftest_result = runner.invoke(selftest, "tests")
    # Check; will result in 1 due to I/O descriptor manipulation
    assert selftest_result.exit_code == 1


from django import forms
from django.forms import TextInput, Select

from numeAplicatie.models import Location

class LocationForm(forms.ModelForm):
    class Meta:
        model = Location
        fields = ['country', 'city']

        widgets = {
            'city': TextInput(attrs={'placeholder': 'City', 'class': 'field'}),
            'country': TextInput(attrs={'placeholder': 'Country', 'class': 'field'}),
        }

    def __init__(self, test, *args, **kwargs):
        super(LocationForm, self).__init__(*args, **kwargs)
        self.test = test

    def clean(self):
        cleaned_data = self.cleaned_data
        city_val = self.cleaned_data['city']
        country_val = self.cleaned_data['country']
        if self.test:
            all_locations = Location.objects.all().exclude(id=self.test)
        else:
            all_locations = Location.objects.all()
        for location in all_locations:
            if city_val == location.city and country_val == location.country:
                self._errors['city'] = 'Duplicate entry'
        return cleaned_data


from DeepWhiskerCuts.setting.setting import leftcam1,pupil_destination
# from DeepWhiskerCuts.lib.ProgressManager import ProgressManager
import pdb
import os
import shutil
from dirsync import sync

animals = os.listdir(leftcam1['data_path'])

for animali in animals:
    experiments = os.listdir(os.path.join(leftcam1['data_path'],animali))
    print(animali)
    for experimenti in experiments:
        experiment_folder = os.path.join(leftcam1['data_path'],animali,experimenti)
        nfiles = len(os.listdir(experiment_folder))
        print('    ' + experimenti)
        print('    '+str())
        if nfiles > 30:
            destination_folder = os.path.join(pupil_destination,leftcam1['tag'],*experiment_folder.split(os.path.sep)[-2:])
            os.makedirs(destination_folder,exist_ok=True)
            print('copying')
            sync(experiment_folder, destination_folder, 'sync')

        # manager = ProgressManager(experiment_folder,'side')
        # if manager.finished:
        #     destination_folder = os.path.join(pupil_destination,leftcam1['tag'],*manager.dir.split(os.path.sep)[-2:])
        #     os.makedirs(destination_folder,exist_ok=True)
        #     print('copying')
        #     sync(experiment_folder, destination_folder, 'sync')


import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import OneHotEncoder, StandardScaler

def set_missing_ages(df):
    age_df = df[['Age', 'Fare', 'Parch', 'SibSp', 'Pclass']]
    known_age = age_df[age_df.Age.notnull()].values
    unknown_age = age_df[age_df.Age.isnull()].values
    y = known_age[:, 0]
    x = known_age[:, 1:]
    rfr = RandomForestRegressor(random_state=0, n_estimators=2000, n_jobs=-1)
    # 表示使用2000个决策树，n_jobs表示使用cpu的核数，random_state表示随机种子
    rfr.fit(x, y)
    predicted_ages = rfr.predict(unknown_age[:, 1::])  # 1::表示从第一个元素开始，每隔一个元素取一个元素
    df.loc[(df.Age.isnull()), 'Age'] = predicted_ages
    return rfr

def set_cabin_type(df):
    df.loc[(df.Cabin.notnull()), 'Cabin'] = 'Yes'
    df.loc[(df.Cabin.isnull()), 'Cabin'] = 'No'

def one_hot_encoder(df, col):
    one_hot = OneHotEncoder(sparse_output=False)
    df_encoded = pd.DataFrame(one_hot.fit_transform(df[col]))
    df_encoded.columns = one_hot.get_feature_names_out()
    df.drop(col, axis=1, inplace=True)
    df = pd.concat([df, df_encoded], axis=1)
    return df

def standard_scaler(df, col):
    scaler = StandardScaler()
    df[col] = scaler.fit_transform(df[col])


"""Counter Strike: Global Offensive test script"""
import logging
import os
import time
import sys
from argparse import ArgumentParser
import pyautogui as gui
import pydirectinput as user
from utils import (
    get_resolution,
    benchmark_folder_exists,
    download_benchmark,
    copy_benchmark,
    STEAM_GAME_ID
)

sys.path.insert(1, os.path.join(sys.path[0], '..'))

# pylint: disable=wrong-import-position
from harness_utils.output import (
    format_resolution,
    seconds_to_milliseconds,
    setup_log_directory,
    write_report_json,
    DEFAULT_LOGGING_FORMAT,
    DEFAULT_DATE_FORMAT,
)
from harness_utils.process import terminate_processes
from harness_utils.steam import exec_steam_run_command
from harness_utils.keras_service import KerasService
# pylint: enable=wrong-import-position

MAP = "de_dust2"
SCRIPT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
LOG_DIRECTORY = os.path.join(SCRIPT_DIRECTORY, "run")
PROCESS_NAME = "csgo.exe"

def console_command(command):
    """Types out the provided command one character at a time"""
    for char in command:
        gui.press(char)
    user.press("enter")

def run_benchmark():
    """Start the benchmark"""
    if not benchmark_folder_exists():
        download_benchmark()

    copy_benchmark()
    setup_start_time = time.time()
    exec_steam_run_command(STEAM_GAME_ID)
    time.sleep(30)  # wait for game to load into main menu

    logging.info("Waiting for game to start...")
    result = kerasService.wait_for_word("news", interval=2, timeout=120)
    if not result:
        logging.info("Game didn't start in time. Check settings and try again.")
        sys.exit(1)

    logging.info('Game started. Loading map.')
    user.press("`")
    time.sleep(1)
    console_command(f"map {MAP}")
    time.sleep(5)  # wait for map to load

    logging.info("Waiting for map to load...")
    result = kerasService.wait_for_word("terrorists", interval=2, timeout=120)
    if not result:
        logging.info("Game didn't load map. Check settings and try again.")
        sys.exit(1)

    logging.info('Map loaded. Starting benchmark.')
    time.sleep(1)
    user.press("`")
    time.sleep(0.5)
    console_command("exec benchmark")
    time.sleep(0.5)
    console_command("benchmark")

    elapsed_setup_time = round((time.time() - setup_start_time), 2)
    logging.info("Harness setup took %.2f seconds", elapsed_setup_time)
    test_start_time = time.time()

    logging.info("Waiting for benchmark to run...")
    time.sleep(43) #approximate wait time

    logging.info("Waiting for benchmark results...")
    result = kerasService.wait_for_word("finished", interval=1, timeout=60)
    if not result:
        logging.info("Game didn't finish. Check settings and try again.")
        sys.exit(1)

    test_end_time = time.time()
    elapsed_test_time = round(test_end_time - test_start_time, 2)
    logging.info("Benchmark took %.2f seconds", elapsed_test_time)

    terminate_processes(PROCESS_NAME)
    return start_time, end_time

# Entry Point
setup_log_directory(LOG_DIRECTORY)

logging.basicConfig(filename=f'{LOG_DIRECTORY}/harness.log',
                    format=DEFAULT_LOGGING_FORMAT,
                    datefmt=DEFAULT_DATE_FORMAT,
                    level=logging.DEBUG)
console = logging.StreamHandler()
formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT)
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

parser = ArgumentParser()
parser.add_argument("--kerasHost", dest="keras_host",
                    help="Host for Keras OCR service", required=True)
parser.add_argument("--kerasPort", dest="keras_port",
                    help="Port for Keras OCR service", required=True)
args = parser.parse_args()
kerasService = KerasService(args.keras_host, args.keras_port, os.path.join(
    LOG_DIRECTORY, "screenshot.jpg"))

benchmark_folder_exists()
try:
    start_time, end_time = run_benchmark()
    height, width = get_resolution()
    report = {
        "resolution": format_resolution(width, height),
        "start_time": seconds_to_milliseconds(start_time),
        "end_time": seconds_to_milliseconds(end_time)
    }

    write_report_json(LOG_DIRECTORY, "report.json", report)
#pylint: disable=broad-exception-caught
except Exception as e:
    logging.error("Something went wrong running the benchmark!")
    logging.exception(e)
    terminate_processes(PROCESS_NAME)
    sys.exit(1)


import pickle

import numpy as np
import pandas as pd
from sklearn import tree

def tree_accuracy(X, y, depth):
    """Output the score of a scikit-learn DT with given max_depth for comparison"""
    clf = tree.DecisionTreeClassifier(max_depth=depth)
    clf = clf.fit(X, y)
    return(clf.score(X,y))

def pickle_disjoint_data(modt, iteration, filepathprefix=""):
    """Save/export each subset of the data, separated by the gating function"""
    gating_values = modt.all_gating_values[iteration]
    gate = np.argmax(gating_values, axis=1)
    gating_values_hard = np.zeros([modt.n_input, modt.n_experts])
    gating_values_hard[np.arange(0, modt.n_input), gate] = 1

    if modt.X_original_pd is not None:
        X = modt.X_original_pd
    else:
        X = pd.DataFrame(modt.X_original)

    for index_expert in range(modt.n_experts):
        mask = gating_values_hard[:, index_expert] == 1
        df = X[mask].copy()
        df["target"] = modt.y_original[mask]

        pickle.dump(df, open(filepathprefix + "output/disjoint_data_e_{}.pd".format(index_expert), "wb"))

def optuna_optimization(dataset_input, dataset_target, n_experts, max_depth, gating_2D, runs, k_folds=4, delete_studies=True, only_random=True):

    import sys, os
    sys.path.insert(1, os.path.join(sys.path[0], ".."))
    from modt.modt import MoDT
    from modt._initialization import KDTmeans_init
    from modt._initialization import Kmeans_init
    from modt._initialization import BGM_init

    from datetime import datetime
    import gc
    from timeit import default_timer as timer

    import optuna
    from optuna.samplers import TPESampler
    import numpy as np
    import pandas as pd
    from sklearn.utils import shuffle
    from sklearn.model_selection import train_test_split
    from sklearn.model_selection import RepeatedKFold

    storage_name = "sqlite:///../temp/optuna_optimization.sqlite3"

    parameters = {
        "X": "overwritten",
        "y": "overwritten",
        "n_experts": "overwritten",
        "iterations": 100,
        "max_depth": "overwritten",
        "init_learning_rate": "overwritten",
        "learning_rate_decay": "overwritten",
        "initialization_method": "overwritten",
        "feature_names": None,
        "class_names": None,
        "use_2_dim_gate_based_on": "overwritten",
        "use_2_dim_clustering": "overwritten",
        "black_box_algorithm": None,
        }

    parameters_fit = {
        "optimization_method": "overwritten",
        "early_stopping": True,
        }

    if gating_2D:
        gate_selection = optuna.distributions.CategoricalDistribution(["feature_importance",
                                                                       "feature_importance_lda",
                                                                       "feature_importance_lda_max",
                                                                       "feature_importance_lr",
                                                                       "feature_importance_lr_max",
                                                                       "feature_importance_pca_loadings",
                                                                       "feature_importance_xgb",
                                                                       "PCA"])
    else:
        gate_selection = optuna.distributions.CategoricalDistribution([None])

    distributions = {
        "init_learning_rate": optuna.distributions.UniformDistribution(1,150),
        "learning_rate_decay": optuna.distributions.UniformDistribution(0.975,1),
        "n_experts": optuna.distributions.IntUniformDistribution(n_experts, n_experts),
        "max_depth": optuna.distributions.IntUniformDistribution(max_depth, max_depth),
        "use_2_dim_gate_based_on": gate_selection,
        "use_2_dim_clustering": optuna.distributions.CategoricalDistribution([gating_2D]), # Set to True for 2D
        "optimization_method": optuna.distributions.CategoricalDistribution(["least_squares_linear_regression","ridge_regression","lasso_regression"]),

                    }

    distributions_KDT_means = {
        "alpha": optuna.distributions.UniformDistribution(0.7,4),
        "beta": optuna.distributions.UniformDistribution(0.0001,0.5),
        "gamma": optuna.distributions.UniformDistribution(0.0001,0.5),
    }

    distributions_BGM = {
        "mean_precision_prior": optuna.distributions.UniformDistribution(0.1, 1),
        "weight_concentration_prior_type": optuna.distributions.CategoricalDistribution(["dirichlet_process", "dirichlet_distribution"]),
        "weight_concentration_prior": optuna.distributions.UniformDistribution(0.1, 1),
        "weight_cutoff": optuna.distributions.UniformDistribution(0.0, 0.1), # If max not 0.0, BGM can output fewer outputs
    }

    if only_random:
        initialization_methods = ["random"]
    else:
        initialization_methods = ["random", Kmeans_init(), KDTmeans_init(), BGM_init()]

    start = timer()
    n_trials = runs # per initialization_method
    n_startup_trials = int(runs/10) + 5 # random starting points instead of the TPE algorithm.

    data_input = dataset_input
    data_target = dataset_target

    for initialization_method in initialization_methods:

        parameters["initialization_method"] = initialization_method

        study_name = "{} Hyper: {} {}".format(datetime.now().strftime("%Y.%m.%d %H:%M:%S"), "Adhoc", initialization_method.__class__.__name__)
        study = optuna.create_study(study_name=study_name, directions=["maximize"], sampler=TPESampler(n_startup_trials=n_startup_trials), storage=storage_name)
        study.set_system_attr("initialization_method", initialization_method.__class__.__name__)

        use_dataframe = False
        if isinstance(data_input, pd.core.frame.DataFrame):
            use_dataframe = True

        for idx_trial in range(n_trials):

            if isinstance(initialization_method, KDTmeans_init):
                trial = study.ask({**distributions, **distributions_KDT_means})
                alpha = trial.params["alpha"]
                beta = trial.params["beta"]
                gamma = trial.params["gamma"]
                parameters["initialization_method"] = KDTmeans_init(alpha=alpha, beta=beta, gamma=gamma)
            elif isinstance(initialization_method, BGM_init):
                trial = study.ask({**distributions, **distributions_BGM})
                mean_precision_prior = trial.params["mean_precision_prior"]
                weight_concentration_prior_type = trial.params["weight_concentration_prior_type"]
                weight_concentration_prior = trial.params["weight_concentration_prior"]
                weight_cutoff = trial.params["weight_cutoff"]
                parameters["initialization_method"] = BGM_init(mean_precision_prior=mean_precision_prior,
                                                                weight_concentration_prior_type=weight_concentration_prior_type,
                                                                weight_concentration_prior=weight_concentration_prior,
                                                                weight_cutoff=weight_cutoff)
            else:
                trial = study.ask(distributions)

            parameters["init_learning_rate"] = trial.params["init_learning_rate"]
            parameters["learning_rate_decay"] = trial.params["learning_rate_decay"]
            parameters["n_experts"] = trial.params["n_experts"]
            parameters["max_depth"] = trial.params["max_depth"]
            parameters["use_2_dim_gate_based_on"] = trial.params["use_2_dim_gate_based_on"]
            parameters["use_2_dim_clustering"] = trial.params["use_2_dim_clustering"]

            parameters_fit["optimization_method"] = trial.params["optimization_method"]

            accuracies_training = []
            accuracies_validation = []
            rkf = RepeatedKFold(n_splits=k_folds, n_repeats=1)
            for train_idx, val_idx in rkf.split(data_input):

                if use_dataframe:
                    X_temp = data_input.iloc[train_idx].reset_index(inplace=False, drop=True)
                    y_temp = data_target.iloc[train_idx].reset_index(inplace=False, drop=True)
                else:
                    X_temp = data_input[train_idx]
                    y_temp = data_target[train_idx]

                # Insert k-fold dataset params
                parameters["X"] = X_temp
                parameters["y"] = y_temp

                modt = MoDT(**parameters)
                modt.fit(**parameters_fit)
                accuracies_training.append(modt.score_internal_disjoint())

                if use_dataframe:
                    X_temp = data_input.iloc[val_idx].reset_index(inplace=False, drop=True)
                    y_temp = data_target.iloc[val_idx].reset_index(inplace=False, drop=True)
                else:
                    X_temp = data_input[val_idx]
                    y_temp = data_target[val_idx]
                accuracies_validation.append(modt.score(X_temp, y_temp))

            dict_results = {}
            dict_results["accuracy_train"] = np.mean(accuracies_training)
            dict_results["accuracy_val"] = np.mean(accuracies_validation)
            dict_results["std_train"] = np.std(accuracies_training)
            dict_results["std_val"] = np.std(accuracies_validation)

            for key, value in dict_results.items():
                trial.set_user_attr(key, value)

            study.tell(trial, np.mean(accuracies_validation))

            #print("Completed trial:", idx_trial, initialization_method.__class__.__name__)
            gc.collect()

    print("Duration:", timer() - start, "Returning trials...")

    studies = optuna.study.get_all_study_summaries(storage=storage_name)
    loaded_study = optuna.load_study(study_name=studies[0].study_name, storage=storage_name)
    df = loaded_study.trials_dataframe()
    for key, value in loaded_study.system_attrs.items():
        df[key] = value
    for study in studies[1:]:
        loaded_study = optuna.load_study(study_name=study.study_name , storage=storage_name)
        df_new = loaded_study.trials_dataframe()
        for key, value in loaded_study.system_attrs.items():
            df_new[key] = value
        df = pd.concat([df, df_new])
        if delete_studies:
            optuna.delete_study(study_name=study.study_name , storage=storage_name)
    df.reset_index(inplace=True, drop=True)
    return df


from tkinter import *
from random import randrange
import random
haut = 150
larg = 150
cote = 7.5
vivant = 1
mort = 0
compta = 2
bleu = 3
comptat = 4
pourcompta = 20
pourcdeath = 3
pourcheal = 50
pourcres = 14
global jour
jour = 0
global t
t = 0
global it
it = 0
global an
an = 0
global main
man = 0
xp = 0
global comp
comp = 0
# Créer les matrices
cell = [[0 for row in range(haut)] for col in range(larg)]
matrice = [[mort for row in range(haut)] for col in range(larg)]
temp = [[mort for row in range(haut)] for col in range(larg)]
# Calculer et dessiner le prochain tableau
def tableau():
    global jour
    global t
    global it
    global an
    global xp
    global man
    main()
    aff()
    if t != 0:
        jour = jour + 14
        it = it + 1
        if it == 26:
            xp = xp + man
            man =  t - xp
            an = an +1
            it = 0
    print("nombre de jour: "+str(jour)+ " nombre de mort: " +str(t)+ " Année numeros: "+str(an)+" nombre de mort l'annéee d'avant: "+str(man)+" Nombre d'infecter : ", comp)
    fenetre.after(100, tableau)

def init():
    global pourcompta
    global pourcdeath
    global pourcheal
    global pourcres
    for y in range(haut):
        for x in range(larg):
            matrice[x][y] = vivant
            temp[x][y] = vivant
            cell[x][y] = canvas.create_rectangle((x*cote, y*cote,
                (x+1)*cote, (y+1)*cote), outline="gray", fill="white")
    matrice[35] [35] = compta
    matrice[35+1] [35] = compta
    matrice[35] [35+1] = compta
    matrice[35+1] [35+1] = compta
    choice  = int(input("Chargez des données perso(0), chargez données de base du corona (1)"))
    if choice == 0:
        pourcompta = int(input("chance de comptamination par cellule (1/?) "))
        pourcdeath = int(input("chance de mourrir par cellule infecte (1/?)"))
        pourcheal = int(input("chance d'etre soigne par cellule infecte (1/?)"))
        pourcres = int(input("chance de devenir resistant par cellule soigner (1/?)"))
def main():
    global t
    global comp
    for y in range(haut):
        for x in range(larg):
            nb_voisins = malade(x,y)

            if matrice[x][y] == vivant and nb_voisins > 0:
                nb = nb_voisins
                while nb != 0:
                    rand = random.randint(1,100)
                    if rand < pourcompta:
                        temp[x][y] = compta
                        comp = comp + 1
                    nb -= 1
            if matrice[x][y] == bleu and nb_voisins > 0:
                nb = nb_voisins
                while nb != 0:
                    rand = random.randint(1,200)
                    if rand < pourcompta:
                        temp[x][y] = comptat
                    nb -= 1
            if matrice[x][y] == compta  or matrice[x][y] == comptat :
                ra = random.randint(1,100)
                if ra < pourcheal:
                    rand = random.randint(1,100)
                    if rand < pourcres or matrice[x][y] == comptat:
                        temp[x][y] = bleu
                    else:
                        temp[x][y] = vivant
                if ra < pourcdeath:
                    temp[x][y] = mort
                    t += 1
            #if matrice[x][y] == vivant:
             ##   rand = random.randint(1,1000000)
            #    if rand == 5:
              #      temp[x][y] = compta
            #if matrice[x][y] == mort:
             #   rand = random.randint(1,10)
              #  if rand == 2:
               #     temp[x][y] = vivant
    for y in range(haut):
        for x in range(larg):
            matrice[x][y] = temp[x][y]

# Compter les voisins vivants - tableau torique
def malade(a,b):
    nb_voisins = 0
    if matrice[(a-1)%larg][(b+1)%haut] == 2:
        nb_voisins += 1
    if matrice[a][(b+1)%haut] == 2:
        nb_voisins += 1
    if matrice[(a+1)%larg][(b+1)%haut] == 2:
        nb_voisins += 1
    if matrice[(a-1)%larg][b] == 2:
        nb_voisins += 1
    if matrice[(a+1)%larg][b] == 2:
        nb_voisins += 1
    if matrice[(a-1)%larg][(b-1)%haut] == 2:
        nb_voisins += 1
    if matrice[a][(b-1)%haut] == 2:
        nb_voisins += 1
    if matrice[(a+1)%larg][(b-1)%haut] == 2:
        nb_voisins += 1
    return nb_voisins
def aff():
    red = 0
    for y in range(haut):
        for x in range(larg):
            if matrice[x][y] == 0:
                coul = "black"
            elif matrice [x][y] == 1:
                coul = "green"
            elif matrice [x][y] == 3:
                coul = "blue"
            elif matrice [x][y] == 2:
                coul = "red"
                red += 1
            elif matrice [x][y] == 4:
                coul = "red"
                red += 1
            canvas.itemconfig(cell[x][y], fill=coul)
fenetre = Tk()
fenetre.title("Simdemie")
canvas = Canvas(fenetre, width=cote*larg, height=cote*haut, highlightthickness=0)
canvas.pack()
init()
tableau()
fenetre.mainloop()


#!/usr/bin/python

import sys
import re

if __name__ == '__main__':
	fa = sys.argv[1]
	with open(fa,'r') as f:
		file = f.read()
	lst = file.split('>')[1:]
	dic = {}
	for i in range(len(lst)):
		name = lst[i].split('\n')[0]
		seq = ''.join(lst[i].split('\n')[1:])
		dic[name] = seq
	seqLst = dic.values()
	poly = {}
	for seq in seqLst:
		for i in range(len(seq)):
			if i not in poly.keys():
				poly[i] = []
			nuc = seq[i]
			if (nuc != '-') and (nuc not in poly[i]):
				poly[i].append(nuc)
	out = open(fa.split('.')[0] + '_PolymorphicSites','w')
	out2 = open(fa.split('.')[0] + '_ContigLinkages','w')
	siteLst = poly.keys()
	siteLst.sort()
	real = []
	for i in range(len(siteLst)):
		nucLst = poly[siteLst[i]]
		nucLst.sort()
		if len(nucLst) >= 2:
			real.append(siteLst[i])
			string = str(siteLst[i]) + '\t' + '\t'.join(nucLst) + '\n'
			out.write(string)
	contigLst = dic.keys()
	for contig in contigLst:
		seq = dic[contig]
		result = []
		for site in real:
			nuc = seq[site]
			result.append(str(site) + nuc)
		string = '>' + contig + '\n' + '\t'.join(result) + '\n'
		out2.write(string)
	out.close()
	out2.close()


from operator import itemgetter

# O(n) time, O(n) space
class Solution:

    @staticmethod
    def manacher(s: str, bogus='#'):
        s = bogus + bogus.join(list(s)) + bogus
        n = len(s)
        # radius of the longest palindrome with center at each index
        dp = [0 for _ in range(n)]
        radius, center = 0, 0
        while center < n:

            # find the longest palindrome for current center
            while (
                0 <= center - radius - 1
                and center + radius + 1 < n
                and s[center - radius - 1] == s[center + radius + 1]
            ):
                radius += 1
            dp[center] = radius

            # for other centers inside found palindrome
            old_center, old_radius = center, radius
            center, radius = center + 1, 0
            while center <= old_center + old_radius:
                # since it lies inside a palindrome it has a mirrored value
                mirrored_center = old_center - (center - old_center)
                max_mirrored_radius = old_center + old_radius - center

                if dp[mirrored_center] < max_mirrored_radius:
                    # if mirrored palindrome is entirely inside old palindrome
                    dp[center] = dp[mirrored_center]
                    center += 1
                elif dp[mirrored_center] > max_mirrored_radius:
                    # if mirrored palindrome is outside of old palindrome
                    # then new palindrome ends at the edge of old palindrome
                    # otherwise old palindrome radius would be bigger
                    dp[center] = max_mirrored_radius
                    center += 1
                else:
                    # dp[mirrored_center] == max_mirrored_radius

                    # since mirrored palindrome ended at old palindrome's edge
                    # new palindrome might be bigger
                    radius = max_mirrored_radius
                    # exit while loop
                    break
        center, radius = max(enumerate(dp), key=itemgetter(1))
        return s[center - radius:center + radius + 1].replace(bogus, "")

    def longestPalindrome(self, s: str) -> str:
        return self.manacher(s)

# O(n^2) time, O(1) space
class Solution1:
    @staticmethod
    def _expand(s: str, left: int, right: int) -> int:
        n = len(s)
        while (
            left >=0
            and right < n
            and s[left] == s[right]
        ):
            left -= 1
            right += 1
        return right - left - 1

    def longestPalindrome(self, s: str) -> str:
        left, right = 0, 0
        for i in range(len(s)):
            even_len = self._expand(s, i, i+1)
            odd_len = self._expand(s, i, i)
            new_len = max(even_len, odd_len)
            if new_len > right - left + 1:
                left = i - (new_len - 1) // 2
                right = i + new_len // 2

        return s[left:right+1]


from npstructures.arrayfunctions import diff
from npstructures.raggedarray import RaggedArray
import pytest
from tests.npbackend import np

@pytest.fixture
def array_list():
    return [[0, 1, 2], [2, 1], [1, 2, 3, 4], [3]]

@pytest.fixture
def array_list2():
    return [[0, 1, 2, 2], [2, 1, 1, 3], [1, 2, 3], [3, 3, 3]]

@pytest.fixture
def array_list3():
    return [[0, 1, 2, 2], [], [1, 2, 3], [3, 3, 3], []]

@pytest.mark.parametrize("n", [1, 2])
def test_diff_1(array_list, n):
    ra = RaggedArray(array_list)
    d = np.diff(ra, n, axis=-1)
    true = RaggedArray([np.diff(row, n) for row in array_list])
    assert d.equals(true)

def _test_convolve(array_list2):
    ra = RaggedArray(array_list2)
    convolved = np.convolve(ra)

def test_unique(array_list2):
    ra = RaggedArray(array_list2)
    unique = np.unique(ra, axis=-1)
    true = RaggedArray([np.unique(row) for row in array_list2])
    assert unique.equals(true)

def test_unique_with_counts(array_list2):
    ra = RaggedArray(array_list2)
    unique, counts = np.unique(ra, axis=-1, return_counts=True)
    tu, tc = (
        RaggedArray(a)
        for a in zip(*(np.unique(row, return_counts=True) for row in array_list2))
    )
    assert unique.equals(tu)
    assert counts.equals(tc)

def test_unique_2(array_list3):
    ra = RaggedArray(array_list3)
    unique = np.unique(ra, axis=-1)
    true = RaggedArray([np.unique(row) for row in array_list3])

    assert unique.equals(true)

def test_unique_bug():
    array_list3 = [[], [0, 0], [], [4], [0, 0]]
    ra = RaggedArray(array_list3)
    unique, counts = np.unique(ra, axis=-1, return_counts=True)
    true = RaggedArray([np.unique(row) for row in array_list3])
    true_counts = RaggedArray(
        [np.unique(row, return_counts=True)[1] for row in array_list3]
    )
    assert unique.equals(true)
    assert counts.equals(true_counts)


#!/usr/bin/env python

from modsim import *

def make_system(x, y, vx, vy, alpha):
    """
    """
    state = State(x, y, vx, vy)
    g = 9.8 * UNITS.meter / UNITS.second**2
    m = .175 * UNITS.kilogram # Mass of frisbee
    rho = 1.23  * UNITS.kilogram/UNITS.meter**3 # Density of air
    area = 0.0568 * UNITS.meter**2 # Surface area of frisbee
    CL0 = 0.1 # Lift coefficient alpha=0.
    CLA = 1.4 # Alpha-dependent lift coefficient
    # Drag coefficient when alpha = 0
    CDO = 0.08
    # Alpha-dependent drag coefficient
    CDA = 2.72
    # Constant associated with launch angle.
    alpha_constant = -4
    # Launch angle (in degrees).
    alpha = alpha

    # Now that we have lots of constants, we can calculate the actual coefficients.
    # Lift coefficient.
    CL = CL0 + CLA*alpha_constant*math.pi/180
    # Drag coefficient.
    CD = CD0 + CDA*((alpha - alpha_constant) * math.pi/180)**2
    # Return our system, because real object oriented programming is "soooo overrated"
    return System(state, g=g, m=m, rho=rho, area=area, CL=CL, CD=CD)

def slope_func(state, t, system):
    """
    """
    x, y, vx, vy = state
    unpack(system)

    # Make some useful vectors.
    a_grav = Vector(a, -g)
    v = Vector(vx, vy)
    # Make some change vectors.
    dvydt = (rho*(vy**2)*area*(CL/2)/(m + g))
    dvxdt = (rho*(vx**2)*area*CD)
    return dvxdt, dvydt

system = make_system(0, 0, 10, 0, 10)
run_odeint(system, slope-func)
plot(system.results)


def cal(i, j):
    if j == 0:
        return 1
    if i == j:
        return 1
    return cal(i - 1, j - 1) + cal(i - 1, j)

matrix = [0] * 100000

Ncount = int(input())
Ni, Nj = 0, 0
FloorB = 1
FloorE = 1
FloorLength = 1
count = 1
while True:
    if FloorB <= Ncount <= FloorE:
        Ni = count - 1
        Nj = Ncount - FloorB
        break
    else:
        FloorB += FloorLength
        FloorE += FloorLength + 1
        FloorLength += 1
        count += 1
print(cal(Ni, Nj))


import string
from gs1.Patterns import gtin_patterns, sscc_patterns, gln_patterns
import re

def ishex(s):
    if(s==None): return False
    if(len(s)==0): return False
    if(isbinary(s)):return False
    for c in s:
        if not c in string.hexdigits: return False
    return True

def isbinary(s):
    if(s==None): return False
    if(len(s)==0): return False
    for c in s:
        if c != "1" and c!="0": return False

    return True

def isGS1(val):
        '''
        Determines if the value passed in is a GS1 Encoding.

        Args:
            val (str) - A string that needs to be evaluated as a GS1 Encoding

        Returns:
            (bool) - True, if the val is a GS1 Encoding. False, if not.

        '''

        for pat in gtin_patterns:
            m = re.match(pat, val)
            if(m!=None):
                return True

        for pat in sscc_patterns:
            m = re.match(pat, val)
            if(m!=None):
                return True

        for pat in gln_patterns:
            m = re.match(pat, val)
            if(m!=None):
                return True

        return False

def hextobin(hexval):
        '''
        Takes a string representation of hex data with
        arbitrary length and converts to string representation
        of binary.  Includes padding 0s
        '''
        thelen = len(hexval)*4
        binval = bin(int(hexval, 16))[2:]
        while ((len(binval)) < thelen):
            binval = '0' + binval
        return binval


from typing import List, Dict
from CSP.CSP import Fix

class CountFix(Fix[tuple[int, int], int]):
    def __init__(self, variables: List[tuple[int, int]]):
        super().__init__(variables)

    def fix_domain(self, domains: Dict[tuple[int, int], List[int]], assignment: Dict[tuple[int, int], int]) -> bool:
        row_size = len(self.variables)
        items = [assignment[coordinates] for coordinates in self.variables if coordinates in assignment]
        if not (len(items) > row_size / 2):
            return True
        else:
            zero_counter = 0
            one_counter = 0
            for value in items:
                if value == 0:
                    zero_counter += 1
                else:
                    one_counter += 1
            if zero_counter == row_size / 2:
                for variable in self.variables:
                    if variable not in assignment:
                        domain = domains[variable].copy()
                        if 0 in domain:
                            if len(domain) == 1:
                                return False
                            domain.remove(0)
                        domains[variable] = domain
            elif one_counter == row_size / 2:
                for variable in self.variables:
                    if variable not in assignment:
                        domain = domains[variable].copy()
                        if 1 in domain:
                            if len(domain) == 1:
                                return False
                            domain.remove(1)
                        domains[variable] = domain
        return True