I am continuing to teach C++, which I am now convinced is a specialized language whose main feature is unchecked array access. However, my students discovered a cool application of said feature. I asked students to write some code to turn this elephant


into this grid of 4 elephants:


They have a primitive bitmap library, which reads a 256 pixel square grayscale bitmap into a 256-by-256 array of unsigned chars (bytes). Here is an attempted solution that several students stumbled upon:

#include "bmplib.h"

int main() {
  unsigned char src[256][256];
  unsigned char dest[256][256];
  readGSBMP("elephant.bmp", src);
  for (int i=0; i<256; i++) // row
    for (int j=0; j<256; j++) // column
      dest[i][j] = src[2*i][2*j];

To their surprise and mine, it generated the following picture, which was way cooler than the desired one:


The questions for the reader are:

  • why does the result look like this?
  • what needs to change to get the 4-elephant grid originally desired?

On C++


I’m teaching C++ this semester, for CSCI 103 at the University of Southern California. The students are great! However, the transition to this language is challenging. I am trying to build some tools to work around the language, with mixed success. As always, StackOverflow is very helpful, as is the DeathHandler tool on GitHub.

With C++ there are so many opportunities for a student to shoot themselves in the foot. But even with these tools it feels like trying to get them better shoes rather than getting rid of the gun.





Hey RSS readers, and the greater internets! I’m married as of 4 days ago. Here’s a link to some pictures. We’re not on honeymoon technically, although we are both crashing on the same floor in the bride’s sister’s place, and I always thought Kitchener is pretty romantic. It was really a fantastic ceremony, an even better party, and it was better than anything I could have imagined to see all of our friends and family gathered at once. Here’s to another 40000 days!


It’s that time again! Both to celebrate our rich national heritage in 60-second increments (fake version) (real version) and to look at maps again. A few weeks ago in the Soho area of NYC, we ran across an antique map dealer. A little haggling later, I ended up with the following piece of wall candy.



You can click on the map for the full version. It’s a little bit mysterious: I had never heard of many of the regions shown. The map shows:

  • Athabasca (1882-1905)
  • Assiniboia (1882-1905)
  • Keewatin (1876-1912)
  • Saskatchewan and Manitoba being broader east-west than north-south
  • the non-existence of the Yukon territory (created in 1898)
  • Northeast Territory

Many of these listed areas were districts, or administrative subsets, of the Northwest Territories. However, Franklin and Mackenzie districts, both created in 1895, are not shown.

The map has one fishy part. It seems like there was never really any part of Canada officially called the Northeast Territory. Says The New International Encyclopædia (1916),

[after talking about events in 1895]… At this time … that part of Keewatin which was north of Ontario, and the territory northwest of Quebec, were named the Northeast Territories. But the latter designation was discontinued, and eventually both the Northwest and the Northeast Territories, together with the district of Keewatin, became known as the Northwest Territories.

and Municipal Government in the North-West Territories (1904),

Some years ago Ungava appeared on the map as the North-East Territory, but by what authority is not known.

But is it reasonable that there was some confusion; after the Keewatin Act (1876), the Northwest Territories would have had two non-contiguous parts with a giant gap in the middle, and one might well wonder why they were all so “west”.

On the map, the part depicted as “the Northeast Territories” indeed resembles the District of Ungava’s 1895-1898 boundaries, but described more simply, consists of the area east of the Hudson Bay. There is another hint in the excellent Wikipedia article Territorial evolution of Canada, which would seem to place the map between May 7, 1886 and August 12, 1889 (when Manitoba lost a border dispute with Ontario in the Canada (Ontario Boundary) Act).

When I took out the map to scan it, the back side included a table entitled

From the Report of the Secretary of the Treasury for the Year ending June 30, 1890.

I guess the mapmaker was a little out of date, or not closely following Parliament, or had their map printed a bit late. The map is signed W. H. Holmes at the bottom, which Wikipedia seems to suggest is William Henry Holmes. Who, incidentally, published a work that sounds amazing based on the title alone: “Random Records of a Lifetime, 1846-1931: Cullings, largely personal, from the scrap heap of three score years and ten, devoted to science, literature and art“. Thanks Mr. Holmes, for this random record of history on Canada day!

Post-script. Here are two more bonus maps:

  1. map from an 1888 textbook that seems to be identical in fonts and the placement of many letters, although it has updated borders and the “Northeast Territory” label is absent
  2. map of Toronto from 1894

One of my favourite pieces of technology is WordPress. My main project with it is Computer Science Circles, but I’ve also used it for online course notes and I first learned of it helping my colleague Douglas with a student organization website. It was my head-first introduction to the language PHP.

PHP is capable of a lot of nifty stuff. PHP pages act like little programs that run and whose output is an HTML page that is displayed to the user. This lets you do things like interact with databases or client state (e.g. shopping baskets, logins, etc). But even with stateless pages, one interesting thing about using PHP in place of HTML is that you can define new commands to shorten or clarify repetitive structures.

Here’s some repetitive structure as an example: imagine a page with a lot of links to Wikipedia articles, like this.

<a href='http://en.wikipedia.org/wiki/Cheese'>Cheese</a>
is made from
<a href='http://en.wikipedia.org/wiki/milk'>milk</a>
which comes from
<a href='http://en.wikipedia.org/wiki/mammals'>mammals</a>

Displays as: Cheese is made from milk which comes from mammals

There’s a common pattern repeated 3 times in that HTML fragment: the pattern

<a href='http://en.wikipedia.org/wiki/X'>X</a>

occurs once with X=Cheese, once with X=milk, and once with X=mammals. Were HTML a real programming language, it would be good programming practice to define a function that could handle that pattern, and to call it three times. This can be done in PHP like so:

function linkish($X) {
  echo "<a href='http://en.wikipedia.org/wiki/$X'>$X</a>";}
<?php linkish("Cheese"); ?> is made from <?php linkish("milk"); ?>
 which comes from <?php linkish("mammals"); ?>

In WordPress, which first made me think of this kind of design pattern, you are allowed to do an essentially identical thing called a “shortcode”. It looks a lot like the above PHP, where you define and register a shortcode inside of a plugin, and you write [linkish]Cheese[/linkish] to call it. Note that it is almost like you are defining a new HTML element in terms of old ones.

However, it seems like a little bit of overkill to ask the server to do so much thinking, whether with plain PHP or with shortcodes. It’s not serving a truly dynamic page: this content will be the same every time a user looks as it. On top of this, served webpages are allowed to contain function calls and definitions, as long as they are written in JavaScript. Can we get JavaScript to do this work for us?

One approach would be to signify these elements and arguments in some way, to wait until the client has the page, and then to have the client do all of the substitutions.

<a class='linkish'>Cheese</a> is made from 
 <a class='linkish'>milk</a> which comes from
 <a class='linkish'>mammals</a>
<script type='text/javascript'>
var elts = document.querySelectorAll('a.linkish');
for (var i=0; i<elts.length; i++)

This code waits until everything’s displayed, then goes through and retroactively modifies the <a class=’linkish’>X</a> objects as desired.

This is similar to how MathJax is able to insert \LaTeX formulas like \sin^2(x)+\cos^2(x)=1 into virtually any webpage, including this one! After the page is loaded, it searches the whole page for expressions like $latex \sin^2(x)+\cos^2(x)=1$ and then re-renders the contents appropriately.

However, this approach still has one downside compared to PHP. Until the full HTML page has been received by the human browsing the site, no replacements will take place. (You can confirm this by trying out MathJax on a long page: no LaTeX appears until everything is loaded.) This is not ideal since it’s jarring to the user to see weird placeholders sit around for so long, and it prevents them from starting to read the page until everything it totally done. This is the opposite of progressive HTML rendering, which refers to the fact that your browser will try to show you the first parts of the page while it’s still receiving and rendering the parts further down off-screen.

You could periodically re-check the page for new <a class=’linkish’> or ... elements, but this is a pretty hacky solution and causes work to be repeated and therefore does more computation than necessary. What we’d really like is to transform the incoming data on-the-fly. You could imagine it as a filter: as the HTML data is coming in, we would like to have some kind of stream-replacer that would search for something and replace it appropriately. I don’t think there is any way to literally do stream replacement on incoming HTML, but what I learned this week is that you can use a JavaScript MutationObserver to achieve basically the same effect.

A MutationObserver is a device that lets your code get notified whenever HTML elements on your page are changed; including, how the page is built while it is loaded. For example, here’s how it gives a new solution to the task mentioned above.

<script type='text/javascript'>
// construct observer _before_ anything is rendered
var mo = new MutationObserver(
 // constructor argument: callback on MutationRecord[]
 function (events) {
  // for each record,
  for (var i=0; i<events.length; i++)
   // MutationRecord has Node "target" and Node[] "addedNodes"
   for (var j=0; j<events[i].addedNodes.length; j++)
    // we'll define "process(parent, child)" below
    process(events[i].target, events[i].addedNodes[j]);

// what should we observe, and with what options?
mo.observe(document, {childList: true, subtree: true});

// as promised, the callback
var process = function (parent, child) {
 if (child.nodeName=="A" && child.classList.contains("linkish"))
<!-- now the same page as before -->
<a class='linkish'>Cheese</a> is made from <a class='linkish'>milk</a>
 which comes from <a class='linkish'>mammals</a>

I will admit this is no longer shorter or easier to read, although it is just a toy example. I managed to find two different uses for this technique last week while writing the manual for my websheets Java coding exercise tool. One use was similar to the above (rendering links automatically, in fact rendering two parallel links at once, but it was very cumbersome and error-prone to re-type in the same structure over and over). The other use was to automatically build a table of contents: every time an H2 or H3 header element showed up, it automatically added a new bulleted item to the table of contents. (In fact, if your internet connection is slow enough, you can see the table of contents of the manual extending bit by bit as the H2 and H3 elements further below arrive.) See the manual source code for details. And, for a better list of options and explanations, consult the full MutationObserver API.

I was curious to explore a few of the finer details of this technique. What order will elements be added in? HTML has a tree-like structure, but it’s not clear if parents will be added before children or vice-versa. So I built a small test, replacing process() with a simple logging function, and using the content

<div>This is <b>bold</b><i> and italically <span>nested</span></i></div>

(See source of this page, and its console.) The order of events happening was:

  1. The div was added to its parent
  2. “This is” was added to the div
  3. The <b> was added to the div
  4. “bold” was added to the b
  5. The <i> was added to the div
  6. “and italically” was added to the <i>
  7. The span was added to the <i>
  8. “nested” was added to the span.

So, this would be a tree preorder. But because the MutationObserver sends you updates in batches, there was one more surprise: in step 3, by the time I looked at the <b> element, it already contained “bold”, and similarly for the other grandchildren.

This general design goal, of defining a new kind of element in terms of old ones, is something that HTML feels like it sorely needs. If you are making an awesome code editing widget or database slice displayer or simply trying to add “click to pop up” or “click to hide/show” functionality, this is the most natural approach. In fact, it looks like the new Custom Elements API lets us do precisely that!

Yesterday I found myself face-to-face with salmon to cook for dinner. I have been lucky enough to have a certain special someone cook coriander-spiced pan-fried salmon with jalapeño-mango-pineapple pan salsa on previous occasions, but this time I was on my own.

So, what to do? The internet came to my rescue and like my previous post, I want to document it a bit for my own reference. I found an amazingly simple rosemary-garlic roasted salmon recipe; here’s the picture, taken from the recipe page itself.


The recipe was simpler than I could have imagined:

  1. put salt and pepper on salmon
  2. put chopped garlic and rosemary on salmon
  3. roast in preheated 425-degree oven for about 10-12 minutes (I needed 15)

I was very surprised that no oil was needed! But the natural fat in the salmon is the right amount for it to conduct heat well and stay moist. It’s suggested to cook on parchment paper though to avoid stickage.

831948To go with the salmon I made cottage fries, thick spiced coins of potato roasted in the oven. They are also very simple: slice potatoes about 1cm thick, coat lightly with oil and heavily with spices; then roast in the same 425-degree oven (I think mine took 45 minutes), flipping occasionally. They go well with any spice or herb you can imagine: I like chili powder, oregano, herbes de provence, paprika, granulated onion or garlic, cumin, coriander… it’s pretty hard to go wrong unless you accidentally reach for the cocoa.

Today it’s time to do some wedding planning. I have to sample some Toronto poutine and pizza in advance of ordering our government-mandated late-night snack. It’s a tough job, but somebody has to do it.





Get every new post delivered to your Inbox.