import os
from glob import glob
from tqdm import tqdm
from pprint import pprint
from pathlib import Path
import cv2 as cv
import numpy as np
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
import json

def cal_stats(dataloader, batch_size=4, img_size=64):
    psum = torch.zeros((1, 3))
    psum_sq = torch.zeros((1, 3))

    # loop through images
    for inputs in tqdm(dataloader):
        inputs = inputs[0]
        psum += inputs.sum(axis=[0, 2, 3])
        psum_sq += (inputs ** 2).sum(axis=[0, 2, 3])

    # pixel count
    count = len(dataloader) * batch_size * img_size * img_size

    # mean and std
    total_mean = psum / count
    total_var = (psum_sq / count) - (total_mean ** 2)
    total_std = torch.sqrt(total_var)
    return {'mean': total_mean[0].tolist(), 'std': total_std[0].tolist()}

def plot_hist(dataloader, img_size=64):
    all_images = torch.zeros((3, img_size, img_size))
    # loop through images
    for inputs in tqdm(dataloader):
        inputs = inputs[0]
        all_images += inputs.sum(axis=[0])
    colors = ('red', 'green', 'blue')
    plt.figure()
    plt.xlim([0, 256])
    for channel_id, color in enumerate(colors):
        histogram, bin_edges = np.histogram(
            all_images[channel_id, :, :], bins=256, range=(0, 256)
        )
        plt.plot(bin_edges[0:-1], histogram, color=color)

    plt.title('Histogram')
    plt.xlabel('Color value')
    plt.ylabel('Pixel count')
    plt.savefig(dataset_path.split('/')[-1] + '.png')
    plt.show()

def main(dataset_path):
    img_size = 64
    batch_size = 4
    transforms_ = transforms.Compose([transforms.Resize((img_size, img_size)), transforms.ToTensor()])
    data = torchvision.datasets.ImageFolder(dataset_path, transform=transforms_)
    dataloader = DataLoader(data, batch_size=batch_size, shuffle=False, num_workers=2, pin_memory=True)
    stats = cal_stats(dataloader)

    print('mean: ' + str(stats['mean']))
    print('std:  ' + str(stats['std']))
    with open('stats.json', 'w') as js:
        json.dump(stats, js, indent=4)

    # plot_hist(dataloader)

if __name__ == '__main__':
    dataset_path = '/home/asebaq/SAC/healthy_aug_22_good'
    # dataset_path = '/home/asebaq/CholecT50_sample/data/images'
    main(dataset_path)


import zipfile
from pathlib import Path
from pacu.core.lib import pacu_dir
from pacu.utils import zip_file

def test_pacu_dir():
    assert str(pacu_dir()) == str(Path(__file__).parents[1]/'pacu')

def test_zip_file(tmp_path):
    ZIP_PATH = tmp_path/'test.zip'
    file_data = {
        'file01':'abc',
        'file02':'zxy'
    }
    zip_file(ZIP_PATH, file_data)

    assert ZIP_PATH.is_file()

    with zipfile.ZipFile(ZIP_PATH,"r") as zip_ref:
        zip_ref.extractall(tmp_path)
    assert (tmp_path/'file01').is_file()
    assert (tmp_path/'file02').is_file()

    with open(tmp_path/'file01') as f:
        assert file_data['file01'] == f.read()

    with open(tmp_path/'file02') as f:
        assert file_data['file02'] == f.read()


import pipenv.vendor.click as click

from pipenv.patched.safety.formatter import FormatterAPI
from pipenv.patched.safety.output_utils import build_announcements_section_content, format_long_text, \
    add_empty_line, format_vulnerability, get_final_brief, \
    build_report_brief_section, format_license, get_final_brief_license, build_remediation_section, \
    build_primary_announcement
from pipenv.patched.safety.util import get_primary_announcement, get_basic_announcements, get_terminal_size

class ScreenReport(FormatterAPI):
    DIVIDER_SECTIONS = '+' + '=' * (get_terminal_size().columns - 2) + '+'

    REPORT_BANNER = DIVIDER_SECTIONS + '\n' + r"""
                               /$$$$$$            /$$
                              /$$__  $$          | $$
           /$$$$$$$  /$$$$$$ | $$  \__//$$$$$$  /$$$$$$   /$$   /$$
          /$$_____/ |____  $$| $$$$   /$$__  $$|_  $$_/  | $$  | $$
         |  $$$$$$   /$$$$$$$| $$_/  | $$$$$$$$  | $$    | $$  | $$
          \____  $$ /$$__  $$| $$    | $$_____/  | $$ /$$| $$  | $$
          /$$$$$$$/|  $$$$$$$| $$    |  $$$$$$$  |  $$$$/|  $$$$$$$
         |_______/  \_______/|__/     \_______/   \___/   \____  $$
                                                          /$$  | $$
                                                         |  $$$$$$/
  by pyup.io                                              \______/

""" + DIVIDER_SECTIONS

    ANNOUNCEMENTS_HEADING = format_long_text(click.style('ANNOUNCEMENTS', bold=True))

    def __build_announcements_section(self, announcements):
        announcements_section = []

        basic_announcements = get_basic_announcements(announcements)

        if basic_announcements:
            announcements_content = build_announcements_section_content(basic_announcements)
            announcements_section = [add_empty_line(), self.ANNOUNCEMENTS_HEADING, add_empty_line(),
                                     announcements_content, add_empty_line(), self.DIVIDER_SECTIONS]

        return announcements_section

    def render_vulnerabilities(self, announcements, vulnerabilities, remediations, full, packages):
        announcements_section = self.__build_announcements_section(announcements)
        primary_announcement = get_primary_announcement(announcements)
        remediation_section = build_remediation_section(remediations)
        end_content = []

        if primary_announcement:
            end_content = [add_empty_line(),
                           build_primary_announcement(primary_announcement, columns=get_terminal_size().columns),
                           self.DIVIDER_SECTIONS]

        table = []
        ignored = {}
        total_ignored = 0

        for n, vuln in enumerate(vulnerabilities):
            if vuln.ignored:
                total_ignored += 1
                ignored[vuln.package_name] = ignored.get(vuln.package_name, 0) + 1
            table.append(format_vulnerability(vuln, full))

        report_brief_section = build_report_brief_section(primary_announcement=primary_announcement, report_type=1,
                                                          vulnerabilities_found=max(0, len(vulnerabilities)-total_ignored),
                                                          vulnerabilities_ignored=total_ignored,
                                                          remediations_recommended=len(remediations))

        if vulnerabilities:

            final_brief = get_final_brief(len(vulnerabilities), len(remediations), ignored, total_ignored)

            return "\n".join(
                [ScreenReport.REPORT_BANNER] + announcements_section + [report_brief_section,
                                                                        add_empty_line(),
                                                                        self.DIVIDER_SECTIONS,
                                                                        format_long_text(
                                                                            click.style('VULNERABILITIES FOUND',
                                                                                bold=True, fg='red')),
                                                                        self.DIVIDER_SECTIONS,
                                                                        add_empty_line(),
                                                                        "\n\n".join(table),
                                                                        final_brief,
                                                                        add_empty_line(),
                                                                        self.DIVIDER_SECTIONS] +
                remediation_section + end_content
            )
        else:
            content = format_long_text(click.style("No known security vulnerabilities found.", bold=True, fg='green'))
            return "\n".join(
                [ScreenReport.REPORT_BANNER] + announcements_section + [report_brief_section,
                                                                        self.DIVIDER_SECTIONS,
                                                                        add_empty_line(),
                                                                        content,
                                                                        add_empty_line(),
                                                                        self.DIVIDER_SECTIONS] +
                end_content
            )

    def render_licenses(self, announcements, licenses):
        unique_license_types = set([lic['license'] for lic in licenses])

        report_brief_section = build_report_brief_section(primary_announcement=get_primary_announcement(announcements),
                                                          report_type=2, licenses_found=len(unique_license_types))
        announcements_section = self.__build_announcements_section(announcements)

        if not licenses:
            content = format_long_text(click.style("No packages licenses found.", bold=True, fg='red'))
            return "\n".join(
                [ScreenReport.REPORT_BANNER] + announcements_section + [report_brief_section,
                                                                        self.DIVIDER_SECTIONS,
                                                                        add_empty_line(),
                                                                        content,
                                                                        add_empty_line(),
                                                                        self.DIVIDER_SECTIONS]
            )

        table = []
        for license in licenses:
            table.append(format_license(license))

        final_brief = get_final_brief_license(unique_license_types)

        return "\n".join(
            [ScreenReport.REPORT_BANNER] + announcements_section + [report_brief_section,
                                                                    add_empty_line(),
                                                                    self.DIVIDER_SECTIONS,
                                                                    format_long_text(
                                                                        click.style('LICENSES FOUND',
                                                                                bold=True, fg='yellow')),
                                                                    self.DIVIDER_SECTIONS,
                                                                    add_empty_line(),
                                                                    "\n".join(table),
                                                                    final_brief,
                                                                    add_empty_line(),
                                                                    self.DIVIDER_SECTIONS]
        )

    def render_announcements(self, announcements):
        return self.__build_announcements_section(announcements)


# coding=utf-8

""" Autor: Víctor García Carrera, victorgarciacarrera@gmail.com
	Descarga el contenido del buscador de google con un término
	de búsqueda concreto y guarda el NUMERO DE RESULTADOS

	v3.2	BUSCA TAMBIEN CON site:*.es para covid-19 y coronavirus
"""

import sys
import os
import errno
from math import *
from random import *

""" Ejemplo obtenido de: https://www.edureka.co/blog/web-scraping-with-python/ """

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
#from selenium.webdriver.common.keys import keys		#The Keys class provide keys in the keyboard like RETURN, F1, ALT etc.

from bs4 import BeautifulSoup		#Libreria bs4 version ultima BeautifulSoup4
import pandas as pd

import string
import time
from datetime import datetime
import numpy as np

# INTENTAR ThreadPoolExecutor
from concurrent.futures import ProcessPoolExecutor
# Para ver si procesos o threads: https://dev.to/rhymes/how-to-make-python-code-concurrent-with-3-lines-of-code-2fpe

POOLSIZE = 10

""" ### FALTA HACER LISTA DE DRIVERS (meter @|FIREFOX|@) +
	###		+ CALCULO DE RESULTADOS (estadisticas, valorar con desviacion respecto a la media...)
	### 	+ INSPECCIONAR/MEDIR + DATOS como tiempo de respuesta, enlaces (expresiones regulares)
"""

def main():

	global POOLSIZE

	###########################################################################
	#########		CONFIGURACIÓN DE LAS BÚSQUEDAS		#######################
	#########		driver, lista de BUSQUEDAS 			#######################
	###########################################################################

	""" LINEAS PARA DESHABILITAR EL CONTROL DE GOOGLE: "Chrome is being controlled by automated test software" """
	chrome_options = webdriver.ChromeOptions();
	chrome_options.add_argument('--headless');		# EJECUCION EN BACKGROUND
	# To fix execution in script
	chrome_options.add_argument('--no-sandbox');
	chrome_options.add_argument('--disable-dev-shm-usage');
	##

	chrome_options.add_experimental_option("excludeSwitches", ['enable-automation', 'disable-infobars']);

	driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options );
	# ,service_args=['--verbose', '--log-path=/tmp/chromedriver.log' )

	""" Lista con el numero de resultados por termino de busqueda """
	resultados = []
	resultados_groups = []
	## Lista con los términos de búsqueda
	busquedas = []
	busquedas2 = []
	## Listas NUEVAS con los términos de búsqueda (SITE:*.es)
	busquedas_site = []
	busquedas2_site = []
	## Lista con los términos agrupados para paralelizar mejor la búsqueda
	busquedas_groups = []
	busquedas_groups2 = []
	## Lista NUEVAS con los términos agrupados para paralelizar mejor la búsqueda (SITE:*.es)
	busquedas_groups_site = []
	busquedas_groups2_site = []

	"""busquedas = ["*.es"]"""
	""" Lista(array numpy) con las búsquedas a realizar en Google """

	###########################################################################
	###########################################################################
	#### PROBAR CON site:*.es 		IMP!!!! 	###############################
	busquedas = np.array( ["*.es", "covid-19 *.es", "crisis * covid-19 *.es", "calma * covid-19 *.es", "esperanza * covid-19 *.es" ,
					"pánico * covid-19 *.es", "miedo * covid-19 *.es", "ansiedad * covid-19 *.es", "terror * covid-19 *.es",
					"inseguridad * covid-19 *.es", "enfado * covid-19 *.es", "rabia * covid-19 *.es", "ira * covid-19 *.es" ,
					"alegría * covid-19 *.es", "tristeza * covid-19 *.es" , "sorpresa * covid-19 *.es", "alivio * covid-19 *.es",
					"desconfianza * covid-19 *.es", "incertidumbre * covid-19 *.es", "sanidad * covid-19 *.es", "aislamiento * covid-19 *.es",
					"cuarentena * covid-19 *.es", "solidaridad * covid-19 *.es", "cooperación * covid-19 *.es", "protección * covid-19 *.es",
					"irresponsable * covid-19 *.es", "polític* * covid-19 *.es", "polític* * irresponsable* * covid-19 *.es", "medic* * covid-19 *.es",
					"cura * covid-19 *.es", "abastecimiento * covid-19 *.es", "alimentos crisis * covid-19 *.es", "alimentos * covid-19 *.es",
					"aislamiento * covid-19 *.es", "memes * covid-19 *.es", "bromas * covid-19 *.es", "chistes * covid-19 *.es",
					"alarma * covid-19 *.es", "gratitud * covid-19 *.es", "aplausos * covid-19 *.es", "agradecimiento * covid-19 *.es",
					"vacuna * covid-19 *.es", "mortalidad * covid-19 *.es", "muerte * covid-19 *.es"] )

	# Gestionamos otra lista de términos de búsqueda, buscando coronavirus en vez de covid-19
	for term in busquedas:
		new_term = term.replace('covid-19', 'coronavirus')
		busquedas2.append(new_term)

		term_site = term.replace('*.es', 'site:*.es')
		busquedas_site.append(term_site)
		term_site2 = term_site.replace('covid-19', 'coronavirus')
		busquedas2_site.append(term_site2)

	#print(busquedas2)

	"""busquedas2 = np.array( ["*.es", "coronavirus *.es", "crisis * coronavirus *.es", "calma * coronavirus *.es", "esperanza * coronavirus *.es" ,
					"pánico * coronavirus *.es", "miedo * coronavirus *.es", "ansiedad * coronavirus *.es", "terror * coronavirus *.es",
					"inseguridad * coronavirus*.es", "enfado * coronavirus *.es", "rabia * coronavirus *.es", "ira * coronavirus *.es" ,
					"alegría * coronavirus *.es", "tristeza * coronavirus *.es" , "sorpresa * coronavirus *.es", "alivio * coronavirus *.es",
					"desconfianza * coronavirus *.es", "incertidumbre * coronavirus *.es", "sanidad * coronavirus *.es", "aislamiento * coronavirus *.es",
					"cuarentena * coronavirus *.es", "solidaridad * coronavirus *.es", "cooperación * coronavirus *.es", "protección * coronavirus *.es",
					"irresponsable * coronavirus *.es", "polític* * coronavirus *.es", "polític* * irresponsable* * coronavirus *.es", "medic* * coronavirus *.es",
					"cura * coronavirus *.es", "abastecimiento * coronavirus *.es", "alimentos crisis * coronavirus *.es", "alimentos * coronavirus *.es",
					"aislamiento * coronavirus *.es", "memes * coronavirus *.es", "bromas * coronavirus *.es", "chistes * coronavirus *.es",
					"alarma * coronavirus *.es", "gratitud * coronavirus *.es", "aplausos * coronavirus *.es", "agradecimiento * coronavirus *.es",
					"vacuna * coronavirus *.es", "mortalidad * coronavirus *.es", "muerte * coronavirus *.es"] )
	"""

	# REORGANIZAMOS LA LISTA DE BÚSQUEDA PARA AGRUPAR LOS TÉRMINOS EN FUNCION DE POOLSIZE!!!
	init_len = len(busquedas)
	#print(init_len)
	groups = ceil(init_len/POOLSIZE)		# Agrupamos los términos para minimizar los lanzamientos del pool que son costosos

	# EJEMPLO: len(busquedas)=40, POOLSIZE=10, groups=4
	"""		busquedas_groups = np.array_split(busquedas, groups)
	print busquedas_groups		"""

	# Recorremos la lista de búsquedas agrupando por terminos
	for pos in range(0,init_len):
		if pos%groups==0:
			terms = []
			terms2 = []
			terms_site = []
			terms2_site = []
		terms.append(busquedas[pos])
		terms2.append(busquedas2[pos])
		terms_site.append(busquedas_site[pos])
		terms2_site.append(busquedas2_site[pos])
		if pos%groups==(groups-1) or pos==(init_len-1):	# Hemos llenado un grupo de terminos
			busquedas_groups.append(terms)
			busquedas_groups2.append(terms2)
			busquedas_groups_site.append(terms_site)
			busquedas_groups2_site.append(terms2_site)

	# Obtemos el array de búsquedas con subarrays agrupados para mejorar la búsqueda
	#print(busquedas_groups)
	#print(busquedas_groups2)

	"""SECUENCIAL!!"""
	""" Seleccionamos uno a uno los términos a buscar para obtener su número de resultados """
	"""for termino in busquedas:
		res = buscar(termino)
		resultados.append(str(res))
		"""

	"""PARALELO!!!!"""

	#### Finalizada INICIALIZACION, pasamos a busqueda

	executor = ProcessPoolExecutor(POOLSIZE)

	###########################################################################
	#########		ESCRITURA DE DATOS EN FICHEROS		#######################
	###########################################################################

	ahora = datetime.now()

	nombre_dir_clasica = 'Busqueda_'+ str(ahora.day) + "-" + str(ahora.month) + "-" + str(ahora.year) + "CLASICA"
	nombre_dir_nueva = 'Busqueda_'+ str(ahora.day) + "-" + str(ahora.month) + "-" + str(ahora.year) + "NUEVA"

	## Creamos un directorio donde guardar los resultados de las búsquedas
	try:
		os.mkdir(nombre_dir_clasica)
		os.mkdir(nombre_dir_nueva)
	except OSError as e:
		if e.errno != errno.EEXIST:
			raise

	## x:0..2 BUSQUEDA CLÁSICA, x:3..4 BUSQUEDA CON SITE
	for x in range(4):
		if x==0:		# primera busqueda con busquedas_groups con covid-19
			busq = busquedas_groups
			name = "covid-19_"
			search = busquedas
		elif x==1:			# segunda busqueda con busquedas_groups2 con coronavirus
			busq = busquedas_groups2
			name = "coronavirus_"
			search = busquedas2
		elif x==2:			# tercera busqueda con busquedas_groups_site con covid-19
			busq = busquedas_groups_site
			name = "covid-19_"
			search = busquedas_site
		elif x==3:			# cuarta busqueda con busquedas_groups2_site con coronavirus
			busq = busquedas_groups2_site
			name = "coronavirus_"
			search = busquedas2_site
		else:
			print("ERROR switch de las 4 busquedas")

		resultados = []

		## Inicio TIME
		start_time = time.time()

		######		LANZAMOS LOS HILOS DE BUSQUEDAS 		######

		#timeout=None, chunksize=1000
		resultados_groups = list(executor.map(buscar, busq))

		## Tiempo de busqueda
		busqueda_time = time.time() - start_time
		busqueda_time = round(busqueda_time,2)

		for arr in resultados_groups:
			for res in arr:
				resultados.append(res)

		print("\n\nResultados: " + str(resultados))
		ahora = datetime.now()

		""" Escribimos en un fichero BUSQUEDA *.es: NUMERO DE RESULTADOS: 500"""
		if x<2:		# BUSQUEDAS CLÁSICAS
			nombre_dir = nombre_dir_clasica
			nombre_file = nombre_dir + "/" + name + "CLASICO_" + str(ahora.day) + "-" + str(ahora.month) + "-" + str(ahora.year) + "_v3" + ".txt"
		else:
			nombre_dir = nombre_dir_nueva
			nombre_file = nombre_dir + "/" + name + "NUEVA_" + str(ahora.day) + "-" + str(ahora.month) + "-" + str(ahora.year) + "_v3" + ".txt"

		"""if (ahora.hour < 14 and ahora.hour > 2):
			nombre += " Morning" + ".txt"
		else:
			nombre += " Noche" + ".txt"
		"""

		print(nombre_file)
		print("\n\nVIENE ESCRITURA!!!")
		## ESCRIBIMOS LOS FICHEROS
		f = open(nombre_file, "w+")
		f.write("***\tBuscador v3.2 \t Archivo con el número de resultados obtenidos por término de búsqueda en GOOGLE\t***")
		f.write("\n***\tFECHA: " + str(ahora) + "\t***\n\n")
		f.write("TÉRMINO DE BÚSQUEDA\t\tNÚMERO APROXIMADO DE RESULTADOS\n")

		for j in range(0, len(resultados)):
			linea = "\n" + search[j] + "\t\t" + str(resultados[j])
			f.write(linea)

		f.write("\n\nTIEMPO DE BUSQUEDA(en segundos): " + str(busqueda_time))

		f.close()

	# Cierra todas las ventanas de búsqueda y finaliza correctamente la sesión WebDriver
	driver.quit()

### FUNCION QUE RECIBE UNA LISTA DE TÉRMINOS Y LOS BUSCA EN GOOGLE
def buscar(terminos):

	#global driver

	res = []

	###### CONFIGURACIÓN DEL DRIVER ######

	""" LINEAS PARA DESHABILITAR EL CONTROL DE GOOGLE: "Chrome is being controlled by automated test software" """
	chrome_options = webdriver.ChromeOptions();
	chrome_options.add_argument('--headless');		# EJECUCION EN BACKGROUND
	# To fix execution in script
	chrome_options.add_argument('--no-sandbox');
	chrome_options.add_argument('--disable-dev-shm-usage');
	##

	chrome_options.add_experimental_option("excludeSwitches", ['enable-automation', 'disable-infobars']);

	driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options );
	# , service_args=['--verbose', '--log-path=/tmp/chromedriver.log'] )

	## BUSCAMOS LOS TÉRMINOS
	for termino in terminos:
		""" Creamos el link de búsqueda con el término correspondiente """
		## v3.2 CAMBIO A google.es!!!!
		link = "https://www.google.es/search?q=" + termino
		print("\n" + link)

		""" Establecemos un tiempo entre las búsquedas para evitar CAPTCHA de Google """
		## NOTA: (cambiar IP????) ###################
		wait = random()*2
		time.sleep(wait)

		""" Abrimos la URL con la búsqueda """
		""" CDE PARA EVITAR FALLO DE CONEXIONES!!!! """
		try:
			driver.get(link)
		except requests.exceptions.ConnectionError:
			buscar(terminos)		# Retry

		""" Buscamos por tags, en nuestro caso, queremos buscar el tag con <div id="result-stats"> """
		content = driver.page_source
		soup = BeautifulSoup(content, "lxml")
		RESULT = soup.find(id ="result-stats")

		""" Obtenemos del texto el número de resultados """
		resu = str(RESULT)
		print("\nRESULT: " + resu)

		""" buscamos el numero de resultados por la cadena de Aproximadamente """
		iniIndex = resu.find("Aproximadamente")
		""" Situamos el indice despues de Aproximadamente, donde va el numero """
		iniIndex += 16
		endIndex = resu.find("resultados")
		num = resu[iniIndex:endIndex]
		#print(num)
		res.append(str(num))

	""" Cerramos la pestaña abierta """
	driver.close()

	""" Devolvemos el número de resultados de buscar el termino """
	return res

if __name__ == '__main__':
	main()


from typing import Sequence, Tuple, Union
from dataclasses import dataclass
from scipy.integrate import odeint

import numpy as np
import logging

from dno.environment import EnvironmentModel

_logger = logging.getLogger(f'windy.model.{__name__}')

@dataclass
class WindyModel:
    v0: float
    pos0: np.array
    alpha: float
    mass: float

    env: EnvironmentModel
    verbose: Union[bool, int] = False

    v: np.ndarray = None
    run_time: float = None
    pos: np.ndarray = None

    @dataclass
    class ModelState:
        v: np.array
        pos: np.array
        time: float

    def __post_init__(self):
        self._log = logging.getLogger(f'{__name__}.{self.__class__.__name__}[{id(self)}]')
        if isinstance(self.verbose, bool):
            self.verbose = logging.DEBUG if self.verbose else logging.CRITICAL
        self._log.setLevel(logging.getLevelName(self.verbose))
        self.alpha = np.deg2rad(self.alpha)
        self.v0 = np.array([self.v0 * np.cos(self.alpha), 0, self.v0 * np.sin(self.alpha)])
        self.reset()

    def reset(self):
        self.v = self.v0
        self.pos = self.pos0
        self.run_time = 0

    # function that returns dy/dt
    def velocity_model(self, v: np.ndarray, time: np.ndarray):
        v_mod = np.linalg.norm(v)
        dvdt = np.array([
            -self.env.aerodynamic_coef.value / self.mass * v[0] * v_mod,
            -self.env.aerodynamic_coef.value / self.mass * v[1] * v_mod - self.env.g,
            -self.env.aerodynamic_coef.value / self.mass * v[2] * v_mod,
        ])
        return dvdt.ravel()

    def position_model(self, state: np.ndarray, time: np.ndarray):
        v = state[:3]
        v_mod = np.linalg.norm(v)
        dvdt = np.array([
            -self.env.aerodynamic_coef.value / self.mass * v[0] * v_mod,
            -self.env.aerodynamic_coef.value / self.mass * v[1] * v_mod - self.env.g,
            -self.env.aerodynamic_coef.value / self.mass * v[2] * v_mod,
        ]).ravel()
        print(dvdt)
        drdt = state[:3]
        print(drdt)
        dalldt = np.hstack((dvdt, drdt))
        return dalldt

    def position_model_alt(self, state: np.ndarray, time: np.ndarray):
        v = state[:3]
        v_mod = np.linalg.norm(v)
        dvdt = np.array([
            -self.env.aerodynamic_coef.value / self.mass * v[0] * v_mod,
            -self.env.aerodynamic_coef.value / self.mass * v[1] * v_mod - self.env.g,
            -self.env.aerodynamic_coef.value / self.mass * v[2] * v_mod,
        ]).ravel()
        drdt = state[:3] + self.env.winds.predict(state[4])
        dalldt = np.hstack((dvdt, drdt))
        return dalldt

    def solve_velocities(self, time: np.ndarray):
        return odeint(self.velocity_model, self.v0, time)

    def solve_positions(self, time: np.ndarray, wind: np.ndarray, v0: np.ndarray, pos0: np.ndarray):
        return odeint(self.position_model, np.hstack((np.asarray(v0) + np.asarray(wind), pos0)), time)

    def solve_positions_alt(self, time: np.ndarray, v0: np.ndarray, pos0: np.ndarray):
        return odeint(self.position_model_alt, np.hstack((np.asarray(v0), pos0)), time)

    def solve(self, target: np.ndarray):
        state = np.hstack((self.v0, self.pos0))
        last_state_stack = np.array((state, ))
        t_start = 0
        while state[4] > target[1]:
            t = np.linspace(t_start, t_start + 1, num=10)
            last_state_stack = self.solve_positions_alt(t, v0=state[:3], pos0=state[3:])
            state = last_state_stack[-1]
            t_start += 1
        starting_point = self.offset_for_target(target, state[3:])
        return starting_point

    @property
    def current_wind(self) -> np.array:
        return self.env.winds.predict(self.pos[1])

    @property
    def aerodynamic_acc(self) -> np.array:
        return -self.v * np.linalg.norm(self.v) * self.env.aerodynamic_coef.value / self.mass

    def step(self, dt: float):
        self._log.debug(f"Current position: {self.pos[1]:.2f}m above ground.")
        self._log.debug(f"Aerodynamic acc: {self.aerodynamic_acc}")
        self._log.debug(f"Winds: {self.current_wind}")
        self.v = np.asarray(self.v) + self.aerodynamic_acc * dt + dt * np.array([0, -self.env.g, 0])
        self._log.debug(f"Object's speed is: {self.v}")
        v_eff = self.current_wind + self.v
        self._log.debug(f"Effective speed is: {v_eff}")
        self.pos = self.pos + np.asarray(v_eff) * dt
        self._log.debug(f"Position is: {self.pos}")
        self.run_time += dt

    def offset_for_target(self, target: np.ndarray, position: np.ndarray) -> np.ndarray:
        drop_point = target - position + 2 * np.array(self.pos0)
        drop_point[1] = self.pos0[1]
        return drop_point

    def predict(self, target: np.ndarray, reset: bool = True, **run_kwargs) -> np.ndarray:
        if reset:
            self.reset()
        self.run(**run_kwargs)
        starting_point = self.offset_for_target(target, self.pos)
        return starting_point

    def score(self, starting_point: np.array, destination_point: np.array, reset: bool = True, **run_kwargs) -> Tuple[
        np.ndarray, float]:
        saved_pos0 = self.pos0
        try:
            self.pos0 = starting_point
            if reset:
                self.reset()
            self.run(**run_kwargs)
            landing_point = self.state.pos
            landing_point[1] = destination_point[1]
            return landing_point, np.linalg.norm(landing_point - destination_point)
        except Exception as e:
            self.pos0 = saved_pos0
            raise e
        finally:
            self.pos0 = saved_pos0

    @property
    def state(self) -> 'ModelState':
        return self.ModelState(v=self.v, pos=self.pos, time=self.run_time)

    def run(self, max_steps: int = None, dt: float = 0.01) -> Sequence['ModelState']:
        step = 0
        states = []
        while self.pos[1] > 0 and (max_steps is None or step < max_steps):
            self.step(dt)
            step += 1
            states.append(self.state)
            self._log.debug(f"State is: {self.state}")
        self._log.info(f"Final state is: {self.state}")
        if max_steps is not None and step >= max_steps:
            self._log.warning(f"WARN: stopped after maximum iterations: {step}")
        return states


from http import server
import streamlit as st
import pandas as pd

###################################
from st_aggrid import AgGrid
from st_aggrid.grid_options_builder import GridOptionsBuilder
from st_aggrid.shared import JsCode

###################################

from functionforDownloadButtons import download_button

###################################

def _max_width_():
    max_width_str = f"max-width: 1800px;"
    st.markdown(
        f"""
    <style>
    .reportview-container .main .block-container{{
        {max_width_str}
    }}
    </style>
    """,
        unsafe_allow_html=True,
    )

st.set_page_config(page_icon="🤝", page_title="Uploader")

st.image(
    "https://i.ibb.co/kHH7yvK/logo-include.png",
    width=200,
)

st.title("include.us")

uploaded_file = st.file_uploader(
    "",
    key="1",
    help="To activate 'wide mode', go to the hamburger menu > Settings > turn on 'wide mode'",
)

if uploaded_file is not None:
    st.success(
        f"""
            Upload successful!
            """
    )

else:
    st.info(
        f"""
            👆 Upload a .mp3 or .mp4 file for the data evaluation. What is a [.mp4?](https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab_channel=RickAstley)
            """
    )

    st.stop()

st.text("")

st.text("")


from nose.tools import (
    with_setup,
    assert_equal,
    assert_not_equal,
    assert_true,
    assert_not_in,
    assert_in,
)
from pylons import tmpl_context as c, app_globals as g
from webob import Request
from mock import patch, Mock
from datetime import datetime, timedelta

from ming.orm.ormsession import ThreadLocalORMSession
from ming.odm import session

from allura import model as M
from allura.lib import plugin
from allura.tests import decorators as td
from alluratest.controller import setup_basic_test, setup_global_objects, setup_functional_test

def setUp():
    setup_basic_test()
    ThreadLocalORMSession.close_all()
    setup_global_objects()

@with_setup(setUp)
def test_email_address():
    addr = M.EmailAddress(email='test_admin@domain.net',
                          claimed_by_user_id=c.user._id)
    ThreadLocalORMSession.flush_all()
    assert addr.claimed_by_user() == c.user
    addr2 = M.EmailAddress.create('test@domain.net')
    addr3 = M.EmailAddress.create('test_admin@domain.net')

    # Duplicate emails are allowed, until the email is confirmed
    assert addr3 is not addr

    assert addr2 is not addr
    assert addr2
    addr4 = M.EmailAddress.create('test@DOMAIN.NET')
    assert addr4 is not addr2

    assert addr is c.user.address_object('test_admin@domain.net')
    c.user.claim_address('test@DOMAIN.NET')
    assert 'test@domain.net' in c.user.email_addresses

@with_setup(setUp)
def test_email_address_lookup_helpers():
    addr = M.EmailAddress.create('TEST@DOMAIN.NET')
    nobody = M.EmailAddress.create('nobody@example.com')
    ThreadLocalORMSession.flush_all()
    assert_equal(addr.email, 'TEST@domain.net')

    assert_equal(M.EmailAddress.get(email='TEST@DOMAIN.NET'), addr)
    assert_equal(M.EmailAddress.get(email='TEST@domain.net'), addr)
    assert_equal(M.EmailAddress.get(email='test@domain.net'), None)
    assert_equal(M.EmailAddress.get(email=None), None)
    assert_equal(M.EmailAddress.get(email='nobody@example.com'), nobody)
    # invalid email returns None, but not nobody@example.com as before
    assert_equal(M.EmailAddress.get(email='invalid'), None)

    assert_equal(M.EmailAddress.find(dict(email='TEST@DOMAIN.NET')).all(), [addr])
    assert_equal(M.EmailAddress.find(dict(email='TEST@domain.net')).all(), [addr])
    assert_equal(M.EmailAddress.find(dict(email='test@domain.net')).all(), [])
    assert_equal(M.EmailAddress.find(dict(email=None)).all(), [])
    assert_equal(M.EmailAddress.find(dict(email='nobody@example.com')).all(), [nobody])
    # invalid email returns empty query, but not nobody@example.com as before
    assert_equal(M.EmailAddress.find(dict(email='invalid')).all(), [])

@with_setup(setUp)
def test_email_address_canonical():
    assert_equal(M.EmailAddress.canonical('nobody@EXAMPLE.COM'),
                 'nobody@example.com')
    assert_equal(M.EmailAddress.canonical('nobody@example.com'),
                 'nobody@example.com')
    assert_equal(M.EmailAddress.canonical('I Am Nobody <nobody@example.com>'),
                 'nobody@example.com')
    assert_equal(M.EmailAddress.canonical('  nobody@example.com\t'),
                 'nobody@example.com')
    assert_equal(M.EmailAddress.canonical('I Am@Nobody <nobody@example.com> '),
                 'nobody@example.com')
    assert_equal(M.EmailAddress.canonical(' No@body <no@body@example.com> '),
                 'no@body@example.com')
    assert_equal(M.EmailAddress.canonical('no@body@example.com'),
                 'no@body@example.com')
    assert_equal(M.EmailAddress.canonical('invalid'), None)

@with_setup(setUp)
def test_email_address_send_verification_link():
    addr = M.EmailAddress(email='test_admin@domain.net',
                          claimed_by_user_id=c.user._id)

    addr.send_verification_link()

    with patch('allura.tasks.mail_tasks.smtp_client._client') as _client:
        M.MonQTask.run_ready()
    return_path, rcpts, body = _client.sendmail.call_args[0]
    assert_equal(rcpts, ['test_admin@domain.net'])

@td.with_user_project('test-admin')
@with_setup(setUp)
def test_user():
    assert c.user.url() .endswith('/u/test-admin/')
    assert c.user.script_name .endswith('/u/test-admin/')
    assert_equal(set(p.shortname for p in c.user.my_projects()),
                 set(['test', 'test2', 'u/test-admin', 'adobe-1', '--init--']))
    # delete one of the projects and make sure it won't appear in my_projects()
    p = M.Project.query.get(shortname='test2')
    p.deleted = True
    ThreadLocalORMSession.flush_all()
    assert_equal(set(p.shortname for p in c.user.my_projects()),
                 set(['test', 'u/test-admin', 'adobe-1', '--init--']))
    u = M.User.register(dict(
        username='nosetest-user'))
    ThreadLocalORMSession.flush_all()
    assert_equal(u.private_project().shortname, 'u/nosetest-user')
    roles = g.credentials.user_roles(
        u._id, project_id=u.private_project().root_project._id)
    assert len(roles) == 3, roles
    u.set_password('foo')
    provider = plugin.LocalAuthenticationProvider(Request.blank('/'))
    assert provider._validate_password(u, 'foo')
    assert not provider._validate_password(u, 'foobar')
    u.set_password('foobar')
    assert provider._validate_password(u, 'foobar')
    assert not provider._validate_password(u, 'foo')

@with_setup(setUp)
def test_user_project_creates_on_demand():
    u = M.User.register(dict(username='foobar123'), make_project=False)
    ThreadLocalORMSession.flush_all()
    assert not M.Project.query.get(shortname='u/foobar123')
    assert u.private_project()
    assert M.Project.query.get(shortname='u/foobar123')

@with_setup(setUp)
def test_user_project_already_deleted_creates_on_demand():
    u = M.User.register(dict(username='foobar123'), make_project=True)
    p = M.Project.query.get(shortname='u/foobar123')
    p.deleted = True
    ThreadLocalORMSession.flush_all()
    assert not M.Project.query.get(shortname='u/foobar123', deleted=False)
    assert u.private_project()
    ThreadLocalORMSession.flush_all()
    assert M.Project.query.get(shortname='u/foobar123', deleted=False)

@with_setup(setUp)
def test_user_project_does_not_create_on_demand_for_disabled_user():
    u = M.User.register(
        dict(username='foobar123', disabled=True), make_project=False)
    ThreadLocalORMSession.flush_all()
    assert not u.private_project()
    assert not M.Project.query.get(shortname='u/foobar123')

@with_setup(setUp)
def test_user_project_does_not_create_on_demand_for_anonymous_user():
    u = M.User.anonymous()
    ThreadLocalORMSession.flush_all()
    assert not u.private_project()
    assert not M.Project.query.get(shortname='u/anonymous')
    assert not M.Project.query.get(shortname='u/*anonymous')

@with_setup(setUp)
@patch('allura.model.auth.log')
def test_user_by_email_address(log):
    u1 = M.User.register(dict(username='abc1'), make_project=False)
    u2 = M.User.register(dict(username='abc2'), make_project=False)
    addr1 = M.EmailAddress(email='abc123@abc.me', confirmed=True,
                           claimed_by_user_id=u1._id)
    addr2 = M.EmailAddress(email='abc123@abc.me', confirmed=True,
                           claimed_by_user_id=u2._id)
    # both users are disabled
    u1.disabled, u2.disabled = True, True
    ThreadLocalORMSession.flush_all()
    assert_equal(M.User.by_email_address('abc123@abc.me'), None)
    assert_equal(log.warn.call_count, 0)

    # only u2 is active
    u1.disabled, u2.disabled = True, False
    ThreadLocalORMSession.flush_all()
    assert_equal(M.User.by_email_address('abc123@abc.me'), u2)
    assert_equal(log.warn.call_count, 0)

    # both are active
    u1.disabled, u2.disabled = False, False
    ThreadLocalORMSession.flush_all()
    assert_in(M.User.by_email_address('abc123@abc.me'), [u1, u2])
    assert_equal(log.warn.call_count, 1)

    # invalid email returns None, but not user which claimed
    # nobody@example.com as before
    nobody = M.EmailAddress(email='nobody@example.com', confirmed=True,
                            claimed_by_user_id=u1._id)
    ThreadLocalORMSession.flush_all()
    assert_equal(M.User.by_email_address('nobody@example.com'), u1)
    assert_equal(M.User.by_email_address('invalid'), None)

@with_setup(setUp)
def test_project_role():
    role = M.ProjectRole(project_id=c.project._id, name='test_role')
    M.ProjectRole.by_user(c.user, upsert=True).roles.append(role._id)
    ThreadLocalORMSession.flush_all()
    roles = g.credentials.user_roles(
        c.user._id, project_id=c.project.root_project._id)
    roles_ids = [r['_id'] for r in roles]
    roles = M.ProjectRole.query.find({'_id': {'$in': roles_ids}})
    for pr in roles:
        assert pr.display()
        pr.special
        assert pr.user in (c.user, None, M.User.anonymous())

@with_setup(setUp)
def test_default_project_roles():
    roles = dict(
        (pr.name, pr)
        for pr in M.ProjectRole.query.find(dict(
            project_id=c.project._id)).all()
        if pr.name)
    assert 'Admin' in roles.keys(), roles.keys()
    assert 'Developer' in roles.keys(), roles.keys()
    assert 'Member' in roles.keys(), roles.keys()
    assert roles['Developer']._id in roles['Admin'].roles
    assert roles['Member']._id in roles['Developer'].roles

    # There're 1 user assigned to project, represented by
    # relational (vs named) ProjectRole's
    assert len(roles) == M.ProjectRole.query.find(dict(
        project_id=c.project._id)).count() - 1

@with_setup(setUp)
def test_email_address_claimed_by_user():
    addr = M.EmailAddress(email='test_admin@domain.net',
                          claimed_by_user_id=c.user._id)
    c.user.disabled = True
    ThreadLocalORMSession.flush_all()
    assert addr.claimed_by_user() is None

@td.with_user_project('test-admin')
@with_setup(setUp)
def test_user_projects_by_role():
    assert_equal(set(p.shortname for p in c.user.my_projects()),
                 set(['test', 'test2', 'u/test-admin', 'adobe-1', '--init--']))
    assert_equal(set(p.shortname for p in c.user.my_projects_by_role_name('Admin')),
                 set(['test', 'test2', 'u/test-admin', 'adobe-1', '--init--']))
    # Remove admin access from c.user to test2 project
    project = M.Project.query.get(shortname='test2')
    admin_role = M.ProjectRole.by_name('Admin', project)
    developer_role = M.ProjectRole.by_name('Developer', project)
    user_role = M.ProjectRole.by_user(c.user, project=project, upsert=True)
    user_role.roles.remove(admin_role._id)
    user_role.roles.append(developer_role._id)
    ThreadLocalORMSession.flush_all()
    g.credentials.clear()
    assert_equal(set(p.shortname for p in c.user.my_projects()),
                 set(['test', 'test2', 'u/test-admin', 'adobe-1', '--init--']))
    assert_equal(set(p.shortname for p in c.user.my_projects_by_role_name('Admin')),
                 set(['test', 'u/test-admin', 'adobe-1', '--init--']))

@td.with_user_project('test-admin')
@with_setup(setUp)
def test_user_projects_unnamed():
    """
    Confirm that spurious ProjectRoles associating a user with
    a project to which they do not belong to any named group
    don't cause the user to count as a member of the project.
    """
    sub1 = M.Project.query.get(shortname='test/sub1')
    M.ProjectRole(
        user_id=c.user._id,
        project_id=sub1._id)
    ThreadLocalORMSession.flush_all()
    project_names = [p.shortname for p in c.user.my_projects()]
    assert_not_in('test/sub1', project_names)
    assert_in('test', project_names)

@patch.object(g, 'user_message_max_messages', 3)
def test_check_sent_user_message_times():
    user1 = M.User.register(dict(username='test-user'), make_project=False)
    time1 = datetime.utcnow() - timedelta(minutes=30)
    time2 = datetime.utcnow() - timedelta(minutes=45)
    time3 = datetime.utcnow() - timedelta(minutes=70)
    user1.sent_user_message_times = [time1, time2, time3]
    assert user1.can_send_user_message()
    assert_equal(len(user1.sent_user_message_times), 2)
    user1.sent_user_message_times.append(
        datetime.utcnow() - timedelta(minutes=15))
    assert not user1.can_send_user_message()

@td.with_user_project('test-admin')
@with_setup(setUp)
def test_user_track_active():
    # without this session flushing inside track_active raises Exception
    setup_functional_test()
    c.user = M.User.by_username('test-admin')

    assert_equal(c.user.last_access['session_date'], None)
    assert_equal(c.user.last_access['session_ip'], None)
    assert_equal(c.user.last_access['session_ua'], None)

    req = Mock(headers={'User-Agent': 'browser'}, remote_addr='addr')
    c.user.track_active(req)
    c.user = M.User.by_username(c.user.username)
    assert_not_equal(c.user.last_access['session_date'], None)
    assert_equal(c.user.last_access['session_ip'], 'addr')
    assert_equal(c.user.last_access['session_ua'], 'browser')

    # ensure that session activity tracked with a whole-day granularity
    prev_date = c.user.last_access['session_date']
    c.user.track_active(req)
    c.user = M.User.by_username(c.user.username)
    assert_equal(c.user.last_access['session_date'], prev_date)
    yesterday = datetime.utcnow() - timedelta(1)
    c.user.last_access['session_date'] = yesterday
    session(c.user).flush(c.user)
    c.user.track_active(req)
    c.user = M.User.by_username(c.user.username)
    assert_true(c.user.last_access['session_date'] > yesterday)

    # ...or if IP or User Agent has changed
    req.remote_addr = 'new addr'
    c.user.track_active(req)
    c.user = M.User.by_username(c.user.username)
    assert_equal(c.user.last_access['session_ip'], 'new addr')
    assert_equal(c.user.last_access['session_ua'], 'browser')
    req.headers['User-Agent'] = 'new browser'
    c.user.track_active(req)
    c.user = M.User.by_username(c.user.username)
    assert_equal(c.user.last_access['session_ip'], 'new addr')
    assert_equal(c.user.last_access['session_ua'], 'new browser')

@with_setup(setUp)
def test_user_index():
    c.user.email_addresses = ['email1', 'email2']
    c.user.set_pref('email_address', 'email2')
    idx = c.user.index()
    assert_equal(idx['id'], c.user.index_id())
    assert_equal(idx['title'], 'User test-admin')
    assert_equal(idx['type_s'], 'User')
    assert_equal(idx['username_s'], 'test-admin')
    assert_equal(idx['email_addresses_t'], 'email1 email2')
    assert_equal(idx['email_address_s'], 'email2')
    assert_in('last_password_updated_dt', idx)
    assert_equal(idx['disabled_b'], False)
    assert_in('results_per_page_i', idx)
    assert_in('email_format_s', idx)
    assert_in('disable_user_messages_b', idx)
    assert_equal(idx['display_name_t'], 'Test Admin')
    assert_equal(idx['sex_s'], 'Unknown')
    assert_in('birthdate_dt', idx)
    assert_in('localization_s', idx)
    assert_in('timezone_s', idx)
    assert_in('socialnetworks_t', idx)
    assert_in('telnumbers_t', idx)
    assert_in('skypeaccount_s', idx)
    assert_in('webpages_t', idx)
    assert_in('skills_t', idx)
    assert_in('last_access_login_date_dt', idx)
    assert_in('last_access_login_ip_s', idx)
    assert_in('last_access_login_ua_t', idx)
    assert_in('last_access_session_date_dt', idx)
    assert_in('last_access_session_ip_s', idx)
    assert_in('last_access_session_ua_t', idx)
    # provided bby auth provider
    assert_in('user_registration_date_dt', idx)

@with_setup(setUp)
def test_user_index_none_values():
    c.user.email_addresses = [None]
    c.user.set_pref('telnumbers', [None])
    c.user.set_pref('webpages', [None])
    idx = c.user.index()
    assert_equal(idx['email_addresses_t'], '')
    assert_equal(idx['telnumbers_t'], '')
    assert_equal(idx['webpages_t'], '')


from typing import Callable, Tuple

import torch
from torch.nn import functional as F

from src.fwdgrad.activation import softmax
from src.fwdgrad.utils import clamp_probs

def _xent(x: torch.Tensor, t: torch.Tensor, num_classes: int = 10) -> torch.Tensor:
    """Compute cross-entropy loss.

    Args:
        x (torch.Tensor): Output of the model.
        t (torch.Tensor): Targets.
        num_classes (int, optional): Maximum number of classes. Defaults to 10.

    Returns:
        torch.Tensor: Cross-entropy loss.
    """
    y = clamp_probs(softmax(x))
    logy = -torch.log(y)
    loss = torch.mean(torch.sum(logy * F.one_hot(t, num_classes), dim=1))
    return loss

def xent(
    model: torch.nn.Module, x: torch.Tensor, t: torch.Tensor, num_classes: int = 10
) -> torch.Tensor:
    """Cross-entropy loss. Given a pytorch model, it computes the cross-entropy loss.

    Args:
        model (torch.nn.Module): PyTorch model.
        x (torch.Tensor): Input tensor for the PyTorch model.
        t (torch.Tensor): Targets.
        num_classes (int, optional): Maximum number of classes. Defaults to 10.

    Returns:
        torch.Tensor: Cross-entropy loss.
    """
    y = model(x)
    return _xent(y, t, num_classes)

def functional_xent(
    params: Tuple[torch.nn.Parameter, ...],
    model: Callable[[Tuple[torch.nn.Parameter, ...], torch.Tensor], torch.Tensor],
    x: torch.Tensor,
    t: torch.Tensor,
    num_classes: int = 10,
) -> torch.Tensor:
    """Functional cross-entropy loss. Given a functional version of a pytorch model, which can be obtained with
    `fmodel, params = functorch.make_functional(model)`, it computes the cross-entropy loss.

    Args:
        params (Tuple[torch.nn.Parameter, ...]): Model parameters obtained by `fmodel, params = fc.make_functional(model)`.
        model (Callable[[Tuple[torch.nn.Parameter, ...], torch.Tensor], torch.Tensor]): Functional version of a pytorch model,
            obtained by fmodel, `params = fc.make_functional(model)`
        x (torch.Tensor): Input tensor for the PyTorch model.
        t (torch.Tensor): Targets.
        num_classes (int, optional): Maximum number of classes. Defaults to 10.

    Returns:
        torch.Tensor: Cross-entropy loss.
    """
    y = model(params, x)
    return _xent(y, t, num_classes)


import json

CAMINHO_JSON = 'aula127.json'

class Pessoa :
    def __init__(self, nome, idade):
        self.nome = nome
        self.idade = idade

p1= Pessoa('joao', 33)
p2= Pessoa('joana', 23)
p3= Pessoa('maria', 13)
bd= [vars(p1), p2.__dict__, vars(p3)]

def fazer_dump():
    with open(CAMINHO_JSON, 'w') as arquivo:
        json.dump(bd, arquivo, ensure_ascii=False, indent=2)

if __name__ == '__main__':
    print('ele e o main')
    fazer_dump()


# -*- coding: utf-8 -*-
"""
Created on Thu Mar  2 01:57:23 2023

@author: atver
"""

import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from sklearn.metrics import f1_score

class vid_Model(nn.Module):
    def __init__(self, clip_len, device, RL=False, drop = 0):
        super().__init__()
        self.clip_len = clip_len
        self.mname = "vid_Model_" + str(self.clip_len)

        self.gru = nn.GRU(input_size=1280, hidden_size=8, batch_first=True)
        self.dense1 = nn.Linear(8*clip_len, 10)
        self.dense2 = nn.Linear(10, 6)
        self.device = device

    def forward(self, x):
        #print("shape x ", x.shape)
        vid_fts, sensor_fts = x[:,:,:1280], x[:,:,1280:]
        vid_fts = vid_fts.to(device = self.device, dtype = torch.float32)
        sensor_fts = torch.squeeze(sensor_fts)
        #print("shape vid_fts ", vid_fts.shape)
        #print("shape sensor_fts ", sensor_fts.shape)
        #vid_fts, sensor_fts = torch.split(x, [1280,36],dim=1) # dim0 = batch
        # y = torch.permute(vid_fts,(0,2,1))
        y, _ = self.gru(vid_fts) #
        y = y.reshape(-1, self.gru.hidden_size*(1+self.gru.bidirectional)*self.clip_len) # Reshape
        y = self.dense1(y)
        y = self.dense2(y)
        #print("shape y ", y.shape)
        # y = self.softmax(y) # Present in cross entropy loss already
        return y

# model = vid_finalstate_Model()

class sensor_Model(nn.Module):
    def __init__(self, clip_len, device, RL=False, drop=0):
        super().__init__()
        self.clip_len = clip_len
        self.mname = "sensor_Model_" + str(self.clip_len)
        self.gru = nn.GRU(input_size=36, hidden_size=8, batch_first=True)
        self.dense1 = nn.Linear(8*clip_len, 10)
        self.dense2 = nn.Linear(10, 6)
        self.device = device

    def forward(self, x):
        vid_fts, sensor_fts = x[:,:,:1280], x[:,:,1280:]
        vid_fts = vid_fts.to(device = self.device, dtype = torch.float32)
        sensor_fts = sensor_fts.to(device = self.device, dtype = torch.float32)
        y, _ = self.gru(sensor_fts)
        y = y.reshape(-1, self.gru.hidden_size*(1+self.gru.bidirectional)*self.clip_len) # Reshape
        y = self.dense1(y)
        y = self.dense2(y)
        return y

class combineEarly(nn.Module):

    def __init__(self, clip_len, device, RL = False, drop = 0):
        super().__init__()
        self.mname = "combineEarly_" + str(clip_len)
        if RL:
            self.mname = "RL_combineEarly_" + str(clip_len)
        NUM_FEATURES = 1280 + 36  # frame features + 36 kinematic
        RNN_OUT = 64 #32
        NUM_TARGETS = 6
        bi = True
        self.clip_len = clip_len
        self.device = device
        self.RL = RL
        if RL:
            self.dense0 = nn.Linear(NUM_FEATURES,NUM_FEATURES)
            self.leaky0 = nn.LeakyReLU()
        self.lstm = nn.LSTM(input_size=NUM_FEATURES, hidden_size=RNN_OUT, bidirectional=bi, batch_first=True)
        self.dropout = torch.nn.Dropout(p=drop)
        self.dense1 = nn.Linear((1+bi)*RNN_OUT,128,device=device) #(2*(1+bi)*RNN_OUT)
        self.leaky1 = nn.LeakyReLU()
        self.dense2 = nn.Linear(128,64,device=device)
        self.tanh2 = nn.Tanh()
        self.dense3 = nn.Linear(64,NUM_TARGETS,device=device)
        self.leaky3 = nn.LeakyReLU()

    def forward(self, x):
        fts = x.to(device = self.device, dtype = torch.float32)
        if self.RL:
            fts = self.dense0(fts)
            fts = self.leaky0(fts)
        # print("fts ", fts.shape)
        _, (final_bft, _) = self.lstm(fts)
        # print("final_bft ", final_bft.shape) # (D*num_layers, N, Hout)   [2*1, batch12, 64]
        final_bft = torch.permute(final_bft, (1,0,2)) # final_bft = N,D∗num_layers,H_out
        final_bft = final_bft.reshape(final_bft.shape[0], -1) # final_v = N,D∗num_layers*H_out
        # print("final_bft ", final_bft.shape) # final_v = N,D∗num_layers*H_out
        output = self.dropout(final_bft)
        output = self.dense1(output)
        output = self.leaky1(output)
        # print("output1 ", output.shape)
        output = self.dense2(output)
        output = self.tanh2(output)
        # print("output2 ", output.shape)
        output = self.dense3(output)
        output = self.leaky3(output)
        #print("output3 ", output.shape)
        return output

class combineLate(nn.Module):
    def __init__(self, clip_len, device, RL=False, drop = 0):
        super().__init__()
        self.mname = "combineLate_" + str(clip_len)
        if RL:
            self.mname = "RL_combineLate_" + str(clip_len)
        bi = True
        NUM_FEATURES_VIDEO = 1280
        NUM_FEATURES_KINEMATIC = 36
        NUM_TARGETS = 6
        RNN_OUT = 32
        self.clip_len = clip_len
        self.device = device
        self.RL = RL
        if RL:
            self.dense0v = nn.Linear(NUM_FEATURES_VIDEO,NUM_FEATURES_VIDEO)
            self.leaky0v = nn.LeakyReLU()
            self.dense0k = nn.Linear(NUM_FEATURES_KINEMATIC,NUM_FEATURES_KINEMATIC)
            self.leaky0k = nn.LeakyReLU()
        self.lstm_video =     nn.LSTM(input_size=NUM_FEATURES_VIDEO,     hidden_size=RNN_OUT, batch_first=True, bidirectional=bi)# only when num_layer>1 dropout = .2
        self.lstm_kinematic = nn.LSTM(input_size=NUM_FEATURES_KINEMATIC, hidden_size=RNN_OUT, batch_first=True, bidirectional=bi)
        self.dropoutv = torch.nn.Dropout(p=drop)
        self.dropoutk = torch.nn.Dropout(p=drop)
        self.dense1 = nn.Linear(2*(1+bi)*RNN_OUT,128,device=device) #(2*(1+bi)*RNN_OUT)
        self.leaky1 = nn.LeakyReLU()
        self.dense2 = nn.Linear(128,64,device=device)
        self.tanh2 = nn.Tanh()
        self.dense3 = nn.Linear(64,NUM_TARGETS,device=device)
        self.leaky3 = nn.LeakyReLU()

    def forward(self, x):
        vid_fts, sensor_fts = x[:,:,:1280], x[:,:,1280:]

        vid_fts = vid_fts.to(device = self.device, dtype = torch.float32)
        sensor_fts = sensor_fts.to(device = self.device, dtype = torch.float32)
        #print("vid_fts ",vid_fts.shape)
        #print("sensor_fts ", sensor_fts.shape)
        if self.RL:
            vid_fts = self.dense0v(vid_fts)
            vid_fts = self.leaky0v(vid_fts)
            sensor_fts = self.dense0k(sensor_fts)
            sensor_fts = self.leaky0k(sensor_fts)

        _, (final_v, _) = self.lstm_video(vid_fts)
        _, (final_s, _) = self.lstm_kinematic(sensor_fts)

        #print("final_v ", final_v.shape) # (D*num_layers, N, Hout)
        #print("final_s ", final_s.shape) # [2*1, batch12, 32]
        final_v = torch.permute(final_v, (1,0,2)) # final_v = N,D∗num_layers,H_out
        final_s = torch.permute(final_s, (1,0,2))
        final_v = final_v.reshape(final_v.shape[0], -1) # final_v = N,D∗num_layers*H_out
        final_s = final_s.reshape(final_s.shape[0], -1)
        #print("final_v ", final_v.shape) # (D*num_layers, N, Hout)
        #print("final_s ", final_s.shape) # [2*1, batch12, 32]
        final_v = self.dropoutv(final_v)
        final_s = self.dropoutk(final_s)
        combined_tensor = torch.concat([final_v, final_s], dim=1).float()
        #print("combined_tensor ", combined_tensor.shape)
        output = self.dense1(combined_tensor)
        output = self.leaky1(output)
        #print("output1 ", output.shape)
        output = self.dense2(output)
        output = self.tanh2(output)
        #print("output2 ", output.shape)
        output = self.dense3(output)
        output = self.leaky3(output)
        #print("output3 ", output.shape)
        return output

def train(dataloader, model, loss_fn, optimizer, device):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    model.train()
    avgb_loss, correct = 0, 0
    for batch, (X, y) in enumerate(dataloader):
        X, y = X.to(device, dtype = torch.float32), y.argmax(1).to(device, dtype = torch.long)
        y=torch.reshape(y, (-1,))
        # Compute prediction error
        pred = model(X)
        pred = pred.to(device, dtype = torch.float32)
        # print("pred type ", pred.dtype)
        # print("y(target) shpae and type ", y.shape, y.dtype)
        loss = loss_fn(pred, y) # target for cross entropy is the index
        avgb_loss += loss.item()
        correct += (pred.argmax(1) == y).sum().item()

        # Backpropagation
        optimizer.zero_grad(set_to_none=True)
        loss.backward()
        optimizer.step()

        #if batch % 100 == 0:
            #loss, current = loss.item(), (batch + 1) * len(X)
            # print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")
    # Return the metrics for epoch to be logged    Top k categorical?
    avgb_loss /= num_batches
    correct /= size
    print(f"Train Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {avgb_loss:>8f} \n")
    return model, correct, avgb_loss

def validate(dataloader, model, loss_fn, device, last=0):
    # used for validation and test
    test_mode = False
    if dataloader.dataset.group.lower() == "test":
        test_mode = True
    with torch.no_grad():
        size = len(dataloader.dataset)
        num_batches = len(dataloader)
        model.eval()
        test_loss, correct = 0, 0
        batch = 0
        pred_list = []
        y_list = []
        for X, y in dataloader:
            X, y = X.to(device, dtype = torch.float32), y.argmax(1).to(device, dtype = torch.long)
            y=torch.reshape(y, (-1,))
            # Compute prediction error
            pred = model(X)
            pred = pred.to(device, dtype = torch.float32)
            # if test_mode or last:
            pred_list += pred.argmax(1).tolist()
            y_list += y.tolist()
            try:
                test_loss += loss_fn(pred.to(device, dtype = torch.float32), y).item()
            except:
                print("in batch# ", batch)
                print("validate pred size ", pred.shape)
                print("validate target y size ", y.shape)
                print("fold ",dataloader.dataset.fold)
                print("size alllabs ", dataloader.dataset.alllabs.shape)
                print("size allvids ", dataloader.dataset.allvids.shape)
                print("size allsens ", dataloader.dataset.allsens.shape)
                print("problem batch y: ", y[dataloader.batch_size*batch:])
            correct += (pred.argmax(1) == y).sum().item()
            batch += 1
    test_loss /= num_batches
    correct /= size
    f1_v = f1_score(y_list,pred_list,average='macro') # f1 macro of validation
    if test_mode:
        print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f}, F1 score: {f1_v:>8f}\n")
    else:
        print(f"Validation Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f}, F1 score: {f1_v:>8f}\n")
    if test_mode or last:
        save_name = "cm_{}_{}_fold{}.png".format(model.mname,dataloader.dataset.group,dataloader.dataset.fold)
        save_cm(y_list, pred_list, save_name)

    return correct, test_loss, y_list, pred_list

def save_cm(y_list, pred_list, save_name):
    ConfusionMatrixDisplay.from_predictions(y_list, pred_list, normalize = "true", display_labels=["G"+str(i) for i in range(6)], cmap = mpl.colormaps['RdYlGn'])
    plt.title(save_name)
    plt.savefig(save_name)
    plt.close()


import pandas as pd
from pathlib import Path
import pandas as pd
from top2vec import Top2Vec
import logging
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer

# Customize logger
#############################################################################################
logger = logging.getLogger('Train sentence-bert')
logger.setLevel(logging.INFO)
sh = logging.StreamHandler()
sh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(sh)
#############################################################################################

PATH_TO_DATA = Path('data')
INDATA = 'meta_prop_sou.pkl'
N_TOPICS=32 #Number of topics

df=pd.read_pickle(PATH_TO_DATA / INDATA)
df=df.set_index('dok_id') # Set correct index

logger.info(f'Loaded {df.shape[0]} documents')

# Load model
sentence_model = SentenceTransformer('KBLab/sentence-bert-swedish-cased').encode
# Load tokenizer

tokenizer = AutoTokenizer.from_pretrained('KBLab/sentence-bert-swedish-cased').tokenize
model = Top2Vec(df['titel'].values, document_ids=df.index.to_list(), split_documents=False, embedding_model=sentence_model, use_embedding_model_tokenizer=True, tokenizer=tokenizer, workers=8)

model_path=r"models\Modell_sbertKB_titel.mod"

# Reduce number of topics to N_TOPICS
logger.info('Reduce number of topics')
model.hierarchical_topic_reduction(N_TOPICS)

model.save(model_path)

logger.info('Done!')
logger.info(f'Model saved to {model_path}')
logger.info(f'Metadata can be found in: {str(PATH_TO_DATA / INDATA)}')


# 实现PCA算法实现手写字体识别，要求：
# 1、实现手写数字数据集的降维；
# 2、比较两个模型（64维和10维）的准确率；
# 3、对两个模型分别进行10次10折交叉验证，绘制评分对比曲线。

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

# 加载手写数字数据集
digits = load_digits()
X = digits.data
y = digits.target

# 定义PCA模型和逻辑回归模型
pca64 = PCA(n_components=64)
pca10 = PCA(n_components=10)
logreg = LogisticRegression(solver='liblinear', max_iter=100)

# 定义Pipeline，将PCA和逻辑回归模型串联起来
model64 = Pipeline([('scaler', StandardScaler()), ('pca', pca64), ('logreg', logreg)])
model10 = Pipeline([('scaler', StandardScaler()), ('pca', pca10), ('logreg', logreg)])

# 1. 手写数字数据集的降维
X64 = pca64.fit_transform(X)
X10 = pca10.fit_transform(X)

# 2. 比较两个模型的准确率
accuracy64 = np.mean(cross_val_score(model64, X, y, cv=10))
accuracy10 = np.mean(cross_val_score(model10, X, y, cv=10))
print("64维模型准确率：", accuracy64)
print("10维模型准确率：", accuracy10)

# 3. 对两个模型进行10次10折交叉验证，并绘制评分对比曲线
kfold = StratifiedKFold(n_splits=10)

scores64 = []
scores10 = []

for train_index, test_index in kfold.split(X, y):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

    model64.fit(X_train, y_train)
    score64 = model64.score(X_test, y_test)
    scores64.append(score64)

    model10.fit(X_train, y_train)
    score10 = model10.score(X_test, y_test)
    scores10.append(score10)

# 绘制评分对比曲线
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.figure(figsize=(10, 6))
plt.plot(range(1, 11), scores64, label='64维模型')
plt.plot(range(1, 11), scores10, label='10维模型')
plt.xlabel('Fold')
plt.ylabel('Accuracy')
plt.title('Cross-validation Scores')
plt.legend()
plt.show()


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

from django.conf.urls import patterns

urlpatterns = patterns('home_application.views',
	# app列表，默认为主页
    (r'^$', 'applist'),
    # 连接paas数据库配置页
    (r'^setting/$', 'setting'),
    # 配置用户app权限页
    (r'^app_permission/$', 'app_permission'),
    # 删除数据库配置
    (r'^del_db/$', 'del_db'),
    # 删除数据库配置
    (r'^return_result_b/$', 'return_result_b'),
    # 删除用户
    (r'^del_users/$', 'del_users'),
    # 添加用户
    (r'^add_users/$', 'add_users'),
    # 从paas同步数据
    (r'^test/$', 'test'),
    (r'^students/$','students'),
    (r'^return_data/$','return_data'),

    (r'^return_forbidden/$','return_forbidden')
)


import argparse

from dash import ALL, Dash, dcc, html, MATCH, no_update, Input, Output
import pandas
import plotly.express as px
import plotly.graph_objects as go

app = Dash(__name__)
dataframes = {}
series_counter = 0

def create_series_layout(index=None, dataframe_names=None, default_dataframe=None):
    global series_counter
    if index is None:
        index = series_counter
        series_counter += 1

    if dataframe_names is None:
        dataframe_names = []

    if default_dataframe is None:
        columns = []
    else:
        columns = dataframes[default_dataframe].columns

    return html.Div(children=[
        dcc.Dropdown(id={'type': 'series-dataframe', 'index': index},
                     options=dataframe_names, value=default_dataframe),
        dcc.Dropdown(id={'type': 'series-x', 'index': index},
                     options=columns),
        dcc.Dropdown(id={'type': 'series-y', 'index': index},
                     options=columns),
        dcc.Checklist(id={'type': 'series-options', 'index': index},
                      options=['scatter', 'line'], value=['scatter'])
    ])

def init_app(filenames):
    global series_counter
    series_layouts = []
    for i, filename in enumerate(filenames):
        dataframes[filename] = pandas.read_csv(filename)
        series_layouts.append(create_series_layout(series_counter + i, filenames, filename))

    series_counter = i

    app.layout = html.Div(children=[
        html.Div(id='series-div', children=series_layouts),
        dcc.Graph(id='graph', config={'scrollZoom': True})
    ])
    return app

@app.callback(
    Output({'type': 'series-x', 'index': MATCH}, 'options'),
    Output({'type': 'series-y', 'index': MATCH}, 'options'),
    Input({'type': 'series-dataframe', 'index': MATCH}, 'value')
)
def update_series_dropdowns(dataframe):
    if dataframe is None:
        return ((), ())
    else:
        return (dataframes[dataframe].columns,) * 2

@app.callback(
    Output('graph', 'figure'),
    Input({'type': 'series-dataframe', 'index': ALL}, 'value'),
    Input({'type': 'series-x', 'index': ALL}, 'value'),
    Input({'type': 'series-y', 'index': ALL}, 'value'),
    Input({'type': 'series-options', 'index': ALL}, 'value')
)
def update_figure(dataframe, x, y, options):
    figure = go.Figure()
    for index, (dataframe, x, y, options) in enumerate(zip(dataframe, x, y, options)):
        if dataframe is None or (x is None and y is None):
            continue

        if options is None:
            options = []

        color = px.colors.qualitative.Plotly[index]

        if 'line' in options:
            figure.add_traces(
                list(
                    px.line(
                        dataframes[dataframe],
                        x=x,
                        y=y,
                        color_discrete_sequence=[color],
                        markers='scatter' in options,
                    ).select_traces()
                )
            )
        elif 'scatter' in options:
            figure.add_traces(
                list(
                    px.scatter(
                        dataframes[dataframe],
                        x=x,
                        y=y,
                        color_discrete_sequence=[color],
                    ).select_traces()
                )
            )
    return figure

def main():
    parser = argparse.ArgumentParser(description="Quick CSV Plotting Utility")
    parser.add_argument('files', nargs='*')
    args = parser.parse_args()
    init_app(args.files)
    app.run_server(debug=True)


from sqlalchemy.orm import Session

from schemas.database_schema import City

class CityRepository:

    @classmethod
    def find_all_cities(cls, session: Session):
        cities = session.query(City).all()
        session.close()
        return cities

    @classmethod
    def insert_new_city(cls, city: City, session: Session):
        session.add(city)
        session.commit()
        session.close()

    @classmethod
    def find_city_by_id(cls, c_id: str, session: Session):
        city = session.query(City).filter_by(city_id=c_id).first()
        session.close()
        return city

    @classmethod
    def find_city_by_city_name_and_state_id(cls, c_name: str, s_id: str, session: Session):
        city = session.query(City).filter_by(city_name=c_name, state_id=s_id).first()
        session.close()
        return city

    @classmethod
    def find_cities_by_state_id(cls, s_id: str, session: Session):
        cities = session.query(City).filter_by(state_id=s_id).all()
        session.close()
        return cities


from django.db import models
from Login.models import Customers
from django.contrib.auth.models import User,auth

# Create your models here.

class Calculations(models.Model):
    BMR=models.FloatField(default=None,null=True)
    date=models.DateTimeField(auto_now_add=True, blank=True)
    fieldname=models.CharField(max_length=20)
    user=models.ForeignKey(User,on_delete=models.CASCADE,default=None)
    BDI=models.FloatField(default=None,null=True)
    Exerciselvl=models.IntegerField(default=1)


from Crypto.Cipher import AES, PKCS1_OAEP, PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Util.number import inverse, long_to_bytes, bytes_to_long, isPrime, getPrime, GCD
from tqdm import tqdm
from pwn import *
from sage.all import *
import gmpy2, pickle, itertools, sys, json, hashlib, os, math, time, base64, binascii, string, re, struct, datetime, subprocess
import numpy as np
import random as rand
import multiprocessing as mp
from base64 import b64encode, b64decode
from sage.modules.free_module_integer import IntegerLattice
from ecdsa import ecdsa

### r = (k * G).x

# ks = H(m) + dr

# x_1 s_1 = H(m_1) + d r_1
# (ax_1 + b) s_2 = H(m_2) + d r_2
# (a(ax_1+b)+b) s_3 = H(m_3) + dr_3

fun = remote('crypto.be.ax', 6002)

p = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF
a = p - 3
b = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B

Gx = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296
Gy = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5

E = EllipticCurve(GF(p), [a, b])
G = E(Gx, Gy)

N = E.order()

PR = PolynomialRing(GF(N), ['X', 'A', 'B', 'D'])
X, A, B, D = PR.gens()

class RNG:
	def __init__(self, seed, A, b, p):
		self.seed = seed
		self.A = A
		self.b = b
		self.p = p

	def gen(self):
		out = self.seed
		while True:
			out = (self.A*out + self.b) % self.p
			yield out

def H(m):
	h = hashlib.sha256()
	h.update(m)
	return bytes_to_long(h.digest())

def sign(m, d):
	k = 1
	r = int((k*G).xy()[0]) % N
	s = ((H(m) + d*r)*inverse(k, N)) % N
	return r, s

f = []
g = X

print(fun.recvline())
print(fun.recvline())
print(fun.recvline())

for i in range(1, 5):
    fun.sendline("00" * i)
    r = int(fun.recvline().split()[-1])
    s = int(fun.recvline().split()[-1])
    f.append(X * s - H(b"\x00" * i) - D * r)
    X = A * X + B

I = Ideal(f).groebner_basis()

print(I)

for pol in I:
    try:
        print(pol.factor())
    except:
        pass

d = (N+int(input())) % N

finr, fins = sign(b'i wish to know the ways of the world', d)

fun.recvline()
fun.sendline(str(finr))
fun.sendline(str(fins))

print(fun.recvline())
print(fun.recvline())


import cv2

nothing = lambda *a, **k: None

class Window:
    def __init__(self, name):
        self.name = name
        cv2.namedWindow(self.name, cv2.WINDOW_AUTOSIZE)
        self.slider_names = []

    def add_slider(self, name, default=0, max=255):
        self.slider_names.append(name)
        cv2.createTrackbar(
            name,
            self.name,
            default,
            max,
            nothing
            )
        return self

    def get_slider(self, name):
        return cv2.getTrackbarPos(name, self.name)

    def get_sliders(self):
        return list(map(self.get_slider, self.slider_names))


from django.shortcuts import render, redirect, get_object_or_404
from checkout.models import Order

def cart(request):
    return render(request, "cart/cart.html")

def add_to_cart(request):
    quantity=int(request.POST.get('ammount'))
    id=request.POST['item']
    cart = request.session.get('cart', {})
    cart[id] = cart.get(id, quantity)
    request.session["cart"] = cart
    print(cart)
    return redirect('cart')

def remove_from_cart(request, id):
    cart = request.session.get('cart', {})
    cart.pop(id)
    request.session["cart"] = cart
    return redirect('cart')

def add_count_cart(request, id):
    cart = request.session.get('cart', {})
    cart[id] += 1
    request.session["cart"] = cart
    return redirect('cart')

def dec_count_cart(request, id):
    cart = request.session.get('cart', {})
    cart[id] -= 1
    if cart[id] == 0:
        cart.pop(id)
    request.session["cart"] = cart
    return redirect('cart')

def updatecart(request, id):
    cart = request.session.get('cart', {})
    quantity = request.GET.get("quantity")
    cart[id] = int(quantity)
    request.session["cart"] = cart
    return redirect('cart')

def dumpcart(request):
    del request.session["cart"]
    return redirect('cart')

def check_order(request):
    if request.method =="POST":
        id = int(request.POST.get("orderid"))
        print(id)
        order = get_object_or_404(Order, pk=id)
    else:
        order="no"
    return render(request, "cart/orderhistory.html", {"order":order})


import matplotlib.pyplot as plt
import numpy as np

print("Oto prosta wizualizacja funkcji ax^2+bx+c")
wyroznik1 = float(input("Wspolczynnik 1: "))
wyroznik2 = float(input("Wspolczynnik 2: "))
wyroznik3 = float(input("Wspolczynnik 3: "))
opisx = input("Wprowadź opis dla osi x:")
opisy = input("Wprowadź opis dla osi y: ")
tytul = input("Wprowadź tytul wykresu: ")
#GranicaDolna = input("Wprowadź granice dolna osi OX wykresu: ")
#GranicaGorna = input("Wprowadź granice gorna osi OX wykresu: ")
wartoscx = np.linspace(-4, 4, 5000)
wartoscy = np.array([wyroznik1*(x**2)+wyroznik2*(x)+ wyroznik3 for x in wartoscx])

fix, a = plt.subplots(figsize=(5,5))

a.plot(wartoscx, wartoscy)
plt.xlabel(opisx)
plt.ylabel(opisy)
plt.title(tytul)

plt.show()

#Z czystej ciekawości, jak możnaby było podstawić zmienne w matplotlib.pyplot.linespace()[wyrzuca błąd przy każdej próbie wstawienia zmiennej]?
#Oczywiście możemy narysować dla ogromnego przedziału zamiast <-4,4> a potem przesuwać za pomocą kontrolek ale jest to niezbyt praktyczne, zwłaszcza kiedy interesuje nas tylko określony, mały wycinek funkcji

Lab 1 Funkcja Kwadratowa/ProstaWizualizacja/ProstaWizualizacjaGraficznaFunkcjiKwadratowej.py