Ejemplo n.º 1
0
def show_server(server, notebook_url, server_id):
    """
    Displays a bokeh server inline in the notebook.

    Parameters
    ----------
    server: bokeh.server.server.Server
        Bokeh server instance which is already running
    notebook_url: str
        The URL of the running Jupyter notebook server
    server_id: str
        Unique ID to identify the server with
    """
    from bokeh.embed import server_document
    from IPython.display import publish_display_data

    if callable(notebook_url):
        url = notebook_url(server.port)
    else:
        url = _server_url(notebook_url, server.port)

    script = server_document(url, resources=None)

    publish_display_data({
        HTML_MIME: script,
        EXEC_MIME: ""
    },
                         metadata={EXEC_MIME: {
                             "server_id": server_id
                         }})
Ejemplo n.º 2
0
    def load_hvjs(cls, logo=False, bokeh_logo=False, mpl_logo=False, plotly_logo=False,
                  JS=True, message='HoloViewsJS successfully loaded.'):
        """
        Displays javascript and CSS to initialize HoloViews widgets.
        """
        import jinja2
        # Evaluate load_notebook.html template with widgetjs code
        if JS:
            widgetjs, widgetcss = Renderer.html_assets(extras=False, backends=[], script=True)
        else:
            widgetjs, widgetcss = '', ''

        # Add classic notebook MIME renderer
        widgetjs += nb_mime_js

        templateLoader = jinja2.FileSystemLoader(os.path.dirname(os.path.abspath(__file__)))
        jinjaEnv = jinja2.Environment(loader=templateLoader)
        template = jinjaEnv.get_template('load_notebook.html')
        html = template.render({'widgetcss':   widgetcss,
                                'logo':        logo,
                                'bokeh_logo':  bokeh_logo,
                                'mpl_logo':    mpl_logo,
                                'plotly_logo': plotly_logo,
                                'message':     message})
        publish_display_data(data={'text/html': html})

        # Vanilla JS mime type is only consumed by classic notebook
        # Custom mime type is only consumed by JupyterLab
        if JS:
            mimebundle = {
                MIME_TYPES['js']           : widgetjs,
                MIME_TYPES['jlab-hv-load'] : widgetjs
            }
            publish_display_data(data=mimebundle)
Ejemplo n.º 3
0
def show_app(app, state, notebook_url):
    '''

    '''
    logging.basicConfig()

    from tornado.ioloop import IOLoop
    from ..server.server import Server

    loop = IOLoop.current()
    server = Server({"/": app}, io_loop=loop, port=0,  allow_websocket_origin=[notebook_url])

    server_id = uuid4().hex
    curstate().uuid_to_server[server_id] = server

    server.start()
    url = 'http://%s:%d%s' % (notebook_url.split(':')[0], server.port, "/")

    from ..embed import server_document
    script = server_document(url)

    publish_display_data({
        HTML_MIME_TYPE: script,
        EXEC_MIME_TYPE: ""
    }, metadata={
        EXEC_MIME_TYPE: {"server_id": server_id}
    })
Ejemplo n.º 4
0
 def set(self, dim, n_part):
     self.d_n = dim * n_part
     publish_display_data(
         {SIMZERO_SET_MIME_TYPE: {
             'dim': dim,
             'n_part': n_part
         }})
Ejemplo n.º 5
0
 def _ipython_display_(self):
     """Display the visualization in the Jupyter notebook."""
     id = uuid.uuid4()
     publish_display_data({'text/html': self._generate_html(id)},
                          metadata={'jupyter-vega': '#{0}'.format(id)})
     publish_display_data({'application/javascript': self._generate_js(id)},
                          metadata={'jupyter-vega': '#{0}'.format(id)})
Ejemplo n.º 6
0
def show_doc(obj, state, notebook_handle):
    '''

    '''
    if obj not in state.document.roots:
        state.document.add_root(obj)

    from ..embed.notebook import notebook_content
    comms_target = make_id() if notebook_handle else None
    (script, div, cell_doc) = notebook_content(obj, comms_target)

    publish_display_data({HTML_MIME_TYPE: div})
    publish_display_data({
        JS_MIME_TYPE: script,
        EXEC_MIME_TYPE: ""
    },
                         metadata={EXEC_MIME_TYPE: {
                             "id": obj.id
                         }})

    # Comms handling relies on the fact that the cell_doc returned by
    # notebook copy has models with the same IDs as the original curdoc
    # they were copied from
    if comms_target:
        handle = CommsHandle(get_comms(comms_target), cell_doc)
        state.document.on_change_dispatch_to(handle)
        state.last_comms_handle = handle
        return handle
Ejemplo n.º 7
0
def display(obj, raw=False, **kwargs):
    """
    Renders any HoloViews object to HTML and displays it
    using the IPython display function. If raw is enabled
    the raw HTML is returned instead of displaying it directly.
    """
    if isinstance(obj, GridSpace):
        with option_state(obj):
            output = grid_display(obj)
    elif isinstance(obj, (CompositeOverlay, ViewableElement)):
        with option_state(obj):
            output = element_display(obj)
    elif isinstance(obj, (Layout, NdLayout, AdjointLayout)):
        with option_state(obj):
            output = layout_display(obj)
    elif isinstance(obj, (HoloMap, DynamicMap)):
        with option_state(obj):
            output = map_display(obj)
    else:
        output = {'text/plain': repr(obj)}

    if raw:
        return output
    elif isinstance(output, tuple):
        data, metadata = output
    else:
        data, metadata = output, {}
    publish_display_data(data, metadata)
Ejemplo n.º 8
0
def notebook_show(obj, doc, target):
    """
    Displays bokeh output inside a notebook and returns a CommsHandle.
    """
    publish_display_data({'text/html': notebook_div(obj, target)})
    handle = _CommsHandle(get_comms(target), doc, doc.to_json())
    return handle
Ejemplo n.º 9
0
    def display_immediately(self, plain_text, rich_output):
        """
        Show output immediately.

        This method is similar to the rich output :meth:`displayhook`,
        except that it can be invoked at any time.

        INPUT:

        Same as :meth:`displayhook`.

        OUTPUT:

        This method does not return anything.

        EXAMPLES::

            sage: from sage.repl.rich_output.output_basic import OutputPlainText
            sage: plain_text = OutputPlainText.example()
            sage: from sage.repl.rich_output.backend_ipython import BackendIPythonNotebook
            sage: backend = BackendIPythonNotebook()
            sage: _ = backend.display_immediately(plain_text, plain_text)
            Example plain text output
        """
        formatted, metadata = self.displayhook(plain_text, rich_output)
        if not formatted:
            return
        publish_display_data(data=formatted, metadata=metadata)
Ejemplo n.º 10
0
def _add_or_remove_tags(tags_to_add=(), tags_to_remove=()):
  """Adds or removes tags from the frontend."""
  # Clear tags when this cell is done.
  output_tags = _get_or_create_tags()
  tags_to_add = tuple(tags_to_add)
  tags_to_remove = tuple(tags_to_remove)

  output_tags.update(tags_to_add)
  output_tags.difference_update(tags_to_remove)

  sys.stdout.flush()
  sys.stderr.flush()

  metadata = {
      'outputarea': {
          'nodisplay': True,
          'add_tags': tags_to_add,
          'remove_tags': tags_to_remove
      }
  }

  if ipython.in_ipython():
    if IPython.version_info[0] > 2:
      display.publish_display_data({}, metadata=metadata)
    else:
      display.publish_display_data('display', {}, metadata=metadata)

  return output_tags
Ejemplo n.º 11
0
    def load_hvjs(cls, logo=False, bokeh_logo=False, mpl_logo=False, plotly_logo=False,
                  JS=True, message='HoloViewsJS successfully loaded.'):
        """
        Displays javascript and CSS to initialize HoloViews widgets.
        """
        import jinja2
        # Evaluate load_notebook.html template with widgetjs code
        if JS:
            widgetjs, widgetcss = Renderer.html_assets(extras=False, backends=[], script=True)
        else:
            widgetjs, widgetcss = '', ''

        # Add classic notebook MIME renderer
        widgetjs += nb_mime_js

        templateLoader = jinja2.FileSystemLoader(os.path.dirname(os.path.abspath(__file__)))
        jinjaEnv = jinja2.Environment(loader=templateLoader)
        template = jinjaEnv.get_template('load_notebook.html')
        html = template.render({'widgetcss':   widgetcss,
                                'logo':        logo,
                                'bokeh_logo':  bokeh_logo,
                                'mpl_logo':    mpl_logo,
                                'plotly_logo': plotly_logo,
                                'message':     message})
        publish_display_data(data={'text/html': html})

        # Vanilla JS mime type is only consumed by classic notebook
        # Custom mime type is only consumed by JupyterLab
        if JS:
            mimebundle = {
                MIME_TYPES['js']           : widgetjs,
                MIME_TYPES['jlab-hv-load'] : widgetjs
            }
            publish_display_data(data=mimebundle)
Ejemplo n.º 12
0
    def display_immediately(self, plain_text, rich_output):
        """
        Show output immediately.

        This method is similar to the rich output :meth:`displayhook`,
        except that it can be invoked at any time.

        INPUT:

        Same as :meth:`displayhook`.

        OUTPUT:

        This method does not return anything.

        EXAMPLES::

            sage: from sage.repl.rich_output.output_basic import OutputPlainText
            sage: plain_text = OutputPlainText.example()
            sage: from sage.repl.rich_output.backend_ipython import BackendIPythonNotebook
            sage: backend = BackendIPythonNotebook()
            sage: _ = backend.display_immediately(plain_text, plain_text)
            Example plain text output
        """
        formatted, metadata = self.displayhook(plain_text, rich_output)
        if not formatted:
            return
        publish_display_data(data=formatted, metadata=metadata)
Ejemplo n.º 13
0
def show_app(app, state, notebook_url):
    '''

    '''
    logging.basicConfig()

    from tornado.ioloop import IOLoop
    from ..server.server import Server

    loop = IOLoop.current()
    server = Server({"/": app},
                    io_loop=loop,
                    port=0,
                    allow_websocket_origin=[notebook_url])

    server_id = uuid4().hex
    curstate().uuid_to_server[server_id] = server

    server.start()
    url = 'http://%s:%d%s' % (notebook_url.split(':')[0], server.port, "/")

    from ..embed import server_document
    script = server_document(url)

    publish_display_data({
        HTML_MIME_TYPE: script,
        EXEC_MIME_TYPE: ""
    },
                         metadata={EXEC_MIME_TYPE: {
                             "server_id": server_id
                         }})
Ejemplo n.º 14
0
def show_embed(panel, max_states=1000, max_opts=3, json=False,
              save_path='./', load_path=None):
    """
    Renders a static version of a panel in a notebook by evaluating
    the set of states defined by the widgets in the model. Note
    this will only work well for simple apps with a relatively
    small state space.

    Arguments
    ---------
    max_states: int
      The maximum number of states to embed
    max_opts: int
      The maximum number of states for a single widget
    json: boolean (default=True)
      Whether to export the data to json files
    save_path: str (default='./')
      The path to save json files to
    load_path: str (default=None)
      The path or URL the json files will be loaded from.
    """
    from IPython.display import publish_display_data
    from ..config import config

    doc = Document()
    comm = Comm()
    with config.set(embed=True):
        model = panel.get_root(doc, comm)
        embed_state(panel, model, doc, max_states, max_opts,
                    json, save_path, load_path)
    publish_display_data(*render_model(model))
Ejemplo n.º 15
0
def load_notebook(inline=True, load_timeout=5000):
    from IPython.display import publish_display_data

    resources = INLINE if inline else CDN
    prev_resources = settings.resources(default="server")
    user_resources = settings.resources._user_value is not _Unset
    resources = Resources.from_bokeh(resources)
    try:
        bundle = bundle_resources(resources)
        bundle = Bundle.from_bokeh(bundle)
        configs, requirements, exports, skip_imports = require_components()
        ipywidget = 'ipywidgets_bokeh' in sys.modules
        bokeh_js = _autoload_js(bundle, configs, requirements, exports,
                                skip_imports, ipywidget, load_timeout)
    finally:
        if user_resources:
            settings.resources = prev_resources
        else:
            settings.resources.unset_value()

    publish_display_data({
        'application/javascript': bokeh_js,
        LOAD_MIME: bokeh_js,
    })
    bokeh.io.notebook.curstate().output_notebook()

    # Publish comm manager
    JS = '\n'.join([PYVIZ_PROXY, _JupyterCommManager.js_manager, nb_mime_js])
    publish_display_data(data={LOAD_MIME: JS, 'application/javascript': JS})
Ejemplo n.º 16
0
def publish_display_data(data: Dict[str, Any], metadata: Dict[Any, Any] | None = None,
        source: str | None = None, *, transient: Dict[str, Any] | None = None, **kwargs: Any) -> None:
    '''

    '''
    # This import MUST be deferred or it will introduce a hard dependency on IPython
    from IPython.display import publish_display_data
    publish_display_data(data, metadata, source, transient=transient, **kwargs)
Ejemplo n.º 17
0
def show(captured_io, to_html_func):
    output = captured_io.stdout + captured_io.stderr
    display.publish_display_data('', {
        'text/plain': output,
        'text/html': to_html_func(output)
    }, {})
    for o in captured_io.outputs:
        o.display()
Ejemplo n.º 18
0
 def load_nb(cls, inline=True):
     """
     Loads the plotly notebook resources.
     """
     from IPython.display import publish_display_data
     cls._loaded = True
     init_notebook_mode(connected=not inline)
     publish_display_data(data={MIME_TYPES['jlab-hv-load']: get_plotlyjs()})
Ejemplo n.º 19
0
    def display(self):
        from IPython.display import publish_display_data

        publish_display_data(
            data=self.data,
            metadata=self.metadata,
            transient=self.transient,
            update=self.update,
        )
Ejemplo n.º 20
0
 def load_nb(cls, inline=True):
     """
     Loads the plotly notebook resources.
     """
     from IPython.display import publish_display_data
     cls._loaded = True
     init_notebook_mode(connected=not inline)
     publish_display_data(data={MIME_TYPES['jlab-hv-load']:
                                get_plotlyjs()})
Ejemplo n.º 21
0
def display_info_string(**kwargs):
    _template = """
    {{widgetcss}}
    <table><tr><td>
    {% if logo %}
    <img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAAlw
    SFlzAAAJOgAACToB8GSSSgAAAetpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6
    bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8x
    OTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPH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xrDmcYX0MBsdF7egvXZ7+O0vZA4X8QmOQWjlSK7
    RDz5wIM30gp9UbWcGjXxhzdDu1SiNSpx6kcQB57rPnr/3dlkZarWLnlRq5oPET1dOCIOk4wALib9eeS5iygfhkd09H0DWphB/+gs
    +PcOAS+ssrFmmXXgVfR0de9cpbAJfH3Q1jofW9DZk56dDcVsq9YcsoUMEd1qyLoT3BX1YiyHMJuk97hyjqIoE91t+NcTLeN0ZrfM
    oXatZbu6G0h4VG+ibqq0IJVK6cAjo6serG3vSUezCMct0yQeSOFJSUImqb2qbknUpDqlZxE0QZ+ZUpSlZx79h4Nda6zef9dlk121
    JDjbR5XggPRZlRnS6bRQRtLpn4++cuie/Yvn2svmNxuLw9WCcYIl4fEoTEGiSTUqJdfgU+8ROqf1iMkLzS389YtNPXc/PH8l8ONB
    JZkHD+4JtD04HmVEDWWErmBhzV2/2LB1bemJG6krzv2S6NOHUgtEP0Oif5pE/3fHoruP7N8RiP61GArzSwbUhJJQpXJKiKbfr/3b
    IhKq76sKPUdF9NW/LSqfSn6vjv8C45H/6FSgvZQAAAAASUVORK5CYII='
         style='height:25px; border-radius:12px; display:inline-block; float:left; vertical-align:middle'></img>
    {% endif %}
    </td><td>
    {% if message %}
    &nbsp;&nbsp;<span style='font-size:12px'>{{ message }}</span>
    {% endif %}
    </td></tr></table>
    </div>
    """

    clear_output()

    logo = kwargs.get('logo', True)
    message = kwargs.get('message', 'info ')

    template = Template(_template)
    html = template.render({
        'logo': logo,
        'message': message.strip().replace('\n', '<br/>')
    })
    publish_display_data(data={'text/html': html})
Ejemplo n.º 22
0
def _ipython_display_(self):
    """
    Render Scenes using crystaltoolkit-extension for Jupyter Lab.

    This function ensures that objects are also printed in string format
    as previously.
    """
    from IPython.display import publish_display_data

    publish_display_data(self._repr_mimebundle_())
Ejemplo n.º 23
0
 def _ipython_display_(self):
     """Display the visualization in the Jupyter notebook."""
     if self.InitNeeded:
         html = self._generate_html(self.ID)
         #print "generated html:", html
         publish_display_data({'text/html': html}, metadata={})
     js = self._generate_js(self.ID)
     #print "generated javascript:", js
     publish_display_data({'application/javascript': js}, metadata={})
     self.InitNeeded = False
Ejemplo n.º 24
0
 def load_nb(cls, inline=True):
     """
     Loads the plotly notebook resources.
     """
     from IPython.display import display, HTML, publish_display_data
     if not cls._loaded:
         display(HTML(PLOTLY_WARNING))
         cls._loaded = True
     init_notebook_mode(connected=not inline)
     publish_display_data(data={MIME_TYPES['jlab-hv-load']: get_plotlyjs()})
Ejemplo n.º 25
0
Archivo: io.py Proyecto: sigongli/bokeh
def _show_jupyter_doc_with_state(obj, state, notebook_handle):
    comms_target = make_id() if notebook_handle else None
    (script, div) = notebook_content(obj, comms_target)
    publish_display_data({HTML_MIME_TYPE: div})
    publish_display_data({JS_MIME_TYPE: script, EXEC_MIME_TYPE: ""}, metadata={EXEC_MIME_TYPE: {"id": obj._id}})
    if comms_target:
        handle = _CommsHandle(get_comms(comms_target), state.document,
                              state.document.to_json())
        state.last_comms_handle = handle
        return handle
Ejemplo n.º 26
0
 def _ipython_display_(self):
     """Display the visualization in the Jupyter notebook."""
     id = uuid.uuid4()
     publish_display_data(
         {'text/html': self._generate_html(id)},
         metadata={'jupyter-vega': '#{0}'.format(id)}
     )
     publish_display_data(
         {'application/javascript': self._generate_js(id)},
         metadata={'jupyter-vega': '#{0}'.format(id)}
     )
Ejemplo n.º 27
0
 def _ipython_display_(self):
     js = ("""
         (function (el) {
             require(['candela'], function (candela) {
                 var comp = candela.components['%s'];
                 var vis = new comp(el.get(0), %s);
                 vis.render();
             });
         })(element);
         """ % (self.name, json.dumps(self.options, cls=DataFrameEncoder)))
     publish_display_data({'application/javascript': js})
Ejemplo n.º 28
0
def js_publish(id_, inst):
    """Generate Vega JS

    Args:
      id_: a unique ID to tag the element
      inst: a Vega instance

    """
    publish_display_data(
        # pylint: disable=protected-access
        {'application/javascript': inst._generate_js(id_)},
        metadata={'jupyter-vega': '#{0}'.format(id_)}
    )
Ejemplo n.º 29
0
def notebook_show(obj, doc, target):
    """
    Displays bokeh output inside a notebook and returns a CommsHandle.
    """
    bokeh_script, bokeh_div, _ = bokeh.embed.notebook.notebook_content(obj, target)

    bokeh_output = """
    {bokeh_div}
    <script type="application/javascript">{bokeh_script}</script>
    """.format(bokeh_div=bokeh_div, bokeh_script=bokeh_script)

    publish_display_data({'text/html': encode_utf8(bokeh_output)})
    return bokeh.io.notebook.CommsHandle(bokeh.io.notebook.get_comms(target), doc)
Ejemplo n.º 30
0
def load_notebook(inline=True):
    from IPython.display import publish_display_data

    # Create a message for the logo (if shown)
    LOAD_MIME_TYPE = bokeh.io.notebook.LOAD_MIME_TYPE
    bokeh.io.notebook.LOAD_MIME_TYPE = LOAD_MIME
    bk_load_notebook(hide_banner=True, resources=INLINE if inline else CDN)
    bokeh.io.notebook.LOAD_MIME_TYPE = LOAD_MIME_TYPE
    bokeh.io.notebook.curstate().output_notebook()

    # Publish comm manager
    JS = '\n'.join([PYVIZ_PROXY, JupyterCommManager.js_manager, nb_mime_js])
    publish_display_data(data={LOAD_MIME: JS, 'application/javascript': JS})
Ejemplo n.º 31
0
 def on_iopub(self, msg):
     if msg["msg_type"] == "error":
         publish_display_data(
             {
                 "text/plain":
                 "{} - {}\n{}".format(
                     msg["content"]["ename"], msg["content"]["evalue"],
                     "\n".join(msg["content"]["traceback"]))
             },
             metadata={"echo": True})
     elif msg["msg_type"] == "stream":
         publish_display_data({"text/plain": msg["content"]["text"]},
                              metadata={"echo": True})
     elif msg["msg_type"] == "display_data":
         publish_display_data(msg["content"]["data"],
                              metadata={"echo": True})
     elif msg["msg_type"] == "execute_result":
         publish_display_data(msg["content"]["data"],
                              metadata={"echo": True})
     elif msg["msg_type"] in [
             "execute_input", "execution_state", "status"
     ]:
         pass
     else:
         pprint(msg)
Ejemplo n.º 32
0
def load_notebook(resources=None,
                  verbose=False,
                  hide_banner=False,
                  load_timeout=5000,
                  notebook_type='jupyter'):
    ''' Prepare the IPython notebook for displaying Bokeh plots.

    Args:
        resources (Resource, optional) :
            how and where to load BokehJS from (default: CDN)

        verbose (bool, optional) :
            whether to report detailed settings (default: False)

        hide_banner (bool, optional):
            whether to hide the Bokeh banner (default: False)

        load_timeout (int, optional) :
            Timeout in milliseconds when plots assume load timed out (default: 5000)

        notebook_type (string):
            notebook_type (default: jupyter)

    .. warning::
        Clearing the output cell containing the published BokehJS
        resources HTML code may cause Bokeh CSS styling to be removed.

    Returns:
        None

    '''
    nb_html, nb_js = _load_notebook_html(resources, verbose, hide_banner,
                                         load_timeout)
    lab_html, lab_js = _load_notebook_html(resources,
                                           verbose,
                                           hide_banner,
                                           load_timeout,
                                           register_mimetype=False)
    if notebook_type == 'jupyter':
        publish_display_data({
            'text/html': nb_html + _wrap_in_script_tag(nb_js),
            LOAD_MIME_TYPE: {
                "script": lab_js,
                "div": lab_html
            }
        })
    else:
        _publish_zeppelin_data(lab_html, lab_js)
Ejemplo n.º 33
0
def show_server(panel, notebook_url, port):
    """
    Displays a bokeh server inline in the notebook.

    Arguments
    ---------
    panel: Viewable
      Panel Viewable object to launch a server for
    notebook_url: str
      The URL of the running Jupyter notebook server
    port: int (optional, default=0)
      Allows specifying a specific port
    server_id: str
      Unique ID to identify the server with

    Returns
    -------
    server: bokeh.server.Server
    """
    from IPython.display import publish_display_data

    if callable(notebook_url):
        origin = notebook_url(None)
    else:
        origin = _origin_url(notebook_url)
    server_id = uuid.uuid4().hex
    server = get_server(panel,
                        port,
                        origin,
                        start=True,
                        show=False,
                        server_id=server_id)

    if callable(notebook_url):
        url = notebook_url(server.port)
    else:
        url = _server_url(notebook_url, server.port)

    script = server_document(url, resources=None)

    publish_display_data({
        HTML_MIME: script,
        EXEC_MIME: ""
    },
                         metadata={EXEC_MIME: {
                             "server_id": server_id
                         }})
    return server
Ejemplo n.º 34
0
def table(df):
    """Format a small :class:`~pandas.DataFrame` as an `org-mode table<https://orgmode.org/manual/Tables.html>`_.

    :param df: input DataFrame
    :type df: :class:`~pandas.DataFrame`
    :returns: org-mode table as IPython display string with 'text/org' MIME type

    """
    def index(idx):
        if isinstance(idx, MultiIndex):
            x = list(idx)
            return [x[0]
                    ] + [[' ' if x[i][j] == z else z for j, z in enumerate(y)]
                         for i, y in enumerate(x[1:])]
        else:
            return [[i] for i in idx]

    idx = index(df.index)
    cols = index(df.columns)
    M = df.as_matrix()
    s = '|\n|'.join('|'.join(' ' for _ in range(len(idx[0]))) + '|' + \
                          '|'.join(str(c[i]) for c in cols) for i in range(len(cols[0]))) + \
        '|\n|' + '|'.join('-' for _ in range(len(idx[0]) + len(M[0]))) + '|\n|' + \
        '|\n|'.join('|'.join(str(i) for j in z for i in j) for z in zip(idx, M))
    return publish_display_data({'text/org': '|' + s + '|'})
Ejemplo n.º 35
0
def publish_display_data(*args, **kw):
    '''

    '''
    # This import MUST be deferred or it will introduce a hard dependency on IPython
    from IPython.display import publish_display_data
    return publish_display_data(*args, **kw)
Ejemplo n.º 36
0
def publish_display_data(*args, **kw):
    '''

    '''
    # This import MUST be deferred or it will introduce a hard dependency on IPython
    from IPython.display import publish_display_data
    return publish_display_data(*args, **kw)
    def load_hvjs(cls, logo=False, bokeh_logo=False, mpl_logo=False, plotly_logo=False,
                  JS=True, message='HoloViewsJS successfully loaded.'):
        """
        Displays javascript and CSS to initialize HoloViews widgets.
        """
        import jinja2

        templateLoader = jinja2.FileSystemLoader(os.path.dirname(os.path.abspath(__file__)))
        jinjaEnv = jinja2.Environment(loader=templateLoader)
        template = jinjaEnv.get_template('load_notebook.html')
        html = template.render({'logo':        logo,
                                'bokeh_logo':  bokeh_logo,
                                'mpl_logo':    mpl_logo,
                                'plotly_logo': plotly_logo,
                                'message':     message})
        publish_display_data(data={'text/html': html})
Ejemplo n.º 38
0
    def _ipython_display_(self):
        serialized = self.to_json()
        js = ("""
            var render = function () {
                %s
                var c = %s;
                require(['candela'], function (candela) {
                    var comp = candela.components[c.name];
                    var vis = new comp(element.get(0), c.options);
                    vis.render();
                });
            };
            render();
            """ % (_require_config, serialized))

        publish_display_data({
            'application/javascript': js,
            MIME_TYPE: json.loads(serialized)
        })
Ejemplo n.º 39
0
def show_doc(obj, state, notebook_handle):
    '''

    '''
    from ..embed import notebook_content
    comms_target = make_id() if notebook_handle else None
    (script, div, cell_doc) = notebook_content(obj, comms_target)

    publish_display_data({HTML_MIME_TYPE: div})
    publish_display_data({JS_MIME_TYPE: script, EXEC_MIME_TYPE: ""}, metadata={EXEC_MIME_TYPE: {"id": obj._id}})

    # Comms handling relies on the fact that the cell_doc returned by
    # notebook copy has models with the same IDs as the original curdoc
    # they were copied from
    if comms_target:
        handle = CommsHandle(get_comms(comms_target), cell_doc)
        state.document.on_change_dispatch_to(handle)
        state.last_comms_handle = handle
        return handle
Ejemplo n.º 40
0
def show_app(app, state, notebook_url, port=0):
    ''' Embed a Bokeh serer application in a Jupyter Notebook output cell.

    Args:
        app (Application) :

        state (State) :

        notebook_url (str) :

        port (int) : the port the embedded server will listen on. By default
        the port is 0, which results in the server listening on a random dynamic port.

    Returns:
        None

    '''
    logging.basicConfig()

    from tornado.ioloop import IOLoop
    from ..server.server import Server

    loop = IOLoop.current()

    origin = _origin_url(notebook_url)
    server = Server({"/": app}, io_loop=loop, port=port,  allow_websocket_origin=[origin])

    server_id = uuid4().hex
    curstate().uuid_to_server[server_id] = server

    server.start()
    url = _server_url(notebook_url, server.port)

    from ..embed import server_document
    script = server_document(url)

    publish_display_data({
        HTML_MIME_TYPE: script,
        EXEC_MIME_TYPE: ""
    }, metadata={
        EXEC_MIME_TYPE: {"server_id": server_id}
    })
Ejemplo n.º 41
0
def init():
    init_js = _require_config + """
    require(['candela'], function (candela) {
        var components = [];
        for (var comp in candela.components) {
            if (candela.components.hasOwnProperty(comp)) {
                components.push(comp);
            }
        }
        var kernel = IPython.notebook.kernel;
        kernel.execute('import pycandela as __pycandela');
        kernel.execute('__pycandela._component_list = ' +
            JSON.stringify(components));
    }, function (error) {
        element.append('<pre>' + error + '</pre>');
    });
    """

    publish_display_data({
        'application/javascript': init_js,
        MIME_TYPE: None
    })
Ejemplo n.º 42
0
def html_publish_map(data):
    """Run IPython's 'publish_display_data' for each spec.

    Args:
      data: list of (id, spec) pairings
    """
    pipe(
        data,
        map(lambda x: x[0]),
        list,
        lambda x: publish_display_data(
            {'text/html': render_html(x)},
            metadata={'jupyter-vega': '#{0}'.format(x[0])})
    )
Ejemplo n.º 43
0
 def on_iopub(self, msg):
     if msg["msg_type"] == "error":
         publish_display_data({"text/plain": "{} - {}\n{}".format(msg["content"]["ename"],
                                                                  msg["content"]["evalue"],
                                                                  "\n".join(msg["content"]["traceback"]))},
                              metadata={"echo": True})
     elif msg["msg_type"] == "stream":
         publish_display_data({"text/plain": msg["content"]["text"]}, metadata={"echo": True})
     elif msg["msg_type"] == "display_data":
         publish_display_data(msg["content"]["data"], metadata={"echo": True})
     elif msg["msg_type"] == "execute_result":
         publish_display_data(msg["content"]["data"], metadata={"echo": True})
     elif msg["msg_type"] in ["execute_input", "execution_state", "status"]:
         pass
     else:
         pprint(msg)
Ejemplo n.º 44
0
def publish_to_display(obj):
    output, _ = DisplayFormatter().format(obj)
    publish_display_data(output)
Ejemplo n.º 45
0
def load_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000):
    ''' Prepare the IPython notebook for displaying Bokeh plots.

    Args:
        resources (Resource, optional) :
            how and where to load BokehJS from (default: CDN)

        verbose (bool, optional) :
            whether to report detailed settings (default: False)

        hide_banner (bool, optional):
            whether to hide the Bokeh banner (default: False)

        load_timeout (int, optional) :
            Timeout in milliseconds when plots assume load timed out (default: 5000)

    .. warning::
        Clearing the output cell containing the published BokehJS
        resources HTML code may cause Bokeh CSS styling to be removed.

    Returns:
        None

    '''

    global _NOTEBOOK_LOADED

    from .. import __version__
    from ..core.templates import NOTEBOOK_LOAD
    from ..util.serialization import make_id
    from ..resources import CDN
    from ..util.compiler import bundle_all_models

    if resources is None:
        resources = CDN

    if not hide_banner:

        if resources.mode == 'inline':
            js_info = 'inline'
            css_info = 'inline'
        else:
            js_info = resources.js_files[0] if len(resources.js_files) == 1 else resources.js_files
            css_info = resources.css_files[0] if len(resources.css_files) == 1 else resources.css_files

        warnings = ["Warning: " + msg['text'] for msg in resources.messages if msg['type'] == 'warn']
        if _NOTEBOOK_LOADED and verbose:
            warnings.append('Warning: BokehJS previously loaded')

        element_id = make_id()

        html = NOTEBOOK_LOAD.render(
            element_id    = element_id,
            verbose       = verbose,
            js_info       = js_info,
            css_info      = css_info,
            bokeh_version = __version__,
            warnings      = warnings,
        )

    else:
        element_id = None

    _NOTEBOOK_LOADED = resources

    custom_models_js = bundle_all_models() or ""

    nb_js = _loading_js(resources, element_id, custom_models_js, load_timeout, register_mime=True)
    jl_js = _loading_js(resources, element_id, custom_models_js, load_timeout, register_mime=False)

    if not hide_banner:
        publish_display_data({'text/html': html})
    publish_display_data({
        JS_MIME_TYPE   : nb_js,
        LOAD_MIME_TYPE : jl_js
    })
Ejemplo n.º 46
0
def show_app(app, state, notebook_url, port=0, **kw):
    ''' Embed a Bokeh server application in a Jupyter Notebook output cell.

    Args:
        app (Application or callable) :
            A Bokeh Application to embed inline in a Jupyter notebook.

        state (State) :
            ** Unused **

        notebook_url (str or callable) :
            The URL of the notebook server that is running the embedded app.

            If ``notebook_url`` is a string, the value string is parsed to
            construct the origin and full server URLs.

            If notebook_url is a callable, it must accept one parameter,
            which will be the server port, or None. If passed a port,
            the callable must generate the server URL, otherwise if passed
            None, it must generate the origin URL for the server.

        port (int) :
            A port for the embedded server will listen on.

            By default the port is 0, which results in the server listening
            on a random dynamic port.

    Any additional keyword arguments are passed to :class:`~bokeh.server.Server` (added in version 1.1)

    Returns:
        None

    '''
    logging.basicConfig()

    from tornado.ioloop import IOLoop
    from ..server.server import Server

    loop = IOLoop.current()

    if callable(notebook_url):
        origin = notebook_url(None)
    else:
        origin = _origin_url(notebook_url)

    server = Server({"/": app}, io_loop=loop, port=port,  allow_websocket_origin=[origin], **kw)

    server_id = uuid4().hex
    curstate().uuid_to_server[server_id] = server

    server.start()

    if callable(notebook_url):
        url = notebook_url(server.port)
    else:
        url = _server_url(notebook_url, server.port)

    logging.debug("Server URL is %s" % url)
    logging.debug("Origin URL is %s" % origin)

    from ..embed import server_document
    script = server_document(url, resources=None)

    publish_display_data({
        HTML_MIME_TYPE: script,
        EXEC_MIME_TYPE: ""
    }, metadata={
        EXEC_MIME_TYPE: {"server_id": server_id}
    })
Ejemplo n.º 47
0
 def display(self):
     from IPython.display import publish_display_data
     publish_display_data(data=self.data, metadata=self.metadata)
Ejemplo n.º 48
0
 def display(self):
     from IPython.display import publish_display_data
     publish_display_data(data=self.data, metadata=self.metadata,
                          transient=self.transient, update=self.update)
Ejemplo n.º 49
0
def show(captured_io, to_html_func):
    output = captured_io.stdout + captured_io.stderr
    display.publish_display_data('', {'text/plain': output,
                                      'text/html': to_html_func(output)}, {})
    for o in captured_io.outputs:
        o.display()
Ejemplo n.º 50
0
 def display(self):
     from IPython.display import publish_display_data
     publish_display_data(self.source, self.data, self.metadata)