Пример #1
0
def show(close=None, block=None):
    """Show all figures as SVG/PNG payloads sent to the yap_ipython clients.

    Parameters
    ----------
    close : bool, optional
      If true, a ``plt.close('all')`` call is automatically issued after
      sending all the figures. If this is set, the figures will entirely
      removed from the internal list of figures.
    block : Not used.
      The `block` parameter is a Matplotlib experimental parameter.
      We accept it in the function signature for compatibility with other
      backends.
    """
    if close is None:
        close = InlineBackend.instance().close_figures
    try:
        for figure_manager in Gcf.get_all_fig_managers():
            display(figure_manager.canvas.figure)
    finally:
        show._to_draw = []
        # only call close('all') if any to close
        # close triggers gc.collect, which can be slow
        if close and Gcf.get_all_fig_managers():
            matplotlib.pyplot.close('all')
Пример #2
0
    def latex(self, line, cell):
        """Render the cell as a block of latex

        The subset of latex which is support depends on the implementation in
        the client.  In the Jupyter Notebook, this magic only renders the subset
        of latex defined by MathJax
        [here](https://docs.mathjax.org/en/v2.5-latest/tex.html)."""
        display(Latex(cell))
Пример #3
0
def display_page(strng, start=0, screen_lines=25):
    """Just display, no paging. screen_lines is ignored."""
    if isinstance(strng, dict):
        data = strng
    else:
        if start:
            strng = u'\n'.join(strng.splitlines()[start:])
        data = {'text/plain': strng}
    display(data, raw=True)
Пример #4
0
def display_page(strng, start=0, screen_lines=25):
    """Just display, no paging. screen_lines is ignored."""
    if isinstance(strng, dict):
        data = strng
    else:
        if start:
            strng = u'\n'.join(strng.splitlines()[start:])
        data = { 'text/plain': strng }
    display(data, raw=True)
Пример #5
0
def test_display_id():
    ip = get_ipython()
    with mock.patch.object(ip.display_pub, 'publish') as pub:
        handle = display.display('x')
        nt.assert_is(handle, None)
        handle = display.display('y', display_id='secret')
        nt.assert_is_instance(handle, display.DisplayHandle)
        handle2 = display.display('z', display_id=True)
        nt.assert_is_instance(handle2, display.DisplayHandle)
    nt.assert_not_equal(handle.display_id, handle2.display_id)

    nt.assert_equal(pub.call_count, 3)
    args, kwargs = pub.call_args_list[0]
    nt.assert_equal(args, ())
    nt.assert_equal(kwargs, {
        'data': {
            'text/plain': repr('x')
        },
        'metadata': {},
    })
    args, kwargs = pub.call_args_list[1]
    nt.assert_equal(args, ())
    nt.assert_equal(
        kwargs, {
            'data': {
                'text/plain': repr('y')
            },
            'metadata': {},
            'transient': {
                'display_id': handle.display_id,
            },
        })
    args, kwargs = pub.call_args_list[2]
    nt.assert_equal(args, ())
    nt.assert_equal(
        kwargs, {
            'data': {
                'text/plain': repr('z')
            },
            'metadata': {},
            'transient': {
                'display_id': handle2.display_id,
            },
        })
Пример #6
0
def flush_figures():
    """Send all figures that changed

    This is meant to be called automatically and will call show() if, during
    prior code execution, there had been any calls to draw_if_interactive.

    This function is meant to be used as a post_execute callback in yap_ipython,
    so user-caused errors are handled with showtraceback() instead of being
    allowed to raise.  If this function is not called from within yap_ipython,
    then these exceptions will raise.
    """
    if not show._draw_called:
        return

    if InlineBackend.instance().close_figures:
        # ignore the tracking, just draw and close all figures
        try:
            return show(True)
        except Exception as e:
            # safely show traceback if in yap_ipython, else raise
            ip = get_ipython()
            if ip is None:
                raise e
            else:
                ip.showtraceback()
                return
    try:
        # exclude any figures that were closed:
        active = set([fm.canvas.figure for fm in Gcf.get_all_fig_managers()])
        for fig in [fig for fig in show._to_draw if fig in active]:
            try:
                display(fig)
            except Exception as e:
                # safely show traceback if in yap_ipython, else raise
                ip = get_ipython()
                if ip is None:
                    raise e
                else:
                    ip.showtraceback()
                    return
    finally:
        # clear flags for next round
        show._to_draw = []
        show._draw_called = False
Пример #7
0
def test_display_id():
    ip = get_ipython()
    with mock.patch.object(ip.display_pub, 'publish') as pub:
        handle = display.display('x')
        nt.assert_is(handle, None)
        handle = display.display('y', display_id='secret')
        nt.assert_is_instance(handle, display.DisplayHandle)
        handle2 = display.display('z', display_id=True)
        nt.assert_is_instance(handle2, display.DisplayHandle)
    nt.assert_not_equal(handle.display_id, handle2.display_id)

    nt.assert_equal(pub.call_count, 3)
    args, kwargs = pub.call_args_list[0]
    nt.assert_equal(args, ())
    nt.assert_equal(kwargs, {
        'data': {
            'text/plain': repr('x')
        },
        'metadata': {},
    })
    args, kwargs = pub.call_args_list[1]
    nt.assert_equal(args, ())
    nt.assert_equal(kwargs, {
        'data': {
            'text/plain': repr('y')
        },
        'metadata': {},
        'transient': {
            'display_id': handle.display_id,
        },
    })
    args, kwargs = pub.call_args_list[2]
    nt.assert_equal(args, ())
    nt.assert_equal(kwargs, {
        'data': {
            'text/plain': repr('z')
        },
        'metadata': {},
        'transient': {
            'display_id': handle2.display_id,
        },
    })
Пример #8
0
def draw_if_interactive():
    """
    Is called after every pylab drawing command
    """
    # signal that the current active figure should be sent at the end of
    # execution.  Also sets the _draw_called flag, signaling that there will be
    # something to send.  At the end of the code execution, a separate call to
    # flush_figures() will act upon these values
    manager = Gcf.get_active()
    if manager is None:
        return
    fig = manager.canvas.figure

    # Hack: matplotlib FigureManager objects in interacive backends (at least
    # in some of them) monkeypatch the figure object and add a .show() method
    # to it.  This applies the same monkeypatch in order to support user code
    # that might expect `.show()` to be part of the official API of figure
    # objects.
    # For further reference:
    # https://github.com/ipython/ipython/issues/1612
    # https://github.com/matplotlib/matplotlib/issues/835

    if not hasattr(fig, 'show'):
        # Queue up `fig` for display
        fig.show = lambda *a: display(fig)

    # If matplotlib was manually set to non-interactive mode, this function
    # should be a no-op (otherwise we'll generate duplicate plots, since a user
    # who set ioff() manually expects to make separate draw/show calls).
    if not matplotlib.is_interactive():
        return

    # ensure current figure will be drawn, and each subsequent call
    # of draw_if_interactive() moves the active figure to ensure it is
    # drawn last
    try:
        show._to_draw.remove(fig)
    except ValueError:
        # ensure it only appears in the draw list once
        pass
    # Queue up the figure for drawing in next show() call
    show._to_draw.append(fig)
    show._draw_called = True
Пример #9
0
 def markdown(self, line, cell):
     """Render the cell as Markdown text block"""
     display(Markdown(cell))
Пример #10
0
 def html(self, line, cell):
     """Render the cell as a block of HTML"""
     display(HTML(cell))
Пример #11
0
 def svg(self, line, cell):
     """Render the cell as an SVG literal"""
     display(SVG(cell))
Пример #12
0
 def javascript(self, line, cell):
     """Run the cell block of Javascript code"""
     display(Javascript(cell))