import os.path
import errno
import copy
import six

from twisted.trial import unittest
from twisted.internet import defer

from virtualbricks import (link, virtualmachines as vm, errors, settings,
                           configfile, tools)
from virtualbricks.tests import (stubs, test_link, successResultOf,
                                 failureResultOf, TEST_DATA_PATH)

def disks(vm):
    return (vm.config.__getitem__(d) for d in ("hda", "hdb", "hdc", "hdd",
                                               "fda", "fdb", "mtdblock"))

ARGS = ["true", "-m", "64", "-smp", "1", "@@DRIVESARGS@@", "-name", "vm",
        "-net", "none", "-mon", "chardev=mon", "-chardev",
        "socket,id=mon,path=/home/marco/.virtualbricks/vm.mgmt,server,nowait",
        "-mon", "chardev=mon_cons", "-chardev", "stdio,id=mon_cons,signal=off"]

class _Image(vm.Image):

    def __init__(self):
        self.acquired = []
        self.released = []

    def acquire(self, disk):
        self.acquired.append(disk)

    def release(self, disk):
        self.released.append(disk)

class TestVirtualMachine(unittest.TestCase):

    def setUp(self):
        self.factory = stubs.FactoryStub()
        self.vm = stubs.VirtualMachineStub(self.factory, "vm")
        self.image_path = os.path.abspath(self.mktemp())
        self.image = vm.Image("test", self.image_path)
        self.vm.get("hda").set_image(self.image)

    def get_args(self, *drive_args):
        args = ARGS[:]
        i = args.index("@@DRIVESARGS@@")
        args[i:i + 1] = drive_args
        return args

    def test_args(self):
        self.todo = 'test broken, to be refactored'
        args = self.get_args("-hda", self.image_path)
        self.assertEquals(successResultOf(self, self.vm.args()), args)

    def test_args_virtio(self):
        self.todo = 'test broken, to be refactored'
        self.vm.set({"use_virtio": True})
        drv = "file={0},if=virtio".format(self.image_path)
        args = self.get_args("-drive", drv)
        self.assertEquals(successResultOf(self, self.vm.args()), args)

    def test_add_plug_hostonly(self):
        mac, model = object(), object()
        plug = self.vm.add_plug(vm.hostonly_sock, mac, model)
        self.assertEqual(plug.mode, "vde")
        self.assertEqual(len(self.vm.plugs), 1)
        self.assertIs(plug.sock, vm.hostonly_sock)
        self.assertIs(plug.mac, mac)
        self.assertIs(plug.model, model)

    def test_add_plug_sock(self):
        brick = stubs.BrickStub(self.factory, "test")
        sock = vm.VMSock(self.factory.new_sock(brick))
        plug = self.vm.add_plug(sock)
        self.assertEqual(plug.mode, "vde")
        self.assertEqual(len(self.vm.plugs), 1)
        self.assertIs(plug.sock, sock)
        self.assertEqual(len(sock.plugs), 1)
        # self.assertIs(sock.plugs[0], plug)

    def test_add_sock(self):
        mac, model = object(), object()
        sock = self.vm.add_sock(mac, model)
        self.assertEqual(self.vm.socks, [sock])
        self.assertIs(sock.mac, mac)
        self.assertIs(sock.model, model)
        self.assertEqual(self.factory.socks, [sock.original])

    def test_get_disk_args(self):
        disk = DiskStub(self.vm, "hda")
        self.vm.config["hda"] = disk

    def test_del_brick(self):
        factory = stubs.FactoryStub()
        vm = factory.new_brick("vm", "test")
        sock = vm.add_sock()
        self.assertEqual(factory.socks, [sock.original])
        factory.del_brick(vm)
        self.assertEqual(factory.socks, [])

    def test_brick_plug_sock_self(self):
        """A plug can be connected to a sock of the same brick."""
        sock = self.vm.add_sock()
        plug = self.vm.add_plug(sock)
        self.assertEqual(self.vm.socks, [sock])
        self.assertEqual(self.vm.plugs, [plug])
        self.assertIs(plug.sock, sock)
        self.assertIs(plug.brick, sock.brick)

    def test_poweron_loop_on_self_plug(self):
        """If a vm is plugged to itself it can start without error. The last
        check seem obvious but poweron() deferred is called only there is no
        errors."""
        self.vm._poweron = lambda _: defer.succeed(None)
        self.vm.add_plug(self.vm.add_sock())
        d = self.vm.poweron()
        d.callback(self.vm)
        self.assertEqual(successResultOf(self, d), self.vm)

    def test_lock(self):
        self.vm.acquire()
        self.vm.release()
        image = vm.Image("test", "/vmimage")
        disk = DiskStub(self.vm, "hdb")
        disk.set_image(image)
        disk.acquire()
        self.vm.config["hda"].set_image(image)
        self.assertRaises(errors.LockedImageError, self.vm.acquire)
        _image = _Image()
        self.vm.config["hdb"].set_image(_image)
        try:
            self.vm.acquire()
        except errors.LockedImageError:
            pass
        else:
            self.fail("vm lock acquired but it should not happend")
        self.assertEqual(_image.acquired, _image.released)

class TestVMPlug(test_link.TestPlug):

    @staticmethod
    def sock_factory(brick):
        return vm.VMSock(link.Sock(brick))

    @staticmethod
    def plug_factory(brick):
        return vm.VMPlug(link.Plug(brick))

class TestVMSock(test_link.TestSock):

    @staticmethod
    def plug_factory(brick):
        return vm.VMPlug(link.Plug(brick))

    @staticmethod
    def sock_factory(brick):
        return vm.VMSock(link.Sock(brick))

    def test_has_valid_path2(self):
        factory = stubs.FactoryStub()
        vm = stubs.VirtualMachineStub(factory, "vm")
        sock = vm.add_sock()
        self.assertTrue(sock.has_valid_path())

HOSTONLY_CONFIG = """[Qemu:vm]
name=vm

link|vm|_hostonly|rtl8139|00:11:22:33:44:55
"""

class TestPlugWithHostOnlySock(unittest.TestCase):

    def setUp(self):
        self.factory = stubs.FactoryStub()
        self.vm = self.factory.new_brick("vm", "vm")
        self.plug = self.vm.add_plug(vm.hostonly_sock, "00:11:22:33:44:55")

    def test_add_plug(self):
        self.assertIs(self.plug.sock, vm.hostonly_sock)

    def test_poweron(self):
        self.vm._poweron = lambda _: defer.succeed(self.vm)
        d = self.vm.poweron()
        d.callback(self.vm)

    def test_config_save(self):
        sio = six.StringIO()
        configfile.ConfigFile().save_to(self.factory, sio)
        self.assertEqual(sio.getvalue(), HOSTONLY_CONFIG)

    def test_config_resume(self):
        self.factory.del_brick(self.vm)
        self.assertEqual(len(self.factory.bricks), 0)
        sio = six.StringIO(HOSTONLY_CONFIG)
        configfile.ConfigFile().restore_from(self.factory, sio)
        self.assertEqual(len(self.factory.bricks), 1)
        vm1 = self.factory.get_brick_by_name("vm")
        self.assertEqual(len(vm1.plugs), 1)
        plug = vm1.plugs[0]
        self.assertEqual(plug.mac, "00:11:22:33:44:55")
        self.assertIs(plug.sock, vm.hostonly_sock)

class ImageStub:

    path = "cucu"

class NULL:

    def __eq__(self, other):
        return self is other

    def __ne__(self, other):
        return self is not other

class FULL:

    def __eq__(self, other):
        return True

    def __ne__(self, other):
        return False

class DiskStub(vm.Disk):

    _basefolder = None
    sync_cmd = "false"

    def get_basefolder(self):
        if self._basefolder is not None:
            return self._basefolder
        return self.VM.get_basefolder()

    def set_basefolder(self, value):
        self._basefolder = value

    basefolder = property(get_basefolder, set_basefolder)

class Object:
    pass

class TestDisk(unittest.TestCase):

    def setUp(self):
        self.factory = stubs.FactoryStub()
        self.vm = stubs.VirtualMachineStub(self.factory, "test_vm")
        self.disk = DiskStub(self.vm, "hda")

    def test_create_cow(self):
        settings.set("qemupath", "/supercali")
        failureResultOf(self, self.disk._create_cow("name"),
                        errors.BadConfigError)
        settings.set("qemupath", TEST_DATA_PATH)
        self.disk.image = ImageStub()

        def cb(ret):
            self.fail("cow created, callback called with %s" % ret)

        def eb(failure):
            failure.trap(RuntimeError)
        return self.disk._create_cow("1").addCallbacks(cb, eb)

    def test_sync_err(self):
        def cb(ret):
            self.fail("_create_cow did not failed while it had to")

        def eb(failure):
            failure.trap(RuntimeError)
            failure.value.args[0].startswith("sync failed")

        return self.disk._sync(("", "", 0)).addCallbacks(cb, eb)

    def test_check_base(self):
        err = self.assertRaises(IOError, self.disk._check_base, "/montypython")
        self.assertEqual(err.errno, errno.ENOENT)
        self.patch(tools, "get_backing_file", lambda _: NULL())
        self.disk._create_cow = lambda _: defer.succeed(None)
        self.disk.image = ImageStub()
        cowname = self.mktemp()
        fp = open(cowname, "w")
        fp.close()
        result = []
        self.disk._check_base(cowname).addCallback(result.append)
        self.assertEqual(result, [cowname])
        self.patch(tools, "get_backing_file", lambda _: FULL())
        del result[:]
        cowname = self.mktemp()
        fp = open(cowname, "w")
        fp.close()
        self.disk._check_base(cowname).addCallback(result.append)
        self.assertEqual(result, [cowname])

    def test_get_cow_name(self):
        self.disk.basefolder = "/nonono/"
        err = self.assertRaises(OSError, self.disk._get_cow_name)
        self.assertEqual(err.errno, errno.EACCES)
        self.disk.basefolder = basefolder = self.mktemp()
        self.disk._check_base = lambda passthru: defer.succeed(passthru)

        def cb(cowname):
            self.assertTrue(os.path.exists(basefolder))
            self.assertEqual(cowname, os.path.join(basefolder, "%s_%s.cow" %
                                                   (self.disk.VM.name,
                                                    self.disk.device)))
        return self.disk._get_cow_name().addCallback(cb)

    def test_get_cow_name_create_cow(self):

        def throw(_errno):
            def _check_base(_):
                raise IOError(_errno, os.strerror(_errno))
            return _check_base

        self.disk.basefolder = basefolder = self.mktemp()
        cowname = os.path.join(basefolder, "%s_%s.cow" % (self.disk.VM.name,
                                                          self.disk.device))
        self.disk._check_base = throw(errno.EACCES)
        self.disk._create_cow = lambda passthru: defer.succeed(passthru)
        err = self.assertRaises(IOError, self.disk._get_cow_name)
        self.assertEqual(err.errno, errno.EACCES)
        self.disk._check_base = throw(errno.ENOENT)
        result = []
        self.disk._get_cow_name().addCallback(result.append)
        self.assertEqual(result, [cowname])

    def test_args(self):
        # XXX: Temporary pass this test but rework disk.args()
        self.assertIs(self.disk.image, None)
        self.disk.get_real_disk_name = lambda: defer.succeed("test")
        self.assertEqual(successResultOf(self, self.disk.args()), [])
        # self.assertEqual(successResultOf(self, self.disk.args()),
        #                                  ["-hda", "test"])
        # f = failure.Failure(RuntimeError())
        # self.disk.get_real_disk_name = lambda: defer.fail(f)
        # failureResultOf(self, self.disk.args(), RuntimeError)

    def test_get_real_disk_name(self):

        def raise_IOError():
            raise IOError(-1)

        result = successResultOf(self, self.disk.get_real_disk_name())
        self.assertEqual(result, "")
        self.disk.image = Object()
        self.disk.image.path = "ping"
        result = successResultOf(self, self.disk.get_real_disk_name())
        self.assertEqual(result, "ping")
        self.disk._get_cow_name = raise_IOError
        self.vm.config["private" + self.disk.device] = True
        failureResultOf(self, self.disk.get_real_disk_name(), IOError)

    def test_deepcopy(self):
        disk = copy.deepcopy(self.disk)
        self.assertIsNot(disk, self.disk)
        self.assertIs(disk.image, None)
        image = self.factory.new_disk_image("test", "/cucu")
        self.disk.set_image(image)
        disk = copy.deepcopy(self.disk)
        self.assertIsNot(disk, self.disk)
        self.assertIsNot(disk.image, None)
        self.assertIs(disk.image, image)

    def test_acquire(self):
        self.assertFalse(self.disk.cow)
        self.assertIs(self.disk.image, None)
        self.assertFalse(self.vm.config["snapshot"])
        self.disk.acquire()
        image = vm.Image("test", "/vmimage")
        self.vm.set({"snapshot": False, "privatehda": False})
        self.disk.set_image(image)
        self.disk.acquire()
        self.assertIs(image.master, self.disk)
        disk = DiskStub(self.vm, "hdb")
        disk.set_image(image)
        self.assertRaises(errors.LockedImageError, disk.acquire)

    def test_release(self):
        self.assertFalse(self.disk.cow)
        self.assertIs(self.disk.image, None)
        self.assertFalse(self.vm.config["snapshot"])
        self.disk.release()
        image = vm.Image("test", "/vmimage")
        self.vm.set({"snapshot": False, "privatehda": False})
        self.disk.set_image(image)
        self.disk.acquire()
        self.disk.release()

class TestImage(unittest.TestCase):

    def test_acquire(self):
        image = vm.Image("test", "/vmimage")
        o = object()
        image.acquire(o)
        self.assertIs(image.master, o)
        exc = self.assertRaises(errors.LockedImageError, image.acquire,
                                object())
        self.assertEqual(exc.args, (image, o))
        image.acquire(o)

    def test_release(self):
        image = vm.Image("test", "/vmimage")
        exc = self.assertRaises(errors.LockedImageError, image.release,
                                object())
        self.assertEqual(exc.args, (image, None))
        image.release(None)
        o = object()
        image.acquire(o)
        image.release(o)
        self.assertRaises(errors.LockedImageError, image.release, o)


#!/usr/bin/env python

import json
import unittest
from unittest.mock import patch
from urllib.request import Request

import imi.handlers

__all__ = ['TestCustomHandler']

class TestCustomHandler(unittest.TestCase):

    def setUp(self):
        self.handler = imi.handlers.CustomHandler()

    def test_noop_open(self):
        data = json.dumps({'a': 'b'}).encode('utf-8')
        req = Request('noop://example?b=c', data=data)
        res = json.loads(self.handler.noop_open(req).read().decode('utf-8'))
        self.assertEqual({'a': 'b', 'b': 'c'}, res)

    @patch('imi.handlers.subprocess.check_output')
    def test_command_open(self, check_output):
        data = json.dumps({'a': 'b'}).encode('utf-8')
        check_output.return_value = json.dumps({'b': 'c'}).encode('utf-8')
        req = Request('command://example', data=data)
        res = json.loads(self.handler.command_open(req).read().decode('utf-8'))
        self.assertEqual({'b': 'c'}, res)

    def tearDown(self):
        pass

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


import os

from fastapi import FastAPI
from fastapi.responses import FileResponse

app = FastAPI()

path = "/home/nathalia/Documents/python/intro-fastapi"

@app.get("/")
def index():
    return {"message": "Hello World"}

@app.get("/dog", responses={200: {"description": "A picture of a dog."}})
def dog():
    file_path = os.path.join(path, "files/dog.jpg")
    if os.path.exists(file_path):
        return FileResponse(
            file_path,
            media_type="image/jpeg",
            filename="dog.jpg"
        )

    return {"error": "File not found!"}


import os.path as osp

from .builder import DATASETS
from .custom import CustomDataset

@DATASETS.register_module()
class ChaseDB1Dataset(CustomDataset):
    """Chase_db1 dataset.

    In segmentation map annotation for Chase_db1, 0 stands for background,
    which is included in 2 categories. ``reduce_zero_label`` is fixed to False.
    The ``img_suffix`` is fixed to '.png' and ``seg_map_suffix`` is fixed to
    '_1stHO.png'.
    """

    CLASSES = ('background', 'vessel')

    PALETTE = [[120, 120, 120], [6, 230, 230]]

    def __init__(self, **kwargs):
        super(ChaseDB1Dataset, self).__init__(
            img_suffix='.png',
            seg_map_suffix='_1stHO.png',
            reduce_zero_label=False,
            **kwargs)
        assert osp.exists(self.img_dir)


### Model Configuration File ###

### Model config ###
# models path
model_path = "./model/checkpoints/"
# model checkpoint path pattern, used for restoring models and saving checkpoints in training
checkpoint_pattern = "checkpoint-*.h5"
model_config_name = "DenseNet-model.json"
model_weights_name = "DenseNet-weights.h5"

output_size = 2
img_dim = (None, None, 3)
input_dim = (48, 48, 3)

### Network params ###
dropout = 0.2
depth = 20
growth_rate = 12
dense_blocks = 3
filters = 16
weight_decay = 1e-4

labels = {
        'unknown' : 0,
        'off' : 1,

        'green' : 2,
        'yellow' : 4,
        'red' : 8
    }


# from PIL import Image, ImageFont, ImageDraw, ImageEnhance
import json

# source_img = Image.open("test_nt_tut.jpg").convert("RGBA")
import os
import sys
import subprocess

im_height = 2337  # height of pixels
im_width = 1637  # width of pixels

def get_av(my_data):
    av = []
    for block in my_data:
        if len(av) == 0:
            av.append({"bottom": block['bottom'], "top": block['top']})
        else:
            apnded = True
            for i in range(len(av)):
                if min(av[i]['bottom'], block['bottom']) - max(av[i]['top'], block['top']) > 0:  # some error value
                    av[i]['bottom'] = max(av[i]['bottom'], block['bottom'])
                    av[i]['top'] = min(av[i]['top'], block['top'])
                    apnded = False;
                    break
            if apnded:
                av.append({"bottom": block['bottom'], "top": block['top']})
    i = 0
    while i < len(av):
        j = 0
        while j < len(av):
            if i != j and min(av[i]['bottom'], av[j]['bottom']) - max(av[i]['top'], av[j]['top']) > 0:
                av[i]['bottom'] = max(av[i]['bottom'], av[j]['bottom'])
                av[i]['top'] = min(av[i]['top'], av[j]['top'])
                del av[j]
                if j < i:
                    i -= 1
                j -= 1
            j += 1
        i += 1
    newlist = sorted(av, key=lambda k: k['top'])
    return newlist

def is_script(t_val, b_val, block):
    return (b_val - t_val) > 1.5 * (block['bottom'] - block['top']) and (
        "\\sum" not in block['label'] and "\\prod" not in block['label'] and "\\int" not in block['label'])

def assign_char(my_data, rows):
    result = [list() for _ in range(len(rows))]
    for block in my_data:
        mdpnt = (block["bottom"] - block["top"]) / 2 + block["top"]
        for i in range(len(rows)):
            if rows[i]['top'] <= mdpnt and rows[i]['bottom'] >= mdpnt:
                result[i].append(block)

    for i in range(len(result)):
        newlist = sorted(result[i], key=lambda k: k['left'])
        result[i] = newlist
    return result

def parse_line(row):
    sp = " \quad "
    line_divide = "\\noindent\\makebox[\\linewidth]{\\rule{\\textwidth}{1pt}}"
    mt_str = ""
    char_width = 10
    char_height = 20
    if len(row) == 0:
        return mt_str
    my_prev = None
    underline = False
    supers = False
    subscr = False
    superscript = ""
    subscript = ""
    word = ""
    my_top = 0
    my_bot = 0
    lngdvd = None
    nmrtr = ""
    dnmtr = ""
    for block in row:
        if block['label'] == "-" and block['right'] - block['left'] > 100:
            underline = True
        else:
            if my_prev != None and my_prev['right'] + 1 < block['left']:
                word += (subscript + superscript)
                supers = False
                subscr = False
                superscript = ""
                subscript = ""
                if "\\" in word or "_" in word or "^" in word or "<" in word or ">" in word:
                    word = " \\( " + word + " \\) "
                mt_str += (word + sp)
                word = ""
                my_top = im_height
                my_bot = 0
            is_s = is_script(my_top, my_bot, block)
            if block['label'] == "long_divide" or block['label'] == "lond_divide":
                lngdvd = block
            elif lngdvd != None:
                if lngdvd['left'] < block['left'] and lngdvd['right'] > block['right']:
                    if block['top'] < lngdvd['top']:
                        nmrtr += block['label']
                    else:
                        dnmtr += block['label']
                    block = lngdvd
                else:
                    word += " \\frac{" + nmrtr + "}{" + dnmtr + "} "
                    lngdvd = None
            elif is_s and my_top > block['top']:  # superscript
                if supers:
                    superscript = superscript[0:-1] + block['label'] + "}"
                else:
                    superscript = "^{" + block['label'] + "}"
                supers = True
            elif is_s and my_bot < block['bottom']:  # subscript
                if subscr:
                    subscript = subscript[0:-1] + block['label'] + "}"
                else:
                    subscript = "_{" + block['label'] + "}"
                subscr = True
            else:
                my_top = min(my_top, block['top'])
                my_bot = max(my_bot, block['bottom'])
                word += (subscript + superscript + block['label'])
                superscript = ""
                subscript = ""
                supers = False
                subscr = False
            my_prev = block
    if lngdvd != None:
        word += " \\frac{" + nmrtr + "}{" + dnmtr + "} "
    word += (subscript + superscript)
    if "\\" in word or "_" in word or "^" in word or "<" in word or ">" in word:
        word = " \\( " + word + " \\) "
    mt_str += word
    if underline and len(mt_str) > 0:
        mt_str = "\\underline{" + mt_str + "}"
    if underline and len(mt_str) == 0:
        mt_str = line_divide
    return mt_str

def gen_tex(my_json, uid, bid):
    with open(my_json, "r") as myfile:
        data = json.load(myfile)

    # draw = ImageDraw.Draw(source_img)
    my_av = get_av(data)

    my_rows = assign_char(data, my_av)

    # colors = ["red","orange","lime","cyan","blue"]
    # indx = 0
    my_latex = "\documentclass[12pt]{article}\n\\usepackage{xcolor}\n\\usepackage[normalem]{ulem}\n\\usepackage[utf8]{inputenc}\n\\usepackage[margin=0.5in]{geometry}\n\\usepackage[english]{babel}\n\\usepackage[document]{ragged2e}\n\\usepackage{ushort}\n\\begin{document}\n\t\\begin{center}\n"

    for row in my_rows:
        # color = colors[indx%5]
        # draw.rectangle((0, my_av[indx]['top'], 1600, my_av[indx]['bottom']), fill=None, outline=color)
        # indx+=1
        this_line = parse_line(row)
        if len(this_line) > 0:
            my_latex += ("\t\t" + this_line + "\\newline\n")
            # for block in row:
            #	draw.rectangle(((block['left'], block['top']), (block['right'], block['bottom'])), fill=None, outline=color)
            #	if block['label'] != None:
            #		draw.text((block['left'], block['top']), block['label'], fill="black")
    # source_img.save("out_file.jpg", "JPEG")
    filename = str(uid) + str(bid)
    file = open(filename, "w")
    file.write(my_latex + "\t\\end{center}\n\\end{document}")
    file.close()
    return filename

def run_main():
    filename = ''
    for line in sys.stdin:
        json_dicts = json.loads(line)
        user_id = json_dicts['userId']
        book_id = json_dicts['bookId']
        temp_file = 'temp' + str(user_id) + str(book_id)
        with open(temp_file, 'w') as f:
            json.dump(json_dicts['data'], f)
        filename = gen_tex(temp_file, user_id, book_id)
        os.remove(temp_file)
        break

    process = subprocess.Popen(['pdflatex', '-interaction=nonstopmode', filename],
                               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    process.communicate()

    os.remove(filename + '.log')
    os.remove(filename + '.aux')

if __name__ == '__main__':
    run_main()


class Solution:
    def bagOfTokensScore(self, tokens: List[int], P: int) -> int:
        tokens.sort()
        power, max_score, score = P, 0, 0
        i, j = 0, len(tokens) - 1
        while i <= j:
            while i <= j and power >= tokens[i]:
                power -= tokens[i]
                score += 1
                i += 1
            max_score = max(max_score, score)

            if not score:
                return max_score
            power += tokens[j]
            score -= 1
            j -= 1
        return max_score


#!/usr/bin/python

#from __future__ import print_function
# argv argument
import sys
# REGEX
import re
# prace se soubory
import os.path
#xml data
import xml.etree.ElementTree as ET

class Frame:
     def __init__(self, frame ):
         self.table = []
         self.frame = frame
         self.inicialized = 1

class Interpret:

    def __init__(self, structure ):
       self.glob_frame = Frame ('global' ) ;
       self.local_frame = Frame ('local' ) ;
       self.tmp_frame = Frame ('temporary' ) ;

       # inicializujeme globalni ramec, dame sem empty array
       self.glob_frame.table = ([[]])

       self.expectedLabel = []
       self.labels = []
       self.dataStack = []
       self.callStack = []; # zasobnik volani
       self.structure = structure
       # zacneme u instrukce 1
       self.processedInstruction = 1

       # abychom vedeli jake volat funkce k jednotlivym instrkcim
       self.callInstruction = {
            "ADD" : "getAdd", "SUB" : "getSub" , "MUL" : "getMul", "IDIV" : "getIdiv",
            "LT" : "getLT" , "GT" : "getGT" , "EQ" :"getEQ", "AND" :"getAnd",
            "OR" : "getOr", "STRI2INT" : "getStri2int", "GETCHAR" : "getGetchar" , "SETCHAR" : "getSetchar","CONCAT" : "getConcat",
            "JUMPIFEQ": "getJumpIfEq", "JUMPIFNEQ" : "getJumpIfNeq",
            "INT2CHAR" : "getInt2char", "STRLEN" : "getStrlen", "TYPE" : "getTypeI", "MOVE" : "getMove" ,"NOT" : "getNot",
            "READ" :"getRead" ,
            "DEFVAR" : "getDefvar" , "POPS" : "getPops",
            "PUSHS" : "getPushs", "WRITE" : "getWrite", "DPRINT" : "getDprint",
            "CALL" : "getCall", "LABEL" :"getLabel", "JUMP" : "getJump" ,
            "BREAK" : "getBreak", "CREATEFRAME" : "getCreateFrame" , "PUSHFRAME" : "getPushFrame", "POPFRAME" : "getPopFrame",
            "RETURN" : "getReturn"
        }

    def getTableAccorrdingToFrame( self, frame ):
        # je neco na vrcholu zasobniku
        if ( frame == 'GF' ):
             table_name = 'glob_frame';
        if ( frame == 'TF' ):
            table_name = 'tmp_frame';
        elif( frame == 'LF' ):
            table_name = 'local_frame';

        frame_obj = getattr(self, table_name )
        if ( len( frame_obj.table ) != 0):
            return frame_obj.table[len( frame_obj.table ) - 1]
        else:
            print ( "Snazime se deklarovat lokalni promennou bez definovani ramce" , file=sys.stderr )
            exit ( 55 ) # ramec neexistuje

    # pridame item do tabulky podle framu
    def addNewItem( self, name, frame ):
        # mohu vlozit pouze pokud na vrcholu zasobniku je nejake pole, do ktereho muzu vlozit
        table = self.getTableAccorrdingToFrame(frame)
        table.append( { 'name' : name, 'inicialized' : 0 } )

    # hledam item podle jmena a framu
    def searchItem( self, name, frame ):
        table = self.getTableAccorrdingToFrame(frame)

        for hash_item in table:
            if hash_item[ 'name' ] == name:
                return hash_item
        # pokud nic nenajdeme
        return 0

    # najdu v tabulce, inicliazuju
    # pro bool si to ukladame v pythonovkych makrech True a False
    def initItem( self, name, value, typevar, frame ):
        table = self.getTableAccorrdingToFrame(frame);
        for hash_item in table:
            if name in hash_item[ 'name' ] == name:
                hash_item[ 'inicialized' ] = 1
                if typevar == 'bool':
                    if ( value == 'true' or value == True ):
                        value = True
                    else:
                        value = False
                elif( typevar == 'int' ):
                     value = int(value)

                hash_item[ 'value' ] = value
                hash_item[ 'type' ] = typevar
                return hash_item # jak najdeme, muzeme skoncit
        return None

    def initItemElseExit( self, name, value, typevar, frame ):
        table = self.getTableAccorrdingToFrame(frame)
        for hash_item in table:
            if name in hash_item[ 'name' ] == name:
                hash_item[ 'inicialized' ] = 1
                if typevar == 'bool':
                    if ( value == 'true' or value == True ):
                        value = True
                    else:
                        value = False
                hash_item[ 'value' ] = value
                hash_item[ 'type' ] = typevar
                #print (table);
                return hash_item # jak najdeme, muzeme skoncit

        #nenasli jsme, neni v tabulce
        print ( "Nedefinovana promenna %s" % name, file=sys.stderr )
        exit ( 54) #semanticka kontrola

    # zjistim, jestli uz je inicilaizovana
    def isInit( self, name, frame ):
        item = self.searchItem(name, frame)
        if item:
            return item[ 'inicialized' ]
        else:
            return 0

    # funkce vraci typ promenne
    def getTypeVar(self, name, frame):
        item = self.searchItem(name, frame)
        # vracim hodnotu pouze pokud je inicializovana
        if item and item[ 'inicialized' ]:
            return item[ 'type' ]
        else:
            return None

     # funkce vraci hodnotu promenne pokud je inicializovana
    def getValueVar(self, name, frame):
        item = self.searchItem(name, frame)
        # vracim hodnotu pouze pokud je inicializovana
        if item and item[ 'inicialized' ]:
            # pokud se jedna o typ bool => vracim 1/0
            #if item[ 'type' ] == 'bool':
             #   return True if item[ 'value' ] == 'true' else False
            #else:
            return item[ 'value' ]
        else:
            return None

    # funkce vraci hodnotu symbolu => kontanta/promenna
    def getVal(self, symb):

        if ( symb[ 'type' ] == 'var' ):
            # u promenne hledame v tabulce
            return self.getValueVar( symb[ 'name' ], symb[ 'frame' ] )
        else:
            # u retezce primo vypiseme
            return symb[ 'text' ]

    # funkce vraci typ symbolu => kontanta/promenna
    def getType(self, symb):
        if ( symb[ 'type' ] == 'var' ):
            # hledame v tabulce jaky ma typ
            return self.getTypeVar( symb[ 'name' ], symb[ 'frame' ] )
        else:
            return symb[ 'type' ]

    # tisknu tabulku podle framu
    def printStructure(self, frame):
        table = self.getTableAccorrdingToFrame(frame)
        print (table)

     # nazev promenne v argumentech metody
     # kontrola, ze promenna je  inicializovana a musi mit ocekavany typ jinak chyba
    def _checkVarIfInitIfType(self, var_name, expected_type, frame):
        if ( self.isInit( var_name, frame ) ):
                if ( self.getTypeVar( var_name, frame ) != expected_type ):
                     print ( "Ocekavam typ %s u promenne %s" % ( expected_type, var_name), file=sys.stderr )
                     exit ( 53) #semanticka kontrola
        else:
            # zjistim, jestli vubecexistuje a podle toho vyhodim hlasku
            if self.searchItem(var_name, frame):
                print ( "Cteni neinicializovane promenne %s" % ( var_name), file=sys.stderr )
                exit ( 56) #semanticka kontrola
            else:
                print ( "Cteni nedefinovane promenne %s" % ( var_name), file=sys.stderr )
                exit ( 54) #semanticka kontrola

    # vraci hodnotu promenne, ktera musi existovat, jinak chyba
    # vraci promennou v pripade uspechu
    def _checkVarIfInit(self, var_name, frame):
        if self.isInit( var_name, frame ):
            return self.searchItem( var_name, frame )
        else:
            # zjistim, jestli vubecexistuje a podle toho vyhodim hlasku
            if self.searchItem(var_name, frame):
                print ( "Cteni neinicializovane promenne %s" % ( var_name), file=sys.stderr )
                exit ( 56) #semanticka kontrola
            else:
                print ( "Cteni nedefinovane promenne %s" % ( var_name), file=sys.stderr )
                exit ( 54) #semanticka kontrola

    # vrati nam poradi navesti, nazev navesti je unikatni
    def _orderOfLabel(self, label_name ):
        for lab in self.labels:
            if lab[ 'text' ] == label_name:
                return lab[ 'order' ]
        # pokud nic nenajdeme
        return 0

    def _orderOfLabelElseExit(self, label_name ):
        for lab in self.labels:
            if lab[ 'text' ] == label_name:
                return lab[ 'order' ]
        # pokud nic nenajdeme
        print ( "Neexistujici navesti %s" % label_name, file=sys.stderr )
        exit ( 52)

    #############
    # INSTRUKCE #
    #############
    # kontrola, ze label existuje, musim to kontrolovat az bude konec prochazeni, ulozim si proto ocekavane labely
    def getJump(self, label):
        orderLabel = self._orderOfLabelElseExit( label[ 'text' ] );
        self.processedInstruction = orderLabel;

    #pokud o redefinici navesti => 52
    def getLabel( self, label ):
        if ( self._orderOfLabel( label[ 'text' ] ) ):
            print ( "Pokud o redefinici navesti %s" % label[ 'text' ], file=sys.stderr )
            exit ( 52)
        self.labels.append( { "text" : label[ 'text' ], "order" : self.processedInstruction } );

    # 1. pokud ctu promennou, musi existovat
    # 2. pokud zapisuji do promenne, muzu menit jeji typ
    # 3. pristupy k ramcum, pristup k nedefinovanemu ramci vede na chybu 55 => resi interpret
    def getMove(self, var, symb):
        # var musi existovat
        searchvar = self.searchItem(  var[ 'name' ], var[ 'frame' ] )
        # nedefinovana
        if ( searchvar == 0):
            print ( "Zapis nedefinovane promenne %s pomoci instrukce MOVE" % ( var[ 'name' ]), file=sys.stderr )
            exit ( 54) #semanticka kontrola

        if ( symb[ 'type' ] == 'var' ):
            variable = self._checkVarIfInit( symb[ 'name' ], symb[ 'frame' ] )

            # zjistim si typ a hodnoty z tabulky promennych

            typ = variable[ 'type' ]
            val = variable[ 'value' ]
        else:
            typ = symb[ 'type' ]
            val = symb[ 'text' ]

        # definovana je, ulozim si informace

        self.initItemElseExit( var[ 'name' ], val, typ, var[ 'frame' ])

    # pokud vytvorim ramec, mohu pouzivat TF temporary
    def getCreateFrame(self):
        self.tmp_frame.table = ([[]])

    # uz nebudu moct pouzivat TF, ale muzu pouzivat LF
    def getPushFrame(self):
        if ( len( self.tmp_frame.table ) ):
            self.local_frame.table.append( self.tmp_frame.table[len( self.tmp_frame.table ) - 1]  )
            # TF bude pro provedeni nedefinovan
            self.tmp_frame.table.pop()

        else:
            print ( "Pristup k nedefinovanym ramci", file=sys.stderr )
            exit ( 55 ) # semanticka kontrola

    # presun LF do TF, pokud nic v LF => 55 chyba
    def getPopFrame(self):
        if ( len( self.local_frame.table ) ):
            #self.tmp_frame.table = [ self.local_frame.table[len( self.local_frame.table ) - 1] ]
            self.tmp_frame.table = [ self.local_frame.table.pop() ]
        else:
            print ( "Pristup k nedefinovanym ramci", file=sys.stderr )
            exit ( 55 ) # semanticka kontrola

    # definuje promennou
    # 1. pozor, kdy muzu definovat LF a TF, kontrola
    def getDefvar(self, arg):
        self.addNewItem( arg[ 'name' ], arg[ 'frame' ] )

    # kontrola na existenci label, musim si pockat na konci
    def getCall(self, label):
        order = self._orderOfLabelElseExit( label[ 'text' ] )
        # ulozim si navratovou adresu
        self.callStack.append( self.processedInstruction );
        self.processedInstruction = order;

    # vyjmu pozici ze zasobniku volani
    # uklid lokalnich ramcu zajistuji jine instrukce
    def getReturn(self):
        if ( len ( self.callStack ) ):
            order = self.callStack.pop();
            self.processedInstruction = order;
        else:
            print ( "Chybejici hodnota v zasobniku volani" , file=sys.stderr )
            exit ( 56) # chybejici hodnota

    # pokud prom => musi byt definiovana a inicializovana
    # staci mi si ukladat typ a hodnotu
    def getPushs(self,symb):
        value = self.getVal( symb )
        typevar = self.getType( symb )
        if ( value is not None ):
             self.dataStack.append( { 'type' : typevar, 'value' :  value } );
        else:
            print ( "Promenna %s, kterou chceme vlozit na zasobnik, neni inicializovana" % ( symb[ 'text' ] ), file=sys.stderr )
            exit ( 56) # chybejici hodnota

    # je zasobnik prazdny ? -> 56
    def getPops(self, var):
        if ( len( self.dataStack ) == 0 ):
            print ( "Datovy zasobnik je prazdny", file=sys.stderr )
            exit ( 56)

        value = self.dataStack.pop();
        # zmenim typ a jmeno o promenne var na typ a hodnotu z value
        # do var dam value
        self.initItemElseExit( var[ 'name' ], value[ 'value' ], value[ 'type' ], var[ 'frame' ] )

     # funkce na konvertovani spravneho typu
    def _getConvertVal(self, symb):
        # musim porovnavat spravne typy
        val = self.getVal(symb)
        typ = self.getType(symb)
        return self._getConvertConst( val, typ )

     # funkce na konvertovani spravneho typu
    def _getConvertConst(self, val, typ):
        # musim porovnavat spravne typy
        if (typ == 'int'):
            return int(val)
        if (typ == 'string'):
            return str(val)
        if typ == 'bool':
            if ( val == 'true' or val == True ):
               return( True )
            else:
               return ( False )

    # 1.source musi byt typu expected_type
    def _controlType(self, source, expected_type):
        # pokud se jedna o promennou, musim zjistit, jestli existuje a je inicializovana a pokud ano zkontrolovat jeji typ
        if ( source[ 'type' ] == 'var' ):
            self._checkVarIfInitIfType( source[ 'name' ], expected_type, source[ 'frame' ] )

        elif ( source[ 'type' ] != expected_type ):
            print ( "Ocekavam typ %s" % expected_type, file=sys.stderr )
            exit ( 53) #semanticka kontrola

    # 1.source1 a source2 musi byt typu expected_type
    def _controlTypeTwoValues(self, source1, source2, expected_type):
        # pokud se jedna o promennou, musim zjistit, jestli existuje a je inicializovana a pokud ano zkontrolovat jeji typ
        self._controlType( source1, expected_type )
        self._controlType( source2, expected_type )

    # dostaneme vysledek operace
    def _operation( self, source1, source2, operation, typ ):

        val1 = self._getConvertVal( source1 )
        val2 = self._getConvertVal( source2 )

        if ( operation == 'plus' ):
            return int(val1) + int(val2)
        elif( operation == 'minus'  ):
            return int(val1) - int(val2)
        elif( operation == 'mul'  ):
            return int(val1) * int(val2)
        elif( operation == 'idiv'  ):
            #konstrola nuly
            if int(val2) != 0:
                return int ( int(val1) / int(val2) )
            else:
                print ( "POZOR, snazite se delit nulou" , file=sys.stderr )
                exit ( 57) # deleni nulou

        elif( operation == 'lt' ):
            return ( val1 < val2 )
        elif( operation == 'gt' ):
            return ( val1 > val2 )
        elif( operation == 'eq' ):
            return ( val1 == val2)

        elif( operation == 'and' ):
            return (val1 and val2)
        elif( operation == 'or' ):
            return (val1 or val2)
        elif( operation == 'not' ):
            return (not val1 )

    def _getArithmetic( self, desc, source1, source2, expected_type, expected_result, operation  ):
        self._controlTypeTwoValues(source1, source2, expected_type )
        vysl = self._operation( source1, source2, operation, expected_type  )
        self.initItemElseExit( desc[ 'name' ], vysl, expected_result, desc[ 'frame' ] )

    # 2. vysledek do desc a kdyztak to prepisu
    def getAdd(self, desc, source1, source2):
       self._getArithmetic( desc, source1, source2, 'int', 'int', 'plus' )

    def getSub(self, desc, source1, source2):
        self._getArithmetic( desc, source1, source2, 'int', 'int','minus' )

    def getMul(self, desc, source1, source2):
        self._getArithmetic( desc, source1, source2, 'int', 'int','mul' )

    # pozor na deleni nulou => 57
    def getIdiv(self, desc, source1, source2):
        self._getArithmetic( desc, source1, source2, 'int', 'int','idiv' )

    # vraci typ a kontroluje zda jsou typy stejne
    def _sameType(self, source1, source2):
        if ( source1[ 'type' ] == 'var' ):
            type1 = self.getTypeVar( source1[ 'name' ], source1[ 'frame' ] )
        else:
            type1 = source1[ 'type' ]

        if ( source2[ 'type' ] == 'var' ):
            type2 = self.getTypeVar( source2[ 'name' ], source2[ 'frame' ] )
        else:
            type2 = source2[ 'type' ]

        #print("Source1: " + type1 + "Source2: "+ type2)
        #print(source1)
        #print(source2)
        if ( type1 == type2  ):
            return type1
        else:
            print ( "U instrukci pracujeme s odlisnymi typy, typ1 %s != typ2 %s" % ( type1, type2 ), file=sys.stderr )
            exit ( 53 ) # jine typy

    # 1. ukladam stejny typ
    # do bool prom var zapise false pri neplatnosti nebo true v pripade platnosti relace
    # false < true
    # muzeme pouzit AND,OR< NOT
    def getLT(self, desc, source1, source2):
        self._getArithmetic( desc, source1, source2, self.getType(source1 ), 'bool', 'lt' )

    def getGT(self, desc, source1, source2):
        #print(desc)
        #print(source1)
        #print(source2)
        self._getArithmetic( desc, source1, source2, self.getType(source1), 'bool', 'gt' )

    def getEQ(self, desc, source1, source2):
        self._getArithmetic( desc, source1, source2, self.getType(source1), 'bool', 'eq' )

    # kontrola zda se jedna o bool
    def getAnd(self, desc, source1, source2):
        self._getArithmetic( desc, source1, source2, 'bool','bool', 'and' )

    def getOr(self, desc, source1, source2):
        self._getArithmetic( desc, source1, source2, 'bool', 'bool','or' )

    def getNot(self, desc, source1 ):
        self._getArithmetic( desc, source1, source1, 'bool', 'bool','not' )

    # var - kdyztak prepisu
    # symb - typ int, musi byt validni ordinalni hodnota znaku v unicode (viz chr) => 58
    def getInt2char(self, var, symb):
        self._controlType( symb, 'int' )
        val = int ( self.getVal( symb ) );
        if ( val is not None ):
            try:
                ordinal_val = chr( val )
            except ValueError:
                print ( "Pokus o prevedeni nevalidni ordinalni hodnoty %s na unicode znak" % ( val ), file=sys.stderr )
                exit ( 58 )

            # povedlo se, prepisu hodnotu a typ promenne
            # musim ji najit napred v tabulce
            self.initItemElseExit( var[ 'name' ], ordinal_val, 'string', var[ 'frame' ] )

        else:
            print ( "Prace s neinicializovanou promennou %s" % ( symb[ 'name' ]), file=sys.stderr )
            exit ( 56 )

    # symb2 - pozice, index od 0, musi byt int
    # symb1 - typ string
    # ve var je string
    # indexace mimo => 58 viz ord, pozice nesmi byt zaporna, nesmi byt vetsi nez pocet znaku v symb1
    def getStri2int(self, var, symb1, symb2):
        self._controlType( symb1, 'string' )
        self._controlType( symb2, 'int' )

        val1 = str ( self.getVal( symb1 ) )   #string
        val2 = int( self.getVal( symb2 ) ) # int

        if ( len(val1) > val2 and val2 >= 0 ):
            try:
                ordinal_val = ord( val1[ val2 ] )
            except TypeError:
                print ( "Pokus o prevedeni nevalidni unicode hodnoty %s na Int" % ( val1[ val2 ] ), file=sys.stderr )
                exit ( 58 )
        else:
            print ( "Indexace mimo pole retezec %s, index %s" % ( val1, val2, ), file=sys.stderr )
            exit ( 58)
        # povedlo se, prepisu hodnotu a typ promenne
        # musim ji najit napred v tabulce
        # priradim ji nove hodnoty a jdu dal
        self.initItemElseExit( var[ 'name' ], ordinal_val, 'int', var[ 'frame' ] )

    # var musi existovat, nemusi byt inicializovana
    # cte typ, funkci input
    # provede se konverze na specifikovany typ, retezec true se prevadi na bool@true jinak bool@false
    # v pripade chybneho vstupu do var ulozena implicitni hodnota (0,prazdny retezec nebo false)
    def getRead(self, var, type_input):
        input_val = input()

        # musime osetrit chybny vstup
        if ( type_input[ 'text' ] == 'int' ):
            # matchuje cislo
            if ( re.match( input_val, '^((\+|-)?\d+|)$'  ) == 0 ):
                input_val = 0
        if ( type_input[ 'text' ] == 'string' ):
            # retezec
            if ( re.match(  input_val, '^(([^\\\\\s#]|(\\\\[0-9]{3}))*)$' ) == 0 ):
                input_val = ""

        # bool se prevede vzdy dobre
        # priradim ji nove hodnoty a jdu dal
        self.initItemElseExit( var['name'], input_val, type_input[ 'text' ], var[ 'frame' ] )

    # var musi existovat, musi byt inicializovana
    def getWrite(self, symb):
        if ( symb[ 'type' ] == 'var' ):
            self._checkVarIfInit( symb[ 'name' ], symb[ 'frame' ] )
        #print(symb)
        val = self.getVal(symb)
        typ = self.getType(symb)
        # pozor na typ bool, True se vypise jako true a False jako false
        if typ == 'bool':
               if ( val == True ):
                    val = 'true'
               elif ( val == False ):
                    val = 'false'

        print( val )

    # symb1, symb2 jsou retezce
    # ve var bude string
    def getConcat(self, desc, source1, source2):
        self._controlTypeTwoValues( source1, source2, 'string' )
        val1 = self.getVal(source1)
        val2 = self.getVal(source2)
        ret_val = val1 + val2
        variable = self.searchItem( desc[ 'name' ], desc[ 'frame' ] )
        # priradim ji nove hodnoty a jdu dal
        self.initItemElseExit( desc['name'], ret_val, 'string', desc[ 'frame' ] )

    # ve var bude int
    # symb je string
    def getStrlen(self, var, symb):
        #self._controlType( var, 'int' )
        self._controlType( symb, 'string' )
        val = self.getVal( symb )
        length = len( val )
        #print(var['name'])
        self.initItemElseExit( var[ 'name' ], length, 'int', var[ 'frame' ] )

    # symb2 - int (pozice)
    # sym1 - string
    # ve var bude string
    # indexace mimo => 58 viz ord, pozice nesmi byt zaporna, nesmi byt vetsi nez pocet znaku v symb1
    def getGetchar(self, desc, symb1, symb2):
        self._controlType( symb1, 'string' )
        self._controlType( symb2, 'int' )

        val1 = self._getConvertVal( symb1 )
        val2 = self._getConvertVal( symb2 )

        if ( len( val1 ) > val2 and val2 >= 0):
            ordinal_val = val1[ val2 ]
        else:
            print ( "Indexace mimo pole retezec %s, index %s" % ( val1, val2 ), file=sys.stderr )
            exit ( 58)

        # povedlo se, prepisu hodnotu a typ promenne
        # musim ji najit napred v tabulce
        self.initItemElseExit( desc[ 'name' ], ordinal_val, 'string', desc[ 'frame' ] )

    # symb2 - string, beru prvni znak, pokud symb2 obsahuje vice znaku
    # symb1 - int, pozice, index od nuly
    # ve var musi byt na zacatku string => modifukuju pozici symb1 znakem symb2
    # indexace mimo => 58 viz ord, pozice nesmi byt zaporna, nesmi byt vetsi nez pocet znaku v symb1
    def getSetchar(self, desc, symb1, symb2):
        self._controlType( symb1, 'int' )
        self._controlType( symb2, 'string' )
        self._controlType( desc, 'string' )

        val1 = self._getConvertVal( symb1 )
        val2 = self._getConvertVal( symb2 )
        var = self.getVal( desc )

        # bereme prvni znak
        #print("val2: " + val2)
        if ( val2 ):
            val2 = val2[0]
        else:
            print ( "Neexistuje prvni znak na pozici 2" ,file=sys.stderr )
            exit ( 58)

        if ( len( var ) > val1 and val1 >= 0):
            #var[ val1 ] = val2;
            var = var[:val1] + val2 + var[val1+1:]
        else:
            print ( "Indexace mimo pole retezec %s, index %s, hodnota %s" % ( var, val1, val2 ), file=sys.stderr )
            exit ( 58)

        # povedlo se, prepisu hodnotu a typ promenne
        # musim ji najit napred v tabulce
        self.initItemElseExit( desc[ 'name' ], var, 'string', desc[ 'frame' ] )

    # zde pouze kontrola, aby symb v pripade var byla definovana, ale nemusi byt inicializovana
    def getTypeI(self, var, symb):
        #print(symb)
        if ( symb[ 'type' ] == 'var' ):
            if ( self.searchItem( symb[ 'name' ], symb[ 'frame' ] ) == 0):
                print ( "Prace s nedefinovanou promennou %s" % ( symb[ 'name' ]), file=sys.stderr )
                exit ( 54) #54 pokus o cteni neexistujici promenne

        typ = self.getType(symb)
        if ( typ is None ):
            # neni inicializovana, jedna se o prazdny string
            typ = ''

        # zapisi retezec znacici tento typ symbolu
        self.initItemElseExit( var[ 'name' ], typ, 'string', var[ 'frame' ] )

    # pridam label do expected label, pokud neni v labels
    # symb1 a symb2 musi byt stejneho typu
    def getJumpIfEq(self, label, symb1, symb2):
        #if ( label[ 'text' ] not in self.labels ):
            #self.expectedLabel.append( label[ 'text' ] )
        self._sameType(symb1, symb2)

        val1 = self._getConvertVal(symb1)
        val2 = self._getConvertVal(symb2)

        if ( val1 == val2 ):
            self.getJump( label )

    def getJumpIfNeq(self, label, symb1, symb2):
        #if ( label[ 'text' ] not in self.labels ):
            #self.expectedLabel.append( label[ 'text' ] )
        self._sameType(symb1, symb2)
        val1 = self._getConvertVal(symb1)
        val2 = self._getConvertVal(symb2)
        if ( val1 != val2 ):
            self.getJump( label )

    # pokud promenna -musi mit init
    def getDprint(self, symb):
        if ( symb[ 'type' ] == 'var' ):
            self._checkVarIfInit( symb[ 'name' ], symb[ 'frame' ] )
        val = self.getVal(symb)
        print ( "%s" % ( val), file=sys.stderr )

    def getBreak(self):
        print ( "Number of instruction: %s" % self.processedInstruction )
        print ( "GF frame:" , file=sys.stderr )
        print ( "%s" % self.glob_frame.table , file=sys.stderr )
        print ( "LF frame:" , file=sys.stderr )
        print ( "%s" % self.local_frame.table , file=sys.stderr )
        print ( "TF frame:" , file=sys.stderr )
        print ( "%s" % self.tmp_frame.table , file=sys.stderr )

    def findAllLabels(self):
        instructionInfo = self.structure[ self.processedInstruction ]
        while ( instructionInfo[ 'instruction_name' ] != 'END' ):
            # zavolam danou funkci k dane instrukci s parametry instrukce
            if ( instructionInfo[ 'instruction_name' ] == 'LABEL' ):
                getattr(self, self.callInstruction[ instructionInfo[ 'instruction_name' ] ] )( *instructionInfo[ 'arg' ] )

            self.processedInstruction = self.processedInstruction + 1
            if ( self.processedInstruction in self.structure):
                instructionInfo = self.structure[ self.processedInstruction ]

        # musime zase na zacatek
        self.processedInstruction = 1;

    def proceed(self):
        # jedu az do az do konce
        instructionInfo = self.structure[ self.processedInstruction ]
        while ( instructionInfo[ 'instruction_name' ] != 'END' ):
            # zavolam danou funkci k dane instrukci s parametry instrukce
            if ( instructionInfo[ 'instruction_name' ] != 'LABEL' ):
                #print(instructionInfo[ 'instruction_name' ])
                #print( instructionInfo[ 'arg' ] )
                getattr(self, self.callInstruction[ instructionInfo[ 'instruction_name' ] ] )( *instructionInfo[ 'arg' ] )

            self.processedInstruction = self.processedInstruction +1

            if ( self.processedInstruction in self.structure):
                instructionInfo = self.structure[ self.processedInstruction ]

        # todo pridat linebreaky
        #print()

class SyntaxParse:

    def __init__(self,xml):
        self.xml = xml

        self.instruction_map = {
            "ADD": "A1", "SUB" : "A1", "MUL" : "A1", "IDIV" : "A1", "LT" : "A1", "GT" : "A1", "EQ" : "A1", "AND" : "A1",
            "OR" : "A1", "STRI2INT" : "A1", "GETCHAR" : "A1", "SETCHAR" : "A1","CONCAT" : "A1",

            "JUMPIFEQ" : "A2", "JUMPIFNEQ" : "A2",

            "INT2CHAR" : "B1", "STRLEN" : "B1", "TYPE" : "B1", "MOVE" : "B1","NOT" : "B1",

            "READ" : "B2",

            "DEFVAR" : "C1", "POPS" : "C1",

            "PUSHS" : "C2", "WRITE" : "C2", "DPRINT" : "C2",

            "CALL" : "C3", "LABEL" : "C3", "JUMP" : "C3",

            "BREAK" : "D", "CREATEFRAME" : "D", "PUSHFRAME" : "D", "POPFRAME" : "D", "RETURN" : "D",
        }
        type_xml = "type"
        type_reg = "(string|int|bool)"
        label_reg = "\D(\w|%|\*|&|\\$|-|)+"
        variable_reg = "^(GF|LF|TF)@("+label_reg+")$"
        int_reg = '^((\+|-)?\d+|)$'
        bool_reg = '^(false|true)$'
        string_reg = '^(([^\\\\\s#]|(\\\\[0-9]{3}))*)$'

        constant_reg = '^(([^\\\\\s#]|(\\\\[0-9]{3}))*)|(((\+|-)?\d+|))|(false|true)$'
        symbol_reg = "("+ constant_reg +"|"+ variable_reg +")"

        # a) 1. ADD, SUB, MUL, IDIV, LT, GT, EQ, AND, OR, STRI2INT, GETCHAR, SETCHAR, CONCAT (3 operandy) <var> <symm1> <symb2> ^
        #    2. JUMPIFEQ, JUMPIFNEQ, <label> <symm1> <symb2>
        #
        # b) 1. INT2CHAR, STRLEN, TYPE, MOVE, NOT <var> <symb>
        #    2. READ, <var> <type>  (2 operandy)
        #
        # c) 1. DEFVAR, POPS (1 operand) <var>
        #    2. PUSHS, WRITE, DPRINT <symb>
        #    3. CALL, LABEL, JUMP <label>
        #
        # d) BREAK, CREATEFRAME, PUSHFRAME, POPFRAME, RETURN (0 operandu)
        self.dictionaryInstruction = {
            "A1": { 'number' : 3, 'arg0' : variable_reg, 'arg1' : symbol_reg, 'arg2' : symbol_reg },
            "A2": { 'number' : 3, 'arg0' : label_reg, 'arg1' : symbol_reg, 'arg2' : symbol_reg },
            "B1": { 'number' : 2, 'arg0' : variable_reg, 'arg1' : symbol_reg },
            "B2": { 'number' : 2, 'arg0' : variable_reg, 'arg1' : type_reg },
            "C1": { 'number' : 1, 'arg0' : variable_reg },
            "C2": { 'number' : 1, 'arg0' : symbol_reg },
            "C3": { 'number' : 1, 'arg0' : label_reg },
            "D": { 'number' : 0 }  ,
        }
        self.dictionaryType = {
            "int" : int_reg,
            "string" : string_reg,
            "bool" : bool_reg,
            "label" : '^'+label_reg+'$',
            "var" : variable_reg,
            "type" : type_reg
        }

    def _checkFormatOfOneInstruction( self, instruction_name, instruction_arg ):
        if ( instruction_name in self.instruction_map ):
             type_instruction = self.instruction_map[ instruction_name ]
        else:
           print ( "Spatny nazev instrukce  %s" % instruction_name, file=sys.stderr )
           exit ( 32)

        structure = self.dictionaryInstruction[ type_instruction ]
        if ( len( instruction_arg ) == structure[ 'number' ] ):
            for arg in range( structure[ 'number' ]  ):
                index = "arg" + str(arg);
                if ( instruction_arg[ arg ][ 'text' ] is None ):
                    # aby regex nehodil chybu
                    instruction_arg[ arg ][ 'text' ] = ''
                if ( re.match(  structure[ index ], instruction_arg[ arg ][ 'text' ] ) ):
                    # kontrola regexem kazdy operand instrukce
                    # proslo, tak jeste zkontroluj typ
                    if ( instruction_arg[ arg ][ 'type' ] in self.dictionaryType ):

                        if ( re.match(  self.dictionaryType[ instruction_arg[ arg ][ 'type' ]  ], instruction_arg[ arg ][ 'text' ] ) is None):
                            print ( "Spatny typ operandu u instrukce %s, operand %s" % ( instruction_name, instruction_arg[ arg ][ 'text' ]  ), file=sys.stderr )
                            exit ( 32)
                        # tady by se hodilo prevedeni stringu na normalni string :)
                        if ( instruction_arg[ arg ][ 'type' ] == 'string' ):
                            # prevedeme
                            def replace(m): return chr(int(m.group(1)))
                            instruction_arg[ arg ][ 'text' ] = re.sub( '\\\\([0-9]{3})', replace, instruction_arg[ arg ][ 'text' ]  )

                    else:
                        print ( "Neznamy typ u instrukce %s, typ %s" % ( instruction_name, instruction_arg[ arg ][ 'type' ]  ), file=sys.stderr )
                        exit ( 32)

                else:
                    print ( "Spatny format operandu u instrukce %s, operand %s" % ( instruction_name, instruction_arg[ arg ][ 'text' ]  ), file=sys.stderr )
                    #print >> sys.stderr, "Spatny format operandu u instrukce "
                    exit ( 32)
        else:
            print ( "Spatny pocet operandu u instrukce %s" % instruction_name, file=sys.stderr )
            exit ( 32)

        return True

    # funkce zkontroluje syntax a v pripade uspechu vraci strukturu xml v poli slovniku, ktera vypada asi takto:
    # {1: {'arg': [{'type': 'label', 'text': 'MAIN'}], 'instruction_name': 'JUMP'},
    # 2: {'arg': [{'type': 'label', 'text': 'FOO'}], 'instruction_name': 'LABEL'},
    # 3: {'arg': [], 'instruction_name': 'END'} }
    def checkParseSyntax(self):
        try:
            tree = ET.parse( self.xml)
            root = tree.getroot()
        except:
            print ( "Chybna struktura xml" , file=sys.stderr )
            exit ( 31)

        sums = 0
        instruction_arg = []
        instruction = {}
        for child in root:
            #print(child.tag, child.attrib)
            if ( 'opcode' in child.attrib and 'order' in child.attrib ):
                instruction_name = child.attrib[ 'opcode' ]
                instruction_order = int (child.attrib[ 'order' ])
            else:
                print ( "Chybi argument opcode nebo order u instrukce %s" % instruction_name, file=sys.stderr )
                exit ( 31)
            for child2 in child:
                # ulozim struktutu a zkontroluju syntax
                sums = sums +1
                if ('type' in child2.attrib ):
                    # pokud se jedna o promennou, chceme si navic ukladat zvlast promennou a zvlast ramec
                    if ( child2.attrib[ 'type' ] == 'var' ):
                         var = re.match(  '^(GF|LF|TF)@(.*)$', child2.text)
                         if (var is not None):
                             instruction_arg.append( { 'type' : child2.attrib[ 'type' ], 'text' : child2.text, 'name' : var.group(2), 'frame' : var.group(1) } )
                    else:
                        # nejedna se o promennnou, ale kontantu
                        instruction_arg.append( { 'type' : child2.attrib[ 'type' ], 'text' : child2.text } )
                else:
                     print ( "Chybi argument type u instrukce %s" % instruction_name, file=sys.stderr )
                     exit ( 31)
            # ulozime do struktury, kterou budeme vracet
            instruction[ instruction_order ] = { 'instruction_name' : instruction_name, 'arg' : instruction_arg }
            if ( self._checkFormatOfOneInstruction( instruction_name, instruction_arg ) == False ):
                 print ( "Syntakticka chyba u instrukce %s" % instruction_name, file=sys.stderr )
                 exit ( 32)
            instruction_arg = []

        # konec zpracovani oznacime retezcem END, zarazka
        instruction[ instruction_order+1 ] = { 'instruction_name' : 'END', 'arg' : [] }
        return instruction

class Main:
    def __init__(self):
        ########################
        # ZPRACOVANI ARGUMENTU #
        ########################

        if (len( sys.argv ) != 2 ):
            # ocekavame vzdy jeden argument
            print >> sys.stderr, "Spatny pocet argumentu, ocekavam jeden"
            exit( 10 )

        if (sys.argv[ 1 ] == '--help') :
            print( "POUZITI:\npython3 interpret.py --source=zdroj_xml\n" )
            exit(0)
        #print (sys.argv[1])
        split = re.match(  r"(--source=)(.+)", sys.argv[1] )
        #print( "source: %s" % sys.argv[1] );
        if (split is None):
            print ( "Pouzijte argument --help pro vypsani napovedy" , file=sys.stderr )
            #print >> sys.stderr, "Pouzijte argument --help pro vypsani napovedy"
            exit( 10 )

        syntax = SyntaxParse( split.group(2) )
        structTree = syntax.checkParseSyntax()
        #print (structTree)
        # mame strukturu, musime provest semantickou kontrolu
        interpret = Interpret( structTree )
        interpret.findAllLabels();
        interpret.proceed()

main = Main()

exit(0)


def combinations(line, index):
    if index >= len(line):
        print(''.join(line))
        return
    combinations(line, index + 1)
    for i in range(index + 1, len(line)):
        line[index], line[i] = line[i], line[index]
        combinations(line, index + 1)
        line[index], line[i] = line[i], line[index]

text = list(input())
combinations(text, 0)

# def print_comb(text1, idx):
#     if idx >= len(text1):
#         print(''.join(text1))
#         return
#     print_comb(text1, idx + 1)
#     for i in range(idx + 1, len(text1)):
#         text1[idx], text1[i] = text1[i], text1[idx]
#         print_comb(text1, idx + 1)
#         text1[idx], text1[i] = text1[i], text1[idx]
#
#
# text1 = list(input())
# print_comb(text1, 0)

# def fibo(n):
#     if n == 0:d
#         return 0
#     if n == 1:
#         return 1
#
#     return fibo(n - 1) + fibo(n - 2)
#
#
# print(fibo(7))

# def finder(n):          # Factoriel finding recursion
#     if n == 0:
#         return 1
#     return n * finder(n - 1)


import torch
from torch import nn, optim
from torch.autograd import Variable
import torch.nn.functional as F
from assessor.base_model import BaseModel
import os

class FFNN(nn.Module):
    def __init__(self, input_size, output_size, hidden_size):
        super(FFNN, self).__init__()
        self.linear = nn.Linear(input_size, hidden_size)
        self.relu = F.relu
        self.linear2 = nn.Linear(hidden_size, output_size)

    def forward(self, x):
        y = self.linear(x)
        y = self.relu(y)
        y = self.linear2(y)
        return y

class NNModel(BaseModel):
    def __init__(self, config):
        input_size = config.get('input_size', 1)
        output_size = config.get('output_size', 1)
        lr = config.get('lr', 0.001)
        hidden_size = config.get('hidden_size', 100)

        self.loss = nn.SmoothL1Loss()
        self.model = FFNN(input_size, output_size, hidden_size)
        self.optimizer = optim.Adam(self.model.parameters(), lr=lr)
        self.epochs = config.get('epochs', 100)

    def _torch_var(self, value):
        return Variable(torch.Tensor(value))

    def train(self, x_inputs, y_labels, x_val=None, y_val=None):
        for epoch in range(self.epochs):
            y_pred = self.model(self._torch_var(x_inputs))
            loss = self.loss(y_pred, self._torch_var(y_labels))

            val_loss = 0
            if x_val and y_val:
                y_pred_val = self.model(self._torch_var(x_val))
                val_loss = self.loss(y_pred_val, self._torch_var(y_val))

            print(f'Epoch {epoch}, Train_Loss: {loss}, Val_Loss: {val_loss}')

            self.optimizer.zero_grad()
            loss.backward()
            self.optimizer.step()

    def eval(self, x):
        y_pred = self.model(self._torch_var(x))
        formatted_y = y_pred.data.numpy()
        return formatted_y

    def save(self, filepath):
        model_path = os.path.join(filepath, 'nn_model.pth')
        torch.save(self.model.state_dict(), model_path)

    def load(self, filepath):
        model_path = os.path.join(filepath, 'nn_model.pth')
        self.model.load_state_dict(torch.load(model_path))


import os
import unittest
import warnings
from io import BytesIO
from Bio._py3k import StringIO
from Bio import BiopythonWarning
from Bio import SeqIO
from Bio import AlignIO
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
from Bio import Alphabet

# List of formats including alignment only file formats we can read AND write.
# We don't care about the order
test_write_read_alignment_formats = sorted(SeqIO._FormatToWriter)
for format in sorted(AlignIO._FormatToWriter):
    if format not in test_write_read_alignment_formats:
        test_write_read_alignment_formats.append(format)
test_write_read_alignment_formats.remove("gb")  # an alias for genbank
test_write_read_alignment_formats.remove("fastq-sanger")  # an alias for fastq

# This is a list of three-tuples.  Each tuple contains a
# list of SeqRecord objects, a description (string), and
# a list of tuples for expected failures (each with a
# list of formats, exception type, exception message).
test_records = [
    ([], "zero records", {}),
    ([SeqRecord(Seq("CHSMAIKLSSEHNIPSGIANAL", Alphabet.generic_protein), id="Alpha"),
      SeqRecord(Seq("HNGFTALEGEIHHLTHGEKVAF", Alphabet.generic_protein), id="Gamma"),
      SeqRecord(Seq("DITHGVG", Alphabet.generic_protein), id="delta")],
     "three peptides of different lengths", []),
    ([SeqRecord(Seq("CHSMAIKLSSEHNIPSGIANAL", Alphabet.generic_protein), id="Alpha"),
      SeqRecord(Seq("VHGMAHPLGAFYNTPHGVANAI", Alphabet.generic_protein), id="Beta"),
      SeqRecord(Seq("HNGFTALEGEIHHLTHGEKVAF", Alphabet.generic_protein), id="Gamma")],
     "three proteins alignment", []),
    ([SeqRecord(Seq("AATAAACCTTGCTGGCCATTGTGATCCATCCA", Alphabet.generic_dna), id="X"),
      SeqRecord(Seq("ACTCAACCTTGCTGGTCATTGTGACCCCAGCA", Alphabet.generic_dna), id="Y"),
      SeqRecord(Seq("TTTCCTCGGAGGCCAATCTGGATCAAGACCAT", Alphabet.generic_dna), id="Z")],
     "three DNA sequence alignment", []),
    ([SeqRecord(Seq("AATAAACCTTGCTGGCCATTGTGATCCATCCA", Alphabet.generic_dna), id="X",
                name="The\nMystery\rSequece:\r\nX"),
      SeqRecord(Seq("ACTCAACCTTGCTGGTCATTGTGACCCCAGCA", Alphabet.generic_dna), id="Y",
                description="an%sevil\rdescription right\nhere" % os.linesep),
      SeqRecord(Seq("TTTCCTCGGAGGCCAATCTGGATCAAGACCAT", Alphabet.generic_dna), id="Z")],
     "3 DNA seq alignment with CR/LF in name/descr",
     [(["genbank"], ValueError, r"Invalid whitespace in 'The\nMystery\rSequece:\r\nX' for LOCUS line"),
      (["mauve"], ValueError, "Sequences have different lengths, or repeated identifier")]),
    ([SeqRecord(Seq("CHSMAIKLSSEHNIPSGIANAL", Alphabet.generic_protein), id="Alpha"),
      SeqRecord(Seq("VHGMAHPLGAFYNTPHGVANAI", Alphabet.generic_protein), id="Beta"),
      SeqRecord(Seq("VHGMAHPLGAFYNTPHGVANAI", Alphabet.generic_protein), id="Beta"),
      SeqRecord(Seq("HNGFTALEGEIHHLTHGEKVAF", Alphabet.generic_protein), id="Gamma")],
     "alignment with repeated record",
     [(["stockholm"], ValueError, "Duplicate record identifier: Beta"),
      (["maf"], ValueError, "Identifiers in each MultipleSeqAlignment must be unique"),
      (["phylip", "phylip-relaxed", "phylip-sequential"], ValueError, "Repeated name 'Beta' (originally 'Beta'), possibly due to truncation")]),
    ]
# Meddle with the annotation too:
assert test_records[4][1] == "3 DNA seq alignment with CR/LF in name/descr"
# Add a list of strings,
test_records[4][0][2].annotations["note"] = [
    "Note%salso" % os.linesep + "\r\nhas\n evil line\rbreaks!", "Wow"]
# Add a simple string
test_records[4][0][2].annotations["comment"] = (
    "More%sof" % os.linesep + "\r\nthese\n evil line\rbreaks!")
# Add a float too:
test_records[4][0][2].annotations["weight"] = 2.5

class WriterTests(unittest.TestCase):
    """Cunning unit test where methods are added at run time."""

    def check(self, records, format):
        """General test function with with a little format specific information.

        This has some general expected exceptions hard coded!
        """
        # TODO - Check the exception messages?
        lengths = len(set(len(r) for r in records))
        if not records and format in ["stockholm", "phylip", "phylip-relaxed",
                                      "phylip-sequential", "nexus", "clustal",
                                      "sff", "mauve"]:
            self.check_write_fails(records, format, ValueError,
                                   "Must have at least one sequence")
        elif lengths > 1 and format in AlignIO._FormatToWriter:
            self.check_write_fails(records, format, ValueError,
                                   "Sequences must all be the same length")
        elif records and format in ["fastq", "fastq-sanger", "fastq-solexa",
                                    "fastq-illumina", "qual", "phd"]:
            self.check_write_fails(records, format, ValueError,
                                   "No suitable quality scores found in "
                                   "letter_annotations of SeqRecord "
                                   "(id=%s)." % records[0].id)
        elif records and format == "sff":
            self.check_write_fails(records, format, ValueError,
                                   "Missing SFF flow information")
        else:
            self.check_simple(records, format)

    def check_simple(self, records, format):
        if format in SeqIO._BinaryFormats:
            handle = BytesIO()
        else:
            handle = StringIO()
        count = SeqIO.write(records, handle, format)
        self.assertEqual(count, len(records))
        # Now read them back...
        handle.seek(0)
        new_records = list(SeqIO.parse(handle, format))
        self.assertEqual(len(new_records), len(records))
        for record, new_record in zip(records, new_records):
            # Using compare_record(record, new_record) is too strict
            if format == "nexus":
                # The nexus parser will dis-ambiguate repeated record ids.
                self.assertTrue(record.id == new_record.id or
                                new_record.id.startswith(record.id + ".copy"))
            else:
                self.assertEqual(record.id, new_record.id)
            self.assertEqual(str(record.seq), str(new_record.seq))
        handle.close()

    def check_write_fails(self, records, format, err_type, err_msg=""):
        if format in SeqIO._BinaryFormats:
            handle = BytesIO()
        else:
            handle = StringIO()
        if err_msg:
            try:
                with warnings.catch_warnings():
                    warnings.simplefilter('ignore', BiopythonWarning)
                    SeqIO.write(records, handle, format)
            except err_type as err:
                self.assertEqual(str(err), err_msg)
        else:
            self.assertRaises(err_type, SeqIO.write, records, handle, format)
        handle.close()

    def test_bad_handle(self):
        handle = os.devnull
        record = SeqRecord(Seq("CHSMAIKLSSEHNIPSGIANAL", Alphabet.generic_protein), id="Alpha")
        records = [record]
        format = "fasta"
        # These deliberately mix up the handle and record order:
        self.assertRaises(TypeError, SeqIO.write, handle, record, format)
        self.assertRaises(TypeError, SeqIO.write, handle, records, format)
        self.assertEqual(1, SeqIO.write(records, handle, format))

for (records, descr, errs) in test_records:
    for format in test_write_read_alignment_formats:
        # Assume no errors expected...
        def funct(records, format, descr):
            f = lambda x: x.check(records, format)
            f.__doc__ = "%s for %s" % (format, descr)
            return f
        setattr(WriterTests,
                "test_%s_%s" % (format, descr.replace(" ", "_")),
                funct(records, format, descr))
        # Replace the method with an error specific one?
        for err_formats, err_type, err_msg in errs:
            if format in err_formats:
                def funct_e(records, format, descr, err_type, err_msg):
                    f = lambda x: x.check_write_fails(
                        records,
                        format,
                        err_type,
                        err_msg)
                    f.__doc__ = "%s for %s" % (format, descr)
                    return f
                setattr(WriterTests,
                        "test_%s_%s" % (format, descr.replace(" ", "_")),
                        funct_e(records, format, descr, err_type, err_msg))
                break
        del funct

if __name__ == "__main__":
    runner = unittest.TextTestRunner(verbosity=2)
    unittest.main(testRunner=runner)


# Getting Started with MicroPython on Raspberry Pi Pico, Chapter 8...
# ADC - Reading Potententiometer
import machine
import utime
import math

pot = machine.ADC(26)
led = machine.PWM(machine.Pin(15))
led.freq(1000)

max_int = 2**16 - 1
to_volts_factor = 3.3 / max_int

last_reading = 0
while True:
    reading = pot.read_u16()
    led.duty_u16(reading)
    voltage = round(reading * to_volts_factor, 1)
    pct =  round(voltage / 3.3 * 100)
    if pct != last_reading:
        print("Potententiometer is {: >3}% ({} volts, {} raw).".format(pct, voltage, reading))
        last_reading = pct
        utime.sleep(0.2)


import socket
import sys
import re

strClient= input("Que veux-tu envoyer au serveur : ")
pattern = r"(meo|waf)"

if type(strClient) != str:
    raise TypeError("La donnée envoyée au serveur doit être de type str")
if re.search(pattern, strClient) == None:
    raise ValueError("La donnée envoyée au serveur doit contenir le mot 'meo' ou 'waf'")

# On définit la destination de la connexion
host = '10.1.1.112'  # IP du serveur
port = 13337               # Port choisir par le serveur

# Création de l'objet socket de type TCP (SOCK_STREAM)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    # Connexion au serveur
    s.connect((host, port))
    print(f"Connecté avec succès au serveur {host} sur le port {port}")
except ConnectionRefusedError:
    print("Le serveur n'est pas joignable")
    exit(1)

# Envoi de data bidon
s.sendall(strClient.encode())

# On reçoit 1024 bytes qui contiennent peut-être une réponse du serveur
data = s.recv(1024)

# On libère le socket TCP
s.close()

# Affichage de la réponse reçue du serveur
print(f"Le serveur a répondu {repr(data.decode())}")

# On quitte le programme
exit(0)


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

def buildJointPlot(embedded_array, n_trial_data, classes, strains, unique_classes, usingFullData=True, fname='full'):
    '''
    Create bivariate plot for TSNE visualization

    embedded_array
        2-dimensional array output from TSNE

    n_trial_data
        Dictionary with key = strain, value = number of flies recorded for this strain

    classes
        List of colors applied to each fly

    strains
        array containg the corresponding strain to each fly

    unique_classes
        List of colors applied to each strain

    usingFullData
        If true, displays the legend for the scatter plot (as there would be multiple strains)
        If only one strain is to be displayed, use False (the name of the used strain will appear in the title)

    fname
        Filename to save the plot
        "full" is left by default for the plot of the whole data
        For singular strain plots, the suggested filename is the name of the strain (e.g. 'MDN.png' for MDN)
    '''

    g = sns.JointGrid(embedded_array[:,0], embedded_array[:,1])
    g.plot_joint(sns.kdeplot)

    #Clear the axes containing the scatter plot
    g.ax_joint.cla()
    g.ax_marg_x.set_axis_off()
    g.ax_marg_y.set_axis_off()

    # set the current axis to be the joint plot's axis
    plt.sca(g.ax_joint)

    sc = plt.scatter(embedded_array[:,0], embedded_array[:,1], c = classes, label = strains)

    if usingFullData:
        lp = lambda i: plt.plot([], color = unique_classes[i], mec="none",
                                label=list(n_trial_data.keys())[i], ls="", marker="o")[0]

        handles = [lp(i) for i in np.arange(len(np.unique(strains)))]
        plt.legend(bbox_to_anchor=(1.01, 1), loc='upper left', handles=handles, ncol=2, prop={'size': 8})
    else:
        plt.title(fname)

    plt.show()
    plt.savefig(fname + '.png')


from flask import Blueprint
from flask import render_template
from flask import request, session, redirect, url_for
from routes import menu

loginController = Blueprint("loginController", __name__)

@loginController.route('/login', methods=['POST', 'GET'])
def login():
    """
    Обрабатывает функциональность входа в систему.

    Параметры:
    - Нет

    Возвращает:
    - Если пользователь уже авторизован, перенаправляет на страницу профиля
        пользователя.
    - Если метод запроса POST, устанавливает переменную сеанса 'userLogged'
        и перенаправляет на страницу профиля пользователя.
    - В противном случае, отображает страницу входа с указанным
        заголовком и меню.

    """
    if 'userLogged' in session:
        return redirect(url_for(
            'profileController.profile',
            username=session['userLogged']
        ))
    elif request.method == 'POST':
        session['userLogged'] = request.form['username']
        return redirect(
            url_for(
                'profileController.profile',
                username=session['userLogged']
            )
        )

    return render_template('login.html', title='Авторизация', menu=menu)


""" implementação de uma lista encadeada circular """

import unittest

class Node:
    def __init__(self, value):
        self.__value = value
        self.next = None

    def get_value(self):
        return self.__value

class CircularlyLinkedList:
    def __init__(self):
        self.__head = None
        self.__tail = None
        self.__size = 0

    def __len__(self):
        return self.__size

    def __iter__(self):
        node = self.__head
        while node:
            yield node
            if node == self.__tail:
                break
            node = node.next

    def __str__(self):
        items = ""
        for item in self.__iter__():
            items += str(item.get_value()) + " "
        return items

    def __repr__(self):
        return self.__str__()

    def insert(self, value):
        new_node = Node(value)
        new_node.next = self.__head
        self.__head = new_node
        if self.__size == 0:
            self.__tail = new_node
        self.__tail.next = self.__head
        self.__size += 1

    def append(self, value):
        new_node = Node(value)
        if self.__size == 0:
            self.__head = new_node
        else:
            self.__tail.next = new_node
        self.__tail = new_node
        self.__tail.next = self.__head
        self.__size += 1

    def remove(self, value):
        prev_node = None
        found = False
        for curr_node in self.__iter__():
            if value == curr_node.get_value():
                found = True
                if prev_node:
                    prev_node.next = curr_node.next
                    if curr_node == self.__tail:
                        self.__tail = prev_node
                else:
                    if self.__size == 1:
                        self.__init__()
                        break
                    else:
                        self.__head = curr_node.next
                        self.__tail.next = self.__head
                        curr_node = None
                self.__size -= 1
            prev_node = curr_node
        if not found:
            raise ValueError(str(value) + " not found in list")

class TestCircularlyLinkedList(unittest.TestCase):
    def setUp(self):
        self.list = CircularlyLinkedList()

    def test_insert(self):
        self.list.insert(1)
        self.list.insert(2)
        self.assertEqual("2 1 ", str(self.list))

    def test_append(self):
        self.list.append(1)
        self.list.append(2)
        self.assertEqual("1 2 ", str(self.list))

    def test_remove(self):
        self.list.insert(1)
        self.list.insert(2)
        self.list.append(3)
        self.list.append(4)
        self.list.remove(3)
        self.assertEqual("2 1 4 ", str(self.list))
        self.list.remove(2)
        self.assertEqual("1 4 ", str(self.list))
        self.list.remove(4)
        self.assertEqual("1 ", str(self.list))
        self.list.remove(1)
        self.assertEqual("", str(self.list))
        self.assertRaises(ValueError, self.list.remove, 9)

    def test_size(self):
        self.list.insert(1)
        self.list.append(2)
        self.list.insert(3)
        self.list.remove(2)
        self.assertEqual(2, len(self.list))

if __name__ == "__main__":
    suite = unittest.TestLoader().loadTestsFromTestCase(TestCircularlyLinkedList)
    unittest.TextTestRunner(verbosity=2).run(suite)


"""
The helper methods for getting and adding stories
Is used in __init__.py for the functionality
"""

__version__ = '0.0.1'
__author__ = 'hharutyunyan'
__copyright__ = 'Copyright 2018, hharutyunyan'
__license__ = 'All Rights Reserved'
__maintainer__ = 'hharutyunyan'
__status__ = "Production"

from app.lib.db import db

def getStories(place_id):
    """Return the stories given the place id."""
    database = db()
    return database.select('stories', 'id, story, author',
                           "place_id LIKE '{}'".format(place_id))

def addStory(data):
    """Add a story for given place id."""
    database = db()
    database.insert('stories', data)
    return '{"status": "ok"}'


import torch
import tqdm
import time
import sys
import json
import torch.optim as optim
from torch.utils.data import TensorDataset, random_split, DataLoader, RandomSampler, SequentialSampler
from transformers import BertTokenizer, BertForSequenceClassification
from train_results import EpochResult, FitResult
import os

MAX_LEN = 66

def create_data_list(input_path):
    with open(input_path, 'r') as file_json:
        data = json.load(file_json)

    all_words = []
    all_labels = []
    for key in data:
        headline = data[key]['headline'].lower()

        all_words.append(headline)
        all_labels.append(data[key]['is_sarcastic'])

    return all_words, all_labels

class BertClassifier:
    def __init__(self, headlines_list, labels, config, checkpoint_file=None):
        self.config = config
        self.headlines_list = headlines_list
        if labels:
            self.labels = torch.tensor(labels).unsqueeze(1)
        self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
        self.model = BertForSequenceClassification.from_pretrained('bert-base-uncased', return_dict=True)
        self.batch_size = self.config.batch_size
        self.checkpoint_file = None
        if checkpoint_file is not None:
            checkpoint_dir = os.path.join('.', 'checkpoints')
            if not os.path.isdir(checkpoint_dir):
                os.mkdir(checkpoint_dir)
            self.checkpoint_file = os.path.join(checkpoint_dir, checkpoint_file)

            if os.path.isfile(self.checkpoint_file):
                saved_state = torch.load(self.checkpoint_filename,map_location=self.device)
                self.model.load_state_dict(saved_state['model_state'])

    def save_checkpoint(self, fit_result):
        saved_state = dict(fit_result=fit_result,
                           model_state=self.model.state_dict())
        torch.save(saved_state, self.checkpoint_file)

    def load_checkpoint(self):
        """
        Load the init checkpoint file
        :return: A tuple of:
                    Best test accuracy for last checkpoint
                    A EpochHeatMap object holds the attention map for all sequences for last checkpoint
                    A FitResult object containing train and test losses per epoch for last checkpoint
        """

        print(f'=== Loading checkpoint {self.checkpoint_file}, ', end='')
        data = torch.load(self.checkpoint_file, map_location=torch.device('cpu'))
        return data

    def get_dataset(self):
        max_len = 0
        input_ids = []
        attention_masks = []
        for sent in self.headlines_list:
            # from here: this code is just to see what max_length should be. not necessary once we know
            input_ids_len = self.tokenizer.encode(sent, add_special_tokens=True)
            max_len = max(max_len, len(input_ids_len))
            if max_len == len(input_ids_len):
                max_input = sent
            # to here
            encoded_dict = self.tokenizer.encode_plus(
                sent, add_special_tokens=True, max_length=MAX_LEN, padding='max_length',
                return_attention_mask=True, return_tensors='pt',
            )
            input_ids.append(encoded_dict['input_ids'])
            attention_masks.append(encoded_dict['attention_mask'])

        input_ids = torch.cat(input_ids, dim=0)
        attention_masks = torch.cat(attention_masks, dim=0)
        labels = torch.tensor(self.labels)

        # Combine the training inputs into a TensorDataset.
        dataset = TensorDataset(input_ids, attention_masks, labels)

        return dataset

    def get_dataloader(self, dataset):

        # Calculate the number of samples to include in each set.
        train_size = int((1-self.config.test_size) * len(dataset))
        test_size = len(dataset) - train_size

        # Divide the dataset by randomly selecting samples.
        train_dataset, test_dataset = random_split(dataset, [train_size, test_size])
        train_dataloader = DataLoader(train_dataset, sampler=RandomSampler(train_dataset), batch_size=self.batch_size)
        test_dataloader = DataLoader(test_dataset, sampler=SequentialSampler(test_dataset), batch_size=self.batch_size)
        return train_dataloader, test_dataloader

    def inference(self, sentence):
        input_ids_len = self.tokenizer.encode(sentence, add_special_tokens=True)

        encoded_dict = self.tokenizer.encode_plus(
            sent, add_special_tokens=True, return_attention_mask=True, return_tensors='pt',
        )
        b_input_ids = encoded_dict['input_ids'].to(device)
        b_input_mask = encoded_dict['attention_mask'].to(device)

        with torch.no_grad():
            output = self.model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask)
            logits = output.logits
            logits = logits.detach().cpu()

            y_pred = torch.argmax(logits, dim=1)

            return y_pred

    def fit(self, train_dataloader: DataLoader, test_dataloader: DataLoader):
        train_loss, train_acc, test_loss, test_acc = [], [], [], []
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        print(device)

        # model = self.model
        self.model.to(device)
        optimizer = optim.Adam(self.model.parameters(), lr=self.config.lr)
        epochs = self.config.num_epochs
        for epoch_i in range(0, epochs):
            print('======== Epoch {:} / {:} ========'.format(epoch_i + 1, epochs))
            res_train = self.train_epoch(train_dataloader, optimizer, device)
            train_loss.append(res_train[0])
            train_acc.append(res_train[1])
            res_test = self.test_epoch(test_dataloader, device)
            test_loss.append(res_test[0])
            test_acc.append(res_test[1])
        fit_result = FitResult(epochs, train_loss, train_acc, test_loss, test_acc)
        if self.checkpoint_file is not None:
            self.save_checkpoint(fit_result)
        return fit_result

    def train_epoch(self, train_dataloader, optimizer, device):
        train_loss, train_acc, losses = [], [], []
        total_train_accuracy = 0
        total_train_loss = 0
        tp_tot, fp_tot, tn_tot, fn_tot = 0, 0, 0, 0
        self.model.train()
        pbar_file = sys.stdout
        pbar_name = "train_batch"
        num_batches = len(train_dataloader.batch_sampler)
        with tqdm.tqdm(desc=pbar_name, total=num_batches,
                       file=pbar_file) as pbar:
            for step, batch in enumerate(train_dataloader):
                b_input_ids = batch[0].to(device)
                b_input_mask = batch[1].to(device)
                b_labels = batch[2].to(device)
                self.model.zero_grad()

                # Forward pass
                output = self.model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels)
                # Log the train loss
                loss = output.loss
                logits = output.logits
                total_train_loss += loss.item()

                # Backward pass
                loss.backward()
                torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0)

                # Weight updates
                optimizer.step()

                logits = logits.detach().cpu()
                y = b_labels.to('cpu').squeeze(1)
                y_pred = torch.argmax(logits, dim=1) #.unsqueeze(1)
                tp, fp, tn, fn = calculate_acc(y_pred, y)
                tp_tot += tp
                fp_tot += fp
                tn_tot += tn
                fn_tot += fn
                total_train_accuracy += torch.sum(y_pred == y).float().item()
                pbar.set_description(f'{pbar_name} ({loss.item():.3f})')
                pbar.update()
        avg_train_accuracy = (total_train_accuracy / len(train_dataloader.dataset))*100
        #print("  Training accuracy: {0:.2f}".format(avg_train_accuracy))
        print(f"accuracy={avg_train_accuracy:.3f}, tp: {tp_tot}, fp: {fp_tot}, tn: {tn_tot}, fn: {fn_tot}")
        if tp_tot + fn_tot > 0:
            print(f"Pos acc: {tp_tot / (tp_tot + fn_tot):.3f},  Neg acc: {tn_tot / (tn_tot + fp_tot):.3f}")
        avg_train_loss = total_train_loss / len(train_dataloader)
        # Log the Avg. train loss
        print("  Training loss: {0:.4f}".format(avg_train_loss))
        return EpochResult(avg_train_loss, avg_train_accuracy)

    def test_epoch(self, test_dataloader, device):
        self.model.eval()
        total_eval_accuracy = 0
        total_eval_loss = 0
        tp_tot, fp_tot, tn_tot, fn_tot = 0, 0, 0, 0
        # Evaluate data for one epoch
        pbar_file = sys.stdout
        pbar_name = "test_batch"
        num_batches = len(test_dataloader.batch_sampler)
        with tqdm.tqdm(desc=pbar_name, total=num_batches,
                       file=pbar_file) as pbar:
            for batch in test_dataloader:
                b_input_ids = batch[0].to(device)
                b_input_mask = batch[1].to(device)
                b_labels = batch[2].to(device)
                with torch.no_grad():
                    output = self.model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels)
                    loss = output.loss
                    logits = output.logits
                    total_eval_loss += loss.item()
                    logits = logits.detach().cpu()
                    y = b_labels.to('cpu').squeeze(1)
                    y_pred = torch.argmax(logits, dim=1)
                    tp, fp, tn, fn = calculate_acc(y_pred, y)
                    tp_tot += tp
                    fp_tot += fp
                    tn_tot += tn
                    fn_tot += fn
                total_eval_accuracy += torch.sum(y_pred == y).float().item()
                pbar.set_description(f'{pbar_name} ({loss.item():.3f})')
                pbar.update()

        avg_val_accuracy = (total_eval_accuracy / len(test_dataloader.dataset))*100
        # print("  Validation accuracy: {0:.2f}".format(avg_val_accuracy))
        print(f"accuracy={avg_val_accuracy:.3f}, tp: {tp_tot}, fp: {fp_tot}, tn: {tn_tot}, fn: {fn_tot}")
        if tp_tot + fn_tot > 0:
            print(f"Pos acc: {tp_tot / (tp_tot + fn_tot):.3f},  Neg acc: {tn_tot / (tn_tot + fp_tot):.3f}")
        avg_val_loss = total_eval_loss / len(test_dataloader)
        # Log the Avg. validation accuracy
        print("  Validation Loss: {0:.4f}".format(avg_val_loss))
        return EpochResult(avg_val_loss, avg_val_accuracy)

    def get_bert_classification(self):
        for i in range(0, len(self.head_lines_list), self.batch_size):
            batch = self.head_lines_list[i:i+self.batch_size]
            encoded = self.tokenizer(batch, return_tensors='pt', padding=True)
            encoded = torch.tensor(encoded)
            target = torch.tensor(self.labels[i:i+self.batch_size])
            # inp = batch.cuda()
            # target = target.cuda()
            output = self.model(batch, target)
            loss = output.loss
            print(f"loss: {loss}")
            logits = output.logits
            print(f"logits:{logits}")

def calculate_acc(y_pred, y):
    """
    Calculates the accuracy of predicted y vector
    """
    tp, fp, tn, fn = 0, 0, 0, 0
    for i in range(y_pred.shape[0]):
        if y_pred[i] == 0:
            if y[i] == 0:
                tn += 1
            else: fn += 1
        elif y[i] == 0:
            fp += 1
        else:
            tp += 1
    return tp, fp, tn, fn


# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# from __future__ import unicode_literals

import MeCab

from typing import Any, List, Text

from rasa_nlu.components import Component
from rasa_nlu.config import RasaNLUModelConfig
from rasa_nlu.tokenizers import Tokenizer, Token
from rasa_nlu.training_data import Message
from rasa_nlu.training_data import TrainingData

class WordDividor():
    INDEX_CATEGORY = 0
    INDEX_ROOT_FORM = 6
    TARGET_CATEGORIES = ["名詞", "動詞",  "形容詞", "副詞", "連体詞", "感動詞"]

    def __init__(self, dictionary="mecabrc"):
        self.dictionary = dictionary
        self.tagger = MeCab.Tagger(self.dictionary)

    def extract_words(self, text):
        self.TARGET_CATEGORIES = ["名詞", "動詞",  "形容詞", "副詞", "連体詞", "感動詞"]
        if not text:
            return []

        words = []
        if type(text) != str:
            text = u''.join((text)).encode('utf-8')
        node = self.tagger.parseToNode(str(text))
        while node:
            features = node.feature.split(',')
            #print features
            if features[self.INDEX_CATEGORY] in self.TARGET_CATEGORIES:
                if features[self.INDEX_ROOT_FORM] == "*":
                    words.append(node.surface)
                else:
                    words.append(features[self.INDEX_ROOT_FORM])

            node = node.next
        for eachword in words:
            print('Word ==> {}'.format(eachword))
        return words

class My_Mecab(Tokenizer, Component):
    name = "My_Mecab"

    provides = ["tokens"]

    # INDEX_CATEGORY = 0
    # INDEX_ROOT_FORM = 6
    # TARGET_CATEGORIES = ["名詞", "動詞",  "形容詞", "副詞", "連体詞", "感動詞"]

    # dictionary = "mecabrc"

    # def __init__(self, dictionary="mecabrc"):

    def train(self, training_data, config, **kwargs):
        # type: (TrainingData, RasaNLUModelConfig, **Any) -> None

        for example in training_data.training_examples:
            example.set("tokens", self.tokenize(example.text))

    def process(self, message, **kwargs):
        # type: (Message, **Any) -> None

        message.set("tokens", self.tokenize(message.text))

    def tokenize(self, text):
        indivi = WordDividor()
        data = indivi.extract_words(text)
        print(data)
        return data

        # self.dictionary = "mecabrc"
        # self.tagger = MeCab.Tagger(self.dictionary)
        #
        # if not text:
        #     return []
        #
        # words = []
        # if type(text) != str:
        #     text = u''.join((text)).encode('utf-8')
        # node = self.tagger.parseToNode(str(text))
        # while node:
        #     features = node.feature.split(',')
        #     #print features
        #     if features[self.INDEX_CATEGORY] in self.TARGET_CATEGORIES:
        #         if features[self.INDEX_ROOT_FORM] == "*":
        #             words.append(node.surface)
        #         else:
        #             words.append(features[self.INDEX_ROOT_FORM])
        #
        #     node = node.next
        # # for eachword in words:
        # #     print('Word ==> {}'.format(eachword))
        # return words

call = WordDividor()
print (call.extract_words("This is Me モバイルドメインリストの最新版が欲しい"))


from enlarge_dataset import create_large_dataset
from pyspark_versions import pyspark_dataframe, pyspark_rdd, pyspark_sql, start_spark
from native_python import native_python_count
import time

def main():

    # Increase locally
    #create_large_dataset(2)
    #dataset = "src/data/new_shakespeare.txt"
    #spark = start_spark()

    # Run Pyspark with RDD
    #start_time= time.time()
    #pyspark_rdd(dataset, spark)
    #print(time.time() - start_time)

    # Run Pyspark with Dataframe
    #start_time= time.time()
    #pyspark_dataframe(dataset, spark)
    #print(time.time() - start_time)

    I = [1, 16, 64,256,1024,2048]
    #logFile = "src/data/shakespeare_processed_"
    logFile = "s3://anthonybucketcs532/532_data_files/shakespeare_processed_"
    #Run Native Python Word Count
    for i in I:
        output = logFile + str(i) + ".txt"
        start_time= time.time()
        native_python_count(output)
        print(f' FileSize: {i} and time: {time.time() - start_time}')

if __name__ == "__main__":
    main()