from datetime import date
import sqlite3
from app.core.Database import Database
from app.core.Jeu import Jeu
from app.core.Parametre import Parametre
from app.core.Utilisateur import Utilisateur
from app.core.Texte import Texte

conn = Database.getConnexion()
c = Database.getCursor()

"""
Fonctions concernant les réservations.
"""
class Reservation:

        """
        Retourne la liste des reservations d'un utilisateur.
        ((0.idReservation1, 1.idJeu1, 2.idUtilisateur1, 3.dateDebutReservation1, 4.dateFinReservation1), ...)

        Paramètres:
                -> idUtilisateur: Entier
        Pré-conditions:
                -> Seul un utilisateur ayant pour rôle « Administrateur » peut voir la liste des reservations d'un autre utilisateur.
                -> L'identifiant est obligatoire.
        Post-conditions:
                -> La liste est vide si l'utilisateur n'a pas de reservation.
        Retour:
                -> Une liste.
        """
        def getReservationsUtilisateur(idUtilisateur):
                if (idUtilisateur is None):
                        raise ValueError(Texte.UTILISATEUR_ID_OBLIGATOIRE)

                # Verifie que l'utilisateur connecter est un admin si ce n'est pas celui connecter.
                if (idUtilisateur != Utilisateur.getIdUtilisateurActif()):
                        Utilisateur.verifierUtilisateurActifEstAdmin()

                c.execute("SELECT * FROM reservation WHERE idUtilisateur = ?", (int(idUtilisateur),))
                reservations = c.fetchall()

                if (reservations is None):
                        reservations = tuple()

                return reservations
        """
        Retourne les informations d'une reservation à partir de son identifiant.
        (0.idReservation, 1.idJeu, 2.idUtilisateur, 3.dateDebutReservation, 4.dateFinReservation)

        Paramètres:
                -> idReservation: Entier
        Pré-conditions:
                -> Seul un utilisateur ayant pour rôle « Administrateur » peut voir des reservations à partir de leurs identifiants.
                -> L'identifiant est obligatoire.
        Post-conditions:
                -> La liste est vide si l'utilisateur n'a pas de reservation.
        Retour:
                -> Un tuple.
        """
        def getReservation(idReservation):
                if (idReservation is None):
                        raise ValueError(Texte.RESERVATION_ID_OBLIGATOIRE)

                # Verifie que l'utilisateur connecter est un admin
                Utilisateur.verifierUtilisateurActifEstAdmin()

                c.execute("SELECT * FROM reservation WHERE idReservation = ?", (int(idReservation),))
                reservation = c.fetchone()

                return reservation

        """
        Retourne la liste des reservations d'un jeu.
        ((0.idReservation1, 1.idJeu1, 2.idUtilisateur1, 3.dateDebutReservation1, 4.dateFinReservation1), ...)

        Paramètres:
                -> idJeu: Entier
        Pré-conditions:
                -> Seul un utilisateur ayant pour rôle « Administrateur » peut voir la liste des reservations d'un jeu.
                -> L'identifiant est obligatoire.
        Post-conditions:
                -> La liste est vide si le jeu n'est pas reserve.
        Retour:
                -> Une liste.
        """
        def getReservationsJeu(idJeu):
                if (idJeu is None):
                        raise ValueError(Texte.JEU_ID_OBLIGATOIRE)

                # Verifie que l'utilisateur connecter est un admin
                Utilisateur.verifierUtilisateurActifEstAdmin()

                c.execute("SELECT * FROM reservation WHERE idJeu = ?", (int(idJeu),))
                reservations = c.fetchall()

                if (reservations is None):
                        reservations = tuple()

                return reservations

        """
        Valide une réservation pour un utilisateur donné et un jeu donné.

        Paramètres:
                -> idUtilisateur: Entier
                -> idJeu: Entier
                -> dateDebut : date
                -> dateRetour: date
        Pré-conditions:
                -> Tous les parametres sont obligatoires.
                -> La date de retour se trouve au maximum dans les 7 prochains jours de la date de début (ce nombre est modifiable dans les parametres).
                -> Un utilisateur ne peut avoir plus d’une réservation en même temps sauf s’il s’agit d’une extension.
        Dans ce cas l’utilisateur peut avoir en même temps une extension et le jeu auquel elle est rattachée.
                -> Si le jeu est déjà réservé entre les date de debut et de retour, la reservation est impossible.
                -> Si l’utilisateur n’est pas à jour dans ses cotisations la réservation est refusé.
        Retour:
                -> Rien.
        """
        def validerReservation(idUtilisateur, idJeu, dateDebut, dateRetour):
                # Si un des parametres est absent, erreur
                if ((idUtilisateur is None) or (idJeu is None) or (dateDebut is None) or (dateRetour is None)):
                        raise ValueError(Texte.PARAMETRES_OBLIGATOIRES)

                # Verification que l'utilisateur a bien payer c'est cotisation
                if (not Utilisateur.cotisationAJour(idUtilisateur)):
                        raise EnvironmentError(Texte.UTILISATEUR_NON_AJ_COTISATIONS)

                # Verification de la disponibilité du jeu dans les dates du pret pour l'utilisateur
                elif (not Jeu.estDisponible(idJeu, dateDebut, dateRetour)):
                        raise EnvironmentError(Texte.JEU_INDISPONIBLE_DATE)

                # Verification de la validité des dates indiquées
                elif (not (Reservation.__validerDateDeRetour(dateDebut, dateRetour) and Reservation.__validerDateDeDepart(dateDebut)) ):
                        return;

                # Verifier si l'utilisateur n'a pas deja un pret (sauf extension)
                elif (not Reservation.__utilisateurPeutReserverJeu(idUtilisateur, idJeu)):
                        raise EnvironmentError(Texte.RESERVATION_UTILISATEUR_LIMITE_EMPRUNT)

                elif (Reservation.__utilisateurEmprunteDejaJeu(idUtilisateur, idJeu)):
                        raise EnvironmentError(Texte.RESERVATION_UTILISATEUR_DEJA_EMPRUNT)

                # Réservation Valide
                else:

                        # Dans une transaction
                        # Sauvegarde de la reservation
                        try:
                                sql = "INSERT INTO reservation (idJeu, idUtilisateur, dateDebutReservation, dateFinReservation) VALUES (?, ?, ?, ?);"
                                c.execute(sql, (idJeu, idUtilisateur, dateDebut.isoformat(), dateRetour.isoformat()))
                                conn.commit()
                        except Exception as e:
                                conn.rollback()
                                print(e)
                                raise SystemError(Texte.RESERVATION_PB_SAUVEGARDE)

        """
        Valide la supression d'une réservation.

        Paramètres:
                -> idReservation: Entier
        Pré-conditions:
                -> L'identifiant est obligatoire.
        Retour:
                -> Rien.
        """
        def annuler(idReservation):
                if (idReservation is None):
                    raise ValueError(Texte.RESERVATION_ID_OBLIGATOIRE)

                # Dans un transaction
                try:
                        c.execute("DELETE FROM reservation WHERE idReservation = ?", (idReservation,))
                        conn.commit()
                except Exception as e:
                        conn.rollback()
                        print(e)
                        raise SystemError(Texte.RESERVATION_PB_SAUVEGARDE)

        """
        Retourne True si l'utilisateur peut reserver le jeu, False sinon.
        Un utilisateur peut emprunter un jeu si :
                - il ne possede pas de reservation
                - ou si le jeu qu'il veut reserver est une extension de sa reservation

        Paramètres:
                -> idUtilisateur: Entier
                -> idJeu: Entier
        Pré-conditions:
                -> Tous les parametres sont obligatoires.
        Retour:
                -> Boolean indiquant si l'utilisateur peut reserver. True si oui, False sinon.
        """
        def __utilisateurPeutReserverJeu(idUtilisateur, idJeu):
                # Si un des parametres est absent, erreur
                if ((idUtilisateur is None) or (idJeu is None)):
                        raise ValueError(Texte.PARAMETRES_OBLIGATOIRES)

                # On verifie si l'utilisateur a deja une reservation
                reservationsUtilisateur = Reservation.getReservationsUtilisateur(idUtilisateur)
                if (not reservationsUtilisateur is None and len(reservationsUtilisateur) > 0):
                        # Si l'utilisateur a deja trop de reservation, il ne peut pas emprunter
                        if (len(reservationsUtilisateur) >= Reservation.__getMaximumReservation()):
                                return False
                        else:
                                # Verifier si extension
                                return Jeu.estExtension(reservationsUtilisateur[0][1], idJeu) or Jeu.estExtension(idJeu, reservationsUtilisateur[0][1])
                else:
                        # Si pas de pret, l'utilisateur peut reserver
                        return True

        """
        Retourne True si l'utilisateur emprunte deja le jeu.

        Paramètres:
                -> idUtilisateur: Entier
                -> idJeu: Entier
        Pré-conditions:
                -> Tous les parametres sont obligatoires.
        Retour:
                -> Boolean indiquant si l'utilisateur emprunte deja le jeu. True si oui, False sinon.
        """
        def __utilisateurEmprunteDejaJeu(idUtilisateur, idJeu):
                from app.core.Pret import Pret

                # Si un des parametres est absent, erreur
                if ((idUtilisateur is None) or (idJeu is None)):
                        raise ValueError(Texte.PARAMETRES_OBLIGATOIRES)

                prets = Pret.getPretsUtilisateur(idUtilisateur)
                if (len(prets) == 0):
                        return False
                else:
                        empruntExiste = False
                        i = 0
                        while (i < len(prets) and not empruntExiste):
                                if (int(prets[i][1]) == int(idJeu)):
                                        empruntExiste = True
                                i = i + 1
                        # i >= len(prets) or empruntExiste
                        return empruntExiste

        """
        Retourne True si la date de retour est valide par rapport a la date de debut due la reservation.
        Une date de retour est valide si :
                - elle est posterieure a la date de debut
                - le nombre de jour entre la date de debut et de fin est inferieur ou egale a 7 (nombre modifiable dans les parametres)

        Paramètres:
                -> dateDepart: date
                -> dateRetour: date
        Pré-conditions:
                -> Tous les parametres sont obligatoires.
        Retour:
                -> Boolean indiquant si la date de retour est valide. True si oui, Erreur sinon.
        """
        def __validerDateDeRetour(dateDepart, dateRetour):
                # Si un des parametres est absent, erreur
                if ((dateDepart is None) or (dateRetour is None)):
                        raise ValueError(Texte.PARAMETRES_OBLIGATOIRES)

                if (dateRetour < dateDepart):
                        raise EnvironmentError(Texte.RESERVATION_DATE_RETOUR_INVALIDE_ANT)

                dateDifference = dateRetour - dateDepart
                maxPeriodeEmprunt = Parametre.valeur(Parametre.MAX_PERIODE_EMPRUNT)
                if (dateDifference.days > maxPeriodeEmprunt):
                        raise EnvironmentError(Texte.RESERVATION_DATE_RETOUR_INVALIDE_DUREE_LIMITE.format(periodeEmprunt=str(maxPeriodeEmprunt)))
                else:
                        return True

                """
        Retourne True si la date de depart est valide (dans les 90 prochains jours)

        Paramètres:
                -> dateDepart: date
        Pré-conditions:
                -> Tous les parametres sont obligatoires.
        Retour:
                -> Boolean indiquant si la date de depart est valide. True si oui, Erreur sinon.
        """
        def __validerDateDeDepart(dateDepart):
                # Si un des parametres est absent, erreur
                if ((dateDepart is None)):
                        raise ValueError(Texte.PARAMETRES_OBLIGATOIRES)

                aujourdhui = date.today()

                # Si la date départ est passé, erreur
                if (dateDepart < aujourdhui):
                        raise EnvironmentError(Texte.RESERVATION_DATE_DEBUT_INVALIDE_ANT)

                # Test si la date de départ est dans le prochains jours
                dateDifference = dateDepart - aujourdhui
                maxPeriodeReservation = Parametre.valeur(Parametre.MAX_PERIODE_RESERVATION)
                if (dateDifference.days > maxPeriodeReservation):
                        raise EnvironmentError(Texte.RESERVATION_DATE_DEBUT_INVALIDE_DUREE_LIMITE.format(periodeReservation=str(maxPeriodeReservation)))
                else:
                        return True

        """
        Retourne le nombre maximum de reservation qu'un utilisateur peut avoir.
        """
        def __getMaximumReservation():
                return 2

        """
        Retourne la liste de toutes les reservations.
        Si retard a True, retourne la liste de tous les emprunts non rendus en cours.
        ((0.idReservation1, 1.idJeu1, 2.idUtilisateur1, 3.dateDebutReservation1, 4.dateFinReservation1), ...)

        Paramètres:
                -> retard: Boolean
        Retour:
                -> Une liste.
        """
        def getReservations(retard = False):
                # Execute la selection dans la base de données.
                if (retard):
                        c.execute("SELECT * FROM reservation WHERE dateDebutReservation < ?", (date.today().isoformat(),))
                else:
                        c.execute("SELECT * FROM reservation")
                resultat = c.fetchall()
                return resultat


import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep

def get_bands_from_page(page):
  soup = BeautifulSoup(page, features="html.parser")
  band_tags = soup.select("a[routerLinkActive]")
  bands = [tag["href"].replace("#/artist/", "").replace("-", " ") for tag in band_tags]
  return bands

def fetch_hurricane_lineup():
  print("Fetching Hurricane bands...")
  lineup_url = "https://www.hurricane.de/en/line-up#/artists/alphabetical"
  browser = webdriver.Firefox()
  browser.get(lineup_url)
  # scroll down until no new bands are lazily loaded
  old_bands = []
  while True:
    browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    sleep(10)
    bands = get_bands_from_page(browser.page_source)
    print("Fetched {} bands".format(len(bands)))
    if len(old_bands) == len(bands):
      break
    old_bands = bands
  print("Finished fetching of Hurricane bands.")
  print("Total bands: {}".format(len(bands)))
  browser.close()
  return bands


# main.py
# Midnight Rider
# A text-based adventure game

import random
import sys
import textwrap
import time

INTRODUCTION = """
WELCOME TO MIDNIGHT RIDER.

WE'VE STOLEN A CAR, WE NEED TO GET IT HOME.
THE CAR IS SPECIAL.

WE CAN'T LET THEM HAVE IT.

ONE GOAL: SURVIVAL... AND THE CAR.
REACH THE END BEFORE THE MEN GON GETCHU.
"""

WIN = """
YOU PRESSED THE BUTTON TO OPEN THE GATE.
THIS ISN'T THE FIRST TIME YOU'VE DONE THIS.
YOU CAN TIME IT PERFECTLY SO THAT YOU
SLIDE THE CAR IN AS THE GATES CLOSE.

YOU KNOW YOU DID THE RIGHT THING.
THE GOVERNMENT WOULD HAVE TORN THE CAR APART,
ANALYSING IT, TESTING IT, THEN DESTROYING IT.

THEY DON'T KNOW ITS SECRETS...
THAT IT HOLDS THE KEY TO DIFFERENT WORLDS.

AS YOU STEP OUT OF THE VEHICLE, FIDO RUNS
UP TO YOU.
"THANK YOU FOR SAVING ME," HE SAYS.

AS YOU TAKE A COUPLE OF STEPS AWAY FROM THE CAR,
IT MAKES A STRANGE NOISE.

BEFORE YOUR EYES, IT SHIFTS ITS SHAPE.
YOU'VE SEEN IT BEFORE, BUT ONLY ON TV.

"BUMBLEBEE...?"

----GAME OVER----
"""

LOSE_HUNGER = """
YOU SUCCUMBED TO YOUR HUNGER AND CANNOT CONTINUE.
THE FLASHING RED AND BLUE LIGHTS GET CLOSER AND
CLOSER AS YOU FADE IN AND OUT OF CONSCIOUSNESS.
THE END IS NEAR.

----GAME OVER----
"""

LOSE_AGENTS = """
THE AGENTS HAVE CLOSED IN ON YOU.
THERE ARE AT LEAST 20 CARS SURROUNDING YOU.
THE LEAD CAR BUMPS YOUR PASSENGER SIDE.
YOU MANAGE TO CORRECT YOUR STEERING
TO KEEP YOU FROM CRASHING.

YOU DIDN'T SEE THE AGENT'S CAR BESIDE YOU.
THE DRIVER BUMPS YOUR CAR.
AND THAT'S IT.

YOU SPIN UNCONTROLLABLY.
THE CAR FLIPS OVER AT LEAST TWO TIMES.
OR MORE... YOU SEEM TO HAVE LOST COUNT.

SIRENS.

"ARE THEY ALIVE?" THEY SAY AS YOU HEAR
FOOTSTEPS GETTING CLOSER.
"DOESN'T MATTER, ALL WE WANTED WAS THE CAR.

YOU SEE A DOG SLOWLY STEP OUT OF THE
OVERTURNED CAR.

"YOU WILL NEVER STOP THE REVOLUTION,"
THE DOG SEEMS TO SAY TO THE OFFICERS.

IT WAS IN THE CAR THE WHOLE TIME.

YOU DRIFT OFF INTO UNCONSCIOUSNESS.

----GAME OVER----
"""

LOSE_FUEL = """
YOUR CAR SPUTTERS AND SEEMS TO LET OUT
A BIG SIGH. THERE'S NO MORE FUEL LEFT.

THE COPS SURROUND YOU AND THEY STEP
OUT OF THEIR CARS. THE LEAD AGENT
RIPS THE DOOR OPEN AND THROWS YOU
OUT OF THE CAR.

"WE FINALLY GOT IT"

YOU FAILED.

----GAME OVER----
"""

CHOICES = """
    ----
    A. EAT A PIECE OF TOFU
    B. DRIVE AT A MODERATE SPEED
    C. DRIVE FULL THROTTLE
    D. STOP TO REFUEL (NO FOOD AVAILABLE)
    E. STATUS CHECK
    Q. QUIT
    ----
"""

def type_text_output(string):
    for char in textwrap.dedent(string):
        time.sleep(0.05)
        sys.stdout.write(char)
        sys.stdout.flush()

    time.sleep(1)

def main():
    type_text_output(INTRODUCTION)

    # CONSTANTS
    MAX_FUEL_LEVEL = 50
    MAX_DISTANCE_TRAVELLED = 100
    MAX_TOFU = 3
    MAX_HUNGER = 50
    STARTING_AGENTS_DISTANCE = -20

    # Variables
    done = False
    kms_travelled = 0
    agents_distance = STARTING_AGENTS_DISTANCE
    turns = 0
    tofu = MAX_TOFU
    fuel = MAX_FUEL_LEVEL
    hunger = 0

    #MAIN LOOP
    while not done:
        # Random events
        # FIDO - refills your food (5%)
        if tofu < 3 and random.random() < 0.05:
            # Refill tofu
            tofu = MAX_TOFU
            # Player feedback
            print("******** You look at your tofu container.")
            print("******** It is filled magically.")
            print("******** \"You're welcome\", says a small voice.")
            print("******** The dog used its magic tofu cooking skills.")
        # Check if reached END GAME
        # WIN - Travelled the distance required
        # Print win scenario
        if kms_travelled > MAX_DISTANCE_TRAVELLED:
            time.sleep(2)
            type_text_output(WIN)
            break

        # LOSE - by hunger > MAX_HUNGER (50)
        elif hunger > MAX_HUNGER:
            time.sleep(2)
            type_text_output(LOSE_HUNGER)
            break

        # LOSE - agents reach you
        elif agents_distance >= 0:
            time.sleep(2)
            type_text_output(LOSE_AGENTS)
            break

        # LOSE - no fuel
        elif fuel <= 0:
            time.sleep(2)
            type_text_output(LOSE_FUEL)
            break

        # Display hunger
        if hunger > 33:
            print("******** Your stomach rumbles, you need to eat something soon.")
            time.sleep(1)
        elif hunger > 20:
            print("******** Your hunger is small, but manageable.")
            time.sleep(1)

        # Display the user their choices
        print(CHOICES)

        user_choice = input("WHAT DO YOU WANT TO DO?\n").lower().strip("!?,.")

        if user_choice == "a":
            # Eat/Hunger
            if tofu > 0:
                tofu -= 1
                hunger = 0
                print()
                print("-------- Mmmmmmm, soybean goodness.")
                print("YOUR HUNGER IS SATED")
                print()
            else:
                print()
                print("-------- YOU DON'T HAVE ANY TOFU")
                print()

        elif user_choice == "b":
            # Moderate speed
            player_distance_now = random.randrange(4, 12)
            agents_distance_now = random.randrange(7, 15)

            # Burn fuel
            fuel -= random.randrange(3, 7)

            # Player distance travelled
            kms_travelled += player_distance_now

            # Agent distance travelled
            agents_distance -= player_distance_now - agents_distance_now

            # Feedback to player
            print()
            print(f"-------- YOU TRAVELED {player_distance_now} KM.")
            print()

        elif user_choice == "c":
            # FAST
            player_distance_now = random.randrange(9, 16)
            agents_distance_now = random.randrange(7, 15)

            # Burn fuel
            fuel -= random.randrange(7, 11)

            # Player distance travelled
            kms_travelled += player_distance_now

            # Agent distance travelled
            agents_distance -= player_distance_now - agents_distance_now

            # Feedback to player
            print()
            print("ZOOOOOOOOM")
            print(f"-------- YOU TRAVELED {player_distance_now} KM.")
            print()

        elif user_choice == "d":
            # Refueling
            # Fill up the fuel tank
            fuel = MAX_FUEL_LEVEL

            # Consider the agents coming closer
            agents_distance += random.randrange(7, 15)

            # Give player feedback
            print()
            print("-------- YOU FILLED THE FUEL TANK")
            print("-------- THE AGENTS GOT CLOSER...")
            print()

        elif user_choice == "e":
            # Display status of game
            print(f"\t---STATUS CHECK---")
            print(f"\tKM TRAVELLED: {kms_travelled}")
            print(f"\tFUEL REMAINING: {fuel} L")
            print(f"\tAGENTS ARE {abs(agents_distance)} KM BEHIND")
            print(f"\tYOU HAVE {tofu} TOFU LEFT")
            print(f"\t--------\n")

        elif user_choice == "q":
            done = True
        else:
            print("\tPlease select a valid input")

        # UPKEEP
        if user_choice in ["b", "c", "d"]:
            hunger += random.randrange(8, 18)
            turns += 1

        time.sleep(1.5)

    # Outro
    print()
    print(f"You finished the game in {turns} turns.")
    print("Thanks for playing. Hope to see you again soon")

if __name__ == "__main__":
    main()


#6개의 숫자를 뽑아 출력해주는 프로그램
import random

numbers = range(1, 46)
#마치 [1,2,3,...,45] 과 비슷하다

#alt + shift + 위 or 아래 방향키
#alt + 위 or 아래 방향키

lotto = random.sample(numbers, 6)   #sample() 중복되지않게 표본에서 지정 갯수만큼 표본 추출
print(sorted(lotto))    #자동정렬 sorted()


#  keras model is used in trainers.| after trainer added data
import pdb
import numpy as np
from matplotlib import pyplot as plt
from keras.initializers import Orthogonal
from keras.models import load_model
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Activation
from keras.layers import CuDNNLSTM
from keras.layers import CuDNNGRU
from keras.optimizers import Adam

#  autokeras:
from hyperopt import Trials, STATUS_OK, tpe
from hyperas import optim
from hyperas.distributions import choice, uniform, conditional

def data():
    # collectting data structure:
    x_train = np.load('data/fast_data/trainX.npy')
    y_train = np.load('data/fast_data/trainY.npy')
    x_test = np.load('data/fast_data/valX.npy')
    y_test = np.load('data/fast_data/valY.npy')
    #  look shape
    print('x_train shape: {}'.format(x_train.shape))
    print('x_test shape: {}'.format(x_test.shape))
    return x_train, y_train, x_test, y_test

def create_model(x_train, y_train, x_test, y_test):
    model = Sequential()
    init = {{choice([Orthogonal(), 'glorot_uniform'])}}
    drop_rate = {{choice([0, 0.1, 0.3])}}
    model.add(CuDNNGRU(32, input_shape=(self.config['time_step'], 3*self.config['m'],), return_sequences=True, \
              kernel_initializer=init))
    model.add(CuDNNGRU(64, return_sequences=True, kernel_initializer=init, dropout=drop_rate))
    model.add(CuDNNGRU(64, return_sequences=True, kernel_initializer=init, dropout=drop_rate))
    model.add(CuDNNGRU(64, return_sequences=True, kernel_initializer=init, dropout=drop_rate))
    model.add(CuDNNGRU(32, return_sequences=True, kernel_initializer=init, dropout=drop_rate))
    model.add(CuDNNGRU(1, return_sequences=True, kernel_initializer=init))
    #  define learning structure
    adam = Adam(lr={{choice([1e-1, 1e-2, 1e-3, 1e-4, 1e-5])}})
    model.compile(loss={{choice(['mae', 'mse'])}}, metrics=['mae'], optimizer=adam)
    #  find best structure in 100 epochs
    model.fit(x_train, y_train, batch_size={{choice([32, 64, 128])}}, epochs=1, verbose=2, validation_data=(x_test, y_test))
    score, acc = model.evaluate(x_test, y_test, verbose=0)
    print('Test accuracy:', acc)
    return {'loss': -acc, 'status': STATUS_OK, 'model': model}

if __name__ == '__main__':
    best_run, best_model = optim.minimize(model=create_model, \
                                        data=data, \
                                        algo=tpe.suggest, \
                                        max_evals=5,\
                                        trials=Trials(),\
                                        notebook_name='simple_notebook')

    X_train, Y_train, X_test, Y_test = data()
    print("Evalutation of best performing model:")
    print(best_model.evaluate(X_test, Y_test))
    print("Best performing model chosen hyper-parameters:")
    print(best_run)


#!/usr/bin/env python3
#
# -----------------------------------------------------------------------------
# Copyright (c) 2018, Battelle National Biodefense Institute.
#
# This file is part of MicroHapulator (github.com/bioforensics/microhapulator)
# and is licensed under the BSD license: see LICENSE.txt.
# -----------------------------------------------------------------------------

from setuptools import setup
import versioneer

with open('README.md', 'r') as infile:
    longdesc = infile.read()

setup(
    name='microhapulator',
    version=versioneer.get_version(),
    cmdclass=versioneer.get_cmdclass(),
    description='Software package for simulating and analyzing microhaplotype sequence data',
    long_description=longdesc,
    long_description_content_type='text/markdown',
    url='https://github.com/bioforensics/microhapulator',
    author='Daniel Standage',
    author_email='daniel.standage@nbacc.dhs.gov',
    packages=['microhapulator', 'microhapulator.cli', 'microhapulator.tests'],
    package_data={
        'microhapulator': [
            'microhapulator/data/*', 'microhapulator/tests/data/*',
            'microhapulator/tests/data/*/*'
        ]
    },
    include_package_data=True,
    install_requires=['insilicoseq', 'numpy', 'microhapdb', 'happer', 'jsonschema'],
    entry_points={
        'console_scripts': ['mhpl8r = microhapulator.__main__:main']
    },
    classifiers=[
        'Environment :: Console',
        'Framework :: IPython',
        'Framework :: Jupyter',
        'Intended Audience :: Science/Research',
        'Intended Audience :: Legal Industry',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python :: 3',
        'Topic :: Scientific/Engineering :: Bio-Informatics',
    ],
    zip_safe=True,
)


import pygame, sys, random
from pygame.locals import *
import os

pygame.init()

pygame.display.set_caption("rain")
screen = pygame.display.set_mode((1000, 600))

clock = pygame.time.Clock()

raindrop_spawn_time = 0

current_path = os.path.dirname(__file__) # Where your .py file is located
image_path = os.path.join(current_path, 'images') # The image folder path

person_umbrella = pygame.image.load(os.path.join(image_path, 'umbrella.png'))
cloud = pygame.image.load(os.path.join(image_path, 'cloud.png'))

class Raindrop :
    def __init__(self,x,y) :
        self.x = x
        self.y = y
        self.speed = random.randint(5,10)

    def move(self) :
        self.y += self.speed

    def draw(self) :
        pygame.draw.line(screen, (0,0,0), (self.x,self.y), (self.x, self.y+15), 1)
        #pygame.draw.line(screen, (153,255,204), (self.x,self.y), (self.x, self.y+15), 2)

    def off_screen(self) :
        return self.y > 800

class Person :
    def __init__(self) :
        self.x = 300
        self.y = 400

    def draw(self) :
        screen.blit(person_umbrella, (self.x, self.y))

    def hit_by(self,raindrop) :
        return pygame.Rect(self.x, self.y, 200,200).collidepoint((raindrop.x, raindrop.y))

class Cloud :
    def __init__(self,x, y) :
        self.x = x
        self.y = y

    def draw(self) :
        screen.blit(cloud, (self.x, self.y))

    def rain(self) :
        raindrops.append(Raindrop(random.randint(self.x+50, self.x+175), self.y+150))

raindrops = list()
person = Person()
clouds = Cloud(500,25) # 구름 객체 생성 (위치 좌표 x, y)

while 1 :
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT :
            sys.exit()

    screen.fill((255,255,255))
    #screen.fill((125,125,125))
    person.draw()
    clouds.draw()
    clouds.rain()

    i = 0
    while i < len(raindrops) :
        raindrops[i].move()
        raindrops[i].draw()
        if raindrops[i].off_screen() or person.hit_by(raindrops[i]):
            del raindrops[i]
            i -= 1
        i += 1

    pygame.display.update()


import msg_gen
from datetime import datetime
import twilio_tools
import time
import app

'''
Run once when server up

def schedule_the_message_send_scheduler(scheduler):
    pass
'''

'''
Need to schedule this for every day, and w user setting call every time user changes or adds a settings

Run on new usersetting whenever one is added or changed
Run on all usersettings every day

Takes in the db's us

Return new lask_worked_mgroups string
'''
def schedule_message_sends(scheduler, usersettingsarr):
    print(usersettingsarr)

    nums = []
    new_worked_mgroups_arr = []

    for usersettings in usersettingsarr:
        print(usersettings.last_worked_mgroups)
        msg, new_worked_mgroups = msg_gen.workout(usersettings.last_worked_mgroups,usersettings.difficulty,usersettings.goal)

        num = usersettings.phone_number
        time = usersettings.time

        #time = [h1, h2, m1, m2]

        hour = str(time[0]) + str(time[1])
        minute = str(time[3]) + str(time[4])

        print("\n---Scheduling text to be sent:---\n Num: {}\n Message: {}\nHour: {}\nMinute: {}\n".format(num, msg, hour, minute))

        jobs = scheduler.get_jobs()
        scheduled_numbers = []
        for job in jobs:
            scheduled_numbers.append(job.id)

        if num in scheduled_numbers:
            scheduler.remove_job(num)

        scheduler.add_job(func=lambda: twilio_tools.send_message(msg, num), \
            trigger="date", id=num, run_date=datetime(int(datetime.now().year), int(datetime.now().month), int(datetime.now().day), int(hour), int(minute), 0))

        #app.update_worked_mgroups(num, new_worked_mgroups)
        nums.append(num)
        new_worked_mgroups_arr.append(new_worked_mgroups)
    return nums, new_worked_mgroups_arr

    #return new_worked_mgroups


import MeCab
import matplotlib.pyplot as plt
#from normalize_neologd import normalize_neologd as normalize
from collections import OrderedDict

tag = "-Ochasen -d /usr/local/lib/mecab/dic/mecab-ipadic-neologd/"
mt = MeCab.Tagger(tag)
mt.parse('')

class Tokens():
    def __init__(self, ctx):
        self.__tokens = []
        node = mt.parseToNode(ctx)
        while node:
            if node.surface is not '':
                features = node.feature.split(',')
                if features[-2] == '*':
                    features[-2] = node.surface
                token = [node.surface, features[-2]]
                self.__tokens.append(token)
            node = node.next

    def tokens(self):
        return self.__tokens

    def size(self):
        return len(self.__tokens)

    def create_ngram(self, n):
        words = [token[0] for token in self.__tokens]
        pronounces = [token[1] for token in self.__tokens]

        w = [''.join(words[i:i+n]) for i in range(self.size() - n + 1)]
        p = [''.join(pronounces[i:i+n]) for i in range(self.size() - n + 1)]
        return w, p

    def create_bigram(self):
        return self.create_ngram(2)

def sorted_ngram(words, pronounces):
    words.sort()
    pronounces.sort()
    wDict = {}
    pDict = {}
    for w, p in zip(words, pronounces):
        if w in wDict:
            wDict[w] += 1
            pDict[w] += 1
        else:
            wDict[w] = 1
            pDict[w] = 1
    wDict = OrderedDict(
        sorted(wDict.items(), key=lambda x:x[1], reverse=True))
    pDict = OrderedDict(
        sorted(pDict.items(), key=lambda x:x[1], reverse=True))
    wDict = [[key, value] for key, value in wDict.items()]
    pDict = [[key, value] for key, value in pDict.items()]
    return wDict, pDict

def findSameFreq(ngram, s):
    ans = []
    thisFreq = 2147483647
    for key, value in ngram:
        tmp = thisFreq
        if value < thisFreq:
            thisFreq = value
        if thisFreq == tmp:
            continue
        if thisFreq <= 3:
            break
        sameFreq = [key for key, value in ngram if value == thisFreq]
        if len(sameFreq) == 1:
            continue
        try: pos = [[s.index(word), len(word)] for word in sameFreq]
        except: pass
        pos.sort()
        splited = []
        start = pos[0][0]
        end = 0
        length = len(pos)
        for i in range(1, length):
            if sum(pos[i - 1]) > pos[i][0] and i != length - 1:
                continue
            else:
                end = sum(pos[i - 1])
                splited.append([start, end])
                start = pos[i][0]
                if i == length - 1:
                    end = sum(pos[i])
                    splited.append([start, end])
        for start, end in splited:
            ans.append(s[start:end])
    return ans

def show(words, num = 20):
    num = min(len(words), num)
    words = words[:num]
    x = range(len(words))
    plt.bar(x, [row[1] for row in words], align='center')
    plt.xticks(x, [row[0] for row in words])
    plt.show()

def makeTokens(s):
    return Tokens(s)

if __name__ == '__main__':
    s = ''
    rep1 = '私と契約して、魔法少女になってよ！'
    rep2 = 'ノード繊毛'
    for i in range(10):
        s += str(i) + rep1
    for i in range(10, 20):
        s += str(i) + rep2
    f = open('./text.txt', 'r')
    s = f.read()
    f.close()
    #print(mt.parse(s))
    tokens = makeTokens(s)
    words, pronounces = tokens.create_bigram()
    w, p = sorted_ngram(words, pronounces)
    #show(w)
    print()
    print(findSameFreq(w, s))


import numpy as np
import pandas as pd

def obtener_krw(swi, sor, n):
    sw = np.linspace(swi, 1 - sor, n)
    swd = (sw - swi) / (1 - swi - sor)
    krw = swd ** 4
    matriz_krw = np.array([sw, krw])
    dataframe1 = pd.DataFrame(matriz_krw)
    dataframe1 =dataframe1.T
    print(dataframe1)
    return krw

#print(obtener_krw(0.363, 0.205, 20))


import arcpy

# Create insert cursor for table
#
rows = arcpy.InsertCursor("D:/St_Johns/data.gdb/roads_lut")
x = 1

# Create 25 new rows. Set the initial row ID and distance values
#
while x <= 25:
    row = rows.newRow()
    row.rowid = x
    row.distance = 100
    rows.insertRow(row)
    x += 1

# Delete cursor and row objects to remove locks on the data
#
del row
del rows


#!/usr/bin/python3
"""
This module contains the Student class
"""

class Student:
    """
    Defines the cllass student
    """

    def __init__(self, first_name, last_name, age):
        """
        This is the instantiation of the class
        """
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def to_json(self, attrs=None):
        """
        returns the dict or a specified dict
        """
        if attrs is not None:
            n = {key: self.__dict__[key]
                 for key in attrs if hasattr(self, key)}
        else:
            n = self.__dict__
        return n


import os
import sys
from there_application import which

def virtualenv(project):
    print('\033[92m Creamos el virtuaalenv\033[0m')
    comando = 'su '+project+' -l -c \'virtualenv VirtualEnv\''
    os.system(comando)

def virtualenv_check():
    print('\033[92m Comprobando si esta instalado VIRTUALENV\033[0m')
    if which('virtualenv') == None:
        print('\033[91m  *  Virtualenv no esta instalado. Instalalo para poder seguir\033[0m')
        sys.exit(0)
    else:
        print('\033[92m  * Virtualenv esta instalado\033[0m')


import cv2
import numpy as np
import math

def contour(image):
    # 사진 사이즈 조정

    a = 0

    def Resizing(img):
        width = 500
        ratio = width / img.shape[1]  # width * 사진 너비 = 비율
        height = int(ratio * img.shape[0])  # 비율 * 사진 높이
        # 비율 유지한 채로 이미지 Resize
        resize = cv2.resize(img, dsize=(width, height), interpolation=cv2.INTER_AREA)
        print(resize.shape)

        return resize

    # 창 이름 설정

    # cv2.namedWindow('image')

    # 이미지 파일 읽기
    base = cv2.imread(image, cv2.IMREAD_COLOR)
    rotImg = cv2.rotate(base, cv2.ROTATE_90_CLOCKWISE)

    # 이미지 사이즈 조정

    img = Resizing(rotImg)

    # 이미지 hsv 색 변경

    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    # 피부색 범위 검출

    img_hsv = cv2.fastNlMeansDenoisingColored(img_hsv, None, 10, 10, 7, 21)  # 노이즈제거

    lower = np.array([0, 50, 80], dtype="uint8")  # 최소 범위
    upper = np.array([70, 255, 255], dtype="uint8")  # 최대 범위

    img_hand = cv2.inRange(img_hsv, lower, upper)  # 범위 내 이미지 추출

    # 손 가장자리 외각선 찾기

    contours, hierarchy = cv2.findContours(img_hand, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

    max = 0

    maxctr = None
    for cnt in contours:

        area = cv2.contourArea(cnt)

        if (max < area):
            max = area

            maxctr = cnt  # 손 가장자리 배열

    # 흰색으로 손 내부 다시 칠하기

    mask = np.zeros(img.shape).astype(img.dtype)

    color = [255, 255, 255]

    img_hand = cv2.fillPoly(mask, [maxctr], color)

    # 손 외각선 그리기

    cv2.drawContours(img_hand, [maxctr], 0, (0, 0, 255), 3)

    # 중심점
    img_gray = cv2.cvtColor(img_hand, cv2.COLOR_BGR2GRAY)
    img_dist = cv2.fillPoly(mask, [maxctr], color)
    dist = cv2.distanceTransform(img_gray, cv2.DIST_L2, 5)
    dist_max = np.argmax(dist)
    # contour_max=np.argmax(contours)
    maxY, maxX = divmod(dist_max, 500)
    # conY,conX=divmod(contour_max,400)
    result = cv2.normalize(dist, None, 255, 0, cv2.NORM_MINMAX, cv2.CV_8UC1)
    cv2.circle(img_hand, (maxX, maxY), 3, (0, 0, 255), -1)
    #cv2.imwrite('contour.png', img_hand)
    # 손목찾기
    corners = cv2.goodFeaturesToTrack(img_gray, 500, 0.01, 8)
    rightX = 600
    rightY = maxY
    leftY = maxY
    leftX = 0
    while a < 50:
        for i in corners:
            x, y = i.ravel()
            if y > maxY:
                if rightY - y < 0 and rightY - y > -20 and x > maxX and rightX > x:
                    rightX = x
                    rightY = y
        a = a + 1
    a = 0
    while a < 50:
        for i in corners:
            x, y = i.ravel()
            if y > maxY:
                if leftY - y < 0 and leftY - y > -30 and x < maxX and leftY < rightY + 5:
                    leftX = x
                    leftY = y
        a = a + 1
    cv2.imwrite('contour2.png', img_hand)
    # 손끝 중심
    corners = cv2.goodFeaturesToTrack(img_gray, 10, 0.01, 10)
    for i in corners:
        x, y = i.ravel()
        if y > maxY:
            if rightY - y < 0 and x > maxX:
                rhandX = x
                rhandY = y
    for i in corners:
        x, y = i.ravel()
        if y > maxY:
            if rightY - y < 0 and x < maxX:
                lhandX = x
                lhandY = y

    # 손끝 중심

    #exitX = int((rhandX + lhandX) / 2)
    #exitY = int((rhandY + lhandY) / 2)
    # 손목 중심
    wristX = int((rightX + leftX) / 2)
    wristY = int((rightY + leftY) / 2)

    #cv2.circle(img_hand, (rightX, rightY), 3, (255, 0, 0), -1)
    #cv2.circle(img_hand, (leftX, leftY), 3, (255, 0, 0), -1)
    #cv2.circle(img_hand, (rhandX, rhandY), 3, (0, 255, 0), -1)
    #cv2.circle(img_hand, (lhandX, lhandY), 3, (0, 255, 0), -1)
    #cv2.circle(img_hand, (wristX, wristY), 3, (0, 0, 255), -1)
    #cv2.circle(img_hand, (exitX, exitY), 3, (0, 0, 255), -1)

    print('손 중심점:', (maxX, maxY))
    print('손목 중심점:', (wristX, wristY))
    #print('손끝 중심점:', (rightX, rightY))

    x1 = maxX - wristX
    y1 = maxY - wristY
    x2 = rightX - wristX
    y2 = rightY - wristY
    angle = math.atan2(y1 * x2 - x1 * y2, x1 * x2 + y1 * y2) * 180 / math.pi
    angle = abs(angle)
    if angle > 90:
        angle = angle-90
    else:
        angle=90-angle
    angle = round(angle)
    print('각도:', angle)

    # 이미지 보여주기
    cv2.imwrite('contour.png', img_hand)
    cv2.imwrite('hsv2.png', img_hsv)
    '''
    cv2.imshow('gray', img_dist)
    cv2.imshow('main', img_hand)
    cv2.imshow('distance', result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    '''

    return img_hand, angle


"""
An RDFLib ConjunctiveGraph is an (unnamed) aggregation of all the named graphs
within a Store. The :meth:`~rdflib.graph.ConjunctiveGraph.get_context`
method can be used to get a particular named graph for use such as to add
triples to, or the default graph can be used

This example shows how to create named graphs and work with the
conjunction (union) of all the graphs.
"""

from rdflib import Namespace, Literal, URIRef
from rdflib.graph import Graph, ConjunctiveGraph
from rdflib.plugins.stores.memory import Memory

if __name__ == "__main__":

    ns = Namespace("http://love.com#")

    mary = URIRef("http://love.com/lovers/mary")
    john = URIRef("http://love.com/lovers/john")

    cmary = URIRef("http://love.com/lovers/mary")
    cjohn = URIRef("http://love.com/lovers/john")

    store = Memory()

    g = ConjunctiveGraph(store=store)
    g.bind("love", ns)

    # add a graph for Mary's facts to the Conjunctive Graph
    gmary = Graph(store=store, identifier=cmary)
    # Mary's graph only contains the URI of the person she love, not his cute name
    gmary.add((mary, ns["hasName"], Literal("Mary")))
    gmary.add((mary, ns["loves"], john))

    # add a graph for John's facts to the Conjunctive Graph
    gjohn = Graph(store=store, identifier=cjohn)
    # John's graph contains his cute name
    gjohn.add((john, ns["hasCuteName"], Literal("Johnny Boy")))

    # enumerate contexts
    for c in g.contexts():
        print("-- %s " % c)

    # separate graphs
    print(gjohn.serialize(format="n3").decode("utf-8"))
    print("===================")
    print(gmary.serialize(format="n3").decode("utf-8"))
    print("===================")

    # full graph
    print(g.serialize(format="n3").decode("utf-8"))

    # query the conjunction of all graphs
    xx = None
    for x in g[mary : ns.loves / ns.hasCuteName]:
        xx = x
    print("Q: Who does Mary love?")
    print("A: Mary loves {}".format(xx))


#    Copyright 2015 Mirantis, Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import logging
import sys

from cliff import command

import url_access_checker.api as api
import url_access_checker.errors as errors
from url_access_checker.network import manage_network

LOG = logging.getLogger(__name__)

class CheckUrls(command.Command):
    """Check if it is possible to retrieve urls."""
    def get_parser(self, prog_name):
        parser = super(CheckUrls, self).get_parser(prog_name)
        parser.add_argument('urls', type=str, nargs='+',
                            help='List of urls to check')
        return parser

    def take_action(self, parsed_args):
        LOG.info('Starting url access check for {0}'.format(parsed_args.urls))
        try:
            api.check_urls(parsed_args.urls)
        except errors.UrlNotAvailable as e:
            sys.stdout.write(str(e))
            raise e

class CheckUrlsWithSetup(CheckUrls):

    def get_parser(self, prog_name):
        parser = super(CheckUrlsWithSetup, self).get_parser(
            prog_name)
        parser.add_argument('-i', type=str, help='Interface', required=True)
        parser.add_argument('-a', type=str, help='Addr/Mask pair',
                            required=True)
        parser.add_argument('-g', type=str, required=True,
                            help='Gateway to be used as default')
        parser.add_argument('--vlan', type=int, help='Vlan tag')
        return parser

    def take_action(self, pa):
        with manage_network(pa.i, pa.a, pa.g, pa.vlan):
            return super(
                CheckUrlsWithSetup, self).take_action(pa)


import discord
import os
from discord.ext import commands
#from utils import checks, output
from aiohttp import ClientSession
import urllib.request
import json

class Pricing:
    def __init__(self, bot: discord.ext.commands.Bot):
        self.bot = bot

    @commands.command()
    async def price(self, amount=1):
        """
        PHRの価格情報を確認
        """
        try:
            async with ClientSession() as session:
                async with session.get("https://api.coinmarketcap.com/v1/ticker/phore/?convert=JPY") as response:
                    responseRaw = await response.read()
                    priceData = json.loads(responseRaw)[0]
                    embed = discord.Embed(colour=0x00FF00)
                    embed.add_field(
                        name="順位", value="{} 位".format(priceData["rank"]))
                    embed.add_field(name="価格(BTC)", value="{} BTC".format(
                        priceData["price_btc"]))
                    embed.add_field(name="価格(JPY)", value="{} JPY".format(
                        priceData["price_jpy"]))
                    embed.add_field(name="流通枚数", value="{} PHR".format(
                        (priceData["available_supply"])))
                    await self.bot.say(embed=embed)
        except:
            await self.bot.say(":エラー: 価格情報の取得に失敗しました!")

def setup(bot):
    bot.add_cog(Pricing(bot))


# 資料︰程式的基本單位
# terminal輸入cls可清空畫面

# 數字
3456 # 整數
3.5 # 浮點數(小數)

# 字串
"測試中文"
"Hello World"

# 布林值
True
False

# 有順序、可動的列表 List
[3,4,5]
["Hello","World"]

# 有順序、不可動的列表 Tuple
(3,4,5)
("Hello","World")

# 集合 Set (unOrder)
{3,4,5}
{"Hello World"}

# 字典 Dictionary
{"apple":"蘋果","data":"資料"}

# 變數︰用來儲存資料的自訂名稱
# 變數名稱=資料
x=3

# print(資料)
print(x)
x=True # 取代舊的資料
print(x)
x="Hello"
print(x)


from .exceptions import *

# internal helpers
def _position_is_empty_in_board(position, board):
    x,y = position
    return board[x][y] == '-'

def _position_is_valid(position):
    if not isinstance(position, tuple):
        return False
    if len(position) > 2:
        return False
    for dimension in position:
        if (dimension < 0) or (dimension > 2):
            return False
    return True

def _board_is_full(board): #Kenneth
    return not any('-' in row for row in board)

def _is_winning_combination(board, combination, player):
    players_comb = [board[x][y] for (x,y) in combination]
    return [player] * 3 == players_comb

def _check_winning_combinations(board, player):

    for i in range(2):
        # horizontal check
        for line in board:#range(len(board)):
            if line == [player] * 3:
                return player
        # transposing the board allows us to check the columns as rows.
        # before the loop ends, the board returns to its original state.
        board = list(map(list, zip(*board)))

    #Check diagonals
    length = len(board)
    diag_1 = [board[i][i] for i in range(length)] # top-left to bottom right
    diag_2 = [board[i][-i-1] for i in range(length)] # top right to bottom left
    diagonals = [diag_1,diag_2]

    if [player] * 3 in diagonals:
        return player
    else:
        return None

# public interface
def start_new_game(player1="X", player2="O"):
    #initializes a new game, with player1 as the starting player

    return {
        'player1': player1,
        'player2': player2,
        'board': [
                ['-','-','-'],
                ['-','-','-'],
                ['-','-','-']
            ],
        'next_turn': player1,
        'winner': None
    }

def get_winner(game):
    return game['winner']

def update_game(game,position):

    # update the board
    x, y = position
    player = game['next_turn']
    game['board'][x][y] = player

    # update the next player
    if player == game['player1']:
        game['next_turn'] = game['player2']
    else:
        game['next_turn'] = game['player1']

def move(game, player, position):

    # check if the game is over and if the player should move
    if not get_next_turn(game): # if it's no player's next turn, game's over
        raise InvalidMovement("Game is over.")
    elif get_next_turn(game) != player:
        raise InvalidMovement('\"'+get_next_turn(game)+'\"' + " moves next")

    #check if the position is valid
    if not _position_is_valid(position):
        raise InvalidMovement('Position out of range.')

    #check if the position is already taken
    if not _position_is_empty_in_board(position,game['board']):
        raise InvalidMovement('Position already taken.')

    update_game(game,position)

    # check if the player won
    if _check_winning_combinations(game['board'],player):
        game['winner'] = player
        game['next_turn'] = None
        raise GameOver('\"'+player+'\"'+' wins!')

    # or if they tied
    elif _board_is_full(game['board']):
        game['next_turn'] = None
        raise GameOver("Game is tied!")

def get_board_as_string(game):
    as_string = "\n"
    for i, line in enumerate(game['board']):
        for j,element in enumerate(line):
            as_string += element
            if j < 2:
                as_string += "  |  "
        if i < 2:
            as_string += "\n--------------\n"
    as_string += "\n"

    return as_string

def get_next_turn(game):
    # returns the player for next turn if there hasn't been a winner yet
    if get_winner(game):
        return None
    else:
        return game['next_turn']


from Jumpscale import j

class TokenCreator:
    def __init__(self, simulation, environment):
        self.simulation = simulation
        self.environment = environment
        self.sheet = j.data.worksheets.sheet_new("tokencreator", nrcols=120)

    def farming_cpr_tft(self,month):
        """
        cpr is the cloud production rate, like a hashrate for a bitcoin miner
        in our case a production rate of capacity for the internet

        cost to buy 1 cpr production capability in Q1 2020 = 40USD
        we took as definition that nr for cpr to usd
        we say ROI for batch 1 (month 1) is 6 months, thats why we need to devide by 6

        ROI = Return on investment
        """

        cpr_investment_cost_in_usd_month = j.tools.tfgrid_simulator.simulator_config.tokenomics.cpr_investment_usd / 6
        cpr_investment_cost_in_tft_month = cpr_investment_cost_in_usd_month / self.simulation.tft_price_get(month)
        return cpr_investment_cost_in_tft_month

    def tft_farm(self, month, nodes_batch):
        """
        calculate the farming of tft's
        """
        tft_new = nodes_batch.cpr * self.farming_cpr_tft(month) / self.difficulty_level_get(month)

        return tft_new

    def difficulty_level_get(self, month):
        """
        return difficulty in relation to how many token there are
        the difficulty factor makes sure that there can never be more than 4 billion tokens
        """

        if month == 0:
            nr_of_tft_ever_farmed = 800000000 #starting point
        else:
            nr_of_tft_ever_farmed = int(self.simulation.tft_total(month - 1)) #look at previous month

        p = nr_of_tft_ever_farmed / 4000000000
        if p > 0.999999:
            perc = 1000000
        else:
            perc = 1 / (1 - p)

        return perc

    def tft_cultivate(self, month, nodes_batch):
        """
        calculate the nr of TFT cultivated for the full batch
        cultivation means selling of capacity which results in TFT income for farmer
        """
        tftprice_now = self.simulation.tft_price_get(month)
        revenue_usd = nodes_batch.revenue_get(month)
        return revenue_usd / tftprice_now * 0.9

    def tft_burn(self, month, nodes_batch):
        """
        burning is no part of the chosen tokenomics model
        """
        return 0


import requests
from bs4 import BeautifulSoup

user_budget = int(input("Enter your budget: "))

content = requests.get("https://www.johnlewis.com/browse/home-garden/plants-planting/pots-planters/_/N-5urc").content
soup = BeautifulSoup(content, features="html.parser")
element = soup.find("span", {"class": "product-card__price-span", "data-test": "product-card__price product-card__price--current"})
price = element.text.strip()
price_no_currency = price[1:]
price_float = float(price_no_currency)
if price_float > user_budget:
    print("The price of this item is more than your budget")
else:
    print("You can afford this item")


import argparse
from VsbAnalyzer import VsbAnalyzer
parser = argparse.ArgumentParser()
parser.add_argument("vsbFilePath", help=".vsb File path")
parser.add_argument("-u", "--up", help="Upper boundary index for print", type=int)
parser.add_argument("-b", "--bottom", help="Bottom boundary index for print", type=int)
parser.add_argument("-v", "--verbose", help="Verbose mode for more print", action="store_true")
parser.add_argument("--pcap", help="Generate pcap", action="store_true")
parser.add_argument("--gmlanonly", help="Output GMLAN msg only, excluding Ethernet", action="store_true")
parser.add_argument("--ethonly", help="TBD : Output Ethernet only, excluding GMLAN", action="store_true")
parser.add_argument("--fsaonly", help="TBD : Output FSA only, excluding GMLAN & Eth Frame", action="store_true")

args = parser.parse_args()
print("verbose val : {}".format(args.verbose))
vsbAzer = VsbAnalyzer.VsbAnalyzer(args.vsbFilePath, prt_btm = args.bottom, prt_up = args.up, \
            b_pcap = args.pcap, b_verbose = args.verbose, b_gmlanonly = args.gmlanonly)
vsbAzer.parseMsg()
vsbAzer.printDataAsFile()

print(args.vsbFilePath + " analyze complete : Total {} msg found - Among them, {} has EDP".\
        format(vsbAzer.msgCnt, vsbAzer.edpMsgCnt))


import os
import tifffile
import numpy as np
import torch
import torch.utils.data as da

# from torchvision import datasets, transforms
# import random

def dynamic_binary_value_cuda_2_one(data,zoom1,zoom2):
    data_tem = np.copy(data)
    data_tem = torch.from_numpy(data_tem)
    num = torch.tensor(64*64*32)
    # ave = torch.tensor(data.shape[0])
    #获得每一个样本灰度值的平均值×zoom
    tem = torch.flatten(data_tem)
    tem = torch.sum(tem)

    # print(tem.shape)
    zoom1 = torch.tensor(zoom1, dtype=torch.float)
    ave = tem/num*zoom1
    ave = np.array(ave,dtype='uint8')
    ave = torch.from_numpy(ave)
    kk = torch.zeros_like(data_tem)

    data_tem = torch.where(data_tem < ave, kk, data_tem)

    sum_num = torch.sum(data_tem>ave)

    #获得每一个样本灰度值的平均值×zoom
    tem = torch.flatten(data_tem)
    tem = torch.sum(tem)

    zoom2 = torch.tensor(zoom2,dtype=torch.float)
    ave2 = tem/sum_num *zoom2
    ave2 = np.array(ave2,dtype='uint8')
    ave2 = torch.from_numpy(ave2)

    # data_tem = torch.where(data_tem < ave, kk, data_tem)

    # data_tem = data_tem.numpy()

    return ave2

def omit_background(data_ori, threshold):

    for i in range(data_ori.shape[0]):
        data_ori[i] = np.where(data_ori[i] < threshold[i], 0, data_ori[i])

    return data_ori

# dir structure would be: data/class_name(0 and 1)/dir_containing_img/img
class GetSample(da.Dataset):
    def __init__(self, root = '/disk1/001yangbin/002vaa3d_img_samples/data agumentation/outimg_good_block_agumentation_0/', mode = 'train', transform = None):
        self.root = root
        self.mode = mode
        # self.raw_samples = glob.glob(root+ '*')
        self.raw_samples = os.listdir(root)
        # 排序
        self.raw_samples.sort(key=lambda x: int(x[0:8]))
        # print(self.raw_samples)
        self.samples = []
        for raw_sample in self.raw_samples:
            self.samples.append((raw_sample, int(raw_sample.split('l')[1].split('.')[0])))
            # print(raw_sample,int(raw_sample.split('/')[-2]))
        # print(self.samples)

    def __len__(self):
        return len(self.samples)

    def __getitem__(self, index):
        # if self.mode == 'train':
        #     random.shuffle(self.samples)
        # print(index)
        image_name, label = self.samples[index]

        image_dir = self.root + image_name

        image = tifffile.imread(image_dir)
        # threshold_ave = dynamic_binary_value_cuda_2_one(image, 1.0, 0.7)
        # image = omit_background(image, threshold_ave)
        # top_k = 30
        # image = segmentation_block_order(image, threshold_ave, top_k)

        if(label != 0):
            label = 1

        return (image, label,image_name)

# ###test
# data_path_train = "/disk1/001yangbin/002vaa3d_img_samples/data agumentation/outimg_good_block_agumentation_0/"
# data_path_test = "/disk1/001yangbin/002vaa3d_img_samples/data agumentation/test_image/"
#
# # data = PatchMethod(root = data_path_train)
# val_data =PatchMethod(root = data_path_test, mode = 'test')
# # train_loader = torch.utils.data.DataLoader(data, shuffle = True, num_workers = 6, batch_size = 1)
# test_loader = torch.utils.data.DataLoader(val_data, shuffle = False, num_workers = 6, batch_size = 1)
#
# import time
# start_time = time.time()
# count = 0
# for batch_idx, (train_data, train_label) in enumerate(test_loader):
#
#     bag_label = train_label[0]
#     count +=1
# print("spend time:",time.time()-start_time, count)


import hashlib

# b = bitestring, strips metadata away
# ending with '.encode()' does the same thing

key = b'str'
my_string = 'this is a normal string. Nothing to see here'

for i in range(10):
    hashed = hashlib.sha256(key).hexdigest()
    print(hashed)

for i in range(10):
    hashed = hash(key)
    print(hashed % 8)


import datetime
import json
import threading
from time import sleep
import multiprocessing
import config
import re
import time
import redis
import html as HT
from lxml import etree
from lxml.etree import HTML
from download import Download
from db import MongoClient, MysqlClient, RedisClient

SHI_URL = 'https://www.zhipin.com/{shi_id}/'
QU_URL = 'https://www.zhipin.com/{shi_id}/{qu_id}/?ka=sel-business-1'
POSITION_URL = 'https://www.zhipin.com/c{pid}-p{zhiwei_id}/{zhen_id}/?page={pageToken}&sort=2&ka=page-{pageToken}'
NEW_POSITION_URL = 'https://www.zhipin.com/c{pid}-p{zhiwei_id}/?page={pageToken}&sort=2&ka=page-{pageToken}'

class Scheduler(object):
    def __init__(self):
        self.download = Download()
        self.db = MysqlClient()
        self.redisClient = RedisClient()

    def run(self):
        #self.get_qu()
        #self.get_zhen()
        # self.push_url_to_redis()
        self.get_position()

    def get_qu(self):
        sql = 'select * from shi'
        results = self.db.find_all(sql)
        for res in results:
            shi_id = res[2]
            url = SHI_URL.format(shi_id='c'+shi_id)
            print(url)
            html = self.download.get_html(url)
            if html.status_code == 200 and html is not None:
                html = HTML(html.text)
                qu_id_list = html.xpath('//dl[@class="condition-district show-condition-district"]/dd/a/@href')
                qu_name_list = html.xpath('//dl[@class="condition-district show-condition-district"]/dd/a/text()')
                for qu_id, name in zip(qu_id_list[1:], qu_name_list[1:]):
                    qu_id = qu_id.split('/')
                    qu_id = qu_id[2]
                    sql = '''insert into qu(pid,qu_id,name) VALUES ('{pid}','{qu_id}','{name}')'''\
                        .format(pid=shi_id,qu_id=qu_id, name=name)
                    print(sql)
                    self.db.save(sql)
            else:
                print('该url无数据')

    def get_zhen(self):
        sql = 'select * from qu'
        results = self.db.find_all(sql)
        for res in results:
            shi_id = res[1]
            qu_id = res[2]
            url = QU_URL.format(shi_id='c'+shi_id, qu_id=qu_id)
            print(url)
            html = self.download.get_html(url)
            if html is not None and html.status_code == 200:
                html = HTML(html.text)
                zhen_id_list = html.xpath('//dl[@class="condition-area show-condition-area"]/dd/a/@href')
                zhen_name_list = html.xpath('//dl[@class="condition-area show-condition-area"]/dd/a/text()')
                for zhen_id, name in zip(zhen_id_list[1:], zhen_name_list[1:]):
                    zhen_id = zhen_id.split('/')
                    zhen_id = zhen_id[2]
                    sql = '''insert into zhen(pid,qu_id, zhen_id,name) VALUES ('{pid}','{qu_id}','{zhen_id}','{name}')'''\
                        .format(pid=shi_id,qu_id=qu_id,zhen_id=zhen_id, name=name)
                    print(sql)
                    self.db.save(sql)
            else:
                print('该url无数据')

    def get_position(self):
        redis_results = self.redisClient.pop('employment')
        try:
            json_obj = json.loads(redis_results[1].decode('utf8'))
        except:
            return None

        if json_obj:
            flag = True
            pageToken = 1

            #处理翻页问题
            while flag:
                detail_url_list = []
                url = json_obj['url']
                pre_page = re.search('\/\?page=(.*?)&', url).group(1)
                if int(pageToken) > 10:
                    break
                url = url.replace('page='+pre_page+'&sort=2&ka=page-'+pre_page, 'page=' + str(pageToken) + '&sort=2&ka=page-' + str(pageToken))
                cityId = json_obj['cityId']
                zhiweiId = json_obj['zhiweiId']
                print(url)
                html = self.download.get_html(url)

                if html is not None and html.status_code == 200:
                    html = HTML(html.text)

                    #判断是否是当天发布，是的话请求详情页, 判断数据库是否有这条数据，有的话不请求（暂时）
                    li_xpath = html.xpath('//div[@class="job-list"]/ul/li')
                    for li in li_xpath:
                        content = etree.tostring(li)
                        content = HT.unescape(content.decode())
                        content = HTML(content)
                        li_time = content.xpath('string(//div[@class="info-publis"]/p)')
                        href_url = content.xpath('string(//div[@class="info-primary"]//h3/a/@href)')
                        try:
                            last_str = li_time.split('发布于')[1]
                            minute = last_str.split(':')[1]
                            #判断是否当天发布
                            if minute:
                                #判断数据库存不存在：
                                try:
                                    cid = re.match('^/job_detail/(.*?)\.html', href_url).group(1)
                                    sql = "select * from positions where cid='%s'" %(cid)
                                    find_one_res = self.db.find_one(sql)
                                    if find_one_res is None:
                                        #先把cid插入，避免重复抓取
                                        sql = "insert into positions(cid) values ('%s')" %(cid)
                                        self.db.save(sql)
                                        detail_url_list.append(config.HOST_URL + href_url)
                                    elif find_one_res[2] is None:
                                        detail_url_list.append(config.HOST_URL + href_url)
                                    else:
                                        print('数据库存在该记录：' + str(cid))
                                except:
                                    print('查询数据库出错：' + str(cid))
                        except:
                            print('该URL发布日期小于当天：' + config.HOST_URL + href_url)

                    results = self.get_detail(detail_url_list, cityId, zhiweiId)

                    #判断是否翻页
                    try:
                        last_li = html.xpath('string(//div[@class="job-list"]/ul/li[last()]//div[@class="info-publis"]/p)')
                        last_str = last_li.split('发布于')[1]
                        minute = last_str.split(':')[1]
                        if minute:
                            pageToken = str(int(pageToken) + 1)
                    except:
                        flag = False

                else:
                    print('该url无数据')

    def get_detail(self, detail_url_list, cityId, zhiweiId):
        for url in detail_url_list:
            print('下载该详情页：' + url)
            html = self.download.get_html(url)
            if html is not None and html.status_code == 200:
                html = HTML(html.text)

                try:
                    cid = re.match('^https://www.zhipin.com/job_detail/(.*?)\.html', url).group(1)
                except:
                    print('获取cid失败')
                    continue

                title = html.xpath('string(//h1)')
                url = url
                try:
                    publishDateStr = html.xpath('string(//span[@class="time"])').split('发布于')[1]
                    publishDate = int(time.mktime(time.strptime(publishDateStr, "%Y-%m-%d %H:%M")))
                except:
                    publishDateStr = None
                    publishDate = None

                try:
                    info = html.xpath('string(//div[@class="job-banner"]//div[@class="info-primary"]/p)')
                    info = info.split('：')
                    city = info[1][:-2]
                    jingyan = info[2][:-2]
                    xueli = info[3]
                except:
                    city = None
                    jingyan = None
                    xueli = None
                price = html.xpath('string(//div[@class="info-primary"]//span[@class="badge"])')
                posterName = html.xpath('string(//h2)')
                posterId = None
                posterUrl = html.xpath('string(//div[@class="detail-figure"]/img/@src)')
                content = html.xpath('string(//div[@class="job-sec"]/div[@class="text"])').strip()

                try:
                    company_text = html.xpath('string(//a[@ka="job-cominfo"]/@href)')
                    companyID = re.match('/gongsi/(.*?)\.html', company_text).group(1)
                except:
                    companyID = None
                createDate = int(time.time())

                #判断是否是当天发布
                temp_time = time.localtime(int(time.time()))
                now_DateStr = time.strftime("%Y-%m-%d", temp_time)
                lt = time.strptime(now_DateStr, "%Y-%m-%d")
                now_timestamp = int(time.mktime(lt))
                if publishDate == None or publishDate < now_timestamp or publishDate >= (now_timestamp + 86400):
                    print('特例.该url不是当天发布：' + str(url))
                    continue

                res_obj = {
                    'cid': cid,
                    'title': title,
                    'url': url,
                    'publishDateStr': publishDateStr,
                    'publishDate': publishDate,
                    'city': city,
                    'jingyan': jingyan,
                    'xueli': xueli,
                    'price': price,
                    'posterName': posterName,
                    'posterId': posterId,
                    'posterUrl': posterUrl,
                    'content': content,
                    'companyID': companyID,
                    'createDate': createDate,
                    'cityId': cityId,
                    'zhiweiId': zhiweiId
                }
                print(res_obj)
                sql = "insert into positions(cid,title,url,publishDate,publishDateStr,city,jingyan,xueli,price,posterName,posterId,posterUrl,content,companyID,createDate,cityId, zhiweiId)" \
                      " VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" \
                      % (cid,title,url,publishDate,publishDateStr,city,jingyan,xueli,price,posterName,posterId,posterUrl,content,companyID,createDate,cityId, zhiweiId)\
                      + "ON DUPLICATE KEY UPDATE title='%s', url='%s', publishDate='%s', publishDateStr='%s', city='%s', jingyan='%s', xueli='%s', price='%s', posterName='%s', posterId='%s', posterUrl='%s', content='%s', companyID='%s', createDate='%s',cityId='%s', zhiweiId='%s'" \
                      %(title,url,publishDate,publishDateStr,city,jingyan,xueli,price,posterName,posterId,posterUrl,content,companyID,createDate,cityId, zhiweiId)
                self.db.save(sql)
            else:
                print('请求详情页失败：' + str(url))

    def push_url_to_redis(self):
        # zhiwei_list = []
        # zhiwei_sql = 'select * from zhiwei'
        # zhiwei_results = self.db.find_all(zhiwei_sql)
        # for zhiwei in zhiwei_results:
        #     zhiwei_list.append(zhiwei[2])
        #
        # zhen_sql = 'select * from zhen'
        # zhen_results = self.db.find_all(zhen_sql)
        #
        # for res in zhen_results:
        #     pid = res[1]
        #     zhen_id = res[2]
        #     for zhiwei_id in zhiwei_list:
        #         url = POSITION_URL.format(pid=pid, zhen_id=zhen_id, zhiwei_id=zhiwei_id, pageToken='1')
        #         self.redisClient.push('employment',url)

        zhiwei_list = []
        zhiwei_sql = 'select * from zhiwei'
        zhiwei_results = self.db.find_all(zhiwei_sql)
        for zhiwei in zhiwei_results:
            zhiwei_list.append(zhiwei[2])

        shi_sql = 'select * from shi'
        shi_results = self.db.find_all(shi_sql)

        for res in shi_results:
            pid = res[2]
            for zhiwei_id in zhiwei_list:
                url = NEW_POSITION_URL.format(pid=pid, zhiwei_id=zhiwei_id, pageToken='1')
                url_obj = {"url":url, "cityId":pid, "zhiweiId":zhiwei_id}
                self.redisClient.push('employment', json.dumps(url_obj))


# -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 22:14:38 2020

@author: Liz
"""

############################################################################
##  This program has one parameter - input directory
##  The program goes through all of the .csv files in that directory
##  It puts each .csv file into a sheet of an excel file
##  It should be run on the output_bom directory which was created from the other program

import os
from glob import glob
import csv
import pandas as pd
import sys
from xlsxwriter.workbook import Workbook

def unify_norm_boms(dir_name):
    colwidths = {}
    colwidths[0] = 40
    colwidths[1] = 15
    colwidths[2] = 15
    colwidths[3] = 5
    colwidths[4] = 5
    colwidths[5] = 20
    colwidths[6] = 5
    colwidths[7] = 5
    colwidths[8] = 40
    colwidths[9] = 10
    colwidths[10] = 20
    colwidths[11] = 10

    output_dir_name = dir_name+"/*.csv"
#    print("output_dir_name =", output_dir_name)
    workbook = Workbook(dir_name + '/all_norm_boms.xlsx', {'strings_to_numbers': True,'constant_memory': True})

    for csvfile in glob(output_dir_name):
        name = os.path.basename(csvfile).split('.')[-2]
        print("Processing ", name)

        with open(csvfile, 'r') as f:
            worksheet = workbook.add_worksheet(name)
            for col_num, width in colwidths.items():
                worksheet.set_column(col_num, col_num, width)

            r = csv.reader(f)
            for row_index, row in enumerate(r):
                for col_index, data in enumerate(row):
                    worksheet.write(row_index, col_index, data)
    print("Normalized BOMs are now in", dir_name,"/all_norm_boms.xlsx")
    print("")
    print("NEXT STEP:  If no errors were reported, run the 'Get Sort Keys' program on the output normalized BOM file")

    workbook.close()

# The following makes this program start running at normalize_all()
# when executed as a stand-alone program.
if __name__ == '__main__':
    if len(sys.argv) != 2:
        print ("ERROR:  Re-run program with output_bom directories")
        sys.exit(1)
    else:
        unify_norm_boms(sys.argv[1])


from xai.brain.wordbase.nouns._snapdragon import _SNAPDRAGON

#calss header
class _SNAPDRAGONS(_SNAPDRAGON, ):
	def __init__(self,):
		_SNAPDRAGON.__init__(self)
		self.name = "SNAPDRAGONS"
		self.specie = 'nouns'
		self.basic = "snapdragon"
		self.jsondata = {}


# https://leetcode.com/problems/combination-sum-iii/submissions/
class Solution(object):
    def __init__(self):
        self.comb = []

    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        arr = set()
        self.helper(k, n, arr)
        return self.comb

    def helper(self, k, n, arr):
        # sum cant be <0 and we need to stick to array length of k
        if n < 0 or len(arr) > k:
            return

        if len(arr) == k and n == 0 and list(arr) not in self.comb:
            # its important to add list(arr) and not arr. Why?
            # because list(arr) creates a new list, and just arr is a reference
            self.comb.append(list(arr))
            return

        for i in range(1,10):
            #  cant have duplicates
            if i not in arr:
                arr.add(i)
                self.helper(k, n-i, arr)
                # discard does not throw error if element is not found
                # remove does throw error if element is not found
                arr.discard(i)


import os
import numpy as np
import csv

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
from sklearn.metrics import classification_report

# split a univariate sequence

def split_sequence(sequence, n_steps):
    X, y = list(), list()
    for i in range(len(sequence)):
        # find the end of this pattern
        end_ix = i + n_steps
        # check if we are beyond the sequence
        if end_ix > len(sequence)-1:
            break
        # gather input and output parts of the pattern
        seq_x, seq_y = sequence[i:end_ix], sequence[end_ix]
        X.append(seq_x)
        y.append(seq_y)
    return np.array(X), np.array(y)

# configuration
n_steps = 6
train_split = 0.25
epochs = 100

# read data
data = []
for file in os.listdir('./data'):
    filename = os.fsdecode(file)
    arr = np.genfromtxt('./data/' + filename, delimiter=',')
    if len(arr) > n_steps:
        data.append(arr)

# construct network
model = Sequential()
model.add(LSTM(50, activation='relu',
               return_sequences=True, input_shape=(n_steps, 1)))
model.add(LSTM(50, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
              optimizer='adam', metrics=['accuracy'])

# train
sep = int(len(data) * train_split)

for i in range(epochs):
    for instance in data[:sep]:
        X, y = split_sequence(instance, n_steps)
        X = X.reshape((X.shape[0], X.shape[1], 1))
        model.fit(X, y, epochs=1, verbose=1)

# test
pred = []
truth = []
for instance in data[sep:]:
    X, y = split_sequence(instance, n_steps)
    X = X.reshape((X.shape[0], X.shape[1], 1))
    pred.append(model.predict(X, verbose=0))
    truth.append(y)

pred = np.round(np.vstack(pred))
truth = np.concatenate(truth).reshape(-1, 1)

print(classification_report(truth, pred))