<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Rob&#039;s Blog</title>
	<atom:link href="http://www.robbritton.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.robbritton.com</link>
	<description></description>
	<lastBuildDate>Mon, 27 Feb 2012 15:40:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Vim Relative Line Numbers</title>
		<link>http://www.robbritton.com/2012/02/27/vim-relative-line-numbers/</link>
		<comments>http://www.robbritton.com/2012/02/27/vim-relative-line-numbers/#comments</comments>
		<pubDate>Mon, 27 Feb 2012 15:40:17 +0000</pubDate>
		<dc:creator>rob</dc:creator>
				<category><![CDATA[vim]]></category>

		<guid isPermaLink="false">http://www.robbritton.com/?p=254</guid>
		<description><![CDATA[A little trick I learned the other day at Montreal.rb: relative-line numbering (can be enabled with :set rnu). The current line number is zero, and the left-hand column shows the distance from your cursor. This way you can easily do commands like d5k to delete the 5 lines above the cursor, or d5j to delete [...]]]></description>
			<content:encoded><![CDATA[<p>A little trick I learned the other day at <a href = "http://www.montrealonrails.com/">Montreal.rb</a>: relative-line numbering (can be enabled with <code>:set rnu</code>). The current line number is zero, and the left-hand column shows the distance from your cursor. This way you can easily do commands like <code>d5k</code> to delete the 5 lines above the cursor, or <code>d5j</code> to delete the 5 lines below it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.robbritton.com/2012/02/27/vim-relative-line-numbers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Asynchronous Function Looping in C#</title>
		<link>http://www.robbritton.com/2012/02/24/asynchronous-function-looping-in-c/</link>
		<comments>http://www.robbritton.com/2012/02/24/asynchronous-function-looping-in-c/#comments</comments>
		<pubDate>Fri, 24 Feb 2012 17:42:40 +0000</pubDate>
		<dc:creator>rob</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.robbritton.com/?p=256</guid>
		<description><![CDATA[It is often the case in code that you have to do several things in a sequence since each computation is dependent on the one(s) before it: // ... // stuff 1 // ... // stuff 2 // ... // stuff 3 // ... etc. Good software techniques will tell you that you should break [...]]]></description>
			<content:encoded><![CDATA[<p>It is often the case in code that you have to do several things in a sequence since each computation is dependent on the one(s) before it:
<pre>// ...
// stuff 1
// ...
// stuff 2
// ...
// stuff 3
// ... etc.</pre>
<p>Good software techniques will tell you that you should break some of these up into methods:
<pre>
stuff1();
stuff2();
stuff3();</pre>
<p>If it gets big, you can even put it all in a collection and iterate (we&#8217;re starting to get into weird coding now, I don&#8217;t think anybody would actually do this):
<pre>var collection = new List&lt;Action&gt;() { stuff1, stuff2, stuff3 };
foreach (var func in collection){
  func();
}</pre>
<p>Now the part where this would actually be useful. What if some of these functions could potentially be asynchronous? That is, they depend on some value that may not be readily available &#8211; maybe user input, maybe some data from a network, etc. Blocking is not usually a great option &#8211; a modal dialog demands that the user pays attention to it even if there is something more important somewhere else. It would be better if this computation could &#8220;pause&#8221; and then resume later on when we get what we need. In some languages including Scheme and Ruby, you can accomplish this using a construct called <code>callcc</code>:
<pre>var collection = new List&lt;Action&lt;Action&gt;&gt;() { stuff1, stuff2,
                                              stuff3 };
foreach (var func in collection){
  // pseudo-code warning
  call_cc(func);
}</pre>
<p>Here, <code>call_cc()</code> will call <code>func</code> and pass in a function which will start executing right after the <code>call_cc()</code> call: it is a <i>continuation</i> of the loop. When <code>func</code> is done (or when it receives the response it wants), it can call this function to nicely continue executing the loop.</p>
<p>Unfortunately, C# 4.0 and lower do not support anything like <code>callcc</code>. C# 5.0 will support the <code>await</code> and <code>async</code> keywords which will accomplish exactly what we want, but for the time being we&#8217;ll have to make do with what we have. How can we do that without <code>callcc</code>?</p>
<p>Let&#8217;s give it a shot using a recursive function:
<pre>void AsyncForeach(IEnumerator&lt;Action&lt;Action&gt;&gt; iter){
  if (iter.MoveNext()){
    iter.Current( () => {
      AsyncForeach(iter);
    });
  }
}
void OtherFunc(){
  // ...
  var collection = new List&lt;Action&lt;Action&gt;&gt;() { stuff1, stuff2,
                                                stuff3 };

  AsyncForeach(collection.GetEnumerator());
}</pre>
<p>This would require every function in <code>collection</code> adhere to the <code>Action&lt;Action&gt;</code> delegate and when it is done, it will need to call the continuation manually in order to resume the computation. This is a bit annoying, and it&#8217;s why all the <code>BeginConnect</code>, <code>BeginSend</code>, etc. in <code>System.Net</code> require an <code>AsyncCallback</code> to call when they are done. The new <code>async</code> and <code>await</code> keywords will be extremely useful to accomplish our task since everything is called automatically:
<pre>var collection = new List&lt;Action&gt;() { stuff1, stuff2, stuff3 };
foreach (var func in collection){
  // func doesn't even need to call anything to
  // keep this thing going!
  await func();
}</pre>
<p>It is useful to learn this from approach though. Say we want to halt the loop prematurely from within one of the functions. In that case, the function could simply not call the continuation. That would end our recursion, causing us to break out of our loop &#8211; the equivalent of the <code>break</code> keyword. In order to do that with the <code>await</code> keyword we&#8217;d have to have some sort of exception handling system, or return type, etc.</p>
<p>We could go even further and implement something similar to Python&#8217;s <code>for...else</code> construct where if <code>break</code> is called somewhere in the computation it will run the <code>else</code> block:
<pre>for i in range(10):
  if i == 5:
    break
else:
  # this is executed
  print "should run"

for i in range(10):
  if i == 12:
    break
else:
  # this is not executed
  print "should not run"</pre>
<p>We can do this by adding failure &#8220;continuations&#8221; to our functions:
<pre>void AsyncForeach(IEnumerator&lt;Action&lt;Action, Action&gt;&gt; iter,
                  Action failure){
  if (iter.MoveNext()){
    iter.Current( () => {
      AsyncForeach(iter, failure);
    }, failure);
  }
}
void OtherFunc(){
  // ...
  var collection =
    new List&lt;Action&lt;Action, Action&gt;&gt;() { stuff1, stuff2, stuff3 };

  AsyncForeach(collection.GetEnumerator(), () => {
    // handle failure
  });
}</pre>
<p>In this case the functions <code>stuff1</code>, <code>stuff2</code>, etc. will call the first function if they should continue looping, or call the second one in case of failure.</p>
<p>There&#8217;s one final tweak to all of this. At the moment there are two problems with <code>AsyncForeach</code>: it depends on the type of the list we&#8217;re iterating over (<code>IEnumerator&lt;Action&lt;Action, Action&gt;&gt;</code>), and it does not close over any variables that we may need for the loop. Can we do this using a closure?</p>
<p>In fact, we can:
<pre>var collection =
    new List&lt;Action&lt;Action, Action&gt;&gt;() { stuff1, stuff2, stuff3 };

// declare looper early so that it closes over itself
Action looper = null;
var iter = collection.GetEnumerator();
looper = () => {
  if (iter.MoveNext()){
    iter.Current(looper, () => {
      // handle failure
    });
  }
};
// don't forget to start the loop
looper();</pre>
<p>Since this isn&#8217;t so DRY, we can top it all off with a function that returns a function:
<pre>Action GetAsyncForeach&lt;T&gt;(IEnumerable&lt;T&gt; collection,
                          Action&lt;T&gt; body){
  var iter = collection.GetEnumerator();
  return () => {
    if (iter.MoveNext()){
      body(iter.Current);
    }
  };
}

void OtherFunc(){
  // ...
  var collection =
    new List&lt;Action&lt;Action, Action&gt;&gt;() { stuff1, stuff2, stuff3 };

  Action checker = null;
  checker = GetAsyncForeach(collection, (current) => {
    current(checker, () => {
      // handle failure
    });
  });
  checker(); // start the loop
}</pre>
<p>We now have a DRY, re-usable component for implementing an asynchronous foreach loop in our code. It&#8217;s not the most elegant approach, but it works really well and we don&#8217;t need that much extra boiler plate to get this done (if C# supported a <code>let rec</code> keyword, we could make it even shorter!).</p>
<p>This is a useful method of looping through some asynchronous tasks that you may have to do. I found myself needing this sort of thing when calling <code>ShowDialog</code> would lock the entire GUI while the system waited for the user to input something, however sometimes the user would have to attend to something else before responding to the dialog. Since later actions in the loop depended on the result of the dialog box, a more asynchronous method was necessary.</p>
<p>Ultimately, this is why I believe that all programmers should have some experience with functional programming; this is a technique that would be obvious to a programmer in Lisp or OCaml but might be a bit trickier to someone who just has OO experience. Having functional programming know-how in your toolbelt will make you a better C# programmer.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.robbritton.com/2012/02/24/asynchronous-function-looping-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Non-deterministic Programming &#8211; Amb</title>
		<link>http://www.robbritton.com/2012/02/13/non-deterministic-programming-amb/</link>
		<comments>http://www.robbritton.com/2012/02/13/non-deterministic-programming-amb/#comments</comments>
		<pubDate>Mon, 13 Feb 2012 03:15:49 +0000</pubDate>
		<dc:creator>rob</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.robbritton.com/?p=189</guid>
		<description><![CDATA[I&#8217;ve been very slowly plowing through SICP and I&#8217;ve recently read through their chapter on non-deterministic programming. When you program this way your variables no longer have just one value, they can take on all of their possible values until stated otherwise. An example: x = amb(1, 2, 3, 4) In this case x is [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been very slowly plowing through <a href = "http://mitpress.mit.edu/sicp/">SICP</a> and I&#8217;ve recently read through their chapter on <a href = "http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-28.html#%_sec_4.3">non-deterministic programming</a>. When you program this way your variables no longer have just one value, they can take on <i>all</i> of their possible values until stated otherwise. An example:
<pre>x = amb(1, 2, 3, 4)</pre>
<p>In this case <code>x</code> is all of 1, 2, 3, and 4. If you try to print out <code>x</code> it will print out 1 because the act of printing it temporarily forces a value, but otherwise you can treat the variable as though it had all of those values.</p>
<p>You can then force certain subsets of the values with assertions:
<pre>assert x.odd?</pre>
<p>In this case <code>x</code> would become just 1 and 3. If you then added a final assertion that <code>x > 2</code> you would force a single value and <code>x</code> would be 3. If you instead added the assertion <code>x > 3</code> then <code>x</code> would have no values: an exception would be thrown saying that <code>x</code> is basically &#8220;impossible&#8221;.</p>
<p>This is useful when you are searching for something. Suppose you&#8217;re trying to find numbers that satisfy Pythagorus&#8217; theorem:
<pre>a = amb(*1..10)
b = amb(*1..10)
c = amb(*1..10)

assert a**2 + b**2 == c**2

puts a, b, c
next_value
puts a, b, c</pre>
<p>This code would print out 3, 4, and 5 on the first output, followed by 6, 8, and 10 on the second. The <code>next_value</code> function would tell the <code>amb</code> system to find another solution to the set of variables that satisfy the assertions we specified. If nothing else is found, an exception will be thrown.</p>
<p>Even more interesting, there is a library in Ruby called <a href = "https://github.com/chikamichi/amb">amb</a> that implements this stuff. Unfortunately it doesn&#8217;t work just like the above example, you can only get the either the first set of values that fit, or all of them:
<pre>require 'rubygems'
require 'amb'
include Amb::Operator

a = amb(*1..10)
b = amb(*1..10)
c = amb(*1..10)

# calling amb with no arguments causes it
# to backtrack until the criteria is met
amb unless a*a + b*b == c*c

# prints out the first match
puts "#{a}, #{b}, #{c}"

# prints out every match and then crashes
amb
puts "#{a}, #{b}, #{c}"</pre>
<p>This is a pretty cool way to program, and it would be interesting to know when it might be practical to use. I tried it with a couple of problems on <a href = "http://projecteuler.net/">Project Euler</a> but unfortunately since the backtracking method that <code>amb</code> uses isn&#8217;t always the most efficient approach it would choke a bit. Perhaps if this gem gets some attention and some love, it might end up as something a bit more performant!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.robbritton.com/2012/02/13/non-deterministic-programming-amb/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Brilliant Design of Magic Ink</title>
		<link>http://www.robbritton.com/2012/02/10/the-brilliant-design-of-magic-ink/</link>
		<comments>http://www.robbritton.com/2012/02/10/the-brilliant-design-of-magic-ink/#comments</comments>
		<pubDate>Fri, 10 Feb 2012 18:56:27 +0000</pubDate>
		<dc:creator>rob</dc:creator>
				<category><![CDATA[art]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[ui]]></category>

		<guid isPermaLink="false">http://www.robbritton.com/?p=236</guid>
		<description><![CDATA[I&#8217;ve been plowing through Bret Victor&#8217;s Magic Ink essay and I&#8217;ve noticed a set of very interesting UI elements that I really enjoy and hope to add to my style of writing (it might even be worth it to add these features to WordPress&#8217; publishing code). These are: Anchors at every paragraph: the essay is [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been plowing through Bret Victor&#8217;s <a href = "http://worrydream.com/MagicInk/">Magic Ink</a> essay and I&#8217;ve noticed a set of very interesting UI elements that I really enjoy and hope to add to my style of writing (it might even be worth it to add these features to WordPress&#8217; publishing code).</p>
<p>These are:
<ul>
<li>Anchors at every paragraph: the essay is long. When I sent it to some of the fellow programmers at work, the first thing they did was complain about how long it was. Since you don&#8217;t usually read a 50 page essay in one sitting, you need a way to bookmark not only the page you are on (useless since everything is on one page) but where you are on that page. Victor takes advantage of HTML&#8217;s ability to set anchor points within a page to anchor <i>every</i> paragraph so that when you don&#8217;t really want to read anymore, you can just click on the hash next to paragraph (only visible when you mouse over the paragraph) and it will update your address bar to anchor to that paragraph. This is not exactly fancy modern technology, this entire feature just takes advantage of named anchors and the fact that when you click on one the browser doesn&#8217;t reload the page. Extremely useful for long essays, yet I can&#8217;t recall seeing this anywhere else.</li>
<li>Footnotes/endnotes are actually sidenotes. It&#8217;s a bit annoying when you read an essay online that has footnotes/endnotes with a star or a cross or something and you have to scroll all the way to the bottom to see those notes (some posts make it easier by providing a link, but as vi users know moving your hand to the mouse is a pain). It takes effort and there is a disconnect between when you read what you are writing and navigating to wherever the note is. By putting the note on the side next to the paragraph, it is much easier to just move your eyes to look at the note rather scrolling or clicking. This comes at the cost of screen real-estate, however if you make the actual content of your essay thinner you don&#8217;t lose a whole lot since there is still a flow when you&#8217;re reading line-to-line.</li>
</ul>
<p>I really like these UI tweaks because they are so incredibly simple, yet somehow are not very common practice. If ever I write something that is long and actually decent enough to slog through I hope to remember these little features to help people better read my stuff.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.robbritton.com/2012/02/10/the-brilliant-design-of-magic-ink/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Thoughts on Stanford&#8217;s Online Courses</title>
		<link>http://www.robbritton.com/2012/01/27/thoughts-on-stanfords-online-courses/</link>
		<comments>http://www.robbritton.com/2012/01/27/thoughts-on-stanfords-online-courses/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 20:37:17 +0000</pubDate>
		<dc:creator>rob</dc:creator>
				<category><![CDATA[learning]]></category>

		<guid isPermaLink="false">http://www.robbritton.com/?p=195</guid>
		<description><![CDATA[Last year I enrolled in a couple of the extremely popular Stanford online classes: Intro to AI and Machine Learning. While many other people who took the courses also wrote on the topic I feel like none of the descriptions quite matched how I feel about the courses, so I think I will talk about [...]]]></description>
			<content:encoded><![CDATA[<p>Last year I enrolled in a couple of the extremely popular Stanford online classes: <a href = "https://www.ai-class.com/">Intro to AI</a> and <a href = "http://www.ml-class.org/">Machine Learning</a>. While many other people who took the courses also wrote on the topic I feel like none of the descriptions quite matched how I feel about the courses, so I think I will talk about them a little bit here.</p>
<p>First, the good things:</p>
<ul>
<li><b>The connection</b> &#8211; I feel like in a course like this you have a much closer connection to the professor than you do in recorded videos like the MIT OpenCourseWare lectures or even a real classroom (with the exception of smaller class sizes) since the professor is talking directly to the camera or the camera is filming some sort of drawing surface. The professors were all extremely passionate about their topics and talked about them with so much enthusiasm (especially Sebastian Thrun) that I couldn&#8217;t help but feel more enthusiastic about the topics as well &#8211; although I didn&#8217;t really need the help, I found the courses very interesting! Despite the fact that in reality the video method of teaching is extremely impersonal, it seems much more personal because it is like a one-on-one enviroment where the professor is talking just to you instead of an entire classroom. Most of the time this makes you feel like you have to pay attention! Compare this to a class of 100+ students where if you fall asleep, zone out, or start doodling it&#8217;s not likely the professor will notice or care.</li>
<li><b>The flexibility</b> &#8211; Picture scenario one: you&#8217;re sitting in your living room in a comfy chair covered in a warm blanket sipping delicious beer. You&#8217;re watching the online videos on your laptop while occasionally pausing the video to go get a snack, do some chores, or check on dinner.<br />
Now picture scenario two: you&#8217;re sitting in a hard plastic chair in a windowless room dimly lit by the projection of PowerPoint slides onto the wall (you&#8217;ve all had a class like that, don&#8217;t lie) at 8am in the morning. Some guy is chewing loudly in the seat behind you while someone, somewhere is rapidly tapping their pen against the desk.<br />
Which enviroment would you prefer? While these are two extreme examples, personally I would prefer the former.</li>
<li><b>The technology</b> &#8211; I found the websites modern and very easy to navigate with no clutter distracting you from what you were looking for. The two main hiccups that I noticed with the technology:
<ul>
<li>With the AI class the videos wouldn&#8217;t always skip ahead to the next video or to the quiz &#8211; probably because I was watching the videos under Linux. The first time it happened it took a little while to realize that you could click on the question mark to access the quiz.</li>
<li>With the ML class the video would appear on a &#8220;pop-up&#8221; div inside the window and the background would fade out, but if you clicked on the background it would close the video. This was annoying when you flip to another window but then click on the browser to re-focus it and end up killing the video.</li>
</ul>
<p>These aren&#8217;t huge problems, just little bugs or UI quirks that are expected with new software. I really enjoyed the submission system for the ML class where you could submit your assignments directly from within Octave by typing <code>submit</code>. I&#8217;ve had some programming classes do this type of thing and it really makes it easy to get your work done.</li>
</ul>
<p>Some things I found so-so:</p>
<ul>
<li><b>The content</b> &#8211; I&#8217;m going to be a little harsh. The content was very interesting for both courses, however I found myself disappointed with the depth of the knowledge. It seemed like we were only scratching the surface of the topics without going into the detail or rigour that I would expect from a full university course. Then again, this is an introductory course and it has been a long time since I took an introductory course to anything. Maybe I&#8217;m just biased.</li>
</ul>
<p>Inevitably, the downsides:</p>
<ul>
<li><b>The assignments</b> &#8211; I&#8217;m a person that learns by doing. I can see the things in the lecture and understand them fully, but everything tends to go in one ear and right out the other. When it comes to applying the concepts learned in the lecture I need to do it myself before the material really sinks in. In the AI class I found that the only assignment/quiz that I really connected with was the optional assignment for a simple decryption problem using NLP and statistics that was presented at the very end of the course. The rest of the assignments were just quizzes and while you do learn something by having to answer questions, I felt that the learning wasn&#8217;t quite as deep on these topics as it could have been if we were actually supposed to program something.<br />With the ML class they actually did have programming assignments in addition to quizzes, however with those I found that most of the time all you really had to do was translate the equations from the ones written in the assignment description to Octave and it would work. You weren&#8217;t really learning and understanding what was going on, you were essentially just copying and pasting. I feel like I would have learned a lot more if the assignments had a bit more challenge to them.</li>
<li><b>Lack of interaction</b> &#8211;  Some of my favourite classes involved a good deal of interaction between the professor and/or the other members of the class (seminar or lab classes come to mind). In these types of classes the interaction component is a huge benefit to learning compared to the StackOverflow-style Q&#038;A forums that they had for the AI class. Because of the online nature of the courses, there isn&#8217;t really a solution to this problem that I&#8217;m aware of.</li>
</ul>
<p>I will most certainly continue to spend free time taking these online classes, unfortunately there are too many courses that I would like to take and not enough time to take them (I had this same problem back when I was in university). One thing that would be great to see is a Khan Academy style approach where you can take the class whenever you want instead of just during the semesters that they are offered.</p>
<p>In the very unlikely chance that any of the Stanford profs read this, thanks! I really have enjoyed the classes and will continue taking them for a long time yet.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.robbritton.com/2012/01/27/thoughts-on-stanfords-online-courses/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamic Pictures</title>
		<link>http://www.robbritton.com/2012/01/23/dynamic-pictures/</link>
		<comments>http://www.robbritton.com/2012/01/23/dynamic-pictures/#comments</comments>
		<pubDate>Mon, 23 Jan 2012 19:43:15 +0000</pubDate>
		<dc:creator>rob</dc:creator>
				<category><![CDATA[art]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.robbritton.com/?p=125</guid>
		<description><![CDATA[At CUSEC 2012 a programmer/designer by the name of Bret Victor gave one of the most interesting presentations at the conference (he received a standing ovation for it) on the importance of having visual connections between the code you write and what that code does. Among other things, he showed a very interesting prototype where [...]]]></description>
			<content:encoded><![CDATA[<p>At <a href = "http://2012.cusec.net/">CUSEC 2012</a> a programmer/designer by the name of <a href = "http://worrydream.com/">Bret Victor</a> gave one of the most interesting presentations at the conference (he received a standing ovation for it) on the importance of having visual connections between the code you write and what that code does.</p>
<p>Among other things, he showed a very interesting prototype where when you modify some Javascript code it will execute the code in real-time and show you exactly what will happen when you make those changes. On top of that, it provides a number of tools for &#8220;tweaking&#8221; constants: click on an integer and a slider will pop up above it that will modify that integer. As you move the slider the number will change, updating the visual display at the same time. Press the &#8216;.&#8217; after an object and it will give you an autocomplete list, but unlike every other autocomplete system it will actually show you what will happen if you call this method. Select drawRect and you will see a little black rectangle appear. Select arc and a little black circle will appear.</p>
<p>The demo worked amazingly well, however he admitted afterwards that they weren&#8217;t based on a program that works but just some proof-of-concept demos that don&#8217;t actually work outside of his presentation. That inspired me to actually attempt building some of this stuff to make it easier for people to build &#8220;dynamic pictures&#8221; &#8211; that is, pictures that change over time and respond to what the user might want to do. This is a non-trivial task because it not only involves processing the Javascript code live, but also determining what might be &#8220;good&#8221; values in each case. For example if you were to be adjusting numbers in context.lineTo() you might want to go between 0 and the width/height of the canvas, but if you were in context.arc() you would want to be adjusting angles. It would involve some kind of annotations to functions to determine what the valid ranges of values are for that argument.</p>
<p>You can check out the basic prototype <a href = "/dynamicpictures">here</a> (warning: it is very basic at the moment) and see the code on Github <a href = "https://github.com/robbrit/dynamicpictures">here</a>. When you enter code in the right-hand panel it will execute the code and any canvas drawing done will appear in the left-hand side.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.robbritton.com/2012/01/23/dynamic-pictures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>World Peak Oil</title>
		<link>http://www.robbritton.com/2011/12/28/world-peak-oil/</link>
		<comments>http://www.robbritton.com/2011/12/28/world-peak-oil/#comments</comments>
		<pubDate>Wed, 28 Dec 2011 23:52:54 +0000</pubDate>
		<dc:creator>rob</dc:creator>
				<category><![CDATA[economics]]></category>

		<guid isPermaLink="false">http://www.robbritton.com/?p=111</guid>
		<description><![CDATA[In my last post I wrote a bit about Canadian oil production vs. our proven reserves and gave some projections on how long our reserves might last. Our government says that our oil reserves will last 200 years, however I showed that that is subject to the fragile assumption that there will be no increase [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href = "http://www.robbritton.com/2011/12/27/canadian-peak-oil/">my last post</a> I wrote a bit about Canadian oil production vs. our proven reserves and gave some projections on how long our reserves might last. Our government says that our oil reserves will last 200 years, however I showed that that is subject to the fragile assumption that there will be no increase in production during that time. The post further shows that over the last 30 years Canadian oil production has averaged about 2.65% growth per year, so using that as a baseline for future oil growth the length of time until Canadian reserves run dry is about 70 years.</p>
<p>This post will blow all that out of the water and show that 70 years is much longer than a more realistic estimate.</p>
<p>I picked up some data from the CIA World Factbook on global oil <a href = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/2174rank.html">consumption</a> and <a href = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/2178rank.html">proven reserves</a>. From this we can see that world consumption is about 36.75 billion barrels of oil per year, and the total proven reserves is about 1.48 trillion barrels. If we do the simple calculation of just dividing reserves by consumption we get just over 40 years. This means that if oil consumption does not grow any more, we will run out of all the oil we have proven to exist in 2051. This seems like a long time away, however it is within one human lifetime: I will turn 65 in 2051.</p>
<p>That is assuming that there will be no growth in consumption during those 40 years. Looking at <a href = "http://www.indexmundi.com/energy.aspx">this page</a> the average growth rate in oil consumption is 1.18% per year (using a <a href = "http://en.wikipedia.org/wiki/Geometric_mean">geometric mean</a> since this is a growth rate). If we predict that oil consumption will continue to rise at this rate, we will run out of our reserves a bit sooner: just under 33 years from now, sometime in 2044. This is less than half of our prediction from the Canadian example, and one sixth of the Canadian government&#8217;s prediction of how long our oil supplies will last.</p>
<p>How is it that the amount of time here is so much smaller than in the Canadian case? Why is it that the world oil reserves will somehow be drained sooner than the Canadian ones, a logical impossibility? The main culprit here is our assumption that Canadian oil production will continue to grow at 2.65% and not something higher. If you look at <a href = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/2173rank.html">global oil production by country</a> you can see that four countries (Russia, the USA, China and Iran) all have much higher production than Canada but all have lower proven reserves; they will run out of their oil far sooner than we will. When that happens, consumers around the world who want oil will have to turn to somebody else. Will our 2.65% per year increase in production be able to satisfy those consumers once other sources start running out?</p>
<p>As in the last post, I am stressing that this is not driven by ideology. There is no liberal or conservative bias here, it is just numbers from reasonably good sources and simple, widely known mathematics. You can repeat this analysis yourself and see that you will come to the same numbers. The R code for this one is available <a href = "https://gist.github.com/1530380">here</a>, you&#8217;ll need the data that I listed above and then convert the CIA files from fixed-width format to CSV format.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.robbritton.com/2011/12/28/world-peak-oil/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Canadian Peak Oil</title>
		<link>http://www.robbritton.com/2011/12/27/canadian-peak-oil/</link>
		<comments>http://www.robbritton.com/2011/12/27/canadian-peak-oil/#comments</comments>
		<pubDate>Tue, 27 Dec 2011 01:39:39 +0000</pubDate>
		<dc:creator>rob</dc:creator>
				<category><![CDATA[economics]]></category>

		<guid isPermaLink="false">http://www.robbritton.com/?p=103</guid>
		<description><![CDATA[One thing that interested me back in my university days was peak oil &#8211; the idea that at some point, our ability to produce oil will at some point peak and then decline. It seemed very logical to me that given a finite resource and an ever-increasing demand for it, we will eventually run out. [...]]]></description>
			<content:encoded><![CDATA[<p>One thing that interested me back in my university days was peak oil &#8211; the idea that at some point, our ability to produce oil will at some point peak and then decline. It seemed very logical to me that given a finite resource and an ever-increasing demand for it, we will eventually run out. Given the drastic consequences that could happen if we happened to run out of this resource that seems to be used <i>everywhere</i>, it seemed like a good idea to be concerned about this problem and try to figure out how to at least minimize the damage should this disaster scenario come sometime soon.</p>
<p>Today I&#8217;m marginally wiser than I was then, so I like to verify myself if these types of things I hear through the media are true or not. I decided to look up some of the details about this whole peak oil thing and wonder, &#8220;when would this whole thing start going down?&#8221;</p>
<p>I looked on Natural Resources Canada&#8217;s web page to see some information about oil production. I found <a href = "http://www.nrcan.gc.ca/energy/sources/crude/1165">this tidbit</a> which says, &#8220;Canada&#8217;s oil reserves are sufficient to meet demand for the next 200 years at current rates of production.&#8221; Nice! I suppose that means I don&#8217;t have to care, and let the future generations figure out how they are going to deal with this problem.</p>
<p>Right?</p>
<p>Well, maybe not. The first thing we want to do is verify that this number is actually correct. After all, while we know that the government would <i>never</i> lie to us, it&#8217;s always a smart idea to figure things out for yourself in case somebody over there made a mistake.</p>
<p>To figure out our rate of extraction, <a href = "http://www.nrcan.gc.ca/energy/sources/crude/1287#us">this FAQ</a> tells us that Canada currently produces about 2.5 million barrels of crude oil per day (consistent with some data that is mentioned below). To figure out how much oil Canada has proved to have, <a href = "http://www.eia.gov/emeu/international/reserves.html">a 2010 report</a> by the US Energy Information Association tells us that Canada currently has about 178 billion barrels of proven oil reserves that can be extracted, including the oil sands. If you take this number and divide it by the amount of oil we produce each day, we get approximately 195 years of producing oil; the number given by the government website is more or less correct.</p>
<p>Does this mean all is well for the next 200 years? Well, not really. See, the bit that breaks this whole analysis is right in the quote taken from the government&#8217;s FAQ: &#8220;at current rates of production.&#8221; The 200 year figure assumes that Canadian production of oil will not grow at all over the next 200 years. Intuitively that doesn&#8217;t seem right, but let&#8217;s be scientific about this. Maybe it is in fact true that oil production is constant.</p>
<p>Doing a bit of a search with my trusty sidekicks Google and Wikipedia, I found some data <a href = "http://membernet.capp.ca/SHB/Sheet.asp?SectionID=3&#038;SheetID=233">here</a> on the website of the Canadian Association of Petroleum Producers that shows the yearly oil production in Canada from 1971 to 2010. Rather than describe it to you, here&#8217;s a picture:</p>
<p><a href = "http://www.robbritton.com/wp-content/uploads/oil.png"><img src = "http://www.robbritton.com/wp-content/uploads/oil.png" alt = "Canadian Oil Production" width = "400px" /></a></p>
<p>If the government&#8217;s assumption were true, this graph would be a flat line at 2.5. As you can see it is definitely not, in fact it seems to be increasing at a fairly quick rate!</p>
<p>What happens to our numbers if we start increasing oil production each year? Let&#8217;s find out.</p>
<p>With a linear model, we get that it is increasing by about 0.0336 Mbbl, or 33 000 barrels of oil per year. If this trend continues, it means that the reserves will run out in&#8230;194 years. So one year less than if we assumed it would be flat.</p>
<p>Of course, typically in economics it is assumed that economies grow <i>exponentially</i>, not linearly. Since both population and productivity due to technology seem to increase at exponential rates, it a fairly safe assumption to make that production of anything increases at an exponential rate provided nothing stops it.</p>
<p>When we use an exponential model, we can calculate that the oil production is growing at about 1.68% per year. If we extrapolate this out, it turns out our oil supply will run out after&#8230;87 years. That&#8217;s a bit shorter than the last time frame! Even scarier for the people living in that time, we will use up the first half of our current amount in about 60 years, with the second half being used up in a short 27 year time frame! So in short, if production keeps up as it has been, then our grandchildren (assuming you&#8217;re my age, I&#8217;m 25) will see the day when the known oil deposits of Canada will run dry.</p>
<p>In fact, there&#8217;s another problem with this analysis. The data set we&#8217;re using includes the 1970&#8242;s with a massive oil boom followed by a collapse in the mid-70&#8242;s that lasted until about 1980. If we re-run the exponential model after dropping the 1970&#8242;s (so we are left with 30 years of data) the rate of increase goes up to 2.56% with an R<sup>2</sup> of 0.98 (meaning a near perfect fit). With that rate of increase, our oil will run out in 70 years. This is a lot closer than the 200 years given by NR Canada.</p>
<p>I tried to leave out any speculation from this post and just use numbers and math based on what has been happening and from those numbers, make a simple extrapolation to see what would happen should the existing trends continue. The growth rate of 2.56% per year may change in the future (up or down), which obviously would change the results of this simple analysis.</p>
<p>To add my own little bit of speculation, from what I&#8217;ve seen in the news I think that this rate of production will actually increase over time given the attitudes of the current Canadian government &#8211; as more projects such as the <a href = "http://en.wikipedia.org/wiki/Keystone_Pipeline">Keystone pipeline</a> get completed it will be even cheaper to transport oil into the United States and other countries from Canada. An economics 101 class will tell you that as the efficiency of supply increases, the amount of production will increase: as Canadians get better at shipping the oil to other places, more oil will be produced to ship.</p>
<p>As always with my statistics-oriented posts, you can see the code <a href = "https://gist.github.com/1522394">here</a>. In the code you can see I did a linear model with the 1970&#8242;s excluded but didn&#8217;t talk about it here, it&#8217;s because the exponential model fits both better with the data and better with economic theory.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.robbritton.com/2011/12/27/canadian-peak-oil/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Chrome is the Best Thing for the Web since 2004</title>
		<link>http://www.robbritton.com/2011/11/10/chrome-is-the-best-thing-for-the-web-since-2004/</link>
		<comments>http://www.robbritton.com/2011/11/10/chrome-is-the-best-thing-for-the-web-since-2004/#comments</comments>
		<pubDate>Thu, 10 Nov 2011 18:33:56 +0000</pubDate>
		<dc:creator>rob</dc:creator>
				<category><![CDATA[other]]></category>

		<guid isPermaLink="false">http://www.robbritton.com/?p=91</guid>
		<description><![CDATA[A little disclaimer to begin. I don&#8217;t use Chrome. Despite the fact that it is damn fast, reliable, and tends to pick up new web features faster than any other browser, I prefer to limit my dependence on Google and so I will stick to the more open Firefox for my web needs. That doesn&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>A little disclaimer to begin. I don&#8217;t use Chrome. Despite the fact that it is damn fast, reliable, and tends to pick up new web features faster than any other browser, I prefer to limit my dependence on Google and so I will stick to the more open Firefox for my web needs.</p>
<p>That doesn&#8217;t mean that Chrome isn&#8217;t great. However contrary to what you might think, I&#8217;m not making the case that it is great because of the reasons I listed above. Instead, Chrome is great because it provides a worthwhile competitor to Firefox. It wasn&#8217;t hard for Firefox to be amazing in 2004 when the only other widely used browser was IE6. It wasn&#8217;t even fair. All that Mozilla had to do was make the browser not suck by having decent security, a Google search bar, extendability and tabbed browsing and you&#8217;re set. Later on Firebug came out to make web development hugely more productive (think, Javascript error output that is actually useful!)</p>
<p>However after that, Firefox didn&#8217;t really change all that much. That is, until Chrome came out and the new browser &#8220;arms race&#8221; started. Now we are seeing huge improvements to what the web is capable of in record time &#8211; audio APIs, web sockets, 3D graphics, etc. We can now use the web to build rich applications that before we either needed Flash/Java, or we had to stick to building a plain-old desktop application. I&#8217;ve even tried writing simple financial software using Javascript, and it actually works really well &#8211; you can receive a data feed directly from the exchange and have it appear in real time in an HTML table. Beautiful!</p>
<p>What&#8217;s even better about this arms race compared to the one in the 90&#8242;s is that Mozilla and Google are actually cooperating to make sure that things are standardized. None of the old problems where Netscape would use one name but IE would use a different one &#8211; no, now we know that after the APIs become stable there will be efforts to standardize them across the more modern browsers.</p>
<p>One thing I&#8217;ve deliberately left out of the discussion is Internet Explorer. It continues to be developed, but as is typical of the IE team there doesn&#8217;t seem to be a whole lot of effort to make it compatible with the things that Google and Mozilla are building. I think that the web would be better off if developers showed a bit of defiance and just decided to ignore Internet Explorer: focus on building amazing applications for the browsers that are actually pleasant to use. The users of those browsers will be much happier that way, and more people would migrate to those browsers when they see that they can have a much richer web experience that way. To quote some advice I&#8217;ve heard from various VCs and startups, &#8220;focus on making a few people very happy than trying to get a lot of ambivalent users.&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.robbritton.com/2011/11/10/chrome-is-the-best-thing-for-the-web-since-2004/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Trading with IronRuby</title>
		<link>http://www.robbritton.com/2011/11/08/trading-with-ironruby/</link>
		<comments>http://www.robbritton.com/2011/11/08/trading-with-ironruby/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 19:31:30 +0000</pubDate>
		<dc:creator>rob</dc:creator>
				<category><![CDATA[finance]]></category>
		<category><![CDATA[ironruby]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.robbritton.com/?p=72</guid>
		<description><![CDATA[Over the last year I&#8217;ve been using Ruby (more specifically IronRuby) to write algorithmic trading scripts. These aren&#8217;t high-frequency algorithms, more implementations of various longer-term strategies using Ruby. There was poll over in an algorithmic trading forum on EliteTrader asking about what was the programming language of the future among Java, Scala, C#, F#, C++ [...]]]></description>
			<content:encoded><![CDATA[<p>Over the last year I&#8217;ve been using Ruby (more specifically IronRuby) to write algorithmic trading scripts. These aren&#8217;t high-frequency algorithms, more implementations of various longer-term strategies using Ruby.</p>
<p>There was poll over in an algorithmic trading forum on <a href = "http://www.elitetrader.com">EliteTrader</a> asking about what was the programming language of the future among Java, Scala, C#, F#, C++ and OCaml. A number of other people posted about other languages such as Python or Lisp, and how well they satisfied four criteria:
<ol>
<li>memory management (GC vs unmanaged)</li>
<li>concurrency model</li>
<li>static typing vs duck typing (or better yet, type inference)</li>
<li>object-oriented programming vs functional programming</li>
</ol>
<p>I wrote a post on there about my experiences using IronRuby for trading, so I decided I would share that here as well:</p>
<div style = "border: 1px solid black; padding: 3px; background: #EEE">
I&#8217;ve been using IronRuby for the last year, I&#8217;ve found it works very well as I&#8217;m able to go from idea to a working script in no time flat. Performance is not amazing, but the majority of my ideas do not require performance.</p>
<p>For the evaluation (note that pretty much every point also applies to JRuby, the implementation of the language within the Java virtual machine):</p>
<p>1. memory management (GC vs unmanaged)</p>
<p>Uses .NET garbage collector, which is pretty solid. It tends to use a bit more memory than the equivalent VB.NET or C# script, but that&#8217;s alright. RAM is cheaper than my time.</p>
<p>2. concurrency model</p>
<p>Again, uses .NET threads which are fairly solid. You can use any of the classes in the .NET library for concurrency.</p>
<p>3. static typing vs duck typing (or better yet, type inference)</p>
<p>Ruby uses duck typing. Mixins (aka traits in Scala) means you can write code in chunks and mix-and-match them per script. For example, you could have a SpreadTrade mixin that you just drop into a script and it will make the script do spread trading.</p>
<p>There is a bit of clunkiness when interacting between C#/VB.NET code and IronRuby code due to type conversions and what-not &#8211; since Ruby collections can contain an arbitrary mix of types, collections are always treated as collections of Object when passing into C# code.</p>
<p>4. object-oriented programming vs functional programming</p>
<p>Ruby has a very nice blend of both. Absolutely everything is an object (including classes and primitives like integers), existing classes are open (you can add methods to existing classes), and closures passed to methods have a rather succinct syntax. For example, it is possible to build a library where the following code is valid:</p>
<pre>
symbol.changes_by 2.5.percent do
  # now within a closure with some code to execute when the stock changes by 2.5%
end
</pre>
<p>At the same time, you still have all your nice functional programming techniques:</p>
<pre>
# higher order functions:
(1..5).map { |i| i * 2 }   # produces: [2, 4, 6, 8, 10]
(1..100).select &#038;:odd?     # gets all the odd numbers from 1 to 100
(1..100).inject &#038;:+        # produces the sum of 1 to 100

# currying
f = lambda { |a, b| a + b }
g = f.curry[1]
g[2]          # produces 3
</pre>
<p>Two new criteria that could be added:</p>
<p>5. Meta-programming. In Ruby not only are things dynamically typed, but types themselves are dynamic. Rather than manually coding something every time, I can write one line within a class that will automatically generate the code that I want:</p>
<pre>
class SomeOrder
  # this code will automatically generate code to cause orders of type SomeOrder to be
  # hedged by an object of SomeOtherOrder
  hedged_by SomeOtherOrder

  # generate code that will cancel the order on some condition
  cancel_if {
    # market is tanking
  }

  # etc.
end
</pre>
<p>This allows you to write code in a more declarative way, which can lead to less bugs as there are less moving parts you have to manually specify each time.</p>
<p>6. Readability: As demonstrated in the examples above, I can show my scripts to non-programming traders and they are able to follow the strategy fairly easily. They may not understand the meaning of the punctuation, but the flow of the logic can be set up in a way similar to the way they might describe the strategy in English.</p>
<p>Some downsides:<br />
- Like I said, performance is not amazing, it&#8217;s on par with Python and the other scripting languages.<br />
- When coming from static languages it is inevitable you will get frustrated the first time you stub your toe on the dynamic typing system &#8211; you can get some weird bugs when you accidentally pass in a string instead of an array or something like that.<br />
- Those nice declarative meta-programming things can be rather tricky to implement within a library.<br />
- Finally, the language assumes that everybody knows what they&#8217;re doing. It is possible for some people to write very bad code in Ruby that messes things up &#8211; for example, overriding the + operator for arrays to implement vector addition when the standard library has it defined as the array concatenation operator. Imagine your surprise when [1, 2] + [3, 4] produces [4, 6] instead of the expected [1, 2, 3, 4].</p></div>
<p>Out of the readers who are also Rubyists, what do you guys think about this topic?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.robbritton.com/2011/11/08/trading-with-ironruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

