import numba as nb
import numpy as np
import struct

#----------------------------------------------------------------------
# files

def bin_to_float(file):
    b = []
    for i2 in range(3):
        text = file.read(8)
        b.append(struct.unpack('<d', text)[0])
    return b

def bin_to_int(file, b = 8):
    N_str = ''
    for i in range(b):
        t = bin(ord(file.read(1)))
        t = t[2:]
        t = '0'*(8 - len(t)) + t
        N_str = str(t) + N_str
    return int(N_str, 2)

def float_to_bin(file, value):
    [d] = struct.unpack(">Q", struct.pack("<d", value))
    return '{:064b}'.format(d)

def bin_to_string1(file):  # new
    material = ''
    file.read(1)
    text = file.read(1)#.decode("utf-8")
    #count = 0
    while text != b'\x00':
        #print("text:", text)
        #if count > 20:
            #print('error:', material)
            #return
        #count += 1
        material += text.decode("utf-8")
        #print("material:", material, len(material))
        text = file.read(1)#.decode("utf-8")
    #print("return")
    #print(material)
    return material

def bin_to_string(file):
    text = file.read(6)
    return text.decode("utf-8")

def bin_to_string7(file, k):
    text = file.read(k)
    return text.decode("utf-8")

def open_file(filename):
    f = open(filename, 'rb')
    try:
        f.read(8)
        Zones = bin_to_int(f)
        points = []
        walls_list = []
        materials = []
        for i in range(Zones):
            f.read(24)
            Npoints = bin_to_int(file = f)
            for _ in range(Npoints):
                points.append(bin_to_float(f))
        Nfigures = bin_to_int(file = f)
        for i1 in range(Nfigures):
            #f.read(80)
            f.read(4*8)
            #print("i1:", i1)
            material = bin_to_string1(f)
            f.read(302-len(material))
            if material[:7] == 'Ceiling':
                material = 'Ceiling'
            """if i1 == 0:
                material = bin_to_string1(f)
            if i1 == 69:
                f.read(1)
                k = 5
                material = bin_to_string7(f, k)
                f.read(304-k-1)
            elif i1 == 70:
                material = bin_to_string7(f, 9)
                f.read(295)
            else:
                material = bin_to_string(f)
                f.read(298)"""
            materials.append(material)
            #print(i1, material)
            #f.read(298)
            faces = bin_to_int(f)
            #print('faces:', faces)
            #if i1 == 0 and faces != 9:
            #    print("error:", faces)
            #    return 0, 0,0
            #if faces < 1 and faces > 20:
            #    return 0, 0
            edge_list = []
            for i2 in range(faces):
                segments = []
                try:
                    DR = bin_to_float(f)
                except:
                    return points, walls_list
                plane_points = bin_to_int(f)
                #print('DR:', DR)
                try:
                    for _ in range(2*plane_points):
                        segments.append(bin_to_float(f))
                except:
                    return points, walls_list
                edge_list.append([DR, segments])
            walls_list.append(edge_list)
            #print(edge_list)
    finally:
        f.close()
        #print(len(walls_list))
    return points, walls_list, materials

def walls_to_arrays(walls):
    faces = [0]
    segments = [0]
    DRs = []
    face_ps = []
    face_vs = []
    for i in range(len(walls)):
        for j in range(len(walls[i])):
            face = walls[i][j]
            DRs.append(face[0])
            for k in range(len(face[1])//2):
                face_ps.append(face[1][2*k])
                face_vs.append(face[1][2*k+1])
            segments.append(segments[-1] + len(face[1])//2)
        faces.append(faces[-1] + len(walls[i]))
    return len(walls), faces, segments, DRs, np.array(face_ps), np.array(face_vs)

#----------------------------------------------------------------------

def find_crossing_plane(p1, p2, DR, facet):
    D0 = (DR[0] * facet[0][0] + DR[1] * facet[0][1] + DR[2] * facet[0][2])
    tmp1 = D0 - DR[0] * p1[0] - DR[1] * p1[1] - DR[2] * p1[2]
    tmp2 = DR[0] * (p2[0] - p1[0]) + DR[1] *(p2[1] - p1[1]) + DR[2] * (p2[2] - p1[2])
    if tmp2 == 0:
        return False
    t0 = tmp1 / tmp2
    crossing_p = [0.0] * 3
    for k in range(3):
        crossing_p[k] = (p2[k] - p1[k]) * t0 + p1[k]
    if skal(crossing_p, p1, p2) > 0:
        return False
    if is_point_inside_figure(crossing_p, DR, np.array(facet[::2]), np.array(facet[1::2])):
        return crossing_p

@nb.njit(cache=True)
def crossing_wall(p1, p2, n_walls, faces, segments,
            DRs=np.array([[]]), face_ps=np.array([[]]), face_vs=np.array([[]])):
    cr_walls = 0
    #pool_cr_points = np.array([])
    #pool_cr_points = None
    for i in range(n_walls):  # walls
        first_interaction = False
        for j in range(faces[i+1]-faces[i]):  # faces
            ind = faces[i] + j
            DR = DRs[ind]
            D0 = (DR[0] * face_ps[segments[ind]][0] + DR[1] * face_ps[segments[ind]][1]
                    + DR[2] * face_ps[segments[ind]][2])
            tmp1 = D0 - DR[0] * p1[0] - DR[1] * p1[1] - DRs[ind][2] * p1[2]
            tmp2 = DR[0] * (p2[0] - p1[0]) + DR[1] *(p2[1] - p1[1]) + DR[2] * (p2[2] - p1[2])
            if tmp2 == 0:
                continue
            t0 = tmp1 / tmp2
            crossing_p = [0.0] * 3
            for k in range(3):
                crossing_p[k] = (p2[k] - p1[k]) * t0 + p1[k]
            if skal(crossing_p, p1, p2) > 0:
                continue
            if is_point_inside_figure(crossing_p, DR,
                                face_ps[segments[ind]:segments[ind + 1], :],
                                face_vs[segments[ind]:segments[ind + 1], :]):
                #if is_pr:
                #    print('crossing point:', crossing_p)
                #crossing_p = np.array(crossing_p)
                if not cr_walls:
                    #pool = np.array(crossing_p, dtype=np.float64)
                    pool = np.zeros((2, 3))
                    pool[0,:] = np.array(crossing_p)
                    pool[1,:] = np.array(crossing_p)
                    #pool = np.vstack((np.array(crossing_p), np.array(crossing_p)))
                    cr_walls += 1
                    break
                    #if not first_interaction:
                    #    first_interaction = True
                    #else:
                    #    cr_walls += 1
                    #    break
                elif not check(pool, np.array(crossing_p)):
                    #old_pool = np.array(pool, dtype=np.float64)
                    old_pool = pool[:, :]
                    pool = np.empty((old_pool.shape[0] + 1, old_pool.shape[1]))
                    pool[:-1, :] = old_pool
                    pool[-1,:] = np.array(crossing_p)
                    #print(crossing_p)
                    #pool = np.vstack((pool, np.array(crossing_p)))
                    cr_walls += 1
                    break
                    #if not first_interaction:
                    #    first_interaction = True
                    #else:
                    #    cr_walls += 1
                    #    break

                #if pool_cr_points and crossing_p not in pool_cr_points:
                #    if not pool_cr_points:
                #        pool_cr_points = np.array(crossing_p)
                #    else:
                #        pool_cr_points = np.vstack((pool_cr_points, np.array(crossing_p)))
                #    cr_walls += 1
    return cr_walls

@nb.njit(cache=True)
def d_crossing_wall(p1, p2, n_walls, faces, segments, materials,
            DRs=np.array([[]]), face_ps=np.array([[]]), face_vs=np.array([[]])):
    #cr_walls = 0
    #faces_d = []
    #faces_theta = []
    pool = np.zeros((2, 3))
    faces_d = nb.typed.List.empty_list(nb.float64)
    faces_theta = nb.typed.List.empty_list(nb.float64)
    #faces_materials = nb.typed.List.empty_list(nb.float64)
    faces_idxs = nb.typed.List.empty_list(nb.float64)
    for i in range(n_walls):  # walls
        #if i not in [6]:   # change
        #    continue
        cr_p1 = [0.0] * 3
        cr_p2 = [0.0] * 3
        #cr_points = []
        for j in range(faces[i+1]-faces[i]):  # faces
            ind = faces[i] + j
            DR = DRs[ind]
            D0 = (DR[0] * face_ps[segments[ind]][0] + DR[1] * face_ps[segments[ind]][1]
                    + DR[2] * face_ps[segments[ind]][2])
            #tmp1 = D0 - DR[0] * p1[0] - DR[1] * p1[1] - DRs[ind][2] * p1[2]
            tmp1 = D0 - DR[0] * p1[0] - DR[1] * p1[1] - DR[2] * p1[2]
            tmp2 = DR[0] * (p2[0] - p1[0]) + DR[1] *(p2[1] - p1[1]) + DR[2] * (p2[2] - p1[2])
            if tmp2 == 0.0:
                continue
            t0 = tmp1 / tmp2
            crossing_p = [0.0] * 3
            for k in range(3):
                crossing_p[k] = (p2[k] - p1[k]) * t0 + p1[k]
            if skal(crossing_p, p1, p2) > 0.0:
                continue
            if is_point_inside_figure(crossing_p, DR,
                                face_ps[segments[ind]:segments[ind+1], :],
                                face_vs[segments[ind]:segments[ind+1], :]):
                #print("cross:", i,j,crossing_p)
                if not check(pool, np.array(crossing_p)):
                    old_pool = pool[:, :]
                    pool = np.empty((old_pool.shape[0] + 1, old_pool.shape[1]))
                    pool[:-1, :] = old_pool
                    pool[-1,:] = np.array(crossing_p)
                    if cr_p1 != [0.0]*3:
                        cr_p2 = list(crossing_p)
                        #print("Yes i,j,cr_p2:", i, j, cr_p2)
                        tmp = vec_len(cr_p1, cr_p2)
                        #print("cr1, cr2:", i,j,cr_p1, cr_p2, tmp)
                        if tmp > 0.3:
                            tmp = 0.3
                        faces_d.append(tmp)
                        cr_p1 = [p1[k] - crossing_p[k] for k in range(3)]
                        theta = np.arccos(skal_mul(cr_p1, DR) / vec_len(p1, crossing_p))
                        if theta > np.pi/2:
                            theta = np.pi - theta
                        faces_theta.append(theta)
                        #faces_materials.append(materials[i])
                        faces_idxs.append(i)
                        cr_p1 = [0.0]*3
                        #break
                    else:
                        cr_p1 = list(crossing_p)
                        #print("Yes i,j,cr_p1:", i, j, cr_p1)
    res = np.zeros((3, len(faces_d)), dtype=nb.float64) #TODO
    for i in range(len(faces_d)):
        res[0, i] = faces_d[i]
        res[1, i] = faces_theta[i]
        res[2, i] = faces_idxs[i]
    return res

@nb.njit(cache=True)
def is_point_inside_figure(p, DR, face_p=np.array([[]]),
        face_v=np.array([[]])):
    if face_p.shape[0] == 4:
        return _is_point_inside_figure_rect(p, DR, face_p, face_v)
    else:
        return _is_point_inside_figure_complex(p, DR, face_p)

@nb.njit(cache=True)
def _is_point_inside_figure_mid(p, DR, face_p=np.array([[]]), face_v=np.array([[]])):
    #DR = face[0]
    #vc = np.zeros(face_p.shape[0]//2)
    vc = []
    for v in range(face_p.shape[0]):
        #AB = face_p[1+2*v]    # vector
        AB = face_v[v]
        #AM = [p[k] - face[1][2*v][k] for k in range(3)]
        #AM = np.zeros(3)
        AM = [0.0]*3
        #AM = np.array(p - face_p[2*v])
        for k in range(3):
            tmp = face_p[v]
            AM[k] = p[k] - tmp[k]
        vc.append(vect_mul(AB, AM, DR))
    if case_more(vc):
        return True
    if case_less(vc):
        return True
    return False

@nb.njit(cache=True)
def _is_point_inside_figure_complex(p, DR,
                            face_p=np.array([[]])):
    angle = 0.0
    for i in range(len(face_p)):
        #vec1 = face_p[i-1] - p
        #vec2 = face_p[i] - p
        vec1 = [face_p[i-1, j] - p[j] for j in range(3)]
        vec2 = [face_p[i, j] - p[j] for j in range(3)]
        a = np.arccos(dot(vec1, vec2) / (vec_abs(vec1) * vec_abs(vec2)))
        #if np.cross(vec1, vec2)[2] > 0:
        #if np.cross(vec1, vec2) @ DR > 0.0:
        if vect_mul(vec1, vec2, DR) > 0.0:
            angle += a
        else:
            angle -= a
        #print("complex:", i, a, angle, np.cross(vec1, vec2)[2])
    #res = np.round(angle/(2*np.pi))
    res = angle/(2*np.pi)
    #print(res)
    #if res == 1 or res == -1:
    if res > 0.6 or res < -0.6:
        return True
    return False

@nb.njit(cache=True)
def _is_point_inside_figure_rect(p, DR, face_p=np.array([[]]), face_v=np.array([[]])):
    #tmp1 = np.array(face_p[0, :])
    AB = face_v[0, :]
    BC = face_v[1, :]
    #AM = np.zeros(3)
    AM = [p[i] - face_p[0, i] for i in range(3)]
    #BM = p - face_p[1, :]
    BM = [p[i] - face_p[1, i] for i in range(3)]
    #return (0 <= AB @ AM <= AB @ AB and 0 <= BC @ BM <= BC @ BC)
    #if np.dot(AB, AM) < 0:
    if dot(AB, AM) < 0:
        return False
    if dot(AB, AM) > dot(AB, AB):
        return False
    if dot(BC, BM) < 0:
        return False
    if dot(BC, BM) > dot(BC, BC):
        return False
    return True

@nb.njit(cache=True)
def dot(a, b):
    sum = 0.0
    for k in range(3):
        sum += a[k] * b[k]
    return sum

@nb.njit(cache=True)
def skal(crossing_p, p1, p2):
    #return (p1 - crossing_p) * (p2 - crossing_p)
    sum = 0.0
    for k in range(3):
        sum += (p1[k] - crossing_p[k]) * (p2[k] - crossing_p[k])
    return sum

@nb.njit(cache=True)
def vect_mul(AB, AM, DR):
    """ Cross + dot product
    """
    vc1 = [0.0] * 3
    vc1[0] = (AB[1] * AM[2] - AM[1] * AB[2]) * DR[0]
    vc1[1] = (AB[0] * AM[2] - AM[0] * AB[2]) * DR[1]
    vc1[2] = (AB[0] * AM[1] - AM[0] * AB[1]) * DR[2]
    return vc1[0] + vc1[1] + vc1[2]

@nb.njit(cache=True)
def case_more(vect):
    #return (vect >= 0).all()
    for x in vect:
        if x <= 0.0:
            return False
    return True

@nb.njit(cache=True)
def case_less(vect):
    #return (vect <= 0).all()
    for x in vect:
        if x >= 0.0:
            return False
    return True

@nb.njit(cache=True)
def skal_mul(vec1, vec2):
    sum = 0.0
    for i in range(3):
        sum += vec1[i]*vec2[i]
    return sum

@nb.njit(cache=True)
def vec_len(p1, p2):
    s = 0.0
    for i in range(3):
        s += (p1[i] - p2[i])**2
    return np.sqrt(s)

@nb.njit(cache=True)
def vec_abs(v):
    s = 0.0
    for i in range(3):
        s += v[i]**2
    return np.sqrt(s)

@nb.njit(cache=True)
def check(A, b):
    a = np.empty(A.shape[1], dtype=np.bool_)
    rows = A.shape[0]
    for r in range(rows):
        a = A[r] == b
        if a.all():
            return True
    return False

def waterpouring(Mt, H_chan):
    r = Mt
    H_sq = np.dot(H_chan,np.matrix(H_chan, dtype=complex).H)
    lambdas = np.linalg.eigvals(H_sq)
    lambdas = np.sort(lambdas)[::-1]
    p = 1
    gammas = np.zeros((r,1))
    flag = True
    while flag == True:
        lambdas_r_p_1 = lambdas[0:(r-p+1)]
        inv_lambdas_sum =  np.sum(1/lambdas_r_p_1)
        mu = ( Mt / (r - p + 1) ) * ( 1 + inv_lambdas_sum)
        for idx, item in enumerate(lambdas_r_p_1):
            gammas[idx] = mu - (Mt/(item))
        if gammas[r-p] < 0:
            gammas[r-p] = 0
            p = p + 1
        else:
            flag = False
    res = []
    for gamma in gammas:
        res.append(float(gamma))
    return np.array(res)


from distutils.command.clean import clean
from pathlib import Path
from os import rmdir, system
import os
import string

base = Path.home()
username = str(base).split("\\")[-1]
path = Path(base, "OneDrive", "Documentos", "curso_python", "dia6", "project", "Recetas")

def init():
    n_recipes = 0

    for n in Path(path).glob("**/*.txt"):
        n_recipes += 1

    system("cls")
    print(f"\nHello {username}.\nThe recipes are stored in {path}\nYou have {n_recipes} recipes.\n")

def menu():
    inp = "Choose an option:\n"

    options = ["Read recipe", "Create recipe", "Create category", "Delete recipe", "Delete category", "End program"]

    for n in range(0, len(options)):
        inp += f"[{n+1}] - {options[n]}\n"
    inp += ">>> "

    option = input(inp)
    if option.isnumeric() == False:
        print("Enter a number.")
        return 0

    option = int(option)
    if option < 1 or option > len(options):
        return 0

    return option

def choose_category():
    inp = "Choose a category:\n"

    categ = next(os.walk('Recetas'))[1]

    for n in range(0, len(categ)):
        inp += f"[{n+1}] - {categ[n]}\n"
    inp += ">>> "

    option = input(inp)
    if option.isnumeric() == False:
        print("Enter a number.")
        return ""

    option = int(option)
    if option < 1 or option > len(categ):
        return ""

    system("cls")
    return categ[option-1]

def choose_recipe(path):
    inp = "Choose a recipe:\n"

    recipes = next(os.walk(path))[2]

    for n in range(0, len(recipes)):
        n_path = Path(path, recipes[n])
        inp += f"[{n+1}] - {n_path.stem}\n"
    inp += ">>> "

    option = input(inp)
    if option.isnumeric() == False:
        print("Enter a number.")
        return ""

    option = int(option)
    if option < 1 or option > len(recipes):
        return ""

    system("cls")
    return recipes[option-1]

def read_recipe():
    category = ""
    recipe = ""

    while category == "":
        category = choose_category()
        if category == "":
            system("cls")
            print("Choose a valid option.")

    while recipe == "":
        recipe = choose_recipe(Path(path, category))
        if recipe == "":
            system("cls")
            print("Choose a valid option.")

    pf = open(Path(path, category, recipe))
    print(pf.read())
    input("\n\nPress enter to continue with other recipes.")
    pf.close()
    system("cls")

def create_recipe():
    category = ""

    while category == "":
        category = choose_category()
        if category == "":
            system("cls")
            print("Choose a valid option.")

    name = input("Name of your recipe: ")
    pf = open(Path(path, category, name), "w")
    inp = input("Create your recipe:\n")
    pf.write(inp)
    pf.close()
    system("cls")

def create_category():

    name = input("Name of your new directory: ")
    n_path = Path(path, name)
    os.makedirs(n_path)
    print(f"Directory {name} created.")

def delete_recipe():

    category = ""
    recipe = ""

    while category == "":
        category = choose_category()
        if category == "":
            system("cls")
            print("Choose a valid option.")

    while recipe == "":
        recipe = choose_recipe(Path(path, category))
        if recipe == "":
            system("cls")
            print("Choose a valid option.")

    name = Path(path, category, recipe).stem

    sure = input(f"Are you sure you want to delete {name.upper()}?\nPress Y for Yes or N for no. ")
    print(sure)
    if sure.lower() == "y":
        os.remove(Path(path, category, recipe))
        print("Recipe deleted.")
    elif sure.lower() == "n":
        print("Recipe not deleted.")
    else:
        print("Command not understood")

def delete_category():
    category = ""

    while category == "":
        category = choose_category()
        if category == "":
            system("cls")
            print("Choose a valid option.")

    sure = input(f"Are you sure you want to delete {category.upper()}?\nPress Y for Yes or N for no.")
    if sure.lower() == "y":
        n_path = Path(path, category)
        rmdir(n_path)
        print("Directory deleted.")
    elif sure.lower() == "n":
        print("Directory not deleted.")
    else:
        print("Command not understood")

def main():
    option = 0

    init()

    while option != -1:
        option = menu()
        if option == 0:
            system("cls")
            print("Choose a valid option.")

        system("cls")
        if option == 1:
            read_recipe()

        elif option == 2:
            create_recipe()

        elif option == 3:
            create_category()

        elif option == 4:
            delete_recipe()

        elif option == 5:
            delete_category()

        elif option == 6:
            print(f"Thanks for using us! See you soon {username}.")
            break
        else:
            print("Choose a valid option.")

if __name__ == "__main__":
    main()


from flask import flash
from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed
from wtforms import (
    StringField,
    SubmitField,
    TextAreaField,
    SelectField,
    DecimalField,
    IntegerField,
    HiddenField,
    FileField,
    MultipleFileField,
    BooleanField,
)
from wtforms.validators import (
    InputRequired,
    Length,
    Optional,
    NumberRange,
    ValidationError,
)

from myshop.models.brand_model import Brand
from myshop.models.category_model import Category
from myshop.models.product_model import Product

class ConsoleForm(FlaskForm):
    csrf_token = HiddenField()
    product_name = StringField("Název *:", validators=[InputRequired(), Length(max=80)])
    price = DecimalField(
        "Cena *:",
        validators=[InputRequired(), NumberRange(min=0, max=999999.99)],
        default=0,
    )
    discount = IntegerField(
        "Sleva:", validators=[NumberRange(min=0, max=100)], default=0
    )
    stock = IntegerField("Počet kusů:", validators=[NumberRange(min=0)], default=0)
    description = TextAreaField(
        "Popis *:", validators=[InputRequired()], render_kw={"rows": 10}
    )
    subheading = TextAreaField("Podnadpis *:", validators=[InputRequired()])

    color = SelectField(
        "Barva:",
        validators=[Optional()],
        choices=[
            ("cerna", "černá"),
            ("bila", "bílá"),
            ("seda", "šedá"),
            ("hneda", "hnědá"),
            ("tmava_hneda", "tmavě hnědá"),
            ("svetla_hneda", "světle hnědá"),
            ("modra", "modrá"),
            ("tmava_modra", "tmavě modrá"),
            ("svetla_modra", "světle modrá"),
            ("zelena", "zelená"),
            ("tmava_zelena", "tmavě zelená"),
            ("svetla_zelena", "světle zelená"),
            ("zluta", "žlutá"),
            ("oranzova", "oranžová"),
            ("cervena", "červená"),
            ("ruzova", "růžová"),
            ("fialova", "fialová"),
        ],
    )

    ssd = BooleanField("SSD Disk:", default=False)
    hdd = BooleanField("HDD Disk:", default=False)

    ssd_capacity = IntegerField(
        "Velikost disku SSD:",
        validators=[InputRequired(), NumberRange(min=0)],
        default=0,
    )
    hdd_capacity = IntegerField(
        "Velikost disku HDD:",
        validators=[InputRequired(), NumberRange(min=0)],
        default=0,
    )

    dvd_drive = BooleanField("DVD Mechanika:")

    brand_id = SelectField("Značka:", coerce=int, choices=[], validators=[Optional()])
    category_id = SelectField(
        "Kategorie:", coerce=int, choices=[], validators=[Optional()]
    )

    product_image = FileField(
        "Foto *:",
        validators=[
            InputRequired(),
            FileAllowed(["jpg", "png", "jpeg", "webp"], "Images only!"),
        ],
    )
    additional_images = MultipleFileField(
        "Další fotky:",
        validators=[FileAllowed(["jpg", "png", "jpeg", "webp"], "Images only!")],
    )

    add_product_submit = SubmitField("Přidat produkt")
    edit_product_submit = SubmitField("Upravit produkt")

    def __init__(self, *args, **kwargs):
        super(ConsoleForm, self).__init__(*args, **kwargs)
        self.brand_id.choices = [
            (brand.id, brand.brand_name) for brand in Brand.query.all()
        ]
        self.category_id.choices = [
            (category.id, category.category_name) for category in Category.query.all()
        ]

    def validate_product_name(self, product_name):
        if len(product_name.data.strip()) < 2:
            flash("Produkt musí mít alespoň dva znaky.", "error")
            raise ValidationError("Produkt musí mít alespoň dva znaky.")

        product = Product.query.filter_by(product_name=product_name.data).first()
        if product:
            flash("Tento produkt je už zaregistrován v naší databázi.", "error")
            raise ValidationError("Tento produkt je už zaregistrován v naší databázi.")

    def validate_subheading(self, subheading):
        if len(subheading.data.strip()) < 20:
            flash("Podnadpis musí mít alespoň dvacet znaků.", "error")
            raise ValidationError("Podnadpis musí mít alespoň dvacet znaků.")

    def validate_description(self, subheading):
        if len(subheading.data.strip()) < 50:
            flash("Popis musí mít alespoň padesát znaků.", "error")
            raise ValidationError("Popis musí mít alespoň padesát znaků.")

    def validate_price(self, price):
        if price.data == 0:
            flash("Cena produktu nemůže být nulová.", "error")
            raise ValidationError("Cena produktu nemůže být nulová.", "error")


import httpx
import pytest
from bilix.sites.hanime1 import api

client = httpx.AsyncClient(**api.dft_client_settings)

@pytest.mark.asyncio
async def test_get_video_info():
    data = await api.get_video_info(client, "https://hanime1.me/watch?v=39123")
    assert data.title
    data = await api.get_video_info(client, "https://hanime1.me/watch?v=13658")
    assert data.title


# -*- coding: utf-8 -*-
"""
Created on Sat Oct 27 03:07:56 2018

@author: Minkush and Mononito
"""
from scipy import spatial

def Detect(thresholdc,thresholdz,avgLatency,stddev,newTransaction):
    cosineSimilarity = 1 - spatial.distance.cosine(avgLatency,newTransaction)
    zscore = 0
    for i in range(len(avgLatency)):
        if(stddev[i] != 0):
            zscore+=((avgLatency[i]-newTransaction[i])/stddev[i])**2
    zscore/=len(avgLatency)
    cs = None
    if cosineSimilarity > thresholdc:
        cs = True
    else:
        cs = False
    zs = None
    if zscore < thresholdz:
        zs = True
    else:
        zs = False

    return cs and zs

def FindAns(Username,Password,newT):
    thresholdc = 0.5
    thresholdz = 2
    return Detect(thresholdc,thresholdz,Username[1],Username[0],newT)


import argparse
import csv
import gzip
import pathlib

import pandas
import pytest
from pandas import testing as pandas_testing

from analysis import cohort_joiner

@pytest.fixture
def dataframe():
    return pandas.DataFrame(
        {
            "patient_id": [1],
            "has_sbp_event": [True],
            "sbp_event_code": [198081000000101],
        }
    )

@pytest.fixture
def write_dataframe(tmp_path, dataframe):
    def _write_dataframe(ext):
        path = tmp_path / f"input{ext}"
        cohort_joiner.write_dataframe(dataframe, path)
        return path, dataframe

    return _write_dataframe

class TestReadDataframe:
    @pytest.mark.parametrize(
        "ext,check_dtype",
        [
            (".csv", True),
            (".csv.gz", True),
            (".feather", True),
            # Stata stores int64 as float64, meaning that the sbp_event_code column
            # causes this test to fail.
            (".dta", False),
            (".dta.gz", False),
        ],
    )
    def test_read_supported_file_type(self, write_dataframe, ext, check_dtype):
        path, dataframe_in = write_dataframe(ext)
        dataframe_out = cohort_joiner.read_dataframe(path)
        pandas_testing.assert_frame_equal(
            dataframe_in, dataframe_out, check_dtype=check_dtype
        )

    def test_read_unsupported_file_type(self):
        with pytest.raises(ValueError):
            cohort_joiner.read_dataframe(pathlib.Path("input.xlsx"))

class TestWriteDataframe:
    @pytest.mark.parametrize(
        "ext,open_func",
        [
            (".csv", open),
            (".csv.gz", gzip.open),
        ],
    )
    def test_write_csv(self, tmp_path, ext, dataframe, open_func):
        csv_path = tmp_path / f"input{ext}"
        cohort_joiner.write_dataframe(dataframe, csv_path)
        # When writing a dataframe to a CSV, it's easy to write the dataframe's index,
        # too. If the index doesn't have a name, then the first column in the CSV won't
        # have a header. This is undesirable, as it can introduce subtle bugs into
        # downstream actions within the OpenSAFELY framework, especially those that
        # expect their input to resemble cohort-extractor's output. For this reason, we
        # read the CSV that we wrote, and test that the header row (the zeroth row) is
        # correct.
        with open_func(csv_path, "rt", newline="") as f:
            lines = list(csv.reader(f))
        assert list(dataframe.columns) == lines[0]

    def test_write_feather(self, tmp_path, dataframe):
        feather_path = tmp_path / "input.feather"
        cohort_joiner.write_dataframe(dataframe, feather_path)
        feather_path.exists()

    @pytest.mark.parametrize("ext", [".dta", ".dta.gz"])
    def test_write_dta(self, tmp_path, ext, dataframe):
        dta_path = tmp_path / f"input{ext}"
        cohort_joiner.write_dataframe(dataframe, dta_path)
        dta_path.exists()

    def test_write_unsupported_file_type(self, tmp_path, dataframe):
        xlsx_path = tmp_path / "input.xlsx"
        with pytest.raises(ValueError):
            cohort_joiner.write_dataframe(dataframe, xlsx_path)

def test_left_join():
    lhs_dataframe = pandas.DataFrame(
        {
            "patient_id": [1, 3],
            "has_sbp_event": [True, True],
            "sbp_event_code": [198081000000101, 198081000000101],
        }
    )
    rhs_dataframe = pandas.DataFrame(
        {
            "patient_id": [1, 2],
            "ethnicity": [1, 1],
        }
    )
    exp_dataframe = pandas.DataFrame(
        {
            "patient_id": [1, 3],
            "has_sbp_event": [True, True],
            "sbp_event_code": [198081000000101, 198081000000101],
            "ethnicity": [1, None],
        }
    )
    obs_dataframe = cohort_joiner.left_join(lhs_dataframe, rhs_dataframe)
    pandas_testing.assert_frame_equal(exp_dataframe, obs_dataframe)

def test_parse_args(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    monkeypatch.setattr(
        "sys.argv",
        [
            "cohort_joiner.py",
            "--lhs",
            "input_2021-*.csv",
            "--rhs",
            "input_ethnicity.csv",
        ],
    )
    for name in ["input_2021-01-01.csv", "input_ethnicity.csv"]:
        pathlib.Path(name).touch()

    args = cohort_joiner.parse_args()

    assert args.lhs_paths == [tmp_path / "input_2021-01-01.csv"]
    assert args.rhs_path == tmp_path / "input_ethnicity.csv"
    assert args.output_path == tmp_path / "output" / "joined"

def test_get_path():
    with pytest.raises(argparse.ArgumentTypeError):
        cohort_joiner.get_path("input_*.csv")

class TestCheckPaths:
    def test_output_contains_input(self, tmp_path):
        lhs_paths = [tmp_path / "input_2021-01-01.csv"]
        rhs_path = tmp_path / "input_ethnicity.csv"
        output_path = tmp_path
        with pytest.raises(ValueError):
            cohort_joiner.check_paths(lhs_paths, rhs_path, output_path)

    def test_output_does_not_contain_input(self, tmp_path):
        lhs_paths = [tmp_path / "input_2021-01-01.csv"]
        rhs_path = tmp_path / "input_ethnicity.csv"
        output_path = tmp_path / "joined"
        assert cohort_joiner.check_paths(lhs_paths, rhs_path, output_path) is None

@pytest.mark.parametrize(
    "s,result",
    [
        ("input_*.csv", True),
        ("input_?.csv", True),
        ("input_[a-z].csv", True),
        ("input.csv", False),
    ],
)
def test_is_glob(s, result):
    assert cohort_joiner.is_glob(s) == result


#1d varying A proper
#very similar code to "odeint_nskm" file

import numpy as np
from scipy.integrate import solve_ivp as si
import matplotlib.pyplot as plt

def A(t,Q,R,k,Am):
    return Am+ (k*(1 + np.tanh((Q*np.sin(0.5*np.pi*t)) -R)))

def A2(t,Q,R,k1,k2,Am):
    return Am+ (k1*(1 + np.tanh((Q*np.sin(0.5*np.pi*t)) -R))) + (k2*(1 + np.tanh((Q*np.sin((0.5*np.pi*t)+(np.pi))) -R)))

def ivp_nskm(t,z,Q,R,k,k2 = 0.5,Am = 0.7,B=0.45,rf = 1):
    u = z[0]
    w = z[1]
    dudt = w*(u**2) - B*u
    if rf == 1:
        dwdt = A(t,Q,R,k,Am) - w - w*(u**2)
    else:
        dwdt = A2(t,Q,R,k,k2,Am) - w - w*(u**2)
    return [dudt,dwdt]

def basic_fig_plot(z,tmax = 20,rf = 1,Q=1.3518,R=1,k=1,k2 = 0.5,Am = 0.7,B=0.45,save = False,title='plot',tmin = 0):
    '''z should be (u,w) in form tuple,list or np array'''
    #points it will evaluate at (these are not all points it is evaluated at just the ones you want out)
    #explicitly giving it time points to get out gives a smoother graph
    tsp = np.linspace(tmin,tmax,1000)
    #solve
    sola = si(ivp_nskm,(tmin,tmax),z,t_eval = tsp,args = (Q,R,k,k2,Am,B,rf))
    #as z was a list length 2 where u = z[0] and w = z[1] can read solns like this
    u = sola.y[0]
    w = sola.y[1]
    #plot against time points
    plt.plot(tsp,u,'g')
    plt.plot(tsp,w,'b')
    plt.margins(0.01)
    plt.xlabel('time' , fontsize = 15)
    plt.ylabel('density' , fontsize = 15)
    plt.legend(['u(t)','w(t)'])
    plt.xticks(fontsize = 15)
    plt.yticks(fontsize = 15)

    if save:
        plt.savefig('plots/' + title + '.png')
    plt.show()

def t_min_find(z=(0.5,0.5),tr = (0,4),tmax = 50,points=101):
    '''z is initial cond,
tr is range of values tmin can take (i.e., how far through the cycle it is
tmax is the cut off point for the solver
points is the no of evaluations'''
    tmin_vals = np.linspace(tr[0],tr[1],points)
    #
    a_val  = []
    a2_val = []
    #for each val
    for a in tmin_vals:
        #evaluate using solver
        a_sol  = si(ivp_nskm,(a,tmax+a),z,args = (1.3513,1,1,0.5,0.7,0.45,1))
        a2_sol = si(ivp_nskm,(a,tmax+a),z,args = (4,3.42,1,0.5,0.7,0.45,2))
        #if at late times is non zero  add to list of valid regions
        if a_sol.y[0][-1] > 1e-2:
            a_val.append(a)
        if a2_sol.y[0][-1] > 1e-2:
            a2_val.append(a)
    plt.plot([0,0],[0,1.5],linewidth = 0,markersize=0)#quicker than setting range
    plt.plot(a_val,np.ones(len(a_val)),linewidth = 0,marker = 's',markersize = 1)
    plt.plot(a2_val,np.ones(len(a2_val))*0.5,linewidth = 0,marker = 's',markersize = 1)
    plt.margins(0)
    plt.show()
    return a_val ,  a2_val


import glob
import pathlib

from redis import Redis
from rq import Queue

from ticfortoe.jobs import get_and_save_rasterized_TICs

import os

testing = os.uname().nodename == "pinguin"

if testing:
    connection = Redis()
else: # must be in the lab
    connection = Redis(
        host='192.168.1.176',
        port=6379,
    )

queue = Queue(
    connection=connection,
    name="ticfortoe"
)
# queue.empty()
# queue.count

if testing:
    kwargs = {
        "rawdata_path": '/home/matteo/raw_data/majestix/M201203_013_Slot1-1_1_708.d',
        "target_path": "/tmp/test13.npz",
        "_verbose": True
    }
    # status = get_and_save_rasterized_TICs(**kwargs)
    res = queue.enqueue(
        get_and_save_rasterized_TICs,
        kwargs=kwargs
    )

patterns = []
for instr in ("gutamine", "falbala", "obelix", "majestix"):
    patterns.append(f"/mnt/ms/old/rawdata/{instr}/ARCHIVIERT/*/*.d")
    patterns.append(f"/mnt/ms/old/rawdata/{instr}/RAW/*.d")

def iter_raw_folders(patterns):
    for pattern in patterns:
        for path in glob.iglob(pattern):
            yield pathlib.Path(path)

raw_folders = list(iter_raw_folders(patterns))
_total_number_of_files = len(raw_folders)

output_folder = pathlib.Path("/mnt/ms/new/processed/.ticfortoe2")
output_folder.mkdir(parents=True, exist_ok=True)
output_folder.exists()

enqueued_jobs = []
# raw_folder_No, raw_folder = next(enumerate(raw_folders))
for raw_folder_No, raw_folder in enumerate(raw_folders):
    target_path = output_folder/f"{raw_folder.stem}.npz"
    print(f"Enquing raw folder No {raw_folder_No + 1}/{_total_number_of_files}.")
    enqueued_job = queue.enqueue(
        get_and_save_rasterized_TICs,
        kwargs={
            "rawdata_path": str(raw_folder),
            "target_path": str(target_path),
            "_verbose": True,
            "_total_number_of_files": _total_number_of_files,
            "_file_number": raw_folder_No
        }
    )
    enqueued_jobs.append(enqueued_job)

# from ticfortoe.binning import BinnedData
# BinnedData.read(output_folder/f"{raw_folder.stem}.npz")


import os
import pkg_resources
import shutil
import subprocess
import tempfile
import time

try:
    import httplib
except ImportError: # pragma: no cover
    import http.client as httplib

from pyramid.scaffolds.tests import TemplateTest

class SubstanceDTemplateTest(TemplateTest):
    # Override to avoid pyramid-specific stuff
    def install(self, tmpl_name): # pragma: no cover
        try:
            self.old_cwd = os.getcwd()
            self.directory = tempfile.mkdtemp()
            self.make_venv(self.directory)
            os.chdir(pkg_resources.get_distribution('substanced').location)
            subprocess.check_call(
                [os.path.join(self.directory, 'bin', 'python'),
                 'setup.py', 'develop'])
            os.chdir(self.directory)
            subprocess.check_call(['bin/pcreate', '-s', tmpl_name, 'Dingle'])
            os.chdir('Dingle')
            py = os.path.join(self.directory, 'bin', 'python')
            subprocess.check_call([py, 'setup.py', 'install'])
            subprocess.check_call([py, 'setup.py', 'test'])
            pserve = os.path.join(self.directory, 'bin', 'pserve')
            for ininame, hastoolbar in (('development.ini', True),
                                        ('production.ini', False)):
                proc = subprocess.Popen([pserve, ininame])
                try:
                    time.sleep(5)
                    proc.poll()
                    if proc.returncode is not None:
                        raise RuntimeError('%s didnt start' % ininame)
                    conn = httplib.HTTPConnection('localhost:6543')
                    conn.request('GET', '/')
                    resp = conn.getresponse()
                    assert resp.status == 200, ininame
                    data = resp.read()
                    toolbarchunk = b'<div id="pDebug"'
                    if hastoolbar:
                        assert toolbarchunk in data, ininame
                    else:
                        assert not toolbarchunk in data, ininame
                finally:
                    proc.terminate()
        finally:
            shutil.rmtree(self.directory)
            os.chdir(self.old_cwd)

if __name__ == '__main__':     # pragma: no cover
    test = SubstanceDTemplateTest()
    test.install('substanced')


''' takes a multi level dict and flattens it into a single level dict
    > cant handle lists of dicts within dicts'''
import collections
from pprint import pprint

def flatten_dict(dctnry, parent_key='', sep='_'):
    ''' takes a multi level dict and flattens it into a single level dict
    > cant handle lists of dicts within dicts'''
    items = []
    for k, v in dctnry.items():
        new_key = parent_key + sep + k if parent_key else k
        if isinstance(v, collections.MutableMapping):
            items.extend(flatten_dict(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)

if __name__ == '__main__':
    diction = {'a': 1, 'b': {'c':2, 'd':3}}
    pprint(flatten_dict(diction))


# -*- coding: utf-8 -*-
from pyAudioAnalysis import audioFeatureExtraction
from pyAudioAnalysis import audioBasicIO
import matplotlib.pyplot as plt
from boto.s3.connection import S3Connection
from django.conf import settings
import scipy.io.wavfile as wav

def extract_features(song):
    # Init amazon S3 to get the songs.
    conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
    # Connect to bucket
    bucket = conn.get_bucket('music-emotions')
    k = bucket.get_key(song.key)
    # Get the contents of the key into a file
    k.get_contents_to_filename("song-wavs/"+song.name)
    [Fs, x] = audioBasicIO.readAudioFile("song-wavs/"+song.name)
    x = audioBasicIO.stereo2mono(x)  # convert to MONO if required
    F = audioFeatureExtraction.stFeatureExtraction(x, Fs, round(0.050 * Fs), round(0.050 * Fs))
    F_M = a
    plt.subplot(2, 1, 1)
    plt.plot(F[0, :])
    plt.xlabel('Frame no')
    plt.ylabel('ZCR')
    plt.subplot(2, 1, 2)
    plt.plot(F[1, :])
    plt.xlabel('Frame no')
    plt.ylabel('Energy')
    plt.show()


import sys
sys.path.append(".")
import os
import random
import numpy as np
import torch
import time
from dataset.dataset_amass import AMASSDatasets
from model.model import JRTransformer
from torch.utils.data import DataLoader
from utils.metrics import batch_MPJPE_, batch_VIM_
from utils.config_3dpw import *
from utils.util import rotate_Y, get_adj, get_connect, distance_loss, relation_loss, process_pred
from datetime import datetime

class Trainer:
    def __init__(self, args):
        # Set cuda device
        if torch.cuda.is_available():
            self.device = torch.device("cuda")
            torch.cuda.manual_seed(0)
        else:
            self.device = torch.device("cpu")
        print('Using device:', self.device)
        self.cuda_devices = args.device

        # Training parameters
        self.batch_size = args.batch_size
        self.learning_rate = args.lr
        self.num_epoch = args.num_epoch
        self.weight_loss_pred = args.weight_loss_pred
        self.weight_loss_recon = args.weight_loss_recon
        self.weight_loss_aux = args.weight_loss_aux

        # Defining models
        self.model = JRTransformer(N=args.N, J=args.J, in_joint_size=args.in_joint_size, in_relation_size=args.in_relation_size,
                                   feat_size=args.d_k, out_joint_size=args.out_joint_size, out_relation_size=args.out_relation_size,
                                   num_heads=args.num_heads, depth=args.depth).to(self.device)
        self.opt = torch.optim.AdamW(self.model.parameters(), lr=self.learning_rate)
        self.scheduler_model = torch.optim.lr_scheduler.StepLR(self.opt, step_size=args.pretrain_step_size, gamma=args.pretrain_gamma)

        amass_path = AMASS_dir
        dset_train = AMASSDatasets(path_to_data=amass_path, skel_path=skel_path, input_n=args.input_length, output_n=args.output_length, split=0)
        self.train_len = len(dset_train)
        self.train_loader = DataLoader(dset_train, batch_size=self.batch_size, num_workers=2, shuffle=True)
        print("Load Train set!")
        dset_val =  AMASSDatasets(path_to_data=amass_path, skel_path=skel_path, input_n=args.input_length, output_n=args.output_length, split=1)
        self.val_len = len(dset_val)
        self.valid_loader = DataLoader(dset_val, batch_size=self.batch_size, num_workers=2, shuffle=False)
        print("Load Valid set!")
        dset_test =  AMASSDatasets(path_to_data=amass_path, skel_path=skel_path, input_n=args.input_length, output_n=args.output_length, split=2)
        self.test_len = len(dset_test)
        self.test_loader = DataLoader(dset_test, batch_size=self.batch_size, num_workers=2, shuffle=False)
        print("Load Test set!")

        self.joint_to_use = np.array([1, 2, 4, 5, 7, 8, 15, 16, 17, 18, 19, 20, 21])

        edges = [(0, 1), (1, 8), (8, 7), (7, 0),
			 (0, 2), (2, 4),
			 (1, 3), (3, 5),
			 (7, 9), (9, 11),
			 (8, 10), (10, 12),
			 (6, 7), (6, 8)]
        self.adj = get_adj(args.N, args.J, edges)
        self.adj = self.adj.unsqueeze(0).unsqueeze(-1)
        self.conn = get_connect(args.N, args.J)
        self.conn = self.conn.unsqueeze(0).unsqueeze(-1)

        # Training log
        self.log_dir = args.log_dir
        self.model_dir = 'pretrain_' + \
                'h_' + str(args.d_k) + '_' + \
                'd_' + str(args.depth) + '_' + \
                'nh_' + str(args.num_heads) + '_' +\
                datetime.now().strftime('%m%d%H%M') + '/'
        if not os.path.exists(self.log_dir + self.model_dir):
            os.makedirs(self.log_dir + self.model_dir)

    def test(self):
        self.model.eval()

        all_mpjpe = np.zeros(5)
        all_vim = np.zeros(5)
        count = 0
        with torch.no_grad():
            for i, data in enumerate(self.test_loader):
                data = data.float().cuda()
                batch_size = data.shape[0]
                if batch_size % 2 != 0:
                    continue
                data_to_use = data[:, :, self.joint_to_use].contiguous().view(batch_size//2, 2, 30, 13, 3)
				# B/2, N, T=30, 13, 3
                data_vel = torch.zeros_like(data_to_use)
                data_vel[:, :, 1:] = data_to_use[:, :, 1:] - data_to_use[:, :, :-1]
                data_pos = data_to_use - data_to_use[:, 0, 0].mean(dim=(1))[:, None, None, None]

                batch_size = data_pos.shape[0]

                input_total = torch.cat((data_pos, data_vel), dim=4).permute(0, 1, 3, 2, 4)
				# B/2, N, J, T, 6
                input_total = input_total.contiguous().view(batch_size, -1, 30, 6)
				# B/2, NxJ, T, 6

                input_joint = input_total[:,:, :16]

                pos = input_total[:,:,:16,:3]
                pos_i = pos.unsqueeze(-3)
                pos_j = pos.unsqueeze(-4)
                pos_rel = pos_i - pos_j
                dis = torch.pow(pos_rel, 2).sum(-1)
                dis = torch.sqrt(dis)
                exp_dis = torch.exp(-dis)
                input_relation = torch.cat((exp_dis, self.adj.repeat(batch_size, 1, 1, 1), self.conn.repeat(batch_size, 1, 1, 1)), dim=-1)

                pred_vel = self.model.predict(input_joint, input_relation)
                pred_vel = pred_vel[:, :, 16:]

				# Cumsum velocity to position with initial pose.
                motion_gt = input_total[..., :3].cpu().numpy()
                motion_pred = (pred_vel.cumsum(dim=2).cpu().numpy() + motion_gt[:, :, 15:16])

                metric_MPJPE = batch_MPJPE_(motion_gt[:, :13, 16:], motion_pred[:, :13, :])
                all_mpjpe += metric_MPJPE

                metric_VIM = batch_VIM_(motion_gt[:, :13, 16:], motion_pred[:, :13, :])
                all_vim += metric_VIM

                count += batch_size

            all_mpjpe *= 100
            all_vim *= 100
            all_mpjpe /= count
            all_vim /= count
            with open(os.path.join(self.log_dir + self.model_dir, 'log.txt'), 'a+') as log:
                log.write('Test MPJPE:\t avg: {:.2f} | 100ms: {:.2f} | 240ms: {:.2f} | 500ms: {:.2f} | 640ms: {:.2f} | 900ms: {:.2f}\n'.format(all_mpjpe.mean(), all_mpjpe[0],  all_mpjpe[1],  all_mpjpe[2],  all_mpjpe[3],  all_mpjpe[4]))
                log.write('Test VIM:\t avg: {:.2f} | 100ms: {:.2f} | 240ms: {:.2f} | 500ms: {:.2f} | 640ms: {:.2f} | 900ms: {:.2f}\n'.format(all_vim.mean(), all_vim[0],  all_vim[1],  all_vim[2],  all_vim[3],  all_vim[4]))
        return all_mpjpe.mean()

    def train(self):

        start_time = time.time()
        steps = 0
        losses = []
        start_epoch = 0
        self.best_eval=100

        for train_iter in range(start_epoch, self.num_epoch):
            print("Epoch:", train_iter)
            print("Time since start:", (time.time() - start_time) / 60.0, "minutes.")
            self.model.train()
            self.epoch = train_iter
            all_mpjpe = np.zeros(5)
            all_vim = np.zeros(5)

            for i, data in enumerate(self.train_loader):
                data = data.float().cuda()
                batch_size = data.shape[0]
                if batch_size % 2 != 0:
                    continue
                data_to_use = data[:, :, self.joint_to_use].contiguous().view(batch_size//2, 2, 30, 13, 3)
                # B/2, N, T=30, 13, 3
                data_vel = torch.zeros_like(data_to_use)
                data_vel[:, :, 1:] = data_to_use[:, :, 1:] - data_to_use[:, :, :-1]
                data_pos = data_to_use - data_to_use[:, 0, 0].mean(dim=(1))[:, None, None, None]

                batch_size = data_pos.shape[0]

                input_total = torch.cat((data_pos, data_vel), dim=4).permute(0, 1, 3, 2, 4)
                # B/2, N, J, T, 6
                angle = random.random()*360
                # random rotation
                input_total = rotate_Y(input_total, angle)
                input_total *= (random.random()*0.4+0.8)
                # B/2, N, J, T, 6
                input_total = input_total.contiguous().view(batch_size, -1, 30, 6)
                # B/2, NxJ, T, 6

                input_joint = input_total[:,:, :16]

                pos = input_total[:,:,:,:3]
                pos_i = pos.unsqueeze(-3)
                pos_j = pos.unsqueeze(-4)
                pos_rel = pos_i - pos_j
                dis = torch.pow(pos_rel, 2).sum(-1)
                dis = torch.sqrt(dis)
                exp_dis = torch.exp(-dis)

                exp_dis_in = exp_dis[:, :, :,:16]
                dis_recon = exp_dis[:,:,:,:16]
                dis_pred = exp_dis[:,:,:,16:]
                input_relation = torch.cat((exp_dis_in, self.adj.repeat(batch_size, 1, 1, 1), self.conn.repeat(batch_size, 1, 1, 1)), dim=-1)

                pred_vel, pred_relation, pred_vel_aux, pred_relation_aux = self.model(input_joint, input_relation)
                recon_vel, pred_vel, recon_vel_aux, pred_vel_aux = process_pred(pred_vel, pred_vel_aux)

                gt_vel = input_total[..., 3:]
                # [B, NxJ, T=30, 3]
                gt_vel_x = gt_vel[:, :, :16]
                gt_vel_y = gt_vel[:, :, 16:]

                loss_recon = distance_loss(recon_vel, gt_vel_x)
                loss_pred = distance_loss(pred_vel, gt_vel_y)
                loss_relation_recon= relation_loss(pred_relation[..., :16], dis_recon)
                loss_relation_pred = relation_loss(pred_relation[..., 16:], dis_pred)
                loss_aux_recon, loss_aux_pred, loss_aux_relation_recon, loss_aux_relation_pred = 0, 0, 0, 0
                for i_ in range(len(recon_vel_aux)):
                    loss_aux_recon = loss_aux_recon + distance_loss(recon_vel_aux[i_], gt_vel_x)
                    loss_aux_pred  = loss_aux_pred  + distance_loss(pred_vel_aux[i_], gt_vel_y)
                    loss_aux_relation_recon  = loss_aux_relation_recon + relation_loss(pred_relation_aux[i_][..., :16], dis_recon)
                    loss_aux_relation_pred  = loss_aux_relation_pred + relation_loss(pred_relation_aux[i_][..., 16:], dis_pred)

                loss =  loss_pred * self.weight_loss_pred + loss_recon * self.weight_loss_recon + loss_relation_pred * self.weight_loss_pred + loss_relation_recon * self.weight_loss_recon + (loss_aux_recon + loss_aux_pred + loss_aux_relation_pred + loss_aux_relation_recon) * self.weight_loss_aux

                self.opt.zero_grad()
                # Backward pass: compute gradient of the loss with respect to parameters.
                loss.backward()
                # Perform gradient clipping.
                torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.)
                # Calling the step function to update the parameters.
                self.opt.step()

                losses.append([loss.item()])

                # if i % 5 == 0:
                #     print(i, "Obs_Loss", losses[-1][0])
                steps += 1
            self.scheduler_model.step()

            print("Loss", np.array(losses).mean())

            all_mpjpe *= 100
            all_vim *= 100
            all_mpjpe /= self.train_len
            all_vim /= self.train_len
            with open(os.path.join(self.log_dir + self.model_dir, 'log.txt'), 'a+') as log:
                log.write('Epoch: {}, Train Loss: {},\n'.format(train_iter, np.array(losses).mean()))

            eval = self.test()
            if eval < self.best_eval:
                self.best_eval = eval
                self.best_model = self.model.state_dict()
                print('best_eval:{}'.format(self.best_eval))
                checkpoint = {
                        "net": self.model.state_dict(),
                    }
                torch.save(checkpoint, self.log_dir + self.model_dir + 'best.pt')

            if train_iter % 10 == 9:
                checkpoint = {
                    "net": self.model.state_dict(),
                }
                torch.save(checkpoint, self.log_dir + self.model_dir + 'epoch_{}.pt'.format(train_iter))

if __name__=='__main__':
    args = parse_args()
    os.environ["CUDA_VISIBLE_DEVICES"] = args.device

    trainer = Trainer(args)
    trainer.train()


from django.core.mail import send_mail
from django.conf import settings

def mail_feedback(context):
    subject = context['title']
    message = '''
    {text}

    FROM: {sender}
    '''.format(text=context['text'], sender=context['email'])
    sender = settings.FEEDBACK_EMAIL_SENDER
    receiver = settings.FEEDBACK_EMAIL_RECEIVER

    return send_mail(subject, message, sender, [receiver], fail_silently=False)


"""
    Módulo de inicialização da DAG
"""
from airflow import DAG
from airflow.operators.python_operator import (
    PythonOperator,
)
from datetime import datetime, timedelta
import pendulum

from airflow_dags.example_sql_dag.utils import (
    get_module,
    run_sql,
)

result = get_module(__file__)
module_name = result.get("module_name")
local_tz = pendulum.timezone("America/Sao_Paulo")

args = {
    "owner": "David",
    "depends_on_past": False,
    "start_date": datetime(2020, 7, 20, 0, 0, 0, tzinfo=local_tz),
    "provide_context": True,
    "retries": 1,
    "retry_delay": timedelta(minutes=5),
}

dag = DAG(
    f"{module_name}", schedule_interval=None,
    default_args=args, catchup=False, max_active_runs=1
)

def exec_sql(**kwargs):
    """
        Python Operator para execução do SQL

        Este Operator cria uma conexão com o banco de dados selecionado
        através de um Hook PostgresSQL e realiza a consulta criada dentro
        do arquivo .sql indicado

        :note: Em operadores como este, os parâmetros são fornecidos
            automaticamente pelo Airflow
    """
    parameters = dict()
    response = run_sql(
        "example_query.sql",
        "airflow_db_conn",  # nome da connection para o database (Airflow)
        "schema_name",
        "airflow_pool_conn",  # Nome do pool para o banco (Airflow)
        parameters=parameters,
        to_df=True
    )
    print(f"O dataframe de responsa:\n {response}")

with dag:
    node_exec_Sql = PythonOperator(
        provide_context=True,
        task_id="exec_sql",
        python_callable=exec_sql
    )

node_exec_Sql


import struct
from io import IOBase
from zlib import decompress

from demo_analyzer import constants

class BufferError(Exception):
    pass

class DataView(IOBase):
    def __init__(self, buffer, pos=0, size=-1):
        self._buffer = buffer
        self._initial_pos = pos
        self._relative_pos = 0
        if size == -1:
            size = len(buffer) - pos
        self._size = size

    @property
    def _absolute_pos(self):
        return self._initial_pos + self._relative_pos

    def _check_enough_bytes(self, size):
        if (self._relative_pos + size) > self._size:
            raise BufferError('not enough bytes')

    def seek(self, pos, whence=0):
        if whence == 0:
            if pos < 0:
                raise ValueError(f'negative seek position {pos}')
            if pos >= self._size:
                raise ValueError(f'seek beyond buffer size {pos}')
            self._relative_pos = pos
        elif whence == 1:
            self._relative_pos = max(0, self._relative_pos + pos)
        elif whence == 2:
            self._relative_pos = max(0, self._size + pos)
        else:
            raise ValueError('unsupported whence value')
        return self._relative_pos

    def peek(self, size=1):
        self._check_enough_bytes(size)
        return self._buffer[self._absolute_pos:self._absolute_pos + size]

    def read(self, size=1):
        ret = self.peek(size)
        self.seek(size, 1)
        return ret

    def getbuffer(self):
        return self._buffer

    def getvalue(self):
        self._buffer = self._buffer[self._initial_pos:self._initial_pos+self._size]
        self._initial_pos = 0
        return self._buffer

    def __bytes__(self):
        return self.getvalue()

class MessageView(DataView):
    type = None

    def __init__(self, buffer, pos=0, size=-1, with_type=True):
        super().__init__(buffer, pos, size)
        if with_type is True:
            self.type = message_type(self)

class DemoView(DataView):
    def readmessage(self):
        try:
            msg_size, = struct.unpack('<H', self.read(2))
            self._check_enough_bytes(msg_size)
        except BufferError:
            return
        pos = self._absolute_pos
        self.seek(msg_size, 1)
        return MessageView(self.getbuffer(), pos, msg_size)

    def __next__(self):
        message = self.readmessage()
        if not message:
            raise StopIteration
        return message

    def __iter__(self):
        return self

def open_demo(filename):
    with open(filename, 'rb') as f:
        buffer = decompress(f.read())
    return DemoView(buffer)

def message_type(message):
    msg_type, = struct.unpack('<c', message.read(1))
    return constants.MessageTypes(msg_type)


import logging
import os
import re
import time
from collections import namedtuple

SCRIPT_RE = re.compile(
    r"(?P<command>\w+)(?:\:(?P<param>[\w\s]+))?(?:\@(?P<count>\d+))?(?:\*(?P<sleep>[\d\.]+))?"
)  # noqa

Command = namedtuple("Command", ["command", "param", "count", "sleep"])

logger = logging.getLogger("roku.scripting")

def load_script(path, params=None, raw=False):
    if not os.path.exists(path):
        raise ValueError(f"script at {path} not found")
    with open(path) as infile:
        content = infile.read()
    if params:
        content = content.format(**params)
    if not raw:
        content = content.strip().split("\n")
    return content

def parse_script(script):
    commands = []
    for line in script:
        if not line:
            continue
        m = SCRIPT_RE.match(line)
        if m:
            data = m.groupdict()
            data["count"] = int(data["count"] or 1)
            data["sleep"] = float(data["sleep"]) if data["sleep"] else None
            commands.append(Command(**data))
    return commands

def run_script(roku, script, sleep=0.5):
    for cmd in script:
        logger.debug(cmd)
        for i in range(cmd.count or 1):
            func = getattr(roku, cmd.command)
            if func:
                if cmd.param:
                    func(cmd.param)
                else:
                    func()
                time.sleep(cmd.sleep or sleep)


from Project import Project
import argparse
from pythonosc import udp_client

search = "cat"

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--ip", default="192.168.1.145",
                        help="The ip of the OSC server")
    parser.add_argument("--port2", default=12000,
                        help="The port the OSC server is listening on")
    parser.add_argument("--port", type=int, default=7004,
                        help="The port the OSC server is listening on")
    args = parser.parse_args();

client = udp_client.SimpleUDPClient(args.ip, args.port)

client.send_message("/HA/Jackfreesound", search)

SimpleThings = Project(search, 10, 25)
SimpleThings.Haiku.display_haiku()


# -*- coding: utf-8 -*-
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import os
import datetime as dt

def check_results():
    pd.set_option('display.max_rows', 800)
    pd.set_option('display.min_rows', 200)

    today = dt.datetime.now()
    today_str = today.strftime("%Y-%m-%d")
    yest = today - dt.timedelta(days = 1)
    yest_str = yest.strftime("%Y-%m-%d")
    n_dir = '../nope_dataframes/'
    today_file = f'../ohlcv/{today_str}_openprices.csv'
    b = pd.read_csv(today_file, compression='gzip')
    list_of_files = [(n_dir + i) for i in os.listdir(n_dir) if (i.startswith(f'recs_{yest_str}'))]
    list_of_files = sorted(list_of_files)
    print('\n\n\n')
    for j in list_of_files:
        rec_file = j
        #rec_file = f'../nope_dataframes/recs_2021-02-19_14.30.csv'
        print (rec_file)
        print (today_file)
        a = pd.read_csv(rec_file, compression = 'gzip')
        x = pd.merge(a, b, on='symbol')
        cols = ['symbol','close_price','hurdle','confidence','buy','Open']
        x = x[cols]
        x = x[x['buy']==1]
        x['profit'] = ((x['Open'] - x['close_price']) / x['close_price']) * x['buy']
        x['profit'] = round(x['profit'],3)
        x['Open'] = round(x['Open'], 3)
        x = x.sort_values(by='profit', ascending=False)

        print (x)

        r = x['profit'].sum() / x['buy'].sum()
        print (f'num bets: {len(x.index)}')
        print (f'return: {r}')
        print ('\n\n\n')
        #sns.regplot(x['pred'], x['profit'])
        #plt.show()

if __name__ == "__main__":
    check_results()


from webex_skills.api import MindmeldAPI
from webex_skills.dialogue import responses
from webex_skills.models.mindmeld import DialogueState
import requests, json, datetime
from datetime import date

api = MindmeldAPI()

PORTAL_URL = 'http://127.0.0.1:5000'

@api.handle(intent='greet', default=True)
async def greet(current_state: DialogueState) -> DialogueState:
    text = 'Hello I am a super simple skill using NLP'
    new_state = current_state.copy()

    new_state.directives = [
        responses.Reply(text),
        responses.Speak(text),
        responses.Sleep(10),
    ]

    return new_state

@api.handle(intent='exit')
async def goodbye(current_state: DialogueState) -> DialogueState:
    text = 'Have a nice day!'
    new_state = current_state.copy()

    new_state.directives = [
        responses.Reply(text),
        responses.Speak(text),
        responses.Sleep(10),
    ]

    return new_state

@api.handle(intent='join')
async def join(current_state: DialogueState) -> DialogueState:

    # GET all appointments
    url = PORTAL_URL + '/getAppointments'
    r = requests.get(url, False)
    data = json.loads(r.text)

    today = date.today()
    today_date = today.strftime("%Y-%m-%d")
    now = datetime.datetime.now()

    today_apt = []

    # Find all the appointments for today
    # TODO: Get all appointments for specific provider
    for appointment in data:
        if (appointment['date'] == today_date):
            today_apt.append(appointment)

    is_apt = True

    if len(today_apt) == 0:
        is_apt = False
    # Sort the appointments in ascending order
    if (is_apt):
        text = 'Joining current meeting.'
        today_apt.sort(key=lambda x: x['appointmentTime'], reverse=False)

        appointment_to_join = {}

        # Set the upcoming appointment
        for i in today_apt:
            if int(i['appointmentTime']) >= now.hour:
                appointment_to_join = i
                break

        # Create the assistant-event payload
        assistant_event_payload = {
            'name': 'join',
            'payload': {
                'sip_uri': appointment_to_join['spaceUri']
            }
        }

        new_state = current_state.copy()

        new_state.directives = [
            responses.Reply(text),
            responses.Speak(text),
            responses.AssistantEvent(payload=assistant_event_payload),
            responses.Sleep(10),
        ]

    else:
        text = 'Cannot join meeting - You have no meetings scheduled for today.'
        new_state = current_state.copy()
        new_state.directives = [
            responses.Reply(text),
            responses.Speak(text),
            responses.Sleep(10),
        ]

    return new_state


# Databricks notebook source
# DBTITLE 1,Importação das funções de apoio
from pyspark.sql.functions import col, base64, lit, concat

# COMMAND ----------

# DBTITLE 1,Path onde as imagens estão armazenadas
path = "/FileStore/imgs/"

# COMMAND ----------

# DBTITLE 1,Leitura do DataFrame
#Leitura em formato binário selecionando apenas arquivos JPG
df = spark.read.format("binaryFile").option("pathGlobFilter", "*.jpg").load(path)

#Criação de coluna base64
df = df.withColumn("base64", concat( lit("data:image/jpg;base64,"), base64(col("content"))))

#Exibição do dataframe
df.display()


def visualize(cnn_model):

    import matplotlib.pyplot as plt

    # summarize history for accuracy
    plt.plot(cnn_model.history['accuracy'])
    plt.plot(cnn_model.history['val_accuracy'])
    plt.title('Model Accuracy')
    plt.ylabel('Accuracy')
    plt.xlabel('Epochs')
    plt.legend(['Train', 'Validation'], loc='lower left')
    plt.show()

    # summarize history for loss
    plt.plot(cnn_model.history['loss'])
    plt.plot(cnn_model.history['val_loss'])
    plt.title('Model Loss')
    plt.ylabel('Loss')
    plt.xlabel('Epochs')
    plt.legend(['Train', 'Validation'], loc='upper left')
    plt.show()


import urllib2

import tornado.web
import tornado.ioloop

from config import settings
from core.utils import show_urls
from core.utils import show_words
from core.utils import url_save_to_db
from core.utils import words_save_to_db
from core.utils import html_body_to_list_text

class WebPageProcessing(tornado.web.RequestHandler):
    def get(self):
        data = {}
        self.render("templates/main.html", data=data)

    def post(self):
        data = {}
        url = self.get_argument('url')
        req = urllib2.Request(url)
        try:
            html = urllib2.urlopen(req).read()
        except ValueError:
            data['error'] = {
                'msg': 'Please Enter a valid URL!'
            }
            self.render("templates/main.html", data=data)
        # Process words based on questionario
        process_words = html_body_to_list_text(html)

        # Save to DB
        words_save_to_db(process_words[:100])
        result_url = url_save_to_db(url, process_words[:100])
        data['words'] = process_words[:100]
        data['result_url'] = result_url
        self.render("templates/main.html", data=data)

class DashboardAdmin(tornado.web.RequestHandler):
    def get(self, mode=None):
        data = {}
        if mode == 'words':
            data['words'] = show_words()
        elif mode == 'urls':
            data['urls'] = show_urls()
        data['mode'] = mode

        self.render("templates/dashboard.html", data=data)

application = tornado.web.Application(
    [
        (r"/", WebPageProcessing),
        (r"/dashboard/([^/]*)", DashboardAdmin),
    ],
    **settings
)

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()


from utils.google_drive import download, upload

import os

if __name__ == '__main__':
    file_name = 'test.xlsx'
    file_save_dir = './result/google_drive_download/'

    f = os.path.join(file_save_dir, file_name)
    download.down('1Ko-qeL8zCk4AxKmT00Nw2pO_0uFRZ7d2OH_UhIXqxzM', f)  # 다운로드 파일

    f = os.path.join(file_save_dir, 'somefile.txt')  # 업로드 파일
    upload.up(f)


#V7实现文字型壁球小游戏，使用rend方法绘制
'''
Font.render(text, fgcolor=None, bgcolor=None,rotation=0, size=0) —> (Surface, Rect)
• text 绘制的文字内容
• fgcolor, bgcolor 字体颜色、背景颜色
• rotation 逆时针的旋转角度，取值0-359，部分字体可旋转
• size 文字大小，赋值该参数将覆盖Font中的设定值
----返回一个已绘制的surface对象和一个rect对象，需要结合blit()方法才能绘制到主图层上
'''

#框架---1.引入pygame库及sys库
import  pygame,sys
import pygame.freetype#文字渲染模块，主要使用Font()方法

#框架---2.初始化init()及设置
pygame.init()
size = width, height = 600,400
speed = [1,1]
WHITE = 255,255,255
GOLD = 255,251,0
pos = [230,160]

fps = 300
ftick = pygame.time.Clock()

screen = pygame.display.set_mode(size)#模式设置函数 参数为一个二元元组，表示窗口宽和高
pygame.display.set_caption("pygame壁球_文字型")#标题设置
f1 = pygame.freetype.Font("C://Windows//Fonts//msyh.ttc",36)
f1surf, f1rect= f1.render("中国制造",fgcolor=GOLD,size=50)

#框架---3.获取事件并诼类响应
    #框架3.4.均处于一个死循环
while True:
    for event in pygame.event.get():#pygame.event.get()--从事件栈中获取事件
        if event.type == pygame.QUIT:
            sys.exit()
    if pos[0] < 0 or pos[0] + f1rect.width > width:
        speed[0] = -speed[0]
    if pos[1] < 0 or pos[1] + f1rect.bottom > height:
        speed[1] = -speed[1]
    pos[0] = pos[0] + speed[0]
    pos[1] = pos[1] + speed[1]
#框架---4.刷新屏幕
    screen.fill(WHITE)#背景填充 黑色（BLACK = 0，0，0）白色（WHITE = 255，255，255）
    f1surf, f1rect = f1.render("中国制造", fgcolor=GOLD, size=50)
    screen.blit(f1surf,(pos[0],pos[1]))
    pygame.display.update()#刷新屏幕  update（）---只是更新有变化的部分 flip()---重新绘制整个窗口
    ftick.tick(fps)


import os
import openai
from dotenv import load_dotenv

load_dotenv()

def _load_openai():
    openai.proxy = {
        "http": "http://127.0.0.1:7890",
        "https": "http://127.0.0.1:7890"
    }
    openai.api_key = os.getenv("OPENAI_API_KEY")
    print('Init OpenAI env')
    return openai

def _load_aiproxy():
    openai.proxy = {
        "http": "http://127.0.0.1:7890",
        "https": "http://127.0.0.1:7890"
    }
    openai.api_key = os.getenv("AIPROXY_API_KEY")
    openai.api_base = "https://api.aiproxy.io/v1"
    print('Init AIPROXY env')
    return openai

def init_llm(is_open_ai: bool = True):
    return _load_openai() if is_open_ai else _load_aiproxy()


import random
import numpy as np
from typing import List
from scipy.optimize import linprog
import utils

def chi(strings, i, j, a):
    if strings[i][j] == a:
        return 0
    return 1

def reconstruct_solution(m, Q, primary_reference_string, x_values, alphabet):
    A = len(alphabet)
    s_prime_as_list = ['' for _ in range(m)]
    p_index = 0
    for x_index in range(m):
        if x_index in Q:
            s_prime_as_list[x_index] = primary_reference_string[x_index]
        else:
            # For each position j we treat all of its a-solutions as the probability distribution
            # for picking the letter a, that is j: (xja1, xja2, ... xja|A|) is the distrib
            candidate_vars = x_values[p_index * A:(p_index + 1) * A]
            # print(f'x_values={x_values}', file=sys.stderr)
            # print(f'candidate vars={candidate_vars}', file=sys.stderr)
            # print(f'Candidate vars sum: {sum(candidate_vars)}')
            alph_idx = random.choices(range(len(candidate_vars)), k=1, weights=candidate_vars)[0]
            s_prime_as_list[x_index] = alphabet[alph_idx]
            p_index += 1

    s_prime = ''.join(s_prime_as_list)
    return s_prime

# Optimize on disagreeing positions
# P - disagreeing positions
# Q - agreeing positions
def solve_by_lp_relaxation(P, Q, alphabet, m, n, original_strings, primary_reference_string):
    LP_T_ = 'float64'

    A = len(alphabet)
    nP = len(P)

    # There are nP*A + 1 variables - nP*A for each xja, and 1 for d
    num_variables = nP*A + 1

    # ======================= CONSTRUCTING THE EQUALITY CONSTRAINTS ========================
    # There are nP constraints with equality
    lp_eq_matrix = np.zeros((nP, num_variables), dtype=LP_T_)
    # For each j we need an "exactly one" constraints
    # The constraint will have ones only within one j-group, and zeros on other positions
    # Therefore we iterate over j-groups
    for i in range(nP):
        left_bound = i*A
        right_bound = (i+1)*A
        lp_eq_matrix[i][left_bound:right_bound] = np.ones(A, dtype=LP_T_)

    # The ds are not in this part and they remain zeros since the matrix was constructed with np.zerps
    # RHS are all ones
    lp_eq_b = np.ones(nP, dtype=LP_T_)

    # ======================= CONSTRUCTING THE INEQUALITY CONSTRAINTS ======================
    # There are n inequality constraints
    # For x_j_a, its absolute position as a variable
    # is j*A + a
    lp_leq_matrix = np.zeros((n, num_variables), dtype=LP_T_)
    # Each of them has -1 coefficient with d, and those correspond to the very last column
    lp_leq_matrix[:, -1] = -np.ones(n, dtype=LP_T_)
    # Other coefficients are chi(i, j, a)
    for i in range(n):
        for a in range(A):
            for j in range(nP):
                actual_var_idx = j*A + a
                lp_leq_matrix[i][actual_var_idx] = chi(original_strings, i, j, alphabet[a])
    # RHS are -d(si|Q, s'|Q)
    lp_leq_b = -np.array([utils.hamming_distance(utils.sat(original_strings[i], Q), utils.sat(primary_reference_string, Q)) for i in range(n)], dtype='int32')

    # Target function is just 'd'
    c = np.zeros(num_variables, dtype=LP_T_)
    c[-1] = 1

    # Every variable must be positive
    lower_bounds = [0.0 for _ in range(num_variables)]
    # xs are constrainted by 1, d is unconstrained above
    upper_bounds: List[any] = [1.0 for _ in range(num_variables-1)] + [None]

    # Now we just plug it into scipy's solver
    # sout, serr = sys.stdout, sys.stderr
    # sys.stdout, sys.stderr = None, None
    lp_solution = linprog(c,
                          A_ub=lp_leq_matrix,
                          b_ub=lp_leq_b,
                          A_eq=lp_eq_matrix,
                          b_eq=lp_eq_b,
                          bounds=list(zip(lower_bounds, upper_bounds)))
    # sys.stdout, sys.stderr = sout, serr

    if not lp_solution.success:
        print('not stonks')
        return None

    # print(lp_solution)
    s_prime = reconstruct_solution(m, Q, primary_reference_string, lp_solution.x, alphabet)
    return s_prime, utils.problem_metric(s_prime, original_strings)


import datetime
from google.appengine.ext import ndb
from google.net.proto import ProtocolBuffer
from webob import exc
import common
import converters
from datastore import models, transactions
from util import  parse_csv, parse, util, currency_rates_util

class DoEditProfile(common.CommonHandler):
  def HandlePost(self, command):
    # TODO: check permissions
    profile_id = parse.ParseInt(self.request.get('profile_id'))
    name = self.request.get('name', None)
    main_currency = self.request.get('main_currency', None)

    # TODO: use JSON request
    kw = {}
    if name is not None:
      kw['name'] = name

    if command == 'add':
      kw['name'] = kw.get('name') or 'Untitled'
      main_currency = main_currency or 'USD'
      assert currency_rates_util.IsCurrencySupported(main_currency)
      kw['main_currency'] = main_currency
      profile = models.Profile.Create(self.visitor.key.id(), **kw)
      models.User.Update(
        self.visitor.key.id(), active_profile_id=profile.key.id())
    elif command == 'edit':
      profile = models.Profile.Update(profile_id, **kw)
    elif command == 'delete':
      assert profile_id is not None
      if profile_id == self.visitor.active_profile_id:
        models.User.Update(self.visitor.key.id(), active_profile_id=None)
      ndb.Key(models.Profile, profile_id).delete()
      profile = None
    else:
      raise ValueError('Command %r is not supported' % command)

    response = {'status': 'ok'}
    if profile:
      response['profile'] = converters.ConvertProfile(profile)
    return response

class DoSetActiveProfile(common.CommonHandler):
  def HandlePost(self):
    profile_id = parse.ParseInt(self.request.get('id'))

    if models.Profile.get_by_id(profile_id):
      models.User.Update(self.visitor.key.id(), active_profile_id=profile_id)
      return {'status': 'ok'}
    else:
      return {'status': 'profile_does_not_exist'}

class DoConnectToProfile(common.CommonHandler):
  def HandlePost(self):
    profile_code = self.request.get('profile_code')
    if not profile_code:
      raise exc.HTTPBadRequest('Profile code is not specified')

    try:
      profile = models.Profile.GetByCode(profile_code)
    except ProtocolBuffer.ProtocolBufferDecodeError:
      raise exc.HTTPBadRequest('Profile code %r can\'t be parsed' % profile_code)
    if not profile:
      raise exc.HTTPBadRequest('Profile for code %r does not exist' % profile_code)

    # TODO: ask the owner's permission.
    profile.AddUser(self.visitor.key.id())
    # TODO: create a helper function for this
    models.User.Update(
      self.visitor.key.id(), active_profile_id=profile.key.id())

    return {'status': 'ok'}

class DoEditAccount(common.CommonHandler):
  @common.active_profile_required
  def HandlePost(self, command):
    account_id = parse.ParseInt(self.request.get('account_id'))
    name = self.request.get('name', None)
    currency = self.request.get('currency', None)
    type = self.request.get('type', None)
    balance = parse.ParseFloat(self.request.get('balance'))

    # TODO: use JSON request
    kw = {}
    if name is not None:
      kw['name'] = name

    if command == 'add':
      kw['name'] = kw.get('name') or 'Untitled'
      if type == models.Account.Types.VIRTUAL and not currency:
        currency = self.profile.main_currency
      assert currency_rates_util.IsCurrencySupported(currency)
      kw['currency'] = currency
      if not type:
        type = models.Account.Types.PHYSICAL
      assert type in models.Account.Types.ALL
      kw['type'] = type

      account = self.profile.AddAccount(**kw)
    elif command == 'edit':
      assert account_id is not None
      account = self.profile.UpdateAccount(account_id, **kw)
    elif command == 'delete':
      assert account_id is not None
      self.profile.DeleteAccount(account_id)
      account = None
    else:
      raise ValueError('Command %r is not supported' % command)

    if account and balance is not None and abs(balance - account.balance) > 0.001:
      transactions.AddTransaction(
        self.profile.key.id(), balance - account.balance, util.DatetimeUTCNow(),
        description='Manual account balance adjust',
        dest_account_id=account.id, source='manual')
      self.ReloadProfile()

    response = {'status': 'ok'}
    if account:
      response['account'] = converters.ConvertAccount(
        self.profile.GetAccountById(account.id))
    return response

class DoEditTransaction(common.CommonHandler):
  @common.active_profile_required
  def HandlePost(self, command):
    amount = parse.ParseFloat(self.request.get('amount'))
    description = self.request.get('description')
    # TODO: use consistent date formats.
    raw_date = self.request.get('date')
    date = raw_date and datetime.datetime.strptime(raw_date, '%d.%m.%Y')
    transaction_id = parse.ParseInt(self.request.get('id'))

    if command == 'add':
      source_account_id = parse.ParseInt(self.request.get('source_account_id'))
      dest_account_id = parse.ParseInt(self.request.get('dest_account_id'))
      transaction = transactions.AddTransaction(
        self.profile.key.id(), amount, date, description=description,
        source_account_id=source_account_id, dest_account_id=dest_account_id,
        source=models.Transaction.Sources.MANUAL)
    elif command == 'edit':
      assert transaction_id is not None
      transaction = transactions.UpdateTransaction(
        self.profile.key.id(), transaction_id, amount, date, description=description)
    elif command == 'delete':
      assert transaction_id is not None
      transactions.DeleteTransaction(self.profile.key.id(), transaction_id)
      transaction = None
    else:
      raise ValueError('Command %r is not supported' % command)

    response = {'status': 'ok'}
    if transaction:
      response['transaction'] = converters.ConvertTransaction(transaction)
    return response

# Not tested

class DoAddParseSchema(common.CommonHandler):
  def HandlePost(self):
    name = self.request.get('name')
    schema = self.request.get('schema')

    self.profile.parse_schemas.append(
      models.ParseSchema(name=name, schema=schema))
    self.profile.put()

    self.WriteToJson({'status': 'ok'})

class DoApplyParseSchemaToImportedFile(common.CommonHandler):
  def HandlePost(self):
    imported_file_id = int(self.request.get('id'))
    schema = self.request.get('schema')

    imported_file = lookup.GetImportedFileById(self.profile, imported_file_id)
    imported_file.schema = schema
    imported_file.parsed = True
    imported_file.parsed_transactions = parse_csv.ParseCsv(
      imported_file.schema, imported_file.source_file)

    # For future performance
    imported_file.source_file = None
    imported_file.put()

    self.WriteToJson({'status': 'ok'})


import os.path as op
import json

from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from soma import aims
from deepsulci.deeptools.dataset import extract_data
from deepsulci.sulci_labeling.method.unet import UnetSulciLabeling
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from using_deepsulci.cohort import Cohort

def main():
    wk_dir = "/neurospin/dico/bcagna/data/deepsulci_basic_learning"
    model_f = wk_dir + "/models/cohort-pclean50A_hemi-L_model-unet3d_d00b01/run-01/cohort-pclean50A_hemi-L_model-unet3d_d00b01_model.mdsm"
    cohort_name = 'PClean_hemi-L'
    out_f = '/var/tmp/tmp_data_sulci.csv'
    vs = 2

    cfile = wk_dir + '/cohorts/cohort-' + cohort_name + '.json'
    cohort = Cohort(from_json=cfile)

    graphs_f = [s.graph for s in cohort.subjects]
    model_params_f = model_f[:-11] + '_params.json'

    params = json.load(open(model_params_f, 'r'))
    ss_list = params["sulci_side_list"]

    n_graphs = len(graphs_f)
    n_labels = len(ss_list)
    print('{} labels'.format(n_labels))

    model = UnetSulciLabeling(
        ss_list, num_filter=64, batch_size=1, dropout=0, cuda=-1)
    model.load(model_f, dropout=0)

    results = {}
    for ss in ss_list:
        results[ss + '_p'] = []
        results[ss + '_e'] = []

    # for ig, gfile in enumerate(graphs_f):
    #     print("Labelling graph {}/{}".format(ig+1, n_graphs))
    #     data = extract_data(aims.read(gfile), voxel_size=vs, filter_key='name',
    #                         filter_list=ss_list)
    #     ytrue, ypred, prob = model.labeling(gfile, data['bck'], data['names'])
    #
    #     labels = np.argmax(prob, axis=1)
    #     labels_prob = np.exp(np.max(prob, axis=1))
    #
    #     for s, ss in enumerate(ss_list):
    #         avg_prob = np.nan_to_num(np.mean(labels_prob[labels == s]))
    #         error_rate = np.sum(np.array(ytrue) == np.array(ypred)) / len(ypred)
    #         results[ss + '_p'].append(avg_prob)
    #         results[ss + '_e'].append(error_rate)
    # df = pd.DataFrame(results)
    # df.to_csv(out_f, index=False)

    results = pd.read_csv(out_f)
    clf = LinearRegression()
    x = np.linspace(0, 1, 2)
    lin_preds = {}
    r = []
    coefs = {}
    for ss in ss_list:
        if len(results[ss + '_p']) > 0:
            xs = np.atleast_2d(results[ss + '_p']).T
            clf.fit(xs, results[ss + '_e'])
            lin_preds[ss] = clf.predict(np.atleast_2d(x).T)
            r.append(r2_score(results[ss + '_e'], clf.predict(xs)))
            coefs[ss] = [clf.coef_[0], clf.intercept_]
        else:
            r.append(0)
    r = np.array(r)

    sort_idx = np.argsort(r)
    r = r[sort_idx]
    ss_list = np.array(ss_list)[sort_idx]

    v = 12
    fig, axes = plt.subplots(6, v, figsize=(24, 12), sharex=True, sharey=True)
    for i in range(6):
        for j in range(v):
            idx = i * v + j
            if idx in range(n_labels):
                ss = ss_list[idx]

                ax = axes[i, j]
                ax.scatter(results[ss + '_p'], results[ss + '_e'], s=4)
                if ss in lin_preds.keys():
                    ax.plot(x, lin_preds[ss], '--k', linewidth=.8)
                    ax.text(.1, .1, "{:.03f}".format(r[idx]))
                    ax.text(.1, .2, "{:.3f}*x + {:.03f}".format(coefs[ss][0], coefs[ss][1]))
                ax.set_xlim([0, 1])
                ax.set_ylim([0, 1])
                ax.set_title(ss)
                ax.grid()

    plt.tight_layout()
    fig.savefig(op.join(wk_dir + '/figures/labelling_accuracy_vs_label_probability.svg'))
    plt.show()

if __name__ == "__main__":
    main()


import importlib
import torch
import numpy as np
import random
from torch.utils.data import DataLoader, Subset

class PytorchDataset:
    """Base class defining pytorch datasets."""
    def __init__(self, dataset_name) -> None:
        """ Constructor method.

            Parameters:
            dataset_name    (str): Name of dataset to use.
        """
        module = importlib.import_module(f"torchvision.datasets")
        self.data_class = getattr(module, dataset_name)
        self.client_data_indices = []
        self.train_data = None
        self.test_data = None
        self.public_data = None
        self.num_workers = 0

    def _split_train_public(self, public_fraction, transform, split=None):
        """
        """
        if split is None:
            train_data = self.data_class(
                root='data',
                train=True,
                transform=transform,
                download=True)
        else:
            train_data = self.data_class(
                root='data',
                train=True,
                transform=transform,
                download=True,
                split=split)
            train_data.targets = train_data.targets - 1

        if not torch.is_tensor(train_data.targets):
            train_data.targets = torch.tensor(train_data.targets)

        idx_split = int(len(train_data) * public_fraction)

        return Subset(train_data, np.arange(idx_split)), Subset(train_data, np.arange(idx_split, len(train_data)))

    def generate_client_data(self, n_clients, distribution, alpha):
        """ Generate iid client data or non-iid by sampling from Dirichlet distribution.

            Parameters:
            n_clients       (int): Number of clients.
            distribution    (str): Indicator to sample iid or non-iid.
            alpha           (float): Concentration parameter for Dirichlet distribution.
        """
        labels = np.array([self.train_data[i][1] for i in range(len(self.train_data))])
        n_classes = len(np.unique(labels))
        partition_matrix = np.ones((n_classes, n_clients))

        # iid: Sample from each class until no samples left.
        if distribution == "iid":
            partition_matrix /= n_clients
            local_sets_indices = [np.array([], dtype=int) for _ in range(n_clients)]
            clients_iter = np.arange(n_clients)

            for i in range(n_classes):
                class_indices = np.where(labels == i)[0]

                clients_iter = clients_iter[::-1]
                samples_left = True
                while samples_left:
                    for j in clients_iter:
                        if len(class_indices) == 0:
                            samples_left = False
                            break
                        else:
                            sample_idx = np.random.choice(len(class_indices))
                            local_sets_indices[j] = np.append(local_sets_indices[j], self.train_data.indices[class_indices[sample_idx]])
                            class_indices = np.delete(class_indices, sample_idx)

        # non-iid: Sample from dirichlet distribution.
        else:
            class_indices = []
            for i in range(n_classes):
                class_indices.append(np.array(range(len(labels)))[labels == i])
            valid_pm = False
            while not valid_pm:
                partition_matrix = np.random.dirichlet((alpha, )*n_clients, n_classes)
                valid_pm = all(np.sum(partition_matrix, axis=0) > 0.01)

            local_sets_indices = [[] for _ in range(n_clients)]
            for each_class in range(n_classes):
                sample_size = len(class_indices[each_class])
                for client in range(n_clients):
                    np.random.shuffle(class_indices[each_class])
                    local_size = int(partition_matrix[each_class, client] * sample_size)
                    local_sets_indices[client] += list(self.train_data.indices[class_indices[each_class][:local_size]])
                    class_indices[each_class] = class_indices[each_class][local_size:]

        self.local_sets_indices = local_sets_indices

    def get_train_data_loaders(self, batch_size):
        """ Get list of client training data loaders.

            Parameters:
            n_clients       (int): Number of clients.
            distribution    (str): iid/non-iid distributed data.
            alpha           (float): Concentration parameter for dirichlet distribution.
            batch_size      (int): Batch size for loading training data.

            Returns List[torch.utils.data.DataLoader]
        """
        client_data_loaders = []
        for client_indices in self.local_sets_indices:
                np.random.shuffle(client_indices)
                client_data_loaders.append(DataLoader(Subset(self.train_data.dataset, client_indices), batch_size, num_workers=self.num_workers))
        return client_data_loaders

    def get_test_data_loader(self, batch_size):
        """ Get test data loader.

            Parameters:
            batch_size      (int): Batch size for loading test data.
        """
        return DataLoader(self.test_data, batch_size, num_workers=self.num_workers)

    def get_public_data_loader(self, batch_size):
        """ Get test data loader.

            Parameters:
            batch_size      (int): Batch size for loading test data.
        """
        return DataLoader(self.public_data, batch_size, num_workers=self.num_workers)

    def get_local_sets_indices(self):
        """
        """
        return self.local_sets_indices

    def get_test_indices(self):
        """
        """
        return self.test_data.indices

    def get_public_indices(self):
        """
        """
        return self.public_data.indices

    def set_local_sets_indices(self, local_sets_indices):
        """
        """
        self.local_sets_indices = local_sets_indices

    def set_test_indices(self, test_indices):
        """
        """
        self.test_data.indices = test_indices

    def set_public_indices(self, public_indices):
        """
        """
        self.public_data.indices = public_indices


"""trt_mtcnn.py

This script demonstrates how to do real-time face detection with
Cython wrapped TensorRT optimized MTCNN engine.
"""

import sys
import time
import argparse
import json

import cv2
from utils.camera import add_camera_args, Camera
from utils.display import open_window, set_display, show_fps
from utils.mtcnn import TrtMtcnn

WINDOW_NAME = 'TrtMtcnnDemo'
WINDOW_NAME2 = 'TrtMtcnnExtracted'
BBOX_COLOR = (0, 255, 0)  # green

import paho.mqtt.client as mqtt
LOCAL_MQTT_HOST="tx2broker"
LOCAL_MQTT_PORT=1883
LOCAL_MQTT_TOPIC="/facedetect/local/faces"
keepalive=1200 #set MQTT time out to 20 minutes

def parse_args():
    """Parse input arguments."""
    desc = ('Capture and display live camera video, while doing '
            'real-time face detection with TrtMtcnn on Jetson '
            'Nano')
    parser = argparse.ArgumentParser(description=desc)
    # print(f"desc: {desc}")
    parser = add_camera_args(parser)
    parser.add_argument('--minsize', type=int, default=40,
                        help='minsize (in pixels) for detection [40]')
    args = parser.parse_args()
    # print(f"args: {args}")
    return args

def show_faces(img, boxes, landmarks):
    """Draw bounding boxes and face landmarks on image."""
    for bb, ll in zip(boxes, landmarks):
        x1, y1, x2, y2 = int(bb[0]), int(bb[1]), int(bb[2]), int(bb[3])
        cv2.rectangle(img, (x1, y1), (x2, y2), BBOX_COLOR, 2)
        send_face(img[y1:y2, x1:x2, : ])
        for j in range(5):
            cv2.circle(img, (int(ll[j]), int(ll[j+5])), 2, BBOX_COLOR, 2)
    return img

def send_face(img):
    # Display the extracted face on the window
    cv2.imshow(WINDOW_NAME2, img)

    # first member is a tuple showing the resolution of the captured face
    json_string = json.dumps( ( img.shape, img.tolist()) )
    local_mqttclient.publish(LOCAL_MQTT_TOPIC, payload=json_string, qos=0, retain=False)

    return img

def loop_and_detect(cap, mtcnn, minsize):
    """Continuously capture images from camera and do face detection."""
    full_scrn = False
    fps = 0.0
    tic = time.time()

    fps_count=10

    while True:
        if cv2.getWindowProperty(WINDOW_NAME, 0) < 0:
            break
#         img = cam.read()
        ret,img = cap.read()
        if img is not None:
            dets, landmarks = mtcnn.detect(img, minsize=minsize)
            print('{} face(s) found'.format(len(dets)))
            img = show_faces(img, dets, landmarks)
            img = show_fps(img, fps)
            cv2.imshow(WINDOW_NAME, img)
            toc = time.time()
            curr_fps = 1.0 / (toc - tic)
            # calculate an exponentially decaying average of fps number
            fps = curr_fps if fps == 0.0 else (fps*0.95 + curr_fps*0.05)
            tic = toc
        fps_count -= 1
        if fps_count == 0:
            print(f"frames: {fps}")
            fps_count = 10
        key = cv2.waitKey(1)
        if key == 27:  # ESC key: quit program
            break
        elif key == ord('F') or key == ord('f'):  # Toggle fullscreen
            full_scrn = not full_scrn
            set_display(WINDOW_NAME, full_scrn)

def main():
    args = parse_args()

    cap = cv2.VideoCapture(0)

    # Attach to messaging
    global local_mqttclient
    local_mqttclient = mqtt.Client("facedetect")
    local_mqttclient.connect(LOCAL_MQTT_HOST, LOCAL_MQTT_PORT,keepalive)

    mtcnn = TrtMtcnn()

    open_window(WINDOW_NAME, args.image_width, args.image_height,
                'Image with Identified Faces')
    open_window(WINDOW_NAME2, int(args.image_width / 4) , int(args.image_height / 4),
                'Extracted Face')
    loop_and_detect(cap, mtcnn, args.minsize)

    cv2.destroyAllWindows()

    del(mtcnn)

if __name__ == '__main__':
    main()


import os
from imutils import paths
from tensorflow.keras.models import load_model
import pickle
import numpy as np
import base64
from imageio import imread
import API_KERAS.processing_lab as processing_lab
from tqdm import tqdm
import cv2

CAPTCHA_IMAGE_FOLDER = r"C:\Users\DANIEL BEMERGUY\OneDrive\CaptchaML\Data\test_set\7"
MODEL_FILENAME = r"C:\Users\DANIEL BEMERGUY\OneDrive\CaptchaML\API_KERAS\result_model_letter.h5"
MODEL_LABELS_FILENAME = r"C:\Users\DANIEL BEMERGUY\OneDrive\CaptchaML\API_KERAS\model_labels.dat"

# Load up the model labels (so we can translate model predictions to actual letters)
with open(MODEL_LABELS_FILENAME, "rb") as f:
    lb = pickle.load(f)

# Load the trained neural network
model = load_model(MODEL_FILENAME)

# captcha_image_files = list(paths.list_images(CAPTCHA_IMAGE_FOLDER))

def predict_text(path):
    img = cv2.imread(path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    predictions = []
    img = processing_lab.model2(img)
    for letter in img:
        # rgb = cv2.cvtColor(letter, cv2.COLOR_BGR2RGB)
        # Re-size the letter image to 20x20 pixels to match training data
        letter_image = processing_lab.resize_to_fit(letter, 20, 20)

        # Turn the single image into a 4d list of images to make Keras happy
        letter_image = np.expand_dims(letter_image, axis=2)
        letter_image = np.expand_dims(letter_image, axis=0)

        # Ask the neural network to make a prediction
        prediction = model.predict(letter_image)

        # Convert the one-hot-encoded prediction back to a normal letter
        letter = lb.inverse_transform(prediction)[0]
        predictions.append(letter)

        # Get captcha's text
        captcha_text = "".join(predictions)
        captcha_text = captcha_text.replace("_","")
        # filename = name1.filename
        # Find real captcha name
        # end = filename.rfind('.')  # last occurence of '.'
        # real = filename[:end]
    return str(captcha_text)

# teste = predict_text(captcha_image_files[0]) == '010E3'
# print('Predicted:',teste)
# print('Real:',captcha_image_files[0])

'''
1 = caxias
2 = barueri
3 = niteroi
4 = aparecido de goiania
'''
correct = 0
folder = 7

path = r"C:\Users\DANIEL BEMERGUY\OneDrive\CaptchaML\Data\test_set\{}".format(folder)
captcha_image_files = list(paths.list_images(path))
# print(captcha_image_files)
wrongs = []
for file in tqdm(captcha_image_files):
    name = os.path.basename(file).split('.')[0]
    predicted = predict_text(file)
    if predicted == name: #check right predictions
        correct += 1
    if predicted != name: #check wrong predictions
        wrongs.append(os.path.basename(file).split('.')[0])
print('Acc:',correct/len(captcha_image_files)*100)
print("wrong captchas:",len(wrongs))
print(wrongs)


from settings import MEDIA_ROOT
from django.conf.urls.defaults import *

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # static files
    url(r'^static/javascripts/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': MEDIA_ROOT + '/javascripts'}, name='javascripts'),
    url(r'^static/images/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': MEDIA_ROOT + '/images'}, name='images'),
    url(r'^static/stylesheets/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': MEDIA_ROOT + '/stylesheets'}, name='stylesheets'),
    url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': MEDIA_ROOT}, name='static'),

    url(r'^$', 'maps.views.new', name='root'),
    (r'^admin/', include(admin.site.urls)),
    (r'^mapy/', include('maps.urls')),
    (r'^czas/', include('stats.urls')),
    (r'^profil/', include('profiles.urls')),
    (r'^punkt/', include('points.urls')),
    (r'^zdjecie/', include('avatar.urls')),

    (r'^komentarze/', include('comments.urls')),

    url(r'^nowy/$', 'profiles.views.new', name='new-profile'),
    url(r'^edytuj/$', 'profiles.views.edit', name='edit-profile'),
    url(r'^zaloguj/$', 'profiles.views.login', name='login'),
    url(r'^wyloguj/$', 'profiles.views.logout', name='logout'),
)


import pytest

from nhl_data.models.utils import camel_to_snake_case, convert_keys_to_snake_case

@pytest.mark.parametrize(
    "test_value, expected",
    [
        ("", ""),
        ("is_snake_case", "is_snake_case"),
        ("camelCase", "camel_case"),
        ("simpletextthatisalllower", "simpletextthatisalllower"),
        ("snake_thenCamelCase", "snake_then_camel_case"),
        ("camelCaseWithNums12345", "camel_case_with_nums12345"),
    ],
)
def test_camel_to_snake_case(test_value, expected):
    result = camel_to_snake_case(test_value)
    assert expected == result

@pytest.mark.parametrize(
    "test_value, expected",
    [
        (dict(), dict()),
        (
            {"helloWorld": None, "fine_world": None},
            {"hello_world": None, "fine_world": None},
        ),
        (
            {"hiThere": {"nestedHiThere": None, "nested_fine": None}},
            {"hi_there": {"nested_hi_there": None, "nested_fine": None}},
        ),
    ],
    ids=["empty_dict", "normal_level", "nested_dict"],
)
def test_convert_keys_to_snake_case(test_value, expected):
    result = convert_keys_to_snake_case(test_value)
    assert expected == result