import inspect
import os
import sys
import traceback

if __name__ == "__main__":
    currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
    parentdir = os.path.dirname(currentdir)
    parentdir2 = os.path.dirname(parentdir)
    sys.path.insert(0, parentdir)
    sys.path.insert(0, parentdir2)
    import time

    from pm4py.objects.log.importer.xes import importer as xes_importer
    from pm4py.algo.discovery.inductive import algorithm as inductive
    from pm4py.algo.conformance.alignments.petri_net.variants import state_equation_a_star
    from pm4py.algo.discovery.footprints import algorithm as footprints_discovery
    from pm4py.algo.conformance.footprints import algorithm as footprints_conformance
    from pm4py.algo.discovery.alpha import algorithm as alpha
    from pm4py.algo.discovery.heuristics import algorithm as heuristics_miner
    from pm4py.objects.conversion.process_tree import converter as pt_converter
    from pm4py.algo.evaluation.replay_fitness import algorithm as fitness_evaluator
    from pm4py.algo.evaluation.precision import algorithm as precision_evaluator
    from pm4py.algo.evaluation.simplicity import algorithm as simplicity_evaluator
    from pm4py.algo.evaluation.generalization import algorithm as generalization_evaluator
    from pm4py.objects.log.util import insert_classifier
    from pm4py.objects.petri_net.exporter import exporter as pnml_exporter
    from pm4py.visualization.petri_net import visualizer as petri_vis
    from pm4py.visualization.common.save import save as vis_save
    from pm4py import util as pmutil
    from pm4py.algo.analysis.woflan import algorithm as woflan

    def get_elonged_string(stru):
        nchar = 30

        if len(stru) >= nchar:
            return stru

        return stru + " ".join([""] * (nchar - len(stru)))

    def get_elonged_float(value):
        stru = "%.3f" % value

        return get_elonged_string(stru)

    ENABLE_VISUALIZATIONS = False
    ENABLE_VISUALIZATIONS_INDUCTIVE = False
    ENABLE_ALIGNMENTS = False
    ENABLE_PRECISION = True
    ENABLE_PETRI_EXPORTING = False
    ENABLE_PETRI_EXPORTING_DEBUG = True
    CHECK_SOUNDNESS = True
    WOFLAN_RETURN_ASAP = True
    WOFLAN_PRINT_DIAGNOSTICS = True
    WOFLAN_RETURN_DIAGNOSTICS = True
    INDUCTIVE_MINER_VARIANT = inductive.Variants.IM_CLEAN
    ALIGN_VARIANT = state_equation_a_star
    logFolder = os.path.join("..", "compressed_input_data")
    pnmlFolder = "pnml_folder"
    pngFolder = "png_folder"
    times_tokenreplay_alpha = {}
    times_tokenreplay_imdf = {}
    times_footprints_imdf = {}
    times_alignments_imdf = {}
    fitness_token_alpha = {}
    fitness_token_imdf = {}
    fitness_footprints_imdf = {}
    fitness_align_imdf = {}
    precision_alpha = {}
    precision_imdf = {}
    simplicity_alpha = {}
    simplicity_imdf = {}
    generalization_alpha = {}
    generalization_imdf = {}

    def write_report():
        f = open("report.txt", "w")

        f.write("\n\n")
        f.write("Fitness on Alpha and Inductive models - measured by token-based replay and alignments\n")
        f.write("----\n")
        f.write(
            get_elonged_string("log") + "\t" + get_elonged_string("fitness_token_alpha") + "\t" + get_elonged_string(
                "times_tokenreplay_alpha") + "\t" + get_elonged_string(
                "fitness_token_imdf") + "\t" + get_elonged_string("times_tokenreplay_imdf") + "\t" + get_elonged_string(
                "fitness_footprints_imdf") + "\t" + get_elonged_string("times_footprints_imdf"))
        if ENABLE_ALIGNMENTS:
            f.write(
                "\t" + get_elonged_string("fitness_align_imdf") + "\t" + get_elonged_string("times_alignments_imdf"))
        f.write("\n")
        for this_logname in precision_alpha:
            # F.write("%s\t\t%.3f\t\t%.3f\n" % (logName, fitness_token_alpha[logName], fitness_token_imdf[logName]))
            f.write(get_elonged_string(this_logname))
            f.write("\t")
            f.write(get_elonged_float(fitness_token_alpha[this_logname]))
            f.write("\t")
            f.write(get_elonged_float(times_tokenreplay_alpha[this_logname]))
            f.write("\t")
            f.write(get_elonged_float(fitness_token_imdf[this_logname]))
            f.write("\t")
            f.write(get_elonged_float(times_tokenreplay_imdf[this_logname]))
            f.write("\t")
            f.write(get_elonged_float(fitness_footprints_imdf[this_logname]))
            f.write("\t")
            f.write(get_elonged_float(times_footprints_imdf[this_logname]))
            if ENABLE_ALIGNMENTS:
                f.write("\t")
                f.write(get_elonged_float(fitness_align_imdf[this_logname]))
                f.write("\t")
                f.write(get_elonged_float(times_alignments_imdf[this_logname]))
            f.write("\n")
        f.write("\n\n")
        f.write("Precision measured by ETConformance where activated transitions are retrieved using token replay\n")
        f.write("----\n")
        f.write(get_elonged_string("log") + "\t" + get_elonged_string("precision_alpha") + "\t" + get_elonged_string(
            "precision_imdf") + "\n")
        for this_logname in precision_alpha:
            f.write(get_elonged_string(this_logname))
            f.write("\t")
            f.write(get_elonged_float(precision_alpha[this_logname]))
            f.write("\t")
            f.write(get_elonged_float(precision_imdf[this_logname]))
            f.write("\n")
        f.write("\n\n")
        f.write("Generalization based on token replay transition recall\n")
        f.write("----\n")
        f.write(
            get_elonged_string("log") + "\t" + get_elonged_string("generalization_alpha") + "\t" + get_elonged_string(
                "generalization_imdf") + "\n")
        for this_logname in precision_alpha:
            f.write(get_elonged_string(this_logname))
            f.write("\t")
            f.write(get_elonged_float(generalization_alpha[this_logname]))
            f.write("\t")
            f.write(get_elonged_float(generalization_imdf[this_logname]))
            f.write("\n")
        f.write("\n\n")
        f.write("Simplicity based on inverse arc degree\n")
        f.write("----\n")
        f.write(get_elonged_string("log") + "\t" + get_elonged_string("simplicity_alpha") + "\t" + get_elonged_string(
            "simplicity_imdf") + "\n")
        for this_logname in precision_alpha:
            f.write(get_elonged_string(this_logname))
            f.write("\t")
            f.write(get_elonged_float(simplicity_alpha[this_logname]))
            f.write("\t")
            f.write(get_elonged_float(simplicity_imdf[this_logname]))
            f.write("\n")
        f.write("\n")
        f.close()

    for logName in os.listdir(logFolder):
        if "." in logName:
            logNamePrefix = logName.split(".")[0]
            logExtension = logName[len(logNamePrefix) + 1:]

            print("\nelaborating " + logName)

            logPath = os.path.join(logFolder, logName)
            if "xes" in logExtension:
                log = xes_importer.apply(logPath, variant=xes_importer.Variants.CHUNK_REGEX)

            log, classifier_key = insert_classifier.search_act_class_attr(log, force_activity_transition_insertion=True)

            print("loaded log")

            activity_key = "concept:name"
            if classifier_key is not None:
                activity_key = classifier_key

            parameters_discovery = {pmutil.constants.PARAMETER_CONSTANT_ACTIVITY_KEY: activity_key,
                                    pmutil.constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY: activity_key}
            t1 = time.time()
            alpha_model, alpha_initial_marking, alpha_final_marking = alpha.apply(log, parameters=parameters_discovery)
            if ENABLE_PETRI_EXPORTING:
                pnml_exporter.export_net(alpha_model, alpha_initial_marking,
                                         os.path.join(pnmlFolder, logNamePrefix + "_alpha.pnml"),
                                         final_marking=alpha_final_marking)
            t2 = time.time()
            print("time interlapsed for calculating Alpha Model", (t2 - t1))
            if CHECK_SOUNDNESS:
                try:
                    res_woflan, diagn = woflan.apply(alpha_model, alpha_initial_marking, alpha_final_marking,
                                              parameters={"return_asap_when_not_sound": WOFLAN_RETURN_ASAP,
                                                          "print_diagnostics": WOFLAN_PRINT_DIAGNOSTICS,
                                                          "return_diagnostics": WOFLAN_RETURN_DIAGNOSTICS})
                    print("alpha woflan", res_woflan)
                except:
                    if ENABLE_PETRI_EXPORTING_DEBUG:
                        exce = traceback.format_exc()
                        pnml_exporter.export_net(alpha_model, alpha_initial_marking,
                                                 os.path.join(pnmlFolder, logNamePrefix + "_alpha.pnml"),
                                                 final_marking=alpha_final_marking)
                        F = open(logNamePrefix + "_alpha.txt", "w")
                        F.write(exce)
                        F.close()
            t1 = time.time()
            heu_model, heu_initial_marking, heu_final_marking = heuristics_miner.apply(log,
                                                                                parameters=parameters_discovery)
            if ENABLE_PETRI_EXPORTING:
                pnml_exporter.export_net(heu_model, heu_initial_marking,
                                         os.path.join(pnmlFolder, logNamePrefix + "_heuristics.pnml"),
                                         final_marking=heu_final_marking)
            t2 = time.time()
            print("time interlapsed for calculating Heuristics Model", (t2 - t1))
            if CHECK_SOUNDNESS:
                try:
                    res_woflan, diagn = woflan.apply(heu_model, heu_initial_marking, heu_initial_marking,
                                              parameters={"return_asap_when_not_sound": WOFLAN_RETURN_ASAP,
                                                          "print_diagnostics": WOFLAN_PRINT_DIAGNOSTICS,
                                                          "return_diagnostics": WOFLAN_RETURN_DIAGNOSTICS})
                    print("heuristics woflan", res_woflan)
                except:
                    if ENABLE_PETRI_EXPORTING_DEBUG:
                        exce = traceback.format_exc()
                        pnml_exporter.export_net(heu_model, heu_initial_marking,
                                                 os.path.join(pnmlFolder, logNamePrefix + "_heuristics.pnml"),
                                                 final_marking=heu_final_marking)
                        F = open(logNamePrefix + "_heuristics.txt", "w")
                        F.write(exce)
                        F.close()

            t1 = time.time()
            tree = inductive.apply(log, parameters=parameters_discovery, variant=INDUCTIVE_MINER_VARIANT)
            # print(tree)

            inductive_model, inductive_im, inductive_fm = pt_converter.apply(tree,
                                                                             variant=pt_converter.Variants.TO_PETRI_NET)

            """inductive_model, inductive_im, inductive_fm = inductive.apply(log, parameters=parameters_discovery,
                                                                          variant=INDUCTIVE_MINER_VARIANT)"""
            if ENABLE_PETRI_EXPORTING:
                pnml_exporter.export_net(inductive_model, inductive_im,
                                         os.path.join(pnmlFolder, logNamePrefix + "_inductive.pnml"),
                                         final_marking=inductive_fm)
            """
            generated_log = pt_semantics.generate_log(tree)
            print("first trace of log", [x["concept:name"] for x in generated_log[0]])
            """
            t2 = time.time()
            print("time interlapsed for calculating Inductive Model", (t2 - t1))
            if CHECK_SOUNDNESS:
                res_woflan, diagn = woflan.apply(inductive_model, inductive_im, inductive_fm,
                                          parameters={"return_asap_when_not_sound": WOFLAN_RETURN_ASAP,
                                                          "print_diagnostics": WOFLAN_PRINT_DIAGNOSTICS,
                                                          "return_diagnostics": WOFLAN_RETURN_DIAGNOSTICS})
                print("inductive woflan", res_woflan)

            parameters = {fitness_evaluator.Variants.TOKEN_BASED.value.Parameters.ACTIVITY_KEY: activity_key,
                          fitness_evaluator.Variants.TOKEN_BASED.value.Parameters.ATTRIBUTE_KEY: activity_key,
                          "align_variant": ALIGN_VARIANT,
                          "format": "png"}

            t1 = time.time()
            fitness_token_alpha[logName] = \
                fitness_evaluator.apply(log, alpha_model, alpha_initial_marking, alpha_final_marking,
                                        parameters=parameters, variant=fitness_evaluator.Variants.TOKEN_BASED)[
                    'perc_fit_traces']
            print(str(time.time()) + " fitness_token_alpha for " + logName + " succeeded! " + str(
                fitness_token_alpha[logName]))
            t2 = time.time()
            times_tokenreplay_alpha[logName] = t2 - t1

            t1 = time.time()
            fitness_token_imdf[logName] = \
                fitness_evaluator.apply(log, inductive_model, inductive_im, inductive_fm, parameters=parameters,
                                        variant=fitness_evaluator.Variants.TOKEN_BASED)[
                    'perc_fit_traces']
            print(str(time.time()) + " fitness_token_inductive for " + logName + " succeeded! " + str(
                fitness_token_imdf[logName]))
            t2 = time.time()
            times_tokenreplay_imdf[logName] = t2 - t1

            t1 = time.time()
            fp_log = footprints_discovery.apply(log, parameters=parameters)
            fp_tree = footprints_discovery.apply(tree, parameters=parameters)
            conf = footprints_conformance.apply(fp_log, fp_tree,
                                                variant=footprints_conformance.Variants.TRACE_EXTENSIVE,
                                                parameters=parameters)
            # fitness_fp = float(len([x for x in conf if len(x) == 0])) / float(len(conf)) * 100.0 if conf else 0.0
            fitness_fp = float(len([x for x in conf if x["is_footprints_fit"]])) / float(
                len(conf)) * 100.0 if conf else 0.0
            t2 = time.time()
            fitness_footprints_imdf[logName] = fitness_fp
            times_footprints_imdf[logName] = t2 - t1

            if ENABLE_ALIGNMENTS:
                t1 = time.time()
                fitness_align_imdf[logName] = \
                    fitness_evaluator.apply(log, inductive_model, inductive_im, inductive_fm,
                                            variant=fitness_evaluator.Variants.ALIGNMENT_BASED, parameters=parameters)[
                        'percFitTraces']
                print(str(time.time()) + " fitness_token_align for " + logName + " succeeded! " + str(
                    fitness_align_imdf[logName]))
                t2 = time.time()
                times_alignments_imdf[logName] = t2 - t1

            if ENABLE_PRECISION:
                precision_alpha[logName] = precision_evaluator.apply(log, alpha_model, alpha_initial_marking,
                                                                     alpha_final_marking,
                                                                     variant=precision_evaluator.Variants.ETCONFORMANCE_TOKEN,
                                                                     parameters=parameters)
            else:
                precision_alpha[logName] = 0.0
            print(str(time.time()) + " precision_alpha for " + logName + " succeeded! " + str(precision_alpha[logName]))

            generalization_alpha[logName] = generalization_evaluator.apply(log, alpha_model, alpha_initial_marking,
                                                                           alpha_final_marking, parameters=parameters)
            print(str(time.time()) + " generalization_alpha for " + logName + " succeeded! " + str(
                generalization_alpha[logName]))
            simplicity_alpha[logName] = simplicity_evaluator.apply(alpha_model, parameters=parameters)
            print(
                str(time.time()) + " simplicity_alpha for " + logName + " succeeded! " + str(simplicity_alpha[logName]))

            if ENABLE_PRECISION:
                precision_imdf[logName] = precision_evaluator.apply(log, inductive_model, inductive_im,
                                                                    inductive_fm,
                                                                    variant=precision_evaluator.Variants.ETCONFORMANCE_TOKEN,
                                                                    parameters=parameters)
            else:
                precision_imdf[logName] = 0.0
            print(str(time.time()) + " precision_imdf for " + logName + " succeeded! " + str(precision_imdf[logName]))

            generalization_imdf[logName] = generalization_evaluator.apply(log, inductive_model, inductive_im,
                                                                          inductive_fm, parameters=parameters)
            print(str(time.time()) + " generalization_imdf for " + logName + " succeeded! " + str(
                generalization_imdf[logName]))
            simplicity_imdf[logName] = simplicity_evaluator.apply(inductive_model, parameters=parameters)
            print(str(time.time()) + " simplicity_imdf for " + logName + " succeeded! " + str(simplicity_imdf[logName]))

            write_report()

            if ENABLE_VISUALIZATIONS:
                try:
                    alpha_vis = petri_vis.apply(alpha_model, alpha_initial_marking, alpha_final_marking, log=log,
                                                parameters=parameters, variant=petri_vis.Variants.FREQUENCY)
                    vis_save(alpha_vis, os.path.join(pngFolder, logNamePrefix + "_alpha.png"))
                    print(str(time.time()) + " alpha visualization for " + logName + " succeeded!")
                except:
                    print(str(time.time()) + " alpha visualization for " + logName + " failed!")
                    traceback.print_exc()

                try:
                    heuristics_vis = petri_vis.apply(heu_model, heu_initial_marking, heu_final_marking,
                                                     log=log, parameters=parameters,
                                                     variant=petri_vis.FREQUENCY_DECORATION)
                    vis_save(heuristics_vis, os.path.join(pngFolder, logNamePrefix + "_heuristics.png"))
                    print(str(time.time()) + " heuristics visualization for " + logName + " succeeded!")
                except:
                    print(str(time.time()) + " heuristics visualization for " + logName + " failed!")
                    traceback.print_exc()

            if ENABLE_VISUALIZATIONS or ENABLE_VISUALIZATIONS_INDUCTIVE:
                try:
                    inductive_vis = petri_vis.apply(inductive_model, inductive_im, inductive_fm,
                                                    log=log, parameters=parameters,
                                                    variant=petri_vis.PERFORMANCE_DECORATION)
                    vis_save(inductive_vis, os.path.join(pngFolder, logNamePrefix + "_inductive.png"))
                    print(str(time.time()) + " inductive visualization for " + logName + " succeeded!")
                except:
                    print(str(time.time()) + " inductive visualization for " + logName + " failed!")
                    traceback.print_exc()


#program to read all the lines in a file accepted from the user and print all email ids contained in it.

import re
fhand = open('mbox.txt')
f=fhand.read()
#f="faranazannigeri@gmail.com a bc cd  faranazanni3142@gmail.com"
#d=f.split()
#print(d)
#print(f)
#for line in f:
    #line = line.rstrip()
x = re.findall('\S+@\S+',f)
for d in x:
    print(d)

#print(x)

#print(line)


from random import randint
from time import clock

# Algorithm timer
start = clock()

# Cost limit
maxCost = 72
# Deck size
maxCards = 9

# List of cards with [Hp, Atk, Cost]
collection = [
    [780,390,13],
    [941,294,7],
    [787,393,7],
    [728,448,7],
    [750,235,9],
    [598,389,9],
    [485,306,7],
    [620,263,8],
    [769,231,9],
    [500,256,7],
    [609,396,9],
    [627,379,9],
    [793,306,10],
    [744,240,9],
    [421,259,4],
    [517,160,4],
    [450,225,4],
    [299,190,3],
    [360,141,3],
    [318,188,3],
    [480,190,4],
    [475,192,4],
    [305,192,3],
    [565,282,5],
    [480,192,4],
    [330,169,3],
    [420,253,4],
    [448,219,4],
    [612,240,5],
    [512,160,4]
    ]

# Test with 1,000 cards
#collection = [ [randint(300,800), randint(150,400), randint(3,13)] for i in range(1000)]

# Create a list of decks where decks[i][j] is the highest value deck for total cards up to 'i' and total cost up to 'j'
# Decks[0][0] has total cards 0 and total cost 0 so highest possible value is 0
# Decks are built from previous lower card and lower cost decks
# Decks are in the form [k_1, k_2,..., k_n] where k_i is True or False
# If k_i is True, collection[i] is used in the deck
decks = [[[False for k in range(len(collection))] for j in range(maxCost+1)] for i in range(maxCards+1)]

# What to use to calculate value
def getValue(card):
    #return card[0] # Focus on Hp
    #return card[1] # Focus on Atk
    #return 5*card[0] + 11*card[1] # Custom balance
    return card[0]+card[1] # Equal balance

# What to use to calculate cost
def getCost(card):
    return card[2]

# Get the total value for a given deck
def getDeckValue(deck):
    total = 0
    for i, card in enumerate(deck):
        if(card):
            total += getValue(collection[i])
    return total

# Get the total cost for a given deck
def getDeckCost(deck):
    total = 0
    for i, card in enumerate(deck):
        if(card):
            total += getCost(collection[i])
    return total

# Count the number of cards used in a given deck
def getDeckCount(deck):
    total = 0
    for card in deck:
        if(card):
            total += 1
    return total

# Convert a deck into a list of cards from collection
def makeDeck(deck):
    return [collection[i] for i,card in enumerate(deck) if card]

#Build decks starting from 1 to maxCards
for n in range(1,maxCards+1):
    # Use deck with 1 less card as basis
    decks[n] = list(decks[n-1])
    # Build decks starting from 1 to maxCost
    for i in range(1,maxCost+1):
        # Use the previous deck as a basis
        decks[n][i] = list(decks[n][i-1])
        # Go through collection to see if value can be added
        for j in range(len(collection)):
            # If cost of card is greater than total cost, skip
            if(getCost(collection[j]) <= i):
                # Check if previous deck can add a card without going over total cards
                if( getDeckCount(decks[n][i-getCost(collection[j])]) < n ):
                    # Use the deck where adding this card would give total cost of i
                    testDeck = list(decks[n][i-getCost(collection[j])]) # Copy deck
                    testDeck[j] = True # Add card
                    # Check if value is added
                    if( getDeckValue(testDeck) > getDeckValue(decks[n][i]) ):
                        decks[n][i] = list(testDeck) # Copy deck
                else:
                    # Use the deck where there is space for adding a card
                    testDeck = list(decks[n-1][i-getCost(collection[j])]) # Copy deck
                    testDeck[j] = True # Add card
                    # Check if value is added
                    if( getDeckValue(testDeck) > getDeckValue(decks[n][i]) ):
                        decks[n][i] = list(testDeck) # Copy deck

deck = makeDeck(decks[maxCards][maxCost])
print(deck)
print("Total Value: " + str(sum([getValue(x) for x in deck])))
print("HP:  " + str(sum([x[0] for x in deck])) + "\t#:  " + str(len(deck)))
print("ATK: " + str(sum([x[1] for x in deck])) + "\tCP: " + str(sum([x[2] for x in deck])))
print("Calc Time: " + str(clock() - start))


def main(str1, str2):
    same = True
    first = str1[0]
    for char in str1:
        if char != first:
            same = False

    for char in str2:
        if char != first:
            same = False

    if same == False:
        reverse = str1[::-1]
        count = str1.count(str2)
        count2 = reverse.count(str2)
        return count + count2
    else:
        count = len(str1) + len(str2) - 1
        return count

if __name__ == "__main__":
    print(
        main(
            input("Input string: "),
            input("Input substring: ")
        )
    )


'''
Created on 31 dic. 2020

@author: RSSpe
'''

import turtle

for y in range(IMAGE_SIZE_Y):
    zy = y * (MAX_Y - MIN_Y) / (IMAGE_SIZE_Y - 1) + MIN_Y
    for x in range(IMAGE_SIZE_X):
        zx = x * (MAX_X - MIN_X) / (IMAGE_SIZE_Y - 1) + MIN_X
        z = zx + zy * 1j
        c = z
        for i in range(MAX_ITERATIONS):
            if abs(z) > 2.0:
                break
            z = z * z + c
turtle.color((i % 4 * 64, i % 8 * 32, i % 16 * 16))
turtle.setposition(x - SCREEN_OFFSET_X,
                   y - SCREEN_OFFSET_Y)

turtle.pendown()
turtle.dot(1)
turtle.penup()

turtle.done()


"""
Created on Nov 28, 2010
Adaboost is short for Adaptive Boosting
@author: Peter
"""
from numpy import array, ones, shape, mat, inf, zeros, multiply, exp, sign
from math import log
import matplotlib.pyplot as plt

def load_simple_data():
    dat_mat = array([
        [1., 2.1],
        [2., 1.1],
        [1.3, 1.],
        [1., 1.],
        [2., 1.]
    ])
    class_labels = [1.0, 1.0, -1.0, -1.0, 1.0]
    return dat_mat, class_labels

# general function to parse tab -delimited floats
def load_data_set(file_name):
    # get number of fields
    num_feat = len(open(file_name).readline().split('\t'))
    data_mat = []
    label_mat = []
    fr = open(file_name)
    for line in fr.readlines():
        line_arr = []
        cur_line = line.strip().split('\t')
        for i in range(num_feat-1):
            line_arr.append(float(cur_line[i]))
        data_mat.append(line_arr)
        label_mat.append(float(cur_line[-1]))
    return data_mat, label_mat

# just classify the data
def stump_classify(data_matrix, dimension, thresh_val, thresh_inequal):
    ret_array = ones((shape(data_matrix)[0], 1))
    if thresh_inequal == 'lt':
        ret_array[data_matrix[:, dimension] <= thresh_val] = -1.0
    else:
        ret_array[data_matrix[:, dimension] > thresh_val] = -1.0
    return ret_array

def build_stump(dataArr, class_labels, D):
    data_matrix = mat(dataArr)
    label_mat = mat(class_labels).T
    m, n = shape(data_matrix)
    num_steps = 10.0
    best_stump = {}
    best_class_est = mat(zeros((m, 1)))
    # init error sum to +infinity
    min_error = inf
    for i in range(n):  # loop over all dimensions
        range_min = data_matrix[:, i].min()
        range_max = data_matrix[:, i].max()
        step_size = (range_max-range_min)/num_steps
        # loop over all range in current dimension
        for j in range(-1, int(num_steps)+1):
            for inequal in ['lt', 'gt']:    # go over less than and greater than
                thresh_val = range_min + float(j) * step_size
                # call stump classify with i, j, lessThan
                predicted_vals = stump_classify(data_matrix, i, thresh_val, inequal)
                err_arr = mat(ones((m, 1)))
                err_arr[predicted_vals == label_mat] = 0
                weighted_error = D.T*err_arr  # calc total error multiplied by D
                # print("split: dim %d, thresh %.2f, thresh inequal: %s, the weighted error is %.3f"
                #       % (i, thresh_val, inequal, weighted_error))
                if weighted_error < min_error:
                    min_error = weighted_error
                    best_class_est = predicted_vals.copy()
                    best_stump['dim'] = i
                    best_stump['thresh'] = thresh_val
                    best_stump['ineq'] = inequal
    return best_stump, min_error, best_class_est

def ada_boost_train_ds(data_arr, class_labels, num_it=40):
    """
    使用单层决策树作为弱分类器的AdaBoost算法
    :param data_arr:
    :param class_labels:
    :param num_it: 迭代次数
    :return:
    """
    weak_class_arr = []
    m = shape(data_arr)[0]
    D = mat(ones((m, 1))/m)   # init D to all equal
    agg_class_est = mat(zeros((m, 1)))
    for i in range(num_it):
        best_stump, error, class_est = build_stump(data_arr, class_labels, D)   # build Stump
        # print("D:", D.T)
        # calc alpha, throw in max(error,eps) to account for error=0
        alpha = float(0.5*log((1.0-error)/max(error, 1e-16)))
        best_stump['alpha'] = alpha
        # store Stump Params in Array
        weak_class_arr.append(best_stump)
        # print("class_est: ", class_est.T)
        # exponent for D calc, getting messy
        exponent = multiply(-1 * alpha * mat(class_labels).T, class_est)
        # Calc New D for next iteration
        D = multiply(D, exp(exponent))
        D = D/D.sum()
        # calc training error of all classifiers, if this is 0 quit for loop early (use break)
        agg_class_est += alpha*class_est
        # print("agg_class_est: ", agg_class_est.T)
        agg_errors = multiply(sign(agg_class_est) != mat(class_labels).T, ones((m, 1)))
        error_rate = agg_errors.sum()/m
        # print("total error: ", error_rate)
        if error_rate == 0.0:
            break
    return weak_class_arr, agg_class_est

def ada_classify(datToClass, classifierArr):
    # do stuff similar to last aggClassEst in ada_boost_train_ds
    dataMatrix = mat(datToClass)
    m = shape(dataMatrix)[0]
    aggClassEst = mat(zeros((m, 1)))
    for i in range(len(classifierArr)):
        # call stump classify
        classEst = stump_classify(
            dataMatrix, classifierArr[i]['dim'], classifierArr[i]['thresh'], classifierArr[i]['ineq'])
        aggClassEst += classifierArr[i]['alpha']*classEst
        # print(aggClassEst)
    return sign(aggClassEst)

def plot_roc(predStrengths, classLabels):
    # cursor
    cur = (1.0, 1.0)
    # variable to calculate AUC
    ySum = 0.0
    numPosClass = sum(array(classLabels) == 1.0)
    yStep = 1/float(numPosClass)
    xStep = 1/float(len(classLabels)-numPosClass)
    # get sorted index, it's reverse
    sortedIndices = predStrengths.argsort()
    fig = plt.figure()
    fig.clf()
    ax = plt.subplot(111)
    # loop through all the values, drawing a line segment at each point
    for index in sortedIndices.tolist()[0]:
        if classLabels[index] == 1.0:
            delX = 0
            delY = yStep
        else:
            delX = xStep
            delY = 0
            ySum += cur[1]
        # draw line from cur to (cur[0]-delX,cur[1]-delY)
        ax.plot([cur[0], cur[0]-delX], [cur[1], cur[1]-delY], c='b')
        cur = (cur[0]-delX, cur[1]-delY)
    ax.plot([0, 1], [0, 1], 'b--')
    plt.xlabel('False positive rate')
    plt.ylabel('True positive rate')
    plt.title('ROC curve for AdaBoost horse colic detection system')
    ax.axis([0, 1, 0, 1])
    plt.show()
    print("the Area Under the Curve is: ", ySum*xStep)

def test_simple_data():
    my_data_mat, my_class_labels = load_simple_data()
    print("my_class_labels")
    print(my_class_labels)
    my_d = mat(ones((5, 1)) / 5)
    # print(build_stump(my_data_mat, my_class_labels, my_d))
    classifierArray = ada_boost_train_ds(my_data_mat, my_class_labels, 9)
    print("classifierArray")
    print(classifierArray)
    print(ada_classify([0, 0], classifierArray))
    print(ada_classify([[5, 5], [0, 0]], classifierArray))

def test_horse_data():
    datArr, labelArr = load_data_set("horseColicTraining2.txt")
    testArr, testLabelArr = load_data_set("horseColicTest2.txt")
    test_size = len(testLabelArr)
    classifier_count = 50
    classifierArray = ada_boost_train_ds(datArr, labelArr, classifier_count)
    prediction10 = ada_classify(testArr, classifierArray)
    errArr = mat(ones((test_size, 1)))
    errCount = errArr[prediction10 != mat(testLabelArr).T].sum()
    print("classifier count:{}, error count:{}, error rate:{:.2f}".format(
        classifier_count, errCount, errCount/test_size))

if __name__ == '__main__':
    # test_simple_data()
    # test_horse_data()
    datArr, labelArr = load_data_set("horseColicTraining2.txt")
    classifierArray, aggClassEst = ada_boost_train_ds(datArr, labelArr, 10)
    plot_roc(aggClassEst.T, labelArr)
    print("Run adaboost finish")


import sys

N = int(sys.stdin.readline())
board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
dp = [[[0 for _ in range(3)] for _ in range(N)] for _ in range(N)]

for i in range(1, N):
    if board[0][i] == 1:
        break
    dp[0][i][0] = 1

for i in range(1, N):
    for j in range(2, N):
        if board[i][j] == 1:
            continue

        dp[i][j][0] += dp[i][j-1][0] + dp[i][j-1][2]
        dp[i][j][1] += dp[i-1][j][1] + dp[i-1][j][2]
        if board[i][j-1] != 1 and board[i-1][j] != 1:
            dp[i][j][2] += dp[i-1][j-1][0]+dp[i-1][j-1][1]+dp[i-1][j-1][2]
print(sum(dp[N-1][N-1]))
# print(dp)

# import sys
#
# N = int(sys.stdin.readline())
# board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
# ans = 0
#
#
# def check(tail):
#     return board[tail[0]+1][tail[1]] != 1 and board[tail[0]][tail[1]+1] != 1 and board[tail[0]+1][tail[1]+1] != 1
#
#
# def move(tail, status):
#     if tail == [N-1, N-1]:
#         global ans
#         ans += 1
#         return
#
#     if status == 0:
#         # horizontal
#         if tail[1]+1 < N and board[tail[0]][tail[1]+1] != 1:
#             move([tail[0], tail[1]+1], 0)
#
#         if tail[0]+1 < N and tail[1]+1 < N and check(tail):
#             move([tail[0]+1, tail[1]+1], 2)
#     elif status == 1:
#         # vertical
#         if tail[0] + 1 < N and board[tail[0]+1][tail[1]] != 1:
#             move([tail[0]+1, tail[1]], 1)
#
#         if tail[0] + 1 < N and tail[1] + 1 < N and check(tail):
#             move([tail[0]+1, tail[1] + 1], 2)
#     elif status == 2:
#         # diagonal
#         if tail[1] + 1 < N and board[tail[0]][tail[1] + 1] != 1:
#             move([tail[0], tail[1] + 1], 0)
#
#         if tail[0] + 1 < N and board[tail[0]+1][tail[1]] != 1:
#             move([tail[0]+1, tail[1]], 1)
#
#         if tail[0] + 1 < N and tail[1] + 1 < N and check(tail):
#             move([tail[0]+1, tail[1] + 1], 2)
#     return
#
#
# move([0, 1], 0)
# print(ans)


# global
CONFIG_FILE = 'config.json'
LOG_FILE = 'log.log'
TAKER = 'taker'
MAKER = 'maker'

# okex contract type
SWAP = 'SWAP'
FUTURE = 'FUTURE'

# okex instrument_id
# XBTUSDTM
BTC_USDT_SWAP = 'BTC-USDT-SWAP'
# XBTUSDM
BTC_USD_SWAP = 'BTC-USD-SWAP'
# XBTMM20
BTC_USD_200626 = 'BTC-USD-200626'
# XBTMU20
BTC_USD_200925 = 'BTC-USD-200925'


import functools
import logging

import numpy as np
from scipy.interpolate import griddata, Rbf
from scipy.spatial import cKDTree, ConvexHull, Delaunay, qhull

from . import geometry, tools
from ..package_tools import Exporter
from ..units import units

exporter = Exporter(globals())

log = logging.getLogger(__name__)

def cressman_point(sq_dist, values, radius):
    r"""Generate a Cressman interpolation value for a point.

    The calculated value is based on the given distances and search radius.

    Parameters
    ----------
    sq_dist: (N, ) numpy.ndarray
        Squared distance between observations and grid point
    values: (N, ) numpy.ndarray
        Observation values in same order as sq_dist
    radius: float
        Maximum distance to search for observations to use for
        interpolation.

    Returns
    -------
    value: float
        Interpolation value for grid point.

    """
    weights = tools.cressman_weights(sq_dist, radius)
    total_weights = np.sum(weights)

    return sum(v * (w / total_weights) for (w, v) in zip(weights, values))

def barnes_point(sq_dist, values, kappa, gamma=None):
    r"""Generate a single pass Barnes interpolation value for a point.

    The calculated value is based on the given distances, kappa and gamma values. This
    is calculated as an inverse distance-weighted average of the points in the neighborhood,
    with weights given as:

    .. math:: w = e ^ \frac{-r^2}{\kappa}

    * :math:`\kappa` is a scaling parameter
    * :math:`r` is the distance to a point.

    For more information see [Barnes1964]_ or [Koch1983]_.

    Parameters
    ----------
    sq_dist: (N, ) numpy.ndarray
        Squared distance between observations and grid point
    values: (N, ) numpy.ndarray
        Observation values in same order as sq_dist
    kappa: float
        Response parameter for barnes interpolation.
    gamma: float
        Adjustable smoothing parameter for the barnes interpolation. Default 1.

    Returns
    -------
    value: float
        Interpolation value for grid point.

    """
    if gamma is None:
        gamma = 1
    weights = tools.barnes_weights(sq_dist, kappa, gamma)
    total_weights = np.sum(weights)

    return sum(v * (w / total_weights) for (w, v) in zip(weights, values))

def natural_neighbor_point(xp, yp, variable, grid_loc, tri, neighbors, circumcenters):
    r"""Generate a natural neighbor interpolation of the observations to the given point.

    This uses the Liang and Hale approach [Liang2010]_. The interpolation will fail if
    the grid point has no natural neighbors.

    Parameters
    ----------
    xp: (N, ) numpy.ndarray
        x-coordinates of observations
    yp: (N, ) numpy.ndarray
        y-coordinates of observations
    variable: (N, ) numpy.ndarray
        observation values associated with (xp, yp) pairs.
        IE, variable[i] is a unique observation at (xp[i], yp[i])
    grid_loc: (float, float)
        Coordinates of the grid point at which to calculate the
        interpolation.
    tri: `scipy.spatial.Delaunay`
        Delaunay triangulation of the observations.
    neighbors: (N, ) numpy.ndarray
        Simplex codes of the grid point's natural neighbors. The codes
        will correspond to codes in the triangulation.
    circumcenters: list
        Pre-calculated triangle circumcenters for quick look ups. Requires
        indices for the list to match the simplices from the Delaunay triangulation.

    Returns
    -------
    value: float
       Interpolated value for the grid location

    """
    edges = geometry.find_local_boundary(tri, neighbors)
    edge_vertices = [segment[0] for segment in geometry.order_edges(edges)]
    num_vertices = len(edge_vertices)

    p1 = edge_vertices[0]
    p2 = edge_vertices[1]

    c1 = geometry.circumcenter(grid_loc, tri.points[p1], tri.points[p2])
    polygon = [c1]

    area_list = []
    total_area = 0.0

    for i in range(num_vertices):

        p3 = edge_vertices[(i + 2) % num_vertices]

        try:

            c2 = geometry.circumcenter(grid_loc, tri.points[p3], tri.points[p2])
            polygon.append(c2)

            for check_tri in neighbors:
                if p2 in tri.simplices[check_tri]:
                    polygon.append(circumcenters[check_tri])

            pts = [polygon[i] for i in ConvexHull(polygon).vertices]
            value = variable[(tri.points[p2][0] == xp) & (tri.points[p2][1] == yp)]

            cur_area = geometry.area(pts)

            total_area += cur_area

            area_list.append(cur_area * value[0])

        except (ZeroDivisionError, qhull.QhullError) as e:
            message = ('Error during processing of a grid. '
                       'Interpolation will continue but be mindful '
                       f'of errors in output. {e}')

            log.warning(message)
            return np.nan

        polygon = [c2]

        p2 = p3

    return sum(x / total_area for x in area_list)

@exporter.export
def natural_neighbor_to_points(points, values, xi):
    r"""Generate a natural neighbor interpolation to the given points.

    This assigns values to the given interpolation points using the Liang and Hale
    [Liang2010]_. approach.

    Parameters
    ----------
    points: array-like, (N, 2)
        Coordinates of the data points.
    values: array-like, (N,)
        Values of the data points.
    xi: array-like, (M, 2)
        Points to interpolate the data onto.

    Returns
    -------
    img: numpy.ndarray, (M,)
        Array representing the interpolated values for each input point in `xi`

    See Also
    --------
    natural_neighbor_to_grid

    """
    tri = Delaunay(points)
    members, circumcenters = geometry.find_natural_neighbors(tri, xi)

    if hasattr(values, 'units'):
        org_units = values.units
        values = values.magnitude
    else:
        org_units = None

    img = np.asarray([natural_neighbor_point(*np.array(points).transpose(),
                                             values, xi[grid], tri, neighbors, circumcenters)
                      if len(neighbors) > 0 else np.nan
                      for grid, neighbors in members.items()])

    if org_units:
        img = units.Quantity(img, org_units)

    return img

@exporter.export
def inverse_distance_to_points(points, values, xi, r, gamma=None, kappa=None, min_neighbors=3,
                               kind='cressman'):
    r"""Generate an inverse distance weighting interpolation to the given points.

    Values are assigned to the given interpolation points based on either [Cressman1959]_ or
    [Barnes1964]_. The Barnes implementation used here is based on [Koch1983]_.

    Parameters
    ----------
    points: array-like, (N, 2)
        Coordinates of the data points.
    values: array-like, (N,)
        Values of the data points.
    xi: array-like, (M, 2)
        Points to interpolate the data onto.
    r: float
        Radius from grid center, within which observations are considered and weighted.
    gamma: float
        Adjustable smoothing parameter for the barnes interpolation. Default None.
    kappa: float
        Response parameter for barnes interpolation. Default None.
    min_neighbors: int
        Minimum number of neighbors needed to perform barnes or cressman interpolation
        for a point. Default is 3.
    kind: str
        Specify what inverse distance weighting interpolation to use.
        Options: 'cressman' or 'barnes'. Default 'cressman'

    Returns
    -------
    img: numpy.ndarray, (M,)
        Array representing the interpolated values for each input point in `xi`

    See Also
    --------
    inverse_distance_to_grid

    """
    if kind == 'cressman':
        interp_func = functools.partial(cressman_point, radius=r)
    elif kind == 'barnes':
        interp_func = functools.partial(barnes_point, kappa=kappa, gamma=gamma)
    else:
        raise ValueError(f'{kind} interpolation not supported.')

    obs_tree = cKDTree(points)
    indices = obs_tree.query_ball_point(xi, r=r)

    if hasattr(values, 'units'):
        org_units = values.units
        values = values.magnitude
    else:
        org_units = None

    img = np.asarray([interp_func(geometry.dist_2(*grid, *obs_tree.data[matches].T),
                                  values[matches]) if len(matches) >= min_neighbors else np.nan
                      for matches, grid in zip(indices, xi)])

    if org_units:
        img = units.Quantity(img, org_units)

    return img

@exporter.export
def interpolate_to_points(points, values, xi, interp_type='linear', minimum_neighbors=3,
                          gamma=0.25, kappa_star=5.052, search_radius=None, rbf_func='linear',
                          rbf_smooth=0):
    r"""Interpolate unstructured point data to the given points.

    This function interpolates the given `values` valid at ``points`` to the points `xi`.
    This is modeled after `scipy.interpolate.griddata`, but acts as a generalization of it by
    including the following types of interpolation:

    - Linear
    - Nearest Neighbor
    - Cubic
    - Radial Basis Function
    - Natural Neighbor (2D Only)
    - Barnes (2D Only)
    - Cressman (2D Only)

    Parameters
    ----------
    points: array-like, (N, P)
        Coordinates of the data points.
    values: array-like, (N,)
        Values of the data points.
    xi: array-like, (M, P)
        Points to interpolate the data onto.
    interp_type: str
        What type of interpolation to use. Available options include:
        1) "linear", "nearest", "cubic", or "rbf" from `scipy.interpolate`.
        2) "natural_neighbor", "barnes", or "cressman" from `metpy.interpolate`.
        Default "linear".
    minimum_neighbors: int
        Minimum number of neighbors needed to perform Barnes or Cressman interpolation for a
        point. Default is 3.
    gamma: float
        Adjustable smoothing parameter for the barnes interpolation. Default 0.25.
    kappa_star: float
        Response parameter for barnes interpolation, specified non-dimensionally
        in terms of the Nyquist. Default 5.052.
    search_radius: float
        A search radius to use for the Barnes and Cressman interpolation schemes.
        If search_radius is not specified, it will default to 5 times the average spacing of
        observations.
    rbf_func: str
        Specifies which function to use for Rbf interpolation.
        Options include: 'multiquadric', 'inverse', 'gaussian', 'linear', 'cubic',
        'quintic', and 'thin_plate'. Default 'linear'. See `scipy.interpolate.Rbf` for more
        information.
    rbf_smooth: float
        Smoothing value applied to rbf interpolation.  Higher values result in more smoothing.

    Returns
    -------
    values_interpolated: ndarray, (M,)
        Array representing the interpolated values for each input point in `xi`.

    See Also
    --------
    interpolate_to_grid

    Notes
    -----
    This function primarily acts as a wrapper for the individual interpolation routines. The
    individual functions are also available for direct use.

    """
    # If this is a type that `griddata` handles, hand it along to `griddata`
    if interp_type in ['linear', 'nearest', 'cubic']:
        if hasattr(values, 'units'):
            org_units = values.units
            values = values.magnitude
        else:
            org_units = None

        ret = griddata(points, values, xi, method=interp_type)

        if org_units:
            ret = units.Quantity(ret, org_units)

        return ret

    # If this is natural neighbor, hand it along to `natural_neighbor`
    elif interp_type == 'natural_neighbor':
        return natural_neighbor_to_points(points, values, xi)

    # If this is Barnes/Cressman, determine search_radius and hand it along to
    # `inverse_distance`
    elif interp_type in ['cressman', 'barnes']:
        ave_spacing = tools.average_spacing(points)
        if search_radius is None:
            search_radius = 5 * ave_spacing

        if interp_type == 'cressman':
            return inverse_distance_to_points(points, values, xi, search_radius,
                                              min_neighbors=minimum_neighbors,
                                              kind=interp_type)
        else:
            kappa = tools.calc_kappa(ave_spacing, kappa_star)
            return inverse_distance_to_points(points, values, xi, search_radius, gamma, kappa,
                                              min_neighbors=minimum_neighbors,
                                              kind=interp_type)

    # If this is radial basis function, make the interpolator and apply it
    elif interp_type == 'rbf':
        points_transposed = np.array(points).transpose()
        xi_transposed = np.array(xi).transpose()

        if hasattr(values, 'units'):
            org_units = values.units
            values = values.magnitude
        else:
            org_units = None

        rbfi = Rbf(points_transposed[0], points_transposed[1], values, function=rbf_func,
                   smooth=rbf_smooth)
        ret = rbfi(xi_transposed[0], xi_transposed[1])

        if org_units:
            ret = units.Quantity(ret, org_units)

        return ret

    else:
        raise ValueError(f'Interpolation option {interp_type} not available. '
                         'Try: linear, nearest, cubic, natural_neighbor, '
                         'barnes, cressman, rbf')


'''!    @file       task_controller.py
        @brief      Runs the motor and controller tasks together.
        @details    Implements closed-loop position control on a motor
                    using a task defined as a generator.

        @author     Juan Luna
        @date       2022-03-10 Original file
        @date       2022-12-30 Modified for portfolio update
'''
import controller
import motor

class Task_Controller:
    '''! @brief     Task motor controller class.
    '''
    def __init__(self, encoder_share, gain_share, set_point_share, next_flag, ENA_pin, In1_pin, In2_pin, Timer):
        '''! @brief    Instantiates objects of the Task_Motor_Controller class.
             @param  encoder_share  Passes the present value from the encoder
             @param  gain_share    Share variable for proportional gain value.
             @param  set_point_share   Share variable for setpoint value.
             @param  next_flag  Share variable to indicate that the motor has reached its setpoint.
             @param  ENA_pin            Enable pin object for the motor.
             @param  In1_pin       Control pin 1 associated with motor.
             @param  In2_pin       Control pin 2 associated with motor.
             @param  Timer          Timer object for motor.
        '''
        # Define shares for motor and encoder 1

        ## Passes the present value from the encoder
        self.encoder_share = encoder_share
        ## Share variable for proportional gain value.
        self.gain_share = gain_share
        ## Share variable for setpoint value.
        self.set_point_share = set_point_share
        ## Share variable to say when the motor has reached its setpoint
        self.next_flag = next_flag

        # Define motor-related pin objects

        ## Enable pin object for the motor.
        self.ENA = ENA_pin
        ## Control pin 1 associated with motor.
        self.IN1A_pin = In1_pin
        ## Control pin 2 associated with motor.
        self.IN2A_pin = In2_pin
        ## Timer object for motor.
        self.tim_MOT_A = Timer

        ## Motor object
        self.motor = motor.Motor_Driver(self.ENA, self.IN1A_pin, self.IN2A_pin, self.tim_MOT_A)

    def run(self):
        '''! @brief Runs the controller task and sets new duty cycle
        '''
        ## Controller object
        self.controller = controller.Controller(self.set_point_share, self.gain_share.get())

        while True:

            print(self.set_point_share.get())

            ## Encoder position reading
            true_position = int(self.encoder_share.get())
            print('Encoder value: ', true_position)
            ## Difference between measured and setpoint values
            self.controller.set_point(self.set_point_share.get())
            self.calc_error = self.controller.run(true_position)
            self.motor.set_duty_cycle(float(self.calc_error))

            if  self.set_point_share.get() - self.set_point_share.get()*.05 <= true_position <= self.set_point_share.get() + self.set_point_share.get()*.05:
                self.next_flag.put(1)
                self.motor.set_duty_cycle(0)
            yield (0)


from .basehandler import BaseHandler
from ..file import DefaultHandler as FileHandler
from .. import models, forms, settings
from andweb.utils import cacheclassproperty
from django.db.models import Q
import json

class DefaultHandler(BaseHandler):
    __slots__ = ()

    def oninit(self):
        super().oninit()
        if self.is_get:
            self.assign('cats', models.Category.objects.filter(parent=None))

    def list(self):
        if self.is_get:
            args = self.get_args_adv(('search', ('cat', int, 0),
                ('page', int, 1), ('limit', int, 0), 'order_by', 'order'), '')
            search = args.search
            cat = args.cat
            query = Q()
            if search:
                query |= Q(name__icontains=search) | Q(desc__icontains=search)
            if cat:
                query &= Q(category_id=cat) | Q(category__parent_id=cat)
            data = models.Goods.publics().filter(query)
            if args.order_by:
                if args.order == 'DESC':
                    args.order_by = '-' + args.order_by
                data = data.order_by(args.order_by)
            data, pagination = self.pagination(data, args.page, args.limit)
            hots = models.Goods.publics().order_by('-view_count')[:3]
            return self.render(
                data=data,
                args=args,
                catid=cat,
                hots=hots,
                pagination=pagination)

    def publish(self):
        if self.is_get:
            form = forms.GoodsForm()
            if self.userinfo:
                form.initial = {'phone': self.userinfo.phone}
                catid = self.get_arg('cat', None)
                if catid:
                    form.initial['category'] = catid
            del form.fields['images']
        else:
            form = forms.GoodsForm(self.request.POST)
            if form.is_valid():
                form.instance.seller = self.user
                form.instance.status = models.Goods.VERIFY
                form.save()
                return self.redirect('../account/goods')

        return self.render(form=form, upload_url=self.upload_url)

    def update(self):
        goods = models.Goods.objects.filter(id=self.get_arg('id'), seller=self.user).first()
        if goods:
            if self.is_get:
                form = forms.GoodsForm(instance=goods, is_update=True)
                del form.fields['images']
            else:
                form = forms.GoodsForm(self.request.POST, instance=goods, is_update=True)
                if form.is_valid():
                    form.instance.status = models.Goods.VERIFY
                    form.save()
                    return self.redirect('../account/goods')

            images = {"files": [FileHandler.get_file_dict(img) for img in goods.images.all()]}
            iamges = json.dumps(images)
            return self.render(
                form=form,
                upload_url=self.upload_url,
                images=iamges
            )
        else:
            return self.page404()

    def detail(self):
        if self.is_get:
            goods = models.Goods.objects.filter(id=self.get_arg('id')).first()
            if goods:
                similar = models.Goods.objects.filter(category=goods.category).exclude(id=goods.id)
                hots = models.Goods.objects.exclude(id=goods.id).order_by('-view_count')[:6]
                goods.view_count += 1
                goods.save()
                return self.render(goods=goods, similar=similar, hots=hots)
        return self.page404()

    def delete(self):
        models.Goods.objects.filter(id=self.get_arg('id'), seller=self.user).delete()
        return self.goback()

    def comment(self):
        if self.is_get:
            return self.render()
        else:
            pass

    @cacheclassproperty
    def upload_url(self):
        return FileHandler.guessUrl('upload')


# coding: utf-8
from __future__ import unicode_literals

from .common import InfoExtractor
from ..utils import (
    dict_get,
    int_or_none,
    unified_timestamp,
)

class URPlayIE(InfoExtractor):
    _VALID_URL = r'https?://(?:www\.)?ur(?:play|skola)\.se/(?:program|Produkter)/(?P<id>[0-9]+)'
    _TESTS = [{
        'url': 'https://urplay.se/program/203704-ur-samtiden-livet-universum-och-rymdens-markliga-musik-om-vetenskap-kritiskt-tankande-och-motstand',
        'md5': 'ff5b0c89928f8083c74bbd5099c9292d',
        'info_dict': {
            'id': '203704',
            'ext': 'mp4',
            'title': 'UR Samtiden - Livet, universum och rymdens märkliga musik : Om vetenskap, kritiskt tänkande och motstånd',
            'description': 'md5:5344508a52aa78c1ced6c1b8b9e44e9a',
            'timestamp': 1513292400,
            'upload_date': '20171214',
        },
    }, {
        'url': 'https://urskola.se/Produkter/190031-Tripp-Trapp-Trad-Sovkudde',
        'info_dict': {
            'id': '190031',
            'ext': 'mp4',
            'title': 'Tripp, Trapp, Träd : Sovkudde',
            'description': 'md5:b86bffdae04a7e9379d1d7e5947df1d1',
            'timestamp': 1440086400,
            'upload_date': '20150820',
        },
    }, {
        'url': 'http://urskola.se/Produkter/155794-Smasagor-meankieli-Grodan-i-vida-varlden',
        'only_matching': True,
    }]

    def _real_extract(self, url):
        video_id = self._match_id(url)
        url = url.replace('skola.se/Produkter', 'play.se/program')
        webpage = self._download_webpage(url, video_id)
        urplayer_data = self._parse_json(self._html_search_regex(
            r'data-react-class="components/Player/Player"[^>]+data-react-props="({.+?})"',
            webpage, 'urplayer data'), video_id)['currentProduct']
        episode = urplayer_data['title']

        host = self._download_json('http://streaming-loadbalancer.ur.se/loadbalancer.json', video_id)['redirect']
        formats = []
        urplayer_streams = urplayer_data.get('streamingInfo', {})

        for k, v in urplayer_streams.get('raw', {}).items():
            if not (k in ('sd', 'hd') and isinstance(v, dict)):
                continue
            file_http = v.get('location')
            if file_http:
                formats.extend(self._extract_wowza_formats(
                    'http://%s/%splaylist.m3u8' % (host, file_http),
                    video_id, skip_protocols=['f4m', 'rtmp', 'rtsp']))
        self._sort_formats(formats)

        subtitles = {}
        subs = urplayer_streams.get("sweComplete", {}).get("tt", {}).get("location")
        if subs:
            subtitles.setdefault('Svenska', []).append({
                'url': subs,
            })

        image = urplayer_data.get('image') or {}
        thumbnails = []
        for k, v in image.items():
            t = {
                'id': k,
                'url': v,
            }
            wh = k.split('x')
            if len(wh) == 2:
                t.update({
                    'width': int_or_none(wh[0]),
                    'height': int_or_none(wh[1]),
                })
            thumbnails.append(t)

        series = urplayer_data.get('series') or {}
        series_title = dict_get(series, ('seriesTitle', 'title')) or dict_get(urplayer_data, ('seriesTitle', 'mainTitle'))

        return {
            'id': video_id,
            'subtitles': subtitles,
            'title': '%s : %s' % (series_title, episode) if series_title else episode,
            'description': urplayer_data.get('description'),
            'thumbnails': thumbnails,
            'timestamp': unified_timestamp(urplayer_data.get('publishedAt')),
            'series': series_title,
            'formats': formats,
            'duration': int_or_none(urplayer_data.get('duration')),
            'categories': urplayer_data.get('categories'),
            'tags': urplayer_data.get('keywords'),
            'season': series.get('label'),
            'episode': episode,
            'episode_number': int_or_none(urplayer_data.get('episodeNumber')),
        }


from navmazing import NavigateToSibling

from airgun.entities.base import BaseEntity
from airgun.navigation import NavigateStep, navigator
from airgun.views.contentcredential import (
    ContentCredentialCreateView,
    ContentCredentialEditView,
    ContentCredentialsTableView,
)

class ContentCredentialEntity(BaseEntity):

    def create(self, values):
        view = self.navigate_to(self, 'New')
        view.fill(values)
        view.submit.click()

    def delete(self, entity_name):
        view = self.navigate_to(self, 'Edit', entity_name=entity_name)
        view.remove.click()
        view.dialog.confirm()
        view.flash.assert_no_error()
        view.flash.dismiss()

    def search(self, value):
        view = self.navigate_to(self, 'All')
        return view.search(value)

    def read(self, entity_name, widget_names=None):
        view = self.navigate_to(self, 'Edit', entity_name=entity_name)
        return view.read(widget_names=widget_names)

    def update(self, entity_name, values):
        view = self.navigate_to(self, 'Edit', entity_name=entity_name)
        filled_values = view.fill(values)
        view.flash.assert_no_error()
        view.flash.dismiss()
        return filled_values

@navigator.register(ContentCredentialEntity, 'All')
class ShowAllContentViews(NavigateStep):
    VIEW = ContentCredentialsTableView

    def step(self, *args, **kwargs):
        self.view.menu.select('Content', 'Content Credentials')

@navigator.register(ContentCredentialEntity, 'New')
class AddNewContentCredential(NavigateStep):
    VIEW = ContentCredentialCreateView

    prerequisite = NavigateToSibling('All')

    def step(self, *args, **kwargs):
        self.parent.new.click()

@navigator.register(ContentCredentialEntity, 'Edit')
class EditContentCredential(NavigateStep):
    VIEW = ContentCredentialEditView

    def prerequisite(self, *args, **kwargs):
        return self.navigate_to(self.obj, 'All')

    def step(self, *args, **kwargs):
        entity_name = kwargs.get('entity_name')
        self.parent.search(entity_name)
        self.parent.table.row(name=entity_name)['Name'].widget.click()


import sys; input = sys.stdin.readline
from heapq import heappop, heappush

def dijkstra(raser, _map):
    d = [(-1, 0), (0, 1), (1, 0), (0, -1)]
    ret = 10000
    # s = raser[0], e = raser[1]
    visit = [[[-1, 10000] for _ in range(len(_map[0]))] for _ in range(len(_map))]
    h = [(0, raser[0][0], raser[0][1], -1, 0)]
    while h:
        dist, cur_r, cur_c, cur_dir, change_num = heappop(h)
        if cur_r == raser[1][0] and cur_c == raser[1][1]:
            # 방향이 바뀌는 최소 횟수 저장
            ret = min(ret, change_num)
        if visit[cur_r][cur_c][1] >= change_num:
            visit[cur_r][cur_c][1] = change_num
        elif visit[cur_r][cur_c][0] > -1:
            continue
        visit[cur_r][cur_c][0] = dist

        for i in range(4):
            nr = cur_r + d[i][0]
            nc = cur_c + d[i][1]
            n_num = change_num
            if _map[nr][nc] == "*": continue
            if cur_dir != -1 and cur_dir != i:
                n_num += 1
            heappush(h, (dist + 1, nr, nc, i, n_num))

    return ret

def main():
    W, H = map(int, input().split())
    raser = []
    _map = ["*" * (W + 2)]
    for r in range(H):
        tmp = input().rstrip()
        _map.append("*" + tmp + "*")
        for c in range(W):
            if tmp[c] == "C":
                raser.append((r + 1, c + 1))
    _map.append("*" * (W + 2))

    print(dijkstra(raser, _map))

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
"""
create a filtered csv version of NCBI's accession2taxid
"""
import argparse
import csv
import gzip
import sys
import ya16sdb

def main():
    p = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument('accession2taxid')
    p.add_argument('accessions', nargs=argparse.REMAINDER)
    p.add_argument(
        '--out',
        default=sys.stdout,
        type=argparse.FileType('w'))
    args = p.parse_args()
    accessions = set(ya16sdb.open_clean(args.accessions))
    a2t = csv.reader(gzip.open(args.accession2taxid, 'rt'), delimiter='\t')
    next(a2t)  # header
    acc, tax_id = 1, 2
    a2t = ((a[acc], a[tax_id]) for a in a2t if a[acc] in accessions)
    out = csv.writer(args.out)
    out.writerow(['version', 'tax_id'])
    out.writerows(a2t)

if __name__ == '__main__':
    main()


from flask_restplus import Resource, Namespace
from flask import jsonify, request
from Models.assessments import Assessment
from Util.dto import AssessmentDto
from Services.assessment_service import get_all_assessments,add_assessment,update_assessment, get_assessment, delete_assessment

api=AssessmentDto.api
model=AssessmentDto.model

# sanity check route
@api.route('/')
class AssessmentList(Resource):
  @api.marshal_with(model)
  @api.doc('List of assessments')
  def get(self):
    return get_all_assessments()

  @api.marshal_with(model)
  @api.expect(model)
  def post(self):
    data = request.json
    return add_assessment(data)

@api.route('/<assessment_id>')
@api.param('assessment_id','Assessment id')
@api.response(404,'Assessment not found')
class Assess(Resource):
  @api.doc('Get Assessment info')
  @api.marshal_with(model)
  def get(self, assessment_id):
    assessment= get_assessment(assessment_id)
    if not assessment:
      api.abort(404)
    else:
      return assessment

  def delete(self, assessment_id):
    return delete_assessment(assessment_id)

  @api.doc('Update Assessment info')
  @api.marshal_with(model)
  def post(self,assessment_id):
    data = request.json
    return update_assessment(assessment_id,data)

@api.route('/healthcheck')
class healthCheck(Resource):
  def get(self):
    return jsonify('Ok!')


from piccata.constants import *
from piccata import core
from piccata import message
from piccata import resource
from transport import tsocket

from ipaddress import ip_address
import sys

import unittest
import time

SERVER_PORT = 5683

PAYLOAD = b"123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 "

class TextResource(resource.CoapResource):

    def __init__(self):
        resource.CoapResource.__init__(self)
        self.text = PAYLOAD

    def render_GET(self, request):
        response = message.Message(code=CONTENT, payload=self.text)
        return response

class TestClientServerCommunication(unittest.TestCase):

    def setUp(self):
        self.stopWaiting = False
        self.responseReceived = False
        self.responsePayload = ""

        server_root = resource.CoapResource()
        text = TextResource()
        server_root.put_child(b'text', text)
        server_endpoint = resource.CoapEndpoint(server_root)

        self.server_transport = tsocket.SocketTransport(SERVER_PORT)
        self.server_protocol = core.Coap(self.server_transport)
        self.server_request_handler = resource.ResourceManager(server_endpoint)
        self.server_transport.register_receiver(self.server_protocol)
        self.server_protocol.register_request_handler(self.server_request_handler)

        self.client_transport = tsocket.SocketTransport()
        self.client_protocol = core.Coap(self.client_transport)
        self.client_transport.register_receiver(self.client_protocol)

        self.server_transport.open()
        self.client_transport.open()

    def tearDown(self):
        self.server_transport.close()
        self.client_transport.close()

    def _handle_text_response(self, result, request, response):
        if result == RESULT_SUCCESS:
            self.responsePayload = response.payload
            self.responseReceived = True
            self.stopWaiting = True
        else:
            self.stopWaiting = True
            self.assertFalse(True, "No response received.")

    def test_client_server_communication(self):
        request = message.Message(mtype = CON, code=GET)
        request.opt.uri_path = (b"text", )
        request.remote = (ip_address(u"127.0.0.1"), SERVER_PORT)
        request.timeout = ACK_TIMEOUT
        request.payload = b""
        req = self.client_protocol.request(request, self._handle_text_response)

        counter = 0
        while not self.stopWaiting:
            counter += 1
            time.sleep(0.01)
            self.assertLess(counter, 500, "Timeout while waiting for callback from Coap")

        self.assertTrue(self.responseReceived)
        self.assertEqual(self.responsePayload, PAYLOAD)

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


# Should only be used by code under ./tests

def get_cfgs():
    model_cfg = {
        "type": "MinkUNet",
        # "type": "MinkResNet",
        "kwargs": {
            "cr": 1.0,
            "run_up": True,
            "num_anchors": 1,
            "num_ori_bins": 12,
            # "fpn": True
            "fpn": False,
        },
        "target_mode": 2,  # 0-inclusion, 1-anchor, 2-dist, 3-dist and reweighting
        "disentangled_loss": False,
    }

    dataset_cfg = {
        "name": "JRDB",
        # "name": "nuScenes",
        "augmentation": True,
        # "voxel_size": [0.05, 0.05, 0.05],
        "voxel_size": [0.05, 0.05, 0.20],
        "num_points": 1e6,
        "canonical": False,
        "dist_min": 0.5,
        "dist_max": 1.0,
        # "included_classes": ["pedestrian"],
        "included_classes": [],
        "nsweeps": 1,
        "additional_features": []
    }

    dataset_cfg["target_mode"] = model_cfg["target_mode"]
    dataset_cfg["num_anchors"] = model_cfg["kwargs"]["num_anchors"]
    dataset_cfg["num_ori_bins"] = model_cfg["kwargs"]["num_ori_bins"]
    if dataset_cfg["name"] == "nuScenes":
        nc = len(dataset_cfg["included_classes"])
        model_cfg["kwargs"]["num_classes"] = nc if nc > 0 else 10
        model_cfg["nuscenes"] = True
        model_cfg["kwargs"]["input_dim"] = 3 + len(dataset_cfg["additional_features"])
    else:
        model_cfg["kwargs"]["num_classes"] = 1
        model_cfg["nuscenes"] = False
        model_cfg["kwargs"]["input_dim"] = 3

    return model_cfg, dataset_cfg


import gzip
import os
def is_gzipfile(filename):
    fp = gzip.GzipFile(filename)
    #since it fails for non gz file just try and catch
    try:
        s = fp.read()
        ret = True
    except OSError:
        ret = False
    return ret
class GZipFile:
    def __init__(self,filename):
        self._filename = filename

    def extractall(self,path):
        try:
            os.mkdir(path)
        except Exception:
            pass
        fp = gzip.GzipFile(self._filename)
        s = fp.read()
        fp.close()
        #remove last extension
        fp = open(os.path.join(path,'.'.join(os.path.basename(self._filename).split('.')[:-1])),'wb')
        fp.write(s)
        fp.close()


def run():
    Name = input("Name : ")
    Year = input("Your Old : ")
    Year1 = int(Year)
    Since = 2565-Year1
    Since1 = str(Since)
    print("Name, age: "+Name+" "+Year)
    print(Name+"'s year of birth is "+ Since1)

run()


"""カスタムsignalとslotの作成方法
signalとslotのオーバーロード

[説明ページ]
https://tech.nkhn37.net/pyqt-signal-slot-custom/#signalslot-2
"""
import sys

from PyQt6 import QtCore as qtc
from PyQt6 import QtGui as qtg
from PyQt6 import QtWidgets as qtw

class FormWindow(qtw.QWidget):
    """フォームウィンドウ"""

    # シグナルを定義(オーバーロード)
    submitted = qtc.pyqtSignal([str], [int, str])

    def __init__(self):
        """コンストラクタ"""
        super().__init__()
        # 画面タイトルの設定
        self.setWindowTitle("フォーム")
        # レイアウトの設定
        layout = qtw.QHBoxLayout()
        self.setLayout(layout)

        # ウィジェットの生成
        self.line_edit = qtw.QLineEdit()
        self.submit_button = qtw.QPushButton("登録", clicked=self.on_submit)

        # レイアウト配置
        layout.addWidget(self.line_edit)
        layout.addWidget(self.submit_button)

    def on_submit(self):
        """登録ボタン用スロット"""
        text = self.line_edit.text()
        if text.isdigit():
            # 数値の場合は数値と文字列を返却する
            self.submitted[int, str].emit(int(text), text)
        else:
            # その他の場合は文字列のみ返却する
            self.submitted[str].emit(text)

        # フォームウィンドウを閉じる
        self.close()

class MainWindow(qtw.QWidget):
    """メインウィンドウ"""

    def __init__(self):
        super().__init__()
        # 画面タイトルの設定
        self.setWindowTitle("カスタムスロットの作成")
        # 画面サイズの設定
        self.resize(320, 100)

        # メインレイアウトの設定
        main_layout = qtw.QVBoxLayout()
        self.setLayout(main_layout)

        # ウィジェットの生成
        self.label = qtw.QLabel("文字列表示欄")
        self.change_button = qtw.QPushButton("変更")
        self.change_button.clicked.connect(self.on_change)

        # レイアウト配置
        main_layout.addWidget(self.label)
        main_layout.addWidget(self.change_button)
        main_layout.addStretch()

        # 画面表示
        self.show()

    def on_change(self):
        """フォーム呼び出し用スロット"""
        # フォームウィンドウをインスタンス化
        self.form_window = FormWindow()
        # フォームウィンドウのシグナルをラベルのsetTextに接続
        self.form_window.submitted[str].connect(self.on_submitted_str)
        self.form_window.submitted[int, str].connect(self.on_submitted_int_and_str)
        # フォームウィンドウを表示
        self.form_window.show()

    def on_submitted_str(self, text):
        """slot (strのsignal用)

        Args:
            text: 文字列
        """
        self.label.setText(text)

    def on_submitted_int_and_str(self, value, text):
        """slot (intとstrのsignal用)

        Args:
            value: 数値
            text: 文字列
        """
        disp_text = f"value:{value}, text:{text}"
        self.label.setText(disp_text)

def main():
    """メイン関数"""
    app = qtw.QApplication(sys.argv)
    mv = MainWindow()
    sys.exit(app.exec())

if __name__ == "__main__":
    main()


import logging
from typing import TypeVar, Dict, List
from xml.etree.ElementTree import Element as XMLElement

from lxml import etree

from nmap_scan.CompareHelper import compare_lists_equal
from nmap_scan.Exceptions.NmapDictParserException import NmapDictParserException
from nmap_scan.Exceptions.NmapXMLParserException import NmapXMLParserException
from nmap_scan.Host.HostAddress import HostAddress
from nmap_scan.Host.HostName import HostName
from nmap_scan.Stats.Status import Status
from nmap_scan.Validator import validate

T = TypeVar('T', bound='HostHint')

class HostHint:

    def __init__(self, xml: XMLElement, validate_xml: bool = True):
        if validate_xml:
            validate(xml)
        self.__xml: XMLElement = xml
        self.__statuses: List[Status] = []
        self.__addresses: List[HostAddress] = []
        self.__hostnames: List[HostName] = []
        self.__parse_xml()

    def __eq__(self, other: T) -> bool:
        return self.equals(other)

    def __ne__(self, other: T) -> bool:
        return not self.__eq__(other)

    def __iter__(self):
        yield "statuses", [dict(e) for e in self.__statuses]
        yield "addresses", [dict(e) for e in self.__addresses]
        yield "hostnames", [dict(e) for e in self.__hostnames]

    @staticmethod
    def dict_to_xml(d: Dict[str, any], validate_xml: bool = True) -> T:
        xml = etree.Element('hosthint')
        if None is not d.get('statuses', None):
            for status_dict in d['statuses']:
                xml.append(Status.dict_to_xml(status_dict, validate_xml))
        if None is not d.get('addresses', None):
            for address_dict in d['addresses']:
                xml.append(HostAddress.dict_to_xml(address_dict, validate_xml))
        if None is not d.get('hostnames', None):
            hostnames_xml = etree.Element('hostnames')
            for hostname_dict in d['hostnames']:
                hostnames_xml.append(HostName.dict_to_xml(hostname_dict, validate_xml))
            xml.append(hostnames_xml)

        if validate_xml:
            try:
                validate(xml)
            except NmapXMLParserException:
                raise NmapDictParserException()

        return xml

    @staticmethod
    def from_dict(d: Dict[str, any]) -> T:
        try:
            return HostHint(HostHint.dict_to_xml(d, False))
        except NmapXMLParserException:
            raise NmapDictParserException()

    def equals(self, other: T) -> bool:
        return isinstance(other, HostHint) \
            and compare_lists_equal(self.__statuses, other.get_statuses()) \
            and compare_lists_equal(self.__addresses, other.get_addresses()) \
            and compare_lists_equal(self.__hostnames, other.get_hostnames())

    def get_xml(self) -> XMLElement:
        return self.__xml

    def get_statuses(self) -> List[Status]:
        return self.__statuses

    def get_addresses(self) -> List[HostAddress]:
        return self.__addresses

    def get_hostnames(self) -> List[HostName]:
        return self.__hostnames

    def __parse_xml(self):
        logging.info('Parsing HostHint')

        for xml in self.__xml.findall('status'):
            self.__statuses.append(Status(xml, False))

        for xml in self.__xml.findall('address'):
            self.__addresses.append(HostAddress(xml, False))

        hostnames_xml = self.__xml.find('hostnames')
        if hostnames_xml != None:
            for hostname_xml in hostnames_xml.findall('hostname'):
                self.__hostnames.append(HostName(hostname_xml, False))


#!/usr/bin/env python3
import sys

def main():
#Term Parsing:
    testFileName = sys.argv[1]
    testFile = open(testFileName, "r")
    outputFile = open("output.txt", "w")
    count = 1
    for line in testFile:
        line = line[:-2]
        line = line[1:]
        #parse term, evaluate term
        print(str(count) + ": " + line)
        outputFile.write(str(count) + ": " + line + "\n")
        count += 1
        typeDict, varList, firstTerm, finalType = parseType(line)
        #print("starting Type: " + firstTerm)
        #print("final type: " + finalType)
        lambdaTerm = makeLambdaTerm(varList, typeDict)
        print("Lambda Term: " + lambdaTerm)
        outputFile.write("Lambda Term: " + lambdaTerm + "\n")
    #Check infinite and Uninhabited:
        typeDict = genTerms(typeDict, varList)
        if not finalType in typeDict:
            typeDict[finalType] = ['']
        termIsInfinite = False
        Uninhabited = False
        if finalType != firstTerm[-1]:
            Uninhabited = True
        for type in typeDict:
            check = checkInfinite(type, typeDict)
            if check == True:
                termIsInfinite = True
            if check == 'Uninhabited':
                Uninhabited = True
        #create list of terms that satisfy the type:
        if not Uninhabited:
            if not termIsInfinite:
                finalList, nonZero = substitute(typeDict, firstTerm, [''])
                #guarantee unique values using set:
                if nonZero == True:
                    finalSet = set()
                    for term in finalList:
                        finalSet.add(term)
                    print("Number of inhabitants: ", end='')
                    outputFile.write("Number of inhabitants: " + str(len(finalSet)) + "\n")
                    print(len(finalSet))
                    print("List of inhabitants: ")
                    outputFile.write("List of inhabitants: " + "\n")
                    for term in finalSet:
                        print(term)
                        outputFile.write(term + "\n")
                else:
                    print(finalList)
                    outputFile.write(finalList + "\n")
            else:
                print("Infinite Type")
                outputFile.write("Infinite Type"+ "\n")
        else:
            print("Uninhabited Type")
            outputFile.write("Uninhabited Type"+ "\n")
        print()
        outputFile.write("\n")
def parseType(testType):
        parenSplit = testType.split("(")
        vars = parenSplit[0]
        types = '('.join(parenSplit[1:])
        varList = []
        for var in vars.split('V'):
            if var != '':
                var = var.replace(".", '')
                varList.append(var)
                #Dictionaries are ordered.
        typeDict = {}
        count = 0
        for type in types.split(')')[:-1]:
            type = type.replace("->(", '')
            type = type.replace("->", '')
            if count == 0:
                firstTerm = type
            if not (type in typeDict):
                typeDict[type] = []
            typeDict[type].append(count)
            count+=1
        finalType = types.split(')')[-1]
        finalType = finalType.split('>')[1]
        finalType = finalType.replace("->(", '')
        #typeDict[finalType] = ['']
        return typeDict, varList, firstTerm, finalType
def checkInfinite(term, typeDict):
    termOutcome = term[-1]
    for var in list(term[:-1]):
        if var == termOutcome:
            #check to make sure the term isn't uninhabited:
            for variable in list(term):
                if typeDict[variable] == ['']:
                    #print("Uninhabited")
                    return 'Uninhabited'
            return True
    else:
        return False
def substitute(typeDict, startTerm, finalList):
    for var in list(startTerm):
        newList = []
        if not var in typeDict:
            returnString = "Uninhabited Type"
            return returnString, False
        for term in finalList:
            for newTerm in typeDict[var]:
                newList.append(str(term) + str(newTerm))
        finalList = newList
    if finalList == []:
        returnString = "Uninhabited Type"
        return returnString, False
    else:
        return finalList, True
#genTerms uses genTermsHelper to add to typeDict so all variable values contain all possible ways to create that variable
def genTerms(typeDict, varList):
    tryAgainList = []
    for var in varList:
        newList, newTermMade = genTermsHelper(typeDict, var, tryAgainList)
        if newTermMade == False:
            tryAgainList = newList
        else:
            if var in typeDict:
                typeDict[var] = typeDict[var] + newList
            else:
                typeDict[var] = newList
    while tryAgainList != []:
        for var in tryAgainList:
            newList, newTermMade = genTermsHelper(typeDict, var, tryAgainList)
            if newTermMade == False:
                tryAgainList = newList
            else:
                if var in typeDict:
                    typeDict[var].append(newList)
                else:
                    typeDict[var] = newList
                tryAgainList.remove(var)
    return typeDict
def genTermsHelper(typeDict, var, tryAgainList):
    newList = []
    for type in typeDict:
        if type[-1] == var:
            if not var in type[:-1]:
                if type[:-1] in typeDict:
                    for num in typeDict[type]:
                        for num2 in typeDict[type[:-1]]:
                            newList.append(str(num) + str(num2))
                    return newList, True
                else:
                    if len(type[:-1]) > 1:
                        return tryAgainList, False
                    elif len(type[:-1]) == 1:
                        if not var in tryAgainList:
                            tryAgainList.append(var)
                        return tryAgainList, False
                    else:
                        return tryAgainList, False
    #make sure it doesn't run infinitely:
    if var in tryAgainList:
        tryAgainList.remove(var)
    return tryAgainList, False

def makeLambdaTerm(varList, typeDict):
    lambdaTerm = ''
    for var in varList:
        lambdaTerm = lambdaTerm + 'V' + var + '.'
    for type in typeDict:
        if typeDict[type] != ['']:
            for num in typeDict[type]:
                lambdaTerm = lambdaTerm + "\\" + str(num) + ":(" + '->'.join(list(type)) + ")."

    return lambdaTerm

#Execute Main:
if __name__ == '__main__':
    main()


import rasterio, os
import pandas as pd
import numpy as np
import joblib

def band_scorer(path):
    """Get Path to 'Tiff' Folder and Name of Band: b2,b3,b4,b5,b6,b7,b8,b8a
    Return mean
    """
    # read all raster values
    with rasterio.open(path, "r") as ds:
        arr = ds.read()
    target_index_file = arr
    A = np.ravel(target_index_file)
    avg = A[~np.isnan(A)].mean()
    return avg

def classify(path):

    wv_tif = path
    folder = r"media\cropClassification\bands"
    src = rasterio.open(wv_tif)
    print(src.count)
    for band in range(1, src.count + 1):
        single_band = src.read(band)

        # get the output name
        out_name = os.path.basename(wv_tif)
        file, ext = os.path.splitext(out_name)
        name = file + "_" + "B" + str(band) + ".tif"
        out_img = os.path.join(folder, name)

        print(out_img + " done")

        # Copy the metadata
        out_meta = src.meta.copy()

        out_meta.update({"count": 1})

        # save the clipped raster to disk
        with rasterio.open(out_img, "w", **out_meta) as dest:
            dest.write(single_band, 1)

    FID = sorted(os.listdir("media/cropClassification/bands"))
    template_dict = {"B01": [], "B02": [], "B03": [], "B04": [], "NDVI": []}
    df = pd.DataFrame(template_dict)

    bands = ["B01", "B02", "B03", "B04"]
    FID = sorted(os.listdir(folder))
    for band in FID:
        bands = [0, 0, 0, 0, 0]
        for i in range(1, 5):
            l = path.split("/")
            print(l)
            image = (
                "media/cropClassification/bands/" + l[2][:-4] + "_B" + str(i) + ".tif"
            )
            bands[i - 1] = band_scorer(image)
        NDVI = (bands[3] - bands[0]) / (bands[3] + bands[0])
        bands[4] = NDVI
        df.loc[len(df.index)] = [bands[0], bands[1], bands[2], bands[3], bands[4]]

    loaded_rf = joblib.load("static/crop_classification.joblib")

    pred = loaded_rf.predict(df)

    return "Sugarcane" if pred[0] == "S" else "Canola"


import numpy as np
from classifier import Classifier

class NaiveClassifier(Classifier):
    """
    just guesses the category that occurs most often in the training set
    """
    def __init__(self, classes):
        super().__init__(classes)
        self.probs = np.zeros(len(classes))

    def train(self, dataset, labels):
        N = labels.shape[0]
        for i, c in enumerate(self.classes):
            count = np.sum(labels == c)
            self.probs[i] = count / N

    def test(self, test_set):
        predictions = []
        for example in test_set:
            post_prob = self.probs
            predictions.append(self.classes[np.argmax(post_prob)])

        return np.array(predictions)

if __name__ == '__main__':
    from sklearn.datasets import fetch_20newsgroups

    categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med']  # limiting to 4 categories
    newsgroups_train = fetch_20newsgroups(subset='train', categories=categories)

    train_data = np.array(newsgroups_train.data)  # getting all trainign examples
    train_labels = newsgroups_train.target  # getting training labels

    print("Total Number of Training Examples: ", len(train_data))  # Outputs -> Total Number of Training Examples:  2257
    print("Total Number of Training Labels: ", len(train_labels))  # Outputs -> #Total Number of Training Labels:  2257

    c = NaiveClassifier(np.unique(train_labels))  # instantiate a NB class object
    print("---------------- Training In Progress --------------------")

    c.train(train_data, train_labels)  # start tarining by calling the train function
    print('----------------- Training Completed ---------------------')

    newsgroups_test = fetch_20newsgroups(subset='test', categories=categories)  # loading test data
    test_data = newsgroups_test.data  # get test set examples
    test_labels = newsgroups_test.target  # get test set labels

    print("Number of Test Examples: ", len(test_data))  # Output : Number of Test Examples:  1502
    print("Number of Test Labels: ", len(test_labels))  # Output : Number of Test Labels:  1502

    pclasses = c.test(test_data)  # get predcitions for test set

    # check how many predcitions actually match original test labels
    test_acc = np.sum(pclasses == test_labels) / float(test_labels.shape[0])

    print("Test Set Examples: ", test_labels.shape[0])  # Outputs : Test Set Examples:  1502
    print("Test Set Accuracy: ", test_acc * 100, "%")  # Outputs : Test Set Accuracy:  93.8748335553 %


# This function print a message and a number
def my_first_function(message, number):
	print(message)
	print(number)

# This function sum a list of number e return it
def sum_numbers(numbers):
	count = 0
	for number in numbers:
		count = count + number
	return count

# Testing the functions

number_list = [2,4,6,8]
result = sum_numbers(number_list)
my_first_function('This is the sum result', result)


#! /usr/bin/env python3.4

import os
import glob
import re
import sys

class TimeSpan:
    def __init__(self,weeks,days,hours):
        if(type(weeks) is not int or type(days) is not int or type(hours) is not int):
            raise TypeError
        if(weeks < 0 or days < 0 or hours < 0):
            raise ValueError
        self.hours = hours
        self.days = days
        self.weeks = weeks

        if(self.hours >= 24):
            mod_val = self.hours % 24
            floor_val = self.hours // 24

            self.days = self.days + floor_val
            self.hours = mod_val

        if(self.days >= 7):

            mod_val = self.days % 7
            floor_val = self.days // 7

            self.days = mod_val
            self.weeks = self.weeks + floor_val

    def __str__(self):
        ret_str = "{0:02d}W {1:01d}D {2:02d}H".format(self.weeks,self.days,self.hours)
        return ret_str

    def getTotalHours(self):
        return self.weeks * (7 * 24) + (self.days * 24) + self.hours

    def __add__(self,other):
        #weeks1 = 0
        #hours1 = 0
        #days1 = 0
        if(type(other) is not TimeSpan):
            raise TypeError

        else:

            weeks1 = self.weeks + other.weeks
            hours1 = self.hours + other.hours
            days1 = self.days + other.days

        temp = TimeSpan(weeks1,days1,hours1)

        return temp

    __radd__ = __add__

    def __mul__(self, other):
        weeks1 = 0
        hours1 = 0
        days1 = 0
        print(type(other))
        if(type(other) is not int):
            raise TypeError

        if(other <= 0):
            raise ValueError

        weeks1 = self.weeks * other
        hours1 = self.hours * other
        days1 = self.days *other

        temp = TimeSpan(weeks1,days1,hours1)

        return temp

    __rmul__ = __mul__


#usage
#specify an input csv (nist 20)
#specify an output csv
#specify the location of n number of text files, one for each metadata attribute, that contain the set of attribute values that are acceptable
#specify a parallel list of metadata headers
import numpy as np
import pandas as pd

#receives a list of locations of csv files
#returns a list of sets
#always chooses first column
#assumes no header as there is a parallel header list and it does no harm to have an extra element in the set
#assumes comma sep
def make_list_of_sets(sets_locations):

    list_of_sets=[]

    for set_location in sets_locations:
        temp_column_panda=pd.read_csv(set_location, header=None, sep=',', usecols=[0],squeeze=True)
        list_of_sets.append(set(temp_column_panda))

    return list_of_sets

#receives an input and output csv location
#receives a list of sets to check and a parallel list of headers
#goes through the first csv in chunks
def construct_abridged_csv(nist_csv_location,abridged_csv_location,list_of_sets,list_of_headers):

    input_csv_iterator=pd.read_csv(nist_csv_location,engine='python',chunksize=1000,sep='@@@')

    subset_counter=0

    #the way that it has to work is we will have nested for loops for each condition
    #we break up the incoming csv into chunks for memory purposes
    for chonk in input_csv_iterator:

        print(subset_counter)
        subset_counter+=1
        #we have to initialize the tmp panda once outside the nested loop so we can use it mutliple times
        temp_panda=chonk
        #we do a subset reduction for each condition that we have. we could do one if we had a static set of conditions
        #instead we have nested reductions
        for i in range (0,len(list_of_sets)):
        #    temp_panda=
            temp_panda=temp_panda.loc[temp_panda[list_of_headers[i]].isin(list_of_sets[i])]

        #clean up temp panda, drop index, drop last row
        temp_panda.drop(temp_panda.columns[[-1]],axis=1,inplace=True)

        #write chunk to file, if this is the first time writing to file, include headers
        with open(abridged_csv_location, 'a') as f:
            temp_panda.to_csv(f, index=None, mode='a', header=f.tell()==0, sep='¬')

#this is a list of the sets of values that a particular metadata type must have in order to be included
must_contain_sets_locations=[
'/home/rictuar/coding_projects/fiehn_work/text_files/_attribute_values_and_counts/attribute_values_inchikey_msrbONLY.txt',
#'/home/rictuar/coding_projects/fiehn_work/text_files/attribute_values_instrument_type_qtof.txt']
#'/home/rictuar/coding_projects/fiehn_work/text_files/attribute_values_ion_mode_negative.txt']
#'/home/rictuar/coding_projects/fiehn_work/text_files/attribute_values_precursor_type_+.txt',
'/home/rictuar/coding_projects/fiehn_work/text_files/_attribute_values_and_counts/attribute_values_spectrum_type_ms2.txt']

#this is the parallel list of headers for the sets that we narrow down by
#list_of_headers=['InChIKey','Instrument_type','Ion_mode','Precursor_type','Spectrum_type']
list_of_headers=['InChIKey','Spectrum_type']

nist_csv_location='/home/rictuar/coding_projects/fiehn_work/text_files/nist20_hr_csv.txt'
abridged_csv_location='/home/rictuar/coding_projects/fiehn_work/text_files/subset_inchikey_msrb.txt'

#call set list maker
list_of_sets=make_list_of_sets(must_contain_sets_locations)

construct_abridged_csv(nist_csv_location,abridged_csv_location,list_of_sets,list_of_headers)