"""
birthday.py
Author: Ella Edmonds
Credit: None
Assignment:

Your program will ask the user the following questions, in this order:

1. Their name.
2. The name of the month they were born in (e.g. "September").
3. The year they were born in (e.g. "1962").
4. The day they were born on (e.g. "11").

If the user's birthday fell on October 31, then respond with:

  You were born on Halloween!

If the user's birthday fell on today's date, then respond with:

  Happy birthday!

Otherwise respond with a statement like this:

  Peter, you are a winter baby of the nineties.

Example Session

  Hello, what is your name? Eric
  Hi Eric, what was the name of the month you were born in? September
  And what year were you born in, Eric? 1972
  And the day? 11
  Eric, you are a fall baby of the stone age.
"""

name = input ('Hello, what is your name? ')
a = input (str('Hi '+name+', what was the name of the month you were born in? '))
b = float (input ('And what year were you born in, '+name+'? '))
c = float (input ('And the day? '))

if a == 'October' and c == 31:
    print('You were born on Halloween!')
elif a == 'September' and c == 21:
    print('Happy birthday!')

else:
    if a in ['September','October','November']:
        season ='fall'
    elif a in ['December','January','February']:
        season = 'winter'
    elif a in ['March','April','May']:
        season = 'spring'
    elif a in ['June','July','August']:
        season = 'summer'

    if 0<=b<=1979:
        age = 'Stone Age.'
    elif 1980<=b<=1989:
        age = 'eighties.'
    elif 1990<=b<=1999:
        age = 'nineties.'
    elif 2000<=b<=2020:
        age = 'two thousands.'

    print(name+', you are a '+season+' baby of the '+age)


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

import sys
import os
import argparse
from workflow.util.useful import const
from workflow.util.useful import parse_group_file,mkdir,Rparser,get_name,image_trans,cutcol_dataFrame

def read_params(args):
    parser = argparse.ArgumentParser(description='a wrapper for LEfSe | v1.0 at 2017/1/23 by huangy')
    parser.add_argument('-i', '--summarize_all', dest='infile', metavar='FILE', type=str, required=True,
                        help="set hte otu_table_all.txt produced by 02_summarize_trans.py")
    parser.add_argument('-l', '--LEfSe_path', dest='LEfSe_path', metavar='DIR', type=str, default=None,
                        help="set the LEfSe path, default find in env")
    parser.add_argument('-g', '--group_file', dest='group', metavar='FILE', type=str, required=True,
                        help="set the group file")
    parser.add_argument('-o', '--out_dir', dest='out_dir', metavar='DIR', type=str, required=True,
                        help="set the output dir")
    parser.add_argument('--LDA', dest='LDA', metavar='FLOAT', type=float, default=2,
                        help="set the LDA cutoff, [default is 2]")
    parser.add_argument('--class_row', dest='c', metavar='INT', type=int, default=1,
                        help="set the class row, [default is 1]")
    parser.add_argument('--subject_row', dest='u', metavar='INT', type=int, default=2,
                        help="set the subject row, [default is 2]")
    parser.add_argument('--quantile',dest="quantile",metavar='FLOAT',type=float,default=0)
    parser.add_argument('--cut_off',dest='cut_off',metavar='FLOAT',type=float,default=1e-20)
    args = parser.parse_args()
    params = vars(args)
    params['groupDir'] = params['group']
    params['group'] = parse_group_file(params['group'])
    if params['LEfSe_path'] is None:
        params['LEfSe_path'] = ''
    else:
        params['LEfSe_path'] += '/'
    return params

def do_format(infile, outfile, groupDir,quantile,cut_off):
    data,group = cutcol_dataFrame(infile,groupDir)
    groups=group.values()
    samples = group.keys()

    data.index=[i.replace('[','') for i in data.index.tolist()]
    data.index=[i.replace(']','') for i in data.index.tolist()]
    for temp in data.index:
        if temp.endswith('Other'):
            data.drop(temp)
        if temp.endswith('norank'):
            data.drop(temp)
        if temp.endswith('unclassfied'):
            data.drop(temp)
    sample_num = len(data.columns)
    data["sum"] = data.sum(axis=1)
    data = data.sort_values(by="sum",ascending=False)
    quantile_value = float(data["sum"].quantile(quantile))
    dd = data[data>cut_off]
    data["num_True"] = dd.count(axis=1)
    index_list = []
    for i in range(len(data.index)):
        if data.ix[i,sample_num] < quantile_value:
            if data.ix[i,sample_num+1] <2:
                index_list.append(i)
    data = data.drop(data.index[index_list])
    del data["sum"]
    del data["num_True"]
    with open(outfile, 'w') as out_fp:
        out_fp.write('class\t%s\n' % '\t'.join(groups))
        out_fp.write('Taxon\t%s\n' % '\t'.join(samples))
        data.to_csv(out_fp,header=False,sep="\t")

def get_commands(infile, LEfSe_path, out_dir, LDA, c, u):
    commands = []
    command = '%sformat_input.py %s %s/LDA.in -c %s -u %s -o 1000000' % (LEfSe_path, infile, out_dir, c, u)
    commands.append(command)
    command = '%srun_lefse.py %s/LDA.in %s/LDA.res -l %s' % (LEfSe_path, out_dir, out_dir, LDA)
    commands.append(command)
    command = '%splot_res.py %s/LDA.res %s/LDA.pdf --format pdf --dpi 150' % (LEfSe_path, out_dir, out_dir)
    commands.append(command)
    command = '%splot_res.py %s/LDA.res %s/LDA.png --format png --dpi 150' % (LEfSe_path, out_dir, out_dir)
    commands.append(command)
#    command = '%splot_cladogram.py %s/LDA.res %s/LDA.cladogram.pdf --format pdf --dpi 150' % (
 #       LEfSe_path, out_dir, out_dir)
 #   commands.append(command)
 #   command = '%splot_cladogram.py %s/LDA.res %s/LDA.cladogram.png --format png --dpi 150' % (
     #   LEfSe_path, out_dir, out_dir)
   # commands.append(command)
  #  if not os.path.isdir('%s/biomarkers_raw_images' % out_dir):
   #     os.mkdir('%s/biomarkers_raw_images' % out_dir)
   # command = '%(LEfSe_path)splot_features.py %(out_dir)s/LDA.in %(out_dir)s/LDA.res %(out_dir)s/biomarkers_raw_images/ --format pdf --dpi 200' % {
    #    'LEfSe_path': LEfSe_path, 'out_dir': out_dir}
    #commands.append(command)
    return commands

if __name__ == '__main__':
    params = read_params(sys.argv)
    mkdir(params['out_dir'])
    for_analysis = '%s/otu_table_for_lefse.txt' % params['out_dir']
    do_format(params['infile'], for_analysis, params['groupDir'],params['quantile'],params['cut_off'])
    commands = get_commands(for_analysis, params['LEfSe_path'], params['out_dir'],
                            params['LDA'], params['c'], params['u'])
    with open(params['out_dir'] + '/commands.sh', 'w') as fp:
        fp.write('\n'.join(commands))
    for command in commands:
        os.system(command)
    os.system("awk '$4>%s' %s/LDA.res >%s/diff.marker.filter.txt.tmp"%(params['LDA'],params['out_dir'],params['out_dir']))
    with open("%s/diff.marker.filter.txt.tmp"%params['out_dir']) as fqin,open("%s/diff.marker.filter.tsv"%params['out_dir'],"w") as fqout:
        for line in fqin:
            tabs = line.strip().split("\t")
            fqout.write("%s\t%s\t\t%s\t\t%s\n"%(tabs[0],tabs[1],tabs[4],tabs[2]))
    os.system("rm %s/diff.marker.filter.txt.tmp"%(params['out_dir']))
    os.system("cut -f 1 %s/diff.marker.filter.tsv |while read line;do echo \"grep \'$line\' %s >> %s/diff.marker.filter.profile.tsv\";done>%s/do.sh"%(params['out_dir'],params['infile'],params['out_dir'],params['out_dir']))
    os.system("head -1 %s > %s/diff.marker.filter.profile.tsv"%(params['infile'],params['out_dir']))
    os.system("sh %s/do.sh"%params['out_dir'])
    os.system("rm %s/do.sh"%params['out_dir'])


import numpy as np
import pickle
from preprocessor import preprocess
import json
from joblib import Parallel, delayed
import time
import multiprocessing
import sys
# from Gru import Gru

p_file = open('params.json','r')
p = json.loads(p_file.read())
params = p["lstm"]

class LstmCell:

    def __init__(self,m):
        self.cache = None
        self.errors = None  # this will be initialized
        self.initErrors(m)

    def initErrors(self,m):
        hidden_nodes = params["hidden_nodes"]

        input_gate = np.zeros((m,hidden_nodes))
        forget_gate = np.zeros((m,hidden_nodes))
        gate_gate = np.zeros((m,hidden_nodes))
        output_gate = np.zeros((m,hidden_nodes))
        cell = np.zeros((m,hidden_nodes))
        hidden = np.zeros((m,hidden_nodes))
        output = np.zeros((m,p["preprocess"]["vocab_size"]))
        prev_hidden = np.zeros((m,hidden_nodes))
        prev_cell = np.zeros((m,hidden_nodes))

        self.errors = dict(input_gate=input_gate, forget_gate=forget_gate, gate_gate=gate_gate, output_gate=output_gate, cell=cell, hidden=hidden, output=output, prev_cell=prev_cell, prev_hidden=prev_hidden)

    def forward(self, X, prev_hidden, prev_cell, time_step, weights):
        input_gate = self.inputGate(X,weights['Whi'],weights['Uii'],weights['bhi'],weights['bii'],prev_hidden,time_step,self.sigmoid)
        forget_gate = self.forgetGate(X,weights['Whf'],weights['Uif'],weights['bhf'],weights['bif'],prev_hidden,time_step,self.sigmoid)
        output_gate = self.outputGate(X,weights['Who'],weights['Uio'],weights['bho'],weights['bio'],prev_hidden,time_step,self.sigmoid)
        gate_gate = self.gateGate(X,weights['Whg'],weights['Uig'],weights['bhg'],weights['big'],prev_hidden,time_step,self.tanh)
        current_cell = self.cellState(forget_gate,prev_cell,input_gate,gate_gate)
        current_cell_tan = self.tanh(current_cell)
        current_hidden = output_gate * current_cell_tan
        out = weights["b"] + np.dot(current_hidden,weights["V"].T)
        output = self.softmax(out)
        self.cache = dict(input_gate=input_gate, forget_gate=forget_gate, gate_gate=gate_gate, output_gate=output_gate, current_cell=current_cell, current_cell_tan=current_cell_tan,  current_hidden=current_hidden, output=output, prev_cell=prev_cell, prev_hidden=prev_hidden)

    @staticmethod
    def inputGate(X, W, U, bh, bi, prev_hidden, t, sig):
        from_hidden = np.dot(prev_hidden, W.T) + bh
        from_input = (U[:,X[:,t]]).T + bi
        return sig(from_hidden + from_input)

    @staticmethod
    def forgetGate(X, W, U, bh, bi, prev_hidden, t, sig):
        from_hidden = np.dot(prev_hidden, W.T) + bh
        from_input = (U[:,X[:,t]]).T + bi
        return sig(from_hidden + from_input)

    @staticmethod
    def outputGate(X, W, U, bh, bi, prev_hidden, t, sig):
        from_hidden = np.dot(prev_hidden, W.T) + bh
        from_input = (U[:,X[:,t]]).T + bi
        return sig(from_hidden + from_input)

    @staticmethod
    def gateGate(X, W, U, bh, bi, prev_hidden, t, tanh):
        from_hidden = np.dot(prev_hidden, W.T) + bh
        from_input = (U[:,X[:,t]]).T + bi
        return tanh(from_hidden + from_input)

    @staticmethod
    def cellState(forget_gate, prev_cell, input_gate, gate_gate):
        return forget_gate * prev_cell + input_gate * gate_gate

    @staticmethod
    def sigmoid(z):
        #receives m X hidden_nodes
        return 1.0/(1 + np.exp(-z))

    @staticmethod
    def dsigmoid(a):
        return a * (1-a)

    @staticmethod
    def tanh(z):
        return np.tanh(z)

    @staticmethod
    def dtanh(a):
        return 1 - a ** 2

    @staticmethod
    def softmax(outputs):
        l = len(outputs)
        outputs -= np.max(outputs,axis=-1).reshape(l,1) #for numeric stability
        expo = np.exp(outputs)
        return 1.0*expo/np.sum(expo,axis=-1).reshape(l,1)

    def backprop(self, X, y, t, weights):
        #get the errors in the ouput layer
        dy = self.cache['output']
        dy[np.arange(X.shape[0]),y[:,t]] -= 1
        #pass to the hidden layer
        dhidden = self.errors['hidden']
        dhidden += np.dot(dy, weights['V']) #this is the error propogated to both the components that added up to get the current hidden state

        #error at output gate
        doutput_gate = (dhidden * self.cache['current_cell_tan']) * self.dsigmoid(self.cache['output_gate'])

        #error at cell gate
        dcell = self.errors['cell']
        dcell_from_ht = (dhidden * self.cache['output_gate']) * self.dtanh(self.cache['current_cell_tan'])
        dcell += dcell_from_ht

        #
        dprev_cell = dcell * self.cache['forget_gate']
        dforget_gate = (dcell * self.cache['prev_cell']) * self.dsigmoid(self.cache['forget_gate'])
        dinput_gate = (dcell * self.cache['gate_gate']) * self.dsigmoid(self.cache['input_gate'])
        dgate_gate = (dcell * self.cache['input_gate']) * self.dtanh(self.cache['gate_gate'])

        #dprev_hidden
        dprev_hidden = np.dot(dgate_gate, weights['Whg'])
        dprev_hidden += np.dot(doutput_gate, weights['Who'])
        dprev_hidden += np.dot(dforget_gate, weights['Whf'])
        dprev_hidden += np.dot(dinput_gate, weights['Whi'])

        errors = dict(input_gate=dinput_gate, forget_gate=dforget_gate, gate_gate=dgate_gate, output_gate=doutput_gate, cell=dcell, hidden=dhidden, output=dy, prev_cell=dprev_cell, prev_hidden=dprev_hidden)
        self.errors = errors

    def addErrorFromNextCell(self, hidden, cell):
        self.errors['cell'] += cell
        self.errors['hidden'] += hidden

    @staticmethod
    def _calcForinputU(shape, error, X, t):
        dJdU = np.zeros(shape)
        if len(set(X[:,t])) == len(X[:,t]):
            dJdU[:,X[:,t]] += error.T
        else:
            update_cols = X[:,t]
            tpose = error.T
            for dps in range(len(update_cols)):
                dJdU[:,update_cols[dps]] += tpose[:,dps]

        return dJdU

    # order ['Whi','Whf','Who','Whg','Uii','Uif','Uio','Uig','V','bhi','bhf','bho','bhg','bii','bif','bio','big','b']
    def getdJdW(self, X, weights, t ):

        ts = self.cache['current_hidden'].shape
        dJdV = np.matmul(self.errors['output'].reshape(self.errors['output'].shape+(1,)), self.cache['current_hidden'].reshape((ts[0],1,ts[1])))
        dJdV = np.sum(dJdV,axis=0)
        dJdb = np.sum(self.errors['output'],axis=0)

        ths = self.cache['prev_hidden'].shape

        ts = self.errors['input_gate'].shape
        dJdWhi = np.matmul(self.errors['input_gate'].reshape(ts+(1,)), self.cache['prev_hidden'].reshape((ths[0],1,ths[-1])))
        dJdWhi = np.sum(dJdWhi, axis=0)
        dJdUii = self._calcForinputU(weights['Uii'].shape, self.errors['input_gate'], X, t)
        dJdbhi = np.sum(self.errors['input_gate'], axis = 0)
        dJdbii = np.sum(self.errors['input_gate'], axis = 0)

        ts = self.errors['forget_gate'].shape
        dJdWhf = np.matmul(self.errors['forget_gate'].reshape(ts+(1,)), self.cache['prev_hidden'].reshape((ths[0],1,ths[-1])))
        dJdWhf = np.sum(dJdWhf, axis=0)
        dJdUif = self._calcForinputU(weights['Uif'].shape, self.errors['forget_gate'], X, t)
        dJdbhf = np.sum(self.errors['forget_gate'], axis = 0)
        dJdbif = np.sum(self.errors['forget_gate'], axis = 0)

        ts = self.errors['output_gate'].shape
        dJdWho = np.matmul(self.errors['output_gate'].reshape(ts+(1,)), self.cache['prev_hidden'].reshape((ths[0],1,ths[-1])))
        dJdWho = np.sum(dJdWho, axis=0)
        dJdUio = self._calcForinputU(weights['Uio'].shape, self.errors['output_gate'], X, t)
        dJdbho = np.sum(self.errors['output_gate'], axis = 0)
        dJdbio = np.sum(self.errors['output_gate'], axis = 0)

        ts = self.errors['gate_gate'].shape
        dJdWhg = np.matmul(self.errors['gate_gate'].reshape(ts+(1,)), self.cache['prev_hidden'].reshape((ths[0],1,ths[-1])))
        dJdWhg = np.sum(dJdWhg, axis=0)
        dJdUig = self._calcForinputU(weights['Uig'].shape, self.errors['gate_gate'], X, t)
        dJdbhg = np.sum(self.errors['gate_gate'], axis = 0)
        dJdbig = np.sum(self.errors['gate_gate'], axis = 0)

        grads = [dJdWhi,dJdWhf,dJdWho,dJdWhg,dJdUii,dJdUif,dJdUio,dJdUig,dJdV,dJdbhi,dJdbhf,dJdbho,dJdbhg,dJdbii,dJdbif,dJdbio,dJdbig,dJdb]

        return grads


from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('usermag.views',
                       # Examples:
                       url(r'^$', 'dashboard', name='dashboard'),
                       # url(r'^blog/', include('blog.urls')),
                       url(r'^users/$', 'users', name='usermag_users'),
                       url(r'^groups/$', 'groups', name='usermag_groups'),

                       url(r'^user/(?P<user_id>\d+)$', 'user', name='usermag_user'),
)


'''
Created on 2015.6.4

@author: wby
'''
from primeSieve import *
import time

result = 0
primeList = primeSieve(1000000)
t = time.time()
count = 0
i = 4
while count < 11:
    rightTrunk = primeList[i]
    leftTrunk = 0
    multiplier = 1
    isTrunkPrime = True
    while rightTrunk > 0 and isTrunkPrime:
        leftTrunk += multiplier*(rightTrunk%10)
        isTrunkPrime = isPrime(leftTrunk) and isPrime(rightTrunk)
        rightTrunk /= 10
        multiplier *= 10
    if isTrunkPrime:
        count+=1
        result += primeList[i]

    i+=1

print(result)
print(time.time()-t)


# see machine learning odt to learn about the following code.
# Simple Linear Regression

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')   #usin pandas library

X = dataset.iloc[:, :-1].values     #select the entire line and click ctrl+ enter, we will see that see that statement got
#got executed inside console as well as dataset X is formed inside variable explorer.
#x is the matrix of independent variable # i.e. years of experience in dataset
#here -1 means that we have removed salary, the last column and consider only year of experience. click on X in variable
#explorer and you will see only year of experience and not salary.
#in front of X we can see size is (30,1) which means 30 options in one column because it is matrix

y = dataset.iloc[:, 1].values   #same process needs to be done here. here 1 means that we are considering
# ony salary and not years of experience.
#in front of y we can see size is (30,) which means it is vector.

#difference between [:,:-1] it means we are creating a 2D object, that's why X is matrix here
#whereas [:,1] means 1D object, that's why y is vector here.

# Splitting the dataset into the Training set and Test set
#X(containing 30 observations) is split into training set(containing 20 of 30 observations) and test set(containing 10 of 30 observations)
#similarily y consist of training set and test set. hence total four datasets are formed.

#so select the below two lines and click ctrl + enter and four dataset are formed in variable explorer.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
#clearly here test size is 1/3 which means 10 observations.
#Step1:moreove X training set and Y training set are co related and our training model is prepared.
#Step2:model can later predict salaries based on experience which it will predict by using test cases which
#are present in test set of x.
#step3:then we will get the value of predicted salary which we will compare with
#atual salary present in Y test set.
#this entire process is known as data preprocessing.

# Feature Scaling
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
sc_y = StandardScaler()
y_train = sc_y.fit_transform(y_train)"""

#in simple linear regression we don't use Feature scaling, that's why it has been commented out by using """   """

# Fitting Simple Linear Regression to the Training set
#select linearRegression class and press ctrl+I which displays help in R.H.S which gives information about linear regression class.
from sklearn.linear_model import LinearRegression  #here we are importing library from sklearn (which is itself a library and consist of many libraries) for implementing linear regression.
regressor = LinearRegression()      #we are using linear_model library from where we get linearRegreesion in-built class which consist of fit method.
regressor.fit(X_train, y_train)    #here regressor is the object of class linear regression
                                   #select fit and click ctrl+I and you will get the information about fit method on R.H.S
#finally select the entire code and ctrl+enter and we will see that regressor is created and fitted to the training datatset
#Note: so finally here our model linear regression learns from the available dataset which we proveided and finally going to use it to prdict.

# Predicting the Test set results
# here the model which we have prepared(y using training set) is used to find the predicted salaries
y_pred = regressor.predict(X_test)   #predict method is of linearregression class which will give the predicted salary by using test set X and the predicted salary_y is compared with test set_y
#now select the above line and press ctrl + enter. this will give y_predict in variable explore. Click it and also y_test and compare them.

# Visualising the Training set results
#so here we are using matplot library.
plt.scatter(X_train, y_train, color = 'red')     #this will show points scattered around regression line. here X_train is going to be x-cordinate and y_train is going to be y-coordinate.
plt.plot(X_train, regressor.predict(X_train), color = 'blue')   #this will give regression line
#in the above line x-coordinate is X_train and Y-coordinate is  regressor.predict(X_train). here we have used X_train and y_train because we have to predict the y_train using x_train.
plt.title('Salary vs Experience (Training set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()
#highlight the entire code from plt.scatter to plt.show() and press ctrl+enter. You will get the entire result.
#now we can easily see that some points lie closer to the regression line and some are far.
#Note: so all the points whcih are red in color are the observations of Training set(not test set)
#and our linear regression model was trained on these red points.

# Visualising the Test set results
#now here we will use our trained regression model on test set observations.
#we will plot same blue line but this time we will have new observations in orange color.
plt.scatter(X_test, y_test, color = 'orange')
plt.plot(X_train, regressor.predict(X_train), color = 'blue') #very important to note here is that we will rain  X_t ,not X_test and y-test because we need use regression model which we trained using red points and not orange points.
#moreover by using regressonr.predict we were able to predict salary and generate orange points.
plt.title('Salary vs Experience (Test set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()


from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

from models import PublicTeam, SkillList, Mentors

import settings

engine = create_engine(settings.DB_NAME)

Session = sessionmaker(bind=engine)

session = Session()

def insert_skill(name):
    s = SkillList(name=name)
    session.add(s)
    session.commit()

def get_skills():
    skillies = [s.name for s in session.query(SkillList).all()]
    return skillies

def get_skill(skill_name):
    skill = session.query(SkillList).filter(skill_name == SkillList.name).one()
    return skill

def get_mentor(mentor_name):
    mentor = session.query(Mentors).filter(mentor_name == Mentors.name).one()
    return mentor

def get_team(team_name):
    team = session.query(PublicTeam).filter(team_name == PublicTeam.name).one()
    return team

def get_all_teams():
    teams = [(team.name, team.idea_description) for team in session.query(
        PublicTeam).all()]
    return teams

def insert_team(name, idea_desc, repo, need_members, members_needed_desc,
                room, techs, place="null"):
    team = PublicTeam(name=name, idea_description=idea_desc, repository=repo,
                      need_more_members=need_members,
                      members_needed_desc=members_needed_desc, room=room,
                      place=place)
    for tech in techs:
        skill = get_skill(tech['name'])
        team.skills.append(skill)
    session.add(team)
    session.commit()

def insert_mentor(name, description, picture, teams):
    mentor = Mentors(name=name, description=description, picture=picture)
    for team in teams:
        t = get_team(team['name'])
        mentor.teams.append(t)
    session.add(mentor)
    session.commit()

def get_teams_in_room(room):
    teams = session.query(PublicTeam).filter(room == PublicTeam.room).count()
    return teams

def get_teams_for_technology(tech):
    skill = get_skill(tech)
    return [t.name for t in skill.teams]

def get_mentor_teams(mentor_name):
    mentor = get_mentor(mentor_name)
    for team in mentor.teams:
        print("name: {}, \nidea_description: {}, \nrepository: {}, \
              \nmore members?: {}, \nwhat members needed?: {},\
              \nroom: {}, \nskills: {}".format(team.name,
                                               team.idea_description,
                                               team.repository,
                                               team.need_more_members,
                                               team.members_needed_desc,
                                               team.room,
                                               [skill.name for skill in
                                                team.skills]))

def get_mentor_rooms(mentor_name):
    mentor = get_mentor(mentor_name)
    rooms = []
    for team in mentor.teams:
        rooms.append(team.room)

    sorted_rooms = sorted([int(room) for room in rooms if room != 'mazata'])
    if 'mazata' in rooms:
        sorted_rooms.append('mazata')

    return sorted_rooms

def remove_skill(team_name, skill_name):
    team = get_team(team_name)
    for skill in team.skills:
        if skill.name == skill_name:
            team.skills.remove(skill)

def add_skill_to_team(team_name, skills):
    team = get_team(team_name)
    for skill in skills:
        s = get_skill(skill)
        if s not in team.skills:
            team.skills.append(s)

def update_team_attr(team_name, attr, new_value):
    team = get_team(team_name)
    setattr(team, attr, new_value)


from neurolight.match.costs import get_costs
from neurolight.match.preprocess import mouselight_preprocessing
from funlib.match.helper_functions import match

import networkx as nx

from obj_to_npz import parse_npy_graph
import pickle

from pathlib import Path
import copy

penalty_attr = "penalty"
location_attr = "location"

trimmed = Path.cwd() / "invalid_trimmed"
trimmed.mkdir(parents=True, exist_ok=True)

for i, valid in enumerate(Path("invalid").iterdir()):
    print(valid.name)
    graph = pickle.load((valid / "graph.obj").open("rb"))
    tree = pickle.load((valid / "tree.obj").open("rb"))

    temp = copy.deepcopy(graph)

    max_edge_len = 48
    mouselight_preprocessing(
        temp,
        max_dist=150,
        voxel_size=[10, 3, 3],
        penalty_attr=penalty_attr,
        location_attr=location_attr,
    )

    node_match_threshold = 76
    edge_match_threshold = 76
    node_balance = 10

    node_costs, edge_costs = get_costs(
        temp,
        tree,
        location_attr=location_attr,
        penalty_attr=penalty_attr,
        node_match_threshold=100,
        edge_match_threshold=100,
        node_balance=node_balance,
    )

    try:
        matched = match(temp, tree, node_costs, edge_costs)
    except:
        print("failed to match!")
        matched = graph

    untouched_ccs = list(set(x) for x in nx.connected_components(graph))

    for node in matched.nodes():
        for cc in untouched_ccs:
            if node in cc:
                untouched_ccs.remove(cc)

    (trimmed / f"{i:03}").mkdir(exist_ok=True, parents=True)
    for untouched_cc in untouched_ccs:
        graph.remove_nodes_from(untouched_cc)
    pickle.dump(graph, open(f"invalid_trimmed/{i:03}/graph.obj", "wb"))
    pickle.dump(tree, open(f"invalid_trimmed/{i:03}/tree.obj", "wb"))


DATA_DIR = '../data'
MODEL_NAME = 'model.joblib'
X_TRAIN = 'X_train.zip'
Y_TRAIN = 'y_train.zip'
X_TEST = 'X_test.zip'
Y_TEST = 'y_test.zip'

DTYPES = {
    'id': 'int64',
    'photo': 'str',
    'name': 'str',
    'blurb': 'str',
    'goal': 'float64',
    'slug': 'str',
    'disable_communication': 'bool',
    'country': 'str',
    'currency': 'str',
    'currency_symbol': 'str',
    'currency_trailing_code': 'bool',
    'deadline': 'int64',
    'created_at': 'int64',
    'launched_at': 'int64',
    'static_usd_rate': 'float64',
    'creator': 'str',
    'location': 'str',
    'category': 'str',
    'profile': 'str',
    'urls': 'str',
    'source_url': 'str',
    'friends': 'str',
    'is_starred': 'str',
    'is_backing': 'str',
    'permissions': 'str',
    'state': 'int64'
}

PARAMS = {
    'model__max_depth': 7,
    'model__min_samples_split': 20,
    'preprocessor__categories__transformer__use_all': True
}

GRID_PARAMS = {
    'model__max_depth': [5, 7, 9],
    'model__min_samples_split': [5, 10, 20],
    'preprocessor__categories__transformer__use_all': [False, True]
}


import sys
import time
import torch
import argparse
import PIL.ImageOps
from tqdm import tqdm
import torch.nn as nn
from torch import optim
import torchvision.utils
import matplotlib.pyplot as plt
import torch.nn.functional as F
import matplotlib.pyplot as plt
import torchvision.datasets as dset
import torchvision.datasets.fakedata
import torchvision.transforms as transforms
from loss import ContrastiveLoss
from torch.utils.data import DataLoader
from siamesenetwork import SiameseNetwork
from siamesenetwork import SiameseNetworkDataset

def show_plot(iteration, loss):
    plt.plot(iteration, loss)
    plt.xlabel("iteration")
    plt.ylabel("loss")
    plt.savefig("loss_figure.png")
    plt.show()

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"training device: {device}")

args = argparse.ArgumentParser()
args.add_argument("--model")
res = args.parse_args()
model_name = res.model

net = None
loaded_model = None

net = SiameseNetwork().to(device)
loaded_model = torch.load(model_name, map_location=torch.device("cuda"))
net.load_state_dict(loaded_model["state_dict"])

criterion = ContrastiveLoss().to(device)
optimizer = optim.Adam(net.parameters(), lr=0.0005)

optimizer.load_state_dict(loaded_model["optim_dict"])
epochs = loaded_model["epoch"]
loss_history = loaded_model["loss_history"]
counter = loaded_model["counter"]

if net is not None:
    print("model loaded... ")
else:
    print("model loading failed... try again")

print(f"resuming training from: {model_name}")

class Config:
    training_dir = "./images/train_q/"
    train_batch_size = 64
    train_number_epochs = 5000

folder_dataset = dset.ImageFolder(root=Config.training_dir)

siamese_dataset = SiameseNetworkDataset(
    imageFolderDataset=folder_dataset,
    transform=transforms.Compose(
        [
            transforms.Resize((100, 100)),
            transforms.RandomHorizontalFlip(),
            transforms.RandomVerticalFlip(),
            transforms.ColorJitter(),
            transforms.ToTensor(),
        ]
    ),
    should_invert=False,
)

train_dataloader = DataLoader(
    siamese_dataset,
    shuffle=True,
    # num_workers=8,
    batch_size=Config.train_batch_size,
)

iteration_number = counter[-1]

for epoch in tqdm(
    range(epochs, Config.train_number_epochs + epochs),
    ascii=True if sys.platform == "win32" else False,
):
    for i, data in enumerate(train_dataloader, 0):
        start = time.time()
        img0, img1, label = data
        img0, img1, label = img0.to(device), img1.to(device), label.to(device)
        optimizer.zero_grad()
        output1, output2 = net(img0, img1)
        loss_contrastive = criterion(output1, output2, label)
        loss_contrastive.backward()
        optimizer.step()
        if i % 10 == 0:
            print(
                "epoch: {} current loss: {} time taken: {}s\n".format(
                    epoch + 1, loss_contrastive.item(), str(time.time() - start)[:5]
                )
            )
            iteration_number += 10
            counter.append(iteration_number)
            loss_history.append(loss_contrastive.item())

    if epoch % 500 == 0 and epoch > 0:
        state_dict = {
            "epoch": epoch + 1,
            "state_dict": net.state_dict(),
            "optim_dict": optimizer.state_dict(),
            "loss_history": loss_history,
            "counter": counter,
        }
        torch.save(state_dict, f"model_state_dict_{epoch}.pt")
        print()
        print(f"model checkpoint saved to models/model_state_dict_{epoch    }")

show_plot(counter, loss_history)


import tensorflow as tf
from tensorflow import keras
import time

import gpflow as gp
from tensorflow.keras.regularizers import l2

from tensorflow.keras import Sequential
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Flatten
from tensorflow.keras.optimizers import Adam
# from sklearn.preprocessing import to_categorical
from tensorflow.keras.utils import to_categorical
from gpflow.utilities import print_summary
import tensorflow_probability as tfp
import tensorflow as tf
from matplotlib import pyplot
from tensorflow.keras.preprocessing.image import load_img
import numpy as np

def prep_pixels(train, test):
	# convert from integers to floats
	train_norm = train.astype('float32')
	test_norm = test.astype('float32')
	# normalize to range 0-1
	train_norm = train_norm / 255.0
	test_norm = test_norm / 255.0
	# return normalized images
	return train_norm, test_norm

def load_cifar():
	# load dataset
	(trainX, trainY), (testX, testY) = keras.datasets.cifar10.load_data()
	# one hot encode target values
	trainY = to_categorical(trainY)
	testY = to_categorical(testY)
	return trainX, trainY, testX, testY

class Keras_model_fashion():

    def __init__(self):
        (train_images, train_labels), (test_images, test_labels) = keras.datasets.fashion_mnist.load_data()
        self.train_images= train_images
        self.train_labels= train_labels
        self.test_images= test_images
        self.test_labels= test_labels

    def evaluate_error_and_cost(self, layer_sizes, alpha, l2_regul, num_epoch):
        layer_sizes = np.ndarray.astype(np.rint(np.power(2, layer_sizes)), dtype= int)
        alpha= np.power(10.0, alpha)
        l2_regul= np.power(10.0, l2_regul)
        num_epoch= np.int(np.rint(np.power(10, num_epoch)))

        xt_eval= np.empty([1, len(layer_sizes)+ 2])

        xt_eval[0, 0:len(layer_sizes)]= np.log2(layer_sizes[:])
        # xt_eval[0,len(filter_sizes):len(filter_sizes)+ len(dense_sizes)]= np.log2(dense_sizes[:])
        xt_eval[0,len(layer_sizes)]= np.log10(alpha)
        xt_eval[0, len(layer_sizes)+1]= np.log10(l2_regul)

        print('layer_sizes:{}\nalpha:{}\nl2_regul:{}\nnum_epoch:{}'.format(layer_sizes, alpha, l2_regul, num_epoch))
        '''define model'''
        t1= time.clock()
        model = keras.Sequential([
            keras.layers.Flatten(input_shape=(28, 28)),
            keras.layers.Dense(layer_sizes[0], activation='relu',  kernel_initializer='he_uniform', kernel_regularizer= l2(l2_regul)),
            keras.layers.Dense(layer_sizes[1], activation='relu', kernel_initializer='he_uniform', kernel_regularizer= l2(l2_regul)),
            keras.layers.Dense(layer_sizes[2], activation='relu', kernel_initializer='he_uniform', kernel_regularizer= l2(l2_regul)),
            keras.layers.Dense(layer_sizes[3], activation='relu', kernel_initializer='he_uniform', kernel_regularizer= l2(l2_regul)),
            keras.layers.Dense(10)
        ])
        opt = keras.optimizers.Adam(learning_rate= alpha)
        '''compile model'''
        model.compile(optimizer= opt,  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                      metrics=['accuracy'])

        '''fit'''
        model.fit(self.train_images, self.train_labels, epochs= num_epoch)

        '''test set accuracy'''
        test_loss, test_acc = model.evaluate(self.test_images,  self.test_labels, verbose=2)
        print('\nTest accuracy:', test_acc)
        t2= time.clock()

        return np.atleast_2d(-test_acc), np.atleast_2d(t2- t1), xt_eval

class Keras_model_fashion2():

    def __init__(self):
        (train_images, train_labels), (test_images, test_labels) = keras.datasets.fashion_mnist.load_data()
        self.train_images= train_images
        self.train_labels= train_labels
        self.test_images= test_images
        self.test_labels= test_labels

    def evaluate_error_and_cost(self, layer_size, num_layers, alpha, num_epoch):
        layer_size= np.int(np.power(2.0, layer_size))
        alpha= np.power(10.0, alpha)
        # l2_regul= np.power(10.0, l2_regul)
        num_epoch= np.int(np.rint(np.power(10, num_epoch)))
        num_layers= np.int(num_layers)

        xt_eval= np.empty([1, 3])

        xt_eval[0, 0]= np.log2(layer_size)
        xt_eval[0, 1]= num_layers
        # xt_eval[0,len(filter_sizes):len(filter_sizes)+ len(dense_sizes)]= np.log2(dense_sizes[:])
        xt_eval[0,2]= np.log10(alpha)
        # xt_eval[0,2]= np.log10(l2_regul)

        print('layer_sizes:{}\nnum_layers:{}\nalpha:{}\nnum_epoch:{}'.format(layer_size, num_layers, alpha,
                                                                            num_epoch))
        '''define model'''
        t1= time.clock()
        model = Sequential()
        model.add(keras.layers.Flatten(input_shape=(28, 28)))
        for i in range(num_layers):
            model.add(keras.layers.Dense(layer_size, activation='relu',
                                         kernel_initializer='he_uniform'))
        model.add(keras.layers.Dense(10))
        # model = keras.Sequential([
        #     keras.layers.Flatten(input_shape=(28, 28)),
        #     keras.layers.Dense(layer_sizes[0], activation='relu',  kernel_initializer='he_uniform', kernel_regularizer= l2(l2_regul)),
        #     keras.layers.Dense(layer_sizes[1], activation='relu', kernel_initializer='he_uniform', kernel_regularizer= l2(l2_regul)),
        #     keras.layers.Dense(layer_sizes[2], activation='relu', kernel_initializer='he_uniform', kernel_regularizer= l2(l2_regul)),
        #     keras.layers.Dense(layer_sizes[3], activation='relu', kernel_initializer='he_uniform', kernel_regularizer= l2(l2_regul)),
        #     keras.layers.Dense(10)
        # ])
        opt = keras.optimizers.Adam(learning_rate= alpha)
        '''compile model'''
        model.compile(optimizer= opt,  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                      metrics=['accuracy'])

        '''fit'''
        model.fit(self.train_images, self.train_labels, epochs= num_epoch)

        '''test set accuracy'''
        test_loss, test_acc = model.evaluate(self.test_images,  self.test_labels, verbose=2)
        print('\nTest accuracy:', test_acc)
        t2= time.clock()

        return np.atleast_2d(-test_acc), np.atleast_2d(t2- t1), xt_eval

class Keras_model_cifar():

    def __init__(self):

        train_images, train_labels, test_images, test_labels= load_cifar()
        train_images,  test_images = prep_pixels( train_images, test_images)

        self.train_images= train_images
        self.train_labels= train_labels
        self.test_images= test_images
        self.test_labels= test_labels

    def evaluate_error_and_cost(self, filter_sizes, dense_sizes, alpha, l2_regul, dropout, num_epoch=0):

        filter_sizes= np.ndarray.astype(np.rint(np.power(2, filter_sizes)), dtype= int)
        dense_sizes= np.ndarray.astype(np.rint(np.power(2, dense_sizes)), dtype= int)
        alpha= np.power(10, alpha)
        l2_regul= np.power(10, l2_regul)
        # dropout= np.power(10, dropout)
        num_epoch= np.int(np.rint(np.power(10, num_epoch)))

        xt_eval= np.empty([1, len(filter_sizes)+ len(dense_sizes)+3])

        xt_eval[0, 0:len(filter_sizes)]= np.log2(filter_sizes[:])
        xt_eval[0,len(filter_sizes):len(filter_sizes)+ len(dense_sizes)]= np.log2(dense_sizes[:])
        xt_eval[0, len(filter_sizes)+ len(dense_sizes)]= np.log10(alpha)
        xt_eval[0, len(filter_sizes)+ len(dense_sizes)+1]= np.log10(l2_regul)
        xt_eval[0, len(filter_sizes)+ len(dense_sizes)+2]= dropout

        t1 = time.clock()
        model = Sequential()

        model.add(
            Conv2D(filter_sizes[0], (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same',
                   input_shape=(32, 32, 3), kernel_regularizer=l2(l2_regul)))
        model.add(BatchNormalization())

        model.add(Conv2D(filter_sizes[0], (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same',
                         kernel_regularizer=l2(l2_regul)))
        model.add(BatchNormalization())

        model.add(MaxPooling2D((2, 2)))
        model.add(Dropout(dropout))

        # model.add(Conv2D(filter_sizes[1], (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same',
        #                  kernel_regularizer=l2(l2_regul)))
        # model.add(BatchNormalization())
        #
        # model.add(Conv2D(filter_sizes[1], (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same',
        #                  kernel_regularizer=l2(l2_regul)))
        # model.add(BatchNormalization())
        #
        # model.add(MaxPooling2D((2, 2)))
        # model.add(Dropout(0.3))

        # model.add(Conv2D(filter_sizes[2], (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same',
        #                  kernel_regularizer=l2(l2_regul)))
        # model.add(BatchNormalization())
        #
        # model.add(Conv2D(filter_sizes[2], (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same',
        #                  kernel_regularizer=l2(l2_regul)))
        # model.add(BatchNormalization())
        #
        # model.add(MaxPooling2D((2, 2)))
        # model.add(Dropout(0.4))

        model.add(Flatten())
        model.add(Dense(dense_sizes[0], activation='relu', kernel_initializer='he_uniform', kernel_regularizer=l2(l2_regul)))
        model.add(Dropout(dropout))
        model.add(BatchNormalization())
        model.add(Dense(10, activation='softmax'))

        # compile model
        opt = Adam(lr=alpha)
        model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])

        '''fit'''
        model.fit(self.train_images, self.train_labels, epochs= num_epoch)

        '''test set accuracy'''
        test_loss, test_acc = model.evaluate(self.test_images,  self.test_labels, verbose=2)
        print('\nTest accuracy:', test_acc)
        t2= time.clock()

        return np.atleast_2d(test_loss), np.atleast_2d(t2- t1), xt_eval

class Keras_model_boston():

    def __init__(self):
        (X_train, Y_train), (X_test, Y_test) = keras.datasets.boston_housing.load_data()
        self.X_train= X_train
        self.Y_train= Y_train
        self.X_test= X_test
        self.Y_test= Y_test

    def evaluate_error_and_cost(self, layer_sizes, alpha, l2_regul, num_epoch):

        layer_sizes = np.ndarray.astype(np.rint(np.power(2, layer_sizes)), dtype= int)
        alpha= np.power(10.0, alpha)
        l2_regul= np.power(10.0, l2_regul)
        num_epoch= np.int(np.rint(np.power(10, num_epoch)))
        print('layer_sizes:{}\nalpha:{}\nl2_regul:{}\nnum_epoch:{}'.format(layer_sizes, alpha, l2_regul, num_epoch))
        '''define model'''
        t1= time.clock()
        model = keras.Sequential([
            keras.layers.Flatten(input_shape=(13, )),
            keras.layers.Dense(layer_sizes[0], activation='relu',  kernel_initializer='he_uniform', kernel_regularizer= l2(l2_regul)),
            keras.layers.Dense(layer_sizes[1], activation='relu', kernel_initializer='he_uniform', kernel_regularizer= l2(l2_regul)),
            keras.layers.Dense(layer_sizes[2], activation='relu', kernel_initializer='he_uniform', kernel_regularizer= l2(l2_regul)),
            keras.layers.Dense(layer_sizes[3], activation='relu', kernel_initializer='he_uniform', kernel_regularizer= l2(l2_regul)),
            keras.layers.Dense(1)
        ])
        opt = keras.optimizers.Adam(learning_rate= alpha)
        '''compile model'''
        model.compile(optimizer= opt,  loss=tf.keras.losses.mean_squared_error,
                      metrics=['MeanSquaredError'])

        '''fit'''
        model.fit(self.X_train, self.Y_train, epochs= num_epoch)

        '''test set accuracy'''
        test_loss, test_mse = model.evaluate(self.X_test,  self.Y_test, verbose=2)
        print('\nTest mse:', test_mse)
        t2= time.clock()

        return np.atleast_2d(test_mse), np.atleast_2d(t2- t1), model

def uniformly_choose_from_domain(domain, num_samples):
    X= np.empty([num_samples, len(domain)])
    # Y= np.empty([num_samples, 1])

    for i in range(len(domain)):
        xi= np.random.uniform(domain[i][0], domain[i][1], (num_samples,1))
        X[:, i]= xi[:,0]
    return X

def initial_training_cifar(domain, num_samples, num_layer, num_dense, num_epoch= 1.7):

    X= uniformly_choose_from_domain(domain, num_samples)

    keras_model = Keras_model_cifar()

    Y= np.empty([X.shape[0], 1])
    Y_cost= np.empty([X.shape[0], 1])

    for i in range(X.shape[0]):
        xi= X[i, :].reshape(1,-1)
        z= num_layer+num_dense
        filter_sizes =xi[0, 0:num_layer]; dense_sizes = xi[0, num_layer:z];
        alpha = xi[0, z]; l2_regul = xi[0, z+1]; dropout = xi[0, z+2]

        Y[i, 0], Y_cost[i, 0], X[i, :]= keras_model.evaluate_error_and_cost(filter_sizes, dense_sizes, alpha, l2_regul, dropout,
                                                                  num_epoch= num_epoch)

    return X, Y, Y_cost

def initial_training_fashion(domain, num_samples, num_layer, num_epoch= 1.7):

    X= uniformly_choose_from_domain(domain, num_samples)

    keras_model= Keras_model_fashion()

    Y= np.empty([X.shape[0], 1])
    Y_cost= np.empty([X.shape[0], 1])

    for i in range(X.shape[0]):
        xi= X[i, :].reshape(1,-1)
        layer_sizes =xi[0, 0:num_layer]; alpha = xi[0, num_layer]; l2_regul = xi[0, num_layer+1];
        #num_epoch= xi[0, num_layer+2]

        Y[i, 0], Y_cost[i, 0], X[i, :]= keras_model.evaluate_error_and_cost(layer_sizes, alpha, l2_regul, num_epoch)

    return X, Y, Y_cost

def initial_training_fashion2(domain, num_samples, num_epoch= 1.7):

    X= uniformly_choose_from_domain(domain, num_samples)

    keras_model= Keras_model_fashion2()

    Y= np.empty([X.shape[0], 1])
    Y_cost= np.empty([X.shape[0], 1])

    for i in range(X.shape[0]):
        xi= X[i, :].reshape(1,-1)
        layer_size = xi[0, 0]; num_layers = xi[0, 1];alpha = xi[0, 2];
        #num_epoch= xi[0, num_layer+2]

        Y[i, 0], Y_cost[i, 0], X[i, :]= keras_model.evaluate_error_and_cost(layer_size, num_layers,  alpha, num_epoch)

    return X, Y, Y_cost

def get_cifar_domain(num_layer, num_dense):

    domain_filter_size_log2= [0.0, 8.0]; domain_dense_size_log2= [0.0, 8.0]; domain_alpha_log10= [-6.0, 0.0];
    domain_l2_regul = [0.0, 0.1]; domain_dropout= [0.0, 0.8]; domain_num_epoch_log10 = [0, 2]

    domain= []

    for i in range(num_layer):
        domain.append(domain_filter_size_log2)
    for k in range(num_dense):
        domain.append(domain_dense_size_log2)

    domain.append(domain_alpha_log10)
    domain.append(domain_l2_regul)
    domain.append(domain_dropout)
    # domain.append(domain_num_epoch_log10)
    return domain

def get_fashion_domain(num_layer):

    domain_layer_size_log2= [0.0, 8.0]; domain_alpha_log10= [-6.0, 0.0];
    domain_l2_regul = [-8.0, -1.0];  #domain_num_epoch_log10 = [0, 1.3]

    domain= []

    for i in range(num_layer):
        domain.append(domain_layer_size_log2)

    domain.append(domain_alpha_log10)
    domain.append(domain_l2_regul)
    #domain.append(domain_num_epoch_log10)

    return domain

def get_fashion2_domain():

    domain_layer_size_log2= [0.0, 8.0]; domain_alpha_log10= [-6.0, 0.0];
    domain_num_layers = [1, 8]

    domain= [domain_layer_size_log2, domain_num_layers, domain_alpha_log10]

    return domain

def logistic_bjt(lower, upper):
    '''define logistic bijector'''
    low= tf.constant(lower, dtype= tf.float64); high= tf.constant(upper, dtype= tf.float64)
    affine = tfp.bijectors.AffineScalar(shift=low.numpy(), scale=(high.numpy() - low.numpy()))
    sigmoid = tfp.bijectors.Sigmoid()
    logistic = tfp.bijectors.Chain([affine, sigmoid])
    return logistic

def find_best_suited_gp_kernels(X, Y, Y_cost, noise, noise_cost):

    '''constraint values'''
    lower= 10**(-3); upper= 10**(6); #lengtscale and variance constarint
    lower_noise= 10**(-3); upper_noise= 10**(6); #noise constarint

    latent_kernel= gp.kernels.RBF()
    latent_cost_model= gp.models.GPR((X, np.log(Y_cost)), latent_kernel)
    '''limit latent cost kernel hyperparameters'''
    latent_cost_model.kernel.lengthscales= gp.Parameter(latent_cost_model.kernel.lengthscales.numpy(),transform=logistic_bjt(lower, upper))
    latent_cost_model.kernel.variance= gp.Parameter(latent_cost_model.kernel.variance.numpy(), transform= logistic_bjt(lower, upper))
    latent_cost_model.likelihood.variance= gp.Parameter(latent_cost_model.likelihood.variance.numpy(), transform= logistic_bjt(lower_noise, upper_noise))

    # latent_cost_model.likelihood.variance.assign(noise_cost)
    '''optimize cost model hyperparamters'''
    # gp.set_trainable(latent_cost_model.likelihood, False)
    opt_cost = gp.optimizers.Scipy()
    opt_cost.minimize(latent_cost_model.training_loss, latent_cost_model.trainable_variables, options=dict(maxiter=100))

    kernel= gp.kernels.RBF()
    model= gp.models.GPR((X, Y), kernel)
    '''limit objective kernel hyperparameters'''
    model.kernel.lengthscales= gp.Parameter(model.kernel.lengthscales.numpy(), transform= logistic_bjt(lower, upper))
    model.kernel.variance= gp.Parameter(model.kernel.variance.numpy(), transform= logistic_bjt(lower, upper))
    model.likelihood.variance= gp.Parameter(model.likelihood.variance.numpy(), transform= logistic_bjt(lower_noise, upper_noise))

    # model.likelihood.variance.assign(noise)

    '''optimize objective model hyperparamters'''
    opt_obj = gp.optimizers.Scipy()
    opt_obj.minimize(model.training_loss, model.trainable_variables, options=dict(maxiter=100))

    print_summary(model)
    print_summary(latent_cost_model)

    return kernel, latent_kernel

import sys
sys.path.append('../bo_cost_budget_cont_domain')
from util import *
import h5py
def grid_search_fashion():
    keras_model = Keras_model_fashion2()
    disc= 21
    domain= get_fashion2_domain()

    '''create grid'''
    x_list= []
    x_layer_size= np.linspace(1, 8, 8)
    x_width = np.linspace(0, 8.0, 21)
    x_list.append(x_layer_size); x_list.append(x_width)
    X_temp = np.meshgrid(*x_list)
    X_grid = np.empty([8*21,2])
    for i in range(2):
        X_grid[:, i] = X_temp[i].flatten()

    '''evaluate'''
    loss_list= np.empty([8*21, 1])
    X_eval=  np.empty([8*21, 3])
    cost_list=  np.empty([8*21, 1])

    for i in range(X_grid.shape[0]):
        xi = X_grid[i, :].reshape(1,-1)
        layer_size= xi[0, 0]; num_layers= xi[0, 1]
        alpha= -4
        test_lossi, time_costi, x_evali= keras_model.evaluate_error_and_cost(layer_size, num_layers, alpha, 1.7)
        loss_list[i, 0]= test_lossi
        cost_list[i, 0]= time_costi
        X_eval[i, :]= x_evali[0, :]
    with h5py.File('./keras_results/'+'fashion_grid.h5', 'a') as hf:

        hf.create_dataset('X_eval', data= X_eval)
        hf.create_dataset('loss_list', data= loss_list)
        hf.create_dataset('cost list', data= cost_list)

def test_model_fashion():
    fashion_mnist = keras.datasets.fashion_mnist
    (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

    keras_model= Keras_model_fashion()
    domain_alpha= [1e-6, 1.0]
    domain_l2= [0, 0.1]
    domain_epochs= [1,100]
    layer_sizes= [32, 32, 32, 32, 32]; alpha_log= -4; l2_regul_log= -2; num_epoch_log= 1
    l2_regul= 10**(l2_regul_log); alpha= 10**(alpha_log); num_epoch= 10**(num_epoch_log)
    test_loss, time_cost, x_eval= keras_model.evaluate_error_and_cost(layer_sizes, alpha, l2_regul, num_epoch)
    print('test_loss:{}, time_cost:{}'.format(test_loss, time_cost))

def test_model_fashion2():
    fashion_mnist = keras.datasets.fashion_mnist
    (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
    domain= get_fashion2_domain()
    keras_model= Keras_model_fashion2()

    layer_size= 5; num_layers= 4; alpha= -4
    test_loss, time_cost, x_eval= keras_model.evaluate_error_and_cost(layer_size, num_layers, alpha, 1.7)
    print('test_loss:{}, time_cost:{}'.format(test_loss, time_cost))

def test_model_cifar():
    #batch size
    # (train_images, train_labels), (test_images, test_labels) = keras.datasets.cifar10.load_data()

    filter_sizes, dense_sizes, alpha, l2_regul, num_epoch, dropout= np.array([32, 64, 128]), np.array([128]), 10**(-4), 0.01, 1, 0.1
    model_cifar= Keras_model_cifar()
    test_loss, time_cost= model_cifar.evaluate_error_and_cost(filter_sizes, dense_sizes, alpha, l2_regul, dropout)

def test_boston_model():

    layer_sizes= [5, 5, 5, 5]; alpha_log= -4; l2_regul_log= -2; num_epoch_log= 1
    boston_model= Keras_model_boston()
    test_loss, time_cost, model= boston_model.evaluate_error_and_cost(layer_sizes, alpha_log, l2_regul_log, 2)
    index= 2
    x_test= (boston_model.X_test[index, :]).reshape(1,-1)
    y_test = (boston_model.Y_test[index])
    print(model.predict(x_test))
    print('mean squared error:{}, time_cost:{}'.format(test_loss, time_cost))


# coding: utf-8
#
# Copyright 2019 Geocom Informatik AG / VertiGIS

# 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.

"""
The *datasource* module simplifies working with GEONIS Datasource XML files.
"""

import os as _os
from xml.etree import cElementTree as _ETree

import gpf.common.textutils as _tu
import gpf.tools.workspace as _ws

_GN_XMLTAG_PARAM = 'param'
_GN_XMLTAG_KEY = 'key'
_GN_XMLTAG_VALUE = 'value'

_GN_XMLKEY_PATH = 'path'
_GN_XMLKEY_SDEF = 'sdefile'
_GN_XMLKEY_QLFR = 'qualifier'

class DatasourceManager(_ws.WorkspaceManager):
    """
    DatasourceManager(datasource)

    Helper class to read a GEONIS Datasource XML, so that the user is able to generate fully qualified paths
    for elements (tables, feature datasets etc.) in an Esri workspace.
    To GEONIS, an Esri Workspace means an SDE connection file or a local File/Personal Geodatabase.

    :param datasource:  The full GEONIS Datasource XML file path.
    :type datasource:   str, unicode
    :raises ValueError: If the GEONIS Datasource XML does not exist or failed to parse.

    .. note::           All methods listed below are inherited from :class:`gpf.tools.workspace.WorkspaceManager`.
                        Only the initialization process of the *DatasourceManager* is different.
                        Generally speaking, users will find the :func:`find_path` and :func:`construct` functions
                        most useful.
    """

    def __init__(self, datasource):
        db_dir, db_file, qualifier = self._read_params(datasource)
        super(DatasourceManager, self).__init__(db_file, qualifier, db_dir)

    @staticmethod
    def _parse_xml(xml_path):
        """ Parses the XML file and returns the root Element. """
        try:
            tree = _ETree.parse(xml_path)
        except (TypeError, OSError, _ETree.ParseError) as e:
            raise ValueError('Failed to parse GEONIS Datasource XML {}: {}'.format(_tu.to_repr(xml_path), e))
        return tree.getroot()

    def _read_params(self, xml_path):
        """ Returns a tuple of (DB dir/root, DB path, DB qualifier) from a GEONIS Datasource XML. """
        db_dir = _tu.EMPTY_STR
        db_path = _tu.EMPTY_STR
        qualifier = _tu.EMPTY_STR

        xml_path = _os.path.realpath(xml_path)
        xml_root = self._parse_xml(xml_path)
        for param in xml_root.iter(_GN_XMLTAG_PARAM):
            key = param.attrib.get(_GN_XMLTAG_KEY)
            value = param.attrib.get(_GN_XMLTAG_VALUE, _tu.EMPTY_STR)
            if key in (_GN_XMLKEY_PATH, _GN_XMLKEY_SDEF):
                db_path = _os.path.normpath(value)
                if not _os.path.isabs(db_path):
                    db_dir = _os.path.dirname(xml_path)
            elif key == _GN_XMLKEY_QLFR:
                qualifier = value
        return db_dir, db_path, qualifier


import datetime
import time
import os
import sys
import logging
import argparse
import pkg_resources

from esrally import config, paths, racecontrol
from esrally.utils import io

__version__ = pkg_resources.require("esrally")[0].version

# we want to use some basic logging even before the output to log file is configured
def preconfigure_logging():
    logging.basicConfig(level=logging.INFO)

def configure_logging(cfg):
    log_dir = paths.Paths(cfg).log_root()
    io.ensure_dir(log_dir)
    cfg.add(config.Scope.application, "system", "log.dir", log_dir)
    log_file = "%s/rally_out.log" % log_dir

    print("\nWriting additional logs to %s\n" % log_file)

    # Remove all handlers associated with the root logger object so we can start over with an entirely fresh log configuration
    for handler in logging.root.handlers[:]:
        logging.root.removeHandler(handler)

    if cfg.opts("system", "quiet.mode"):
        log_level = logging.ERROR
    else:
        log_level = logging.INFO

    ch = logging.FileHandler(filename=log_file, mode="a")
    ch.setLevel(log_level)
    formatter = logging.Formatter("%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
    formatter.converter = time.gmtime
    ch.setFormatter(formatter)
    logging.root.addHandler(ch)

def parse_args():
    parser = argparse.ArgumentParser(prog="esrally", description="Benchmark Elasticsearch")
    parser.add_argument('--version', action='version', version="%(prog)s " + __version__)

    subparsers = parser.add_subparsers(
        title="subcommands",
        dest="subcommand",
        help="")

    race_parser = subparsers.add_parser("race", help="Run the benchmarking pipeline. This subcommand should typically be used.")
    # change in favor of "list telemetry", "list tracks", "list pipelines"
    list_parser = subparsers.add_parser("list", help="List configuration options")
    list_parser.add_argument(
        "configuration",
        metavar="configuration",
        help="The configuration for which Rally should show the available options. Possible values are: telemetry, tracks, pipelines, races",
        choices=["telemetry", "tracks", "pipelines", "races"])
    list_parser.add_argument(
        "--limit",
        help="Limit the number of search results for recent races (default: 10).",
        default=10,
    )

    config_parser = subparsers.add_parser("configure", help="Write the configuration file or reconfigure Rally")
    for p in [parser, config_parser]:
        p.add_argument(
                "--advanced-config",
                help="show additional configuration options when creating the config file (intended for CI runs) (default: false)",
                default=False,
                action="store_true")

    for p in [parser, race_parser]:
        p.add_argument(
            "--pipeline",
            help="Selects a specific pipeline to run. A pipeline defines the steps that are executed (default: from-sources-complete).",
            default="from-sources-complete")
        p.add_argument(
            "--quiet",
            help="Suppresses as much as output as possible. Activate it unless you want to see what's happening during the "
                 "benchmark (default: false)",
            default=False,
            action="store_true")
        p.add_argument(
            "--offline",
            help="Assume that Rally has no connection to the Internet (default: false)",
            default=False,
            action="store_true")
        p.add_argument(
            "--preserve-install",
            help="preserves the Elasticsearch benchmark candidate installation including all data. Caution: This will take lots of disk "
                 "space! (default: false)",
            default=False,
            action="store_true")
        p.add_argument(
            "--telemetry",
            help="Rally will enable all of the provided telemetry devices (i.e. profilers). Multiple telemetry devices have to be "
                 "provided as a comma-separated list.",
            default="")
        p.add_argument(
            "--revision",
            help="defines which sources to use when building the benchmark candidate. 'current' uses the source tree as is,"
                 " 'latest' fetches the latest version on master. It is also possible to specify a commit id or a timestamp."
                 " The timestamp must be specified as: \"@ts\" where \"ts\" must be a valid ISO 8601 timestamp, "
                 "e.g. \"@2013-07-27T10:37:00Z\" (default: current).",
            default="current")  # optimized for local usage, don't fetch sources
        p.add_argument(
            "--distribution-version",
            help="defines the version of the Elasticsearch distribution to download. Check https://www.elastic.co/downloads/elasticsearch "
                 "for released versions.",
            default="")
        p.add_argument(
            "--track",
            help="defines which track should be run. Only one is allowed at a time (default: geonames)",
            default="geonames")
        p.add_argument(
            "--track-setup",
            help="defines which track-setups should be run. Multiple track setups can be specified as a comma-separated "
                 "list (default: defaults).",
            default="defaults")  # optimized for local usage
        p.add_argument(
            "--target-hosts",
            help="defines a comma-separated list of host:port pairs which should be targeted iff using the pipeline 'benchmark-only' "
                 "(default: localhost:9200).",
            default="localhost:9200")
        p.add_argument(
            "--user-tag",
            help="defines a user-specific key-value pair that is separated by a ':' and added to each metric record as meta info. "
                 "Example: intention:baseline-ticket-12345",
            default="")

    ###############################################################################
    #
    # The options below are undocumented and can be removed or changed at any time.
    #
    ###############################################################################
    for p in [parser, race_parser]:
        # This option is intended to tell Rally to assume a different start date than 'now'. This is effectively just useful for things like
        # backtesting or a benchmark run across environments (think: comparison of EC2 and bare metal) but never for the typical user.
        p.add_argument(
            "--effective-start-date",
            help=argparse.SUPPRESS,
            type=lambda s: datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S"),
            default=datetime.datetime.utcnow())
        # This is a highly experimental option and will likely be removed
        p.add_argument(
            "--data-paths",
            help=argparse.SUPPRESS,
            default=None)

    for p in [parser, config_parser, race_parser]:
        # This option is needed to support a separate configuration for the integration tests on the same machine
        p.add_argument(
            "--configuration-name",
            help=argparse.SUPPRESS,
            default=None)

    return parser.parse_args()

def print_banner():
    print("    ____        ____     ")
    print("   / __ \____ _/ / /_  __")
    print("  / /_/ / __ `/ / / / / /")
    print(" / _, _/ /_/ / / / /_/ / ")
    print("/_/ |_|\__,_/_/_/\__, /  ")
    print("                /____/   ")

def derive_subcommand(args, cfg):
    subcommand = args.subcommand
    # first, trust the user...
    if subcommand is not None:
        return subcommand
    # we apply some smarts in case the user did not specify a subcommand
    if cfg.config_present():
        return "race"
    else:
        return "configure"

def csv_to_list(csv):
    if csv is None:
        return None
    else:
        return [e.strip() for e in csv.split(",")]

def main():
    preconfigure_logging()
    args = parse_args()
    cfg = config.Config(config_name=args.configuration_name)
    subcommand = derive_subcommand(args, cfg)

    if subcommand == "configure":
        cfg.create_config(advanced_config=args.advanced_config)
        exit(0)
    else:
        if cfg.config_present():
            cfg.load_config()
            if not cfg.config_compatible():
                # logger.info("Detected incompatible configuration file. Trying to upgrade.")
                cfg.migrate_config()
                # Reload config after upgrading
                cfg.load_config()
        else:
            print("Error: No config present. Please run 'esrally configure' first.")
            exit(64)

    # Add global meta info derived by rally itself
    cfg.add(config.Scope.application, "meta", "time.start", args.effective_start_date)
    cfg.add(config.Scope.application, "system", "rally.root", os.path.dirname(os.path.realpath(__file__)))
    cfg.add(config.Scope.application, "system", "invocation.root.dir", paths.Paths(cfg).invocation_root())
    # Add command line config
    cfg.add(config.Scope.applicationOverride, "source", "revision", args.revision)
    cfg.add(config.Scope.applicationOverride, "source", "distribution.version", args.distribution_version)
    cfg.add(config.Scope.applicationOverride, "system", "pipeline", args.pipeline)
    cfg.add(config.Scope.applicationOverride, "system", "track", args.track)
    cfg.add(config.Scope.applicationOverride, "system", "quiet.mode", args.quiet)
    cfg.add(config.Scope.applicationOverride, "system", "offline.mode", args.offline)
    cfg.add(config.Scope.applicationOverride, "system", "user.tag", args.user_tag)
    cfg.add(config.Scope.applicationOverride, "telemetry", "devices", csv_to_list(args.telemetry))
    cfg.add(config.Scope.applicationOverride, "benchmarks", "tracksetups.selected", csv_to_list(args.track_setup))
    cfg.add(config.Scope.applicationOverride, "provisioning", "datapaths", csv_to_list(args.data_paths))
    cfg.add(config.Scope.applicationOverride, "provisioning", "install.preserve", args.preserve_install)
    cfg.add(config.Scope.applicationOverride, "launcher", "external.target.hosts", csv_to_list(args.target_hosts))
    if subcommand == "list":
        cfg.add(config.Scope.applicationOverride, "system", "list.config.option", args.configuration)
        cfg.add(config.Scope.applicationOverride, "system", "list.races.max_results", args.limit)

    configure_logging(cfg)
    print_banner()

    race_control = racecontrol.RaceControl(cfg)
    success = race_control.start(subcommand)
    if not success:
        sys.exit(1)

if __name__ == "__main__":
    main()


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

from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.views.generic.base import TemplateView

from rest_framework import generics
from rest_framework.authentication import SessionAuthentication
from rest_framework.response import Response

from .forms import PrimaryForm, SecondaryForm, TertiaryForm
from .models import (
    SubstanceSurvey,
    Region,
    City,
    AcquiredFrom,
    Origin,
    UserCode,
    Alias,
    Substance,
    Apperance,
    Kind,
    Color,
    TestMethod,
    Drug,
)
from .serializers import (
    SubstanceSurveySerializer,
    RegionSerializer,
    CitySerializer,
    AcquiredFromSerializer,
    OriginSerializer,
    UserCodeSerializer,
    AliasSerializer,
    SubstanceSerializer,
    ApperanceSerializer,
    KindSerializer,
    ColorSerializer,
    TestMethodSerializer,
    DrugSerializer,
)

class CsrfExemptSessionAuthentication(SessionAuthentication):
    def enforce_csrf(self, request):
        return  # To not perform the csrf check previously happening

@method_decorator(staff_member_required, name='dispatch')
class SubstanceSurveyAddView(TemplateView):
    template_name = 'survey/substancesurvey_add.html'

    def get_context_data(self, **kwargs):
        context = super(SubstanceSurveyAddView, self).get_context_data(**kwargs)
        context['primary_form'] = PrimaryForm()
        context['secondary_form'] = SecondaryForm()
        context['tertiary_form'] = TertiaryForm()
        return context

class SubstanceSurveyAPIView(generics.ListAPIView):
    serializer_class = SubstanceSurveySerializer

    def get_queryset(self):
        if self.request.user.is_staff:
            queryset = SubstanceSurvey.objects.all()
        else:
            sample = self.request.query_params.get('sample', None)
            if sample is not None:
                queryset = SubstanceSurvey.objects.filter(sample_code=sample)
            else:
                queryset = SubstanceSurvey.objects.exclude(user_code__isnull=False)

        return queryset

    def post(self, request, format=None):
        data = request.data
        s = SubstanceSurvey.objects.create()

        SURVEY_ONLY_FIELDS = (
            'date_acquired',
            'price',
            'sample_code',
            'image',
            'observations',
            'contact'
        )
        SURVEY_FOREIGN_FIELDS = (
            ('region', Region, 'name'),
            ('city', City, 'name'),
            ('acquired_from', AcquiredFrom, 'name'),
            ('origin', Origin, 'name'),
            ('user_code', UserCode, 'code'),
            ('alias', Alias, 'name'),
            ('substance', Substance, 'name'),
            ('apperance', Apperance, 'name')
        )
        SURVEY_M2M_FIELDS = (
            ('kinds', Kind),
            ('color', Color),
            ('testmethods', TestMethod)
        )

        for field in SURVEY_ONLY_FIELDS:
            value = data.get(field, '')
            if value:
                setattr(s, field, value)

        for atr, model, arg_name in SURVEY_FOREIGN_FIELDS:
            get_data = data.get(atr)
            if get_data != '':
                obj, crt = model.objects.get_or_create(**{arg_name: get_data})
                if not crt:
                    obj.save()
                setattr(s, atr, obj)

        for attr, model in SURVEY_M2M_FIELDS:
            get_data = data.get(attr)
            if get_data:
                data_split = get_data.split(",")
                for el in data_split:
                    add_el, crt = model.objects.get_or_create(name=el)
                field = getattr(s, attr)
                field.add(add_el)

        get_data = data.get('detected')
        if get_data:
            d_l = get_data.split(",")
            for d in d_l:
                try:
                    dect = Drug.objects.get(name=d)
                    s.detected.add(dect)
                except Drug.DoesNotExist:
                    pass

        s.save()
        return Response("OK")

class DuplicateSurveyView(TemplateView):
    def get(self, request, uuid, **kwargs):
        ss = get_object_or_404(SubstanceSurvey, uuid=uuid)
        ss.pk = None
        ss.save()
        return HttpResponseRedirect(reverse_lazy('index'))

class SubstanceSurveyListView(TemplateView):
    template_name = 'survey/substancesurvey_list.html'

class RegionAPIView(generics.ListAPIView):
    queryset = Region.objects.all()
    serializer_class = RegionSerializer

class CityAPIView(generics.ListAPIView):
    queryset = City.objects.all()
    serializer_class = CitySerializer

class AcquiredFromAPIView(generics.ListAPIView):
    queryset = AcquiredFrom.objects.all()
    serializer_class = AcquiredFromSerializer

class OriginAPIView(generics.ListAPIView):
    queryset = Origin.objects.all()
    serializer_class = OriginSerializer

class UserCodeAPIView(generics.ListAPIView):
    queryset = UserCode.objects.all()
    serializer_class = UserCodeSerializer

class AliasAPIView(generics.ListAPIView):
    queryset = Alias.objects.all()
    serializer_class = AliasSerializer

class SubstanceAPIView(generics.ListAPIView):
    queryset = Substance.objects.all()
    serializer_class = SubstanceSerializer

class ApperanceAPIView(generics.ListAPIView):
    queryset = Apperance.objects.all()
    serializer_class = ApperanceSerializer

class KindAPIView(generics.ListAPIView):
    queryset = Kind.objects.all()
    serializer_class = KindSerializer

class ColorAPIView(generics.ListAPIView):
    queryset = Color.objects.all()
    serializer_class = ColorSerializer

class TestMethodAPIView(generics.ListAPIView):
    queryset = TestMethod.objects.all()
    serializer_class = TestMethodSerializer

class DetectedAPIView(generics.ListAPIView):
    queryset = Drug.objects.all()
    serializer_class = DrugSerializer


"""Support for tracking a Nissan Leaf."""
import logging

from homeassistant.helpers.dispatcher import dispatcher_connect
from homeassistant.util import slugify

from . import DATA_LEAF, DATA_LOCATION, SIGNAL_UPDATE_LEAF

_LOGGER = logging.getLogger(__name__)

ICON_CAR = "mdi:car"

def setup_scanner(hass, config, see, discovery_info=None):
    """Set up the Nissan Leaf tracker."""
    if discovery_info is None:
        return False

    def see_vehicle():
        """Handle the reporting of the vehicle position."""
        for vin, datastore in hass.data[DATA_LEAF].items():
            host_name = datastore.leaf.nickname
            dev_id = 'nissan_leaf_{}'.format(slugify(host_name))
            if not datastore.data[DATA_LOCATION]:
                _LOGGER.debug("No position found for vehicle %s", vin)
                return
            _LOGGER.debug("Updating device_tracker for %s with position %s",
                          datastore.leaf.nickname,
                          datastore.data[DATA_LOCATION].__dict__)
            attrs = {
                'updated_on': datastore.last_location_response,
            }
            see(dev_id=dev_id,
                host_name=host_name,
                gps=(
                    datastore.data[DATA_LOCATION].latitude,
                    datastore.data[DATA_LOCATION].longitude
                ),
                attributes=attrs,
                icon=ICON_CAR)

    dispatcher_connect(hass, SIGNAL_UPDATE_LEAF, see_vehicle)

    return True


import FWCore.ParameterSet.Config as cms
process = cms.PSet()

process.generalSet = cms.PSet(
    defaultTree= cms.string('lbSpecificDecay'),
    plotTitle  = cms.string('impact parameter from proton in  #Lambda^{0}'),
    XaxisTitle = cms.string( '' ),
    XaxisMin   = cms.double( 0. ),
    XaxisMax   = cms.double( 0.2 ),
    YaxisTitle = cms.string( 'Normalized to background shape' ),
    YaxisMin   = cms.int32( 0 ), # if -1 is set, find the value automatically.
    YaxisMax   = cms.int32( 1 ), # if -1 is set, find the value automatically.
    isSideBand = cms.bool(False),
    isLogScale = cms.bool(False),
    outFormat  = cms.string('.png')
)
process.LegendSet = cms.PSet(
        Title = cms.string('Type:'),
        xLeft = cms.double( 0.70 ),
        xRight= cms.double( 0.88 ),
        yLeft = cms.double( 0.65 ),
        yRight= cms.double( 0.85 ),
        SetTransparent=cms.bool(True),
        )

process.plotSet = cms.VPSet(
    cms.PSet( NameInTree    = cms.string( 'fd180parSignalIPt_proton_inLam0' ),
              TitleName= cms.string( 'signal proton' ), # used in TLegend
              #ScaleFactor   = cms.double( 1./4565. ), # if -1 set, normalize automatically
              ScaleFactor   = cms.double( 1./190. ), # if -1 set, normalize automatically
              SetFill  = cms.bool( False ),
              LineWidth= cms.int32( 2 ),
              LineColor= cms.int32( 3 ),
              FillStyle= cms.int32( 0 ),
              FillColor= cms.int32( 0 ),
              ),
    cms.PSet( NameInTree    = cms.string( 'fd180parBackgroundIPt_proton_inLam0' ),
              TitleName= cms.string( 'background' ), # used in TLegend
              #ScaleFactor   = cms.double( 1./36599. ),
              ScaleFactor   = cms.double( 1./1851. ),
              SetFill  = cms.bool( False ),
              LineWidth= cms.int32( 2 ),
              LineColor= cms.int32( 2 ),
              FillStyle= cms.int32( 0 ),
              FillColor= cms.int32( 0 ),
              ),
)


from .serializers import ChoiceSerializer, QuestionSerializer, CustomerSerializer, TestSerializer
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.response import Response
from rest_framework import status
from rest_framework import generics, permissions
from rest_framework.decorators import api_view
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView
from rest_framework import viewsets
from django.http import Http404
#from rest_framework.exceptions import ValidationError, ObjectDoesNotExist
#from django_filters import rest_framework as filters
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.db import transaction
import json
from .models import *
from .serializers import *
#from .models import Choice, Question, PersonalCare, Category, QuizModal, Customer, Hydration, Concerns, Products, Skin_profile, SkinTest

def get_customer_obj(uname):
    try:
        return Customer.objects.get(employee_id=uname)
    except Customer.DoesNotExist:
        raise Http404

def get_test_code():
    try:
        top = SkinTest.objects.all().order_by('-code')[0]
        #top = SkinTest.objects.filter(customer=user_info).order_by('-code')[0]
        if top:
            test_code = top.code + 1
    except IndexError:
        test_code = 1
    return test_code

# Response Function
def responsedata(status, message, code, data={}):
    if status:
        return {"success":status,"data":data,"code":code,"message":message}
    else:
        return {"success":status,"data":{},"code":code,"message":message}

#@api_view(['GET','POST'])
#def create_customer(request):
class create_customer1(APIView):
    #data = dict()
    def get(self,request):
        emp_id = request.query_params['employee_id']
        customer = get_customer_obj(emp_id)
        customer_obj = Customer.objects.get(employee_id=emp_id)
        serializer = CustomerSerializer(customer_obj, many=False)
        #data['user_info'] = serializer.data
        #return Response(data)
        return Response(serializer.data)

    def post(self,request):
        serializer = CustomerSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,status=status.HTTP_201_CREATED)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

class create_customer2(generics.ListAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ('employee_id',)
    ordering_fields = ['id']
    ordering = ['-category_id']

class create_customer3(generics.ListAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ('employee_id',)

    """
    def get_queryset(self):
        emp_id = self.request.query_params['employee_id']
        return Customer.objects.get(employee_id=emp_id)

    def get_object(self):
        emp_id = self.request.query_params['employee_id']
        return self.get_queryset().filter(employee_id=emp_id)
    """

class create_customer(generics.ListAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ('employee_id',)

class CustomerViewSet(viewsets.ModelViewSet):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ('employee_id',)

@api_view(['GET'])
def questions_list(request):
    data = dict()
    #print("request.headers :", request.headers)

    if request.method == "GET":
        user_name = request.GET['user_name']
        test_code = request.GET['test_code']

        dummy = request.headers.get('test_code')
        print(dummy)
        customer_obj = Customer.objects.get(employee_id=user_name)

        if user_name:
            skin_test_obj = SkinTest()
            skin_test_obj.code = test_code
            skin_test_obj.customer = customer_obj
            skin_test_obj.save()
            questions = Question.objects.filter(category__personalcare_id=1).order_by('code')
            serializer = QuestionSerializer(questions, many=True)
            data['questions'] = serializer.data
            data['quiz_type'] = 'skin'
            return Response(data)

@csrf_exempt
def quiz_answers(request):
    data = dict()
    user_name = request.GET.get('user_name')
    user_choice = request.GET.get('user_choice')
    test_code = request.GET.get('test_code')
    choice_data = json.loads(user_choice)

    customer_obj = Customer.objects.get(employee_id=user_name)
    skin_test_obj = SkinTest.objects.get(code=test_code)

    if choice_data:
        for x in choice_data:
            try:
                choice_obj = Choice.objects.get(pk=x)
                quiz_save = QuizModal()
                quiz_save.choice = choice_obj
                quiz_save.customer = customer_obj
                quiz_save.skin_test = skin_test_obj
                quiz_save.save()
            except ObjectDoesNotExist:
                pass
                #choice_obj = get_object_or_404(Choice, pk=x)
    data = {
        'saved': True
    }
    return JsonResponse(data, safe=False)

@csrf_exempt
def water_info(request):
    data = dict()
    if request.method == "POST":
        test_code = request.POST.get('test_code')
        user_name = request.POST.get('user_name')
        weight = request.POST.get('weight')
        physical_activity = request.POST.get('physical_activity')
        water_intake = request.POST.get('water_intake')
        status = request.POST.get('status')

        if Customer.objects.filter(employee_id=user_name).exists():
            customer_obj = Customer.objects.get(employee_id=user_name)
            skin_test_obj = SkinTest.objects.get(code=test_code)
            water_save = Hydration()
            water_save.customer = customer_obj
            water_save.weight = weight
            water_save.physical_activity = physical_activity
            water_save.water_intake = water_intake
            water_save.status = status
            water_save.skin_test = skin_test_obj
            water_save.save()
            data['is_valid'] = True
        else:
           data['is_valid'] = False
    return JsonResponse(data, safe=False)

@api_view(['GET'])
def questions_test(request):
    data = dict()

    if request.method == "GET":
        user_name = request.GET['user_name']
        test_code = request.GET['test_code']
        query_p1 = request.query_params['test_code']
        #dummy = request.headers.get('test_code')
        #print(request.headers)
        print("query_p1 :", query_p1)
        customer_obj = Customer.objects.get(employee_id=user_name)

        return Response(data)

        """
        if user_name:
            questions = Question.objects.filter(category__personalcare_id=1).order_by('code')
            serializer = QuestionSerializer(questions, many=True)
            data['questions'] = serializer.data
            data['quiz_type'] = 'skin'
            return Response(data)
        """

"""
class QuestionsTest(generics.ListAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
    filter_backends = (DjangoFilterBackend)
    filterset_fields = ('id',)

class QuestionsTest(generics.ListAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ('id', 'category',)
    search_fields = ['id']
    ordering_fields = ['id']

"""
#questions = Question.objects.filter(category__personalcare_id=1).order_by('-category_id')

class QuestionsTest1(generics.ListAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ('category__personalcare_id',)
    ordering_fields = ['id']
    ordering = ['-category_id']

class Quiz1(generics.ListAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

    def get_queryset(self):
        return self.queryset.filter(category__personalcare_id=1).order_by('-category_id')[:3]

class Quiz2(generics.ListAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

    def get_queryset(self):
        return self.queryset.filter(category__personalcare_id=1).order_by('-category_id')

class SkinTestCreate(APIView):
    def post(self,request):
        uname = request.data['user_name']
        customer = get_customer_obj(uname)
        data = request.data
        data.pop('user_name')
        #data['customer'] = data.pop('user_name')
        #data['user_name'] = data['customer'] = customer.pk
        data['customer'] = customer.pk
        serializer = SkinTestSerializer(data = data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,status=status.HTTP_201_CREATED)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

#class CompanyContactViewSet(viewsets.ModelViewSet):
class SkinTestCreate3(generics.ListCreateAPIView):
    serializer_class = SkinTestSerializer

    def create(self, validated_data):
        serializer = self.get_serializer(data=self.request.data)
        uname =  self.request.data.pop('user_name')
        #customer_instance = Customer.objects.filter(employee_id=uname).first()
        customer_instance = Customer.objects.get(employee_id=uname)

        if not serializer.is_valid():
            #print(serializer.errors)
            print("data :", serializer.data)
            data = serializer.validated_data
            serializer.save(customer=customer_instance)
            #headers = self.get_success_headers(serializer.data)
            return Response(serializer.data,status = status.HTTP_201_CREATED)
        return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)


# Author: Colin Rice
# Last edited 8/4/2015
# Does not follow MVC standards, sorry...

from tkinter import *
import webbrowser

def closewindow():    # Sets closewindow action to exit Python
    exit()

def manipulatetext():    # Takes addresses from window and manipulates the text
    s = fromaddress.get()
    s1 = toaddress.get()

    if not s and not s1:    # Check for input error
        messagebox.showinfo('Error!', "Please enter a \"to\" and \"from\" address")
        return()
    elif not s:
        messagebox.showinfo("Error!", "Please enter a \"from\" address")
        return()
    elif not s1:
        messagebox.showinfo("Error!", "Please enter a \"to\" address")
        return()
    else:
        final = paste(*parser(s, s1))
        executepage(*final)
        exit()

def parser(s, s1):    # Parses text string by spaces
    text = s.split(' ')
    text1 = s1.split(' ')
    return(text, text1)

def paste(text, text1):    # Pastes string together with '+'
    g = "+"
    finalfrom = g.join(text)
    finalto = g.join(text1)
    return(finalfrom, finalto)

def executepage(finalfrom, finalto):    # Executes Google Maps with custom address
    webbrowser.open_new("http://www.google.com/maps/dir/" + finalfrom + "/" + finalto)

maps = Tk()    # Sets up window and fonts
maps.geometry("300x225")
maps.title("Directions")
labelfont = ('times', 15,  'normal')
buttonfont = ('times', 15, 'bold')

l1 = Label(maps, font=labelfont, text="From this address:")    # Adds labels and entry box
l1.pack()
fromaddress = StringVar()
e = Entry(maps, width="250", bd=3, justify=CENTER, textvariable=fromaddress)
e.pack()

l2 = Label(maps, font=labelfont, text="To this address:")
l2.pack()
toaddress = StringVar()
e1 = Entry(maps, width="250", bd=3, justify=CENTER, textvariable=toaddress)
e1.pack()

searchbutton = Button(maps, text="Search Route", font=buttonfont, underline=15, height=2, width=10, command=manipulatetext)
searchbutton.pack()    # Defines buttons and action pressed functionality

closebutton = Button(maps, text="Close Window",  height=2, width=10, command=closewindow)
closebutton.pack()

maps.mainloop


from django.conf import settings
from os.path import dirname, realpath

if not settings.configured:
    settings.configure()

INSTALLED_APPS = getattr(settings, 'INSTALLED_APPS', [])

OAI_PROVIDER_ROOT = dirname(realpath(__file__))

# core_website_app settings
SERVER_URI = getattr(settings, 'SERVER_URI', "")

CUSTOM_NAME = getattr(settings, 'CUSTOM_NAME', '')

# OAI_PMH parameters
OAI_ADMINS = (
    ('Administrator', 'admin@curator.com'),
)
OAI_HOST_URI = SERVER_URI
OAI_NAME = CUSTOM_NAME + " OAI-PMH Server"
OAI_DELIMITER = ':'
OAI_DESCRIPTION = 'OAI-PMH ' + CUSTOM_NAME
OAI_GRANULARITY = 'YYYY-MM-DDThh:mm:ssZ'  # the finest harvesting granularity supported by the repository
OAI_PROTOCOL_VERSION = '2.0'  # the version of the OAI-PMH supported by the repository
OAI_SCHEME = 'oai'
OAI_REPO_IDENTIFIER = 'server-x'
OAI_SAMPLE_IDENTIFIER = OAI_SCHEME+OAI_DELIMITER+OAI_REPO_IDENTIFIER+OAI_DELIMITER+'id/12345678a123aff6ff5f2d9e'
OAI_DELETED_RECORD = 'persistent'  # no ; transient ; persistent


from flask_restful import Resource
from flask import (request,
                   redirect,
                   url_for,
                   render_template,
                   make_response,
                   send_from_directory,
                   send_file)
from werkzeug import secure_filename
from app import app, apis
from app.Constants import *
from app.Main import *
from app.forms import *

import os

control = Main()

class Index(Resource):
    def get(self):
        control.setUpDatabase()
        return make_response(render_template('index.html'))

class Upload_Training(Resource):
    def allowed_file(self, filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

    def post(self):
        file = request.files['file']
        if file and self.allowed_file(file.filename):
            filename = secure_filename(TRAINING_FILE)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('second'))
        return redirect(url_for('first'))

    def get(self):
        return make_response(render_template('first.html'))

class Upload_Org(Resource):
    def allowed_file(self, filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

    def post(self):
        file = request.files['file']
        if file and self.allowed_file(file.filename):
            filename = secure_filename(ORGANISATION_FILE)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            control.uploadOrg()
            return redirect(url_for('third'))
        return redirect(url_for('second'))

    def get(self):
        return make_response(render_template('second.html'))

class Upload_Test(Resource):
    def allowed_file(self, filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

    def post(self):
        file = request.files['file']
        if file and self.allowed_file(file.filename):
            filename = secure_filename(TESTING_FILE)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            control.predict()
            control.uploadResult()
            return redirect(url_for('result'))
        return redirect(url_for('third'))

    def get(self):
        return make_response(render_template('third.html'))

class Download(Resource):
    def get(self):
        basedir = os.path.abspath(os.path.dirname(__file__))
        uploads = os.path.join(basedir, 'static\\tmp\\' + RESULT_FILE)
        return send_file(uploads, mimetype='Document')

class Result(Resource):
    def __init__(self):
        self.form = InputForm()

    def get(self):
        u = None
        return make_response(render_template('result.html', u=u,
                                             form=self.form))

    def post(self):
        if self.form.validate_on_submit():
            u = control.getUserData(self.form)
            return make_response(render_template('result.html', u=u,
                                                 form=self.form))
        u = None
        return make_response(render_template('result.html', u=u,
                                             form=self.form))

apis.add_resource(Index,
                  '/',
                  endpoint='index')

apis.add_resource(Result,
                  '/result',
                  endpoint='result')

apis.add_resource(Upload_Training,
                  '/upload/training',
                  endpoint='first')

apis.add_resource(Upload_Org,
                  '/upload/org',
                  endpoint='second')

apis.add_resource(Upload_Test,
                  '/upload/test',
                  endpoint='third')

apis.add_resource(Download,
                  '/download',
                  endpoint='download')


#!/usr/bin/env python3
# Written by Jung Cho (jungyoun.cho@mmk.su.se), MMK, Stockholm University
import sys
import CifFile
import random

def read(cifName):
    a = []
    fileName = cifName+'.cif'
    my_cif = CifFile.CifFile(fileName)
    keys = my_cif.keys()
    strName = keys[0]
    cif = my_cif[strName]
    atmtype = cif['_atom_site_label']
    atmlabel = cif['_atom_site_type_symbol']
    xpos = cif['_atom_site_fract_x']
    ypos = cif['_atom_site_fract_y']
    zpos = cif['_atom_site_fract_z']
    iso = cif['_atom_site_U_iso_or_equiv']
    adp = cif['_atom_site_adp_type']
    occ = cif['_atom_site_occupancy']

    for i in range(len(atmtype)):
        a.append([atmtype[i], atmlabel[i], xpos[i], ypos[i], zpos[i], iso[i], adp[i], occ[i]])

    return a

def write_cif(cifName, ax, cx, fname):
    ary = read(cifName)
    f = open(fname, 'a')
    for i in range(len(ary)):
        for j in range(ax):
            for k in range(cx):
                print(ary[i][0], ary[i][1], float(ary[i][2])/ax+j/ax, ary[i][3], float(ary[i][4])/cx+k/cx, ary[i][5],
                      ary[i][6], ary[i][7], file=f)
    f.close()

def write_d5r(cifName, ax, cx, row, col, fname):
    ary = read(cifName)
    f = open(fname, 'a')
    for i in range(len(ary)):
        for j in range(row-1, row):
            for k in range(col-1, col):
                print(ary[i][0], ary[i][1], float(ary[i][2]) / ax + j / ax, ary[i][3], float(ary[i][4]) / cx + k / cx,
                      ary[i][5], ary[i][6], ary[i][7], file=f)
    f.close()

def randomize(flag, ax, cx, fname):
    f = open(fname, 'a')

    for i in range(ax):
        for j in range(cx):
            rn = random.uniform(0, 4)
            # print(rn)
            if flag == 'odd':
                if rn < 1:
                    write_d5r('odd_t1', ax, cx, i+1, j+1, fname)
                elif 1 <= rn < 2:
                    write_d5r('odd_t2', ax, cx, i+1, j+1, fname)
                elif 2 <= rn < 3:
                    write_d5r('odd_t3', ax, cx, i+1, j+1, fname)
                elif 3 <= rn < 4:
                    write_d5r('odd_t4', ax, cx, i+1, j+1, fname)
            elif flag == 'even':
                if rn < 1:
                    write_d5r('even_t1', ax, cx, i+1, j+1, fname)
                elif 1 <= rn < 2:
                    write_d5r('even_t2', ax, cx, i+1, j+1, fname)
                elif 2 <= rn < 3:
                    write_d5r('even_t3', ax, cx, i+1, j+1, fname)
                elif 3 <= rn < 4:
                    write_d5r('even_t4', ax, cx, i+1, j+1, fname)
    f.close()

def main():
    # super cell size
    ax = 20
    cx = 20

    # Lattice parameters
    a = 23.736
    b = 10.1738
    c = 21.323

    # Print fractional coordinates to the file
    f = open('mod.cif', 'w')
    print('data_meh\n_symmetry_space_group_name_H-M \'P1\'\n_symmetry_Int_Tables_number 1\n'
          '_symmetry_cell_setting triclinic\nloop_\n_symmetry_equiv_pos_as_xyz\nx,y,z\n'
          '_cell_length_a '+str(a*ax)+'\n_cell_length_b 10.1738\n_cell_length_c '
          + str(c*cx)+'\n_cell_angle_alpha 90\n'
          '_cell_angle_beta 111.83\n_cell_angle_gamma 90\nloop_\n_atom_site_label\n'
          '_atom_site_type_symbol\n_atom_site_fract_x\n_atom_site_fract_y\n_atom_site_fract_z\n'
          '_atom_site_U_iso_or_equiv\n_atom_site_adp_type\n_atom_site_occupancy\n', file=f)
    f.close()
    write_cif('cas_odd', ax, cx, 'mod.cif')
    write_cif('cas_even', ax, cx, 'mod.cif')
    # # write_cif('odd_t1', ax, cx, 'mod.cif')
    # # write_cif('even_t2', ax, cx, 'mod.cif')
    # # randomize('odd', ax, cx, 'mod.cif')
    randomize('odd', ax, cx, 'mod.cif')
    randomize('even', ax, cx, 'mod.cif')

if __name__ == '__main__':
    main()


def identificar_caracter():
    print("\n___________________ IDENTIFICACION DE CARACTERES ___________________")
    caracter = input("Digite un caracter: ")

    #Enfoque 1
    if (caracter.isalpha()):
        if (caracter.isupper()):
            print("Es una MAYUSCULA")
        else:
            print("Es una MINUSCULA")

    #Enfoque 2
    lista_de_mayusculas = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
    lista_de_minusculas = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

    if (caracter in lista_de_mayusculas):
        print("Es una MAYUSCULA")
    if (caracter in lista_de_minusculas):
        print("Es una MINUSCULA")

identificar_caracter()

#------------------------- PSEUDO-CODIGO -------------------------
"""
caracter = Obtener valor desde la consola

si caracter es mayuscula entonces imprimir "Es Mayuscula"
si caracter es minuscula entonces imprimir "Es Minuscula"

"""