from django.urls import include, path
from . import views
from django.contrib.auth import login, logout
from django.contrib.auth import views as auth_views

urlpatterns = [
    #path('', views.IndexView.as_view(), name='index'),

    path('', views.Signup, name='signup'),
    path('signup/customer', views.CustomerSignUpView.as_view(), name='customer_signup'),
    path('signup/store-admin', views.StoreAdminSignUpView.as_view(), name='store_admin_signup'),
    path('login/', auth_views.LoginView.as_view(), name='login'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
    path('home/', views.HomeView.as_view(), name='home'),
    path('<int:pk>', views.ProductDetailView.as_view(), name='detail'),
    path('delete/<int:pk>/', views.deleteProduct, name='deleteProduct'),
    path('edit/<int:pk>/', views.edit, name='edit'),
    path('storeadmin/', views.StoreView.as_view(), name='storeadmin'),
    path('add-product/', views.AddProduct, name='addproduct'),
    path('cart-detail/<int:pk>', views.AddToCartView, name='cartdetail'),
    path('cart',views.cart_view.as_view(),name='cart'),
]


#!/usr/bin/env python
from __future__ import division
import cPickle as pickle
import numpy as np
import math
import shelve
from itertools import chain
from rpy import r
import csv

pchisq = r.pchisq
padjust = r.p_adjust
RATIO_MINREADS = 50
SPLITCNTLABELS = ('5UTR', 'CDS', '3UTR', 'Exon')
NULLREADS = (0, 0, 0)

def load(d, name, infile):
    splitcnts = d
    splitcntidx = dict((label, i) for i, label in enumerate(SPLITCNTLABELS))

    p = pickle.load(open(infile))
    for (acc, label), cnts in p.iteritems():
        cntplace = splitcnts[splitcntidx[label]]
        if acc not in cntplace:
            cntplace[acc] = {}
        cntplace[acc][name] = cnts

    return splitcnts

def calclogratio(d, samplea, sampleb):
    r = {}
    for acc, cnts in d.iteritems():
        cnta = cnts.get(samplea, NULLREADS)
        cntb = cnts.get(sampleb, NULLREADS)
        if cnta[0] < RATIO_MINREADS and cntb[0] < RATIO_MINREADS:
            continue

        l2rat = math.log((cntb[0] + 1) / (cnta[0] + 1), 2)
        r[acc] = l2rat

    return r

def writeresult(refsample, samples, origcnt, l2ratio, significance):
    w = csv.writer(sys.stdout)
    w.writerow(['accession', 'gene', 'p-value', 'FDR',
                'exonCount', 'totalLength', 'cdsLength', 'noncodingLength'] +
                list(chain(*[['%s 5UTR cnt' % sample, '%s CDS cnt' % sample,
                              '%s 3UTR cnt' % sample, '%s Exon cnt' % sample,
                              '%s 5UTR l2r' % sample, '%s CDS l2r' % sample,
                              '%s 3UTR l2r' % sample, '%s Exon l2r' % sample]
                              for sample in samples])))

    l2idx = range(len(SPLITCNTLABELS))

    allacc = reduce(lambda x, y: x|y, (set(cnt) for cnt in origcnt))
    for acc in allacc:
        if all((acc not in inst)
                for sample in samples for inst in l2ratio[sample]):
            continue

        entry = REFFLAT[acc]
        if 'cdsBlocks' in entry:
            cdslen = sum(b-a for a, b in entry['cdsBlocks'])
        else:
            cdslen = 0

        gsym = entry['geneName']
        out = [acc, gsym, significance.get(acc, (1., 1.))[0],
               significance.get(acc, (1., 1.))[1], entry['exonCount'],
               entry['totalLength'], cdslen, entry['totalLength'] - cdslen]
        for sample in samples:
            out.extend([cnt.get(acc, {}).get(sample, NULLREADS)[0]
                        for cnt in origcnt])
            out.extend([rat.get(acc, 0.) for rat in l2ratio[sample]])

        w.writerow(out)

def calc_significance(ratios):
    # ranking for nonparametric tests
    commonaccs = reduce(lambda x, y: x & y,
                        (set(ratios[smp][3]) for smp in SAMPLES_FOR_FDR))
    accranks = None
    for sample in SAMPLES_FOR_FDR:
        sratios = ratios[sample]
        ordered = sorted(commonaccs,
                         key=lambda acc: sratios[3][acc], reverse=True)
        if accranks is None:
            accranks = dict((acc, [rank]) for rank, acc in enumerate(ordered))
        else:
            for rank, acc in enumerate(ordered):
                accranks[acc].append(rank)

    # chi-squared test
    totaltranscripts = len(accranks)

    accs, pvalues = [], []
    for acc, ranks in accranks.iteritems():
        chisq = -2 * np.log(np.add(ranks, 1) / totaltranscripts).sum()
        pvalue = 1 - pchisq(chisq, len(SAMPLES_FOR_FDR)*2)
        accs.append(acc)
        pvalues.append(pvalue)

    fdrs = padjust(pvalues, 'BH')

    return dict(zip(accs, zip(pvalues, fdrs)))

if __name__ == '__main__':
    import sys

    REFFLAT = shelve.open(sys.argv[1], 'r')
    refsample = sys.argv[2]
    clipsamples = sys.argv[3].split(',')
    datafiles = [token.split(':') for token in sys.argv[4:]]
    samples = [label for label, _ in datafiles]

    SAMPLES_FOR_FDR = clipsamples

    d = {}, {}, {}, {}

    for label, fname in datafiles:
        load(d, label, fname)

    # add 0, 1, 2 (UTRs and CDS) to 3 (exon)
    exoncnt = d[3]
    for partcnt in d[0:3]:
        for acc, smpcnt in partcnt.iteritems():
            if acc not in exoncnt:
                exoncnt[acc] = smpcnt
                continue

            currcnt = exoncnt[acc]
            for smp, cnt in smpcnt.iteritems():
                currcnt[smp] = tuple(np.add(cnt, currcnt[smp]))

    ratios = {}
    for sample in samples:
        l2r = []
        for iidx in range(len(d)):
            l2r.append(calclogratio(d[iidx], refsample, sample))
        ratios[sample] = tuple(l2r)

    significance = calc_significance(ratios)

    writeresult(refsample, samples, d, ratios, significance)


# y is kept var
import re
from part_one import get_sub_formulas, tseitin_to_cnf
import pprint
from LP.SMT_TQ_Input_test import *
from part_two import get_equation_and_predicates
import numpy as np
from LP.LPInput import LPInput
import copy
from sympy.logic.boolalg import to_dnf
from sympy.logic import simplify_logic

# separate the string to list such that if we sum the values we get the string
def create_final_vars_and_const_separate(single_frml_side):
    vars_and_const = re.split("\+", single_frml_side)
    final_vars_and_const_separate = []
    for i in range(len(vars_and_const)):
        if "-" in vars_and_const[i][1:]:
            vars_and_const_minus = vars_and_const[i].split("-")
            start_index_minus = len(final_vars_and_const_separate)
            for j in range(len(vars_and_const_minus)):
                final_vars_and_const_separate.append("-" + vars_and_const_minus[j])
            if vars_and_const[i][0] == "-":
                del final_vars_and_const_separate[start_index_minus]
            else:
                final_vars_and_const_separate[start_index_minus] = final_vars_and_const_separate[start_index_minus][1:]
        else:
            final_vars_and_const_separate.append(vars_and_const[i])
    return final_vars_and_const_separate

# TODO smart
def to_float(s):
    if s == "-":
        return -1
    try:
        f_s = float(s)
    except ValueError:
        f_s = None
    return f_s

# TODO do not return types
def sum_mul_const_single_frml_side(num, types, final_vars_count, coefficient):
    num *= coefficient
    final_vars_count = [i * coefficient for i in final_vars_count]
    return num, types, final_vars_count

def sum_2_single_frml_side(num1, types1, final_vars_count1, num2, types2, final_vars_count2):
    num = num1 + num2
    # TODO need copy?
    types = types1.copy()
    final_vars_count = final_vars_count1.copy()
    for type_index in range(len(types2)):
        if types2[type_index] not in types:
            types.append(types2[type_index])
            final_vars_count.append(final_vars_count2[type_index])
        else:
            final_vars_count[types.index(types2[type_index])] += final_vars_count2[type_index]
    return num, types, final_vars_count

def create_final_vars_and_const(single_frml_side, single_frml_side_without_bracket_solved: dict):
    """
    :param single_frml_side: string without =,!=,<,>,(,)
    :return: num - the sum of the numerical values
            types - the var names
            final_vars_count - the coefficient of the var in types with the same index
    """
    final_vars_and_const_separate = create_final_vars_and_const_separate(single_frml_side)

    types = []
    num = 0
    final_vars_count = []
    for i in range(len(final_vars_and_const_separate)):

        element = final_vars_and_const_separate[i]
        to_float_res = to_float(element)
        if to_float_res is not None:
            num += to_float_res
        else:
            if "!" not in element:
                start_name_index = element.find(re.findall("[a-zA-Z]", element)[0])
            else:
                start_name_index = element.find("!")
            type_name = element[start_name_index:]
            if start_name_index == 0:
                type_num = 1
            elif element[0] == "-" and start_name_index == 1:
                type_num = -1
            else:
                type_num = to_float(element[:start_name_index])

            if "!" in element and element.find("%") != len(element) - 1:
                type_num *= to_float(element[element.find("%") + 1:])
            if "!" in element:
                num_element, types_element, final_vars_count_element = single_frml_side_without_bracket_solved[
                    type_name[type_name.find("!") + 1:type_name.find("%")]]
                num_element, types_element, final_vars_count_element = sum_mul_const_single_frml_side(num_element,
                                                                                types_element,
                                                                                final_vars_count_element,
                                                                                type_num)
                num, types, final_vars_count = sum_2_single_frml_side(num, types, final_vars_count, num_element,
                                                                      types_element, final_vars_count_element)
            else:
                if type_name not in types:
                    types.append(type_name)
                    final_vars_count.append(type_num)
                else:
                    final_vars_count[types.index(type_name)] += type_num

    return num, types, final_vars_count

def create_final_vars_and_const_with_brackets(single_frml_side):
    """
    :param single_frml_side: string without =,!=,<,>
    :return: num - the sum of the numerical values
            types - the var names
            final_vars_count - the coefficient of the var in types with the same index
    """
    if "(" not in single_frml_side:
        return create_final_vars_and_const(single_frml_side, {})

    single_frml_side_without_bracket = get_sub_formulas(single_frml_side, P="!", add_prefix="%")
    single_frml_side_without_bracket_solved = {}

    for current_index in range(len(single_frml_side_without_bracket)):
        single_frml_side_without_bracket_solved[str(current_index + 1)] = create_final_vars_and_const(
            single_frml_side_without_bracket[current_index][1:-1], single_frml_side_without_bracket_solved)
    return single_frml_side_without_bracket_solved[str(len(single_frml_side_without_bracket))]

def move_vars_and_const(num1, types1, final_vars_count1, num2, types2, final_vars_count2):
    """
    :return: num is in the 2 side
            the vars are in 1 side
    """
    num2, types2, final_vars_count2 = sum_mul_const_single_frml_side(num2, types2, final_vars_count2, -1)
    num, types, final_vars_count = sum_2_single_frml_side(num1, types1, final_vars_count1, num2, types2,
                                                          final_vars_count2)
    return -num, types, final_vars_count

def parse_single_frml_smaller_eq(single_frml):
    sides = single_frml.split("<=")
    num1, types1, final_vars_count1 = create_final_vars_and_const_with_brackets(sides[0])
    num2, types2, final_vars_count2 = create_final_vars_and_const_with_brackets(sides[1])
    return list(move_vars_and_const(num1, types1, final_vars_count1, num2, types2, final_vars_count2))

def parse_single_frml_bigger_eq(single_frml):
    sides = single_frml.split("=>")
    num1, types1, final_vars_count1 = create_final_vars_and_const_with_brackets(sides[0])
    num2, types2, final_vars_count2 = create_final_vars_and_const_with_brackets(sides[1])
    return list(move_vars_and_const(num2, types2, final_vars_count2, num1, types1, final_vars_count1))

def parse_single_frml_eq(single_frml):
    sides = single_frml.split("=")
    num1, types1, final_vars_count1 = create_final_vars_and_const_with_brackets(sides[0])
    num2, types2, final_vars_count2 = create_final_vars_and_const_with_brackets(sides[1])
    num, types, final_vars_count = move_vars_and_const(num2, types2, final_vars_count2, num1, types1, final_vars_count1)
    num_rev, types_rev, final_vars_count_rev = sum_mul_const_single_frml_side(num, types, final_vars_count, -1)
    return [[num, types, final_vars_count], [num_rev, types_rev, final_vars_count_rev]]

def parse_single_frml_smaller(sides, start_index):
    """
    :param sides: [a (<) b]
    """
    num1, types1, final_vars_count1 = create_final_vars_and_const_with_brackets(sides[0])
    num2, types2, final_vars_count2 = create_final_vars_and_const_with_brackets(sides[1])
    num, types, final_vars_count = move_vars_and_const(num1, types1, final_vars_count1, num2, types2, final_vars_count2)
    types.append("y")
    final_vars_count.append(1)
    return start_index + 1, "a" + str(start_index), [num, types, final_vars_count]

def parse_single_frml(single_frml, start_index):
    """

    :param single_frml:
    :param start_index:
    :return:
            new start_index
            sat string to replace frml with
            dict from index to parsed frml
    """
    if "<=" in single_frml:
        return start_index + 1, "a" + str(start_index), {
            "a" + str(start_index): parse_single_frml_smaller_eq(single_frml)}
    elif "=>" in single_frml:
        return start_index + 1, "a" + str(start_index), {
            "a" + str(start_index): parse_single_frml_bigger_eq(single_frml)}
    elif ">" in single_frml:
        sides = single_frml.split(">")
        parse_single_frml_smaller_res = parse_single_frml_smaller([sides[1], sides[0]], start_index)
        return parse_single_frml_smaller_res[0], parse_single_frml_smaller_res[1], {
            "a" + str(start_index): parse_single_frml_smaller_res[2]}
    elif "<" in single_frml:
        sides = single_frml.split("<")
        parse_single_frml_smaller_res = parse_single_frml_smaller(sides, start_index)
        return parse_single_frml_smaller_res[0], parse_single_frml_smaller_res[1], {
            "a" + str(start_index): parse_single_frml_smaller_res[2]}
    elif "!=" in single_frml:
        sides = single_frml.split("!=")
        parse_single_frml_smaller_res1 = parse_single_frml_smaller(sides, start_index)
        parse_single_frml_smaller_res2 = parse_single_frml_smaller([sides[1], sides[0]], start_index + 1)
        return start_index + 2, "(" + "a" + str(start_index) + "&y>0)|(" + "a" + str(start_index + 1) + "&y>0)", {
            "a" + str(start_index): parse_single_frml_smaller_res1[2],
            "a" + str(start_index + 1): parse_single_frml_smaller_res2[2]}
    else:  # =
        parse_single_frml_eq_res = parse_single_frml_eq(single_frml)
        return start_index + 2, "a" + str(start_index) + "&" + "a" + str(start_index + 1), {
            "a" + str(start_index): parse_single_frml_eq_res[0],
            "a" + str(start_index + 1): parse_single_frml_eq_res[1]}


import cherrypy
import json
import mastermind
from mastermind import A

def withREST(o_class):
    o_class._cp_config = {'tools.CORS.on': True}
    o_new = o_class.new
    @cherrypy.expose
    def new(self):
        o_new(self)
        return(self.get())
    o_class.new = new

    @cherrypy.expose
    def get(self):
        cherrypy.response.headers['Content-Type'] = "application/json"
        return_dict = {}
        return_dict['board'] = [{"move": tuple(row[0]), "result": row[1]} for row in self.board.board]
        return_dict['state'] = "end" if self.ended else "running"
        return_dict['ttl']   = self.board.ttl
        return json.dumps(return_dict)
    o_class.get  = get

    o_move = o_class.move
    @cherrypy.expose
    @cherrypy.tools.json_in()
    def move(self):
        try:
            data = cherrypy.request.json
            o_move(self, data["request"])
        except:
            pass
        return(self.get())
    o_class.move = move

    return (o_class)

Game = withREST(mastermind.Game)

def CORS():
    cherrypy.response.headers['Access-Control-Request-Headers'] = 'content-type'
    cherrypy.response.headers['Access-Control-Allow-Methods']   = 'POST'
    cherrypy.response.headers['Access-Control-Allow-Origin']    = "*"
    cherrypy.response.headers['Access-Control-Allow-Headers']   = 'Content-Type'

if __name__ == '__main__':
    # cherrypy.tools.CORS = cherrypy.Tool('before_finalize', CORS)
    cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)
    cherrypy.tree.mount(Game([1,2,3,4,5,6]))
    # cherrypy.server.socket_host = '10.0.101.42' # TT-LAN
    cherrypy.server.socket_host = '127.0.0.1'
    cherrypy.engine.start()
    cherrypy.engine.block()


# -*- coding: utf-8 -*-
#%%
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix,classification_report
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
# estimator
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
#%%
df= pd.read_csv("https://raw.githubusercontent.com/digipodium/Datasets/main/classfication/Social_Network_Ads.csv")
df
#%%
X = df[['Age','EstimatedSalary']]
y= df['Purchased']
X_train, X_test, y_train, y_test= train_test_split(X,y,test_size=.2)
#%%
c1 = Pipeline(steps=[
    ('scaler',StandardScaler()),
    ('model',LogisticRegression())
    ] )
#%%
c2 = Pipeline(steps=[
    ('scaler',StandardScaler()),
    ('model',DecisionTreeClassifier())
    ] )
#%%
c3 = Pipeline(steps=[
    ('scaler',StandardScaler()),
    ('model',SVC())
    ] )
#%%
c4 = Pipeline(steps=[
    ('scaler',StandardScaler()),
    ('model',RandomForestClassifier())
    ] )
#%%
c5 = Pipeline(steps=[
        ('scaler',StandardScaler()),
        ('model',KNeighborsClassifier())
        ] )
#%%
c6 = Pipeline(steps=[
    ('scaler',StandardScaler()),
    ('model',GaussianNB())
    ] )
#%%
c1.fit(X_train,y_train)
y_pred =c1.predict(X_test)
cf1= confusion_matrix(y_test, y_pred)
cf1 = classification_report(y_test, y_pred)
#%%
c2.fit(X_train,y_train)
y_pred =c2.predict(X_test)
cf2= confusion_matrix(y_test, y_pred)
cf2 = classification_report(y_test, y_pred)
#%%
c3.fit(X_train,y_train)
y_pred =c3.predict(X_test)
cf3 = confusion_matrix(y_test, y_pred)
cf3 = classification_report(y_test, y_pred)
#%%
c4.fit(X_train,y_train)
y_pred =c4.predict(X_test)
cf4 = confusion_matrix(y_test, y_pred)
cf4 = classification_report(y_test, y_pred)
#%%
c5.fit(X_train,y_train)
y_pred =c5.predict(X_test)
cf5 = confusion_matrix(y_test, y_pred)
cf5 = classification_report(y_test, y_pred)
#%%
c6.fit(X_train,y_train)
y_pred =c6.predict(X_test)
cf6 = confusion_matrix(y_test, y_pred)
cf6 = classification_report(y_test, y_pred)
#%%
from mlxtend.plotting import plot_decision_regions
plot_decision_regions(X.values,y.values,c1,)
plt.show()
#%%
from mlxtend.plotting import plot_decision_regions
plot_decision_regions(X.values,y.values,c2,)
plt.show()
#%%
from mlxtend.plotting import plot_decision_regions
plot_decision_regions(X.values,y.values,c3,)
plt.show()
#%%
from mlxtend.plotting import plot_decision_regions
plot_decision_regions(X.values,y.values,c4,)
plt.show()
#%%
from mlxtend.plotting import plot_decision_regions
plot_decision_regions(X.values,y.values,c5,)
plt.show()
#%%
from mlxtend.plotting import plot_decision_regions
plot_decision_regions(X.values,y.values,c6,)
plt.show()
#%%KNN shows best performance
from joblib import dump
dump(c5,'knn_sicial_ads')


import tkinter as tk
import tkinter.ttk as ttk
import guiLibs.rusEntry as rusEntry

class editEntry(tk.Toplevel):
	def __init__(self, master, line):
		tk.Toplevel.__init__(self, master)
		self.geometry("500x500")
		self.master = master
		self.createWidgets()

	def createWidgets(self):
		self.labels = []
		self.entries = []

		self.textLabel = tk.Label(self, text = "Entry")
		self.labels.append(self.textLabel)

		self.textEntry = rusEntry.Entry(self)
		self.entries.append(self.textEntry)

		self.transLabel = tk.Label(self, text = "Translation")
		self.labels.append(self.transLabel)

		self.transEntry = rusEntry.Entry(self)
		self.entries.append(self.transEntry)

		self.tagsLabel = tk.Label(self, text = "Tags")
		self.labels.append(self.tagsLabel)

		self.tagsEntry = tk.Entry(self)
		self.entries.append(self.tagsEntry)

		self.learnedLabel = tk.Label(self, text = "Learned")
		self.labels.append(self.learnedLabel)

		self.learnedEntry = tk.Label(self, text = "-")
		self.entries.append(self.learnedEntry)

		self.attemptsLabel = tk.Label(self, text = "Attmpts")
		self.labels.append(self.attemptsLabel)

		self.attemptsEntry = tk.Label(self, text = "-")
		self.entries.append(self.attemptsEntry)

		self.successfulAttemptsLabel = tk.Label(self, text = "Successful attempts")
		self.labels.append(self.successfulAttemptsLabel)

		self.successfulAttemptsEntry = tk.Label(self, text = "-")
		self.entries.append(self.successfulAttemptsEntry)

		self.dayLastAttemptLabel = tk.Label(self, text = "Day of last attempt")
		self.labels.append(self.dayLastAttemptLabel)

		self.dayLastAttemptEntry = tk.Label(self, text = "-")
		self.entries.append(self.dayLastAttemptEntry)

		self.lastAttemptResultLabel = tk.Label(self, text = "Result of last attempt")
		self.labels.append(self.lastAttemptResultLabel)

		self.lastAttemptResultEntry = tk.Label(self, text = "-")
		self.entries.append(self.lastAttemptResultEntry)

		self.dayToReviewLabel = tk.Label(self, text = "Day of next review")
		self.labels.append(self.dayToReviewLabel)

		self.dayToReviewEntry = tk.Label(self, text = "-")
		self.entries.append(self.dayToReviewEntry)

		self.attemptStreakLabel = tk.Label(self, text = "Attempt streak")
		self.labels.append(self.attemptStreakLabel)

		self.attemptStreakEntry = tk.Label(self, text = "-")
		self.entries.append(self.attemptStreakEntry)

		self.idLabel = tk.Label(self, text = "ID")
		self.labels.append(self.idLabel)

		self.idLabel2 = tk.Label(self, text = "-")
		self.entries.append(self.idLabel2)

		self.deckLabel = tk.Label(self, text = "Deck")
		self.labels.append(self.deckLabel)

		self.deckEntry = tk.Entry(self)
		self.entries.append(self.deckEntry)

		self.levelLabel = tk.Label(self, text = "Level")
		self.labels.append(self.levelLabel)

		self.levelEntry = tk.Entry(self)
		self.entries.append(self.levelEntry)

		self.ignoreLabel = tk.Label(self, text = "Ignore")
		self.labels.append(self.ignoreLabel)

		self.ignoreEntry = tk.Label(self, text = "-")
		self.entries.append(self.ignoreEntry)

		self.langLabel = tk.Label(self, text = "Language")
		self.labels.append(self.langLabel)

		self.langEntry = tk.Entry(self)
		self.entries.append(self.langEntry)

		for n,w in enumerate(self.labels):
			w.grid(row = n, column = 1)
		for n,w in enumerate(self.entries):
			w.grid(row = n, column = 2, sticky = 'w', columnspan = 999)
			w['width'] = 55
			if w == self.ignoreEntry:
				w['width'] = 50

			if w['text'] == "-":
				w['text'] = self.master.line[n]
			else:
				w.insert(0, self.master.line[n].replace("commaChar", ","))

		self.ignoreCheck = tk.Checkbutton(self, command = self.ignoreCheckFunc)
		self.ignoreCheck.grid(column = 875, row = 13, sticky = 'e')
		if self.ignoreEntry['text'] == "yes":
			self.ignoreCheck.select()
		else:
			self.ignoreCheck.deselect()

		self.saveButton = tk.Button(self, text = "Save", command = self.saveEdits)
		self.saveButton.grid(column = 0, columnspan = 2)

	def ignoreCheckFunc(self):
		if self.ignoreEntry['text'] == "no":
			self.ignoreEntry['text'] =  "yes"
		else:
			self.ignoreEntry['text'] = "no"

	def saveEdits(self):
		self.master.lineEdited = True
		for n,w in enumerate(self.entries):
			try:
				self.master.line[n] = w.get().replace(",", "commaChar")
			except:
				self.master.line[n] = w['text']


from django.shortcuts import render, redirect
from Transporte.models import Transporte
from Transporte.forms import TransporteForm
from . import forms

def listadoTransportes(request):
    transportes = Transporte.objects.all()
    data = {'transportes': transportes}
    return render(request, 'Transporte/transporte.html', data)

def agregarTransporte(request):
    form = TransporteForm()
    if request.method == 'POST':
        form = TransporteForm(request.POST)
        if form.is_valid():
            form.save()
        return redirect('listado_transportes')
    data = {'form': form}
    print(form)
    print(data)
    return render(request, 'Transporte/AgregarTransporte.html', data)

def eliminarTransporte(request, id):
    transporte = Transporte.objects.get(id=id)
    transporte.delete()
    return redirect('listado_transportes')

def actualizarTransporte(request, id):
    transporte = Transporte.objects.get(id=id)
    form = TransporteForm(instance=transporte)
    if request.method == 'POST':
        form = TransporteForm(request.POST, instance=transporte)
        if form.is_valid():
            form.save()
        return redirect('listado_transportes')
    data = {'form': form}
    return render(request, 'Transporte/AgregarTransporte.html', data)


#from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render

from .models import Jogador
# Create your views here.

def index(request):
    texto = "Página principal do novo site da barragem"
    context = {
        'meu_texto': texto
    }
    return render(request, 'tenis/index.html', context)

def tabela(request):
    texto = "Página da tabela do novo site barragem"
    context = {
        'meu_texto': texto
    }
    return render(request, 'tenis/tabela.html', context)

def tenista(request):
    texto = "Página da lista de tenistas"
    jogadores = Jogador.objects.all()
    context = {
        'meu_texto': texto,
        'jogadores': jogadores,
    }
    return render(request, 'tenis/tenista.html', context)


# Find your mozilla profile path and put here
# Default: C:\Users\username\AppData\Roaming\Mozilla\Firefox\Profiles
MOZILLA_PROFILE_PATH = 'C:\\Users\\username\\AppData\\Roaming\\Mozilla\\Firefox\\Profile'

# Channel to download videos
CHANNEL = 'https://www.youtube.com/channel/'
# Or
# Add video links, separating them with comma and in quotes
VIDEOS = []

# To add a intro to video, insert the intro path below:
INTRO_PATH = 'D:\\Videos\\intro.mp4'

# For the following variables, use 0 for not copy the video information and 1 for copy
COPY_TITLE = 1
COPY_DESC = 1
COPY_TAGS = 1

# Video amount to download
AMOUNT_VIDEO = 5

# The time between the videos will be post | Time in seconds: 3600 = 1 hour
TIME_BETWEEN_POSTS = 3600

# Time before click on Upload Video | Time in seconds: 300 = 5 minutes
TIME_BEFORE_UPLOAD = 300


# This program accepts two integers and
# outputs whichever number is larger

# The main function
def main():
    #Get user's input information
    first_num = int(input('What is the first number?'))
    sec_num = int(input('What is the second number?'))

    #Get the answer
    answer = max(first_num, sec_num)

    #Determine if answer is equal to one or two
    if answer == 1:

        #Output the greater number
        print(first_num, 'is the greater number')
    else:
        print(sec_num, ' is the greater number')

def max(num1, num2):
    # determine if the first number is greater or not
    if num1>num2:
        return 1
    else:
        return 2

# Call the main function
main()

print('Stephen Oakford')


"""
    tow sum
        [2, 7, 11, 15] , 9 = =>[1, 2]
"""

def tow_sum(numbers, target):
    p1 = 0
    p2 = len(numbers) - 1

    while p1 < p2:
        s = numbers[p1] + numbers[p2]
        if s == target:
            return [p1, p2] # index
            # return [p1 + 1 , p2 + 1] # index + 1
        elif s > target:
            p2 = p2 - 1
        else:
            p1 = p1 + 1

if __name__ == '__main__':
    print(tow_sum([2, 7, 11, 15], 18))


__author__='thiagocastroferreira'

import sys
sys.path.append('../')
import json
import os
import re
import xml.etree.ElementTree as ET

import nlg.ordering as ordering
import nlg.structuring as structuring
import nlg.lexicalization as lexicalization
import nlg.reference as reference

from nlg import contractions

def parse(path):
    tree = ET.parse(path)

    trainset = []
    for entry in tree.getroot():
        print(entry.attrib['date'])
        # reading content in meaning
        meaning = entry.find('meaning')
        intents = []
        for unit in meaning:
            str_unit = unit.text
            intent, attributes = re.findall('(.+?)\((.+?)\)', str_unit)[-1]
            # TO DO: fix quotes on .xml
            # attributes = dict([w.split('=') for w in attributes.split(',')])
            attributes = dict(re.findall('(.+?)=\"(.+?)\",*', attributes))

            delex_attributes = '(' + ','.join([attr[0] + '=' + attr[0].upper() for attr in sorted(attributes.items(), key=lambda x: x[0].lower())]) + ')'
            delex_format = intent + delex_attributes
            # parse intent, attributes and string format
            intents.append({
                'intent': intent,
                'attributes': attributes,
                'str_msg': str_unit,
                'delex_msg': delex_format,
            })
        intents = sorted(intents, key=lambda x: x['str_msg'])

        # reading ordering info
        ordering_xml = entry.find('ordering')
        ordintents, visited = [], []
        for i, unit in enumerate(ordering_xml):
            str_unit = unit.text
            for j, intent in enumerate(intents):
                if intent['str_msg'] == str_unit and j not in visited:
                    # set an order attribute to set the position
                    intents[j]['order'] = i
                    visited.append(j)
                    break

        # structuring
        structuring = entry.find('structuring')
        visited = []
        for pidx, paragraph in enumerate(structuring):
            for sntidx, snt in enumerate(paragraph):
                for unit in snt:
                    str_unit = unit.text
                    for j, intent in enumerate(intents):
                        if intent['str_msg'] == str_unit and j not in visited:
                            intent['paragraph'] = pidx
                            intent['sentence'] = sntidx
                            visited.append(j)
                            break

        # lexicalization
        templates = []
        lexicalization = entry.find('lexicalization')
        for pidx, paragraph in enumerate(lexicalization):
            for sntidx, snt in enumerate(paragraph):
                templates.append({
                    'paragraph': pidx,
                    'sentence': sntidx,
                    'template': contractions.parse(' '.join(snt.text.replace('\n', '').split()))
                })

        # references
        references, entities = [], []
        references_xml = entry.find('references')
        for pidx, paragraph in enumerate(references_xml):
            for sntidx, sentence in enumerate(paragraph):
                for ref in sentence:
                    entity = ref.attrib['entity']

                    status = 'old'
                    if entity not in entities:
                        entities.append(entity)
                        status = 'new'
                    references.append({
                        'entity': ref.attrib['entity'],
                        'gender': ref.attrib['gender'],
                        'number': ref.attrib['number'],
                        'status': status,
                        'refex': ref.text
                    })

        trainset.append({ 'messages': intents, 'templates': templates, 'references': references })
    return trainset

def run(inp_path, out_path):
    # parse xml
    trainset = parse(inp_path)

    # train order
    trainorder = ordering.train(trainset)
    json.dump(trainorder, open(os.path.join(out_path, 'ordering.json'), 'w'), separators=(',', ':'), indent=4)

    # train ordering/structuring
    trainstruct = structuring.train(trainset)
    json.dump(trainstruct, open(os.path.join(out_path, 'structuring.json'), 'w'), separators=(',', ':'), indent=4)

    # train lexicalization
    trainlex = lexicalization.train(trainset)
    json.dump(trainlex, open(os.path.join(out_path, 'lexicalization.json'), 'w'), separators=(',', ':'), indent=4)

    # train references
    trainref = reference.train(trainset)
    json.dump(trainref, open(os.path.join(out_path, 'references.json'), 'w'), separators=(',', ':'), indent=4)

if __name__ == '__main__':
    inp_path = '../inpe_deter/data/month_corpus.xml'
    out_path = '../inpe_deter/data/month_grammar'

    if not os.path.exists(out_path):
        os.mkdir(out_path)

    run(inp_path=inp_path, out_path=out_path)


#!/opt/bin/lv_micropython
import time
import lvgl as lv
import init_gui

def close_win_cb():
    nonlocal win
    if win:
        win.delete()
        win = None

# create a window
win = lv.win(lv.scr_act(),None)
win.set_title("Window title")                   # Set the title

win_style = lv.style_t()
win_style.init()
win_style.set_margin_right(lv.STATE.DEFAULT, 50)
win.add_style(lv.win.PART.CONTENT_SCROLLABLE,win_style)

# Add control button to the header
close_btn = win.add_btn_right(lv.SYMBOL.CLOSE)  # Add close button and use built-in close action
close_btn.set_event_cb(lambda obj,e:  e == lv.EVENT.RELEASED and close_win_cb())

win.add_btn_right(lv.SYMBOL.SETTINGS)           # Add a setup button

# Add some dummy content
txt = lv.label(win)
txt.set_text(
"""This is the content of the window

You can add control buttons to
the window header

The content area becomes automatically
scrollable is it's large enough.

You can scroll the content
See the scroll bar on the right!"""
)

while True:
    lv.task_handler()
    time.sleep_ms(5)


# This file is a script that will help create the dataset required to train the haar cascades.
import copy

import cv2
import os
from .image_processor import ImageProcessor
from ...utils import crop_and_zoom

SAMPLE_TYPE = 'negative'  # 'positive' or 'negative'
IMAGE_PIXELS = 50
DATA_PATH = os.path.join(os.getcwd(), 'data', SAMPLE_TYPE)
SAMPLE_KEY = '75_additional'  # Height at which the images are captured: 60, 75, 99, 105

def setup_capture():
    cv2.namedWindow('collect', cv2.WINDOW_GUI_NORMAL)
    cv2.resizeWindow('collect', 1080, 720)
    cap = cv2.VideoCapture(2)
    cap.set(3, 1920)
    cap.set(4, 1080)
    return cap

def draw_grid(image):
    """
    Helper. Draws grid the same size as the output image.
    Can be used as a reference for the user to know how the image is framed.
    :return: Image with grid
    """
    height, width, _ = image.shape  # h w channels
    for i in range(1, int(height/IMAGE_PIXELS) + 1):
        # Horizontal lines, (start_x, start,y), (end_x, end_y), Blue
        cv2.line(image, (0, i * IMAGE_PIXELS), (width, i * IMAGE_PIXELS), (255, 0, 0), 1, 1)
    for j in range(1, int(width/IMAGE_PIXELS) + 1):
        # Vertical lines
        cv2.line(image, (j * IMAGE_PIXELS, 0), (j * IMAGE_PIXELS, height), (255, 0, 0), 1, 1)
    return image

def main():
    cap = setup_capture()
    image_processor = ImageProcessor(IMAGE_PIXELS, DATA_PATH, SAMPLE_TYPE, SAMPLE_KEY)
    while True:
        _, image = cap.read()
        image = crop_and_zoom(image, 2.5, 2.5)
        original_image = image
        grid_image = copy.deepcopy(image)
        cv2.imshow("collect", draw_grid(grid_image))

        image_processor.set_image(original_image)
        cv2.setMouseCallback('collect', image_processor.click_event)

        if cv2.waitKey(1) == 27:
            # ESC to quit
            break

    cv2.destroyAllWindows()


from lxml import html
import requests, sqlite3, re

def Process(url):
	id = int(re.findall('/([0-9]+)/.*?$', url)[0])
	if (id in id_fetched):
		print('Skiping ', id)
		return
	page = requests.get(url + '/userrecs')
	tree = html.fromstring(page.content)
	try:
		name = tree.xpath('//span[@itemprop="name"]/text()')[0]
	except:
		return
	print(id, name)
	try:
		img_url = tree.xpath('//img[@itemprop="image"]/@src')[0]
		img = sqlite3.Binary(requests.get(img_url, stream=True).content)
	except:
		img = None
	year = re.findall('Aired:\n.*([0-9][0-9][0-9][0-9]).*\n', page.text)
	try:
		year = int(year[0])
	except:
		year = 0
	genres = ''
	tmp = re.findall('Genres:\n(.*)
', page.text)[0]
	for item in re.findall('>(.*?)<', tmp):
		genres += item
	restrict = re.findall('Rating:\n(.*?)\n', page.text)[0].replace('amp;', '').strip()
	cur.execute('INSERT INTO ani_lst VALUES (?, ?, ?, ?, ?, ?)', (id, name, img, year, genres, restrict))
	for recc in re.findall('<a href="/anime/([0-9]+)/.*?" class="hoverinfo_trigger"', page.text):
		cur.execute('INSERT INTO userrecs VALUES (?, ?)', (id, recc))
	conn.commit()
	id_fetched.append(id)

conn = sqlite3.connect('MAL.db')
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS ani_lst (id INTEGER UNIQUE, name TEXT UNIQUE, img BLOB, year INTEGER, genres TEXT, restrict TEXT)')
cur.execute('CREATE TABLE IF NOT EXISTS userrecs (from_id INTEGER, to_id INTEGER)')
cur.execute('SELECT id FROM ani_lst')
id_fetched = []
for item in cur.fetchall():
	id_fetched.append(item[0])
threshold = 8000
p = len(id_fetched)
while (p < threshold):
	page = requests.get('https://myanimelist.net/topanime.php?limit={}'.format(p))
	print('Processing ', p, '/', threshold)
	tree = html.fromstring(page.content)
	for i in tree.xpath('//a[@class="hoverinfo_trigger fl-l fs14 fw-b"]/@href'):
		Process(i)
	p += 50
cur.close()
conn.close()


import options_creator
import staff
import misc_helpers
import staff_helpers
import chords
from fractions import Fraction
import os
import sys
import subprocess
import cv2

def print_progress(info, long=False):
    """
    This keeps the output on the same line.
    """
    text = "\r"
    for s, value in info:
        if long:
            text += s + ": {:40s}   ".format(str(value))
        else:
            text += s + ": {:10s}   ".format(str(value))
    sys.stdout.write(text)
    sys.stdout.flush()

def resize_images(output_folder, new_width, new_height):
    file_index = 0
    print("Resize images.")
    filenames = [output_folder + "presentation_mode_start.png"]

    while True:
        filename = output_folder + "%05i.png" % file_index
        if os.path.isfile(filename):
            filenames.append(filename)
            file_index += 1
        else:
            break

    for filename in filenames:
        print_progress([("file", filename.split("/")[-1])], long=True)
        img = cv2.imread(filename)
        height = img.shape[0]
        width = img.shape[1]
        if float(width) / float(height) > float(new_width)/new_height:
            scale = float(new_width) / width
            new_size = (int(round(scale * width)), int(round(scale * height)))
            img = cv2.resize(img, new_size)
        else:
            scale = float(new_height) / height
            new_size = (int(round(scale * width)), int(round(scale * height)))
            img = cv2.resize(img, new_size)
        cv2.imwrite(filename, img)

    print("") # new line

def clean_output_folder(output_folder, del_png=False, del_lily=False, del_txt=False):
    endings = ["count", "tex", "texi", "eps"]
    if del_png:
        endings.append("png")
    if del_lily:
        endings.append("ly")

    for ending in endings:
        os.system("rm " + output_folder + "*." + ending + " 2>/dev/null")

    if del_txt:
        os.system("rm " + output_folder + "*.txt 2>/dev/null")

    if del_png:
        os.system("rm " + output_folder + "cropped/*.png 2>/dev/null")

def create_lily_output(step, staff_strings, chord_symbols, output_folder, image_resolution, filename=None):
    if not filename:
        filename = "%05i" % step
    complete_lilypond_string = ""
    lily_front_filename = "lily_front.ly"

    with open(lily_front_filename) as infile:
        complete_lilypond_string += infile.read()

    if len(chord_symbols) > 0:
        complete_lilypond_string += "\\chords {"
        for s in [c.full_string for c in chord_symbols]:
            complete_lilypond_string += s + " "
        complete_lilypond_string += " }\n"

    for s in staff_strings:
        complete_lilypond_string += "\\new Staff {"
        complete_lilypond_string += s
        complete_lilypond_string += " }\n"

    with open("lily_back.ly") as infile:
        complete_lilypond_string += infile.read()

    with open(output_folder + filename + ".ly", "w") as outfile:
        outfile.write(complete_lilypond_string)

    with open(os.devnull, 'wb') as quiet_output:
        outfilename = output_folder + filename
        subprocess.call(["lilypond", "-dbackend=eps", "-dresolution=%i" % image_resolution,
                "--png", "-o", outfilename, output_folder + filename + ".ly"], stdout=quiet_output, stderr=quiet_output)
        if not os.path.isfile(outfilename + ".png"):
            print("ERROR: no PNG written!!!!!!!!!!!!!")

    clean_output_folder(output_folder, del_lily=False)

def resize_image_to_height(img, new_height):
    """
    This preserves the aspect ratio.
    """
    new_width = round(new_height * img.shape[1] / float(img.shape[0]))
    img_resized = cv2.resize(img, (int(new_width), new_height))
    return img_resized

def create_timing_info_output(time, output_folder):
    with open(output_folder + "timing.txt", "a") as outfile:
        outfile.write(str(float(time)) + "\n")

def create_midi_notes_output(mingus_notes, output_folder):
    with open(output_folder + "midi_notes.txt", "a") as outfile:
        midi_notes = sorted([str(int(n)) for n in mingus_notes])
        # remove duplicates
        midi_notes = sorted(list(set(midi_notes)))
        outfile.write(" ".join(midi_notes) + "\n")
    with open(output_folder + "mingus_notes.txt", "a") as outfile:
        mingus_notes = sorted([str(n).replace("'", "") for n in mingus_notes])
        outfile.write(" ".join(mingus_notes) + "\n")

def modify_staff_string_with_color(staff_string, staff_index, stream, index, elem, action_notes, chord_root, calculated_belongs_to_chord_without_end, color_mode):
    is_chord_note = calculated_belongs_to_chord_without_end[index] or ">" in elem
    is_first_chord_note = "<" in elem
    if is_chord_note:
        if is_first_chord_note:
            modify = True
        else:
            modify = False
    else:
        modify = True

    if modify:
        color_string = staff_helpers.create_color_string(action_notes, chord_root, staff_index, color_mode)
        staff_string += " " + color_string

    return staff_string

def get_chord_root(chord_symbols, elem_time):
    chord_root = None
    for c in chord_symbols:
        if elem_time >= c.time:
            chord_root = c.root
    return chord_root

def get_initial_clef(bar_start, clef_changes):
    clef_changes = [(Fraction(-999999999999,1), "treble")] + clef_changes
    for index, k in enumerate(clef_changes):
        if clef_changes[index][0] <= bar_start:
            if index == len(clef_changes) - 1:
                return k
            else:
                if clef_changes[index + 1][0] > bar_start:
                    return k
    print("initial clef ERROR: You should never see this.")

def get_initial_time_signature(bar_start, time_signature_changes):
    for index, k in enumerate(time_signature_changes):
        if time_signature_changes[index][0] <= bar_start:
            if index == len(time_signature_changes) - 1:
                return k
            else:
                if time_signature_changes[index + 1][0] > bar_start:
                    return k
    print("initial time_signature_changes ERROR: You should never see this.")

def get_initial_key(bar_start, key_changes):
    for index, k in enumerate(key_changes):
        if key_changes[index][0] <= bar_start:
            # print(index, k)
            if index == len(key_changes) - 1:
                return k
            else:
                if key_changes[index + 1][0] > bar_start:
                    return k
    print("initial key changes ERROR: You should never see this.")

def create_staff_string(bar_start, bar_end, time, action_notes, chord_symbols, staff, staff_index, active, key_changes, time_signature_changes, color_mode):
    initial_key = get_initial_key(bar_start, key_changes)
    initial_clef = get_initial_clef(bar_start, staff.clef_changes)
    initial_time_signature = get_initial_time_signature(bar_start, time_signature_changes)
    staff_string = ""
    staff_string += " \\key " + initial_key[1]
    staff_string += " \\clef " + initial_clef[1]
    staff_string += " \\time " + initial_time_signature[1]
    stream = staff.total_stream
    for index, elem in enumerate(stream):
        if type(elem) != list:
            elem_time = staff.calculated_start_times[index]
            if elem_time >= bar_start and elem_time < bar_end:
                if staff.res_is_note[index] and time == elem_time and not staff.grace_note_stream[index]:
                    chord_root = get_chord_root(chord_symbols, elem_time)
                    staff_string = modify_staff_string_with_color(staff_string, staff_index, stream, index, elem, action_notes, chord_root, staff.calculated_belongs_to_chord_without_end, color_mode)
                staff_string += " " + elem

        else:
            sub_staff_strings = []
            for sub_index, sub_stream in enumerate(elem):
                sub_staff_string = ""
                for sub_elem_index, sub_elem in enumerate(sub_stream):
                    elem_time = staff.calculated_start_times[index][sub_index][sub_elem_index]
                    if elem_time >= bar_start and elem_time < bar_end:
                        if staff.res_is_note[index][sub_index][sub_elem_index] and time == elem_time and not staff.grace_note_stream[index][sub_index][sub_elem_index]:
                            sub_stream = stream[index][sub_index]
                            sub_calculated_belongs_to_chord_without_end = staff.calculated_belongs_to_chord_without_end[index][sub_index]
                            chord_root = get_chord_root(chord_symbols, elem_time)
                            sub_staff_string = modify_staff_string_with_color(sub_staff_string, staff_index, sub_stream, sub_elem_index, sub_elem, action_notes, chord_root, sub_calculated_belongs_to_chord_without_end, color_mode)
                        sub_staff_string += " " + sub_elem
                if sub_staff_string != "":
                    sub_staff_strings.append(sub_staff_string)

            if len(sub_staff_strings) > 0:
                staff_string += " <<"
                for s_ind, s in enumerate(sub_staff_strings):
                    # first add brackets for the case that voices are longer than one measure, i.e.
                    # voices may be unfinished
                    if s[0:2] != " {":
                        s = " { " + s
                    if s.count("{") > s.count("}"):
                        s += " }"
                    staff_string += s
                    if s_ind < len(sub_staff_strings) - 1:
                        staff_string += " \\\\"
                staff_string += " >>"
    return staff_string

def get_bar_no_from_time(time, bar_starts):
    for index, bar in enumerate(bar_starts[:-1]):
        if time >= bar and time < bar_starts[index + 1]:
            return index
    return len(bar_starts) - 1

def get_actions_from_staff(s):
    actions = []
    times = []
    ns = s.note_stream_without_holds
    for elem in ns:
        if type(elem) != list:
            if elem.start_time in times:
                add_index = times.index(elem.start_time)
                actions[add_index] += elem.notes
            else:
                if len(elem.notes) > 0:
                    actions.append(elem.notes)
                    times.append(elem.start_time)
        else:
            for sub_stream in elem:
                for sub_elem in sub_stream:
                    if sub_elem.start_time in times:
                        add_index = times.index(sub_elem.start_time)
                        actions[add_index] += sub_elem.notes
                    else:
                        if len(sub_elem.notes) > 0:
                            actions.append(sub_elem.notes)
                            times.append(sub_elem.start_time)
    ret = zip(times, actions)
    ret = sorted(ret, key = lambda x : x[0])
    return ret

def get_actions(staffs, staff_activations):
    staff_actions = []
    for staff_index, s in enumerate(staffs):
        if staff_activations[staff_index]:
            actions = get_actions_from_staff(s)
        else:
            actions = []
        staff_actions.append(actions)
    all_times = []
    all_staff_actions = []
    for actions in staff_actions:
        for time, _ in actions:
            if not time in all_times:
                all_times.append(time)
                all_staff_actions.append( [time, [ [] for i in range(len(staffs))] ] )
    for actions_index, actions in enumerate(staff_actions):
        for time, a in actions:
            add_index = all_times.index(time)
            all_staff_actions[add_index][1][actions_index] = a
    all_staff_actions = sorted(all_staff_actions, key = lambda x : x[0])
    return all_staff_actions

def main():
    options = options_creator.get_options()
    misc_helpers.delete_and_create_folder(options["output_folder_complete"])
    staffs = staff.get_staffs(options["lily_file"])
    misc_helpers.write_debug_file(staffs, options["output_folder_complete"])
    all_chord_symbols = chords.get_chords(options["lily_file"])

    index_containing_meta = 0 # index of the staff containing changes of measures and keys
    ref_staff = staffs[index_containing_meta]

    actions = get_actions(staffs, options["staff_activations"])

    note_positions = []
    print("Create pngs in " + options["output_folder_complete"])
    for step, action in enumerate(actions[0:]):
        time = action[0]
        action_notes = action[1]
        bar_no = get_bar_no_from_time(time, ref_staff.bar_starts)
        bar_start = ref_staff.bar_starts[bar_no]
        bar_end = ref_staff.bar_starts[bar_no + 1] if bar_no < len(ref_staff.bar_starts) - 1 else Fraction(99999999,1)

        key_changes = []
        for st in staffs:
            for c in st.key_changes:
                if not c in key_changes:
                    key_changes.append(c)
        key_changes.append( (Fraction(-999999999999,1), "c \\major") )
        key_changes = sorted(key_changes, key = lambda x : x[0])

        time_signature_changes = []
        for st in staffs:
            for c in st.time_signature_changes_strings:
                if not c in time_signature_changes:
                    time_signature_changes.append(c)
        time_signature_changes.append( (Fraction(-999999999999,1), "4/4") )
        time_signature_changes = sorted(time_signature_changes, key = lambda x : x[0])

        print_progress([("file", str(step)), ("bar", str(bar_no)), ("time", str(float(time)))])
        staff_strings = []
        mingus_notes = []
        chord_symbols = [c for c in all_chord_symbols if (c.time >= bar_start and c.time < bar_end) ]
        color_mode = "chord_root"
        for st_index, st in enumerate(staffs):
            current_notes = action_notes[st_index]
            staff_string = create_staff_string(bar_start, bar_end, time, current_notes, chord_symbols, st, st_index, options["staff_activations"][st_index], key_changes, time_signature_changes, color_mode)

            show_staffs = [True, True]
            if show_staffs[st_index]:
                staff_strings.append(staff_string)
                mingus_notes += staff_helpers.get_mingus_notes(current_notes)

        create_midi_notes_output(mingus_notes, options["output_folder_complete"])
        create_lily_output(step, staff_strings, chord_symbols, options["output_folder_complete"], options["image_resolution"])
        create_timing_info_output(time, options["output_folder_complete"])

        # make first image for presentation mode (only black notes)
        if step == 0:
            staff_strings = []
            for st_index, st in enumerate(staffs):
                color_mode = "all_black"
                staff_string = create_staff_string(bar_start, bar_end, time,
                            current_notes, chord_symbols, st, st_index,
                            options["staff_activations"][st_index], key_changes,
                            time_signature_changes, color_mode)
                show_staffs = [True, True]
                if show_staffs[st_index]:
                    staff_strings.append(staff_string)
            create_lily_output(0, staff_strings, chord_symbols, options["output_folder_complete"], options["image_resolution"], filename="presentation_mode_start")

    print("") # new line
    resize_images(options["output_folder_complete"], options["image_width"], options["image_height"])

if __name__ == '__main__':
    main()


import os

from flask import request, g
from flask_restx import abort
from decorator import decorator
import jwt

import user.models as models
import user.exceptions as exceptions

type_maps = {
    "string": str,
    "integer": int,
    "boolean": bool,
}

def validate_params(params):
    """
    A decorator which checks and stops execution if the params are invalid
    """

    def validate(function, *args, **kwargs):
        json_obj = {}
        if request.method == "HEAD" or request.method == "OPTIONS":
            return function(*args, **kwargs)
        elif request.args:
            json_obj.update(request.args)
        elif request.json:
            json_obj.update(request.json)
        elif request.content_type and "multipart/form-data" in request.content_type:
            if getattr(request, "files"):
                json_obj.update(request.files)
            if getattr(request, "data"):
                json_obj.update(request.data.to_dict())
        elif request.method == "DELETE":
            json_obj = json_obj
        kwargs["params"] = json_obj
        response = check_missing_params(params, json_obj)
        if not response == {}:
            return abort(400, error=response, success=False)
        response = check_incorrect_types(params, json_obj)
        if not response == {}:
            return abort(400, error=response, success=False)
        return function(*args, **kwargs)

    return decorator(validate)

def check_missing_params(params, filtered_params):
    response = {}
    missing = [
        r for r in params.keys() if params[r].required and r not in filtered_params
    ]
    if missing:
        response = {
            "message": "payload missing required params",
            "missing": ",".join(missing),
        }
    return response

def check_incorrect_types(params, filtered_params):
    response = {}
    wrong_types = [
        r
        for r in params.keys()
        if params[r].required
        and not isinstance(filtered_params[r], type_maps.get(params[r].__schema_type__))
    ]
    if wrong_types:
        response = {
            "message": "payload type error",
            "param_types": {
            k: str(params[k].__schema_type__) for k in params.keys()
            },
        }
    return response

@decorator
def decode_auth_token(f, *args, **kwargs):
    """
    Decorator for views that require a certain permission of the logged in
    user.
    """
    if "AUTHORIZATION" in request.headers or "auth_token" in request.view_args:
        auth_token = request.headers.get('AUTHORIZATION') or request.view_args.get('auth_token')
        if auth_token:
            try:
                payload = jwt.decode(auth_token, os.getenv("SECRET_KEY"))
            except exceptions.AuthError(message="Signature expired, login again"):
                return response_dict(status=400, message="Signature expired, login again")
            email = payload["sub"]
            user_obj = models.User.fetch_user({"email": email})
            if not user_obj:
                raise exceptions.UserUnauthorizedError(message="Authentication failed")
            kwargs["id"] = user_obj.id
            kwargs["email"] = email
            g.user_id = user_obj.id
        return f(*args, **kwargs)
    raise NoAuthTokenPresentError


"""
Minimal code that illustrates the active storage principle in API.
"""
import os
from S3netCDF4._s3netCDF4 import s3Dataset as Dataset

# file specifier
root = "/home/valeriu/climate_data/cmip5/output1"
ncfile = "NSF-DOE-NCAR/CESM1-CAM5/historical/mon/atmos/Amon/r1i1p1/v20130313/tas_Amon_CESM1-CAM5_historical_r1i1p1_185001-200512.nc"
filepath = os.path.join(root, ncfile)

def load_storage_data(filepath, var, slices):
    """Load specified data using S3 dataset."""
    if slices == ":":
        return Dataset(filepath, "r").variables[var][:]
    elif isinstance(slices, list):
        s1, s2 = slices
        return Dataset(filepath, "r").variables[var][s1:s2]
    else:
        return ValueError('Slices must be either ":" or a two member list.')

def active_storage_operation(filepath, var, operation, slices):
    """
    Simulate computations INSIDE active storage.

    This is a toy and doesn't necessarily refelect
    what's the hap there, inside the Black Box.
    """
    data = load_storage_data(filepath, var, slices)
    if operation == "max":
        op_result = data.max()
    if operation == "min":
        op_result = data.min()  # and so on ...

    return op_result

def load(filepath, var, slices, active=False, operation=None):
    """
    Get a max with or without active storage participation.

    Parameters
    ----------
    file path: str, path to ``var`` data file on Active Storage
    var: str, variable that user needs its data
    active: bool, use or not the Active Storage for computations
    operation: str, string of linear operation
    """

    if not active:
        if operation is not None:
            return getattr(load_storage_data(filepath, var, slices), operation)()
        else:
            return load_storage_data(filepath, var, slices)
    else:
        if operation is not None:
            return getattr(active_storage_operation(filepath,
                                                    var,
                                                    operation,
                                                    slices),
                           operation)()
        else:
            return NotImplementedError("To use Active Storage, "
                                       "supply an operation first!")

# run examples
simple_load = load(filepath, "tas", slices=":")
inactive_max = load(filepath, "tas", slices=":", operation="max")
active_max = load(filepath, "tas", slices="[1990, 2014]",
                  active=True, operation="max")


import abc
from functools import wraps

import ast
import inspect
from copy import deepcopy
from textwrap import dedent
from typing import Callable
from core import astunparse

class ClassMethodTransformer(ast.NodeTransformer):
    """Convert class method call to the binded class method call."""

    def __init__(self, decoration='bind') -> None:
        self.decoration = decoration

    def visit_Call(self, node: ast.Call) -> ast.Call:
        """Apply transformer to visited node.

        This transformer converts class method call to the binded one;
        that is, `self.bind()` binds each class method call.

        Parameters:
            node: visited node to transform

        Return:
            node_trans: transformed node
        """
        assert node.func.value.id == "self", "Only calling of class method are permitted"
        node_trans = ast.copy_location(
            ast.Call(
                func=ast.Call(
                    func=ast.Attribute(
                        value=ast.Name(id="self", ctx=ast.Load()),
                        attr=self.decoration,
                        ctx=ast.Load(),
                    ),
                    args=[
                        ast.Attribute(
                            value=ast.Name(id="self", ctx=ast.Load()),
                            attr=node.func.attr,
                            ctx=ast.Load(),
                        )
                    ],
                    keywords=[],
                ),
                args=node.args,
                keywords=node.keywords,
            ),
            node,
        )
        return node_trans

class Monad:

    @property
    def binded_run(self):
        """
        The binded `run` method:

        Originally:
        def run(self, a, b, c):
            a = self.func_1(b, c)
            d = self.func_2(a)
            return a, d

        Becomes:
        def binded_run(self, a, b, c):
            a = self.bind(self.func_1)(b, c)
            d = self.bind(self.func_2)(a)
            return a, d
        """
        self.__parse_main_func(
            self.run,
            decoration='bind',
            target_func_name='binded_run_real')
        return self.binded_run_real

    @property
    def decorated_run(self):
        """
        The decorated `run` method:

        Originally:
        def run(self, a, b, c):
            a = self.func_1(b, c)
            d = self.func_2(a)
            return a, d

        Becomes:
        def decorated_run(self, a, b, c):
            a = self.decorator(self.func_1)(b, c)
            d = self.decorator(self.func_2)(a)
            return a, d
        """
        self.__parse_main_func(
            self.run,
            decoration='decorator',
            target_func_name='decorated_run_real')
        return self.decorated_run_real

    @abc.abstractmethod
    def run(self, *args):
        """
        The main function to be altered by monad

        Originally:
        def run(self, a, b, c):
            a = self.func_1(b, c)
            d = self.func_2(a)
            return a, d

        Becomes:
        1)
        def binded_run(self, a, b, c):
            a = self.bind(self.func_1)(b, c)
            d = self.bind(self.func_2)(a)
            return a, d
        2)
        def decorated_run(self, a, b, c):
            a = self.decorator(self.func_1)(b, c)
            d = self.decorator(self.func_2)(a)
            return a, d
        """
        raise NotImplementedError()

    @property
    @abc.abstractmethod
    def return_cls(self):
        """
        The Return object used in monad
        NOTE: a content property must be included in the return object
        """
        class ReturnObj:
            def __init__(self, content):
                self.content = content
        return ReturnObj

    @abc.abstractmethod
    def decorator(self, orig_func):
        """The decorator that bind into the function"""
        return orig_func

    def bind(self, orig_func):
        '''decorator to be bind to the `run` function, designed in monad pattern'''
        @wraps(orig_func)
        def wrapper_of_bind(*args, **kwargs):
            """
            function warped by bind
            """
            # extract content from the return object
            args = [a.content for a in args]
            kargs = dict([(key, value.content)
                         for key, value in kwargs.items()])
            # adopt the original function to content
            result = self.decorator(orig_func)(*args, **kargs)
            # encapsulate content into the return object
            if isinstance(result, list):
                return [self.return_cls(x) for x in result]
            elif isinstance(result, tuple):
                return tuple([self.return_cls(x) for x in result])
            else:
                return self.return_cls(result)
        return wrapper_of_bind

    def __parse_main_func(self, func: Callable, decoration: str,
                          target_func_name: str) -> None:
        """Parse `run` and construct the corresponding target
        function `target_func_name` as new class method.

        Parameters:
            func: function to parse,
            decoration: func name of `decorator`
            target_func_name: func name of `run` after alternation
        """
        # Retrieve `main_func` function node
        lines = inspect.getsourcelines(func)[0]
        main_func_str = dedent("".join(lines))
        main_func_node = ast.parse(main_func_str).body[0]

        # Construct `target_func_name` function node
        target_main_func_node = self.__gen_target_main_func_node(
            main_func_node, decoration, target_func_name)

        # Bind `target_func_name` as class method
        target_main_func_str = astunparse.unparse(target_main_func_node)
        exec(target_main_func_str, globals())
        exec(f'Monad.{target_func_name} = {target_func_name}')

    def __gen_target_main_func_node(
        self, main_func_node: ast.FunctionDef, decoration: str, target_func_name: str
    ) -> ast.FunctionDef:
        """Return `TARGET_MAIN_FUNC` node corresponding to `run`.

        Parameters:
            main_func_node: `run` function node
            decoration: func name of `decorator`
            target_func_name: func name of `run` after alternation

        Return:
            target_main_func_node: `target_func_name` function node
        """
        cls_method_traformer = ClassMethodTransformer(decoration=decoration)
        target_main_func_node = deepcopy(main_func_node)
        target_main_func_node.name = target_func_name
        target_main_func_node = cls_method_traformer.visit(
            target_main_func_node)

        # Remove function annotation from target_main_func
        for i, arg in enumerate(target_main_func_node.args.args):
            target_main_func_node.args.args[i].annotation = None
        target_main_func_node.returns = None

        return target_main_func_node


from seq0 import *

print("-----| Exercise 5 |------")

FOLDER = "../Session-04/"
bases = ["A", "C", "T", "G"]
files_list = ["U5", "ADA", "FRAT1", "FXN", "RNU6_269P"]

for file in files_list:
    sequence = seq_read_fasta(FOLDER + file + ".txt")
    print("Gene " + file, seq_count(sequence))

# Implement the seq_count(seq) function, that calculates the number of times all the bases appears on the sequence.
# It returns a dictionary with all the information. The keys of the dictionary are the bases: 'A', 'T', 'C' and 'G'


ls = None
with open("Day9-input.txt") as f:
    ls = list(map(lambda l:l.strip("\n"), f.readlines()))

def I(list_):
    for i in range(len(list_)):
        list_[i] = int(list_[i])
    return list_

hPos = (0,0)
tPos = (0,0)

def mvHead(d):
    global hPos
    if d=="R":
        hPos = (hPos[0]+1, hPos[1])
    elif d=="U":
        hPos = (hPos[0], hPos[1]+1)
    elif d=="L":
        hPos = (hPos[0]-1, hPos[1])
    elif d=="D":
        hPos = (hPos[0], hPos[1]-1)

def mvTail(hPos, tPos):
    if hPos[0] == tPos[0] and abs(tPos[1] - hPos[1]) == 2:
        tPos = (tPos[0], tPos[1] + (hPos[1] - tPos[1])/2)
    elif hPos[1] == tPos[1] and abs(tPos[0] - hPos[0]) == 2:
        tPos = (tPos[0] + (hPos[0] - tPos[0])/2, tPos[1])
    elif abs(tPos[1] - hPos[1]) == 2 or abs(tPos[0] - hPos[0]) == 2:
        tPos = (tPos[0] + abs(tPos[0] - hPos[0])/(hPos[0] - tPos[0]), tPos[1] + abs(tPos[1] - hPos[1])/(hPos[1] - tPos[1]))
    tPos = (int(tPos[0]), int(tPos[1]))
    return tPos

vis = {(0,0)}
for i in range(len(ls)):
    d,n = ls[i].split()
    n = int(n)
    for i in range(n):
        mvHead(d)
        tPos = mvTail(hPos, tPos)
        vis.add(tPos)

print("Star 1:", len(vis))

hPos = (0,0)
tPos = [(0,0)]*9
vis = {(0,0)}
for i in range(len(ls)):
    d,n = ls[i].split()
    n = int(n)
    for j in range(n):
        mvHead(d)
        tPos[0] = mvTail(hPos, tPos[0])
        for k in range(1, len(tPos)):
            tPos[k] = mvTail(tPos[k-1], tPos[k])
        vis.add(tPos[8])

print("star 2:", len(vis))


from defines import getCreds, makeApiCall
import datetime

def debugAcessToken( params ):
    endpointParams = dict()
    endpointParams['input_token'] = params['access_token']
    endpointParams['access_token'] = params['access_token']

    url = params['graph_domain'] + 'debug_token'

    return makeApiCall( url, endpointParams, params['debug'] )

params = getCreds()
params['debug'] = 'yes'
response = debugAcessToken( params )

validade = datetime.datetime.fromtimestamp( response['json_data']['data']['expires_at'])
print(f"\nToken expira em: {validade}")


from os import strerror

# Inicializa 26 contadores para cada letra latina.
# Nota: hemos usado una comprensión para esto.
counters = {chr(ch): 0 for ch in range(ord('a'), ord('z') + 1)} #Se crea un diccionario de llaves den letras y valores como numeros
counters.update({str(num): 0 for num in range(10)})
counters['caracter especial'] = 0
file_name = input("Ingresa el nombre del archivo a analizar: ") #Se pide que ingrese el nombre del archivo
try: #Se inicia try para prevenir posibles errores
    file = open(file_name, "rt") #Se intenta abrir el archivo en modo lectura
    for line in file: #Se recorre cada linea
        for char in line: #Se recorren los caracteres de la linea
            # Si es una letra...
            if char.isalpha(): #Se verifica si es letra
                # ... lo trataremos en minúsculas y actualizaremos el contador apropiado.
                counters[char.lower()] += 1 #Si es letra se pasa a minuscula y se suma 1 al contador.
            elif char.isdigit():
                counters[char] += 1
            else:
                counters['caracter especial'] += 1

    file.close() #Se cierra el archivo
    # Demos salida a los contadores.
    for char in counters.keys(): #Se recorren las llaves del diccionario
        c = counters[char] #Se obtiene el numero del contador para la letra actual
        if c > 0: #Si el contador es mayor a 0
            print(char, '->', c) #Se imprime la letra y el numero del contador
except IOError as e: #Al error IOError se le apoda e
    print("Se produjo un error de E/S: ", strerror(e.errno)) #Si ocurre un error se muestra el mesaje


import unittest

def number_format(num):
    '''
    python3 return format(2131234243.42314123,',')
    '''
    if num < 0:
        return '-' + number_format(-num)
    num = str(num).split('.')
    result = ''
    for index in range(len(num[0])):
        if (len(num[0]) - index) % 3 == 0 and index != 0:
            result += ','
        result += num[0][index]
    num[0] = result
    return '.'.join(num)

class TestBackendTopic(unittest.TestCase):

    def test_topic1(self):
        '''
        Please implement a string function in a numeric format in a language that you are good at.
        And mark every three digits with a comma. Please attach unit test.
        e.g.
            f(9527) => "9,527", f(3345678) => "3,345,678", f(-1234.45) => "-1,234.45"
        '''

        self.assertEqual(number_format(9527), '9,527')
        self.assertEqual(number_format(3345678), '3,345,678')
        self.assertEqual(number_format(-1234.45), '-1,234.45')

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


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar  5 23:20:03 2021

@author: ozkan
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

fandango = pd.read_csv("fandango_scrape.csv")

x = fandango['VOTES']
y = fandango['RATING']

#plt.scatter(y,x)
#plt.ylabel('VOTES')
#plt.xlabel('RATING')

corre = fandango.corr()

fandango['YEAR'] = fandango['FILM'].apply(lambda title: title.split('(')[-1])
fandango['YEAR'] = fandango['YEAR'].apply(lambda x: x.replace(')',''))
count_per_year = fandango['YEAR'].value_counts()

#plt.hist(fandango['YEAR'])
#plt.xlabel('YEAR')
#plt.ylabel('count')
#plt.show()

highest_10_ratings = fandango.sort_values('VOTES',ascending=False)[:10]

zero_votes_sum = fandango.value_counts([fandango['VOTES']==0])

fan_reviewed = fandango.drop(fandango[fandango.VOTES==0].index)

#plt.figure(figsize=(10,4),dpi=150)
#sns.kdeplot(data=fan_reviewed,x='RATING',clip=[0,5],fill=True,label='True Rating')
#sns.kdeplot(data=fan_reviewed,x='STARS',clip=[0,5],fill=True,label='Stars Displayed')

#plt.legend(loc=(1.05,0.5))

fan_reviewed['STARS_DIFF'] = (fan_reviewed['STARS']-fan_reviewed['RATING']).round(2)

#sns.countplot(data=fan_reviewed,x='STARS_DIFF',palette='magma')

one_star_different = fan_reviewed[fan_reviewed['STARS_DIFF']==1]

all_sites = pd.read_csv('all_sites_scores.csv')
all_sites.info()
all_sites.describe()

#sns.scatterplot(data=all_sites,x='RottenTomatoes',y='RottenTomatoes_User')
#plt.xlim(0,100)
#plt.ylim(0,100)
all_sites['DIFF'] = all_sites['RottenTomatoes']-all_sites['RottenTomatoes_User']

mean_diff = all_sites['DIFF'].mad()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 16 14:32:50 2023

@author: johnmorgan
"""

# Review

import stack as s

def insertAtBottom(stack, item):
    if s.isEmpty(stack):
        s.push(stack, item)

    else:
        temp = s.pop(stack)
        insertAtBottom(stack, item)
        s.push(stack, temp)

def reverse(testVariable):
    if not s.isEmpty(testVariable):
        temp = s.pop(testVariable)
        reverse(testVariable)
        insertAtBottom(testVariable, temp)

stack = s.createStack()
s.push(stack, 2)
s.push(stack, 3)
s.push(stack, 5)
s.push(stack, 8)
print(stack)
reverse(stack)
print(stack)