import utils
import conexion
import clientes
import productos
import empresa
import tipopago
import facturadetalle
from datetime import datetime
from time import sleep

log = utils.log("INIT")
log.info("inicio del programa")
lstClientes = []
lstTipoPago = []
lstEmpresa = []
lstProductos = []
lstFacDetalle = []

def cargarObjetos():
    conn = conexion.conexionBDD(1)
    query = "select idCliente, nombreCliente as Nombre, nroIdentidicacionCliente as ID, direccionCliente as Direccion from clientes;"
    resconn = conn.consultarBDD(query)
    for row in resconn:
        cliente = clientes.clientes(row[0],row[1],row[2],row[3])
        lstClientes.append(cliente)

    for obj in lstClientes:
        print(obj.nombreCliente)
    input("continuar")

def crearFactura():

    igv = 0.18
    valorProducto = 0.00
    igvProducto = 0
    igvFacCabecera = 0.00
    subtotalFac = 0.00
    totalFac = 0.00
    fecha = datetime.today().strftime('%Y-%m-%d')

    print(f"La fecha de hoy es: {fecha}")
    idcliente = input("escribe el codigo del Cliente: ")
    idtipopago = input("ingrese el codigo de tipo de pago: ")
    #fecha = input("Ingrese la fecha de la factura (yyyy-mm-dd): ")

    log.debug("crear factura")
    conn = conexion.conexionBDD(1)

    stopIngreso = True
    while stopIngreso:
        idproducto = input("ingrese el codigo de  producto: ")
        cantFacDetalle = input("ingrese la cantidad: ")
        masProducto = input("Desea ingresar otro producto Si (1) / No (0): ")
        if masProducto != '1':
            stopIngreso = False
        query = f"select idproducto, valorProducto, igvProducto from productos where idproducto = {idproducto};"
        resconn = conn.consultarBDD(query)
        for row in resconn:
            valorProducto = row[1]
            igvProducto = row[2]

        factdetalle = facturadetalle.facturadetalle(1, 1, idproducto, cantFacDetalle, valorProducto)
        lstFacDetalle.append(factdetalle)

        subtotalFac = valorProducto * int(cantFacDetalle)
        if igvProducto == 1:
            igvFacCabecera += float(subtotalFac) * float(igv)

    totalFac = float(subtotalFac) + igvFacCabecera

    if  totalFac > 0:
        query = "insert into faccabecera (idempresa, idcliente, idtipoPago, fechaFacCabecera, igvFacCabecera, subtotalFacCabecera, totalFacCabecera, estadoFactura) "
        query += f"values(1, {idcliente}, {idtipopago}, '{fecha}', {igvFacCabecera}, {subtotalFac}, {totalFac}, '1');"
        resConn = conn.ejecutarBDD(query)
        if(resConn):
            print("Se ejecuto correctamente registro de factura")
        else:
            print("Hubo un error")
        sleep(5)

        query = f"select MAX(idfacCabecera) AS 'idFactura' from faccabecera where fechaFacCabecera = '{fecha}';"
        resconn = conn.consultarBDD(query)
        for row in resconn:
            print(row[0])
            idfacCabecera = int(row[0])

        if idfacCabecera > 0:
            for obj in  lstFacDetalle:
                query = "insert into facdetalle (idfacCabecera, idproducto, cantFacDetalle, valorFacDetalle) "
                query += f"values({idfacCabecera}, {idproducto}, {obj.cantFacDetalle}, {obj.valorFacDetalle});"
                resConn = conn.ejecutarBDD(query)
            if(resConn):
                print("Se ejecuto correctamente registro de factura detalle")
            else:
                print("Hubo un error")
            sleep(5)

def mantenimientoCliente():
    dicMenuCliente = {  "\t- Buscar Cliente Todos": 1,
                        "\t- Buscar Cliente por DNI": 2,
                        "\t- Modificar Cliente por DNI": 3,
                        "\t- Crear Cliente": 4,
                        "\t- Borrar Cliente": 5}
    menuCliente = utils.Menu("Menu Cliente", dicMenuCliente)
    resMenuCliente = menuCliente.mostrarMenu()
    if(resMenuCliente == 1):
        log.debug("buscamos cliente")
        conn = conexion.conexionBDD(1)
        query = "select idCliente, nombreCliente as Nombre, nroIdentidicacionCliente as ID, direccionCliente as Direccion from clientes;"
        resConn = conn.consultarBDD(query)
        print("\tID\t\tNombre\t\t\tDNI\t\t\tDireccion")
        for row in resConn:
            print(f"\t{str(row[0])}\t\t{str(row[1])}\t\t{str(row[2])}\t\t{str(row[3])}")

        input("continuar???")
        print(resConn)
    elif(resMenuCliente == 2):
        log.debug("buscamos cliente por DNI")
        print("escribe el numero de DNI")
        dni = input()
        conn = conexion.conexionBDD(1)
        query = f"select idCliente, nombreCliente as Nombre, nroIdentidicacionCliente as ID, direccionCliente as Direccion from clientes where nroIdentidicacionCliente = '{dni}';"
        resConn = conn.consultarBDD(query)
        print("\tID\t\tNombre\t\t\tDNI\t\t\tDireccion")
        for row in resConn:
            print(f"\t{str(row[0])}\t\t{str(row[1])}\t\t{str(row[2])}\t\t{str(row[3])}")
        input("continuar???")
        print(resConn)
    elif(resMenuCliente == 3):
        log.debug("buscamos cliente")
        conn = conexion.conexionBDD(1)
        query = "select idCliente, nombreCliente as Nombre, nroIdentidicacionCliente as ID, direccionCliente as Direccion from clientes;"
        resConn = conn.consultarBDD(query)
        print("Escoja el ID del cliente que desea modificar")
        print("\tID\t\tNombre\t\t\tDNI\t\t\tDireccion")
        for row in resConn:
            print(f"\t{str(row[0])}\t\t{str(row[1])}\t\t{str(row[2])}\t\t{str(row[3])}")

        idcliente = input()
        print("Escriba el nuevo valor para Nombre")
        nombre = input()
        print("Escriba el nuevo valor para DNI")
        dni = input()
        print("Escriba el nuevo valor para Direccion")
        direccion = input()
        query = f"update clientes set nombreCliente = '{nombre}', nroIdentidicacionCliente = '{dni}',direccionCliente = '{direccion}' where idCliente = {idcliente};"
        resConn = conn.ejecutarBDD(query)
        if(resConn):
            print("Se ejecuto correctamente")
        else:
            print("Hubo un error")

        input("desea continuar???")
    elif(resMenuCliente == 4):
        print("##Creacion de un cliente##")
        print("Escriba el Nombre del Cliente")
        nombre = input()
        print("Escriba el DNI del Cliente")
        dni = input()
        print("Escriba el Direccion del Cliente")
        direccion = input()
        conn = conexion.conexionBDD(1)
        query = f"insert into clientes (nombreCliente, nroIdentidicacionCliente,direccionCliente) values('{nombre}','{dni}','{direccion}');"
        resConn = conn.ejecutarBDD(query)
        if(resConn):
            print("Se ejecuto correctamente")
        else:
            print("Hubo un error")

        input("desea continuar???")
    elif(resMenuCliente == 5):
        log.debug("eliminamos cliente")
        conn = conexion.conexionBDD(1)
        query = "select idCliente, nombreCliente as Nombre, nroIdentidicacionCliente as ID, direccionCliente as Direccion from clientes;"
        resConn = conn.consultarBDD(query)
        print("Escoja el ID del cliente que desea eliminar")
        print("\tID\t\tNombre\t\t\tDNI\t\t\tDireccion")
        for row in resConn:
            print(f"\t{str(row[0])}\t\t{str(row[1])}\t\t{str(row[2])}\t\t{str(row[3])}")

        idcliente = input()

        query = f"delete from clientes where idCliente = {idcliente} ;"
        resConn = conn.ejecutarBDD(query)
        if(resConn):
            print("Se ejecuto correctamente")
        else:
            print("Hubo un error")

        input("desea continuar???")

def mantenimientoProducto():
    dicMenuProducto = { "\t- Buscar todos Productos": 1,
                        "\t- Buscar Producto por codigo de Producto": 2,
                        "\t- Modificar Producto por codigo de Producto": 3,
                        "\t- Crear Producto": 4,
                        "\t- Borrar Producto": 5}
    menuProducto = utils.Menu("Menu Producto", dicMenuProducto)
    resMenuProducto = menuProducto.mostrarMenu()
    #print(resMenuProducto)
    if(resMenuProducto == 1):
        log.debug("buscamos producto")
        conn = conexion.conexionBDD(1)
        #2query = "select idCliente, nombreCliente as Nombre, nroIdentidicacionCliente as ID, direccionCliente as Direccion from clientes;"
        query = "select idproducto, nombreProducto as Nombre, valorProducto as Valor, igvProducto as IGV from productos;"
        resConn = conn.consultarBDD(query)
        print("\tID\t\tNombre\t\t\tValor\t\t\tIGV")
        for row in resConn:
            print(f"\t{str(row[0])}\t\t{str(row[1])}\t\t{str(row[2])}\t\t{str(row[3])}")

        input("continuar???")
        print(resConn)
    elif(resMenuProducto == 2):
        log.debug("buscamos producto por codigo de producto")
        print("escribe el código del producto")
        codigoproducto = input()
        conn = conexion.conexionBDD(1)
        query = f"select idproducto, nombreProducto as Nombre, valorProducto as Valor, igvProducto as IGV from productos where idproducto = {codigoproducto};"
        print(query)
        resConn = conn.consultarBDD(query)
        print("\tID\t\tProducto\t\t\tValor\t\t\tIGV")
        for row in resConn:
            print(f"\t{str(row[0])}\t\t{str(row[1])}\t\t{str(row[2])}\t\t{str(row[3])}")
        input("continuar???")
        print(resConn)
    elif(resMenuProducto == 3):
        log.debug("buscamos el producto")
        conn = conexion.conexionBDD(1)
        #query = "select idCliente, nombreCliente as Nombre, nroIdentidicacionCliente as ID, direccionCliente as Direccion from clientes;"
        query = "select idproducto, nombreProducto as Nombre, valorProducto as Valor, igvProducto as IGV from productos;"
        resConn = conn.consultarBDD(query)
        print("Escoja el ID del producto que desea modificar")
        print("\tID\t\tNombre\t\t\tValor\t\t\tIGV")
        for row in resConn:
            print(f"\t{str(row[0])}\t\t{str(row[1])}\t\t{str(row[2])}\t\t{str(row[3])}")

        idproducto = input()
        print("Escriba el nuevo valor para Nombre")
        nombreproducto = input()
        print("Escriba el nuevo valor para Valor del producto")
        valorproducto = input()
        print("Escriba el nuevo valor para IGV")
        igvproducto = input()
        #query = f"update clientes set nombreCliente = '{nombre}', nroIdentidicacionCliente = '{dni}',direccionCliente = '{direccion}' where idCliente = {idcliente};"
        query = f"update productos set nombreProducto = '{nombreproducto}', valorProducto = '{valorproducto}', igvProducto = {igvproducto} where idproducto = {idproducto};"

        resConn = conn.ejecutarBDD(query)
        if(resConn):
            print("Se ejecuto correctamente")
        else:
            print("Hubo un error")

        input("desea continuar???")
    elif(resMenuProducto == 4):
        print("##Creacion de un Producto##")
        print("Escriba el Nombre del Producto")
        nombreproducto = input()
        print("Escriba el valor del Producto")
        valorproducto = input()
        print("Escriba el IGV del Producto")
        igvproducto = input()
        conn = conexion.conexionBDD(1)
        print("hola")
        #query = f"insert into clientes (nombreCliente, nroIdentidicacionCliente,direccionCliente) values('{nombre}','{dni}','{direccion}');"
        query = f"insert into productos (nombreProducto, valorProducto, igvProducto) values('{nombreproducto}', '{valorproducto}', '{igvproducto}');"
        #print (query)
        resConn = conn.ejecutarBDD(query)
        if(resConn):
            print("Se ejecuto correctamente")
        else:
            print("Hubo un error")

        input("desea continuar???")
    elif(resMenuProducto == 5):
        log.debug("eliminamos producto")
        conn = conexion.conexionBDD(1)
        #query = "select idCliente, nombreCliente as Nombre, nroIdentidicacionCliente as ID, direccionCliente as Direccion from clientes;"
        query = "select idproducto, nombreProducto as Nombre, valorProducto as Valor, igvProducto as IGV from productos;"
        resConn = conn.consultarBDD(query)
        print("Escoja el codigo del producto que desea eliminar")
        print("\tID\t\tNombre\t\t\tValor\t\t\tIGV")
        for row in resConn:
            print(f"\t{str(row[0])}\t\t{str(row[1])}\t\t{str(row[2])}\t\t{str(row[3])}")

        idproducto = input()

        query = f"delete from productos where idproducto = {idproducto} ;"

        resConn = conn.ejecutarBDD(query)
        if(resConn):
            print("Se ejecuto correctamente")
        else:
            print("Hubo un error")

        input("desea continuar???")

def mantenimientoEmpresa():
    dicMenuEmpresa = { "\t- Buscar datos de Empresa": 1,
                        "\t- Modificar datos de Empresa por codigo de Empresa": 2,
                      }
    menuEmpresa = utils.Menu("Menu Producto", dicMenuEmpresa)
    resMenuEmpresa = menuEmpresa.mostrarMenu()
    if(resMenuEmpresa == 1):
        log.debug("buscamos Empresa")
        conn = conexion.conexionBDD(1)
        #2query = "select idCliente, nombreCliente as Nombre, nroIdentidicacionCliente as ID, direccionCliente as Direccion from clientes;"
        query = "select idempresa, rucEmpresa as RUC, nombreEmpresa as Empresa from empresa;"
        resConn = conn.consultarBDD(query)
        print("\tID\t\tRUC\t\t\tEmpresa")
        for row in resConn:
            print(f"\t{str(row[0])}\t\t{str(row[1])}\t\t{str(row[2])}")

        input("continuar???")
        print(resConn)
    elif(resMenuEmpresa == 2):
        log.debug("buscamos la empresa")
        conn = conexion.conexionBDD(1)
        #query = "select idCliente, nombreCliente as Nombre, nroIdentidicacionCliente as ID, direccionCliente as Direccion from clientes;"
        # query = "select idproducto, nombreProducto as Nombre, valorProducto as Valor, igvProducto as IGV from productos;"
        # resConn = conn.consultarBDD(query)
        query = "select idempresa, rucEmpresa as RUC, nombreEmpresa as Empresa from empresa;"
        resConn = conn.consultarBDD(query)
        print("Escoja el ID de la empresa que desea modificar")
        print("\tID\t\tRUC\t\t\tEmpresa")
        for row in resConn:
            print(f"\t{str(row[0])}\t\t{str(row[1])}\t\t{str(row[2])}")

        idempresa = input()
        print("Escriba el nuevo valor para Nombre")
        nombreempresa = input()
        print("Escriba el nuevo valor para el RUC")
        rucempresa = input()

        #query = f"update clientes set nombreCliente = '{nombre}', nroIdentidicacionCliente = '{dni}',direccionCliente = '{direccion}' where idCliente = {idcliente};"
        #query = f"update productos set nombreProducto = '{nombreproducto}', valorProducto = '{valorproducto}', igvProducto = {igvproducto} where idproducto = {idproducto};"
        query = f"update empresa set rucEmpresa = '{rucempresa}', nombreEmpresa = '{nombreempresa}' where idempresa = {idempresa};"

        resConn = conn.ejecutarBDD(query)
        if(resConn):
            print("Se ejecuto correctamente")
        else:
            print("Hubo un error")

        input("desea continuar???")

def mantenimientoTipoPago():
    dicMenuTipoPago = { "\t- Buscar tipo de pago": 1,
                        "\t- Buscar tipo de pago por codigo de tipo de pago": 2,
                        "\t- Modificar tipo de pago por codigo de tipo de pago": 3,
                        "\t- Crear tipo de pago": 4,
                        "\t- Borrar tipo de pago": 5}
    menuTipoPago= utils.Menu("Menu TipoPago", dicMenuTipoPago)
    resMenuTipoPago = menuTipoPago.mostrarMenu()
    if(resMenuTipoPago == 1):
        log.debug("buscamos Tipo de Pago")
        conn = conexion.conexionBDD(1)
        #2query = "select idCliente, nombreCliente as Nombre, nroIdentidicacionCliente as ID, direccionCliente as Direccion from clientes;"
        #query = "select idempresa, rucEmpresa as RUC, nombreEmpresa as Empresa from empresa;"
        query = "Select idtipopago, descTipoPago as Descripcion from tipopago;"

        resConn = conn.consultarBDD(query)
        print("\tID\t\tTipo de Pago")
        for row in resConn:
            print(f"\t{str(row[0])}\t\t{str(row[1])}")

        input("continuar???")
        print(resConn)

    elif(resMenuTipoPago == 2):
        log.debug("buscamos tipo de pago por codigo de tipo de pago")
        print("escribe el código del producto")
        codigotipopago = input()
        conn = conexion.conexionBDD(1)
        query = "Select idtipopago, descTipoPago as Descripcion from tipopago where descTipoPago = 'Efectivo';"

        print(query)
        resConn = conn.consultarBDD(query)
        print("\tID\t\tTipo de Pago")
        for row in resConn:
            print(f"\t{str(row[0])}\t\t{str(row[1])}")
        input("continuar???")
        print(resConn)

    elif(resMenuTipoPago == 3):
        log.debug("buscamos el tipo de pago")
        conn = conexion.conexionBDD(1)
        #query = "select idCliente, nombreCliente as Nombre, nroIdentidicacionCliente as ID, direccionCliente as Direccion from clientes;"
        query = "Select idtipopago, descTipoPago as Descripcion from tipopago;"
        resConn = conn.consultarBDD(query)

        print("Escoja el codigo de tipo de pago que desea modificar")
        print("\tcodigo\t\tTipo de Pago")
        for row in resConn:
            print(f"\t{str(row[0])}\t\t{str(row[1])}")

        codigotipopago = input()
        print("Escriba el nuevo valor para tipo de pago")
        desctipopago = input()
        #query = f"update clientes set nombreCliente = '{nombre}', nroIdentidicacionCliente = '{dni}',direccionCliente = '{direccion}' where idCliente = {idcliente};"
        #query = f"update productos set nombreProducto = '{nombreproducto}', valorProducto = '{valorproducto}', igvProducto = {igvproducto} where idproducto = {idproducto};"
        query = f"update tipopago set descTipoPago = '{desctipopago}' where idtipopago = '{codigotipopago}';"

        resConn = conn.ejecutarBDD(query)
        if(resConn):
            print("Se ejecuto correctamente")
        else:
            print("Hubo un error")

        input("desea continuar???")

    elif(resMenuTipoPago == 4):
        print("##Creacion de un tipo de pago##")
        print("Escriba el Tipo de Pago")
        desctipopago = input()

        conn = conexion.conexionBDD(1)
        #print("hola")
        #query = f"insert into clientes (nombreCliente, nroIdentidicacionCliente,direccionCliente) values('{nombre}','{dni}','{direccion}');"
        query = f"insert into tipopago(descTipoPago) values('{desctipopago}');"
        #INSERT INTO tipopago(descTipoPago)VALUES('Efectivo');
        #print (query)
        resConn = conn.ejecutarBDD(query)
        if(resConn):
            print("Se ejecuto correctamente")
        else:
            print("Hubo un error")

        input("desea continuar???")

    elif(resMenuTipoPago == 5):
        log.debug("eliminamos un tipo de pago")
        conn = conexion.conexionBDD(1)
        #query = "select idCliente, nombreCliente as Nombre, nroIdentidicacionCliente as ID, direccionCliente as Direccion from clientes;"
        #query = "select idproducto, nombreProducto as Nombre, valorProducto as Valor, igvProducto as IGV from productos;"
        query = "Select idtipopago, descTipoPago as Descripcion from tipopago;"
        resConn = conn.consultarBDD(query)
        print("Escoja el codigo del tipo de pago que desea eliminar")
        print("\tcodigo\t\tTipo de Pago")
        for row in resConn:
            print(f"\t{str(row[0])}\t\t{str(row[1])}")

        codigotipopago = input()

        query = f"delete from tipopago where idtipopago = {codigotipopago} ;"
        resConn = conn.ejecutarBDD(query)
        if(resConn):
            print("Se ejecuto correctamente")
        else:
            print("Hubo un error")

        input("desea continuar???")

def mantenimento(resMenu):
    if resMenu == 1:
        log.debug("escogio 1")
        mantenimientoCliente()
    elif resMenu == 2:
        log.debug("escogio 2")
        mantenimientoProducto()
    elif resMenu == 3:
        log.debug("escogio 3")
        mantenimientoEmpresa()
    elif resMenu == 4:
        log.debug("escogio 4")
        mantenimientoTipoPago()
    else:
        log.debug(f"escogio {resMenu}")

stopMenuInicio = True
while stopMenuInicio:
    dicMenuInicio = {"\t- Crear Factura": 1, "\t- Mantenimientos": 2}
    menuInicio = utils.Menu("Menu Inicio", dicMenuInicio)
    resMenuInicio = menuInicio.mostrarMenu()
    if(resMenuInicio == 1):
        log.debug("Mostramos el Menu crear Factura")
        #cargarObjetos()
        crearFactura()
    elif(resMenuInicio == 2):
        log.debug("Mostramos los Mantenimientos")
        dicMenuMantenimiento = {"\t- Clientes": 1, "\t- Productos": 2,
                                "\t- Empresa": 3, "\t- Tipo de pago": 4}
        menuMantenimiento = utils.Menu(
            "Menu Mantenimiento", dicMenuMantenimiento)
        resMenuMantenimiento = menuMantenimiento.mostrarMenu()
        mantenimento(resMenuMantenimiento)
    elif(resMenuInicio == 9):
        log.debug("finalizar Programa")
    else:
        log.debug("volvemos a mostrar menu")
        stopMenuInicio = False


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 29 00:29:56 2018

@author: ari
"""

import time as tm
import csv as cv
import json as jsn
import os
import copy as cp

def process(line):
    coAuthList=[]
    authInList = []
    data = jsn.loads(line)
    try:
        t = data['authors']
    except KeyError:
        return

    for names_dict in t:
        coAuthList.append(names_dict['name'])
        if names_dict['name'] in hashAuth:
            authInList.append(names_dict['name'])

    if len(authInList)>0:
        temp = {}
        try:
            temp['id'] = data['id']
        except KeyError:
            return

        try:
            temp['title'] = data['title']
        except KeyError:
            temp['title'] = 'None'

        try:
            temp['venue'] = data['venue']
        except KeyError:
            temp['venue']='None'

        try:
            temp['year'] = data['year']
        except KeyError:
            temp['year']='None'

        try:
            temp['fos'] = data['fos']
        except KeyError:
            temp['fos'] = 'None'

        try:
            temp['references']=data['references']
        except KeyError:
            temp['references'] = 'None'

        try:
            temp['keywords'] = data['keywords']
        except KeyError:
            temp['keywords'] = 'None'

        try:
            temp['n_citation'] = data['n_citation']
        except KeyError:
            temp['n_citation'] = 'None'

        try:
            temp['lang'] = data['lang']
        except KeyError:
            temp['lang'] = 'None'

        try:
            temp['abstract'] = data['abstract']
        except KeyError:
            temp['abstract'] = 'None'

        try:
            temp['publisher'] = data['publisher']
        except KeyError:
            temp['publisher'] = 'None'

        for word in authInList:
           # prisnt(coAuthList)
            tempDict = cp.copy(temp)
            tempList = cp.copy(coAuthList)
            tempList.remove(word)
            tempDict['CoAuthors'] = cp.copy(tempList)
            if word in authData:
                authData[word].append(tempDict)
            else:
                authData[word] = []
                authData[word].append(tempDict)

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

hashAuth = {}
authData = {}
with open("get_authors.txt",'r') as f:
    index=0
    for line in f:
        hashAuth[line.replace('\n','')] = 'auth_'+str(index)
        index=index+1

tot_time = tm.time()
#for reading the mag_papers
for i in range(0,3):
    filename ="mag_papers_"+str(i)+'.txt'
    with open(filename,'r') as f:
        start_time = tm.time()
        print("Reading file "+ filename)
        for line in f:
            process(line)
        print("Reading completed in = "+str(tm.time()-start_time)+' sec')

#for reading the aminer papers
for i in range(1,2):
    filename ="/home/ari/Documents/Ambiguity-Project/Dataset/mag_papers/mag_papers_"+str(i)+'.txt'
    with open(filename,'r') as f:
        start_time = tm.time()
        print("Reading file "+ filename)
        for line in f:
            process(line)
        print("Reading completed in = "+str(tm.time()-start_time)+' sec')

print("Writing Data to CSV file")

with open("Author_Map.csv",'w') as csvfile:
    for key in hashAuth.keys():
        csvfile
        csvfile.write(key+','+hashAuth[key]+'\n')

#printing dictionary to the csv file
fieldnames = authData[key][0].keys()
for key in authData.keys():
    filename = hashAuth[key]+'.csv'
    with open(filename, 'w') as output_file:
        dict_writer = cv.DictWriter(output_file,fieldnames)
        dict_writer.writeheader()
        dict_writer.writerows(authData[key])

print("Writing complete to csv file")
print("Total time = " + str(tm.time()-tot_time))


from hashlib import md5
import logging
from django.core.files.base import ContentFile

logger = logging.getLogger("zentral.contrib.mdm.utils")

MD5_SIZE = 10 * 2**20  # 10MB

def get_md5s(package_file, md5_size=MD5_SIZE):
    file_chunk_size = 64 * 2**10  # 64KB
    md5_size = (md5_size // file_chunk_size) * file_chunk_size
    md5s = []
    h = md5()
    current_size = 0
    for chunk in package_file.chunks(chunk_size=file_chunk_size):
        h.update(chunk)
        current_size += len(chunk)
        if current_size == md5_size:
            md5s.append(h.hexdigest())
            h = md5()
            current_size = 0
    if current_size:
        md5s.append(h.hexdigest())
        if len(md5s) == 1:
            md5_size = current_size
    return md5_size, md5s

def build_manifest(title, package_file, pkg_refs):
    md5_size, md5s = get_md5s(package_file)
    asset = {"kind": "software-package",
             "md5-size": md5_size,
             "md5s": md5s}
    metadata = {"kind": "software", "title": title, "sizeInBytes": package_file.size}
    # we will add the url dynamically
    bundles = [{"bundle-identifier": pkg_ref["id"],
                "bundle-version": pkg_ref["version"]}
               for pkg_ref in pkg_refs]
    metadata.update(bundles.pop(0))
    if bundles:
        metadata["items"] = bundles
    return {"items": [{"assets": [asset], "metadata": metadata}]}

def build_mdm_enrollment_package(mep):
    builder = mep.get_builder_class()(mep.get_enrollment(), version=mep.version)
    _, pkg_refs, package_content = builder.build()
    package_file = ContentFile(package_content)
    mep.manifest = build_manifest(builder.name, package_file, pkg_refs)
    mep.file.delete(False)
    mep.file.save(mep.get_enrollment_package_filename(), package_file, save=True)


# Node class
#Time complexity O(n)
#Space complexity O(n) if you include the list, else O(1)
class Node:

    # Function to initialise the node object
    def __init__(self, data):
    	self.data = data
    	self.next = None

class LinkedList:

    def __init__(self):
        self.head = Node(0)
        self.end = self.head

    def push(self, new_data):
    	self.end.next = Node(new_data)
    	self.end = self.end.next

    # Function to get the middle of
    # the linked list
    def printMiddle(self):
    	p1 = p2 = self.head
    	while p2 and p2.next:
    		p1 = p1.next
    		p2 = p2.next.next
    	print(p1.data)

# Driver code
list1 = LinkedList()
list1.push(5)
list1.push(4)
list1.push(2)
list1.push(3)
list1.push(1)
list1.printMiddle()


import h5py as h5
import matplotlib.pyplot as plt
import numpy as np
import gvar as gv
import lsqfit as lsf
import math

class Prepare_data():
    def __init__(self, file_name, file_path, pt2_data_range, pt3_data_range):
        self.file_name = file_name
        self.file_path = file_path
        self.pt2_data_range = pt2_data_range
        self.pt3_data_range = pt3_data_range

    def rotate(self, lis, n): # used to rotate the list
        return lis[n:] + lis[:n]

    def find_key(self, part_of_file, name_of_key): # find the keys that named with specific string in the dictionary
        i = 0
        list_of_key = []
        for key in part_of_file:
            if name_of_key in key:
                list_of_key.append(key)
                i += 1

        if self.pt3_data_range[1] > 10:
            list_of_key = self.rotate(list_of_key, self.pt3_data_range[1]-10)

        return list_of_key

    def read_data_with_average(self):
        myfile = h5.File(self.file_path,'r')

        two_point_ml0p00951 = myfile['gf1p0_w3p5_n45_M51p1_L56_a1p5']['spec']['ml0p00951'] # different data file need different path here

        two_point_proton = np.array([two_point_ml0p00951['proton']['px0_py0_pz0']['spin_dn'][:],
        two_point_ml0p00951['proton']['px0_py0_pz0']['spin_up'][:]])
        two_point_proton_np = np.array([two_point_ml0p00951['proton_np']['px0_py0_pz0']['spin_dn'][:],
        two_point_ml0p00951['proton_np']['px0_py0_pz0']['spin_up'][:]])

        two_point_data = (two_point_proton[0] + two_point_proton[1] + two_point_proton_np[0] + two_point_proton_np[1])/4
        two_point_data = np.squeeze(two_point_data)

        three_point_ml0p00951 = myfile['gf1p0_w3p5_n45_M51p1_L56_a1p5']['formfac']['ml0p00951']

        proton_DD_dn_dn = self.find_key(three_point_ml0p00951, 'proton_DD_dn_dn')
        proton_DD_up_up = self.find_key(three_point_ml0p00951, 'proton_DD_up_up')
        proton_np_DD_dn_dn = self.find_key(three_point_ml0p00951, 'proton_np_DD_dn_dn')
        proton_np_DD_up_up = self.find_key(three_point_ml0p00951, 'proton_np_DD_up_up')

        proton_UU_dn_dn = self.find_key(three_point_ml0p00951, 'proton_UU_dn_dn')
        proton_UU_up_up = self.find_key(three_point_ml0p00951, 'proton_UU_up_up')
        proton_np_UU_dn_dn = self.find_key(three_point_ml0p00951, 'proton_np_UU_dn_dn')
        proton_np_UU_up_up = self.find_key(three_point_ml0p00951, 'proton_np_UU_up_up')

        data_dict = {}

        start = 0 ### used to adjust stat range for half stat
        end = 784

        #temp = two_point_data[::2]

        for i in range(len(two_point_data[0])):
            data_dict['pt2_tsep_' + str(i)] = two_point_data[start:end, i, 0] # 2pt ss data
            #data_dict['pt2_tsep_' + str(i)] = temp[:, i, 0]
            ## shape = (784,)

        pro_up = {}
        pro_dn = {}
        pnp_dn = {}
        pnp_up = {}

        for i in range(self.pt3_data_range[0], self.pt3_data_range[1]): # average
            for key in ['A3', 'V4']:
                pro_up[key] = three_point_ml0p00951[proton_UU_up_up[i-self.pt3_data_range[0]]][key]['px0_py0_pz0']['local_curr'][start:end] - three_point_ml0p00951[proton_DD_up_up[i-self.pt3_data_range[0]]][key]['px0_py0_pz0']['local_curr'][start:end]

                pro_dn[key] = three_point_ml0p00951[proton_UU_dn_dn[i-self.pt3_data_range[0]]][key]['px0_py0_pz0']['local_curr'][start:end] - three_point_ml0p00951[proton_DD_dn_dn[i-self.pt3_data_range[0]]][key]['px0_py0_pz0']['local_curr'][start:end]

                pnp_dn[key] = three_point_ml0p00951[proton_np_UU_dn_dn[i-self.pt3_data_range[0]]][key]['px0_py0_pz0']['local_curr'][start:end] - three_point_ml0p00951[proton_np_DD_dn_dn[i-self.pt3_data_range[0]]][key]['px0_py0_pz0']['local_curr'][start:end]

                pnp_up[key] = three_point_ml0p00951[proton_np_UU_up_up[i-self.pt3_data_range[0]]][key]['px0_py0_pz0']['local_curr'][start:end] - three_point_ml0p00951[proton_np_DD_up_up[i-self.pt3_data_range[0]]][key]['px0_py0_pz0']['local_curr'][start:end]

            data_dict['pt3_A3_tsep_' + str(i)] = ( np.imag(pro_up['A3']) - np.imag(pro_dn['A3']) + np.imag(pnp_dn['A3']) - np.imag(pnp_up['A3']) )/4

            data_dict['pt3_V4_tsep_' + str(i)] = ( np.real(pro_up['V4']) + np.real(pro_dn['V4']) - np.real(pnp_dn['V4']) - np.real(pnp_up['V4']) )/4

            ## shape = (784, tsep+1)

        print(np.shape(data_dict['pt2_tsep_1']))
        print(np.shape(data_dict['pt3_A3_tsep_3']))

        data_avg_dict = gv.dataset.avg_data(data_dict)

        return data_avg_dict

    def add_sum_data(self, data_avg_dict, sum_tau_cut):
        for i in range(self.pt3_data_range[0], self.pt3_data_range[1]):
            data_avg_dict['sum_A3_tsep_' + str(i)] = gv.gvar(0, 0)
            data_avg_dict['sum_V4_tsep_' + str(i)] = gv.gvar(0, 0)

            for j in range(sum_tau_cut, i-sum_tau_cut+1): # do the summation
                data_avg_dict['sum_A3_tsep_' + str(i)] += data_avg_dict['pt3_A3_tsep_' + str(i)][j]
                data_avg_dict['sum_V4_tsep_' + str(i)] += data_avg_dict['pt3_V4_tsep_' + str(i)][j]

        for i in range(self.pt3_data_range[0], self.pt3_data_range[1]-1): # use ratio form to do the fit
            # fit_14 will use tsep_15 here, so the tsep range of sum part should not be bigger than 13
            data_avg_dict['sum_A3_fit_'+str(i)] = (data_avg_dict['sum_A3_tsep_' + str(i+1)]/data_avg_dict['pt2_tsep_'+str(i+1)]) - (data_avg_dict['sum_A3_tsep_' + str(i)]/data_avg_dict['pt2_tsep_'+str(i)])

            data_avg_dict['sum_V4_fit_'+str(i)] = (data_avg_dict['sum_V4_tsep_' + str(i+1)]/data_avg_dict['pt2_tsep_'+str(i+1)]) - (data_avg_dict['sum_V4_tsep_' + str(i)]/data_avg_dict['pt2_tsep_'+str(i)])

        return data_avg_dict


import random

import pygame

FPS = 30
DEFAULT_SPEED = 4
IN_GAME = True
RECT_SIZE = 25
CAR_W = (RECT_SIZE + 4) * 3
CAR_H = (RECT_SIZE + 4) * 4
BG = (180, 195, 180)
ORANGE = (255, 150, 100)
W = 4 + (RECT_SIZE + 4) * 11
block = None
pygame.init()

pygame.font.init()
myfont = pygame.font.SysFont('Comic Sans MS', 30)

clock = pygame.time.Clock()

sc = pygame.display.set_mode((W, 0))

sc_w, sc_h = sc.get_rect()[2:4]
if sc_h / 2 > W:
    sc = pygame.display.set_mode((W, W * 2))
    sc_w, sc_h = sc.get_rect()[2:4]

class Rect:
    global sc
    color = (0, 0, 0)

    def __init__(self, x, y):
        self.move(x, y)

    def move(self, x, y):
        self.x = x
        self.y = y
        self.x1 = x
        self.x2 = x + 5
        self.y1 = y
        self.y2 = y + 5
        self.coords1 = (self.x1, self.y1, RECT_SIZE, RECT_SIZE)
        self.coords2 = (self.x2, self.y2, int(RECT_SIZE - 9), int(RECT_SIZE - 9))

    def draw(self):
        global sc
        pygame.draw.rect(sc, self.color,
                         self.coords1, 2)
        pygame.draw.rect(sc, self.color,
                         self.coords2)

blocks = []

k = 0
class Block:
    # 0: куб, 1:т, 2:г, 3:левая z, 4:правая z, 5:прямая, 6:обратная г
    def __init__(self, x, y):
        self.block_type = random.randint(0, 6)
        self.rotate = 0
        self.move(x, y)

    def draw(self):
        for i in self.__dict__.values():
            if isinstance(i, Rect):
                i.draw()

    def move(self, x, y):
        self.x = x
        self.y = y
        if self.block_type == 0:
            self.x2 = x + (RECT_SIZE) * 2
            self.y2 = y + (RECT_SIZE) * 2
            self.w = self.x2 - self.x
            self.h = self.y2 - self.y
            self._lt = Rect(x, y)
            self._rt = Rect(x + RECT_SIZE, y)
            self._lb = Rect(x, y + RECT_SIZE)
            self._rb = Rect(x + RECT_SIZE, y + RECT_SIZE)
        elif self.block_type == 1:
            self.x2 = x + (RECT_SIZE) * 3
            self.y2 = y + (RECT_SIZE) * 2
            self.w = self.x2 - self.x
            self.h = self.y2 - self.y
            self._t = Rect(x + RECT_SIZE, y)
            self._lb = Rect(x, y+ RECT_SIZE)
            self._mb = Rect(x + RECT_SIZE, y + RECT_SIZE)
            self._rb = Rect(x + RECT_SIZE * 2, y + RECT_SIZE)
        elif self.block_type == 2:
            self.x2 = x + (RECT_SIZE) * 3
            self.y2 = y + (RECT_SIZE) * 2
            self.w = self.x2 - self.x
            self.h = self.y2 - self.y
            self._t = Rect(x + RECT_SIZE * 2, y)
            self._lb = Rect(x, y+ RECT_SIZE)
            self._mb = Rect(x + RECT_SIZE, y + RECT_SIZE)
            self._rb = Rect(x + RECT_SIZE * 2, y + RECT_SIZE)
        elif self.block_type == 6:
            self.x2 = x + (RECT_SIZE) * 3
            self.y2 = y + (RECT_SIZE) * 2
            self.w = self.x2 - self.x
            self.h = self.y2 - self.y
            self._t = Rect(x, y)
            self._lb = Rect(x , y+ RECT_SIZE)
            self._mb = Rect(x + RECT_SIZE, y + RECT_SIZE)
            self._rb = Rect(x + RECT_SIZE * 2, y + RECT_SIZE)
        elif self.block_type == 3:
            self.x2 = x + (RECT_SIZE) * 3
            self.y2 = y + (RECT_SIZE) * 2
            self.w = self.x2 - self.x
            self.h = self.y2 - self.y
            self._lt = Rect(x, y)
            self._mt = Rect(x + RECT_SIZE, y)
            self._mb = Rect(x + RECT_SIZE, y + RECT_SIZE)
            self._rb = Rect(x + RECT_SIZE * 2, y + RECT_SIZE)
        elif self.block_type == 4:
            self.x2 = x + (RECT_SIZE) * 3
            self.y2 = y + (RECT_SIZE) * 2
            self.w = self.x2 - self.x
            self.h = self.y2 - self.y
            self._mt = Rect(x + RECT_SIZE, y)
            self._rt = Rect(x + RECT_SIZE * 2, y)
            self._lb = Rect(x, y + RECT_SIZE)
            self._mb = Rect(x + RECT_SIZE, y + RECT_SIZE)
        elif self.block_type == 5:
            self.x2 = x + (RECT_SIZE) * 4
            self.y2 = y + (RECT_SIZE) * 1
            self.w = self.x2 - self.x
            self.h = self.y2 - self.y
            self._lt = Rect(x, y)
            self._lmt = Rect(x + RECT_SIZE, y)
            self._rmt = Rect(x + RECT_SIZE * 2, y)
            self._rt = Rect(x + RECT_SIZE * 3, y)
        self.draw()

    def __eq__(self, other):
        global block
        if (self.y <= other.y <= self.y2 and self.x <= other.x < self.x2) or (self.y <= other.y2 <= self.y2 and
                                                                              self.x < other.x2 <= self.x2):
            # Более сложная логика размещения
            y = other.y-1
            block.move(block.x,y-block.h)
            block = None
            blocks.append(self)

start_pos = sc_w / 2 - RECT_SIZE * 2

iter = 0
motion = 'stop'
IN_GAME = True
SPEED = DEFAULT_SPEED

while IN_GAME:
    iter += 1
    if iter > 800:
        iter = 0
    sc.fill(BG)
    for i in pygame.event.get():
        try:
            if i.type == pygame.QUIT:
                exit()
            elif i.type == pygame.KEYDOWN:
                if i.key == pygame.K_LEFT:
                    motion = 'left'
                elif i.key == pygame.K_RIGHT:
                    motion = 'right'
                elif i.key == pygame.K_DOWN:
                    motion = 'speed'
            elif i.type == pygame.KEYUP:
                if i.key in [pygame.K_LEFT, pygame.K_RIGHT, pygame.K_DOWN]:
                    motion = 'stop'
            elif i.type == pygame.FINGERDOWN:
                if i.x < 0.5:
                    print(i.x)
                    motion = 'left'
                else:
                    motion = 'right'
            elif i.type == pygame.FINGERUP:
                motion = 'stop'
        except AttributeError:
            pass
    if block:
        if motion == 'left' and block.x-RECT_SIZE>=0:
            block.move(block.x-RECT_SIZE,block.y)
        elif motion == 'right' and block.x2+RECT_SIZE<=sc_w:
            block.move(block.x+RECT_SIZE,block.y)
        elif motion == 'speed':
            SPEED = DEFAULT_SPEED + 10
        elif motion == 'stop':
            SPEED = DEFAULT_SPEED
    if block is None:
        block = Block(start_pos, -RECT_SIZE * 2)
    elif block.y2 < sc_h:
        block.move(block.x, block.y + SPEED)
    if block.y2 > sc_h:
        block.move(block.x, sc_h-block.h)
        blocks.append(block)
        block = None
    for i in blocks:
        if block:
            block == i
        i.draw()
    pygame.display.update()
    if pygame.get_error():
        pass
        # print(pygame.get_error())
    clock.tick(FPS)
textsurface = myfont.render('Game Over', False, (255, 0, 0))
sc.blit(textsurface, (sc_w / 4, sc_h / 2))
pygame.display.update()
while 1:
    for i in pygame.event.get():
        if i.type == pygame.QUIT:
            exit()


from django.conf.urls import url, include

from transaction import views

urlpatterns = [
    url(r'^$', views.index, name='transaction.index'),
    url(r'^punchin/(?P<car_id>[0-9a-zA-Z]+)/$', views.punchin, name='transaction.punchin'),
    url(r'^punchin/(?P<car_id>[0-9a-zA-Z]+)/property/(?P<property_id>[0-9]+)/$', views.punchin, name='transaction.punchin'),
    url(r'^punchout/(?P<car_id>[0-9a-zA-Z]+)/$', views.punchout, name='transaction.punchout'),
    url(r'^(?P<recipt_id>[0-9]+)/$', views.recipt, name='transaction.recipt'),
    url(r'^payment/(?P<recipt_id>[0-9]+)/(?P<method>[0-9]+)/$', views.payment_method, name='transaction.payment'),
    url(r'^payment/(?P<recipt_id>[0-9]+)/$', views.payment_method, name='transaction.payment'),
]


# pylint: disable=not-callable, no-member, invalid-name, line-too-long, wildcard-import, unused-wildcard-import, missing-docstring
import math
import unittest
from functools import partial

import torch

from e3nn import o3, rs

class Tests(unittest.TestCase):

    def test_decomposition_spherical_harmonics(self):
        with o3.torch_default_dtype(torch.float64):
            lmax = 4
            beta = torch.linspace(1e-3, math.pi - 1e-3, 100).view(1, -1)
            alpha = torch.linspace(0, 2 * math.pi, 100).view(-1, 1)
            Y1 = o3.spherical_harmonics_alpha_part(lmax, alpha) * o3.spherical_harmonics_beta_part(lmax, beta.cos())
            Y2 = o3.spherical_harmonics([l for l in range(lmax + 1)], alpha, beta)
            Y2 = torch.einsum('lmi,iab->lmab', o3.spherical_harmonics_expand_matrix(lmax), Y2)
            self.assertLess((Y1 - Y2).abs().max(), 1e-10)

    def test_sh_is_in_irrep(self):
        with o3.torch_default_dtype(torch.float64):
            for l in range(4 + 1):
                a, b = 3.14 * torch.rand(2)  # works only for beta in [0, pi]
                Y = o3.spherical_harmonics(l, a, b) * math.sqrt(4 * math.pi) / math.sqrt(2 * l + 1) * (-1) ** l
                D = o3.irr_repr(l, a, b, 0)
                self.assertLess((Y - D[:, l]).norm(), 1e-10)

    def test_sh_cuda_single(self):
        if torch.cuda.is_available():
            with o3.torch_default_dtype(torch.float64):
                for l in range(10 + 1):
                    x = torch.randn(10, 3)
                    x_cuda = x.cuda()
                    Y1 = o3.spherical_harmonics_xyz(l, x)
                    Y2 = o3.spherical_harmonics_xyz(l, x_cuda).cpu()
                    self.assertLess((Y1 - Y2).abs().max(), 1e-7)
        else:
            print("Cuda is not available! test_sh_cuda_single skipped!")

    def test_sh_cuda_ordered_full(self):
        if torch.cuda.is_available():
            with o3.torch_default_dtype(torch.float64):
                l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
                x = torch.randn(10, 3)
                x_cuda = x.cuda()
                Y1 = o3.spherical_harmonics_xyz(l, x)
                Y2 = o3.spherical_harmonics_xyz(l, x_cuda).cpu()
                self.assertLess((Y1 - Y2).abs().max(), 1e-7)
        else:
            print("Cuda is not available! test_sh_cuda_ordered_full skipped!")

    def test_sh_cuda_ordered_partial(self):
        if torch.cuda.is_available():
            with o3.torch_default_dtype(torch.float64):
                l = [0, 2, 5, 7, 10]
                x = torch.randn(10, 3)
                x_cuda = x.cuda()
                Y1 = o3.spherical_harmonics_xyz(l, x)
                Y2 = o3.spherical_harmonics_xyz(l, x_cuda).cpu()
                self.assertLess((Y1 - Y2).abs().max(), 1e-7)
        else:
            print("Cuda is not available! test_sh_cuda_ordered_partial skipped!")

    def test_sh_parity(self):
        """
        (-1)^l Y(x) = Y(-x)
        """
        with o3.torch_default_dtype(torch.float64):
            for l in range(7 + 1):
                x = torch.randn(3)
                Y1 = (-1) ** l * o3.spherical_harmonics_xyz(l, x)
                Y2 = o3.spherical_harmonics_xyz(l, -x)
                self.assertLess((Y1 - Y2).abs().max(), 1e-10 * Y1.abs().max())

    def test_sh_dirac(self):
        with o3.torch_default_dtype(torch.float64):
            for l in range(5):
                a = o3.spherical_harmonics_dirac(l, 1.2, 2.1)
                a = o3.spherical_harmonics_coeff_to_sphere(a, 1.2, 2.1)
                self.assertAlmostEqual(a.item(), 1)

    def test_sh_norm(self):
        with o3.torch_default_dtype(torch.float64):
            l_filter = list(range(15))
            Ys = [o3.spherical_harmonics_xyz(l, torch.randn(10, 3)) for l in l_filter]
            s = torch.stack([Y.pow(2).mean(0) for Y in Ys])
            d = s - 1 / (4 * math.pi)
            self.assertLess(d.pow(2).mean().sqrt(), 1e-10)

    def test_sh_closure(self):
        """
        integral of Ylm * Yjn = delta_lj delta_mn
        integral of 1 over the unit sphere = 4 pi
        """
        with o3.torch_default_dtype(torch.float64):
            x = torch.randn(200000, 3)
            Ys = [o3.spherical_harmonics_xyz(l, x) for l in range(0, 3 + 1)]
            for l1, Y1 in enumerate(Ys):
                for l2, Y2 in enumerate(Ys):
                    m = (Y1.view(2 * l1 + 1, 1, -1) * Y2.view(1, 2 * l2 + 1, -1)).mean(-1) * (4 * math.pi)
                    if l1 == l2:
                        i = torch.eye(2 * l1 + 1)
                        self.assertLess((m - i).pow(2).max(), 1e-4)
                    else:
                        self.assertLess(m.pow(2).max(), 1e-4)

    def test_clebsch_gordan_orthogonal(self):
        with o3.torch_default_dtype(torch.float64):
            for l_out in range(3 + 1):
                for l_in in range(l_out, 4 + 1):
                    for l_f in range(abs(l_out - l_in), l_out + l_in + 1):
                        Q = o3.clebsch_gordan(l_f, l_in, l_out).reshape(2 * l_f + 1, -1)
                        e = (2 * l_f + 1) * Q @ Q.t()
                        d = e - torch.eye(2 * l_f + 1)
                        self.assertLess(d.pow(2).mean().sqrt(), 1e-10)

    def test_clebsch_gordan_sh_norm(self):
        with o3.torch_default_dtype(torch.float64):
            for l_out in range(3 + 1):
                for l_in in range(l_out, 4 + 1):
                    for l_f in range(abs(l_out - l_in), l_out + l_in + 1):
                        Q = o3.clebsch_gordan(l_out, l_in, l_f)
                        Y = o3.spherical_harmonics_xyz(l_f, torch.randn(1, 3)).view(2 * l_f + 1)
                        QY = math.sqrt(4 * math.pi) * Q @ Y
                        self.assertLess(abs(QY.norm() - 1), 1e-10)

    def test_rot_to_abc(self):
        with o3.torch_default_dtype(torch.float64):
            R = o3.rand_rot()
            abc = o3.rot_to_abc(R)
            R2 = o3.rot(*abc)
            d = (R - R2).norm() / R.norm()
            self.assertTrue(d < 1e-10, d)

    def test_wignerd(self):
        for l__ in range(7):
            self._test_is_representation(partial(o3.irr_repr, l__))

    def _test_is_representation(self, R):
        """
        R(Z(a1) Y(b1) Z(c1) Z(a2) Y(b2) Z(c2)) = R(Z(a1) Y(b1) Z(c1)) R(Z(a2) Y(b2) Z(c2))
        """
        with o3.torch_default_dtype(torch.float64):
            a1, b1, c1, a2, b2, c2 = torch.rand(6)

            r1 = R(a1, b1, c1)
            r2 = R(a2, b2, c2)

            a, b, c = o3.compose(a1, b1, c1, a2, b2, c2)
            r = R(a, b, c)

            r_ = r1 @ r2

            self.assertLess((r - r_).abs().max(), 1e-10 * r.abs().max())

    def test_spherical_harmonics(self):
        """
        This test tests that
        - irr_repr
        - compose
        - spherical_harmonics
        are compatible

        Y(Z(alpha) Y(beta) Z(gamma) x) = D(alpha, beta, gamma) Y(x)
        with x = Z(a) Y(b) eta
        """
        for order in range(7):
            with o3.torch_default_dtype(torch.float64):
                a, b = torch.rand(2)
                alpha, beta, gamma = torch.rand(3)

                ra, rb, _ = o3.compose(alpha, beta, gamma, a, b, 0)
                Yrx = o3.spherical_harmonics(order, ra, rb)

                Y = o3.spherical_harmonics(order, a, b)
                DrY = o3.irr_repr(order, alpha, beta, gamma) @ Y

                self.assertLess((Yrx - DrY).abs().max(), 1e-10 * Y.abs().max())

    def test_xyz_vector_basis_to_spherical_basis(self, ):
        with o3.torch_default_dtype(torch.float64):
            A = o3.xyz_vector_basis_to_spherical_basis()

            a, b, c = torch.rand(3)

            r1 = A.t() @ o3.irr_repr(1, a, b, c) @ A
            r2 = o3.rot(a, b, c)

            self.assertLess((r1 - r2).abs().max(), 1e-10)

    def test_conventionRs(self):
        Rs = [(1, 0)]
        Rs_out = rs.convention(Rs)
        self.assertSequenceEqual(Rs_out, [(1, 0, 0)])
        Rs = [(1, 0), (2, 0)]
        Rs_out = rs.convention(Rs)
        self.assertSequenceEqual(Rs_out, [(1, 0, 0), (2, 0, 0)])

    def test_simplifyRs(self):
        Rs = [(1, 0), (2, 0)]
        Rs_out = rs.simplify(Rs)
        self.assertSequenceEqual(Rs_out, [(3, 0, 0)])

    def test_irrep_dimRs(self):
        Rs = [(1, 0), (3, 1), (2, 2)]
        self.assertTrue(rs.irrep_dim(Rs) == 1 + 3 + 5)
        Rs = [(1, 0), (3, 0), (2, 0)]
        self.assertTrue(rs.irrep_dim(Rs) == 1 + 1 + 1)

    def test_mul_dimRs(self):
        Rs = [(1, 0), (3, 1), (2, 2)]
        self.assertTrue(rs.mul_dim(Rs) == 6)
        Rs = [(1, 0), (3, 0), (2, 0)]
        self.assertTrue(rs.mul_dim(Rs) == 6)

    def test_dimRs(self):
        Rs = [(1, 0), (3, 1), (2, 2)]
        self.assertTrue(rs.dim(Rs) == 1 * 1 + 3 * 3 + 2 * 5)
        Rs = [(1, 0), (3, 0), (2, 0)]
        self.assertTrue(rs.dim(Rs) == 1 * 1 + 3 * 1 + 2 * 1)

    def test_map_irrep_to_Rs(self):
        with o3.torch_default_dtype(torch.float64):
            Rs = [(3, 0)]
            mapping_matrix = rs.map_irrep_to_Rs(Rs)
            self.assertTrue(torch.allclose(mapping_matrix, torch.ones(3, 1)))

            Rs = [(1, 0), (1, 1), (1, 2)]
            mapping_matrix = rs.map_irrep_to_Rs(Rs)
            self.assertTrue(torch.allclose(mapping_matrix, torch.eye(1 + 3 + 5)))

    def test_map_mul_to_Rs(self):
        with o3.torch_default_dtype(torch.float64):
            Rs = [(3, 0)]
            mapping_matrix = rs.map_mul_to_Rs(Rs)
            self.assertTrue(torch.allclose(mapping_matrix, torch.eye(3)))

            Rs = [(1, 0), (1, 1), (1, 2)]
            mapping_matrix = rs.map_mul_to_Rs(Rs)
            check_matrix = torch.zeros(1 + 3 + 5, 3)
            check_matrix[0, 0] = 1.
            check_matrix[1:4, 1] = 1.
            check_matrix[4:, 2] = 1.
            self.assertTrue(torch.allclose(mapping_matrix, check_matrix))

if __name__ == '__main__':
    unittest.main()


"""owdr URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from owdr_app.views import LandingPage, Login, Register, AddDonation, Logout, UserView, IsTaken, EditUser

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', LandingPage.as_view()),
    path('login/', Login.as_view()),
    path('register/', Register.as_view()),
    path('add-donation/', AddDonation.as_view()),
    path('logout/', Logout.as_view()),
    path('user/', UserView.as_view()),
    path('user/is-taken/<int:pk>/', IsTaken.as_view()),
    path('user/edit/', EditUser.as_view()),

]


# uncompyle6 version 3.7.4
# Python bytecode 3.8 (3413)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build\bdist.win32\egg\shaonutil\math.py
# Compiled at: 2020-04-12 12:08:25
# Size of source mod 2**32: 209 bytes
"""Math"""

def calculate_distance(p1, p2):
    """Calculate Distance between two points p1=[x1,y1],p2=[x2,y2]"""
    x1, y1 = p1
    x2, y2 = p2
    distance = ((y1 - y2) ** 2 + (x1 - x2) ** 2) ** 0.5
    return distance


#! /usr/bin/env python

# a red background

import pygame

# setting screen size
screen = pygame.display.set_mode((640,400))
# keep out programm running
running = 1

# the main event loop
while running:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
           running = 0                 # jump out the main event loop and quit

    screen.fill((255, 0, 0))
    pygame.display.flip()


from pyhocon import ConfigFactory
import os.path as osp
from dea_ml.config.product_feature_config import FeaturePathConfig
from odc.stats.model import OutputProduct, DateTimeRange

def parse_config(default: str = None) -> FeaturePathConfig:
    """
    parse the hocon type of config
    :param default: config file path
    :return: parsed data class
    """
    cwd = osp.dirname(__file__)
    config_file_path = default

    if not default:
        config_file_path = osp.join(cwd, "product_feature_paths.config")
    config = ConfigFactory.parse_file(config_file_path)

    prd_properties = dict(config.get("prd_properties").as_plain_ordered_dict())
    product_fields = config.get("product_fields").as_plain_ordered_dict()
    product_fields["properties"] = prd_properties

    output_product = OutputProduct(**product_fields)

    FPConfig = FeaturePathConfig()
    FPConfig.PRODUCT_VERSION = config.get("PRODUCT_VERSION")
    FPConfig.PRODUCT_NAME = config.get("PRODUCT_NAME")
    FPConfig.DATA_PATH = config.get("PATH.DATA_PATH")
    FPConfig.REMOTE_PATH = config.get("PATH.REMOTE_PATH")
    FPConfig.TIF_path = config.get("PATH.TIF_path")
    FPConfig.model_path = config.get("PATH.model_path")
    FPConfig.tiles_geojson = config.get("PATH.tiles_geojson")
    FPConfig.rename_dict = config.get("bands.rename_dict")
    FPConfig.url_slope = config.get("PATH.url_slope")
    FPConfig.rainfall_path = config.get("PATH.rainfall_path").as_plain_ordered_dict()
    FPConfig.training_features = config.get("training_features")
    FPConfig.resolution = config.get("resolution")
    FPConfig.time = config.get("time")
    FPConfig.datetime_range = DateTimeRange(config.get("datetime_range"))
    FPConfig.output_crs = config.get("output_crs")
    FPConfig.query = config.get("query").as_plain_ordered_dict()
    FPConfig.product = output_product

    return FPConfig


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('pconspectus', '0003_auto_20150213_2004'),
    ]

    operations = [
        migrations.RenameField(
            model_name='book',
            old_name='title',
            new_name='title_first',
        ),
        migrations.AddField(
            model_name='book',
            name='title_second',
            field=models.CharField(choices=[('Dr.', 'Dr.'), ('Mrs.', 'Mrs.'), ('Miss.', 'Miss.'), ('Mr.', 'Mr.')], max_length=50, default='Mrs'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='book',
            name='title_third',
            field=models.CharField(choices=[('Dr.', 'Dr.'), ('Mrs.', 'Mrs.'), ('Miss.', 'Miss.'), ('Mr.', 'Mr.')], max_length=50, default='Mrs'),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='book',
            name='publication_year',
            field=models.IntegerField(blank=True),
            preserve_default=True,
        ),
    ]


import sublime, sublime_plugin
import os,subprocess

import gautoy

DEFAULT_LOG_PATH = None

#class TraceclientSearchCommand(sublime_plugin.WindowCommand):
class TraceclientSearchCommand(sublime_plugin.WindowCommand):
   search_in_progress = False

   def run(self):
      #print(gautoy.core.config.get_option("log.message_fields"))
      #return
      if self.search_in_progress:
         sublime.status_message
         sublime.error_message('TraceClient search in progress. Please wait...')
      else:
         sublime.set_timeout_async(self.log_findall_utility_search, 0)

   def register_output_view(self, panel_name = 'traceclient_search'):
      if not hasattr(self, 'output_view'):
         self.output_view = self.window.get_output_panel(panel_name)
      self.window.run_command("show_panel", {"panel": "output." + panel_name})
      return self.output_view

   def log_findall_utility_search(self):
      self.search_in_progress = True # Freez any actions

      view = self.window.active_view()
      if not hasattr(self, 'output_view'):
         self.output_view = self.window.get_output_panel('traceclient_search')
         self.output_view.set_syntax_file("Packages/C++/C++.tmLanguage")#("Packages/Graphviz/DOT.tmLanguage")("Packages/Batch File/Batch File.tmLanguage")
         self.output_view.settings().set("rulers", [200])
         self.window.run_command("show_panel", {"panel": "output." + 'traceclient_search'})

      patterns = []
      for region in view.sel():
         pat = view.substr(region)
         if len(pat) > 0:
            patterns.append(pat)
            print(patterns)
            #linesRegions.extend(view.lines(region))

      if len(patterns) > 0:
         findall_utility_folder = "C:\\Users\\sgogolenko\\AppData\\Roaming\\Sublime Text 2\\Packages\\Gautoy"
         #gautoy.core.config.get_option("log.findall_utility.folder")
         args = ['python', os.path.join(findall_utility_folder, 'traceclient_findall.py')]

         args.extend(patterns)
         print(args)
         matches = subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0].decode("utf-8")

         self.output_view.run_command('insert_text_to_log_search_output', {'matches': matches})
         sublime.status_message("Found {0} pattern matches in TraceClient".format(matches.count('\n')))

      self.search_in_progress = False # unfreez any actions

class InsertTextToLogSearchOutputCommand(sublime_plugin.TextCommand):
   def message(self, edit, text = ''):
      print(text)
      self.view.insert(edit, self.view.size(), text + '\n')

   def run(self, edit, matches = ''):
      self.view.set_read_only(False)
      print(matches)
      if len(matches) > 0:
         self.message(edit, r'Found {0} matches:'.format(matches.count('\n')))
         self.message(edit, matches)  #startupinfo=startupinfo
      else:
         self.message(edit, 'Found no matches.')
      self.view.set_read_only(True)

import sublime, sublime_plugin, functools
class IdleWatcher(sublime_plugin.EventListener):
   pending = 0
   def handleTimeout(self, view):
      self.pending = self.pending - 1
      if self.pending == 0:
         self.on_idle(view)

   def on_modified(self, view):
      self.pending += 1
      # Ask for handleTimeout to be called in 1000ms
      sublime.set_timeout(functools.partial(self.handleTimeout, view), 1000)

   def on_idle(self, view):
      pass #print("No activity in the past 1000ms")


import os

import matplotlib.pyplot as plt

def parse_jastrow_file(path):
    with open(path,'r') as f:
        thelines = f.readlines()

    jastsize = len(thelines)
    jast_array = np.empty((jastsize,4))
    counter = 0
    for line in thelines:
        line = line.split()
        for n in range(4):
            jast_array[counter][n]=float(line[n])
        counter+=1

    return jast_array

if __name__=='__main__':

    with open('analyze2.out','r') as f:
        thelines=f.readlines()

spacings=[]
energies=[]
plusminus=[]

N=len(thelines)
for line in thelines:
    if 'a=' in line:
        spacings.append(float(line.split('=')[1]))
    else:
        energies.append(float(line.split()[3]))
        plusminus.append(float(line.split()[5]))

with open('analyze3.out','w') as f:

    for n in range(len(spacings)):
        thestr=str(spacings[n])+','+str(energies[n])+','+str(plusminus[n])+'\n'
        f.write(thestr)


from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.CoursesView.as_view(), name="courses"),
    url(r'^(?P<course_id>[0-9]+)/$',
        views.CourseView.as_view(),
        name="Course"),
    url(
        r'^(?P<course_id>[0-9]+)/(?P<lesson_id>[0-9]+)/$',
        views.LessonView.as_view(),
        name="Lesson"
    ),
    url(
        r'^(?P<course_id>[0-9]+)/(?P<lesson_id>[0-9]+)/quiz/$',
        views.QuizView.as_view(),
        name="Quiz"
    ),
]


import random

from combat import Combat

COLORS = ['yellow', 'red', 'blue', 'green']

class Monster(Combat):
  min_hit_points = 1
  max_hit_points = 1
  min_experiance = 1
  max_experiance = 1
  weapon = 'sword'
  sound = 'roar'

  def __init__(self, **kwargs):
    self.hit_points = random.randint(self.min_hit_points, self.max_hit_points)
    self.experiance = random.randint(self.min_experiance, self.max_experiance)
    self.color = random.choice(COLORS)

    for key, value in kwargs.items():
      setattr(self, key, value)

  def __str__(self):
    return '{} {}, HP: {}, XP: {}'.format(self.color.title(),
                                          self.__class__.__name__,
                                          self.hit_points,
                                          self.experiance)

  def battlecry(self):
              return self.sound.upper()

class Goblin(Monster):
  max_hit_points = 3
  max_experiance = 2
  sound = 'squeak'

class Troll(Monster):
  min_hit_points = 3
  max_hit_points = 5
  min_experiance = 2
  max_experiance = 6
  sound = 'growl'

class Dragon(Monster):
  min_hit_points= 5
  max_hit_points = 10
  min_experiance = 6
  max_experiance = 10
  sound = 'raaaaaaaaaaaar'

PythonPrograms/Python Monster Game- OOP/monster.py


import numpy as np
import matplotlib.pyplot as plt
from graphviz import Digraph

sample_state = np.array([[1,0], [0,1], [0,0], [0,0], [0,0]
                         , [0,0], [0,0], [0,0], [0,0]], dtype = int)
sample_cand_edges = np.array(
[
    [[0,1], [2,3], [1,4], [3,3], [4,5], [5,6], [7,8], [6,0], [8,2]],
    [[0,1], [2,3], [1,4], [3,3], [4,7], [5,6], [7,8], [6,0], [8,2]],
    [[0,1], [2,3], [1,1], [3,4], [4,5], [5,6], [7,8], [6,0], [8,2]],
    [[0,1], [2,3], [1,1], [3,4], [4,7], [5,6], [7,8], [6,0], [8,2]]
], dtype=int)

def edges2matrix(n_node, edges):
    N = n_node
    mat = np.zeros([N,N], dtype=int)
    mat[edges[:,1], edges[:,0]] = 1
    return mat

def block(route, state):
    N, _     = state.shape
    isfilled = np.sum(state, axis=1) > 0
    isstop   = np.sum(route[isfilled], axis=0) > 0
    croute   = np.copy(route)
    croute[:, isstop] = np.eye(N, dtype=np.int)[:, isstop]
    return croute

class Simulator:
    def setup_sample_network(self):
        N, M = sample_state.shape
        self.n_node = N
        self.n_spec = M
        self.edges  = None
        self.cand_edges  = sample_cand_edges
        self.cand_routes = np.array([ edges2matrix(N,es) for es in self.cand_edges])
        self.p_entry     = None
        self.reward_vec  = None
        self.state       = sample_state

    def step(self, action):
        now_state  = self.state
        route      = self.cand_routes[action]
        route      = block(route, now_state)
        next_state = np.dot(route, now_state)
        # next_state = add new box
        reward, terminal = None, None
        self.state = next_state
        return self.state, terminal, reward

    def make_graph(self, output='graph'):
        G = Digraph(format = 'png')
        for e in self.edges:
            G.edge(str(e[0]), str(e[1]))
        G.render(output)

if __name__ == '__main__':
    env = Simulator()
    env.setup_sample_network()
#    env.make_graph()
#    env.step([0,1])


#!/usr/bin/env python3

import re
from collections import defaultdict, deque
from sys import exit

def load_graph():

    g = defaultdict(set)
    pat = re.compile("Step ([A-Z]{1}) must be finished before step ([A-Z]{1}) can begin.")

    known_nodes = set()

    with open("7ex.txt") as f:
        for line in f:
            m = pat.match(line.strip())
            if m:
                this = m.groups()[1]
                pred = m.groups()[0]
                g[this].add(pred)
                known_nodes.add(this)
                known_nodes.add(pred)

    return g, known_nodes

def find_initial_nodes(graph, nodes):
    return list(nodes - graph.keys())

if __name__ == "__main__":
    g, nodes = load_graph()
    print(g)
    starts = find_initial_nodes(g, nodes)
    print(starts)
    l = deque()

    i = 0
    while len(starts):
        starts = sorted(starts)
        starts.reverse()
        print(starts)
        n = starts.pop()
        print("start {}".format(n))
        l.append(n)

        for m in g.keys():
            if n in g[m]:
                print("{} has an edge from {}".format(m, n))
                g[m].remove(n)
                if len(g[m]) == 0:
                    print("{} has no predecessors".format(m))
                    starts.append(m)

        print("+============================+")
        i += 1
        if i == 5:
            print(l)

    print(l)
    print("".join(l))


import wikipedia
from bs4 import BeautifulSoup
import requests
import os
def get_articles():
    wikipedia.set_lang("no")
    sok = wikipedia.search('"Eksterne baser (Autoritetsdata) GND"', results = 5000)
    pages = []
    error_searchTerm = open("error_file.txt","w")

    if not os.path.exists('wiki_data'):
        os.makedirs('wiki_data')

    for title in sok:

        try:
            page = wikipedia.page(title)
            pages.append(page)
            urls = []
        except wikipedia.exceptions.DisambiguationError:
            print("Dette var feil")
            error_searchTerm.write(title+'\n')
        text = open("wiki_data/"+title+".txt","w")
        meta_path = "wiki_data/meta-"+title+".txt"
        meta_file = open(meta_path,"w")
        if get_gnd_url_from_html(page.html()) is not None:
            meta_file.write(get_gnd_url_from_html(page.html()))
        else:
            meta_file.write("mangler meta-data")
        text.write(page.content)
        text.close()
        meta_file.close()

def get_gnd_url_from_html(html_doc):
    # Denne henter url til det tyske nasjonalbiblioteket fra wikipediasiden. Og kaller deretter funksjonen
    # som henter deweynr fra Det Tyske Nasjonalbiblioteket (GND) sine sider.

    soup = BeautifulSoup(html_doc,'html.parser')

    for link  in soup.find_all('a'):
        if link.get('href') is not None:
            if "d-nb.info" in link.get('href'):
                gnd_link = link.get('href')
                return get_dewey_from_gnd(gnd_link)

def get_dewey_from_gnd (url):

    #Denne scraper Deweynr fra GND sine sider.

    r = requests.get(url)
    soup = BeautifulSoup(r.text)
    td_soup = iter(soup.find_all('td'))

    td_all = []
    for td in td_soup :
        iter_td = iter(td)
        for element in td:
            if "DDC-Notation" in element:
                td_all.append(next(td_soup))

    for element in td_all:
        dewey = str(element).replace('','')
        dewey = dewey.replace('	','')
        dewey = dewey.replace('
',' ')
        dewey = dewey.strip()
        dewey_u_html = BeautifulSoup(dewey).text
        dewey_stripped = dewey_u_html.strip()
        print(dewey_stripped)

        return dewey_u_html

if __name__ == '__main__':
    get_articles()


import os
import click
import datetime
import sys

from app.service import Crud
from app.model import Client, Product
from app.connection import Connection

import config

class Console(object):
    actions = ('index', 'store', 'show', 'update', 'delete', 'export')
    idRequired = ('show', 'update', 'delete')

    def __init__(self, model, action, id, export=False):
        if model is None:
            model = config.get('entity_default')

        if action is None and id:
            action = 'show'
        elif action is None and id is None:
            action = config.get('action_default')

        if action not in self.actions:
            print('Action is not enabled')
            os.abort()

        if action in self.idRequired:
            if id is None or len(id.split('=')[1]) == 0:
                print('Identifier is required')
                os.abort()
            else:
                id = id.split('=')[1]

        if model == 'products':
            entity = Product()
        else:
            entity = Client()

        connection = Connection()
        service = Crud(entity, action, connection)
        crudObj = getattr(service, action)

        if action == 'store':
            data = self.asking(entity.fields_store)
            runner = crudObj(data)
        elif action == 'update':
            data = self.asking(entity.fields_update)
            runner = crudObj(id, data)
        elif id is not None:
            runner = crudObj(id)
        else:
            runner = crudObj()

        print(runner)

    def asking(self, fields):
        inputs = {}
        keys = list(fields.keys())
        values = list(fields.values())

        for key in keys:
            inputs.update({key: input(fields.get(key))})

        return list([inputs])


import pygame,sys
import numpy as np

pygame.init()
size = (300, 300)
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Tic Tac Toe')
screen.fill((225, 218, 218))# RGB color tuple
pygame.draw.line(screen,(111, 106, 106),(100,0),(100,300),1)
pygame.draw.line(screen,(111, 106, 106),(200,0),(200,300),1)
pygame.draw.line(screen,(111, 106, 106),(0,100),(300,100),1)
pygame.draw.line(screen,(111, 106, 106),(0,200),(300,200),1)
def cross(n,m):
	pygame.font.init()
	font = pygame.font.SysFont('',80)
	text = font.render('X',1,(111, 106, 106))
	screen.blit(text,(m-20,n-20))
	return(a)
def circle(k,l):
	b = pygame.draw.circle(screen,(111, 106, 106),(k,l),25,6)
	return(b)

def clickcircle():
	if mouse_pos[0]<100 and mouse_pos[1]<100:
		circle(50,50)
		a[0,0] = 2
	elif (mouse_pos[0]>100 and mouse_pos[0]<200) and mouse_pos[1]<100:
		circle(150,50)
		a[0,1] = 2
	elif (mouse_pos[0]>200 and mouse_pos[0]<300) and mouse_pos[1]<100:
		circle(250,50)
		a[0,2] = 2

	elif mouse_pos[0]<100 and (mouse_pos[1]>100 and mouse_pos[1]<200):
		circle(50,150)
		a[1,0] = 2
	elif (mouse_pos[0]>100 and mouse_pos[0]<200) and (mouse_pos[1]>100 and mouse_pos[1]<200):
		circle(150,150)
		a[1,1] = 2
	elif (mouse_pos[0]>200 and mouse_pos[0]<300) and (mouse_pos[1]>100 and mouse_pos[1]<200):
		circle(250,150)
		a[1,2] = 2

	elif mouse_pos[0]<100 and (mouse_pos[1]>200 and mouse_pos[1]<300):
		circle(50,250)
		a[2,0] = 2
	elif (mouse_pos[0]>100 and mouse_pos[0]<200) and (mouse_pos[1]>200 and mouse_pos[1]<300):
		circle(150,250)
		a[2,1] = 2
	elif (mouse_pos[0]>200 and mouse_pos[0]<300) and (mouse_pos[1]>200 and mouse_pos[1]<300):
		circle(250,250)
		a[2,2] = 2
	return (a)
def clickcross():
	if mouse_pos[0]<100 and mouse_pos[1]<100:
		cross(50,50)
		a[0,0] = 1
	elif (mouse_pos[0]>100 and mouse_pos[0]<200) and mouse_pos[1]<100:
		cross(50,150)
		a[0,1] = 1
	elif (mouse_pos[0]>200 and mouse_pos[0]<300) and mouse_pos[1]<100:
		cross(50,250)
		a[0,2] = 1

	elif mouse_pos[0]<100 and (mouse_pos[1]>100 and mouse_pos[1]<200):
		cross(150,50)
		a[1,0] = 1
	elif (mouse_pos[0]>100 and mouse_pos[0]<200) and (mouse_pos[1]>100 and mouse_pos[1]<200):
		cross(150,150)
		a[1,1] = 1
	elif (mouse_pos[0]>200 and mouse_pos[0]<300) and (mouse_pos[1]>100 and mouse_pos[1]<200):
		cross(150,250)
		a[1,2] = 1
	elif mouse_pos[0]<100 and (mouse_pos[1]>200 and mouse_pos[1]<300):
		cross(250,50)
		a[2,0] = 1
	elif (mouse_pos[0]>100 and mouse_pos[0]<200) and (mouse_pos[1]>200 and mouse_pos[1]<300):
		cross(250,150)
		a[2,1] = 1
	elif (mouse_pos[0]>200 and mouse_pos[0]<300) and (mouse_pos[1]>200 and mouse_pos[1]<300):
		cross(250,250)
		a[2,2] = 1
	return (a)

def winnercirc():
	screen.fill((111, 106, 106))
	pygame.font.init()
	font = pygame.font.SysFont('',20)
	text = font.render('Winner is a circle player!',1,(218, 24, 24))
	screen.blit(text,(50,50))
	return
def winnercros():
	screen.fill((111, 106, 106))
	pygame.font.init()
	font = pygame.font.SysFont('',20)
	text = font.render('Winner is a cross player!',1,(218, 24, 24))
	screen.blit(text,(50,50))
	return
def win(g,h):
	if a[g,h]==2:
		print('WINNER IS CIRCLE PLAYER!')
		winnercirc()
	else:
		print('WINNER IS CROSS PLAYER!')
		winnercros()
	return

# Quit when the user closes the window

a = np.array([[0,0,0],[0,0,0],[0,0,0]])
while 0 in a:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			print ("Exiting...")
			looping = False
	c = pygame.mouse.get_pressed()

	if c[0] != 0:
		mouse_pos = pygame.mouse.get_pos()
		print('Pozice kliku:', mouse_pos)
		clickcircle()
		print(a)
	elif c[2] != 0:
		mouse_pos = pygame.mouse.get_pos()
		print('Pozice kliku:', mouse_pos)
		clickcross()
		print(a)
	if a.all() != 0:
		if a[0,0]==a[0,1]==a[0,2]:
			win(0,0)
		elif a[1,0]==a[1,1]==a[1,2]:
			win(1,0)
		elif a[2,0]==a[2,1]==a[2,2]:
			win(2,0)
		elif a[0,0]==a[1,0]==a[2,0]:
			win(0,0)
		elif a[0,1]==a[1,1]==a[2,1]:
			win(0,1)
		elif a[0,2]==a[1,2]==a[2,2]:
			win(0,2)
		elif a[0,0]==a[1,1]==a[2,2]:
			win(0,0)
		elif a[0,2]==a[1,1]==a[2,0]:
			win(0,2)
		else:
			print('Nobody is master')
			screen.fill((111, 106, 106))
			pygame.font.init()
			font = pygame.font.SysFont('',20)
			text = font.render('Nobody is winner',1,(218, 24, 24))
			screen.blit(text,(50,50))
			time.sleep(10)

	pygame.display.flip()


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

import os

import pyotp
import requests
from ratelimit import limits, sleep_and_retry

from ...models import Apps, Providers
from ..abstract_provider import AbstractProvider

class Client(AbstractProvider):

    provider = Providers.bitskins
    base_url = "https://bitskins.com/api/v1/"

    def __init__(self, app):
        super().__init__(app)
        self.__otp = pyotp.TOTP(os.environ.get('BITSKINS_2FA_KEY'))

    @staticmethod
    def get_parser(app):
        if app == Apps.csgo:
            from ..parsers.csgo import Parser
            return Parser
        raise NotImplemented

    @property
    def __2fa_code(self):
        return self.__otp.now()

    @sleep_and_retry
    @limits(calls=5, period=1)
    def __get(self, method, params=None):
        if not params:
            params = {}
        params['api_key'] = os.environ.get('BITSKINS_API_KEY')
        params['code'] = self.__2fa_code

        return requests.get(self.base_url + method + "/", params)

    def get_prices(self):
        result = self.__get('get_price_data_for_items_on_sale', params={'app_id': self.parser.app_id})
        result = result.json()['data']['items']
        for row in result:
            item_name = row['market_hash_name']
            item_price = float(row['lowest_price'])
            skin = self.parser.get_skin_from_item_name(item_name)
            if skin and item_price > 0:
                yield (skin, item_price)


import copy
import os
import shutil
import time

from logger import logger
from perfrunner.helpers import local
from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.misc import pretty_dict, read_json
from perfrunner.helpers.profiler import with_profiles
from perfrunner.helpers.worker import (
    jts_run_task,
    jts_warmup_task,
    spring_task,
)
from perfrunner.tests import PerfTest

class JTSTest(PerfTest):

    result = dict()

    def __init__(self, cluster_spec, test_config, verbose):
        super().__init__(cluster_spec, test_config, verbose)
        self.access = self.test_config.jts_access_settings
        if self.test_config.collection.collection_map:
            self.access.collections_enabled = True
        self.showfast = self.test_config.showfast
        self.fts_index_map = dict()
        self.fts_index_defs = dict()

    def download_jts(self):
        if self.worker_manager.is_remote:
            self.remote.init_jts(
                repo=self.access.jts_repo,
                branch=self.access.jts_repo_branch,
                worker_home=self.worker_manager.WORKER_HOME,
                jts_home=self.access.jts_home_dir
            )
        else:
            local.init_jts(
                repo=self.access.jts_repo,
                branch=self.access.jts_repo_branch,
                jts_home=self.access.jts_home_dir
            )

    @with_stats
    @with_profiles
    def run_test(self):
        self.run_phase(
            'jts run phase',
            jts_run_task,
            self.access,
            self.target_iterator
        )
        self._download_logs()

    def warmup(self):
        if int(self.access.warmup_query_workers) > 0:
            self.run_phase(
                'jts warmup phase',
                jts_warmup_task,
                self.access,
                self.target_iterator
            )

    def _download_logs(self):
        local_dir = self.access.jts_logs_dir
        if self.worker_manager.is_remote:
            if os.path.exists(local_dir):
                shutil.rmtree(local_dir, ignore_errors=True)
            os.makedirs(local_dir)
            self.remote.get_jts_logs(
                self.worker_manager.WORKER_HOME,
                self.access.jts_home_dir,
                self.access.jts_logs_dir
            )
        else:
            local.get_jts_logs(
                self.access.jts_home_dir,
                local_dir
            )

class FTSTest(JTSTest):

    def __init__(self, cluster_spec, test_config, verbose):
        super().__init__(cluster_spec, test_config, verbose)
        self.fts_master_node = self.fts_nodes[0]

    def delete_index(self):
        self.rest.delete_fts_index(
            self.fts_master_node,
            self.access.couchbase_index_name
        )

    def collection_split(self, collection_map, bucket, scope):
        collection_list_per_index = []
        start = 0
        collection_list = list(collection_map[bucket][scope].keys())
        total_num_collections = len(collection_list)
        collections_per_index = int(total_num_collections / int(self.access.index_groups))
        end = collections_per_index
        end_index = collections_per_index*int(self.access.index_groups)

        if int(self.access.index_groups) == 1:
            # if index is built on all the collections
            return [collection_list]
        while end <= end_index:
            collection_list_per_index.append(collection_list[start:end])
            start = end
            end = end + collections_per_index

        return collection_list_per_index

    def get_collection_index_def(self, collection_list, scope_name, index_type_mapping,
                                 custom_type_mapping_keys=[]):
        coll_type_mapping = []
        for collection_group in collection_list:
            types_col = {}
            for col_name in collection_group:
                key_name = "{}.{}".format(scope_name, col_name)
                if len(custom_type_mapping_keys) != 0:
                    for ind, custom_key in enumerate(custom_type_mapping_keys):
                        key_name = key_name+".{}".format(custom_key)
                        types_col[key_name] = index_type_mapping[ind]
                else:
                    types_col[key_name] = index_type_mapping
            coll_type_mapping.append(types_col)
        return coll_type_mapping

    def create_fts_index_definitions(self):
        logger.info("In the Indexing function:")
        # On a singlee fts index definition
        index_def = read_json(self.access.couchbase_index_configfile)
        collection_map = self.test_config.collection.collection_map
        # this variable will hold the key valuesfor the custom type mapping
        key_values = []
        # index_type_mapping holds the type mapping part of the index
        index_type_mapping = {}
        index_id = 0
        # on a single bucket
        bucket_name = self.test_config.buckets[0]
        index_def.update({
            'sourceName': bucket_name,
        })
        if self.access.couchbase_index_type:
            index_def["params"]["store"]["indexType"] = self.access.couchbase_index_type

        # setting the type mapping for collection indexes
        if collection_map:
            index_def["params"]["doc_config"]["mode"] = "scope.collection.type_field"

        # Geo queries have a slightly different index type with custom type mapping
        if "types" in list(index_def["params"]["mapping"].keys()):
            # if any custom type mapping is present
            key_values = list(index_def["params"]["mapping"]["types"].keys())

        default_index_type_mapping = {}
        # for default collection settings
        if collection_map and len(collection_map[bucket_name].keys()) == 1:
            key_name = "{}.{}".format("_default", "_default")
            if len(key_values) > 0:
                # there is custom mapping
                for type_name in key_values:
                    type_mapping_key_name = key_name + ".{}".format(type_name)
                    default_index_type_mapping[type_mapping_key_name] = \
                        index_def["params"]["mapping"]["types"][type_name]
            else:
                default_index_type_mapping[key_name] = index_type_mapping
                index_def["params"]["mapping"]["default_mapping"]["enabled"] = False

        # if collection map exists , the index is on collections
        if collection_map and len(collection_map[bucket_name].keys()) > 1:
            scope_names = list(collection_map[bucket_name].keys())[1:]
            if "types" in list(index_def["params"]["mapping"].keys()):
                # to get the custom mapping
                temp = index_def["params"]["mapping"]["types"]
                index_type_mapping = [temp[type_key] for type_key in key_values]
            else:
                index_type_mapping = \
                    copy.deepcopy(index_def["params"]["mapping"]["default_mapping"])
                index_def["params"]["mapping"]["default_mapping"]["enabled"] = False
            # on a single scope
            collection_name_list = list(collection_map[bucket_name][scope_names[0]].keys())
            collection_list = self.collection_split(collection_map, bucket_name, scope_names[0])
            index_type_mapping_per_group = self.get_collection_index_def(collection_list,
                                                                         scope_names[0],
                                                                         index_type_mapping,
                                                                         key_values
                                                                         )
            # calculating the doc per collection for persistence
            num_docs_per_collection = \
                self.test_config.load_settings.items // len(collection_name_list)
            items_per_index = num_docs_per_collection * len(collection_list[0])
            # as the test is on a single scope:
            for coll_group_id, collection_type_mapping in enumerate(index_type_mapping_per_group):
                for index_count in range(0, self.access.indexes_per_group):
                    index_name = "{}-{}".format(self.access.couchbase_index_name, index_id)
                    index_def.update({
                        'name': index_name,
                    })
                    index_def["params"]["mapping"]["types"] = collection_type_mapping
                    self.fts_index_map[index_name] = \
                        {
                            "bucket": bucket_name,
                            "scope": scope_names[0],
                            "collections": collection_list[coll_group_id],
                            "total_docs": items_per_index
                        }
                    self.fts_index_defs[index_name] = {
                        "index_def": index_def
                    }
                    index_id += 1

        else:
            # default , multiple indexes with the same index def
            for num_indexes in range(0, self.access.indexes_per_group):
                index_name = "{}-{}".format(self.access.couchbase_index_name, num_indexes)
                index_def.update({
                    'name': index_name,
                })
            # for indexes with default collection and scope in the index
            if collection_map and len(collection_map[bucket_name].keys()) == 1:
                index_def["params"]["mapping"]["types"] = default_index_type_mapping
            self.fts_index_map[index_name] = {
                "bucket": bucket_name,
                "scope": "_default",
                "collections": ["_default"],
                "total_docs": int(self.access.test_total_docs)
            }
            self.fts_index_defs[index_name] = {
                "index_def": index_def
            }

        self.access.fts_index_map = self.fts_index_map

    def create_fts_indexes(self):
        total_time = 0
        for index_name in self.fts_index_defs.keys():
            index_def = self.fts_index_defs[index_name]['index_def']
            logger.info('Index definition: {}'.format(pretty_dict(index_def)))
            t0 = time.time()
            self.rest.create_fts_index(self.fts_master_node, index_name, index_def)
            self.wait_for_index(index_name)
            t1 = time.time()
            logger.info("Time taken by {} is {} s".format(index_name, (t1-t0)))
            total_time = total_time+(t1-t0)
        return total_time

    def wait_for_index(self, index_name):
        self.monitor.monitor_fts_indexing_queue(
            self.fts_master_node,
            index_name,
            self.fts_index_map[index_name]["total_docs"]
        )

    def wait_for_index_persistence(self, fts_nodes=None):
        if fts_nodes is None:
            fts_nodes = self.fts_nodes
        for index_name in self.fts_index_map.keys():
            self.monitor.monitor_fts_index_persistence(
                fts_nodes,
                index_name
            )

    def add_extra_fts_parameters(self):
        logger.info("Adding extra parameter to the fts nodes")
        nodes_before_rebalance = self.test_config.cluster.initial_nodes[0]
        servers_and_roles = self.cluster_spec.servers_and_roles
        fts_nodes_before = []
        for i in range(0, nodes_before_rebalance):
            host = servers_and_roles[i][0]
            roles = servers_and_roles[i][1]
            if "fts" in roles:
                fts_nodes_before.append(host)
        if len(self.access.fts_node_level_parameters.keys()) != 0:
            node_level_params = self.access.fts_node_level_parameters
            for node in fts_nodes_before:
                self.rest.fts_set_node_level_parameters(node_level_params, node)
        return fts_nodes_before

    def calculate_index_size(self) -> int:
        size = 0
        for index_name, index_info in self.fts_index_map.items():
            metric = '{}:{}:{}'.format(
                index_info['bucket'],
                index_name,
                'num_bytes_used_disk'
            )
            for host in self.fts_nodes:
                stats = self.rest.get_fts_stats(host)
                size += stats[metric]
        return size

    @with_stats
    def build_indexes(self):
        elapsed_time = self.create_fts_indexes()
        return elapsed_time

    def spread_data(self):
        settings = self.test_config.load_settings
        #  if self.access.test_collection_query_mode == "collection_specific":
        #      settings.fts_data_spread_worker_type = "collection_specific"
        settings.seq_upserts = False
        self.run_phase(
            'data spread',
            spring_task,
            settings,
            self.target_iterator
        )

    def data_restore(self):
        if self.test_config.collection.collection_map:
            self.fts_collections_restore()
            self.wait_for_persistence()
            self.spread_data()
        else:
            self.restore()

    def cleanup_and_restore(self):
        self.delete_index()
        self.data_restore()
        self.wait_for_persistence()

class FTSThroughputTest(FTSTest):

    COLLECTORS = {'jts_stats': True, 'fts_stats': True}

    def report_kpi(self):
        self.reporter.post(*self.metrics.jts_throughput())

    def run(self):
        self.cleanup_and_restore()
        self.create_fts_index_definitions()
        self.create_fts_indexes()
        self.download_jts()
        self.wait_for_index_persistence()
        self.warmup()
        self.run_test()
        self.report_kpi()

class FTSLatencyTest(FTSTest):

    COLLECTORS = {'jts_stats': True, 'fts_stats': True}

    def report_kpi(self):
        self.reporter.post(*self.metrics.jts_latency(percentile=80))
        self.reporter.post(*self.metrics.jts_latency(percentile=95))

    def run(self):
        self.cleanup_and_restore()
        self.create_fts_index_definitions()
        self.create_fts_indexes()
        self.download_jts()
        self.wait_for_index_persistence()
        self.warmup()
        self.run_test()
        self.report_kpi()

class FTSIndexTest(FTSTest):

    COLLECTORS = {'fts_stats': True}

    def report_kpi(self, time_elapsed: int, size: int):
        self.reporter.post(
            *self.metrics.fts_index(time_elapsed)
        )
        self.reporter.post(
            *self.metrics.fts_index_size(size)
        )

    @with_stats
    def build_index(self, fts_nodes):
        elapsed_time = self.create_fts_indexes()
        self.wait_for_index_persistence(fts_nodes)
        return elapsed_time

    def run(self):
        self.cleanup_and_restore()
        fts_nodes = self.add_extra_fts_parameters()
        self.create_fts_index_definitions()
        time_elapsed = self.build_index(fts_nodes)
        size = self.calculate_index_size()
        self.report_kpi(time_elapsed, size)

class FTSThroughputCloudTest(FTSThroughputTest):

    def run(self):
        self.load()
        self.wait_for_persistence()
        self.check_num_items()
        self.compact_bucket()
        self.create_fts_index_definitions()
        self.create_fts_indexes()
        self.download_jts()
        self.wait_for_index_persistence()
        self.warmup()
        self.run_test()
        self.report_kpi()

class FTSLatencyCloudTest(FTSLatencyTest):

    def run(self):
        self.load()
        self.wait_for_persistence()
        self.check_num_items()
        self.compact_bucket()
        self.create_fts_index_definitions()
        self.create_fts_indexes()
        self.download_jts()
        self.wait_for_index_persistence()
        self.warmup()
        self.run_test()
        self.report_kpi()


import numpy as np
from base import sigmoid, bernuolli, random_argmax
from numpy import dot
from arms import BernulliLinearArm

class SimpleEnvironment():
    """Simple environment for N-armed bandit. """

    __name__ = 'SimpleEnvironment'

    def __init__(self, arms):
        """Create the environent. If arms is None - default is bernulli arms
        Params:
            arms - list: list of arms objects
        """
        self.arms = arms
        self.k_arms = len(self.arms)
        self.optimal_mean = np.max([arm.mean for arm in arms])
        self.optimal_arm = np.argmax([arm.mean for arm in arms])
        self.means = np.array([arm.get_mean() for arm in arms])

#    def get_observation(self, arm_index):
#        # record the last observation
#        self.observation = self.arms[arm_index].pull()
#        return self.observation

    def get_stochastic_reward(self, arm_index):
        """Same as above but I am not sure which naming i like better
        """
        self.reward = self.arms[arm_index].pull()
        return self.reward
#
#    def get_optimal_reward(self):
#        """Returns the value of the optimal mean
#        """
#        return self.optimal_mean

    def get_optimal_mean(self):
        """Returns the value of the optimal(real) mean
        """
        return self.optimal_mean

    def get_optimal_arm(self):
        """Returns the index of the optimal mean
        """
        return self.optimal_arm

    def get_all_means(self):
        return self.means

    def __repr__(self):
        return '{} with arms: {}'.format(self.__name__, self.arms)

class ContextualEnvironment():

    def __init__(self, arms, context_options = [0.6, 0.4], add_bias = True):

        self.arms = arms
        self.k_arms = len(arms)
        self.dimension = arms[0].dimension
        self.thetas = [arm.theta for arm in arms]
        self.context_options = context_options
        self.add_bias = add_bias
        self.current_optimal_mean = None
        self.current_optimal_arm = None
        self.current_means = None
        self.current_rewards = None

    def generate_context(self):
        """Generates context vector of indicators and computes current
        real reward probability
        """
        context = []
        context_vector = bernuolli(self.context_options)
        if self.add_bias:
            context_vector = np.append([1], context_vector)
        for i in range(self.k_arms):
            context.append(context_vector)
        # pull all arms to generate current mean, rewards and get the optimal one
        # agent/policy/algorithm knows only the context but means are not revealed
        self.current_rewards = [arm.pull(context_vector) for arm, context_vector in zip(self.arms, context)]
        self.current_means = [arm.get_current_mean() for arm in self.arms]
        self.current_optimal_arm = random_argmax(self.current_means)
        self.current_optimal_mean = self.current_means[self.current_optimal_arm]

        return context

    def get_stochastic_reward(self, arm_index):
        return self.current_rewards[arm_index]


# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

map_permission = client.sync \
    .services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
    .sync_maps("Players") \
    .sync_map_permissions("bob") \
    .update(True, True, False)

print(map_permission.read)  # True
print(map_permission.write)  # True
print(map_permission.manage)  # False


from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import datetime
import json
import os
import re
import sys
import logging
from logging import handlers

class MyHandler(BaseHTTPRequestHandler):
    def get_json(self, seconds):
        """
        This function return final json that will show webserver. Function
        get seconds that put in path request, access log file creation and
        get files
        """
        files = []
        filenames_lenght = []
        json_file = []
        creations_file = open('/var/log/newfiles.log', 'r')
        now = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        date_before = int(now) - int(seconds)
        # Loop in file to get all lines
        for line in creations_file:
            (key, val) = line.split()
            check_date_time = int(key)
            # Check between two datatimes because could be posibility of
            # new files creation after request
            if date_before <= check_date_time <= now:
                path = os.path.basename(val)
                lenght = len(path)
                files.append(path)
                filenames_lenght.append(lenght)
        # It's only for return json empty data and not get an error
        if files:
            median = self.get_median(filenames_lenght)
        else:
            median = ''
        json_file.append({'files': files, 'median_lenght': median})
        return(json.dumps(json_file))

    def get_median(self, data_list):
        """
        If using python3 I could use median function but in python 2.7 it's
        not available, so I toke this median function from github:
        https://github.com/bycoffe/python-math/blob/master/calculate/median.py
        """
        data_list = map(float, data_list)
        n = len(data_list)
        data_list.sort()
        # Test whether the n is odd
        if n & 1:
          # If is is, get the index simply by dividing it in half
          index = n / 2
          return data_list[index]
        else:
          # If the n is even, average the two values at the center
          low_index = n / 2 - 1
          high_index = n / 2
          average = (data_list[low_index] + data_list[high_index]) / 2
          return average

    def log_request(self, code='-', size='-'):
        # Send request info to logger file
        logger.info('"%s" %s %s', self.requestline, str(code), str(size))

    def do_GET(self):
        # Only continue if there is only one path after URL
        regexp = re.compile('^\/(\d+)$')
        match = regexp.match(self.path)
        if match:
            self.send_response(200)
            self.send_header("Content-type", "application/json")
            self.end_headers()
            seconds = match.group(1)
            self.wfile.write("%s" % self.get_json(seconds))
        else:
            self.send_response(404)
            self.send_header("Content-type", "application/json")
            self.end_headers()
            self.wfile.write("{ 'error': 'You must specify seconds on url path' }")
        return

def write_pidfile():
    pid_file = '/var/run/http_service.pid'
    if os.path.exists(pid_file):
        print("Cannot daemonize: pid file %s already exists." % pid_file)
        raise SystemExit(1)
    pid = str(os.getpid())
    f = open(pid_file, 'w')
    f.write(pid)
    f.close()

try:
    logger = logging.getLogger("watchdog")
    file_log = logging.FileHandler(filename="/var/log/http_service.log")
    logger.addHandler(file_log)
    logger.setLevel(logging.INFO)
    write_pidfile()
    server = HTTPServer(('localhost', 8888), MyHandler)
    logger.info('Started http server')
    server.serve_forever()
except KeyboardInterrupt:
    logger.info('^C received, shutting down server')
    server.socket.close()