Esempio n. 1
0
    def make_index(self,where='.',debug=False):
        """
        Produce rst code files from the database and an index reading first line of the %summary field.

        Command line use: 
            The ``where`` input argument, when specified,  will contain all details of Sphinx compilation.

        LINKS:

        http://code.activestate.com/recipes/193890-using-rest-restructuredtext-to-create-html-snippet/

        """

        html_index = SphinxExporter(self,where,debug)
        print "Index is at: "+ html_index.htmlfile

        if is_notebook():
            if where == '.': 
                #To open a browser
                pos = html_index.htmlfile.find(".")
                html(r'<a href="%s" target=_blank>Press to open database index.</a>' % html_index.htmlfile[pos:])
            elif 'data' in where:
                #To open a browser
                pos = html_index.htmlfile.find("/home")
                pos2 = html_index.htmlfile.find("/home",pos+1)
                if pos2>=0:
                    pos = pos2
                html(r'<a href="%s" target=_blank>Press to open database index.</a>' % html_index.htmlfile[pos:])
            else:
                #print "Index is at: "+ html_index.htmlfile
                print "See index at Megua button at top."
        else:
            print "firefox -no-remote ", html_index.htmlfile
Esempio n. 2
0
 def embed_video(self, video_output):
     filename = graphics_filename(ext=video_output.ext)
     video_output.video.save_as(filename)
     world_readable(filename)
     html(video_output.html_fragment(
         url='cell://' + filename,
         link_attrs='class="file_link"',
     ))
Esempio n. 3
0
 def embed_video(self, video_output):
     filename = graphics_filename(ext=video_output.ext)
     video_output.video.save_as(filename)
     world_readable(filename)
     html(
         video_output.html_fragment(
             url='cell://' + filename,
             link_attrs='class="file_link"',
         ))
Esempio n. 4
0
def jsmath(x, mode='display'):
    r'''
    Attempt to nicely render an arbitrary SAGE object wih jsmath typesetting.
    Tries to call ._latex_() on x. If that fails, it will render a string
    representation of x.

    .. warning::

        2009-04: This function is deprecated; use ``html`` instead:
        replace ``jsmath('MATH', mode='display')`` with ``html('$$MATH$$')``,
        and replace ``jsmath('MATH', mode='inline')`` with ``html('$MATH$')``.

    INPUT:
        x -- the object to render
        mode -- 'display' for displaymath or 'inline' for inline math

    OUTPUT:
        A string of html that contains the LaTeX represntation of x. In the
        notebook this gets embedded into the cell.

    EXAMPLES::
    
        sage: from sage.misc.latex import jsmath
        sage: f = maxima('1/(x^2+1)')
        sage: g = f.integrate()
        sage: jsmath(f)
        ... DeprecationWarning: The jsmath function is deprecated.  Use html('$math$') for inline mode or html('$$math$$') for display mode.
        # -*- coding: utf-8 -*-
        <html><font color='black'><div class="math">{{1}\over{x^2+1}}</div></font></html>
        sage: jsmath(g, 'inline')
        <html><font color='black'><span class="math">\tan^{-1} x</span></font></html>
        sage: jsmath('\int' + latex(f) + '\ dx=' + latex(g))
        <html><font color='black'><div class="math">\int{{1}\over{x^2+1}}\ dx=\tan^{-1} x</div></font></html>

    AUTHORS: 

    - William Stein (2006-10): general layout (2006-10)

    - Bobby Moretti (2006-10): improvements, comments, documentation
    '''
    from sage.misc.misc import deprecation
    from sage.misc.html import html
    deprecation("The jsmath function is deprecated.  Use html('$math$') for inline mode or html('$$math$$') for display mode.")    
    if mode == 'display':
        delimiter = '$$'
    elif mode == 'inline':
        delimiter = '$'
    else:
        raise ValueError, "mode must be either 'display' or 'inline'"
    try:
        # try to get a latex representation of the object
        x = x._latex_()
    except AttributeError:
        # otherwise just get the string representation
        x = str(x)
    return html(delimiter + x + delimiter)
Esempio n. 5
0
    def latex_formatter(self, obj, **kwds):
        r"""
        Hook to override how latex is being formatted.

        INPUT:

        - ``obj`` -- anything.

        - ``**kwds`` -- optional keyword arguments to control the
          formatting. Supported are:

            * ``concatenate`` -- boolean (default: ``False``). If
              ``True``, the argument ``obj`` must be iterable and its
              entries will be concatenated. There is a single
              whitespace between entries.

        OUTPUT:

        Instance of :class:`~sage.repl.rich_output.output_browser.OutputHtml`
        containing the latex string representation of the object.

        EXAMPLES::

            sage: from sage.repl.rich_output.backend_base import BackendBase
            sage: backend = BackendBase()
            sage: out = backend.latex_formatter(1/2)
            sage: out
            OutputHtml container
            sage: out.html
            buffer containing 105 bytes
            sage: out.html.get_str()
            '<html><script type="math/tex; mode=display">\\newcommand{\\Bold}[1]{\\mathbf{#1}}\\frac{1}{2}</script></html>'

            sage: out = backend.latex_formatter([1/2, x, 3/4, ZZ], concatenate=False)
            sage: out.html.get_str()
            '<html><script type="math/tex; mode=display">\\newcommand{\\Bold}[1]{\\mathbf{#1}}\\left[\\frac{1}{2}, x, \\frac{3}{4}, \\Bold{Z}\\right]</script></html>'
            sage: out = backend.latex_formatter([1/2, x, 3/4, ZZ], concatenate=True)
            sage: out.html.get_str()
            '<html><script type="math/tex; mode=display">\\newcommand{\\Bold}[1]{\\mathbf{#1}}\\frac{1}{2} x \\frac{3}{4} \\Bold{Z}</script></html>'

        TESTS::

            sage: backend.latex_formatter([], concatenate=False).html.get_str()
            '<html><script type="math/tex; mode=display">\\newcommand{\\Bold}[1]{\\mathbf{#1}}\\left[\\right]</script></html>'
            sage: backend.latex_formatter([], concatenate=True).html.get_str()
            '<html><script type="math/tex; mode=display">\\newcommand{\\Bold}[1]{\\mathbf{#1}}</script></html>'
        """
        concatenate = kwds.get('concatenate', False)
        from sage.misc.html import html
        from sage.repl.rich_output.output_browser import OutputHtml
        return OutputHtml(html(obj, concatenate=concatenate))
Esempio n. 6
0
    def listen(self):
        """
        Listen to (or download) this wave file.

        Creates a link to this wave file in the notebook.
        """
        i = 0
        fname = 'sage%s.wav'%i
        while os.path.exists(fname):
            i += 1
            fname = 'sage%s.wav'%i

        self.save(fname)
        return html('<a href="cell://%s">Click to listen to %s</a>'%(fname, self._name))
Esempio n. 7
0
    def listen(self):
        """
        Listen to (or download) this wave file.

        Creates a link to this wave file in the notebook.
        """
        i = 0
        fname = 'sage%s.wav' % i
        while os.path.exists(fname):
            i += 1
            fname = 'sage%s.wav' % i

        self.save(fname)
        return html('<a href="cell://%s">Click to listen to %s</a>' %
                    (fname, self._name))
Esempio n. 8
0
    def search_print_row(self,exrow):
        r"""
        This is an helper function of ``Meg.search`` function to print the contents of a search.
        Not to be called by meg user.

        INPUT:

        - ``exrow`` -- an sqlite row structure_ where fields are accessible by name.

        OUTPUT:

        - html or text.

        NOTES:
            unicode is in utf-8 -> string
            http://en.wikipedia.org/wiki/ISO/IEC_8859-1
            Sage html() requires string.
        """
    
        sname = 'Exercise name %s' % exrow['owner_key'].encode('utf8')
        if is_notebook():
            html('<b>' + sname + ': </b><pre>' + exrow['problem_text'].encode('utf8') + '</pre><br/>')
        else:
            print sname + '\n' + exrow['problem_text'].encode('utf8') + '\n'
Esempio n. 9
0
def graph_editor(graph=None,
                 graph_name=None,
                 replace_input=True,
                 **layout_options):
    """
    Opens a graph editor in the Sage notebook.

    INPUT:

    - ``graph`` - a :class:`Graph` instance (default:
      graphs.CompleteGraph(2)); the graph to edit

    - ``graph_name`` - a string (default: None); the variable name to
      use for the updated instance; by default, this function attempts
      to determine the name automatically

    - ``replace_input`` - a boolean (default: True); whether to
      replace the text in the input cell with the updated graph data
      when "Save" is clicked; if this is False, the data is **still**
      evaluated as if it had been entered in the cell

    EXAMPLES::

        sage: g = graphs.CompleteGraph(3)
        sage: graph_editor(g)                       # not tested
        sage: graph_editor(graphs.HouseGraph())     # not tested
        sage: graph_editor(graph_name='my_graph')   # not tested
        sage: h = graphs.StarGraph(6)
        sage: graph_editor(h, replace_input=False)  # not tested
    """
    import sagenb.notebook.interact
    if graph is None:
        graph = graphs.CompleteGraph(2)

    if not EMBEDDED_MODE:
        return "This graph editor only runs in the Sage notebook."

    graph.layout(save_pos=True, **layout_options)

    if graph_name is None:
        graph_name = ''
        locs = sys._getframe(1).f_locals
        for var in locs:
            if id(locs[var]) == id(graph):
                graph_name = var

    cell_id = sagenb.notebook.interact.SAGE_CELL_ID

    # TODO: Put reasonable checks for large graphs, before disaster
    # occurs (i.e., breaks browser).

    close_button = r"""<button onclick="cell_delete_output(%(cell_id)s);">Close</button>""" % locals(
    )

    if replace_input:
        eval_strategy = r"""
    f += ' graph_editor(' + g[2] + ');'
    \$('#cell_input_%(cell_id)s').val(f);
    cell_input_resize(%(cell_id)s);
    evaluate_cell(%(cell_id)s, false);
""" % locals()
    else:
        eval_strategy = r"""
    saved_input = \$('#cell_input_%(cell_id)s').val();
    \$('#cell_input_%(cell_id)s').val(f);
    evaluate_cell(%(cell_id)s, false);
    \$('#cell_input_%(cell_id)s').val(saved_input);
    send_cell_input(%(cell_id)s);
    cell_input_resize(%(cell_id)s);
""" % locals()

    update_button = r"""<button onclick="
    var f, g, saved_input;
    g = \$('#iframe_graph_editor_%(cell_id)s')[0].contentWindow.update_sage();

    if (g[2] === '') {
        alert('You need to give a Sage variable name to the graph, before saving it.');
        return;
    }
    f = g[2] + ' = Graph(' + g[0] + '); ' + g[2] + '.set_pos(' + g[1] + '); '
    %(eval_strategy)s
">Save</button>""" % locals()

    graph_js = graph_to_js(graph)
    data_fields = """<input type="hidden" id="graph_data_%(cell_id)s" value="%(graph_js)s"><input type="hidden" id="graph_name_%(cell_id)s" value="%(graph_name)s">""" % locals(
    )

    return html(r"""<div id="graph_editor_%(cell_id)s"><table><tbody>
      <tr><td><iframe style="width: 800px; height: 400px; border: 0;" id="iframe_graph_editor_%(cell_id)s" src="/javascript/graph_editor/graph_editor.html?cell_id=%(cell_id)s"></iframe>%(data_fields)s</td></tr>
      <tr><td>%(update_button)s%(close_button)s</td></tr>
</tbody></table></div>""" % locals())
Esempio n. 10
0
    def display_immediately(self, plain_text, rich_output):
        r"""
        Show output without waiting for the prompt.

        INPUT:

        - ``plain_text`` -- instance of
          :class:`~sage.repl.rich_output.output_basic.OutputPlainText`. The
          plain text version of the output.

        - ``rich_output`` -- instance of an output container class
          (subclass of
          :class:`~sage.repl.rich_output.output_basic.OutputBase`). Guaranteed
          to be one of the output containers returned from
          :meth:`supported_output`, possibly the same as
          ``plain_text``.

        OUTPUT:

        This method does not return anything.

        EXAMPLES::

            sage: import sage.repl.rich_output.output_catalog as catalog
            sage: plain_text = catalog.OutputPlainText.example()
            sage: from sage.repl.rich_output.backend_sagenb import BackendSageNB
            sage: backend = BackendSageNB()
            sage: backend.display_immediately(plain_text, plain_text)
            Example plain text output
            sage: latex = catalog.OutputLatex.example()
            sage: backend.display_immediately(plain_text, latex)
            <html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}\int \sin\left(x\right)\,{d x}</script></html>
        """
        if isinstance(rich_output, (OutputPlainText, OutputAsciiArt)):
            rich_output.print_to_stdout()
        elif isinstance(rich_output, OutputLatex):
            print(rich_output.mathjax())
        elif isinstance(rich_output, OutputHtml):
            print(rich_output.with_html_tag())
        elif isinstance(rich_output, OutputImagePng):
            self.embed_image(rich_output.png, '.png')
        elif isinstance(rich_output, OutputImageGif):
            self.embed_image(rich_output.gif, '.gif')
        elif isinstance(rich_output, OutputImageJpg):
            self.embed_image(rich_output.jpg, '.jpg')
        elif isinstance(rich_output, OutputImagePdf):
            self.embed_image(rich_output.pdf, '.pdf')
        elif isinstance(rich_output, OutputImageSvg):
            self.embed_image(rich_output.svg, '.svg')
        elif isinstance(rich_output, OutputSceneJmol):
            rich_output.embed()
        elif isinstance(rich_output, OutputSceneThreejs):
            filename = graphics_filename(ext='.html')
            rich_output.html.save_as(filename)
            world_readable(filename)
            iframe = IFRAME_TEMPLATE.format(
                html='cell://' + filename,
                width=700,
                height=400,
            )
            from pretty_print import pretty_print
            pretty_print(html(iframe))
        elif isinstance(rich_output, OutputSceneCanvas3d):
            self.embed_image(rich_output.canvas3d, '.canvas3d')
        elif isinstance(rich_output, OutputVideoBase):
            self.embed_video(rich_output)
        else:
            raise TypeError(
                'rich_output type not supported, got {}'.format(rich_output))
Esempio n. 11
0
def graph_editor(graph=None, graph_name=None,
                 replace_input=True, **layout_options):
    """
    Opens a graph editor in the Sage notebook.

    INPUT:

    - ``graph`` - a :class:`Graph` instance (default:
      graphs.CompleteGraph(2)); the graph to edit

    - ``graph_name`` - a string (default: None); the variable name to
      use for the updated instance; by default, this function attempts
      to determine the name automatically

    - ``replace_input`` - a boolean (default: True); whether to
      replace the text in the input cell with the updated graph data
      when "Save" is clicked; if this is False, the data is **still**
      evaluated as if it had been entered in the cell

    EXAMPLES::

        sage: g = graphs.CompleteGraph(3)
        sage: graph_editor(g)                       # not tested
        sage: graph_editor(graphs.HouseGraph())     # not tested
        sage: graph_editor(graph_name='my_graph')   # not tested
        sage: h = graphs.StarGraph(6)
        sage: graph_editor(h, replace_input=False)  # not tested
    """
    if graph is None:
        graph = graphs.CompleteGraph(2)

    if not EMBEDDED_MODE:
        return "This graph editor only runs in the Sage notebook."

    graph.layout(save_pos = True, **layout_options)

    if graph_name is None:
        graph_name = ''
        locs = sys._getframe(1).f_locals
        for var in locs:
            if id(locs[var]) == id(graph):
                graph_name = var

    cell_id = sagenb.notebook.interact.SAGE_CELL_ID

    # TODO: Put reasonable checks for large graphs, before disaster
    # occurs (i.e., breaks browser).

    close_button = r"""<button onclick="cell_delete_output(%(cell_id)s);">Close</button>""" % locals()

    if replace_input:
        eval_strategy = r"""
    f += ' graph_editor(' + g[2] + ');'
    \$('#cell_input_%(cell_id)s').val(f);
    cell_input_resize(%(cell_id)s);
    evaluate_cell(%(cell_id)s, false);
""" % locals()
    else:
        eval_strategy = r"""
    saved_input = \$('#cell_input_%(cell_id)s').val();
    \$('#cell_input_%(cell_id)s').val(f);
    evaluate_cell(%(cell_id)s, false);
    \$('#cell_input_%(cell_id)s').val(saved_input);
    send_cell_input(%(cell_id)s);
    cell_input_resize(%(cell_id)s);
""" % locals()

    update_button = r"""<button onclick="
    var f, g, saved_input;
    g = \$('#iframe_graph_editor_%(cell_id)s')[0].contentWindow.update_sage();

    if (g[2] === '') {
        alert('You need to give a Sage variable name to the graph, before saving it.');
        return;
    }
    f = g[2] + ' = Graph(' + g[0] + '); ' + g[2] + '.set_pos(' + g[1] + '); '
    %(eval_strategy)s
">Save</button>""" % locals()

    graph_js = graph_to_js(graph)
    data_fields = """<input type="hidden" id="graph_data_%(cell_id)s" value="%(graph_js)s"><input type="hidden" id="graph_name_%(cell_id)s" value="%(graph_name)s">""" % locals()

    return html(r"""<div id="graph_editor_%(cell_id)s"><table><tbody>
      <tr><td><iframe style="width: 800px; height: 400px; border: 0;" id="iframe_graph_editor_%(cell_id)s" src="/javascript/graph_editor/graph_editor.html?cell_id=%(cell_id)s"></iframe>%(data_fields)s</td></tr>
      <tr><td>%(update_button)s%(close_button)s</td></tr>
</tbody></table></div>""" % locals())