Esempio n. 1
0
def snekprint(*args, toplevel=False, to=None, **kwargs):
    sess = current_print_session()
    if sess is None:
        orig_print(*args)
    elif to is not None:
        if toplevel:
            html = hrepr(*args, **kwargs)
        else:
            html = hrepr(PrintSequence(args), **kwargs)
        sess.queue(
            command="insert",
            value=html,
            target=to,
        )
    else:
        if all(isinstance(arg, str) for arg in args):
            html = H.div["snek-print-str"](" ".join(args))
        elif toplevel:
            html = hrepr(*args, **kwargs)
        else:
            html = hrepr(PrintSequence(args), **kwargs)
        sess.queue(
            command="result",
            value=html,
            type="print",
        )
Esempio n. 2
0
 def __hrepr__(self, H, hrepr):
     # H.instance is a special kind of tag to format data like an instance.
     # Notice how we call the hrepr parameter on self.age and self.job to
     # format them.
     return H.instance["person"](
         H.pair("age", hrepr(self.age), delimiter=" ↦ "),
         H.pair("job", hrepr(self.job), delimiter=" ↦ "),
         # The "type" represents the header for the "instance"
         type=self.name,
         # "vertical=True" means we'll display the pairs as a table with
         # the delimiters aligned, instead of sticking them horizontally
         # next to each other
         vertical=True,
     )
Esempio n. 3
0
    def __hrepr__(self, H, hrepr):
        exclude = {'save_trace', 'about'}

        def mkdict(info):
            d = {
                k: v
                for k, v in info.__dict__.items()
                if not k.startswith('_') and k not in exclude
            }
            tr = d.get('trace', None)
            if tr:
                fr = tr[-3]
                d['trace'] = parser.Location(fr.filename, fr.lineno, 0,
                                             fr.lineno, 0, None)
            d['name'] = short_labeler.label(info)
            return d

        tabs = []
        info = self
        while getattr(info, 'about', None):
            tabs.append((info, info.about.relation))
            info = info.about.debug
        tabs.append((info, 'initial'))

        rval = H.boxTabs()
        for info, rel in tabs:
            pane = hrepr(mkdict(info))
            rval = rval(H.tabEntry(H.tabLabel(rel), H.tabPane(pane)))

        return rval
Esempio n. 4
0
 def __hrepr__(self, H, hrepr):
     d = {}
     curr = self
     while curr:
         d[curr.graph] = curr.argkey
         curr = curr.parent
     return hrepr(d)
Esempio n. 5
0
def _run(command, options, interactive=None):
    if interactive is None:
        interactive = options['--interactive']

    if interactive:
        code_globals['options'] = options
        repl = Repl(
            buche,
            reader,
            code_globals=code_globals,
            address="/repl",
            log_address="/"
        )
        buche.command_template(content=str(hrepr(repl)))

    buche.master.send({
        "command": "redirect",
        "from": "/stdout",
        "to": "/"
    })

    try:
        res = command(Options(options))
        code_globals['res'] = res
    except InferenceError as e:
        print_inference_error(e)
    except Exception as e:
        buche(e, interactive=True)

    if interactive:
        repl.start(nodisplay=True)
Esempio n. 6
0
 def __type_hrepr__(cls, H, hrepr):
     if cls.is_generic():
         return H.span('Class')
     else:
         return hrepr.stdrepr_object(
             str(cls.tag),
             [(attr, hrepr(typ)) for attr, typ in cls.attributes.items()],
             delimiter='↦')
Esempio n. 7
0
 def html(self, x):
     if not self.html_file:
         return
     if isinstance(x, DataFrame):
         sty = _style(x)
         self._html(sty._repr_html_())
     else:
         self._html(hrepr(x))
Esempio n. 8
0
 def show(cls, *args, nav=False, **kwargs):
     instance = cls(*args, **kwargs)
     html = hrepr(instance)
     if nav:
         current_session().queue(command="set_nav", value=html)
     else:
         print(html)
     return instance
Esempio n. 9
0
    def represent(self, typ, result):
        if isinstance(result, Tag):
            return typ, result

        try:
            html = hrepr(result)
        except Exception as exc:
            try:
                html = hrepr(exc)
            except Exception:
                html = H.pre(
                    traceback.format_exception(
                        builtins.type(exc), exc, exc.__traceback__
                    )
                )
                typ = "hrepr_exception"
        return typ, html
Esempio n. 10
0
File: gprint.py Progetto: tor4z/myia
 def __hrepr__(self, H, hrepr):
     if (len(self.inputs) == 2 and isinstance(self.inputs[0], Constant)
             and self.inputs[0].value is primops.return_):
         if hasattr(hrepr, "hrepr_nowrap"):
             return hrepr.hrepr_nowrap(self.inputs[1])["node-return"]
         else:
             return hrepr(self.inputs[1])["node-return"]
     else:
         return super(Apply, self).__hrepr__(H, hrepr)
Esempio n. 11
0
 def set_nav(self, nav):
     self.add_nav_action(
         "nav",
         lambda: self.queue(
             command="set_nav",
             value=hrepr(nav, interactive=False),
             navid=id(nav),
         ),
     )
Esempio n. 12
0
 def __hrepr__(self, H, hrepr):
     tb = H.table["table"]()
     for k, v in self.fields.items():
         if isinstance(v, float):
             entry = H.td["float"](f"{v:.2f}")
         else:
             entry = H.td(hrepr(v))
         tb = tb(H.tr(H.th(k), entry))
     return tb
Esempio n. 13
0
 def __hrepr__(self, H, hrepr):
     if len(self.inputs) == 2 and \
             isinstance(self.inputs[0], Constant) and \
             self.inputs[0].value is primops.return_:
         if hasattr(hrepr, 'hrepr_nowrap'):
             return hrepr.hrepr_nowrap(self.inputs[1])['node-return']
         else:
             return hrepr(self.inputs[1])['node-return']
     else:
         return super(Apply, self).__hrepr__(H, hrepr)
Esempio n. 14
0
def H(node):
    try:
        from hrepr import hrepr
    except ImportError:
        print('The --format html option requires the \'hrepr\' package',
              'to be installed.\nTo install the package, use the command:',
              '\n\n$ pip3 install hrepr',
              file=sys.stderr)
        sys.exit(1)
    return hrepr(node)
Esempio n. 15
0
 def __hrepr__(self, H, hrepr):
     return hrepr.stdrepr_iterable(
         [
             H.div(hrepr.stdrepr_object('',
                                        _clean(self.values).items(),
                                        delimiter="↦",
                                        cls='noborder'),
                   hrepr(self.element),
                   style='display:flex;flex-direction:column;')
         ],
         before='★A',
         cls='abstract',
     )
Esempio n. 16
0
File: gprint.py Progetto: tor4z/myia
 def cynode(self, id, label, classes, parent=None, node=None):
     """Build data structure for a node in cytoscape."""
     if not isinstance(id, str):
         if node is None:
             node = id
         id = self.id(id)
     data = {"id": id, "label": str(label)}
     if self.tooltip_gen and node:
         ttip = self.tooltip_gen(self._strip_cosmetic(node))
         if ttip is not None:
             if not isinstance(ttip, str):
                 ttip = str(hrepr(ttip))
             data["tooltip"] = ttip
     if parent:
         parent = parent if isinstance(parent, str) else self.id(parent)
         data["parent"] = parent
     self.nodes.append({"data": data, "classes": classes})
Esempio n. 17
0
 def cynode(self, id, label, classes, parent=None, node=None):
     """Build data structure for a node in cytoscape."""
     if not isinstance(id, str):
         if node is None:
             node = id
         id = self.id(id)
     data = {'id': id, 'label': str(label)}
     if self.tooltip_gen and node:
         ttip = self.tooltip_gen(self._strip_cosmetic(node))
         if ttip is not None:
             if not isinstance(ttip, str):
                 ttip = str(hrepr(ttip))
             data['tooltip'] = ttip
     if parent:
         parent = parent if isinstance(parent, str) else self.id(parent)
         data['parent'] = parent
     self.nodes.append({'data': data, 'classes': classes})
Esempio n. 18
0
File: gprint.py Progetto: tor4z/myia
 def __hrepr__(self, H, hrepr):
     return hrepr.stdrepr_iterable(
         [
             H.div(
                 hrepr.stdrepr_object(
                     "",
                     _clean(self.values).items(),
                     delimiter="↦",
                     cls="noborder",
                 ),
                 hrepr(self.element),
                 style="display:flex;flex-direction:column;",
             )
         ],
         before="★A",
         cls="abstract",
     )
Esempio n. 19
0
 def __hrepr__(self, H, hrepr):
     """Return HTML representation (uses buche-cytoscape)."""
     if hrepr.config.depth > 1 and not hrepr.config.graph_expand_all:
         return hrepr(Constant(self))
     dc = hrepr.config.duplicate_constants
     dfv = hrepr.config.duplicate_free_variables
     fin = hrepr.config.function_in_node
     fr = hrepr.config.follow_references
     tgen = hrepr.config.node_tooltip
     cgen = hrepr.config.node_class
     xsty = hrepr.config.graph_style
     gpr = MyiaGraphPrinter(
         {self},
         duplicate_constants=True if dc is None else dc,
         duplicate_free_variables=True if dfv is None else dfv,
         function_in_node=True if fin is None else fin,
         follow_references=True if fr is None else fr,
         tooltip_gen=tgen,
         class_gen=cgen,
         extra_style=xsty)
     gpr.process()
     return gpr.__hrepr__(H, hrepr)
Esempio n. 20
0
 def __hrepr__(self, H, hrepr):
     return H.table["hrepr-body"](
         *[H.tr(H.td(k), H.td(" = ", hrepr(v))) for k, v in self.items()])
Esempio n. 21
0
def _default_click(obj, evt):
    if evt.get("shiftKey", False):
        sess = current_session()
        sess.queue(command="result", value=hrepr(obj), type="print")
    else:
        pastevar(obj)
Esempio n. 22
0
def hdir(obj):
    return hrepr(HDir(obj), max_depth=2)
Esempio n. 23
0
 def __hrepr__(self, H, hrepr):
     return H.div["snek-print-sequence"](*[H.div(hrepr(x)) for x in self],
                                         onclick=False)
Esempio n. 24
0
 def __hrepr__(self, H, hrepr):
     return hrepr(set(self._d.keys()))
Esempio n. 25
0
 def __hrepr__(self, H, hrepr):
     return hrepr(self.value)
Esempio n. 26
0
def insert_at(target, value, index=None, **kwargs):
    html = hrepr(value, **kwargs)
    sess = current_session()
    sess.queue(command="insert", value=html, target=target, index=index)
Esempio n. 27
0
 def hprint(*objs, **kwargs):
     entries.append(hrepr(*objs, **kwargs))
Esempio n. 28
0
def fill_at(target, value, **kwargs):
    html = hrepr(value, **kwargs)
    sess = current_session()
    sess.queue(command="fill", value=html, target=target)
Esempio n. 29
0
 def __hrepr__(self, H, hrepr):
     return hrepr({'node': self.node, 'context': self.context})
Esempio n. 30
0
 def __hrepr__(self, H, hrepr):
     return hrepr(self.__dict__)