# import the necessary packages
from pyimagesearch.localbinarypatterns import LocalBinaryPatterns
from sklearn.svm import SVC
from imutils import paths
import argparse
import cv2
import os
import regex as re
from sklearn.metrics import classification_report, confusion_matrix, roc_curve, auc, roc_auc_score, accuracy_score
import pickle
from matplotlib import pyplot

# construct the argument parse and parse the arguments
#ap = argparse.ArgumentParser()
#ap.add_argument("-t", "--training", required=True,
#	help="path to the training images")
#ap.add_argument("-e", "--testing", required=True,
#	help="path to the tesitng images")
#args = vars(ap.parse_args())
# initialize the local binary patterns descriptor along with
# the data and label lists
desc = LocalBinaryPatterns(24, 3) #Era 24,3
data = []
labels = []
y_test = []
y_pred = []
y_pred_number = []
y_pred_proba = []
# loop over the training images
for imagePath in paths.list_images(os.getcwd()+"/images/training"):
	# load the image, convert it to grayscale, and describe it
	image = cv2.imread(imagePath)
	gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	hist = desc.describe(gray)
	# extract the label from the image path, then update the
	# label and data lists
	labels.append(imagePath.split(os.path.sep)[-2])
	print(imagePath.split(os.path.sep)[-1])
	data.append(hist)
# train a Linear SVM on the data
for label in labels:
        print(label)

model = SVC(C=200, random_state=42, probability=True) #C era 200 / random_state era 42
model.fit(data, labels)

# loop over the testing images
for imagePath in paths.list_images(os.getcwd()+"/images/testing"):
	# load the image, convert it to grayscale, describe it,
	# and classify it
	image = cv2.imread(imagePath)
	#img = cv2.resize(image, (800, 800))
	gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	hist = desc.describe(gray)
	prediction = model.predict(hist.reshape(1, -1))
	predictict_proba = model.predict_proba(hist.reshape(1, -1))

	#if prediction[0] == 'cataract':
	#	predNumber = 1
	#else:
	#	predNumber = 0

	if prediction == 'cataract':
		y_pred_number.append(1)
	else:
		y_pred_number.append(0)

	y_pred.append(prediction)
	y_pred_proba.append(predictict_proba)

	if re.search('\Acataract', imagePath.split(os.path.sep)[-1], re.IGNORECASE):
		y_test.append(1)
	else:
		y_test.append(0)

	print(imagePath.split(os.path.sep)[-1])
	#print(predNumber)

filename = 'finalized_model.sav'
pickle.dump(model, open(filename, 'wb'))

	# display the image and the prediction
	#cv2.putText(image, prediction[0], (10, 30), cv2.FONT_HERSHEY_SIMPLEX,
	#	1.0, (0, 0, 255), 3)
	#cv2.imshow("Image", image)
	#cv2.waitKey(0)

print("y_pred")
print(y_pred)

print("y_pred_proba")
print(y_pred_proba)

#ns_probs = [0 for _ in range(len(y_test))]

#ns_auc = roc_auc_score(y_test, ns_probs)
#lr_auc = roc_auc_score(y_test, y_pred_proba)

#print('No Skill: ROC AUC=%.3f' % (ns_auc))
#print('Logistic: ROC AUC=%.3f' % (lr_auc))

#ns_fpr, ns_tpr, _ = roc_curve(y_test, ns_probs)
#lr_fpr, lr_tpr, _ = roc_curve(y_test, y_pred_proba)

#pyplot.plot(ns_fpr, ns_tpr, linestyle='--', label='No Skill')
#pyplot.plot(lr_fpr, lr_tpr, marker='.', label='Logistic')

#pyplot.xlabel('False Positive Rate')
#pyplot.ylabel('True Positive Rate')

#pyplot.legend()

#pyplot.show()

#pyplot.savefig("grafico")

print("AUC Score = "+str(roc_auc_score(y_test, y_pred_number)))
print(confusion_matrix(y_test, y_pred_number))
print(classification_report(y_test, y_pred_number))


from os import remove
from glob import glob
import json

from supp.utils import create_sstable_filename, get_sstable_pattern

def list_sstables():
    '''
    Lists all sstables (path names)
    '''
    return glob(get_sstable_pattern('json'))

def read_sstable(filename):
    '''
    Reads sstable from file
    '''
    fin = open(filename, 'rt' )
    sstable_json = fin.read()
    fin.close()

    sstable = {}
    for record in json.loads(sstable_json):
        sstable[record['key']] = record

    return sstable

def write_sstable(memtable):
    '''
    Writes memtable to sstable in file
    '''
    filename = create_sstable_filename('json')
    memtable_json = json.dumps(list(memtable.values()), indent=4)
    fout = open(filename, 'wt' )
    fout.write(memtable_json)
    fout.close()

def delete_sstables():
    '''
    Deletes all sstable files
    '''
    for filename in list_sstables():
        remove(filename)


from odoo import api, fields, models

class StockPicking(models.Model):
    _inherit = "stock.picking"

    invoice_ids = fields.Many2many(
        comodel_name="account.move", copy=False, string="Invoices", readonly=True
    )
    invoice_count = fields.Integer(
        string="Invoices Orders", compute="_compute_invoice_count"
    )

    def action_view_invoice(self):
        """This function returns an action that display existing invoices
        of given stock pickings.
        It can either be a in a list or in a form view, if there is only
        one invoice to show.
        """
        self.ensure_one()
        form_view_name = "account.view_move_form"
        result = self.env["ir.actions.act_window"]._for_xml_id(
            "account.action_move_out_invoice_type"
        )
        if len(self.invoice_ids) > 1:
            result["domain"] = "[('id', 'in', %s)]" % self.invoice_ids.ids
        else:
            form_view = self.env.ref(form_view_name)
            result["views"] = [(form_view.id, "form")]
            result["res_id"] = self.invoice_ids.id
        return result

    @api.depends("invoice_ids")
    def _compute_invoice_count(self):
        for order in self:
            order.invoice_count = len(order.invoice_ids)


class Account:

    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def __str__(self):
        return f'Account owner: {self.owner} \nAccount balance: {self.balance}'

    def deposit(self, amount):
        self.balance += amount
        print('Deposit Accepted')

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
            print('Withdraw Accepted')
        else:
            print('Fund unavailable!')

acc1 = Account('Krzysztof', 120)
print(acc1)

acc1.deposit(80)
acc1.deposit(30)
acc1.withdraw(100)
print(acc1.balance)
acc1.withdraw(300)


from tracardi.domain.profile import Profile
from tracardi.process_engine.action.v1.metrics.key_counter.service.key_counter import KeyCounter
from tracardi.service.plugin.service.plugin_runner import run_plugin

from tracardi.process_engine.action.v1.metrics.key_counter.plugin import KeyCounterAction

def test_key_counter():

    c = KeyCounter({"d": 1})
    c.count('a')
    c.count('b')
    c.count(['a', 'c'])
    c.count({"a": 10, "b": 1, "f": 1})
    try:
        c.count({"g": "asas"})
        assert False
    except ValueError:
        assert True

    result = c.counts

    assert result == {'d': 1, 'a': 12, 'b': 2, 'c': 1, 'f': 1}

def test_key_counter_plugin():
    init = {
        "key": ['mobile', 'desktop', 'mobile'],
        'save_in': 'profile@stats.counters.MobileVisits'
    }

    payload = {}
    profile = Profile(id="aaa")
    result = run_plugin(KeyCounterAction, init, payload, profile)
    assert result.profile.stats.counters['MobileVisits'] == {'mobile': 2, 'desktop': 1}


from config.db import meta
from sqlalchemy import Table, Column
from sqlalchemy.sql.sqltypes import Integer, String

tab_users=Table(
    'tab_users',meta,
    Column('id', Integer, primary_key=True),
    Column('nome', String(100)),
    Column('email', String(100), unique=True),
    Column('senha', String(50)),
    Column('departamento', String(50))
  )


import cv2

# def read_kbd_input(inputQueue):
#     print('Ready for keyboard input:')
#     while (True):
#         input_str = input()
#         inputQueue.put(input_str)
#
# def main():
#     EXIT_COMMAND = "exit"
#     inputQueue = queue.Queue()
#
#     inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
#     inputThread.start()
#
#     while (True):
#         if (inputQueue.qsize() > 0):
#             input_str = inputQueue.get()
#             print("input_str = {}".format(input_str))
#
#             if (input_str == EXIT_COMMAND):
#                 print("Exiting serial terminal.")
#                 break
#
#             Insert your code here to do whatever you want with the input_str.
        #
        # The rest of your program goes here.
        #
        # time.sleep(0.01)
    # print("End.")

# video_name = '/home/hclee/workspace/git_adev2/lane_localization/video/서하남-구리1.mp4'
video_name = '/home/hclee/workspace/git_adev2/lane_localization/video/20190110/sony1/movie/MAH08411.MP4'
# video_name = "/home/data/highway_lane/video/20190226/sony1.MAH01283.MP4"

caption_name = video_name[:-4] + '.srt'
capture = cv2.VideoCapture(video_name)

if capture.isOpened() == False:
    print('capture is not open')

fps = capture.get(cv2.CAP_PROP_FPS)

mode = 0
srt_index = 0
startframe = 0
endframe = 0
fps_count = 0
enterkey = 0
writeSubtitle = False

text = "waiting input code ('s') :: "

while True:
    if(capture.get(cv2.CAP_PROP_POS_FRAMES) == capture.get(cv2.CAP_PROP_FRAME_COUNT)):
        # capture.open("/home/hclee/workspace/git_adev2/lane_localization/video/서하남-구리1.mp4")
        # capture.open("/home/data/highway_lane/video/20190226/sony1.MAH01283.MP4")
        capture.open(video_name)

    ret, frame = capture.read()
    fps_count = fps_count + 1

    # if cv2.waitKey(33) > 0: break
    # try:
    #     number = nput("what's your name???")
    # except ValueError:
    #     print("Invalid number")

    key = cv2.waitKey(9)

    if key >= 48 and key < 57:
        if mode == 0:
            if key == 49:
                text = '000010400'
                number = '000010400'
            elif key == 50:
                text = '000020400'
                number = '000020400'
            elif key == 51:
                text = '000030400'
                number = '000030400'
            elif key == 52:
                text = '000040400'
                number = '000040400'
            elif key == 53:
                text = '100020400'
                number = '100020400'

            enterkey = key
            mode = 1
            startframe = fps_count
            srt_index = srt_index + 1
        # elif mode == 1 and enterkey == key:
        # elif mode == 1:
        #     mode = 0
        #     endframe = fps_count
        #     writeSubtitle = True
    # spacebar
    elif key == 32:
        if mode == 1:
            mode = 0
            endframe = fps_count
            writeSubtitle = True
            number = '00000000'
            text = "ready subtitle~"
        else:
            mode = 1
            startframe = fps_count
            srt_index = srt_index + 1
            text = "save subtitle~"
    elif key == ord('s'):
    # if key == ord('s'):
        try:
            number = input("enter label code :: ")
            text = number
        except ValueError:
            print("Invalid number")

        enterkey = key
        startframe = fps_count
        srt_index = srt_index + 1
    elif key == ord('e'):
        endframe = fps_count
        writeSubtitle = True
        # text = "input code ('s') :: "
    elif key == 27:
        break
    else:
        output = frame

    if writeSubtitle == True:
        startTime = '{:02d}:{:02d}:{:02d},00'.format(int((startframe / fps) // 3600), int((startframe / fps) % 3600 // 60), int((startframe / fps) % 60))
        endTime = '{:02d}:{:02d}:{:02d},00'.format(int((endframe / fps) // 3600), int((endframe / fps) % 3600 // 60), int((endframe / fps) % 60))
        srtfile = open(caption_name, mode='a', encoding='utf-8')
        str = (("%d\n%s --> %s\n%s\n\n") % (srt_index, startTime, endTime, number))
        srtfile.write(str)
        srtfile.close()
        # text = 'please input code :: '
        number = ''
        writeSubtitle = False

    # Write some Text

    font = cv2.FONT_HERSHEY_SIMPLEX
    bottomLeftCornerOfText = (10, 500)
    fontScale = 1
    fontColor = (255, 255, 255)
    lineType = 2

    cv2.putText(frame, text,
                bottomLeftCornerOfText,
                font,
                fontScale,
                fontColor,
                lineType)

    imS = cv2.resize(frame, (480, 270))
    cv2.imshow("VideoFrame", imS)

capture.release()
cv2.destroyAllWindows()


'''
From: https://keras.io/getting-started/sequential-model-guide/#multilayer-perceptron-mlp-for-multi-class-softmax-classification
'''
#Imports
#Initialize neural network model
import numpy as np
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization, AveragePooling2D
from keras.optimizers import SGD, Adadelta
from keras.preprocessing import image
from img_loader import load_images
import tensorflow as tf
from keras.utils import multi_gpu_model, to_categorical
from keras.models import load_model
from sklearn.model_selection import train_test_split
import os

#Custom python scripts
from prediction_chooser import get_highest_predictions
#For preprocessing images
from keras.preprocessing.image import ImageDataGenerator
from exp_stats import save_stats, save_data_info, save_histogram
from exp_stats import plot_confusion_matrix
from img_loader import load_images

# Importing augmentation functions
from augmentationsettings import augmentationSettings

#Building CNN model

def __get_image_generator(path, X_train, X_test, y_train, y_test):
    #Preprocessing images to avoid overfitting
    '''
    Performing augmentation of images.
    Preparing test data.
    Data directory name will be the label.
    '''
    # Augmentation settings from document
    train_datagen = augmentationSettings("basicAug")
    test_datagen = ImageDataGenerator(rescale=1./255)

    #Create image dirs if not exists
    train_dir = '{0}training_images'.format(path)
    test_dir = '{0}test_images'.format(path)
    if not os.path.exists(train_dir):
        os.makedirs(train_dir)
    if not os.path.exists(test_dir):
        os.makedirs(test_dir)

    train_set = train_datagen.flow(X_train, y_train,
                                   save_to_dir=train_dir,
                                   batch_size=5)
    test_set = test_datagen.flow(X_test, y_test,
                                 save_to_dir=test_dir,
                                 batch_size=5)

    return (train_datagen, test_datagen, train_set, test_set)

def __create_model():
    #Creates sequential network
    model = Sequential()

    #Convolution
    '''
    Adding convolutional layer
    param 1: number of filters
    param 2: filter shape (matrix)
    param 3: input shape 200x200 image, and type, 3 = RGB
    param 4: activation function, relu = rectifier function
    '''
    model.add(Conv2D(32, (5,5), strides=1, input_shape=(200, 200, 3), activation='relu'))
    model.add(Conv2D(32, (3,3), strides=1, input_shape=(200, 200, 3), activation='relu'))
    model.add(Conv2D(32, (3,3), strides=1, input_shape=(200, 200, 3), activation='relu'))

    #Pooling
    '''
    Reducing image size as much as possible
    Helps reducing number of nodes in the layers
    Trying to reduce complexity without loosing performance
    '''
    model.add(AveragePooling2D(pool_size=(2,2), strides=2))

    #Convolution
    model.add(Conv2D(64, (3,3), strides=1, input_shape=(100, 100, 3), activation='relu'))
    model.add(Conv2D(64, (3,3), strides=1, input_shape=(100, 100, 3), activation='relu'))

    #Pooling
    model.add(AveragePooling2D(pool_size=(2,2), strides=2))

    #Convolution
    model.add(Conv2D(128, (2,2), strides=1, input_shape=(50, 50, 3), activation='relu'))

    #Pooling
    model.add(AveragePooling2D(pool_size=(2,2), strides=2))

    #Convolution
    model.add(Conv2D(256, (3,3), strides=1, input_shape=(25, 25, 3), activation='relu'))

    #Pooling
    model.add(AveragePooling2D(pool_size=(2,2), strides=2))

    #Convolution
    model.add(Conv2D(512, (3,3), strides=1, input_shape=(13, 13, 3), activation='relu'))

    #Pooling
    model.add(AveragePooling2D(pool_size=(2,2), strides=2))

    #Convolution
    model.add(Conv2D(512, (3,3), strides=1, input_shape=(7, 7, 3), activation='relu'))

    #Pooling
    model.add(AveragePooling2D(pool_size=(2,2), strides=2))

    #Fully Connected Layer
    '''
    Make images into continous vector.
    Converting 2-D image pixel matrices to
    one dimensional vector.
    Keras can do the flattening automatically
    '''
    model.add(Flatten())
    model.add(Dense(512, activation='relu'))
    model.add(Dense(200, activation='relu'))

    #Output layer
    model.add(Dense(5, activation='softmax')) #research why softmax is used

    #Compiling CNN model

    '''
    optimizer: choosing stochastic gradient decent algorithm
    loss: choosing the loss function
    metrics: choosing the performance metric
    '''
    #sgd: Stochastic Gradient Decent
    model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])

    return model

def __train_model(save_path, train_set, test_set):
    model = __create_model()

    #Fitting data to model

    epochs = 2
    '''
    steps_per_epoch: number of training images
    epochs: Number of times the network will be trained
    on every training sample.
    validation_steps: number of test images
    '''
    history = model.fit_generator(train_set,
                        steps_per_epoch=2,
                        epochs=epochs,
                        validation_data=test_set,
                        validation_steps=2)

    print('Saving model...')
    model.save(save_path+'model.hdf5')
    save_stats(model, history, save_path)

    return model

def get_model(save_path, create):
    #Preprocess images in samples
    seed = 7
    X, y, label_map = load_images('../images/')

    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, random_state=seed)
    y_train_cat = to_categorical(y_train)
    y_test_cat = to_categorical(y_test)

    train_datagen, test_datagen, train_set, test_set = __get_image_generator(save_path,
    X_train, X_test, y_train_cat, y_test_cat)

    if save_path.endswith('.hdf5'):
            save_path = save_path[:-5]
    if create:
        model = __train_model(save_path, train_set, test_set)
    else:
        model = load_model(save_path+'.hdf5')

    save_data_info(train_datagen, test_datagen, train_set, test_set,
    len(X_train), len(X_test), len(label_map), save_path)

    #Evaluate model predictions
    print('Generating confusion matrix...')
    predictions = model.predict_generator(test_set, steps=2)
    y_pred = np.argmax(predictions, axis=1)
    y_true = y_test[:10]
    print(y_pred)
    print(y_true)
    plot_confusion_matrix(y_pred, y_true, label_map.values(), save_path)
    save_histogram(save_path, predictions)

    return model


import random

class Character:
    def __init__(self, health, power, name):
        self.health = health
        self.power = power
        self.name = name

    def alive(self):
            return self.health > 0

    def print_status(self):
        print("{} has {} health and {} power".format(self.name, self.health, self.power))

class Hero(Character):
    def __init__(self, health, power, name):
        super().__init__(health, power, name)

    def attack(self, enemy):
        raw_input == input()
        if raw_input == "1":
            enemy_health -= self.power
            print("You do {} damage to the goblin.".format(hero_power))
            if goblin_health <= 0:
                print("The goblin is dead.")
        elif raw_input == "2":
            pass
        elif raw_input == "3":
            print("Goodbye.")

        else:
            print("Invalid input {}".format(raw_input))

class Goblin:
    def __init__(self, health, power, name):
       super().__init__(health, power, name)
    def attack(self, hero):
         if goblin_health > 0:
            hero_health -= goblin_power
            print("The goblin does {} damage to you.".format(goblin_power))
            if hero_health <= 0:
                print("You are dead.")

def main():
    hero = Hero (10, 6, 'Strongguy')
    goblin = Goblin (10, 2, 'Greenboy')
    zombie = Zombie (50, 50, 'Brainboy')

    enemy = []
    menuchoice = input("Which enemy would you like to fight? Press 1 or 2: \n1 goblin, \n2. zombie" )

    if menuchoice == "1":
        enemy = goblin

    if menuchoice == "2":
        enemy = zombie

    while enemy.health > 0 and hero.health > 0:
        print("You have {} health and {} power.".format(hero.health, hero.power))
        print("The goblin has {} health and {} power.".format(enemy.health, enemy.power))
        print()
        print("What do you want to do?")
        print("1. fight", enemy.name)
        print("2. do nothing")
        print("3. flee")
        print("> ", end=' ')
        raw_input = input()
        if raw_input == "1":
            if random.randint(0, 100) >= 20:
                goblin_health -= hero_power * 2
                print("You do {} damage to the goblin.".format(hero_power))
            else:
                goblin_health -= hero_power
            print("You do {} damage to the goblin.".format(hero_power))
        if enemy.health <= 0:
                print("The enemy is dead.")
        elif raw_input == "2":
            pass
        elif raw_input == "3":
            print("Goodbye.")
            break
        else:
            print("Invalid input {}".format(raw_input))

        if enemy.health > 0:
            # Goblin attacks hero
            hero.health -= enemy.power
            print("The enemy does {} damage to you.".format(enemy.power))
            if hero.health <= 0:
                print("You are dead.")

main()


#!/usr/bin/env python3

# Faça um programa que mostre a TABUADA de VÁRIOS NÚMEROS,
# um de cada vez, para cada valor digitado pelo usuário
# O programa será INTERROMPIDO quando o número solicitado
# for NEGATIVO #

# f : fator
# n : número fator

from time import sleep
f = 0
n = int(input('Tabuada do '))
while True:
    while True:
        f += 1
        print(' {} x  {} =   {}'.format(n, f, n * f))
        if f >= 10:
            sleep(1)
            f = 0
            n = int(input('Tabuada do '))
        elif n < 0:
            break
    break
print('fim')


import torch
from functools import reduce
from torch.optim.optimizer import Optimizer

class LBFGS(Optimizer):

    def __init__(self,
                 params,
                 lr=1,
                 max_iter=200,
                 max_eval=None,
                 tolerance_grad=1e-7,
                 tolerance_change=1e-9,
                 history_size=100):
        if max_eval is None:
            max_eval = max_iter * 5 // 4
        defaults = dict(
            lr=lr,
            max_iter=max_iter,
            max_eval=max_eval,
            tolerance_grad=tolerance_grad,
            tolerance_change=tolerance_change,
            history_size=history_size)
        super(LBFGS, self).__init__(params, defaults)

        if len(self.param_groups) != 1:
            raise ValueError("LBFGS doesn't support per-parameter options "
                             "(parameter groups)")

        self._params = self.param_groups[0]['params']
        self._numel_cache = None

    def _numel(self):
        if self._numel_cache is None:
            self._numel_cache = reduce(lambda total, p: total + p.numel(), self._params, 0)
        return self._numel_cache

    def _gather_flat_grad(self):
        views = []
        for p in self._params:
            if p.grad is None:
                view = p.new(p.numel()).zero_()
            elif p.grad.is_sparse:
                view = p.grad.to_dense().view(-1)
            else:
                view = p.grad.view(-1)
            views.append(view)
        return torch.cat(views, 0)

    def _add_grad(self, step_size, update):
        offset = 0
        for p in self._params:
            numel = p.numel()
            d = update[offset:offset + numel].view_as(p)
            p.add_(d, alpha=step_size)
            offset += numel
        assert offset == self._numel()

    def _clone_param(self):
        return [p.clone(memory_format=torch.contiguous_format) for p in self._params]

    def _set_param(self, params_data):
        for p, pdata in zip(self._params, params_data):
            p.copy_(pdata)

    def _directional_evaluate(self, closure, x, t, d):
        self._add_grad(t, d)
        loss = float(closure())
        flat_grad = self._gather_flat_grad()
        self._set_param(x)
        return loss, flat_grad

    @torch.no_grad()
    def step(self, closure):
        """Performs a single optimization step.

        Args:
            closure (callable): A closure that reevaluates the model
                and returns the loss.
        """
        assert len(self.param_groups) == 1

        # Make sure the closure is always called with grad enabled
        closure = torch.enable_grad()(closure)

        group = self.param_groups[0]
        lr = group['lr']
        max_iter = group['max_iter']
        max_eval = group['max_eval']
        tolerance_grad = group['tolerance_grad']
        tolerance_change = group['tolerance_change']
        history_size = group['history_size']

        # NOTE: LBFGS has only global state, but we register it as state for
        # the first param, because this helps with casting in load_state_dict
        state = self.state[self._params[0]]
        state.setdefault('func_evals', 0)
        state.setdefault('n_iter', 0)

        # evaluate initial f(x) and df/dx
        orig_loss = closure()
        loss = float(orig_loss)
        current_evals = 1
        state['func_evals'] += 1

        flat_grad = self._gather_flat_grad()
        opt_cond = flat_grad.abs().max() <= tolerance_grad

        # optimal condition
        if opt_cond:
            return orig_loss

        # tensors cached in state (for tracing)
        d = state.get('d')
        t = state.get('t')
        old_dirs = state.get('old_dirs')
        old_stps = state.get('old_stps')
        ro = state.get('ro')
        H_diag = state.get('H_diag')
        prev_flat_grad = state.get('prev_flat_grad')
        prev_loss = state.get('prev_loss')

        n_iter = 0
        # optimize for a max of max_iter iterations
        while n_iter < max_iter:
            # keep track of nb of iterations
            n_iter += 1
            state['n_iter'] += 1

            ############################################################
            # compute gradient descent direction
            ############################################################
            if state['n_iter'] == 1:
                d = flat_grad.neg()
                old_dirs = []
                old_stps = []
                ro = []
                H_diag = 1
            else:
                # do lbfgs update (update memory)
                y = flat_grad.sub(prev_flat_grad)
                s = d.mul(t)
                ys = y.dot(s)  # y*s
                if ys > 1e-10:
                    # updating memory
                    if len(old_dirs) == history_size:
                        # shift history by one (limited-memory)
                        old_dirs.pop(0)
                        old_stps.pop(0)
                        ro.pop(0)

                    # store new direction/step
                    old_dirs.append(y)
                    old_stps.append(s)
                    ro.append(1. / ys)

                    # update scale of initial Hessian approximation
                    H_diag = ys / y.dot(y)  # (y*y)

                # compute the approximate (L-BFGS) inverse Hessian
                # multiplied by the gradient
                num_old = len(old_dirs)

                if 'al' not in state:
                    state['al'] = [None] * history_size
                al = state['al']

                # iteration in L-BFGS loop collapsed to use just one buffer
                q = flat_grad.neg()
                for i in range(num_old - 1, -1, -1):
                    al[i] = old_stps[i].dot(q) * ro[i]
                    q.add_(old_dirs[i], alpha=-al[i])

                # multiply by initial Hessian
                # r/d is the final direction
                d = r = torch.mul(q, H_diag)
                for i in range(num_old):
                    be_i = old_dirs[i].dot(r) * ro[i]
                    r.add_(old_stps[i], alpha=al[i] - be_i)

            if prev_flat_grad is None:
                prev_flat_grad = flat_grad.clone(memory_format=torch.contiguous_format)
            else:
                prev_flat_grad.copy_(flat_grad)
            prev_loss = loss

            ############################################################
            # compute step length
            ############################################################
            # reset initial guess for step size
            if state['n_iter'] == 1:
                t = min(1., 1. / flat_grad.abs().sum()) * lr
            else:
                t = lr

            # directional derivative
            gtd = flat_grad.dot(d)  # g * d

            # directional derivative is below tolerance
            if gtd > -tolerance_change:
                break

            # optional line search: user function
            ls_func_evals = 0
            self._add_grad(t, d)
            if n_iter != max_iter:
                # re-evaluate function only if not in last iteration
                # the reason we do this: in a stochastic setting,
                # no use to re-evaluate that function here
                with torch.enable_grad():
                    loss = float(closure())
                flat_grad = self._gather_flat_grad()
                opt_cond = flat_grad.abs().max() <= tolerance_grad
                ls_func_evals = 1

            # update func eval
            current_evals += ls_func_evals
            state['func_evals'] += ls_func_evals

            ############################################################
            # check conditions
            ############################################################
            if n_iter == max_iter:
                break

            if current_evals >= max_eval:
                break

            # optimal condition
            if opt_cond:
                break

            # lack of progress
            if d.mul(t).abs().max() <= tolerance_change:
                break

            if abs(loss - prev_loss) < tolerance_change:
                break

        state['d'] = d
        state['t'] = t
        state['old_dirs'] = old_dirs
        state['old_stps'] = old_stps
        state['ro'] = ro
        state['H_diag'] = H_diag
        state['prev_flat_grad'] = prev_flat_grad
        state['prev_loss'] = prev_loss

        return orig_loss


import numpy as np
import pandas as pd
import sklearn
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score
train = pd.read_csv("../input/train.csv")
train.shape
train.head()
train.dtypes.value_counts()
train.select_dtypes(include='object').columns
train2 = train.drop(columns = ['Id', 'idhogar', 'dependency', 'edjefe', 'edjefa'])
null_columns = train2.columns[train2.isnull().any()]
train2[null_columns].isnull().sum()
train3 = train2.drop(columns = ['v2a1', 'v18q1', 'rez_esc', 'meaneduc', 'SQBmeaned'])
ntrain = train3.dropna()
ntrain.head()
test = pd.read_csv("../input/test.csv")
null_columns = test.columns[test.isnull().any()]
test[null_columns].isnull().sum()
Xtest = test.drop(columns = ['Id', 'idhogar', 'dependency', 'edjefe', 'edjefa', 'v2a1', 'v18q1', 'rez_esc', 'meaneduc', 'SQBmeaned'])
Xntest = Xtest.dropna()
Xid = test.drop(columns = ['idhogar', 'dependency', 'edjefe', 'edjefa', 'v2a1', 'v18q1', 'rez_esc', 'meaneduc', 'SQBmeaned'])
Xnid = Xid.dropna()

Xid.shape

Xtrain = ntrain.drop(columns = ["Target"])
Ytrain = ntrain.Target
knn = KNeighborsClassifier(n_neighbors=3)
scores = cross_val_score(knn, Xtrain, Ytrain, cv=10)
np.mean(scores)
knn = KNeighborsClassifier(n_neighbors = 97)
knn.fit(Xtrain, Ytrain)
Ypred = knn.predict(Xntest)
result = np.vstack((Xid["Id"], Ypred)).T
x = ["Id","Target"]
Resultado = pd.DataFrame(columns = x, data = result)
Resultado.to_csv("results.csv", index = False)
Resultado


from VascularGenerator import VascularGenerator
from VasGen2 import VasGen2
from equations import *
from diffu2D_u0 import lab_meat_diffuse
import os
import math
import matplotlib.pyplot as plt

import random

import imageio
from natsort import natsorted, ns
from sklearn.preprocessing import minmax_scale

import autograd.numpy as np
from autograd import grad
from autograd.scipy.integrate import odeint
from autograd.builtins import tuple
from autograd.misc.optimizers import adam
import autograd.numpy.random as npr
import autograd.scipy.signal as sig
from timeit import default_timer as timer

def sigmoid(x):
    return 1 / (1 + math.exp(-x))

def gaussian(x):
    return math.exp(-x**2)

def create_remove_imgs():
    path_to_diffuse_pngs = 'Hillclimb/diffusePngs/'
    sim_img_folder = 'Hillclimb/imgs/'
    sim_graph_folder = 'Hillclimb/graphs/'
    sim_fig_folder = 'Hillclimb/figs/'
    if not os.path.exists(path_to_diffuse_pngs):
        os.makedirs(path_to_diffuse_pngs)

    if not os.path.exists(sim_img_folder):
        os.makedirs(sim_img_folder)

    if not os.path.exists(sim_graph_folder):
        os.makedirs(sim_graph_folder)

    if not os.path.exists(sim_fig_folder):
        os.makedirs(sim_fig_folder)

    for img_file in os.listdir(path_to_diffuse_pngs):
        os.remove(path_to_diffuse_pngs + img_file)

    if os.path.exists(sim_img_folder):
        for img_file in os.listdir(sim_img_folder):
            os.remove(sim_img_folder + img_file)

    if os.path.exists(sim_graph_folder):
        for img_file in os.listdir(sim_graph_folder):
            os.remove(sim_graph_folder + img_file)

    if os.path.exists(sim_fig_folder):
        for img_file in os.listdir(sim_fig_folder):
            os.remove(sim_fig_folder + img_file)

def get_submatrix_add(lst_matrix, center_pt_tuple, convolution, submatrix_size=2):
    w, h = len(lst_matrix), len(lst_matrix[0])
    orig_row, orig_col = center_pt_tuple
    row, col = orig_row, orig_col
    row_start = -1
    row_end = -1
    col_start = -1
    col_end = -1

    if row >= 0 and row < h:
        row_start = row - submatrix_size + 1 if (row - submatrix_size + 1) > 0 else 0
        row_end = row + submatrix_size if (row + submatrix_size) <= h else h
    elif row == h:
        row -= 1
        row_start = row - submatrix_size + 1 if (row - submatrix_size + 1) > 0 else 0
        row_end = row + submatrix_size if (row + submatrix_size) <= h else h
    elif row < 0 or row > h:
        print('Bad row dimension of ', row)

    if col >= 0 and col < w:
        col_start = col - submatrix_size + 1 if (col - submatrix_size + 1) > 0 else 0
        col_end = col + submatrix_size if (col + submatrix_size) <= w else w
    elif col == w:
        col -= 1
        col_start = col - submatrix_size + 1 if (col - submatrix_size + 1) > 0 else 0
        col_end = col + submatrix_size if (col + submatrix_size) <= w else w
    elif col < 0 or col > w:
        print('Bad col dimension of ', col)

    conv_row_start = 0
    conv_row_end = 3
    conv_col_start = 0
    conv_col_end = 3
    new_convolution = None

    if (orig_row - submatrix_size + 1) < 0:
        conv_row_start = 1
    if (orig_row + submatrix_size ) >= h:
        conv_row_end = 1

    if (orig_col - submatrix_size + 1) < 0:
        conv_col_start = 1
    if (orig_col + submatrix_size) >= w:
        conv_col_end = 1

    new_convolution = convolution[conv_row_start:conv_row_end][conv_col_start:conv_col_end]

    new_matrix = []
    for row_idx, lst_row in enumerate(lst_matrix):
        count = 0
        if row_idx >= row_start and row_idx < row_end and count < conv_col_end:
            val2 = new_convolution[conv_col_start + count]
            updated_lst_vals = [sum(x) for x in zip(lst_row[col_start:col_end], val2)]

            new_row=[]
            row_count = 0
            for cur_col_idx, val in enumerate(lst_row):
                if cur_col_idx >= col_start and cur_col_idx < col_end:
                    new_row.append(updated_lst_vals[0+row_count])
                    row_count = row_count + 1
                else:
                    new_row.append(val)

            count = count + 1
            lst_row = new_row

        new_matrix.append(lst_row)
    return new_matrix

def diffusion(mvble_pts, img):
    # D is the defusion constant
    # D = .225
    # B = D / 10
    D = 0.03
    B = D / 4
    # D = 0.00000001
    # B = D / 4

    #https://programtalk.com/python-examples/autograd.scipy.signal.convolve/
    for _ in range(0, 60): # how many times you run a diffusion update
        convolve = np.array([[1*D, 1*D, 1*D],[1*D,-8*D,1*D], [1*D, 1*D, 1*D]])
        deltaDiffusion = sig.convolve(np.array(img), convolve)[1:-1, 1:-1] #take off first and last
        # deltaDiffusion = deltaDiffusion + np.array(img)

        # the update to the img from one step of diffusion
        img = np.array(np.array(img) + np.array(deltaDiffusion) + np.array(nonlinearDiffusion(mvble_pts, img)))
        img = img - (B * img)

    np_img = np.array(img)
    mn, mx = np_img.min(), np_img.max()
    np_img = (np_img - mn) / (mx - mn)
    return np_img

# None linear diffusion (compute each convoution for each location)
def nonlinearDiffusion(mvble_pts, img):
    #http://greg-ashton.physics.monash.edu/applying-python-functions-in-moving-windows.html
    #https://stackoverflow.com/questions/12816293/vectorize-this-convolution-type-loop-more-efficiently-in-numpy
    h, w = np.array(img).shape
    deltaDomain2 = []
    for _ in range(w):
        deltaDomain2.append([0.0 for _ in range(h)])

    for i in range(len(mvble_pts)):
        pt = mvble_pts[i]
        x = pt[0]
        y = pt[1]
        int_x = 0
        int_y = 0

        if type(x) != type(np.array((1,1))) and type(x) != type(1):
            int_x = int(np.array(mvble_pts[i][0]))
            int_y = int(np.array(mvble_pts[i][1]))
        else:
            int_x = int(np.array(mvble_pts[i][0]))
            int_y = int(np.array(mvble_pts[i][1]))

        np_pt = np.array([x, y])

        inc = 0.5
        dist_0 = np.linalg.norm(np_pt - np.array([int_x-1 + inc, int_y-1 + inc]))
        dist_1 = np.linalg.norm(np_pt - np.array([int_x + inc, int_y-1 + inc]))
        dist_2 = np.linalg.norm(np_pt - np.array([int_x+1 + inc, int_y-1 + inc]))

        dist_3 = np.linalg.norm(np_pt - np.array([int_x-1 + inc, int_y + inc]))
        dist_4 = np.linalg.norm(np_pt - np.array([int_x + inc, int_y + inc]))
        dist_5 = np.linalg.norm(np_pt - np.array([int_x+1 + inc, int_y + inc]))

        dist_6 = np.linalg.norm(np_pt - np.array([int_x-1 + inc, int_y+1 + inc]))
        dist_7 = np.linalg.norm(np_pt - np.array([int_x + inc, int_y+1 + inc]))
        dist_8 = np.linalg.norm(np_pt - np.array([int_x+1 + inc, int_y+1 + inc]))

        X = -dist_0 - dist_1 - dist_2 - dist_3 - dist_5 - dist_6 - dist_7 - dist_8

        convolution = [[sigmoid(dist_0 - 1), sigmoid(dist_1 - 1), sigmoid(dist_2 - 1)], [sigmoid(dist_3 - 1), X, sigmoid(dist_5 - 1)], [sigmoid(dist_6 - 1), sigmoid(dist_7 - 1), sigmoid(dist_8 - 1)]]

        deltaDomain2 = get_submatrix_add(deltaDomain2, (int_x, int_y), convolution)

    return deltaDomain2

def create_loss_map(img, iter):
    h, w = np.array(img).shape
    loss_map = []
    for _ in range(w):
        loss_map.append([0.0 for _ in range(h)])

    ideal = np.ones(img.shape)[1:,1:]
    val = np.abs(ideal - img[1:,1:])
    return val

def loss_health(img, iter, vessel_points):
    threshold = 0.9
    # 2D array of neutrient values
    # sum of sigmoid values (high N is low low, low N is high loss)
    total_loss = 0.0
    for ix,iy in np.ndindex(img.shape):
        if vessel_points[(ix,iy)] > 0.0:
            val = img[ix,iy]
            loss = 1
            if val >= threshold:
                loss = 1/(1+img[ix,iy])
            total_loss += loss

    return total_loss

def adjustMoveRate(num):
    num = num/2
    if num < 0.2:
        if num > 0:
            num = 0.2
        elif num > -0.2:
            num = -0.2
    return num

def saveImageOne(iteration):
    fig.savefig('HillClimb/figs/' + str(iteration) + '.png', size=[1600,400])#, size=[1000,1000]) #, size=[700,700] IF 1000, renders each quadrant separately

if __name__ == "__main__":
    print("Climbing the hill")
    numNodes = 2
    path_to_diffuse_pngs = 'Hillclimb/diffusePngs/'
    sim_img_folder = 'Hillclimb/imgs/'
    sim_graph_folder = 'Hillclimb/graphs/'

    create_remove_imgs()

    vas_structure = VasGen2(max_range=20, num_of_nodes=numNodes, side_nodes=False)
    vas_structure.print_images(graph_name='HillClimb/HillClimb_startGraph.png', img_name='HillClimb/HillClimb_startImg.png')

    test_movement = np.array([-5, -2, -1, 0, 1, 2, 5])

    def fitness(fit_mvable_pts, iter):
        diffused_img = diffusion(fit_mvable_pts, img)
        return loss_health(diffused_img, iter, vas_structure.pts_on_vessels)

    flowDict = computeFlow(vas_structure)
    vas_structure.add_flows_to_img(flowDict)
    img = vas_structure.img
    diffused_img = img

    mvable_pts = vas_structure.moveable_pts

    all_loss = []
    time_lst = []

    fig = plt.figure(figsize=(16, 4), facecolor='white')

    ax_loss         = fig.add_subplot(151, frameon=True)
    ax_node_graph   = fig.add_subplot(152, frameon=True)

    ax_img          = fig.add_subplot(153, frameon=True)
    ax_diffused_img = fig.add_subplot(154, frameon=True)
    ax_loss_map     = fig.add_subplot(155, frameon=True)

    plt.show(block=False)
    count = 1
    imgcolorbar = None

    def callback(mvable_pts, iter):

        ####################################
        # LOSS as a function of TIME
        ax_loss.cla()
        ax_loss.set_title('Train Loss')
        ax_loss.set_xlabel('t')
        ax_loss.set_ylabel('loss')
        nowLoss = fitness(mvable_pts, iter)
        all_loss.append(nowLoss)
        time = np.arange(0, len(all_loss), 1)

        ax_loss.plot(time, all_loss, '-', linestyle = 'solid', label='loss') #, color = colors[i]
        ax_loss.set_xlim(time.min(), time.max())
        ax_loss.legend(loc = "upper left")

        ## Plots the Node Graph
        ax_node_graph.cla()
        ax_node_graph.set_title('Node Graph')
        for j, s in enumerate(vas_structure.tri.simplices):
            p = np.array(vas_structure.pts)[s].mean(axis=0)
            ax_node_graph.text(p[0], p[1], 'Cell #%d' % j, ha='center') # label triangles
        ax_node_graph.triplot(np.array(vas_structure.pts)[:,0], np.array(vas_structure.pts)[:,1], vas_structure.tri.simplices)
        ax_node_graph.plot(np.array(vas_structure.pts)[:,0], np.array(vas_structure.pts)[:,1], 'o')

        # ==== Plot Img Version ==== #
        ax_img.cla()
        imgcolorbar = None
        ax_img.set_title('Flow Image')
        ax_img.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
        ax_img.tick_params(axis='y', which='both', left=False, right=False, labelleft=False)
        imgplot = ax_img.imshow(np.rot90(np.array(vas_structure.img)[1:,1:]))

        # ==== Plot Diffused Img Version ==== #
        ax_diffused_img.cla()
        diffused_img_plt1 = diffusion(mvable_pts, vas_structure.img)
        ax_diffused_img.set_title('Diffused Image')
        ax_diffused_img.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
        ax_diffused_img.tick_params(axis='y', which='both', left=False, right=False, labelleft=False)
        diffusedplot = ax_diffused_img.imshow(np.rot90(diffused_img_plt1[1:,1:]), vmin=0, vmax=1)

        # ==== Plot Diffused LOSS MAP ==== #
        ax_loss_map.cla()
        loss_map = create_loss_map(np.array(diffused_img_plt1), iter)
        ax_loss_map.set_title('Diffusion Loss Map')
        ax_loss_map.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
        ax_loss_map.tick_params(axis='y', which='both', left=False, right=False, labelleft=False)
        loss_plot = ax_loss_map.imshow(np.rot90(np.array(loss_map)), vmin=0, vmax=1)

        plt.draw()
        saveImageOne(iter)
        plt.pause(0.001)
        return 3

    dImproved = False
    currentLoss = fitness(mvable_pts, 0)
    temperature = 20

    for i in range(200):

        if not dImproved:
            index = random.randrange(0, numNodes)
            inc_index_x = np.random.choice(test_movement, 1, replace=False)[0]
            inc_index_y = np.random.choice(test_movement, 1, replace=False)[0]
        else:
            inc_index_x = adjustMoveRate(inc_index_x)
            inc_index_y = adjustMoveRate(inc_index_y)

        originalPoints = vas_structure.moveable_pts[index]

        test_x = vas_structure.moveable_pts[index][0] + inc_index_x
        test_y = vas_structure.moveable_pts[index][1] + inc_index_y

        if test_x < 1:
            test_x = 1
        if test_x > 19:
            test_x = 19

        if test_y < 1:
            test_y = 1
        if test_y > 19:
            test_y = 19

        vas_structure.moveable_pts[index] = [test_x, test_y]
        flowDict = computeFlow(vas_structure)
        vas_structure.add_flows_to_img(flowDict)
        mvable_pts = vas_structure.moveable_pts

        loss = fitness(mvable_pts, i)
        if loss < currentLoss:
            currentLoss = loss
            dImproved = True
            all_loss.append(loss)
            callback(mvable_pts, i)
            time_lst.append(i)
            print(i, 'REDUCED LOSS:', loss)
            vas_structure.update_hillclimb_pts(mvable_pts)
            vas_structure.print_images(graph_name=sim_graph_folder+'test_graph'+str(i)+'.png', img_name=sim_img_folder+'test_img'+str(i)+'.png')
        else:
            if temperature - (loss - currentLoss) > 0:
                temperature = temperature - (loss - currentLoss)
                currentLoss = loss
                all_loss.append(loss)
                callback(mvable_pts, i)
                time_lst.append(i)
                dImproved = False
                print(i, 'TOOK WORSE LOSS, REMAINING TEMP: ', temperature, 'NEW LOSS:', currentLoss)
                vas_structure.update_hillclimb_pts(mvable_pts)
                vas_structure.print_images(graph_name=sim_graph_folder+'test_graph'+str(i)+'.png', img_name=sim_img_folder+'test_img'+str(i)+'.png')
            else:
                vas_structure.moveable_pts[index] = originalPoints
                mvable_pts = vas_structure.moveable_pts
                dImproved = False
                print(i, 'LOSS IS >= CURRENT')

    def img_path_generator(path_to_img_dir):
        for i, file_name in enumerate(natsorted(os.listdir(path_to_img_dir), key=lambda y: y.lower())):
            if file_name.endswith('.png'):
                if not i == 0:
                    file_path = os.path.join(path_to_img_dir, file_name)
                    yield imageio.imread(file_path)

    sim_fig_folder = 'HillClimb/figs/'
    imageio.mimsave('HillClimb/HillClimb_Figs.gif', img_path_generator(sim_fig_folder), fps=8)


from __future__ import print_function, absolute_import

import os
import vtk
import platform
import numpy as np
from vtk.util import numpy_support

if platform.uname().system.lower() == 'windows':
    # VTK warnings crashes python on windows
    vtk.vtkObject.SetGlobalWarningDisplay(False)

def _indices(extent):
    """
        Indices to data in full volume
    """
    if len(extent) == 4:
        return np.meshgrid(np.arange(extent[2], extent[3] + 1),
                           np.arange(extent[0], extent[1] + 1))

    return np.meshgrid(np.arange(extent[2], extent[3] + 1),
                       np.arange(extent[0], extent[1] + 1),
                       np.arange(extent[4], extent[5] + 1))

def dtype(i):
    """
        Map VTK type i to numpy.dtype
    """
    if i == vtk.VTK_CHAR:
        return np.int8
    elif i == vtk.VTK_UNSIGNED_CHAR:
        return np.uint8
    elif i == vtk.VTK_SHORT:
        return np.int16
    elif i == vtk.VTK_UNSIGNED_SHORT:
        return np.uint16
    elif i == vtk.VTK_INT:
        return np.int32
    elif i == vtk.VTK_UNSIGNED_INT:
        return np.uint32
    elif i == vtk.VTK_LONG:
        return np.int64
    elif i == vtk.VTK_UNSIGNED_LONG:
        return np.uint64
    elif i == vtk.VTK_FLOAT:
        return np.float32
    elif i == vtk.VTK_DOUBLE:
        return np.float64
    elif i == vtk.VTK_LONG_LONG:
        return np.int128 if hasattr(np, 'int128') else np.int64
    elif hasattr(np, 'uint128') and i == vtk.VTK_UNSIGNED_LONG_LONG:
        return np.uint128
    else:
        raise ValueError('Cannot understand type {}'.format(i))

def vtk_type(i):
    """
        Map numpy.dtype i to VTK type
    """
    if i == np.int8:
        return vtk.VTK_CHAR
    elif i == np.uint8:
        return vtk.VTK_UNSIGNED_CHAR
    elif i == np.int16:
        return vtk.VTK_SHORT
    elif i == np.uint16:
        return vtk.VTK_UNSIGNED_SHORT
    elif i == np.int32:
        return vtk.VTK_INT
    elif i == np.uint32:
        return vtk.VTK_UNSIGNED_INT
    elif i == np.int64:
        return vtk.VTK_LONG
    elif i == np.uint64:
        return vtk.VTK_UNSIGNED_LONG
    elif i == np.float32:
        return vtk.VTK_FLOAT
    elif i == np.float64:
        return vtk.VTK_DOUBLE
    elif hasattr(np, 'int128') and i == np.int128:
        return vtk.VTK_LONG_LONG
    elif hasattr(np, 'uint128') and i == np.uint128:
        return vtk.VTK_UNSIGNED_LONG_LONG
    else:
        raise ValueError('Cannot understand dtype {}'.format(i))

def create(array):
    """
        Return numpy array 'arr' as VTKImage array
    """
    return array.view(VTKImage)

class VTKInformation(dict):
    """
        Holds image metadata

            * datatype, VTK datatype, int
            * bounds, bounds of the geometry, size 6
            * center, center of the geometry, size 3
            * dimensions, size of the geometry, size 6
            * extent, six integers - give the index of the first and last
                      point in each direction
            * origin,
            * spacing,

        :param path:
            Path to vtk image

        :param reader:
            Instance of a vtk image reader
    """
    def __init__(self, path=None, reader=None):
        self.path = path

        if self.path is None and reader is None:
            return

        _del_reader = False

        if reader is None:
            if not isinstance(path, str):
                raise ValueError('path has to be of type string, not {}'
                                 .format(type(path)))

            if not os.path.exists(self.path):
                raise IOError("No such file or directory: '{}'"
                              .format(self.path))

            reader = vtk.vtkXMLImageDataReader()
            reader.SetFileName(self.path)
            _del_reader = True
        elif isinstance(reader, vtk.vtkXMLImageDataReader):
            self.path = reader.GetFileName()

            if self.path is None or not os.path.exists(self.path):
                raise ValueError('vtkXMLImageDataReader improperly configured.'
                                 ' Image path is empty or does not exist')
        else:
            if not hasattr(reader, 'Update') and not hasattr(reader, 'GetOutput'):
                if hasattr(reader, 'GetClassName'):
                    name = reader.GetClassName()
                else:
                    name = type(reader)

                raise ValueError('Unsupported reader, {}'.format(name))

        reader.Update()
        output = reader.GetOutput()

        self.datatype = output.GetPointData().GetArray(0).GetDataType()
        self.bounds = output.GetBounds()
        self.center = output.GetCenter()
        self.dimensions = output.GetDimensions()
        self.extent = output.GetExtent()
        self.origin = output.GetOrigin()
        self.spacing = output.GetSpacing()

        if _del_reader:
            del reader
            del output

        super(VTKInformation, self).__init__(self, extent=self.extent,
                                             origin=self.origin,
                                             spacing=self.spacing)

    @property
    def dtype(self):
        return dtype(self.datatype)

    def __repr__(self):
        return str(dict(
            datatype=self.datatype,
            dtype=dtype(self.datatype),
            bounds=self.bounds,
            center=self.center,
            dimensions=self.dimensions,
            extent=self.extent,
            origin=self.origin,
            spacing=self.spacing,
        ))

class VTKImage(np.ndarray):
    """
        Numpy ndarray wrapper for VTK images. This class holds meta data
        about the image such that reading and writing to file will keep
        the correct attributes

        >>> import numpy as np
        >>> import dictlearn as dl
        >>> # volume is a numpy array
        >>> volume = VTKImage.read('path/to/volume.vti')
        >>> assert isinstance(volume, np.ndarray)
        >>> prod = np.dot(volume[:10, :10], np.random.rand(10, 5))
        >>> assert prod.shape == (10, 5)

        >>> patches = dl.Patches(volume)
        >>> patch_generator = patches.create_batch_and_reconstruct(10000):
        >>> for batch, reconstruct in patch_generator:
        >>>     # Handle batch
        >>>     reconstruct(batch)

        Write 'patches.reconstructed' to disk with the
        same attributes as 'path/to/volume.vti'

        >>> volume.write('path/to/volume_new.vti', patches.volume)
    """
    ORIGIN = np.array([0, 0, 0], np.float32)
    SPACING = np.array([1, 1, 1], np.float32)

    # todo pickle support for faster to/from python

    @property
    def dimensions(self):
        return (self.extent[1] - self.extent[0] + 1,
                self.extent[3] - self.extent[2] + 1,
                self.extent[5] - self.extent[4] + 1)

    def information(self):
        """
            Get image meta data. See VTKInformation
        """
        if not hasattr(self, '_info'):
            self._info = VTKInformation()
            self._info.datatype = self.datatype
            self._info.bounds = self.bounds
            self._info.center = self.center
            self._info.dimensions = self.dimensions
            self._info.extent = self.extent
            self._info.origin = self.origin
            self._info.spacing = self.spacing

        return self._info

    @property
    def info(self):
        return self.information()

    @staticmethod
    def from_array(array, info=None):
        """
            Create a VTKImage from a numpy array
        """

        if array.ndim != 3:
            raise ValueError('Need array.ndim == 3, not {}'.format(array.ndim))

        if not isinstance(array, np.ndarray):
            array = np.asarray(array)

        obj = array.view(VTKImage)

        if info is None:
            obj.origin = (0, 0, 0)
            obj.spacing = (1, 1, 1)
            x, y, z = array.shape
            obj.extent = (0, x - 1, 0, y - 1, 0, z - 1)
            obj.bounds = obj.extent
            obj.center = np.array(obj.extent)[1::2] / 2.0
            obj.datatype = vtk_type(array.dtype)
        else:
            obj.origin = info.origin
            obj.spacing = info.spacing
            obj.extent = info.extent
            obj.bounds = info.bounds
            obj.center = info.center
            obj.datatype = info.datatype

        return obj

    @staticmethod
    def from_image_data(image_data, name=None):
        """
            Crate VTKImage from vtkImageData

        :param image_data:
            vtk.vtkImageData instance

        :param name:
            Name of point array to extract. Defaults to array at
            index 0

        :return:
            VTKImage
        """

        if not isinstance(image_data, vtk.vtkImageData):
            raise ValueError("'image_data' is not vtk.vtkImageData, but {}"
                             .format(str(image_data)))

        bounds = image_data.GetBounds()
        center = image_data.GetCenter()
        dimensions = image_data.GetDimensions()
        extent = image_data.GetExtent()
        origin = image_data.GetOrigin()
        spacing = image_data.GetSpacing()

        array = image_data.GetPointData().GetArray(0 if name is None else name)
        datatype = array.GetDataType()

        array = numpy_support.vtk_to_numpy(array)
        array = array.reshape(*dimensions, order='F')
        obj = array.view(VTKImage)
        obj.bounds = bounds
        obj.center = center
        obj.extent = extent
        obj.origin = origin
        obj.spacing = spacing
        obj.datatype = datatype

        return obj

    @staticmethod
    def from_dicom(filename):
        raise NotImplementedError()

    @staticmethod
    def read(path, name=None):
        """
        Read a vti image.

        :param path:
            Path to file

        :param name:
            Name or index of array.
            If 'name' is None then array at index 0 is returned

        :return:
            VTKImage instance
        """
        if not os.path.exists(path):
            raise IOError("No such file or directory: '{}'"
                          .format(path))

        reader = vtk.vtkXMLImageDataReader()
        reader.SetFileName(path)
        reader.Update()

        output = reader.GetOutput()
        obj = VTKImage.from_image_data(output, name)
        obj.info.path = path
        del output
        del reader
        return obj

    def write(self, path, array=None):
        """
            Write data (array or self) to 'vti' file. This file is written with
            self.extent, self.origin, self.spacing and self.dtype.
            If the instance is created with VTKImage.read() these attributes
            are copied from the read file, otherwise the default values are used:

                * extent = [0, self.dimensions[0] - 1,
                            0, self.dimensions[1] - 1,
                            0, self.dimensions[2] - 1]

                * origin = [0, 0, 0]
                * spacing = [1, 1, 1]
                * dtype = np.float64

        :param path:
            Filename, where to save

        :param array:
            Optional, if array is None 'self' is written to file.
            If array is not None then array is written to file

        :return:
            True if writing successful
        """
        if array is not None:
            if array.shape != self.dimensions:
                raise ValueError(
                    'Incompatible dimensions read image {} and array {}'
                    .format(self.dimensions, array.shape)
                )

        image = self if array is None else array

        return VTKImage.write_vti(path, image, self.extent,
                                  self.origin, self.spacing)

    @staticmethod
    def write_vti(path, array, info=None, extent=None, origin=None,
                  spacing=None, use_array_type=True, name='ImageScalars'):
        """
            Write 'array' to 'path' as vti file

        :param path:
            Where to write

        :param array:
            Data to write, ndarray with array.ndim == 3

        :param info:
            Optional instance of VTKInformation, overwrites extent, origin
            and spacing.

        :param extent:
            Data extent, array like, len(extent) == 6. Default [0, array.shape[0] - 1,\
            0, array.shape[1] - 1, 0, array.shape[2] - 1]

        :param origin:
            Data origin, default [0, 0, 0]

        :param spacing:
            Spacing between voxels, default [1, 1, 1]

        :param use_array_type:
            Only used if info is not None. If this is False the image is
            saved with the data type given by info, otherwise
            array.dtype is used

        :param name:
            Name of scalar array

        :return:
            True if write successful
        """
        dimensions = array.shape
        datatype = vtk_type(array.dtype)

        if info is not None:
            extent = info.extent
            origin = info.origin
            spacing = info.spacing

            if not use_array_type:
                datatype = info.datatype
        else:
            if extent is None:
                extent = np.zeros(2 * array.ndim, np.int32)
                extent[1::2] = np.asarray(dimensions, np.int32) - 1

            if origin is None:
                origin = VTKImage.ORIGIN

            if spacing is None:
                spacing = VTKImage.SPACING

        importer = vtk.vtkImageImport()
        importer.SetDataScalarType(datatype)
        importer.SetNumberOfScalarComponents(1)
        importer.SetDataExtent(extent)
        importer.SetWholeExtent(extent)
        importer.SetDataOrigin(origin)
        importer.SetDataSpacing(spacing)
        importer.SetScalarArrayName(name)

        array = array.astype(dtype(datatype))
        size = len(array.flat)*array.dtype.itemsize
        array = array.flatten('F')
        vtk_array = numpy_support.numpy_to_vtk(array, 0, datatype)
        # Set pointer to image scalars
        importer.CopyImportVoidPointer(vtk_array.GetVoidPointer(0), size)
        importer.Update()
        data = importer.GetOutput()

        writer = vtk.vtkXMLImageDataWriter()
        writer.SetFileName(path)
        writer.SetInputData(data)
        return bool(writer.Write())

    def print(self):
        """
            Print image information
        """
        string = 'VTKImage:\n  dimensions {}\n'.format(self.dimensions)
        string += '  bounds {}\n'.format(self.bounds)
        string += '  center {}\n'.format(self.center)
        string += '  extent {}\n'.format(self.extent)
        string += '  origin {}\n'.format(self.origin)
        string += '  spacing {}\n'.format(self.spacing)
        print(string)

    def copy(self, order='C'):
        """
        Return a copy of the image

        :param order: {'C', 'F', 'A', 'K'}, optional
            Controls the memory layout of the copy. 'C' means C-order,
            'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
            'C' otherwise. 'K' means match the layout of `a` as closely
            as possible.
        """
        res = np.ndarray.copy(self, order)
        try:
            res.bounds = self.bounds
            res.center = self.center
            res.extent = self.extent
            res.origin = self.origin
            res.spacing = self.spacing
            res.datatype = self.datatype
        except AttributeError:
            # Trying to copy a slice of this array
            # Don't need to keep track of the stuff above.
            # Ex: self[12].copy()
            # Implement __getitem__ to fix
            pass

        return res

def vtp_to_vti(surface, information, invalue=1, outvalue=0, flip=None):
    """
    Convert a closed surface to ImageData using
    vtkPolyDataToImageStencil. All points on or inside
    the takes 'invalue' while all point outside the
    surface takes 'outvalue'

    :param surface:
        Path to surface file

    :param information:
        Information about the volume to create. Either an
        instance of VTKInformation or path to a vti file. If
        this is a path to an image, its attributes are copied
        to the converted image

    :param invalue:
        Value of points inside or of the surface

    :param outvalue:
        Value of points outside the surface.

    :param flip:
        Flip around an axis, options: 'x', 'y', 'z' or None to keep
        as is

    :return:
        An instance of VTKImage
    """

    if not isinstance(surface, str) or not os.path.isfile(surface):
        raise IOError("No such file or directory: '{}'".format(surface))

    if not isinstance(information, VTKInformation):
        if os.path.isfile(information):
            information = VTKInformation(information)
        else:
            raise IOError("No such file or directory: '{}'".format(surface))

    reader = vtk.vtkXMLPolyDataReader()
    reader.SetFileName(surface)
    reader.Update()
    polydata = reader.GetOutput()
    del reader

    # Foreground, takes value invalue on all point
    # inside or on the surface
    image_data = vtk.vtkImageData()
    image_data.SetSpacing(information.spacing)
    image_data.SetOrigin(information.origin)
    image_data.SetDimensions(information.dimensions)
    image_data.SetExtent(information.extent)
    image_data.AllocateScalars(information.datatype, 1)

    num_points = image_data.GetNumberOfPoints()

    for i in range(num_points):
        image_data.GetPointData().GetScalars().SetTuple1(i, invalue)

    # Surface stencil
    stencil = vtk.vtkPolyDataToImageStencil()
    stencil.SetInputData(polydata)
    stencil.SetOutputOrigin(information.origin)
    stencil.SetOutputSpacing(information.spacing)
    stencil.SetOutputWholeExtent(image_data.GetExtent())
    stencil.Update()

    # Image stencil. All points not in stencil
    # gets value outvalue
    img_stencil = vtk.vtkImageStencil()
    img_stencil.SetInputData(image_data)
    img_stencil.SetStencilConnection(stencil.GetOutputPort())
    img_stencil.ReverseStencilOff()
    img_stencil.SetBackgroundValue(outvalue)
    img_stencil.Update()

    image = img_stencil.GetOutput()

    if flip is not None:
        axes = {'x': 0, 'y': 1, 'z': 2}
        flipper = vtk.vtkImageFlip()
        flipper.SetFilteredAxis(axes[flip])
        flipper.SetInputData(image)
        flipper.Update()
        image = flipper.GetOutput()

    return VTKImage.from_image_data(image)

def as_image_data(volume, info=None):
    """
        Convert a numpy array 'volume' to vtk.vtkImageData
    """
    if info is None and not isinstance(volume, VTKImage):
        raise ValueError('Need info instance of VTKInformation or '
                         'volume instance of VTKImage')

    if info is None:
        info = volume.information()

    # TODO: Fix seg fault when extent is not (0, x, 0, y, 0, z)
    # it's an issue with python's gc. The allocated memory
    # for importer.GetOutput() is freed when vtk_array goes
    # out of scope
    importer = vtk.vtkImageImport()
    importer.SetDataScalarType(info.datatype)
    importer.SetNumberOfScalarComponents(1)
    importer.SetDataExtent(info.extent)
    importer.SetWholeExtent(info.extent)
    importer.SetDataOrigin(info.origin)
    importer.SetDataSpacing(info.spacing)

    size = len(volume.flat)*volume.dtype.itemsize
    array = volume.flatten('F')
    vtk_array = numpy_support.numpy_to_vtk(array, 1, info.datatype)
    # Set pointer to image scalars
    importer.CopyImportVoidPointer(vtk_array.GetVoidPointer(0), size)
    importer.Update()
    return vtk_array, importer.GetOutput()

def marching_cubes(image_data, contours, connectivity=False, path=None):
    """
    """
    if isinstance(image_data, VTKImage):
        info = image_data.information()
        importer = vtk.vtkImageImport()
        importer.SetDataScalarType(info.datatype)
        importer.SetNumberOfScalarComponents(1)
        importer.SetDataExtent(info.extent)
        importer.SetWholeExtent(info.extent)
        importer.SetDataOrigin(info.origin)
        importer.SetDataSpacing(info.spacing)

        size = len(image_data.flat) * image_data.dtype.itemsize
        array = image_data.flatten('F')
        vtk_array = numpy_support.numpy_to_vtk(array, 1, info.datatype)
        importer.CopyImportVoidPointer(vtk_array.GetVoidPointer(0), size)
        importer.Update()
        image_data = importer.GetOutput()

    if isinstance(contours, (int, float)):
        contours = (contours, )

    contour = vtk.vtkMarchingContourFilter()
    contour.SetInputData(image_data)

    for i, value in enumerate(contours):
        contour.SetValue(0, value)

    contour.Update()
    poly_data = contour.GetOutput()

    if connectivity:
        connectivity = vtk.vtkConnectivityFilter()
        connectivity.SetInputData(poly_data)
        connectivity.SetExtractionModeToLargestRegion()
        connectivity.Update()

        mapper = vtk.vtkGeometryFilter()
        mapper.SetInputData(connectivity.GetOutput())
        mapper.Update()
        poly_data = mapper.GetOutput()

    if isinstance(path, str):
        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetFileName(path)
        writer.SetInputData(poly_data)
        writer.Write()

    return poly_data


# Enter your code here. Read input from STDIN. Print output to STDOUT
import re

def is_valid_regex(regex):
    try:
        re.compile(regex)
        return True
    except re.error:
        return False

n = int(input())

for i in range(n):
    print(is_valid_regex(input()))


def AMCount():
    a_count = 0
    m_count = 0
    with open('poem.txt', 'r') as file:
        content = file.read()
        for i in range(len(content)):
            if (content[i] == 'a' or content[i] == 'A'):
                a_count += 1
            elif (content[i] == 'm' or content[i] == 'M'):
                m_count += 1
    print('A or a: {}; M or m: {}'.format(a_count, m_count))

    # Another approach
    # for letter in content:
    #     if letter == 'A' or letter == 'a':
    #          a_count += 1
    #     elif (letter == 'm' or letter == 'M'):
    #         m_count += 1

AMCount()


import datetime
import os

from twilio.rest import Client

CHECKIN_MSG_TEMPLATE = (
    '{date} ({day})\n' +
    'Please confirm you have taken your medicine today (Yes/No).'
)

def make_checkin_message():
    today = datetime.datetime.today()
    weekday = today.strftime("%a")
    date = "%s/%s" %(today.month, today.day)

    return CHECKIN_MSG_TEMPLATE.format(date=date,
        day=weekday)

if __name__ == "__main__":
    account = os.environ["TWILIO_ACCOUNT"]
    token = os.environ["TWILIO_AUTH_TOKEN"]
    twilio_number = os.environ["TWILIO_PHONE_NUMBER"]
    home_number = os.environ["TWILIO_HOME_PHONE_NUMBER"]

    client = Client(account, token)
    checkin_message = make_checkin_message()

    message = client.messages.create(from_=twilio_number,
        to=home_number, body=checkin_message)


class Solution(object):
    def wordsTyping(self, sentence, rows, cols):
        #print "\n"
        end, left, res = cols - 1, rows, 0
        precomputed = [None] * (cols + 1)

        def compute(start):
            """computes in a DP fashion how many lines it takes
            to write all words in senteces, return lines and end"""
            #print "call compute "+str(start)
            if precomputed[start] is not None:
                return precomputed[start]
            height, index = 0, start
            for word in sentence:
                if index + len(word) + 1 > cols:
                    index = len(word)
                    height += 1
                else:
                    index += len(word) + 1
                #print word, index
            precomputed[start] = (index, height)
            #print index, height
            return index, height

        total_len = sum([len(word) for word in sentence]) + len(sentence)
        while left >= 0:
            start = end
            res += (cols - start) / total_len
            start += ((cols - start) / total_len) * total_len
            res += 1
            end, height = compute(start)
            left -= height
        return res - 1


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

import inspect

import discord

def control(reaction):
    def inner(func):
        func.__map_reaction__ = reaction

        return func

    return inner

class MapSession:
    def __init__(self, ctx, map_array):
        self.ctx = ctx

        self.current_pos = [0, 0]
        self.msg = None
        self._task = None

        def is_control(thing):
            return inspect.ismethod(thing) and hasattr(thing, "__map_reaction__")

        self.controls = {
            emoji: func
            for emoji, func in [(x.__map_reaction__, x) for _, x in inspect.getmembers(self, is_control)]
        }

        self.original_map = map_array
        self.map_copy = map_array.copy()

    @property
    def alive(self):
        return not self._task.done()

    def start(self):
        self._task = self.ctx.bot.loop.create_task(self.task())

    async def cancel(self):
        self._task.cancel()
        del self.ctx.bot.sessions[f"{self.ctx.author.id}-{self.ctx.guild.id}"]

        if self.msg is not None:
            try:
                await self.msg.edit(content="Session cancelled.", embed=None)
            except discord.HTTPException:
                pass

            try:
                await self.msg.clear_reactions()
            except discord.HTTPException:
                try:
                    await self.msg.delete()
                except discord.HTTPException:
                    pass

    def check(self, payload):
        return (str(payload.emoji) in self.controls
                and payload.user_id == self.ctx.author.id
                and payload.message_id == self.msg.id)

    def make_embed(self):
        embed = discord.Embed(description=self.render_map())

        embed.add_field(
            name="Current tile",
            value=f"You landed on a **{self.original_map[self.current_pos[0]][self.current_pos[1]]}** tile!"
        )

        return embed

    @control("\U000025b6")
    def right(self):
        if not self.current_pos[1] == (len(self.original_map[self.current_pos[0]]) - 1):
            self.current_pos[1] += 1

    @control("\U0001f53d")
    def down(self):
        if not self.current_pos[0] == (len(self.map_copy) - 1):
            self.current_pos[0] += 1

    @control("\U000025c0")
    def left(self):
        if not self.current_pos[1] == 0:
            self.current_pos[1] -= 1

    @control("\U0001f53c")
    def up(self):
        if not self.current_pos[0] == 0:
            self.current_pos[0] -= 1

    @control("\U000023f9")
    async def stop(self):
        await self.cancel()

    async def task(self):
        self.map_copy[0][0] = 200

        self.msg = await self.ctx.send(embed=self.make_embed())

        for reaction in sorted(self.controls.keys(), reverse=True):
            await self.msg.add_reaction(reaction)

        while True:
            payload = await self.ctx.bot.wait_for("raw_reaction_add", check=self.check)

            pos = self.current_pos
            self.map_copy[pos[0]][pos[1]] = self.original_map[pos[0]][pos[1]]

            func = self.controls[str(payload.emoji)]

            if inspect.iscoroutinefunction(func):
                await func()
            else:
                func()

            self.map_copy[self.current_pos[0]][self.current_pos[1]] = 200

            await self.msg.edit(embed=self.make_embed())

    def render_map(self):
        fmt = ""

        for line in self.map_copy:
            for tile in line:
                if tile == 200:
                    fmt += "<:player:609140893563355137>"
                    continue
                fmt += f"{tile}\N{combining enclosing keycap}"
            fmt += "\n"

        return fmt


import os
from decouple import config
from datetime import timedelta

BASE_DIR = os.path.dirname(os.path.realpath(__file__))

uri = config('DATABASE_URL') #or other relevant config var
if uri.startswith('postgres://'):
    uri = uri.replace('postgres://', 'postgresql://', 1)

authorization = {
        'security':[{"bearerAuth": []}],
        'components':{
            "securitySchemes":
                {
                    "bearerAuth": {
                        "type":"http",
                        "scheme": "bearer",
                        "bearerFormat": "JWT",
                        "description": "Add a JWT Token to the header ** < JWT > ** to get authorized"
                    }

                    # USE THE CONFIGURATION BELOW FOR apiKey
                    # "bearerAuth": {
                    #     "type":"apiKey",
                    #     "in": "header",
                    #     "name": "Authorization",
                    #     "description": "Add a JWT Token to the header with ** Bearer < JWT > ** to get authorized"
                    # }
                }
        }
    }

class Config:
    SECRET_KEY = config('SECRET_KEY', 'secret')
    JWT_ACCESS_TOKEN_EXPIRES = timedelta(minutes=60)
    JWT_REFRESH_TOKEN_EXPIRES = timedelta(minutes=60)
    JWT_SECRET_KEY = config('JWT_SECRET_KEY', 'jwt_secret')

    PROPAGATE_EXCEPTIONS = True
    API_TITLE = "Student Management API"
    API_VERSION = "v1"
    OPENAPI_DESCRIPTION = "A student Management system for registering students and courses"
    API_SPEC_OPTIONS = authorization
    OPENAPI_VERSION = "3.0.3"
    OPENAPI_URL_PREFIX = "/"
    OPENAPI_SWAGGER_UI_PATH = ""
    OPENAPI_SWAGGER_UI_URL = "https://cdn.jsdelivr.net/npm/swagger-ui-dist/"

class DevConfig(Config):
    DEBUG = True
    SQLALCHEMY_ECHO = True
    SQLALCHEMY_TRACK_MODIFICATION = False
    SQLALCHEMY_DATABASE_URI = 'sqlite:///'+os.path.join(BASE_DIR, 'db.sqlite3')

class TestConfig(Config):
    TESTING = True
    SQLALCHEMY_ECHO = True
    SQLALCHEMY_TRACK_MODIFICATION = False
    SQLALCHEMY_DATABASE_URI = 'sqlite://' #THIS USES SQL MEMORY DATABASE INSTEAD OF CREATING A NEW ONE

class ProdConfig(Config):
    SQLALCHEMY_DATABASE_URI = uri
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    DEBUG = config('DEBUG', False, cast=bool)
    # pass

config_dict = {
    'dev': DevConfig,
    'prod': ProdConfig,
    'test': TestConfig
}


import numpy as np

from torch import nn

from .ode_solvers import euler_step
from .neural_ode_solvers import AdjointODE

class ResidualBlock(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(ResidualBlock, self).__init__()
        stride = (1, 1)
        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=(3, 3),
                               stride=stride, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=(3, 3),
                               stride=(1, 1), padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(out_channels)

    def forward(self, x):
        residual = x
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)
        out = self.conv2(out)
        out = self.bn2(out)
        out += residual
        out = self.relu(out)
        return out

class ODEResFunc(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(ODEResFunc, self).__init__()
        stride = (1, 1)
        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=(3, 3),
                               stride=stride, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=(3, 3),
                               stride=(1, 1), padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(out_channels)

    def forward(self, x):
        x = x[1]
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)
        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)
        return out

class ODEBlock(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(ODEBlock, self).__init__()
        ode_solver = euler_step
        timestamps = np.linspace(0, 1., 11)
        self.neural_ode = AdjointODE(ode_func=ODEResFunc(in_channels, out_channels),
                                     timestamps=timestamps,
                                     ode_solver=ode_solver)

    def forward(self, x):
        self.neural_ode(x)
        return x

class MNISTClassifier(nn.Module):
    def __init__(self, block_type, channels=(1, 64, 64, 128, 128, 10)):
        super(MNISTClassifier, self).__init__()
        stride = (1, 1)
        self.conv1 = nn.Conv2d(channels[0], channels[1], kernel_size=(3, 3),
                               stride=stride, padding=1, bias=False)

        self.layer1 = nn.Sequential(
            block_type(channels[1], channels[1]),
            block_type(channels[1], channels[1]))

        self.maxpool1 = nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2), padding=(1, 1), dilation=1, ceil_mode=False)

        self.conv2 = nn.Conv2d(channels[1], channels[2], kernel_size=(3, 3),
                               stride=stride, padding=1, bias=False)
        self.layer2 = nn.Sequential(
            block_type(channels[2], channels[2]),
            block_type(channels[2], channels[2]))

        self.maxpool2 = nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2), padding=(1, 1), dilation=1, ceil_mode=False)

        self.conv3 = nn.Conv2d(channels[2], channels[3], kernel_size=(3, 3),
                               stride=stride, padding=1, bias=False)
        self.layer3 = nn.Sequential(
            block_type(channels[3], channels[3]),
            block_type(channels[3], channels[3]))

        self.maxpool3 = nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2), padding=(1, 1), dilation=1, ceil_mode=False)

        self.conv4 = nn.Conv2d(channels[3], channels[4], kernel_size=(3, 3),
                               stride=stride, padding=1, bias=False)

        self.layer4 = nn.Sequential(
            block_type(channels[4], channels[4]),
            block_type(channels[4], channels[4]))

        self.maxpool4 = nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2), padding=(1, 1), dilation=1, ceil_mode=False)

        self.avgpool = nn.AdaptiveAvgPool2d(output_size=1)
        self.dropout = nn.Dropout(0.5)

        self.fc = nn.Linear(channels[4], channels[5])
        self.softmax = nn.LogSoftmax(dim=-1)

    def forward(self, x):
        out = self.conv1(x)
        out = self.layer1(out)
        out = self.maxpool1(out)

        out = self.conv2(out)
        out = self.layer2(out)
        out = self.maxpool2(out)

        out = self.conv3(out)
        out = self.layer3(out)
        out = self.maxpool3(out)

        out = self.conv4(out)
        out = self.layer4(out)
        out = self.maxpool4(out)

        out = self.avgpool(out)
        out = self.dropout(out)
        out = out[:, :, 0, 0]
        out = self.fc(out)
        out = self.softmax(out)
        return out


'''
Leetcode 24 submission
Your runtime beats 90.27 % of python3 submissions.
'''
from collections import deque as _deque

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

def solve(head):
    # simple return cases
    if head and head.next:
        deque = _deque()
        deque.append(head)
        deque.append(head.next)
        head = head.next
    else:
        return head

    while len(deque) >= 2:
        # swap the latest pair's pointer
        deque[-2].next, deque[-1].next = deque[-1].next, deque[-2]

        # swap them in the deque so they make sequential sense
        deque[-1], deque[-2] = deque[-2], deque[-1]

        # update the rightmost of the previous pair as it's neighbor changed
        if len(deque) > 2:
            deque[-3].next = deque[-2]

        # the leftmost element is now totally complete, so we pop it
        deque.popleft()

        # enqueue iff another non-null pair to swap is possible
        if deque[-1].next and deque[-1].next.next:
            deque.append(deque[-1].next)
            deque.append(deque[-1].next)
        else:
            break

    return head

def execute_tests():
    simple = ListNode(1)
    simple.next = ListNode(2)
    simple.next.next = ListNode(3)
    simple.next.next.next = ListNode(4)

    ans = "2143"

    for test_case in [(simple, ans)]:
        test(*test_case)

def test(head, expected):
    answer = solve(head)
    print(as_string((answer)))
    assert as_string(answer) == expected

def as_string(head):
    s = ''
    while head:
        s += str(head.x)
        head = head.next
    return s

def main():
    return execute_tests()

if __name__ == '__main__':
    main()


#!/usr/bin/env python

##from https://github.com/NamWoo

from __future__ import print_function
#import roslib
#roslib.load_manifest('my_package')
import sys
import rospy
import cv2
import numpy as np
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError

from line_functions import *

class image_converter:
    def __init__(self):
    # self.image_pub = rospy.Publisher("image_topic_2",Image)
        ros_topic = "rgb"
        self.bridge = CvBridge()
        self.image_sub = rospy.Subscriber(ros_topic, Image, self.callback)
        cv2.namedWindow("output", cv2.WINDOW_GUI_EXPANDED)
        rospy.loginfo("ros camera : %s", ros_topic)

    def callback(self,data):
        try:
            cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8")
        except CvBridgeError as e:
            print(e)

        cv_image = line_dectecting(cv_image)

        cv2.imshow("output", cv_image)
        cv2.waitKey(3)

    # try:
    #   self.image_pub.publish(self.bridge.cv2_to_imgmsg(cv_image, "bgr8"))
    # except CvBridgeError as e:
    #   print(e)

def main(args):
    ic = image_converter()
    rospy.init_node('image_converter', anonymous=True)
    try:
        rospy.spin()
    except KeyboardInterrupt:
        print("Shutting down")
    cv2.destroyAllWindows()

def nothing(x):
    pass

if __name__ == '__main__':
    main(sys.argv)


from respect_validation.Exceptions.FilteredValidationException import FilteredValidationException

class SpaceException(FilteredValidationException):

    _default_templates = {
        'default': {
            'standard': '{name} must contain only space characters',
            'extra': '{name} must contain only space characters and {additional_chars}',
        },
        'negative': {
            'standard': '{name} must not contain space characters',
            'extra': '{name} must not contain space characters or {additional_chars}',
        }
    }


import time

def print_rangoli(size):
    string = "abcdefghijklmnopqrstuvwxyz"
    list = []
    for i in range(size):
        x = string[size-1-i:size]
        for char in x[::-1]:
            list.append(char)

        for char in x[1:len(x)]:
            list.append(char)

        x = "-".join(list)
        print(int((4*size-3-len(x))/2)*"-"+x+int((4*size-3-len(x))/2)*"-")
        list.clear()
        x = ""

    for i in range(size-1): #i = 0,1,2,3,4
        y = string[i+1:size]

        for char in y[::-1]:
            list.append(char)

        for char in y[1:len(y)]:
            list.append(char)

        x = "-".join(list)
        print(int((4*size-3-len(x))/2)*"-"+x+int((4*size-3-len(x))/2)*"-")
        list.clear()
        x = ""

if __name__ == '__main__':
    while 1:
        n = int(input("sayı giriniz:"))
        print_rangoli(n)
        time.sleep(1)


import os
import pandas as pd
from ast import literal_eval

data_directory = os.path.join(os.path.split(os.getcwd())[0], 'data')
for big_category in ['beauty', 'fashion', 'mobile']:
    train = pd.read_csv(os.path.join(data_directory, f'{big_category}_train_split.csv'))
    valid = pd.read_csv(os.path.join(data_directory, f'{big_category}_valid_split.csv'))
    train['filler_column'] = 'a'
    valid['filler_column'] = 'a'
    train['extractions'] = train['extractions'].map(literal_eval)
    valid['extractions'] = valid['extractions'].map(literal_eval)
    train['extractions'] = train['extractions'].map(
        lambda s: ' '.join(s) if s else pd.NaT)
    valid['extractions'] = valid['extractions'].map(
        lambda s: ' '.join(s) if s else pd.NaT)
    train = train.dropna()
    valid = valid.dropna()
    train_output = train[['Category', 'filler_column', 'extractions']]
    valid_output = valid[['Category', 'filler_column', 'extractions']]
    print(train_output.shape)
    print(valid_output.shape)
    #test_output = valid[['Category', 'title']]
    output_dir = os.path.join(data_directory, 'tsvs', 'extractions', big_category)
    if not os.path.isdir(output_dir):
        os.makedirs(output_dir, exist_ok=True)
    train_output.to_csv(os.path.join(output_dir, 'train.tsv'),
                        sep='\t', index=True, header=False)
    valid_output.to_csv(os.path.join(output_dir, 'dev.tsv'),
                        sep='\t', index=True, header=False)
    #test_output.to_csv(os.path.join(data_directory, f'{big_category}_valid.tsv'),
    #                    sep='\t', index=False, header=['id', 'sentence'])


import datetime
def validade():
    fabricacao_str = input('Data de fabricação: ')
    fabricacao = datetime.datetime.strptime(fabricacao_str, '')

    prazo_em_dias = int(input('Prazo de validade em dias: '))
    intervalo_validade = datetime.timedelta(day=prazo_em_dias)

    data_de_validade = fabricacao + intervalo_validade

    print(data_de_validade)

if __name__ == '__main__':
    validade()


"""quarantine URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/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.conf.urls import include
from django.contrib import admin
from django.urls import path
from . import settings
from website import views

from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.static import serve
from django.conf.urls import url

urlpatterns = [

    path('x', views.login, name='login'),
    path('admin/', admin.site.urls),
    path('', views.home_view, name='home'),
    path('login/', views.login, name='login'),
    path('home/', views.home_view, name='home'),
    path('success/', views.success, name='success'),
    path('unsuccessful/', views.unsuccessful, name='unsuccessful'),
    path('success1/', views.success1, name='success1'),
    path('room/success/', views.success1, name='success1'),
    path('accounts/', include('allauth.urls')),
    path('accounts/login/login', views.home_view,name="home"),
    path('host/rooms', views.roomRegistration_view, name='rooms'),
    path('view/mumbai', views.mumbai_view,name='houses'),
    path('view/bangalore', views.bangalore_view,name='houses'),
    path('view/delhi', views.delhi_view,name='houses'),
    path('view/pune', views.pune_view,name='houses'),
    path('dashboard/', views.dashboard_view,name='dashboard'),
    path('room/<int:pk>', views.RoomBookingView.as_view(), name='room-detail'),
    path('test', views.test_view,name='test'),
    path('confirm',views.confirm,name='confirm'),
    path('covidtracker', views.covidView,name='covidtracker'),
    url(r'^media/(?P<path>.*)$', serve,{'document_root':       settings.MEDIA_ROOT}),
    url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),

]

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 24 00:04:54 2018

@author: laureano
"""

def parse(filename):
    with open(filename, "r") as f:
        aux =  [i.strip("\n ") for i in f.readlines()]
        result = ''
        for i in aux:
            if i == "(":
                result += "("
            else:
                result += i + ","
        result = "("+result+")"
        return eval(result)

print(parse('tuple1.txt'))