Sunday, November 8, 2015

Some Additional Resources for CodeSkulptor

As we've seen before, Codeskulptor is a browser-based Python programming environment built by Scott Rixner that uses Skulpt to interpret/run python code in your browser.

Here are a few additional resources you can use:


The super() function is not implemented in CodeSkulptor (actually in Skulpt). Here's a Super class disguised as the super function you can use instead. This uses python 2's syntax of super(Classname, self).method(...)

from user40_oKHcLUHi2y_6 import super


The following imports a base64 encoder that, thanks to one of CodeSkulptor's unique libraries (simplegui), works at almost the same speed as an equivalent JavaScript function.

from user40_fLJEVmzz56qKjnu import base64
print base64("Kevin van Zonneveld")

Reading Text Data from Dropbox or Google Drive

One of the custom CodeSkulptor modules is codeskulptor, which includes a file2url function. This function takes as a parameter a CodeSkulptor filename, and converts it into a readable/downloadable url. The following functions are designed to work similarly, but for Dropbox and Google Drive instead. They will return a url that can be used with CodeSkulptor's urllib2.urlopen function.

To read a shared text file from Dropbox
Call this function, passing it the dropbox url of the shared text file.
def dropboxfile2url(url):
    url = url.replace("www.dropbox.","dl.dropboxusercontent.")
    return url
For example,
import urllib2
my_file = urllib2.urlopen(dropboxfile2url(url))
Reading a shared text file from Google Drive
Similarly, call this function and pass it a Google Documents url (if the text file has been shared).
def googlefile2url(url):
    url = url.replace("/edit","")
    baseurl = url.find("/",9)
    part1 = url.find("/",baseurl+1)
    part2 = url.find("/",part1+1)
    url = url.replace(url[part1:part2+1],"/export?format=txt&id=")
    return url
For example,
import urllib2
my_file = urllib2.urlopen(googlefile2url(url))

Data Permanence

The following store information to the cloud. The data will remain in the cloud permanently, or at least until the webservice clears the data.

You could, instead, set up your own server for data or database storage, but this is at your own risk and requires some knowledge and skills outside the scope of this post.
MIT App Inventor for Android provides an online public database service called TinyWebDB. By using the service provided by TinyWebDB, you can read/write a strings of data to the cloud.

App Inventor's TinyWebDB service has some limitations, but it provides instructions for running your own TinyWebDB service if you want privacy, or to not be bound by these limits.

According to the App Inventor for Android: TinyWebDB Service site:
NOTE: This service is being modified. It might go offline without notice
This service is only a demo. The database will store at most 250 entries; adding entries beyond that will cause the oldest entries to be deleted. Also, individual data values are limited to at most 500 characters.

Whether you wish to use MIT's public TinyWebDB database or run your own, the following code can be used to read and write data to the database:
from user40_z7IvquyR5AIkShD_0 import TinyWebDB

db = TinyWebDB(optional url for the TinyWebDB database)
a = db.read_cookie('test')
print a
db.write_cookie('test','this is cool')
print db.read_cookie('test')

Yahoo's Sherpa Storage using YQL
By using the power of Yahoo Query Language (YQL), we can store information to Yahoo's Sherpa Storage. One of the tables available in YQL is the csv table which manages data in a comma-separated values file. This pseudo-database DB class can be imported and saves "cookies" to Yahoo's Sherpa storage, with the following restrictions:
from user37_sy2hPG6N72tRcaz_0 import DB

#sets up access to a YQL storage
#if you don't pass a select and an update URL, 
#    the default store will be used
db = DB(optional YQL_store_select, optional YQL_store_update)

# db.ReadUserCookies(app_name,user)
#    read all cookies for a given app and user
# db.ReadCookie(app,user,cookie)
#    read a cookie for a given app, user, and cookie name
# db.ReadAppUsers(app,cookie)
#    read all users for a given app and cookie
# db.WriteCookie(app,user,cookie,value)
#    write a cookie for a given app, user, and cookie name

Friday, December 5, 2014

Some CodeSkulptor Tricks

As we've seen before, Codeskulptor is a browser-based Python programming environment built by Scott Rixner of Rice University, and uses Skulpt to interpret/run python code.

Codeskulptor screenshot

Since Skulpt's python interpreter switches back and forth between Javascript objects and Python objects, some pieces of python code have slightly different effects when run within the Codeskulptor enviromnent than they would if run in Python, and these differences can be used to create useful effects.

Reading the Console

One such useful effect comes from using the open keyword. This keyword uses the ids of the page's DOM elements as filenames, but these "files" are currently read-only.

Everytime you use the print keyword, the string is shown in the console (on the right-hand column of the screen). This function will read the contents of the console and return it as a string.

def readConsole():
    a = open("console")

Browser type detection

Another useful effect comes from using the file keyword. The open keyword uses file to find and return the contents of the DOM element whose id matches the "filename" being opened. However, if you call file directly, it returns an inmutable object of unknown type, which is actually a referrence to the Javascript window variable. Although this object is inmutable, dir is able to read its list of properties and methods.

This function is a moddified version of the browser-detection code used in Codeskulptor's simplegui module.

def browserPrefix():
    w = dir(file("code"))
    v = ['ms', 'moz', 'webkit', 'o'];
    z = ''
    for y in v:
        if y+"RequestAnimationFrame" in w:
            z += y
    if z=='': z='unknown'
    return z

Session cookies

This class uses file to set up a reference to the Javascript window variable. Then creates a simplegui Control class object with this reference to window. In combining these, the Control class is able to read and write to window.textContent. Since the window variable doesn't change when you re-run or reset the python code, window.textContent can be used to simulate session cookies.

import simplegui as sg
class SessionCookie:
    __init__ = type('',[])
    def __str__(self):
        return ""
    def setup():
        a = file("code")
        c = sg.Control(a)
        def rsc(a):
                b = a.get_text()
                return b
            except:return ' '
        return c
    __init__.setup = setup
    del setup
    def get_pos(c,name):
        t = c.get_text()
        r = t.find(" "+name+"=")
        if (r==-1): return [-1,-1,-1,t]
            s = r + len(name) + 2
            p = t.find(";",s)
            return [r,s,p,t]
    __init__.get_pos = get_pos
    del get_pos
    def get(self,name=None):
        if name==None:
            name = self
        self = SessionCookie.__init__
        a = self.get_pos(self.setup(),str(name))
        if (a[0]==-1): return 'None'
        else: return a[3][a[1]:a[2]]
    def set(self,name,value=None):
        if value==None:
            name,value = self,name
        self = SessionCookie.__init__
        a = self.get_pos(self.setup(),str(name))
        if (a[0]==-1): v = a[3]+" "+str(name)+"="+str(value)+";"
            v = a[3][0:a[0]]+a[3][a[2]+1:len(a[3])]+" "+str(name)+"="+str(value)+";"

Set an Unload Handler for a simplegui Frame

By default, when the user closes the simplegui popup window, the code is not notified of this event. This sometimes results in background audio that continues to play until the "reset" button is clicked. This function appends a set_unload_hander method to simplegui's Frame class. Any frames created after this automatically include this method. In this way, you can define a function to be called when the user closes the popup window.

def simplegui_frame_set_unload_handler(self,hand):
    def unload_timer_check():
        def gct():
                return self.get_canvas_textwidth("t",12)
                return 0
        t = gct()
        if t==0:
    self.unload = simplegui.create_timer(1000,unload_timer_check)
simplegui.Frame.set_unload_handler = simplegui_frame_set_unload_handler

Include these functions in you code

These functions can all be seen working here:

To include these in your own projects, you can use import user28_SWD5iUaoIAQvHpx_1 in your code. Here's an example of the unload handler in use:

Sunday, December 8, 2013

How to Run Codeskulptor Python Programs on your own Page

Codeskulptor is a browser-based Python programming environment built by Scott Rixner of Rice University and is used in his An Introduction to Interactive Programming in Python class on Coursera.

Codeskulptor screenshot

In order to make the programming environment easy to use, Codeskulptor implements, among other things, a "simplegui" module which makes it easier to build interactive programs in the browser. The module is written in JavaScript and can therefore not be used in python projects outside of Codeskultor.

However, since CodeSkulptor is based on Skulpt and JavaScript, it should be possible to use these to run CodeSkulptor-specific interactive programs on your own website.

First, we visit Skulpt and copy the code under the heading "Getting Started". What we mostly need is all the code inside the <body> </body> tags.

<script type="text/javascript">
// output functions are configurable.  This one just appends some text
// to a pre element.
function outf(text) {
   var mypre = document.getElementById("output");
   mypre.innerHTML = mypre.innerHTML + text;
function builtinRead(x) {
   if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
           throw "File not found: '" + x + "'";
   return Sk.builtinFiles["files"][x];
// Here's everything you need to run a python program in skulpt
// grab the code from your textarea
// get a reference to your pre element for output
// configure the output function
// call Sk.importMainWithBody()
function runit() {
  var prog = document.getElementById("yourcode").value;
  var mypre = document.getElementById("output");
  mypre.innerHTML = '';
  Sk.canvas = "mycanvas";
  Sk.pre = "output";
  Sk.configure({output:outf, read:builtinRead});
<h3>Try This</h3>
<textarea id="yourcode" cols="40" rows="10">import turtle
t = turtle.Turtle()
print "Hello World"
</textarea><br />
<button type="button" onclick="runit()">Run</button>
<pre id="output" ></pre>
<!-- If you want turtle graphics include a canvas -->
<canvas id="mycanvas" ></mycanvas>

Second, we head over to Codeskulptor, and get a copy of the JavaScript include files there (to use in place of the ones used in Skulpt). As of this writing, the current list of included JavaScript files are

 <script src=""></script>
 <script src=""></script>
 <script src=""></script>
 <script src=""></script>
 <script src=""></script>
 <script src=""></script>
 <script src=""></script>
 <script src=""></script>
 <script src=""></script>
 <script src=""></script>

Ideally, you probably should copy those files to your own server (in case they change in the future), but you can, instead, just include those same JavaScript files on your own page, preferably in the header.

(There is one other JavaScript file include in Codeskulptor
<script src=""></script>
but you don't need this one because it is part of CodeMirror's code to syntax-color the code.)

Then use the HTML+JavaScript code copied from Skulpt on your page.

Don't forget to put your python code as the contents of the textarea.

To see this in action, see here or at here.

Monday, August 26, 2013

View Feed in Feedly Bookmarklet or Instructions

If, when clicking an RSS feed, you find yourself looking at a page full of code like this:

You can use the following bookmarklet to view the current feed in Feedly.

(Tested in Chrome version 29.0.1547.57)

View in Feedly

The code for the bookmarklet is:*):\/\//,'$1://'));

If, instead, you use the RSS Subscription Extension (by Google) and would like to add Feedly to your list of available feed readers, you can

• click Manage...

• Then Add...

• give it a description and use the following for the URL

• Dont' forget to [Save] and you're ready to go!

Happy reading! Meebo-smile.gif