Example #1
0
    def __init__(self, container, rows=20):

        table = html.TABLE(style=styles["panel"])

        menu_td = html.TD(colspan=2, style=styles["menu"])
        self.menu = menu.Menu(menu_td)
        m1 = self.menu.add_menu("Edition")
        m1.add_item("Search", self.search_dialog)
        table <= html.TR(menu_td)

        self.linenums = html.TEXTAREA(rows=21,
                                      cols=5,
                                      autocomplete="off",
                                      disabled=True,
                                      style=styles["linenums"])
        self.editor = html.TEXTAREA(rows=20,
                                    cols=120,
                                    wrap="off",
                                    autocomplete="off",
                                    spellcheck="false",
                                    style=styles["editor"])
        table <= html.TR(
            html.TD(self.linenums, valign="top") +
            html.TD(self.editor, valign="top"))
        container <= table
        self.editor.bind("keydown", self.keydown)
        self.editor.bind("keyup", self.keyup)
        self.editor.bind("scroll", self.scroll)
        self.set_line_nums()
        self.stack = []
        self.store_undo()
Example #2
0
    def build_grid(self) -> None:
        """Create the grid with the letters."""
        table = html.TABLE(CLass='p300')
        tr = html.TR()
        table <= tr

        characters_train, ncols = CHARACTERS

        for i, char in enumerate(characters_train):
            char_print = CHARACTERS_SRLZ[i]
            row = i // ncols
            col = i % ncols
            if row == 6:
                style = {"font-size": "6vh"}
            else:
                style = {}
            td = html.TD(
                char,
                Class=f'p300-char p300-{char_print}- col-{col} row-{row}',
                style=style)
            td.attrs['char'] = char_print
            tr <= td
            if i != 0 and not (i + 1) % ncols:
                tr = html.TR()
                table <= tr
        self.stimuli_area <= table
Example #3
0
def display_map() -> None:
    table = html.TABLE(style={"border": "1 solid grey"})
    table <= html.TR(html.TH("Text") + html.TH("Base64"))
    table <= (html.TR(html.TD(key) + html.TD(b64_map[key])) for key in b64_map)
    base64_display = document["b64-display"]
    base64_display.clear()
    base64_display <= table
Example #4
0
 def __init__(self):
     super().__init__("Data Table", "#fbd0d0", tabwidth="12%", id="datatable")
     lines = open("cost-of-living-2018.csv").readlines()
     data = [line.strip().split(",") for line in lines[:26]]
     self.attach(html.TABLE(
         html.TR(html.TH(header) for header in data[0]) +
         (html.TR(html.TD(field) for field in row) for row in data[1:])
         ))
Example #5
0
def display_map():
    table = html.TABLE(Class="pure-table")
    table <= html.THEAD(html.TR(html.TH("Text") + html.TH("Base64")))
    table <= (html.TR(html.TD(key) + html.TD(b64_map[key])) for key in b64_map)
    base64_display = document["b64-display"]
    base64_display.clear()
    base64_display <= table
    document["text-src"].value = ""
Example #6
0
def load(sheet_name=None):
    global current_cell_info, menu_file

    if sheet_name is None:
        sheet_name = 'New document'

    panel = document['panel']

    title = html.DIV(style=dict(width='auto'))
    title <= html.H2(sheet_name, id="sheet_name")

    panel <= title

    menu = ui.Menu()

    menu_file = menu.add('File')
    menu_file.add('New', None)
    menu_file.add('Open...', select_sheet)
    menu_file.add('Save as...', save_as)

    panel <= html.SPAN(menu)

    panel <= html.BR()
    cell_editor = html.INPUT(style=dict(width="200px"), Id="current")
    cell_editor.bind('click', enter_editor)
    cell_editor.bind('keydown', editor_keydown)
    cell_editor.bind('keyup', update_from_editor)
    panel <= cell_editor

    t = html.TABLE(Id="sheet_table")
    srow = -1
    rows, cols = 20, 20
    col_widths = [100 for i in range(rows)]

    line = html.TR()
    line <= html.TH()
    for i in range(cols):
        col_name = chr(65 + i)
        line <= html.TH(col_name, style={'min-width': '%spx' % col_widths[i]})
    t <= line

    for i in range(rows * cols):
        row, column = divmod(i, cols)
        if row > srow:
            line = html.TR()
            line <= html.TH(row + 1)
            t <= line
            srow = row
        cell = html.TD('',
                       id='c%s_%s' % (row, column),
                       style=dict(padding='2px'))
        cell.bind('click', select)
        cell.bind('dblclick', entry)
        cell.info = {'entry': ''}
        line <= cell

    panel <= html.DIV(t, style=dict(float='left'))
    mark_selected(t.get(selector='TD')[0])
    def show_results(self):
        """ show table of results"""

        doc['container'].clear()

        doc['container'] <= html.DIV(
            'Browser Version: %s' % window.navigator.userAgent)
        _v = sys.implementation.version
        doc['container'] <= html.DIV('Brython Version: %s.%s.%s' %
                                     (_v.major, _v.minor, _v.micro))
        doc['container'] <= html.DIV(
            'Brython debug mode: %s' % sys.brython_debug_mode)
        doc['container'] <= html.DIV(
            'CPython Version: %s' % self.cpython_version)

        doc['container'] <= html.P(html.I('Results are in milliseconds (ms)'))

        _table = html.TABLE()
        _tr = html.TR()
        _tr <= html.TH('Benchmark')
        _tr <= html.TH('Code')
        _tr <= html.TH('Brython')
        _tr <= html.TH('CPython')
        _tr <= html.TH('Difference')
        _tr <= html.TH('X Faster')
        _table <= _tr
        for _filename in self._timings.keys():
            _tr = html.TR()
            _tr <= html.TD(_filename)
            _tr <= html.TD(
                highlight.highlight(self._timings[_filename]['code']))
            for _platform in ('brython', 'cpython'):
                _tr <= html.TD('%5.0f' % self._timings[_filename][_platform],
                               style={'text-align': 'right'})

            _diff = self._timings[_filename]['cpython'] - self._timings[
                _filename]['brython']
            _x = self._timings[_filename]['cpython'] / self._timings[
                _filename]['brython']

            if _x > 1:
                _color = "green"
            elif _x < 0.5:
                _color = "red"
            else:
                _color = "black"
            _tr <= html.TD('%5.0f' % _diff, style={'text-align': 'right'})
            _tr <= html.TD('%4.2f' % _x,
                           style={
                               'color': _color,
                               'text-align': 'right'
                           })
            _table <= _tr

        doc['container'] <= _table
Example #8
0
def display_map():
    if not hash_map:
        return
    table = html.TABLE(Class="pure-table")
    table <= html.THEAD(html.TR(html.TH("Text") + html.TH("SHA-256")))
    table <= (html.TR(html.TD(key) + html.TD(hash_map[key]))
              for key in hash_map)
    hash_display = document["hash-display"]
    hash_display.clear()
    hash_display <= table
    document["text-src"].value = ""
Example #9
0
def load(sheet_name=None):
    global current_cell_info, menu_file

    panel = document['panel']

    cell_editor = html.DIV("A",
                           style=dict(width="25%",
                                      padding="5px",
                                      marginBottom="20px",
                                      height="1.5em"),
                           Id="current",
                           contentEditable="true",
                           Class="selected")
    cell_editor.bind('click', enter_editor)
    cell_editor.bind('keydown', editor_keydown)
    cell_editor.bind('keyup', update_from_editor)
    panel <= cell_editor

    t = html.TABLE(Id="sheet_table")
    srow = -1
    rows, cols = 20, 20
    col_widths = [100 for i in range(rows)]

    line = html.TR()
    line <= html.TH()
    for i in range(cols):
        col_name = chr(65 + i)
        line <= ColumnHead(col_name,
                           Class="col-head",
                           style={'min-width': '%spx' % col_widths[i]})
    t <= line

    for i in range(rows * cols):
        row, column = divmod(i, cols)
        if row > srow:
            line = html.TR()
            line <= RowHead(row + 1, Class="row-head")
            t <= line
            srow = row
        cell = html.TD(contentEditable="true", style=dict(padding='2px'))
        cell.bind("click", select)
        cell.bind("focus", focus)
        cell.bind("keyup", keyup)
        cell.bind("blur", blur)
        cell.info = {'entry': ''}
        line <= cell

    panel <= html.DIV(t, style=dict(float='left'))

    for cell in document.get(selector="th.row-head"):
        cell.bind("mousedown", select_row)

    t.get(selector='TD')[0].dispatchEvent(window.MouseEvent.new("click"))
Example #10
0
    def __init__(self, container=document.body, parent=None):
        self.container = container
        self.parent = parent
        if parent is None:
            self._table = html.TABLE(Class="menu-table")
            self.panel = html.TR(Class="menu-row")
            self._table <= self.panel
            self.container <= self._table

            self.panel.bind("mouseover", self.hide_submenus)

            document.bind("click", self.reset)

        else:
            self.panel = html.TABLE(Class="menu-table")
            self.container <= self.panel

        @bind(self.panel, "click")
        def click(evt):
            evt.stopPropagation()

        cstyle = window.getComputedStyle(self.container)
        self.fontSize = cstyle.getPropertyValue('font-size')
        self.selecting = False
        container.open_child = None
Example #11
0
 def addSuccess(self, test):
     self.success_count += 1
     TestResult.addSuccess(self, test)
     row = html.TR(self.ident(test), Class="method")
     row.style.backgroundColor = "lightgreen"
     row <= html.TD('ok', colspan=2, Class="report_cell")
     document['report'] <= row
Example #12
0
 def addFailure(self, test, err):
     self.failure_count += 1
     TestResult.addFailure(self, test, err)
     row = html.TR(self.ident(test), Class="method")
     row <= html.TD('fail', Class="report_cell")
     row <= (html.TD(x) for x in self.excInfos(test, err))
     document['report'] <= row
        def on_complete(*args):
            doc['container'] <= html.PRE('Results are in milliseconds (ms)')
            doc['container'] <= html.PRE(
                'Browser Version:%s' % window.navigator.userAgent)
            _v = sys.implementation.version
            doc['container'] <= html.PRE('Brython Version:%s.%s.%s' %
                                         (_v.major, _v.minor, _v.micro))

            _table = html.TABLE()
            _tr = html.TR()
            _tr <= html.TH('Benchmark')
            _tr <= html.TH('Brython')
            _tr <= html.TH('CPython')
            _tr <= html.TH('Difference')
            _tr <= html.TH('X Faster')
            _table <= _tr
            for _filename in self._timings.keys():
                _tr = html.TR()
                _tr <= html.TD(_filename)
                for _platform in ('brython', 'cpython'):
                    _tr <= html.TD(
                        '%5.0f' % self._timings[_filename][_platform],
                        style={'text-align': 'right'})

                _diff = self._timings[_filename]['cpython'] - self._timings[
                    _filename]['brython']
                _x = self._timings[_filename]['cpython'] / self._timings[
                    _filename]['brython']

                if _x > 1:
                    _bg = "green"
                elif _x < 0.5:
                    _bg = "red"
                else:
                    _bg = "yellow"
                _tr <= html.TD('%5.0f' % _diff, style={'text-align': 'right'})
                _tr <= html.TD('%4.2f' % _x,
                               style={
                                   'background': _bg,
                                   'text-align': 'right'
                               })
                _table <= _tr

            doc['container'] <= _table

            doc['container'] <= html.PRE("results uploaded...")
Example #14
0
 def addError(self, test, err):
     self.error_count += 1
     TestResult.addError(self, test, err)
     row = html.TR(self.ident(test), Class="method")
     row.style.backgroundColor = "violet"
     row <= html.TD('fail', Class="report_cell")
     row <= (html.TD(x) for x in self.excInfos(test, err))
     document['report'] <= row
Example #15
0
 def create_root(self):
     root = html.DIV()
     root <= html.DIV(
         html.B(
             f"Replicator - Un Ennemi du peuple ({version})")) + html.BR()
     table = html.TABLE()
     table <= html.TR(
         html.TD("1. Sélectionner le personnage", Id="char_sel_panel_title")
         + html.TD("2. Sélectionner la scène", Id="scene_sel_panel_title"))
     table <= html.TR(
         html.TD(self.create_character_selection_panel(),
                 Id="char_sel_panel_td") + html.
         TD(self.create_scene_selection_panel(), Id="scene_sel_panel_td"))
     root <= table
     root <= html.HR()
     root <= html.DIV("3. Jouer", Id="start_game_panel_title")
     root <= html.DIV(self.create_start_game_panel(), Id="start_game_panel")
     return root
Example #16
0
 def run(self, test):
     "Run the given test case or test suite."
     t = html.TABLE(Id="report")
     t <= html.TR(html.TH(x, Class="header")
         for x in ('Test class', 'Method', 'Line', 'Duration (ms)', 'Result',
         'Error message'))
     document["container"] <= t
     result = _TestResult(self.verbosity)
     test(result)
     self.stopTime = datetime.datetime.now()
Example #17
0
 def _make_item(self, name):
     if self.parent is None:
         # Add item to main menu bar
         td = html.TD(name, Class="menu-item-top")
         self.panel <= td
     else:
         # Add item to submenu
         td = html.TD(name, Class="menu-item-sub")
         self.panel <= html.TR(td)
     td.style.fontSize = self.fontSize
     return td
Example #18
0
def cria_tabela(mapa, id):
    tbl = browser.document[id]
    tbl.innerHTML = ''

    for i in range(len(mapa)):
        linha = html.TR()
        for j in range(len(mapa[i])):
            celula = html.TD()
            celula.class_name = 'parede' if mapa[i][j] == '#' else 'chao'
            linha <= celula
        tbl <= linha
Example #19
0
    def code():
        from browser import document, html

        # Construction de la calculatrice
        calc = html.TABLE()
        calc <= html.TR(
            html.TH(html.DIV("0", id="result"), colspan=3) + html.TD("C"))
        lines = ["789/", "456*", "123-", "0.=+"]

        calc <= (html.TR(html.TD(x) for x in line) for line in lines)

        document <= calc

        result = document["result"]  # direct acces to an element by its id

        def action(event):
            """Handles the "click" event on a button of the calculator."""
            # The element the user clicked on is the attribute "target" of the
            # event object
            element = event.target
            # The text printed on the button is the element's "text" attribute
            value = element.text
            if value not in "=C":
                # update the result zone
                if result.text in ["0", "error"]:
                    result.text = value
                else:
                    result.text = result.text + value
            elif value == "C":
                # reset
                result.text = "0"
            elif value == "=":
                # execute the formula in result zone
                try:
                    result.text = eval(result.text)
                except:
                    result.text = "error"

        # Associate function action() to the event "click" on all buttons
        for button in document.select("td"):
            button.bind("click", action)
Example #20
0
    def __init__(self, files_list, name, is_dir=False, size=None, created=None, **kwargs):
        self.files_list = files_list
        self.name = name
        self.is_dir = is_dir
        self.size = size
        self.created = created.replace('-', '.') if created else created

        self.selected = False
        self.super_selected = False
        self.element = html.TR()
        self.element.bind('click', self.on_click)
        self.element.bind('dblclick', self.on_double_click)
        self.render()
    def doParse(self, event):
        self.reset()
        res = self.parse(self.batchEditor.value)

        lastRow = self.constructionRow

        if self.batchErrorRow:
            self.batchErrorRow.parent.removeChild(self.batchErrorRow)
            self.batchErrorRow = None

        for entry in res:
            row = html.TR()
            row.activity = entry

            if isinstance(entry, airbatch.Activity):
                for txt in [
                        #str(entry.row),
                        #entry.takeoff.strftime("%d.%m.%Y"),
                        str(entry.aircraft),
                        str(entry.pilot),
                        str(entry.copilot) if entry.copilot else "-",
                        entry.takeoff.strftime("%H:%M"),
                        str(entry.ltakeoff),
                        entry.touchdown.strftime("%H:%M"),
                        str(entry.ltouchdown),
                        str(entry.duration)
                ]:

                    col = row.insertCell()
                    col.innerHTML = txt

                row.commit = html.SPAN("✓", Class="commit")
                row.commit.bind("click", self.commitRow)

                row.close = html.SPAN("⨉", Class="close")
                row.close.bind("click", self.removeRow)

                col = row.insertCell()
                col.appendChild(row.commit)
                col.appendChild(row.close)

            else:
                self.batchErrorRow = row
                row.classList.add("error")

                col = row.insertCell()
                col.colSpan = "10"
                col.innerHTML = str(entry)

            self.construction.insertBefore(row, lastRow)
Example #22
0
    def add_link(self, label, href):
        """Add a link to the specified address."""
        if self.parent is None:
            # First level
            item = html.A(label, Class="brython-menu-navbar-link", href=href)
            self.container <= item
        else:
            # Next levels
            item = html.TR(Class="brython-menu-submenu-row")
            self.parent.submenu <= item
            item <= html.TD(
                html.A(label, Class="brython-menu-submenu-link", href=href))

        return item
    def rebuildBatch(self):
        for c in [x for x in self.construction.children][:-1]:
            self.construction.removeChild(c)

        self.reset(False)

        for token in [x for x in self.editorRow.children][:-1]:
            self.extend(token.result)

        lastRow = self.constructionRow

        res = self.commit()
        for entry in res:
            row = html.TR()
            row.activity = entry

            if isinstance(entry, airbatch.Activity):
                for txt in [
                        #entry.takeoff.strftime("%d.%m.%Y"),
                        str(entry.aircraft),
                        str(entry.pilot),
                        str(entry.copilot) if entry.copilot else "-",
                        entry.takeoff.strftime("%H:%M"),
                        str(entry.ltakeoff),
                        entry.touchdown.strftime("%H:%M"),
                        str(entry.ltouchdown),
                        str(entry.duration)
                ]:

                    col = row.insertCell()
                    col.innerHTML = txt

                row.commit = html.SPAN("✓", Class="commit")
                row.commit.bind("click", self.commitRow)

                row.close = html.SPAN("⨉", Class="close")
                row.close.bind("click", self.removeRow)

                col = row.insertCell()
                col.appendChild(row.commit)
                col.appendChild(row.close)

            else:
                row.classList.add("error")

                col = row.insertCell()
                col.colSpan = "10"
                col.innerHTML = str(entry)

            self.construction.insertBefore(row, lastRow)
Example #24
0
 def run(self, test):
     "Run the given test case or test suite."
     b = html.BUTTON("Clique para voltar para o editor", Id="editor")
     b.onclick = self.back_editor
     t = html.TABLE(Id="report")
     t <= html.TR(
         html.TH(x, Class="header", style={"backgroundColor": "lightgrey"})
         for x in ('Test class', 'Method', 'Line', 'T(ms)', 'Result',
                   'Error message'))
     document["container"].html = ""
     document["container"] <= b
     document["container"] <= t
     result = _TestResult(self.verbosity)
     test(result)
     self.stopTime = datetime.datetime.now()
Example #25
0
def make_numbers():
    t = html.TABLE()
    tb = html.TBODY()
    t <= tb
    i = 1
    val = ""
    for row in range(5):
        line = html.TR()
        tb <= line
        for column in range(10):
            b = html.BUTTON(str(i), id="x%s" % i, Class="nobutton")
            cell = html.TD(b)
            b.bind("click", on_number_button_pressed)
            line <= cell
            i += 1
    return t
Example #26
0
    def addSubTest(self, test, subtest, err):
        TestResult.addSubTest(self, test, subtest, err)
        # special case, don't use ident()
        cell2 = (test._testMethodName + html.BR() +
            str(subtest._subDescription()))

        row = html.TR([html.TD(test.__class__.__name__),
            html.TD(cell2),
            html.TD(test.lineno, Class="number"),
            html.TD(round(1000*(time.time() - test.startTime)),
                Class="number")], Class="method")

        row <= html.TD('ok', colspan=2, Class="report_cell")
        # reset startTime
        test.startTime = time.time()
        document['report'] <= row
Example #27
0
def setup_top_panel():
    top_panel = document["about_panel"]

    table = html.TABLE()
    tableBody = html.TBODY()
    row = html.TR()

    # html style properties:
    # http://www.w3schools.com/jsref/dom_obj_style.asp

    global buttonHome
    buttonHome = html.BUTTON('Data Analysis')
    button_style_default(buttonHome)
    buttonHome.bind('click', click_home)
    buttonHome.bind('mouseout', mouse_out_home)
    buttonHome.bind('mouseover', mouse_over_home)

    global buttonAbout
    buttonAbout = html.BUTTON('About')
    button_style_default(buttonAbout)
    buttonAbout.bind('click', click_about)
    buttonAbout.bind('mouseout', mouse_out_about)
    buttonAbout.bind('mouseover', mouse_over_about)

    global buttonGuide
    buttonGuide = html.BUTTON('User Guide')
    button_style_default(buttonGuide)
    buttonGuide.bind('click', click_guide)
    buttonGuide.bind('mouseout', mouse_out_guide)
    buttonGuide.bind('mouseover', mouse_over_guide)

    global buttonContact
    buttonContact = html.BUTTON('Contact')
    button_style_default(buttonContact)
    buttonContact.bind('click', click_contact)
    buttonContact.bind('mouseout', mouse_out_contact)
    buttonContact.bind('mouseover', mouse_over_contact)

    row <= html.IMG(src="genexpresso.png", width="100")
    row <= buttonHome
    row <= buttonGuide
    row <= buttonAbout
    row <= buttonContact

    tableBody <= row
    table <= tableBody
    top_panel <= table
    def draw(self, parent_node):
        self.node = html.DIV(Class="task", Id=self.id, draggable=True)
        self.node.style.backgroundColor = DB["TASKS_COLORS"][self.color]
        parent_node <= self.node

        self.zprogress = html.DIV(Class="task_progress")

        self.progress_text = html.P("%d" % self.progress + "%",
                                    Class="task_progress_text")
        self.zprogress <= self.progress_text

        self.progress_bar = html.DIV(Class="task_progress_bar")
        self.progress_bar.style.width = percent(self.progress)
        self.zprogress <= self.progress_bar

        self.command_delete = html.DIV("X", Class="task_command_delete")

        self.command = html.TABLE(html.TR(
            html.TD(self.zprogress, Class="task_command") +
            html.TD(self.command_delete)),
                                  Class="task_command")
        self.node <= self.command

        self.zdesc = html.P(Class="task_desc")
        self.node <= self.zdesc

        self.node.drop_id = self.id
        self.node.task = self
        self.node.bind('dragstart', self.drag_start)
        self.node.bind('dragover', self.drag_over)
        self.node.bind('drop', self.drag_drop)
        self.node.bind('click', self.color_change)

        self.zprogress.task = self
        self.zprogress.bind('click', self.make_progress)

        self.command_delete.task = self
        self.command_delete.bind('click', self.task_delete)

        self.zdesc.task = self
        self.zdesc.desc = self.desc
        self.zdesc.bind('click', self.task_edit)

        self.set_text()

        for task in self.tasks:
            task.draw(self.node)
Example #29
0
def init():
    global state
    start_pos = (7, 7)
    for i in range(SIZE):
        row = html.TR()
        for j in range(SIZE):
            state[(i, j)] = None  # Initialize game state
            square = html.TD('', id=f"square_{i}_{j}", Class="square")
            if (i, j) in PREMIUMS:
                kind = PREMIUMS[(i, j)]
            elif (i, j) == start_pos:
                kind = "start"
            else:
                kind = "white"
            square.style.backgroundColor = COLORS[kind]
            BOARD[(i, j)] = COLORS[kind]
            row <= square
        document["game-board"] <= row
Example #30
0
    def add_item(self, label, callback=None, menu=False):
        if self.parent is None:
            # First level
            item = html.SPAN(label, Class="brython-menu-navbar-item")
            self.container <= item
            item.bind("click", self.hide_menus)
        else:
            # Next levels
            item = html.TR(Class="brython-menu-submenu-row")
            self.parent.submenu <= item
            item <= html.TD(label, Class="brython-menu-submenu-item")
            item <= html.TD(">" if menu else "&nbsp;",
                            Class="brython-menu-submenu-item",
                            paddingLeft="2em")

        if callback is not None:
            item.bind("click", callback)

        return item