import os, sys, serial, time

option = str(sys.argv[1:2])

if(option == '[\'--start\']'):
	#create communication file
	if(not os.path.isfile('/var/www/Smart-Calendar/HTML/temporary/message.txt')):
		file = open('/var/www/Smart-Calendar/HTML/temporary/message.txt', 'w+')
		file.close()
	#create timestamp file
	if(not os.path.isfile('/var/www/Smart-Calendar/HTML/temporary/stamp.txt')):
		file = open('/var/www/Smart-Calendar/HTML/temporary/stamp.txt', 'w+')
		file.write('File Created ' + time.asctime() + '\n')
		file.close()
	#turn on pins, set to input
	os.system("echo 17 > /sys/class/gpio/export")
	os.system("echo in > /sys/class/gpio/gpio17/direction")
	os.system("echo 27 > /sys/class/gpio/export")
	os.system("echo in > /sys/class/gpio/gpio27/direction")
	os.system("python /var/www/Smart-Calendar/Background/pins.py &")

elif(option == '[\'--stop\']'):
	os.system("kill $(ps -eF | grep pins.py | grep -v grep | awk '{print $2}')") #end pins.py
	os.system("kill $(ps -eF | grep firefox | grep -v grep | awk '{print $2}')") #end firefox
	#turn off pins
	os.system("echo 17 > /sys/class/gpio/unexport")
	os.system("echo 27 > /sys/class/gpio/unexport")
	#format timestamp file
	timevar = time.asctime()
	file = open('/var/www/Smart-Calendar/HTML/temporary/stamp.txt', 'a+')
	file.write('File Closed ' + timevar + '\n')
	file.close()
	timevar = timevar[4:7] + '_' + timevar[8:10] + '_' + timevar[20:] + '_stamp.txt'
	os.rename("/var/www/Smart-Calendar/HTML/temporary/stamp.txt", "/var/www/Smart-Calendar/HTML/temporary/" + timevar)
	#email file

elif(option == '[\'--monitor-on\']'):
	os.system("tvservice -p; chvt 6; chvt 7") #turn on hdmi port
	#close power to monitor through serial
	ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
	code = 'A00101A2'
	ser.write(code.decode('HEX'))

elif(option == '[\'--monitor-off\']'):
	os.system("tvservice -p; tvservice -o") #turn off hdmi port
	#open power to monitor through serial
	ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
	code = 'A00100A1'
	ser.write(code.decode('HEX'))


# =====> Importando modulos <====
import modulos as xs # con la palabra reservada de import, importamos otro modulo que hayamos creado u otro de los que vienen incluidos en python.
# con la palabra as cambiamos el nombre a nuestro archivo de "modulos" a "xs", con esto cada vez que llamemos a nuestro archivo modulos lo tendremos que nombrar "xs"

# print(modulos.mascotas) # con esto llamamos especificamente al elemento llamado mascotas en el archivo modulos
# modulos.saludo('Nicolas') # con esto llamamos a la funcions saludo del archvivo modulos
print(xs.mascotas)
xs.saludo('Felipe')

# ====> importar solo un elemento <====
# Para importar solo un elemento desde un modulo primero usamos from para indicar desde donde importaremos, y luego usamos import e indicamos el elemento que queremos importar
from modulos import saludo, mascotas
from camelcase import CamelCase

print(mascotas)
saludo('Nicolas')

c = CamelCase()
s = 'esta oracion necesita camelCase!'

camelcased = c.hump(s)
print(camelcased)


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_())


import time
import json
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import requests

# Parameters
search_query = "site:youtube.com openinapp.co"
results_limit = 30

# Set up Chrome options
chrome_options = Options()
chrome_options.add_argument("--headless")  # Run Chrome in headless mode (without GUI)

# Set up Chrome WebDriver
webdriver_path = "./chromedriver.exe"  # Path to your Chrome WebDriver executable
service = Service(webdriver_path)
driver = webdriver.Chrome(service=service, options=chrome_options)

# Perform the search and collect YouTube links
search_results = []
start_index = 0

while len(search_results) < results_limit:
    # Prepare the search query URL
    params = {
        "q": search_query,
        "start": start_index
    }

    # Construct the Google search URL
    base_url = "https://www.google.com/search?" + "&".join([f"{key}={value}" for key, value in params.items()])
    print(base_url)
    # Load the search results page
    driver.get(base_url)
    time.sleep(2)  # Wait for the page to load

    # Extract the page source and parse it with BeautifulSoup
    page_source = driver.page_source
    soup = BeautifulSoup(page_source, "html.parser")

    # Find all the search result links
    links = soup.select('.MjjYud a')
    #print(links)

    for link in links:
        href = link.get('href')
        #print(href)
        if href.startswith('https://www.youtube.com/watch?'):

            youtube_link = href
            driver.get(youtube_link)

            time.sleep(2)

# Locate the element using a CSS selector
            chilledCowElem = driver.find_element_by_css_selector("div.ytd-channel-name a")

# Access the name of the channel and gets its href value
            #print(chilledCowElem.text)
            #print(chilledCowElem.get_attribute("href"))

            search_results.append(chilledCowElem.get_attribute("href"))

    # Update the start index for the next page of results
    start_index += 10

    # Break the loop if no more results are found
    #if len(links) == 0:
     #   break

    print(f"Scraped {len(search_results)} YouTube links")

# Close the Chrome WebDriver
driver.quit()

# Store the results in a JSON file
output_file = "youtube_links.json"
with open(output_file, "w") as file:
    json.dump(search_results, file, indent=4)

print(f"\nScraping completed. {len(search_results)} YouTube links were scraped and saved to {output_file}.")


def p_lic_xref_1(self, p):
        """lic_xref : LICS_CRS_REF LINE"""
        try:
            if six.PY2:
                value = p[2].decode(encoding='utf-8')
            else:
                value = p[2]
            self.builder.add_lic_xref(self.document, value)
        except OrderError:
            self.order_error('LicenseCrossReference', 'LicenseName', p.lineno(1))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 17 14:40:59 2018

@author: zdhughes
"""

#global FAKE_CBLT
#global TIMED_FAKE_CBLT
#global EVENT_FAKE_CBLT
#global CONTINUOUS_FAKE_CBLT
#global CLOSE_SERVER

#global SERVER_CLOSED
#global SERVER_RENDEVOUS_DEFAULT
#global RENDEVOUS_PROCEED
#global RENDEVOUS_HALT

# =============================================================================
# FAKE_CBLT = 1
# TIMED_FAKE_CBLT = 2
# EVENT_FAKE_CBLT = 3
# CONTINUOUS_FAKE_CBLT = 4
# CLOSE_SERVER = 255
#
# SERVER_CLOSED = 0
# SERVER_RENDEVOUS_DEFAULT = 255
# RENDEVOUS_PROCEED = 1
# RENDEVOUS_HALT = 0
# =============================================================================

CLEAR_EVENT = 200
SINGLE_CBLT = 201
TIMED_CBLT = 202
EVENT_CBLT = 203
CONTINUOUS_CBLT = 204
AUTOMATED_CBLT = 205
SINGLE_REREAD = 207
CLOSE_SERVER = 255

SERVER_CLOSED = 0
SERVER_RENDEVOUS_DEFAULT = 255
RENDEVOUS_PROCEED = 1
RENDEVOUS_HALT = 0

GET_DATA_WIDTH = 50
GET_DATA_OFFSET = 51
GET_AREA_WIDTH = 52
GET_AREA_OFFSET = 53
GET_REREAD_WIDTH = 54
GET_REREAD_OFFSET = 55
GET_HILO_WIDTH = 56
GET_HILO_OFFSET = 57
GET_CFD_THRESH = 58
GET_0_SUPRESS_LEVEL = 59
READ_ALL_PARAMS = 60
GET_FADC_MODE = 61

SET_DATA_WIDTH = 150
SET_DATA_OFFSET = 151
SET_AREA_WIDTH = 152
SET_AREA_OFFSET = 153
SET_REREAD_WIDTH = 154
SET_REREAD_OFFSET = 155
SET_HILO_WIDTH = 156
SET_HILO_OFFSET = 157
SET_CFD_THRESH = 158
SET_0_SUPRESS_LEVEL = 159
CLEAR_ALL_SCALARS = 160
SET_FADC_MODE = 161

#define CLEAR_EVENT 200
#define SINGLE_CBLT 201
#define TIMED_CBLT 202
#define EVENT_CBLT 203
#define CONTINUOUS_CBLT 204
#define AUTOMATED_CBLT 205
#define SINGLE_REREAD 207
#define CLOSE_SERVER 255


import sys
input = sys.stdin.readline

from collections import deque
queue = deque(list(input().rstrip()))

i = 1
while queue:
    for s in str(i):
        if queue and s == queue[0]:
            queue.popleft()
    i += 1
print(i - 1)

백준/Silver/1515. 수 이어 쓰기/수 이어 쓰기.py


'''
Created on Feb 8, 2018

@author: stelios
'''

try:
    import logging
    from models.base.base_object import BaseObject
    import os
    import core as core
    import adql
    import time
except Exception as e:
    logging.exception(e)

class AdqlQuery(BaseObject):
    """
    classdocs
    """

    def __init__(self, adql_resource, json_object=None, url=None):
        """
        Constructor
        """
        self.adql_resource = adql_resource
        super().__init__(self.adql_resource.account, json_object, url)
        self.query_engine = core.query_engine.QueryEngine(self.account)

    def ident(self):
        if (self.json_object==None):
            if (self.url!=None):
                self.json_object = self.get_json(self.url)
                return os.path.basename(self.json_object.get("self",""))
        else:
            return os.path.basename(self.json_object.get("self",""))

    def resource(self):
        if (self.json_object!=None):
            return adql.AdqlResource(account=self.account, url=self.json_object.get("workspace",""))
        else:
            return None

    def osql(self):
        if (self.json_object==None):
            if (self.url!=None):
                self.json_object = self.get_json(self.url)
                return self.json_object.get("osql","")
        else:
            return self.json_object.get("osql","")

    def adql(self):
        if (self.json_object==None):
            if (self.url!=None):
                self.json_object = self.get_json(self.url)
                return self.json_object.get("adql","")
        else:
            return self.json_object.get("adql","")

    def error (self):
        """Get Error message
        """
        error = ""
        try:
            error = self.json_object.get("syntax").get("friendly",None)
        except Exception as e:
            logging.exception(e)

        return error

    def status(self, refresh=True):
        if (refresh):
            self.json_object = self.get_json(self.url)
            return self.json_object.get("status","").upper()
        else:
            if (self.json_object==None):
                if (self.url!=None):
                    self.json_object = self.get_json(self.url)
                    return self.json_object.get("status","").upper()
            else:
                return self.json_object.get("status","").upper()

    def results(self):
        return self.table()

    def table(self):
        if (self.json_object==None):
            if (self.url!=None):
                self.json_object = self.get_json(self.url)

        table_json = self.get_json(self.json_object.get("results",None).get("table",None))
        schema_json = self.get_json(table_json.get("schema",None))
        resource_json = self.get_json(schema_json.get("resource",None))
        new_resource = adql.AdqlResource(json_object=resource_json, account=self.account)
        new_schema = adql.AdqlSchema(json_object=schema_json, adql_resource = new_resource)
        return adql.AdqlTable(url=self.json_object.get("results",None).get("table",None), adql_schema=new_schema)

    def getAttr(self, attribute):
        if (self.json_object==None):
            if (self.url!=None):
                self.json_object = self.get_json(self.url)
                return self.json_object.get(attribute,"")
        else:
            return self.json_object.get(attribute,"")

    def update(self, adql_query_input=None, adql_query_status_next=None, adql_query_wait_time=None):
        return self.query_engine.update_query(adql_query_input=adql_query_input, adql_query_status_next=adql_query_status_next, adql_query=self, adql_query_wait_time=adql_query_wait_time)

    def run_sync(self):
        self.update(adql_query_status_next="COMPLETED")
        while self.status()=="RUNNING" or self.status()=="READY":
            time.sleep(3)

        return

    def isRunning(self):
        """
        Check if a Query is running
        """

        if (self.status(True)=="RUNNING" or self.status(True)=="READY"):
            return True
        else:
            return False


import math

from projecteuler.mathlibrary import MathLibrary
from .IEulerSolution import IEulerSolution

class LargestPrimeFactor(IEulerSolution):
    """
    Solution to problem 3, Find the largest prime factor of 600,851,475,143
    """
    VALUE = 600851475143

    def __init__(self, problem_number = None):
        IEulerSolution.__init__(self)

    def compute(self):
        factors = MathLibrary.get_factors(self.VALUE, MathLibrary.get_prime(10000))
        return int(factors[-1])


#
# 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)


from triangleChecker import triangleChecker

def test_class():
    good_triangle = triangleChecker(2, 4, 3)
    assert good_triangle.is_triangle() == 'Ура, можно построить треугольник!'
    triangle_negative_num = triangleChecker(4, -5, 3)
    assert triangle_negative_num.is_triangle() == 'С отрицательными числами ничего не выйдет!'
    triangle_str = triangleChecker('2', 4, 5)
    assert triangle_str.is_triangle() == 'Нужно вводить только числа!'
    not_triangle = triangleChecker(1, 2, 3)
    assert not_triangle.is_triangle() == 'Жаль, но из этого треугольник не сделать.'


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


import requests, json

machine_address = "http://3R-UNIT-01:8000"
url = 'http://3R-UNIT-01:8000/machine/axis_positions'
myobj = {'somekey': 'somevalue'}

x = requests.get(machine_address+"/machine/axis_positions", data = myobj)
positions = json.loads(x.content.decode())
print(f'X position is {positions["x"]}, Z position is {positions["z"]}')

x=requests.post(machine_address+"/machine/gripper", data=data)
data={"gripper_state":"open"}


try:
    archivo = open('prueba.txt', 'r', encoding='utf8')
    # leer toda la informacion del archivo
    # print(archivo.read())

    # leer algunos caracteres
    # print(archivo.read(5))

    # leer lineas completas
    #print(archivo.readline())

    # iterar archivo
    #for linea in archivo:
    #     print(linea)

    # leer lineas
    # nota: se genera una lista con las lineas del archivo
    #print(archivo.readlines()[2])

    # abrimos un nuevo archivo
    # a - anexar informacion
    archivo2 = open('copia.txt','a')
    archivo2.write(archivo.read())

    archivo.close()
    archivo2.close()

except Exception as e:
    print(e)
finally:
    archivo.close()


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')


# -*- 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 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()


#!/usr/bin/python3.5
# -*- coding: utf-8 -*-
# Project: Python100example
#    File: Example89
#  Author: liyaoyan
#   Email: helloalvin@163.com
#    Time: 2018/10/21 下午10:54

"""某个公司采用公用电话传递数据，数据
是四位的整数，在传递过程中是加密的，加
密规则如下：每位数字都加上5,然后用和除
以10的余数代替该数字，再将第一位和第四
位交换，第二位和第三位交换。"""
from com.python100.example.files.ExampleBase import *

class Example89(ExampleBase):
    def execute(self):
        num = input('请输入四位整数：')
        if isinstance(int(num),int) and len(num) == 4:
            temp = []
            for i in num:
                temp.append(str((int(i)+5)%10))
            temp[0],temp[len(temp)-1]=temp[len(temp)-1],temp[0]
            temp[1],temp[2]=temp[2],temp[1]
            print(''.join(temp))
        else:
            self.execute()


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()


# 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)


from django.shortcuts import render, redirect
from django.http import JsonResponse
from datetime import datetime

from .models import *
from .scrapers import create_data_set

# main page
def show_home_page(request):
    text = 'With the help of this site, \
        in the graphics section, you can find out where to buy yarn at the best price among the stores in your city, \
            find out the dynamics of yarn price growth, as well as in which store you can buy the colors of yarn you are \
                interested in.'
    return render(request, 'yarn_prices/home.html', context={'title': 'Home', 'description_text': text})

# визуализация полученных данных в HighCharts
def show_charts_page(request):
    colors_query_set = ColorsAvailability.objects.values('code', 'name').order_by('code')
    colors_set = create_colors_range(colors_query_set)

    context = {
        'title': 'Charts',
        'colors_set': colors_set,
    }
    return render(request, 'yarn_prices/charts.html', context=context)

# подготовка данных для графиков в ответ на ajax запрос
def get_data_for_the_charts(request):
    # Если в базе нет записи с текущей датой
    todays_day = datetime.now().date()

    if not YarnDetails.objects.filter(date=todays_day).exists():
        parse_data_and_save_to_db()

    column_chart = set_column_chart_config()
    line_chart = set_basic_line_chart_config()

    response = {
        'column_chart': column_chart,
        'line_chart': line_chart
    }

    return JsonResponse(response)

# конфигурация столбчатой диаграммы
def set_column_chart_config(shops_list=None) -> dict:
    # подготовка датасета для графика
    today = datetime.now().date()
    data_values = []
    if not shops_list:
        details = YarnDetails.objects.select_related('yarn').filter(date=today).order_by('price')
        for yd in details:
            shop = yd.yarn.shop.name
            data_values.append([shop, yd.price])
    else:
        for shop in shops_list:
            yarn_id = shop.yarncategory_set.get().pk
            details = YarnDetails.objects.get(date=today, yarn=yarn_id)
            data_values.append([shop.name, details.price])
            data_values.sort(key=lambda x: x[1])

    # конфигурация данных для графика series
    data = [{
        'name': 'Цена',
        'data': data_values,
        'color': '#FFCCCC',
        'dataLabels': {
            'enabled': True,
            'color': '#000000',
            'align': 'center',
            'format': '{point.y:.2f}',
            'style': {
                'fontSize': '10px',
            }
        }
    }]

    # общая конфигурация графика
    chart = {
        'chart': {'type': 'column'},
        'legend': {'enabled': False},
        'title': {'text': 'Детская новинка', 'align': 'left'},
        'subtitle': {'text': today.strftime('%d-%m-%Y'), 'align': 'left'},
        'xAxis': {'type': 'category'},
        'yAxis': {'min': 0, 'title': {'text': 'BYN'}},
        'tooltip': {'pointFormat': "Цена: {point.y:.2f}"},
        'series': data,
    }

    return chart

# конфигурация линейных графиков
def set_basic_line_chart_config() -> dict:
    # подготовка датасета для графика
    yarns_categories = YarnCategory.objects.select_related('shop').all()
    data_set = []
    for category in yarns_categories:
        shop_prices_by_time = []
        details = category.yarndetails_set.all().order_by('date')
        for yd in details:
            date = yd.date.strftime('%d-%m-%Y')
            shop_prices_by_time.append([date , yd.price])

        # конфигурация данных для графика
        data_set.append({
            'name': category.shop.name,
            'data': shop_prices_by_time,
            'lineWidth': 2,
            'marker': {
                'radius': 2,
                'symbol': 'circle'
                }
            })

    # конфигурация графика
    chart = {
        'title': {
            'text': 'Детская новинка',
            'align': 'left'
        },

        'subtitle': {
            'text': 'г. Минск',
            'align': 'left'
        },

        'yAxis': {
            'title': {
                'text': 'BYN'
            }
        },

        'xAxis': {
            'type': 'category',
            'accessibility': {
                'rangeDescription': 'Range: 2010 to 2020'
            },
            'labels': {
                'rotation': -45,
                'style': {
                    'fontSize': '13px',
                    'fontFamily': 'Verdana, sans-serif'
                }
            }

        },

        'legend': {
            'layout': 'horizontal',
            'align': 'right',
            # 'verticalAlign': 'middle'
        },

        'plotOptions': {
            'series': {
                'label': {
                    'connectorAllowed': 'false'
                },
            }
        },

        'series': data_set,

        'responsive': {
            'rules': [{
                'condition': {
                    'maxWidth': 500
                },
                'chartOptions': {
                    'legend': {
                        'layout': 'horizontal',
                        'align': 'center',
                        'verticalAlign': 'bottom'
                    }
                }
            }]
        }
    }

    return chart

# the function starts the BS4 web parser and saves the received data to the database
def parse_data_and_save_to_db() -> None:
    dataset: list = create_data_set()
    for data in dataset:
        try:
            if not Shop.objects.filter(name=data.get('shop')).exists():
                shop = Shop.objects.create(name=data.get('shop'), url=data.get('url'))
            else:
                shop = Shop.objects.get(name=data.get('shop'))

            if not YarnCategory.objects.filter(name=data.get('yarn'), shop=shop).exists():
                yarn = YarnCategory.objects.create(name=data.get('yarn'), shop=shop)
            else:
                yarn = YarnCategory.objects.get(name=data.get('yarn'), shop=shop)

            YarnDetails.objects.create(yarn=yarn, price=data.get('price'))

            for color in data.get('colors'):
                if not ColorsAvailability.objects.filter(code=color[0], yarn=yarn).exists():
                    ColorsAvailability.objects.create(yarn=yarn, code=int(color[0]),
                                                    name=color[1], availability=color[2])
                else:
                    color_obj = ColorsAvailability.objects.get(code=int(color[0]), yarn=yarn)
                    color_obj.name = color[1]
                    color_obj.availability = color[2]
                    color_obj.save()

        except Exception as ex:
            print(f'Exception: {ex}')
            print('an exception was thrown while the data was being saved to the database')
            return redirect('yarn_prices_urls:home')
    return redirect('yarn_prices_urls:charts')

# подготовка списка цветов из базы для dropdown list
def create_colors_range(colors_query_set) -> dict:
    colors_set = {}
    for color in colors_query_set:
        if not color['code'] in colors_set.keys():
            colors_set.update({color['code']: color['name']})
    return colors_set

# response для ajax по выбору цвета из dropdown
def colors_list_ajax_response(request) -> dict:
    not_available = ['нет в наличии']

    if request.method == 'POST':
        color_code = int(request.POST.get('submit'))
        colors = ColorsAvailability.objects.select_related('yarn', 'yarn__shop').filter(code=color_code)

        shops_list = []
        available = []
        for color in colors:
            if not color.availability in not_available:
                shop = color.yarn.shop
                available.append({'shop': shop.name, 'shop_url': shop.url, 'availability':  color.availability})
                shops_list.append(shop)

        column_chart = set_column_chart_config(shops_list)

        response = {
            'color_code': color_code,
            'color_name': colors[0].name,
            'available': available,
            'column_chart': column_chart
        }
        return JsonResponse(response)


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')


from tests.selenium.Admin import generic
import tests.rerun

from tests.package.interface import Interface

class Selenium_Admin_TerrainTest(
    generic.Selenium_Admin_Generic,
    Interface
):
    @tests.rerun.retry()
    def testCreateTerrainByCoordinate(self):
        self.login()
        self._goToAdmin()

        self.byCssSelector('div.from .x').send_keys(1)
        self.byCssSelector('div.from .y').send_keys(1)

        self.byCssSelector('div.to .x').send_keys(1)
        self.byCssSelector('div.to .y').send_keys(1)

        self.byXPath('//span[@data-type="1"]/button').click()

        self.byCssSelector('.send').click()

        self.operationIsSuccess()

    @tests.rerun.retry()
    def testCreateTerrainByChunks(self):
        self.login()
        self._goToAdmin()

        self.byAttribute('data-type', 'chunk').click()

        self.byCssSelector('.block-chunk .chunk').send_keys(1)
        self.byCssSelector('.sl-add-to-list').click()
        try:
            self.byAttribute('data-chunk', '1')
        except self.NoSuchElementException:
            self.fail('Chunk not added')

        self.byCssSelector('.chunk-position .x').send_keys(16)
        self.byCssSelector('.chunk-position .y').send_keys(0)
        self.byCssSelector('.sl-add-to-list').click()
        try:
            self.byAttribute('data-chunk', '2')
        except self.NoSuchElementException:
            self.fail('Chunk not added')

        self.byAttribute('data-chunk', '2').click()
        try:
            self.byAttribute('data-chunk', '2')
            self.fail('Chunk not deleted')
        except self.NoSuchElementException:
            pass

        self.byXPath('//span[@data-type="1"]/button').click()

        self.byCssSelector('.send').click()

        self.operationIsSuccess()


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'),
]


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()


import sys
import threading
from trackermodule.trackerconfighandler import TrackerConfigHandler
from trackermodule.threadedtrackerserver import ThreadedTrackerServer

if __name__ == "__main__":
    server = None
    try:
        tracker_config = TrackerConfigHandler()
        tracker_host = ''
        tracker_port = tracker_config.tracker_port
        tracker_server_address = (tracker_host, tracker_port)
        server = ThreadedTrackerServer(tracker_server_address)
        server.listen()

    except Exception as err:
        print("Oops! Error: {}.".format(err))

    finally:
        main_thread = threading.current_thread()
        for t in threading.enumerate():
            if t is main_thread:
                continue
            t.close_connection()
        if server:
            server.stop_server()


"""Methods for simplicial complexes."""

from ..core import Hypergraph, SimplicialComplex
from ..exception import XGIError
from ..generators import empty_simplicial_complex

__all__ = ["from_simplex_dict", "from_max_simplices"]

def from_simplex_dict(d, create_using=None):
    """Creates a Simplicial Complex from a dictionary of simplices,
    if the subfaces of existing simplices are not given in the dict
    then the function adds them with integer IDs.

    Parameters
    ----------
    d : dict
        A dictionary where the keys are simplex IDs and the values
        are containers of nodes specifying the simplices.
    create_using : SimplicialComplex constructor, optional
        The simplicial complex object to add the data to, by default None

    Returns
    -------
    SimplicialComplex object
        The constructed simplicial complex object

    """
    SC = empty_simplicial_complex(create_using)
    SC.add_simplices_from((members, uid) for uid, members in d.items())
    return SC

def from_max_simplices(SC):
    """Returns a hypergraph constructed from the
    maximal simplices of the provided simplicial complex.

    Parameters
    ----------
    SC : SimplicialComplex

    Returns
    -------
    Hypergraph

    """
    if type(SC) != SimplicialComplex:
        raise XGIError("The input must be a SimplicialComplex")

    max_simplices = SC.edges.maximal()
    H = Hypergraph()
    H.add_nodes_from(SC.nodes)  # to keep node order and isolated nodes
    H.add_edges_from([list(SC.edges.members(e)) for e in max_simplices])
    return H


'''
This program counts the distribution of the hour of the day for each of the messages.
You can pull the hour from the “From” line by finding the time string and
then splitting that string into parts using the colon character.
Once you have accumulated the counts for each hour, print out the counts,
one per line, sorted by hour as shown below.

   python timeofday.py
   Enter a file name: mbox-short.txt
   04 3
   06 1
   07 1
   09 2
   10 3
   11 6
   14 1
   15 2
   16 4
   17 2
   18 1
   19 1
'''

fhand = open('mbox-short.txt')

d=dict()
for line in fhand :
    if not line.startswith('From ') :
        continue
    words=line.split()
    hsplit = words[5].split(':')
    for word in hsplit[0:1] :
        d[word] = d.get(word,0) + 1

for k,v in sorted(d.items()) :
    print(k,v)


"""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()


from odoo import fields, models, api

class CourseEnrollment(models.Model):
    _name = 'course.enrollment'
    _description = 'Course Enrollment'
    _inherit = ['mail.thread','mail.activity.mixin']

    name = fields.Char('Title', required=True)
    enroll_date = fields.Date(default=lambda self: fields.Date.today(),tracking=True)
    course_id = fields.Many2one('training_center.course', 'Course',tracking=True)
    member_id = fields.Many2one('training_members.member','Member',tracking=True)
    member_image = fields.Binary(related='member_id.image_1920')

    currency_id = fields.Many2one('res.currency')
    price = fields.Monetary('Price', 'currency_id', related='course_id.price')

    discount = fields.Float('Discount', 'currency_id', compute='_compute_discount')
    total_amount = fields.Monetary('Total Amount', 'currency_id', compute='_compute_total_amount')

    state = fields.Selection(
        string="state",
        selection=[('new','New'),('draft','Draft'),('confirmed','Confirmed'),('canceled','Canceled')],
        default='new'
    )

    @api.model_create_multi
    def create(self,vals_list):
        for vals in vals_list:
            vals['name']= self.env['ir.sequence'].next_by_code('enroll.course') or '/'
        return super().create(vals_list)

    #@api.model
    #def create(self,vals_list):
    #    vals_list['name']= self.env['ir.sequence'].next_by_code('course.enrollment') or '/'
    #    return super().create(vals_list)

    @api.depends('enroll_date', 'price')
    def _compute_discount(self):
        for enrollment in self:
            if enrollment.enroll_date and enrollment.enroll_date < fields.Date.from_string('2023-06-01'):
                enrollment.discount = enrollment.price * 0.25
            else:
                enrollment.discount = enrollment.price * 0.20

    @api.depends('price', 'discount')
    def _compute_total_amount(self):
        for enrollment in self:
            enrollment.total_amount = enrollment.price - enrollment.discount

    def action_do_cancel(self):
        if self.state != "confirmed":
            self.state ="canceled"
        return True

    def action_do_confirmed(self):
        return self.write({"state":"confirmed"})

    def action_do_draft(self):
        return self.write({"state":"draft"})


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'),


from climate.initialiser import environment, db

from climate import command, presenter

from . import helpers

def run():
    record_date = helpers.prompt_for_date()
    while True:
        selection = helpers.show_menu_and_prompt(_main_menu())
        if selection is None:
            break
        flow_step = selection(record_date)
        if isinstance(flow_step, helpers.ExitTerminator) and flow_step.is_exit():
            break

def _temperatures(record_date):
    flow = None
    while True:
        locale = helpers.get_locale_from_input()
        if isinstance(locale, helpers.ExitTerminator):
            flow = locale
            break
        minimum = helpers.prompt_for_temperature('Minimum')
        maximum = helpers.prompt_for_temperature('Maximum')
        command.add_temperature(locale, minimum, maximum, record_date)
    return flow

def _narrative(record_date):
    flow = None
    while True:
        locale_or_terminator = helpers.get_locale_from_input()
        if isinstance(locale_or_terminator, helpers.ExitTerminator):
            flow = locale_or_terminator
            break
        command.add_narrative(locale=locale_or_terminator,
                              terms=helpers.get_narrative_terms_from_import(),
                              date=record_date)
    return flow

def _plot(_record_date):
    channel = helpers.get_channel_from_input()
    command.plot_temperatures(channel=channel)
    return None

def _main_menu():
    return {
        1: ('Add Temperatures', _temperatures),
        2: ('Add Narrative', _narrative),
        4: ('Plot', _plot),
        3: ('Exit', None)
    }


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)


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


def image_plane_pix_grid_from_regular_grid(self, regular_grid):
        """Calculate the image-plane pixelization from a regular-grid of coordinates (and its mask).

        See *grid_stacks.SparseToRegularGrid* for details on how this grid is calculated.

        Parameters
        -----------
        regular_grid : grids.RegularGrid
            The grid of (y,x) arc-second coordinates at the centre of every image value (e.g. image-pixels).
        """

        pixel_scale = regular_grid.mask.pixel_scale

        pixel_scales = ((regular_grid.masked_shape_arcsec[0] + pixel_scale) / (self.shape[0]),
                        (regular_grid.masked_shape_arcsec[1] + pixel_scale) / (self.shape[1]))

        return grids.SparseToRegularGrid(unmasked_sparse_grid_shape=self.shape, pixel_scales=pixel_scales,
                                         regular_grid=regular_grid, origin=regular_grid.mask.centre)


high_ord_func = lambda x,func: x + func(x)

increment = lambda x: x + 2

result = high_ord_func(2,increment) #Puedo pasarle una funcion de parametro
print(result)                        #en este caso es "increment"

result = high_ord_func(2,lambda x: x + 2) #Tambien puedo pasar el codigo directamente
print(result)                              #Sin necesidad de crear una funcion


#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os

# ------------------- Directories --------------------

DIRECTORY_MAIN = "/".join(os.path.realpath(__file__).split("/")[:-3])
DIRECTORY_LOG_BASE = DIRECTORY_MAIN + "/logs"
DIRECTORY_LOG = ""
DIRECTORY_OUTPUT_BASE = DIRECTORY_MAIN + "/output"
DIRECTORY_OUTPUT = ""
DIRECTORY_TMP = ""
DIRECTORY_BACKUP = DIRECTORY_MAIN + "/backup"
DIRECTORY_TESTS = DIRECTORY_MAIN + "/tests"
DIRECTORY_VECTORS_A = DIRECTORY_OUTPUT + "/vectors-a"
DIRECTORY_VECTORS_B = DIRECTORY_OUTPUT + "/vectors-b"
DIRECTORY_VECTORS_C = DIRECTORY_OUTPUT + "/vectors-c"
DIRECTORY_TOOLS = DIRECTORY_MAIN + "/third-party"
DIRECTORY_DATA = DIRECTORY_MAIN + "/data"

# ------------------- Files --------------------

FILE_MAIN_LOG = ""
FILE_ERROR_LOG = DIRECTORY_LOG_BASE + "/log-error"
FILE_LAST_LOG = DIRECTORY_LOG_BASE + "/log-latest"
FILE_MAKE_LOG = DIRECTORY_LOG_BASE + "/log-make"
FILE_COMMAND_LOG = DIRECTORY_LOG_BASE + "/log-command"
FILE_STANDARD_FUNCTION_LIST = DIRECTORY_DATA + "/standard-function-list"
FILE_STANDARD_MACRO_LIST = DIRECTORY_DATA + "/standard-macro-list"
FILE_STANDARD_DATATYPE_LIST = DIRECTORY_DATA + "/standard-data-type-list"

FILE_AST_SCRIPT = DIRECTORY_TMP + "/ast-script"
FILE_TEMP_DIFF = DIRECTORY_TMP + "/temp_diff"
FILE_AST_MAP = DIRECTORY_TMP + "/ast-map"
FILE_AST_DIFF_ERROR = DIRECTORY_TMP + "/errors_ast_diff"
FILE_PARTIAL_PATCH = DIRECTORY_TMP + "/gen-patch"
FILE_EXCLUDED_EXTENSIONS = DIRECTORY_TMP + "/excluded-extensions"
FILE_EXCLUDED_EXTENSIONS_A = DIRECTORY_TMP + "/excluded-extensions-a"
FILE_EXCLUDED_EXTENSIONS_B = DIRECTORY_TMP + "/excluded-extensions-b"
FILE_GIT_UNTRACKED_FILES = DIRECTORY_TMP + "/untracked-list"
FILE_DIFF_C = DIRECTORY_TMP + "/diff_C"
FILE_DIFF_H = DIRECTORY_TMP + "/diff_H"
FILE_DIFF_ALL = DIRECTORY_TMP + "/diff_all"
FILE_FIND_RESULT = DIRECTORY_TMP + "/find_tmp"
FILE_TEMP_TRANSFORM = DIRECTORY_TMP + "/temp-transform"

FILE_DIFF_INFO = ""
FILE_ORIG_DIFF_INFO = ""
FILE_PORT_DIFF_INFO = ""
FILE_TRANSPLANT_DIFF_INFO = ""
FILE_ORIG_DIFF = ""
FILE_PORT_DIFF = ""
FILE_TRANSPLANT_DIFF = ""
FILE_CLONE_INFO = ""
FILE_LIST_PATCH_FILES = ""
FILE_VECTOR_MAP = ""
FILE_SOURCE_MAP = ""
FILE_DATATYPE_MAP = ""
FILE_NAMESPACE_MAP_LOCAL = ""
FILE_NAMESPACE_MAP_GLOBAL = ""
FILE_SCRIPT_INFO = ""
FILE_MACRO_DEF = ""

FILE_AST_MAP_LOCAL = ""
FILE_AST_MAP_GLOBAL = ""

FILE_TRANSLATED_SCRIPT_INFO = ""
FILE_COMPARISON_RESULT = ""
FILE_TEMP_FIX = ""

FILE_PROJECT = ""
FILE_PROJECT_A = ""
FILE_PROJECT_B = ""
FILE_PROJECT_C = ""
FILE_PROJECT_D = ""
FILE_PROJECT_E = ""
FILE_VAR_MAP_STORE = ""
FILE_VEC_MAP_STORE = ""
FILE_SOURCE_MAP_STORE = ""
FILE_MISSING_FUNCTIONS = ""
FILE_MISSING_MACROS = ""
FILE_MISSING_HEADERS = ""
FILE_MISSING_TYPES = ""
FILE_SEGMENT_STATE = ""
FILE_ORIG_N = ""
FILE_PORT_N = ""
FILE_TRANS_N = ""

# ------------------- Configuration --------------------

CONF_PATH_A = "path_a:"
CONF_PATH_B = "path_b:"
CONF_PATH_C = "path_c:"
CONF_PATH_E = "path_e:"
CONF_COMMIT_A = "commit_a:"
CONF_COMMIT_B = "commit_b:"
CONF_COMMIT_C = "commit_c:"
CONF_COMMIT_E = "commit_e:"
CONF_PATH_POC = "path_poc:"
CONF_EXPLOIT_A = "exploit_command_a:"
CONF_CONFIG_COMMAND_A = "config_command_a:"
CONF_BUILD_COMMAND_A = "build_command_a:"
CONF_EXPLOIT_C = "exploit_command_c:"
CONF_CONFIG_COMMAND_C = "config_command_c:"
CONF_BUILD_COMMAND_C = "build_command_c:"
CONF_FLAGS_A = "build_flags_a:"
CONF_FLAGS_C = "build_flags_c:"
CONF_ASAN_FLAG = "asan_flag:"
CONF_KLEE_FLAGS_A = "klee_flags_a:"
CONF_KLEE_FLAGS_C = "klee_flags_c:"
CONF_DIFF_SIZE = "diff_size:"
CONF_VC = "version-control:"
CONF_LINUX_KERNEL = "linux-kernel:"
CONF_BACKPORT = "backport:"
CONF_CONTEXT_LEVEL = "context_level:"
CONF_TAG_ID = "tag_id:"

# ----------------- KEY DEFINITIONS -------------------

KEY_DURATION_TOTAL = 'run-time'
KEY_DURATION_INITIALIZATION = 'initialization'
KEY_DURATION_BUILD_ANALYSIS = "build-process"
KEY_DURATION_DIFF_ANALYSIS = 'diff-analysis'
KEY_DURATION_CLONE_ANALYSIS = "clone-analysis"
KEY_DURATION_SLICE = "slicing-process"
KEY_DURATION_EXTRACTION = "patch-extraction"
KEY_DURATION_MAP_GENERATION = "map-generation"
KEY_DURATION_TRANSLATION = 'translation'
KEY_DURATION_EVOLUTION = "evolution"
KEY_DURATION_TRANSPLANTATION = "transplantation"
KEY_DURATION_VERIFICATION = 'verification'
KEY_DURATION_REVERSE = "reverse"
KEY_DURATION_EVALUATION = 'evaluation'
KEY_DURATION_SUMMARIZATION = "summarize-analysis"
KEY_DURATION_COMPARISON = "comparison-analysis"

# ---------------- PHASES ---------------------------
PHASE_BUILD = "build"
PHASE_DIFF = "diff"
PHASE_DETECTION = "detect"
PHASE_SLICING = "slice"
PHASE_EXTRACTION = "extract"
PHASE_MAPPING = "map"
PHASE_TRANSLATION = "translate"
PHASE_EVOLUTION = "evolve"
PHASE_WEAVE = "weave"
PHASE_VERIFY = "verify"
PHASE_REVERSE = "reverse"
PHASE_EVALUATE = "eval"
PHASE_COMPARE = "compare"
PHASE_SUMMARIZE = "summary"

# ---------------- ARGUMENTS ---------------------------
ARG_CONF_FILE = "--conf="
ARG_TIMEOUT = "--time="
ARG_DEBUG = "--debug"
ARG_HELP = "--help"
ARG_DEBUG_DATA = "--debug-data"
ARG_BACKPORT = "--backport"
ARG_FORK = "--fork"
ARG_LINUX_KERNEL = "--linux-kernel"
ARG_BREAK_WEAVE = "--break-weave"
ARG_USE_CACHE = "--use-cache"
ARG_OPERATION_MODE = "--mode="
ARG_CONTEXT_LEVEL = "--context="
ARG_OUTPUT_FORMAT = "--format="

ARG_ONLY_BUILD = "--only-" + PHASE_BUILD
ARG_ONLY_DIFF = "--only-" + PHASE_DIFF
ARG_ONLY_DETECT = "--only-" + PHASE_DETECTION
ARG_ONLY_SLICE = "--only-" + PHASE_SLICING
ARG_ONLY_EXTRACT = "--only-" + PHASE_EXTRACTION
ARG_ONLY_MAP = "--only-" + PHASE_MAPPING
ARG_ONLY_TRANSLATE = "--only-" + PHASE_TRANSLATION
ARG_ONLY_EVOLVE = "--only-" + PHASE_EVOLUTION
ARG_ONLY_WEAVE = "--only-" + PHASE_WEAVE
ARG_ONLY_VERIFY = "--only-" + PHASE_VERIFY
ARG_ONLY_REVERSE = "--only-" + PHASE_REVERSE
ARG_ONLY_EVALUATION = "--only-" + PHASE_EVALUATE
ARG_ONLY_COMPARE = "--only-" + PHASE_COMPARE
ARG_ONLY_SUMMARY = "--only-" + PHASE_SUMMARIZE

ARG_SKIP_BUILD = "--skip-" + PHASE_BUILD
ARG_SKIP_DIFF = "--skip-" + PHASE_DIFF
ARG_SKIP_DETECT = "--skip-" + PHASE_DETECTION
ARG_SKIP_SLICE = "--skip-" + PHASE_SLICING
ARG_SKIP_EXTRACT = "--skip-" + PHASE_EXTRACTION
ARG_SKIP_MAP = "--skip-" + PHASE_MAPPING
ARG_SKIP_TRANSLATE = "--skip-" + PHASE_TRANSLATION
ARG_SKIP_EVOLVE = "--skip-" + PHASE_EVOLUTION
ARG_SKIP_WEAVE = "--skip-" + PHASE_WEAVE
ARG_SKIP_VERIFY = "--skip-" + PHASE_VERIFY
ARG_SKIP_REVERSE = "--skip-" + PHASE_REVERSE
ARG_SKIP_EVAL = "--skip-" + PHASE_EVALUATE
ARG_SKIP_COMPARE = "--skip-" + PHASE_COMPARE
ARG_SKIP_SUMMARY = "--skip-" + PHASE_SUMMARIZE
ARG_SKIP_VEC_GEN = "--skip-vec-gen"
ARG_SKIP_RESTORE = "--skip-restore"
ARG_ANALYSE_NEIGHBORS = "--analyse-n"
ARG_BUILD_AND_ANALYSE = "--analyse-b-n"

# ----------------- TOOLS --------------------------------
TOOL_VECGEN = "third-party/deckard/cvecgen_fail "
TOOL_VECGEN_ORIG = "third-party/deckard/cvecgen "

APP_AST_DIFF = "crochet-diff"
PATCH_COMMAND = "crochet-patch"
LINUX_PATCH_COMMAND = "patch"
PATCH_SIZE = "1000"
DIFF_COMMAND = "crochet-diff "
LINUX_DIFF_COMMAND = "diff "
DIFF_SIZE = "1000"
SYNTAX_CHECK_COMMAND = "clang-check "
STYLE_FORMAT_COMMAND = "clang-format -style=LLVM "

crash_word_list = ["abort", "core dumped", "crashed", "exception", "dumped core"]
error_word_list = ["runtime error", "buffer-overflow", "unsigned integer overflow"]

operation_mode = {0: "fixmorph", 1: "patch", 2: "patch-context", 3: "sydit"}
output_format_list = ["normal", "unified"]

UPDATEMOVE = "UpdateMove"
UPDATE = "Update"
MOVE = "Move"
INSERT = "Insert"
DELETE = "Delete"
MATCH = "Match"
REPLACE = "Replace"
TO = " to "
AT = " at "
INTO = " into "
AND = "and"
WITH = " with "
order = [DELETE, INSERT, REPLACE, UPDATE, UPDATEMOVE, MOVE]


import pandas as pd
import numpy as np

def edgelist2snapshots(filepath, g):
    """Convert a edgelist with timestamps into g snapshots.

    Arguments:
        filepath (str): the filepath of the edgelist
        g (int): the number of graph snapshots
    """
    df = pd.read_csv(filepath, sep='\s+', header=None, names=['from', 'to', 'weight', 'timestamp'], dtype={'from':'str', 'to':'str', 'weight':np.float64, 'timestamp':int})
    ecount = len(df.index)
    start_time = df['timestamp'].min()
    end_time = df['timestamp'].max()
    interval = (end_time - start_time) / g

    snapshots = dict()
    for i in range(g):
        snapshots[i] = []

    dfs = df.sort_values(by=['timestamp'])
    for i in range(ecount):
        idx = np.floor((dfs.iloc[i]['timestamp'] - start_time) / interval)
        if int(idx) == g:
            snapshots[g - 1].append(i)
        else:
            snapshots[int(idx)].append(i)

    filename = filepath.split('/')[1].split('.')[0]
    for i in range(g):
        dfs.iloc[snapshots[i]].to_csv(f'datasets/temporal-{filename}/{filename}-{i}.txt', sep=' ', header=False, index=False)


import logging
from functools import cmp_to_key
from typing import Callable
from typing import Optional

from cryptojwt import KeyJar
from cryptojwt.jwe import SUPPORTED
from cryptojwt.jws.jws import SIGNER_ALGS
from cryptojwt.key_jar import init_key_jar
from cryptojwt.utils import importer

from idpyoidc.client.util import get_uri
from idpyoidc.impexp import ImpExp
from idpyoidc.util import add_path
from idpyoidc.util import qualified_name

logger = logging.getLogger(__name__)

def metadata_dump(info, exclude_attributes):
    return {qualified_name(info.__class__): info.dump(exclude_attributes=exclude_attributes)}

def metadata_load(item: dict, **kwargs):
    _class_name = list(item.keys())[0]  # there is only one
    _cls = importer(_class_name)
    _cls = _cls().load(item[_class_name])
    return _cls

class Metadata(ImpExp):
    parameter = {"prefer": None, "use": None, "callback_path": None, "_local": None}

    _supports = {}

    def __init__(self, prefer: Optional[dict] = None, callback_path: Optional[dict] = None):

        ImpExp.__init__(self)
        if isinstance(prefer, dict):
            self.prefer = {k: v for k, v in prefer.items() if k in self._supports}
        else:
            self.prefer = {}

        self.callback_path = callback_path or {}
        self.use = {}
        self._local = {}

    def get_use(self):
        return self.use

    def set_usage(self, key, value):
        self.use[key] = value

    def get_usage(self, key, default=None):
        return self.use.get(key, default)

    def get_preference(self, key, default=None):
        return self.prefer.get(key, default)

    def set_preference(self, key, value):
        self.prefer[key] = value

    def remove_preference(self, key):
        if key in self.prefer:
            del self.prefer[key]

    def _callback_uris(self, base_url, hex):
        _uri = []
        for type in self.get_usage("response_types", self._supports["response_types"]):
            if "code" in type:
                _uri.append("code")
            elif type in ["id_token", "id_token token"]:
                _uri.append("implicit")

        if "form_post" in self.supports:
            _uri.append("form_post")

        callback_uri = {}
        for key in _uri:
            callback_uri[key] = get_uri(base_url, self.callback_path[key], hex)
        return callback_uri

    def construct_redirect_uris(self, base_url: str, hex: str, callbacks: Optional[dict] = None):
        if not callbacks:
            callbacks = self._callback_uris(base_url, hex)

        if callbacks:
            self.set_preference("callbacks", callbacks)
            self.set_preference("redirect_uris", [v for k, v in callbacks.items()])

        self.callback = callbacks

    def verify_rules(self, supports):
        return True

    def locals(self, info):
        pass

    def _keyjar(self, keyjar=None, conf=None, entity_id=""):
        _uri_path = ""
        if keyjar is None:
            if "keys" in conf:
                keys_args = {k: v for k, v in conf["keys"].items() if k != "uri_path"}
                _keyjar = init_key_jar(**keys_args)
                _uri_path = conf["keys"].get("uri_path")
            elif "key_conf" in conf and conf["key_conf"]:
                keys_args = {k: v for k, v in conf["key_conf"].items() if k != "uri_path"}
                _keyjar = init_key_jar(**keys_args)
                _uri_path = conf["key_conf"].get("uri_path")
            else:
                _keyjar = KeyJar()
                if "jwks" in conf:
                    _keyjar.import_jwks(conf["jwks"], "")

            if "" in _keyjar and entity_id:
                # make sure I have the keys under my own name too (if I know it)
                _keyjar.import_jwks_as_json(_keyjar.export_jwks_as_json(True, ""), entity_id)

            _httpc_params = conf.get("httpc_params")
            if _httpc_params:
                _keyjar.httpc_params = _httpc_params

            return _keyjar, _uri_path
        else:
            if "keys" in conf:
                _uri_path = conf["keys"].get("uri_path")
            elif "key_conf" in conf and conf["key_conf"]:
                _uri_path = conf["key_conf"].get("uri_path")
            return keyjar, _uri_path

    def get_base_url(self, configuration: dict):
        raise NotImplementedError()

    def get_id(self, configuration: dict):
        raise NotImplementedError()

    def add_extra_keys(self, keyjar, id):
        return None

    def get_jwks(self, keyjar):
        return None

    def handle_keys(
        self, configuration: dict, keyjar: Optional[KeyJar] = None, base_url: Optional[str] = ""
    ):
        _jwks = _jwks_uri = None
        _id = self.get_id(configuration)
        keyjar, uri_path = self._keyjar(keyjar, configuration, entity_id=_id)

        self.add_extra_keys(keyjar, _id)

        # now that keys are in the Key Jar, now for how to publish it
        if "jwks_uri" in configuration:  # simple
            _jwks_uri = configuration.get("jwks_uri")
        elif uri_path:
            if not base_url:
                base_url = self.get_base_url(configuration)
            _jwks_uri = add_path(base_url, uri_path)
        else:  # jwks or nothing
            _jwks = self.get_jwks(keyjar)

        return {"keyjar": keyjar, "jwks": _jwks, "jwks_uri": _jwks_uri}

    def load_conf(
        self, configuration, supports, keyjar: Optional[KeyJar] = None, base_url: Optional[str] = ""
    ):
        for attr, val in configuration.items():
            if attr == "preference":
                for k, v in val.items():
                    if k in supports:
                        self.set_preference(k, v)
            elif attr in supports:
                self.set_preference(attr, val)

        self.locals(configuration)

        for key, val in self.handle_keys(configuration, keyjar=keyjar, base_url=base_url).items():
            if key == "keyjar":
                keyjar = val
            elif val:
                self.set_preference(key, val)

        self.verify_rules(supports)
        return keyjar

    def get(self, key, default=None):
        if key in self._local:
            return self._local[key]
        else:
            return default

    def set(self, key, val):
        self._local[key] = val

    def construct_uris(self, *args):
        pass

    def supports(self):
        res = {}
        for key, val in self._supports.items():
            if isinstance(val, Callable):
                res[key] = val()
            else:
                res[key] = val
        return res

    def supported(self, claim):
        return claim in self._supports

    def prefers(self):
        return self.prefer

SIGNING_ALGORITHM_SORT_ORDER = ["RS", "ES", "PS", "HS", "Ed"]

def cmp(a, b):
    return (a > b) - (a < b)

def alg_cmp(a, b):
    if a == "none":
        return 1
    elif b == "none":
        return -1

    _pos1 = SIGNING_ALGORITHM_SORT_ORDER.index(a[0:2])
    _pos2 = SIGNING_ALGORITHM_SORT_ORDER.index(b[0:2])
    if _pos1 == _pos2:
        return (a > b) - (a < b)
    elif _pos1 > _pos2:
        return 1
    else:
        return -1

def get_signing_algs():
    # Assumes Cryptojwt
    _algs = [name for name in list(SIGNER_ALGS.keys()) if name != "none"]
    return sorted(_algs, key=cmp_to_key(alg_cmp))

def get_encryption_algs():
    return SUPPORTED["alg"]

def get_encryption_encs():
    return SUPPORTED["enc"]

def array_or_singleton(claim_spec, values):
    if isinstance(claim_spec[0], list):
        if isinstance(values, list):
            return values
        else:
            return [values]
    else:
        if isinstance(values, list):
            return values[0]
        else:  # singleton
            return values

def is_subset(a, b):
    if isinstance(a, list):
        if isinstance(b, list):
            return set(b).issubset(set(a))
    elif isinstance(b, list):
        return a in b
    else:
        return a == b