On C++

10Sep14

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.

</rant>

img


++

30Jul14

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!

pv-11


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.

1889canada-thumb

 

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

UNITED STATES COMMERCIAL STATISTICS
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:

<?php
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++)
  elts[i].setAttribute('href', 
    'http://en.wikipedia.org/wiki/'+elts[i].innerHTML);
</script>

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"))
 child.setAttribute('href',
 'http://en.wikipedia.org/wiki/'+child.innerHTML);
};
</script>
<!-- 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.

roasted-salmon-cv-600x399

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.

 


IMG_20140618_175616-001


OLYMPUS DIGITAL CAMERAClasses are almost done! This means more free time for me and hence, more cooking! I brushed off a recipe that I received as part of Great Road Farm‘s excellent CSA last year. The CSA was quite an excellent culinary experience: we cooked and ate really good beets for the first time, as well as watermelon radishes (pictured at right), edible flowers, miniature eggplants, and all manner of vegetation. Including kale, which we had only limited experience with before. That brings me to the recipe: Kale and White Bean Soup. Hopefully by posting it here, it will outlive its flimsy laminated paper existence.
IMG_20140519_202443

Kale and White Bean Soup (adapted from Chef Josh Thompson of Agricola)

Feature ingredient:

  • 1 bunch of kale

Wash and separate the stems from the leaves. Make a stock by combining

  • stems from the kale
  • 1 onion, quartered
  • 2-4 carrots, broken into thirds
  • 2-4 celery stalks, broken into thirds
  • 3 cloves of garlic, crushed
  • ~12 peppercorns
  • other spices optional: mace, parsley stems, bay leaf, thyme, etc
  • enough water to mostly fill your pot (about 3L)

Boil for 1-2 hours and strain out the solids.

To begin the soup, sauté

  • 1 onion, diced
  • 3 cloves of garlic, sliced
  • 3 stalks of celery, sliced (optional)
  • 2 tbsp olive oil
  • pinch of salt, pepper

Sauté until translucent and soft. Add

  • the stock
  • 1 lb sliced carrots

and bring to a boil. Add

  • 1 can (15.5 oz) cannellini beans
  • 1 lb chopped fresh tomatoes (optional)
  • the kale leaves, chopped roughly

Add hot water to cover if needed. Return to a boil then simmer until the kale is tender. Optionally finish with

  • juice from 1 lemon
  • chopped parsley (1/2 to 1 bunch)
  • salt and pepper to taste

The soup is vegetarian! But not if you use the first delicious optional step below:

  • garnish w/sausage (esp. chorizo), sliced and then pan-fried (1 sausage/2 ppl)
  • serve w/toasted baguette or crusty bread.

Enjoy!

 




Categories

Follow

Get every new post delivered to your Inbox.