# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        curHead, curTail = head, head
        nextHead = None
        i = 0
        resHead = None
        isFirstSection = True
        while i < k and curTail:
            self.printList(head)
            curTail = curTail.next
            i += 1
            if i == k - 1:
                # Res head is first section's tail
                if isFirstSection:
                    resHead = curTail
                    isFirstSection = False
                # reverse section
                nextHead = curTail.next
                while curHead.next != nextHead:
                    cur = curHead.next
                    curHead.next = cur.next
                    cur.next = curHead

                curHead, curTail = nextHead, nextHead
                i = 0

        return resHead

    def printList(self, head):
        while head:
            print(head.val)
            head = head.next

Linked List/25. Reverse Nodes in k-Group.py


from typing import Dict
from dataclasses import asdict

from ..models import Resource
from ..db import Orm
from ..utils import get_value

def create_resource(fields:Dict):
    try:
        id_ = get_value(fields, 'id', str)
        name = get_value(fields, 'name')
        abreviation = get_value(fields, 'abreviation', str)
        metric = get_value(fields, 'metric', str)
        type = get_value(fields, 'type', str)
        value_per_hour = float(get_value(fields, 'value_per_hour'))

        new_resource = Resource(id_, name, abreviation, metric, type, value_per_hour)

        Orm.create('resources', new_resource)
        Orm.save()

        return {
            'msg': 'Recurso creado exitosamente',
            'resource': asdict(new_resource)
        }

    except Exception as e:
        return {
            'msg': str(e)
        }


n = int(input())

array = []
for i in range(n):
    array.append(int(input()))

# 책 풀이
# array = sorted(array, reverse=True)
#
# for i in array:
#     print(i, end = ' ')

# 선택 정렬
# for i in range(len(array)):
#     max_index = i                       # 가장 앞쪽 원소
#     for j in range(i+1, len(array)):    # 다음 인덱스부터 반복, 선형탐색
#         if array[max_index] < array[j]:
#             max_index = j               # 가장 큰 원소를 min_index에 담기
#         array[i], array[max_index] = array[max_index], array[i]   # 자리 바꾸기

# 삽입 정렬
# for i in range(1, len(array)):
#     for j in range(i, 0, -1):          # 인덱스 i부터 1까지 감소하여 반복하는 문법
#         if array[j] > array[j - 1]:    # 앞의 숫자보다 크다면
#             array[j], array[j - 1] = array[j - 1], array[j] # 자리 바꿈
#         else:      # 앞의 숫자보다 작다면
#             break  # 멈추고 다음 차례로

# 계수 정렬
count = [0] * (max(array) + 1)

for i in range(len(array)):
    count[array[i]] += 1

for i in range(len(count)):
    for j in range(count[i]):
        print(i, end = ' ')


from django import forms
from .models import CustomUser

class CustomUserForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = "__all__"

    def clean_national_code(self):
        national_code = self.cleaned_data['national_code']
        if len(national_code) != 10:
            message = "invalid national code"
            raise forms.ValidationError(message)
        return national_code

    def clean_full_name(self):
        full_name = self.cleaned_data['full_name']
        first_name, last_name = full_name.split()
        if first_name.istitle() and last_name.istitle():
            return full_name
        message = "invalid full name"
        raise forms.ValidationError(message)


from django.test import TestCase
# Create your tests here.

import base64
import filemaker_api.filemaker_api as filemaker

token = filemaker.login()

data = filemaker.adaptive_find_record(token, FirstName="Test", LastName='Person')

byuid = data[0]['response']['data'][0]['fieldData']['BYUID']
language = data[0]['response']['data'][0]['fieldData']['Language']
entrydate = data[0]['response']['data'][0]['fieldData']['EntryDate']

final = byuid + '&' + language + '&' +entrydate
filemaker.logout(token)

test_string = final

string_bytes = test_string.encode('ascii')

base64_bytes = base64.b64encode(string_bytes)
base64_string = base64_bytes.decode('ascii')

print(base64_string)

base64_bytes = base64_string.encode('ascii')

string_bytes = base64.b64decode(base64_bytes)

test_string = string_bytes.decode('ascii')

print(test_string)


import mysql.connector

mydb=mysql.connector.connect(user='root',host='localhost',passwd='')

mycursor=mydb.cursor()

try:
    mycursor.execute("create database bank")
    mycursor.execute("use bank")
except:
    mycursor.execute("use bank")

print("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print("++                                                      ++")
print("++                                                      ++")
print("++         Welcome To Banking Management System         ++")
print("++                                                      ++")
print("++                                                      ++")
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")

def Menu():
    print("\n======================= MAIN MENU ========================")
    print("\n1. Insert Record/Records")
    print("\n2. Display Records : ")
    print("  (a). Sorted as per Account Number")
    print("  (b). Sorted as per Customer Name")
    print("  (c). Sorted as per Customer Balance")
    print("\n3. Search Record Details as per the account number")
    print("\n4. Update Record")
    print("\n5. Delete Record")
    print("\n6. Transactions Debit/Withdraw from the account : ")
    print("  (a). Debit/Withdraw from the account")
    print("  (b). Credit into the account")
    print("\n7. Exit")

def MenuSort():
    print("\n a. Sorted as per Account Number")
    print(" b. Sorted as per Customer Name")
    print(" c. Sorted as per Customer Balance")
    print(" d. Back\n")

def MenuTransaction():
    print("")
    print("\n a. Debit/Withdraw from the account")
    print(" b. Credit into the account")
    print(" c. Back\n")

def Create():
    try:
        mycursor.execute('create table bank(ACCNO varchar(10),NAME varchar(50),MOBILE varchar(10),EMAIL varchar(50),ADDRESS varchar(50),CITY varchar(10),COUNTRY varchar(20),BALANCE integer(15))')
        Insert()
    except:
        Insert()

def Insert():
            while True:
              Acc=input("Enter account number : ")
              Name=input("Enter Name : ")
              Mob=input("Enter Mobile number : ")
              email=input("Enter Email : ")
              Add=input("Enter Address : ")
              City=input("Enter City : ")
              Country=input("Enter Country : ")
              Bal=int(input("Enter Balance : "))
              Rec=[Acc,Name.upper(),Mob,email.upper(),Add.upper(),City.upper(),Country.upper(),Bal]
              Cmd="insert into BANK values(%s,%s,%s,%s,%s,%s,%s,%s)"
              mycursor.execute(Cmd,Rec)
              mydb.commit()
              print("\nRecord Inserted.\n")
              break

def Disp(cmd):
    try:
        mycursor.execute(cmd)
        S=mycursor.fetchall()
        print("%15s %15s %15s %15s %15s %15s %15s %15s" % ("ACCNO","NAME","MOBILE","EMAIL ID","ADDRESS","CITY","COUNTRY","BALANCE"))
        print("="*130)
        for i in S:
            for j in i:
                print("%14s" % j, end=' ')
            print()
        print("="*130)
    except:
        print("\nTable doesn't exist.\n")

def DispSortAcc():
    cmd=Disp("select * from BANK order by ACCNO")

def DispSortName():
    cmd=Disp("select * from BANK order by NAME")

def DispSortBal():
    cmd=Disp("select * from BANK order by BALANCE")

def DispSearchAcc():
    try:
        mycursor.execute("select * from BANK")
        S=mycursor.fetchall()
        ch=input("\nEnter the account number to be searched : ")
        for i in S:
            if i[0]==ch:
                print("="*130)
                print("%15s %15s %15s %15s %15s %15s %15s %15s" % ("ACCNO","NAME","MOBILE","EMAIL ID","ADDRESS","CITY","COUNTRY","BALANCE"))
                print("="*130)
                for j in i:
                    print('%14s' % j,end=' ')
                print()
                break
        else:
            print("\nRecord Not found.\n")
    except:
        print("\nTable doesn't exist.\n")

def Update():
    try:
        mycursor.execute("select * from BANK")
        S=mycursor.fetchall()
        A=input("Enter the account number whose details to be changed : ")
        for i in S:
            i=list(i)
            if i[0]==A:
                ch=input("Change Name(Y/N) : ")
                if ch=='y' or ch=='Y':
                    i[1]=input("Enter Name : ")
                    i[1]=i[1].upper()
                ch=input("Change Mobile(Y/N) : ")
                if ch=='y' or ch=='Y':
                    i[2]=input("Enter Mobile : ")
                ch=input("Change Email(Y/N) : ")
                if ch=='y' or ch=='Y':
                    i[3]=input("Enter email : ")
                    i[3]=i[3].upper()
                ch=input("Change Address(Y/N) : ")
                if ch=='y' or ch=='Y':
                    i[4]=input("Enter Address : ")
                    i[4]=i[4].upper()
                ch=input("Change city(Y/N) : ")
                if ch=='y' or ch=='Y':
                    i[5]=input("Enter City : ")
                    i[5]=i[5].upper()
                ch=input("Change Country(Y/N) : ")
                if ch=='y' or ch=='Y':
                    i[6]=input("Enter country : ")
                    i[6]=i[6].upper()
                ch=input("Change Balance(Y/N) : ")
                if ch=='y' or ch=='Y':
                    i[7]=float(input("Enter Balance : "))
                cmd="UPDATE BANK SET NAME=%s,MOBILE=%s,EMAIL=%s,ADDRESS=%s,CITY=%s,COUNTRY=%s,BALANCE=%s WHERE ACCNO=%s"
                val=(i[1],i[2],i[3],i[4],i[5],i[6],i[7],i[0])
                mycursor.execute(cmd,val)
                mydb.commit()
                print("\nAccount Updated.\n")
                break
        else:
            print("\nRecord not found.\n")
    except:
        print("\nNo such table.\n")

def Delete():
    try:
        mycursor.execute("select * from BANK")
        S=mycursor.fetchall()
        A=input("Enter the account number whose record is to be deleted : ")
        for i in S:
            i=list(i)
            if i[0]==A:
                cmd="delete from bank where accno=%s"
                val=(i[0],)
                mycursor.execute(cmd,val)
                mydb.commit()
                print("\nAccount Deleted.\n")
                break
        else:
            print("\nRecord not found.\n")
    except:
        print("\nNo such Table.\n")

def Debit():
    try:
        mycursor.execute("select * from BANK")
        S=mycursor.fetchall()
        print("\nNOTE : Money can only be debited if minimum balance of Rs.5000 exists.\n")
        acc=input("Enter the account number from which the money is to be withdrawn : ")
        for i in S:
            i=list(i)
            if i[0]==acc:
                Amt=float(input("\nEnter the amount to be withdrawn : "))
                if i[7]-Amt>=5000:
                    i[7]-=Amt
                    cmd="UPDATE BANK SET BALANCE=%s WHERE ACCNO=%s"
                    val=(i[7],i[0])
                    mycursor.execute(cmd,val)
                    mydb.commit()
                    print("\nAmount Debited.\n")
                    break
                else:
                    print("\nThere must be min balance of Rs 5000.\n")
                    break
        else:
            print("\nRecord Not found.\n")
    except:
        print("\nTable Doesn't exist.\n")

def Credit():
    try:
        mycursor.execute("select * from BANK")
        S=mycursor.fetchall()
        acc=input("\nEnter the account number in which the money is to be credited : ")
        for i in S:
            i=list(i)
            if i[0]==acc:
                Amt=float(input("\nEnter the amount to be credited : "))
                i[7]+=Amt
                cmd="UPDATE BANK SET BALANCE=%s WHERE ACCNO=%s"
                val=(i[7],i[0])
                mycursor.execute(cmd,val)
                mydb.commit()
                print("\nAmount Credited.\n")
                break
        else:
            print("\nRecord Not found.\n")
    except:
        print("\nTable Doesn't exist.\n")

while True:
    Menu()
    ch=input("\nEnter your Choice : ")
    if ch=="1":
        Create()
    elif ch=="2":
        while True:
            MenuSort()
            ch1=input("\nEnter choice [a/b/c/d] : ")
            print("")
            if ch1 in ['a','A']:
                DispSortAcc()
            elif ch1 in ['b','B']:
                DispSortName()
            elif ch1 in ['c','C']:
                DispSortBal()
            elif ch1 in ['d','D']:
                print("\nBack to the main menu.\n")
                break
            else:
                print("\nInvalid choice.\n")
    elif ch=="3":
        DispSearchAcc()
    elif ch=="4":
        Update()
    elif ch=="5":
        Delete()
    elif ch=="6":
        while True:
            MenuTransaction()
            ch1=input("\nEnter choice [a/b/c] : ")
            if ch1 in ['a','A']:
                Debit()
            elif ch1 in ['b','B']:
                Credit()
            elif ch1 in ['c','C']:
                print("\nBack to the main menu.\n")
                break
            else:
                print("\nInvalid choice.\n")
    elif ch=="7":
        print("\nExiting...".center(75))
        print("\nThank you ! Have a nice day .\n")
        break
    else:
        print("\nInvalid choice.\n")


#!/usr/bin/env python3

'''
Find directories and files that satisfy certain conditions using subprocess
'''

import subprocess
import numpy as np

# Use the subprocess.os module to get a list of files and  directories
# in your ubuntu home directory
# Get the user's home directory.
home = subprocess.os.path.expanduser("~")
subprocess.os.listdir(path = home)

# Hint: look in subprocess.os and/or subprocess.os.path and/or
# subprocess.os.walk for helpful functions

#################################
#~Get a list of files and
#~directories in your home/ that start with an uppercase 'C'

# Type your code here:
# Create a list to store the results.

# Use a for loop to walk through the home directory.
l_root = []
l_subdir = []
l_files = []
for (root, subdir, files) in subprocess.os.walk(home):
    l_subdir.append(subdir)
    l_files.append(files)

#Make flat list from list of lists
l_directories = [j for i in l_subdir for j in i]
l_files_ = [j for i in l_files for j in i]

#Select only those that start with C
dir_C = [i for i in l_directories if i.startswith('C')]
files_C = [i for i in l_files_ if i.startswith('C')]

#Join lists
DirFiles_C = dir_C + files_C
print('Directories and Files that start with C\n')
print(DirFiles_C, '\n')
#################################
# Get files and directories in your home/ that start with either an
# upper or lower case 'C'

# Type your code here:
#Select only those that start with C or c

dir_C_c = [i for i in l_directories if i.lower().startswith('c')]
files_C_c = [i for i in l_files_ if i.lower().startswith('c')]

#Join lists
DirFiles_C_c = dir_C_c + files_C_c
print('Directories and Files that start with C or c\n')
print(DirFiles_C_c, '\n')
#################################
# Get only directories in your home/ that start with either an upper or
#~lower case 'C'

# Type your code here:
Dir_C_c = dir_C_c
print('Directories that start with C or c\n')
print(Dir_C_c, '\n')


# constants

from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.gaussian_process import GaussianProcessClassifier
from lightgbm import LGBMClassifier
from imblearn import over_sampling

class constants(object):
    def __init__(self):
        super().__init__()
        self.DIMENSION = 3
        # the number of spatial transformation
        self.N = 3
        self.RESOLUTION = 0.2
        self.CT_RAW = r'data/raw/ct'
        self.CT_PROCESSED = r'data/processed/ct'
        self.SEED = 81921
        self.sampling_funcs = {
            'SMOTE': over_sampling.SMOTE,
            'ADASYN': over_sampling.ADASYN,
            'BorderlineSMOTE': over_sampling.BorderlineSMOTE,
        }
        self.models = {
            'LogisticRegression': LogisticRegression,
            'RandomForestClassifier': RandomForestClassifier,
            'LGBMClassifier': LGBMClassifier,
            'GaussianProcessClassifier': GaussianProcessClassifier
        }
        self.params = {
            'LogisticRegression': {'solver': 'liblinear'},
            'RandomForestClassifier': {},
            'GaussianProcessClassifier': {},
            'LGBMClassifier': {},
        }
        self.base_params = {
            'LogisticRegression': {
                'solver': 'liblinear',
                'random_state':self.SEED,
                'class_weight': 'balanced',
            }
        }


import manager

class OpenMPI(manager.Lib):
    def __init__(self, compile_flags='-Dfortran=ON -Dtest=ON'):
        super().__init__(name='openmpi', compile_flags=compile_flags)
        self.mpiexec = 'mpirun'
        self.mpiexec_np = '-np'
        self.mpiexec_hostfile = '-hostfile {}'

        self.preload = '-x LD_PRELOAD={}'

    def format_command(self, context):
        context.env['INTERFERENCE_LOCALID'] = 'OMPI_COMM_WORLD_LOCAL_RANK'
        context.env['INTERFERENCE_LOCAL_SIZE'] = 'OMPI_COMM_WORLD_LOCAL_SIZE'

        hostfile = self.mpiexec_hostfile.format(context.hostfile.path)
        preload = self.preload.format(context.machine.get_lib())
        parameters = " ".join([hostfile,
                               self.mpiexec_np, str(context.bench.np),
                               preload,
                               '-oversubscribe',
                               '--bind-to none'])
        return "{} {} ./bin/{}".format(self.mpiexec, parameters,
                                       context.bench.name)


import numpy as np
import pytest

from zhinst.toolkit.driver.modules.base_module import BaseModule

@pytest.fixture()
def base_module(data_dir, mock_connection, session):
    json_path = data_dir / "nodedoc_awg_test.json"
    with json_path.open("r", encoding="UTF-8") as file:
        nodes_json = file.read()
    mock_connection.return_value.awgModule.return_value.listNodesJSON.return_value = (
        nodes_json
    )
    yield BaseModule(mock_connection.return_value.awgModule(), session)

def test_repr(base_module):
    assert "MagicMock(DataServerSession(localhost:8004))" in repr(base_module)

def test_raw_module(base_module, mock_connection):
    assert base_module.raw_module == mock_connection.return_value.awgModule()

def test_device(zi_devices_json, base_module, mock_connection):
    connected_devices = "dev1234"

    def get_string_side_effect(arg):
        if arg == "/zi/devices":
            return zi_devices_json
        if arg == "/zi/devices/connected":
            return connected_devices
        if arg == "/dev1234/features/devtype":
            return "Test"
        raise RuntimeError("ZIAPINotFoundException")

    mock_connection.return_value.getString.side_effect = get_string_side_effect

    # get
    mock_connection.return_value.awgModule.return_value.getString.return_value = ""
    result = base_module.device()
    assert result == ""

    mock_connection.return_value.awgModule.return_value.getString.return_value = (
        "dev1234"
    )
    result = base_module.device()
    assert result.serial == "dev1234"

    # set
    base_module.device("dev1634")
    mock_connection.return_value.awgModule.return_value.set.assert_called_with(
        "/device", "dev1634"
    )

    base_module.device(result)
    mock_connection.return_value.awgModule.return_value.set.assert_called_with(
        "/device", "dev1234"
    )

def test_wait_done(base_module, mock_connection):
    module_mock = mock_connection.return_value.awgModule.return_value
    module_mock.finished.return_value = 1
    base_module.wait_done()

    module_mock.finished.return_value = 0
    module_mock.progress.return_value = np.array([0.1])
    with pytest.raises(TimeoutError) as e_info:
        base_module.wait_done(timeout=0.01)

def test_subscribe(base_module, mock_connection):
    module_mock = mock_connection.return_value.awgModule.return_value
    base_module.subscribe(base_module.test)
    module_mock.subscribe.assert_called_with("/test")

def test_unsubscribe(base_module, mock_connection):
    module_mock = mock_connection.return_value.awgModule.return_value
    base_module.unsubscribe(base_module.test)
    module_mock.unsubscribe.assert_called_with("/test")

def test_execute(base_module, mock_connection):
    module_mock = mock_connection.return_value.awgModule.return_value
    base_module.execute()
    module_mock.execute.assert_called_once()


#coding: utf8
from OpenGL import GL
import sdl2
import sdl2.ext

from program.const import *
from program.box import BOX
from sequence.locals import MenuItems, backimage

class ChoiceMode(object):

    EASY   = 0
    NORMAL = 1
    HARD   = 2
    TRAVEL = 3
    RETURN = 4

    def __init__(self):
        self.texts = ["Easy",
                      "Normal",
                      "Hard",
                      "Travel"]

    def init(self):
        self.menu = MenuItems(self.texts, BOX.Y/10, ret=True)
        self.menu.choice = {"EASY":0,
                            "NORMAL":1,
                            "HARD":2,
                            "TRAVEL":3}[BOX.MODE]
        self.menu.pos[-2][1] -= self.menu.height*0.25

    def mainloop(self):
        self.init()
        while True:
            choice = -1
            for event in sdl2.ext.get_events():
                if event.type == sdl2.SDL_QUIT:
                    BOX.game_quit()
                elif event.type == sdl2.SDL_KEYDOWN:
                    key = event.key.keysym.sym
                    if key in KS_ESC:
                        if self.menu.choice == self.menu.RETURN:
                            return
                        else:
                            choice = self.menu.RETURN
                        break
                    elif key == sdl2.SDLK_UP:
                        self.menu.up()
                    elif key == sdl2.SDLK_DOWN:
                        self.menu.down()
                    elif key in KS_RETURN:
                        choice = self.menu.choice
                        break
                elif event.type == sdl2.SDL_MOUSEBUTTONDOWN:
                    mouse = event.button
                    if mouse.button == 1:
                        choice = self.menu.mouse_check(mouse.x, mouse.y)
                        break

            if 0 <= choice:
                if choice != self.menu.RETURN:
                    BOX.set_mode({0:"EASY",
                                  1:"NORMAL",
                                  2:"HARD",
                                  3:"TRAVEL"}[choice])
                return choice

            backimage.draw()
            self.menu.draw()
            sdl2.SDL_GL_SwapWindow(BOX.window)
            sdl2.SDL_Delay(10)


from src.dato.EnComun import Precio

class Pedido(object):

    def __init__(self, idExterno='', tipoEnvio=0, canalVenta='', importePedido='', monedaPedido='', numArticulos=0, listProduc=None,
                 NIF_DR=None, nombre_DR=None, email_DR = None, telefono_DR=None,
                 tipoVia_DR='', nombreVia_DR='', numVia_DR='', otrosDatos_DR='', codPostal_DR='', ciudad_DR='', region_DR='', codPais_DR='',
                 contacto_DR = None, aLaAtencionDe_DR = None, horario_DR= None, observaciones_DR = None,
                 NIF_DE=None, nombre_DE=None, email_DE = None, telefono_DE=None,
                 tipoVia_DE='', nombreVia_DE='', numVia_DE='', otrosDatos_DE='', codPostal_DE='', ciudad_DE='', region_DE='', codPais_DE='',
                 contacto_DE = None, aLaAtencionDe_DE = None, horario_DE= None, observaciones_DE = None,
                 fecha='', numAlbaran='', referencia = "", enFranquicia = '', codigoServicio='', numBultos = '', peso = "", entregaSabado = '',
                 entregaPartirDe = '', horario = None, tramoHorario = '', notificaciones=None):
        '''
        Constructor
        '''
        'IdExterno del pedido'
        self.idExterno = idExterno
        'Tipo Envío (Estándar o Urgente)'
        self.tipoEnvio=tipoEnvio
        'Canal de venta del pedido (Amazon.es, Amazon.fr, eBay...)'
        self.canalVenta = canalVenta
        'Precio total del pedido'
        self.precio = Precio(importePedido, monedaPedido)
        'Número de artículos del pedido'
        self.numArticulos=numArticulos
        'Lista con los productos del pedido'
        self.productos=listProduc
        'Datos de recogida, remitente y dirección'
        self.datosRecogida=DatosCliente(NIF=NIF_DR, nombre=nombre_DR, email=email_DR, telefono=telefono_DR,
                                        tipoVia=tipoVia_DR, nombreVia=nombreVia_DR, numVia=numVia_DR, otrosDatos=otrosDatos_DR, codPostal=codPostal_DR, ciudad=ciudad_DR, region=region_DR, codPais=codPais_DR,
                                        contacto=contacto_DR, aLaAtencionDe=aLaAtencionDe_DR, horario=horario_DR, observaciones=observaciones_DR)
        'Datos de envío, destinatario y dirección'
        self.datosEnvio=DatosCliente(NIF=NIF_DE, nombre=nombre_DE, email=email_DE, telefono=telefono_DE,
                                     tipoVia=tipoVia_DE, nombreVia=nombreVia_DE, numVia=numVia_DE, otrosDatos=otrosDatos_DE, codPostal=codPostal_DE, ciudad=ciudad_DE, region=region_DE, codPais=codPais_DE,
                                     contacto=contacto_DE, aLaAtencionDe=aLaAtencionDe_DE, horario=horario_DE, observaciones=observaciones_DE)
        'Datos del servicio'
        self.datosServicio = DatosServicio(fecha=fecha, numAlbaran=numAlbaran, referencia=referencia, enFranquicia=enFranquicia,
                                           codigoServicio=codigoServicio, numBultos=numBultos, peso=peso, entregaSabado=entregaSabado,
                                           entregaPartirDe=entregaPartirDe, horario=horario, tramoHorario=tramoHorario, notificaciones=notificaciones)

class DatosCliente():
    '''
    Clase que va a tener los datos personales de la persona, así como la dirección
    '''
    def __init__(self,
                 NIF=None, nombre=None, email = None, telefono=None,
                 tipoVia='', nombreVia='', numVia='', otrosDatos='', codPostal='', ciudad='', region='', codPais='',
                 contacto = None, aLaAtencionDe = None, horario= None, observaciones = None):

        self.datosPersonales = DatosPersonales()
        self.direccion = Direccion()
        self.datosPersServicio = DatosPersonalesServicio()

class DatosPersonales(object):

    def __init__(self, NIF=None, nombre=None, email = None, telefono=None):
        'Nombre completo'
        self.nombre=nombre
        'NIF'
        self.NIF=NIF
        'Email'
        self.email = email
        'Teléfono'
        self.telefono=telefono

class Direccion(object):

    def __init__(self, tipoVia='', nombreVia='', numVia='', otrosDatos='', codPostal='', ciudad='', region='', codPais=''):
        '''
        Constructor
        '''
        'Tipo vía'
        self.tipoVia = tipoVia
        'Nombre vía'
        self.nombreVia = nombreVia
        'Número de la vía'
        self.numVia=numVia
        'Piso, puerta, escalera, etc'
        self.otrosDatos = otrosDatos
        'Código postal'
        self.codigoPostal = codPostal
        'Ciudad'
        self.ciudad = ciudad
        'Provincia, comunidad o región'
        self.region = region
        'Código país'
        self.codPais = codPais

class DatosPersonalesServicio(object):
    '''
        Datos de la persona asociados al servicio, tales como contacto, horario, observaciones, etc
    '''
    def __init__(self, contacto = None, aLaAtencionDe = None, horario= None, observaciones = None):
        'Contacto'
        self.contacto = contacto
        'A la atención de'
        self.aLaAtencionDe = aLaAtencionDe
        'Horario'
        self.horario= horario
        'Observaciones'
        self.observaciones = observaciones

class DatosServicio(object):
    '''
    Clase con los datos del servicio de envío,
    están cargados casi todos los datos que necesitamos por defecto
    Los datos de esta clase son los que hay para el envío nacional
    '''

    def __init__(self, fecha='', numAlbaran='', referencia = "", enFranquicia = '',
                 codigoServicio='', numBultos = '', peso = "", entregaSabado = '',
                 entregaPartirDe = '', horario = None, tramoHorario = '', notificaciones=None):
        '''
        Constructor
        '''
        'Fecha. Obligatorio'
        self.fecha=fecha
        'NumeroAlbaran'
        self.numAlbaran=numAlbaran
        'Referencia'
        self.referencia = referencia
        'EnFranquicia'
        self.enFranquicia = enFranquicia
        'Obligatorio'
        self.codigoServicio=codigoServicio
        'Número Bultos. Obligatorio'
        self.numBultos = numBultos
        'Peso, en kilogramos. Obligatorio'
        self.peso = peso
        'Entrega en Sabado'
        self.entregaSabado = entregaSabado
        'Entrega a partir de'
        self.entregaPartirDe = entregaPartirDe
        'Entrega en tramo horario. '
        self.horario = horario
        'Entrega en tramo horario. '
        self.tramoHorario = tramoHorario
        'Notificaciones'
        self.notificaciones=notificaciones

class NotificacionEnvio(object):

    def __init__(self, canal='', tipo='', telEmail=''):

        'Canal de notificacion 1=SMS(coste adicional) 2=EMAIL(gratuito)'
        self.canal=canal

        'Tipo Notificacion'
        '1 = Confirmación de entrega'
        '2 = Seguimiento de envío (informa los diferentes estados de tránsito del envío)'
        '3 = Aviso de entrega en franquicia (informa al destinatario del envío que la mercancía está disponible en la franquicia de destino. Solo tendrá sentido para entrega en franquicia, y será obligatorio)'
        '4 = Preaviso de entrega (informa al destinatario del envío de la fecha de entrega de la mercancía. Solo tendrá sentido cuando NO sea entrega en franquicia)'
        '5 = Confirmación de recogida (informa al destinatario que el envío ha sido recogido en origen. Solo tendrá sentido cuando NO sea entrega en franquicia)'
        self.tipo = tipo

        'Teléfono móvil o dirección email, según CanalNotificacion'
        self.telEmail=telEmail


from flask_app.config.mysqlconnection import MySQLConnection
from flask import flash
import re

EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')

class Email:
    def __init__(self,data):
        self.id = data["id"]
        self.email = data["email"]
        self.created_at = data["created_at"]
        self.updated_at = data['updated_at']

    @classmethod
    def save(cls,data):
        query = "INSERT INTO emails ( email, created_at, updated_at ) VALUES (%(email)s, Now(), Now());"
        return MySQLConnection("email_validation").query_db(query,data)

    @classmethod
    def get_all(cls):
        query = "SELECT * FROM emails;"
        results = MySQLConnection("email_validation").query_db(query)
        emails = []
        for e in results:
            emails.append(cls(e))
        return emails

    @staticmethod
    def validate_email(email):
        is_valid = True
        data=Email.get_all()
        if not EMAIL_REGEX.match(email["email"]):
            flash("Email is invalid")
            is_valid = False
        for d in data:
            if d.email == email["email"]:
                flash("email already used")
                is_valid = False
        return is_valid


#!/usr/bin/env python3

import speech_recognition as sr

from os import path
from sys import argv

if len(argv) != 2:
    print("Usage: " + argv[0] +" <wav_list_file>")
    print()
    print("<wav_list_file> \t is a list with .wav files to be recognized." \
          "Format: one audio per line. ")
    exit()

file_list = argv[1]

r = sr.Recognizer()

with open(file_list, 'r') as audio_list:
    for audio_file in audio_list:

        with sr.AudioFile(audio_file.strip()) as source:
            audio = r.record(source) # read the entire audio file
        # recognize speech using Google Speech Recognition
        try:
            print(audio_file.strip() + '\t' + r.recognize_google(audio, language="pt-BR"), flush=True)
        except sr.UnknownValueError:
            print(" ", flush=True)
        except sr.RequestError as e:
            print("Could not request results from Google Speech Recognition service; {0}".format(e), flush=True)


import os

import click
import tableprint as tp

@click.group(
    name="waymo",
    help="Utilities for using the Waymo Motion Dataset with SMARTS. See `scl waymo COMMAND --help` for further options.",
)
def waymo_cli():
    pass

@waymo_cli.command(
    name="overview", help="Display summary info for each scenario in the TFRecord file."
)
@click.argument(
    "tfrecord_file", type=click.Path(exists=True), metavar="<tfrecord_file>"
)
def overview(tfrecord_file: str):
    from smarts.waymo import waymo_utils

    scenarios = waymo_utils.get_tfrecord_info(tfrecord_file)
    rows = [
        [k, v["timestamps"], v["vehicles"], v["pedestrians"]]
        for k, v in scenarios.items()
    ]
    headers = [
        "Scenario ID",
        "Timestamps",
        "Vehicles",
        "Pedestrians",
    ]
    tp.table(rows, headers)

@waymo_cli.command(
    name="preview", help="Plot the map and trajectories of the scenario."
)
@click.argument(
    "tfrecord_file", type=click.Path(exists=True), metavar="<tfrecord_file>"
)
@click.argument("scenario_id", type=str, metavar="<scenario_id>")
@click.option(
    "--animate",
    is_flag=True,
    default=False,
    help="Animate the vehicle trajectories.",
)
@click.option(
    "--label_vehicles",
    is_flag=True,
    default=False,
    help="Plot the initial positions of all vehicles with their IDs.",
)
def preview(
    tfrecord_file: str,
    scenario_id: str,
    animate: bool,
    label_vehicles: bool,
):
    from smarts.waymo import waymo_utils

    waymo_utils.plot_scenario(tfrecord_file, scenario_id, animate, label_vehicles)

@waymo_cli.command(
    name="export", help="Export the Waymo scenario to a SMARTS scenario."
)
@click.argument(
    "tfrecord_file", type=click.Path(exists=True), metavar="<tfrecord_file>"
)
@click.argument("scenario_id", type=str, metavar="<scenario_id>")
@click.argument(
    "export_folder", type=click.Path(exists=False), metavar="<export_folder>"
)
def export(
    tfrecord_file: str,
    scenario_id: str,
    export_folder: str,
):
    from smarts.waymo import waymo_utils

    scenario_folder = os.path.join(export_folder, scenario_id)
    if not os.path.exists(scenario_folder):
        os.makedirs(scenario_folder)
    scenario_file = os.path.join(scenario_folder, "scenario.py")
    with open(scenario_file, "w") as f:
        f.write(waymo_utils.gen_smarts_scenario_code(tfrecord_file, scenario_id))

waymo_cli.add_command(overview)
waymo_cli.add_command(preview)
waymo_cli.add_command(export)


import copy
import os
import sys
import re

# remove text per command so only the numbers are left over
def extract_arguments_from_command(command: str) -> tuple:
    target_containers, source, destination = re.findall(r'\b\d+\b', command)
    return int(target_containers), int(source), int(destination)

def find_top_crates_of_stacks(stacks, commands, isReverse):
    for command in arguments_per_command:
        target_containers: int = command[0] # move this many containers
        source: int = command[1] # from this list
        destination: int = command[2] # to this list
        stacks[destination][0:0] = reversed(stacks[source][:target_containers]) if isReverse else stacks_copy[source][:target_containers] # insert taken containers on top of destination stack
        del stacks[source][:target_containers] # remove the taken containers from the source
    crates_on_top_each_stack = [stacks[i][0] for i in stacks] # select only the top crate of each stack
    return crates_on_top_each_stack

with open(os.path.join(sys.path[0], "crates.txt"), "r") as f:
    commands = f.read().splitlines()[10:]
    stacks = {
        1: 'TRGWQMFP',
        2: 'RFH',
        3: 'DSHGVRZP',
        4: 'GWFBPHQ',
        5: 'HJMSP',
        6: 'LPRSHTZM',
        7: 'LMNHTP',
        8: 'RQDF',
        9: 'HPLNCSD'
    }

    # convert each value per key to list of str characters
    for key in stacks:
        stacks[key] = list(stacks[key])

    stacks_copy = copy.deepcopy(stacks) # for part 2, because original will be modified
    arguments_per_command = [extract_arguments_from_command(command) for command in commands]

    print(f"Crates on top of each stack are: {find_top_crates_of_stacks(stacks, arguments_per_command, True)}")

    #part 2
    print(f"Crates on top of each stack (CrateMover 9001): {find_top_crates_of_stacks(stacks_copy, arguments_per_command, False)}")


import pygame
from typing import List

from src.animation import AnimateSprite

def vector_equals(v1: pygame.Vector2, v2: pygame.Vector2) -> bool:
    return v1.x == v2.x and v1.y == v2.y

def get_animation_name(direction: pygame.Vector2):
    return 'down' if direction.y > 0 and direction.y > abs(direction.x) else ('up' if direction.y < 0 and direction.y < -abs(direction.x) else ('left' if direction.x < 0 else 'right'))

class Entity(AnimateSprite):

    def __init__(self, name, x, y):
        super().__init__(name)
        self.image = self.get_image(0, 0)
        self.image.set_colorkey([0, 0, 0])
        self.rect = self.image.get_rect()
        self.position = pygame.Vector2(x, y)
        self.current_movement = pygame.Vector2(0, 0)
        self.feet = pygame.Rect(0, 0, self.rect.width * 0.3, self.rect.height * 0.3)
        self.old_position = pygame.Vector2(self.position.x, self.position.y)

    def save_location(self): self.old_position = pygame.Vector2(self.position.x, self.position.y)

    def move(self, inputs: pygame.Vector2):
        if inputs.magnitude() == 0 and self.current_movement.magnitude() != 0:
            self.current_movement = pygame.Vector2(0, 0)
            self.image = self.images['down'][1]
            self.image.set_colorkey(0, 0)
        elif inputs.magnitude() != 0:
            direction = inputs.normalize()
            movement = pygame.Vector2(round(direction.x), round(direction.y))
            if not vector_equals(movement, self.current_movement):
                self.current_movement = movement
                if self.current_animation != get_animation_name(movement):
                    self.change_animation(get_animation_name(movement))
            self.tick_animation()
            self.position += movement

    def update(self):
        self.rect.topleft = self.position
        self.feet.midbottom = self.rect.midbottom

    def move_back(self):
        self.position = self.old_position
        self.update()

    def objective_to_direction(self, objective: pygame.math.Vector2):
        return pygame.math.Vector2(0, 0) if vector_equals(objective, self.position) else pygame.math.Vector2(
            objective.x - self.position.x, objective.y - self.position.y
        ).normalize()

class Player(Entity):

    def __init__(self):
        super().__init__('player', 0, 0)
        self.cooldown = 0

class NPC(Entity):
    def __init__(self, name, path_points_count, dialog):
        super().__init__(name, 0, 0)
        self.path_points_count = path_points_count
        self.dialog = dialog
        self.points: List[pygame.Vector2] = []
        self.name = name
        self.current_point = 0

    def target_point(self):
        target_point = self.current_point + 1

        if target_point >= self.path_points_count:
            target_point = 0

        point_pos = self.points[target_point]
        if(self.position - point_pos).magnitude() < 3:
            self.current_point = target_point
            return
        self.move(self.objective_to_direction(point_pos))

    def teleport_spawn(self):
        location = self.points[self.current_point]
        self.position[0] = location.x
        self.position[1] = location.y
        self.save_location()

    def load_points(self, tmx_data):
        for num in range(1, self.path_points_count + 1):
            point = tmx_data.get_object_by_name(f'{self.name}_path{num}')
            position = pygame.Vector2(point.x, point.y)
            self.points.append(position)


"""Create the input data pipeline using `tf.data`"""
import tensorflow as tf
from utils.data import *

def preprocess_data(raw_image, aligned_image, size_w, size_h, label_size):
    """ preprocessing images """

    raw_image_string = tf.io.read_file(raw_image)
    raw_image = load_image(raw_image_string, size_w, size_h, label_size, raw_image_flag = True)
    raw_image = augment_image(raw_image)

    aligned_image_string = tf.io.read_file(aligned_image)
    aligned_image = load_image(aligned_image_string, size_w, size_h, label_size, raw_image_flag = False)
    aligned_image = augment_image(aligned_image)

    return raw_image, aligned_image

def load_image(image_string, size_w, size_h, label_size, raw_image_flag):
    """ decoding the images """

    image = tf.image.decode_jpeg(image_string, channels=3)
    image = tf.image.convert_image_dtype(image, tf.float32)
    # image = tf.expand_dims(image[:,:,1], 2) # only the green channel is being used
    if raw_image_flag:
        image = tf.image.resize(image, [size_w, size_h])
    else:
        image = tf.image.resize(image, [label_size, label_size])

    return image

def augment_image(image):
    """ augmenting the images """

    # image = tf.image.adjust_saturation(image,0.5)
    image = tf.clip_by_value(image, 0.0, 1.0)

    return image

def input_fn(is_training, filenames_raw, filenames_aligned, params = None):
    """Input function for the SIGNS dataset.
    The filenames have format "{img}_{id}.jpg",For instance: "data_dir/img_0004.jpg".
    Args:
        is_training: (bool) whether to use the train or test pipeline. At training, we shuffle the data and have multiple epochs
        filenames: (list) filenames of the images, as ["data_dir/{img}_{id}.jpg"...]
        params: (Params) contains hyperparameters of the model (ex: `params.num_epochs`)
    """
    num_samples = len(filenames_raw)
    assert len(filenames_raw) == len(filenames_aligned), "raw and aligned images should have same length"

    # Create a Dataset serving batches of images and labels
    preproc_fn = lambda f, l: preprocess_data(f, l, params.image_size_w, params.image_size_h, params.label_size)

    if is_training:
        dataset = (tf.data.Dataset.from_tensor_slices((filenames_raw, filenames_aligned))
        .shuffle(buffer_size = num_samples)  # whole dataset into the buffer ensures good shuffling
        .map(preproc_fn, num_parallel_calls=params.num_parallel_calls)
        .batch(params.batch_size)
        .prefetch(tf.data.experimental.AUTOTUNE)  # make sure you always have one batch ready to serve (can also use one 1)
    )
    else:
        dataset = (tf.data.Dataset.from_tensor_slices((filenames_raw, filenames_aligned))
        .map(preproc_fn)
        .batch(params.batch_size)
        .prefetch(1)  # make sure you always have one batch ready to serve
    )

    return dataset


import tkinter as tk
from random import randint
from time import sleep

def sortear_numero():
    label_resultado.config(text="Sorteando ... ")
    root.update()
    sleep(2)
    numero_sorteado = randint(0,20)
    label_resultado.config(text=f"O número sorteado foi {numero_sorteado} Parabéns!")

root = tk.Tk()
root.title("Sorteio de números")
root.geometry("300x200")

label_instruções = tk.Label(root, text="Clique no botão para sortear umnúmero entre 0 e 20.")
label_instruções.pack(pady=20)

botão_sorteio = tk.Button(root, text="Sortear", command=sortear_numero)
botão_sorteio.pack()

label_resultado = tk.Label(root, text="")
label_resultado.pack(pady=20)

root.mainloop()


''' AD_OCS Model with VLE ideal '''

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

from SS_Algebraic import*
from Influent import*
from GLConstants import*

from functions_V5 import gompertz, growth_SRB, AD_OCS_Model, AMOCO_HN, f_deviations, deviations_check
from GL_Equilibrium import f_RR_equilibrium
# Oxygen test
# System definition
print(KH_S)
print(H_S_atm)
# System definition
d_start = 10        # [d] - Start time
d_end   = 40        # [d] - End time
hours   = 6         # [h] - Discretization time
n_times = int((d_end-d_start)*24/hours) # Number of time steps

print('***Intervals of {hours} hours. \n {n_times} time steps***'.format(hours=hours, n_times=n_times))

t_span = np.linspace(d_start,d_end,n_times) # time span

y_influent = f_deviations(t_span, T3.index.values, y_in_0) # Get the deviated influent values at each timestamp

# --------------------------------------------------------------------------------------------
# Ode Integration of AMOCO_HN: use to get X2
# --------------------------------------------------------------------------------------------

y0= [SSTATE[0], SSTATE[1], SSTATE[2], SSTATE[3], SSTATE[4], SSTATE[5], SSTATE[6]] # initial conditions esxkcdlished from SS

YOUT_pre = odeint(AMOCO_HN, y0, t_span, args=(alfa, mu_max, Ks, KI2, KH, Pt, kLa, D, k, kd, N_bac, N_S1, y0[2], t_span[0], y_in_0, T3.index.values))
X2_pre = YOUT_pre[:,2]
print('************** AMOCOHN OK *******************')

# --------------------------------------------------------------------------------------------
# Ode Integration of the AD_OCS_Model: uses the previous X2 to get rho
# --------------------------------------------------------------------------------------------

y0 = [SSTATE[0], SSTATE[1], SSTATE[2], SSTATE[3], SSTATE[4], SSTATE[5], SSTATE[6]] # initial conditions esxkcdlished from SS

YOUT = odeint(AD_OCS_Model, y0, t_span, args=(alfa, mu_max, Ks, KI2, KH, Pt, kLa, D, k, kd, N_bac, N_S1, y0[2], t_span[0], y_in_0, T3.index.values, X2_pre, t_span))

# Get results
XT = YOUT[:,0]              # [gCOD/L] - Particulate
X1 = YOUT[:,1]              # [g/L]    - Acidogenics  Bacteria
X2 = YOUT[:,2]              # [g/L]    - Methanogenic Bacteria
Z  = YOUT[:,3]              # [mmol/L] - Total Alkalinity
S1 = YOUT[:,4]              # [g/L]    - Organic Soluble Substrate
S2 = YOUT[:,5]              # [mmol/L] - VFA dissolved
C  = YOUT[:,6]              # [mmol/L] - Inorganic Carbon Dissolved

print('************** AD_OCS_Model OK *******************')

# Solver Output: from all the variables from the ones of the ODE
mu1 = np.zeros(len(t_span))
mu2 = np.zeros(len(t_span))
CO2 = np.zeros(len(t_span))
B   = np.zeros(len(t_span))
phi = np.zeros(len(t_span))
p_C = np.zeros(len(t_span))
q_C = np.zeros(len(t_span))
q_M = np.zeros(len(t_span))
pH  = np.zeros(len(t_span))

for x in range(len(t_span)):
    mu1[x] = mu_max[0]*(S1[x]/(S1[x]+Ks[0]))                     # [1/d]      - Specific Growth Rate for X1 (Monod)
    mu2[x] = mu_max[1]*(S2[x]/(S2[x]+Ks[1]+S2[x]**2/KI2))        # [1/d]      - Specific Growth Rate for X2 (Haldane)
    CO2[x] = C[x] + S2[x] - Z[x]                                 # [mmol/L]   - Dissolved CO2
    B[x]   = Z[x] - S2[x]                                        # [mmol/L]   - Alkalinity
    phi[x] = CO2[x] + KH*Pt + k[5]/kLa*mu2[x]*X2[x]
    p_C[x]  = (phi[x] - (phi[x]**2- 4*KH*Pt*CO2[x])**0.5)/(2*KH) # [atm]      - CO2 Partial Pressure
    q_C[x] = kLa*(CO2[x] - KH*p_C[x])                            # [mmol/L/d] - CO2 Outlet Molar Flow
    q_M[x] = k[5]*mu2[x]*X2[x]                                   # [mmol/L/d] - CH4 Outlet Molar Flow
    pH[x]  = np.real(-np.log10(Kb*CO2[x]/B[x]))                  # [-]        - System pH

q_tot = q_C + q_M                                                # [mmol/L/d] - Outlet global molar flow

# Sulfur and Oxygen Influence Evaluation

Xs     = np.zeros(len(t_span))                                   # [g/L]      - Sulfate Reducing Bacteria
Ss     = np.zeros(len(t_span))                                   # [mmol/L]      - Sulfur dissolved
y_S = np.zeros(len(t_span))                                   # [-]        - Sulfur Mole fraction in gas phase
Ss_max = np.zeros(len(t_span))                                   # [mmol/L]      - Maximum Sulfur dissolved concentration
Xs_max = np.zeros(len(t_span))                                   # [g/L]      - Maximum Sulfate Reducing Bacteria concentration (Gompertz Asymptote)
mu_srb = np.zeros(len(t_span))                                   # [g/L/d]    - Gompertz parameter for SRB growth
growth_rate = np.zeros(len(t_span))                              # [g/L/d]    - Gompertz derivative: states the growth rate of SRB

dXsdt = np.zeros([len(t_span),len(t_span)])                     # [g/L/d]    - SRB growth rate matrix, preallocation
lam = 0                                                         # [-]        - Lag Time as defined by Gompertz

for j in range(len(t_span)):
    # Iterate over each time step

    Ss_max[j] = frac_sulfur*y_influent[j,4]*1000/64*S2[j]/y_influent[0,4]
    Xs_max[j] = Y_srb/(1-Y_srb)*Ss_max[j]

    # Gompertz function for microbial population and dissolved sulfur
    mu_srb[j] = (- X2[0] + X2[j])/max(1e-14,t_span[j]-t_span[0])
    Xs[j]  = gompertz(t_span[j], Xs_max[j], mu_srb[j], lam)           # [g/L]      - Sulfate Reducing Bacteria - Gompertz
    Ss[j]  = Xs[j]*(1-Y_srb)/(Y_srb)                                  # [g/L]      - Sulfur dissolved concentration

            # [g/L/d]    - Gompertz parameter for SRB growth
    for snapshot in range(len(t_span)):

        mu_srb_loc = np.nan_to_num((- X2[0] + X2[snapshot])/max(1e-14,(t_span[snapshot] - t_span[0])), nan=0, neginf=0)    # [g/L/d]    - Gompertz parameter for SRB growth, local
        dXsdt[j, snapshot] = growth_SRB(t_span[snapshot], Xs_max[j], mu_srb_loc, lam)                     # [g/L/d]    - SRB growth rate matrix, local (Gompertz Derivative)

        growth_rate[j] = np.nanmax(dXsdt[j])                                  # [g/L/d]    - Get the growth rate of SRB at each time step as the maximum of the possible rates

    y_S[j]   = (KH_S*Ss[j])/P_dig                                    # [-]        - Sulfur Mole fraction in gas phase (G/L equilibrium)

#### Evaluation of the G/L equilibrium effects on the system ####
F_W = water_percentage*Q_in*rho_water/18                      # [kmol/d]    - Water Flow
F_W = F_W*1000                                                # [mol/d]     - Water Flow

q_S = y_S*q_tot                                               # [mmol/L/d] - Sulfur Outlet Specific Molar Flow

F_M = q_M*V_liq                                               # [mol/d]   - Methane Flow
F_C = q_C*V_liq                                               # [mol/d]   - CO2 Flow
F_S = q_S*V_liq                                               # [mol/d]   - Sulfur Flow
n_species = 4                                                 # [-]       - Number of species in the system

F_i = np.zeros([len(t_span),n_species])                       # [-] - Outlet Molar Fraction - In of the flash
for t in range(len(t_span)):
    F_i[t] = np.array([F_M[t], F_C[t], F_S[t], F_W])            # [mol/d] - Outlet Molar Flow - In of the flash

z_i = np.zeros([len(t_span),n_species])                         # [-] - Outlet Molar Fraction - In of the flash
x_i = np.zeros([len(t_span),n_species])                         # [-] - Outlet Molar Fraction - Liquid phase of the flash
y_i = np.zeros([len(t_span),n_species])                         # [-] - Outlet Molar Fraction - Vapor phase of the flash

K = np.zeros([len(t_span),n_species])                         # [-] - Equilibrium Constant
num = np.zeros([len(t_span),n_species])                       # [-] - Numerator of the equilibrium equation
den = np.zeros([len(t_span),n_species])                       # [-] - Denominator of the equilibrium equation

N_L = np.zeros([len(t_span),n_species])                                   # [-] - Liquid Phase Mole Fraction
N_V = np.zeros([len(t_span),n_species])                                   # [-] - Vapor Phase Mole Fraction

alpha = np.zeros(len(t_span))                                 # [-]     -
law = ('H', 'H', 'H', 'R')                                    # [-]     - Define the law to be used for the equilibrium calculation (R for Raoult's Law, H for Henry's Law)
for t in range(len(t_span)):
    F_in = sum(F_i[t])                                        # [mol/d] - Total Inlet Molar Flow
    for i in range(n_species):
        if law[i] == 'R':
            P_sp = P_sat[i]
        else:
            P_sp = H_atm[i]
        K[t,i] = P_sp/P_dig
        z_i[t,i] = F_i[t,i]/F_in
        num[t,i] = z_i[t,i]*(K[t,i]-1)
        den[t,i] = K[t,i]-1

    # sum_num = sum(num[t])
    # den_prod = np.prod(den[t])
    # # print(z_i[t,0], z_i[t,1], z_i[t,2], z_i[t,3])
    # alpha[t] = -(n_species-1)*sum_num/den_prod

    guess = sum(z_i[t,0:2])
    alpha[t] = fsolve(f_RR_equilibrium, guess , args=(z_i[t,:], law, P_sat, H_atm, P_dig)) # [-] - Solve the G/L equilibrium for the alpha factor
    N_V_tot = F_in*alpha[t]                                       # [mol/d] - Vapor Molar Flow
    N_L_tot = F_in - N_V_tot                                          # [mol/d] - Liquid Molar Flow
    for i in range(n_species):
        x_i[t,i] = z_i[t,i]/(1+alpha[t]*(K[t,i]-1))
        y_i[t,i] = K[t,i]*x_i[t,i]
        N_L[t,i] = N_L_tot*x_i[t,i]
        N_V[t,i] = N_V_tot*y_i[t,i]

entrance = sum(F_i[0,0:2])
out = sum(N_V[0,0:2])
delta = entrance - out
print('Entrance: ', entrance)
print('Out: ', out)
print('Delta: ', delta)
print('Relative Error: ', delta/entrance*100,'%')

print(N_V[0])
print(N_L[0])

print('alpha',alpha[0])
print('Liquid:', x_i[0,:])
print('Vapour:',y_i[0,:])
plt.figure()
plt.subplot(2,1,1)
plt.plot(t_span, x_i[:,0], label='Methane')
plt.plot(t_span, x_i[:,1], label='CO2')
plt.plot(t_span, x_i[:,2], label='Sulfur')
plt.plot(t_span, x_i[:,3], label='Water')
plt.legend()
plt.xlabel('Time [d]')
plt.ylabel('Molar Fraction [-]')
plt.title('Liquid Phase')
plt.subplot(2,1,2)
plt.plot(t_span, y_i[:,0], label='Methane')
plt.plot(t_span, y_i[:,1], label='CO2')
plt.plot(t_span, y_i[:,2], label='Sulfur')
plt.plot(t_span, y_i[:,3], label='Water')
plt.legend()
plt.xlabel('Time [d]')
plt.ylabel('Molar Fraction [-]')
plt.title('Vapor Phase')

plt.show()

AD-OCS/Old Versions/NEW Sulfur/V5 - VLE/V5.0 - VLE ideal/main_V5.py


# -*- coding: UTF-8 -*-

from tqdm import tqdm
import numpy as np
from torch.utils.data import DataLoader
from torch import nn
import torch
import math
import sys
from sklearn.metrics import precision_score, recall_score, accuracy_score

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

def __get_pairs(n_users, n_items, dataset):
    """
    Get the pairs of users and items.
    获取数据匹配
    :param n_users:
    :param n_items:
    :param dataset:
    :return:
    """
    ndataset = []
    for data in dataset:
        u, i, r, _ = data.strip().split(',')
        if u == 'userId':
            continue
        u, i, r = int(u), int(i), int(float(r))
        if u > n_users:
            n_users = u
        if i > n_items:
            n_items = i
        ndataset.append((u, i, r))

    return ndataset, n_users, n_items

def read_datas(input_path, file_name, test_ratio=0.1):
    """
    读取数据
    :param input_path:
    :param file_name:
    :param test_ratio:
    :return:
    """
    with open(input_path + file_name, 'r', encoding="utf-8") as f:
        all_datas = f.read().split("\n")
    all_datas = list(set(filter(None, all_datas)))
    test_datas = np.random.choice(all_datas, int(len(all_datas) * test_ratio), replace=False)
    train_datas = list(set(all_datas) - set(test_datas))
    n_users, n_items = 0, 0
    test_datas, n_users, n_items = __get_pairs(n_users, n_items, test_datas)
    train_datas, n_users, n_items = __get_pairs(n_users, n_items, train_datas)
    return train_datas, test_datas, n_users + 1, n_items + 1

class ALS(nn.Module):
    def __init__(self, n_users, n_items, dim=50):
        """
        ALS的pytorch版本
        :param n_users:
        :param n_items:
        :param dim:
        """
        super(ALS, self).__init__()
        self.users = nn.Embedding(n_users, dim, max_norm=1)
        self.items = nn.Embedding(n_items, dim, max_norm=1)
        self.sigmoid = nn.Sigmoid()

    def forward(self, u, i):
        u = self.users(u)
        i = self.items(i)
        ui = torch.sum(u * i, axis=1)
        logit = self.sigmoid(ui)
        return logit

def MSE(y_true, y_pred):
    return np.average((np.array(y_true) - np.array(y_pred)) ** 2)
def RMSE(y_true, y_pred):
    return MSE(y_true, y_pred) ** 0.5
def evalution(model, dataset):
    """
    模型评估
    :param model:
    :param dataset:
    :return:
    """
    label_sigmoid = nn.Sigmoid()
    u, i, r = dataset[:, 0], dataset[:, 1], dataset[:, 2]
    with torch.no_grad():
        output = model(u, i)
    y_pred = np.array(output.cpu().detach().numpy())
    y_true = np.array(label_sigmoid(r).cpu().detach().numpy())
    rmse = RMSE(y_true, y_pred)
    return rmse
def train(input_path, file_name, epochs=20, batch_size=1024):
    """
    lfm推荐算法训练
    :param input_path:
    :param file_name:
    :param epochs: 迭代次数
    :param batch_size:批量数据大小
    :return:
    """
    print("读取数据...")
    train_data, test_data, n_users, n_items = read_datas(input_path, file_name)
    # 初始化als模型
    print("初始化als模型...")
    model = ALS(n_users, n_items)
    optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=0.1)
    criterion = torch.nn.BCELoss()
    model.cuda()
    train_data = torch.LongTensor(train_data).cuda()
    test_data = torch.LongTensor(test_data).cuda()
    dataloader = DataLoader(train_data, batch_size=batch_size, shuffle=True)
    label_sigmoid = nn.Sigmoid()
    print("开始训练...")
    for e in range(epochs):
        all_loss = 0
        for dataset in iter(dataloader):
            u, i, r = dataset[:, 0], dataset[:, 1], dataset[:, 2]
            optimizer.zero_grad()
            r = r.float()
            result = model(u, i)
            r = label_sigmoid(r)
            loss = criterion(result, r)
            all_loss += loss
            loss.backward()
            optimizer.step()
        print('epoch{}, avg_loss={}'.format(e, all_loss / (len(train_data) // batch_size)))
        rmse = evalution(model, test_data)
        print('RMSE:{}'.format(round(rmse, 3)))
    torch.save(model, "models/pytorch_lfm.model")
def reverse_sigmoid(x):
    return -math.log(1 / (x + 1e-8) - 1)
def sigmoid(x):
    """
    sigmoid参数
    :param x:
    :return:
    """
    return 1 / (1 + math.exp(-x))
def predict_single(u_index, i_index, model_path):
    """
    预测单个数据
    :param u_index:
    :param i_index:
    :param model_path:
    :return:
    """
    u = torch.LongTensor([u_index]).to(device)
    i = torch.LongTensor([i_index]).to(device)
    model = torch.load(model_path)
    result = model(u, i)
    result = result.cpu().detach().numpy()[0]
    # result = reverse_sigmoid(result)
    print(result)
if __name__ == '__main__':
    input_path = "datas/ml-25m/"
    file_name = "ratings.csv"
    train(input_path, file_name)
    # predict_single(1, 296, "models/pytorch_lfm.model")


#!/usr/bin/python3
import primes

def triangle_numbers():
    number = 1
    increment = 2
    while True:
        yield number
        number += increment
        increment += 1

def num_divisors(n):
    return sum(1 for _ in primes.divisors(n))

for n in triangle_numbers():
    if num_divisors(n) > 500:
        print(n)
        break


from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from keras.models import Sequential
from keras.layers import Dense
from keras.callbacks import EarlyStopping
from keras.optimizers import Adam
from sklearn.model_selection import train_test_split

def run_logistic_regression(encoded_features, labels):
    # Split your data into a training set and a test set
    features_train, features_test, labels_train, labels_test = train_test_split(encoded_features,
                                                                                labels,
                                                                                test_size=0.2,
                                                                                random_state=42)

    # Initialize a logistic regression model
    model_class = LogisticRegression()

    # Train the model
    model_class.fit(features_train, labels_train)

    # Make predictions
    predictions = model_class.predict(features_test)

    # Assess the accuracy of the model
    accuracy = accuracy_score(labels_test, predictions)

    return accuracy

def run_random_forest(X, y):
    # Split the data
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

    # Initialize and train the RandomForestClassifier
    model = RandomForestClassifier(n_estimators=100, random_state=42)
    model.fit(X_train, y_train)

    # Predict the test set
    y_pred = model.predict(X_test)

    accuracy = accuracy_score(y_test, y_pred)

    return accuracy

def create_nn_model(input_shape):
    # Define the model architecture
    model = Sequential()
    model.add(Dense(32, input_dim=input_shape, activation='relu'))  # Input layer
    model.add(Dense(16, activation='relu'))  # Hidden layer
    model.add(Dense(1, activation='sigmoid'))  # Output layer

    # Compile the model
    model.compile(loss='binary_crossentropy', optimizer=Adam(), metrics=['accuracy'])

    return model

def train_and_evaluate_nn(data, target):
    # Split the data
    X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=42)

    # Create the model
    model_class = create_nn_model(X_train.shape[1])

    # Train the model
    es_callback = EarlyStopping(monitor='val_loss', patience=3)  # stop training if the model isn't improving
    history = model_class.fit(X_train, y_train, validation_split=0.2, epochs=50, callbacks=[es_callback])

    # Evaluate the model
    _, accuracy = model_class.evaluate(X_test, y_test)


class Solution:
    def eventualSafeNodes(self, graph):  # 5.11% 5.35%
        def dfs(idx, seen):
            if not graph[idx]:
                mem[idx] = set([idx])
            if idx in mem:
                return mem[idx]
            if idx in seen:
                return 'cycle'
            seen.add(idx)
            cur = set()
            for i in graph[idx]:
                temp = dfs(i, seen.copy())
                if temp == 'cycle':
                    return 'cycle'
                else:
                    cur.update(temp)
            mem[idx] = cur
            return cur

        terminal = set()
        mem = {}

        out = set()
        for index in range(len(graph)):
            test = dfs(index, set())
            if test != 'cycle':
                out.add(index)
        return sorted(terminal | out)

    def eventualSafeNodes_best_speed(self, graph):
        seen = ['new'] * len(graph)

        def hasCycle(node):
            seen[node] = 'unsafe'
            for adj_node in graph[node]:
                if (seen[adj_node] == 'unsafe') or (seen[adj_node] == 'new' and hasCycle(adj_node)):
                    return True
            seen[node] = 'safe'
            return False

        res = []
        for i in range(len(graph)):
            if seen[i] == 'new':
                hasCycle(i)
            if seen[i] == 'safe':
                res.append(i)
        return res

    def eventualSafeNodes_2nd_best_speed(self, graph):
        res= []
        def dfs(node):
            if color[node]: return color[node] == 1
            color[node] = 2
            for ch in graph[node]:
                if not dfs(ch):
                    return False
            color[node] = 1
            return True

        color = [0]*len(graph)
        for i in range(len(graph)):
            if dfs(i): res.append(i)
        return res

class Solution_best_memory:
    def explore(self, visited, index, graph):
        if index in visited:
            graph[index] = False
            return False
        if graph[index] == True:
            return True
        elif graph[index] == False:
            return False
        for j in range(len(graph[index])):
            visited.add(index)
            next_visited = visited.copy()
            is_safe = self.explore(next_visited, graph[index][j], graph)
            if not is_safe:
                graph[index] = False
                return False
        if not graph[index] == False:
            graph[index] = True
            return True

    def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
        for i in range(len(graph)):
            visited = {i}
            is_safe = True
            if graph[i] == True:
                pass
            elif graph[i] == False:
                pass
            else:
                for j in range(len(graph[i])):
                    is_safe = self.explore(visited, graph[i][j], graph)
                    if not is_safe:
                        graph[i] = False
                        break
            if not graph[i] == False:
                graph[i] = True
        solution = []
        for i in range(len(graph)):
            if graph[i]:
                solution.append(i)
        return solution

Study Plan - Graph Theory/Day 9 Standard Traversal/802 - Find Eventual Safe States.py


# Calendriers
"""Définition des calendriers Julien, Grégorien et musulman.
Bibliographie.
    [1] 'La saga des calendriers' (Jean LEFORT, Pour la Science, 1998).
    [2] 'Calendrical Calculations'.
    (Nachum Dershowitz et Edward M. Reingold, Cambridge University Press, 1997).
    [3] 'Droites discrètes et calendriers'
    (Albert Troesch, Mathématiques et sciences humaines, tome 141, 1998, p. 11-41)
        disponible sur http://www.numdam.org/article/MSH_1998__141__11_0.pdf
    [4] 'Calculs astronomiques à l'usage des amateurs'
    (Jean MEEUS, Société Astronomique de France, Paris, 2014).

Jours de la semaine commençant par 0 pour le lundi
ATTENTION : différent de [2] p. 17 où le dimanche débute le semaine."""

from enum import IntEnum

from . import fqa
from . import outils

def _corr_am(a_=0, m_=1, o_=1):
    # Entrée : une année a et un mois m.
    # Sortie : une année ajustée a et un mois m tels que o <= m <= o+11.
    i_, m_ = outils.divent(m_ - o_, 12)
    a_ += i_
    m_ += o_
    return a_, m_

def _norm_am(a_=0, m_=1):
    # Entrée : une année a et un mois m compris entre 1 et 12.
    # Sortie : une année ajustée a et un mois m tels que 3 <= m <= 14.
    a_, m_ = _corr_am(a_, m_)
    if 3 > m_:
        m_ += 12
        a_ -= 1
    return a_, m_

def _dnorm_am(a_=0, m_=1):
    # Entrée : une année a et un mois m compris entre 3 et 14.
    # Sortie : une année ajustée a et un mois m tels que 1 <= m <= 12.
    a_, m_ = _corr_am(a_, m_, 3)
    if 12 < m_:
        m_ -= 12
        a_ += 1
    return a_, m_

_JOURS = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"]

class Jours(IntEnum):
    LUNDI = 0
    MARDI = 1
    MERCREDI = 2
    JEUDI = 3
    VENDREDI = 4
    SAMEDI = 5
    DIMANCHE = 6

    # https://fr.wikiversity.org/wiki/Arabe/Vocabulaire/Jours_et_mois
    # ELETHNAYN = LUNDI       ## الإثنين
    # ETHTHOLATHA = MARDI     ## الثلاثاء
    # ELARBIEAA = MERCREDI    ## الأربعاء
    # ELKHAMIIS = JEUDI       ## الخميس
    # ELJOMOA = VENDREDI      ## الجمعة
    # ESSABAT = SAMEDI        ## السبت
    # ELAHAD = DIMANCHE       ## الأحد

    def __repr__(self):
        return "Jour de la semaine : {} {}".format(self.value, _JOURS[self.value])

    def __str__(self):
        return _JOURS[self.value]

_DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

class Days(IntEnum):
    MONDAY = 0
    TUESDAY = 1
    WEDNESDAY = 2
    THURSDAY = 3
    FRIDAY = 4
    SATURDAY = 5
    SUNDAY = 6

    def __repr__(self):
        return "Day of week : {} {}".format(self.value, _DAYS[self.value])

    def __str__(self):
        return _DAYS[self.value]

"""Douze mois de l'année numérotés à partir de 1 pour janvier."""

_MOIS = ["janvier",
         "février",
         "mars",
         "avril",
         "mai",
         "juin",
         "juillet",
         "août",
         "septembre",
         "octobre",
         "novembre",
         "décembre",
         ]

class Mois(IntEnum):
    JANVIER = 1
    FEVRIER = 2
    MARS = 3
    AVRIL = 4
    MAI = 5
    JUIN = 6
    JUILLET = 7
    AOUT = 8
    SEPTEMBRE = 9
    OCTOBRE = 10
    NOVEMBRE = 11
    DECEMBRE = 12

    # https://fr.wikiversity.org/wiki/Arabe/Vocabulaire/Jours_et_mois
    # MOUHARRAM = JANVIER	        ## محرم
    # SAFAR = FEVRIER             ## صفر
    # RABI_AL_AWWAL = MARS        ## ربيع الأول
    # RABI_AL_THANI = AVRIL       ## ربيع الثاني
    # JOUMADA_AL_AWWAL = MAI      ## جمادى الأول
    # JOUMADA_AL_THANI = JUIN     ## جمادى الثاني
    # RAJAB = JUILLET             ## رجب
    # CHA_BAN = AOUT              ## شعبان
    # RAMADAN = SEPTEMBRE         ## رمضان
    # CHAWWAL = OCTOBRE           ## شوال
    # DHOUL_AL_QA_DA = NOVEMBRE   ## ذو القعدة
    # DHOUL_AL_HIJJA = DECEMBRE   ## ذو الحجة
    def __repr__(self):
        return "Mois : {} {}".format(self.value, _MOIS[self.value - 1])

    def __str__(self):
        return _MOIS[self.value - 1]

_MONTHS = ["January",
           "February",
           "March",
           "April",
           "May",
           "June",
           "July",
           "August",
           "September",
           "October",
           "November",
           "December",
           ]

class Months(IntEnum):
    JANUARY = 1
    FEBRUARY = 2
    MARCH = 3
    APRIL = 4
    MAY = 5
    JUNE = 6
    JULY = 7
    AUGUST = 8
    SEPTEMBER = 9
    OCTOBER = 10
    NOVEMBER = 11
    DECEMBER = 12

    def __repr__(self):
        return "Month : {} {}".format(self.value, _MONTHS[self.value - 1])

    def __str__(self):
        return _MONTHS[self.value - 1]

class Date:
    """Date de trois nombres (deux premiers entiers et troisième flottant).
       Aucun traitement ni contrôle de cohérence n'est fait.
       ATTENTION : Une Date doit nécessairement être associée à un calendrier
       afin de donner un sens aux trois nombres qui la représentent.
    """

    #  REMARQUE : Le choix u, v, w est arbitraire.
    #             Il est fait pour suggérer que u n'est pas forcément
    #             une année, v un mois et w un jour avec heure au sens du
    #             calendrier grégorien (ou autres) même si cela est le plus souvent
    #             le cas dans ce contexte.
    #             Par exemple, pour le calendrier ISO u serait une année,
    #             v un numéro de semaine dans l'année et w un numéro de jour dans
    #             la semaine.
    #             L'attribut t contient le temps (l'heure) extrait de w.
    def __init__(self, calendrier, u_, v_, w_, t_=0.0):
        """Entrée : les trois paramètres u, v, w et le calendrier.
        Sortie : Le Date.
        Erreur : Si u ou v n'est pas un entier ou si w n'est pas un flottant ou un entier
                 ou si le calendrier n'est pas un Calendrier.
        """
        # assert isinstance(u_, int)
        # assert isinstance(v_, int)
        # assert (isinstance(w_, float) or isinstance(w_, int))
        assert isinstance(calendrier, Calendrier)
        self.calendrier = calendrier
        self.u, self.v = int(u_), int(v_)
        self.w, self.t = outils.ent(float(w_ + t_))

    def __eq__(self, autre):
        if not isinstance(autre, Date):
            return False
        return (self.u == autre.u and self.v == autre.v and self.w == autre.w
                and outils.egalf(self.t, autre.t)
                and self.calendrier == autre.calendrier)

    def __call__(self):
        """Date() retourne le Jour julien."""
        return self.calendrier.date_vers_jj(self)

    def __repr__(self):
        # Le format d'une peut (doit ?) dépendre du calendrier.
        return "Date({}, {}, {}, {}, {})".format(self.calendrier, self.u, self.v, self.w, self.t)

    def __str__(self):
        return "[{}, {}, {}, {}, {}]".format(self.calendrier, self.u, str(self.v), self.w, self.t)

class _Quantite:
    """Une Quantite représente un "nombre" constitué d'une partie entière n et d'un faction f.
    La fraction f vérifie 0.0 <= f < 1.0
    """

    def __init__(self, n_=0, f_=0.0):
        """Entrée : Un nombre entier n et un nombre flottant f.
        Sortie : Une Quantite.
        """
        n_ = int(n_)
        if isinstance(f_, int):
            n_ += f_
            f_ = 0.0
        f_ = float(f_)
        # au final f doit vérifier 0.0 <= f < 1.0.
        j_, self.f = outils.ent(f_)
        self.n = n_ + j_

    def __add__(self, autre):
        """Entrée : un nombre entier ou flottant à ajouter.
        Sortie : Une nouvelle Quantite translatée de autre.
        """
        n_, f_ = outils.ent(float(autre))
        n_ += self.n
        f_ += self.f
        j_, f_ = outils.ent(f_)
        return _Quantite(n_ + j_, f_)

    def __iadd__(self, autre):
        """Entrée : Un nombre entier ou flottant à ajouter.
        Sortie : La même Quantite translaté de autre.
        """
        n_, f_ = outils.ent(float(autre))
        n_ += self.n
        f_ += self.f
        j_, f_ = outils.ent(f_)
        self.n, self.f = n_ + j_, f_
        return self

    def __sub__(self, autre):
        """Soustraire un nombre ou une Quantite.
        Entrée : Un nombre entier ou flottant ou une Quantite à soustraire.
        Sortie : Un nombre flottant si autre est une Quantite.
                 Une Quantite si autre est un nombre.
        REMARQUE : Par exemple dans le cas où Quantite représente des dates,
                   la différence entre deux dates à un sens intuitif
                   mais que pourrait signifier :
                   dt1 + dt2
                   dt1 -= dt2
                   dt * 3
                   ... ?
        """
        # Soustraction d'une Quantite -> un nombre
        if isinstance(autre, _Quantite):
            n_, f_ = autre.n, autre.f
            n_, f_ = self.n - n_, self.f - f_
            j_, f_ = outils.ent(f_)
            return n_ + j_ + f_
        # Soustraction d'un nombre -> une Quantite
        n_, f_ = outils.ent(float(autre))
        n_, f_ = self.n - n_, self.f - f_
        j_, f_ = outils.ent(f_)
        return _Quantite(n_ + j_, f_)

    def __isub__(self, autre):
        """Entrée : Un nombre entier ou flottant à soustraire.
        Sortie : La même Quantite "augmentée" de autre.
        """
        n_, f_ = outils.ent(float(autre))
        n_, f_ = self.n - n_, self.f - f_
        j_, f_ = outils.ent(f_)
        self.n, self.f = n_ + j_, f_
        return self

    def __eq__(self, autre):
        if not isinstance(autre, _Quantite):
            return False
        return self.n == autre.n and outils.egalf(self.f, autre.f)

    def __call__(self):
        return self.n + self.f

    def __repr__(self):
        return "n={}, f={}".format(self.n, self.f)

    def __str__(self):
        return "(n={}, f={})".format(self.n, self.f)

class JourJulien(_Quantite):

    def __add__(self, autre):
        """Force le typage à JourJulien."""
        q = super().__add__(autre)
        return JourJulien(q.n, q.f)

    def __iadd__(self, autre):
        """Force le typage à JourJulien."""
        q = super().__iadd__(autre)
        return JourJulien(q.n, q.f)

    def __sub__(self, autre):
        """Force le typage à JourJulien si nécessaire."""
        q = super().__sub__(autre)
        if isinstance(q, _Quantite):
            return JourJulien(q.n, q.f)
        else:
            return q

    def __isub__(self, autre):
        """Force le typage à JourJulien."""
        q = super().__isub__(autre)
        return JourJulien(q.n, q.f)

    def jour_semaine(self):
        return Jours(self.n % 7)

    def kjour_semaine_precedant(self, k):
        return self - (self.n - k) % 7

    def kjour_semaine_suivant(self, k):
        return self + (6 - (self.n + 6 - k) % 7)

    def kjour_semaine_plus_proche(self, k):
        return self + (3 - (self.n + 3 - k) % 7)

    def kjour_semaine_apres(self, k):
        return self + (7 - (self.n + 7 - k) % 7)

    def kjour_semaine_avant(self, k):
        return self - (1 + (self.n - 1 - k) % 7)

# REMARQUE : Le début du jour est à minuit comme dans [2] et non pas à midi
#           comme pour le jour julien (Julian Day) en astronomie (jd = jj - 0.5).
#           De ce point de vue cela se rapproche de la notion de
#           'Rata Die' (RD) [2] p. 9 même si l'origine n'est pas la même.
# Origine = 0
EPOQUE_JJ = JourJulien()
# Par définition
EPOQUE_JD = EPOQUE_JJ + 0.5
# Origine Rata Die : voir [2] p. 14
# EPOQUE_JD = EPOQUE_RD - 1721424.5
EPOQUE_RD = EPOQUE_JD + 1721424.5
EPOQUE_HEB = EPOQUE_RD - 1373427
EPOQUE_MAY = EPOQUE_RD - 1137142
EPOQUE_HIN = EPOQUE_RD - 1132959
EPOQUE_CHI = EPOQUE_RD - 963099
EPOQUE_JUL = EPOQUE_RD - 1
EPOQUE_GRE = EPOQUE_RD + 1
EPOQUE_ISO = EPOQUE_RD + 1
EPOQUE_ETH = EPOQUE_RD + 2430
EPOQUE_COP = EPOQUE_RD + 103605
EPOQUE_PER = EPOQUE_RD + 226896
EPOQUE_ISL = EPOQUE_RD + 227015
EPOQUE_RFR = EPOQUE_RD + 654415
EPOQUE_BAH = EPOQUE_RD + 673222

class Calendrier(fqa.Base):
    """Calendrier défini comme dans [1]."""

    def date_vers_jj(self, date: Date) -> JourJulien:
        """Entrée : Une Date(calendrier, u, v, w, t) représentant la date dans le calendrier.
        Sortie : le Jour julien correspondant.
        Erreur : Si le paramètre n'est pas une date.
        """
        raise NotImplementedError("Méthode non implémentée.")

    def date(self, jj: JourJulien):
        """Entrée : Un Jour julien.
        Sortie : La Date(calendrier, u, v, w, t) représentant le Jour julien dans le calendrier.
        Erreur : Si le paramètre n'est pas un Jour julien.
        """
        raise NotImplementedError("Méthode non implémentée.")

    # TODO: formatage d'une date selon le calendrier
    # def format(self, jj):
    #    raise NotImplementedError("Méthode non implémentée.")

    def __str__(self):
        raise NotImplementedError("Méthode non implémentée.")

class _CalendrierGre(Calendrier):
    """Calendrier grégorien [année, mois, jour]."""

    def __init__(self):
        super().__init__([
            fqa.Fqa(146097, 4, 6884480),
            fqa.Fqa(1461, 4, 0),
            fqa.Fqa(153, 5, -457),
            fqa.Fqa(1, 1, -1),
        ])

    def date_vers_jj(self, date):
        """Entrée : Une Date(calendrier, a, m, j, t) représentant la date dans le calendrier.
        Sortie : le Jour julien correspondant.
        Erreur : Si le paramètre n'est pas une date.
        """
        assert isinstance(date, Date)
        a_, m_ = _norm_am(date.u, date.v)
        d_, t = date.w, date.t
        c_, b_ = outils.divent(a_, 100)
        n_ = super().__call__([c_, b_, m_, d_])
        jj_ = JourJulien(n_, t)
        return jj_

    def date(self, jj_):
        """Entrée : Un Jour julien.
        Sortie : La Date(calendrier, a, m, j, t) représentant le Jour julien dans le calendrier.
        Erreur : Si le paramètre n'est pas un Jour julien.
        """
        assert isinstance(jj_, JourJulien)
        dt_ = super().inv(jj_.n)
        a_, m_ = _dnorm_am(100 * dt_[0] + dt_[1], dt_[2])
        j_ = dt_[3]
        return Date(self, a_, Mois(m_), j_, jj_.f)

    def __str__(self):
        return "CALENDRIER_GRE"

CALENDRIER_GRE = _CalendrierGre()

class _CalendrierJul(Calendrier):
    """Calendrier julien [année, mois, jour]."""

    def __init__(self):
        super().__init__([
            fqa.Fqa(1461, 4, 6884472),
            fqa.Fqa(153, 5, -457),
            fqa.Fqa(1, 1, -1),
        ])

    def date_vers_jj(self, date):
        """Entrée : Une Date(calendrier, a, m, j, t) représentant la date dans le calendrier.
        Sortie : le Jour julien correspondant.
        Erreur : Si le paramètre n'est pas une date.
        """
        assert isinstance(date, Date)
        a_, m_ = _norm_am(date.u, date.v)
        d_, t_ = date.w, date.t
        n_ = super().__call__([a_, m_, d_])
        jj_ = JourJulien(n_, t_)
        return jj_

    def date(self, jj_):
        """Entrée : Un Jour julien.
        Sortie : La Date(calendrier, a, m, j, t) représentant le Jour julien dans le calendrier.
        Erreur : Si le paramètre n'est pas un Jour julien.
        """
        assert isinstance(jj_, JourJulien)
        dt_ = super().inv(jj_.n)
        a_, m_ = _dnorm_am(dt_[0], dt_[1])
        j_ = dt_[2]
        return Date(self, a_, Mois(m_), j_, jj_.f)

    def __str__(self):
        return "CALENDRIER_JUL"

CALENDRIER_JUL = _CalendrierJul()

class _CalendrierIsl(Calendrier):
    """Calendrier musulman [année, mois, jour]."""

    def __init__(self):
        super().__init__([
            fqa.Fqa(10631, 30, 58442583),
            fqa.Fqa(325, 11, -320),
            fqa.Fqa(1, 1, -1),
        ])

    def date_vers_jj(self, date):
        """Entrée : Une Date(calendrier, a, m, j, t) représentant la date dans le calendrier.
        Sortie : le Jour julien correspondant.
        Erreur : Si le paramètre n'est pas une date.
        """
        assert isinstance(date, Date)
        a_, m_ = _corr_am(date.u, date.v)
        d_, t_ = date.w, date.t
        n_ = super().__call__([a_, m_, d_])
        jj_ = JourJulien(n_, t_)
        return jj_

    def date(self, jj_):
        """Entrée : Un Jour julien.
        Sortie : La Date(a, m, j, t) représentant le Jour julien dans le calendrier.
        Erreur : Si le paramètre n'est pas un Jour julien.
        """
        assert isinstance(jj_, JourJulien)
        dt_ = super().inv(jj_.n)
        a_, m_, j_ = dt_[0], dt_[1], dt_[2]
        return Date(self, a_, m_, j_, jj_.f)

    def __str__(self):
        return "CALENDRIER_ISL"

CALENDRIER_ISL = _CalendrierIsl()

if "__main__" == __name__:

    # 1721424.0
    # JUL0 = EPOQUE_JUL - EPOQUE_JJ

    # a, m, j = 1,3,1

    # JUL1MARS =  Date(CALENDRIER_JUL, a, m, j)()()
    # print("JUL0", JUL0, "JUL1MARS", JUL1MARS, JUL1MARS - JUL0)

    # jul = lambda a, m, j : int((365.25 * a) // 1) + int((30.6 * (m + 1)) // 1) + j + 1720994.5

    print("EPOQUE_JUL", EPOQUE_JUL(), "EPOQUE_JUL - EPOQUE_JD", EPOQUE_JUL - EPOQUE_JD,
          1720994.5 - (EPOQUE_JUL - EPOQUE_JD))
    # print("jul", jul(a, m, j), "JUL1MARS", JUL1MARS)

    # fa, fm, fj = Fqa(1461,4,6884472), Fqa(153,5,-457), Fqa(1,1,-1),
    # print("fa(a) - EPOQUE_JUL()",fa(a) - EPOQUE_JUL(), int((365.25 * (a - 1)) // 1))
    # print("fm(m)",fm(m), int((30.6 * (m + 1)) // 1) - 122)
    # print("fj(j)",fj(j), int(j-1))

    # fm = Fqa(a=153, b=5, r=-162)
    # print("fm(m)",fm(m), int((30.6 * (m + 1)) // 1) - 122)

    # print("fa(1)",fm(1))

    print()
    j = 1
    for i in range(5):
        a = i + 1

        print()
        m = 1
        dt0 = Date(CALENDRIER_JUL, a, m, j)
        print("a m j", a, m, j)
        print("dt0", dt0, dt0(), repr(dt0))
        dt1 = eval(repr(dt0))
        print("dt1", dt1, dt0 == dt1, dt0 is dt1)
        u, v = _norm_am(a, m)
        print("a m j", u, v, j)

        print()
        m = 3
        dt = Date(CALENDRIER_JUL, a, m, j)
        print("a m j", a, m, j)
        print("dt", dt, dt())
        u, v = _norm_am(a, m)
        print("a m j", u, v, j)
        print("*** dt-dt0", dt() - dt0())

        print()
        m = 1
        dt0 = Date(CALENDRIER_GRE, a, m, j)
        print("a m j", a, m, j)
        print("dt0", dt0, dt0(), repr(dt0))
        dt1 = eval(repr(dt0))
        print("dt1", dt1, dt0 == dt1, dt0 is dt1)
        u, v = _norm_am(a, m)
        print("a m j", u, v, j)

        print()
        m = 3
        dt = Date(CALENDRIER_GRE, a, m, j)
        print("a m j", a, m, j)
        print("dt", dt, dt())
        u, v = _norm_am(a, m)
        print("a m j", u, v, j)
        print("*** dt-dt0", dt() - dt0())

        print()
        m = 1
        dt0 = Date(CALENDRIER_ISL, a, m, j)
        print("a m j", a, m, j)
        print("dt0", dt0, dt0(), repr(dt0))
        dt1 = eval(repr(dt0))
        print("dt1", dt1, dt0 == dt1, dt0 is dt1)
        u, v = _norm_am(a, m)
        print("a m j", u, v, j)

        print()
        m = 3
        dt = Date(CALENDRIER_ISL, a, m, j)
        print("a m j", a, m, j)
        print("dt", dt, dt())
        u, v = _norm_am(a, m)
        print("a m j", u, v, j)
        print("*** dt-dt0", dt() - dt0())

    print()
    print(Jours.LUNDI, repr(Jours.LUNDI))
    print(Days.MONDAY, repr(Days.MONDAY))


import threading
from concurrent.futures.thread import ThreadPoolExecutor

from tasks import logger
from tasks.crawl_task import CrawlTask

task_id = 0
tasks = {}
thread_lock = threading.Lock()

tasks_pool = ThreadPoolExecutor(max_workers=20, thread_name_prefix='tasks')

def set_new_task(task_url: str, task_crawl_depth_level: int):
    global task_id, tasks, thread_lock, tasks_pool

    with thread_lock:
        task_id += 1

        while task_id in tasks:
            logger.warning(f'Task with ID {task_id} already exists')
            task_id += 1

        new_task = CrawlTask(
            task_id=task_id,
            task_url=task_url,
            task_crawl_depth_level=task_crawl_depth_level,
        )
        tasks[task_id] = new_task

    job = tasks_pool.submit(new_task.crawl_start)
    job.add_done_callback(new_task.crawl_finish)

    return new_task

def get_task(task_id: int) -> CrawlTask:
    global tasks

    if task_id not in tasks:
        return

    return tasks[task_id]


import numpy as np
from os.path import dirname, join as pjoin
import os
from joblib import Parallel, delayed
from Utility.load_magLS import load_magLS_decoder
from Utility.sh_domain_binaural import compute_auditory_cues_magLS
from Utility.ambisonics import sph2cart, sh_xyz

def computeExponent(spl_decay_distancedoubling):
    return np.log2(10**(spl_decay_distancedoubling / 20))

def computeDirectivityFactor(directivity_index):
    return 10**(directivity_index / 10)

def computeDirectivityIndex(directivity_factor):
    return 10 * np.log10(directivity_factor)

def computeCardioidDirectivityWeights(axis_xyz, eval_xyz):
    weights = np.zeros(axis_xyz.shape[0])
    for idx in range(axis_xyz.shape[0]):
        axis_xyz[idx, :] /= np.linalg.norm(axis_xyz[idx, :])
        eval_xyz[idx, :] /= np.linalg.norm(eval_xyz[idx, :])
        weights[idx] = 0.5 + 0.5 * np.dot(axis_xyz[idx, :], eval_xyz[idx, :])

    return weights

def computeSHCovarianceMatrix(src_dirs,
                              g,
                              Css,
                              N,
                              room_volume,
                              room_T60,
                              directivity_index,
                              Css_identity=True):
    Y = sh_xyz(N, src_dirs[:, 0], src_dirs[:, 1], src_dirs[:, 2]).transpose()
    diag_g_sqrd = np.diag(g**2)

    eps = 1e-6
    room_T60 = room_T60 + eps
    gamma = computeDirectivityFactor(directivity_index)
    r_H = 0.057 * np.sqrt(room_volume / room_T60) * np.sqrt(gamma)

    YGY = Y @ diag_g_sqrd @ Css @ Y.transpose()
    Cxx = YGY + np.eye(YGY.shape[0]) * np.trace(Css) / (r_H**2 * 4 * np.pi)
    return Cxx

def computeAndSaveCues(ls_xyz,
                       source_exponents,
                       config_names,
                       head_rotations,
                       room_volume,
                       room_T60_list,
                       directivity_index_list,
                       IC_range,
                       ILD_range,
                       area_len,
                       save_path,
                       hrir_path,
                       N_ambi=1,
                       max_cue=False,
                       dataset_name=''):

    root_dir = dirname(__file__)
    utility_path = pjoin(root_dir, 'Utility')

    # Define meshgrid simulation area
    orig_area_len = area_len
    area_len = area_len + 0.1 * area_len  # array_radius + 0.1 * array_radius
    x_ls, y_ls, z_ls = ls_xyz[:, 0], ls_xyz[:, 1], ls_xyz[:, 2]

    # Define source signal covariance matrix, default is unit matrix
    Css = np.eye(x_ls.size)

    # Stack source coordinates
    ls = np.array([x_ls, y_ls, z_ls]).transpose()

    # Define source model list
    num_source_models = source_exponents.shape[0]
    assert (len(config_names) == num_source_models)
    assert (len(config_names) == len(directivity_index_list))
    assert (len(config_names) == len(room_T60_list))
    num_variables = len(config_names)

    # Create listener meshgrid
    x = np.arange(-area_len, area_len + 0.05 * orig_area_len,
                  0.05 * orig_area_len)
    y = np.arange(-area_len, area_len + 0.05 * orig_area_len,
                  0.05 * orig_area_len)
    res = x.size

    [list_X, list_Y] = np.meshgrid(x, y)
    listener = np.vstack((list_X.flatten(), list_Y.flatten(),
                          np.zeros(list_Y.flatten().size))).transpose()

    # Load gammatone magnitude windows, precomputed using the 'pyfilterbank' library
    # https://github.com/SiggiGue/pyfilterbank
    filename = 'gammatone_erb_mag_windows_nfft_1024_numbands_320.npy'
    gammatone_mag_win = np.load(pjoin(utility_path, filename))
    Nfft = int((gammatone_mag_win.shape[1] - 1) * 2)
    filename = 'gammatone_fc_numbands_320_fs_48000.npy'
    f_c = np.load(pjoin(utility_path, filename))

    # ERB scale requires using every 8th of the 320 windows
    f_c = f_c[::8]
    gammatone_mag_win = gammatone_mag_win[::8]

    # Load MagLS HRTF set
    N_ambi = int(N_ambi)
    assert (N_ambi <= 7 and N_ambi >= 1)
    path_to_hrir = os.path.join(hrir_path, 'irsOrd' + str(N_ambi) + '.wav')
    hrir = load_magLS_decoder(path_to_hrir)
    N = int(np.sqrt(hrir.shape[1] - 1))
    fs = 48000
    hrtf = np.fft.rfft(hrir, n=Nfft, axis=0)
    h_L = hrtf[:, :, 0].transpose()
    h_R = hrtf[:, :, 1].transpose()

    # Define head rotations used for evaluation of IC and ILD
    rotations = head_rotations

    num_rotations = len(rotations)
    num_listener_pos = listener.shape[0]
    num_speaker_pos = ls.shape[0]

    theta = np.zeros((num_speaker_pos, 3, num_listener_pos))

    ls = np.tile(ls[:, :, np.newaxis], (1, 1, num_listener_pos))
    listener = listener.transpose()
    listener = np.tile(listener[np.newaxis, :, :], (num_speaker_pos, 1, 1))

    theta = ls - listener

    r = np.linalg.norm(theta, axis=1)
    r = np.tile(r[:, np.newaxis, :], (1, 3, 1))
    theta_norm = theta / r
    r = r[:, 0, :]

    source_phi = np.arctan2(theta_norm[:, 1, :],
                            theta_norm[:, 0, :]) / np.pi * 180.0  # + 90.0
    source_phi = source_phi.astype(np.int32)

    source_zen = np.arccos(theta_norm[:, 2, :])

    LEV_ILD = np.zeros((num_variables, num_listener_pos, num_rotations))
    LEV_IC = np.zeros((num_variables, num_listener_pos, num_rotations))

    IC_low_lim = int(np.where(f_c >= IC_range[0])[0][0])
    IC_up_lim = int(np.where(f_c >= IC_range[1])[0][0])

    ILD_low_lim = int(np.where(f_c >= ILD_range[0])[0][0])
    ILD_up_lim = int(np.where(f_c >= ILD_range[1])[0][0])
    freq_window = gammatone_mag_win

    # tau search range, typically +- 1 millisecond
    tau_r = np.arange(-int(fs / 1000), int(fs / 1000))

    def mainLoopSourceModels(s):
        LEV_IC_tmp = np.zeros((num_listener_pos, num_rotations))
        LEV_ILD_tmp = np.zeros((num_listener_pos, num_rotations))

        w_r = np.zeros((x_ls.size, num_listener_pos))
        exponents = source_exponents[s, :]
        directivity_index = directivity_index_list[s]
        room_T60 = room_T60_list[s]

        for i in range(x_ls.size):
            w_r[i, :] = r[i, :]**exponents[i]

        for rot in range(num_rotations):
            for p in range(num_listener_pos):
                azi = source_phi[:, p] + rotations[rot]
                azi = azi / 180 * np.pi
                zen = source_zen[:, p]
                src_dirs = sph2cart(azi, zen).transpose()

                # We could apply some directivity weights here
                # rot_src_dirs = sph2cart(azi - np.pi / 2, zen).transpose()
                # w_direc = computeCardioidDirectivityWeights(ls_xyz, rot_src_dirs)
                g = w_r[:, p]  # * w_direc

                C = computeSHCovarianceMatrix(src_dirs, g, Css, N, room_volume,
                                              room_T60, directivity_index)
                IC, ILD = compute_auditory_cues_magLS(h_L, h_R, C, N,
                                                      freq_window, tau_r)

                # Average across freq ranges:
                IC = np.mean(IC[IC_low_lim:IC_up_lim])
                ILD = np.mean(ILD[ILD_low_lim:ILD_up_lim])

                # Careful: LEV_IC holds 1-IC values for direct plotting
                LEV_IC_tmp[p, rot] = 1 - IC
                LEV_ILD_tmp[p, rot] = -np.abs(ILD)

        return LEV_IC_tmp, LEV_ILD_tmp

    print('Main simulation loop started... \n')
    result_lists = Parallel(n_jobs=3)(delayed(mainLoopSourceModels)(s)
                                      for s in range(num_variables))
    print('Data is saved now.')

    res_arr = np.asarray(result_lists)

    for s in range(num_variables):
        LEV_IC[s, :, :] = res_arr[s, 0, :, :]
        LEV_ILD[s, :, :] = res_arr[s, 1, :, :]

    if max_cue:
        # worst orientation (inverted cues for plots)
        LEV_ILD = np.min(LEV_ILD, axis=-1)
        LEV_IC = np.min(LEV_IC, axis=-1)
    else:
        # mean across orientations
        LEV_ILD = np.mean(LEV_ILD, axis=-1)
        LEV_IC = np.mean(LEV_IC, axis=-1)

    LEV_ILD = np.reshape(LEV_ILD, (num_variables, res, res))
    LEV_IC = np.reshape(LEV_IC, (num_variables, res, res))

    data_to_save = {
        'LEV_ILD': LEV_ILD,
        'LEV_IC': LEV_IC,
        'list_X': list_X,
        'list_Y': list_Y,
        'ls_xyz': ls_xyz,
        'variable_names': config_names
    }

    np.save(pjoin(save_path, 'Data_' + dataset_name),
            data_to_save,
            allow_pickle=True)


import setuptools

descripcion_longa = open('Readme.txt').read()

setuptools.setup(
    name="Proyecto python interfaces",
    version="0.0.1",
    author="finfanterodal",
    author_email="finfanterodal@danielcastelao.org",
    url="https://www.danielcastelao.org",
    license="GLP",
    platforms="Unix",
    clasifiers=["Development Status :: 3 - Alpha",
                "Environment :: Console",
                "Topic :: Software Development :: Libraries",
                "License :: OSI Aproved :: GNU General Public License",
                "Programming Language :: Python :: 3.6.9",
                "Operating System :: Linux Ubuntu"
                ],
    description="Base de datos implementada en interfaz",
    long_description=descripcion_longa,
    keywords='proyectoPython',
    packages=['App', 'App/Albaranes', 'App/GestionClientes', 'App/GestionProductos', 'App/Images',
              'App/SQLiteBD'],
    scripts=["App/lanzador"],
)


#!/usr/bin/env python
from deepdive import *
import random
from collections import namedtuple

def makeSentence(list_of_words):
	s = ""
	for word in list_of_words:
		s = s + word + " "
	return s[0:len(s)-1]

GenePairLabel = namedtuple('GenePairLabel', 'g1_id, g2_id, label, type')

@tsv_extractor
@returns(lambda
        g1_id   = "text",
        g2_id   = "text",
        label   = "int",
        rule_id = "text",
    :[])
# heuristic rules for finding positive/negative examples of gene-gene interactions
def supervise(
        g1_id="text", g1_index="int",
        g2_id="text", g2_index="int",
        doc_id="text", sentence_index="int", sentence_text="text",
        tokens="text[]", lemmas="text[]", pos_tags="text[]", ner_tags="text[]",
        dep_types="text[]", doc_offsets="int[]",
    ):

    ## Constants

    GENE_WORDS = ["gene","genes"]

    PHRASAL_INTERACTIONS = ["interacts with","interaction with","interact","gene-gene interaction","genetic interaction"]

    REGULATION_WORDS = ["downregulates","downregulated","downregulate","upregulates","upregulated","upregulate"]

    MAX_DIST = 10

    # Common data objects
    g1_start_idx = min(g1_index, g2_index)
    g2_start_idx = max(g1_index, g2_index)

    # Find words before and after gene mentions and form sentences
    head_tokens = tokens[0:g1_start_idx]
    intermediate_tokens = tokens[g1_start_idx+1:g2_start_idx]
    tail_tokens = tokens[g2_start_idx+1:]
    sentence_before_genes = makeSentence(tokens[0:g1_start_idx]).lower()
    sentence_between_genes = makeSentence(tokens[g1_start_idx+1:g2_start_idx]).lower()
    sentence_after_genes = makeSentence(tokens[g2_start_idx+1:]).lower()
    full_sentence = makeSentence(tokens).lower()

    genepair = GenePairLabel(g1_id=g1_id, g2_id=g2_id, label=None, type=None)

# len([media_names[i] for i in range(len(media_names)) if media_names[i] in sentence])

    # RULE 1 (POSITIVE): A PHRASAL_INTERACTION appears in between genes
    if len([PHRASAL_INTERACTIONS[i] for i in range(len(PHRASAL_INTERACTIONS)) if PHRASAL_INTERACTIONS[i] in sentence_between_genes])>0:
        yield genepair._replace(label=2, type='POS:geneticInteraction_between_genes')

    # RULE 2 (POSITIVE): A PHRASAL_INTERACTION appears before genes
    if len([PHRASAL_INTERACTIONS[i] for i in range(len(PHRASAL_INTERACTIONS)) if PHRASAL_INTERACTIONS[i] in sentence_before_genes])>0:
        yield genepair._replace(label=1, type='POS:geneticInteraction_before_genes')

    # RULE 3 (NEGATIVE): Not a single GENE_WORD appears in sentence
    if len([GENE_WORDS[i] for i in range(len(GENE_WORDS)) if GENE_WORDS[i] in full_sentence])==0:
        yield genepair._replace(label=-1, type='NEG:noGENE_WORD_in_sentence')

    # RULE 4 (NEUTRAL): REGULATION word in sentence
    if len([REGULATION_WORDS[i] for i in range(len(REGULATION_WORDS)) if REGULATION_WORDS[i] in full_sentence])>0:
        yield genepair._replace(label=0, type='NULL:regulation')

    # RULE 5 (NEGATIVE): Sentences that are too long between two geness
    if len(intermediate_tokens) > MAX_DIST:
        yield genepair._replace(label=-1, type='neg:Too_Far_Apart')


from moduleframework import module_framework
from avocado import skipIf
from avocado import skipUnless

class SkipTest(module_framework.AvocadoTest):
    """
    :avocado: enable
    """

    def testGccSkippedInsideTest(self):
        # rewrite it to calling cancell, it was not in production of avocado,
        # but it is fixed.
        if "gcc" not in self.getActualProfile():
            self.cancel()
        self.start()
        self.run("gcc -v")

    @skipIf(module_framework.get_correct_profile() == "default")
    def testDecoratorNotSkippedForDefault(self):
        self.start()
        self.run("echo for default profile")

    @skipUnless(module_framework.get_correct_profile() == "gcc")
    def testDecoratorSkip(self):
        self.start()
        self.run("gcc -v")