Sunday, June 24, 2012

Code snippets in blogger

I have been experimenting with ways to post code snippets to this blog. Here are two strategies that seem to work:

Strategy 1.

Paste snippets to http://www.smipple.net, then embed them using the embed feature. You can log on to smipple using your google account.



Strategy 2.

Following the advice found here, I experimented with https://code.google.com/p/google-code-prettify/. I just embedded the following code after the meta tag of the html of this blog's template

<link href='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css' rel='stylesheet' type='text/css'/>
<script src='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js' type='text/javascript'/>
and this in the script tag

prettyPrint();

I've been testing this as I go, and I see that those snippets are overflowing the intended area. After looking in the code from the example, I see that I need to also add this to the css part of the blog's template (I stuck it right after the closing bracket for the .post-body entry:

pre.prettyprint {
overflow: auto;
}

Now, to embed code I can just type something like this:

<pre class="prettyprint lang-py">var i = 2 + 4;
</pre>


Using this system, our example snippet looks like this:

import numpy as np

def circmean(alpha,axis=None):
    mean_angle = np.arctan2(np.mean(np.sin(alpha),axis),np.mean(np.cos(alpha),axis))
    return mean_angle
    
def circvar(alpha,axis=None):
    if np.ma.isMaskedArray(alpha) and alpha.mask.shape!=():
        N = np.sum(~alpha.mask,axis)
    else:
        if axis is None:
            N = alpha.size
        else:
            N = alpha.shape[axis]
    R = np.sqrt(np.sum(np.sin(alpha),axis)**2 + np.sum(np.cos(alpha),axis)**2)/N
    V = 1-R
    return V

Neither works perfectly. You must re-insert the code into the html template each time you change the blog's layout. Constantly switching between blogger and smipple doesn't seem great, either...

Strategy 3.

Andrew gave me the idea of using github gists. Here is a test:

No comments: