'''
Hausaufgabe 7
NAME1 MATRIKELNUMMER: Nijat Aghayev 108015250476
NAME2 MATRIKELNUMMER: Mike Josaf 108014224341
'''

'''
1

Schreiben Sie die Programm-Stücke aus den Teilaufgaben 2, 3 und 4
der 5. Hausaufgabe mit regulären Ausdrücken und ohne Listenabstraktionen.
(Sie können dafür bei Teilaufgabe 2 die Kommentarvorgabe ignorieren oder
nur an einigen Stellen ersetzen)
Achten Sie darauf, dass die Ein- und Ausgabe identisch zu der Lösung
von Hausaufgabe 5 (wie in der Übung besprochen und in der Korrektur
angegeben) sein soll.

'''

'''
5.2

Schreiben Sie ein Programm zu folgendem Kommentar. Nutzen Sie dabei an der mit * markierten Stelle Listen-Abstraktion
'''
import re
# Textdatei vorlage.txt oeffnen und verarbeiten
filename = 'vorlage.txt'
infile =  open(filename)

# Gib alle Woerter einer Zeile, deren dritter Buchstabe ein Vokal ist
# umgekehrt sortiert aus
# Fuer jede Zeile der Datei
# Die gefundene Woerter werden in words speichert
words = []
# pattern match-et alle Woerter, deren dritter Buchstabe ein Vokal ist.
pattern = "^\w{2}[aeiouyäöüAEIOUYÄÖÜY]\w*$"
prog = re.compile(pattern)
for line in infile:
    # Teile die Zeile in Worte
    splitted = line.split()
    for token in splitted:
        # * Fuer jedes Wort: Speichere das Wort in Reserveliste,
        # wenn der dritte Buchstabe ein Vokal ist
        if prog.search(token):
            words.append(token)
# Gib Reserveliste rueckwaerts alphabetisch sortiert aus
words.sort(reverse=True)
print("<<umgekehrt sortierte Liste>>")
for word in words:
    print(word)

# Datei wird geschlossen.
infile.close()

# Gib die Datei Zeilenweise unveraendert aus
print("\n<<Inhalt der Datei>>")
with open(filename) as infile:
    for line in infile:
        print(line, end='')

'''
5.3
Kommentieren Sie folgendes Programm und aendern Sie die Variablennamen in
sprechende Namen:

'''
print()
print("<<Teil 3>>")
# 0 and 5 werden als string in s_random_numbers set gespeichert.
s_random_numbers = {'0', '5'}

# Sequenz von 0 bis 10(ausschliesslich) werden iteriert und mit jedem Element dieser Sequenz
# wird neue Zahl erstellt.
# Diese Zahl wird als string in s_random_numbers gespeichert.
for z in range(0,10):
    s_random_numbers.add(str(int(5*z/35*(4+3))))

# third_words wird eine Liste als einziges Element enthalten. Dieses eniziges Element wird
# das dritte Wort  aller Zeilen von datei.txt enthalten ,
# dessen erste Wort in s_random_numbers vorhanden ist.
third_words = []

# Die Datei "datei.txt" wird fuers Lesen geoeffnet und mit "with" wird die geoffnete Datei
# automatisch geschlossen.
with open('datei.txt') as infile:

    # pattern = ^(9|7|0|5|1|8|6|4|2|3)\s+  wird konstruiert.
    pattern = "^("
    for number in s_random_numbers:
        pattern += str(number) + "|"
    pattern = pattern[0:len(pattern)-1] + ")\s+"

    # pattern wird kompiliert und in prog gespeichert.
    prog = re.compile(pattern)

    # infile wird Zeile fuer Zeile gelesen
    for line in infile:
        # Wenn pattern zutrifft , wird das dritte Wort der Zeile in die third_words hinzugefuegt.
        if prog.search(line):
            third_words.append(line.split()[2])

# third_words wird ausgegeben.
print("third_words als Liste der Liste : ", third_words)
print()

'''
5.4
# Nutzen Sie eine Datei '5_text.txt'
# Lesen Sie die Datei ein und tokenisieren Sie den Text
# unter der vereinfachenden Annahme, dass alle Wort-initialen
# und -finalen Sonderzeichen ein eigenes Token darstellen.

# Speichern Sie die Tokens in einer geeigneten Datenstruktur ab.

# Schreiben Sie schliesslich alle Woerter, die einen
# Grossbuchstaben enthalten, alphabetisch sortiert
# in eine Datei namens '4_capitalized.txt' im gleichen
# Verzeichnis,
# im Format 1 Wort pro Zeile.
'''

# Name der Eingabedatei
infile_name = '5_text.txt'
# Name der Ausgabedatei
outfile_name = '4_capitalized.txt'
# Die gefundene Woerter (die Woerter , die einen Grossbuchstaben haben) werden  in capitalized_words gespeichert.
capitalized_words = []
# Alle tokens werden in token_list gespeichert.
token_list = []
# Infile wird fuers Lesen geoeffnet.
with open(infile_name) as infile:
    # (\W+) bedeutet non-word Charakter , alle Zeichen ausser : [a-zA-Z0-9-] und () sichert , dass
    #  non-word Charakter auch als token betrachtet wird.
    pattern = "(\W+)"
    # pattern wird kompiliert und in prog gespeichert.
    prog = re.compile(pattern)
    # infile wird Zeile fuer Zeile gelesen.
    for line in infile:
        # line wird gesplitted und der splitted zugewiesen
        splitted = prog.split(line)
        # splitted wird iteriert
        for token in splitted:
            # fuehrende und schliessende whitespace-s werden aus token entfernt
            token = token.strip()
            # Wenn token ein empty string ist , wird es ignoriert.
            if token == '':continue
            # sonst token wird in die token_list hinzugefuegt.
            token_list.append(token)

# pattern matches die Woerter , die aus \w (alpha-numerischen) Zeichen bestehen , und deren nur einiziger Buchstabe gross ist.
# Bemerkung: pattern fuer die Woerter mit mehr als oder gleich 1 Grossbuchstaben:
# pattern = "^[a-z0-9-]*[A-Z]+[a-z0-9-]*$"
pattern = "^[a-z0-9-]*[A-Z][a-z0-9-]*$"
# pattern wird kompiliert und in prog gespeichert.
prog = re.compile(pattern)
# token_list wird iteriert.
for token in token_list:
    # wenn prog zutrifft , token wird in capitalized_words hinzugefuegt
    if prog.search(token):
        capitalized_words.append(token)

# capitalized_words wird aufsteigend sortiert
capitalized_words.sort()
# outfile wird fuers Schreiben geoffnet
with open(outfile_name, "w") as outfile:
    # capitalized_words wird iteriert
    for word in capitalized_words:
        # word wird in outfile geschrieben.
        outfile.write(word +"\n")

'''
2

a) Schreiben Sie ein kurzes Programm, das eine Datei mit einem deutschen
Beispieltext einliest und zwei Listen ausgibt:
Eine mit allen Nomen, eine mit allen Adjektiven aus dem Text.

Achtung: Sie werden kein 100 %iges Ergebnis für alle möglichen Eingaben
erhalten. Es geht bei dieser Aufgabe darum, durch linguistisch sinnvolle
Kriterien ein möglichst gutes Ergebnis zu erzielen.

b) Testen Sie Ihr Programm an folgendem Text:
"In den vergangenen Jahren haben wir uns mit vielen, schönen und bunten
Themen beschäftigen können. Wir haben unterschiedliche Kriterien anwenden
können und mit Begeisterung am 27.06.2017 den 364. König krönen können.
Begeistert waren auch die bunt gekleideten Besucher, die sich gerne zeigten.
Gewiss, ich schreibe diesen Bericht der Ordnung zuliebe nieder, aus einer
gewissen Pedanterie heraus, damit er zu den Akten komme. Ich will mich
zwingen, noch einmal die Ereignisse zu überprüfen, die zum Freispruch
eines Mörders und zum Tode eines Unschuldigen geführt haben. (Er meint
mehr als zwei Unschulde, aber hier zählen nur reiche, alte Herren.)
"

Vergleichen Sie die Zahl der richtig zugeordneten Nomen/Adjektive mit denen,
die Sie per Hand im Text finden können.
Kommentieren Sie beide Ergebnisse in jeweils 2-3 Sätzen.
'''

# clear_artikel
# Entfernen der Artikel aus der Eingabeliste
# Argument: Eingabeliste
# Rueckgabewert: "bereinigte" Liste
def clear_artikel(input_list):
    # Liste der Artikel
    artikel_list = ['ein', 'eines', 'einem', 'einen',
                    'eine', 'einer',
                    'der', 'des', 'dem', 'den',
                    'die', 'das']

    # pattern = ^(ein|eines|einem|einen|eine|einer|der|des|dem|den|die|das)$
    pattern = r"^("
    for artikel in artikel_list:
        pattern += artikel+ "|"
    pattern = pattern[0:len(pattern)-1] +")$"

    # pattern wird kompiliert und in prog gespeichert.
    prog = re.compile(pattern, re.IGNORECASE)

    # Rueckgabewert : Liste
    res = []

    # input_list wird iteriert
    for token in input_list:
        # wenn prog zutrifft , token wird ignoriert
        if prog.search(token):
            continue
        # sonst token wird in res hinzugefuegt
        else:
            res.append(token)

    # res wird zurueckgegeben.
    return res

# clear_pronomen
# Entfernen der Pronomen aus der Eingabeliste
# Argument: Eingabeliste
# Rueckgabewert: "bereinigte" Liste
def clear_pronomen(input_list):
    # Liste der Pronomen
    pronomen_list = ["ich", "du", "er", "sie", "es", "wir", "ihr", "sie",
                     "mein", "dein", "sein", "ihr", "unser", "euer",
                     "mich", "dich", "sich", "uns", "euch",
                     "jemand", "alle", "einer", "manche", "man", "wer", "etwas",
                     "einige", "andere",
                     "keiner", "nimeand", "nichts",
                     "der", "die", "das", "dieser", "diese", "dieses", "jener",
                     "jene", "jenes", "derjenige", "diejenige", "dasjenige",
                     "derselbe", "dieselbe", "dasselbe",
                     "wer", "was", "wessen", "welcher",
                     "deren", "einander",
                     "meine", "deine", "seine", "ihre", "unsere", "eure",
                     "jemandem", "jemander", "jemandes",
                     "desjenigen", "demjenigen", "denjenigen",
                     "derjenigen",
                     "desselben", "demselben",
                     "diese(?:r|n|m|s)?"]

    # pattern = ^(ich|du|er|sie|es|wir|ihr|sie|mein|dein|sein|ihr|unser|euer|mich|
    # dich|sich|uns|euch|jemand|alle|einer|manche|man|wer|etwas|einige|andere|keiner|
    # nimeand|nichts|der|die|das|dieser|diese|dieses|jener|jene|jenes|derjenige|diejenige|
    # dasjenige|derselbe|dieselbe|dasselbe|wer|was|wessen|welcher|deren|einander|meine|deine|
    # seine|ihre|unsere|eure|jemandem|jemander|jemandes|desjenigen|demjenigen|denjenigen|derjenigen|
    # desselben|demselben|diese(?:r|n|m|s)?)$
    pattern = r"^("
    for pronomen in pronomen_list:
        pattern += pronomen + "|"

    pattern = pattern[0:len(pattern)-1] +")$"

    # pattern wird kompiliert und in prog gespeichert.
    prog = re.compile(pattern,re.IGNORECASE)

    # Rueckgabewert: Liste
    ret = []

    # input_list wird iteriert
    for token in input_list:
        # wenn prog zutrifft , token wird ignoriert
        if prog.search(token): continue
        # sonst token wird in ret hinzugefuegt.
        else: ret.append(token)

    # ret wird zurueckgegeben.
    return ret

# clear_numerale
# Entfernen der Numeralen aus der Eingabeliste
# Argument: Eingabeliste
# Rueckgabewert: "bereinigte" Liste
def clear_numerale(input_list):
    # Liste der Numeralen
    numeral_list = ["[0-9]+", "eins", "zwei", "drei", "vier", "fünf", "sechs", "sieben", "acht", "neun", "zehn",
                    "elf", "zwölf",
                    "erste[smn]?", "zweite[smn]?", "dritte[smn]?", "vierte[smn]?", "fünfte[smn]?",
                    "sechste[smn]?", "siebte[smn]?", "achte[smn]?", "neunte[smn]?", "zehnte[smn]?",
                    "(drei|vier|fünf|sech|sieb|acht|neun)[zehn|zig]", "zwanzig", "hundert", "tausend",
                    "(ein|zwei|drei|vier|fünf|sechs|sieben|acht|neun)und[a-z]+",
                    "(ein|zwei|drei|vier|fünf|sechs|sieben|acht|neun)(mal|fach)",
                    "viel(?:en|e)?"]

    # pattern =  ^([0-9]+|eins|zwei|drei|vier|fünf|sechs|sieben|acht|neun|
    # zehn|elf|zwölf|erste[smn]?|zweite[smn]?|dritte[smn]?|vierte[smn]?|fünfte[smn]?|
    # sechste[smn]?|siebte[smn]?|achte[smn]?|neunte[smn]?|zehnte[smn]?|(drei|vier|fünf|
    # sech|sieb|acht|neun)[zehn|zig]|zwanzig|hundert|tausend|(ein|zwei|drei|vier|fünf|sechs|
    # sieben|acht|neun)und[a-z]+|(ein|zwei|drei|vier|fünf|sechs|sieben|acht|neun)(mal|fach)|
    # viel(?:en|e)?)$
    pattern = "^("
    for numeral in numeral_list:
        pattern += numeral + "|"

    pattern = pattern[0:len(pattern)-1] +")$"

    # pattern wird kompiliert und in prog gespeichert.
    prog = re.compile(pattern, re.IGNORECASE)

    # Rueckgabewert: Liste
    ret = []

    # input_list wird iteriert.
    for token in input_list:
        # wenn prog zutrifft , token wird ignoriert.
        if prog.search(token):continue
        # sonst token wird in ret hinzugefuegt.
        else: ret.append(token)

    # ret wird zurueckgegeben.
    return ret

# clear_konjunktion
# Entfernen der Konjunktionen aus der Eingabeliste
# Argument: Eingabeliste
# Rueckgabewert: "bereinigte" Liste
def clear_konjunktion(input_list):
    # Liste der Konjunktionen
    konjuktion_list = ["während", "indem", "indes", "indessen",
                       "solange", "sowie", "sooft", "als", "wie",
                       "nachdem", "wenn", "sobald", "sowie", "seit",
                       "seitdem", "bis", "bevor", "ehe", "selten",
                       "indem", "soweit", "insoweit", "sofern", "insofern",
                       "soviel", "während", "wohingegen", "als", "ob",
                       "weil", "da", "zumal", "nun", "dass",
                       "sodass", "falls", "sofern", "soweit",
                       "obgleich", "obwohl", "obschon", "obzwar", "wenngleich",
                       "wennschon", "wiewohl", "ungeachtet", "gleichwohl",
                       "damit", "und"]

    # pattern =  ^(während|indem|indes|indessen|solange|sowie|sooft|als|wie|nachdem|wenn|
    # sobald|sowie|seit|seitdem|bis|bevor|ehe|selten|indem|soweit|insoweit|sofern|insofern|
    # soviel|während|wohingegen|als|ob|weil|da|zumal|nun|dass|sodass|falls|sofern|soweit|
    # obgleich|obwohl|obschon|obzwar|wenngleich|wennschon|wiewohl|ungeachtet|gleichwohl|
    # damit|und)$
    pattern = r"^("
    for konkuktion in konjuktion_list:
        pattern += konkuktion + "|"
    pattern = pattern[0:len(pattern)-1] +")$"

    # pattern wird kompiliert und in prog gespeichert.
    prog = re.compile(pattern,re.IGNORECASE)
    # Rueckgabewert: Liste
    ret = []
    # input_list wird iteriert
    for token in input_list:
        # wenn prog zutrifft , token wird ignoriert
        if prog.search(token): continue
        # sonst token wird in ret hinzugefuegt.
        else: ret.append(token)
    # ret wird zurueckgegeben.
    return ret

# clear_praeposition
# Entfernen der Praepositionen aus der Eingabeliste
# Argument: Eingabeliste
# Rueckgabewert: "bereinigte" Liste
def clear_praeposition(input_list):
    # Liste der Praepositionen
    praeposition_list = ["ab", "aus", "von",
                         "an", "am" , "auf", "außer", "bei", "gegenüber", "hinter", "in",
                         "neben", "über", "unter", "vor", "zwischen",
                         "abseits", "außerhalb", "diesseits", "entlang", "inmitten",
                         "innerhalb", "jenseits", "längs", "oberhalb", "unterhalb", "unweit",
                         "an", "auf", "bis", "durch", "gegen", "hinter", "neben", "vor",
                         "nach", "ab", "bei", "mit", "von", "zu(?:r|m)?", "bis", "gegen",
                         "binnen", "in", "seit", "außerhalb", "innerhalb", "während",
                         "angesichts", "anlässlich", "auf", "aufgrund", "aus", "behufs",
                         "bei", "betreffs", "bezüglich", "dank", "durch", "für", "gemäß", "halber",
                         "infolge", "laut", "mangels", "mit", "mittels", "seitens", "trotz", "um",
                         "unbeschadet", "ungeachtet", "vermittels", "vermöge", "wegen", "zufolge",
                         "zwecks",
                         "abzüglich", "auf", "aus", "ausschließlich", "außer", "bei", "bis",
                         "an", "einscgließlich", "mitsamt", "nebt", "ohne", "samt", "statt",
                         "anstatt", "wider", "zuwider", "zuzüglich"]

    # pattern =  ^(ab|aus|von|an|am|auf|außer|bei|gegenüber|hinter|in|neben|über|unter|vor|zwischen|abseits|
    # außerhalb|diesseits|entlang|inmitten|innerhalb|jenseits|längs|oberhalb|unterhalb|unweit|an|auf|
    # bis|durch|gegen|hinter|neben|vor|nach|ab|bei|mit|von|zu(?:r|m)?|bis|gegen|binnen|in|seit|
    # außerhalb|innerhalb|während|angesichts|anlässlich|auf|aufgrund|aus|behufs|bei|betreffs|
    # bezüglich|dank|durch|für|gemäß|halber|infolge|laut|mangels|mit|mittels|seitens|trotz|um|
    # unbeschadet|ungeachtet|vermittels|vermöge|wegen|zufolge|zwecks|abzüglich|auf|aus|ausschließlich|
    # außer|bei|bis|an|einscgließlich|mitsamt|nebt|ohne|samt|statt|anstatt|wider|zuwider|zuzüglich)$
    pattern = r"^("
    for praeposition in praeposition_list:
        pattern += praeposition + "|"

    pattern = pattern[0:len(pattern)-1] +")$"

    # pattern wird kompiliert und in prog gespeichert.
    prog = re.compile(pattern, re.IGNORECASE)
    # Rueckgabewert: Liste
    ret = []

    # input_list wird iteriert.
    for token in input_list:
        # if prog zutrifft , token wird ignoriert.
        if prog.search(token):continue
        # sonst token wird in ret hinzugefuegt
        else: ret.append(token)
    # ret wird zurueckgegeben.
    return ret

# clear_interjektion
# Entfernen der Interjektionen aus der Eingabeliste
# Argument: Eingabeliste
# Rueckgabewert: "bereinigte" Liste
def clear_interjektion(input_list):
    # Liste der Interjektionen
    interjektion_list = ["ach", "au", "pfui", "hä\?", "haha", "hey", "brr", "igit"]

    # pattern =  ^(ach|au|pfui|hä\?|haha|hey|brr|igit)$
    pattern = r"^("
    for interjektion in interjektion_list:
        pattern += interjektion + "|"

    pattern = pattern[0:len(pattern)-1]+")$"

    # pattern wird kompiliert und in prog gespeichert
    prog = re.compile(pattern, re.IGNORECASE)

    # Rueckgabewert : Liste
    ret = []

    # input_list wird iteriert
    for token in input_list:
        # wenn prog zutrifft , token wird ignoriert
        if  prog.search(token) : continue
        # sonst token wird in ret hinzugefuegt.
        else: ret.append(token)

    # ret wird zurueckgegeben.
    return ret

# clear_modal_und_hilfs_verben
# Entfernen der Modal- und Hilfsverben aus der Eingabeliste
# Argument: Eingabeliste
# Rueckgabewert: "bereinigte" Liste
def clear_modal_und_hilfs_verben(input_list):
    # Liste der Modal- und Hilfsverben
    modal_und_hilfs_verbe_list = ["dürfen", "können", "mögen", "müssen", "sollen", "wollen",
                  "darf(?:st)?", "durfte(?:st)?", "dürfte(?:st)?", "gedurft",
                  "kann(?:st)?", "konnte(?:st)?", "könnte(?:st)?", "gekonnt",
                  "mag(?:st)?", "mochte(?:st)?", "möchte(?:st)?", "gemocht",
                  "musst?", "musste(?:st)?", "müsste(?:st)?", "gemusst",
                  "soll(?:st)?", "sollte(?:st)?", "gesollt",
                  "will(?:st)?", "wollte(?:st)?", "gewollt",
                  "haben", "sein", "werden",
                  "habe", "hast", "hat", "hatte(?:st|n)?", "hätte(?:st|n)?", "hab", "habt", "gehabt",
                  "bin", "bist", "ist", "sind", "war(?:st|en)?", "wäre(?:st|n)?", "sei", "seid", "gewesen",
                  "werde", "wirst", "wird", "wurde(?:st|n)?", "würde(?:st|n)?", "ward",
                  "(?:ge)?worden", "aber"
                  ]

    # pattern =  ^(dürfen|können|mögen|müssen|sollen|wollen|darf(?:st)?|durfte(?:st)?|dürfte(?:st)?|
    # gedurft|kann(?:st)?|konnte(?:st)?|könnte(?:st)?|gekonnt|mag(?:st)?|mochte(?:st)?|möchte(?:st)?|
    # gemocht|musst?|musste(?:st)?|müsste(?:st)?|gemusst|soll(?:st)?|sollte(?:st)?|gesollt|will(?:st)?|
    # wollte(?:st)?|gewollt|haben|sein|werden|habe|hast|hat|hatte(?:st|n)?|hätte(?:st|n)?|hab|habt|
    # gehabt|bin|bist|ist|sind|war(?:st|en)?|wäre(?:st|n)?|sei|seid|gewesen|werde|wirst|wird|
    # wurde(?:st|n)?|würde(?:st|n)?|ward|(?:ge)?worden|aber)[.,]?$
    pattern = "^("
    for verb in modal_und_hilfs_verbe_list:
        pattern += verb + "|"

    pattern = pattern[0:len(pattern)-1] + ")[.,]?$"

    # pattern wird kompiliert und in prog gespeichert.
    prog = re.compile(pattern, re.IGNORECASE)
    # Rueckgabewert: Liste
    ret = []

    # input_list wird iteriert
    for token in input_list:
        # wenn prog zutrifft , token wird ignoriert
        if prog.search(token): continue
        # sonst token wird in ret hinzugefuegt.
        else: ret.append(token)

    # ret wird zurueckgegeben.
    return ret

# clear_adverb
# Entfernen der Adverbien aus der Eingabeliste
# Argument: Eingabeliste
# Rueckgabewert: "bereinigte" Liste
def clear_adverb(input_list):
    # Liste der Adverbien
    adverb_list = ["hier", "da", "links", "vorne", "hinten", "überall",
                   "hoch", "vorwärts", "abwärts", "dorthin", "umher", "herum",
                   "herunter", "dorther", "herab", "herunter", "hindurch",
                   "nachdem", "sobald", "während", "solange", "bevor", "bis",
                   "deshalb", "also", "folglich", "dann", "andernfalls", "dennoch",
                   "trotzdem", "so", "dazu", "wozu",
                   "überaus", "äußerst", "einigermaßen", "halbwegs", "sehr", "größtenteils",
                   "kaum", "haufenweise", "umsonst", "ebenfalls", "sonst", "auch",
                   "ferner", "außerdem", "zudem", "erstens", "zweitens", "drittens",
                   "hingegen", "allerdings", "immerhin", "wenigstens", "doch", "noch", "auch", "jedoch", "nur",
                   "zumindest", "kurzerhand", "wahrscheinlich", "(?:un)?glücklicherweise",
                   "mehr", "gerne"]
    # pattern =  ^(hier|da|links|vorne|hinten|überall|hoch|vorwärts|abwärts|dorthin|umher|herum|herunter|dorther|herab|
    # herunter|hindurch|nachdem|sobald|während|solange|bevor|bis|deshalb|also|folglich|dann|andernfalls|dennoch|
    # trotzdem|so|dazu|wozu|überaus|äußerst|einigermaßen|halbwegs|sehr|größtenteils|kaum|haufenweise|umsonst|
    # ebenfalls|sonst|auch|ferner|außerdem|zudem|erstens|zweitens|drittens|hingegen|allerdings|immerhin|wenigstens|
    # doch|noch|auch|jedoch|nur|zumindest|kurzerhand|wahrscheinlich|(?:un)?glücklicherweise|mehr|gerne)$
    pattern = "^("
    for adverb in adverb_list:
        pattern += adverb + "|"
    pattern = pattern[0:len(pattern)-1] +")$"

    # pattern wird kompiliert und in prog gespeichert.
    prog = re.compile(pattern, re.IGNORECASE)

    # Rueckgabewert : Liste
    ret = []

    # input_list wird iteriert.
    for token in input_list:
        # wenn prog zutrifft , token wird ignoriert
        if prog.search(token): continue
        # sonst token wird in ret hinzugefuegt.
        else: ret.append(token)

    # ret wird zurueckgegeben.
    return ret

text = """In den vergangenen Jahren haben wir uns mit vielen, schönen und bunten
Themen beschäftigen können. Wir haben unterschiedliche Kriterien anwenden
können und mit Begeisterung am 27.06.2017 den 364. König krönen können.
Begeistert waren auch die bunt gekleideten Besucher, die sich gerne zeigten.
Gewiss, ich schreibe diesen Bericht der Ordnung zuliebe nieder, aus einer
gewissen Pedanterie heraus, damit er zu den Akten komme. Ich will mich
zwingen, noch einmal die Ereignisse zu überprüfen, die zum Freispruch
eines Mörders und zum Tode eines Unschuldigen geführt haben. (Er meint
mehr als zwei Unschulde, aber hier zählen nur reiche, alte Herren.)
"""

# find_nomen
# Finden der Nomen aus dem Eingabestring
# Argument: Eingabestring
# Rueckgabewert: Gefundene Nomen als eine Liste
def find_nomen(input):
    # input wird nach "\n+" gesplitted und in lines gespeichert.
    lines = input.split("\n+")
    # alle non-empty tokens werden in input_list gespeichert
    input_list = []
    # Rueckgabewert: Liste
    nomen = []
    # \W+ => non-word Zeichen, >= 1 mals
    pattern = "\W+"
    # pattern wird kompiliert und in prog gespeichert.
    prog = re.compile(pattern)
    # lines werden iteriert
    for line in lines:
        # line wird gesplitted und in splitted gespeichert.
        splitted = prog.split(line)
        # splitted wird aus leeren Strings bereinigt
        splitted = [word for word in splitted if word != ""]
        # Elemente der splitted werden in input_list hinzugefuegt.
        input_list.extend(splitted)

    # clear_* Funktionen werden auf input_list aufgerufen , um input_list zu bereinigen.
    input_list = clear_modal_und_hilfs_verben(input_list)
    input_list = clear_numerale(input_list)
    input_list = clear_interjektion(input_list)
    input_list = clear_praeposition(input_list)
    input_list = clear_konjunktion(input_list)
    input_list = clear_pronomen(input_list)
    input_list = clear_artikel(input_list)
    input_list = clear_adverb(input_list)

    # input_list wird iteriert
    for word in input_list:
        # wenn der erste Buchstabe des word ein Grossbuchstabe ist , wird word in nomen hinzugefuegt.
        if word[0].isupper():
            nomen.append(word)

    # nomen wird zurueckgegeben.
    return nomen

# find_adjektive
# Finden der Adjektiven aus dem Eingabestring
# Argument: Eingabestring
# Rueckgabewert: Gefundene Adjektiven als eine Liste
def find_adjektive(input):
    # input wird nach "\n+" gesplitted und in lines gespeichert.
    lines = input.split("\n+")
    # alle non-empty tokens werden in input_list gespeichert
    input_list = []
    # Rueckgabewert: Liste
    adjektive = []
    # \W+ => non-word Zeichen, >= 1 mals
    pattern = "\s+"
    # pattern wird kompiliert und in prog gespeichert.
    prog = re.compile(pattern)
    # lines werden iteriert
    for line in lines:
        # line wird gesplitted und in splitted gespeichert.
        splitted = prog.split(line)
        # splitted wird aus leeren Strings bereinigt
        splitted = [word for word in splitted if word != ""]
        # Elemente der splitted werden in input_list hinzugefuegt.
        input_list.extend(splitted)

    # Woerter die vor dem '.' vorkommen , werden entfernt
    input_list = [word for word in input_list if word[len(word)-1] != '.']

    temp = []
    # input_list wird iteriert
    for word in input_list:
        # ',' wird aus dem Wort entfernt
        if word[len(word)-1] == ",": temp.append(word[0:len(word)-1])
        else: temp.append(word)

    # Elemente der temp werden in input_liste kopiert.
    input_list = temp[0:len(temp)]

    # clear_* Funktionen werden auf input_list aufgerufen , um input_list zu bereinigen.
    input_list = clear_modal_und_hilfs_verben(input_list)
    input_list = clear_numerale(input_list)
    input_list = clear_interjektion(input_list)
    input_list = clear_praeposition(input_list)
    input_list = clear_konjunktion(input_list)
    input_list = clear_pronomen(input_list)
    input_list = clear_artikel(input_list)
    input_list = clear_adverb(input_list)

    # input_list wird iteriert
    for word in input_list:
        # wenn der erste Buchstabe des word ein Kleinbuchstabe ist , wird word in adjektive hinzugefuegt.
        if word[0].islower():
            adjektive.append(word)

    # adjektive wird zurueckgegeben.
    return adjektive

# find_nomen_und_adjektive
# Finden Nomen and Adjektiven aus dem Eingabestring
# Argument: Eingabestring
# Rueckgabewert: Tupel der Nomenliste und Adjektivenliste
def find_nomen_und_adjektive(text):
    # find_nomen() wird aufgerufen und das Ergebnis wird in nomen_list gespeichert.
    nomen_list = find_nomen(text)
    # find_adjektive() wird aufgerufen und das Ergebnis wird in adjektive_list gespeichert.
    adjektive_list = find_adjektive(text)
    # nomen_list and adjektive_list wird as Tupel zurueckgegeben.
    return (nomen_list, adjektive_list)

# find_nomen_und_adjektive() wird aufgerufen und das Ergebnis wird dekomposiert
# das erste Element des Tupels wird in nomen_list , das zweite Element wird in adjektive_list gespeichert.
(nomen_list, adjektive_list) = find_nomen_und_adjektive(text)
# nomen_list wird ausgegeben
print("<<find_nomen>>")
print(nomen_list)
# adjektive_list wird ausgegeben
print("<<find_adjektive>>")
print(adjektive_list)

# Das Ergebnis des Programs
"""
<<find_nomen>>
['Jahren', 'Themen', 'Kriterien', 'Begeisterung', 'König', 'Begeistert', 'Besucher', 'Gewiss',
'Bericht', 'Ordnung', 'Pedanterie', 'Akten', 'Ereignisse', 'Freispruch', 'Mörders', 'Tode', 'Unschuldigen',
 'Unschulde', 'Herren']
<<find_adjektive>>
['vergangenen', 'schönen', 'bunten', 'beschäftigen', 'unterschiedliche', 'anwenden', 'krönen', 'bunt',
'gekleideten', 'schreibe', 'zuliebe', 'nieder', 'gewissen', 'heraus', 'zwingen', 'überprüfen', 'geführt',
 'meint', 'zählen', 'reiche', 'alte']

Finden Nomen liefert besseres Ergebnis , der Trick hier ist , nach der Bereinigung der input_liste , haben wir meistens Nomen,
 Adjektiven , ein paar Adverbien, und Vollverben. Und ausser der Nomen , anderen muessen klein geschrieben werden ,
  wenn sie nicht  am Anfang des Satzes verwendet werden.

Finden Adjektiven liefert nicht so gutes Ergebnis , es war schwierig zwischen Adjektive/Adverb und Adjektive/Vollverb
zu unterscheiden.
"""

# Das manuell-berechnete Ergebnis
"""
Nomen:
Jahren, Themen, Kriterien, Begeisterung, König, Besucher, Bericht , Ordnung , Pedanterie, Akten, Ereignisse ,
Freispruch, Mörders, Tode, Unschuldigen , Unschulde , Herren

Adjektiven:
vergangenen, schönen, bunten , unterschiedliche , Begeistert, gekleideten, gewissen, reiche , alte
"""


from kwippyproject.kwippy.models.quip import Quip
from django import template
from django.shortcuts import get_object_or_404
from django.template import Node, NodeList, Template, Context, Variable
from django.core.cache import cache
from django.conf import settings
import pdb, re

register = template.Library()

regex = re.compile('^.*(https?:\/\/[^\ \s]*).*$')

def do_formaturl(parser, token):
    bits = list(token.split_contents())
    nodelist = NodeList()
    return FormatURLNode(bits[1])

# this can be removed/optimized
def formaturl(parser, token):
    return do_formaturl(parser, token)

class FormatURLNode(Node):
    def __init__(self, var1):
        self.var1 = Variable(var1)

    def __repr__(self):
        return "<FormatTimeNode>"

    def render(self, context):
        try:
            val1 = self.var1.resolve(context)
        except VariableDoesNotExist:
            val1 = None
        cache_key = '%s_quiptext%d' % (settings.CACHE_MIDDLEWARE_KEY_PREFIX,val1,)
        kwip = cache.get(cache_key)
        if kwip is None:
            quip = get_object_or_404(Quip, id=val1)
            text = quip.original.strip()
            match = re.match(regex,text)
            if match:
                url = match.group(1)
                replacement = ''+url+''
                kwip = text.replace(url,replacement)
            else:
                kwip = quip.original
            cache.set(cache_key,kwip,86400)
        return kwip

register.tag('formaturl',do_formaturl)


# Create toggle switch model
from scipy.optimize import fsolve
from scipy.integrate import odeint, quad
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# ODEs
def f_ode(x,t, *args):
    K,b_t,b_l,d_t,d_l,del_t,del_l,beta_t,beta_l, Kt0, Kl0 = args
    m_t = x[0]
    m_l = x[1]
    p_t = x[2]
    p_l = x[3]
    md_t = x[4]
    md_l = x[5]
    pd_t = x[6]
    pd_l = x[7]
    y = np.zeros(8)
    y[0] = K * b_t**2/(b_t**2 + p_l**2) - d_t * m_t
    y[1] = K * b_l**2/(b_l**2 + p_t**2) - d_l * m_l
    y[2] = beta_t * m_t - del_t*p_t
    y[3] = beta_l * m_l - del_l * p_l

    y[4] = K * b_t**2/(b_t**2 + pd_l**2) - d_t * md_t + Kt0
    y[5] = K * b_l**2/(b_l**2 + pd_t**2) - d_l * md_l + Kl0
    y[6] = beta_t * md_t - del_t*pd_t
    y[7] = beta_l * md_l - del_l * pd_l
    return y

x0 = np.zeros(8)
params_nom = [100, 1000, 10, 5, 5, 0.01, 0.01, 0.01, 0.01] # default params
params_nom.append(10) # leak params
params_nom.append(20) # leak params

timepoints = np.linspace(0,450,100)
params = tuple(params_nom)
# Solve ODEs, numerically
y = odeint(f_ode, x0, timepoints, args = params)

# Plot solutions from numerical simulation
plt.subplot(2,2,1)
plt.plot(timepoints,y[:,0], label = 'Original model')
plt.plot(timepoints,y[:,4], label = 'Perturbed model')
plt.legend()
plt.xlabel('Time')
plt.ylabel('Species amount')
plt.title('mRNA TetR response')

plt.subplot(2,2,2)
plt.plot(timepoints,y[:,1], label = 'Original model')
plt.plot(timepoints,y[:,5], label = 'Perturbed model')
plt.legend()
plt.xlabel('Time')
plt.ylabel('Species amount')
plt.title('mRNA LacI response')

plt.subplot(2,2,3)
plt.plot(timepoints,y[:,2], label = 'Original model')
plt.plot(timepoints,y[:,6], label = 'Perturbed model')
plt.legend()
plt.xlabel('Time')
plt.ylabel('Species amount')
plt.title('Protein TetR response')

plt.subplot(2,2,4)
plt.plot(timepoints,y[:,3], label = 'Original model')
plt.plot(timepoints,y[:,7], label = 'Perturbed model')
plt.title('Protein LacI response')
plt.xlabel('Time')
plt.ylabel('Species amount')
plt.legend()

plt.show()


from torchvision import models as models
import torch.nn as nn
import torch

def create_model(is_pretrained=True, num_outputs=14, model_name='resnet50'):

    model = None
    if model_name.lower() == 'resnet50':

        model = models.resnet50(progress=True, pretrained=is_pretrained)
#         model.fc = nn.Sequential(
#                 nn.Linear(2048, 1024),
#                 nn.ReLU(),
#                 nn.Linear(1024, 512),
#                 nn.ReLU(),
#                 nn.Linear(512, num_outputs),
#                 nn.Sigmoid())
        model.fc = nn.Sequential(
                    nn.Linear(2048, 1411),
                    nn.ReLU(),
                    nn.Linear(1411, num_outputs),
                    nn.Sigmoid())

    elif model_name.lower() == 'resnet34':

        model = models.resnet34(progress=True, pretrained=is_pretrained)
        model.fc = nn.Sequential(
                nn.Linear(512, 512),
                nn.ReLU(),
                nn.Linear(512, num_outputs),
                nn.Sigmoid())

    elif model_name.lower() == 'densenet':

        model = models.densenet121(progress=True, pretrained=is_pretrained)
        model.classifier = nn.Sequential(
                nn.Linear(1024, 512),
                nn.ReLU(),
                nn.Linear(512, num_outputs),
                nn.Sigmoid())

    return model

def freeze_model_parameters(model):

    for params in model.parameters():
        params.requires_grad = False

    model_name = model.__class__.__name__

    if model_name.lower() == 'resnet':
        for params in model.fc.parameters():
            params.requires_grad = True           # Unfreezing the last fully connected layers

    elif model_name.lower() == 'densenet':
        for params in model.classifier.parameters():
            params.requires_grad = True           # Unfreezing the last fully connected layers

def unfreeze_model_parameters(model):

    for params in model.parameters():
        params.requires_grad = True

def load_model(model, path):

    model_checkpoint = torch.load(path)
    model.load_state_dict(model_checkpoint['model_state_dict'], strict = False)

    return model

def load_model_for_prediction(model, path):

    model_checkpoint = torch.load(path, map_location=torch.device('cpu'))
    model.load_state_dict(model_checkpoint['model_state_dict'], strict = False)

    return model

def build_model_for_uptuna(trial, model, num_outputs=14, model_name='resnet50'):

    # Suggest the number of layers of neural network model
    n_layers = trial.suggest_int("n_layers", 1, 4)

    if model_name.lower() == 'resnet50':

        layers = generate_model_layers(trial=trial, in_features=2048, n_layers=n_layers, num_outputs=num_outputs)
        model.fc = nn.Sequential(*layers)

    elif model_name.lower() == 'resnet34':

        layers = generate_model_layers(trial=trial, in_features=512, n_layers=n_layers, num_outputs=num_outputs)
        model.fc = nn.Sequential(*layers)

    elif model_name.lower() == 'densenet':

        layers = generate_model_layers(trial=trial, in_features=1024, n_layers=n_layers, num_outputs=num_outputs)
        model.classifier = nn.Sequential(*layers)

    return model

def generate_model_layers(trial, in_features, n_layers, num_outputs):

    layers = []

    for i in range(n_layers):

        # Suggest the number of units in each layer
        out_features = trial.suggest_int("n_units_l{}".format(i), 64, 2048)

        layers.append(nn.Linear(in_features, out_features))
        layers.append(nn.ReLU())

        in_features = out_features

    layers.append(nn.Linear(in_features, num_outputs))
    layers.append(nn.Sigmoid())

    return layers

def apply_optuna_learned_fully_connected_layers(model, num_outputs):

        model.fc = nn.Sequential(
            nn.Linear(2048, 1411),
            nn.ReLU(),
            nn.Linear(1411, num_outputs),
            nn.Sigmoid())

        return model


#!/usr/bin/env python3
#
# smooth_time_series.py: This is a demo script for pre-processing time
# series by applying *exponential weighted averages*. We do *not* make
# use of this technique in the paper but provide it here as an example
# for pre-processing techniques.
#
# Input:  CSV file containing the time series; the first value is used as
#         the label.
# Output: Pre-processed time series in CSV format
#
# All output will be written to `stdout`.

import numpy  as np
import pandas as pd

import sys

if __name__ == "__main__":

  ts_all = []
  labels = []

  with open(sys.argv[1]) as f:
    for line in f:
      values = [ float(x) for x in line.split(",") ]
      label  = values[0]
      values = values[1:len(values)] # Drop the label of the time series; this
                                     # is the convention that we use---similar
                                     # to the UCR data.

      labels.append(label)
      ts_all.append( pd.Series(values) )

  for index, ts in enumerate(ts_all):
    values = ts.ewm(span=5).mean()
    print(str(labels[index])+","+",".join([str(x) for x in values]))


######################################################################
##################  PYTHON PACKAGES  #################################
######################################################################
# Usual SHARPy
import h5py as h5
import numpy as np
import os
import sharpy.utils.algebra as algebra
import sharpy.utils.cout_utils as cout # to use color output
# Read excel files
import pandas as pd
from pandas import ExcelFile
# Generate errors during execution
import sys
# Use .isnan
import math
from IPython import embed

######################################################################
##################  MATHEMATICAL FUNCTIONS  ##########################
######################################################################
def rotate_vector(vector,direction,angle):
    # This function rotates a "vector" around a "direction" a certain "angle"
    # according to Rodrigues formula

    #Create numpy arrays from vectors
    vector=np.array(vector)
    direction=np.array(direction)

    # Assure that "direction" has unit norm
    direction/=np.linalg.norm(direction)

    rot_vector=vector*np.cos(angle)+np.cross(direction,vector)*np.sin(angle)+direction*np.dot(direction,vector)*(1.0-np.cos(angle))

    return rot_vector

def get_airfoil_camber(x,y,n_points_camber):
    # Returns the airfoil camber for a given set of coordinates (XFOIL format expected)

    x=np.array(x, dtype=float)
    y=np.array(y, dtype=float)
    n=len(x)
    imin_x=0

    # Look for the minimum x (it will be assumed as the LE position
    for i in range(0,n):
        if(x[i]<x[imin_x]):
            imin_x=i

    x_suction=np.zeros((imin_x+1, ))
    y_suction=np.zeros((imin_x+1, ))
    x_pressure=np.zeros((n-imin_x, ))
    y_pressure=np.zeros((n-imin_x, ))

    for i in range(0,imin_x+1):
        x_suction[i]=x[imin_x-i]
        y_suction[i]=y[imin_x-i]

    for i in range(imin_x,n):
        x_pressure[i-imin_x]=x[i]
        y_pressure[i-imin_x]=y[i]

    # Compute the camber coordinates
    camber_y=np.zeros((n_points_camber,))
    camber_x=np.linspace(0.0,1.0,n_points_camber)

    # camber_y=0.5*(np.interp(camber_x,x[imin_x::-1],y[imin_x::-1])+np.interp(camber_x,x[imin_x:],y[imin_x:]))
    camber_y=0.5*(np.interp(camber_x,x_suction,y_suction)+np.interp(camber_x,x_pressure,y_pressure))

    # The function should be called as: camber_x, camber_y = get_airfoil_camber(x,y)
    return camber_x, camber_y

######################################################################
##################  DEFINE CASE  #####################################
######################################################################
case_name = 'basic_wing'
route = os.path.dirname(os.path.realpath(__file__)) + '/'

flow = ['BeamLoader',
        'AerogridLoader',
        'StaticCoupled',
        'SteadyHelicoidalWake',
        #'DynamicPrescribedCoupled',
        'AerogridPlot',
        'BeamPlot',
        'SaveData'
        ]

gravity = 'off'

######################################################################
##################  DEFINE CONSTANTS  ################################
######################################################################
n_node_elem=3
deg2rad=2*np.pi/360
n_points_camber=1000

######################################################################
##################  READ EXCEL FILES  ################################
######################################################################
WSP = 10.0
airDensity = 0.5
omega = 1.6

wake_revs = 10
sim_revs = wake_revs**2

dphi_deg = 1.0
dt = dphi_deg*deg2rad / omega

n_tstep = int(sim_revs*360/dphi_deg)
alpha = 0.0*deg2rad
beta = 0.0*deg2rad

# Number of panels on the blade (chordwise direction)
m = 1
# Number of panels on the wake (flow direction)
mstar = 4

numberOfBlades = 1
tilt = 0.0*deg2rad
cone = 0.0*deg2rad
pitch = 0.0*deg2rad

angular_velocity=np.zeros((3,))
angular_velocity[0]=omega*np.cos(tilt)
angular_velocity[1]=omega*np.sin(tilt)
angular_velocity[2]=0.0

n_elem_structural = 6
length = 50.0

Radius = np.linspace(0.1*length,length,n_elem_structural)
BlFract = 0.0*np.ones((n_elem_structural, ))
AeroCent = 0.25*np.ones((n_elem_structural, ))
StrcTwst = 90.0*np.ones((n_elem_structural, ))*deg2rad
BMassDen = np.ones((n_elem_structural, ))
FlpStff = 1e12*np.ones((n_elem_structural, ))
EdgStff = 1e12*np.ones((n_elem_structural, ))
GJStff = 1e12*np.ones((n_elem_structural, ))
EAStff = 1e12*np.ones((n_elem_structural, ))
Alpha = np.ones((n_elem_structural, ))
FlpIner = np.ones((n_elem_structural, ))
EdgIner = np.ones((n_elem_structural, ))
PrecrvRef = np.zeros((n_elem_structural, ))
PreswpRef = np.zeros((n_elem_structural, ))
FlpcgOf = np.zeros((n_elem_structural, ))
EdgcgOf = np.zeros((n_elem_structural, ))
FlpEAOf = np.zeros((n_elem_structural, ))
EdgEAOf = np.zeros((n_elem_structural, ))

n_elem_aero = n_elem_structural
Rnodes = np.linspace(0.1*length,length,n_elem_aero)
AeroTwst = 0.0*np.ones((n_elem_aero, ))*deg2rad
Chord = np.ones((n_elem_aero, ))
pure_airfoils = ["" for x in range(n_elem_aero)]

pure_airfoils_camber=np.zeros((n_points_camber,2,n_elem_aero))
for ielem in range(0,n_elem_aero):
    pure_airfoils_camber[:,0,ielem] = np.linspace(0.0,1.0,n_points_camber)

######################################################################
######################  BLADE DISCRETIZATION  ########################
######################################################################

keep_excel_discretization = True

if(keep_excel_discretization):
    # Check that the number of nodes provided is consistent
    n_elem_main = n_elem_structural-2
    elem_r=np.zeros((n_elem_main,))
    elem_r=Radius[1:-1]

    n_node_main = int(n_elem_main*(n_node_elem-1) + 1)
    r=np.zeros((n_node_main, ))
    r[0]=Radius[0]
    r[-2]=Radius[-2]
    r[-1]=Radius[-1]

    for ielem in range(0,n_elem_main-1):
        r[ielem*(n_node_elem-1)+1]=elem_r[ielem]
        r[ielem*(n_node_elem-1)+2]=0.5*(elem_r[ielem]+elem_r[ielem+1])

else:
    # Choose whatever discretization
    sys.error("ERROR: Change excel discretization not implemented")

# Initialize variables
prebending=np.zeros((n_node_main, ))
presweept=np.zeros((n_node_main, ))
node_struct_twist=np.zeros((n_node_main, ))
EA=np.zeros((n_elem_main, ))
EIz=np.zeros((n_elem_main, ))
EIy=np.zeros((n_elem_main, ))
GJ=np.zeros((n_elem_main, ))

GAy=np.zeros((n_elem_main, ))
GAz=np.zeros((n_elem_main, ))

mass=np.zeros((n_elem_main, ))

inertia_xb=np.zeros((n_elem_main, ))
inertia_yb=np.zeros((n_elem_main, ))
inertia_zb=np.zeros((n_elem_main, ))

pos_cg_B=np.zeros((n_elem_main,3))

# Interpolate all the blade properties
prebending=np.interp(r,Radius,PrecrvRef)
presweept=np.interp(r,Radius,PreswpRef)
node_struct_twist=np.interp(r,Radius,StrcTwst)
EA=np.interp(elem_r,Radius,EAStff)
EIz=np.interp(elem_r,Radius,FlpStff)
EIy=np.interp(elem_r,Radius,EdgStff)
GJ=np.interp(elem_r,Radius,GJStff)

# cout.cout_wrap('WARNING: The poisson cofficient is supossed equal to 0.3', 1)
print('WARNING: The poisson cofficient is supossed equal to 0.3')
print('WARNING: Cross-section area is used as shear area')
poisson_coef=0.3
GAy=EA/2.0/(1+poisson_coef)
GAz=EA/2.0/(1+poisson_coef)

mass=np.interp(elem_r,Radius,BMassDen)

inertia_yb=np.interp(elem_r,Radius,EdgIner)
inertia_zb=np.interp(elem_r,Radius,FlpIner)
print('WARNING: Using perpendicular axis theorem to compute the inertia around xB')
inertia_xb=inertia_yb+inertia_zb

pos_cg_B[:,1]=np.interp(elem_r,Radius,EdgcgOf)
pos_cg_B[:,2]=np.interp(elem_r,Radius,FlpcgOf)

# Initialize variables
blade_x=np.zeros((n_node_main, ))
blade_y=np.zeros((n_node_main, ))
blade_z=np.zeros((n_node_main, ))
blade_y_BFoR=np.zeros((n_node_main,3))
mass_db=np.zeros((n_elem_main,6,6))
stiffness_matrix_db=np.zeros((n_elem_main,6,6))

######################################################################
######################  BLADE STRUCTURE  #############################
######################################################################

for inode in range(0,n_node_main):

    # COORDINATES
    # (x,y,z) are the coordinates (A frame) of the reference line at each position
    blade_x[inode]=-1.0*r[inode]*np.cos(90*deg2rad+cone-tilt)-prebending[inode]*np.sin(90*deg2rad+cone-tilt)
    blade_y[inode]=r[inode]*np.sin(90*deg2rad+cone-tilt)-prebending[inode]*np.cos(90*deg2rad+cone-tilt)
    blade_z[inode]=-1.0*presweept[inode]

    # FRAME_OF_REFERENCE_DELTA
    # y vector of the B frame of reference
    blade_y_BFoR[inode, :]=[-1.0,0.0,0.0]

for ielem in range(0,n_elem_main):
    # MASS DATABASE (1 element per node)
    # mass_db[inode, :, :] = mass[inode]
    mass_db[ielem, 0:3, 0:3] = np.diag(np.ones((3,))*mass[ielem])

    mass_db[ielem, 0:3, 3:6] = [[ 0.0                                , mass[ielem]*pos_cg_B[ielem,2]      ,  -1.0*mass[ielem]*pos_cg_B[ielem,1] ],
                                [ -1.0*mass[ielem]*pos_cg_B[ielem,2] , 0.0                                ,  mass[ielem]*pos_cg_B[ielem,0]      ],
                                [ mass[ielem]*pos_cg_B[ielem,1]      , -1.0*mass[ielem]*pos_cg_B[ielem,0] ,  0.0                                ]]

    mass_db[ielem, 3:6, 0:3] = -1.0*mass_db[ielem, 0:3, 3:6]

    mass_db[ielem, 3:6, 3:6] = np.diag([inertia_xb[ielem], inertia_yb[ielem], inertia_zb[ielem]])

    # STIFFNESS DATABASE (1 element per node)
    stiffness_matrix_db[ielem, :, :] = np.diag([EA[ielem], GAy[ielem], GAz[ielem], GJ[ielem], EIy[ielem], EIz[ielem]])

    # STRUCTURAL_TWIST
    # Already in node_struct_twist

######################################################################
######################  ROTOR STRUCTURE  #############################
######################################################################

if(r[0]==0):
    # Blades are joined at the centre
    n_node=(n_node_main-1)*numberOfBlades+1
    joined_blades=1
    sys.exit("ERROR: Joined blades at the origin not implemented yet.\n")
else:
    n_node=n_node_main*numberOfBlades
    joined_blades=0

n_elem=n_elem_main*numberOfBlades

# Initialize variables
x = np.zeros((n_node, ))
y= np.zeros((n_node, ))
z= np.zeros((n_node, ))
elem_stiffness=np.zeros((n_elem, ), dtype=int)
elem_mass=np.zeros((n_elem, ), dtype=int)
frame_of_reference_delta=np.zeros((n_elem,3,3))
structural_twist=np.zeros((n_node, ))
boundary_conditions=np.zeros((n_node, ), dtype=int)
beam_number=np.zeros((n_node, ), dtype=int)
app_forces=np.zeros((n_node,6))
connectivities=np.zeros((n_elem,3), dtype=int)

for iblade in range(0,numberOfBlades):
    blade_angle=iblade*(360.0/numberOfBlades)*deg2rad

    for inode_main in range(0,n_node_main):
        # Compute the global node
        inode = inode_main+iblade*n_node_main

        structural_twist[inode]=node_struct_twist[inode_main]

        # Boundary conditions
        if (inode_main==0):
            boundary_conditions[inode]=1
        elif(inode_main==n_node_main-1):
            boundary_conditions[inode]=-1
        else:
            boundary_conditions[inode]=0

        # Beam number
        beam_number[inode]=iblade

        # Coordinates
        [x[inode],y[inode],z[inode]]=rotate_vector([blade_x[inode_main],blade_y[inode_main],blade_z[inode_main]],[np.cos(tilt),np.sin(tilt),0.0],blade_angle)

        # Applied forces
        app_forces[inode,:]=np.zeros((6, ))
        if(inode_main==n_node_main-1):
            app_forces[inode,1]=0.0

    # Connectivities
    for ielem_main in range(n_elem_main):
        ielem=ielem_main+iblade*n_elem_main

        # Node characteristics
        elem_stiffness[ielem]=int(ielem_main)
        elem_mass[ielem]=int(ielem_main)

        connectivities[ielem, :] = (np.ones((3, ))*(ielem*(n_node_elem - 1)+iblade) + [0, 2, 1])
        # B frame of reference
        for inode in range(0,n_node_elem):
            frame_of_reference_delta[ielem,inode,:]=rotate_vector(blade_y_BFoR[connectivities[ielem_main,inode], :],[np.cos(tilt),np.sin(tilt),0.0],blade_angle)

######################################################################
######################  BLADE AERODYNAMICS  ##########################
######################################################################

# Look for the first element that is goint to be aerodynamic
first_aero_elem=0
while (elem_r[first_aero_elem]<=Rnodes[0]):
    first_aero_elem+=1

first_aero_node=first_aero_elem*(n_node_elem-1)
n_aero_node=(n_elem_main-first_aero_elem)*(n_node_elem-1)+1

blade_aero_node = np.zeros((n_node_main,), dtype=bool)
blade_aero_node[first_aero_node:]=np.ones((n_node_main-first_aero_node,),dtype=bool)

# Airfoil distribution
blade_airfoil_distribution=np.zeros((n_elem_main,n_node_elem), dtype=int)
for ielem_main in range(n_elem_main):
    blade_airfoil_distribution[ielem_main,:]=connectivities[ielem_main,:]

blade_airfoil=np.zeros((n_points_camber,2,n_node_main))

for inode_main in range(0,n_node_main):
    # camber_x, camber_y = get_airfoil_camber(x,y)

    iairfoil=0
    while(r[inode_main]<Rnodes[iairfoil]):
        iairfoil+=1
        if(iairfoil==len(Rnodes)):
            iairfoil-=1
            break

    beta=min((r[inode_main]-Rnodes[iairfoil-1])/(Rnodes[iairfoil]-Rnodes[iairfoil-1]),1.0)
    beta=max(0.0,beta)

    blade_airfoil[:,0,inode_main]=(1-beta)*pure_airfoils_camber[:,0,iairfoil-1]+beta*pure_airfoils_camber[:,0,iairfoil]
    blade_airfoil[:,1,inode_main]=(1-beta)*pure_airfoils_camber[:,1,iairfoil-1]+beta*pure_airfoils_camber[:,1,iairfoil]

# Node chord, elastic axis
node_chord=np.interp(r, Rnodes, Chord)
node_aero_twist=np.interp(r, Rnodes, AeroTwst)
node_elastic_axis=np.ones((n_node_main,))*0.25

######################################################################
######################  ROTOR AERODYNAMICS  ##########################
######################################################################

aero_node=np.ones((n_node,), dtype=bool)
airfoil_distribution=np.zeros((n_elem,n_node_elem), dtype=int)
surface_distribution=np.zeros((n_elem,), dtype=int)

chord=np.zeros((n_elem,n_node_elem))
elastic_axis=np.zeros((n_elem,n_node_elem))
aerodynamic_twist=np.zeros((n_elem,n_node_elem))

for iblade in range(0,numberOfBlades):

    for inode_main in range(0,n_node_main):
        # Compute the global node
        inode = inode_main+iblade*n_node_main

        # Node characteristics
        aero_node[inode]=blade_aero_node[inode_main]

    # Element characteristics
    for ielem_main in range(0,n_elem_main):
        for inode in range(0,n_node_elem):
            ielem=ielem_main+iblade*n_elem_main

            chord[ielem,inode]=node_chord[connectivities[ielem_main, inode]]
            elastic_axis[ielem,inode]=node_elastic_axis[connectivities[ielem_main, inode]]
            aerodynamic_twist[ielem,inode]=node_aero_twist[connectivities[ielem_main, inode]]

            surface_distribution[ielem]=iblade
            airfoil_distribution[ielem,:]=blade_airfoil_distribution[ ielem_main,: ]

surface_m = np.ones((numberOfBlades, ), dtype=int)*m
m_distribution = 'uniform'

######################################################################
######################  GENERATE FILES  ##############################
######################################################################

def clean_test_files():
    fem_file_name = route + '/' + case_name + '.fem.h5'
    if os.path.isfile(fem_file_name):
        os.remove(fem_file_name)

    dyn_file_name = route + '/' + case_name + '.dyn.h5'
    if os.path.isfile(dyn_file_name):
        os.remove(dyn_file_name)

    aero_file_name = route + '/' + case_name + '.aero.h5'
    if os.path.isfile(aero_file_name):
        os.remove(aero_file_name)

    solver_file_name = route + '/' + case_name + '.solver.txt'
    if os.path.isfile(solver_file_name):
        os.remove(solver_file_name)

    flightcon_file_name = route + '/' + case_name + '.flightcon.txt'
    if os.path.isfile(flightcon_file_name):
        os.remove(flightcon_file_name)

def generate_dyn_file():
    global dt
    global n_tstep
    global route
    global case_name
    global num_elem
    global num_node_elem
    global num_node
    global amplitude
    global period

    dynamic_forces_time = None
    with_dynamic_forces = False
    with_forced_vel = True
    # if with_dynamic_forces:
    #     f1 = 100
    #     dynamic_forces = np.zeros((num_node, 6))
    #     app_node = []
    #     dynamic_forces[app_node, 2] = f1
    #     force_time = np.zeros((n_tstep, ))
    #     limit = round(0.05/dt)
    #     force_time[50:61] = 1
    #
    #     dynamic_forces_time = np.zeros((n_tstep, num_node, 6))
    #     for it in range(n_tstep):
    #         dynamic_forces_time[it, :, :] = force_time[it]*dynamic_forces

    forced_for_vel = None
    if with_forced_vel:
        forced_for_vel = np.zeros((n_tstep, 6))
        forced_for_acc = np.zeros((n_tstep, 6))
        for it in range(n_tstep):
            # forced_for_vel[it, 3:6] = it/n_tstep*angular_velocity
            forced_for_vel[it, 3:6] = angular_velocity

    with h5.File(route + '/' + case_name + '.dyn.h5', 'a') as h5file:
        if with_dynamic_forces:
            h5file.create_dataset(
                'dynamic_forces', data=dynamic_forces_time)
        if with_forced_vel:
            h5file.create_dataset(
                'for_vel', data=forced_for_vel)
            h5file.create_dataset(
                'for_acc', data=forced_for_acc)
        h5file.create_dataset(
            'num_steps', data=n_tstep)

def generate_fem():

    # CHECKING
    if(elem_stiffness.shape[0]!=n_elem):
        sys.exit("ERROR: Element stiffness must be defined for each element")
    if(elem_mass.shape[0]!=n_elem):
        sys.exit("ERROR: Element mass must be defined for each element")
    if(frame_of_reference_delta.shape[0]!=n_elem):
        sys.exit("ERROR: The first dimension of FoR does not match the number of elements")
    if(frame_of_reference_delta.shape[1]!=n_node_elem):
        sys.exit("ERROR: The second dimension of FoR does not match the number of nodes element")
    if(frame_of_reference_delta.shape[2]!=3):
        sys.exit("ERROR: The third dimension of FoR must be 3")
    if(structural_twist.shape[0]!=n_node):
        sys.exit("ERROR: The structural twist must be defined for each node")
    if(boundary_conditions.shape[0]!=n_node):
        sys.exit("ERROR: The boundary conditions must be defined for each node")
    if(beam_number.shape[0]!=n_node):
        sys.exit("ERROR: The beam number must be defined for each node")
    if(app_forces.shape[0]!=n_node):
        sys.exit("ERROR: The first dimension of the applied forces matrix does not match the number of nodes")
    if(app_forces.shape[1]!=6):
        sys.exit("ERROR: The second dimension of the applied forces matrix must be 6")

    # Writting the file
    with h5.File(route + '/' + case_name + '.fem.h5', 'a') as h5file:
        coordinates = h5file.create_dataset('coordinates', data=np.column_stack((x, y, z)))
        conectivities = h5file.create_dataset('connectivities', data=connectivities)
        num_nodes_elem_handle = h5file.create_dataset(
            'num_node_elem', data=n_node_elem)
        num_nodes_handle = h5file.create_dataset(
            'num_node', data=n_node)
        num_elem_handle = h5file.create_dataset(
            'num_elem', data=n_elem)
        stiffness_db_handle = h5file.create_dataset(
            'stiffness_db', data=stiffness_matrix_db)
        stiffness_handle = h5file.create_dataset(
            'elem_stiffness', data=elem_stiffness)
        mass_db_handle = h5file.create_dataset(
            'mass_db', data=mass_db)
        mass_handle = h5file.create_dataset(
            'elem_mass', data=elem_mass)
        frame_of_reference_delta_handle = h5file.create_dataset(
            'frame_of_reference_delta', data=frame_of_reference_delta)
        structural_twist_handle = h5file.create_dataset(
            'structural_twist', data=structural_twist)
        bocos_handle = h5file.create_dataset(
            'boundary_conditions', data=boundary_conditions)
        beam_handle = h5file.create_dataset(
            'beam_number', data=beam_number)
        app_forces_handle = h5file.create_dataset(
            'app_forces', data=app_forces)
        # lumped_mass_nodes_handle = h5file.create_dataset(
        #     'lumped_mass_nodes', data=lumped_mass_nodes)
        # lumped_mass_handle = h5file.create_dataset(
        #     'lumped_mass', data=lumped_mass)
        # lumped_mass_inertia_handle = h5file.create_dataset(
        #     'lumped_mass_inertia', data=lumped_mass_inertia)
        # lumped_mass_position_handle = h5file.create_dataset(
        #     'lumped_mass_position', data=lumped_mass_position)

def generate_aero_file():

    # CHECKING
    if(aero_node.shape[0]!=n_node):
        sys.exit("ERROR: Aero node must be defined for each node")
    if(airfoil_distribution.shape[0]!=n_elem or airfoil_distribution.shape[1]!=n_node_elem):
            sys.exit("ERROR: Airfoil distribution must be defined for each element/local node")
    if(chord.shape[0]!=n_elem):
        sys.exit("ERROR: The first dimension of the chord matrix does not match the number of elements")
    if(chord.shape[1]!=n_node_elem):
        sys.exit("ERROR: The second dimension of the chord matrix does not match the number of nodes per element")
    if(elastic_axis.shape[0]!=n_elem):
        sys.exit("ERROR: The first dimension of the elastic axis matrix does not match the number of elements")
    if(elastic_axis.shape[1]!=n_node_elem):
        sys.exit("ERROR: The second dimension of the elastic axis matrix does not match the number of nodes per element")
    if(surface_distribution.shape[0]!=n_elem):
        sys.exit("ERROR: The surface distribution must be defined for each element")
    if(aerodynamic_twist.shape[0]!=n_elem):
        sys.exit("ERROR: The first dimension of the aerodynamic twist does not match the number of elements")
    if(aerodynamic_twist.shape[1]!=n_node_elem):
        sys.exit("ERROR: The second dimension of the aerodynamic twist does not match the number nodes per element")

    with h5.File(route + '/' + case_name + '.aero.h5', 'a') as h5file:
        airfoils_group = h5file.create_group('airfoils')
        # add the airfoils
        for inode in range(0,n_node_main):
            airfoils_group.create_dataset("%d" % inode, data=blade_airfoil[:,:,inode])

        # chord
        chord_input = h5file.create_dataset('chord', data=chord)
        dim_attr = chord_input .attrs['units'] = 'm'

        # twist
        twist_input = h5file.create_dataset('twist', data=aerodynamic_twist)
        dim_attr = twist_input.attrs['units'] = 'rad'

        # airfoil distribution
        airfoil_distribution_input = h5file.create_dataset('airfoil_distribution', data=airfoil_distribution)

        surface_distribution_input = h5file.create_dataset('surface_distribution', data=surface_distribution)
        surface_m_input = h5file.create_dataset('surface_m', data=surface_m)
        m_distribution_input = h5file.create_dataset('m_distribution', data=m_distribution.encode('ascii', 'ignore'))

        aero_node_input = h5file.create_dataset('aero_node', data=aero_node)
        elastic_axis_input = h5file.create_dataset('elastic_axis', data=elastic_axis)

        #control_surface_input = h5file.create_dataset('control_surface', data=control_surface)
        #control_surface_deflection_input = h5file.create_dataset('control_surface_deflection', data=control_surface_deflection)
        #control_surface_chord_input = h5file.create_dataset('control_surface_chord', data=control_surface_chord)
        #control_surface_types_input = h5file.create_dataset('control_surface_type', data=control_surface_type)

def generate_solver_file():
    file_name = route + '/' + case_name + '.solver.txt'
    settings = dict()
    aux_settings = dict()
    settings['SHARPy'] = {'case': case_name,
                          'route': route,
                          'flow': flow,
                          'write_screen': 'on',
                          'write_log': 'on',
                          'log_folder': route + '/output/',
                          'log_file': case_name + '.log'}

    # AUX DICTIONARIES
    aux_settings['velocity_field_input'] = {'u_inf': WSP,
                                        'u_inf_direction': [1., 0, 0]}

    # LOADERS

    settings['BeamLoader'] = {'unsteady': 'on',
                              'orientation': algebra.euler2quat(np.array([0.0,
                                                                          alpha,
                                                                          beta]))}

    settings['AerogridLoader'] = {'unsteady': 'on',
                                  'aligned_grid': 'on',
                                  'mstar': mstar,
                                  'freestream_dir': ['1', '0', '0']}

    # POSTPROCESS

    settings['AerogridPlot'] = {'folder': route + '/output/',
                                'include_rbm': 'on',
                                'include_forward_motion': 'off',
                                'include_applied_forces': 'on',
                                'minus_m_star': 0,
                                'u_inf': WSP,
                                'dt': dt}

    #settings['AeroForcesCalculator'] = {'folder': route + '/output/forces',
                                        #'write_text_file': 'on',
                                        #'text_file_name': case_name + '_aeroforces.csv',
                                        #'screen_output': 'on',
                                        #'unsteady': 'off'}

    settings['BeamPlot'] = {'folder': route + '/output/',
                            'include_rbm': 'on',
                            'include_applied_forces': 'on',
                            'include_forward_motion': 'on'}

    #settings['BeamCsvOutput'] = {'folder': route + '/output/',
                                 #'output_pos': 'on',
                                 #'output_psi': 'on',
                                 #'screen_output': 'off'}

    settings['BeamLoads'] = {}

    settings['WriteVariablesTime'] = {'delimiter': ' ',
                                      'structure_variables': ['AFoR_steady_forces', 'AFoR_unsteady_forces','AFoR_position', 'AFoR_velocity'],
                                      'structure_nodes': [4],
                                      'aero_panels_variables': ['gamma', 'norm_gamma', 'norm_gamma_star'],
                                      'aero_panels_isurf': [0],
                                      'aero_panels_im': [0],
                                      'aero_panels_in': [4],
                                      'aero_nodes_variables': ['GFoR_steady_force', 'GFoR_unsteady_force'],
                                      'aero_nodes_isurf': [0],
                                      'aero_nodes_im': [0],
                                      'aero_nodes_in': [4]}

    settings['SaveData'] = {}

    # STATIC COUPLED

    settings['NonLinearStatic'] = {'print_info': 'on',
                                   'max_iterations': 150,
                                   'num_load_steps': 1,
                                   'delta_curved': 1e-15,
                                   'min_delta': 1e-8,
                                   'gravity_on': gravity,
                                   'gravity': 9.81}

    settings['StaticUvlm'] = {'print_info': 'on',
                              'horseshoe': 'off',
                              'num_cores': 4,
                              'n_rollup': 0,
                              'rollup_dt': dt,
                              'rollup_aic_refresh': 1,
                              'rollup_tolerance': 1e-4,
                              'velocity_field_generator': 'SteadyVelocityField',
                              'velocity_field_input': aux_settings['velocity_field_input'],
                              'rho': 0.0}

    settings['StaticCoupled'] = {'print_info': 'on',
                                 'structural_solver': 'NonLinearStatic',
                                 'structural_solver_settings': settings['NonLinearStatic'],
                                 'aero_solver': 'StaticUvlm',
                                 'aero_solver_settings': settings['StaticUvlm'],
                                 'max_iter': 100,
                                 'n_load_steps': 4,
                                 'tolerance': 1e-8,
                                 'relaxation_factor': 0}

    # DYNAMIC PRESCRIBED COUPLED

    settings['NonLinearDynamicPrescribedStep'] = {'print_info': 'on',
                                               'max_iterations': 95000,
                                               'delta_curved': 1e-9,
                                               'min_delta': 1e-6,
                                               'newmark_damp': 1e-3,
                                               'gravity_on': gravity,
                                               'gravity': 9.81,
                                               'num_steps': n_tstep,
                                               'dt': dt}

    settings['StepUvlm'] = {'print_info': 'on',
                            'horseshoe': 'off',
                            'num_cores': 4,
                            'n_rollup': 0,
                            'convection_scheme': 2,
                            'rollup_dt': dt,
                            'rollup_aic_refresh': 1,
                            'rollup_tolerance': 1e-4,
                            'velocity_field_generator': 'SteadyVelocityField',
                            'velocity_field_input': aux_settings['velocity_field_input'],
                            'rho': airDensity,
                            'n_time_steps': n_tstep,
                            'dt': dt}

    settings['DynamicPrescribedCoupled'] = {'structural_solver': 'NonLinearDynamicPrescribedStep',
                                            'structural_solver_settings': settings['NonLinearDynamicPrescribedStep'],
                                            'aero_solver': 'StepUvlm',
                                            'aero_solver_settings': settings['StepUvlm'],
                                            'fsi_substeps': 20000,
                                            'fsi_tolerance': 1e-9,
                                            'fsi_vel_tolerance': 1e-5,
                                            'relaxation_factor': 0,
                                            'minimum_steps': 1,
                                            'relaxation_steps': 150,
                                            'final_relaxation_factor': 0.0,
                                            'n_time_steps': n_tstep,
                                            'dt': dt,
                                            'include_unsteady_force_contribution': 'off',
                                            'print_info': 'on',
                                            'rigid_structure': 'on',
                                            'postprocessors': ['WriteVariablesTime'],
                                            'postprocessors_settings': {'WriteVariablesTime': settings['WriteVariablesTime']}}

    # STEADY HELICOIDAL WAKE
    settings['SteadyHelicoidalWake'] = settings['DynamicPrescribedCoupled']

    import configobj
    config = configobj.ConfigObj()
    config.filename = file_name
    for k, v in settings.items():
        config[k] = v
    config.write()

clean_test_files()
generate_dyn_file()
generate_fem()
generate_aero_file()
generate_solver_file()

print("DONE")


#Dice Rolling
from random import randint

the_dice = randint(1,6)
dice_roller = input("Say 'roll' whenever you're ready! ")

if dice_roller == "roll":
    print("You rolled a: ", the_dice)
    dice_roller = input("Would you like to roll again? ")
    if dice_roller == "yes":
        new_dice = randint(1,6)
        print("This time you rolled a: ", new_dice)
    elif dice_roller == "no":
        print("thank you for playing!")
elif dice_roller == "no" or dice_roller == "no thank you":
    print("Maybe next time then.")
else:
    print("Whatever you say weirdo..")


import sys
from functools import reduce
sys.stdin=open('input.txt','r')
sys.stdout=open('output.txt','w')

def is_sorted(lst):
    it = iter(lst)
    try:
        prev = next(it)
    except StopIteration:
        return True
    for x in it:
        print(x,prev)
        if prev >= x:  # For reverse, use <
            return False
        prev = x
    return True

def canBeIncreasing(nums) -> bool:
    temp=[]
    flag=True
    for i in range(1,len(nums)+1):
        #print(nums[:i-1]+nums[i:])
        if is_sorted(nums[:i-1]+nums[i:]):
            return True

    return False

print(canBeIncreasing([512,867,904,997,403]))


import os
import actions
import datetime
import sys
import decimal

# https://stackoverflow.com/a/14996816
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']

size_base = 1000
# Windows file explorer shows values in KiB, MiB..., but labels it KB, MB...
# https://imgs.xkcd.com/comics/kilobyte.png
# We shouldn't be doing this, but most of the windows user will use file explorer
# to check sizes and they'd think it's our application that's wrong
if sys.platform == 'win32':
    size_base = 1024

def human_size(n_bytes):
    # TODO: Due to our database value being float,
    # it will always have 1 decimal number, i.e '0'
    # even if user entered an integer
    # https://stackoverflow.com/a/6190291
    no_of_decimals = abs(decimal.Decimal(str(size_value)).as_tuple().exponent)
    print("No of decimals: {}".format(no_of_decimals))
    unit = unit_value
    i = 0
    while unit != suffixes[i]:
        n_bytes /= size_base
        i += 1
    result = '{:.{}f}'.format(n_bytes, no_of_decimals)
    # Windows file explorer doesn't show decimal value
    # for items above 100 non-decimal value.
    # We shouldn't be handling this, but Harshit282 wants it,
    # so add it.
    if sys.platform == 'win32':
        value = float(result)
        if int(value) >= 100:
            return int(value)

    return float(result)

def get_file_category(file_path):
    ext = os.path.splitext(file_path)[1]
    if ext in ['.jpg', '.png', '.gif', '.bmp']:
        return 'Images'
    elif ext in ['.pdf', '.doc', '.txt', '.xlsx']:
        return 'Documents'
    elif ext in ['.mp4', '.avi', '.wmv', '.mov']:
        return 'Videos'
    elif ext in ['.mp3', '.flac', '.ogg', '.aac', '.opus']:
        return 'Music'
    else:
        return 'Other'

def get_files(rc):
    todo = {}
    file_paths = []
    for subdir, dirs, files in os.walk(rc.original_path):
        for file in files:
            file_path = os.path.join(subdir, file)
            file_category = get_file_category(file_path)

            if rc.condition_value == 'Extension':
                if rc.operator_value == 'is':
                    if file_path.endswith(rc.ext_value):
                        file_paths.append(file)
                        todo[file_path] = (rc.actions_value, file_category)
                elif rc.operator_value == 'is not':
                    if file_path.endswith(rc.ext_value):
                        pass
                    else:
                        file_paths.append(file)
                        todo[file_path] = (rc.actions_value, file_category)

            elif rc.condition_value == 'Date Added':
                dt = datetime.datetime.strptime(rc.date_edit_value, '%Y-%m-%d')
                new_dt = int(dt.strftime('%Y%m%d'))
                file_date = int(datetime.datetime.fromtimestamp(os.path.getctime(file_path)).strftime('%Y%m%d'))
                if rc.operator_value == 'is':
                    if new_dt == file_date:
                        file_paths.append(file)
                        todo[file_path] = (rc.actions_value, file_category)
                if rc.operator_value == 'is before':
                    if new_dt > file_date:
                        file_paths.append(file)
                        todo[file_path] = (rc.actions_value, file_category)
                if rc.operator_value == 'is after':
                    if new_dt < file_date:
                        file_paths.append(file)
                        todo[file_path] = (rc.actions_value, file_category)

            elif rc.condition_value == 'Size':
                global size_value
                size_value = float(size_value)
                if rc.operator_value == 'is':
                    size_of_file = human_size(os.path.getsize(file_path))
                    print("Calculated size of file: {}".format(size_of_file))
                    print("Size given in condition: {}".format(size_value))
                    if size_of_file == size_value == 0:
                        file_paths.append(file)
                    elif size_of_file == size_value:
                        file_paths.append(file)
                        todo[file_path] = (rc.actions_value, file_category)
                elif rc.operator_value == 'greater than':
                    size_of_file = human_size(os.path.getsize(file_path))
                    if size_of_file > size_value:
                        file_paths.append(file)
                        todo[file_path] = (rc.actions_value, file_category)
                elif rc.operator_value == 'less than':
                    size_of_file = human_size(os.path.getsize(file_path))
                    if size_of_file < size_value:
                        file_paths.append(file)
                        todo[file_path] = (rc.actions_value, file_category)

    return todo, file_paths

def run_task(rc, action_performed, file_to_process):  # file_to process == a
    if action_performed == 'Copy':
        actions.copy(file_to_process, rc.target_path)
    elif action_performed == 'Move':
        print(file_to_process)
        print(rc.target_path)
        actions.move(file_to_process, rc.target_path)
    elif action_performed == 'Delete':
        actions.delete(file_to_process)
    elif action_performed == 'Trash Bin':
        actions.trash_bin(file_to_process)
    elif action_performed == 'Rename':
        actions.rename(file_to_process, rc.rename_value)


from django.contrib.auth import get_user_model

from rest_framework import views, generics, permissions, status
from rest_framework.response import Response

from mlhaiti.accounts.api.serializers import UserSerializer

User = get_user_model()

class UserCreateView(generics.CreateAPIView):
    """
        User Registration
    """
    permission_classes = []
    serializer_class = UserSerializer
    queryset = User.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(
                {
                    'status':201,
                    'error':False,
                    'data':serializer.data,
                    'message':'user registred successfully'
                },
                status=status.HTTP_201_CREATED
            )

        return Response(
            {
                'status':400,
                'error':True,
                'data':[],
                'message':serializer.errors
            },
            status=status.HTTP_400_BAD_REQUEST
        )


# 这个抓取弹幕后保存为text文档，然后词云分析,此部分是抓取弹幕内容
__author__ = '布咯咯_rieuse'
__time__ = '2017.6.2'
__github__ = 'https://github.com/rieuse'

import multiprocessing
import re
import socket
import time
import datetime

import requests
from bs4 import BeautifulSoup

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 8601
client.connect(('119.96.201.28', port))

danmu_path = re.compile(b'txt@=(.+?)/cid@')
uid_path = re.compile(b'uid@=(.+?)/nn@')
nickname_path = re.compile(b'nn@=(.+?)/txt@')
level_path = re.compile(b'.*?/level@=(.*?)/')
# pattern = re.compile(b'type@=chatmsg/.+?/nn@=(.+?)/txt@=(.+?)/.+?/level@=(.+?)/')

def sendmsg(msgstr):
    msg = msgstr.encode('utf-8')
    data_length = len(msg) + 8
    code = 689
    msgHead = int.to_bytes(data_length, 4, 'little') \
              + int.to_bytes(data_length, 4, 'little') + int.to_bytes(code, 4, 'little')
    client.send(msgHead)
    sent = 0
    while sent < len(msg):
        tn = client.send(msg[sent:])
        sent = sent + tn

def start(roomid):
    # login request
    msg = 'type@=loginreq/username@=rieuse/password@=douyu/roomid@={}/\0'.format(roomid)
    sendmsg(msg)
    # get barrages
    msg_more = 'type@=joingroup/rid@={}/gid@=-9999/\0'.format(roomid)
    sendmsg(msg_more)

    # print('---------------欢迎连接到{}的直播间---------------'.format(get_name(roomid)))
    print('---------------欢迎连接到某一个直播间---------------')
    while True:
        data = client.recv(1024)
        print('-' * 100)
        uid_more = uid_path.findall(data)
        level_more = level_path.findall(data)
        danmu_more = danmu_path.findall(data)
        if not data:
            break
        else:
            for i in range(0, len(danmu_more)):
                with open('danmutxt2', 'a') as fo:
                    try:
                        danmu = danmu_more[i].decode(encoding='utf-8')
                        uid = uid_more[i].decode(encoding='utf-8')
                        level = level_more[i].decode(encoding='utf-8')
                        print("danmu: " + danmu)
                        print("user id: " + uid)
                        print("level: " + level + "\n")

                        # write to files
                        txt = str(datetime.datetime.now()) + "|   |"
                        txt += danmu + "|   |"
                        txt += uid + "|   |"
                        txt += level + '\n'
                        fo.writelines(txt)

                    except Exception as e:
                        print(e)
                        print('出错了\n')

def keeplive():
    while True:
        msg = 'type@=keeplive/tick@=' + str(int(time.time())) + '/\0'
        sendmsg(msg)
        time.sleep(10)

def get_name(roomid):
    r = requests.get("http://www.douyu.com/" + roomid)
    soup = BeautifulSoup(r.text, 'lxml')
    return soup.find('a', {'class', 'zb-name'}).string

if __name__ == '__main__':
    room_id = input('请输入房间ID： ')
    # room_id = 1756497
    p1 = multiprocessing.Process(target=start, args=(room_id,))
    p2 = multiprocessing.Process(target=keeplive)
    p1.start()
    p2.start()


from itertools import permutations

def solution(numbers):
    answer = 0
    already_check = []
    numbers = list(numbers)
    for i in range(len(numbers)):
        for j in permutations(numbers, i+1):
            temp = int("".join(j))
            if prime_check(temp) and temp not in already_check:
                already_check.append(temp)
                answer += 1

    return answer

import math
def prime_check(n):
    if n < 2:
        return False
    for i in range(2, int(math.sqrt(n))+1):
        if n % i == 0:
            return False
    return True

print(solution("011"))


class Queen:
    def __init__(self, row: int, column: int) -> None:
        if any(idx not in range(8) for idx in (row, column)):
            raise ValueError('Error')

        self.x = row
        self.y = column

    def can_attack(self, o: 'Queen') -> bool:
        if self.x == o.x and self.y == o.y:
            raise ValueError('Error')

        return self.x == o.x \
            or self.y == o.y \
            or abs(self.x - o.x) == abs(self.y - o.y)


import requests
import json
from BookingCar import startQuery
import configparser
import os
from tqdm import tqdm
class queryStationList:
	def __init__(self):
		if "isHeroku" in os.environ:
			IDNumber = os.environ["IDNO"]
			DeviceID = os.environ["DeviceID"]
			print (IDNumber)
			print (DeviceID)
		else:
			config = configparser.ConfigParser()
			config.read('Config.ini')

			#讀取身分證字號
			IDNumber =str(config.get(
				'identifyInformation', 'IDNO'))
			#讀取手機ID
			DeviceID =str(config.get(
				'identifyInformation', 'DeviceID'))

		self.my_data = {
			"para": {
				"app": "1",
				"ProjID": "ALL",
				"ProjMode": 0,
				"appVersion": "3.0.29",
				"DeviceID": DeviceID
			}
		}

	def searchPark(self, CarType,CityName):
		#租賃站的名稱
		stationNameLi = []
		#租賃站ID
		stationIDLi = []

		#station
		stationGISLi = []

		stationAddr = []
		# 將資料加入 POST 請求中
		r = requests.post(
			'https://irent.irentcar.com.tw/iMotoAPI/api/Preferential', json=self.my_data)
		stations = json.loads(r.text)
		if "ErrorCode" in stations:
			if stations["ErrorCode"] != "000000":
				return stations["ErrMsg"]
		#要查詢租車一定要專案ID
		projID = stations["data"][1]["ProjID"]
		#選擇不同縣市的同站租還專案
		for station in stations["data"][1]["Station"]:
			if station["Area"] == CityName:
				#租車站地址
				addr = station["ADDR"]
				#租車站ID
				siteID = station["Site_ID"]

				#租賃站點的中文名稱
				SiteName = station["SiteName"]
				lat, lng = station["Lat"], station["Lng"]
				ADDR = station["ADDR"]
				#可以輸出站點資訊
				# print("SiteName:{0} Addr:{1} siteID:{2}".format(SiteName , addr, siteID))

				#增加篩選車型功能，如果該站點沒有該車型，那就不要去詢問有沒有車
				for car in station["CarType"]:
					if car["TypeID"] == CarType:
						carID = car["TypeID"]
						typeName = car["TypeName"]
						#有該車型，那就加入搜尋的停車場列表
						stationNameLi.append(SiteName)
						stationIDLi.append(siteID)
						stationGISLi.append([lat, lng])
						stationAddr.append(ADDR)
						#依照各車型輸出詳情
						# print("CarID:{0} TypeName:{1}".format(carID,typeName))
		return stationNameLi, stationIDLi, stationGISLi,stationAddr

	def start(self,startQuery,Starttime,EndTime,CarType,CityName):
		try:
			#將所有的租賃站ID跟名稱列出來
			stationNameLi, stationIDLi, stationGISLi, stationAddr = self.searchPark(
				CarType, CityName)
		except ValueError:
			#返回錯誤，可能是請先登入等驗證問題
			return self.searchPark(CarType, CityName)
		index = 0
		hasCarStation = []
		for stationName in tqdm(stationNameLi):
			StationName = stationName
			StationID = stationIDLi[index]
			#座標位置
			stationGIS = stationGISLi[index]

			Addr = stationAddr[index]
			result = startQuery.getCar(
				Starttime, EndTime, CarType, StationName, StationID, stationGIS,Addr)
			if result != None:
				if "ErrMsg" in result:
					yield result["ErrMsg"]
				hasCarStation.append(result)
			index += 1
			yield len(stationNameLi),hasCarStation
		#回傳有車的站點
		yield len(stationNameLi),hasCarStation
if __name__ == "__main__":
	queryStationList = queryStationList()
	startQuery = startQuery()
	queryStationList.start(startQuery)


from tkinter import *

class App(Frame):
    def __init__(self, root):
        super().__init__(root, width=400, height=300)
        self.pack()
        self._init_menus(root)
        self.create_menubutton()
        self.selected_font_name = self.create_options_menu()

    def _init_menus(self, root):
        # create the menubar
        self.menubar = Menu(root)

        # create the File menu
        filemenu = Menu(self.menubar, tearoff=0)
        # and add its commands
        filemenu.add_command(label='New Tab', accelerator='Command+T', activebackground='blue', activeforeground='white',
                             command=lambda e: print('Create new tab'))
        filemenu.add_command(label='New Window', accelerator='Command+N', activebackground='blue', activeforeground='white',
                             command=lambda e: print('Create new window'))
        filemenu.add_command(label='New Incognito Window', accelerator='Shift+Command+N', activebackground='blue', activeforeground='white',
                             command=lambda e: print('Create new incognito window'))
        filemenu.add_command(label='Open File...', accelerator='Command+O', activebackground='blue', activeforeground='white',
                             command=lambda e: print('Open a file'))
        filemenu.add_command(label='Open Location...', accelerator='Command+L', activebackground='blue', activeforeground='white',
                             command=lambda e: print('Open a location'))
        filemenu.add_separator()
        filemenu.add_command(label='Print...', accelerator='Command+P', activebackground='blue', activeforeground='white',
                             command=lambda e: print('Print'))
        # attach the File menu to the menubar
        self.menubar.add_cascade(label='File', menu=filemenu)

        # create the Edit menu
        editmenu = Menu(self.menubar)
        # and add its commands
        editmenu.add_command(label='Cut', accelerator='Command+X', activebackground='blue', activeforeground='white',
                             command=lambda e: print('Edit->Cut'))
        editmenu.add_command(label='Copy', accelerator='Command+C', activebackground='blue', activeforeground='white',
                             command=lambda e: print('Edit->Copy'))
        editmenu.add_command(label='Paste', accelerator='Command+V', activebackground='blue', activeforeground='white',
                             command=lambda e: print('Edit->Paste'))
        editmenu.add_separator()

        # create the Edit->Find menu
        findmenu = Menu(editmenu)
        # and add its commands
        findmenu.add_command(label='Find...', accelerator='Command+F', activebackground='blue', activeforeground='white',
                             command=lambda e: print('Edit->Find->Find'))
        findmenu.add_command(label='Find Next', accelerator='Command+G', activebackground='blue', activeforeground='white',
                             command=lambda e: print('Edit->Find->Find next'))
        findmenu.add_command(label='Find Previous', accelerator='Shift+Command+G', activebackground='blue', activeforeground='white',
                             command=lambda e: print('Edit->Find->Find Previous'))
        # attach Find to the Edit menu
        editmenu.add_cascade(label='Find', activebackground='blue', activeforeground='white', menu=findmenu)
        # attach Edit menu to the menubar
        self.menubar.add_cascade(label='Edit', menu=editmenu)
        # configure top-level window with the menubar
        root.config(menu=self.menubar)

    def create_menubutton(self):
        self.mb = Menubutton(self, text='More Tools', relief=RAISED, width=12, height=2, padx=5, pady=3)
        self.mb.pack(side=BOTTOM)

        self.mb.menu = Menu(self.mb, tearoff=0)
        self.mb['menu'] = self.mb.menu

        self.fsVar = IntVar()
        self.mb.menu.add_checkbutton(label='Show Full Screen', accelerator='Command+F',
                                     variable=self.fsVar)
        self.mb.menu.add_command(label='Clear Browsing data...', accelerator='Shift+Command+Backspace', command=lambda e: print('Clear Browsing Data'))
        self.mb.menu.add_command(label='Extensions', command=lambda e: print('Extensions'))
        self.mb.menu.add_command(label='Task Manager', command=lambda e: print('Task Manager'))
        self.mb.menu.add_command(label='Developer Tools', accelerator='Alt+Command+I', command=lambda e: print('Developer Tools'))

    def create_options_menu(self):
        options = ('Helvetica', 'Verdana', 'Arial', 'Courier')
        self.font = StringVar()
        self.font.set(options[0])
        OptionMenu(self, self.font, *options, command=self.font_selection_changed).pack()

    @staticmethod
    def font_selection_changed(selection):
        print('selected font: {}'.format(selection))

root = Tk()
app = App(root)

mainloop()


from thefuck.utils import is_app, get_closest, replace_argument

_ADB_COMMANDS = (
    'backup',
    'bugreport',
    'connect',
    'devices',
    'disable-verity',
    'disconnect',
    'enable-verity',
    'emu',
    'forward',
    'get-devpath',
    'get-serialno',
    'get-state',
    'install',
    'install-multiple',
    'jdwp',
    'keygen',
    'kill-server',
    'logcat',
    'pull',
    'push',
    'reboot',
    'reconnect',
    'restore',
    'reverse',
    'root',
    'run-as',
    'shell',
    'sideload',
    'start-server',
    'sync',
    'tcpip',
    'uninstall',
    'unroot',
    'usb',
    'wait-for',
)

def match(command):
    return (is_app(command, 'adb')
            and command.output.startswith('Android Debug Bridge version'))

def get_new_command(command):
    for idx, arg in enumerate(command.script_parts[1:]):
        # allowed params to ADB are a/d/e/s/H/P/L where s, H, P and L take additional args
        # for example 'adb -s 111 logcat' or 'adb -e logcat'
        if not arg[0] == '-' and not command.script_parts[idx] in ('-s', '-H', '-P', '-L'):
            adb_cmd = get_closest(arg, _ADB_COMMANDS)
            return replace_argument(command.script, arg, adb_cmd)


import json
import base64
import base58
import struct
import requests
from typing import NamedTuple

class Creator(NamedTuple):
    Address: str
    Verified: bool
    Share: int

class Data(NamedTuple):
    Name: str
    Symbol: str
    Uri: str
    SellerFeeBasisPoints: int
    Creators: list

class Metadata(NamedTuple):
    Key: int
    UpdateAuthority: str
    Mint: str
    Data: Data
    PrimarySaleHappened: bool
    IsMutable: bool
    EditionNonce: int

def decode_rust_string(buffer: bytes, offset: int, isascii=True):
    ssize_r = struct.unpack("I", buffer[offset:(offset+4)])
    ssize = ssize_r[0]  # ssize_r=(ssize,)
    data = buffer[(offset+4):(offset+ssize+4)]
    if isascii:
        data_str = data.decode("ascii")
    else:
        data_str = data
    return data_str, ssize + 4  # sizeof uint is 4

def deserialize(s: str) -> str:
    """metadata struct:
    Key                     uchar
    UpdateAuthority         pubkey (4 bytes)
    Mint                    pubkey (4 bytes)
    Data                    Data
    PrimarySaleHappened     bool
    IsMutable               bool
    EditionNonce            *uint8

    Data struct:
    Name                    string
    Symbol                  string
    Uri                     string
    SellerFeeBasisPoints    uint16
    Creators                *[]Creator

    Creator struct:
    Address                 pubkey (4 bytes)
    Verified                bool
    Share                   uint8
    """
    b = base64.b64decode(s)
    key_r = struct.unpack("B", b[:1])
    key = key_r[0]  # key_r = (key,)
    ua = base58.b58encode(b[1:33]).decode("ascii")
    mint = base58.b58encode(b[33:65]).decode("ascii")

    name, name_offset = decode_rust_string(b, 65)
    symbol, symbol_offset = decode_rust_string(b, 65 + name_offset)
    uri, uri_offset = decode_rust_string(b, 65 + symbol_offset + name_offset)

    new_offset = 65 + symbol_offset + name_offset + uri_offset
    sfbp = struct.unpack("H", b[new_offset:(new_offset+2)])[0]
    new_offset += 2

    # creators pointer
    creators_pt = struct.unpack("B", b[new_offset:(new_offset+1)])[0]
    new_offset += 1

    # unpack creators
    size = struct.unpack("I", b[new_offset:(new_offset+4)])[0]
    new_offset += 4
    creators = list()
    creators_out = list()
    for _ in range(size):
        c = dict()
        c["Address"] = base58.b58encode(b[new_offset:(new_offset+32)]).decode("ascii")
        new_offset += 32
        c["Verified"] = struct.unpack("?", b[new_offset:(new_offset+1)])[0]
        new_offset += 1
        c["Share"] = struct.unpack("B", b[new_offset:(new_offset+1)])[0]
        new_offset += 1
        creators.append(c)
        creators_out.append(
            #Creator(c["Address"], c["Verified"], c["Share"])
            {
                'address' : c["Address"],
                'verified' : c["Verified"]
            }
        )

    primary_sale_happened = struct.unpack("?", b[new_offset:(new_offset+1)])[0]
    new_offset += 1
    is_mutable = struct.unpack("?", b[new_offset:(new_offset+1)])[0]
    new_offset += 1

    # creators pointer
    edition_pt = struct.unpack("B", b[new_offset:(new_offset+1)])[0]
    new_offset += 1
    edition_nonce = struct.unpack("B", b[new_offset:(new_offset+1)])[0]
    new_offset += 1

    #
    #  post processing
    #
    def remove_x00(s:str) -> str:
        return s.replace(b"\x00".decode("ascii"), "")
    uri = remove_x00(uri)
    name = remove_x00(name)
    symbol = remove_x00(symbol)

    # create data struct with creators list of structs inside
    #data_out = Data(name, symbol, uri, sfbp, creators_out)
    data_out = {
        'name': name,
        'symbol': symbol,
        'uri' : uri,
        'sfbp' :sfbp,
        'creators_out' : creators_out
    }

    #metadata_out = dict(key, ua, mint, data_out, primary_sale_happened, is_mutable, edition_nonce)
    metadata_out = {
        'key' : key,
        'ua' :ua,
        'mint': mint,
        'data_out': data_out,
        'primary_sale_happened': primary_sale_happened,
        'is_mutable': is_mutable,
        'edition_nonce' : edition_nonce
    }

    if False:
        print(f"""key={key}
mint={mint}
ua={ua}
name={name}
symbol={symbol}
uri={uri}
sfbp={sfbp}
*creators={creators_pt}
creators={creators}
primary_sale_happened={primary_sale_happened}
is_mutable={is_mutable}
*edition_nonce={edition_pt}
edition_nonce={edition_nonce}
"""
    )
    # print(b[new_offset:])
    # possibly some leftover shit

    return metadata_out

def deserialize_handler(d: dict) -> str:
    return deserialize(d["account"]["data"][0])

output = []
temp_output = []
creator_list = dict()

def set_wide_analysis(data):
    #with open("kam1_analysis.txt", "w") as f:
    for i in range(len(data["result"])):
        res = deserialize_handler(data['result'][i])
        for row in res['data_out']['creators_out']:
            if (row['verified'] == True):
                verified_address = row['address']
                if verified_address not in creator_list:
                    creator_list[verified_address] = 1
                else:
                    creator_list[verified_address] += 1
        temp_output.append([verified_address, res])

    # creators = []
    # for row in temp_output:
    #     if row[0] == max(creator_list, key=creator_list.get):
    #         print(row[1]['mint'])
    #         r = requests.get(row[1]['data_out']['uri']).json()
    #         creator_data = r['properties']['creators']
    #         for row in creator_data:
    #             creators.append(row['address'])
    #         break

    # print(creators)

    #Compare it to the most popular verified creator... doesn't work for multiple creators
    #Will need to check through mint authority
    for row in temp_output:
        if row[0] == max(creator_list, key=creator_list.get):
            output.append(row[1])
        else:
            #print(row[1]['mint'])
            continue

    with open('testoutput.json', 'w') as f:
        json.dump(temp_output, f)

    print(len(output))
    print(creator_list)

    #print(creator_list)

    #print(json.dumps(output))

with open("output_KAM1.json", "r") as f:
    data = json.load(f)

# print(deserialize_handler(data['result'][1]))
set_wide_analysis(data)


#!/bin/python

import math
import os
import random
import re
import sys

def calculateEnergy(n):
    return 1 if n == 0 else 3

def jumpingOnClouds(c, k):
    ar = list(c)
    energy = 100
    i = 0
    while((i+k) % n != 0):
        energy -= calculateEnergy(ar[(i+k) % n])
        i += k
    return (energy - calculateEnergy(ar[0]))

if __name__ == '__main__':
    # fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n, k = map(int, input().split())

    c = map(int, input().rstrip().split())

    result = jumpingOnClouds(c, k)

    print(result)

    # fptr.write(str(result) + '\n')

    # fptr.close()

"""
10 3
1 1 1 0 1 1 0 0 0 0
80
"""

Jumping on the Clouds: Revisited/main.py


from typing import Optional, List
from fastapi import FastAPI, Request, Query
import sys
sys.path.insert(0,'../..')
from importlib import import_module

from python_apps.p20_ml_prediction import main

app = FastAPI()

# Creates new instance.
my_instance = main.p20_ml()

# Defaults
sample_data="Lee"

@app.get("/")
def read_root():
    """
    Displays main page
    """
    return (my_instance.predict_nationality(sample_data))

@app.get("/names/")
async def read_item(request: Request, name: str = Query(None, min_length=3, max_length=50)):
    if request.method == 'GET':
        namequery = request.query_params["name"]
        data = [namequery]
        model_file="/tmp/naive_bayes.pkl"
        result = my_instance.predict_nationality(data, model_file)
        return {"orig_name": data, "prediction": result, "model_file_used": model_file}

# uvicorn 20_ml1:app --reload
# http://127.0.0.1:8000/names/?name=Lee


numbers = []
strings = []
names = ["Adam", "John", "Eric", "Jessica", "Mark", "Jack"]

numbers.append(1)
numbers.append(2)
numbers.append(3)

strings.append("Hello")
strings.append("World")

second_name = names[2]

print (numbers)
print (strings)
print ("The second name on the name list is %s" % second_name)
names.sort()
print(names)

Python Language/2D Lists & Nested Loops/Activity 2.py