import os
import argparse
import time
import logging
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
from math import log, floor
from datetime import datetime
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures import as_completed

def setup_logging(directory):
    directory_name = os.path.basename(os.path.normpath(directory))
    log_file = f"logs/{directory_name}.log"
    logging.basicConfig(filename=log_file, level=logging.INFO,
                        format="%(asctime)s - %(levelname)s: %(message)s")
    logging.getLogger().addHandler(logging.StreamHandler())

def convert_size(size_bytes):
    if size_bytes == 0:
        return "0B", 0
    size_name = ("B", "KB", "MB", "GB", "TB")
    i = int(floor(log(size_bytes, 1024)))
    p = pow(1024, i)
    s = round(size_bytes / p, 2)
    return f"{s} {size_name[i]}", size_bytes

def human_readable_time(seconds):
    if seconds < 1:
        return f"{seconds * 1000:.2f} ms"
    elif seconds < 60:
        return f"{seconds:.2f} s"
    elif seconds < 3600:
        return f"{seconds / 60:.2f} min"
    else:
        return f"{seconds / 3600:.2f} hr"

memoized_sizes = {}
def get_directory_size(path):
    if path in memoized_sizes:
        return memoized_sizes[path]
    total = 0
    for dirpath, dirnames, filenames in os.walk(path):
        for file in filenames:
            file_path = os.path.join(dirpath, file)
            if not os.path.islink(file_path):
                total += os.path.getsize(file_path)
    memoized_sizes[path] = total
    return total

def get_directory_data(directory, max_depth=5):
    current_time = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
    entries_list = []

    # Added a depth control
    depth = directory.count(os.sep)
    if depth > max_depth:
        return entries_list

    for dirpath, dirnames, filenames in os.walk(directory):
        for dirname in dirnames:
            path = os.path.join(dirpath, dirname)
            size_readable, size_bytes = convert_size(get_directory_size(path))

            # Filtering directories with size < 10MB
            # if size_bytes < 10_485_760:  # 10 MB in bytes
            #     continue

            entries_list.append({
                "path": path,
                "name": dirname,
                "size_readable": size_readable,
                "size_bytes": size_bytes,
                "type": "directory",
                "parent_directory": dirpath,
                "scrape_timestamp": current_time
            })
        for filename in filenames:
            path = os.path.join(dirpath, filename)

            try:
                size_readable, size_bytes = convert_size(os.path.getsize(path))

                # Filtering files with size < 10MB
                # if size_bytes < 10_485_760:  # 10 MB in bytes
                #     continue

                entries_list.append({
                    "path": path,
                    "name": filename,
                    "size_readable": size_readable,
                    "size_bytes": size_bytes,
                    "type": "file",
                    "parent_directory": dirpath,
                    "scrape_timestamp": current_time
                })
            except FileNotFoundError:
                continue  # Just skip if file not found

    # Sort the data by size in descending order before returning
    return sorted(entries_list, key=lambda x: x['size_bytes'], reverse=True)

def parallel_directory_walker(root_directory, max_workers=4):
    directories = [os.path.join(root_directory, dir_name) for dir_name in os.listdir(root_directory) if os.path.isdir(os.path.join(root_directory, dir_name))]
    all_entries = []

    with ProcessPoolExecutor(max_workers=max_workers) as executor:
        futures = {executor.submit(get_directory_data, dir_path): dir_path for dir_path in directories}

        for future in as_completed(futures):
            all_entries.extend(future.result())

    return all_entries

def index_exists(es, index_name):
    return es.indices.exists(index=index_name)

def create_index_with_mapping(es, index_name, mapping):
    return es.indices.create(index=index_name, body=mapping)

def generate_mapping_from_data(data):
    mapping = {}
    if isinstance(data, dict):
        properties = {}
        for key, value in data.items():
            properties[key] = generate_mapping_from_data(value)
        mapping["properties"] = properties
    elif isinstance(data, str):
        try:
            datetime.strptime(data, '%Y-%m-%d %H:%M:%S')
            return {"type": "date", "format": "yyyy-MM-dd HH:mm:ss"}
        except ValueError:
            return {"type": "text"}
    else:
        return {"type": "text"}
    return mapping

def add_to_alias(es, index_name, alias_name):
    if not es.indices.exists_alias(name=alias_name):
        es.indices.put_alias(index=index_name, name=alias_name)
    else:
        alias_data = es.indices.get_alias(name=alias_name)
        if index_name not in alias_data:
            es.indices.update_aliases(body={
                "actions": [
                    {"add": {"index": index_name, "alias": alias_name}}
                ]
            })

def get_alias_name_from_directory(directory):
    return os.path.basename(os.path.normpath(directory))

def delete_index_if_exists(es, index_name):
    if index_exists(es, index_name):
        es.indices.delete(index=index_name)

def upload_to_elasticsearch(directory, data_list):
    es = Elasticsearch(
        [{'host': '192.168.50.99', 'port': 9200, 'scheme': 'http'}],
        basic_auth=('elastic', 'LRvs=smuDyD1b1KcUhYs')
    )
    index_name = f"truenas_directory_data_{get_alias_name_from_directory(directory).lower()}"
    root_alias_name = "truenas_directory_data"

    # Delete the index if it already exists
    delete_index_if_exists(es, index_name)

    if not index_exists(es, index_name):
        mapping = {
            "mappings": generate_mapping_from_data(data_list[0] if data_list else {})
        }
        create_index_with_mapping(es, index_name, mapping)

    # Prepare data for bulk indexing
    actions = [
        {
            "_index": index_name,
            "_source": entry
        }
        for entry in data_list
    ]

    # Use the bulk API
    bulk(es, actions)

    add_to_alias(es, index_name, root_alias_name)
    add_to_alias(es, index_name, get_alias_name_from_directory(directory))

def main():
    parser = argparse.ArgumentParser(description='Scan a directory and create a flat list of file data.')
    parser.add_argument('directory', type=str, help='The directory to scan')
    args = parser.parse_args()
    setup_logging(args.directory)
    start_time = time.time()
    flat_data = parallel_directory_walker(args.directory)

    # Sort by size and slice to keep only top 10,000 entries
    flat_data = sorted(flat_data, key=lambda x: x['size_bytes'], reverse=True)[:10000]

    logging.info(f"{args.directory} has been scanned, uploading data...")
    upload_to_elasticsearch(args.directory, flat_data)
    elapsed_time = time.time() - start_time
    logging.info(f"Data for {args.directory} uploaded to Elasticsearch.")
    logging.info(f"Total scanning time: {human_readable_time(elapsed_time)}")

if __name__ == "__main__":
    main()


import random
from openpyxl import Workbook

for i in range(1, 6):

    wb = Workbook()

    for j in range(5):
        ws = wb.create_sheet()

    for x, ws in enumerate(wb, 1):
        ws.title = ('sheet' + str(x).zfill(3))
        for row in range(1, 40):
            ws.append([100*random.random() for _ in range(10)])

    wb.save('book' + str(i).zfill(2) + '.xlsx')


#!/usr/bin/env python3
import os
from collections import defaultdict
from collectRashyUnitIdReplacements import get_unit_type_mapping

replacements = [
	('{~add-ons/Rashy_Era/','{~ERROR_RE_ABSOLUTE_PATH/'),

	("VR_", "AE_RHY_"),
	("vr-", "AE_rhy_"),

	("""
    description= _ ""","""
    description={AE_RHY_UNIT_NOTICE}+ _ """),
	("""
	description= _ ""","""
    description={AE_RHY_UNIT_NOTICE}+ _ """),
	("""
    description=_ ""","""
    description={AE_RHY_UNIT_NOTICE}+ _ """),
	("""
	description=_ ""","""
    description={AE_RHY_UNIT_NOTICE}+ _ """),
	("""
    description=_""","""
    description={AE_RHY_UNIT_NOTICE}+ _ """),
	("""
	description=_""","""
    description={AE_RHY_UNIT_NOTICE}+ _ """),
	("""
    description={NO_DESCR_AVAILABLE}""","""
    description={AE_RHY_UNIT_NOTICE}+{NO_DESCR_AVAILABLE}"""),
	("__DUMMY__","__DUMMY__")
]

unit_type_mapping = get_unit_type_mapping()
for k in sorted(unit_type_mapping, key=lambda x: -len(x)):
	replacements.append((k, unit_type_mapping[k]))

def getAgelessPath(dname, fname):
	if "factions" in dname:
		return os.path.join(".","Ageless_Era","factions","RE",fname)
	if "units" in dname:
		basename = os.path.basename(dname)
		if basename == "units":
			basename = ""
		return os.path.join(".","Ageless_Era","units","RE_units",basename,fname)
	if "macros" in dname:
		return os.path.join(".","Ageless_Era","data","RE_data",fname)
	raise Exception("Unhandled folder {}".format(dname))

eras = defaultdict(str)
for dname, dirs, files in os.walk("."):
	if "factions" not in dname and "units" not in dname and "macros" not in dname:
		continue
	if "Ageless_Era" in dname or "images" in dname:
		continue
	print(dname)
	for fname in files:
		fpath = os.path.join(dname, fname)
		afpath = getAgelessPath(dname, fname)
		# print(fpath, afpath)
		with open(fpath,encoding="utf8") as f:
			s = f.read()
		for (find, replace) in replacements:
			s = s.replace(find, replace)
		if "factions" in dname:
			s = s.replace("{AE_RHY_UNIT_NOTICE}+", "")
			s = s.replace('name= _"', 'name= "RE - " + _"')
			s = s.replace('name=_"', 'name= "RE - " + _"')
			if "default" in fname:
				eras["default"] += s
				eras["default"] += "\n"
			elif "aoh" in fname:
				eras["heroes"] += s
				eras["heroes"] += "\n"
			elif "mrpg" in fname:
				eras["RPG"] += s
				eras["RPG"] += "\n"
			# TODO no rpg era
		else:
			os.makedirs(os.path.dirname(afpath), exist_ok=True)
			with open(afpath, "w", encoding="utf8") as f:
				f.write(s)

if eras["RPG"] == "":
	rpg_era = ""
	for line in eras["default"].split("\n"):
		if "type=" in line or "leader=" in line or "ai]" in line or "recruitment_pattern=" in line:
			continue
		line = line.replace("recruit=","leader=")
		rpg_era += line + "\n"
	eras["RPG"] = rpg_era

with open("Ageless_Era/units/RE_units/units.cfg", "a", encoding="utf8") as f:
	f.write("""

{GET_AE_UNITS RE_units/aquana}
{GET_AE_UNITS RE_units/dwarves}
{GET_AE_UNITS RE_units/elves-dark}
{GET_AE_UNITS RE_units/elyser}
{GET_AE_UNITS RE_units/gnomes}
{GET_AE_UNITS RE_units/human-chevalier}
{GET_AE_UNITS RE_units/human-dardo}
{GET_AE_UNITS RE_units/human-forest}
{GET_AE_UNITS RE_units/human-luz}
{GET_AE_UNITS RE_units/human-mountain}
{GET_AE_UNITS RE_units/human-regis}
{GET_AE_UNITS RE_units/marashy}
{GET_AE_UNITS RE_units/ships}
{GET_AE_UNITS RE_units/trarashy}
{GET_AE_UNITS RE_units/undead}
{GET_AE_UNITS RE_units/vixens}
""")

# factions to file
for era in eras:
	os.makedirs(os.path.dirname("Ageless_Era/factions/{}/".format(era)), exist_ok=True)
	with open("Ageless_Era/factions/{}/{}-RE.cfg".format(era, era), "w", encoding="utf8") as f:
		f.write(eras[era])


import aocd

data = aocd.get_data(day=6, year=2022)

def part1(data, n=4):
    for i in range(len(data)-n):
        if len(set(list(data[i:i+n]))) == n:
            return i+n

def part2(data):
    return part1(data, 14)

print(part1(data))
print(part2(data))


#!/usr/bin/env python3

# IPP Projekt 2 - Interpret.py
# Autor: Vojtech Fiala <xfiala61>

import sys
import re
import xml.etree.ElementTree as ET

# Globalni promenne pro zjednoduseni prace
labels = {}
temp_frame_init = False
local_frame_init = False
global_frame = {}
global_frame_types = {}
temp_frame = {}
temp_frame_types = {}
local_frame = {}
local_frame_types = {}
local_frame_stack = []
local_frame_types_stack = []
call_stack = []
var_stack = []
var_stack_type = []

def print_help():
    print("Skript akceptuje nasledujici parametry:")
    print("        --help                -> Vypise tuto napovedu.")
    print("        --source=file         -> Vstupni soubor s XML reprezentaci zdrojoveho kodu. Nelze kombinovat s --input.")
    print("        --input=file          -> Soubor se vstupy pro samotnou interpretaci zadaneho zdrojoveho kodu. Nelze kombinovat s --source")
    print("        Alespon jeden z parametru --source nebo --input musi byt vzdy zadan. Pokud jeden z nich chybi, jsou data ctena ze STDIN.")

# Podpurna funkce pro ukonceni programu s chybovou hlaskou na STDERR a spravnou navratovou hodnotou
def stderr_exit(message, code):
    sys.stderr.write(message)
    exit(code)

# Funkce na ziskani cesty k souboru z argumentu
def getPath(path):
    path = path.split('=')
    if (len(path) != 2):
        stderr_exit("Neplatna cesta k souboru!", 11)
    return path[1]

# Funkce na zpracovani argumentu
def parse_args():
    help_toggle = False
    source_toggle = False
    source_path = ""
    input_path = ""
    input_toggle = False
    # Zacni az od 2., protoze 1. je nazev souboru a ten me nezajima
    for arg in sys.argv[1:]:
        if (re.search("^--help$", arg)):
            help_toggle = True
        elif (re.search("^--source=.+$", arg)):
            source_toggle = True
            source_path = getPath(arg)
        elif (re.search("^--input=.+$", arg)):
            input_toggle = True
            input_path = getPath(arg)
        else:
            stderr_exit("Neplatny argument! Pro zjisteni povolenych argumentu, pouzijte parametr --help\n", 10)

    # Kontrola, jestli nebyly zadane nepovolene kombinacce argumentu
    if (help_toggle and len(sys.argv) > 2):
        stderr_exit("Neplatna kombinace argumentu! Pro zjisteni povolenych argumentu, pouzijte parametr --help\n", 10)

    if (help_toggle):
        print_help()
        exit(0)

    if (not source_toggle and not input_toggle):
        stderr_exit("Neplatna kombinace argumentu! Pro zjisteni povolenych argumentu, pouzijte parametr --help\n", 10)

    return source_path, input_path

# Funkce pro zjisteni, zda-li zadane soubory existuji
def testFiles(source_path, input_path):
    if (source_path != ""):
        try:
            f = open(source_path)
            f.close()
        except:
            exit(11)
    if (input_path != ""):
        try:
            f = open(input_path)
            f.close()
        except:
            exit(11)

# Nacti obsah zadanycch souboru, pripadne stdin
def loadContent(source_path, input_path):

    testFiles(source_path, input_path)
    input_get = None
    tree = None

    # Jestlize nebyl zadany source argument, cti ze stdin
    try:
        if (source_path == ""):
            tree = ET.parse(sys.stdin)
        else:
            tree = ET.parse(source_path)
    except:
        sys.exit(31)

    if (input_path != ""):
        f = open(input_path, "r")
        sys.stdin = f
    return tree

# Funkce pro ziskani hodnoty promenne
def getVarValue(var):
    global global_frame
    global local_frame
    global temp_frame

    if (var == None):
        return ""

    # Jestlize je kratsi nez 4 (nejkratsi mozne jmeno promenne)
    # Tak rovnou vrat co jsi dostal, neni duvod ziskavat hodnotu, toto uz je hodnota
    var = str(var)
    if (len(var) < 4):
        return var

    # Nacti z pripadne promenne hodnotu
    frame = var[:3]
    name = var[3:]
    value = None
    # Zjisti ramec, podle ktereho spravne prirad promennou
    if (frame == "GF@"):
        if not (varExists(name, global_frame)):
            exit(54)
        value = global_frame.get(name)
    elif (frame == "LF@"):
        if not (frame_initialized(local_frame)):
            exit(55)
        if not (varExists(name, local_frame)):
            exit(54)
        value = local_frame.get(name)
    elif (frame == "TF@"):
        if not (frame_initialized(temp_frame)):
            exit(55)
        if not (varExists(name, temp_frame)):
            exit(54)
        value = temp_frame.get(name)
    else:
        return var

    return value

# Funkce pro ziskani typu promenne
def getVarType(symb, typee):
    global local_frame_types
    global global_frame_types
    global temp_frame_types
    if (typee == 'int'):
        return "int"
    if (typee == 'string'):
        return "string"
    if (typee == 'bool'):
        return "bool"
    if (typee == 'nil'):
        return "nil"
    if (typee == 'var'):
        frame, name = getFrame(symb)
        if (frame == "GF@"):
            return global_frame_types.get(name)
        elif (frame == "TF@"):
            return temp_frame_types.get(name)
        else:
            return local_frame_types.get(name)

# Funkce pro prekonvertovani specialnich znaku stringu (\005 etc) na znaky
def convertString(string):
    ret = ""
    i = 0
    if (string == ""):
        return ret
    if (string == None):
        return None
    length = len(string)
    while i < length:
        if (string[i] == '\\'):
            try:
                val = chr(int(string[i+1] + string[i+2] + string[i+3]))
            except:
                exit(52)
            i += 3
        else:
            val = string[i]
        ret += val
        i+=1

    return ret

# Funkce na kontrolu validity vyrazu daneho typu
def validVar(var):
    if (re.search("^(LF|GF|TF)@[A-Za-z_\-$&%*!?][A-Za-z0-9_\-$&%*!?]*$", var)):
        return True
    return False

def validInt(intt):
    if (re.search("^(\-|\+)?[0-9]+$", intt)):
        return True
    return False

def validString(string):
    if (string != None):
        length = len(string)
        i = 0
        while (i < length):
            # Jestlize se ve stringu nachazi backslash, musi za nim byt 3 cisla
            if (string[i] == '\\'):
                if (i + 3 < length):
                    if (ord(string[i+1]) < 48 or ord(string[i+1]) > 57):
                        exit(32)
                    if (ord(string[i+2]) < 48 or ord(string[i+2]) > 57):
                        exit(32)
                    if (ord(string[i+3]) < 48 or ord(string[i+3]) > 57):
                        exit(32)
                else:
                    exit(32)
            i += 1

    return True

def validBool(bool_val):
    if (re.search("^(true|false)$", bool_val)):
        return True
    return False

def validNil(nil):
    if (re.search("^nil$", nil)):
        return True
    return False

def validLabel(label):
    if (re.search("^[A-Za-z_\-$&%*!?][A-Za-z0-9_\-$&%*!?]*$", label)):
        return True
    return False

def validSymb(symb_type, symb):
    if (symb_type == "string"):
        if (validString(symb)):
            return True
    elif (symb_type == "int"):
        if (validInt(symb)):
            return True
    elif (symb_type == "var"):
        if (validVar(symb)):
            return True
    elif (symb_type == "bool"):
        if (validBool(symb)):
            return True
    elif (symb_type == "nil"):
        if (validNil(symb)):
            return True
    return False

def validType(typee):
    if (re.search("^(int|string|bool)$", typee)):
        return True
    return False

# Podpurne funkce na kontrolu, jestli instrukce obsahuje spravny pocet argumentu validniho typu
def checkLengths(parent, check):
    if (len(parent) != check):
        exit(32)

# Funkce na serazeni argumentu instrukci v pripade, ze jsou argumenty 3
def sortinstrArgs(parent, arg1, arg2, arg3):
    if (arg1.tag == "arg1" and arg2.tag == "arg3" and arg3.tag == "arg2"):
        tmp = arg2
        tmpp = arg3
        arg3 = arg2
        arg2 = tmpp

        parent[2] = arg3
        parent[1] = arg2

    if (arg1.tag == "arg2" and arg2.tag == "arg1" and arg3.tag == "arg3"):
        tmp = arg2
        tmpp = arg1
        arg2 = tmpp
        arg1 = tmp
        parent[1] = arg2
        parent[0] = arg1

    if (arg1.tag == "arg2" and arg2.tag == "arg3" and arg3.tag == "arg1"):
        tmp = arg2
        tmp2 = arg1
        tmp3 = arg3

        arg3 = tmp
        arg1 = tmp3
        arg2 = tmp2

        parent[1] = arg2
        parent[2] = arg3
        parent[0] = arg1

    if (arg1.tag == "arg3" and arg2.tag == "arg2" and arg3.tag == "arg1"):
        tmp = arg1
        tmpp = arg3

        arg1 = tmpp
        arg3 = tmp
        parent[2] = arg3
        parent[0] = arg1

    if (arg1.tag == "arg3" and arg2.tag == "arg1" and arg3.tag == "arg2"):
        tmp = arg1
        tmp2 = arg2
        tmp3 = arg3

        arg3 = tmp
        arg1 = tmp2
        arg2 = tmp3

        parent[1] = arg2
        parent[2] = arg3
        parent[0] = arg1

    return parent, arg1, arg2, arg3

# Funkce na kontrolu spravnosti syntaxe jednotlivych typu argumentu promennych
def checkVar(parent):
    arg1 = parent[0]
    if (arg1.tag != "arg1"):
        exit(32)
    if (arg1.get('type') != "var"):
        exit(32)
    if (arg1.text == None):
        exit(32)
    if (not validVar(arg1.text)):
        exit(32)
    return parent

def checkVarSymb(parent):
    arg1 = parent[0]
    arg2 = parent[1]
    if (arg1.tag == "arg2" and arg2.tag == "arg1"):
        tmp = arg2
        arg2 = arg1
        parent[1] = arg1
        arg1 = tmp
        parent[0] = tmp

    if (arg1.text == None):
            exit(32)
    if (arg2.get('type') != "string"):
        if (arg2.text == None):
            exit(32)
    try:
        if (arg2.get('type') == 'string'):
            arg2.text = convertString(arg2.text)
    except:
        exit(32)

    if (arg1.tag != "arg1" or arg2.tag != "arg2"):
        exit(32)
    if (arg1.get('type') != "var"):
        exit(32)
    if (arg2.get('type') != "string" and arg2.get('type') != "bool" and arg2.get('type') != "var" and arg2.get('type') != "int" and arg2.get('type') != "nil"):
        exit(32)
    if (not validVar(arg1.text)):
        exit(32)
    if (not validSymb(arg2.get('type'), arg2.text)):
        exit(32)
    return parent

def checkVarSymbSymb(parent):
    arg1 = parent[0]
    arg2 = parent[1]
    arg3 = parent[2]

    if (arg2.get('type') != "string"):
        if (arg2.text == None):
            exit(32)
    if (arg3.get('type') != "string"):
        if (arg3.text == None):
            exit(32)
    if (arg1.text == None):
        exit(32)

    try:
        if (arg2.get('type') == 'string'):
            arg2.text = convertString(arg2.text)

        if (arg3.get('type') == 'string'):
            arg3.text = convertString(arg3.text)
    except:
        exit(32)

    parent, arg1, arg2, arg3 = sortinstrArgs(parent, arg1, arg2, arg3)

    if (arg1.tag != "arg1" or arg2.tag != "arg2" or arg3.tag != "arg3"):

        exit(32)
    if (arg1.get('type') != "var"):
        exit(32)
    if (arg2.get('type') != "string" and arg2.get('type') != "bool" and arg2.get('type') != "var" and arg2.get('type') != "int" and arg2.get('type') != "nil"):
        exit(32)
    if (arg3.get('type') != "string" and arg3.get('type') != "bool" and arg3.get('type') != "var" and arg3.get('type') != "int" and arg3.get('type') != "nil"):
        exit(32)
    if (not validVar(arg1.text)):
        exit(32)
    if (not validSymb(arg2.get('type'), arg2.text)):
        exit(32)
    if (not validSymb(arg3.get('type'), arg3.text)):
        exit(32)
    return parent

def checkLabelSymbSymb(parent):
    arg1 = parent[0]
    arg2 = parent[1]
    arg3 = parent[2]

    if (arg1.text == None):
            exit(32)
    if (arg2.get('type') != "string"):
        if (arg2.text == None):
            exit(32)
    if (arg3.get('type') != "string"):
        if (arg3.text == None):
            exit(32)

    try:
        if (arg2.get('type') == 'string'):
            arg2.text = convertString(arg2.text)

        if (arg3.get('type') == 'string'):
            arg3.text = convertString(arg3.text)
    except:
        exit(32)

    parent, arg1, arg2, arg3 = sortinstrArgs(parent, arg1, arg2, arg3)

    if (arg1.tag != "arg1" or arg2.tag != "arg2" or arg3.tag != "arg3"):
        exit(32)
    if (arg1.get('type') != "label"):
        exit(32)
    if (arg2.get('type') != "string" and arg2.get('type') != "bool" and arg2.get('type') != "var" and arg2.get('type') != "int" and arg2.get('type') != "nil"):
        exit(32)
    if (arg3.get('type') != "string" and arg3.get('type') != "bool" and arg3.get('type') != "var" and arg3.get('type') != "int" and arg3.get('type') != "nil"):
        exit(32)
    if (not validLabel(arg1.text)):
        exit(32)
    if (not validSymb(arg2.get('type'), arg2.text)):
        exit(32)
    if (not validSymb(arg3.get('type'), arg3.text)):
        exit(32)
    return parent

def checkLabel(parent):
    arg1 = parent[0]
    if (arg1.text == None):
        exit(32)
    if (arg1.tag != "arg1"):
        exit(32)
    if (arg1.get('type') != "label"):
        exit(32)
    if (not validLabel(arg1.text)):
        exit(32)
    return parent

def checkSymb(parent):
    arg1 = parent[0]

    if (arg1.get('type') != "string"):
        if (arg1.text == None):
            exit(32)

    try:
        if (arg1.get('type') == 'string'):
            arg1.text = convertString(arg1.text)
    except:
        exit(32)

    if (arg1.tag != "arg1"):
        exit(32)
    if (arg1.get('type') != "string" and arg1.get('type') != "bool" and arg1.get('type') != "var" and arg1.get('type') != "int" and arg1.get('type') != "nil"):
        exit(32)
    if (not validSymb(arg1.get('type'), arg1.text)):
        exit(32)
    return parent

def checkVarType(parent):

    arg1 = parent[0]
    arg2 = parent[1]

    if (arg1.text == None or arg2.text == None):
        exit(32)
    if (arg1.tag == "arg2" and arg2.tag == "arg1"):
        tmp = arg2
        arg2 = arg1
        parent[1] = arg1
        arg1 = tmp
        parent[0] = tmp

    if (arg1.tag != "arg1" or arg2.tag != "arg2"):
        exit(32)
    if (arg1.get('type') != "var" or arg2.get('type') != "type"):
        exit(32)
    if (not validVar(arg1.text)):
        exit(32)
    if (not validType(arg2.text)):
        exit(32)
    return parent

# Funkce pro zkontrolovani spravneho poctu a typu argumentu instrukci
def checkArgs(parent, key):
    # Jestli pocet argumentu v instrukci neodpovida ocekavanym, syntax error
    if (key == 0):
        checkLengths(parent, 0)
    elif (key == 1):
        checkLengths(parent, 1)
        parent = checkVar(parent)
    elif (key == 2):
        checkLengths(parent, 2)
        parent = checkVarSymb(parent)
    elif (key == 3):
        checkLengths(parent, 1)
        parent = checkLabel(parent)
    elif (key == 4):
        checkLengths(parent, 1)
        parent = checkSymb(parent)
    elif (key == 5):
        checkLengths(parent, 3)
        parent = checkVarSymbSymb(parent)
    elif (key == 6):
        checkLengths(parent, 2)
        parent = checkVarType(parent)
    elif (key == 7):
        checkLengths(parent, 3)
        parent = checkLabelSymbSymb(parent)
    else:
        exit(32)
    return parent

# Funkce pro zkontrolovani validity instrukci
def checkInstr(root):

    if (root.get('language') != "IPPcode21"):
        exit(32)

    # Povolene instrukce
    # var symb = 2
    # none = 0
    # var = 1
    # label = 3
    # symb = 4
    # var symb symb 5
    # var type 6
    # label symb symb 7

    allowed_inst = {"MOVE":2, "CREATEFRAME":0, "PUSHFRAME":0, "POPFRAME":0, "DEFVAR":1, "CALL":3, "RETURN":0, "PUSHS":4, "POPS":1,
                    "ADD":5, "SUB":5, "MUL":5, "IDIV":5, "LT":5, "GT":5, "EQ":5, "AND":5, "OR":5, "NOT":2, "INT2CHAR":2, "STRI2INT":5, "READ":6,
                    "WRITE":4, "CONCAT":5, "STRLEN":2, "GETCHAR":5, "SETCHAR":5, "TYPE":2, "LABEL":3, "JUMP":3, "JUMPIFEQ":7, "JUMPIFNEQ":7,
                    "EXIT":4, "DPRINT":4, "BREAK":0}
    order = []

    # Projdi vsechny instrukce
    for child in root:
        # Zkontroluj, jestli vubec element je typu instrukce
        if (child.tag != "instruction"):
            exit(32)
        check = child.get('order')
        code = child.get('opcode')
        # Zkontroluj, ze byla instrukce opcode zadana a neni prazdna
        if (code):
            code = code.upper()
        else:
            exit(32)
        # Zkus, jestli lze poradi prekonvertovat na cislo
        try:
            if (re.search("\.", check)):
                exit(32)
            check = int(check)
        except:
            exit(32)
        # Poradi nesmi byt zaporne a 0
        if (check < 1):
            exit(32)
        # Poradi instrukce se nemsi vyskytnout 2x
        if (check in order):
            exit(32)

        # Pridej poradi zpracovane instrukce mezi jiz existujici
        order.append(check)
        # Zkontroluj validitu instrukce
        if (not code in allowed_inst):
            exit(32)
        child = checkArgs(child, allowed_inst.get(code))
    return root

# Funkce pro zkontrolovani, jestli ma instrukce validni poradi a jejich serazeni
def sortInstr(root):

    root = checkInstr(root)
    z = 0
    length = len(root)

    # Projdi array, o kterem uz vis, ze je validni, a serad jej podle poradi
    while (z < length):
        if (z+1 < length):
            check = int(root[z].get('order'))
            peek = int(root[z+1].get('order'))
            if (check > peek):
                tmp = root[z]
                root[z] = root[z+1]
                root[z+1] = tmp
                z = 0
            else:
                z += 1
        else:
            z += 1

    return root

# Funkce pro zjisteni, jestli je ramec inicializovany
def frame_initialized(frame):
    global local_frame
    global local_frame_init
    global temp_frame_init
    global temp_frame
    global global_frame

    if (frame is local_frame):
        if (local_frame_init):
            return True
        else:
            return False
    if (frame is temp_frame):
        if (temp_frame_init):
            return True
        else:
            return False
    elif (frame is global_frame):
        return True

# Funkce pro kontrolu, jestli promenna existuje
def varExists(var, frame):
    if not (frame_initialized(frame)):
        exit(55)
    keys = list(frame.keys())
    if (var in keys):
        return True
    else:
        return False

# Funkce pro kontrolu pri definici, jestli uz se promenna v seznamu nenachazi
# Jeslti ne, prida ji
def checkFrameAdd(instr, frame, value=None):
    keys = list(frame.keys())
    if (instr in keys):
        exit(52)
    # Inicializuj hodnotu None
    frame.update({instr:value})

# Funkce pro ziskani framu ze jmena promenne
def getFrame(var):
    return var[:3], var[3:]

# Funkce na pridani promenne do ramce
def addToFrame(instr):
    global global_frame
    global local_frame
    global temp_frame
    global temp_frame_init
    global local_frame_init
    global global_frame_types
    global local_frame_types
    global temp_frame_types

    frame = instr[:3]
    name = instr[3:]
    # Zjisti ramec, podle ktereho spravne prirad promennou
    if (frame == "GF@"):
        checkFrameAdd(name, global_frame)
        checkFrameAdd(name, global_frame_types)
    elif (frame == "LF@"):
        if (local_frame_init):
            checkFrameAdd(name, local_frame)
            checkFrameAdd(name, local_frame_types)
        else:
            exit(55)
    else:
        if (temp_frame_init):
            checkFrameAdd(name, temp_frame)
            checkFrameAdd(name, temp_frame_types)
        # Jestli TF neexistuje, error
        else:
            exit(55)

# Funkce pro zkontrolovani existence promenne v ramci
def varPresent(new_type, instr):
    global global_frame
    global local_frame
    global temp_frames

    # Kontroluj jenom jestli je typ promenne var
    if (new_type == 'var'):
        # Ziskej jeji frame a nazev
        frame, name = getFrame(instr)
        # Zkontroluj na zaklade ziskaneho framu pritomnost v nem
        if (frame == "GF@"):
            if not (varExists(name, global_frame)):
                exit(54)

        elif (frame == "LF@"):
            if not (varExists(name, local_frame)):
                exit(54)

        elif (frame == "TF@"):
            if not (varExists(name, temp_frame)):
                exit(54)

# Funkcce pro aktualizaci hodnoty promenne
def updateVar(var, value, typee):
    global global_frame
    global local_frame
    global temp_frame
    global global_frame_types
    global local_frame_types
    global temp_frame_types

    # Ziskej frame na kontrolu existence a prirazeni
    frame, name = getFrame(var)
    if (frame == "GF@"):
        if not (varExists(name, global_frame)):
            exit(54)
        else:
            # Prirad jak hodnotu, tak typ
            global_frame.update({name:value})
            global_frame_types.update({name:typee})

    elif (frame == "LF@"):
        if not (varExists(name, local_frame)):
            exit(54)
        else:
            local_frame.update({name:value})
            local_frame_types.update({name:typee})

    elif (frame == "TF@"):
        if not (varExists(name, temp_frame)):
            exit(54)
        else:
            temp_frame.update({name:value})
            temp_frame_types.update({name:typee})

# Podpurna funkce pro aritmeticke instrukce slouzici na dalsi kontroly typu
def arithmeticTypes(new_type, symb, new_type_2, symb2):
    varPresent(new_type, symb)
    new_type = getVarType(symb, new_type)
    typeCheck(new_type, "int")

    varPresent(new_type_2, symb2)
    new_type_2 = getVarType(symb2, new_type_2)
    typeCheck(new_type_2, "int")

# Konvertovani hodnot typu bool
def convertBool(val1, val2):
    if (val1 == "false"):
        val1 = False
    else:
        val1 = True
    if (val2 == "false"):
        val2 = False
    else:
        val2 = True

    return val1, val2

# Funkce na pomoc s Eq instrukcema
def wrapEq(new_type, new_type_2, symb, symb2):
    result = None
    flag = True
    if (new_type == "nil"):
        flag = False
        if (new_type_2 == "nil"):
            result = True
        else:
            result = False

    if (new_type_2 == 'nil'):
        flag = False
        if (new_type == 'nil'):
            result = True
        else:
            result = False

    if (flag):
        if (new_type != new_type_2):
            exit(53)

    val1 = getVarValue(symb)
    val2 = getVarValue(symb2)
    if (new_type != "nil" and new_type_2 != "nil"):
        if (new_type == "int"):
            result = (int(getVarValue(symb)) == int(getVarValue(symb2)))
        elif (new_type == "bool"):
            val1, val2 = convertBool(val1, val2)

            result = val1 == val2
        elif (new_type == "string"):
            result = val1 == val2
        else:
            exit(53)
    return result

# Funkce na overeni danych typu
def typeCheck(new_type, type2):
    if (new_type == None):
        exit(56)
    if (new_type != type2):
        exit(53)

# Zpracovani instrukci
def parseExit(instr):
    new_type = instr.get('type')
    instr = instr.text
    # Zkontroluj, jeslti odpovida typ (a jestlize je to var, jestli promenna existuje)
    varPresent(new_type, instr)
    new_type = getVarType(instr, new_type)

    # Exit musi byt typu int
    typeCheck(new_type, "int")

    instr = getVarValue(instr)
    # Zkontroluj, jeslti to neni float
    if (re.search("\.", instr)):
        exit(57)
    else:
        try:
            ret = int(instr)
        except:
            exit(57)

        # Zkontroluj, zda je navratova hodnota validni
        if (ret >= 0 and ret <= 49):
            exit(ret)
        exit(57)

def parseLabel(position, instr):
    global labels

    checkFrameAdd(instr.text, labels, position)

def parseJump(instr):
    global labels

    keys = list(labels.keys())
    label_name = instr.text
    if not (label_name in keys):
        exit(52)

    # Vrat hodnotu, na kterou se ma skocit
    value = labels.get(label_name)
    return value

def parseDefvar(instr):

    addToFrame(instr.text)

def parseCreateframe():
    global temp_frame
    global temp_frame_init

    temp_frame = {}
    temp_frame_init = True

def parsePushframe():
    global temp_frame
    global temp_frame_init
    global local_frame_stack
    global local_frame
    global local_frame_init
    global local_frame_types
    global temp_frame_types

    if not (temp_frame_init):
        exit(55)

    local_frame_stack.append(temp_frame)
    local_frame_types_stack.append(temp_frame_types)
    local_frame = temp_frame
    local_frame_types = temp_frame_types
    local_frame_init = True
    temp_frame_init = False
    temp_frame = {}
    temp_frame_types = {}

def parsePopframe():
    global temp_frame
    global temp_frame_init
    global local_frame_stack
    global local_frame
    global local_frame_init
    global local_frame_types_stack
    global local_frame_types
    global temp_frame_types

    if (len(local_frame_stack) == 0):
        exit(55)

    # Nahrej do TF posledni ramec ze stacku LF
    temp_frame = local_frame_stack.pop()
    temp_frame_types = local_frame_types_stack.pop()
    temp_frame_init = True
    # Jestlize jich na stacku bylo vic, tak novy LF je posledni ze stacku (nemaz ho!)
    if (len(local_frame_stack) > 0):
        local_frame = local_frame_stack[-1]
        local_frame_types = local_frame_types_stack[-1]
    else:
        local_frame_init = False
        local_frame = {}
        local_frame_types = {}

def parseCall(instr, i):
    global labels
    global call_stack

    keys = list(labels.keys())
    label_name = instr.text
    if not (label_name in keys):
        exit(52)

    value = labels.get(label_name)
    call_stack.append(i)
    return value-1

def parseReturn():
    global call_stack
    if (len(call_stack) == 0):
        exit(56)
    value = call_stack.pop()
    return value

def parseType(var, symb):
    typee = symb.get('type')
    var = var.text
    symb = symb.text

    varPresent(typee, symb)

    value = getVarType(symb, typee)
    if (value == None):
        value = ""

    updateVar(var, value, "string")

def parseWrite(symb):
    typee = symb.get('type')
    symb = symb.text
    if (typee == "var"):
        typee = getVarType(symb, typee)
    value = getVarValue(symb)
    if (typee == None):
        exit(56)
    elif (typee == "int"):
        try:
            value = int(value)
        except:
            exit(53)
    elif (typee == "nil"):
        value = ""

    print(value, end='')

def parseMove(var, symb):
    new_type = symb.get('type')
    var = var.text
    symb = symb.text

    varPresent(new_type, symb)

    new_type = getVarType(symb, new_type)
    if (new_type == None):
        exit(56)
    symb = getVarValue(symb)

    updateVar(var, symb, new_type)

def parseAdd(var, symb, symb2):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    var = var.text
    symb = symb.text
    symb2 = symb2.text

    arithmeticTypes(new_type, symb, new_type_2, symb2)

    result = (int(getVarValue(symb)) + int(getVarValue(symb2)))

    updateVar(var, result, "int")

def parseSub(var, symb, symb2):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    var = var.text
    symb = symb.text
    symb2 = symb2.text

    arithmeticTypes(new_type, symb, new_type_2, symb2)

    result = (int(getVarValue(symb)) - int(getVarValue(symb2)))

    updateVar(var, result, "int")

def parseMul(var, symb, symb2):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    var = var.text
    symb = symb.text
    symb2 = symb2.text

    arithmeticTypes(new_type, symb, new_type_2, symb2)

    result = (int(getVarValue(symb)) * int(getVarValue(symb2)))

    updateVar(var, result, "int")

def parseIdiv(var, symb, symb2):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    var = var.text
    symb = symb.text
    symb2 = symb2.text

    arithmeticTypes(new_type, symb, new_type_2, symb2)

    val1 = int(getVarValue(symb))
    val2 = int(getVarValue(symb2))
    if (val2 == 0):
        exit(57)
    result = (val1 // val2)

    updateVar(var, result, "int")

def parseLt(var, symb, symb2):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    var = var.text
    symb = symb.text
    symb2 = symb2.text

    varPresent(new_type, symb)

    new_type = getVarType(symb, new_type)
    if (new_type == None):
        exit(56)

    varPresent(new_type_2, symb2)

    new_type_2 = getVarType(symb2, new_type_2)
    if (new_type_2 == None):
        exit(56)

    result = None
    if (new_type != new_type_2):
        exit(53)

    val1 = getVarValue(symb)
    val2 = getVarValue(symb2)
    if (new_type == "int"):
        result = (int(getVarValue(symb)) < int(getVarValue(symb2)))
    elif (new_type == "bool"):
        val1, val2 = convertBool(val1, val2)
        result = val1 < val2
    elif (new_type != "nil"):
        result = val1 < val2
    else:
        exit(53)

    result = str(result).lower()
    updateVar(var, result, "bool")

def parseGt(var, symb, symb2):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    var = var.text
    symb = symb.text
    symb2 = symb2.text

    varPresent(new_type, symb)

    new_type = getVarType(symb, new_type)
    if (new_type == None):
        exit(56)

    varPresent(new_type_2, symb2)

    new_type_2 = getVarType(symb2, new_type_2)
    if (new_type_2 == None):
        exit(56)

    result = None
    if (new_type != new_type_2):
        exit(53)
    val1 = getVarValue(symb)
    val2 = getVarValue(symb2)
    if (new_type == "int"):
        result = (int(getVarValue(symb)) > int(getVarValue(symb2)))
    elif (new_type == "bool"):
        val1, val2 = convertBool(val1, val2)
        result = val1 > val2
    elif (new_type == "string"):
        result = val1 > val2
    else:
        exit(53)

    result = str(result).lower()
    updateVar(var, result, "bool")

def parseEq(var, symb, symb2):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    var = var.text
    symb = symb.text
    symb2 = symb2.text

    varPresent(new_type, symb)

    new_type = getVarType(symb, new_type)
    if (new_type == None):
        exit(56)

    varPresent(new_type_2, symb2)

    new_type_2 = getVarType(symb2, new_type_2)
    if (new_type_2 == None):
        exit(56)

    result = wrapEq(new_type, new_type_2, symb, symb2)

    result = str(result).lower()
    updateVar(var, result, "bool")

def parseAnd(var, symb, symb2):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    var = var.text
    symb = symb.text
    symb2 = symb2.text

    varPresent(new_type, symb)

    new_type = getVarType(symb, new_type)
    typeCheck(new_type, "bool")

    varPresent(new_type_2, symb2)

    new_type_2 = getVarType(symb2, new_type_2)
    typeCheck(new_type_2, "bool")

    val1 = getVarValue(symb)
    val2 = getVarValue(symb2)
    val1, val2 = convertBool(val1, val2)

    result = val1 and val2
    result = str(result).lower()

    updateVar(var, result, "bool")

def parseOr(var, symb, symb2):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    var = var.text
    symb = symb.text
    symb2 = symb2.text

    varPresent(new_type, symb)

    new_type = getVarType(symb, new_type)
    typeCheck(new_type, "bool")

    varPresent(new_type_2, symb2)

    new_type_2 = getVarType(symb2, new_type_2)
    typeCheck(new_type_2, "bool")

    val1 = getVarValue(symb)
    val2 = getVarValue(symb2)
    val1, val2 = convertBool(val1, val2)

    result = val1 or val2
    result = str(result).lower()

    updateVar(var, result, "bool")

def parseNot(var, symb):
    new_type = symb.get('type')
    typee = var.get('type')
    var = var.text
    symb = symb.text
    global global_frame
    global local_frame
    global temp_frame
    global global_frame_types
    global local_frame_types
    global temp_frame_types

    varPresent(new_type, symb)
    new_type = getVarType(symb, new_type)
    typeCheck(new_type, "bool")

    val1 = getVarValue(symb)
    if (val1 == "false"):
        val1 = False
    else:
        val1 = True

    result = not val1
    result = str(result).lower()

    updateVar(var, result, "bool")

def parseJumpifeq(label, symb, symb2, i):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    label = label.text
    symb = symb.text
    symb2 = symb2.text
    global labels

    keys = list(labels.keys())
    if not (label in keys):
        exit(52)

    varPresent(new_type, symb)

    new_type = getVarType(symb, new_type)
    if (new_type == None):
        exit(56)

    varPresent(new_type_2, symb2)

    new_type_2 = getVarType(symb2, new_type_2)
    if (new_type_2 == None):
        exit(56)

    result = wrapEq(new_type, new_type_2, symb, symb2)

    if (result):
        # Vrat hodnotu, na kterou se ma skocit
        value = labels.get(label)
        return value-1
    else:
        return i

def parseJumpifneq(label, symb, symb2, i):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    label = label.text
    symb = symb.text
    symb2 = symb2.text
    global labels

    keys = list(labels.keys())
    if not (label in keys):
        exit(52)

    varPresent(new_type, symb)

    new_type = getVarType(symb, new_type)
    if (new_type == None):
        exit(56)

    varPresent(new_type_2, symb2)

    new_type_2 = getVarType(symb2, new_type_2)
    if (new_type_2 == None):
        exit(56)

    result = wrapEq(new_type, new_type_2, symb, symb2)

    if not (result):
        # Vrat hodnotu, na kterou se ma skocit
        value = labels.get(label)
        return value-1
    else:
        return i

def parseInt2char(var, symb):
    new_type = symb.get('type')
    var = var.text
    symb = symb.text

    varPresent(new_type, symb)

    new_type = getVarType(symb, new_type)
    typeCheck(new_type, "int")

    try:
        val1 = getVarValue(symb)
        if (int(val1) < 0):
            exit(58)
        result = chr(int(val1))
    except:
        exit(58)

    updateVar(var, result, "string")

def parseStri2int(var, symb, symb2):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    var = var.text
    symb = symb.text
    symb2 = symb2.text

    varPresent(new_type, symb)

    new_type = getVarType(symb, new_type)
    typeCheck(new_type, "string")

    varPresent(new_type_2, symb2)

    new_type_2 = getVarType(symb2, new_type_2)
    typeCheck(new_type_2, "int")

    val1 = getVarValue(symb)
    val2 = getVarValue(symb2)

    try:
        if (int(val2) < 0):
            exit(58)
    except:
        exit(58)

    try:
        result = ord(val1[int(val2)])
    except:
        exit(58)

    updateVar(var, result, "int")

def parseRead(var, typee):
    new_type = typee.get('type')
    var = var.text
    typee = typee.text

    if (new_type != "type"):
        exit(53)

    x = None
    insert_type = None
    if (typee == 'int'):
        try:
            x = int(input())
            insert_type = "int"
        except:
            x = "nil"
            insert_type = "nil"
    elif (typee == 'bool'):
        try:
            x = input()
            insert_type = "bool"
            if (x.lower() != "true"):
                x = "false"
            else:
                x = "true"
        except EOFError:
            x = "nil"
            insert_type = "nil"

    elif (typee == 'string'):
        insert_type = "string"
        try:
            x = input()
            insert_type = "string"
        except EOFError:
            x = "nil"
            insert_type = "nil"

    updateVar(var, x, insert_type)

def parseConcat(var, symb, symb2):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    var = var.text
    symb = symb.text
    symb2 = symb2.text

    varPresent(new_type, symb)

    new_type = getVarType(symb, new_type)
    typeCheck(new_type, "string")

    varPresent(new_type_2, symb2)

    new_type_2 = getVarType(symb2, new_type_2)
    typeCheck(new_type_2, "string")

    val1 = getVarValue(symb)
    val2 = getVarValue(symb2)

    result = val1 + val2

    updateVar(var, result, "string")

def parseStrlen(var, symb):
    new_type = symb.get('type')
    var = var.text
    symb = symb.text

    varPresent(new_type, symb)
    new_type = getVarType(symb, new_type)
    typeCheck(new_type, "string")

    result = len(getVarValue(symb))

    updateVar(var, result, "int")

def parseGetchar(var, symb, symb2):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    var = var.text
    symb = symb.text
    symb2 = symb2.text

    varPresent(new_type, symb)

    new_type = getVarType(symb, new_type)
    typeCheck(new_type, "string")

    varPresent(new_type_2, symb2)

    new_type_2 = getVarType(symb2, new_type_2)
    typeCheck(new_type_2, "int")

    val1 = getVarValue(symb)
    val2 = getVarValue(symb2)

    try:
        if (int(val2) < 0):
            exit(58)
        result = val1[int(val2)]
    except:
        exit(58)

    updateVar(var, result, "string")

def parseSetchar(var, symb, symb2):
    new_type = symb.get('type')
    new_type_2 = symb2.get('type')
    var = var.text
    symb = symb.text
    symb2 = symb2.text

    varPresent('var', var)
    typee = getVarType(var, 'var')

    typeCheck(typee, "string")

    varPresent(new_type, symb)

    new_type = getVarType(symb, new_type)
    typeCheck(new_type, "int")

    varPresent(new_type_2, symb2)

    new_type_2 = getVarType(symb2, new_type_2)
    typeCheck(new_type_2, "string")

    val3 = getVarValue(var) # String kde menim
    val1 = getVarValue(symb) # Pozice jakou menim
    val2 = getVarValue(symb2) # Novy char

    try:
        if (int(val1) < 0 or int(val1) >= len(val3)):
            exit(58)
        if (val3 == ""):
            exit(58)
        if (val2 == ""):
            exit(58)
    except:
        exit(58)

    try:
        val2 = val2[0]  # Pokud je tohle delsi > 1, beru prvni
        result = val3[:int(val1)] + val2 + val3[int(val1)+1:]
    except:
        exit(58)

    updateVar(var, result, "string")

def parsePushs(symb):
    new_type = symb.get('type')
    symb = symb.text

    global var_stack

    varPresent(new_type, symb)
    new_type = getVarType(symb, new_type)
    if (new_type == None):
        exit(56)

    var_stack.append(getVarValue(symb))
    var_stack_type.append(new_type)

def parsePops(var):
    var = var.text
    global var_stack

    try:
        result = var_stack.pop()
        typee = var_stack_type.pop()
    except:
        exit(56)

    updateVar(var, result, typee)

# Ridici funkce zpracovavajici jednotlive instrukce
def parseInstructions(root):
    # Nejprve je potreba zjistit pozice vsech labelu
    i = 0
    length = len(root)
    while (i < length):
        if (root[i].get('opcode').upper() == 'LABEL'):
            parseLabel(i, root[i][0])
            # Jakmile ho zpracuju, smazu ho, neni ho dal potreba resit
            root.remove(root[i])
            length = len(root)
            i -= 1
        i+=1
    length = len(root)
    i = 0

    while (i < length):
        instr = root[i].get('opcode').upper()
        if (instr == 'EXIT'):
            parseExit(root[i][0])
        if (instr == 'JUMP'):
            i = parseJump(root[i][0])
            i -= 1
        if (instr == 'DEFVAR'):
            parseDefvar(root[i][0])
        if (instr == 'CREATEFRAME'):
            parseCreateframe()
        if (instr == 'PUSHFRAME'):
            parsePushframe()
        if (instr == 'POPFRAME'):
            parsePopframe()
        if (instr == 'CALL'):
            i = parseCall(root[i][0], i)
        if (instr == 'RETURN'):
            i = parseReturn()
        if (instr == 'TYPE'):
            parseType(root[i][0], root[i][1])
        if (instr == 'WRITE'):
            parseWrite(root[i][0])
        if (instr == 'MOVE'):
            parseMove(root[i][0], root[i][1])
        if (instr == 'ADD'):
            parseAdd(root[i][0], root[i][1], root[i][2])
        if (instr == 'SUB'):
            parseSub(root[i][0], root[i][1], root[i][2])
        if (instr == 'MUL'):
            parseMul(root[i][0], root[i][1], root[i][2])
        if (instr == 'IDIV'):
            parseIdiv(root[i][0], root[i][1], root[i][2])
        if (instr == 'LT'):
            parseLt(root[i][0], root[i][1], root[i][2])
        if (instr == 'GT'):
            parseGt(root[i][0], root[i][1], root[i][2])
        if (instr == 'EQ'):
            parseEq(root[i][0], root[i][1], root[i][2])
        if (instr == 'AND'):
            parseAnd(root[i][0], root[i][1], root[i][2])
        if (instr == 'OR'):
            parseOr(root[i][0], root[i][1], root[i][2])
        if (instr == 'NOT'):
            parseNot(root[i][0], root[i][1])
        if (instr == 'JUMPIFEQ'):
            i = parseJumpifeq(root[i][0], root[i][1], root[i][2], i)
        if (instr == 'JUMPIFNEQ'):
            i = parseJumpifneq(root[i][0], root[i][1], root[i][2], i)
        if (instr == 'INT2CHAR'):
            parseInt2char(root[i][0], root[i][1])
        if (instr == 'STRI2INT'):
            parseStri2int(root[i][0], root[i][1], root[i][2])
        if (instr == 'READ'):
            parseRead(root[i][0], root[i][1])
        if (instr == 'CONCAT'):
            parseConcat(root[i][0], root[i][1], root[i][2])
        if (instr == 'STRLEN'):
            parseStrlen(root[i][0], root[i][1])
        if (instr == 'GETCHAR'):
            parseGetchar(root[i][0], root[i][1], root[i][2])
        if (instr == 'SETCHAR'):
            parseSetchar(root[i][0], root[i][1], root[i][2])
        if (instr == 'PUSHS'):
            parsePushs(root[i][0])
        if (instr == 'POPS'):
            parsePops(root[i][0])
        i += 1

def main():
    source_path, input_path = parse_args()
    source = loadContent(source_path, input_path)
    root = source.getroot()
    root = sortInstr(root)
    parseInstructions(root)

if __name__ == "__main__":
    try:
        main()
    except (MemoryError, BufferError):
        exit(99)


import sqlite3

def to_transaction_dict(transaction_tuple):
    ''' transaction is a transaction tuple (item_id, amount, category, date, description) '''
    transaction = {'rowid':transaction_tuple[0], 'amount':transaction_tuple[1], 'category':transaction_tuple[2], 'date':transaction_tuple[3], 'desc': transaction_tuple[4]}
    return transaction

def to_transaction_dict_list(transaction_tuples):
    ''' convert a list of transaction tuples into a list of dictionaries'''
    return [to_transaction_dict(transaction) for transaction in transaction_tuples]

class Transaction:

    def __init__(self, dbfile):
        con= sqlite3.connect(dbfile)
        cur = con.cursor()
        cur.execute('''CREATE TABLE IF NOT EXISTS transactions
                    (amount text, category text, date text, desc text)''')
        con.commit()
        con.close()
        self.dbfile = dbfile

    def select_all(self):
        ''' return all of the transactions as a list of dicts.'''
        con= sqlite3.connect(self.dbfile)
        cur = con.cursor()
        cur.execute("SELECT rowid,* from transactions")
        tuples = cur.fetchall()
        con.commit()
        con.close()
        return to_transaction_dict_list(tuples)

    def delete(self,rowid):
        con= sqlite3.connect(self.dbfile)
        cur = con.cursor()
        cur.execute('''DELETE FROM transactions
                       WHERE rowid=(?);
        ''',(rowid,))
        con.commit()
        con.close()

    def add(self,item):
        ''' add a transaction to the transactions table.
            this returns the rowid of the inserted element
        '''
        con= sqlite3.connect(self.dbfile)
        cur = con.cursor()
        cur.execute("INSERT INTO transactions VALUES(?,?,?,?)",(item['amount'], item['category'], item['date'], item['desc']))
        con.commit()
        cur.execute("SELECT last_insert_rowid()")
        last_rowid = cur.fetchone()
        con.commit()
        con.close()
        return last_rowid[0]

    def summarize_by_date(self, date):
        ''' summarizes transactions by date '''
        con= sqlite3.connect(self.dbfile)
        cur = con.cursor()
        cur.execute("SELECT DISTINCT rowid,* FROM transactions WHERE date=(?)",(date,))
        tuples = cur.fetchall()
        con.commit()
        con.close()
        return tuples

    def summarize_by_month(self, month):
        ''' summarize transactions by month'''
        con= sqlite3.connect(self.dbfile)
        cur = con.cursor()
        cur.execute("SELECT rowid,* FROM transactions WHERE SUBSTRING(date, 5,2)=(?)",(month,))
        tuples = cur.fetchall()
        con.commit()
        con.close()
        return tuples

    def summarize_by_year(self, year):
        '''summarizes transactions by year'''
        con= sqlite3.connect(self.dbfile)
        cur = con.cursor()
        cur.execute("SELECT rowid,* FROM transactions WHERE SUBSTRING(date, 1,4)=(?)",(year,))
        tuples = cur.fetchall()
        con.commit()
        con.close()
        return tuples

    def summarize_by_cat(self, cat):
        '''summarizes by category'''
        con= sqlite3.connect(self.dbfile)
        cur = con.cursor()
        cur.execute("SELECT rowid,* FROM transactions WHERE category=(?)", (cat,))
        tuples = cur.fetchall()
        con.commit()
        con.close()
        return tuples


import torch
import torch.nn as nn
import torch.nn.functional as F

class SoftDotAttention(nn.Module):
    """Soft Dot Attention.

    Ref: http://www.aclweb.org/anthology/D15-1166
    Adapted from PyTorch OPEN NMT.
    """
    def __init__(self, dim, ctx_dim):
        """Initialize layer."""
        super(SoftDotAttention, self).__init__()
        self.linear_in = nn.Linear(dim, ctx_dim, bias=False)
        self.sm = nn.Softmax(dim=-1)
        self.linear_out = nn.Linear(ctx_dim*2, dim, bias=False)
        self.tanh = nn.Tanh()

    def forward(self, input, context, ctx_mask):
        """Propogate input through the network.

        input: batch x dim
        context: batch x sourceL x dim
        """
        # Get attention
        input = self.linear_in(input)
        attn = torch.einsum('bsd,bd->bs', (context, input))
        attn -= (1-ctx_mask) * 100000
        attn = self.sm(attn).clone()#[batch, sourceL]

        weighted_context = torch.einsum('bs,bsd->bd',(attn, context))#[batch, dim]

        h_tilde = torch.cat((weighted_context, input), 1)#[batch, dim*2]
        h_tilde = self.tanh(self.linear_out(h_tilde))#[batch, dim]

        return h_tilde, attn

class LSTMAttentionDot(nn.Module):
    r"""A long short-term memory (LSTM) cell with attention."""

    def __init__(self, input_size, hidden_size, batch_first=True):
        """Initialize params."""
        super(LSTMAttentionDot, self).__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.num_layers = 1
        self.batch_first = batch_first

        self.input_weights = nn.Linear(input_size, 4 * hidden_size)
        self.hidden_weights = nn.Linear(hidden_size, 4 * hidden_size)

        self.attention_layer = SoftDotAttention(hidden_size, input_size)

    def forward(self, steps, hidden, ctx, ctx_mask):
        """Propogate input through the network."""
        def recurrence(hidden):
            """Recurrence helper."""
            hx, cx = hidden  # n_b x hidden_dim
            gates = self.hidden_weights(hx)
            ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1)

            ingate = F.sigmoid(ingate)
            forgetgate = F.sigmoid(forgetgate)
            cellgate = F.tanh(cellgate)
            outgate = F.sigmoid(outgate)

            cy = (forgetgate * cx) + (ingate * cellgate)
            hy = outgate * F.tanh(cy)  # n_b x hidden_dim
            h_tilde, _ = self.attention_layer(hy, ctx, ctx_mask)

            return h_tilde, cy

        output = []
        for _ in range(steps):
            hidden = recurrence(hidden)
            output.append(hidden[0] if isinstance(hidden, tuple) else hidden)

        output = torch.cat(output, 0).view(steps, *output[0].size())

        if self.batch_first:
            output = output.transpose(0, 1)

        return output, hidden

class Ctx2SeqAttention(nn.Module):
    """Container module with an encoder, deocder, embeddings."""
    def __init__(
        self,
        ctx_dim,
        num_steps,
        vocab_size,
        src_hidden_dim,
        trg_hidden_dim,
        attention_mode,
        batch_size,
        pad_token_src,
        pad_token_trg,
        bidirectional=True,
        nlayers=2,
        nlayers_trg=2,
        dropout=0.,
    ):
        """Initialize model."""
        super(Ctx2SeqAttention, self).__init__()
        self.num_steps = num_steps
        self.vocab_size = vocab_size
        self.src_hidden_dim = src_hidden_dim
        self.trg_hidden_dim = trg_hidden_dim
        self.attention_mode = attention_mode
        self.batch_size = batch_size
        self.bidirectional = bidirectional
        self.nlayers = nlayers
        self.dropout = dropout
        self.num_directions = 2 if bidirectional else 1
        self.pad_token_src = pad_token_src
        self.pad_token_trg = pad_token_trg

        self.src_hidden_dim = src_hidden_dim//2 if self.bidirectional else src_hidden_dim
        self.decoder = LSTMAttentionDot(ctx_dim, trg_hidden_dim, batch_first=True)

        self.encoder2decoder = nn.Linear(self.src_hidden_dim * self.num_directions, trg_hidden_dim)
        self.decoder2vocab = nn.Linear(trg_hidden_dim, vocab_size)
        self.init_weights()

    def init_weights(self):
        self.encoder2decoder.bias.data.fill_(0)
        self.decoder2vocab.bias.data.fill_(0)

    def forward(self, ctx, state, ctx_mask):
        h_t, c_t = state.chunk(2, -1)
        decoder_init_state = nn.Tanh()(self.encoder2decoder(h_t))

        trg_h, (_, _) = self.decoder(
            self.num_steps,
            (decoder_init_state, c_t),
            ctx,
            ctx_mask
        )

        trg_h_reshape = trg_h.contiguous().view(
            trg_h.size()[0] * trg_h.size()[1],
            trg_h.size()[2]
        )

        decoder_logit = self.decoder2vocab(trg_h_reshape)
        decoder_logit = decoder_logit.view(
            trg_h.size()[0],
            trg_h.size()[1],
            decoder_logit.size()[1]
        )
        return decoder_logit

    def decode(self, logits):
        """Return probability distribution over words."""
        logits_reshape = logits.view(-1, self.vocab_size)
        word_probs = F.softmax(logits_reshape)
        word_probs = word_probs.view(
            logits.size()[0], logits.size()[1], logits.size()[2]
        )
        return word_probs


import requests
import bs4
import re
import flask
from flask import request, jsonify

swRegex = re.compile(r'\d{4}-\d{4}-\d{4}')
priceRegex = re.compile(r'\d{3}')
userRegex = re.compile(r'ago by (.*?)')

#return bs4 object
def getPage(url,headers):
    res = requests.get(url, headers=headers)
    try:
        res.raise_for_status()
    except:
        pass

    pageHtml=bs4.BeautifulSoup(res.text,'html.parser')
    return pageHtml

#check if previous scrape already contained the given listing
def alreadyHas(tListings,link):
    for k in tListings:
        if k["url"]==link:
            return True
    return False

#check if a listing is still active, or if it is finished
def checkActivity(link,headers):
    curPost=requests.get(link,headers=headers)
    curPageHtml=bs4.BeautifulSoup(curPost.text,'html.parser')

    words=curPageHtml.find("div",class_="thing")
    cleanPost=words.text.strip('•comentsharvidport 1234567890')

    return cleanPost[:6]=='Active'

#add listing to array if the listing is still active
def addListing(link,listings,headers):
    curPost=requests.get(link,headers=headers)
    curPageHtml=bs4.BeautifulSoup(curPost.text,'html.parser')

    words=curPageHtml.find("div",class_="thing")
    cleanPost=words.text.strip('•comentsharvidport 1234567890')
    FC=swRegex.findall(cleanPost)

    if checkActivity(link,headers):
        if len(FC)>0:
            FC=FC[0]
            cleanPost=cleanPost.replace(FC,'')
            price=priceRegex.findall(cleanPost)
        else:
            FC=''
        if len(price)>0:
            price=price[0]
        else:
            price=''
        curListing = {
                        "price" : price,
                        "FC" : "SW-"+FC,
                        "url" : link
                    }
        listings.append(curListing)
    else:
        pass

# Returns an array of dcitionaries - turnip listings
def getListings(old=[]):
    url = "https://old.reddit.com/r/acturnips/new"
    headers = {'User-Agent': 'Mozilla/5.0'}
    tListings = []
    prev=[]
    for i in range(1):
        pageHtml=getPage(url,headers)
        elems = pageHtml.find_all("a", class_="title may-blank")
        url=pageHtml.find("span",class_="next-button").find("a" , recursive=False)['href']
        for j in range(len(elems)):
            link="https://old.reddit.com"+elems[j]['href']
            if alreadyHas(old,link):
                break
            try:
                addListing(link,tListings,headers)
            except:
                pass
    for i in range(len(old)):
        if checkActivity(old[i]['url'],headers):
            prev.append(old[i])

    tListings=tListings+prev
    print (tListings)
    return tListings

getListings()


# -*- coding:latin1 -*
"""
    Christmas tree
    NIVEAU 1
    Robin TURPIN & Tudi MOUGEOT
    17 et 18 décembre 2020
    python 3.7
"""
import sys
"""
     Initialisations des constantes :
"""
width=23

"""
    Cette procédure permet d'afficher un sapin à trois étages.
    On ne demande pas à l'utilisateur de rentrer le nombre d'étages qu'il veut.
"""
def triangles(t, m, b):
    for size in range(1, t + 1, 2):
        print((size * "*").center(width))
    for size in range(3, m + 1, 4):
        print((size * "*").center(width))
    for size in range(5, b + 1, 6):
        print((size * "*").center(width))

"""
    Programme principal
"""
def main():
    triangles(8, 16, 24)
main()


# app.py
from flask import Flask
from flask import render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///trails.sqlite3'
db = SQLAlchemy(app)

db.Model.metadata.reflect(db.engine)

class Trail(db.Model):
    __tablename__ = 'Trails'
    __table_args__ = { 'extend_existing': True }
    TRAIL_ID = db.Column(db.Text, primary_key=True)

@app.route('/')
def hello():
    trailCount = Trail.query.count()

    good_trails = Trail.query.filter_by(CONDITION='Good').all()

    return render_template("index.html", count=trailCount, trails=good_trails)

@app.route('/trails/<slug>')
def detail(slug):
    trail = Trail.query.filter_by(TRAIL_ID=slug).first()

    return render_template("detail.html", trail=trail)

if __name__=='__main__':
    app.run(debug=True)


# 1. Daily Temperatures
class Solution:
    '''
    1. create `ans` array prepopulated with 0
    2. traverse input array
    3. if len(stack) != 0 and current temp
        bigger that last on stack =>

    4. take difference in indicies and put it
        in place of idx from the stack (that
        we popped)

    5. at the bottom add curr idx
    '''
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        ans = [0 for _ in temperatures]
        stack = []

        for i in range(len(temperatures)):
            val = temperatures[i]

            while len(stack) != 0 and val > temperatures[stack[-1]]:
                nodeIdx = stack.pop()
                diff = i - nodeIdx
                ans[nodeIdx] = diff

            stack.append(i)

        return ans

# 2. Evaluate Reverse Polish Notation
# Time: O(n) Space: O(d)
class Solution:
    # mine
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        result = 0
        operators = ['+', '-', '*', '/']

        for t in tokens:
            if t in operators:
                self.make_computations(t, stack)
            else:
                stack.append(int(t))

        return stack[0]

    def make_computations(self, t, stack):
        num1 = stack.pop()
        num2 = stack.pop()

        if t == '+':
            result = num1 + num2
        elif t == '-':
            result = num2 - num1
        elif t == '*':
            result = num1 * num2
        elif t == '/':
            # int() + /
            result = int(num2 / num1)

        stack.append(result)

    # not mine
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        operators = {
            '+': lambda x,y: x + y,
            '-': lambda x,y: x - y,
            '*': lambda x,y: x * y,
            '/': lambda x,y: int(x / y)
        }

        for t in tokens:
            if t in operators:
                num2 = stack.pop()
                num1 = stack.pop()
                op = operators[t]
                stack.append(op(num1, num2))
            else:
                stack.append(int(t))

        return stack.pop()


class Solution(object):
    def checkPossibility(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums)<3:
            return True
        count,count2 = -1,-1
        for i in range(1,len(nums)):
            if nums[i-1]>nums[i]:
                count = i-1
                count2 = i
                break
        i = count2
        nums1 = nums[:i-1]+nums[i:]
        nums2 = nums[:i]+nums[i+1:]
        if self.check(nums1) or self.check(nums2):
            return True
        return False
    def check(self,nums):
        for i in range(1,len(nums)):
            if nums[i-1]>nums[i]:
                return False
        return True


def search1(plist, needle):
    """
    :param plist:
    :param needle:
    :return:
    """
    if not plist:
        return -1
    middle = len(plist)/2
    if needle == plist[middle]:
        return middle
    return search(plist[0:middle], needle) if plist[middle] > needle else middle + search(plist[middle:], needle)

def search2(plist, needle):

    if not plist:
        return -1
    low = 0
    high = len(plist) - 1

    while low <= high:
        middle = (low + high) / 2
        if plist[middle] == needle:
            return middle
        else:
            if needle < plist[middle]:
                high = middle - 1
            else:
                low = middle + 1
    return -1

def search(plist, needle):
    search2(plist, needle)

if __name__ == '__main__':
    print(search([1, 2, 3, 6, 8, 9], 8))
    print(search([1, 2, 3, 6, 8, 9], 8))
    print(search([1, 2, 3, 6, 8, 9], 8))


#!/usr/bin/env python

import rospy
from std_msgs.msg import String
import tf
from tf.transformations import quaternion_from_euler
import geometry_msgs.msg
import roslib
import actionlib
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
import numpy as np
from detect_outlier import DetectOutlier
from signal_recover import SignalRecover
import math
class SmartSurvey:
    def __init__(self, survey_time, map_setting, target_list, record_path):
        self.listener = tf.TransformListener()
        self.client = actionlib.SimpleActionClient('move_base',MoveBaseAction)
        self.client.wait_for_server()
        self.survey_time = survey_time
        self.map_setting = map_setting
        self.sojourn_time = 10
        self.survey_fg = []
        self.recover_fg = None
        self.outlier_fg = None
        self.target_list = target_list.tolist()
        self.target_once = target_list.tolist()
        self.record_path = record_path

        self.chatter_sub = None
        self.register_listener()

    def callback_chatter(self, data):
        # record fingerprints
        gettedData = data.data
        (trans, rot) = self.listener.lookupTransform('/map', '/base_link', rospy.Time(0))

        gettedData = str(rospy.Time.now().secs) +","+ str(trans[0]) + "," + str(trans[1]) + gettedData
        print(gettedData)
        gettedData = gettedData.split(',')
        observe = np.zeros(len(gettedData))
        for i in range(len(gettedData)):
            observe[i] = gettedData[i]
        self.survey_fg.append(observe)

    def register_listener(self):
        self.chatter_sub = rospy.Subscriber("chatter", String, self.callback_chatter)

    def unregister_listener(self):
        if self.chatter_sub != None:
            self.chatter_sub.unregister()

    def recover(self, raw_fg):
        tinker = SignalRecover(self.map_setting, raw_fg)
        tinker.recover_process()
        return tinker.GetResult()

    def detect_outlier(self, recover_fg):
        detector = DetectOutlier(recover_fg, self.map_setting, 2, self.target_list)
        detector.process()
        self.outlier_fg = detector.GetOutlierFingerprints()
        return detector.get_target_list()

    def send_goal(self,x,y,rot = 0):
        goal = MoveBaseGoal()
        goal.target_pose.header.frame_id = "map"
        goal.target_pose.header.stamp = rospy.Time.now()
        goal.target_pose.pose.position.x = x
        goal.target_pose.pose.position.y = y
        q = quaternion_from_euler(0, 0, rot)
        goal.target_pose.pose.orientation.x = q[0]
        goal.target_pose.pose.orientation.y = q[1]
        goal.target_pose.pose.orientation.z = q[2]
        goal.target_pose.pose.orientation.w = q[3]
        print("send goal "+ str(x) + "," +str(y))
        self.client.send_goal(goal)
        wait = self.client.wait_for_result()
        if not wait:
            rospy.logerr("Action server not available!")
        else:
            rospy.loginfo("reach goal")
            return self.client.get_result()

    def survey(self):
        last_target = self.target_once[0]
        for target in self.target_once:
            rot = math.atan2(target[1]-last_target[1], target[0]-last_target[0])
            self.send_goal(target[0], target[1], rot)
            last_target = target

    def resurvey(self):
        last_target = self.target_once[0]
        for target in self.target_once:
            rot = math.atan2(target[1]-last_target[1], target[0]-last_target[0])
            self.send_goal(target[0], target[1], rot)
            last_target = target
            rospy.sleep(self.sojourn_time)

    def run(self):
        print("run")
        for i in range(self.survey_time):
            if i == 0:
                self.survey()
            else:
                self.resurvey()
            np.savetxt(self.record_path + "/survey_points" + str(i) + ".csv", self.target_once, fmt='%f', delimiter=',',
                       newline='\r\n')
            np.savetxt(self.record_path+"/survey"+str(i)+".csv", np.array(self.survey_fg), fmt='%f', delimiter=',', newline='\r\n')
            self.recover_fg = self.recover(np.array(self.survey_fg))
            np.savetxt(self.record_path+"/recover"+str(i)+".csv", self.recover_fg, fmt='%f', delimiter=',', newline='\r\n')
            resurvey_target = self.detect_outlier(self.recover_fg)
            np.savetxt(self.record_path + "/outlier" + str(i) + ".csv", self.outlier_fg, fmt='%f', delimiter=',',
                       newline='\r\n')

            if len(resurvey_target) == len(self.target_list):
                break
            else:
                self.target_once = resurvey_target[len(self.target_list):]
                self.target_list = resurvey_target

    def run_sojourn(self):
        print("run")
        for i in range(1):
            self.resurvey()
            np.savetxt(self.record_path + "/survey_points" + str(i) + ".csv", self.target_once, fmt='%f', delimiter=',',
                       newline='\r\n')
            np.savetxt(self.record_path+"/survey"+str(i)+".csv", np.array(self.survey_fg), fmt='%f', delimiter=',', newline='\r\n')
            self.recover_fg = self.recover(np.array(self.survey_fg))
            np.savetxt(self.record_path+"/recover"+str(i)+".csv", self.recover_fg, fmt='%f', delimiter=',', newline='\r\n')
            resurvey_target = self.detect_outlier(self.recover_fg)
            np.savetxt(self.record_path + "/outlier" + str(i) + ".csv", self.outlier_fg, fmt='%f', delimiter=',',
                       newline='\r\n')

            if len(resurvey_target) == len(self.target_list):
                break
            else:
                self.target_once = resurvey_target[len(self.target_list):]
                self.target_list = resurvey_target

if __name__ == '__main__':
    try:
        rospy.init_node('movebase_client_py')
        map_setting = {'ap_num': 19, 'interval': 0.8, 'origin': [0.0, 0.0], 'lost_signal': -100}

        # run sojourn
        # target_list_generated = np.loadtxt('/home/heinrich/catkin_ws/coordinate/list_3F_corridor_static.csv', dtype=float, delimiter=',')
        # survey_sojourn = SmartSurvey(1,map_setting,target_list_generated,"/home/heinrich/survey_results/3F_corridor/sojourn")
        # survey_sojourn.run_sojourn()
        # survey_sojourn.unregister_listener()

        # run test
        target_list_generated = np.loadtxt('/home/heinrich/catkin_ws/coordinate/list_3F_corridor_mobile.csv', dtype=float, delimiter=',')
        survey_test = SmartSurvey(1,map_setting,target_list_generated,"/home/heinrich/survey_results/3F_corridor/test")
        survey_test.run()
        survey_test.unregister_listener()

        # run fast survey
        target_list_generated = np.loadtxt('/home/heinrich/catkin_ws/coordinate/list_3F_corridor_mobile.csv', dtype=float, delimiter=',')
        survey_re = SmartSurvey(2,map_setting,target_list_generated,"/home/heinrich/survey_results/3F_corridor/survey")
        survey_re.run()
        survey_re.unregister_listener()
    except rospy.ROSInterruptException:
        rospy.loginfo("Navigation test finished.")


from torch.utils.data.sampler import Sampler
import numpy as np
from collections import defaultdict
from .wrapped_summary_writer import WrappedSummaryWriter

# can handle lists of nested dictionaries
def stacked_dict(list_of_dicts):
    dict_of_lists = defaultdict(list)
    for dictionary in list_of_dicts:
        for key, value in dictionary.items():
            if isinstance(value, dict):
                dict_of_lists[key] = stacked_dict(
                    (outer_dict[key] for outer_dict in list_of_dicts)
                )
            else:
                dict_of_lists[key].append(value)
    for key, value in dict_of_lists.items():
        if isinstance(value, list):
            dict_of_lists[key] = np.vstack(value)
    return dict(dict_of_lists)

def canonicalize_audio_options(_audio_options, mmspec):
    audio_options = dict(_audio_options)
    whitelisted_keys = set([
        'sample_rate',
        'frame_size',
        'fft_size',
        'hop_size',
        'num_channels',
        'spectrogram_type',
        'filterbank',
        'num_bands',
        'fmin',
        'fmax',
        'fref',
        'norm',
        'norm_filters',
        'unique_filters',
        'circular_shift',
        'add'
    ])

    spectype = getattr(mmspec, audio_options['spectrogram_type'])
    del audio_options['spectrogram_type']

    if 'filterbank' in audio_options:
        audio_options['filterbank'] = getattr(mmspec, audio_options['filterbank'])

    # delete everything that is not in whitelist
    keys = list(audio_options.keys())
    for key in keys:
        if key not in whitelisted_keys:
            del audio_options[key]

    return spectype, audio_options

class ChunkedRandomSampler(Sampler):
    """Splits a dataset into smaller chunks (mainly to re-define what is considered an 'epoch').
       Samples elements randomly from a given list of indices, without replacement.
       If a chunk would be underpopulated, it's filled up with rest-samples.

    Arguments:
        data_source (Dataset): a dataset
        chunk_size      (int): how large a chunk should be
    """

    def __init__(self, data_source, chunk_size):
        self.data_source = data_source
        self.chunk_size = chunk_size
        self.i = 0
        self.N = len(self.data_source)
        # re-did this as numpy permutation, b/c FramedSignals do not like
        # torch tensors as indices ...
        # self.perm = torch.randperm(self.N)
        self.perm = np.random.permutation(self.N)

    def __iter__(self):
        rest = len(self.perm) - (self.i + self.chunk_size)
        if rest == 0:
            self.i = 0
            self.perm = np.random.permutation(self.N)
        elif rest < 0:
            # works b/c rest is negative
            carryover = self.chunk_size + rest
            self.i = 0
            self.perm = np.hstack([self.perm[-carryover:], np.random.permutation(self.N)])

        chunk = self.perm[self.i: self.i + self.chunk_size]
        self.i += self.chunk_size
        return iter(chunk)

    def __len__(self):
        return self.chunk_size

# from http://joseph-long.com/writing/colorbars/
def colorbar(mappable):
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    ax = mappable.axes
    fig = ax.figure
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    return fig.colorbar(mappable, cax=cax)

def minmax(x, symm):
    if symm:
        r = np.max(np.abs(x))
        vmin = -r
        vmax = r
    else:
        vmin = np.min(x)
        vmax = np.max(x)
    return vmin, vmax

def flip(x, preference):
    rows, cols = x.shape
    if preference == 'horizontal':
        if rows > cols:
            return x.T
    else:
        if rows < cols:
            return x.T
    return x

def tensor_plot_helper(fig, ax, x, cmap, symm, origin='lower', interpolation='nearest', preference='horizontal'):
    if len(x.shape) == 1:
        vmin, vmax = minmax(x, symm)
        x = x.reshape(-1, 1)
        im = ax.imshow(flip(x, preference), cmap=cmap, vmin=vmin, vmax=vmax, origin=origin, interpolation=interpolation)
    if len(x.shape) == 2:
        w, h = x.shape
        vmin, vmax = minmax(x, symm)
        im = ax.imshow(flip(x, preference), cmap=cmap, vmin=vmin, vmax=vmax, origin=origin, interpolation=interpolation)
    elif len(x.shape) == 3:
        n, w, h = x.shape
        a = b = int(np.ceil(np.sqrt(n)))

        ai = 0
        matrices = []
        for i in range(a):
            row = []
            for j in range(b):
                if ai < n:
                    cell = np.pad(x[ai], (1,), mode='constant', constant_values=0.)
                    ai += 1
                else:
                    cell = np.zeros((w + 2, h + 2))
                row.append(cell)
            matrices.append(row)

        _x = np.bmat(matrices)
        vmin, vmax = minmax(_x, symm)
        im = ax.imshow(flip(_x, preference), cmap=cmap, vmin=vmin, vmax=vmax, origin=origin, interpolation=interpolation)
    elif len(x.shape) == 4:
        a, b, w, h = x.shape
        matrices = []
        for i in range(a):
            row = []
            for j in range(b):
                row.append(np.pad(x[i, j], (1,), mode='constant', constant_values=0.))
            matrices.append(row)

        _x = np.bmat(matrices)
        vmin, vmax = minmax(x, symm)
        im = ax.imshow(flip(_x, preference), cmap=cmap, vmin=vmin, vmax=vmax, origin=origin, interpolation=interpolation)

    return im

# WARNING! this is not the same truncated normal as in numpy and tensorflow!!!
def truncated_normal_(tensor, mean=0, std=1):
    size = tensor.shape
    tmp = tensor.new_empty(size + (4,)).normal_()
    valid = (tmp < 2) & (tmp > -2)
    ind = valid.max(-1, keepdim=True)[1]
    tensor.data.copy_(tmp.gather(-1, ind).squeeze(-1))
    tensor.data.mul_(std).add_(mean)


visitors = [int(x) for x in open("prisoners.txt").readlines()]
has_visited = {}
lamp = False
c = 0
visits = 0

for visitor in visitors:
	visits += 1

	if visitor in has_visited:
		continue

	if visitor == 1:
		if lamp:
			lamp = False
			c += 1

		if c == 99:
			break
	elif lamp is False:
		lamp = True
		has_visited[visitor] = True

print(visits, c)


from __future__ import unicode_literals, print_function, absolute_import

#############################################################################

import sys
import unittest
from StringIO import StringIO

class TestPlugin(unittest.TestCase):
    """
    A class to test plugin inputs/outputs.
    """
    def execute(self, plugin, args, return_value, pattern, debug=False):
        sys.argv = [sys.argv[0]]
        for arg in args:
            sys.argv.append(arg)

        out = StringIO()
        old_stdout = sys.stdout
        sys.stdout = out

        try:
            try:
                plugin()
            finally:
                sys.stdout = old_stdout
        except SystemExit as err:
            output = out.getvalue().strip()

            if debug:
                print('Expected: %d, received: %d' % (return_value, err.code))
                print('Expected output: %s, received: %s' % (pattern, output))

            self.assertEquals(err.code, return_value, output)
            self.assertRegexpMatches(output, pattern)
            # in python >= 3.2 : change me to assertRegex
            # see: https://docs.python.org/3.2/library/unittest.html#unittest.TestCase.assertRegex


import sys
input = sys.stdin.readline

N = int(input().rstrip())
total = []
for _ in range(N):
    total.append(list(map(int, input().rstrip().split())))

total.append(total[0])
result = 0

for i in range(N):
    result += total[i][0] * total[i + 1][1]
    result -= total[i][1] * total[i + 1][0]

print(round(1 / 2 * abs(result), 1))

백준/Gold/2166. 다각형의 면적/다각형의 면적.py


import motor.motor_asyncio
import os
from model import Student

# MongoDB driver
mongoHost = os.getenv("MONGODB_HOST", "mongodb")
# url = 'mongodb://mongodb:27017/vdt2023'
url = f'mongodb://{mongoHost}:27017/vdt2023'
client = motor.motor_asyncio.AsyncIOMotorClient(url)

database = client.VDT
collection = database.student

async def fetch_all_students():
    students = []
    cursor = collection.find({})
    async for document in cursor:
        students.append(Student(**document))
    return students


import sys

sys.path.append("C:/Users/Adam/Documents/#Code/SDAQ/Python/lib")
import graphing
from tools import *

filenames = [
    #"C:/Users/Adam/Documents/#Code/SDAQ/Data/Mock R22/Calibration/Low-End/tie-Rod-A.sdaq"
    "C:/Users/Adam/Documents/#Code/SDAQ/Data/Mock R22/Raw/raw_tie_rod_mock.csv"
]

plot = graphing.Plot(title="Tie Rod Mock Endurance", xlabel="Time (s)", ylabel="Load (lbf)")
i = 0

for filename in filenames:
    file = open(filename, "r")
    xData = []
    yData = []

    for line in file:
        data = line.replace("[", "").replace("]", "").replace(",", " ").replace("  ", " ").split()
        isX = True
        for item in data:
            if isX:
                #print("x: " + item)
                xData.append(float(item))
            else:
                #print("y: " + item)
                yData.append(int(item))
            isX = not isX

    scale = 0.69
    flip = True
    graph = True
    roll_depth = 400
    intercept = 0.0

    if i == 0:
        roll_depth = 150

    index = 0
    for j in range(len(xData)):
        if xData[j] > 1500:
            index = j
            break

    xData = xData[index:-1]
    yData = yData[index:-1]

    (xData, yData, extraData) = apply_strain_calculations(xData, yData, isFlipped=flip, scale=scale, rolling_depth=roll_depth, intercept=intercept, angle_depth=4)

    if graph:
        if not (i == 0):
            plot.create_line(line_type="")

        plot.plot(i, xData, yData)
        ymax = yData[0]
        max_index = 0
        for index in range(1, len(xData)):
            if yData[index] > ymax:
                max_index = index
                ymax = yData[index]

        plot.annotate(xData[max_index], yData[max_index], xlabel="s", ylabel="lb")
    i += 1
    file.close()

input("Press ENTER to close...")


# -*- coding=utf-8
from json import load

from urllib3 import Retry
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging
import time
import os
from dotenv import load_dotenv

load_dotenv()
now = time.strftime("%Y-%m-%d_%H%M%S", time.localtime())
filename = "halo-" + now + ".tar.gz"

def backup(src, dest):
    command = "tar zc --exclude=logs --exclude=.git " + src + " -f " + dest
    os.system(command)

def upload_cos(bucket, filename):
    # 正常情况日志级别使用INFO，需要定位时可以修改为DEBUG，此时SDK会打印和服务端的通信信息
    logging.basicConfig(level=logging.INFO, stream=sys.stdout)

    # 1. 设置用户属性, 包括 secret_id, secret_key, region等。Appid 已在CosConfig中移除，请在参数 Bucket 中带上 Appid。Bucket 由 BucketName-Appid 组成
    secret_id = os.getenv("secret_id")
    secret_key = os.getenv("secret_key")
    region = os.getenv("region")
    token = None
    scheme = 'https'

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
    client = CosS3Client(config, retry=5)

    # # 本地路径 简单上传
    # response = client.put_object_from_local_file(
    #     Bucket=bucket,
    #     LocalFilePath=filename,
    #     Key=filename,
    # )
    # print(response['ETag'])

    # 高级上传接口
    response = client.upload_file(
        Bucket=bucket,
        LocalFilePath=filename,
        Key=filename,
        PartSize=1,
        MAXThread=10,
        EnableMD5=False
    )

def clean_tmp(filename):
    os.remove(filename)

if __name__ == "__main__":
    try:
        backup(os.getenv("backup_dir"), filename)
        upload_cos(os.getenv("bucket"), filename)
    finally:
        clean_tmp(filename)


import json
import math

import requests
from scipy.special import ndtri

class Ranking:
    rankingUser = 283230

    user_update_database_address = 'http://127.0.0.1:8080/api/user/{}'
    # user_update_database_address = 'http://157.253.222.182:8080/api/user/{}'
    ratings_file = '../../ml-latest/ratings.csv'
    complete_ranking_file = '../../ml-latest/ranking.json'
    movie_indexes_file = '../../ml-latest/movies-indexes.csv'
    confidence = 0.95

    def __init__(self):
        print('Creating index for movie ids and database ids')
        self.movie_database_id = {}
        with open(self.movie_indexes_file, 'r', encoding='utf-8') as movies_indexes:
            for line in movies_indexes:
                movie_index = line.split(',')
                movie_id = movie_index[0]
                db_id = movie_index[1][:-1]
                self.movie_database_id[movie_id] = db_id

        print('Creating n and total rating for every movie')
        self.movie_totals = {}
        with open(self.ratings_file, 'r', encoding='utf-8') as ratings:
            header = 0
            for line in ratings:
                if header:
                    rating = line.split(',')
                    user_id = rating[0]
                    movie_id = rating[1]
                    stars = float(rating[2])
                    if movie_id not in self.movie_totals:
                        self.movie_totals[movie_id] = (1, stars)
                    else:
                        old_n = self.movie_totals[movie_id][0]
                        old_t = self.movie_totals[movie_id][1]
                        new_n = old_n + 1
                        new_t = old_t + stars
                        self.movie_totals[movie_id] = (new_n, new_t)
                else:
                    header = 1

        print('Creating average for every movie')
        for movie in self.movie_totals:
            n = self.movie_totals[movie][0]
            t = self.movie_totals[movie][1]
            a = t / n
            self.movie_totals[movie] = (n, a)

        print('Creating pos for every movie')
        self.movie_pos = {}
        with open(self.ratings_file, 'r', encoding='utf-8') as ratings:
            header = 0
            for line in ratings:
                if header:
                    rating = line.split(',')
                    user_id = rating[0]
                    movie_id = rating[1]
                    stars = float(rating[2])
                    if movie_id not in self.movie_pos:
                        self.movie_pos[movie_id] = 0
                    average = self.movie_totals[movie_id][1]
                    if stars > average:
                        self.movie_pos[movie_id] += 1
                else:
                    header = 1

        print('Creating a single file with the data from every movie')
        self.movie_parameters = {}
        for movie in self.movie_totals:
            n = self.movie_totals[movie][0]
            p = self.movie_pos[movie]
            self.movie_parameters[movie] = (n, p)

    def ranking(self, top_n=12):
        items_ranking = {}
        print('Getting the complete ranking')
        index = 0
        for movie in self.movie_parameters:
            n = self.movie_parameters[movie][0]
            pos = self.movie_parameters[movie][1]
            if movie in self.movie_database_id:
                items_ranking[self.movie_database_id[movie]] = self.ci_lower_bound(
                    pos, n, self.confidence)

                index += 1
                if index % 1000 == 0:
                    print('Building ranking, {:.2f}% done.'.format(
                        index / 59000 * 100))
        ranking = sorted(items_ranking, key=items_ranking.get, reverse=True)

        with open(self.complete_ranking_file, 'w', encoding='utf-8') as complete_ranking:
            complete_ranking.write(json.dumps(items_ranking))

        return ['{}'.format(r) for r in ranking[:top_n]]

    def ci_lower_bound(self, pos, n, confidence):
        if n == 0:
            return 0
        z = ndtri(1-(1-confidence)/2)
        phat = 1.0*pos/n
        return (phat + z*z/(2*n) - z * math.sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n)

    def put_ranking(self):
        ranking = self.ranking()
        newTop = ''
        for top in ranking:
            newTop += ',{}'.format(top) if newTop else '{}'.format(top)
        print('Ranking: {}'.format(newTop))
        r = requests.put(
            self.user_update_database_address.format(self.rankingUser),
            json={'toponto': newTop})

        if r.status_code >= 300:
            print("Error updating ranking")

if __name__ == '__main__':
    ranking = Ranking()
    ranking.put_ranking()


from ex6_helper import load_image, show , save

def otsu(image):
    mean = lambda X : sum(X) / len(X) if len(X) > 0 else 0
    cost = lambda X , Y : len(X) * len(Y) * (( mean(X) - mean(Y) ) **2)

    optimth , optimcost = 0 , 0
    for th in range(256):
        blackpixels = []
        whitepixels = []
        for row in image:
            for pixel in row :
                 if pixel >= th :
                     blackpixels.append( pixel )
                 else :
                     whitepixels.append( pixel )
        if optimcost < cost(blackpixels , whitepixels) :
            optimth , optimcost = th , cost(blackpixels , whitepixels)
    return optimth

def threshold_filter(image):
    th = otsu(image)

    newimage = []
    for row in image:
        newimage.append([])
        for pixel in row :
            newimage[-1].append( 255 if pixel >= th else 0  )

    #save(newimage , "./test321.jpg")
    show(newimage )

def apply_filter(image, _filter):
    newimage = []
    for j ,row in enumerate(image):
        newimage.append([])
        for i , pixel in enumerate(row) :
            newimage[-1].append(0)
            for yhist in range (-1 , 2) :
                for xhist in range(-1 , 2) :
                    x = min( max( 0 , i + xhist ) , len(row) - 1)
                    y = min( max( 0,  j + yhist ) , len(image) - 1)
                    newimage[-1][-1] += image[y][x] * _filter[1 + yhist][1 + xhist]
            newimage[-1][-1] = min( int (abs( newimage[-1][-1]  )) , 255)
    return newimage

def detect_edges(image):
    _filter = [[ -0.125 for i in range(3)] for j in range(3)]
    _filter[1][1] = 1
    return apply_filter(image , _filter)

def downsample_by_3(image):
    _filter = [[ float( 1 / 9  ) for _ in range(3)] for __ in range(3)]
    newimage = []
    meanimage = apply_filter(image , _filter)
    for j in range(1 ,  len(image) , 3) :
        newimage.append([])
        for i in range ( 1 , len(image[j]) , 3):
             newimage[-1].append( meanimage[j][i])
    return newimage

def downsample(image, max_diagonal_size):

    def diagonal(image):
        return  int((len(image) ** 2 + len(image[0])**2) ** 0.5)
    newimage = image
    while ( diagonal(newimage) > max_diagonal_size ):
        newimage = downsample_by_3( newimage )
    return  newimage

from math import pi
'''
def get_angle(image):
    for angle in range( 0 , pi / 2 , 1 / (2*pi)  ) :
        for distance in range(0 , len(image) / (2 ** 0.5) , 0.1 ):
            lines , newline = [] , True
            for pixel in pixels_on_line(image, angle, distance, top=True):
                if pixel == 0 :
                    if newline :
                        lines.append([])
                        newline = False
                    lines[-1].append( pixel )
                else:
                    newline = True
            weight = 0
            for line in lines:
                weight += len(line) ** 2
'''

import os
if __name__ == "__main__" :
    args = os.sys.argv

    show( downsample_by_3(load_image( args[1 ])))


import pytest
import os
from pathlib import Path

collect_ignore = ["scrape/test_get_boe_pdfs.py"]

@pytest.fixture(scope="session")
def pdf_dir(tmp_path_factory):
    basetemp = Path.cwd() / "temp_dir"
    os.environ["PYTEST_DEBUG_TEMPROOT"] = str(basetemp)
    basetemp.mkdir(parents=True, exist_ok=True)
    dir = tmp_path_factory.mktemp("pdf_files", numbered=False)
    print(dir)
    return dir


from logging import Formatter

# PURP: - TO PROVIDE A CENTRAL FILE FOR STRINGS REPEATEDLY USED THROUGHOUT THE PROJECT.

# MARK: - Logger File Basic Config constants
LOG_FORMAT = '%(levelname)s: %(asctime)s: %(message)s'
LOG_DATE_FORMAT = '%m/%d/%Y %I:%M:%S %p'

# MARK: - Logger constants strings
COMP_ERROR = "Computational Errors"

# MARK: drive_dump.py constants
# NOTE: - Why? Cause Fuck Network Drives that's why.

# drive types
DRIVE_UNKNOWN     = 0  # The drive type cannot be determined.
DRIVE_NO_ROOT_DIR = 1  # The root path is invalid; for example, there is no volume mounted at the specified path.
DRIVE_REMOVABLE   = 2  # The drive has removable media; for example, a floppy drive, thumb drive, or flash card reader.
DRIVE_FIXED       = 3  # The drive has fixed media; for example, a hard disk drive or flash drive.
DRIVE_REMOTE      = 4  # The drive is a remote (network) drive.
DRIVE_CDROM       = 5  # The drive is a CD-ROM drive.
DRIVE_RAMDISK     = 6  # The drive is a RAM disk.

# map drive types to strings
DRIVE_TYPE_MAP = { DRIVE_UNKNOWN     : 'DRIVE_UNKNOWN',
                   DRIVE_NO_ROOT_DIR : 'DRIVE_NO_ROOT_DIR',
                   DRIVE_REMOVABLE   : 'DRIVE_REMOVABLE',
                   DRIVE_FIXED       : 'DRIVE_FIXED',
                   DRIVE_REMOTE      : 'DRIVE_REMOTE',
                   DRIVE_CDROM       : 'DRIVE_CDROM',
                   DRIVE_RAMDISK     : 'DRIVE_RAMDISK'}

MAC_OS = 'Darwin'
LINUX = 'Linux'
WINDOWS = 'Windows'

MACOS_DETECTED = 'MacOS System detected'
LINUX_DETECTED = 'Linux System detected'
WINDOWS_DETECTED = 'Windows System detected'

MACOS_CRITICAL = 'Can not read the MacOS structure'
LINUX_CRITICAL = 'Can not read the Linux structure'
WINDOWS_CRITICAL = 'Can not read the Windows structure'
INDIE_CRITICAL = 'Can not read the OS structure'

# arg constants
V = '-v'
Q = '-q'
D = '-d'
DRV = '--drv'
L = '-l'
FLD = '--fld'
F = '-f'
FIL = '--fil'
T = '-t'
TYP = '--typ'

# For Type Defaults
ALL = "ALL"