import sys
from PyQt5.QtWidgets import (QWidget, QToolTip,
    QPushButton, QComboBox, QLabel, QTextEdit, QGraphicsView, QGraphicsScene, QApplication)
from PyQt5.QtGui import (QFont,QImage, QPixmap)
from PyQt5 import (QtGui, QtCore)
from PyQt5.QtCore import QFile
from PyQt5 import QtPrintSupport
from PyQt5.Qt import QTextStream
from bitcoin import *
from PyQt5.Qt import (QPrinter, QPrintDialog)
from ecdsa import SigningKey, SECP256k1
import sha3
import qrcode

class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    #def extract_to_pdf(self):
     #   pass

    def handlePreview(self):
        f = QFile("Qrcodes.html")
        f.open(QFile.ReadOnly | QFile.Text)
        istream = QTextStream(f)
        self.textfield.setHtml(istream.readAll())
        f.close()
        dialog = QtPrintSupport.QPrintPreviewDialog()
        dialog.paintRequested.connect(self.textfield.print)#self.textEdit1.print)#editor.print_)
        dialog.exec_()

    def showQRCode(self):
        img = qrcode.make(self.priv)
        img2 = qrcode.make(self.address)
        img.save("Priv.png")
        img2.save("Addr.png")
        pixmap = QPixmap("Priv.png")
        pixmap2 = QPixmap("Addr.png")
        scpixmap = pixmap.scaled(self.graph1.size(), QtCore.Qt.KeepAspectRatio)
        scpixmap2 = pixmap2.scaled(self.graph2.size(), QtCore.Qt.KeepAspectRatio)
        self.graph1.setPixmap(scpixmap)
        self.graph2.setPixmap(scpixmap2)
        self.graph1.show()
        self.graph2.show()
        self.show()

    def getbtc(self):
        self.priv = random_key()
        pub = privtopub(self.priv)
        self.address = pubkey_to_address(pub)
        return self.priv, self.address

    def geteth(self):
        keccak = sha3.keccak_256()
        self.priv = SigningKey.generate(curve=SECP256k1)
        pub = self.priv.get_verifying_key().to_string()
        keccak.update(pub)
        self.address = keccak.hexdigest()[24:]
        return self.priv, self.address

    def click_generate(self):
        if self.comboBox1.currentText() == "SHA256":
            self.getbtc()
            self.textEdit1.setText(self.priv)
            self.textEdit2.setText(str(self.address))
            #self.ipriv = self.priv
            #self.iaddress = str(self.address)
        if self.comboBox1.currentText() == "Ethash":
            self.geteth()
            self.textEdit1.setText(self.priv.to_string().hex())
            self.textEdit2.setText('0x'+str(self.address.decode('UTF-8')))
            #self.ipriv = self.priv.to_string().hex()
            #self.iaddress = '0x'+str(self.address.decode('UTF-8'))
        self.showQRCode()

    def changeC(self):
        self.comboBox2.clear()
        if self.comboBox1.currentText() == "SHA256":
            self.comboBox2.addItem("BitCoin")
            self.comboBox2.addItem("Crowd")
        if self.comboBox1.currentText() == "Ethash":
            self.comboBox2.addItem("Eth")
            self.comboBox2.addItem("Etc")

    def initUI(self):

        QToolTip.setFont(QFont('SansSerif', 10))

        self.setToolTip('This is a QWidget widget')

        label1 = QLabel('Algorithm',self)
        label1.setGeometry(90, 5,80,20)

        self.comboBox1 = QComboBox(self)
        self.comboBox1.setGeometry(30,30,200, 27)
        self.comboBox1.setEditable(False)
        self.comboBox1.setObjectName("comboBox")
        self.comboBox1.addItem("SHA256")
        self.comboBox1.addItem("Ethash")
        self.comboBox1.activated.connect(self.changeC)

        label2 = QLabel('Coin', self)
        label2.setGeometry(105, 70, 68, 17)

        self.comboBox2 = QComboBox(self)
        self.comboBox2.move(30, 30)
        self.comboBox2.setGeometry(30, 90, 200, 27)
        self.comboBox2.setEditable(False)
        self.comboBox2.setObjectName("comboBox")
        self.comboBox2.addItem("BitCoin")
        self.comboBox2.addItem("CrownCoin")

        btn = QPushButton('Generate', self)
        btn.setToolTip('This is a QPushButton widget')
        btn.resize(btn.sizeHint())
        btn.setGeometry(250, 80, 120, 40)
        btn.clicked.connect(self.click_generate)

        label3 = QLabel('Private key', self)
        label3.setGeometry(270, 130, 100, 17)

        self.textEdit1 = QTextEdit("",self);
        self.textEdit1.setGeometry(10,150,620,50)

        label4 = QLabel('Address', self)
        label4.setGeometry(280, 210, 68, 17)

        self.textfield = QTextEdit("", self);
        self.textfield.setGeometry(10, 230, 620, 50)

        self.textEdit2 = QTextEdit("", self);
        self.textEdit2.setGeometry(10, 230, 620, 50)

        label5 = QLabel('Private key', self)
        label5.setGeometry(110, 285, 100, 17)

        label6 = QLabel('Address', self)
        label6.setGeometry(440, 285, 100, 17)

        self.graph1 = QLabel(self)
        self.graph1.setGeometry(10, 310, 300, 300)

        self.graph2 = QLabel(self)
        self.graph2.setGeometry(330, 310, 300, 300)

        btn2 = QPushButton('Print It', self)
        btn2.setToolTip('This is a QPushButton widget')
        btn2.resize(btn2.sizeHint())
        btn2.move(270, 620)
        btn2.clicked.connect(self.handlePreview)

        #self.btnclick(self)

        #self.create_cort()

        priv = ""
        address = ""
        ipriv = ""
        iaddress = ""

        font = QtGui.QFont()
        font.setPointSize(13)
        self.setFont(font)
        self.setGeometry(100, 100, 650, 650)
        self.setWindowTitle('Tooltips')
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


#
# File downloader
# Requires git://github.com/jgarzik/python-bitcoinrpc.git
#
# (c) 2013 Satoshi Nakamoto All Rights Reserved
#
# UNAUTHORIZED DUPLICATION AND/OR USAGE OF THIS PROGRAM IS PROHIBITED BY US AND INTERNATIONAL COPYRIGHT LAW

import sys
import os
import jsonrpc
import struct
from binascii import crc32, hexlify, unhexlify

if len(sys.argv) != 2:
    #print("""Usage: %s <txhash> """ % sys.argv[0], file=sys.stderr)
    #Set BTCRPCURL="http://User:Pass@localhost:8332"
    sys.exit()

proxy = jsonrpc.ServiceProxy(os.environ['BTCRPCURL'])

txid = sys.argv[1]

tx = proxy.getrawtransaction(txid,1)

data = b''
for txout in tx['vout'][0:-2]:
    for op in txout['scriptPubKey']['asm'].split(' '):
        if not op.startswith('OP_') and len(op) >= 40:
            data += unhexlify(op.encode('utf8'))

length = struct.unpack('<L', data[0:4])[0]
checksum = struct.unpack('<L', data[4:8])[0]
data = data[8:8+length]

if checksum != crc32(data):
    print('Checksum mismatch; expected %d but calculated %d' % (checksum, crc32(data)), file=sys.stderr)
    sys.exit()

sys.stdout.buffer.write(data)


import json
import hashlib

url = 'https://ru.wikipedia.org/wiki/'

class MyIter:

    def __init__(self, path):
        with open(path, encoding='utf-8') as f:
            self.countries_list = []
            file = json.load(f)
            for country in file:
                self.countries_list.append(country['name']['common'])

    def __iter__(self):
        return self

    def __next__(self):
        try:
            country = self.countries_list.pop(0)
            print(f"{country} : {url + country.replace(' ', '_')}")
        except IndexError:
            raise StopIteration
        return country

with open('new_countries_list.txt', 'w') as f:
    for country in MyIter('countries.json'):
        try:
            f.write(f"{country} : {url + country.replace(' ', '_')}\n")
        except UnicodeEncodeError:
            pass

def get_hash():
    with open('new_countries_list.txt', encoding='utf-8') as f:
        for country in f:
            yield hashlib.md5(country.encode('utf-8')).hexdigest()

if __name__ == '__main__':
    country = get_hash()
    for i in country:
        print(i)


import discord

"""
client = discord.Client()

@client.event
async def on_ready():
    print('Connected!')

client.run('ODg5MTk2NzY0MDk4MzYzNDMy.YUdvBQ.BNSIh4Yb61s_h6mMoVzTJVyF4OU')
"""

class MyRobot(discord.Client):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.target_message_id = 932659947110551662

    async def on_ready(self):
        print('Connected!')

    async def on_raw_reaction_add(self, payload):
        """
        Даёт роль по эмодзи, которую выберит пользователь
        """

        if payload.message_id != self.target_message_id:
            return

        guild = client.get_guild(payload.guild_id)

        if payload.emoji.name == '😎':
            role = discord.utils.get(guild.roles, name='Cool guys')
            await payload.member.add_roles(role)
        elif payload.emoji.name == '🧐':
            role = discord.utils.get(guild.roles, name='Clever guys')
            await payload.member.add_roles(role)
        elif payload.emoji.name == '😶':
            role = discord.utils.get(guild.roles, name='Normal guys')
            await payload.member.add_roles(role)

    async def on_raw_reaction_remove(self, payload):
        """
        Remove a role based on a reaction emoji
        """

        if payload.message_id != self.target_message_id:
            return

        guild = client.get_guild(payload.guild_id)
        member = guild.get_member(payload.user_id)

        if payload.emoji.name == '😎':
            role = discord.utils.get(guild.roles, name='Cool guys')
            await member.remove_roles(role)
        elif payload.emoji.name == '🧐':
            role = discord.utils.get(guild.roles, name='Clever guys')
            await member.remove_roles(role)
        elif payload.emoji.name == '😶':
            role = discord.utils.get(guild.roles, name='Normal guys')
            await member.remove_roles(role)

intents = discord.Intents.default()
intents.members = True

client = MyRobot(intents=intents)

client.run('TOKEN')


import bisect
import fnmatch
import os
from os.path import isdir, isfile, join, basename, splitext
from django.conf import settings

# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
try:
    from os import scandir, walk
except ImportError:
    from scandir import scandir, walk

from graphite.logger import log
from graphite.node import BranchNode, LeafNode
from graphite.readers import WhisperReader, GzippedWhisperReader, RRDReader
from graphite.util import find_escaped_pattern_fields
from graphite.finders.utils import BaseFinder
from graphite.tags.utils import TaggedSeries

from . import fs_to_metric, get_real_metric_path, match_entries, expand_braces

class StandardFinder(BaseFinder):
    DATASOURCE_DELIMITER = '::RRD_DATASOURCE::'

    def __init__(self, directories=None):
        directories = directories or settings.STANDARD_DIRS
        self.directories = directories

    def find_nodes(self, query):
        clean_pattern = query.pattern.replace('\\', '')

        # translate query pattern if it is tagged
        tagged = not query.pattern.startswith('_tagged.') and ';' in query.pattern
        if tagged:
            # tagged series are stored in whisper using encoded names, so to retrieve them we need to
            # encode the query pattern using the same scheme used in carbon when they are written.
            encoded_paths = [
                TaggedSeries.encode(query.pattern, sep=os.sep, hash_only=True),
                TaggedSeries.encode(query.pattern, sep=os.sep, hash_only=False),
            ]

        pattern_parts = clean_pattern.split('.')

        for root_dir in self.directories:
            if tagged:
                relative_paths = []
                for pattern in encoded_paths:
                    entries = [
                        pattern + '.wsp',
                        pattern + '.wsp.gz',
                        pattern + '.rrd',
                    ]
                    for entry in entries:
                        if isfile(join(root_dir, entry)):
                            relative_paths.append(entry)
            else:
                relative_paths = self._find_paths(root_dir, pattern_parts)

            for relative_path in relative_paths:
                if basename(relative_path).startswith('.'):
                    continue

                if self.DATASOURCE_DELIMITER in basename(relative_path):
                    (relative_path, datasource_pattern) = relative_path.rsplit(
                        self.DATASOURCE_DELIMITER, 1)
                else:
                    datasource_pattern = None

                absolute_path = join(root_dir, relative_path)

                # if we're finding by tag, return the proper metric path
                if tagged:
                    metric_path = query.pattern
                    real_metric_path = query.pattern
                else:
                    metric_path = fs_to_metric(relative_path)
                    real_metric_path = get_real_metric_path(absolute_path, metric_path)
                    metric_path_parts = metric_path.split('.')
                    for field_index in find_escaped_pattern_fields(query.pattern):
                        metric_path_parts[field_index] = pattern_parts[field_index].replace('\\', '')
                    metric_path = '.'.join(metric_path_parts)

                # Now we construct and yield an appropriate Node object
                if isdir(absolute_path):
                    yield BranchNode(metric_path)

                elif absolute_path.endswith('.wsp') and WhisperReader.supported:
                    reader = WhisperReader(absolute_path, real_metric_path)
                    yield LeafNode(metric_path, reader)

                elif absolute_path.endswith('.wsp.gz') and GzippedWhisperReader.supported:
                    reader = GzippedWhisperReader(absolute_path, real_metric_path)
                    yield LeafNode(metric_path, reader)

                elif absolute_path.endswith('.rrd') and RRDReader.supported:
                    if datasource_pattern is None:
                        yield BranchNode(metric_path)

                    else:
                        for datasource_name in RRDReader.get_datasources(absolute_path):
                            if match_entries([datasource_name], datasource_pattern):
                                reader = RRDReader(absolute_path, datasource_name)
                                yield LeafNode(metric_path + "." + datasource_name, reader)

    def _find_paths(self, current_dir, patterns):
        """Recursively generates absolute paths whose components underneath current_dir
        match the corresponding pattern in patterns"""
        raw_pattern = patterns[0]
        patterns = patterns[1:]

        for pattern in expand_braces(raw_pattern):
            has_wildcard = pattern.find('[') > -1 or pattern.find('*') > -1 or pattern.find('?') > -1

            matching_subdirs = []
            files = []
            if has_wildcard:  # this avoids os.listdir() for performance
                subdirs = []
                try:
                    for x in scandir(current_dir):
                        if x.is_file():
                            files.append(x.name)
                        if x.is_dir():
                            subdirs.append(x.name)
                except OSError as e:
                    log.exception(e)

                if pattern == "**":
                    matching_subdirs = map(
                      lambda item: item[0][len(current_dir) + 1:],
                      walk(current_dir)
                    )

                    # if this is a terminal globstar, add a pattern for all files in subdirs
                    if not patterns:
                        patterns = ["*"]
                else:
                    matching_subdirs = match_entries(subdirs, pattern)
            elif isdir(join(current_dir, pattern)):
                matching_subdirs.append(pattern)

            # the last pattern may apply to RRD data sources
            if len(patterns) == 1 and RRDReader.supported:
                if not has_wildcard:
                    entries = [
                      pattern + ".rrd",
                    ]
                    rrd_files = [entry for entry in entries if isfile(join(current_dir, entry))]
                else:
                    rrd_files = match_entries(files, pattern + ".rrd")

                if rrd_files:  # let's assume it does
                    datasource_pattern = patterns[0]

                    for rrd_file in rrd_files:
                        yield rrd_file + self.DATASOURCE_DELIMITER + datasource_pattern

            if patterns:  # we've still got more directories to traverse
                for subdir in matching_subdirs:
                    absolute_path = join(current_dir, subdir)
                    for match in self._find_paths(absolute_path, patterns):
                        yield join(subdir, match)

            else:  # we've got the last pattern
                if not has_wildcard:
                    entries = [
                        pattern + '.wsp',
                        pattern + '.wsp.gz',
                        pattern + '.rrd',
                    ]
                    matching_files = [entry for entry in entries if isfile(join(current_dir, entry))]
                else:
                    matching_files = match_entries(files, pattern + '.*')

                for match in matching_files + matching_subdirs:
                    yield match

    def get_index(self, requestContext):
        matches = []

        for root, _, files in walk(settings.WHISPER_DIR):
            root = root.replace(settings.WHISPER_DIR, '')
            for base_name in files:
                if fnmatch.fnmatch(base_name, '*.wsp'):
                    match = join(root, base_name).replace('.wsp', '').replace('/', '.').lstrip('.')
                    bisect.insort_left(matches, match)

        # unlike 0.9.x, we're going to use os.walk with followlinks
        # since we require Python 2.7 and newer that supports it
        if RRDReader.supported:
            for root, _, files in walk(settings.RRD_DIR, followlinks=True):
                root = root.replace(settings.RRD_DIR, '')
                for base_name in files:
                    if fnmatch.fnmatch(base_name, '*.rrd'):
                        absolute_path = join(settings.RRD_DIR, root, base_name)
                        base_name = splitext(base_name)[0]
                        metric_path = join(root, base_name)
                        rrd = RRDReader(absolute_path, metric_path)
                        for datasource_name in rrd.get_datasources(absolute_path):
                            match = join(metric_path, datasource_name).replace('.rrd', '').replace('/', '.').lstrip('.')
                            if match not in matches:
                                bisect.insort_left(matches, match)

        return matches


import numpy as np
import matplotlib.pyplot as plt

t1 = np.arange(0, 8, 0.05)
t2 = np.arange(10, 14, 0.05)
t = np.concatenate([t1, t2])
c = [np.cos(i) for i in t]

fig = plt.figure()
ax = fig.gca()
ax.plot(t, c)
ax.set_title('Undesirable joining line')

t1 = np.arange(0, 8, 0.05)
t2 = np.arange(10, 14, 0.05)
c1 = [np.cos(i) for i in t1]
c2 = [np.cos(i) for i in t2]
t = np.concatenate([t1, t1[-1:], t2])
c = np.concatenate([c1, [None,], c2])

fig = plt.figure()
ax = fig.gca()
ax.plot(t, c)
ax.set_title('Ok if you don\'t pan the plot')

fig = plt.figure()
ax = fig.gca()
ax.plot(t, c)
ax.axis([-1, 12, -0.5, 1.25])
ax.set_title('Strange jumping line')

plt.show()


import pandas as pd
from sgrt_devels.extr_TS import extr_SIG0_LIA_ts_GEE_VV as extrts
from matplotlib import pyplot as plt
import datetime as dt
from pytesmo.time_series import anomaly

s1ts = extrts(35.35, 0.673, 2000, maskwinter=False)
#s1ts = extrts(36.0189, 0.425, 50, maskwinter=False)
s1pd = pd.Series(s1ts['130'][1]['sig0'], index=s1ts['130'][0])
s1pd.sort_index

# scaling
bcksct_min = s1pd.min()
bcksct_max = s1pd.max()
#bcksct_min = -14.8
#bcksct_max = -8.12
bcksct_rng = bcksct_max - bcksct_min

s1pd_scaled = (s1pd - bcksct_min) / bcksct_rng
s1pd_scaled = (s1pd_scaled * 35.) + 5.
# s1pd_scaled = (s1pd - bcksct_min) / bcksct_rng
# s1pd_scaled = (s1pd_scaled * 15.) + 3.
s1pd_scaled = s1pd_scaled.resample('D').mean()
s1pd_scaled.interpolate(inplace=True)

# anomalies
#bcksct_mean = s1pd_scaled.mean()
#s1pd_anom = (s1pd_scaled / bcksct_mean) - 1
climatology = anomaly.calc_climatology(s1pd_scaled, moving_avg_orig=5, moving_avg_clim=30)
s1pd_anom = anomaly.calc_anomaly(s1pd_scaled, climatology=climatology)

plt.figure(figsize=(6.3,3.7))
s1pd_scaled.plot()
plt.xlabel('Date', fontsize=10)
plt.ylabel('SMC [m3/m-3]')
plt.ylim((0,50))
plt.show()
plt.savefig('/mnt/SAT/Workspaces/GrF/02_Documents/ISRSE2017/s1ts.png', dpi=300)
plt.close()

plt.figure(figsize=(6.3,3.7))
s1pd_anom.plot()
timex = pd.date_range('30/9/2014', '30/4/2017', freq='D')
zerolist = pd.Series([0]*len(timex), index=timex)
zerolist.plot(linestyle='--', color='r')
#plt.plot(timex, [0]*len(timex), linestyle='--', color='r', marker='*')
plt.xlabel('Date', fontsize=10)
plt.ylabel('SMC anomaly')
plt.show()
plt.savefig('/mnt/SAT/Workspaces/GrF/02_Documents/ISRSE2017/s1ts_anomaly.png', dpi=300)
plt.close()


from django.urls import path
from pages import views

urlpatterns = [
    path('', views.index, name='index'),
    path('about', views.about, name='about'),
    path('services', views.service, name='service'),
    path('contact', views.contact, name='contact'),
    path('add', views.add, name='add'),
    path('edit/<int:id>', views.edit, name='edit'),
    path('blog/<int:id>/', views.blog, name='blog'),
    path('remove/<int:id>', views.remove, name='remove'),
]


from src.main.Models.Base import Base
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Table
from sqlalchemy.orm import relationship, sessionmaker
from .Persona import libros_personas

libros_autores = Table('libros_autores', Base.metadata,
                       Column('libro_id', Integer, ForeignKey('Libro.id')),
                       Column('autor_id', Integer, ForeignKey('Autor.id'))
                       )

class Libro(Base):
    __tablename__ = 'Libro'
    titulo = Column(String)
    fecha = Column(Integer)
    genero = Column(String)
    paginas = Column(Integer)

    autores = relationship('Autor', secondary=libros_autores, back_populates='Libro')
    personas = relationship('Persona', secondary=libros_personas, back_populates='Libro')


import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import seaborn as sns
import numpy as np

# ==================================================
def init_plot(fig_size=None, font_scale=None):
    """
    initialize matplot.

    Args:
        fig_size (tuple): size of figure, None=(10,8).
        font_scale (float): font scale, None=1.1

    Returns: tuple.
        - pyplot: matplot.pyplot.
        - figure: matplot.pyplot.figure.
    """
    if fig_size is None:
        fig_size = (10, 8)
    if font_scale is None:
        font_scale = 1.4

    sns.set("notebook", "whitegrid", "dark", font_scale=font_scale, rc={"lines.linewidth": 1, "grid.linestyle": "--"})
    figure = plt.figure(figsize=fig_size)

    return plt, figure

# ==================================================
def plot_colormap_line(x, y, c=1.0, cmap="coolwarm", c_range=(-1, 1), width=2.0, opacity=1.0, ax=None):
    """
    plot lines with colormap.

    Args:
        x (list or ndarray): x points.
        y (list or ndarray): (a set of) y points in each column.
        c (float or list or ndarray, optional): (a set of) values for colormap in each column.
        cmap (str, optional): colormap.
        c_range (tuple, optional): range of colormap value.
        width (float, optional): line width.
        opacity (float, optional): opacity.
        ax (Axes, optional): plt axes.

    Returns:
        list: list of LineCollection.
    """
    x = np.array(x)
    c = np.array(c, ndmin=2)
    y = np.array(y, ndmin=2)

    if y.shape[0] == 1:
        y = y.T
    if c.shape[0] == 1:
        c = c.T
    if c.shape != y.shape:
        c = np.full(y.shape, c)

    lc = []
    for i in range(y.shape[1]):
        points = np.array([x, y[:, i]]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)

        lc0 = LineCollection(segments, array=c[:, i], cmap=cmap, linewidth=width, alpha=opacity, norm=plt.Normalize(*c_range))

        if ax is None:
            ax = plt.gca()
        ax.add_collection(lc0)
        lc.append(lc0)

    return lc

# ==================================================
def plot_dispersion(
    k_linear,
    Ek,
    k_name=None,
    phonon=False,
    color="forestgreen",
    width=1.3,
    E_range=None,
    weight=None,
    w_range=None,
    title=None,
    xlabel=None,
    ylabel=None,
    ax=None,
):
    """
    plot dispersion.

    Args:
        k_linear (list): k-linear point.
        Ek (ndarray): eigenvalues, [k_index, eigenstate_index].
        k_name (dict, optional): {position: k point name}.
        phonon (bool, optional): phonon ?
        color (str, optional): color, if colormap name is given, plot with weight and colormap.
        width (float, optional): line width.
        E_range (tuple, optional): enery range.
        weight (ndarray): weight of dispersion, [k_index, eigenstate_index].
        w_range (tuple, optional): weight range.
        title (str, optional): plot title.
        xlabel (str, optional): x label.
        ylabel (str, optional): y label.
        ax (Axes, optional): plt Axes.

    Returns:
        list: list of LineCollection.

    Notes:
        - k-point name, "G" and "Γ" (\u0393) are replaced by "$\Gamma$".
    """
    if k_name is None:
        k_name = {}
    if ylabel is None:
        ylabel = r"$\omega_n(k)$" if phonon else r"$E_n(k)$"
    if title is None:
        title = "dispersion relation"
    if E_range is None:
        E_range = (0.0, Ek.max() + 0.1) if phonon else (Ek.min() - 0.1, Ek.max() + 0.1)
    if w_range is None:
        w_range = (-1, 1)

    k_label = [i.replace("G", r"$\Gamma$").replace("\u0393", r"$\Gamma$") for i in k_name.values()]

    ax.title.set_fontsize(18)
    if xlabel is None:
        ax.set(title=title, xlabel="", ylabel=ylabel)
    else:
        ax.set(title=title, xlabel=xlabel, ylabel=ylabel)

    if len(k_name) > 0:
        ax.set_xticks(list(k_name.keys()))
        ax.set_xticklabels(k_label)
        for i in k_name.keys():
            ax.plot([i, i], E_range, color="gray", linewidth=0.7)
    else:
        ax.grid(which="major", axis="x", color="gray", linewidth=0.7)
    ax.grid(which="major", axis="y", color="gray", linewidth=0.7)

    ax.set_xlim(k_linear[0], k_linear[-1])
    ax.set_ylim(*E_range)

    if color in mpl.colors.cnames.keys() or weight is None:
        cl = ax.plot(k_linear, Ek, color=color, lw=width)
    else:
        cl = plot_colormap_line(k_linear, Ek, weight, c_range=w_range, cmap=color, width=width, ax=ax)

    return cl


# app.py
# Li Yicheng t-yicli@microsoft.com

import feature_extract
import pitch_on_off
import user_input
import librosa
import pitch_extract
import utilities
import peak_break

print('Collecting modules Successfully')
audio_file,mode = user_input.cmd_input()
audio, sr = librosa.load(audio_file, sr = 48000, mono = True)

break_points,hop = peak_break.detect_audio_break(audio,sr=48000,frame_size = 48000, hop_size = 8000 ,threshold = 2)
# print(break_points)
audio_pieces = []
if len(break_points) > 0:
    curr = 0

    for break_point in break_points:
        audio_piece = audio[curr * hop : break_point*hop]
        curr = break_point
        audio_pieces.append(audio_piece)
    audio_piece_last = audio[curr*hop:]
    audio_pieces.append(audio_piece_last)
else:
    audio_pieces.append(audio)

audio_notes = []
i = 0
hop = 8000
hop_length = 128
for audio_piece in audio_pieces:
    audio = audio_piece
    s_crop = feature_extract.freq_feature(audio, sr, freq_min=56, freq_max=1760,
                                      win_length=1024, hop_length=128,
                                      window_shape='hann', n_fft=8192)
    sample_amount = s_crop.shape[1]
    seqs = feature_extract.sep_audio(audio, sample_amount,hop_length=128,win_length=1024)
    energy = feature_extract.compute_energy(seqs)
    zeros_cros = feature_extract.compute_zerocross(seqs)
    auto_corr = feature_extract.compute_autocorr(seqs)
    mean_pks,pks_locs = feature_extract.mean_best2peak(s_crop)
    dataset = feature_extract.gen_dataSet(energy=energy,zeros_cros=zeros_cros,
                                          auto_corr=auto_corr,mean_pks=mean_pks,
                                          sample_amount=sample_amount)
    pitch_on_array, pitch_off_array = pitch_on_off.gen_pitch_on_off(dataset=dataset,energy=energy,
                                                                    small_dur=15,large_dur=215,
                                                                    window_size=80,hop_size=10)
    notes = pitch_extract.pitch_extract(pks_locs,pitch_on_array,pitch_off_array,
                                        suppress_alpha=2.5,n_fft=8192,sr=48000,freq_min=55,
                                        outlier = 8.5, detect_osc = 40.0, jump = 7.0)
    for note in notes:
        if i>0:
            start = break_points[i-1] * hop //hop_length + note[0]
            end = break_points[i-1]*hop//hop_length + note[1]
            audio_notes.append((start,end,note[2]))
        else:
            audio_notes.append(note)
    i+=1

if(mode == 'wav2wav'):
    utilities.genStereo(audio_notes,audio_file,hop_length=128,sr = 48000,crossfade=25,
                        silencefade=15)
elif (mode == 'wav2midi'):
    utilities.genMidi(audio_notes,audio_file,initial_tempo=80,program=42)
else:
    utilities.genStereo(audio_notes,audio_file,hop_length=128,sr = 48000,crossfade=25,
                        silencefade=15)
    utilities.genMidi(audio_notes, audio_file, initial_tempo=80, program=42)


"""
Our N-Body simulator, using odeint
"""
from dataclasses import dataclass

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

from plot import animate_outcome3d

# Specify the mass, location, and velocity of bodies using a dictionary
# km, kg, s
sun = {
    "m": 1.9884754159566474e30,
    "p": (130.12022433639504, 493.88921553478576, 1.9894885155190423),
    "v": (-9.08252417469984e-05, 2.763470714263038e-05, 9.333023252795563e-08),
}
earth = {
    "m": 6.045825576341311e24,
    "p": (-52532397.16477036, -142290670.7988091, 6714.9380375893525),
    "v": (27.459556210605758, -10.428715463342813, 0.0004283693350210454),
}
mars = {
    "m": 6.417120534329241e23,
    "p": (91724696.20692892, -189839018.6923888, -6228099.232650615),
    "v": (22.733051422552098, 12.621328917003236, -0.29323856116219776),
}

init = [sun, earth, mars]
G = 6.67408e-20

# State manipulation code, for getting info from our state vector

def get_n_bodies(s):
    return s.shape[-1] // 7

def get_m(s, i):
    return s[i]

def get_x(s, i):
    num_bodies = get_n_bodies(s)
    return s[num_bodies + i]

def get_y(s, i):
    num_bodies = get_n_bodies(s)
    return s[2 * num_bodies + i]

def get_z(s, i):
    num_bodies = get_n_bodies(s)
    return s[3 * num_bodies + i]

def get_vx(s, i):
    num_bodies = get_n_bodies(s)
    return s[4 * num_bodies + i]

def get_vy(s, i):
    num_bodies = get_n_bodies(s)
    return s[5 * num_bodies + i]

def get_vz(s, i):
    num_bodies = get_n_bodies(s)
    return s[6 * num_bodies + i]

def get_position(s, i):

    x = get_x(s, i)
    y = get_y(s, i)
    z = get_z(s, i)

    return np.array([x, y, z])

def get_r(s, i, j):
    p1 = get_position(s, i)
    p2 = get_position(s, j)
    r = np.linalg.norm(p2 - p1)
    return r

# Compute the acceleration in different directions

def x_accel(s, i, j):
    x1 = get_x(s, i)
    x2 = get_x(s, j)
    m2 = get_m(s, j)

    r = get_r(s, i, j)
    return m2 * (x2 - x1) / (r) ** (3)

def y_accel(s, i, j):
    y1 = get_y(s, i)
    y2 = get_y(s, j)
    m2 = get_m(s, j)

    r = get_r(s, i, j)
    return m2 * (y2 - y1) / (r) ** (3)

def z_accel(s, i, j):
    z1 = get_z(s, i)
    z2 = get_z(s, j)
    m2 = get_m(s, j)

    r = get_r(s, i, j)
    return m2 * (z2 - z1) / (r) ** (3)

# Compute the forces in different directions

def xpp(s, i, G=G):
    num_bodies = get_n_bodies(s)
    other_indices = list(range(num_bodies))
    other_indices.remove(i)
    return G * sum([x_accel(s, i, j) for j in other_indices])

def ypp(s, i, G=G):
    num_bodies = get_n_bodies(s)
    other_indices = list(range(num_bodies))
    other_indices.remove(i)
    return G * sum([y_accel(s, i, j) for j in other_indices])

def zpp(s, i, G=G):
    num_bodies = get_n_bodies(s)
    other_indices = list(range(num_bodies))
    other_indices.remove(i)
    return G * sum([z_accel(s, i, j) for j in other_indices])

# Our overall function, F

def F(s, t, G=G):
    num_bodies = get_n_bodies(s)
    return np.concatenate(
        (
            np.zeros_like(s[4 * num_bodies : 5 * num_bodies]),
            s[4 * num_bodies : 5 * num_bodies],
            s[5 * num_bodies : 6 * num_bodies],
            s[6 * num_bodies : 7 * num_bodies],
            [xpp(s, i, G=G) for i in range(num_bodies)],
            [ypp(s, i, G=G) for i in range(num_bodies)],
            [zpp(s, i, G=G) for i in range(num_bodies)],
        )
    )

def to_positions(solution):
    num_bodies = get_n_bodies(solution)
    outcome = [
        np.stack(
            [
                solution[:, num_bodies + i],
                solution[:, 2 * num_bodies + i],
                solution[:, 3 * num_bodies + i],
            ],
            axis=1,
        )
        for i in range(num_bodies)
    ]
    return np.stack(outcome)

def planet_dict_to_vector(init):
    m = [o["m"] for o in init]
    x0 = [o["p"][0] for o in init]
    y0 = [o["p"][1] for o in init]
    z0 = [o["p"][2] for o in init]
    vx0 = [o["v"][0] for o in init]
    vy0 = [o["v"][1] for o in init]
    vz0 = [o["v"][2] for o in init]

    return np.concatenate((m, x0, y0, z0, vx0, vy0, vz0))

def vector_to_planet_dict(vec):
    num_bodies = get_n_bodies(vec)

    planets = []
    for i in range(num_bodies):
        planets.append(
            dict(
                m=get_m(vec, i),
                p=(get_x(vec, i), get_y(vec, i), get_z(vec, i)),
                v=(get_vx(vec, i), get_vy(vec, i), get_vz(vec, i)),
            )
        )

    return planets

def integrate(init, t_max, N, G=G):
    """
    Our main function, given a dictionary of the planets attributes, simulate
    forward in time to t_max using N steps. This will then return a dictionary
    specifing the final locations, and the trajectories as a numpy array.
    """
    t = np.linspace(0, t_max, N)
    s0 = planet_dict_to_vector(init)
    solution = odeint(lambda s, t: F(s, t, G=G), s0, t)
    final = vector_to_planet_dict(solution[-1])
    return final, to_positions(solution)

if __name__ == "__main__":
    outcome, pos = integrate(init, 3600 * 24 * 365 * 2, 100)
    anim = animate_outcome3d(pos, ["yellow", "blue", "red"], [30, 20, 15])
    plt.show()


from django.urls import path
from .views import fdetemps, choix, listeassistants, assistant_edit, bilanparcontrat, listecontrats, \
    bilanparprojet, listeprojets, projet_new, mise_a_jour_db, correction_pe, calcule_couts

urlpatterns = [
    path('fdt/', fdetemps, name='do_fdt'),
    path('choix/', choix, name='choix'),
    path('liste/', listeassistants, name='listeassistants'),
    path('assistant/<int:pk>/', assistant_edit, name='assistant_edit'),
    path('bcontrat/<int:cid>/', bilanparcontrat, name='bilanparcontrat'),
    path('bprojet/<int:pid>/', bilanparprojet, name='bilanparprojet'),
    path('listecontrats/', listecontrats, name='listecontrats'),
    path('projet/new/', projet_new, name='projet_new'),
    path('projet/', listeprojets, name='listeprojets'),
    path('correction/<int:pk>/', mise_a_jour_db, name='mise_a_jour_db'),
    path('correctionPE/<int:pk>/', correction_pe, name='correction_pe'),
    path('calculecouts/', calcule_couts, name='calcule_couts'),
]

#url(r'^new/$', creerdossier, name='creerdossier'),


import random

from h5py import File
import numpy as np

class HDF5Loader(File):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__fields = None
        self.__index = 0

    def _assert_valid(self, keys):
        # assert keys is not empty
        assert len(keys) > 0
        if len(keys) == 1:
            return
        # assert the datasets have the same amount of samples
        length = self[keys[0]].shape[0]
        for key in keys[1:]:
            assert self[key].shape[0] == length

    def set_dataset(self, *keys, shuffle=False, infinite=False):
        r""" Set the default dataset.
        key (str): the dataset path in the hdf5 file
        shuffle (bool): whether to shuffle the dataset
        infinite (bool): whether to reset the dataset when the iteration
            reaches the end of the dataset

        return: None
        """
        self._assert_valid(keys)
        self.__fields = keys
        self.__indices = list(range(self[keys[0]].shape[0]))
        self.__shuffle = shuffle
        self.__infinite = infinite
        if shuffle:
            random.shuffle(self.__indices)

    def _check_field(self):
        if self.__fields is None:
            raise AttributeError("Set the dataset to iter from first by "
                                 "calling self.set_dataset() method.")

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

    def _get_value(self):
        value = [self[field][self.__indices[self.__index]] for
                 field in self.__fields]
        self.__index += 1
        return value

    def __next__(self):
        self._check_field()
        try:
            value = self._get_value()
        except IndexError:
            if self.__infinite:
                self.__index = 0
                if self.__shuffle:
                    random.shuffle(self.__indices)
                value = self._get_value()
            else:
                raise StopIteration
        return value

    def set_batch_size(self, batch_size):
        self.__batch_size = batch_size

    @property
    def steps(self):
        try:
            self._check_field()
            return int(len(self.__indices) // self.__batch_size)
        except AttributeError as e:
            raise e("Set the batch size with "
                    "self.set_batch_size(batch_size) or call "
                    "self.batch_loader(batch_size) before getting the steps.")

    def batch_loader(self, batch_size=None):
        r""" Mini batch generator. The batch_size argument will overwrite the
        batch size set by the set_batch_size() method. Leave it as default if
        you do not want to change the batch size.
        batch_size (int): mini batch size.

        yield (list): list with mini batches data
        """
        self._check_field()
        if batch_size is not None:
            self.__batch_size = batch_size
        batches = list()
        for field in self.__fields:
            try:
                batch = np.empty((self.__batch_size, self[field].shape[1]),
                                 dtype=self[field].dtype)
            # the dataset does not have dimension value for the features
            except IndexError:
                batch = np.empty((self.__batch_size, 1),
                                 dtype=self[field].dtype)
            batches.append(batch)
        while True:
            index = 0
            while index < self.__batch_size:
                data = next(self)
                for i, batch in enumerate(batches):
                    batch[index] = data[i]
                index += 1
            yield batches


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

# pylint: disable=c0111, c0103, r1705

import pprint
import html as stdlib_html

from types import FunctionType, BuiltinFunctionType, BuiltinMethodType
from collections.abc import Iterator

########## styles in html output
default_font_size='small'
default_header_font_size='medium'

def font_style(font_size):
    return f'font-family:monospace;font-size:{font_size};'

# iteration 1 was using this
#ok_style = 'background-color:#66CC66;'
#ko_style = 'background-color:#CC3300;color:#e8e8e8;'
ok_style = 'background-color:#d6e9ce;'
ko_style = 'background-color:#efd6d6;'

center_text_style = 'text-align: center;'
left_text_style = 'text-align: left;'
right_text_style = 'text-align: right;'

top_border_style = "border-top:2px double black; "
top_border_style2 = "border-top:1px solid gray; "
bottom_border_style = "border-bottom:2px solid gray;"
bottom_border_style2 = "border-bottom:1px solid gray;"
bottom_border_style3 = "border-bottom:1px dotted gray;"
left_border_thick_style = "border-left:3px solid gray;"
left_border_thin_style = "border-left:1px solid gray;"
table_border_style = "margin: 10px;"

DEBUG = False
########## helpers for rendering / truncating
def html_escape(s):
    return s

def truncate_str(message, max_size):
    # width = 0 or less means do not truncate
    if max_size <= 0:
        return message
    truncated = message if len(message) <= max_size \
        else message[:max_size-3]+'...'
    return html_escape(truncated)

# display functions as their name
def custom_repr(x):
    if isinstance(x, (type, FunctionType, BuiltinFunctionType, BuiltinMethodType)):
        return x.__name__
    elif isinstance(x, set):
        return "{" + commas(x) + "}"
    else:
        return repr(x)

def commas(iterable):
    if isinstance(iterable, dict):
        return ", ".join(f"{k}={custom_repr(v)}" for k, v in iterable.items())
    elif isinstance(iterable, str):
        return str
    else:
        return ", ".join([custom_repr(x) for x in iterable])

def truncate_value(value, width):
    # this is the case where we may have a set and prefer to show it with {}
    if isinstance(value, set):
        message = "{" + commas(value)
        return truncate_str(message, width-1) + "}"
    else:
        return truncate_str(repr(value), width)

########## rendering usual objects (not Args or ArgsKeywords)
class CellObj:
    def __init__(self, torender):
        self.torender = torender
    def __repr__(self):
        return f"[CellObj {self.torender}]"
    def layout_truncate(self, width):
        return truncate_value(self.torender, width)
    def layout_pprint(self, width):
        # print(f"using layout pprint on cellobj, self.torender={self.torender}")
        if isinstance(self.torender, Iterator):
            self.torender = list(self.torender)
        indent = 2
        html = "
\n"
        width = width if width > 0 else 80
        html += pprint.pformat(self.torender, indent=indent, width=width)
        html += "
"
        return html
    layout_islice = layout_pprint

    def layout_text(self, width, show_backslash_n=False):
        """
        torender is expected to be a plain string on multiple lines
        WARNING: with this layout, width is expected to be a font size
        """
        style = f"font-size:{width};"
        html = f"
"
        contents = str(self.torender)
        if not show_backslash_n:
            html += contents
        else:
            html += contents.replace("\n", "\\n\n")
        html += "
"
        return html

    def layout_text_backslash_n(self, width):
        """
        Same as layout_text but with \n at the end of line that have it
        """
        return self.layout_text(width, show_backslash_n=True)

    def layout_raw(self, width):
        style = f"font-size:{width};"
        html = f"
"
        html += stdlib_html.escape(str(self.torender))
        html += "
"
        return html

class CellLegend:
    def __init__(self, legend):
        self.legend = legend
    def __repr__(self):
        return f"[CellLegend {self.legend}]"
    def layout_truncate(self, width):
        return truncate_str(self.legend, width)
    layout_pprint = layout_truncate

########## html tags
# create a start tag with arbitrary attributes
# tag_keywords('table', style='text-align:center') to get
#

# special case for 'class' that is a python keyword
# use hclass instead
# use e.g. tag_keywords('tr', hclass='error') to get
#

def tag_keywords(tag, **html_tags):
    html = f"<{tag}"
    for k, v in html_tags.items():
        # ignore stuff that is defined by default as None
        if v is None:
            continue
        html += f" {k if k != 'hclass' else 'class'}='{v}'"
    html += ">"
    return html

# end_tag('table') ->

def end_tag(tag):
    return f"</{tag}>"

##############################
class Table:
    def __init__(self, **html_tags):
        self.html_tags = html_tags
    def header(self):
        return tag_keywords("table", **self.html_tags)
    def footer(self):                                   # pylint: disable=r0201
        return end_tag("table")

class TableRow:                                         # pylint: disable=r0903
    def __init__(self, cells, **html_tags):
        self.cells = cells
        self.html_tags = html_tags

    def __repr__(self):
        return f"[TableRow with {len(self.cells)} cells]"

    def html(self):
        html = tag_keywords("tr", **self.html_tags)
        for cell in self.cells:
            html += cell.html()
        html += end_tag("tr")
        return html

class TableCell:
    """
    Something that will produce a table cell, based on
    (*) a content, that is expected to have the right
        layout method, like e.g. layout_truncate
        since truncate is our default layout
        this typically applies to Args-like objects
        otherwise, a CellObj object is created instead
    (*) a width, 0 meaning no truncation/formatting occurs
    (*) a layout
    (*) a tag, default is 'td' but can be 'th'
    (*) additional html tags can be set using **html_tags
    """
    def __init__(self, content, width=0, tag='td', layout='truncate', **html_tags):
        self.content = content
        self.width = width
        self.tag = tag
        self.layout = layout
        self.html_tags = html_tags

    def __repr__(self):
        return f"[TableCell {self.content}]"

    # if the 'content' object has a 'render' method, then use it
    # otherwise provide a few basic methods for that
    def html(self):
        html = tag_keywords(self.tag, **self.html_tags)
        layout = self.computed_layout()
        symbol = f'layout_{layout}'
        try:
            if hasattr(self.content, symbol):
                if DEBUG:
                    print(f"calling method {symbol} on a {type(self.content).__name__}")
                method = getattr(self.content, symbol)
                cell_html = method(self.width)
                html += "
" + cell_html + "
"
            else:
                proxy = CellObj(self.content)
                method = getattr(proxy, symbol)
                html += method(self.width)
        except:                                         # pylint: disable=w0702
            import traceback
            traceback.print_exc()
            html += f"TableCell.html({self.content})"
        html += end_tag(self.tag)
        return html

    # several layouts for rendering in a table
    # the default is for when this is left unspecified
    # or means something we cannot do
    default_layout = 'truncate'
    supported_layouts = [
        'truncate', 'pprint',
        'void', 'text', 'text_backslash_n', 'raw',
        'islice',
    ]

    def computed_layout(self):
        """
        the layout to use
        the one specified in self.content.layout, if it exists
        takes precedence over self.layout
        """
        # the value specified in the instance wins if set
        # as it is more specific
        # second use the one provided at the exercise level
        # last resort is this default
        computed_layout = None
        if hasattr(self.content, 'layout'):
            computed_layout = self.content.layout
        if computed_layout is None and self.layout:
            computed_layout = self.layout
        if computed_layout is None:
            computed_layout = self.default_layout
        if computed_layout not in self.supported_layouts:
            print(f"WARNING: unsupported layout {computed_layout}"
                  f" - resorting to {self.default_layout}")
            computed_layout = self.default_layout
        return computed_layout

def test_rendering():
    from collections import defaultdict
    test_inputs = [
        ("abc\ndef", 6),
        (defaultdict(a=1, b=2, marseille='lyon'), 5),
        (defaultdict(a=1, b=2, marseille='lyon'), 10),
        (defaultdict(a=1, b=2, marseille='lyon'), 20),
    ]

    for token, width in test_inputs:
        print(20*'*')
        cell = CellObj(token)
        print(f"------width={width} input [[{input}]]")
        print(f"---text          [[{cell.layout_text(width)}]]")
        print(f"---pprint        [[{cell.layout_pprint(width)}]]")
        print(f"---truncate      [[{cell.layout_truncate(width)}]]")
        print(f"text_backslash_n [[{cell.layout_text_backslash_n(width)}]]")

if __name__ == '__main__':
    test_rendering()


import os
import random
import eyed3
import pygame
from pygame.locals import *

# Function to extract cover art and title from an MP3 file
def extract_info(mp3_file):
    audiofile = eyed3.load(mp3_file)
    if audiofile.tag:
        title = audiofile.tag.title
        if not title:
            title = "Unknown Title"
        return (title, audiofile.tag.images[0].image_data if audiofile.tag.images else None)
    return ("Unknown Title", None)

# Function to play a random MP3 file from a folder and its subdirectories
def play_random_mp3(folder):
    mp3_files = []
    for root, dirs, files in os.walk(folder):
        for file in files:
            if file.endswith(".mp3"):
                mp3_files.append(os.path.join(root, file))

    if mp3_files:
        mp3_file = random.choice(mp3_files)
        pygame.mixer.music.load(mp3_file)
        pygame.mixer.music.play()
        return mp3_file  # Return the path of the currently playing song
    return None

# Initialize Pygame
pygame.init()

# Create Pygame window
screen_width, screen_height = 1400, 900  # Increased size and added padding
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Trivia Game")

# Load font for buttons, text, and title
font = pygame.font.Font(None, 36)
title_font = pygame.font.Font(None, 48)

# Initialize points for each player as global variables
player1_points = 0
player2_points = 0

# Get player names from the terminal
player1_name = input("Enter the name of Player 1: ")
player2_name = input("Enter the name of Player 2: ")

# Define buttons for player 1 and player 2
button_width = 240  # Increased button size
button_height = 80  # Increased button size
button_color1 = (255, 165, 0)  # Orange
button_color2 = (0, 191, 255)  # Sky Blue

player1_buttons = [
    [(50, 650, button_width, button_height), button_color1, font.render(f"{player1_name}: 1 pt", True, (0, 0, 0))],
    [(350, 650, button_width, button_height), button_color1, font.render(f"{player1_name}: 2 pts", True, (0, 0, 0))],
    [(650, 650, button_width, button_height), button_color1, font.render(f"{player1_name}: 3 pts", True, (0, 0, 0))],
]

player2_buttons = [
    [(50, 760, button_width, button_height), button_color2, font.render(f"{player2_name}: 1 pt", True, (0, 0, 0))],
    [(350, 760, button_width, button_height), button_color2, font.render(f"{player2_name}: 2 pts", True, (0, 0, 0))],
    [(650, 760, button_width, button_height), button_color2, font.render(f"{player2_name}: 3 pts", True, (0, 0, 0))],
]

# Define buttons for the jury
jury_buttons = [
    [(1050, 300, button_width, button_height), button_color1, font.render("Pause", True, (0, 0, 0))],
    [(1050, 450, button_width, button_height), button_color1, font.render("Next Track", True, (0, 0, 0))],
    [(1050, 650, button_width, button_height), button_color2, font.render("Restart Song", True, (0, 0, 0))],
    [(1050, 760, button_width, button_height), button_color2, font.render("Toggle Title/Cover", True, (0, 0, 0))],
]

# Flag to control track playback
is_paused = False

# Flags to control title/cover visibility
show_title = True
show_cover = True

# Variable to store the path of the currently playing song
current_song_path = None
last_song_path = None  # Store the path of the last played song

# Main game loop
def trivia_game():
    global player1_points  # Declare player1_points as global
    global player2_points  # Declare player2_points as global
    global is_paused
    global show_title
    global show_cover
    global current_song_path  # Declare current_song_path as global
    global last_song_path  # Declare last_song_path as global

    mp3_folder = "mp3_folder"
    current_song_path = play_random_mp3(mp3_folder)  # Play the first random track

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()

                # Check if player 1 buttons were clicked
                for i, button in enumerate(player1_buttons):
                    button_rect = pygame.Rect(button[0])
                    if button_rect.collidepoint(mouse_pos):
                        player1_points += i + 1

                # Check if player 2 buttons were clicked
                for i, button in enumerate(player2_buttons):
                    button_rect = pygame.Rect(button[0])
                    if button_rect.collidepoint(mouse_pos):
                        player2_points += i + 1

                # Check if jury buttons were clicked
                for i, button in enumerate(jury_buttons):
                    button_rect = pygame.Rect(button[0])
                    if button_rect.collidepoint(mouse_pos):
                        if i == 0:  # Pause button
                            if is_paused:
                                pygame.mixer.music.unpause()
                            else:
                                pygame.mixer.music.pause()
                            is_paused = not is_paused
                        elif i == 1:  # Next Track button
                            pygame.mixer.music.stop()
                            last_song_path = current_song_path
                            current_song_path = play_random_mp3(mp3_folder)
                            show_title = True
                            show_cover = True
                        elif i == 2:  # Restart Song button
                            pygame.mixer.music.rewind()
                            player1_points = 0
                            player2_points = 0
                            show_title = True
                            show_cover = True
                        elif i == 3:  # Toggle Title/Cover button
                            show_title = not show_title
                            show_cover = not show_cover

        # Clear the screen
        screen.fill((255, 255, 255))

        # Display cover art, title, and points
        if current_song_path:
            title, cover_art = extract_info(current_song_path)

            if show_cover and cover_art:
                with open("cover_art.jpg", "wb") as cover_file:
                    cover_file.write(cover_art)
                cover_image = pygame.image.load("cover_art.jpg")
                cover_image = pygame.transform.scale(cover_image, (400, 400))

                screen.blit(cover_image, (300, 150))  # Adjust position of cover art

            if show_title:
                # Display title of the song
                title_text = title_font.render(title, True, (0, 0, 0))
                title_rect = title_text.get_rect(center=(screen_width // 2, 50))
                screen.blit(title_text, title_rect)

            # Display points for players at the top left and top right
            player1_points_text = font.render(f"{player1_name}: {player1_points} pts", True, (0, 0, 0))
            player2_points_text = font.render(f"{player2_name}: {player2_points} pts", True, (0, 0, 0))
            screen.blit(player1_points_text, (10, 10))
            screen.blit(player2_points_text, (screen_width - player2_points_text.get_width() - 10, 10))

            # Display buttons for both players and jury
            for button in player1_buttons + player2_buttons + jury_buttons:
                pygame.draw.rect(screen, button[1], button[0])
                screen.blit(button[2], (button[0][0] + 10, button[0][1] + 10))  # Adjust text position

        pygame.display.flip()

    pygame.quit()

if __name__ == "__main__":
    trivia_game()


from flask_restful import Resource, reqparse, abort
from flask import session
from model import *
import app_config
import time
import base64
from tools import *
from app import app

# 代码自动保存

class AutoSave(Resource):
    def __init__(self):
        if 'uid' not in session:
            abort_msg(401, '未登录或登录过期!')

    def get(self, qid):
        # 从redis中取出
        r = app_config.save_redis
        uid = session.get('uid')
        try:
            data = r.get(f'{uid}_{qid}')
        except BaseException as e:
            abort_msg(500, '缓存连接失败!')
            app.logger.warning("Redis连接失败: %s" % str(e))
            return
        if data is None:
            abort_msg(404, '未保存或保存超时')
        return ret_data(data)

    def post(self, qid):
        parser = reqparse.RequestParser()
        parser.add_argument('code', type=str, required=True, nullable=False)
        args = parser.parse_args()
        uid = session.get('uid')
        try:
            coding_decrypt = base64.b64decode(args['code'].encode('utf-8')).decode()
        except BaseException as e:
            app.logger.warning("代码解码失败: %s" % (str(e)))
            abort_msg(500, 'BASE64解码失败')
            return
        if len(coding_decrypt) < 10:
            abort_msg(400, '代码过短不予保存')
        if len(coding_decrypt) > 20480:
            abort_msg(400, '欲保存的代码过长')
        r = app_config.save_redis
        try:
            r.setex(f'{uid}_{qid}', app_config.save_time, coding_decrypt)
        except BaseException as e:
            abort_msg(500, '缓存连接失败!')
            app.logger.warning("Redis连接失败: %s" % str(e))
            return
        return ret_data(None, 204)


"""BERT fine-tuning model, where we train a classifier on top of the [CLS]
vector for a pair of sentences to do NLI predictions."""
import math
import shutil
import torch
from transformers import Trainer, TrainingArguments
from torch.utils.data import Dataset
from typing import List, Dict, Any
import os
from sklearn.metrics import accuracy_score, precision_recall_fscore_support

def compute_metrics(pred):
    labels = pred.label_ids
    preds = pred.predictions.argmax(-1)
    precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='macro')
    acc = accuracy_score(labels, preds)
    return {
        'accuracy': acc,
        'f1': f1,
        'precision': precision,
        'recall': recall,
        'trues': labels,
        'predictions': preds
    }

def my_data_collator(features: List[Any]) -> Dict[str, torch.Tensor]:
    """
    A nearly identical version of the default_data_collator from the
    HuggingFace transformers library.
    """
    first = features[0]
    batch = {}
    # Special handling for labels.
    # Ensure that tensor is created with the correct type
    # (it should be automatically the case, but let's make sure of it.)
    if "label" in first and first["label"] is not None:
        label = first["label"].item() if isinstance(first["label"], torch.Tensor) else first["label"]
        dtype = torch.long if isinstance(label, int) else torch.float
        batch["labels"] = torch.tensor([f["label"] for f in features], dtype=dtype)
    elif "label_ids" in first and first["label_ids"] is not None:
        if isinstance(first["label_ids"], torch.Tensor):
            batch["labels"] = torch.stack([f["label_ids"] for f in features])
        else:
            dtype = torch.long if type(first["label_ids"][0]) is int else torch.float
            batch["labels"] = torch.tensor([f["label_ids"] for f in features], dtype=dtype)
    # Handling of all other possible keys.
    # Again, we will use the first element to figure out which key/values are not None for this model.
    for k, v in first.items():
        if k not in ("label", "label_ids") and v is not None and not isinstance(v, str):
            if isinstance(v, torch.Tensor):
                batch[k] = torch.stack([f[k] for f in features])
            else:
                batch[k] = torch.tensor([f[k] for f in features], dtype=torch.long)
    return batch

def load_data_as_features(data, tokenizer):
    classes = {"CONTRADICTION": 0., "NEUTRAL": 1., "ENTAILMENT": 2.}
    all_data = []
    for (s1, s2, el, rl) in data:
        di = tokenizer(s1.lower(), s2.lower(), max_length=121, padding='max_length')
        # having a max_length of 121 was fine, but with cross-lingual stuff the tokenisation will get messed up so need to increase the max length to 128
        di['label'] = torch.tensor(classes[el], dtype=torch.long)
        all_data.append(di)
    return all_data

class SICK_BERT_DATASET(Dataset):
    def __init__(self, data, tokenizer):
        self.data = load_data_as_features(data, tokenizer)

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

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

class BERTFineTuner(object):
    def __init__(self, name, tokenizer, model, train_dataset, test_dataset,
                 num_epochs=3, freeze=False):
        self.model_name = name.split('/')[-1]
        self.tokenizer = tokenizer
        self.model = model
        self.freeze = freeze
        if self.freeze:
            for p in self.model.base_model.parameters():
                p.requires_grad = False
            self.model_name = self.model_name + '_frozen'
        self.train_dataset = train_dataset
        self.test_dataset = test_dataset
        self.num_epochs = num_epochs
        self.training_args = self.setup_train_args()
        self.trainer = self.setup_trainer()

    def setup_train_args(self):
        batch_size = 16
        step_eval = math.ceil(len(self.train_dataset)/2/batch_size)
        outdir_name = f'./results2_{self.model_name}'
        logdir_name = f'./logs2_{self.model_name}'
        if os.path.exists(outdir_name):
            shutil.rmtree(outdir_name)
        if os.path.exists(logdir_name):
            shutil.rmtree(logdir_name)
        return TrainingArguments(
            output_dir=outdir_name,
            save_total_limit=1,
            # save_steps=0,
            num_train_epochs=self.num_epochs,
            # evaluate_during_training=True,
            eval_steps=step_eval,
            per_device_train_batch_size=batch_size,
            per_device_eval_batch_size=64,
            warmup_steps=250,
            weight_decay=0.01,
            logging_dir=logdir_name,
        )

    def setup_trainer(self):
        return Trainer(
            model=self.model,
            args=self.training_args,
            data_collator=my_data_collator,
            train_dataset=self.train_dataset,
            eval_dataset=self.test_dataset,
            compute_metrics=compute_metrics
        )

    def train(self):
        return self.trainer.train()

    def evaluate(self):
        return self.trainer.evaluate()


import logging
import spikingjelly.activation_based.examples.conv_fashion_mnist as s
from config import *

from utils import *
from CCEP_snn import CCEPSNN

from spikingjelly.activation_based.examples.conv_fashion_mnist import CSNN
from spikingjelly.activation_based.model.train_classify import Trainer

def main():

    args = parser.parse_args()

    set_logger(args)

    net = CSNN(T=args.T, channels=args.channels, use_cupy=args.cupy)
    net.to(args.device)
    train_dataset2 = torchvision.datasets.FashionMNIST(
        root=args.data_dir,
        train=True,
        transform=torchvision.transforms.ToTensor(),
        download=True)
    train_set, valid_set = torch.utils.data.random_split(train_dataset2,
                                                         [int(args.valid_ratio * len(train_dataset2)),
                                                          len(train_dataset2) - int(
                                                              (args.valid_ratio) * len(train_dataset2))])
    test_set = torchvision.datasets.FashionMNIST(
        root=args.data_dir,
        train=False,
        transform=torchvision.transforms.ToTensor(),
        download=True)
    train_loader = torch.utils.data.DataLoader(
        dataset=train_set,
        batch_size=args.b,
        shuffle=True,
        drop_last=True,
        num_workers=args.j,
        pin_memory=True
    )

    test_loader = torch.utils.data.DataLoader(
        dataset=test_set,
        batch_size=args.b,
        shuffle=True,
        drop_last=False,
        num_workers=args.j,
        pin_memory=True
    )
    valid_loader= torch.utils.data.DataLoader(
        dataset=test_set,
        batch_size=args.b,
        shuffle=True,
        drop_last=False,
        num_workers=args.j,
        pin_memory=True
    )
    # train_loader, valid_loader, test_loader = get_data(args)
    # writer_test = SummaryWriter(log_dir, flush_secs=600, purge_step=net.epochs) TODO
    # writer_train = SummaryWriter(log_dir, flush_secs=600, purge_step=net.train_times)
    #
    # model = spiking_vgg._spiking_vgg('vgg16_bn', 'D', True, True, True, BatchNorm2d, neuron.IFNode,
    #                                  surrogate_function=surrogate.ATan(), detach_reset=True)

    #    vgg = get_model(args)
    # x = Trainer()
    # dataset, dataset_test, train_sampler, test_sampler = x.load_ImageNet(args=args)
    # model = get_model(args)

    checkpoint = torch.load("./logs/T4_b128_sgd_lr0.1_c128_amp_cupy/checkpoint_max.pth", map_location='cpu')
    net.load_state_dict(checkpoint['net'])

    net.eval()
    test_loss = 0
    test_acc = 0
    test_samples = 0
    with torch.no_grad():
        for img, label in test_loader:
            img = img.to(args.device)
            label = label.to(args.device)
            label_onehot = s.F.one_hot(label, 10).float()
            out_fr = net(img)
            loss = s.F.mse_loss(out_fr, label_onehot)

            test_samples += label.numel()
            test_loss += loss.item() * label.numel()
            test_acc += (out_fr.argmax(1) == label).float().sum().item()
            functional.reset_net(net)
    test_time = time.time()
    test_loss /= test_samples
    test_acc /= test_samples
    print('test_acc', test_acc)

    # writer.add_scalar('test_loss', test_loss, epoch)
    # writer.add_scalar('test_acc', test_acc, epoch)

    model = net

    logger = logging.getLogger()
    logger.info("=> Model : {}".format(model))

    logger = logging.getLogger()
    logger.info('START PRUNING:')
    alg = CCEPSNN(model, train_loader, valid_loader, test_loader, args)

    alg.run(args.run_epoch)

if __name__ == '__main__':
    main()
# python -m main_snn_2.py -T 4 -device cuda:0 -b 128 -epochs 64 -data-dir /datasets/FashionMNIST/ -amp -cupy -opt sgd -lr 0.1 -j 8


"""
Data Logger Web Server

A simple web application to receive data from an OTT Data app.logger.
The script will accept different actions (determined by the action URL query
parameter.)

Accepted actions:
    * senddata
    * sendalarm

The function ott() is called when a POST request is
sent to the URI /ott/. This routes the action to the appropriate handler.
This then calls the function serialise() which writes
the body of the message to disk. The response is an XML snippet.

Use atomic file writing to ensure that no partially-written files are
synced downstream by the data pipeline.

Authentication is handled separately by the web server (e.g. Apache or NGINX).
"""

import os
import datetime
import pathlib

import atomicwrites
import flask

import settings

app = flask.current_app
blueprint = flask.Blueprint('ott', __name__)

def get_dir(root_dir: pathlib.Path, time: datetime.datetime) -> pathlib.Path:
    """
    Build the target directory and ensure it exists
    """

    root_dir = pathlib.Path(root_dir)

    # Subdirectories for each day
    path = root_dir.joinpath(*time.date().isoformat().split('-'))

    # Create target directory
    path.mkdir(parents=True, exist_ok=True)

    return path

def get_filename(station_id, time: datetime.datetime) -> str:
    """
    Build file name
    """

    # Build filename-safe timestamp
    safe_timestamp = time.isoformat().replace(':', '+')

    return f"{station_id}_{safe_timestamp}"

def get_path(root_dir: pathlib.Path, station_id: str,
             time: datetime.datetime) -> pathlib.Path:
    """
    Build target file path and create subdirectories
    """

    # Get target directory
    target_dir = get_dir(root_dir=root_dir, time=time)

    filename = get_filename(station_id=station_id, time=time)

    return target_dir.joinpath(filename)

def serialise(data: str, path: pathlib.Path) -> None:
    """
    Save the input data as a file

    :param data: Binary data to save
    :param path: Target file path
    """

    # Save to disk (open for exclusive creation, failing if the file already
    # exists). Use atomic writes to avoid partially-written files if a sync
    # starts mid-write. The data will be written to a named temporary file
    # until all data is written.
    with atomicwrites.atomic_write(
            path=str(path), overwrite=False, suffix=settings.TEMP_SUFFIX,
            dir=settings.TEMP_DIR) as file:
        file.write(data)

def build_response_body(station_id: str, resp_time: datetime.datetime) -> str:
    """
    Build a response message (OTT_Response.xsd)
    """

    # Insert parameters into string template
    return app.config['RESPONSE_TEMPLATE'].format(
        station_id=station_id,
        resp_time=resp_time.isoformat()
    )

def decode_request_data() -> str:
    """
    Decode string data from incoming request
    """
    return flask.request.get_data(as_text=True)

def ott_response(root_dir: pathlib.Path):
    """
    Generic OTT netDL response

    :param root_dir: The root directory for this function type or interface
                     e.g. senddata, sendalarm, etc.
    """

    # Get data logger identifier
    station_id = flask.request.args['stationid']

    data = decode_request_data()

    # Generate timestamp
    now = datetime.datetime.utcnow()

    # Build target file name
    path = get_path(root_dir=root_dir, station_id=station_id, time=now)

    # Save data to disk
    serialise(data, path=path)

    body = build_response_body(station_id=station_id, resp_time=now)

    return flask.Response(body, mimetype='application/xml')

@blueprint.route('/ott/', methods=['POST'])
def ott():
    """
    Route request to the appropriate function
    """

    # Map action to handler
    # Each handler has a different function and serialisation directory
    handlers = dict(
        senddata=ott_senddata,
        sendalarm=ott_sendalarm,
    )

    handler = handlers[flask.request.args['action']]

    return handler()

def ott_senddata():
    """
    OTT data app.logger server (action=senddata or OTT_Data.xsd)

    The client will send a self-timed data transmission (see Description of XML
    Data Exchange, section 6.1). The HTTP POST will be sent in XML format
    (using OTT_Data.xsd shown in Sec 9.4).

    In response to the HTTP POST request containing the data, the server
    returns an acknowledge message as defined by the XML schema file
    OTT_Response.xsd (see section 3)

    :return: XML data received success response (OTT_Response.xsd)
            (see Sec. 4.2 and 9.3)
    """

    return ott_response(root_dir=settings.DATA_DIR)

def ott_sendalarm():
    """
    Receive OTT netDL alarm signals (action=sendalarm or OTT_Alarm.xsd)

    See manual Sec 6.2

    :return: XML response (OTT_Response.xsd)
    """

    # Raise the alarm
    app.logger.error(decode_request_data())

    return ott_response(root_dir=settings.ALARM_DIR)

@blueprint.route('/ping')
def ping():
    """
    Test endpoint
    """
    return 'pong\n'


import os
import sys
import json
import time
import pickle
from SPARQLWrapper import SPARQLWrapper, JSON

triple = 'triple'
fin_list = []
sparql = SPARQLWrapper("http://dbpedia.org/sparql")

prefix = """
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX : <http://dbpedia.org/resource/>
PREFIX dbpedia2: <http://dbpedia.org/property/>
PREFIX dbpedia: <http://dbpedia.org/>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
"""

def run_time(func):
    def wrapper(*argv):
        s = time.time()
        f = func(*argv)
        e = time.time()
        print(func.__name__ + ' runtime: ' + str(e-s))
        return f
    return wrapper

def ent_uri(fn):
    ret = []
    with open(fn, 'r') as ent_in:
        ret = ent_in.readlines()
    return ret

def query(sparql_str):
    """
    Parameters:
        param1 - string of sparql query
    Return:
        null
    """
    try:
        sparql.setQuery(sparql_str)
        sparql.setReturnFormat(JSON)
        results = sparql.query().convert()
    except Exception as e:
        print(str(e))
        results = {"results": {"bindings": []}}

    return results

def isnot_literal(ent):
    ent = '<' + ent.strip() + '>'
    return """
    select * where {
        {
            """ + ent + """ ?p ?o.
            filter(!isliteral(?o))
        }
    }
    """

def ent_tail(ent):
    ent = '<' + ent.strip() + '>'
    return """
    select * where {
        {
            ?s ?p """ + ent + """.
        }
    }
    """

def ent_head(ent):
    ent = '<' + ent.strip() + '>'
    return """
    select * where {
        {
            """ + ent + """ ?p ?o.
            filter(lang(?o)="en")
        }
    }
    """

def outdicts(fnpt, ent, rets):
    tab = '    '
    for value in rets['results']['bindings']:
        triple = ent.strip() + tab + value['p']['value'] + tab + value['o']['value']
        fnpt.write(triple + '\n')

def indicts(fnpt, ent, rets):
    tab = '    '
    for value in rets['results']['bindings']:
        triple = value['s']['value'] + tab + value['p']['value'] + tab + ent.strip()
        fnpt.write(triple + '\n')

@run_time
def dfs(ent):
    ent_fn = os.path.join('entity', ent.replace('/','-'))
    ent_write = open(ent_fn, 'w')

    if len(ent) == 0:
        return
    cnt = 0
    rets_in = query(ent_tail(ent))
    indicts(ent_write, ent, rets_in)
    cnt += len(rets_in['results']['bindings'])
    print(cnt)

    rets_out = query(ent_head(ent))
    outdicts(ent_write, ent, rets_out)
    cnt += len(rets_out['results']['bindings'])
    print(cnt)
    ent_write.close()

def run():
    global fin_list
    fin_list = pickle.load(open('entity/finish', 'rb'))

    with open('ent_set', 'r') as ent_read:
        for line in ent_read.readlines():
            entity = line.strip().split(' ')[0]
            print(entity)
            if not entity in fin_list:
                dfs(entity)
                fin_list.append(entity)

if __name__ == '__main__':
    try:
        run()
    except Exception as e:
        print(e)
    finally:
        fin = open('entity/finish', 'wb')
        pickle.dump(fin_list, fin)
        fin.close()


# * Given an integer matrix, find the length of the longest increasing path.
# From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

# Input: nums =
# [
#   [9,9,4],
#   [6,6,8],
#   [2,1,1]
# ]

# Output: 4
# Explanation: The longest increasing path is [1, 2, 6, 9].

import sys
import pytest

nums = [
 [9, 9, 4],
 [6, 6, 8],
 [2, 1, 1]
]

def search(nums, i, j, path, paths):
    row = nums[i]
    row_val = row[j]
    if i-1 >= 0:
        rotate_val = nums[i-1][j]
        if rotate_val > row_val:
            search(nums, i-1, j, path + [rotate_val], paths)
    if i+1 < len(nums):
        rotate_val = nums[i+1][j]
        if rotate_val > row_val:
            search(nums, i+1, j, path + [rotate_val], paths)
    if j-1 >= 0:
        rotate_val = nums[i][j-1]
        if rotate_val> row_val:
            search(nums, i, j-1, path + [rotate_val], paths)
    if j+1 < len(row):
        rotate_val = nums[i][j+1]
        if rotate_val > row_val:
            search(nums, i, j+1, path + [rotate_val], paths)
    paths.append([i for i in path])

def longest_increasing_path(nums):
    paths = []
    for i, row in enumerate(nums):
        for j, row_val in enumerate(row):
            search(nums, i, j, [row_val], paths)

    l = 0
    longest = None
    for p in paths:
        if len(p) > l:
            longest = p
            l = len(p)
    return longest

def test_nums_assignment():
    nums = [
        [9, 9, 4],
        [6, 6, 8],
        [2, 1, 1]
    ]
    assert longest_increasing_path(nums) == [1,2,6,9]

def test_works_not_from_smallest_num():
    nums = [
        [9, 9, 4],
        [10, 6, 8],
        [8, 7, 6]
    ]
    assert longest_increasing_path(nums) == [6,7,8,10]

def test_simple():
    nums = [
        [1,2]
    ]
    assert longest_increasing_path(nums) == [1,2]

def test_negative():
    nums = [
        [9, 9, 4],
        [6, 6, 8],
        [2, -1, 1]
    ]
    assert longest_increasing_path(nums) == [-1, 2, 6, 9]

pytest.main()


"""
Command line interface for dealing with FHI-aims' `species_defaults` basis sets
"""
from pathlib import Path
import sys

import click

from aiida.cmdline.commands.cmd_data import verdi_data
from aiida.cmdline.utils import decorators, echo
from aiida.orm import QueryBuilder
from aiida.plugins import GroupFactory

from aiida_fhiaims.data.species_family import BasisFamily

# from aiida.cmdline.params.types import DataParamType

AimsBasisFamily = GroupFactory("fhiaims.species_family")

@verdi_data.group("species-defaults")
def species_defaults():
    """Command line interface for FHIAims species_defaults"""

@species_defaults.command("install")
@click.argument("path", type=click.Path(exists=True), envvar="AIMS_SPECIES_DIR")
@decorators.with_dbenv()
def install(path):
    """Installs a set of `species_defaults` FHI-aims basis families (light, tight, really_tight...) from a given PATH.
    Defaults to the value of AIMS_SPECIES_DIR environmental variable.
    """
    path = Path(path)
    echo.echo(f"Trying to install basis families from {path.absolute()}... ", nl=False)
    # get all the directories with basis files two levels deep
    files = path.rglob("*_default")
    family_dirs = {f.parent.parent.resolve() for f in files}
    if len(family_dirs) == 0:
        echo.echo_critical("[FAILED]")
    families = []
    for d in family_dirs:
        if d == path or path in d.parents:
            families.append(BasisFamily.from_folder(d, d.name))
    echo.echo_success(" [OK]")
    family_data = [(f.label, f.pk) for f in families]
    echo.echo(
        f'Installed families: {", ".join([f"{label}<pk={pk}>" for (label, pk) in family_data])}'
    )

@species_defaults.command("list")
@decorators.with_dbenv()
def list_():  # pylint: disable=redefined-builtin
    """
    Display all AIMS basis families
    """
    qb = QueryBuilder()
    qb.append(AimsBasisFamily)
    results = qb.all()

    s = ""
    for result in results:
        obj = result[0]
        s += f"{str(obj)}, pk: {obj.pk}\n"
    sys.stdout.write(s)


# test implementation/demo
from tracker import Tracker
import cv2

t = Tracker()
t.run()
f = t.getFrame()
while f is None:
    f = t.getFrame()

while 1:
    f = t.getFrame()
    print(t.calculate_angle("RIGHT_HAND", "LEFT_HAND"))
    cv2.imshow("img", f)
    if (cv2.waitKey(1) & 0xFF == ord('q')):
        break

t.stop()
cv2.destroyAllWindows()


from __future__ import unicode_literals
import frappe
from datetime import date, timedelta, datetime
from frappe.model.document import Document

class StudentInformation(Document):
	pass
	# def autoname(self):
	# 	self.name = "hello world"
	# def validate(self):
	# 	result = frappe.db.sql("SELECT * from `tabStudent Information`", as_dict=1)
	# 	# self.result = str(result[0]['name'])
    #
	# 	first_column = []
	# 	for i in result:
	# 		first_column.append(i['name'])
	# 	self.result = str(first_column)

	# def validate(self):
	# 	result = frappe.get_list("Student Information", {"course": "BSIT"}, ['name', 'full_name'])
    #
	# 	self.result = str(result)

	# def validate(self):
	# 	result = frappe.get_value("Student Information", "SI-2021-03-25-00001", "birthdate")
    #
	# 	self.result = str(result)

	def validate(self):
		#doctype
		if not frappe.db.exists("Courses", self.course):
			new_course = frappe.get_doc({
				"doctype": "Courses",
				"course_id": self.course,
				"course_name": self.course
			})
		#child table
			new_course.append(
				"subjects",{
					"subject_id": self.course,
					"subject_name": self.course,
				}
			)

			new_course.insert()

@frappe.whitelist()
def calculate_age(birthdate):
	converted = datetime.strptime(birthdate, '%Y-%m-%d')
	return (datetime.today() - converted) // timedelta(days=365.2425)

def sample_querry():
	result = frappe.db.sql("SELECT * from `tabStudent Information`", as_dict=1)
	print (result)


from distutils.log import debug
import uuid
import requests
from flask import Flask, render_template, session, request, redirect, url_for
from flask_session import Session  # https://pythonhosted.org/Flask-Session
import msal
import app_config

from service_bus import send_to_servicebus,get_from_servicebus

app = Flask(__name__)
app.config.from_object(app_config)
debug=True
app.config["TEMPLATES_AUTO_RELOAD"]= True
Session(app)

from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)

@app.route("/")
def index():
    if not session.get("user"):
        return redirect(url_for("login"))
    return render_template('index.html', user=session["user"], version=msal.__version__)

@app.route("/login")
def login():
    session["flow"] = _build_auth_code_flow(scopes=app_config.SCOPE)
    return render_template("login.html", auth_url=session["flow"]["auth_uri"], version=msal.__version__)

@app.route(app_config.REDIRECT_PATH)  # Applicatie URI
def authorized():
    try:
        cache = _load_cache()
        result = _build_msal_app(cache=cache).acquire_token_by_auth_code_flow(
            session.get("flow", {}), request.args)
        if "error" in result:
            return render_template("auth_error.html", result=result)
        session["user"] = result.get("id_token_claims")
        _save_cache(cache)
    except ValueError:
        pass
    return redirect(url_for("index"))

@app.route("/logout")
def logout():
    session.clear()
    return redirect(
        app_config.AUTHORITY + "/oauth2/v2.0/logout" +
        "?post_logout_redirect_uri=" + url_for("index", _external=True))

@app.route("/graphcall")
def graphcall():
    token = _get_token_from_cache(app_config.SCOPE)
    if not token:
        return redirect(url_for("login"))
    #Ophalen data met graph API
    graph_data = requests.get(
        app_config.CENDPOINT,
        headers={'Authorization': 'Bearer ' + token['access_token']},
        ).json()['value']
    return render_template('schedule.html', data=graph_data)
    # agendaTitel = graph_data['bodyPreview']
    # send_to_servicebus(agendaTitel)
    # service_bus_data = get_from_servicebus()
    # print(service_bus_data)

@app.route("/egraphcall")
def egraphcall():
    token = _get_token_from_cache(app_config.SCOPE)
    if not token:
        return redirect(url_for("login"))
    graph_data = requests.get(
        app_config.EENDPOINT,
        headers={'Authorization': 'Bearer ' + token['access_token']},
        ).json()
    return render_template('display.html', result=graph_data)

def _load_cache():
    cache = msal.SerializableTokenCache()
    if session.get("token_cache"):
        cache.deserialize(session["token_cache"])
    return cache

def _save_cache(cache):
    if cache.has_state_changed:
        session["token_cache"] = cache.serialize()

def _build_msal_app(cache=None, authority=None):
    return msal.ConfidentialClientApplication(
        app_config.CLIENT_ID, authority=authority or app_config.AUTHORITY,
        client_credential=app_config.CLIENT_SECRET, token_cache=cache)

def _build_auth_code_flow(authority=None, scopes=None):
    return _build_msal_app(authority=authority).initiate_auth_code_flow(
        scopes or [],
        redirect_uri=url_for("authorized", _external=True))

def _get_token_from_cache(scope=None):
    cache = _load_cache()
    cca = _build_msal_app(cache=cache)
    accounts = cca.get_accounts()
    if accounts:
        result = cca.acquire_token_silent(scope, account=accounts[0])
        _save_cache(cache)
        return result

app.jinja_env.globals.update(_build_auth_code_flow=_build_auth_code_flow)  # Used in template

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


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import RobustScaler

#The following function will plot the original and scaled distributions of the zillow data
def compare_dists(train, cols_to_scale, cols_scaled):
    plt.figure(figsize=(13,6))

    for i, col in enumerate(cols_to_scale):
        i += 1
        plt.subplot(2,4,i)
        train[col].plot.hist()
        plt.title(col)

    for i, col in enumerate(cols_scaled):
        i += 5
        plt.subplot(2,4,i)
        train[col].plot.hist()
        plt.title(col)

    plt.tight_layout()
    plt.show()

#The following function will take in train, validate, and test data sets and return the scaled version of each
def scale_zillow_data(train, validate, test):
    #Create lists to hold column names
    cols_to_scale = ['bedroom_count', 'bathroom_count', 'area (sq-ft)', 'tax_amount']
    cols_scaled = ['bedroom_count_scaled', 'bathroom_count_scaled', 'area (sq-ft) scaled', 'tax_amount_scaled']

    #Instantiate the scaler
    robust_scaler = RobustScaler()

    #Fit the scaler on train
    robust_scaler.fit(train[cols_to_scale])

    #Transform the data
    train[cols_scaled] = robust_scaler.transform(train[cols_to_scale])
    validate[cols_scaled] = robust_scaler.transform(validate[cols_to_scale])
    test[cols_scaled] = robust_scaler.transform(test[cols_to_scale])

    #Visualize and compare the scaled and non-scaled distributions
    compare_dists(train, cols_to_scale, cols_scaled)

    #Drop the non-scaled columns
    train.drop(columns = cols_to_scale, inplace = True)
    validate.drop(columns = cols_to_scale, inplace = True)
    test.drop(columns = cols_to_scale, inplace = True)

    return train, validate, test


# Blender data to store

import bpy

class BlenderData(object):
    def __init__(self):
        self.data = [
        'actions', 'armatures', 'brushes',
        'cameras', 'curves', 'filepath', 'fonts',
        'grease_pencil', 'groups', 'images',
        'lamps', 'lattices', 'libraries',
        'linestyles', 'masks', 'materials', 'meshes',
        'metaballs', 'movieclips', 'node_groups',
        'objects', 'particles', 'scenes',
        'scripts', 'shape_keys', 'sounds',
        'speakers', 'texts', 'textures', 'worlds']

        """
        Encode the following in the DB

        actions
        cameras
        groups
        images
        node_groups
        particles
        scenes
        worlds
        """

    @property
    def actions(self):
        # Return a list of the local actions in the scene
        actions = bpy.data.actions
        local_actions = []
        for action in actions:
            if not action.is_library_indirect:
                local_actions.append(BlenderAction(action))
        return local_actions

    '''
    @actions.setter
    def actions(self, value):
        self.actions = value
        return locals()
    '''

    @property
    def groups(self):
        # Return a list of the local groups in the scene
        groups = bpy.data.groups
        local_groups = []
        for group in groups:
            if not group.is_library_indirect:
                local_groups.append(BlenderGroup(group))
        return local_groups

    @property
    def images(self):
        # Return a list of the local images in the scene
        images = bpy.data.images
        local_images = []
        for image in images:
            if not image.is_library_indirect:
                local_images.append(BlenderImage(image))
        return local_images

class BlenderAction(object):
    def __init__(self, action):
        self.name = action.name
        self.start_frame = action.frame_range[0]
        self.end_frame = action.frame_range[1]

        # TODO: take care of other values, such as groups, fcurves, pose_markers, etc

class BlenderGroup(object):
    def __init__(self, group):
        self.name = group.name

        # TODO: there are a few other attributes that may be of interest, including
        # group.objects, group.layers, etc.

class BlenderImage(object):
    def __init__(self, image):
        self.name = image.name
        self.depth = image.depth
        self.display_aspect = image.display_aspect
        self.filepath = image.filepath
        self.filepath_from_user = image.filepath_from_user
        self.size_x = image.size[0]
        self.size_y = image.size[1]
        self.file_format = image.file_format

        # Note:  images are unique to their filepaths on disk - look for a way
        # to use the filepath as an index for the images, and do not allow
        # duplicates in the database.  If a duplicate is found, create a link
        # to the asset that's using the image, so there's a singular reference
        # to it across all assets that use it.