logo4 Evolution is progress—                          
progress is creativity.        
vline

Creole macro to display sage single cell server results

Synonyms: Sage single cell server macro

The sage single cell server is a convenient open source solution to add to interactive mathematical functionality to a web page. It is demonstrated here. The documentation can be found here.

Introduction

Problem

The problem when integrating a sage cell into a Creole macro arises with the fact that sage cells requires extra content included into the <head> ... </head> section, JQuery source scripts. As for performance reasons it is not recommended to include those JQuery scripts into all web pages, we need a way to define an Django {% block extrahead %} block to include the source depending on the presence of the sage cell macro.

Two main possibilities exist to add that functionality into the currently running Creole macro Django framework.

  1. The Creole parser not only creates the text to be included into the <body> ... </body> section but also into the <head> ... </head>. Thus a call of the Creote parser would return a tupel (head,body) to be included by two different variables into the template. That functionality has to be programmed into the both the creole macro interpreter (maybe by the macro environment variable can be used for that purpose) and the view. The view has to receive the parsed head and body html content separately and assign it to different template variables.
  2. A filter has to be written that searches the Creole text for {% block extrahead %} relevant macros.

I opted for the latter solution as it leaves my present code virtually unchanged. The Creole parser is called by the template through a filter already and not implemented in the views.

Solution

The new filter is named creolehead. It uses creole's macro definition though the start end end tokens have to be set during initialization. Also the dictionary of installed macros is searched for the macro name to avoid mistyped macros causing errors.

@register.filter
def creolehead(value):
    extrahead = []
    macro_dict = z = dict(non_bodied_macros.items() + bodied_macros.items())
    macro = Macro('',('<<','>>'),func=None, macros={}, arg_parser= '')
    pattern = re.compile(macro.re_string(),re.DOTALL)
    for m in pattern.finditer(value):
        macro_name = m.groupdict()['name']
        if macro_name in macro_dict:
            macro_modul = macro_dict[macro_name]
            import importlib
            try:
                macro = importlib.import_module('fauceir.myparser.macros.%s' % macro_modul.__name__)
                extrahead += macro.head()
            except:
                pass
                # if there is no head defined simply do nothing
    return "\n\t\t".join(list(set(extrahead)))

This filter will be called from the extrahead block of the template. Don't forget to turn autoescape off as the filter returns pure html

{% block extrahead %}
	{% autoescape off %}
	{{ content|creolehead }}
	{% endautoescape %} 
{% endblock %}

Next each macro that wants to set a extra head information has to provide a head() function. As in my creole parser every macro resides in its own module the head function is simply an other function added to the file. This example shows the head function that provides the CSS data for the pygments code macro used on this page

def head():
    return ["""<link href="/static/css/code.css" rel="stylesheet" type="text/css" />""",]

The Sage cell macro

The macro code is shown below. To allow the several option that the sage cell server offers the java script is included in the body section and commented out. Not all options are implemented.

inputLocation
If multiple cells reside on the same page a unique id has to be given each of them.
template
It probably makes no sense to change the template as this feature is poorly documented and the editor is hidden anyway.
evalButtonText
This is a fancy option to change the evaluation botton.
lang
This parameter accepts a comma separated quoted list like this lang="sage,gap,gp,html,maxima,octave,python,r,singular". The example below include python, sage, and r. The most frequently used languages throughout this website.
import genshi

def head():
    return  ["""<script src="http://sagecell.sagemath.org/static/jquery.min.js"></script>
<script src="http://sagecell.sagemath.org/embedded_sagecell.js"></script>
             """]
            
def sagecell(macro,environ,inputLocation='sagecell',template='sagecell.templates.minimal',
             evalButtonText='Click to start', lang='sage'):
       
    langs = "[" +  ",".join("'" + item + "'" for item in (l.strip() for l in lang.split(','))) + "]"
    script="""<script>
<!--
$(function () {
    sagecell.makeSagecell({inputLocation:  '#%s',
                           template:       %s,
                           evalButtonText: '%s',
                           languages:      %s,
                           hide:           ["editor","permalinks", "done"]});
});
//-->
</script>
""" % (inputLocation,template,evalButtonText,langs)
    cell="""<div id="%s">
    <script type="text/x-sage">
%s    
    </script>
</div>
""" % (inputLocation,macro.body)
    return genshi.core.Markup(script+cell)

Now click the start button to open the cell and run the little demonstration program.

If multiple languages are given a selector is offered. Slecting 'r' wil cause an immediate error as the labguage is incompatible with 'r'. Also if selected python the cell is correctly displayed but moving the slider causes an error as the power function defined in sage is not valid in python.

The code used for this little demonstration is as follows.

@interact
def f(n=(0,10)):
    print 2^n

More examples and demonstration can be found on these sage websites Graphic Tour and Interact Wiki.


Tags: Software


Categories: Software

 
   

(c) Mato Nagel, Weißwasser 2004-2013, Disclaimer