<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><atom:link rel="hub" href="http://tumblr.superfeedr.com/" xmlns:atom="http://www.w3.org/2005/Atom"/><description>
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

try {
var pageTracker = _gat._getTracker("UA-11923739-2");
pageTracker._trackPageview();
} catch(err) {}</description><title>Hasen el Judy</title><generator>Tumblr (3.0; @hasenj-dev)</generator><link>http://dev.hasenj.org/</link><item><title>Interesting hack to create html templates in javascript</title><description>&lt;p&gt;&lt;em&gt;Edit: various people pointed out that this trick is non-standard and not guaranteed to work across browsers, for instance, Firefox. So take this only as an interesting hack .. &lt;strong&gt;don&amp;#8217;t use it in production&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In a quest to have &amp;#8220;reusable&amp;#8221; knockout.js components, I asked on the mailing list if anyone has had any experience dealing with the problem of packaging the templates.&lt;/p&gt;

&lt;p&gt;To distribute your HTML templates for reusability, they are usually written in html files and are meant to be included in your main html file using some server side technology, so for example if you&amp;#8217;re using flask/jinja2 you&amp;#8217;d use the include tag: &lt;code&gt;{% include 'ko_widget.html' %}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This obviously is not ideal.&lt;/p&gt;

&lt;p&gt;At first, I came up with a solution (that now I see is rather crappy) that revolves around a compiler script that crates a little javascript file that will recreate the template and insert it to the DOM using the &lt;code&gt;document.body.insertAdjacentHTML&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;This is the core of it. Very simple. Takes html content, returns javascript:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def process_content(content):
    js_content = json.dumps(content)
    return "document.body.insertAdjacentHTML('beforeend', {0})".format(js_content)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But then someone showed me a different approach: a magic way to include html snippets in javascript. Actually it&amp;#8217;s a hack to create multiline strings.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/xdenser/kc-tree-habr/blob/master/tree.js#L106" target="_blank"&gt;https://github.com/xdenser/kc-tree-habr/blob/master/tree.js#L106&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It&amp;#8217;s amazing what this can do:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function hereDoc(f) {
  return f.toString().
      replace(/^[^\/]+\/\*!?/, '').
      replace(/\*\/[^\/]+$/, '');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This function will extract the text content of block comments inside a function definition and return it as a string!&lt;/p&gt;

&lt;p&gt;So like &amp;#8230;.. you can create a multiline string like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var mlstring = hereDoc(function() {
    /*
        This is a multiline string ..
        Really .. it is!

        it also contains html:

            &amp;lt;a href="http://google.com"&amp;gt;Google&amp;lt;/a&amp;gt;
    */
    })
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Printing the content of &lt;code&gt;mlstring&lt;/code&gt; in the Chrome console:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; mlstring
"
            This is a multiline string ..
            Really .. it is!

            it also contains html:

                &amp;lt;a href="http://google.com"&amp;gt;Google&amp;lt;/a&amp;gt;
        "
&lt;/code&gt;&lt;/pre&gt;

&lt;h1&gt;Building on this&lt;/h1&gt;

&lt;p&gt;I created a function that takes a multiline string in this way and then wraps it in a script tag (with type set to text/tempalte), then sets a unique (random) id to this tag, then inserts it to the dom (or if the dom is not ready, waits for the dom to get ready then does the insertion) and return the generated id.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/**
    Takes a namespace and a function who's inside is a comment containing the content of an html template.

    Generates a randomized id (based on the name space, i.e 'template..random.digits'

    Returns the id

    Guarantees the templates gets inserted into the dom: either now or when it's ready (if the page is still loading).
 */
insertTemplate = function(namespace, f) {
    if(!namespace) { namespace = 'generic'; }
    var text = hereDoc(f);
    var random = (Math.random() * 9000).toFixed(0);
    var timestamp = (new Date()).getTime();
    var id = "template." + namespace + "." + random + "." + timestamp;

    var node = document.createElement("script");
    node.setAttribute("id", id);
    node.setAttribute("type", "text/template");
    node.innerHTML = text;

    var insertNode = function() {
        console.log("Inserting template");
        document.body.appendChild(node);
    }

    // insert node now or when body is loaded
    if(document.readyState == "loading") {
        document.onreadystatechange = function () {
            if (document.readyState == "interactive") {
                insertNode();
            }
        }
    } else {
        insertNode();
    }

    return id;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So now with this, it&amp;#8217;s possible to include the html templates inside the javascript files. This should make it easier to package and distributes knockout.js based components.&lt;/p&gt;</description><link>http://dev.hasenj.org/post/50641574521</link><guid>http://dev.hasenj.org/post/50641574521</guid><pubDate>Fri, 17 May 2013 02:41:00 -0600</pubDate></item><item><title>Experimental "ajax" library</title><description>&lt;p&gt;Lately I&amp;#8217;ve been feeling like jQuery is becoming rather obsolete for me.&lt;/p&gt;

&lt;p&gt;It used be a great library for dom manipulation, but for doing a real interactive UI, knockout.js is much better.&lt;/p&gt;

&lt;p&gt;It also used to be great for abstracting away the different way to send asynchronous requests (aka ajax calls) in various browsers, but now that I don&amp;#8217;t care about IE anymore, this abstraction is not needed all that much.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;m not saying that jQuery is &lt;em&gt;completely&lt;/em&gt; obsolete. I&amp;#8217;m saying that I&amp;#8217;d prefer if I don&amp;#8217;t have to include it &lt;em&gt;just&lt;/em&gt; for its ajax function.&lt;/p&gt;

&lt;p&gt;If I need to do some neat UI effects, sure, I&amp;#8217;ll use jQuery. But I&amp;#8217;d rather not include it or depend on it if I don&amp;#8217;t have to. If I only want a simple ajax library, I&amp;#8217;d rather not include jQuery.&lt;/p&gt;

&lt;p&gt;Actually even an ajax library is not really terribly necessary. If you target only modern browsers (Chrome and Firefox) you can use the &lt;code&gt;XMLHttpRequest&lt;/code&gt; api directly, it&amp;#8217;s simple and straight forward.&lt;/p&gt;

&lt;p&gt;If one was to write an ajax library (now), it should be simple, very simple, designed to handle 90% of the use cases. There&amp;#8217;s no need to add any complexity to make it more flexible; if you ever need more control over your ajax requests, just use XMLHttpRequest directly.&lt;/p&gt;

&lt;p&gt;So, what would make for a nice-to-use ajax api? Well first of all it should not include the term &amp;#8220;ajax&amp;#8221; or &amp;#8220;xml&amp;#8221;, because it&amp;#8217;s not about xml; it&amp;#8217;s about asynchronous requests, and the format is json most of the time.&lt;/p&gt;

&lt;p&gt;A few methods with names like &amp;#8220;get&amp;#8221; or &amp;#8220;post&amp;#8221; to create the request object:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;requests.get("/data")
requests.post("/messages")
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This would not send the request yet; just create the request object. Then more things about the request can be specified via methods that can be chained together.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;.params(json)&lt;/code&gt; sets the arguments in the request url, for instance:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;requests.get("/contacts").params( { "page": 10 } )
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;would set the request url to &lt;code&gt;/contacts?page=10&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;.data(json)&lt;/code&gt; sets the json data to be sent (for PUT/POST/PATCH requests).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;requests.post("/messages").data( { contact_id: 3423, text: "See you soon" });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;.header(name, value)&lt;/code&gt; sets a request header&lt;/p&gt;

&lt;p&gt;&lt;code&gt;.success(fn)&lt;/code&gt; adds a success callback&lt;/p&gt;

&lt;p&gt;&lt;code&gt;.error(fn)&lt;/code&gt; adds an error callback&lt;/p&gt;

&lt;p&gt;&lt;code&gt;.complete(fn)&lt;/code&gt; adds a complete callback&lt;/p&gt;

&lt;p&gt;&lt;code&gt;.send()&lt;/code&gt; actually sends the request.&lt;/p&gt;

&lt;p&gt;The success/error/complete callbacks will receive one parameter: the native &amp;#8220;xhr&amp;#8221; object, which has a &amp;#8220;response&amp;#8221; field that can be used to read the response (and a &amp;#8220;responseType&amp;#8221; field that can be used to check if the response is json or not).&lt;/p&gt;

&lt;p&gt;However like I said I don&amp;#8217;t like to call it &amp;#8220;xhr&amp;#8221;; I prefer to call it &amp;#8216;areq&amp;#8217;, as in &amp;#8220;async request&amp;#8221;.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s what I have so far in a gist: &lt;a href="https://gist.github.com/hasenj/5378660" target="_blank"&gt;https://gist.github.com/hasenj/5378660&lt;/a&gt;&lt;/p&gt;</description><link>http://dev.hasenj.org/post/47866158090</link><guid>http://dev.hasenj.org/post/47866158090</guid><pubDate>Sat, 13 Apr 2013 08:53:00 -0600</pubDate></item><item><title>setTimeout for python</title><description>&lt;p&gt;In Javascript, there&amp;#8217;s a function you can call to execute some function in the future:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;setTimeout(fn, delayMillis)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will call &lt;code&gt;fn()&lt;/code&gt; after &lt;code&gt;delayMillis&lt;/code&gt; milliseconds.&lt;/p&gt;

&lt;p&gt;To get a similar functionality in python, we need first to install a package &lt;code&gt;apscheduler&lt;/code&gt;, then we can implement a similar functionality like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;from apscheduler.scheduler import Scheduler
import datetime as dt

sched = Scheduler()
sched.start()

def timeout(job_fn, *fn_args, **delta_args):
    """Like setTimeout in javascript; returns a job object

    First argument is the function to be called.

    Positional arguments will be passed to the function when it's called.

    Keyword arguemnts will be passed to datetime.timedelta

    Usage:
        # calls `fn()` after 3 seconds
        timeout(fn, seconds=3)

        # calls `fn(foo, bar)` after 10 seconds
        timeout(fn, foor, bar, seconds=10)
    """
    time = dt.datetime.now() + dt.timedelta(**delta_args)
    return sched.add_date_job(job_fn, time, fn_args)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here, the function timeout works sort of like setTimeout, but the delay must be specified using keyword arguments; it accepts the same things that are accepted by &lt;a href="http://docs.python.org/2/library/datetime.html#datetime.timedelta" target="_blank"&gt;datetime.timedelta&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For instance:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def hello(): print "Hello"

timeout(hello, seconds=4)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The thing about this though, is you have to keep the program from quitting. Unlike node.js, the python script &lt;em&gt;will&lt;/em&gt; quit when it reaches the end of the script, even if you have scheduled delayed functions.&lt;/p&gt;

&lt;p&gt;If you are running a web server, you don&amp;#8217;t need to do anything as the web server will continue running for ever (listening for incoming connections).&lt;/p&gt;

&lt;p&gt;Otherwise, you need to somehow block or sleep.&lt;/p&gt;

&lt;p&gt;The simplest way to do that is &lt;code&gt;time.sleep&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;Simplest example:&lt;/h3&gt;

&lt;p&gt;Here&amp;#8217;s a simple example.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def hello_spam(): 
    print "Hello"
    timeout(hello_spam, seconds=3)

hello_spam()

import time
time.sleep(10)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will print &amp;#8220;Hello&amp;#8221; about four times and then die.&lt;/p&gt;

&lt;h3&gt;Additional arguments&lt;/h3&gt;

&lt;p&gt;You can also pass additional arguments to the function you want to call.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def hello_spam(name): 
    print "Hello {0}".format(name)
    timeout(hello_spam, name, seconds=1)

hello_spam("Dude")
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Positional arguments to timeout are going to be passed to the function you&amp;#8217;re delaying.&lt;/p&gt;

&lt;p&gt;Notice that this means if you do this: &lt;code&gt;timeout(fn, 2000)&lt;/code&gt; expecting that you&amp;#8217;ll call &lt;code&gt;fn&lt;/code&gt; after 2 seconds, you would be making a mistake. You&amp;#8217;re telling timeout to call &lt;code&gt;fn(2000)&lt;/code&gt; but you&amp;#8217;re not telling &lt;em&gt;when&lt;/em&gt; you want that call to happen. It will freak out and raise an exception.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s the demo file on a gist: &lt;a href="https://gist.github.com/hasenj/5352608" target="_blank"&gt;https://gist.github.com/hasenj/5352608&lt;/a&gt;&lt;/p&gt;</description><link>http://dev.hasenj.org/post/47607493869</link><guid>http://dev.hasenj.org/post/47607493869</guid><pubDate>Wed, 10 Apr 2013 01:46:00 -0600</pubDate><category>tips</category></item><item><title>Back to SQL</title><description>&lt;p&gt;For the past year or two I was trying to jump around from one nosql system to another. I was unsatisfied with traditional relational database systems, and looking for something more flexible. My main annoyance with sql databases was this:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;The data format is rigid, and migrations are annoying.&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;Really. That&amp;#8217;s it. That was my only complaint. At the time I didn&amp;#8217;t realize it of course; I thought that &amp;#8220;migrations are annoying&amp;#8221; is a genuine reason to hate SQL.&lt;/p&gt;

&lt;p&gt;Well, it kinda is, &lt;em&gt;if&lt;/em&gt; there was an alternative system that has all the benefits/usefulness of SQL but without the annoyance of migrations. And that&amp;#8217;s what I thought I would get from the nosql systems. But it turned out that each system has its own set of annoyances, and sometimes they are much worse than the migrations annoyance.&lt;/p&gt;

&lt;p&gt;At the end of the day, it turns out that it&amp;#8217;s much easier to develop for SQL databases, simply because:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;They&amp;#8217;ve been around longer, so they&amp;#8217;re more mature, and there exists mature and full-featured ORMs/libraries for them.&lt;/li&gt;
&lt;li&gt;They provide a flexible and powerful declarative querying language (the &lt;em&gt;whole&lt;/em&gt; point of SQL: structured querying language).&lt;/li&gt;
&lt;li&gt;Imposing a structure on your data is actually a good thing. It offloads some of the cognitive effort which you&amp;#8217;d otherwise have to carry around in your head all the time.&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;While migrations are annoying, you just have to learn to deal with it and come up with a personal system for yourself to make it as routine and mindless as possible.&lt;/p&gt;</description><link>http://dev.hasenj.org/post/47605966247</link><guid>http://dev.hasenj.org/post/47605966247</guid><pubDate>Wed, 10 Apr 2013 00:55:00 -0600</pubDate><category>sql</category><category>nosql</category><category>web-development</category></item><item><title>Adding web sockets to Flask apps</title><description>&lt;p&gt;This is a walkthrough for integrating push sockets with a Flask app using gevent-socketio&lt;/p&gt;

&lt;p&gt;I will try my best to make this tutorial short and sweet and to the point. No fluff. Only the bare minimum. I won&amp;#8217;t bother explaining what everything means (partly because even I haven&amp;#8217;t completely wrapped my head around all of it)&lt;/p&gt;

&lt;p&gt;You will find a git repository with each commit documenting a step in this walkthrough here: &lt;a href="https://bitbucket.org/hasenj/flask-sockets-tutorial" target="_blank"&gt;https://bitbucket.org/hasenj/flask-sockets-tutorial&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That repo is a very simple flask app: a page that receives push messages from the server and displays these messages as they arrive (in real time).&lt;/p&gt;

&lt;p&gt;The server will listen for shouts on &lt;code&gt;/shout?msg=&lt;/code&gt;, and  broadcast each shout/msg to all connected clients.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; I&amp;#8217;m not an expert on the subject. I wrote this because I wanted to do a simple thing (send a message over a socket from inside a flask request handler) but the information on the net was scattered and I wanted to just get to the core of it and get the smallest possible example working.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note2:&lt;/strong&gt; The example here only works with one server instance. If you run multiple instances of the server, it won&amp;#8217;t really work as expected. For multiple-server setups, people usually use some kind of a message queue or a redis server to act as a central server that can notify all instances of the app server of what message to send over what socket.&lt;/p&gt;

&lt;p&gt;With that cleared out of the way, let&amp;#8217;s proceed.&lt;/p&gt;

&lt;h2&gt;1. Setup a basic Flask project&lt;/h2&gt;

&lt;p&gt;Commit: &lt;a href="https://bitbucket.org/hasenj/flask-sockets-tutorial/commits/eb524632b66a608edbeb01032322b7f8" target="_blank"&gt;https://bitbucket.org/hasenj/flask-sockets-tutorial/commits/eb524632b66a608edbeb01032322b7f8&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is very simple and there isn&amp;#8217;t much to it. If you&amp;#8217;ve worked with virtualenv, Flask and jQuery before, everything here should make perfect sense.&lt;/p&gt;

&lt;p&gt;Source the venv_init.sh file to initialize your virtual environment and install flask:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; source venv_init.sh
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then run the server with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;python main.py
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The server is now running on &lt;a href="http://localhost:6020" target="_blank"&gt;http://localhost:6020&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;main.js&lt;/code&gt;, we have a Javascript function &lt;code&gt;addMessage&lt;/code&gt; that receives a string and adds it to the screen. This is the function that we will call when we receive messages through the push socket.&lt;/p&gt;

&lt;p&gt;Try it! Open the Javascript console on your browser and run:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;addMessage("Hello");
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You should see the word &amp;#8220;Hello&amp;#8221; in big orange-ish color. Try it again, and the new message will appear on top of the &amp;#8220;Hello&amp;#8221;. The idea being, as the page receives messages, it will stack them on top of each other just like that.&lt;/p&gt;

&lt;h2&gt;2. Add socket.io to the client and server&lt;/h2&gt;

&lt;p&gt;Commit: &lt;a href="https://bitbucket.org/hasenj/flask-sockets-tutorial/commits/188ea626622dff233452baeae0a09873" target="_blank"&gt;https://bitbucket.org/hasenj/flask-sockets-tutorial/commits/188ea626622dff233452baeae0a09873&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Socket.io is a library that make working with sockets easier.&lt;/p&gt;

&lt;p&gt;I grabbed the Javascript client from here:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;curl &lt;a href="https://raw.github.com/LearnBoost/socket.io-client/0.9.11/dist/socket.io.min.js" target="_blank"&gt;https://raw.github.com/LearnBoost/socket.io-client/0.9.11/dist/socket.io.min.js&lt;/a&gt; &amp;amp;gt; static/socket.io.js
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For the server, we&amp;#8217;ll use &lt;code&gt;gevent-socketio&lt;/code&gt;. Install it via pip (while the virtual environment is active!) and don&amp;#8217;t forget to add it requirements.txt&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;pip install gevent-socketio
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We have to switch the server from the built-in flask server to a gevent server. &lt;code&gt;gevent-socketio&lt;/code&gt; comes with the &lt;code&gt;SocketIOServer&lt;/code&gt; function that helps glue things together.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;app.debug = True
port = 6020
SocketIOServer(('', port), app, resource="socket.io").serve_forever()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;However, this will lose the auto reloading. Luckily, werkzeug has a &lt;code&gt;run_with_reloader&lt;/code&gt; decorator that can help us here:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@werkzeug.serving.run_with_reloader
def run_dev_server():
    app.debug = True
    port = 6020
    SocketIOServer(('', port), app, resource="socket.io").serve_forever()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So now our &amp;#8220;main&amp;#8221; entry just calls run_dev_server:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if __name__ == "__main__":
    run_dev_server()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Also, and this is &lt;em&gt;very&lt;/em&gt; important, we have to call &lt;code&gt;gevent.monkey.patch_all()&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;from gevent import monkey
# ..
monkey.patch_all()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I placed it at the top.&lt;/p&gt;

&lt;h2&gt;3. Setting up the socket endpoint on the server&lt;/h2&gt;

&lt;p&gt;Commit: &lt;a href="https://bitbucket.org/hasenj/flask-sockets-tutorial/commits/192eb79c5ba0e3ead19a59075c38e18b2145e57d" target="_blank"&gt;https://bitbucket.org/hasenj/flask-sockets-tutorial/commits/192eb79c5ba0e3ead19a59075c38e18b2145e57d&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When a client connects to a socket.io enabled server, it will always go to &lt;code&gt;/socket.io/&lt;/code&gt;. Even though you may never explicitly visit this url on the client side, this is where it goes when you connect to the server using socket.io.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@app.route('/socket.io/&amp;lt;path:rest&amp;gt;')
def push_stream(rest):
    try:
        socketio_manage(request.environ, {'/shouts': ShoutsNamespace}, request)
    except:
        app.logger.error("Exception while handling socketio connection",
                     exc_info=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Please note that we ignore the &lt;code&gt;rest&lt;/code&gt; parameter. It&amp;#8217;s something that socket.io takes care of.&lt;/p&gt;

&lt;p&gt;The function &lt;code&gt;socketio_manage&lt;/code&gt; takes care of setting up the socket for that connection. The second argument maps &amp;#8220;urls&amp;#8221; to &amp;#8220;namespace classes&amp;#8221;.&lt;/p&gt;

&lt;p&gt;You can think of the url as a channel, and the namespace class manages sockets in that channel.&lt;/p&gt;

&lt;p&gt;Read the docs: &lt;a href="https://gevent-socketio.readthedocs.org/en/latest/namespace.html" target="_blank"&gt;https://gevent-socketio.readthedocs.org/en/latest/namespace.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The important bit in the following code is that we&amp;#8217;re adding each new socket to a list that can be accessed globally (as a class variable) and we add a class method that can broadcast a message to all connected sockets:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class ShoutsNamespace(BaseNamespace):
    sockets = {}
    def recv_connect(self):
        print "Got a socket connection" # debug
        self.sockets[id(self)] = self
    def disconnect(self, *args, **kwargs):
        print "Got a socket disconnection" # debug
        if id(self) in self.sockets:
            del self.sockets[id(self)]
        super(ShoutsNamespace, self).disconnect(*args, **kwargs)
    # broadcast to all sockets on this channel!
    @classmethod
    def broadcast(self, event, message):
        for ws in self.sockets.values():
            ws.emit(event, message)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The methods &lt;code&gt;recv_connect&lt;/code&gt; and &lt;code&gt;disconnect&lt;/code&gt; are called by the socketio framework. We&amp;#8217;re overriding them to hook into events so that when a new client is connected, we add its socket to the list, and when it disconnects, we remove its socket from the list.&lt;/p&gt;

&lt;p&gt;Note: the method &lt;code&gt;disconnect&lt;/code&gt; does some necessary work behind the curtains, so it&amp;#8217;s important to call the same method on the superclass!&lt;/p&gt;

&lt;p&gt;Now we have things setup so that when clients connect to a socket on &amp;#8220;/shouts&amp;#8221;, we can broadcast something to all of them by calling &lt;code&gt;ShoutsNamespace.broadcast&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;4. Connect the client to the server&lt;/h2&gt;

&lt;p&gt;Commit: &lt;a href="https://bitbucket.org/hasenj/flask-sockets-tutorial/commits/d158b2214120bcfcef41e038e39eeeaeca053771" target="_blank"&gt;https://bitbucket.org/hasenj/flask-sockets-tutorial/commits/d158b2214120bcfcef41e038e39eeeaeca053771&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The client side code is probably the simplest part in all of this. Simply call &lt;code&gt;io.connect('/shouts');&lt;/code&gt; to get a socket object, then write some event handlers on the socket.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$(document).ready(function() {
    var socket = io.connect('/shouts');
    socket.on('connect', function() {
        console.log("socket connected");
    });
    socket.on('disconnect', function() {
        console.log("socket disconnected");
    });

    socket.on('message', function(data) {
        console.log("Got message:", data);
        addMessage(data);
    });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The important thing here is the &amp;#8216;message&amp;#8217; event handler: it calls our function &lt;code&gt;addMessage&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In this case, we&amp;#8217;re expecting &amp;#8216;data&amp;#8217; (the thing sent over the socket) to be a string. This is not a limitation! It can be a complex nested JSON object. I&amp;#8217;m just using strings here to make things simple.&lt;/p&gt;

&lt;h2&gt;5. Broadcast messages from the server to the client&lt;/h2&gt;

&lt;p&gt;Commit: &lt;a href="https://bitbucket.org/hasenj/flask-sockets-tutorial/commits/9e2e854a46e1a8bc233dc5e879795db40ef00550" target="_blank"&gt;https://bitbucket.org/hasenj/flask-sockets-tutorial/commits/9e2e854a46e1a8bc233dc5e879795db40ef00550&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We&amp;#8217;ll create the shout endpoint:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@app.route("/shout", methods=["GET"])
def say():
    message = request.args.get('msg', None)
    if message:
        ShoutsNamespace.broadcast('message', message)
        return Response("Message shouted!")
    else:
        return Response("Please specify your message in the 'msg' parameter")
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This allows anyone to shout a message via the &lt;code&gt;/shouts&lt;/code&gt; end point.&lt;/p&gt;

&lt;p&gt;Try it yourself! Open &lt;a href="http://localhost:6020/shout?msg=PushIt" target="_blank"&gt;http://localhost:6020/shout?msg=PushIt&lt;/a&gt; in a new window and watch the main page get updated instantaneously! Open several pages and then shout a message again, and behold as they all updated in real time!&lt;/p&gt;

&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;In this tutorial we did the following:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;Change the flask app setup to use the SocktIOServer &lt;/li&gt;
&lt;li&gt;Create a simple socketio namespace class that can broadcast a message.&lt;/li&gt;
&lt;li&gt;Connect to the socket from the client side and receive push events.&lt;/li&gt;
&lt;/ul&gt;&lt;h2&gt;Notes&lt;/h2&gt;

&lt;ul&gt;&lt;li&gt;&lt;p&gt;We barely touched the surface! There&amp;#8217;s a lot more! For instance gevent-socketio has &lt;a href="https://gevent-socketio.readthedocs.org/en/latest/mixins.html" target="_blank"&gt;mixins&lt;/a&gt; that can help with broadcasting.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We used socket.io (a framework) instead of dealing with sockets directly. Socket.io handles events and namespaces, and it also handles automatically reconnecting to the socket server if it gets disconnected.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It&amp;#8217;s all self contained, and we&amp;#8217;re using only python! No redis, no message queues server, no node.js! Just python! (talking about the server side here).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Originally, I tried to make this work with pypy, but unfortunately gevent is not compatible with pypy.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;This setup seems to lose the werkzeug debugger. I tried to re-enable it using wekzeug&amp;#8217;s &lt;a href="http://werkzeug.pocoo.org/docs/debug/" target="_blank"&gt;DebuggedApplication&lt;/a&gt; class, but it seemed to breaks sockets. I haven&amp;#8217;t figured out why exactly.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;</description><link>http://dev.hasenj.org/post/38188152502</link><guid>http://dev.hasenj.org/post/38188152502</guid><pubDate>Mon, 17 Dec 2012 18:03:00 -0700</pubDate><category>flask</category><category>socket.io</category><category>sockets</category><category>web-development</category><category>tutorial</category><category>walkthrough</category></item><item><title>Knockout.js vs Backbone.js</title><description>&lt;p&gt;What the hell am I talking about? Backbone? Knockout?&lt;/p&gt;

&lt;p&gt;These are 2 popular javascript frameworks, supposedly designed to help/facilitate the building of rich client application on the web.&lt;/p&gt;

&lt;p&gt;To me, this means web apps with non-trivial interactive UI, which would be difficult to manage with just jQuery.&lt;/p&gt;

&lt;p&gt;What&amp;#8217;s wrong with jQuery, you say? Well, jQuery is awesome, but it&amp;#8217;s too low-level as far as app-development is concerned. How are you going to manage it when the complexity increases? It gets hairy very quickly.&lt;/p&gt;

&lt;p&gt;If you&amp;#8217;ve been developing mostly in jQuery, and you&amp;#8217;re getting a bit tired of it, you should be looking for alternatives; higher level frameworks/libraries to help you manage the complexity. However, you may find the information on the internet to be very confusing. What should you use? Which framework/library is better? You might have heard of Backbone.js or Knockout.js, and you don&amp;#8217;t know which one you should go with. And to make things worse, Backbone.js and Knockout.js are not the only games in town; there are plenty others as well.&lt;/p&gt;

&lt;p&gt;So, I&amp;#8217;m going to spare you &lt;em&gt;some&lt;/em&gt; of the trouble by telling you straight away which one is better: Knockout.js or Backbone.js&lt;/p&gt;

&lt;p&gt;Some people will disagree, but they are &lt;a href="http://www.youtube.com/watch?v=n-IgqiTD4XA" target="_blank"&gt;ugly and stupid&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Knockout.js is awesome&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Backbone.js is pointless&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Backbone.js doesn&amp;#8217;t solve any problem &lt;em&gt;I&amp;#8217;ve&lt;/em&gt; ever had. When I look at what Backbone provides, I can&amp;#8217;t help but wonder: what&amp;#8217;s the point? None of it made me think &amp;#8220;Ooooh I wish I had that a long time ago!!&amp;#8221;. No, quite the opposite, most of the time I was thinking &amp;#8220;Why would I need this?&amp;#8221; and &amp;#8220;How would this help me?&amp;#8221;.&lt;/p&gt;

&lt;p&gt;As far as I&amp;#8217;m concerned, the only problem that Backbone.js solves is the buzzword compliance problem. &amp;#8220;Building a complex client app? You should use MVC&amp;#8221;. Good for you; you may now say on your resume &amp;#8220;I have experience with MVC&amp;#8221;.&lt;/p&gt;

&lt;p&gt;I even &lt;a href="http://stackoverflow.com/questions/7542948/what-problem-does-backbone-js-solve" target="_blank"&gt;asked this question on StackOverflow&lt;/a&gt;, and the answer was &amp;#8220;it helps do MVC&amp;#8221;.&lt;/p&gt;

&lt;p&gt;Knockout.js actually solves a real problem; a real pain point for anyone who&amp;#8217;s ever done front-end work. When you learn how to use Knockout.js &amp;#8230; when you go through the tutorials, you&amp;#8217;ll constantly feel like &amp;#8220;Wow man, this is awesome! Why didn&amp;#8217;t I have this before?&amp;#8221;&lt;/p&gt;

&lt;p&gt;Knockout.js (hereafter referred to as KO) automates what amounts to 70% of Javascript development work, which is listening to events and binding callbacks so that you can do things like:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;&lt;p&gt;Update variables/data when user changes form values&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Hide or show elements of the page when something happens (or: add/remove elements, instead of simply hiding/showing them)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Change the entire &amp;#8220;page&amp;#8221; to a different component (a special case of the previous point)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Displaying &amp;#8220;items&amp;#8221; and &amp;#8220;objects&amp;#8221; as a complex HTML structure (aka widgets).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Displaying (and updating the display of) a list of items/objects.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;KO automates all that manual work. It&amp;#8217;s a high level framework so you almost never have to deal with &amp;#8220;events&amp;#8221; directly; it&amp;#8217;s abstracted away so you don&amp;#8217;t have to think about the low level aspects of it.&lt;/p&gt;

&lt;p&gt;KO also does a great job of &lt;em&gt;really&lt;/em&gt; binding the data to the UI. You almost never have to assign a special &amp;#8220;class&amp;#8221; or &amp;#8220;id&amp;#8221; for the purpose of manipulating elements and their content from Javascript, as often happens in jQuery-based development.&lt;/p&gt;

&lt;h3&gt;Tiny disclaimer&lt;/h3&gt;

&lt;p&gt;To be slightly fair, Knockout.js and Backbone.js have very different purposes.&lt;/p&gt;

&lt;p&gt;Backbone.js is not really pointless; it serves as a pretty good ORM for REST APIs.&lt;/p&gt;

&lt;p&gt;However, in this article I&amp;#8217;m evaluating its usefulness for building interactive UIs on the web.&lt;/p&gt;

&lt;p&gt;You may say that this is not really what it&amp;#8217;s designed for, but in practice, that&amp;#8217;s what most people think Backbone.js is about: helping you build single-page interactive web applications.&lt;/p&gt;

&lt;p&gt;That&amp;#8217;s what most people end up using it for.&lt;/p&gt;

&lt;h2&gt;A Closer Look&lt;/h2&gt;

&lt;p&gt;So far I&amp;#8217;ve just been trolling basically. Let me backup my opinion by explaining the reasoning behind it.&lt;/p&gt;

&lt;h3&gt;Backbone.js&lt;/h3&gt;

&lt;p&gt;Backbone.js (hereafter referred to as BB) provides you with &amp;#8220;Models&amp;#8221;, &amp;#8220;Collections&amp;#8221;, and &amp;#8220;Views&amp;#8221;.&lt;/p&gt;

&lt;p&gt;Models are object wrappers that fire events when any field in the object gets changed. For example, you have a user model. In one corner of your application, you can say:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;user.set("name", new_name);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And, in another corner, you can say:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;user.on("change:name", function() {
    // do something here
    // yes, this is an event handler function/callback

    // example of what typically goes in here:
    $el.find(".name").text(user.get("name"))
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In essence, you are still dealing with events, and writing event handlers, explicitly. And what&amp;#8217;s worse; inside the event handler, you&amp;#8217;ll be manipulating the DOM using jQuery (or a similar low-level API).&lt;/p&gt;

&lt;p&gt;BB has a &amp;#8220;views&amp;#8221; system, but it&amp;#8217;s not really much of a system; it&amp;#8217;s more of a convention. Each view has a model and an element (a DOM element). Convention has it that the view should have a &lt;code&gt;render()&lt;/code&gt; function, which uses the model data to render HTML into the element. Convention also states that &lt;code&gt;render()&lt;/code&gt; should return the view.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ViewName = Backbone.View.extend({
    // ...
    render: function() {
        var $el = $(this.el);

        // initialize the element's content by some template
        $el.html(loadSomeTemplate("by_name"));

        // fill various template blocks, or something like that ...
        $el.find(".name").html(this.model.get("name"));

        return this; // if you forget this, dragons might hunt you
    },
    // ...
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It&amp;#8217;s typically inside the view definition that you bind to your model&amp;#8217;s &amp;#8220;change&amp;#8221; events, and that&amp;#8217;s basically how you build the interactivity in your application.&lt;/p&gt;

&lt;p&gt;And, at the end of the day, it all comes down to the same old low level jQuery mess. You end up adding special classes and ids to your DOM elements, so you can access them easily (from your code) for the purpose of manipulating them. You write a lot of code to listen for events and do stuff.&lt;/p&gt;

&lt;p&gt;One of the pain points I remember having with BB (I&amp;#8217;m sure it&amp;#8217;s been experienced by a lot of other people as well) is the management of views within views, aka nested view, or sub-views. Particularly annoying was the management of views that are meant to display a &amp;#8220;Collection&amp;#8221; (list) of items. The view itself contains a list of subviews, matching the items in the collection. You end up having to manually write the code to update the view each time the collection changes.&lt;/p&gt;

&lt;p&gt;Handling updates to lists/collections can be very complicated, and hard to do efficiently, so most people (including me) end up writing a very generic render function that simply wipes out all the previous subviews and builds new ones. This means, if you have a collection of a 100 items, and you add one new item, you will destroy a 100 DOM elements (each which contain some number of child elements), destroy a 100 view objects, clear out all the bindings between these view objects and the collection items (models), create 101 new view elements, creating a DOM element for each of those, and attaching it to the page (body) DOM.&lt;/p&gt;

&lt;p&gt;Naturally, it would be much more efficient to simply add 1 new view and append it to the list, and append its DOM element to the list view. But, like I mentioned above, managing all the various ways in which a list can be updated is quite tricky, so we end up with this solution that just &amp;#8220;works&amp;#8221;. I&amp;#8217;m sure plenty of people had to go through the same trouble, over and over. And most likely, no one bothers to tweak the list-view rendering algorithm to make it smarter, because it&amp;#8217;s just not worth it.&lt;/p&gt;

&lt;p&gt;BB also suffers from many &lt;a href="https://paydirtapp.com/blog/backbone-in-practice-memory-management-and-event-bindings/" target="_blank"&gt;other complications&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In short, when it comes to building rich front-ends on the web, I found BB to not be effective at all.&lt;/p&gt;

&lt;p&gt;However, to be fair, (as I&amp;#8217;ve already mentioned), BB is very good at being an ORM for REST APIs.&lt;/p&gt;

&lt;p&gt;Yes, perhaps I&amp;#8217;m evaluating BB against standards which it was not really intended for: managing the complexities involved in building rich interactive UI. But, as I said, that&amp;#8217;s what most people actually use it for, and I find that it&amp;#8217;s not really useful in that department at all.&lt;/p&gt;

&lt;p&gt;Backbone.js does come with a pretty good url router component, but I think of this as more of a &amp;#8220;batteries included&amp;#8221; kind of thing. There are other libraries that provide similar functionality, for instance, &lt;a href="http://visionmedia.github.com/page.js/" target="_blank"&gt;page.js&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;Knockout.js&lt;/h3&gt;

&lt;p&gt;KO provides a sort of declarative language that allows you to bind DOM elements to your data.&lt;/p&gt;

&lt;p&gt;On any DOM element, you can say: this elements takes its value from this variable, or, this element is only displayed when some value is &amp;#8220;truthy&amp;#8221;, and so on.&lt;/p&gt;

&lt;p&gt;KO calls these things &amp;#8220;bindings&amp;#8221;. A &amp;#8220;value&amp;#8221; binding on a text field keeps the content of the field in sync with some JS variable. A &amp;#8220;visible&amp;#8221; binding controls the visibility of an element based on the truthiness of some expression. There are other sorts of bindings, and you can define your own, too.&lt;/p&gt;

&lt;p&gt;To have the DOM update automatically when data changes, there must be a way to &amp;#8220;listen&amp;#8221; to these changes, and the solution KO provides you with is &amp;#8220;observables&amp;#8221;. An observable holds a value and wraps it up in an object so that you can update that value and have the rest of application see that you made a change.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;name = ko.observable(initial_value);

// ....
// sometime later
name(new_value) // change the value

// ...
// to read the value:
val = name()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When you update the value of &amp;#8216;name&amp;#8217;, the rest of the application will automatically adjust. If an element is bound to display the content of &amp;#8216;name&amp;#8217;, it will update itself. If an element is bound to be visible only when name is not empty, it will recalculate its visibility .. and so on.&lt;/p&gt;

&lt;p&gt;KO handles all the event bindings for you; you never have to think about it.&lt;/p&gt;

&lt;p&gt;KO also provides another very powerful concept: &amp;#8220;computed&amp;#8221; values. A &amp;#8220;computed&amp;#8221; object wraps a function (in the functional-programming sense; i.e. it should have no side-effects) and automatically tracks its dependencies.&lt;/p&gt;

&lt;p&gt;What the hell does that mean? Let&amp;#8217;s illustrate with a simple example. Let&amp;#8217;s say that &amp;#8220;Full Name&amp;#8221; is simply &lt;code&gt;firstName + " " + lastName&lt;/code&gt;. If we would write that as a function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; var fullName = function() {
      return firstName + " " + lastName;
 }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you were writing low level Javascript, you&amp;#8217;d have events that listen to when the user changes the firstName and lastName fields, and then you call this fullName() function, take the result, and display it inside some div, which you probably put an &amp;#8216;id&amp;#8217; on so you can access: &lt;code&gt;$("#fullName").html(fullName())&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;With KO&amp;#8217;s &amp;#8220;computed&amp;#8221; concept, you define fullName like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; var fullName = ko.computed(function() {
      return firstName() + " " + lastName();
 });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As far as you care, KO magically figures out the dependency graph for this &amp;#8220;computed&amp;#8221;, and so every time &lt;code&gt;firstName&lt;/code&gt; changes, &lt;code&gt;fullName&lt;/code&gt; also gets updated.&lt;/p&gt;

&lt;p&gt;You can then bind the text value of some div to &lt;code&gt;fullName&lt;/code&gt;, and bind the value of some text field to &lt;code&gt;firstName&lt;/code&gt;, and as the user edits the name in the text field, the div holding the full name will automatically be updated, without you having to do anything extra.&lt;/p&gt;

&lt;p&gt;And, as I&amp;#8217;ve mentioned before, &amp;#8216;text&amp;#8217; and &amp;#8216;value&amp;#8217; are only 2 of the basic bindings that KO provides, and you can also define your own bindings.&lt;/p&gt;

&lt;p&gt;Naturally, inside the binding&amp;#8217;s definition, you will be doing low-level DOM manipulation using jQuery, but once you have that binding written; you can use it everywhere.&lt;/p&gt;

&lt;p&gt;KO comes with a built-in &amp;#8216;foreach&amp;#8217; binding that iterates over a list and displays the items inside it. As you can expect, the first version of this binding probably wasn&amp;#8217;t very smart; it probably just re-rendered the entire element every time an item got changed. But, because it&amp;#8217;s a built-in binding that&amp;#8217;s used by a lot of people, it can be improved, and as far as I can tell, it&amp;#8217;s now quite intelligent; it can find precisely which items have changed, and update only the items that need updating. The official docs say:&lt;/p&gt;

&lt;p&gt;&amp;gt; (&amp;#8230;) The binding will efficiently update the UI to match - inserting or removing more copies of the markup, or re-ordering existing DOM elements, without affecting any other DOM elements. This is far faster than regenerating the entire foreach output after each array change.&lt;/p&gt;

&lt;p&gt;The only downside with KO is that the binding syntax is somewhat obtrusive.&lt;/p&gt;

&lt;p&gt;This is more or less the first example from the tutorials:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;First name: &amp;lt;strong&amp;gt;&amp;lt;/strong&amp;gt;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;Last name: &amp;lt;strong&amp;gt;&amp;lt;/strong&amp;gt;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;Full Name: &amp;lt;strong&amp;gt;&amp;lt;/strong&amp;gt;&amp;lt;/p&amp;gt;


// Javascript
function AppViewModel() {
    var self = this;
    self.firstName = ko.observable("Bert");
    self.lastName = ko.observable("Bertington");
    self.fullName = ko.computed(function() {
      return self.firstName() + " " + self.lastName();
 });
}

rootVM = new AppViewModel();
// Activates knockout.js
ko.applyBindings(rootVM);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Basically, you define bindings on elements using the attribute &amp;#8220;data-bind&amp;#8221;, in it, you specify a binding and an expression that goes as an input to that binding. We have here &amp;#8220;text&amp;#8221; bindings, binding the elements to the &amp;#8220;firstName&amp;#8221;, &amp;#8220;lastName&amp;#8221;, and &amp;#8220;fullName&amp;#8221;.&lt;/p&gt;

&lt;p&gt;Then we have the &amp;#8220;ViewModel&amp;#8221;. Its essentially an object with fields. &amp;#8220;firstName&amp;#8221; is a field in the &amp;#8220;root&amp;#8221; ViewModel. Since it&amp;#8217;s an observable, you can update it, by running this in the console for example &lt;code&gt;rootVM.firstName("Jack")&lt;/code&gt;, and the page will immediately reflect that change. Not only will the &amp;#8220;First Name&amp;#8221; element update itself, but the &amp;#8220;Full Name&amp;#8221; will also reflect that change and update itself.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;KO very nicely un-entangles your messy jQuery code.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;That&amp;#8217;s why it&amp;#8217;s awesome.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s the example on jsFiddle: &lt;a href="http://jsfiddle.net/FEVbz/" target="_blank"&gt;http://jsfiddle.net/FEVbz/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ve extended it to also include text fields so you can change values in real time.&lt;/p&gt;

&lt;p&gt;I strongly encourage you to use the interactive KO tutorial; you will be amazed: &lt;a href="http://learn.knockoutjs.com/" target="_blank"&gt;http://learn.knockoutjs.com/&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;Buzzwords&lt;/h3&gt;

&lt;p&gt;What is that you say? Knockout.js is not MVC? Well, if you care about buzzwords, here&amp;#8217;s one for you: &lt;a href="http://en.wikipedia.org/wiki/Model_View_ViewModel" target="_blank"&gt;MVVM&lt;/a&gt;. As far as I&amp;#8217;m concerned, MVVM is gibberish, and so is MVC.&lt;/p&gt;

&lt;p&gt;Buzzwords don&amp;#8217;t matter. Terms like &amp;#8220;MVC&amp;#8221; are merely a condensed description of a solution to a problem that developers face in real life.&lt;/p&gt;

&lt;p&gt;If you give me a framework that doesn&amp;#8217;t solve my problem, I don&amp;#8217;t care what buzzword you attach to it.&lt;/p&gt;

&lt;p&gt;If you give me a framework that solves my problem beautifully and elegantly, then I&amp;#8217;m happy with it, even if it doesn&amp;#8217;t fill any buzzword compliance requirement.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.youtube.com/watch?v=b2F-DItXtZs" target="_blank"&gt;Obligatory &amp;#8220;web-scale&amp;#8221; video&lt;/a&gt;.&lt;/p&gt;</description><link>http://dev.hasenj.org/post/35572197519</link><guid>http://dev.hasenj.org/post/35572197519</guid><pubDate>Mon, 12 Nov 2012 14:48:00 -0700</pubDate><category>web-development</category><category>backbone.js</category><category>knockout.js</category><category>frameworks</category><category>opinionated</category></item><item><title>Coroutines vs explicitly async APIs</title><description>&lt;p&gt;I&amp;#8217;ve expressed before (rather distastefully) an opinion that Node.js is not a good choice for developing web applications, because its async APIs will usually turn your code to a callback hell.&lt;/p&gt;

&lt;p&gt;Many people responded negatively, perhaps rightly so. But on the other hand, I think some of them didn&amp;#8217;t actually understand why the explicitly async APIs of Node.js are not a good way to handle the &amp;#8220;blocking I/O&amp;#8221; problem; or rather, these people didn&amp;#8217;t understand that &lt;a href="http://gevent.org" target="_blank"&gt;gevent&lt;/a&gt;&amp;#8217;s coroutines and Go&amp;#8217;s goroutines provide a much cleaner solution. They seem to think that if it&amp;#8217;s not callback hell, it won&amp;#8217;t scale. I want to show that they&amp;#8217;re wrong.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;m going to try to explain the difference between an API that&amp;#8217;s explicitly asynchronous and one that appears &amp;#8220;normal&amp;#8221; but is &amp;#8216;asynchronous&amp;#8217; under the hood.&lt;/p&gt;

&lt;h2&gt;Why asynchronous IO?&lt;/h2&gt;

&lt;p&gt;The short answer is that OS threads don&amp;#8217;t scale. Meaning, if you  spawn a new thread per request, your server will not scale to tens of thousands of simultaneous requests.&lt;/p&gt;

&lt;p&gt;I don&amp;#8217;t know much about the details of this, but it appears that OS level threads are expensive (relatively .. and only after you&amp;#8217;ve spawned thousands of them).&lt;/p&gt;

&lt;p&gt;Request handlers typically do some sort of a blocking I/O operation, such as reading a file, or making a network connection (to the database, for instance). To handle more connections, you have to do it in parallel, which is usually done by spawning new threads, but we just mentione d that they don&amp;#8217;t &amp;#8220;scale&amp;#8221;.&lt;/p&gt;

&lt;p&gt;So for scalability, there&amp;#8217;s a need for a different mechanism of handling large amounts of concurrent connections. A mechanism that does not involve spawning a kernel-level thread per request.&lt;/p&gt;

&lt;p&gt;One such method is using asynchronous I/O, because it&amp;#8217;s non-blocking. What you basically do is tell the system: read data from here, and when it arrives, call this function; meanwhile, I will keep working on other stuff. Because I/O operations don&amp;#8217;t block, you don&amp;#8217;t have to spawn a thread for every connection.&lt;/p&gt;

&lt;p&gt;This is basically what Node.js does. This is how it can scale to heavy loads while while doing everything in one thread.&lt;/p&gt;

&lt;p&gt;A typical request handling function merely reads data from files/databases and does simple computations that don’t take more than a few nanoseconds on modern hardware.&lt;/p&gt;

&lt;p&gt;Let’s suppose we have a request handler that takes the userid and fetches some &amp;#8220;items&amp;#8221; that belong to this user so they can be displayed to him.&lt;/p&gt;

&lt;p&gt;In a typical synchronous IO style, it might look something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def serve_items(request):
    user_id = grab_user_id(request) # simple function
    items = fetch_user_items_from_db(user_id) # blocking IO - blocks current process or thread
    items = sort_items_by_score(items) # super fast operation
    return json_response(items) # respond with the items in json format
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That would be the synchronous version of this request handler.&lt;/p&gt;

&lt;p&gt;In Node.js, it would look more like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var serve_items = function(request, response) {
    var user_id = grab_user_id(request); // simple function
    var on_items_ready = function(items) {
        items = sort_items_by_score(items); // simple computation
        response.send_json(items); // respond with the items in json format
    };
    fetch_user_items_from_db(user_id, on_items_ready);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The way you write the code is different.&lt;/p&gt;

&lt;p&gt;Now, if you pay attention, you will find that this function returns almost immediately! The function doesn’t wait for the data fetch to complete before returning, it returns as soon as it fires the fetch request. The actual sorting of the items and sending the response happen later - after the data has arrived.&lt;/p&gt;

&lt;p&gt;The disadvantage here is the way you write the code:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;&lt;p&gt;More cognitive effort is required to express the control flow in a soup of callback handlers.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The resulting code is harder to read.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;I&amp;#8217;d argue that from 1 and 2, we can conclude that the resulting code is harder to maintain, because maintenance requires both reading and writing.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;m not going to delve into more detailed examples. There is a lot of material on the net. Just Google it.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://bjouhier.wordpress.com/2011/01/09/asynchronous-javascript-the-tale-of-harry/" target="_blank"&gt;http://bjouhier.wordpress.com/2011/01/09/asynchronous-javascript-the-tale-of-harry/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There are some solutions to this within the Node.js ecosystem. Here are some examples:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://alexeypetrushin.github.io/synchronize/docs/index.html" target="_blank"&gt;http://alexeypetrushin.github.io/synchronize/docs/index.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/Sage/streamlinejs" target="_blank"&gt;https://github.com/Sage/streamlinejs&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But now I&amp;#8217;d like to take a look at another approach to the issue.&lt;/p&gt;

&lt;h2&gt;Goroutines&lt;/h2&gt;

&lt;p&gt;What makes blocking code &amp;#8220;bad&amp;#8221; or &amp;#8220;undesirable&amp;#8221; is that process and threads are expensive.&lt;/p&gt;

&lt;p&gt;Why are they expensive? Can’t we make them cheap? If we can’t make them cheap, can’t we come up with other concurrency constructs that are cheap?&lt;/p&gt;

&lt;p&gt;Well, it turns out we actually can. This is exactly what goroutines are: cheap concurrency constructs.&lt;/p&gt;

&lt;p&gt;When a goroutine blocks on IO, it&amp;#8217;s not a problem, because it&amp;#8217;s &lt;em&gt;very&lt;/em&gt; cheap to create new goroutines. You can create and teardown hundreds of thousands of goroutines in under a second; that&amp;#8217;s how cheap they are. So &amp;#8220;blocking&amp;#8221; on I/O does not cause any scalability issues.&lt;/p&gt;

&lt;p&gt;So in Go, you can write code in the usual synchronous style, and it will scale. It just works!&lt;/p&gt;

&lt;p&gt;Actually goroutines still do asynchrunous I/O; but it all happens under the cover. The APIs of the language are not &lt;em&gt;explicitly&lt;/em&gt; asynchronous. The APIs are usual, synchrunous.&lt;/p&gt;

&lt;h2&gt;Coroutines and Continuations&lt;/h2&gt;

&lt;p&gt;Goroutines are based on the concept of coroutines. The term &amp;#8220;coroutine&amp;#8221; comes from &amp;#8220;cooperative routines&amp;#8221;. We call them &amp;#8220;cooperative&amp;#8221; because they don’t get scheduled by the OS or any other scheduler, they just run for a while then &amp;#8220;yield&amp;#8221;. When a coroutine yields, other coroutines get to run. When a coroutine gets control back, it continues running from where it left off last time.&lt;/p&gt;

&lt;p&gt;This &lt;a href="http://lua-users.org/wiki/CoroutinesTutorial" target="_blank"&gt;tutorial&lt;/a&gt; gives a nice overview of coroutines in lua.&lt;/p&gt;

&lt;p&gt;The concept of suspending and resuming a coroutine is closely related to the concept of continuations.&lt;/p&gt;

&lt;p&gt;When a coroutine suspends, we can think of this as a snapshot being taken of the coroutine&amp;#8217;s execution context. This snapshot can then be invoked at a later time and it will resume the execution of the coroutine.&lt;/p&gt;

&lt;p&gt;Let&amp;#8217;s look at a simple example of a yielding operation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;print("hello")
sleep(10) // milliseconds
print("world")
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The call to &lt;code&gt;sleep&lt;/code&gt; basically says: capture the state of the current coroutine (i.e.: save the current continuation), and don’t resume it before 10 milliseconds pass. After the sleep time passes (10 milliseconds, in this case), the coroutine may resume whenever it’s given the chance.&lt;/p&gt;

&lt;p&gt;The same can happen with I/O operations that usually block. Depending on the implementation, coroutines may &amp;#8220;yield&amp;#8221; execution when they make, for example, an http request, and don’t resume execution until the response comes back. So, while the request is waiting to return, other coroutines can continue to run (inside the same process).&lt;/p&gt;

&lt;p&gt;If you’re familiar with javascript, the sleep example might remind you of something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;console.log("hello")
setTimeout(10, function() {
    console.log("world")
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Basically, in javascript, you have to manually create something similar to a continuation, but instead of a continuation, it’s a closure, and you pass it to the &amp;#8220;sleep&amp;#8221; function to say: here, forget about me, I’ll be gone now, but when you return, do this thing that I’m telling you about right here.&lt;/p&gt;

&lt;p&gt;Instead of &lt;em&gt;capturing&lt;/em&gt; the state of the current execution context, you &lt;em&gt;terminate&lt;/em&gt; the current execution context and set the stage for a new execution context to be created in the future.&lt;/p&gt;

&lt;p&gt;You may think continuations are conceptually the same thing as closures, but they are not. A continuation includes the call stack, so when a continuation is resuming, it may hit a &amp;#8220;return&amp;#8221; statement, and when it does that, the function returns the result to its caller.&lt;/p&gt;

&lt;p&gt;Consider this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# python syntax, but don’t assume that this is python per se ..

def logError(errorCode):
    message = getExplanation(errorCode)
    time = getTime()
    print(time + ": error " + code + ": " + message)

def getExplanation(code):
    resp_text = http_get_request("http://api.service.example/errors/" + code) # this line dispatches the request and yields execution
    resp_json = json.parse(resp_text)
    return resp_json.human_readable_explanation
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, in this example, &lt;code&gt;http_get_request&lt;/code&gt; is assumed to be a function that makes an http request, and just like &lt;code&gt;sleep&lt;/code&gt; in the above example, it will capture the current continuation and yield execution to other coroutines, and when the request comes back, the captured continuation maybe invoked, to resume the execution of the coroutine.&lt;/p&gt;

&lt;p&gt;Now, when this continuation is resumed, the entire execution context is resumed, including the fact that &lt;code&gt;getExplanation&lt;/code&gt; was called from inside &lt;code&gt;logError&lt;/code&gt; and that &lt;code&gt;logError&lt;/code&gt; is waiting for &lt;code&gt;getExplanation&lt;/code&gt; to return a string.&lt;/p&gt;

&lt;p&gt;So, when the http response comes back, and the continuation is resumed, and we hit the line &lt;code&gt;return resp_json.human_readable_explanation&lt;/code&gt;, we actually take this value and return it, and then continue execution at the line &lt;code&gt;message = getExplanation(errorCode)&lt;/code&gt; inside the caller .. and so on.&lt;/p&gt;

&lt;p&gt;You can&amp;#8217;t do this with closures.&lt;/p&gt;

&lt;p&gt;If the &lt;code&gt;getExplanation&lt;/code&gt; function is to be written in the javascript callback style, it can&amp;#8217;t really &amp;#8220;return&amp;#8221; anything.&lt;/p&gt;

&lt;p&gt;Here, let&amp;#8217;s try to make it return something. It will be absurd - and it won&amp;#8217;t work as expected - but let&amp;#8217;s do it just for fun:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var logError = function(errorCode) {
    var message = getExplanation(errorCode);
    var time = getTime();
    console.log(time + ": error " + code + ": " + message);
}

var getExplanation = function(code) {
    http_get_request("http://api.service.example/errors/" + code, function(resp_text) {
            var resp_json = json.parse(resp_text);
            return resp_json.human_readable_explanation; // absurd!!!
    });
    // getExplanation will infact return here, and it will return null
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To help see the absurdity of this &lt;code&gt;return&lt;/code&gt; attempt more clearly, let&amp;#8217;s rewrite the async http request:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var getExplanation = function(code) {
    var url = "http://api.service.example/errors/" + code;
    var callback = function(resp_text) {
        var resp_json = json.parse(resp_text);
        return resp_json.human_readable_explanation; //absurdity!!!
    };

    http_get_request(url, callback);
    // getExplanation will infact return here, and it will return null
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There&amp;#8217;s no way to tell the callback &amp;#8220;oh btw, return to &lt;code&gt;logError&lt;/code&gt;, please!&amp;#8221;. No! You can&amp;#8217;t do that. It&amp;#8217;s a brand new execution context; all information about the call stack is completely lost.&lt;/p&gt;

&lt;p&gt;So, what you end up having to do instead, is pass a callback to &lt;code&gt;getExplanation&lt;/code&gt; itself!&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// notice the "caller_callback"
var getExplanation = function(code, caller_callback) {
    var url = "http://api.service.example/errors/" + code;

    var callback = function(resp_text) {
        var resp_json = json.parse(resp_text)
        var result = resp_json.human_readable_explanation;
        caller_callback(result);
    };

    http_get_request(url, callback);
    // getExplanation will infact return here, and it will return null
}

// and rewrite the `logError` function too
var logError = function(errorCode) {
    var callback = function(message) {
        var time = getTime();
        console.log(time + ": error " + code + ": " + message)
    };

    getExplanation(errorCode, callback)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So, I hope that I have illustrated why closures are not equivalent to continuations, and are in fact inferior to them.&lt;/p&gt;

&lt;p&gt;Note that when I say a &amp;#8220;continuation&amp;#8221;, I&amp;#8217;m talking about a concept; not any particular implementation detail. When a OS process is suspended and then resumed, we may also think of this as a continuation being resumed. When a thread is suspended and resumed, we may also think of this as a continuation being resumed.&lt;/p&gt;

&lt;p&gt;The key aspect of coroutines is that they are much cheaper than threads or processes, and are not managed by the kernel.&lt;/p&gt;

&lt;p&gt;The &lt;a href="http://gevent.org" target="_blank"&gt;gevent&lt;/a&gt; library for python does just what I described about coroutines and continuations. It wraps an asynchronous I/O with a coroutine yielding mechanism, thus providing a synchronous API on top of an asynchronous API.&lt;/p&gt;

&lt;h2&gt;The obvious conclusion:&lt;/h2&gt;

&lt;p&gt;With an explicitly asynchronous API, such as the one that Node.js gives you, you must manually construct &amp;#8220;callback&amp;#8221; functions that emulate continuations. You get the benefit of asynchronous IO but lose all the benefits of synchronous IO APIs.&lt;/p&gt;

&lt;p&gt;With things like gevent and goroutines, you get all the benefits of asynchronous IO while maintaining all the benefits of the tranditional synchronous IO APIs.&lt;/p&gt;

&lt;p&gt;Another way to look at it is related to closures and continuations.&lt;/p&gt;

&lt;p&gt;With Node.js, you have to create closures, and call the async IO APIs with these closures as the thing to execute when the response arrives.&lt;/p&gt;

&lt;p&gt;With coroutines, the language/compilers does it for you such that when the response comes back, the current continuation is resumed.&lt;/p&gt;

&lt;p&gt;Notice that what the compiler generates for you (continuations) is much more powerful than what you have to write by hand (closures).&lt;/p&gt;

&lt;h2&gt;Footnote:&lt;/h2&gt;

&lt;p&gt;Now, if only it was possible to specify the callbacks as continuations &amp;#8230; it might then be possible to easily wrap async IO functions and make them appear synchronous&lt;/p&gt;

&lt;p&gt;I&amp;#8217;m imagning something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var wrap_async_api = function(async_fn) {
    var sync_version = function() {
        return call_with_current_continuation as cc {
            var callback = function(data) {
                resume_continuation cc {
                    return data
                }
            }
            var args = Array.prototype.slice.call(arguments);
            args.push(callback)
            async_fn.call(this, args);
        }
    }
    return sync_version;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Not sure if this is a reasonable way to imagine using continuations to provide a synchronous API on top of an async one. I haven&amp;#8217;t actually used &lt;code&gt;call/cc&lt;/code&gt; in any real program.&lt;/p&gt;

&lt;p&gt;For a good understanding of scheme&amp;#8217;s continuations and &lt;code&gt;call/cc&lt;/code&gt;, I recommend this article:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://community.schemewiki.org/?call-with-current-continuation" target="_blank"&gt;http://community.schemewiki.org/?call-with-current-continuation&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It&amp;#8217;s really good; read it slowly and carefully.&lt;/p&gt;

&lt;h2&gt;Footnote #2:&lt;/h2&gt;

&lt;p&gt;It appears that there are continuation-based solutions for node.js:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/laverdet/node-fibers" target="_blank"&gt;https://github.com/laverdet/node-fibers&lt;/a&gt;&lt;/p&gt;</description><link>http://dev.hasenj.org/post/31396790746</link><guid>http://dev.hasenj.org/post/31396790746</guid><pubDate>Wed, 12 Sep 2012 06:41:00 -0600</pubDate></item><item><title>Gevent? Coroutines for Flask?</title><description>&lt;p&gt;Yesterday I was reading random stuff on the internet, one thing led to another, and I discovered there&amp;#8217;s something called &amp;#8220;greenlets&amp;#8221; in python, which seem to be essentially coroutines of some sort.&lt;/p&gt;

&lt;p&gt;The Flask docs mention that you can deploy flask apps using gevent:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://flask.pocoo.org/docs/deploying/wsgi-standalone/#gevent" target="_blank"&gt;http://flask.pocoo.org/docs/deploying/wsgi-standalone/#gevent&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;h3&gt;Gevent&lt;/h3&gt;
  
  &lt;p&gt;Gevent is a coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of libevent event loop&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It seems to monkey-patch existing synchronous apis to make them work with greenlets/coroutines, or something to that extent.&lt;/p&gt;

&lt;p&gt;I haven&amp;#8217;t actually figured out what&amp;#8217;s going on, but this seems to be interesting.&lt;/p&gt;</description><link>http://dev.hasenj.org/post/25324894809</link><guid>http://dev.hasenj.org/post/25324894809</guid><pubDate>Sun, 17 Jun 2012 17:36:35 -0600</pubDate></item><item><title>A short introduction to call-with-current-continuation</title><description>&lt;a href="http://community.schemewiki.org/?call-with-current-continuation"&gt;A short introduction to call-with-current-continuation&lt;/a&gt;: &lt;p&gt;Learning about lisp/scheme continuations .. wow .. what a mind twisting concept!&lt;/p&gt;

&lt;p&gt;And there I thought lisp lacked structured exit points like “break” and “continue” and “return” ..&lt;/p&gt;

&lt;p&gt;This is just brilliant .. I’m so humbled.&lt;/p&gt;

&lt;p&gt;When I finally understood how the coroutine implementation works on top of call/cc (it wasn’t obvious how that worked), I felt a sense of awe at the beauty and magnificence. I almost want to cry :”]&lt;/p&gt;</description><link>http://dev.hasenj.org/post/11724664012</link><guid>http://dev.hasenj.org/post/11724664012</guid><pubDate>Thu, 20 Oct 2011 23:58:09 -0600</pubDate></item><item><title>Sketching helped me avoid getting stuck</title><description>&lt;p&gt;For the past couple months, I&amp;#8217;ve been feeling stuck. Every time I sit down and try to get something done, I can&amp;#8217;t. I find myself &amp;#8220;dreading&amp;#8221; the thought of going through all the troubles involved (working out some minor low level details, etc). So instead of doing work, I&amp;#8217;d procrastinate on youtube or facebook or what have you.&lt;/p&gt;

&lt;p&gt;I tried to pin down why I was having this mental block that prevented me from doing work. I thought: maybe I&amp;#8217;m worrying about the code quality. I know that my code won&amp;#8217;t be perfect and elegant, and that disturbed me. Maybe that was one of the reasons. Maybe I was worried about my &amp;#8220;reputation&amp;#8221;; it&amp;#8217;s not that I have any reputation online (I&amp;#8217;m pretty much a nobody), but when potential employers are reviewing my work (say, on github), they may think I&amp;#8217;m a messy programmer when they see my messy code.&lt;/p&gt;

&lt;p&gt;So, I made a mental note (I also wrote down these thoughts on a file) of these worries and how they could be stopping me, but that didn&amp;#8217;t quite get rid of my problems. I still felt &amp;#8220;stuck&amp;#8221;. I still couldn&amp;#8217;t get much done.&lt;/p&gt;

&lt;p&gt;And then one day, I decided to do some &amp;#8220;doodling&amp;#8221; (after I read an article on HN about how doodling helps your brain when you&amp;#8217;re bored). I doodled random non-sense for about a minute, and then I found myself sketching a UI for an iPad app that&amp;#8217;s been in my head for a while now. I didn&amp;#8217;t just draw some boxes; I also wrote down some notes about how various elements should behave. Then after that, I found myself sketching out another version of the same app but for the web. I didn&amp;#8217;t only sketch it, but I also sketched out the basic structure of the code behind it. I basically wrote a high level view of the code that would make it run. Then I worked out some of the mathematical details. All that on paper. All these ideas have been in my head for a while, but I wasn&amp;#8217;t able to express them as code; I was stuck; I had a mental block. But now, I expressed them on paper. This got me excited, so I went to my laptop right away and started translating this stuff into code.&lt;/p&gt;

&lt;p&gt;This time, I didn&amp;#8217;t have anything to worry about. I didn&amp;#8217;t have any psychological worry about how things will turn out. I was basically code-monkeying my sketch. I wasn&amp;#8217;t thinking while I was coding, I had already figured things out on paper, so my coding consisted of me looking at the sketch and writing it down in the programming language I was doing my app in. I was plagiarizing from my sketch.&lt;/p&gt;

&lt;p&gt;There were a few details which I didn&amp;#8217;t get right on paper, but they were easy to fix. And in very little time, I got a working prototype of my idea.&lt;/p&gt;

&lt;p&gt;And then I realized that this is the way to go. And I also realized what exactly was happening, and why sketching is the solution.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;m an INTP, and I think this applies to xNTP types. I don&amp;#8217;t know if it applies the same to xNTJs.&lt;/p&gt;

&lt;p&gt;What happens when I have lots of ideas that I want to express in code is the following: I have a rough/vague picture in my head representing the structure of my program. As soon as I start writing code, I have to concentrate on the details of the code I&amp;#8217;m writing now, and this means that there&amp;#8217;s no more room in my mind for that general &amp;#8220;picture&amp;#8221; I just mentioned. This is a problem because: I don&amp;#8217;t want to lose this picture in my head; if I lose it, I won&amp;#8217;t get it back easily. It&amp;#8217;s basically the same thing when you are in flow and then suddenly you&amp;#8217;re interrupted. You need a lot of time to build the house of cards, and you can&amp;#8217;t afford to let it fall apart; it&amp;#8217;s mentally devastating.&lt;/p&gt;

&lt;p&gt;This is where sketching comes in. When you sketch the idea on paper, you have the entire picture in your head, and you&amp;#8217;re translating it on paper. Because it&amp;#8217;s just paper, you don&amp;#8217;t have to worry about details; you&amp;#8217;re not writing code; you&amp;#8217;re just sketching; there is no need for your mind to do any context switching. After you layout the general structure, you can then dive into some corners and work out some of the details in a very rough/general manner. Again, because it&amp;#8217;s on paper, you get to control how deep you want to dive in, and because the structure is already written on paper, you don&amp;#8217;t have to rebuild it in your head; you just look at it again and delve into the next detail (if needed).&lt;/p&gt;

&lt;p&gt;Then you can translate this into code, and you will not have the problem of context switching. Why? Because you&amp;#8217;re not worried about preserving the &amp;#8220;mental picture&amp;#8221; of the general structure of your idea. This way, you don&amp;#8217;t have to think a lot while you&amp;#8217;re coding, you&amp;#8217;ve already done the thinking and produced this sketch. Now you can just follow your own sketch, like a code-monkey.&lt;/p&gt;

&lt;p&gt;Why is this related to psychological type? Well, It&amp;#8217;s related to how you organize and express your thoughts. In the classical MBTI/Jung theory, INTPs organize logical structure internally (introverted thinking) and express ideas and intuitions externally (extroverted intuition).&lt;/p&gt;

&lt;p&gt;When thinking, you get alot of ideas, and you want to express all of them. The problem is, if you try to express them in code directly, you can&amp;#8217;t, because it will take quite some time to express each idea, and working on one idea at a time kills you, because you have all these other ideas that also want to be expressed, at the same time! And you know that if you start detailing some idea before the other ideas got a chance to be expressed, you&amp;#8217;ll lose them. So, by righting down a sketch of these ideas on paper, you can express all of them in a rough basic form. This way, all of your ideas get to be expressed at the &amp;#8220;same time&amp;#8221;, and this clears up &amp;#8220;cognitive space&amp;#8221; in your brain to start working on the details of each idea.&lt;/p&gt;

&lt;p&gt;Like I said, maybe this doesn&amp;#8217;t apply to INTJs, who constitute about half the programmers/hackers out there, but I&amp;#8217;d be interested to know if any INTJ tries this and finds it helpful.&lt;/p&gt;

&lt;p&gt;This sketching business is not entirely new to me. I used to do it a lot in the past. In fact, now that I think about it, most of my non-trivial programs in the past were sketched out on paper first before I started coding them, otherwise they probably wouldn&amp;#8217;t have been possible. I just didn&amp;#8217;t realize how important/pivotal it was. I don&amp;#8217;t remember how/when did I stop doing it. Maybe somehow I got the impression that real hackers just sit down and churn out code.&lt;/p&gt;</description><link>http://dev.hasenj.org/post/11596100231</link><guid>http://dev.hasenj.org/post/11596100231</guid><pubDate>Mon, 17 Oct 2011 19:39:00 -0600</pubDate></item><item><title>SuperAgent: ajax library without the suck (by visionmedia)</title><description>&lt;a href="http://visionmedia.github.com/superagent/"&gt;SuperAgent: ajax library without the suck (by visionmedia)&lt;/a&gt;</description><link>http://dev.hasenj.org/post/11059186220</link><guid>http://dev.hasenj.org/post/11059186220</guid><pubDate>Wed, 05 Oct 2011 07:05:35 -0600</pubDate></item><item><title>LiveReload: automatically reload browser page when editing local files</title><description>&lt;a href="https://github.com/mockko/livereload"&gt;LiveReload: automatically reload browser page when editing local files&lt;/a&gt;: &lt;p&gt;The &lt;a href="http://livereload.com/" target="_blank"&gt;official&lt;/a&gt; site doesn’t make it clear, but it works on linux too&lt;/p&gt;</description><link>http://dev.hasenj.org/post/9702210272</link><guid>http://dev.hasenj.org/post/9702210272</guid><pubDate>Fri, 02 Sep 2011 05:03:54 -0600</pubDate></item><item><title>Fix for when mongodb won't start on Ubuntu</title><description>&lt;a href="http://www.synchrosinteractive.com/blog/1-software/47-mongodb-repair-on-ubuntu"&gt;Fix for when mongodb won't start on Ubuntu&lt;/a&gt;: &lt;p&gt;Kinda lame ..&lt;/p&gt;</description><link>http://dev.hasenj.org/post/9048256165</link><guid>http://dev.hasenj.org/post/9048256165</guid><pubDate>Wed, 17 Aug 2011 14:04:14 -0600</pubDate></item><item><title>A different kind of writing platform</title><description>&lt;p&gt;I&amp;#8217;ve been thinking for a long time about building a &amp;#8220;writing&amp;#8221; platform. But when I try to put it into simple words, it sounds like &amp;#8220;oh, yet another blog&amp;#8221;. In fact I&amp;#8217;ve even written a post before titled &amp;#8220;yet another blog engine&amp;#8221;. It&amp;#8217;s been probably over a year, and the thing is &lt;em&gt;still&lt;/em&gt; only in my head.&lt;/p&gt;

&lt;p&gt;Most current blog engines are like magazines. You write something, and it gets filed under the date it was published in! If you write an essay, why should it matter whether you wrote it around 15/4/2006 or around 8/10/2007? Most of the time, the exact date doesn&amp;#8217;t matter. Just a general time line is usually enough, &amp;#8220;2006&amp;#8221;. If the date &lt;em&gt;does&lt;/em&gt; matter for a &lt;em&gt;certain&lt;/em&gt; essay, you can add it as a note somewhere.&lt;/p&gt;

&lt;p&gt;When I think about an essay here, I&amp;#8217;m thinking about things that might go in books, more so than newspapers. And in books, you don&amp;#8217;t usually get a date around every essay or chapter. Books are a bit more &amp;#8220;timeless&amp;#8221; than magazines in this sense. There&amp;#8217;s usually only one date on a book: the year it was published.&lt;/p&gt;

&lt;p&gt;This is actually inspired by Paul Graham&amp;#8217;s essays page.&lt;/p&gt;

&lt;p&gt;If most current writing platforms (manifested as blog engines) are designed more around a magazine concept, then there ought to be a place in the market for writing platforms that are designed more around the &amp;#8220;book&amp;#8221; concept.&lt;/p&gt;

&lt;p&gt;It&amp;#8217;s certainly possible to write essays on top of current blog engines; I&amp;#8217;ve seen several people do it, but it&amp;#8217;s somewhat annoying, and you get a lot of other little problems. I&amp;#8217;m sort of doing something similar with Tumblr here, though not quite so.&lt;/p&gt;

&lt;p&gt;The nature of essays is that they can evolve. You write a piece, revise it, revise it, revise it, then publish it. You get lots of criticism, people comment about how stupid you are, etc, and maybe you will want to edit it, to sort of elaborate some problem points. OK, maybe you have a thick skin and you can ignore trolls, good for you. But still, say you change your opinion about something, or you learn of something you didn&amp;#8217;t know before, so you want to go back and revise your essay.&lt;/p&gt;

&lt;p&gt;So in this sense, each essay is like its own project, you work on it, publish it, but you can never really say it&amp;#8217;s &amp;#8220;done&amp;#8221;; there&amp;#8217;s always room for changes and improvements. So it&amp;#8217;s ought to be possible for you to completely &amp;#8220;own&amp;#8221; your project, &lt;em&gt;independently&lt;/em&gt; of the web platform where you&amp;#8217;re publishing it. You should be able to work on it locally on your machine. Blogs don&amp;#8217;t usually give you that kind of freedom. There might be some APIs for importing and exporting blog posts, but that doesn&amp;#8217;t quite cut it. I&amp;#8217;m thinking of ownership here in terms of how you own your project that you&amp;#8217;ve published on github. You have the git repository on your local machine, &lt;em&gt;all the time&lt;/em&gt;. If github disappears, you can publish your local git repository somewhere else. If Google disappears, all your blog posts and Google Docs also disappear. (It&amp;#8217;s much more likely for your computer to break down than for Google to disappear, but it&amp;#8217;s always possible that &lt;a href="http://sunpig.com/martin/archives/2011/07/03/google-made-my-son-cry.html" target="_blank"&gt;Google may suspend your account and delete your content&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Another important thing for this kind of writing platform is how the content is presented. Most blogs allow you to make your blog ugly and stupid in all kinds of different ways. Silly color schemes, useless widgets everywhere, picture backgrounds, etc. I much prefer there be a single, good, minimal theme, or just a few of them to choose from.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://pen.io" target="_blank"&gt;Pen.io&lt;/a&gt; seems like a such a writing platform, though it doesn&amp;#8217;t fulfill the content-ownership I talked about.&lt;/p&gt;

&lt;p&gt;Google Docs also allows you to do pretty much the same, and it&amp;#8217;s much better at being a &lt;em&gt;writing&lt;/em&gt; tool than pen.io and other blogs, but it&amp;#8217;s not &amp;#8220;webby&amp;#8221; at all. You can &amp;#8220;publish&amp;#8221; your writings, but they have a long cryptic URL, and there are no interaction features what so ever.&lt;/p&gt;

&lt;p&gt;Any writing and publishing platform on the web needs to have some way of interacting with readers and the rest of the web. Some kind of a commenting system seems necessary. I&amp;#8217;m not sure if comments should be right on the essay page (like most blogs) or in a separate place. For some reason I prefer to have the comments somewhat &amp;#8220;detached&amp;#8221; from the essay itself, but at the same time readily accessible from it. A simple way to do that is by having a link at the top and/or bottom of the essay to a &amp;#8220;discussion page&amp;#8221;. The discussion page would also have a link to the original essay at the top and/or the bottom.&lt;/p&gt;</description><link>http://dev.hasenj.org/post/7335724881</link><guid>http://dev.hasenj.org/post/7335724881</guid><pubDate>Thu, 07 Jul 2011 01:28:00 -0600</pubDate></item><item><title>Webpage titles</title><description>&lt;p&gt;I just had this idea. The title of a wepage should try to be as short as possible. Perhaps a 5-letter word.&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;&lt;p&gt;Titles (along with icons) are used to recognize tabs in a multi-tabbed browser. Keep that in mind. For the title to be useful, it has to be short, otherwise the browser will cut it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Titles are also used when creating bookmarks; long titles force the user to do the useless task of editing a bookmark name from &amp;#8220;YouTube! Broadcase yourself!&amp;#8221; to &amp;#8220;uTube&amp;#8221;. Why not just make it &amp;#8220;uTube&amp;#8221; to begin with?&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;</description><link>http://dev.hasenj.org/post/5726587727</link><guid>http://dev.hasenj.org/post/5726587727</guid><pubDate>Sun, 22 May 2011 03:13:09 -0600</pubDate></item><item><title>PySide + QtQuick Tutorial</title><description>&lt;a href="http://developer.qt.nokia.com/wiki/Hello_World_in_PySide_and_QtQuick"&gt;PySide + QtQuick Tutorial&lt;/a&gt;: &lt;p&gt;I’m just looking around for tutorials, and just found this (haven’t even read it yet, but seeing as its in the official wiki, it’s gotta be good).&lt;/p&gt;</description><link>http://dev.hasenj.org/post/5446015174</link><guid>http://dev.hasenj.org/post/5446015174</guid><pubDate>Fri, 13 May 2011 02:51:36 -0600</pubDate></item><item><title>bash: mkdir + cd with one command</title><description>&lt;p&gt;&lt;a href="http://codedump.tumblr.com/post/68215495" class="tumblr_blog" target="_blank"&gt;codedump&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;&lt;pre&gt;&lt;code&gt;function mkcd() {
  [ -n "$1" ] &amp;amp;&amp;amp; mkdir -p "$@" &amp;amp;&amp;amp; cd "$1";
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;user@host:~$ cd work
user@host:~/work$ mkcd website.com/{html,src,stuff}
user@host:~/work/website.com/html$&lt;/code&gt;&lt;/pre&gt;&lt;/blockquote&gt;</description><link>http://dev.hasenj.org/post/4864412064</link><guid>http://dev.hasenj.org/post/4864412064</guid><pubDate>Sat, 23 Apr 2011 07:19:50 -0600</pubDate></item><item><title>Synthesizing music</title><description>&lt;p&gt;Please be warned again that this is &lt;em&gt;not&lt;/em&gt; my area of expertise. Don&amp;#8217;t take anything I say too seriously. At best anything I say it just a reasonable approximation that happens to work for me.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;m assuming you&amp;#8217;re trying to generate musical tones, so I&amp;#8217;ll talk about frequencies as if you already know what frequency you want to produce. I will also be using coffee-script and the Firefox Audio Data API.&lt;/p&gt;

&lt;p&gt;The max value of a sample is &lt;code&gt;1.0&lt;/code&gt; and the min value is &lt;code&gt;-1.0&lt;/code&gt; so all samples will be between these two values (these are the &amp;#8220;peaks&amp;#8221; of the volume).&lt;/p&gt;

&lt;h3&gt;Frequency / Period&lt;/h3&gt;

&lt;p&gt;If you consider a sound sample to be a sequence of a repeating shape, then count how many times per second does the shape repeat? This is called the &amp;#8220;period&amp;#8221; (e.g. the period of the sample/signal). The frequency then will be &lt;code&gt;1/p&lt;/code&gt; (where p is the period).&lt;/p&gt;

&lt;p&gt;If your sample rate is &lt;code&gt;SRATE&lt;/code&gt;, then that&amp;#8217;s how many samples are there in a second. So, to get how many samples are required to generate one period &lt;code&gt;p&lt;/code&gt;, it&amp;#8217;s &lt;code&gt;srate/freq&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Technically this is the &amp;#8220;fundamental frequency&amp;#8221; but I&amp;#8217;m not too deep on the math of signal processing.&lt;/p&gt;

&lt;h3&gt;Sine waves&lt;/h3&gt;

&lt;p&gt;Sine waves produce a pure &amp;#8220;peeeeeeep&amp;#8221; sound. Generally speaking a sine wave is a good start when you&amp;#8217;re hacking around, but I don&amp;#8217;t know if you can get far enough with it. The formula for generating a sound wave doesn&amp;#8217;t require calculating the period or anything like that; just the frequency.&lt;/p&gt;

&lt;p&gt;The formula for it is simple mathematically: given a &lt;code&gt;point&lt;/code&gt; in a long sound sample (think of point as &lt;code&gt;index&lt;/code&gt;):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sine = (freq, point) -&amp;gt;
    k = 2 * Math.PI * freq / SRATE
    Math.sin(k * point)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is not very efficient as you keep calculating &lt;code&gt;k&lt;/code&gt; over and over, so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sine = (freq) -&amp;gt;
    k = 2 * Math.PI * freq / SRATE
    (point) -&amp;gt; Math.sin(k * point)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now &lt;code&gt;sine(440)&lt;/code&gt; returns a function that takes a point and returns a sample value.&lt;/p&gt;

&lt;p&gt;Sine waves are not very interesting like I already said. I thought we&amp;#8217;d build more complex sounds on top of them, but it turns out they&amp;#8217;re not needed at all when synthesizing string sounds using the karplus-strong algorithm. Perhaps sine waves are useful when generating sounds in another way.&lt;/p&gt;

&lt;p&gt;There are a few extra things you should take note of, I already mentioned them here:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://dev.hasenj.org/post/4381348236/quick-notes-on-generating-sine-waves" target="_blank"&gt;Quick notes on generating sine waves&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Basically you&amp;#8217;ll need to dampen the signal using &lt;code&gt;e^(-5x)&lt;/code&gt; (you can change 5 to 4 or something else &amp;#8212; feel free to experiment with it). To get x you have to know &lt;em&gt;when&lt;/em&gt; do you want the signal to end.&lt;/p&gt;

&lt;p&gt;In code would look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;dampen = (point, lastpoint) -&amp;gt;
    x = point / lastpoint
    Math.pow(Math.E, x * -5)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When you write the output, you multiply the sample from &lt;code&gt;sine&lt;/code&gt; by the damp factor from &lt;code&gt;dampen&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;And the pink noise process is dead simple: you multiply the signal by &lt;code&gt;100/freq&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;s = sinefn(point)
d = dampen(point, lastpoint)
p = 100/freq
output[point] = s * d * p
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Wavetables&lt;/h3&gt;

&lt;p&gt;Another way to generate sound is to use a pre-populated list. For some reason this list is called a wavetable. Please don&amp;#8217;t confuse this table with hash-tables or dictionaries: it&amp;#8217;s just an array of values.&lt;/p&gt;

&lt;p&gt;For a sound of frequency &lt;code&gt;freq&lt;/code&gt;, the size of the wavetable is &lt;code&gt;SRATE/freq&lt;/code&gt;. Now this actually doesn&amp;#8217;t produce exactly the desired frequency, but a close enough frequency that the ear can&amp;#8217;t differentiate really.&lt;/p&gt;

&lt;p&gt;See, if you want to generate a wavetable for the frequency 440, here&amp;#8217;s what would happen:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;coffee&amp;gt; SRATE = 96000
96000
coffee&amp;gt; freq = 440
440
coffee&amp;gt; SRATE/freq
218.1818181818182
coffee&amp;gt; Math.floor SRATE/freq
218
coffee&amp;gt; SRATE / 218
440.3669724770642
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The period length would be 218, but that&amp;#8217;s the period associated with frequency &lt;code&gt;440.4&lt;/code&gt;. This difference is like I said small enough that the human ear doesn&amp;#8217;t notice a thing.&lt;/p&gt;

&lt;p&gt;So if you pre-populate an array of this size, you can generate the samples on the fly:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;length = Math.round SRATE/freq
wavetable = new Float32Array(length)
# fill table somehow
(point) -&amp;gt;
    wavetable[point % length]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Since the process of pre-populating itself can be time-consuming, we can do it lazily:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(point) -&amp;gt;
    if point &amp;lt; length
        wavetable[point] = wavefn(point)
    else
        wavetable[point % length]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This leads us to the Karplus-Strong method of synthesizing guitar strings, which I already wrote about here:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://dev.hasenj.org/post/4517734448/very-simple-implementation-of-karplus-strong-algorithm" target="_blank"&gt;Very simple implementation of Karplus-Strong algorithm in coffeescript&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Note that it doesn&amp;#8217;t make use of sine waves at all. Instead, it starts with a noise sample and causes it to decay in a very simple-minded way. It&amp;#8217;s very surprising (to me at least) that it manages to generate a sound like that.&lt;/p&gt;

&lt;p&gt;OK, this sums up my experience so far. Unfortunately I haven&amp;#8217;t come across the ultimate function that can generate any kind of musical instrument :) but that ok, since it wasn&amp;#8217;t my goal to begin with.&lt;/p&gt;</description><link>http://dev.hasenj.org/post/4688823524</link><guid>http://dev.hasenj.org/post/4688823524</guid><pubDate>Sun, 17 Apr 2011 08:31:00 -0600</pubDate><category>oud</category><category>music</category><category>awtar</category></item><item><title>Very simple implementation of Karplus-Strong algorithm in coffeescript</title><description>&lt;p&gt;I&amp;#8217;m a bit over excited as I just managed to successfully implement Karplus-Strong&amp;#8217;s guitar string algorithm.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://en.wikipedia.org/wiki/Karplus-Strong_string_synthesis" target="_blank"&gt;http://en.wikipedia.org/wiki/Karplus-Strong_string_synthesis&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The Wikipedia description was too complicated for me. I had to get the original paper and try to study it. It&amp;#8217;s rather old and the terminology was a bit weird, so it took me a while to really understand it.&lt;/p&gt;

&lt;p&gt;This snippet assumes you have &lt;code&gt;SRATE&lt;/code&gt; defined somewhere (the sample rate), and that you already managed to setup the audio output and the mixer and everything else. I&amp;#8217;m using &lt;code&gt;audiodata.js&lt;/code&gt; to output audio using Firefox4&amp;#8217;s Audio Data API.&lt;/p&gt;

&lt;p&gt;The function &lt;code&gt;guitar&lt;/code&gt; here returns a function which takes a sample index/point and returns the sample. It assumes that it will be called with all the samples sequentially, otherwise it won&amp;#8217;t work. Something like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;signal_fn = guitar(440) # 440 being the frequency we want to sound

point = 0
while not done
    sample = signal_fn(point++)
    # output sample
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Not exactly that, but something like that.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s the code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;period_len = (freq) -&amp;gt; Math.floor (SRATE/freq)

avg = (a, b) -&amp;gt; (a + b) / 2

ks_noise_sample = (val) -&amp;gt;
    # get either val or -val with 50% chance
    if Math.random() &amp;gt; 0.5
        val
    else
        -val

# karplus strong algorithm
guitar = (freq) -&amp;gt;
    samples = period_len freq
    table = new Float32Array(samples)
    getsample = (index) -&amp;gt;
        point = index % samples
        if index == point
            table[point] = ks_noise_sample(1)
        else
            prev = (index - 1) % samples
            table[point] = avg(table[point], table[prev])
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that this is coffee-script, where the last expression in a function is returned, and &lt;code&gt;A = B&lt;/code&gt; expressions return &lt;code&gt;B&lt;/code&gt;. So, &lt;code&gt;guitar&lt;/code&gt; returns the &lt;code&gt;getsample&lt;/code&gt; function, and &lt;code&gt;getsample&lt;/code&gt; return &lt;code&gt;table[point]&lt;/code&gt; after we calculate it.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s what this does:&lt;/p&gt;

&lt;p&gt;Fill a table of length &lt;code&gt;p&lt;/code&gt; with random values (actually: fill it with either A or -A, with 50% chance each). Where &lt;code&gt;p&lt;/code&gt; is the period of the signal, which is the &lt;code&gt;sample_rate/frequency&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To produce samples, just keep cycling on this table. That is, to get any point &lt;code&gt;t&lt;/code&gt;, take &lt;code&gt;table[t % p]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;BUT, as you loop on the table, average each two adjacent samples. That is, everytime you get &lt;code&gt;table[t]&lt;/code&gt; (except the first time around), let &lt;code&gt;table[t]&lt;/code&gt; be &lt;code&gt;(table[t] + table[t-1]) / 2&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This causes the signal to decay overtime, or something like that.&lt;/p&gt;

&lt;p&gt;That&amp;#8217;s it.&lt;/p&gt;</description><link>http://dev.hasenj.org/post/4517734448</link><guid>http://dev.hasenj.org/post/4517734448</guid><pubDate>Mon, 11 Apr 2011 00:52:00 -0600</pubDate><category>guitar</category><category>hacking</category><category>music</category><category>oud</category><category>awtar</category></item><item><title>Quick notes on generating sine waves</title><description>&lt;p&gt;A few notes based on my experiments the past couple of days.&lt;/p&gt;

&lt;p&gt;First, when you manage to generate a sine wave, you&amp;#8217;ll notice there&amp;#8217;s a &amp;#8220;clicking&amp;#8221; sound at the end. Where does it come from and how to deal with it? I think it comes from having the volume suddenly drop to 0. So to make it go away, you gotta make the wave form fade away slowly and gradually.&lt;/p&gt;

&lt;p&gt;The graph of &lt;code&gt;e^(-2x)&lt;/code&gt; looks like a good smooth path for that.&lt;/p&gt;

&lt;p&gt;Second, you&amp;#8217;ll notes that high frequencies sound way louder than low frequencies. To work around that, multiply the samples by &lt;code&gt;1/freq&lt;/code&gt; (see: &lt;a href="http://en.wikipedia.org/wiki/Pink_noise" target="_blank"&gt;pink noise&lt;/a&gt;). This makes each tone sound the same loudness. (In reality you use a multiple of &lt;code&gt;1/freq&lt;/code&gt;, for for instance, I used &lt;code&gt;100/freq&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;I realize this is way out of context and perhaps won&amp;#8217;t make sense to most people. I&amp;#8217;ll talk more about generating sound waves later. But I wanted to jot down these quick notes before I forget.&lt;/p&gt;</description><link>http://dev.hasenj.org/post/4381348236</link><guid>http://dev.hasenj.org/post/4381348236</guid><pubDate>Tue, 05 Apr 2011 20:39:52 -0600</pubDate></item></channel></rss>
