#!/usr/bin/python
# -*- coding: latin-1 -*-
"""Shows how to interact with an excel file.
Only works in a windows environment with Microsoft excel installed.
It is possible to read and write values to the excel workbook.

This module depends on the win32com module.
"""

# This line must be at the beginning of the file
from __future__ import print_function

from win32com.client import Dispatch
import sys, os

class XLSFile:
  def __init__( self ):
    "Constructor"
    try:
      self.excel = Dispatch('Excel.Application')
    except:
      raise Exception( "Could not open excel object" )

  def Visible( self, show ):
    "To show or hide the excel application window"
    self.excel.Visible = show

  def Open( self, filename, sheetname ):
    "To actually open the file and select one worksheet"
    # filename must be a complete path
    self.workbook = self.excel.Workbooks.Open( os.path.abspath( filename ) )
    self.ActivateSheet( sheetname )

  def OpenSimple( self, filename, sheetname ):
    "Open the file as read only and only for simple usage. Some other functions may fail..."
    # filename must be a complete path
    self.workbook = self.excel.Workbooks.Open( os.path.abspath( filename ), False, True )
    self.sheet = self.workbook.Sheets( sheetname )
    self.sheet.Activate()

  def Close( self ):
    "Close the currently opened workbook"
    self.workbook.Close(SaveChanges=0) #to avoid prompt

  def Dispose( self ):
    "Dispose all system resources. Do not use this object anymore!"
    try:
      self.excel.Quit()
      self.excel.Visible = 0
      #must make Visible=0 before del self.excelapp or EXCEL.EXE remains in memory.
      del self.excel
    except:
      raise Exception( "Could not close Excel properly (maybe running this script as administrator?). Please close it." )

  def PrintPDF( self, pdfName ):
    "Print current sheet to a PDF file"
    self.sheet.ExportAsFixedFormat( 0, os.path.abspath( pdfName ) )

  def Save( self ):
    "Save currently opened workbook"
    self.workbook.Save()
    self.workbook.Saved = 0 #p.248 Using VBA 5

  def ActivateSheet( self, name ):
    "Select and activate a sheet by name"
    self.sheet = self.workbook.Sheets( name )
    self.sheet.Activate()
    self.nCols = self.sheet.Cells(1,1).SpecialCells(11).Column
    self.nRows = self.sheet.Cells(1,1).SpecialCells(11).Row

  def NumberOfRows( self ):
    "How many rows are filled in the present worksheet"
    return self.nRows

  def NumberOfCols( self ):
    "How many columns are filled in the present worksheet"
    return self.nCols

  def ReadCell( self, row, col ):
    "Read the value of a cell (coordinates are zero based)"
    v = self.sheet.Cells( row+1, col+1 ).Value
    return v if v != None else ""

  def WriteCell( self, row, col, value ):
    "Change the value of a cell (coordinates are zero based)"
    self.sheet.Cells( row+1, col+1 ).Value = value

def main():
  "The main function called when the utility is run."

  print( 'Module XLS Files in a Windows environment' )
  print()

  #Create the excel object
  xls = XLSFile()

  xls.OpenSimple( r"Samples\xls2.xls", "Sheet1" )
  # Save as PDF
  xls.PrintPDF( r"Samples\xx.pdf" )
  #Close the workbook
  xls.Close()

  #open a workbook
  xls.Open( r"Samples\xls2.xls", "Sheet1" )
  print( "Space in use:", xls.NumberOfRows(), "x", xls.NumberOfCols() )

  #get a value
  print( "B4", xls.ReadCell( 3, 1 ) )

  #change a value
  xls.WriteCell( 3, 1, "Her" )

  #save the book
  xls.Save()

  #Close the workbook
  xls.Close()

  xls.Open( r"samples\xls1.xls", "Update" )
  print( "Space in use:", xls.NumberOfRows(), "x", xls.NumberOfCols() )
  print( "A1", xls.ReadCell( 0, 0 ) )

  xls.ActivateSheet( "Notes" )
  print( "Space in use:", xls.NumberOfRows(), "x", xls.NumberOfCols() )
  print( "A8", xls.ReadCell( 7, 0 ) )

  xls.Close()

  #Destroy the object
  xls.Dispose()

  return 0

# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
  rc = main()

  # This function will set the result value of this utility
  sys.exit( rc )


import sys

class Nodo():                        #Esta clase crea los Nodos de la lista con 2 atributos, el valor y el enlace vacio.
    def __init__(self,datos):
        self.datos = datos
        self.siguiente = None

def Enlazar():                       #Este metodo se encarga de enlazar los nodos que se vayan creando.
    global raiz
    bandera = True                  #Declaro e inicializo mis variables.
    q=raiz
    while (bandera):                                            #COn este ciclo me posiciono en el ultimo nodo de la lista.
        if (q.siguiente == raiz) or (q.siguiente == None):      #Si el nodo siguiente es Nulo o es la raiz es porque
            bandera = False                                     #se llego al final de la lista.
        else:
            p = q.siguiente
            q=p
    p=Nodo(str(input("Ingrese el elemento a enlazar: ")))       #Creo un nodo nuevo con el valor ingresado.
    q.siguiente = p                                             #Lo enlazo con el anterior nodo y el nuevo lo enlazo con la raiz.
    p.siguiente = raiz
    q=p                                                         #Al final muevo ambos punteros al final de la lista.

def Peek(eleccion):                                         #Metodo para mostrar nodos de la lista.
    global raiz
    bandera = True
    q=raiz                                                  #Declaro e inicializo mis variables
    p=raiz
    if eleccion == "T":                                     #SI eligio esta opcion es para mostrar todos los valores de la lista.
        while (bandera):
            print(q.datos)                                  #Imprimo el valor del nodo en el que estoy.
            if q.siguiente == raiz:                         #Si su atributo de enlaze es Nulo significa que llegue al final de la lista y termino el ciclo.
                bandera = False
            else:                                           #Si no, avanzo al siguiente nodo con ayuda de los punteros.
                p = q.siguiente                             #Muevo un puntero al sig nodo que esta en el enlace y luego muevo el otro puntero a este nodo.
                q=p
    elif eleccion == "U":                                   #Si eligio esta opcion utilizo exactamente el ciclo anterior solo que solo imprimo el ultimo
        while (bandera):                                    #nodo en el que se quedaron los punteros al salir del ciclo.
            if q.siguiente == raiz:                         #Si el siguiente Nodo es la raiz, es porque llego al final de las listas.
                bandera = False
            else:                                           #SI no, continua al sig Nodo
                p = q.siguiente
                q=p
        print("Ultimo valor de la lista: "+ p.datos+"\n")
    elif eleccion == "R":                                   #SI eligio esta opcion es para imprimir la raiz.
        print("La raiz es: "+raiz.datos+"\n")
    else:                                                   #Si no fue ninguno de los anteriores significa que esta buscando un nodo por su valor.
        contador=1
        while (bandera):                                    #Para esto utilizo el mismo ciclo anterior para moverme a traves de toda la lista y me detengo
            if eleccion == q.datos:                         #hasta que encuentro el valor deseado o hasta que llegue al final de la lista sin encontrarlo.
                print("El dato "+str(eleccion)+" se encuentra en el nodo "+str(contador)+" de la lista...") #Encontro el valor en la lista.
                bandera = False
            elif q.siguiente == raiz:
                print("El dato "+str(eleccion)+" no existe en la lista...")         #NO encontro el valor en la lista.
                bandera = False
            else:
                contador=contador+1
                p = q.siguiente
                q=p
    print()

def Pop(eleccion):                              #Metodo para eliminar Nodos.
    global raiz
    q=raiz                                      #Declaro e inicializo mis variables
    p=raiz
    bandera = True
    if(raiz.siguiente == raiz):                 #Si la raiz esta enlazada con ella misma significa que solo existe la raiz en la lista.
            print("No puede eliminar mas ya que solo existe la raiz en la lista...")
    elif eleccion == "A":                       #SI eligio esta opcion es para eliminar el ultimo nodo de la lista.
        while (bandera):
            if q.siguiente.siguiente == raiz:   #Si el nodo siguiente del que quiero eliminar es la raiz, significa que llegue al final de la lista.
                p = q.siguiente                 #Asigno un puntero al valor que quiero eliminar, lo enlazo con la raiz y elimino el nodo este.
                q.siguiente = raiz
                print("Nodo con el dato "+p.datos+" eliminado...")
                del p
                bandera = False
            else:                               #SI no continuo al siguiente Nodo y asi hasta llegar al ultimo nodo.
                p = q.siguiente
                q=p
    elif eleccion == "B":                       #Si eligio esta opcion es para eliminar y sustituir la raiz.
        while (bandera):                        #Utilizo la misma dinamica del ciclo anterior para posicionarme en el ultimo nodo de la lista.
            if q.siguiente == raiz:
                bandera = False
            else:
                p = q.siguiente
                q=p
        p = q.siguiente                         #Ya que estoy al final, coloco un puntero al nodo siguiente de la raiz, este nodo lo enlazo con el
        raiz = p.siguiente                      #anterior de la raiz y finalmente borro la raiz (el puntero que guardaba la raiz).
        q.siguiente = raiz
        print("Nueva raiz: "+raiz.datos)
        del p
    else:
        while (bandera):                                    #SI no fue ninguna de las anteriores es porque esta buscando un valor en especifico.
            if q.siguiente.datos == eleccion:               #Utilizo la misma dinamica del ciclo anterior para ir recorriendo los nodos de la lista.
                p= q.siguiente                              #hasta que encuentre el nodo deseado o hasta que llegue al final de la lista.
                q.siguiente = p.siguiente
                del p
                print("El dato "+str(eleccion)+" se ha eliminado de la lista...")
                bandera = False
            elif q.siguiente == raiz:
                print("El dato "+str(eleccion)+" no existe en la lista...")
                bandera = False
            else:
                p = q.siguiente
                q=p
    print()

def Menu():                                                         #Menu
    print ("1.- Crear y enlazar nodo.\n"
           "2.- Mostrar los nodos.\n"
           "3.- Eliminar nodo.\n"
           "4.- Salir.")
    eleccion = int(input("Que desea realizar?: "))
    if eleccion ==1:
        Enlazar()                                                   #Si eligio esta opcion llamo al metodo enlazar.
        print("\nNodo creado y enlazado...\n")
        Menu()
    elif eleccion ==2:                                                                          #Si eligio esta opcion es para mostrar los valores de la
        eleccion = str(input("\nTeclee 'T' para mostrar TODA la lista circular,\n"              #lista.
                                         "teclee 'U' para mostrar el ULTIMO nodo enlazado,\n"
                                         "teclee 'R' para mostrar la RAIZ,\n"
                                         "o ingrese el valor que desea buscar en la lista: "))
        print()
        Peek(eleccion)
        Menu()
    elif eleccion ==3:                                                                          #Si eligio esta opcion despliega un menu de opciones
        eleccion = str(input("\t'A'- Eliminar el ultimo nodo creado,\n"                         #para eliminar valores de la lista.
                             "\t'B'- Eliminar y recorrer la raiz o \n"
                             "\tingrese el dato a buscar y eliminar: "))
        print()
        Pop(eleccion)
        Menu()
    elif eleccion ==4:
        sys.exit()                                                      #Utilizo esta libreria para cerrar el programa.
    else:
        print("\nValor ingresado invalido...\n")
        Menu()

raiz = Nodo("Raiz")                                                     #AL inicio del programa creo la Raiz con el valor Raiz como unico.
q=raiz                                                                  #Y mi puntero lo igualo a la raiz para de ahi comenzar la lista.
Menu()                                                                  #LLamo al metodo Menu para iniciar la recursividad...


# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import seaborn as sns
sns.set()

# %% import data
df = pd.read_csv('data/new_data.csv', index_col=0)
# %% wytnij kolumne categories i zlicz wartosci
df_categories = df['categories']
df_categories = df_categories.value_counts()
# %% wykres słupkowy kolumny categories
df_categories.plot(kind='bar', legend=True, title='Categories')

# %% wykres kołowy kolumny categories
df_categories.plot(kind='pie', legend=True, title='Categories')

# %% wykres kolumny rating
df_rating = df['rating']
df_rating = df_rating.value_counts()
df_rating.sort_index().plot(kind='bar', color='red', alpha=0.7, legend=True, title='Rating')

# %% wytnij top 3 najczęsciej ocenianych z kolumny products
df_top_3_name = df[['name', 'rating']]
df_name = df_top_3_name.groupby('name').count()['rating']
df_name = df_name.nlargest(3)

df_name.plot(kind='bar')

# %% wytnij top 3 najwyżej ocenianych z kolumny products
df_top_3_high = df[['name', 'rating']]
df_mean = df_top_3_high.groupby('name').agg('mean')
top3_high = df_mean.nlargest(3, columns='rating')

# %% wytnij bottom 3 products
df_top_3_lower = df[['name', 'rating']]
df_mean_low = df_top_3_lower.groupby('name').agg('mean')
top3_lower = df_mean_low.nsmallest(3, columns='rating')


class Solution:

    def find_range(self, arr, target):
        for i, e in enumerate(arr):
            if i != len(arr) -1:
                if i == 0 and target < e:
                    return -1
                if  target >= e and target < arr[i+1]:
                    return i
            if i == len(arr) -1 and e <= target:
                return i
        return -1

    def find_candidate_row(self, matrix, target):
        vertical = [matrix[i][0] for i in range(len(matrix))]
        return self.find_range(vertical, target)

    def find_column(self, matrix, target, row):
        left = 0
        right = len(matrix[0]) -1
        print(row)
        arr = matrix[row]

        while left <= right:
            mid = (left + right) //2
            if target == arr[mid]:
                return True
            if target < arr[mid]:
                right = mid - 1
            if target > arr[mid]:
                left = mid + 1
        return False

    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        if not len(matrix) or matrix == [[]]:
            return False
        r = self.find_candidate_row(matrix, target)
        if r == -1 or r is None:
            return False
        c = self.find_column(matrix, target, r)
        return c


my_set1 = set()
my_set2 = set()
my_set3 = set()
n = int(input())
m = int(input())
k = int(input())
a = n + m + k
count = 0
for i in range(a):
    name = input()
    if name not in my_set1:
        my_set1.add(name)
    elif name not in my_set2:
        my_set2.add(name)
        count += 1
    else:
        my_set3.add(name)
        count -= 1
print(count)


from django.conf.urls import patterns, url

from shoppinglist import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^create$', views.create, name='create'),
    url(r'^update$', views.update, name='update'),
    url(r'^logout$', views.logout_view, name='logout'),
    url(r'^accounts/login/?$', views.login_view, name='login'),
    url(r'^clear$', views.clear, name='clear'),

)


import argparse
from argparse import RawTextHelpFormatter
import base64
from copy import deepcopy
import inspect
import time
from typing import Dict, Tuple, List, Any, Callable, Optional, Union
import re
import pprint
import logging
import gc
import os
import socket

import git
import git.exc
import joblib
from joblib import Parallel, delayed
from mkdir_p import mkdir_p
from sklearn.model_selection import ParameterGrid

from .base import default_fn_dict, default_val_dict, \
        ParameterAlreadyRanError, VariableValueNotSetError, \
        VariableNotRegisteredError

logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.WARNING,
    datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)

def add_all_commit(repo, commit_msg="update"):
    repo.git.commit('-m', commit_msg)
    files = repo.git.diff(None, name_only=True)
    for f in files.split('\n'):
        repo.git.add(f)

class AutoVar(object):

    def __init__(self, before_experiment_hooks=None, after_experiment_hooks=None,
                 settings: Dict=None, logging_level: int=logging.WARNING) -> None:
        """
        settings : {
            'server_url': 'http://127.0.0.1:8080/nn_attack/',
            'result_file_dir': './results/'
            'file_format': 'json' or 'pickle'
        }
        """
        logger.setLevel(logging_level)

        self.experiments: Dict[str, Any] = {}
        self.variables: Dict[str, dict] = {}
        self.var_shown_name: Dict[str, Dict[str, str]] = {}
        self.var_description: Dict[str, str] = {}
        self.var_class: Dict[str, Any] = {}
        self.var_value: Dict[str, Any] = {}

        self.inter_var: Dict[str, Any] = {}
        self.result_fields: List[str] = []
        self.settings: Dict
        self.settings = {'file_format': 'json'}
        if isinstance(settings, dict):
            self.settings.update(settings)
        if ('result_file_dir' in self.settings) and self.settings['result_file_dir']:
            mkdir_p(self.settings['result_file_dir'])

        try:
            self.repo = git.Repo(search_parent_directories=True)
            self.var_value['git_hash'] = self.repo.head.object.hexsha
        except git.exc.InvalidGitRepositoryError:
            logger.warning("Git repository not found.")

        try:
            self.var_value['hostname'] = socket.gethostname()
        except:
            logger.warning("Unable to get hostname.")

        self.after_experiment_hooks = after_experiment_hooks
        self.before_experiment_hooks = before_experiment_hooks

        self._read_only: bool = False
        self._no_hooks: bool = False

    def set_logging_level(self, level: int):
        logger.setLevel(level)

    def add_variable_class(self, variable_class, var_name: str = None):
        if var_name is None:
            var_name = variable_class.__class__.var_name
            if var_name is None:
                var_name = type(variable_class).__name__

        if var_name in self.var_class:
            raise ValueError('Don\'t register class "{}" twice '.format(var_name))
        self.var_class[var_name] = variable_class
        #self.variables.setdefault(var_name, deepcopy(default_fn_dict))
        self.variables.update(variable_class.__class__.variables)
        self.var_shown_name.update(
                variable_class.__class__.variable_shown_name)

        if variable_class.default is not None:
            self._check_var_argument(var_name=var_name, argument=variable_class.default)

    def add_variable(self, var_name: str, dtype, default=None) -> None:
        d = deepcopy(default_val_dict)
        d['dtype'] = dtype
        self.variables.setdefault(var_name, d)
        if default is not None:
            self._check_var_argument(var_name=var_name, argument=default)
            d['default'] = default

    def get_var_shown_name(self, var_name: str,
                           argument: Union[str, None] = None) -> str:
        if argument is None:
            argument = self.get_variable_name(var_name)
        for key, val in self.var_shown_name[var_name].items():
            if re.fullmatch(key, argument):
                argument = re.sub(key, val, argument)
        return argument

    def get_var(self, var_name: str, *args, **kwargs):
        """[summary]

        Arguments:
            var_name {[type]} -- [description]
            argument {[type]} -- [description]

        Raises:
            ValueError -- [description]
            ValueError -- [description]

        Returns:
            [type] -- [description]
        """
        if var_name not in self.variables:
            raise VariableNotRegisteredError('Variable "%s" not registered.' % var_name)
        if var_name not in self.var_value:
            if self.variables[var_name]['type'] == 'choice':
                if self.var_class[var_name].default is not None:
                    argument = self.var_class[var_name].default
                else:
                    raise VariableValueNotSetError('Value for variable "%s" is not assigned.' % var_name)
            elif self.variables[var_name]['default'] is not None:
                argument = self.variables[var_name]['default']
            else:
                raise VariableValueNotSetError('Value for variable "%s" is not assigned.' % var_name)
        else:
            argument = self.var_value[var_name]

        return self.get_var_with_argument(
                var_name=var_name, argument=argument, *args, **kwargs)

    def match_variable(self, var_name: str, argument):
        if argument is None:
            return False

        if self.variables[var_name]["type"] == "val":
            return True
        else:
            if argument in self.variables[var_name]["argument_fn"]:
                return True
            else:
                for arg_template in self.variables[var_name]["argument_fn"]:
                    m = re.fullmatch(arg_template, argument)
                    if m is not None:
                        return True
        return None

    def get_variable_value(self, var_name: str):
        logger.warn("Use get_variable_name instead.")
        if var_name not in self.var_value:
            raise ValueError(f"{var_name} not in var_value")
        return self.var_value[var_name]

    def get_variable_name(self, var_name: str):
        if var_name not in self.var_value:
            raise ValueError(f"{var_name} not in variable name")
        return self.var_value[var_name]

    def get_var_with_argument(self, var_name: str, argument: str, *args, **kwargs):
        if self.variables[var_name]["type"] == "val":
            return argument
        else:
            cache_dir = None
            if argument in self.variables[var_name]["argument_fn"]:
                func = self.variables[var_name]["argument_fn"][argument]
                cache_dir = self.variables[var_name]['cache_dirs'][argument]
                required_vars = self.variables[var_name]['required_vars'][argument]
            else:
                m = None
                for arg_template, func in self.variables[var_name]["argument_fn"].items():
                    m = re.fullmatch(arg_template, argument)
                    if m is not None:
                        kwargs.update(m.groupdict())
                        cache_dir = self.variables[var_name]['cache_dirs'][arg_template]
                        required_vars = self.variables[var_name]['required_vars'][arg_template]
                        break
                if m is None:
                    raise ValueError('Argument "%s" not matched in Variable '
                                     '"%s".' % (argument, var_name))

            kwargs['auto_var'] = self
            named_args = inspect.getfullargspec(func)[0]
            if 'var_value' in named_args:
                kwargs['var_value'] = self.var_value
            if 'inter_var' in named_args:
                kwargs['inter_var'] = self.inter_var

            if cache_dir is not None:
                mkdir_p(cache_dir)
                #var_used = {var_name: self.var_value[var_name]}
                var_used = {var_name: argument}
                if required_vars is not None:
                    for var in required_vars:
                        if var not in self.var_value:
                            raise ValueError('Variable "%s" required by Variable '
                                             '"%s" is not set.' % (var, argument))

                        var_used[var] = self.var_value[var]
                required_variables = [str(v) for k, v in sorted(var_used.items())]
                cache_filename = os.path.join(cache_dir, '-'.join(required_variables) + '.pkl')

                if os.path.exists(cache_filename):
                    try:
                        func_outputs = joblib.load(cache_filename)
                        logger.info(f"using result from cache file {cache_filename} ...")
                    except:
                        os.unlink(cache_filename)
                        func_outputs = func(*args, **kwargs)
                        logger.info(f"dumping cache file to {cache_filename} ...")
                        joblib.dump(func_outputs, cache_filename)
                else:
                    func_outputs = func(*args, **kwargs)
                    logger.info(f"dumping cache file to {cache_filename} ...")
                    joblib.dump(func_outputs, cache_filename)
            else:
                func_outputs = func(*args, **kwargs)

            return func_outputs

    def get_intermidiate_variable(self, var_name: str):
        return self.inter_var[var_name]

    def set_variable_value(self, var_name: str, value) -> None:
        if self._read_only:
            raise ValueError("should not set variable value while read_only")
        #if var_name not in self.var_value:
        #    raise ValueError(f"{var_name} not in var_value")
        self.var_value[var_name] = value
        self._check_var_argument(var_name=var_name, argument=value)

    def set_intermidiate_variable(self, var_name: str, value) -> None:
        self.inter_var[var_name] = value

    def set_variable_value_by_dict(self, var_value: Dict[str, Any]) -> None:
        if self._read_only:
            raise ValueError("should not set variable value while read_only")
        for k, v in var_value.items():
            self.set_variable_value(k, v)

    def _run_before_hooks(self):
        if not self._no_hooks and self.before_experiment_hooks is not None:
            for hook_fn in self.before_experiment_hooks:
                try:
                    hook_fn(self)
                except ParameterAlreadyRanError:
                    logger.warning("The result for this parameter is "
                                        "already ran.")
                    return False
                except:
                    print("Error occur during running before hooks.")
                    raise
        return True

    def _run_after_hooks(self, ret):
        if not self._no_hooks and self.after_experiment_hooks is not None:
            for hook_fn in self.after_experiment_hooks:
                hook_fn(self, ret)

    def run_single_experiment(self, experiment_fn: Union[Callable[..., Any], str],
                              with_hook: bool=True,
                              verbose: int=0) -> Optional[bool]:
        self._read_only = True
        if isinstance(experiment_fn, str):
            if experiment_fn not in self.experiments:
                raise ValueError(f"experiment_fn {experiment_fn} is not a registered experiment")
            original_settings = deepcopy(self.settings)
            self.settings.update(self.experiments[experiment_fn]['settings'])

        ret = None
        ret_hook = True
        if with_hook:
            ret_hook = self._run_before_hooks()

        try:
            if ret_hook:
                start_time = time.time()
                if isinstance(experiment_fn, str):
                    ret = self.experiments[experiment_fn]['fn'](self)
                else:
                    ret = experiment_fn(self)
                end_time = time.time()
                logger.info("Running time: %f", end_time - start_time)
                if isinstance(ret, dict):
                    ret['running_time'] = end_time - start_time
                else:
                    # return value is not dict
                    pass
                ret['var_value'] = deepcopy(self.var_value)
        finally:
            if with_hook and ret_hook:
                self._run_after_hooks(ret)
            self.inter_var.clear()
            self._read_only = False
            gc.collect()

        if isinstance(experiment_fn, str):
            self.settings = original_settings
        return ret

    def _check_var_argument(self, var_name: str, argument):
        if self.variables[var_name]["type"] != "val" \
            and not self.match_variable(var_name, argument):
                raise ValueError('Argument "%s" not in Variable "%s".' % (argument, var_name))
        elif self.variables[var_name]["type"] == "val" \
            and not isinstance(argument, self.variables[var_name]['dtype']):
            raise TypeError('Argument "%s" not in the correct type "%s" for Variable "%s".' % (
                            type(argument), self.variables[var_name]['dtype'], var_name))

    def _check_grid_params(self, grid_params: Dict[str, List]) -> bool:
        # TODO check duplicated params
        # TODO duplicated check var argument since set_param_value will check
        for k, v in grid_params.items():
            for i in v:
                self._check_var_argument(k, i)
        return True

    def run_grid_params(self,
                        experiment_fn: Union[Callable[..., Any], str],
                        grid_params: Union[Dict[str, List], List[Dict[str, List]]],
                        with_hook: bool=True,
                        max_params: int=-1,
                        commit_before_run: bool=False,
                        verbose: int=0,
                        allow_failure: bool=True,
                        n_jobs: int=-1,
                        backend: Optional[str]=None,
                        pre_dispatch: str='2 * n_jobs') -> Tuple[List, List]:

        if commit_before_run:
            if self.repo is None:
                raise ValueError("Not currently in git repo.")
            add_all_commit(self.repo)

        if isinstance(grid_params, list):
            ret_params: List = []
            for grid_param in grid_params:
                self._check_grid_params(grid_param)

                grid = ParameterGrid(grid_param)
                ret_params += list(grid)
        else:
            ret_params = list(ParameterGrid(grid_params))

        if max_params != -1:
            ret_params = ret_params[:max_params]

        parallel = Parallel(n_jobs=n_jobs, verbose=verbose,
                            backend=backend, pre_dispatch=pre_dispatch)

        def _helper(auto_var, params):
            auto_var.set_variable_value_by_dict(params)
            if verbose:
                logger.info("Running parameter:" + str(params))
            try:
                results = auto_var.run_single_experiment(
                    experiment_fn,
                    with_hook=(with_hook and (not self._no_hooks)),
                    verbose=verbose
                )
            except Exception as e:
                if allow_failure:
                    logger.error("Error with " + str(params))
                else:
                    raise e
                results = None

            return results

        with parallel:
            ret_results = parallel(delayed(_helper)(deepcopy(self), params)
                                   for params in ret_params)

        return ret_params, ret_results

    def summary(self) -> None:
        pp = pprint.PrettyPrinter(indent=4)
        pp.pprint(self.variables)

    def generate_name(self) -> str:
        _ = hash(tuple(sorted(self.var_value.items())))
        return base64.b64encode(str(_).encode()).decode()

    def register_experiment(self, experiment_name: str,
                               experiment_fn: Callable[..., Any],
                               settings: Dict = None) -> None:
        if experiment_name in self.experiments:
            logger.info(f"Overriding experiment {experiment_name}")
        if settings is None:
            settings = dict()
        self.experiments[experiment_name] = {
            "fn": experiment_fn,
            "settings": settings,
        }

    def get_argparser(self) -> argparse.ArgumentParser:
        parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter)
        parser.add_argument('--no-hooks', required=False, action='store_true',
                            help="run without the hooks")

        if len(self.experiments) > 0:
            parser.add_argument('--experiment', type=str, required=True,
                                choices=[k for k in self.experiments.keys()],
                                help="The experiment to run")

        for var_name, v in self.variables.items():
            if v['type'] == 'choice':
                default = self.var_class[var_name].default
                required = False if default is not None else True
                help_str = ''
                if self.var_class[var_name].__doc__ is not None:
                    help_str += self.var_class[var_name].__doc__ + "\n"
                help_str += f"Options: (default: {default})\n"
                help_str += "\n".join(
                    ["  %s: %s" % (kk, vv.__doc__) for kk, vv in v['argument_fn'].items()])
                parser.add_argument(f'--{var_name}', type=str, required=required,
                                    action=make_action(self, var_name), default=default,
                                    help=help_str)
            else:
                default = v['default']
                required = False if default is not None else True
                parser.add_argument(f'--{var_name}', type=v['dtype'], required=required, default=default)

        return parser

    def parse_argparse(self, args: Optional[List[str]]=None):
        parser = self.get_argparser()
        parsed_args = parser.parse_args(args=args)
        self._no_hooks = parsed_args.no_hooks

        variables = vars(parsed_args)
        del variables['no_hooks']
        experiment_name = variables.pop('experiment', None)
        self.set_variable_value_by_dict(variables)

        if experiment_name:
            ret = self.run_single_experiment(experiment_name, with_hook=(not self._no_hooks))
            return ret

        return None

def make_action(auto_var, var_name):
    class CheckArgParseAction(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            argument = values
            if not auto_var.match_variable(var_name, argument):
                raise argparse.ArgumentTypeError(
                    'Argument "%s" not in Variable "%s".' % (argument, var_name))
            setattr(args, self.dest, values)
    return CheckArgParseAction


from django.shortcuts import render, redirect, reverse, get_object_or_404, HttpResponse
from django.contrib import messages
from django.db.models import Q
from .models import Product
from django.db.models.functions import Lower
from django.contrib.auth.decorators import login_required
from .forms import ProductForm

# Create your views here.

def all_products(request):
    """ A view to list all products """

    products = Product.objects.all()
    query = None
    sort = None
    direction = None

    if request.GET:
        if 'sort' in request.GET:
            sortkey = request.GET['sort']
            sort = sortkey
            if sortkey == 'name':
                sortkey = 'lower_name'
                products = products.annotate(lower_name=Lower('name'))
            if sortkey == 'category':
                sortkey = 'category__name'
            if 'direction' in request.GET:
                direction = request.GET['direction']
                if direction == 'desc':
                    sortkey = f'-{sortkey}'
            products = products.order_by(sortkey)

        if 'q' in request.GET:
            query = request.GET['q']
            if not query:
                messages.error(request, "You didn't enter any search criteria!")
                return redirect(reverse('store'))

            queries = Q(name__icontains=query) | Q(description__icontains=query)
            products = products.filter(queries)

    current_sorting = f'{sort}_{direction}'

    context = {
        'products': products,
        'search_term': query,
        'current_sorting': current_sorting,
    }

    return render(request, 'products/store.html', context)

def product_info(request, product_id):
    """ Lists the information of the targeted product """

    products = get_object_or_404(Product, pk=product_id)

    context = {
        'product': products,
    }

    return render(request, 'products/product_info.html', context)

def view_purchase(request):
    """ A view that renders the purchase page """

    return render(request, 'products/purchase.html')

def add_for_purchase(request, item_id):
    """ Add a product for purchase """

    product = Product.objects.get(pk=item_id)
    quantity = int(request.POST.get('quantity'))
    redirect_url = request.POST.get('redirect_url')
    purchase = request.session.get('purchase', {})

    if item_id in list(purchase.keys()):
        purchase[item_id] += quantity
        messages.success(request, f'Increased the quantity of {product.name} to {purchase[item_id]}!')
    else:
        purchase[item_id] = quantity
        messages.success(request, f'Added {product.name} to your list!')

    request.session['purchase'] = purchase
    return redirect(redirect_url)

def modify_purchase(request, item_id):
    """ modify product for purchase """

    product = Product.objects.get(pk=item_id)
    quantity = int(request.POST.get('quantity'))
    purchase = request.session.get('purchase', {})

    if quantity > 0:
        purchase[item_id] = quantity
        messages.success(request, f'Changed the quantity of {product.name} to {purchase[item_id]}')
    else:
        messages.success(request, f'Removed {product.name} from your list!')
        purchase.pop(item_id)

    request.session['purchase'] = purchase
    return redirect(reverse('view_purchase'))

def remove_product(request, item_id):
    """ remove product from purchase list """

    product = Product.objects.get(pk=item_id)
    purchase = request.session.get('purchase', {})

    try:
        purchase.pop(item_id)
        messages.success(request, f'Removed {product.name} from your list!')

        request.session['purchase'] = purchase
        return HttpResponse(status=200)

    except Exception as e:
        return HttpResponse(status=500)

@login_required
def add_product(request):
    """ Add a product to the store """
    if not request.user.is_superuser:
        messages.error(request, 'Sorry, only store owners can do that.')
        return redirect(reverse('home'))

    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            product = form.save()
            messages.success(request, 'Successfully added product!')
            return redirect(reverse('product_info', args=[product.id]))
        else:
            messages.error(request, 'Failed to add product. Please ensure the form is valid.')
    else:
        form = ProductForm()

    template = 'products/add_product.html'
    context = {
        'form': form,
    }

    return render(request, template, context)

@login_required
def edit_product(request, product_id):
    """ Edit a product in the store """
    if not request.user.is_superuser:
        messages.error(request, 'Sorry, only store owners can do that.')
        return redirect(reverse('home'))

    product = get_object_or_404(Product, pk=product_id)
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES, instance=product)
        if form.is_valid():
            form.save()
            messages.success(request, 'Successfully updated product!')
            return redirect(reverse('product_info', args=[product.id]))
        else:
            messages.error(request, 'Failed to update product. Please ensure the form is valid.')
    else:
        form = ProductForm(instance=product)
        messages.info(request, f'You are editing {product.name}')

    template = 'products/edit_product.html'
    context = {
        'form': form,
        'product': product,
    }

    return render(request, template, context)

@login_required
def delete_product(request, product_id):
    """ Delete a product from the store """
    if not request.user.is_superuser:
        messages.error(request, 'Sorry, only store owners can do that.')
        return redirect(reverse('home'))

    product = get_object_or_404(Product, pk=product_id)
    product.delete()
    messages.success(request, 'Product deleted!')
    return redirect(reverse('store'))


import os
import torch
import re
from pathlib import Path
from typing import Tuple, Union
from torch.nn import Module
from torch.optim.lr_scheduler import LRScheduler

def save_state(
        obj: Union[torch.nn.Module, LRScheduler],
        target_dir: str,
        state_name: str, ):
    target_dir_path = Path(target_dir)
    target_dir_path.mkdir(parents=True, exist_ok=True)

    state_name = f"{state_name}.pt"
    state_path = target_dir_path / state_name

    print(f"ℹ Saving state to: {state_path}")
    torch.save(
        obj=obj.state_dict(),
        f=state_path,
    )

def load_state(
        obj: Union[torch.nn.Module, LRScheduler],
        target_dir: str,
        state_name: str,
        extension: str = 'pt',
) -> Union[torch.nn.Module, LRScheduler, None]:
    target_dir_path = Path(target_dir)

    state_name = f"{state_name}.{extension}"
    state_path = target_dir_path / state_name

    if not os.path.isfile(state_path):
        return None

    print(f"ℹ Loading state from: {state_path}")
    obj.load_state_dict(torch.load(state_path))
    return obj

def load_model_w_epoch(
        model: torch.nn.Module,
        target_dir: str,
) -> Tuple[Union[Module, LRScheduler, None], int]:
    epoch = 0
    if not os.path.isdir(target_dir):
        return None, epoch

    for filename in os.listdir(target_dir):
        if filename.startswith('model-e'):
            epoch = get_model_epoch(filename)

    model = load_state(model, target_dir, f"model-e{epoch}")
    return (model if model and epoch else None), epoch

def load_scheduler(scheduler: LRScheduler, target_dir: str) -> Union[LRScheduler, None]:
    if not os.path.isdir(target_dir):
        return None
    return load_state(scheduler, target_dir, "scheduler")

def check_file_in_dir(directory, prefix):
    for filename in os.listdir(directory):
        if filename.startswith(prefix):
            return True

    return False

def get_model_epoch(filename):
    x = re.search(r'_e(\d+)', filename)
    return x.group(1) if x else None

def get_device(force_cpu):
    device = "cpu"
    if not force_cpu and torch.cuda.is_available():
        device = "cuda"
    elif not force_cpu and torch.backends.mps.is_available():
        device = "mps"
    return device


import argparse
import os
from os import listdir
from os.path import isfile, join
from pathlib import Path
from pypdf import PdfMerger
import sys

def merger_pdfs(pdfs: list[str], output_path: Path) -> None:
    """
    Merge pdfs to one pdf

    Parameters
        pdfs: A list of complet path to the PDFs
        output_path: Path to output directory where the merge PDF will be located
    """
    merger = PdfMerger()

    for pdf in pdfs:
        merger.append(pdf)

    merger.write(output_path)
    merger.close()

def get_files(path: Path) -> list[str]:
    """
    Get the complet path to PDFs from a directory

    Parameters
        path: Path to directory

    Returns
        pdfs: A list of complet path to the PDFs in directory
    """
    all_files = [file for file in listdir(path) if isfile(join(path, file))]
    incomplete_pdfs = [file for file in all_files if file[-4:] == ".pdf"]
    pdfs = [f"{path}\\" + pdf for pdf in incomplete_pdfs]

    if len(pdfs) == 0:
        sys.exit("Den valgte mappe indenholder ingen PDf'er")

    return pdfs

if __name__ == "__main__":
    # -------------------------
    # Argsparse
    # -------------------------
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-i", "--input", help="Path to directory where PDFs are located"
    )
    parser.add_argument(
        "-o", "--output", help="Path where the merge PDF will be located"
    )
    args = parser.parse_args()

    if args.output:
        output_path = args.output + r"\result.pdf"
    else:
        # Default output path
        output_path = os.path.join(sys.path[0], r"result\result.pdf")

    if args.input:
        input_path = args.input
    else:
        # Default output path
        input_path = os.path.join(sys.path[0], r"PDFs")

    # -------------------------
    # Main
    # -------------------------
    pdfs = get_files(input_path)
    merger_pdfs(pdfs, output_path)


class WordDictionary:
    def __init__(self):
        self.trie = {}

    def addWord(self, word: str) -> None:
        node = self.trie
        for w in word:
            if w not in node:
                node[w] = {}
            node = node[w]
        node['$'] = word

    def search(self, word: str) -> bool:
        def withDot(node, word):
            if not word:
                return '$' in node
            elif word[0] == '.':
                for n in node:
                    if n is not '$':
                        if withDot(node[n], word[1:]):
                            return True
                return False
            else:
                if word[0] not in node:
                    return False
                else:
                    return withDot(node[word[0]], word[1:])

        return withDot(self.trie, word)

# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)

LeetCode/Design Add and Search Words Data Structure.py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""

"""

import numpy as np
import matplotlib.pyplot as plt
import genlinmod as glm
import OMB_texturegenerator as ombtg

exp = '20180710'
stimnr = 8

steps = glm.loadstim(exp, stimnr)
texture = ombtg.texture_generator()
noiselim = ombtg.noiselim
#texture = np.flipud(texture)
#%%
def clip_trajectory(stimulus, squaredim):
    pos_filter = np.where(stimulus>0)
    neg_filter = not pos_filter
    out = np.zeros(stimulus.shape)
    out = np.fmod(stimulus, squaredim[:, np.newaxis] * 1.5,
                 where=pos_filter)
    out = np.fmod(-stimulus, squaredim[:, np.newaxis] * 1.5,
                 where=neg_filter)
    return out
#clipped = clip_trajectory(stimulus, np.array([200, 200]))

def omb_trajectory(steps):
    """
    Calculate the displacement of the OMB stimulus background texture
    based on the steps by calculating the cumulative sum.

    The input is expected to be a 2,N array containing x and y steps.
    """
    return np.cumsum(steps, axis=1)

traj_raw = omb_trajectory(steps)/4

#traj *= 6

# Clip the trajectory so that it wraps around when it reaches the edges.
# Among the numpy remainder/modulo functions fmod is the one
# that suits this purpose.
traj = np.fmod(traj_raw, 1.5*noiselim[0])

traj *= -1

#traj[0, :] = 0

#plotlim = None
#plt.plot(traj_clip[0, :plotlim], traj_clip[1, :plotlim])
#plt.show()

#%%
#%matplotlib qt
plt.imshow(texture, cmap='Greys_r',
           vmin=0, vmax=1,
           )
import time; time.sleep(2)
for i in range(0,4):
    coord = traj[:, i]
    coord = coord + np.array([*noiselim])*1.5

    plt.xlim(coord[0]+[-noiselim[0]/2, noiselim[0]/2])
    # Order of ylim is reversed from defaults so y axis is flipped
    plt.ylim(coord[1]+[-noiselim[1]/2, noiselim[1]/2])
#    plt.title(i)
    plt.pause(1)

#    input('Press return.')

#plt.show()


#!/bin/python3
import sys
sys.path.append('../')

import adt

"""
1-pass, in-place modification, using odd/even pointers and switching flag.
O(1) space complexity + O(n) running time complexity.
"""
def oddEvenList(head):
  # base case - empty or singleton
  if not head or not head.next:
    return head

  odd_head = odd = head
  even_head = even = head.next

  isOdd = True            # `switching' flag
  curr = head.next.next   # traversal pointer
  while curr:
    if isOdd:
      odd.next = curr
      odd = curr
    else:
      even.next = curr
      even = curr

    isOdd = not isOdd   # toggle flag
    curr = curr.next    # advance pointer

  even.next = None      # new list tail
  odd.next = even_head  # bridge odd's tail to even's head
  return head

if __name__ == "__main__":
  print("Enter space-separated integers: ", end="")
  nums = list(map(int, input().strip().split(' ')))

  head = adt.array_to_list(nums)
  print(head)

  head = oddEvenList(head)
  print(head)


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        iter = head
        while iter and ter.next:
            if iter.next.val == iter.val:
                iter.next = iter.next.next
            else:
                iter = iter.next
        return head

def remove_dupes(head):
    iter = head
    seen = {}
    seen[head.val] = 1
    while iter:
        if iter.next:
           if iter.next.val in seen:
               iter.next = iter.next.next
           else:
               seen[iter.val] = 1
        iter = iter.next
    return head

def remove_dupes(head):
    iter = head
    while iter.next:
        if iter.next.val == iter.val:
           iter.next = iter.next.next
        else:
           iter = iter.next
    return head

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

def addLL(head, val):
    node = ListNode(val)
    node.next = head
    return node

if __name__ == '__main__':
    s = Solution()
    head = addLL(None, 4)
    head = addLL(head, 3)
    head = addLL(head, 2)
    head = addLL(head, 2)
    head = addLL(head, 2)
    head = addLL(head, 1)
    ans = s.deleteDuplicates(head)


# http://tail-island.github.io/programming/2018/06/15/min-max-alpha-beta.html

from funcy import *
from math import inf
from random import randint

def _popcount(x):
    return bin(x).count('1')  # Pythonだと、コレが手軽で速いらしい。

# ゲームの状態。
class State:
    def __init__(self, pieces=0, enemy_pieces=0):
        self.pieces = pieces
        self.enemy_pieces = enemy_pieces

    @property
    def lose(self):
        return any(lambda mask: self.enemy_pieces & mask == mask, (
        0b111000000, 0b000111000, 0b000000111, 0b100100100, 0b010010010, 0b001001001, 0b100010001, 0b001010100))

    @property
    def draw(self):
        return _popcount(self.pieces) + _popcount(self.enemy_pieces) == 9

    @property
    def end(self):
        return self.lose or self.draw

    @property
    def legal_actions(self):
        return tuple(
            i for i in range(9) if not self.pieces & 0b100000000 >> i and not self.enemy_pieces & 0b100000000 >> i)

    def next(self, action):
        return State(self.enemy_pieces, self.pieces | 0b100000000 >> action)

    def __str__(self):
        ox = ('o', 'x') if _popcount(self.pieces) == _popcount(self.enemy_pieces) else ('x', 'o')
        return '\n'.join(''.join((ox[0] if self.pieces & 0b100000000 >> i * 3 + j else None) or (
            ox[1] if self.enemy_pieces & 0b100000000 >> i * 3 + j else None) or '-' for j in range(3)) for i in
                         range(3))

# ランダムで次の手を返します。
def random_next_action(state):
    return state.legal_actions[randint(0, len(state.legal_actions) - 1)]

# ミニ・マックス法（正確にはネガ・マックス法）
def nega_max(state):
    if state.lose:
        return -1

    if state.draw:
        return 0

    best_score = -inf

    for action in state.legal_actions:
        score = -nega_max(state.next(action))

        if score > best_score:
            best_score = score

    return best_score

# 次の手を返します（nega_maxはスコアを返すので、手を返すようにするためにほぼ同じ関数が必要になっちゃいました）。
def nega_max_next_action(state):
    best_score = -inf

    for action in state.legal_actions:
        score = -nega_max(state.next(action))

        if score > best_score:
            best_action = action
            best_score = score

    return best_action

# アルファ・ベータ法（正確にはネガ・アルファ法）
def nega_alpha(state, alpha, beta):
    if state.lose:
        return -1

    if state.draw:
        return 0

    for action in state.legal_actions:
        score = -nega_alpha(state.next(action), -beta, -alpha)

        if score > alpha:
            alpha = score

        if alpha >= beta:
            return alpha

    return alpha

# 次の手を返します（nega_alphaはスコアを返すので、手を返すようにするためにほぼ同じ関数が必要になっちゃいました）。
def nega_alpha_next_action(state):
    alpha = -inf

    for action in state.legal_actions:
        score = -nega_alpha(state.next(action), -inf, -alpha)

        if score > alpha:
            best_action = action
            alpha = score

    return best_action

def main():
    state = State()

    for next_action in cat(repeat((nega_alpha_next_action,
                                   nega_max_next_action))):  # random_next_action, nega_max_next_action, nega_alpha_next_actionの中から適当に選んでください
        if state.end:
            break;

        state = state.next(next_action(state))

        print(state)
        print()

if __name__ == '__main__':
    main()


import sys
from PyQt5 import QtWidgets, QtCore, QtGui

class SystemTrayIcon(QtWidgets.QSystemTrayIcon):

    def __init__(self, icon, parent=None):
        super(SystemTrayIcon, self).__init__(icon, parent)
        menu = QtWidgets.QMenu(parent)
        exitAction = menu.addAction("Exit")
        exitAction.triggered.connect(parent.close)
        self.setContextMenu(menu)

class Window(QtWidgets.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('TrayIcon Test')
        self.setWindowIcon(QtGui.QIcon('test.png'))
        self.tray_icon = SystemTrayIcon(QtGui.QIcon('test.png'), self)
        self.tray_icon.activated.connect(self.iconActivated)
        self.tray_icon.show()

        extractAction = QtWidgets.QAction("&GET TO THE CHOPPAH!!!", self)
        extractAction.setShortcut("Ctrl+Q")
        extractAction.setStatusTip('Leave The App')
        extractAction.triggered.connect(self.close_application)

        self.statusBar()

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(extractAction)

        self.show()

    def closeEvent(self, QCloseEvent):
        if self.tray_icon.isVisible():
            print("hiding...")
            self.hide()
            QCloseEvent.ignore()

    def iconActivated(self, reason):
        if reason == QtWidgets.QSystemTrayIcon.DoubleClick:
            self.show()

    def close_application(self):
        print("whooaaaa so custom!!!")
        sys.exit()

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    w = Window()
    sys.exit(app.exec_())


from django.test import TestCase
from ...services.location_create import create_location

class CreateLocationServiceTests(TestCase):
    acceptable_address = "Villa Straylight"
    acceptable_zone = "Freeside"
    acceptable_latitude = 15
    acceptable_longitude = 120
    acceptable_description = "c'est wow"
    acceptable_location_number = 1

    def test_create_location_from_service_happy_path(self):
        loc = create_location(
            address=self.acceptable_address,
            zone=self.acceptable_zone,
            latitude=self.acceptable_latitude,
            longitude=self.acceptable_longitude,
            description=self.acceptable_description,
            location_number=self.acceptable_location_number
        )
        self.assertEqual(str(loc), loc.address)


import sys
import time
import copy
from enum import Enum

# so, everything that has .core, refers to the api1 level (i.e. swig
# wrapped cpp code)
from valkka import core
# api2 versions of the thread classes
from valkka.api2.threads import LiveThread, USBDeviceThread, OpenGLThread
from valkka.fs import ValkkaFSManager, ValkkaMultiFS, ValkkaSingleFS
from valkka.api2.tools import parameterInitCheck, typeCheck, generateGetters
from valkka.api2.chains.port import ViewPort

from valkka.live.chain.base import BaseFilterchain
from valkka.live import singleton

class ContextType(Enum):
    none = 0
    live = 1
    usb = 2

class RecordType(Enum):
    never = 0
    movement = 1
    always = 2

class MultiForkFilterchain(BaseFilterchain):
    """This class implements the following filterchain:

    ::

        *** main branch ***

        ANYSOURCE --> {ForkFrameFilterN:fork_filter_main} --+
                                                            |
                                       filesystem branch <--+
                                                            |
                                         decoding branch <--+
                                                            |
                                                 [other] <--+   [for tcp server, rtsp server, etc.]

        *** filesystem branch ***

        --> {GateFrameFilter:fs_gate} --> {ForkFrameFilterN:fork_filter_file} -->> ValkkaFSWriterThread
                     |
          [controlled by callback (**)]               [can be recorded to 0-N filesystems on-demand]

        *** decode branch ***
                                                (OpenGLThread: glthread) <<--+
                                                                             |
        -->> (AVThread:avthread) --> {ForkFrameFilterN:fork_filter_decode} --+--> analysis branch
                           [feeds AVBitmapFrames]                            |
                                                                             +--> [other]

        *** analysis branch ***

        --> {MovementFrameFilter: movement_filter}
             |             |
             |             +~~ callback (**)
             |
             +-- {GateFrameFilter: sws_gate} --> {SwScaleFrameFilter: sws_filter} --> {ForkFrameFilterN: sws_fork_M}
                                                                                |
                   +------------+------------+---------------------------------------------+
                   |            |            |
                 on-demand terminals for RGB images, for example

                 - RGBShmemFrameFilter(s)
                 - A common framefilter for all threads:

                 --> {ThreadSafeFrameFilter: common_sws_filter} --> {RGBShmemFrameFilter: common_rgb_shmem_filter}
                 [this could feed a common yolo detector for N streams]

        *** qt bitmap branch *** (in the case you need to pass bitmaps to the qt subsystem)

        --> {GateFrameFilter: qt_gate} --> {TimeIntervalFrameFilter: qt_interval} -->
        --> {SwScaleFrameFilter: qt_sws_filter} --> {ForkFrameFilterN: qt_fork_N}
                                                              |
                   +------------+------------+----------------+
                   |            |            |
                 on-demand terminals for RGB images, for example

    """

    parameter_defs = {
        "context_type"      : ContextType,
        "openglthreads"     : list,
        "livethread"        : LiveThread,
        "usbdevicethread"   : USBDeviceThread,

        #"valkkafsmanager"   : None, # ValkkaFSManager .. this is connected on-demand & can be detached & changed
        #"record_type"       : RecordType,

        # common to LiveThread & USBDeviceThread
        "address"      : str,  # string identifying the stream
        "slot"         : int,
        # Timestamp correction type: TimeCorrectionType_none,
        # TimeCorrectionType_dummy, or TimeCorrectionType_smart (default)
        "time_correction"
                       : (int, core.TimeCorrectionType_smart),

        # identify this device / stream
        "_id"          : int,

        # LiveThread specific
        "recv_buffer_size"  : (int, 0),       # Operating system socket ringbuffer size in bytes # 0 means default
        "reordering_mstime" : (int, 0),       # Reordering buffer time for Live555 packets in MILLIseconds # 0 means default
        # "request_tcp"       : (bool, False),  # Request video over tcp (instead of udp)
        ## that's RTSP specific, so let's set it elsewhere

        # these are for the AVThread instance:
        "n_basic"      : (int, 20),  # number of payload frames in the stack
        "n_setup"      : (int, 20),  # number of setup frames in the stack
        "n_signal"     : (int, 20),  # number of signal frames in the stack
        "flush_when_full"
                       : (bool, False),  # clear fifo at overflow
        "affinity"     : (int, -1),
        "number_of_threads" : (int, 2),  # let's set this to > 1.  Otherwise people start whining when their 4K 60 fps cameras don't work..
        "verbose"      : (bool, False),
        "msreconnect"  : (int, 0),

        "shmem_image_dimensions" : None, # (tuple, (1920//4, 1080//4)),
        "shmem_n_buffer"         : None, # (int, 10),
        "shmem_image_interval"   : None, # (int, 1000),

        "vaapi": (bool, False),

        # "movement_interval" : (int, 100), # pass frames at 10 fps # USE shmem_image_interval
        # "movement_treshold" : (float, 0.01),
        "movement_treshold" : (float, 0.0), # pass always
        "movement_duration" : (int, 30000) # when movement starts, pass through frames during 30 secs
    }

    def __init__(self, **kwargs):
        # auxiliary string for debugging output
        self.pre = self.__class__.__name__ + " : "
        # check for input parameters, attach them to this instance as
        # attributes
        parameterInitCheck(MultiForkFilterchain.parameter_defs, kwargs, self)
        generateGetters(self.parameter_defs, self)

        # check some types
        for openglthread in self.openglthreads:
            assert(issubclass(openglthread.__class__, OpenGLThread))
        #if self.valkkafsmanager is not None:
        #    assert(isinstance(self.valkkafsmanager, ValkkaFSManager))
        #if record_type != RecordType.never:
        #    assert(self.id_rec > -1)

        self.idst = str(id(self))

        self.initVars() # must be called before any clients are requested

        self.make_main_branch()
        self.make_filesystem_branch() # calls by default self.fs_gate.unSet()
        self.make_decode_branch()
        self.make_analysis_branch()
        self.make_qt_branch()

        self.createContext() # creates & registers contexes to LiveThread & USBDeviceThread

        self.start() # starts threads corresponding to this filterchain

    def setTCPStreaming(self, val):
        self.request_tcp = val

    def __del__(self):
        self.requestClose()

    def initVars(self):
        # client counters
        self.decoding_client_count = 0
        self.movement_client_count = 0

        self.sws_client_count = 0
        self.x_screen_count = {}

        self.sws_client_count_qt = 0
        self.x_screen_count_qt = {}

        for i in range(len(self.openglthreads)):
            self.x_screen_count[i] = 0

        # view port related
        self.ports = []
        self.tokens_by_port = {}

        # shmem related
        self.shmem_terminals = {}
        self.width      = self.shmem_image_dimensions[0]
        self.height     = self.shmem_image_dimensions[1]

        self.shmem_terminals_qt = {}

        self.record_type = None
        self.id_rec = None
        # self.valkkafsmanager = None

        self.closed = False

        # RTPS related
        self.request_tcp = False

    def start(self):
        """Starts threads required by the filter chain
        """
        self.avthread.startCall()

    def requestClose(self):
        if not self.closed:
            self.avthread.requestStopCall()
            self.disconnectRec()
            self.releaseAllShmem()
            self.clearAllViewPorts()
        self.closed = True

    def waitClose(self):
        self.avthread.waitStopCall()

    # *** Filesystem branch related ***

    def movement_cb(self, tup: tuple):
        """callback from the cpp side

        tup = (bool, SlotNumber, mstimestamp)

        bool = True means new movement even, bool = False means movement event ended stopped

        Controls the passthrough on self.fs_gate
        """
        try:
            if tup[0]:
                self.fs_gate.set()
            else:
                self.fs_gate.unSet()
        except Exception as e:
            print("MultiFork: movement_cb failed with", e)

    # (De)activate ValkkaFSWriterThread for this slot

    """
    def setRecording(self, record_type: RecordType, manager: ValkkaFSManager, id_rec: int = None, ):
        # for the moment, only one ValkkaFSManager can be set
        if self.record_type == RecordType.never:
            print("setRecording: never")
            return

        if id_rec is None:
            self.id_rec = self._id
        else:
            self.id_rec = id_rec

        if self.valkkafsmanager is not None:
            self.clearRecording()

        self.record_type = record_type
        self.valkkafsmanager = manager

        self.fork_filter_file.connect("recorder_" + str(self.slot) , self.valkkafsmanager.getFrameFilter())
        if self.record_type== RecordType.always:
            self.fs_gate.set()
        elif self.record_type == RecordType.movement:
            print("setRecording: movement")
            self.movement_client(inc = 1)
            self.movement_filter.setCallback(self.movement_cb)
        self.valkkafsmanager.setInput(self.id_rec, self.slot)

    def clearRecording(self):
        if self.record_type == RecordType.never:
            return
        if self.valkkafsmanager is None:
            return

        if self.record_type == RecordType.always:
            self.fs_gate.unSet()
        elif self.record_type == RecordType.movement:
            self.movement_client(inc = -1)
        self.valkkafsmanager.clearInput(self.slot)
        self.fork_filter_file.disconnect("recorder_" + str(self.slot))

        self.record_type = None
        self.id_rec = None
        self.valkkafsmanager = None
    """

    def connectRecTo(self, framefilter, record_type: RecordType):
        self.record_type=record_type
        self.fork_filter_file.connect("recorder_" + str(self.slot) , framefilter)
        if self.record_type== RecordType.always:
            self.fs_gate.set()
        elif self.record_type == RecordType.movement:
            print("setRecording: movement")
            self.movement_client(inc = 1)
            self.movement_filter.setCallback(self.movement_cb)

    def disconnectRec(self):
        if self.record_type is None:
            return
        if self.record_type == RecordType.always:
            self.fs_gate.unSet()
        elif self.record_type == RecordType.movement:
            self.movement_client(inc = -1)
        self.fork_filter_file.disconnect("recorder_" + str(self.slot))
        self.record_type=None

    # *** Context creation for the relevant thread (LiveThread or USBDeviceThread) ***

    def createContext(self):
        if self.context_type == ContextType.live:
            self.createLiveContext()
        elif self.context_type == ContextType.usb:
            self.createUSBContext()

    def closeContext(self):
        if self.context_type == ContextType.live:
            self.livethread.stopStreamCall(self.ctx)
            self.livethread.deRegisterStreamCall(self.ctx)
        elif self.context_type == ContextType.usb:
            self.usbdevicethread.stopStreamCall(self.ctx)

    def createLiveContext(self):
        """Context for LiveThread

        Creates & registers a context to LiveThread and connects it to the main filterchain

        Parameters required:

        ::

            self.slot
            self.address
            self.msreconnect

            self.time_correction
            self.recv_buffer_size
            self.reordering_mstime
        """

        self.ctx = core.LiveConnectionContext()
        self.ctx.slot = self.slot

        if (self.address.find("rtsp://") == 0):
            self.ctx.connection_type = core.LiveConnectionType_rtsp # rtsp connection
        else:
            self.ctx.connection_type = core.LiveConnectionType_sdp  # an sdp file

        if (self.request_tcp):
            self.ctx.request_tcp = self.request_tcp

        self.ctx.address = self.address
        # stream address, i.e. "rtsp://.."
        print("RTSP reconnection time:", self.msreconnect)
        self.ctx.msreconnect = self.msreconnect

        self.ctx.recv_buffer_size = self.recv_buffer_size
        self.ctx.reordering_time = self.reordering_mstime * 1000  # from millisecs to microsecs

        self.ctx.time_correction = self.time_correction
        if self.ctx.time_correction == core.TimeCorrectionType_smart:
            print("createLiveContext: smart timestamps")
        else:
            print("createLiveContext: dummy timestamps")

        # connect to the main filterchain
        self.ctx.framefilter = self.fork_filter_main

        # send the information about the stream to LiveThread
        self.livethread.registerStream(self.ctx) # NOTE: api level 2
        self.livethread.playStream(self.ctx)

    def createTCPContext(self): # TODO
        pass

    def createUSBContext(self):
        """Context for USBDeviceThread

        Creates & registers a context to USBDeviceThread and connects it to the main filterchain

        Required parameters:

        ::

            self.slot
            self.address
            self.msreconnect

            self.time_correction

        """
        self.ctx = core.USBCameraConnectionContext()
        self.ctx.slot        = self.slot
        self.ctx.device      = self.address
        self.ctx.width       = 1280
        self.ctx.height      = 720
        if (self.time_correction is not None):
            self.ctx.time_correction = self.time_correction

        # connect to the main filterchain
        self.ctx.framefilter = self.fork_filter_main

        # start playing
        print("createUSBContext: play")
        self.usbdevicethread.playStream(self.ctx)

    # *** Create filtergraph branches ***

    def make_main_branch(self):
        self.fork_filter_main = core.ForkFrameFilterN("fork_filter_main_" + str(self.slot))

    def make_filesystem_branch(self):
        self.fork_filter_file = core.ForkFrameFilterN("fork_filter_file_" + str(self.slot))
        self.fs_gate = core.GateFrameFilter("fs_gate_" + str(self.slot), self.fork_filter_file)
        # connect to main:
        self.fork_filter_main.connect("fs_gate_" + str(self.slot), self.fs_gate)
        self.fs_gate.unSet()

    def make_decode_branch(self):
        self.fork_filter_decode = core.ForkFrameFilterN("fork_filter_decode_" + str(self.slot))

        self.framefifo_ctx = core.FrameFifoContext()
        self.framefifo_ctx.n_basic = self.n_basic
        self.framefifo_ctx.n_setup = self.n_setup
        self.framefifo_ctx.n_signal = self.n_signal
        self.framefifo_ctx.flush_when_full = self.flush_when_full

        if self.vaapi:
            print("using VAAPIThread")
            self.avthread = core.VAAPIThread(
                "avthread_" + str(self.slot),
                self.fork_filter_decode,
                self.framefifo_ctx)

        else:
            self.avthread = core.AVThread(
                "avthread_" + str(self.slot),
                self.fork_filter_decode,
                self.framefifo_ctx)

        if self.affinity > -1: # affinity overwrites number of threads
            self.avthread.setAffinity(self.affinity)
        elif (self.number_of_threads > 1) and (not self.vaapi):
            # ffmpeg vaapi api doesn't like multithreading!
            self.avthread.setNumberOfThreads(self.number_of_threads) # two by default
            # that's been fixed in the core libValkka: only one decoding thread for vaapi

        # get input FrameFilter from AVThread
        self.av_in_filter = self.avthread.getFrameFilter()

        # connect to main:
        self.fork_filter_main.connect("decoding_" + str(self.slot), self.av_in_filter)

    def make_analysis_branch(self):
        """Connect only if movement detector is required:

        - Recording on movement
        - Analysis on movement
        """
        self.sws_fork_filter = core.ForkFrameFilterN("sws_fork_" + str(self.slot))
        self.sws_filter = core.SwScaleFrameFilter("sws_scale_" + str(self.slot), self.width, self.height, self.sws_fork_filter)
        self.sws_gate = core.GateFrameFilter("sws_gate_" + str(self.slot), self.sws_filter)
        self.movement_filter = core.MovementFrameFilter("movement_" + str(self.slot),
                # self.movement_interval,
                self.shmem_image_interval,
                self.movement_treshold,
                self.movement_duration,
                self.sws_gate
                )
        # MovementFrameFilter(const char* name, long int interval, float treshold, long int duration, FrameFilter* next=NULL);

    def make_qt_branch(self):
        """Connect only if bitmaps needed at the Qt side
        """
        self.qt_fork_filter = core.ForkFrameFilterN("qt_fork_" + str(self.slot))

        self.qt_sws_filter =\
        core.SwScaleFrameFilter("qt_sws_scale_" + str(self.slot), self.width,
            self.height, self.qt_fork_filter)

        self.qt_interval = core.TimeIntervalFrameFilter(
            "qt_interval_" + str(self.slot),
            # self.shmem_image_interval,
            500,
            self.qt_sws_filter
            )
        self.qt_gate = core.GateFrameFilter("qt_gate_" + str(self.slot), self.qt_interval)

        # connect to main:
        self.fork_filter_decode.connect("qt_branch_" + str(self.slot), self.qt_gate)

    # *** Client calculators ***

    def decoding_client(self, inc = 0):
        """Count instances that need decoding

        Start decoding if the number goes from 0 => 1
        Stop decoding if the number goes from 1 => 0
        """
        if self.decoding_client_count < 1 and inc > 0:
            # connect the analysis branch
            print(self.__class__.__name__, "start decoding for slot", self.slot)
            self.avthread.decodingOnCall()
        elif self.decoding_client_count == 1 and inc < 0:
            print(self.__class__.__name__, "stop decoding for slot", self.slot)
            self.avthread.decodingOffCall()
        self.decoding_client_count += inc

    def movement_client(self, inc = 0):
        """Count instances that need the movement detector

        Connect if the number goes from 0 => 1
        Disconnect if the number goes from 1 => 0
        """
        print("movement_client: count, inc:", self.movement_client_count, inc)
        if self.movement_client_count < 1 and inc > 0:
            # connect the analysis branch
            print("connecting analysis branch for slot", self.slot)
            self.fork_filter_decode.connect("analysis_" + str(self.slot), self.movement_filter)
        elif self.movement_client_count == 1 and inc < 0:
            print("disconnecting analysis branch for slot", self.slot)
            self.fork_filter_decode.disconnect("analysis_" + str(self.slot))
        self.movement_client_count += inc
        self.decoding_client(inc = inc)

    def sws_client(self, inc = 0):
        """Count instances that need the sw scaled images

        Enable sws_gate if number goes from 0 => 1
        Disable sws_gate if number goes from 1 => 0
        """
        if self.sws_client_count < 1 and inc > 0:
            # connect the analysis branch
            print("connecting sws_gate for slot", self.slot)
            self.sws_gate.set()
        elif self.sws_client_count == 1 and inc < 0:
            print("disconnecting sws_gate for slot", self.slot)
            self.sws_gate.unSet()
        self.sws_client_count += inc
        self.movement_client(inc = inc)

    def sws_client_qt(self, inc = 0):
        """Count instances that need the sw scaled images for Qt

        Enable qt_gate if number goes from 0 => 1
        Disable qt_gate if number goes from 1 => 0
        """
        if self.sws_client_count_qt < 1 and inc > 0:
            # connect the analysis branch
            print("connecting qt_gate for slot", self.slot)
            self.qt_gate.set()
        elif self.sws_client_count_qt == 1 and inc < 0:
            print("disconnecting qt_gate for slot", self.slot)
            self.qt_gate.unSet()
        self.sws_client_count_qt += inc

    def x_screen_client(self, index, inc = 0):
        if self.x_screen_count[index] < 1 and inc > 0:
            openglthread = self.openglthreads[index]
            self.fork_filter_decode.connect("openglthread_" + str(index), openglthread.getInput())
        elif self.x_screen_count[index] == 1 and inc < 0:
            self.fork_filter_decode.disconnect("openglthread_" + str(index))
        self.x_screen_count[index] += inc
        self.decoding_client(inc = inc)

    # *** Shmem hooks ***

    def getShmem(self):
        """Returns the unique name identifying the shared mem and semaphores.  The name can be passed to the machine vision routines.
        """
        shmem_name = singleton.sema_uuid + "_" +\
            self.idst + "_" + str(len(self.shmem_terminals))
        print("getShmem : reserving", shmem_name)
        shmem_filter = core.RGBShmemFrameFilter(shmem_name, self.shmem_n_buffer, self.width, self.height)
        # shmem_filter = core.BriefInfoFrameFilter(shmem_name) # DEBUG: see if you are actually getting any frames here ..
        self.shmem_terminals[shmem_name] = shmem_filter
        self.sws_fork_filter.connect(shmem_name, shmem_filter)
        # if first time, connect main branch to swscale_branch
        self.sws_client(inc = 1)
        return shmem_name

    def releaseShmem(self, shmem_name):
        try:
            self.shmem_terminals.pop(shmem_name)
        except KeyError:
            return False
        print("releaseShmem : releasing", shmem_name)
        self.sws_fork_filter.disconnect(shmem_name)
        self.sws_client(inc = -1)
        return True

    def releaseAllShmem(self):
        for key in list(self.shmem_terminals.keys()):
            self.releaseShmem(key)

    # *** Shmem hooks for qt bitmaps ***

    def getShmemQt(self):
        """For passing bitmaps to the Qt side
        """
        shmem_name = singleton.sema_uuid + "_" +\
            self.idst + "_qt_" + str(len(self.shmem_terminals_qt))
        print("getShmemQt : reserving", shmem_name)
        shmem_filter = core.RGBShmemFrameFilter(shmem_name, self.shmem_n_buffer, self.width, self.height)
        # shmem_filter = core.BriefInfoFrameFilter(shmem_name) # DEBUG: see if you are actually getting any frames here ..
        self.shmem_terminals_qt[shmem_name] = shmem_filter
        self.qt_fork_filter.connect(shmem_name, shmem_filter)
        # if first time, connect main branch to swscale_branch
        self.sws_client_qt(inc = 1)
        return shmem_name, self.shmem_n_buffer, self.width, self.height

    def releaseShmemQt(self, shmem_name):
        try:
            self.shmem_terminals_qt.pop(shmem_name)
        except KeyError:
            return False
        print("releaseShmemQt : releasing", shmem_name)
        self.qt_fork_filter.disconnect(shmem_name)
        self.sws_client_qt(inc = -1)
        return True

    def releaseAllShmemQt(self):
        for key in list(self.shmem_terminals_qt.keys()):
            self.releaseShmemQt(key)

    # *** Sending video to OpenGLThreads ***
    # now in the mother class

def createTestThreads():

    """
    valkkafsmanager = ValkkaFSManager(
        valkkafs,
        # read = False,   # debugging
        # cache = False,  # debugging
        # write = False   # debugging
        )
    """

    livethread = LiveThread(         # starts live stream services (using live555)
        name="live_thread",
        # verbose=True,
        verbose=False
        )

    usbdevicethread = USBDeviceThread(
        name="usb_thread",
        #verbose=True,
        verbose=False
        )

    openglthread = OpenGLThread(     # starts frame presenting services
        name="opengl_thread",
        # reserve stacks of YUV video frames for various resolutions
        n_720p  = 20,
        n_1080p = 20,
        n_1440p = 20,
        n_4K    = 0,
        verbose = True,
        # verbose=False,
        msbuftime = 300
        )

    return livethread, usbdevicethread, openglthread

def test1():
    """Test basic functionality of the MultiForkFilterchain
    """
    singleton.sema_uuid = "test1"

    valkkafs = ValkkaSingleFS.newFromDirectory(
        dirname = "/home/sampsa/tmp/testvalkkafs",
        blocksize = 512*1024,
        n_blocks = 10,
        verbose = True
        )

    valkkafsmanager = ValkkaFSManager([valkkafs])
    valkkafsmanager.start() # TODO: remember to add this elsewhere

    # getattr(valkkafsmanager,"iterateFsInput")

    livethread, usbdevicethread, openglthread = createTestThreads()

    address = sys.argv[2]
    context_type = ContextType.live

    #address = "/dev/video0"
    #context_type = ContextType.usb

    # record_type = RecordType.never
    #record_type = RecordType.always
    #record_type = RecordType.movement

    fc = MultiForkFilterchain(
        context_type     = context_type,
        openglthreads    = [openglthread],
        livethread       = livethread,
        usbdevicethread  = usbdevicethread,
        address          = address,
        slot             = 2,
        _id              = 123,
        shmem_image_dimensions = (1920//4, 1080//4),
        shmem_n_buffer   = 10,
        shmem_image_interval = 1000
        )

    window_id = openglthread.createWindow()
    view_port = ViewPort(window_id = window_id, x_screen_num = 0)

    n = 2

    print("\nadd view port\n")
    fc.addViewPort(view_port)
    print("\nsleep\n")
    time.sleep(n)

    print("\ndel view port\n")
    fc.delViewPort(view_port)
    print("\nsleep\n")
    time.sleep(n)

    print("\nsetRecording (always)\n")
    # fc.setRecording(12345, RecordType.always, valkkafsmanager)
    for valkkafs, inputfilter in valkkafsmanager.iterateFsInput():
        valkkafsmanager.map_(
            valkkafs=valkkafs,
            # read & cached stream is sent/output'd here:
            # (in this test it is not used)
            # framefilter=playback_fc.getInputFilter(),
            framefilter=None,
            write_slot=fc.slot,
            read_slot=None,
            _id=fc.slot
        )
        fc.connectRecTo(
            inputfilter,
            RecordType.always
        )
    print("\nsleep\n")
    time.sleep(n)

    print("\nclearRecording\n")
    for valkkafs, inputfilter in valkkafsmanager.iterateFsInput():
        valkkafsmanager.unmap(valkkafs, _id=fc.slot)
        fc.disconnectRec()

    print("\nsleep\n")
    time.sleep(n)

    """
    print("\nsetRecording (movement)\n")
    for valkkafs, inputfilter in valkkafsmanager.iterateFsInput():
        fc.connectRecTo(
            inputfilter,
            RecordType.movement
        )
    print("\nsleep\n")
    time.sleep(n)
    """

    again = True
    record_type = RecordType.always
    # record_type = RecordType.movement # ssssegfauuult!

    if again:
        print("\nsetRecording (always) again\n")
        for valkkafs, inputfilter in valkkafsmanager.iterateFsInput():
            valkkafsmanager.map_(
                valkkafs=valkkafs,
                # read & cached stream is sent/output'd here:
                # (in this test it is not used)
                # framefilter=playback_fc.getInputFilter(),
                framefilter=None,
                write_slot=fc.slot,
                read_slot=None,
                _id=fc.slot
            )
            fc.connectRecTo(
                inputfilter,
                record_type
            )
        print("\nsleep\n")
        time.sleep(n)

    print("\nsetRecording getShmem\n")
    name = fc.getShmem()
    print("\nsleep\n")
    time.sleep(n)

    print("\nsetRecording releaseShmem\n")
    fc.releaseShmem(name)
    print("\nsleep\n")
    time.sleep(n)

    if again:
        print("\nclearRecording\n")
        for valkkafs, inputfilter in valkkafsmanager.iterateFsInput():
            valkkafsmanager.unmap(valkkafs, _id=fc.slot)
            fc.disconnectRec()

    print("req close")

    fc.             requestClose()
    valkkafsmanager.requestClose()
    livethread.     requestClose()
    usbdevicethread.requestClose()
    openglthread.   requestClose()

    print("wait close fc")
    fc.             waitClose()
    print("wait close manager")
    valkkafsmanager.waitClose()
    print("wait close live")
    livethread.     waitClose()
    print("wait close usb")
    usbdevicethread.waitClose()
    print("wait close gl")
    openglthread.   waitClose()
    print("bye")

def main():
    pre = __name__ + "main :"
    print(pre, "main: arguments: ", sys.argv)
    if (len(sys.argv) < 2):
        print(pre, "main: needs test number")
    else:
        st = "test" + str(sys.argv[1]) + "()"
        exec(st)

if (__name__ == "__main__"):
    main()


from datetime import datetime
import sys

def read_datetimes(filename='sample_datetimes.txt'):

    datetimes = {'TRAIN':[], 'TEST':[]}

    f = open(filename,'r')

    for aline in f:

        if aline.startswith('*'):
            akey = aline.replace('*','').strip()
            continue

        items = [anitem.strip() for anitem in aline.split()]

        samplenumber = int(items[0])
        adatetime = datetime.strptime(items[1], '%Y%m%d%H%MZ')

        datetimes[akey].append(adatetime)

    f.close()

    return datetimes


from django.urls import path
from coin import views
from django.conf.urls import url
urlpatterns = [
    path('',views.index, name='index'),
    path('CoinCap',views.coinDetail,name='coinDetail'),
    path('MoneyEXC',views.moneyEXC,name='moneyEXC'),
    path('MoneyEXC/excGraph',views.excGraph,name='excGraph'),
    url(r'^graph/(?P<coin_id>[A-Za-z0-9]+)$',views.graph, name='graphDetail'),
]


    #se imprime la fila, esta funcion es llamada por la de ingresar matrix para mostrar a fila que guardo por medio de componentes
def mostrar_matrix (matrix_to_show):
   print("--------------")
   for fila in matrix_to_show:
    print(fila)

    #se añade el numero de filas y columnas... después pide añadir los comonentes que se ingresan en la fila y columna correspondiente
def ingresar_matrix():

  cantidad_de_filas = int(input("introducir cantidad de filas: "))
  cantidad_de_columnas = int(input("introducir cantidad de columnas: "))

  new_matrix = [ ]

   #indice fila esta en el rango que determina la cantidad  de filas puesto arriba
   #indice columna bis y ambos van desde 0 a ---
   #componente: es el numero guardado en infice fila-indice columna
  for indice_fila in range(cantidad_de_filas):
     fila = [ ]

     for indice_columna in range(cantidad_de_columnas):
         componente = int(input(f"ingese el valor del componente en la f{indice_fila} y c{indice_columna}: "))
         fila.append(componente)

     new_matrix.append(fila)

  mostrar_matrix(new_matrix)

  return new_matrix
#matrix1 seria la cantidad de columnas de la primera fila de la matrizx1
# aca bamos a ver si las matrices se pueden sumar, las condiciones es que tengan la misma cantidad de elemento
def se_pueden_sumar_las_matrices():
    if (len(matrix1) == 0) or (len(matrix2) == 0 ) or (len(matrix1) != len(matrix2)):
        return False

    for indice_fila in range(len(matrix1)):
        fila_a_verificar_matrix1 = matrix1[indice_fila]
        fila_a_verificar_matrix2 = matrix2[indice_fila]

        if not (cantidad_columnas == len(fila_a_verificar_matrix1)) and (cantidad_columnas == len(fila_a_verificar_matrix2)):
            return False

    return True

matrixA = ingresar_matrix()
matrixB = ingresar_matrix()

if not se_pueden_sumar_las_matrices(matrixA, matrixB):
    print("las matrices no se pueden sumar porque no tienen el mismo tamaño ")
    quit()


from collections import deque
class Node:
    def __init__(self, v, children=None):
        if children is None:
            children = []
        self.children = children
        self.v = v
    def __eq__(self, other):
        return self.__dict__ == other.__dict__

def serialize(t):
    s = str(t.v)
    for c in t.children:
        s += ' ' + serialize(c)
    s += ' |'
    return s

def deserialize(s):
    a = deque(s.split(' '))
    return dehelper(a)

def dehelper(a):
    n = Node(int(a[0]))
    a.popleft()
    while a[0] != '|':
        n.children.append(dehelper(a))
    a.popleft()
    return n

def dfs(t, l):
    print(t.v, l)
    for c in t.children:
        dfs(c, l+1)

a = Node(3, [Node(4), Node(5, [Node(7), Node(8)]), Node(6)])
b = serialize(a)
c = deserialize(b)
print(b)
print(a == c)


from typing import List

class Solution:
    def containsDuplicate(self, numbers: List[int]) -> bool:
        return self.__method1(numbers)

    # 基于哈希表的解法
    def __method1(self, numbers: List[int]) -> bool:
        d = {}
        for n in numbers:
            if n in d:
                return True
            else:
                d[n] = 1
        return False

    # 基于排序和双指针的解法
    def __method2(self, numbers: List[int]) -> bool:
        length = len(numbers)
        if length == 1:
            return False

        numbers = sorted(numbers)
        i, j = 0, 1
        while j < length:
            if numbers[i] == numbers[j]:
                return True
            i += 1
            j += 1
        return False


# importing dependencies
import requests # request html file of link
from bs4 import BeautifulSoup # html parser to get the data that we need
import numpy as np # vector operations
import pandas as pd # label data
import matplotlib.pyplot as plt # visualize data
from sklearn.linear_model import LinearRegression # process data
import pickle # to use save and reuse model

# NOTE: KIJIJI often changes their html attribute values to avoid parsers, these have
# to be manually scanned and updated for the script to work

# the search result link that will be scraped
# split into 2 as an interger will indicate the page in between
baseSearch = "https://www.kijiji.ca/b-cars-vehicles/canada/equinox/page-"
baseSearch2 = "/k0c27l0?ad=offering&price=3500__"

# get the links of a search page
def get_ads_link(searchLink, numPages):
	# searchLink - the link that will be scraped
	#			   comes in a list of two parts
	# numPages - the number of pages you wish to scrape
	#			 each page has around 20 - 25 unique ads

	ads = []

	#loop through pages
	for i in range(1, numPages+1):
	#request the link, then parse it with beautiful soup
		r = requests.get(searchLink[0] + str(i) + searchLink[1])
		soup = BeautifulSoup(r.content)
		listOfDivs = soup.find_all("div")

	#search for divs with correct attributes then save the link
		for div in listOfDivs:
		# data-vip-url is the attribute for the link of the ad that pops up on search
			if div.has_attr("data-vip-url"):

				# retriving the link
				link = div["data-vip-url"]
				# concat strings to result in a proper link in english
				ads.append("https://www.kijiji.ca" + link + "?null&siteLocale=en_CA")

		print("%d of %d" %(i, numPages), end="\r")
	#return unique ads
	return list(set(ads))

# get relevant data from data
def get_ads_data(ads):
	raw_data = []
	errorLog = []
	numAds = len(ads)

	# retrieve html of each ad
	for i, ad in enumerate(ads):
		r = requests.get(ad)
		soup = BeautifulSoup(r.content)

		# getting the price tag of each ad
		try:
			price = soup.find_all("span", {"class": "currentPrice-3369960085"})[0].text
		except:
			try:
				price = soup.find_all("span", {"data-reactid": "39"})[0]["value"]
			except:
				try:
					price = soup.find_all("span", {"data-reactid": "40"})[0]["value"]
				except:
					try:
						price = soup.find_all("span", {"data-reactid": "42"})[0]["value"]
					except:
						errorLog.append(i)
						print("Price Error")

		# retrieve attributes of car
		try:
			# retrieve the label of data and data
			s_data_label = soup.find_all("p", {"class": "attributeLabel-2129198691"}, text=True)
			s_data = soup.find_all("h4", {"class": "attributeValue-4132240161"})
			# check if data matches
			if len(s_data) != len(s_data_label):
				errorLog.append(i)
				print("Data Error")
			else:
				for j in range(len(s_data)):
					s_data[j] = s_data[j].text
					s_data_label[j] = s_data_label[j].text
		except:
			errorLog.append(i)

	    # retrieve title description of the ad
		try:
			title = soup.find_all("h1", {"class": "title-1093844370"})[0].text
		except:
			errorLog.append(i)
			print("Title Error")
		raw_data.append([price, ad, title, [s_data_label, s_data]])
		print("%d of %d" %(i, numAds))

	# remove all ads in the error log
	for index in sorted(errorLog, reverse=True):
		del raw_data[index]

	return raw_data

ads = get_ads_link([baseSearch, baseSearch2], 1)
raw_data = get_ads_data(ads)

with open("raw_data.pkl", "wb") as output_file:
    pickle.dump(raw_data, output_file)


# coding=utf-8

import hashlib
import string
import random

# texto randomico ASCII uppercase com digítos
def random_key(size=5):
    chars = string.ascii_uppercase + string.digits
    return ''.join(random.choice(chars) for x in range(size))

# adiciona um salt (informações do usuário) ao texto randomico gerado na função de cima
def generate_hash_key(salt, random_str_size=5):
    random_str = random_key(random_str_size)
    text = random_str + salt
    return hashlib.sha224(text.encode('utf-8')).hexdigest()


from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
import pandas as pd
import numpy as np
import matplotlib.pyplot as a
data = pd.read_csv('ds8.csv')
f1 =data['Distance_Feature']
f2=data['Speeding_Feature']
x =np.array(list(zip(f1,f2)))
a.scatter(f1,f2,color='black')
a.title('Real')
a.ylabel('speeding_feature')
a.xlabel('distance_feature')
a.show()
kmeans = KMeans(3).fit(x)
labels = kmeans.predict(x)
a.scatter(f1,f2,c=labels)
a.title('KMeans')
a.ylabel('speeding_feature')
a.xlabel('distance_feature')
a.show()
gm = GaussianMixture(3).fit(x)
labels = gm.predict(x)
a.scatter(f1,f2,c=labels)
a.title('GMM Classification')
a.ylabel('speeding_feature')
a.xlabel('distance_feature')
a.show()

#Dataset
Driver_ID,Distance_Feature,Speeding_Feature
3423311935,71.24,28.0
3423313212,52.53,25.0
3423313724,64.54,78.0
3423311373,55.69,22.0
3423310999,54.58,25.0
3423319935,90.24,28.0
3423318212,82.53,25.0
3423317724,6.54,26.0
3423311363,65.69,32.0
3423310929,44.58,25.0


#!/usr/bin/env python3

# This code jam solution is powered by Nathan West's LibCodeJam; see
# https://github.com/Lucretiel/LibCodeJam for source code and (ostensibly) some
# documentation.

from code_jam import *
from functools import lru_cache

# code_jam.INSERT_NEWLINE = True

# quick reference:
#   @autosolve, @collects, @cases(n)
#   tokens.token(t), tokens.many(n, t)
#   debug(expr), @unroll(t)gen
#   solve(int_token: int, list_token: ('int_token', str), other_list: (None, float)):

G = '+'
B = '-'

@lru_cache()
@unroll(''.join)
def flip(stack):
    for i in reversed(stack):
        yield B if i == G else G

@lru_cache()
@unroll(''.join)
def flip_head(stack):
    stack = iter(stack)

    while next(stack) == G:
        yield B

    yield B
    yield from stack

def num_flips(stack):
    stack = stack.rstrip(G)

    if not stack:
        return 0

    flips = 0

    if stack[0] == G:
        stack = flip_head(stack)
        flips += 1

    stack = flip(stack)
    flips += 1

    return flips + num_flips(stack)

@autosolve
@collects
def solve(stack: str):
    return num_flips(stack)