<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Toby Ho</title>
    <link href="http://tobyho.com/atom.xml" ref="self"/>
    <link href="http://tobyho.com"/>
    <updated>2019-12-10T22:36:58.959Z</updated>
    <id>http://tobyho.com</id>

    <entry>
            <title>How to Level Up as as Junior Developer</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2017/10/26/advice-for-junior-devs">
            <updated>2017-10-26T04:00:00.000Z</updated>
            <id>http://tobyho.com/2017/10/26/advice-for-junior-devs</li>
            <content type="text">
Recently a former student and dear friend asked me this question:
I feel that I am switching back-n-forth between a few different things
at my job, and that there isn't a lot of focus. I worry that I only have
a basic level of knowledge on each thing and am not able to get to the next
level on any of them. What can I do to make sure that my skills don't stagnate?

I thought long and hard about this question. I thought back to my younger
career and the things I did back then. I thought about answers some other
senior developers gave. I even test drove a couple of answers with the junior
developers I currently work with. I settled on a list of four things:

* drill down
* refactoring
* building for developers
* evaluate your progress

Next, I will go into more detail and specifics on each one. Come along!!!

## Drill Down

If you *really* want to get good at something, you want to go deep, not wide.
Don't go chasing after every tutorial that's on discount. Don't learn CS
algorithms just because that's what people are talking about on twitter.
Don't chase all the latest buzz words if they are not relevant to your
day-to-day work.

Don't get me wrong, it is valuable to know a variety of different skills,
but it's not enough. If you want to get to the next level, *you must
go deeper*. And nothing will give you a more immersive experience than your
9 to 5 job. Well, in most cases. If not, maybe re-evaluate your options.

What does *drill down* mean? It means you want to drill down to specific skills
in your repertoire and really get a deep understanding of the subject and
really refine the skill. Get obsessive about it. Like when you hear a song
you really like and you get obsessed about it, and you play it on repeat in the
car, and you memorize the lyrics, and you sing along with the recording in
the car, and you listen to the other songs on that album, and you obsess about
that artist, and you listen to their other album, and another album, and you
obsess about another song that's not an original, and you find the original
artist that recorded that song, and you listen to different versions of that
song, and you memorize that song, and you learn to play that song on your
harmonica or whatever instrument you play. You know what's really insane?
You find this new song you are really obsessed about and then you find that
another favorite artist you used to obsess about also recorded a version of
that song. You listen to it and it's so good and so much feelings are bubbling
up and you are experiencing this euphoria and you are wondering whether you
are hallucinating???!!! 'Know 'I'm sayin'?

*That's* what I mean by drill down.

Okay, how do you find a target for a drill down? Look for things that

1. You feel vague or uncertain about.
2. Has come up multiple times.
3. You are interested in learning more about.
4. Is relevant to your work.

How do you *actually* drill down? Apply all of the learning skills
you already know, but just in a much more focused way, directly at your
target:

1. Research and read articles online.
2. Ask plenty of "why" and other questions.
3. Research some more.
4. Perform toy experiments to get answers for yourself.
5. Ask experts in the field - go find them in Slack communities and IRC rooms.
6. Ask your mentors.

## Refactoring

Refactoring means changing the design of the code without changing its
functionality. It is really important in software development because
software gets more and more complex over time at a rapid rate. This happens
because software developers are constantly adding to it - that's what you
get paid to do every day! As the complexity goes over certain thresholds,
things get untenable unless structural changes are made.

It's like the structure within a company. Take a startup, for example.
If you are a solo-entrepreneur, all you have to worry about is yourself and
there is zero communication overhead. Once you have a co-founder, you
have to work on communication. That means taking care and planning to meet
regularly, and to be courteous of each other's needs and desires. When you scale
up the company to say 5 or 10 people, it's yet a different ball game. You'll
start needing to have company meetings and processes and standards in place,
and think about further growth and how to expand the team. It's more different
yet when there's 50 people, you may need an HR department.
Even more so when there's 500 people; 5000 people, 10,000 people, etc.
As the company grows to each level, new structural changes need to be keep
it running smoothly. Without the needed structural changes at each stage,
the company's operations will bog down.

The same happens with code. A code base that has only 100 lines, vs 1000, vs
10,000, vs 100,000, vs 1,000,000 lines. At each level, different structures are
needed to keep the codebase running smoothly. By running smoothly, that means the developers are able to maintain the code and add new features efficiently.
Refactoring is the work that provides those needed structural changes as
codebases go through these growing pains. But it is too often the case, in
too many companies, that a codebase does not receive the structural changes
it needs. To put it another way, too many codebases in the industry
are overdue for refactorings, and as a result, their developer
productivity spirals downward over time. This is an opportunity for you.

Refactoring is difficult. Few developers are very good at it. Why?
When you refactor code, you are really redesigning the code, and that requires
two abilities:

1. The design chops (skill) to come up with an improved design.
2. The ability to get the codebase from here to there.

Both of the above abilities are difficult to attain. But that's not a reason
to give up. Au contraire, it should motivate you to get good at it. Because
once you attain them, you would be one of the few.

How do you get good at refactoring? Well, by doing it, of course. Look for
refactoring opportunities, big and small. If you are a refactoring novice,
start out with the small ones, and then gradually move your way up.
Uncle Bob's [boy scott rule](http://programmer.97things.oreilly.com/wiki/index.php/The_Boy_Scout_Rule)
is: always leave the campground cleaner than you found it. Apply it to your
work.

When you are tackling larger refactors that involve making changes to multiple
files or components, it may be more difficult to see the forest from the trees,
and you may sometimes pin yourself into a corner in the middle of a large
refactoring move. This is okay. Failure is an option. Do it on an experimental
branch. Throw it away if it doesn't work out. Sometimes you may have to have
several tries in order to come to an improved solution.

If you are at a fork of the road and you are unsure which approach to take -
which approach would yield a better design at the end - there is a simple way
to know: *try them both*. Try them both, then decide. The reason
it was hard to decide is because of uncertainty. Now that you've done it
both ways, you can evaluate the pros and cons of each approach based on the
final result of each. Yes, this does means you are going to throw away some
work, but this is how you gain the design chops you need to be a next-level
refactorer - or err...maybe "software architect"? How does that sound?

Over time, as you get more experience this way, you'll be better able to
imagine what the outcome would be in your head if you chose one approach vs
another. Now you might think: "If that's the case, I'll just get my senior
architect to decide for me." Yes, but then you won't get the experience of
seeing the result of both approaches. And, even senior architects still
sometimes have to do it through trial and error too. So, look at the extra
added work as tuition for getting to the next level.

## Building For Developers

Experienced developers are more "meta" than juniors. Rather than only
building software for users, they also build software for developers,
who in turn build software for users.

Why would you do this? *To make developers more productive*.
In case you didn't catch it, this is the purpose of refactoring as well.
In fact, many artifacts built for developers came as a result of refactoring.
For example:

* a reusable UI component
* a reusable utility module

You can also build things apart from the core software itself. For example:

* a module (ex: npm module, a gem, an egg, a jar, a crate)
* a plugin to a framework (ex: redux thunk, express body parser)
* a CLI tool (ex: npm, eslint)
* a project template (ex: HTML5 Boilerplate)
* a CLI tool that generates a project template (ex: create-react-app)
* a web-based tool (ex: online CSS gradient generator)
* a desktop tool (ex: Postman)

When you gain the ability to build and design software for developers, you are
helping your entire team become more productive, not just yourself. Also,
you'll get a different perspective on what being productive means:
working smarter, not working more.

## Evaluating Yourself

Finally, I want to give you some ways for evaluating your learning progress.
If your goal is to level up, how would you evaluate whether or not you are
actually leveling up? Here are a couple of ideas:

1. Every time you have an ah-ha moment - as in, something in your brain just
clicked into place - you just understood something new - write it down.
At the end of each week, count the number of ah-ha moments you had.
2. Every 2 month or so, look back at some code you worked on 2 months ago
or longer. Do you have new perspectives/ideas on how to improve that code?

That's it! Take everything I say with a grain of salt. Good luck on your
journey! May the force be with you.
</content>
        </entry>,<entry>
            <title>ES2015 Features You are Expected to Know</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2016/12/17/es2015-features-expected-to-know">
            <updated>2016-12-17T05:00:00.000Z</updated>
            <id>http://tobyho.com/2016/12/17/es2015-features-expected-to-know</li>
            <content type="text">
I [teach programming full time](http://digitalcrafts.com), and currently my students have tasked me with teaching them about [ES2015](https://babeljs.io/learn-es2015/) (a.k.a ES6) - the latest version of the EcmaScript (JavaScript) specification. The problem with ES2015 is that the spec is vast and I don't consider it a wise use of time to cover every single feature in great detail. So I asked myself, what are the most important features to cover?

To answer this question, I went back our purpose as a code school: to prepare our students for the industry. How can we know what ES2015 features the industry expects us to know? Software professionals are expected to be able to learn new things on demand. In my own career as a software engineer, invariably, every time I switched to a new job required me to learn new tools. The authors of the most widely used JavaScript frameworks understand this, and therefore they all make it one of their priorities to create great learning resources for their framework. I will use these tutorials as a proxy. For each given ES2015 language feature, if many popular tutorials make use of it, then it is an important feature to learn.

## The Survey

I conducted an informal survey where for each of the following front-end JavaScript web frameworks:

* AngularJS 2
* React
* Ember
* Meteor
* Aurelia

I skimmed through the tutorial or quick-start guide linked from the main website, and catalogued each ES2015 feature used. I am going to walk through the features used in each tutorial below, if you are impatient, you can skip right to the summary.

## AngularJS 2

The [AngularJS 2 tutorial](https://angular.io/docs/ts/latest/tutorial/), at time of writing, walks you through building a custom application called the Tour of Heros - a CRUD application for a list of imaginary super heros. It uses the following ES2015 features

* let
* const
* Module
* Destructuring assignment
* Class
* Template string
* Promise

As this tutorial uses TypeScript, it also uses some TypeScript-specific features like decorators.

## React

The [React examples](https://facebook.github.io/react/) and [tutorial](https://facebook.github.io/react/tutorial/tutorial.html) The tutorial walks through building a Tic Tac Toe game and uses these features:

* let
* const
* Class
* Arrow function

It also uses JSX - the language extension pioneered by React and supported by the Babel transpiler.

## Ember

The [Ember quickstart](https://guides.emberjs.com/v2.10.0/getting-started/quick-start/) walks you through building an app for looking for apartment rentals using a test-driven approach. It uses the following ES2015 features:

* let
* const
* Module
* Destructuring assignment
* Enhanced object literals
* Template strings

## Meteor

Meteor provides [multiple tutorials](https://www.meteor.com/tutorials) on their website. Not only that, it provides 3 versions of their Todo list app, one for Blaze - their only front-end framework, another for Angular and yet another for React. I looked through all three of these, and found these features to be in use:

* let
* const
* Module
* Destructuring assignment
* Class
* Enhanced object literals
* Arrow function

## Aurelia

Aurelia provides a [quickstart tutorial](http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/quick-start) and a more [in-depth tutorial](http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/contact-manager-tutorial/) walking through building a contact manager application. I looked through both of them, and found these ES2015 features in use:

* let
* Module
* Destructuring assignment
* Class
* Arrow Function

<a name="summary"></a>

## Summary

In this survey of the tutorials of the 5 most popular front-end frameworks, I have gather a list of the ES2015 used, and given a tally of the number of tutorials that use each. I will also label each feature with "easy", "medium", or "hard" in terms of how hard the feature is to learn.

<div class="table-box">
<table>
  <tr>
    <th>Feature</th>
    <th># of tutorials used</th>
    <th>Used by</th>
    <th>Difficulty</th>
  </tr>
  <tr>
    <td>let</td>
    <td class="number">5</td>
    <td>All</td>
    <td>Easy</td>
  </tr>
  <tr>
    <td>const</td>
    <td class="number">4</td>
    <td>AngularJS 2, React, Ember, Meteor</td>
    <td>Easy</td>
  </tr>
  <tr>
    <td>Module</td>
    <td class="number">4</td>
    <td>AngularJS 2, Ember, Meteor, Aurelia</td>
    <td>Medium</td>
  </tr>
  <tr>
    <td>Destructuring Assignment</td>
    <td class="number">4</td>
    <td>AngularJS 2, Ember, Meteor, Aurelia</td>
    <td>Easy</td>
  </tr>
  <tr>
    <td>Class</td>
    <td class="number">4</td>
    <td>AngularJS 2, React, Meteor, Aurelia</td>
    <td>Medium if you know classes from another language before, Hard otherwise</td>
  </tr>
  <tr>
    <td>Arrow Function</td>
    <td class="number">3</td>
    <td>React, Meteor, Aurelia</td>
    <td>Easy</td>
  </tr>
  <tr>
    <td>Enhanced Object Literals</td>
    <td class="number">2</td>
    <td>Ember, Meteor</td>
    <td>Easy</td>
  </tr>
  <tr>
    <td>Template Strings</td>
    <td class="number">2</td>
    <td>AngularJS 2, Ember</td>
    <td>Easy</td>
  </tr>
  <tr>
    <td>Promise</td>
    <td class="number">1</td>
    <td>AngularJS 2</td>
    <td>Hard</td>
  </tr>
</table>
</div>

Another comparison we can do with this data is between the frameworks. We can compare which framework requires the most amount of learning in order to get up to speed based on the number of ES2015 features used in their tutorial, the ones that require the least number of learning would appear to be the most beginner-friendly.

<div class="table-box">
<table>
  <tr>
    <th>Language</th>
    <th># of features used in tutorials</th>
  </tr>
  <tr>
    <td>AngularJS</td>
    <td class="number">7</td>
  </tr>
  <tr>
    <td>React</td>
    <td class="number">4</td>
  </tr>
  <tr>
    <td>Ember</td>
    <td class="number">6</td>
  </tr>
  <tr>
    <td>Meteor</td>
    <td class="number">7</td>
  </tr>
  <tr>
    <td>Aurelia</td>
    <td class="number">5</td>
  </tr>
</table>
</div>

## Resources

I will leave you with three great resources for learning ES2015:

* [Luke Hoban's ES2015 feature overview](https://github.com/lukehoban/es6features#readme)
* [Kyle Simpson's ES6 & Beyond](https://github.com/getify/You-Dont-Know-JS/tree/master/es6%20%26%20beyond)
* [Nicholas Zaka's Understanding EcmaScript 6](https://github.com/nzakas/understandinges6)

Happy learning!
</content>
        </entry>,<entry>
            <title>Unstuck Episode 4: OSX Shortcuts and Workflow</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2016/05/07/osx-shortcuts-and-workflow">
            <updated>2016-05-07T04:00:00.000Z</updated>
            <id>http://tobyho.com/2016/05/07/osx-shortcuts-and-workflow</li>
            <content type="text">
I am now teaching at [DigitalCrafts](digitalcrafts.com). One thing I noticed about some of my students is that  practice with just a small set of keyboard shortcuts, and some tweaks in the way they arrange their windows could help them improve their productivity by a lot. I will share these tips in this video.

<div class="video">
  <iframe width="720" height="480" src="https://www.youtube.com/embed/mBoWNL1Iliw" frameborder="0" allowfullscreen></iframe>
</div>

Here is an accompanying cheatsheet for the OSX keyboard shortcuts.

## Shortcut Cheatsheet

### Terminal

* Ctrl-A - go to the beginning of the line
* Ctrl-E - go to the end of the line
* Up Arrow - bring up the previous command in the command history
* TAB - autocomplete commands or files or directories

### OSX

* Cmd-Space - Spot Light to launch programs
* Cmd-TAB - switch to the previous window
* Hold down Cmd, while pressing TAB repeatedly - choose the window you want to switch to
* Cmd-C - copy
* Cmd-X - cut
* Cmd-V - paste
* Cmd-W - close current file or tab
* Cmd-Q - quit current program

### Atom Editor

* Cmd-S - save, blue dot on the right of a tab means the file is unsaved
* Hold down Cmd, press K then B - toggle the project sidebar
* Ctrl-G - Jump to a line by its line number
* Cmd-W - close the current file, or close the current window, if no files are present
* Cmd-LeftArrow - move to beginning of line
* Cmd-RightArrow - move to end of line
* Hold down Shift, move the caret using arrow keys to select text. Can be used in combination with other shortcuts like Cmd-LeftArrow.

### Google Chrome Web Browser

* Cmd-R - reload the web page
</content>
        </entry>,<entry>
            <title>Marty Misses Violin Class</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2016/04/17/marty-misses-violin-class">
            <updated>2016-04-17T04:00:00.000Z</updated>
            <id>http://tobyho.com/2016/04/17/marty-misses-violin-class</li>
            <content type="text">
Last week, I started my new job. Because of this, I had to completely rearrange my daily schedule. Have you ever had the experience of suddenly forgetting how to do something you've done routinely - even subconciously - for years and years? That happened to me. My son's violin lesson holds at 4:15pm every Wednesday, and yet, I mistakenly thought that I needed to be there at 5:15pm. When I got my son, he asked "Why are you so late?" It still didn't occurred to me that I messed up. But when I ran into unusual traffic, it started to dawn on me - normally this trip isn't so bad.

I told Marty that daddy might have messed up, and that we might miss the lesson, and he started protesting, "No, I want to go to violin class!" I said "sorry", repeatedly during the unusually long drive.

When we finally got to the violin lesson, his teacher was teaching another student and she said that she couldn't stay late. I said "That's okay. It was my fault. But can he stay and watch?" So Marty stayed and watched her teach. After the lesson was over, the teacher got ready to go, and Marty began to cry, realizing that he wouldn't get a lesson. I went over to give him a hug.

I felt bittersweet. On the one hand, I felt very bad for screwing up. But on the other hand, I felt very gratified that Marty loves his violin lessons this much. This is a sign that we are on the right path in educating him, and for me, it is a huge success.</content>
        </entry>,<entry>
            <title>Unstuck Episode 3: The Secret to Being Awesome - 8 Tips to Help You Focus</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2016/03/18/secret-to-being-awesome-8-tips-focus">
            <updated>2016-03-18T04:00:00.000Z</updated>
            <id>http://tobyho.com/2016/03/18/secret-to-being-awesome-8-tips-focus</li>
            <content type="text">
This episode was prompted by 2 things. First, after giving a talk entitled "How to Learn" to some developers in Athens, Georgia, US, I received a lot of good questions and discussion about how to stay focused. Second, while working with a student I am mentoring, we realized that being able to stay on task has been a problem for her. This episode will address this, to the best of my knowledge. Enjoy. If you watch this video to the end, please anwser the question of the day in the comments!

<div class="video">
  <iframe width="720" height="480" src="https://www.youtube.com/embed/IBqX134qXXU" frameborder="0" allowfullscreen></iframe>
</div></content>
        </entry>,<entry>
            <title>Unstuck Episode 2: See Code Run</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2016/02/29/unstuck-ep-2-see-code-run">
            <updated>2016-02-29T05:00:00.000Z</updated>
            <id>http://tobyho.com/2016/02/29/unstuck-ep-2-see-code-run</li>
            <content type="text">
This is episode 2 of Unstuck - the show for code learners. In this one, I respond to a viewer comment, then walk through using Python Tutor to visualize your code while it is running, *then* I show you how to visualize your code on your own - without the help of a software tool. Enjoy!

<div class="video">
<iframe width="720" height="480" src="https://www.youtube.com/embed/Krq4Vdbc5Yw" frameborder="0" allowfullscreen></iframe>
</div>

One of the things that make learning to code is harder is that it is hard to visualize a process - what a program looks like while it is running. You can look at the code - and it will help, but it's not the same thing. Not being able to see the process is like trying to fix a car without being able to open up the hood - it's not impossible - this is what Click and Clack the Car Talk guys do all the time, but they are experts, and even they have mixed success. If you really want to understand how programs work, and more specifically how *your* program works, or doesn't, you want to be able to see it in action. Luckily, there are tools that help you do this.

## Python Tutor

[Python Tutor](pythontutor.com) is one such visualization tool. Despite the name, it actually supports several programming languages, including Python, Java, JavaScript, TypeScript, Ruby, C, C++. Let's try it! I am going to "start writing and visualizing code now!"

This tool runs directly in the browser, so there's nothing to download. I could choose from these languages, but I will stick with Python. I am going to write a program to calculate the average of an array of scores.

In the video, I walk through the following code line by line:

{% highlight js %}
scores = [6, 5, 7, 8, 10]
sum = 0
for score in scores:
  sum = sum + score
average = sum / len(scores)
print "Average score is %d" % average
{% endhighlight %}

A really cool feature of Python Tutor is that a shared session mode which allows multiple people to visualize the same code at the same time. As you can imagine, this is really useful for mentoring.

## Do It By Hand

So python tutor is a great way to get a deeper understanding of how your code actually works, and it's so easy to use! Almost too easy. Remember what I said about easy? Easy is not necessarily good. For learning, difficult is better. So, I am going to show you an exercise for you to practice visualizing the process of a program, in a more effortful way - and that is to draw it yourself!

So I have a program which finds the highest number in a list of numbers and prints it out, and in the video I execute this program line by line by hand using pen and paper.

{% highlight js %}
scores = [6, 5, 7]
highest = 0
for score in scores:
  if highest < score:
    highest = score
print "Highest score is %d" % highest
{% endhighlight %}

Okay, so when you do everything by hand, you may make mistakes, so it's a good idea to check your answer at the end by running the program or using something like Python Tutor.

Python Tutor is great, but it is only meant for small, self-contained programs. It's a good thing that there's another tool that will help you visualize programs - the debugger. In future episodes I will deep dive into using the debugger.

Like Python Tutor, the debugger allows you to step through a program line by line, and inspect the current values of variables. I will cover using the debugger on the next episode.

## Homework

You homework is to write a simple program - between 5 to 15 lines long, and then execute that program by hand on pen and paper. Then, execute that same program using python tutor. Please post your work in the comments! Take a picture of your handwriting!</content>
        </entry>,<entry>
            <title>Unstuck Episode 1: Learning to Code is Hard. Difficult is Better.</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2016/02/22/unstuck-ep-1-difficult-is-better">
            <updated>2016-02-22T05:00:00.000Z</updated>
            <id>http://tobyho.com/2016/02/22/unstuck-ep-1-difficult-is-better</li>
            <content type="text">
I am beginnig a web show for people who are learning, or want to learn to code. The show shall be named - *Unstuck*, and this marks the first episode of the show. You may watch the video below, or you may also read my notes for the show beneath the video. Enjoy.

<div class="video">
<iframe width="720" height="480" src="https://www.youtube.com/embed/t_WJJAIZ4KI" frameborder="0" allowfullscreen></iframe>
</div>

## Part I: Learning To Code Is Hard

Do you want to learn to code?
Well, you have access to a wealth of free an affordable online resources to teach you. Treehouse, Lynda.com, Codecademy, Codeschool, and many many more. So what are you waiting for?
What's that? You've already done those? Great! So you can code now, right? What's that? You still don't feel like you can code? Oh. You still cannot build a program from scratch? Oh, oh, oh, I see. You are in - what the Erik Trautman of Viking Code School refers to as the "gulf of dispair".
So first, you go through this hand-holding honeymoon period, where like little child you are guided through a trail . And you gain confidence with each lesson and each successful challenge. Coding is not so bad! One might even say it's easy!
As you get closer to the end of the course, you are thinking, I am almost there! Soon I'll be a real programmer. Little did you know, that the end is only the beginning.
Here's the thing. Once the gentle hand-holding is over, you are on your own, and then things ain't so easy anymore.

So, despite this vast amount of knowledge we have online, a lot of learners are struggling, and maybe you are one of them. Why is this?

Programming is kinda like cooking, but as you'll see, it's also not like cooking.

When you learn to cook a new dish, you follow a recipe.
Chefs - in contrast - don't cook by recipes. Chefs create, improvise, and explore with different ingredients, different flavors and different techniques. They tailor meals to the occation and make different choices depending on who he's cooking for and what ingredients are available. Really good chefs create something they've never created before with every meal.

When you cook, as long as you know how to follow the instructions, you are going to be alright. People will be feed and people will be happy. When you learn programming, yes you can follow a tutorial, and yes you will end up with a working program if you follow the instructions correctly, but most likely, no one will use that program.

Here's the thing, with food - you make more cake to feed more people. But with code, there is no point - from the economic point of view - in writing the exact same program twice, because once that program has been made, you can copy it any many times as you want without costing anything. Therefore, the only reason people write programs - again from the economic point of view - is to create something that has never existed before.

In other words, in order to be a proficient programmer, someone who people will pay for to write programs, you have to be able to program like a chef cooks.

And yet, these online courses have not gone much further than just training you to follow instructions.

## Part II: Difficult Is Better

We love easy.
Google answers any question in an instant, and not only that: it can read your mind.
We can drive to any destination without actually *knowing* how to get there.
Taking pictures and videos is easier than ever. And yet, as if it weren't easy enough, we can now snapchat a video with one touch of the thumb instead of two.

Technology makes things easy - that is what it's for. However, easy isn't always better.

Psychology researcher Robert Bjork has shown in a series of experiments that when people learn things quickly, they are more likely to forget what they learned in the long run, and also are less able to relate what they've learned with things they already know. 

One of the experiments went like this:

Two groups of students were asked to do a reading comprehension test - where they read an article, and then later have to answer questions about the article. Before reading the text, the students were given an summary outline of that text. The first group was given an online that follows the order of the text. The second group was given an online that is out of order with respect to the text. The students in the first group did better on recall. However, when the students were asked to do creative problem solving related to the text - a requirement that required a deeper understanding of the material, the second group won.

Another group of studies showed that if students make a mistake first before getting it right, their learning improves. In one such study, two groups of students were asked to do a standard reading comprehension test. The students in the first group would first read the article, and than answer questions about that article. The students in second group would answer questions about the article first, then read the article, and then answer the same set of questions again - they are given an opportunity to correct mistakes they made the first time. The second group of students performed better.

The brain has two subsystems: the fast, low level, intuitive, automatic, and primitive brain, and then there is the slow, high level, methodical, analytical, logical, and calculating brain.

Normally, people default to using their fast system, but when they encounter failure and difficulty, they then switch to their slow system. The more you think about a concept using your slow system, the better in stores in your long-term memory, and the more able you are to retrieve it in the future and relate it to different concepts.

Bjork has since coined the term "desirable difficulties". It means that if you want to learn something well, really well, chef level well, say, you actually want to make sure you don't learn it in a hurry. Instead, you are better off learning the material slowly and effortfully.

A course that makes it easy for students to learn may in fact, in the long run, be less effective.

Difficult is better.

## Part III: Implications

So what does that means for you, the learner?

1. Learn slower - slow and steady wins the race. Don't rush to move on.
2. Delibrately make connections between the new material and material you already know.
3. Customize the material so it's more challenging. To borrow a phrase from American Idol - make it your own.

## References

* [Why Learning to Code is so Damn Hard - by Viking School](http://www.vikingcodeschool.com/posts/why-learning-to-code-is-so-damn-hard)
* [Overcoming Intuition in Programming by Amjad Masad](http://amasad.me/2016/01/03/overcoming-intuition-in-programming/)
* [Curious by Ian Leslie](http://www.amazon.com/gp/product/B00JZBA9N8/)
* [Thinking Fast and Slow by Daniel Kahneman](http://www.amazon.com/gp/product/B00555X8OA)

</content>
        </entry>,<entry>
            <title>Promise-Based Coroutines in Node.js</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2015/12/27/promise-based-coroutines-nodejs">
            <updated>2015-12-27T05:00:00.000Z</updated>
            <id>http://tobyho.com/2015/12/27/promise-based-coroutines-nodejs</li>
            <content type="text">
Ever since the dawn of Node.js, Node developers have complained about [Callback Hell](http://callbackhell.com/). Various solutions have been proposed with various degrees of success.
[Generators](http://tobyho.com/2013/06/16/what-are-generators/) is an exciting prospect because it finally allows us to write async code in a straight-line fashion. Although generators is not yet available on all browsers, you can make it work using the [Babel compiler](https://babeljs.io/). It is getting more adoption in Node because the modules [co](https://github.com/tj/co) and [koa](https://github.com/koajs/koa) have been around for over 2 years, and first [IO.js](https://iojs.org/en/) and now Node has had out-of-the-box support for it since version 4.0. This post will cover two modules that give support to generators as a coroutine mechanism to tame the async beast: [co](https://github.com/tj/co) and [Bluebird](https://github.com/petkaantonov/bluebird). Both co and Bluebird make use of promises. Bluebird is in fact specifically a promise library. The way you write coroutines with co vs Bluebird are quite similar.

## Prerequisites

While you may be able to vaguely follow along otherwise, I do expect you to know about *generators* and *promises*. Here are some resources if you need to drill down to those topics:

* Generators
  * [What is this thing called generators?](http://tobyho.com/2013/06/16/what-are-generators/)
  * [The Basics of Generators](https://davidwalsh.name/es6-generators)
* Promises
  * [JavaScript Promises](http://www.html5rocks.com/en/tutorials/es6/promises/)
  * [JavaScript Promises: A Tutorial with Examples](http://www.toptal.com/javascript/javascript-promises)

## The Big Idea

Both co and Bluebird let you do the following: `yield` a promise to get the underlying value that's wrapped by the promise. Since we can use promises to wrap async operations, yielding allows async operations to be written in a straight-line manner - something that has been sought after since the dawn of Node.js.

## co

[co](https://github.com/tj/co) is a module that returns just two functions
:

* `co(genFn)` - co takes a generator function and returns a promise. It will execute the supplied generator function to completion and then resolve the promise.
* `co.wrap(genFn)` - co.wrap works like co except it returns a function that returns a promise.

The following program will read a Markdown file from the filesystem, convert the contents to HTML, then read a handlebars template file again from the filesystem, then inject the contents into the template, and finally write the resulting HTML into a file.

{% highlight js %}
'use strict'

const co = require('co');
const marked = require('marked');
const fs = require('fs-promise');
const handlebars = require('handlebars');

co(function *() {
  let md = yield fs.readFile('README.md');
  let html = marked(md.toString());
  let template = yield fs.readFile('layout.hbs');
  let output = handlebars.compile(template.toString())({
    title: 'README',
    contents: html
  });
  yield fs.writeFile('index.html', output);
}).catch(function(err) {
  console.error(err.stack);
});
{% endhighlight %}

[Full Source](https://github.com/airportyh/coroutines-in-node/blob/master/co.js)

There are a few things to note about this example:

1. Instead of the core fs module, I am using the `fs-promise` module which promisifies all the fs APIs.
2. Whenever we need an async operation, we wrap it up inside of a promise, and we `yield` it to get back the underlying value. In this example, I use `yield` twice to read a file, and once to write a file. In the case of writing a file, I didn't care about the resulting value.
3. Error handling: since `co()` returns a promise, I can use [catch()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) to handle any errors occurs within the coroutine - anything from file-not-found to variable-not-defined. If I hadn't set up an error handler this way, any error that occured would have been silenced, which doesn't not make for a good debugging experience.

## Bluebird

Bluebird is primarily a promise library - maybe the most popular one at this time. But it also features a [coroutine function](http://bluebirdjs.com/docs/api/promise.coroutine.html) which works very similarly to co. Rewriting the previous example using Bluebird is a small change

{% highlight js %}
'use strict'

const bluebird = require('bluebird');
const marked = require('marked');
const fs = require('fs-promise');
const handlebars = require('handlebars');

bluebird.coroutine(function *() {
  let md = yield fs.readFile('README.md');
  let html = marked(md.toString());
  let template = yield fs.readFile('layout.hbs');
  let output = handlebars.compile(template.toString())({
    title: 'README',
    contents: html
  });
  yield fs.writeFile('index.html', output);
})().catch(function(err) {
  console.error(err.stack);
});
{% endhighlight %}

[Full Source](https://github.com/airportyh/coroutines-in-node/blob/master/bluebird.js)

The only changes are

1. It use the `bluebird.coroutine()` function instead of `co()`.
2. `bluebird.coroutine()` returns a function that returns a promise, as opposed to `co()` which returns a promise directly - this is like the behavior of `co.wrap()` - this necessitated adding a `()` to invoke the resulting function that was returned.

## Same Example Code in Promsed-Land

For comparison, this is what the example code might have looked like written using promises, but without the help of coroutines

{% highlight js %}
'use strict'

const marked = require('marked');
const fs = require('fs-promise');
const handlebars = require('handlebars');

fs.readFile('README.md').then(function(md) {;
  let html = marked(md.toString());
  return [fs.readFile('layout.hbs'), html];
})
.spread(function(template, html) {
  let output = handlebars.compile(template.toString())({
    title: 'README',
    contents: html
  });
  return fs.writeFile('index.html', output);
})
.catch(function(err) {
  console.error(err.stack);
});
{% endhighlight %}

[Full Source](https://github.com/airportyh/coroutines-in-node/blob/master/promise-based.js)

Note: [spread()](http://bluebirdjs.com/docs/api/spread.html) is a convinience provided by Bluebird, which is used by [fs-promise](https://www.npmjs.com/package/fs-promise) underneath.

## Promisifying Async Operations

Using this coroutine paradigm means that you have to wrap any and all async APIs with promisified versions. You have two options:

1. Use a promise library's helper utilities to wrap Node-style async functions as functions that return a promise.
    * [Bluebird](http://bluebirdjs.com/) provides [promisify](http://bluebirdjs.com/docs/api/promise.promisify.html) and [promisifyAll](http://bluebirdjs.com/docs/api/promise.promisifyall.html).
    * [Q](https://github.com/kriskowal/q) provides [nfcall](https://github.com/kriskowal/q#adapting-node) and [nfapply](https://github.com/kriskowal/q#adapting-node).
2. Use libraries whose sole purpose is to promisify an exist Node-style library. Some examples are:
    * [fs-promise](https://www.npmjs.com/package/fs-promise)
    * [request-promise](https://www.npmjs.com/package/request-promise)
    * [child-process-promise](https://www.npmjs.com/package/child-process-promise)

## Extracting Sub-Coroutines

Now that you are writing a lot of code inside of generator functions, you may want to at some point break them up into sub-routines in order to reuse and better organize your code. Normally you'd extract a new function, but since you can't use `yield` statements inside of functions, you will need need to extract generator functions.

### Subroutines With co

Extracting subroutines will work slightly differently between co and Bluebird. I will start with co.

If I wanted to extract a routine called `md2html` to convert a Markdown file to HTML. I could write

{% highlight js %}
function * md2html(filename) {
  let md = yield fs.readFile(filename + '.md');
  let html = marked(md.toString());
  let template = yield fs.readFile('layout.hbs');
  let output = handlebars.compile(template.toString())({
    title: filename,
    contents: html
  });
  yield fs.writeFile(filename + '.html', output);
  console.log(`Wrote ${filename}.html`);
}
{% endhighlight %}

The body of this generator function is mostly copy-n-pasted from my original, only now with the file name substituted via a variable. To call this generator function via another function, you would simply `yield` it:

{% highlight js %}
yield md2html('README');
{% endhighlight %}

[Full Source](https://github.com/airportyh/coroutines-in-node/blob/master/sub-routine.js)

### Subroutines With A Return Value

If you want to extract a subroutine that returns a value, you can use the `return` statement within the extracted generator function - same as normal functions. For example, let's say we want to return the generated markup instead of writing it to a file:

{% highlight js %}
function * md2html(filename) {
  let md = yield fs.readFile(filename + '.md');
  let html = marked(md.toString());
  let template = yield fs.readFile('layout.hbs');
  let output = handlebars.compile(template.toString())({
    title: filename,
    contents: html
  });
  return output;
}
{% endhighlight %}

Now we can yield to get its value:

{% highlight js %}
let html = yield md2html('README');
{% endhighlight %}

[Full Source](https://github.com/airportyh/coroutines-in-node/blob/master/sub-routine-with-return.js)

### Subroutines With Bluebird

Bluebird's coroutine mechanism doesn't permit yielding generator instances directly. To extract a generator function in Bluebird, you could use the `bluebird.coroutine` function to wrap the extracted generator function

{% highlight js %}
const md2html = bluebird.coroutine(function * md2html(filename) {
  let md = yield fs.readFile(filename + '.md');
  let html = marked(md.toString());
  let template = yield fs.readFile('layout.hbs');
  let output = handlebars.compile(template.toString())({
    title: filename,
    contents: html
  });
  return output;
});
{% endhighlight %}

And then invoking the coroutine the same way

{% highlight js %}
let html = yield md2html('README');
{% endhighlight %}

[Full Source](https://github.com/airportyh/coroutines-in-node/blob/master/sub-routine-with-return-bluebird.js)

## Parallelizing Tasks

Someone once mentioned to me that using generators in Node is not in the Node style because it removes the parallelization of IO operations that Node [gives you for free](http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/). Well, yes and no, because this can be easily rectified.

Let's say you have 100 files you have to convert from Markdown to HTML. You might do this:

{% highlight js %}
let files = yield fs.readdir('markdown');
for (let i = 0; i < files.length; i++) {
  yield md2html('markdown/' + path.basename(files[i], '.md'));
}
{% endhighlight %}

[Full Source](https://github.com/airportyh/coroutines-in-node/blob/master/serial.js)

And this would convert the files serially. But to convert them in parallel is pretty easy too! Just convert each task into a promise and then use [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) or equivalent to execute them in parallel. `Promise.all()` takes an array of promises and resolves as an array of the resolved values of the promises when every one of the promises has resolved. *Hint: you can convert a generator function into a promise using co or Bluebird.*

{% highlight js %}
let files = yield fs.readdir('markdown');
let tasks = files.map(function(file) {
  return co(md2html('markdown/' + path.basename(file, '.md')));
});
yield Promise.all(tasks);
{% endhighlight %}

[Full Source](https://github.com/airportyh/coroutines-in-node/blob/master/parallel.js)

If you want to limit the concurrency - the number of tasks that are being performed at a time, you can use the [throat module](https://www.npmjs.com/package/throat).

## Error Handling

Error handling within a coroutine is easy - you can use try/catch. *What a concept!*

{% highlight js %}
function * md2html(filename) {
  try {
    let md = yield fs.readFile(filename + '.md');
    let html = marked(md.toString());
    let template = yield fs.readFile('layout.hbs');
    let output = handlebars.compile(template.toString())({
      title: filename,
      contents: html
    });
    yield fs.writeFile(filename + '.html', output);
    console.log(`Wrote ${filename}.html`);
  } catch (e) {
    console.error(`Failed to convert ${filename}.md because ${e.message}`);
  }
}
{% endhighlight %}

[Full Source](https://github.com/airportyh/coroutines-in-node/blob/master/error-handling.js)

## Gotchas

The most common gotcha for someone learning to use this paradigm is forgetting to yield a promise. Unfortunately, you often won't get a very illuminating error message in this case due to JavaScript's lack of type safety. For example, if I had forgotten to yield the promise that holds the contents of the file:

{% highlight js %}
let md = fs.readFile(filename + '.md');
let html = marked(md.toString());
{% endhighlight %}

[Full Source](https://github.com/airportyh/coroutines-in-node/blob/master/forgot-yield.js#L15)

`md` would hold the promise object rather than the actual buffer containing the content of the file. Then on the next line, `md.toString()` will actually work and return the string "[object Promise]" because `toString()` is a method that all JavaScript objects have.

If you forget to yield a generator function that doesn't return a value, or whose value you simple don't care about

{% highlight js %}
md2html('README'); // nothing happens!
{% endhighlight %}

[Full Source](https://github.com/airportyh/coroutines-in-node/blob/master/forgot-yield-2.js#L9)

That generator function never executes! Because calling a generator function only instantiates a generator instance, but it doesn't execute that generator instance.

If you are hitting a JSON-based API, and you forget to yield, for example

{% highlight js %}
let result = request({
  url: 'https://api.github.com/repos/petkaantonov/bluebird', 
  json: true,
  headers: { 'User-Agent': 'Script' }
});
let owner = result.owner.login;
{% endhighlight %}

[Full Source](https://github.com/airportyh/coroutines-in-node/blob/master/forgot-yield-3.js)

Will result in a `TypeError: Cannot read property 'login' of undefined` because a promise object doesn't have the properties/object struct you are expecting.

Alas, we are still coding JavaScript!

## Are Coroutines Right For You?

I have been using this approach for Node.js programming to do standalone command-line scripts, app servers, and end-to-end browser tests using selenium, and not having to write the standard Node-style callback pattern and handle error handling code every time I do an IO operation has really help me reduce mental and typing overhead.

I think this approach is particularly appealing if you primarily do server-side programming. You can also use this approach in the browser in a way that works cross-browser if you use the [Babel compiler](https://babeljs.io/) with the [regenerator runtime](https://babeljs.io/docs/usage/polyfill/) - although I have not done this extensively.

One reason some people might shy away from adopting this technique now is the upcoming [async/await](http://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html) feature - which is essentially a small layer of syntactic suger on top of generators. async/await is an ES7 feature, but you can already use it currently if you use the Babel compiler. I have not taken this route myself because I take comfort in staying close to the metal and prefer not using code transpilers. Also, in general I feel more comfortable when there is a bit of distance between me and the bleeding edge.

At the end of the day, try it and see.

## Next Up

In the near future I will have more to say about server programming and testing in this paradigm.</content>
        </entry>,<entry>
            <title>Mocha With Promises</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2015/12/16/mocha-with-promises">
            <updated>2015-12-16T05:00:00.000Z</updated>
            <id>http://tobyho.com/2015/12/16/mocha-with-promises</li>
            <content type="text">
You may not know that the [Mocha JavaScript testing framework](https://github.com/mochajs/mocha) has direct support for promises. Back in the day, Domenic Denicola created [mocha-as-promised](https://www.npmjs.com/package/mocha-as-promised) to add support to Mocha. mocha-as-promised was [rolled into Mocha](https://github.com/domenic/mocha-as-promised) in Mocha version 1.18.0, which means that Mocha now has built-in support for promises. However, this information is not very widely available on the web at the moment. This post will try to help rectify that.

## TL;DR - Get Rid of the `done` Callback, Return A Promise

Whereas the traditional way of testing asynchronous code in Mocha is to have your test function take a `done` callback function:

{% highlight js %}
it('reads some file', function(done) {
  fs.readFile('someFile.json', function(err, data) {
    if (err) return done(err);
    assert(data != null, "File should exist.");
    done();
  });
});
{% endhighlight %}

With built-in promise support - you no longer need the `done` callback. All you have to do is return a promise from the test function:

{% highlight js %}
var fs = require('fs-promise');

it('reads some file', function() {
  return fs.readFile('someFile.json')
    .then(function(data) {
      assert(data != null, "File should exist.");
    });
});
{% endhighlight %}

What's really nice about this is you can stop writing error handling code for good, even for tests with multiple asynchronous steps. For example, this is a test that makes a post request to the server and then verifies the data in the Mongo database:

{% highlight js %}
it('sets settings', function() {
  return agent.post('/settings')
    .send({
      notifications: false
    })
    .expect(200)
    .then(function(resp) {
      expect(resp.body.success).to.equal(true);
      return User.findById(user.id);
    })
    .then(function(user) {
      expect(user.notifications).to.equal(false);
    });
});
{% endhighlight %}

This code uses [superagent-as-promised](https://www.npmjs.com/package/superagent-as-promised) which is a small wrapper on top of [supertest](https://github.com/visionmedia/supertest) to give it promises support. It uses the `supertest.agent` API to handle persistent cookies so that authentication can work in the tests. It also uses [mongoose](http://mongoosejs.com/) - which supports promises out of the box.
</content>
        </entry>,<entry>
            <title>How To Not Fall Asleep While Driving</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2015/12/02/how-to-not-fall-asleep-driving">
            <updated>2015-12-02T05:00:00.000Z</updated>
            <id>http://tobyho.com/2015/12/02/how-to-not-fall-asleep-driving</li>
            <content type="text">
If you've ever driven a car on a long road trip, you have probably faced the challenge of staying awake while driving. The stakes are high on this one - failure could mean death. I am going to share a tip that has worked better than anything else that I have tried, and which has never once failed me. Who knows? It might save your life.

## The Technique

This is what you do: *listen to familiar songs which you can sing by memory and sing along to it* - that's it.

It's better to have a collection of these songs ready - possibly a favorite album, because if you listen to the same song over and over again, you might get bored after a while.

## Alternative Technique

A variation of this technique is to try to learn the lyrics to a song which you are pretty familiar with, but haven't gotten the memorization down yet. Listen to this same song on repeat, and try to sing all the syllables along with the track - it's okay if you sing/say the syllables slightly later than the track. If possible, try doing this with multiple different versions of this song - different recording, different style, different arrangement, different artist, etc.

## Feedback

If don't have any science to back up why this works. If you do, please post it in the comments. If you tried this technique, please let me know if it worked for you.</content>
        </entry>,<entry>
            <title>Changing Code Styles By Source Rewriting</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2015/11/17/changing-code-styles-by-source-rewriting">
            <updated>2015-11-17T05:00:00.000Z</updated>
            <id>http://tobyho.com/2015/11/17/changing-code-styles-by-source-rewriting</li>
            <content type="text">
Recently I switched Testem codebase's JavaScript style from a [semicolonless style](http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding) to a [semicolonful style](https://davidwalsh.name/javascript-semicolons). This post will reveal how I did that in the hope that it will be helpful to others. This post doesn't endorse one style or the other, in fact, you can also use the same technique to switch your codebase's style from semicolonful to semicolonless. In fact, whichever side you are on, maybe you *should* switch for a couple of days to develop empathy for folks whose opinion differ from yours. You can always switch back!

## General Procedure

To tackle this problem, I again turned to my handy source rewriting tool - [falafel](http://tobyho.com/2013/12/20/falafel-source-rewriting-magicial-assert/). The reason falafel is awesome is that you can safely rewrite the parts of the code you want to rewrite without touching any of the code that you *don't* want to change. Source rewriting is usually a trial and error process - at least for me. First you start by parsing some code and looking at its AST, then you decide which types of nodes you want to modify, and you modify them using the `.update()` method provided by falafel. Please read my [falafel introductory article](http://tobyho.com/2013/12/20/falafel-source-rewriting-magicial-assert/) for a proper introduction - which I won't repeat here.

Working a large scale automated code rewrite like this, you risk breaking stuff. Which is why having a test suite is helpful in this case. My procedure would turn out to be:

1. Write/edit the code transform script.
2. Apply the script to the codebase.
3. Run the tests.
  4. If tests fail
    * Diagnose problem.
    * `git reset --hard HEAD`
    * Go to 1.
  5. If tests pass
    * review the code for any visible problems. 
      * If there are visible problems
        * Come up with fix. 
        * `git reset --hard HEAD`
        * Go to 1.
      * If everything looks good, job is done.

## Requirements

I had two requirements:

1. Ensure semicolons are always used, and used properly.
2. Ensure that there is a space between the closing paranthesis `)` and the next open curly bracket `{` for functions, loops, and if statements.

## Adding In The Semicolons

To add semicolons, first I tried simply

{% highlight js %}
var newCode = falafel(code, function(node) {
  if (node.type === 'ExpressionStatement' ||
    node.type === 'ReturnStatement' ||
    node.type === 'VariableDeclaration')
    ensureSemiColon(node);
  }
});

function ensureSemiColon(node) {
  var src = node.source();
  if (src[src.length - 1] !== ';') {
    node.update(node.source() + ';');
  }
}
{% endhighlight %}

This worked for the most part, but broke for loops. In the case of `for-in` loops, this happened:

{% highlight js %}
for (var key; in object){
  ...
}
{% endhighlight %}

Oops!

In the case of regular for loops, it was this:

{% highlight js %}
for (var i = 0;; i < arr.length; i++){
  ...
}
{% endhighlight %}

So I revised my code to

{% highlight js %}
var newCode = falafel(code, function(node) {
  if (node.type === 'ExpressionStatement' ||
    node.type === 'ReturnStatement') {
    ensureSemiColon(node);
  } else if (node.type === 'VariableDeclaration') {
    if (node.parent.type !== 'ForInStatement' &&
      node.parent.type !== 'ForStatement') {
      ensureSemiColon(node);
    }
  }
});
{% endhighlight %}

This passed the tests and all looked good.

## Adding That Space For Padding

For this problem, I first tried simply adding a space in front of all block statements.

{% highlight js %}
var newCode = falafel(code, function(node) {
  if (node.type === 'BlockStatement') {
    node.update(node.source() + ' ');
  }
});
{% endhighlight %}

While this didn't break the tests, it was overkill because any code that already had a space padding now have two spaces for padding. I ended up using just regex matching:

{% highlight js %}
if (node.type === 'ForStatement' ||
  node.type === 'ForInStatement' ||
  node.type === 'IfStatement' ||
  node.type === 'FunctionDeclaration' ||
  node.type === 'FunctionExpression') {
  var src = node.source();
  src = src.replace(/\)\{/, ') {');
  src = src.replace(/\}else/g, '} else');
  src = src.replace(/else{/g, 'else {');
  node.update(src);
}
{% endhighlight %}

Dumb. Simple. Obvious. Works!

That's it! Here is the [full source](https://gist.github.com/airportyh/996c1f1afe7105e3eb07) for the code I used to rewrite Testem's codebase, and here is the [pull request](https://github.com/testem/testem/pull/668).
</content>
        </entry>,<entry>
            <title>Functional Programming By Example</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2015/11/09/functional-programming-by-example">
            <updated>2015-11-09T05:00:00.000Z</updated>
            <id>http://tobyho.com/2015/11/09/functional-programming-by-example</li>
            <content type="text">
While chatting in a CodeNewbie Slack channel I realized that the question of what functional programming is in relation to object oriented programming is a question that comes up a lot and is an area of great confusion. For this reason, I wanted to write an article to hopefully help clear up this confusion, even if just for a little.

What I came up with was [11 different versions](https://github.com/airportyh/word-count) of the same program. The program reads in a file containing some text, breaks the text into individual words, counts them up, and displays the top 10 words that were used in the text.

I don't think this will work as your first introduction to functional programming. It is probably used best as a pairing to another introductory article or lecture. Here are a few to choose from:

* [Chapter 6 of Eloquent JavaScript](http://eloquentjavascript.net/1st_edition/chapter6.html)
* [Mostly Adequate Guide to FP - online book](https://github.com/MostlyAdequate/mostly-adequate-guide)
* [Fun Fun Function's video series on FP in JS](https://www.youtube.com/watch?v=BMUiFMZr7vk)
* [A NetTut's Paid Video Course on FP in JS](http://code.tutsplus.com/courses/functional-programming-in-javascript)
* [JavaScript Allonge - online book](https://leanpub.com/javascriptallongesix/read)

I have heavily commented each of these source files, and I think the best way to read them is to open them all up in individual browser tabs, and then start reading from 1. At times a source file may make reference to another source file, at which point you are welcome to jump to the refering one, and you can certainly bounce around as much as you'd like to. Without further ado, here they are:

1. <a href="https://github.com/airportyh/word-count/blob/master/1.imperative.js" target="_blank">Imperative Code</a>
2. <a href="https://github.com/airportyh/word-count/blob/master/2.imperative-w-functions.js" target="_blank">Imperative Code With Functions</a>
3. <a href="https://github.com/airportyh/word-count/blob/master/3.oo-one-class.js" target="_blank">Object Oriented - One Class</a>
4. <a href="https://github.com/airportyh/word-count/blob/master/4.oo-small-classes.js" target="_blank">Object Oriented - Small Classes</a>
5. <a href="https://github.com/airportyh/word-count/blob/master/5.fp-softcore.js" target="_blank">Functional Programming - Basic</a>
6. <a href="https://github.com/airportyh/word-count/blob/master/6.fp-pure-functions.js" target="_blank">Functional Programming - Pure Functions</a>
7. <a href="https://github.com/airportyh/word-count/blob/master/7.fp-pure-but-slow.js" target="_blank">Functional Programming - Maximally Pure But Slow</a>
8. <a href="https://github.com/airportyh/word-count/blob/master/8.fp-pure-w-mori.js" target="_blank">Functional Programming - With Mori</a>
9. <a href="https://github.com/airportyh/word-count/blob/master/9.fp-currying.js" target="_blank">Functional Programming - Currying</a>
10. <a href="https://github.com/airportyh/word-count/blob/master/10.fp-composition-and-pointfree.js" target="_blank">Functional Programming - Composition and Point-Free</a>
11. <a href="https://github.com/airportyh/word-count/blob/master/11.fp-final.js" target="_blank">Functional Programming - Final Result</a>
</content>
        </entry>,<entry>
            <title>Bypassing B - What's it Good For?</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2015/10/09/uses-of-perceptual-learning">
            <updated>2015-10-09T04:00:00.000Z</updated>
            <id>http://tobyho.com/2015/10/09/uses-of-perceptual-learning</li>
            <content type="text">
In [Making Badass Developers](https://www.youtube.com/watch?v=FKTxC9pl-WM) (recommended!), Kathy Sierra highlights the limited capacity of our working memory, and shares some learning strategies to deal with it. In this post, I want to ponder the last of her three strategies: what she calls "bypassing B". In her talk, she separates your skills into one of three boards: A, B, and C - imagine [kanban boards](https://en.wikipedia.org/wiki/Kanban_board) if you are familiar with the agile methodologies. On board A are skills you have yet to learn, on B are skills you are in the process of learning, and on C are skills you have mastered. Thus, bypassing B means:

> ... going straight from "I have no idea what I'm doing." to "I am an absolute expert."

I know what you are thinking: *is this sort kind of voodoo magic?* This technique is called perceptual learning. It is a technique that's been used successfully to teach people chick sexing (determining the sex of baby chicks by looking at their butt), plane spotting (at war times, determining whether or not an incoming plane is an enemy plane), and interpreting the state of a plane based on its instruments readings. All of these tasks are non-trivial and cannot be solved simply by following a set of rules. The teaching technique works by exposing the learners to many many examples in a short period of time. For each example examined

1. The student sees the example.
2. The student guesses an answer for that example.
3. The teacher gives the actual correct answer.
4. Repeat.

That's it! This is also essentially how you train [neural networks](https://en.wikipedia.org/wiki/Artificial_neural_network) or any kind of [machine-learning](https://en.wikipedia.org/wiki/Machine_learning)-based system. Given that this is an artificial intelligence technique, isn't it apt that it also works on us humans? In one study, it was found that a group of flight trainees were able to learned how to read their instruments with greater accuracy than even seasoned pilots in merely two hours (note, that still doesn't mean the trainees can fly a plane).

## Why My Red Flags Went Off

When I viewed the video, a couple of things set of red flags in my head.

1. With an approach like this, you will end up with people who "don't know how they know". To be a good programmer, it's very important to understand things from first principles and being able to derive the world from the ground up on-demand. Understanding things at a basic level allows you to adapt to different situations and changing environments - both of which are a fact of life in the software industry.
2. As Kathy admits, this will not work for everything, but only some subset of the skills that we need to learn. In a way, it's too good to be true.

Despite this, after reading about more examples for which this concept is applicable, I am convinced that this is more widely applicable than I first thought. One of those examples is reading: when we read a passage in a book, we recognize whole words at a time, rather a letter at a time. How did we learn to do this? Lots, lots, lots of practice of seeing and identifying.

## How Can We Use This?

So how can we apply this concept to learning to code? Here are some ideas.

### When To Refactor?

Kathy mentioned as an idea: the detection of "code smell". A problem with this idea is that simply knowing that something "smells" doesn't tell you how to fix it. Perhaps what could be done is to narrow down the specificity and do this for [each type of refactoring](http://refactoring.com/catalog/) - i.e. in what situations one should use a particular refactoring vs not. Since many of the refactorings in Fowler's book have a corresponding inverse refactoring - an example being [extract method](http://refactoring.com/catalog/extractMethod.html) vs [inline method](http://refactoring.com/catalog/inlineMethod.html). One could create a "training set" - a set of code examples tagged with the correct answer specifying whether in this case it is better to extract a method or to inline it. There are already some heuristics we use in the industry, such as the [rule of three](https://en.wikipedia.org/wiki/Rule_of_three_\(computer_programming\)), but this technique could potentially teach these skills more granularly.

However, one objection does come to mind. In my understanding of refactoring based on the way that I approach it, the best solutions to refactoring are not found instinctively, but rather by first gaining an understanding of the problem, then mentally reflecting on the problem (brainstorming), and then coming up with an alternate solution. Then, even after the alternate solution comes to mind, to really know if it will work out or not, one sometimes has to first actually implement it, or at least prototype it, and then juxtaposition it with the original code. Often times when I do this, if I am unhappy with the outcome, I would undo the refactoring attempt. In order to judge how good a particular code solution is, you have to balance various different trade-offs you made, and you have to look at the solution as a whole. So, while this method could teach some rule-of-thumbs for refactoring, I don't think it is able to teach all of its different nuances.

### Classifying Error Messages

Another idea that could work is to teach students to recognize and classify error messages. Errors are often confusing and intimidating to junior developers. A lot of developers - even some experienced ones - when they see an error, their first instinct is *not* to read it. I think there is a lot of value to having a training program that effectively teaches someone to tell - based on reading the error message - what subsystem might be causing the problem, and therefore, what they should investigate as the next step.

For example, if you are working on a Rails app, and you get an error in your web browser, can you tell whether this is

* a web browser error (it couldn't even connect to your app)
* a routing error (404)
* a syntax / runtime error in your JavaScript
* an error in your HTML
* an error in your CSS
* a syntax error in your web template
* a syntax / runtime error in your controller
* a syntax / runtime error in your model
* a runtime error from active record
* an error coming from one of the gems (libraries) you are using
* a database error (PostgreSQL, MongoDB, etc)

For seasoned developers, each of these types of errors have certain special characteristics which they've internalized so well that they know them subconciously - it is instinctual. I think this skill *is* something that could be taught using an intensive perceptual learning training program such as described by Kathy. The training program would need to be specific to the specific programming environment that the students are targeting to learn, because the error messages coming from Rails would look very different from the ones coming from Django. Given this, fragmentation of the open source ecosystem makes it more difficult to share training material. Companies that use non-mainstream programming environments may have to put together their own training materials.

However, with that said, I think it wouldn't be very hard to put together a training set for any individual who is interested in training their junior developers. All that is required is for some developer(s) to be mindful of taking a screenshot each time they get an error screen during their own development time. Over time, you would have a good collection of screenshots of error messages. Tag each screenshot with the correct subsystem, and you have what you need to train your apprentices!

### Syntax Correctness

Seasoned developers swim in code. They know code so well that they can tell instinctively if a piece of code is syntactically wrong. This ability allows them to self-correct their mistakes before they even attempt to run it, thus speeding up their development process. This instinct is something we also can train by using lots of examples and lots of practice. I can imagine a syntax training program where the student is asked to look at code snippet after code snippet in succession, and are asked to spot any syntax errors in the code, or to verify that the code is indeed syntactically correct. To build something like this, we need a large set of code snippets containing examples of both valid syntax and invalid syntax. I think that for this to work best, the code snippets would need to be small - anywhere between 5 to 15 lines - so that you can scan it quickly. Ideally, the set would contain examples of all the various types of language constructs and various common ways of making syntax errors. Also ideally, we would have a profile of the most common types of syntax errors that developers make. For example, one common mistake is to forget to close your paranthesises, especially in cases where multiple closing parans are required:

{% highlight js %}
if (user.isLoggedIn() {
  ...
}
{% endhighlight %}

Some JS beginners would simply forget that parans are required at all in the conditional clause of an if statement:

{% highlight js %}
if user.isLoggedIn {
  ...
}
{% endhighlight %}

It could be that they are coming from a language like Ruby or Python where this is indeed the case.

Another kind of common mistake is typos: the mispelling of a variable name or a language keyword.

{% highlight js %}
funtion greet(person) {
  console.log(`Hello, ${persn}!`);
}
{% endhighlight %}

Yet another kind of mistake is not realizing you are using a language keyword for a variable name - to avoid this mistake basically requires you to know instinctively what words are "specially" and cannot be used.

{% highlight js %}
var function = 'greet';
bob[function]();
{% endhighlight %}

I made a tool called [tupo](https://github.com/airportyh/tupo) which randomly introduces errors to valid programs, which although doesn't get us all the way there, could be helpful if someone were to build a training set for this purpose. If this approach is successful, it can also be extended to include coding style, picking good names for things, and dangerous or undesirable code patterns which linters would otherwise catch.

### Touch-Typing

Touch-typing: the ability to type without having to look at the keyboard is an underrated skill. Even if you already know touch typing, there are benefits to practicing it and continuing to improve. The ability to produce words or code at or near the speed of thought is extremely powerful, and will - in video game terms - unlock you a new level in both your productivity *and* your creativity. The process of learning to touch-type can be modelled as a perceptual learning task: you are shown a letter you have to type, and you have to move the correct finger to the correct position in order to push the correct key. With enough practice of enough examples, you will get really good at this, and the beauty is: that's *all* you need to do. You don't need to read any books or try to build things that work - things that require thinking at a deeper level. Just practice, and you will get better. That's the whole point of this teaching technique, isn't it?

Here are some touch typing resources:

* [typing.io](https://typing.io/) - this a typing practice program specifically for programmers. Typing in programming requires an emphasis on punctuation and special symbols, which most typing-teacher software de-emphasize.
* [GNU Typist](https://www.gnu.org/software/gtypist/) - GNU typist is a terminal-based unix program for learning to type. It supports QUERTY, DVORAK, and COLEMAK. If you are on mac, you can install it with `brew install gtypist`. On Windows, you can probably run it in cygwin, although I haven't personally tried it.
* [typing.lk](http://typing.lk/) - this looks like a good, relatively distraction-free web-based typing tutor.

## Closing Thoughts

Perceptual learning is a technique that seems to be largely untapped in the field of teaching/learning to code. I think it's time that we tap into it. Although it isn't a silver bullet, perceptual learning can give learners a big speed boost in mastering certain specific skills. If we can apply this technique to some subset of the essential skills that developers need in their day to day work, this would have the effect of reducing the cognitive load of the learners so that they can use that extra cognitive power to learn the rest of what they have to learn.

## Any Ideas?

I think that any skill that exclusively uses our fast thinking, instinctual, reflexive, reactive brain as opposed to our slow thinking, logical, analytical, number crunching brain is a candidate for this technique. Do you have any ideas what other skills could be taught using this technique? Please let me know in the comments or tweet me [@airportyh](https://twitter.com/airportyh).

</content>
        </entry>,<entry>
            <title>How To Get More Curiosity</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2015/10/05/how-to-get-more-curiosity">
            <updated>2015-10-05T04:00:00.000Z</updated>
            <id>http://tobyho.com/2015/10/05/how-to-get-more-curiosity</li>
            <content type="text">
I am working on a talk entitled "How to Learn" to be given at [ConnectJS](http://connect-js.com/) this year, where I will promote life-long learning, the [growth mindset](http://mindsetonline.com/whatisit/about/), and approaching learning to code - and life - with a healthy curiosity. It struck me that some people in my audience might make the objection that this works great for anybody with a natural tendency to be curious, but not for them. So, I googled "cultivating curiosity" and got some great advice on how to cultivate your curiosity from 4 different articles. I would summarize the advice as follows:

## Find interesting things within the familiar

Make a little bit of effort to find the things that are interesting, different, or out of place in otherwise boring things. In an NPR story [[1]](https://experiencelife.com/article/the-power-of-curiosity/), a potato chip factory worker found joy in his work by always being on the look out for odd looking potato chips and collecting them. He ended up with a collection potato chips that look like movie star sihouettes. As a runner, I pay close attention to the way in which the bottom of my feet hit the ground - I use it as an indication of how well balanced my body is at the point of impact. I also take care to notice how my knee joint feels at that point of impact as well as the rhythm of my breathing.

## Be Playful

Be on the watch out for silly things you can do or games you can play while learning. For some ideas, have a watch of Alex Sexton's [Uselessware :: a Brief History](https://alexsexton.com/blog/2012/03/uselessware-a-brief-history-jsconf-2011-talk/).

## Ask Tons of Questions; Get Them Answered

This advice comes from [Psych Central](http://psychcentral.com/blog/archives/2013/10/26/4-ways-to-cultivate-curiosity-for-creating-your-best-work/), but I totally already had it in my notes too, I swear!

Step 1: Keep a running log of questions. You should record a question whenever a questions pops into your head, no exceptions.

Step 2: Take the time to answer each and every one of those questions, by asking people, doing research, planning out and performing experiments on your own, or all of the above.

## Obsess About Things, A Lot

[Todd Kashdan](https://experiencelife.com/article/the-power-of-curiosity/) calls this *explore your passions*, I call it obsess about things. Everyone obsesses about something, explore that even more. When you are *obsessed*, you are much less like to be derailed by setbacks - it's like getting a blinking star in Super Mario Brothers. You can make progress much faster when you are obsessed than in your normal state. The next time you obsess about something, open up an investigation, start a new project, write a paper.

## Take In Information

Make a habit of learning new things, because the more knowledge you have, the more knowledge you have to draw on. Be inspired by consuming a steady diet of books, lectures, podcasts, etc.

## Get Comfortable With Being Uncomfortable

Some of the greatest moments of your life are when you've triumphed under uncomfortable and uncertain situations. You would not have even had those opportunities had you not placed yourself in those circumstances. In order to grow, you need to stretch yourself in slightly awkward positions, and overcome them. The more you do this, the faster you will grow.

One of [Tim Ferriss' productivity hacks](http://fourhourworkweek.com/2013/11/03/productivity-hacks/) puts this concept in to practice:

> Write down the 3-5 things — and no more — that are making you most anxious or uncomfortable. They’re often things that have been punted from one day’s to-do list to the next, to the next, to the next, and so on. For each item, ask yourself:
  * “If this were the only thing I accomplished today, would I be satisfied with my day?”
  * “Will moving this forward make all the other to-do’s unimportant or easier to knock off later?”

## References

* <https://www.psychologytoday.com/articles/200608/cultivating-curiosity>
* <https://experiencelife.com/article/the-power-of-curiosity/>
* <http://fourhourworkweek.com/2013/11/03/productivity-hacks/>
* <http://psychcentral.com/blog/archives/2013/10/26/4-ways-to-cultivate-curiosity-for-creating-your-best-work/>
* <http://www.lifehack.org/articles/productivity/4-reasons-why-curiosity-is-important-and-how-to-develop-it.html></content>
        </entry>,<entry>
            <title>Hardest Things About Learning To Code Today</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2015/09/29/difficult-things-learning-code">
            <updated>2015-09-29T04:00:00.000Z</updated>
            <id>http://tobyho.com/2015/09/29/difficult-things-learning-code</li>
            <content type="text">
I have been running [Hacker Hours](http://hackerhours.org/) events in the Greater Atlanta Area for a couple of months. In one of those, I asked the participants this question: *what are the things about learning to code that is the most difficult for you?*

## The Answers

These are the general responses I got:

1. "A lot of us are self-taught, and have a lot of holes in our knowledge. Some of them we know we have, but some of them we don't even have an idea that we don't know it." 
2. "There's too much information. Lots' of different ways/methods of doing something."
3. "I would like an end-to-end, streamed lined, from beginning to end kind of way to learn something."
4. "The idea that the thing I am learning now will go out of date soon is unsettling."
5. "I've already done Codecademy, TreeHouse, Code School, etc. etc. Now what? Whose resources don't take you far enough."
6. "How deep is the rabbit hole? Sometimes I have trouble deciding between drilling down more into a subject area vs moving on."
7. "Should I attend a coding boot camp like Hack Reactor?"</content>
        </entry>,<entry>
            <title>Framework Trap</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2015/09/27/framework-trap">
            <updated>2015-09-27T04:00:00.000Z</updated>
            <id>http://tobyho.com/2015/09/27/framework-trap</li>
            <content type="text">
I tried to help someone fix her CSS - for some reason her footer appeared before the containing the content. I used "Inspect Element" in Chrome Dev Tools and determined that the problem was due to the contents element having a `float: left` element. I let her know this, and she said: "I am using [Bourbon](http://bourbon.io/), so I don't worry about floating, because bourbon takes care of that for me."

In another instance, she asked me whether she should learn Gulp. I asked, "Why do you want to learn Gulp?" She said, "Because it does auto-prefixing, and deployment, and lots more for me so I don't have to worry about it."

I heard a story where a software startup wrote their app in AngularJS, found significant performance problems, and upon being unable to solve them, rewrote the app using Backbone and Marionette. Actually, I've heard more than one story like this, you probably have too. Just substitute in different framework names and you have your standard: Why we ditched X and rewrote our app in Y story.

So what is the problem? Well, one problem is overhead. Rewriting an app is an enourmous undertaking. Joel Spolsky [advices against it at all costs](http://www.joelonsoftware.com/articles/fog0000000069.html). I take a more nuanced view - that one should weigh the costs vs the benefits of a rewrite, and better to rewrite bit by bit as opposed to all at once. In any case, clearly, rewriting a app incurs a big cost to a business' bottom line. In fact, this is similarly the case with big upgrades. How many of you know someone who is still working on upgrading from Rails 3 to Rails 4? How about upgrading to the latest version of Ember? Furthermore, rewriting an app doesn't guarantee that you'll end up with a better app. You'll just get a different app with a different set of problems. I have personally used plenty of software in which I much prefer an older version then the newer version.

All of that being said, over-rewriting is but a symptom of a deeper problem: *over-reliance*. When you carry the expectation that the framework of your choice is going to solve all your problems, what you don't expect is to have to solve any problems yourself. *"That's not my area"*. In effect what you've done is outsource your architecture decision making. But when you do this, you stop working out your problem solving muscles, and those muscles atrophy - or in some cases never even get a chance to develop. You will feel like if there's a problem, and your framework can't solve it, then it cannot be solved. You've [learned to be helpless](https://en.wikipedia.org/wiki/Learned_helplessness). Except, maybe... with an even better framework, one that will solve this problem *and more!* In other words, *the grass is always greener on the other side*.

But no framework will solve all the problems, no matter what framework or tool you decide to use, there will always be problems. Projects don't fail because the people chose the wrong framework. Projects fail because the people have the wrong mindset.
</content>
        </entry>,<entry>
            <title>Polymorphism That Just Works</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2015/06/23/polymorphism-that-just-works">
            <updated>2015-06-23T04:00:00.000Z</updated>
            <id>http://tobyho.com/2015/06/23/polymorphism-that-just-works</li>
            <content type="text">
Code JavaScript much? Have you ever complained about how the arguments object is not a real array? Ditto for [NodeLists](https://developer.mozilla.org/en-US/docs/Web/API/NodeList), right? Isn't it unsettling that if you care about compatibility with older browsers, you can't rely on useful array methods like `map`, `filter`, `reduce`, or even `indexOf`? Good thing we have underscore and lodash. If you are using a MVC framework that requires you to use their own collection class, it's yet another layer of translation and mental overhead: interacting with a Backbone.Collection or an Ember.Array requires talking to a different API vs a plain vanilla JavaScript array. But, you would think: an array is an array is an array, right? Why is this so hard?

Have you ever designed an object oriented API with crystal clear interfaces for interacting with your objects, only to later find out that someone else has made another library with the same purpose but a slightly different and incompatible API? If one wrote an application using one API and wanted to switch to the other, she would have to rewrite each of the differing integration points - places where her application uses the original API. Where is polymorphism when you need it?

## Polymorphism

In the above scenario, if the engineer were to want to make her application more generic and be able to switch between the two "implementations" at a moment's notice, she would design a new API which normalizes the differences between the two APIs, then write wrappers for each of the two originals which adheres to this new API. This is a use of polymorphism. However, the maneuver to get there has some palpable overhead:

1. The work of implementing the wrappers for each of the original implementations.
2. The work of switching all of the legacy code which used one or the other of the original APIs to the new "unifying" API.

\#1 is tedious but tractable. \#2 is more problematic: *its difficulty is directly proportional to the amount of legacy code you have.* No, actually it's more. If you take the view of all the code there is from a community perspective, there's all the code that's running out there. This maneuver is impossible when you have a large amount of legacy you care about keeping: such is the case with many early mistakes in the design of JavaScript.

## Frozen

To avoid the above overhead, what we do is API standardization. When an API becomes widely used, it's probably not ever changing again. That's why it's so important to get them right the first time, and that's why we have technical committees deliberating endlessly about what the best API should be. However,

1. There's little we can do about historical mistakes that are already there. *cough*arguments object*cough*
2. Even a group of super smart individuals aren't infallible to making mistakes.

## A Different Polymorphism

Which brings us to the point of this post: I will demonstrate an alternate technique for implementing polymorphism - as opposed to [interfaces](http://en.wikipedia.org/wiki/Interface_%28computing%29) or [duck typing](http://en.wikipedia.org/wiki/Duck_typing). This technique solves some if not all of the above problems. It is currently used in the Haskell, Clojure, and Rust realms. Haskell's answer to polymorphism is [type classes](http://learnyouahaskell.com/types-and-typeclasses). Clojure has a similar concept called [protocols](http://clojure.org/protocols). Rust has [traits](https://doc.rust-lang.org/book/traits.html). You are not required to be familiar with Haskell, Clojure, or Rust to understand the rest of this post. Instead of talking in terms of either of those, I will demonstrate a hand-rolled implementation of the concept in JavaScript.

## A Protocol

I will use Clojure's terminology: *protocols*. A protocol is very much like an interface in statically typed languages like Java or C#, but with the difference that the fact that a particular class implements a particular protocol is not tied to the implementation of that class.

Let's see an example. We have a class `User` (I am using [ES6 classes](http://www.2ality.com/2015/02/es6-classes-final.html) because that's how hip I am).

{% highlight js %}
class User {
  constructor(id, name, dateOfBirth) {
    this.id = id;
    this.name = name;
    this.dateOfBirth = dateOfBirth;
  }
}
{% endhighlight %}

I want to able to check two users to see if they are really the same person. In "classical" JS-style polymorphism, I would simply use duck typing, and make a method to implement the comparison.

{% highlight js %}
class User {
  ...
  equals(other) {
    return this.id === other.id;
  }
}
...
> bob.equals(robert)
true
{% endhighlight %}

Then, if you create another class - say `Vehicle` - which also contains the same `equals` method, you can also use `.equals()` with Vehicles - that's polymorphism!

With protocols, I would first define a protocol which I will call `Equal`. If JS had a protocol feature, it might look like:

{% highlight js %}
protocol Equal {
  equals(one, other);
}
{% endhighlight %}

Then, I would declare that all instances of `User` implements the `Equal` protocol:

{% highlight js %}
User implements Equal {
  equals(one, other) {
    // one is of type User. We also assume that other is of type User
    return one.id === other.id;
  }
}
{% endhighlight %}

*A bit of technicality: although `equals` takes two arguments, only the type of the first argument is used for choosing the actual `equals` implementation. This is how protocols in Clojure works, although Haskell's type class system is more generic and can allow dispatching off of arguments in any position.*

Once this is established, you would be able to test equality by using `Equal.equals()` not only for users but for any class that implements `Equal`:

{% highlight js %}
> Equal.equals(bob, robert)
true
> Equal.equals(tesla, bimmer)
false
{% endhighlight %}

## Protomorphism

Of course you realize that the syntax in the above section is completely made up and not runnable. Not to worry, I implemented this as a module: [protomorphism](https://github.com/airportyh/protomorphism). The syntax is not as pretty but it allows you to do the same thing. Instead of

{% highlight js %}
protocol Equal {
  equals(one, other);
}
{% endhighlight %}

, you would write

{% highlight js %}
const protocol = require('protomorphism');

const Equal = protocol({
  equals: function(one, other){}
});
{% endhighlight %}

, and instead of

{% highlight js %}
User implements Equal {
  equals(one, other) {
    return one.id === other.id;
  }
}
{% endhighlight %}

, you would write

{% highlight js %}
Equal.implementation(User, {
  equals: function(one, other) {
    return one.id === other.id;
  }
});
{% endhighlight %}

and that's it! The next examples provided will be all runnable via [protomorphism](https://github.com/airportyh/protomorphism).

## Example: Sorting

You could define a protocol for types that have a natural order, such as numbers or strings:

{% highlight js %}
const Ordered = protocol({
  // compare should return:
  // 0 if one and other are the same
  // positive number if one comes before other
  // negative number if one comes after other
  compare: function(one, other){};
});

Ordered.implementation(Number, {
  compare: function(one, other) {
    return one - other;
  }
});

Ordered.implementation(String, {
  compare(one, other) {
    if (one === other) {
      return 0;
    } else if (one > other) {
      return 1;
    } else {
      return -1;
    }
  }
});
{% endhighlight %}

With these, you can actually define a generic sort method for arrays that will sort either an array of numbers or strings correctly, unlike the [native sort()](http://tobyho.com/2010/03/04/javascript-sort%28%29-gotcha/):

{% highlight js %}
function sort(arr) {
  return arr.sort(Ordered.compare);
}
...
> sort([12, 3, 24])
[ 3, 12, 24 ]
> sort(['Ileen', 'Ahmad', 'Jason'])
[ 'Ahmad', 'Ileen', 'Jason' ]
{% endhighlight %}

You can also use this sort function to sort anything else that implements `Ordered`, such as poker cards - I'll leave this as an exercise for the reader.

## Example: Show

Another useful protocol is a way to return the string representation of an object for printing out while debugging.

{% highlight js %}
protocol Show {
  // show returns a string representing object
  show(object);
}

User implements Show {
  show(user) {
    return `User(${user.id}, ${user.name})`;
  }
}
...
> Show.show(bob)
User(12, "Robert")
{% endhighlight %}

Again, we can retroactively have native types like number and string implement this protocol:

{% highlight js %}
Show.implementation(Number, {
  show: function(n) { return String(n) }
});

Show.implementation(String, {
  show: function(s) { return JSON.stringify(s) }
});
{% endhighlight %}

And we might write a convinience function for printing out any object like:

{% highlight js %}
function print(object) {
  console.log(Show.show(object));
}
...
> print(bob)
User(12, "Robert")
> print(5)
5
> print("Hello world")
"Hello world"
{% endhighlight %}

## Example: Array-Like Things

Let's come back to the example of JavaScript's various array-like things. What if we simply created a protocol and allow all of them to speak it? To keep this example simple - the goal is to implement the generic utility functions: `map`, `filter`, and `reduce`, and allow them to be usable for arrays, the arguments object, as well as Backbone collections.

### The Challenge

If you would rather try it on your own, please stop reading and go do that before coming back.

### The Solution

To solve this problem - at the bare minimun, all you need is a protocol for iterating the collection. So I made:

{% highlight js %}
const Iterable = protocol({
  // return the n-th item in the array
  each: function(arr, fn) {}
});
{% endhighlight %}

With this protocol, I can write generic implementations of 'map', 'filter', and 'reduce':

{% highlight js %}
function map(arr, fn) {
  let values = [];
  Iterable.each(arr, function(item) {
    values.push(fn(item));
  });
  return values;
}

function reduce(arr, fn, initValue) {
  let value = initValue;
  Iterable.each(arr, function(item) {
    value = fn(value, item);
  });
  return value;
}

function filter(arr, fn) {
  let values = [];
  Iterable.each(arr, function(item) {
    if (fn(item)) {
      values.push(item);
    }
  });
  return values;
}
{% endhighlight %}

The next step is to just make arrays, the arguments object, and Backbone collections implement the `Iterator` protocol. Since the arguments object's type is plain `Object`, I am having to tie the implement to the top-level `Object` type.

{% highlight js %}
function _each(arr, fn) {
  for (let i = 0; i < arr.length; i++) {
    fn(arr[i]);
  }
}

Iterable.implementation(Array, {
  each: _each
});

// for the arguments object
Iterable.implementation(Object, {
  each: _each
});

Iterable.implementation(Backbone.Collection, {
  each: function(coll, fn) {
    coll.each(fn);
  }
});
{% endhighlight %}

That's it! Now we have `map`, `filter`, and `reduce` for each of these types.

{% highlight js %}
> map([1, 2, 3], function(n) { return n * 2 })
[ 2, 4, 6 ]

> function fun() {
  return filter(arguments, function(n) { return n % 2 === 0 });
}
> fun(1, 2, 3, 4)
[ 2, 4 ]

> let coll = new Backbone.Collection()
> coll.add({number: 1});
> coll.add({number: 2});
> coll.add({number: 3});
> coll.add({number: 4});
> reduce(coll, function(sum, m) { return sum + m.get('number') }, 0)
10
{% endhighlight %}

That's awesome! But! There's actually a problem with this scheme: the result of map and filter always return an instance of array, regardless of what the original type of the array-like object was. I allowed this in order to keep this code example short. How would you go about making the map and filter methods return the same type as the original? This would be a interesting challenge for you - the reader.

## What Makes Something Something?

Having gone through the exercises of using *protocols* as a means of implementing polymorphism, the question I need to address is: how is it better than what we had? Is it better at all? But first, we need to take a detour.

Various analogies have been used to explain object oriented programming. In particular, the concept of using inheritence to describe the "is-a" relationship - e.g. a cat is-an animal - has been ingrained in us. Should we model objects in our problem domains using an ontology - the same way that botanists classify plants? The problem is that ontology is simplistic and rigid. A cat is an animal, but a cat can also be a pet, and it can also be a playmate, and to a kitten, a cat is mother. Inheritence comes up short in modeling these scenarios.

The way that humans actually learn an "is-a" relationship is quite different, and is based on examples. To teach our children what a chair is, we give them examples of chairs. First, we show them a wooden stool, and they conclude: a chair is something that has four wooden legs. Then we show them a stainless steel stool, they'll update their definition to: something that has four legs. Then we show them a table with four legs, and they update their definition to: *something with four legs and is for sitting*. Then, we show them the exercise ball which you sit on for work. With enough examples, they ultimately come to the most generic definition of a chair.

What makes something something is not always based on their origin, but more often based on their characteristics and their roles, and these depend on the definition of a the word. *"is-a" is definition-based.* With this formulation, even a cat can be a friend.

There are times when you don't realize that something is something until you see it in a different light.

<div class="image">
  <img title="Beauty Or Old Lady" alt="Beauty Or Old Lady" src="/images/beauty-or-old-lady.jpg">
</div>


You may not have known the exercise ball was a chair, until you meet someone who uses it religiously as their office chair. In mathematics, if you can prove that a new problem is equivalent to an old problem by mapping each element of the new problem to each element of the old problem and seeing that all the properties of the old problem also hold in the new problem. Once you do that, any solution to the old problem can also be readily applied to the new problem. Such is the case for the [traveling salesman problem](https://en.wikipedia.org/wiki/Travelling_salesman_problem) and the [hamiltonian cycle problem](https://en.wikipedia.org/wiki/Hamiltonian_path_problem).

## How Is This Different?

Now, let's come back and consider how protocols is different from classical polymorphism. Mainly, there are two key differences:

1. The ability to retroactively make a class implement a protocol after that class has already been defined.
2. Implementing a protocol does not modify the definition of the class itself.

The first is actually doable in JavaScript today: you can certainly modify the prototype object of any "class" in JavaScript. We've all - at one time or another - added extra convinience methods to `Array.prototype`, `Object.prototype`, `Function.prototype`, and more. Only, this is now considered bad practice, because we've been burned before. When the API of an object is modified, we run the risk breaking code which depend on the original API. This is why the second difference is important: *implementing a protocol does not in anyway change the behavior of the class itself.* This guaranteed isolation is what allows protocols to scale, and opens up the possibilities for reusing existing algorithms in new problem domains.

## Summary

I have demonstrated an alternative way to formulate polymorphism than the traditional OO approach - interfaces and duck typing - which relies purely on the shape of objects. This approach is being used in several modern programming languages including Haskell, Clojure and Rust. It can be used in JavaScript to solve some of the thorny issues we have with the language today - I make implemented a proof of concept module [protomorphism](https://github.com/airportyh/protomorphism). Whether this will become the standard going forward is yet to be seen, but if nothing else, I hope that this article provides food for thought.
</content>
        </entry>,<entry>
            <title>Permalink As A Service</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2015/05/28/permalink-as-a-service">
            <updated>2015-05-28T04:00:00.000Z</updated>
            <id>http://tobyho.com/2015/05/28/permalink-as-a-service</li>
            <content type="text">

Bret Victor's recent post [The Web Of Alexandria](http://worrydream.com/TheWebOfAlexandria/) laments the high rate of links going dead on the internet. It compares the lossing of collective knowledge through dead links to the burning of Library of Alexandria. This got me thinking: *how would we fix this?* My mind naturally went to [The Internet Archive](archive.org) and its [WayBack Machine](https://archive.org/web/).

The WayBack Machine has already been archiving historical versions of web pages for almost 20 years. So, perhaps what is needed is simply a little bit of glue to make it convinient to add a URL to the archive and allow authors to link to a "permalink" as opposed to the live link. That way, even if the live page dies, the article will still link to the archived page which has the original content. Ideally, this will happen transparently to the user.

## Idea: Permalink As A Service

The name that came naturally for this service is "Permalink", eventhough this term is already in use, it's too apt for me to think of a better one. So, until there's a better name, I will just call this the "permalink service". So, how this service works is simple:

1. An author wants to link to an external web page from her article as a resource/referenece. Instead of linking to the URL itself, she would: 
2. Go to the permalink service's front page, enter the URL she wants to create a permalink for, and click "Create Permalink".
3. Once the permalink is created, the author would get the URL of the permalink to use in her article.

That's it! In step 2, the permalink service would ask the Way Back Machine to archive a snapshot of the submitted URL. When someone clicks on the permalink, the service would check the availability of the resource. If the resource is available, it would redirect to the live service, otherwise, it would redirect to the Internet Archive's archived version of the resource. Of course, there are circumstances when this wouldn't work. For example:

1. The content of the requested URL could be hidden behind a login.
2. The site may have a robot.txt that prohibits scrappers like search engines or the Internet Archive from retrieving content.

The hope is that this scheme would work at least often enough for it to be worth maintaining. But perhaps this is something we'd have to see to believe. 

## The Prototype

I made a prototype that implements this service, and the code is on [Github under the MIT license](https://github.com/airportyh/permalink). The implementation is extremely simple. It runs on io.js and the Koa framework and the code itself is 122 LOC at the time of this writing. The most interesting bit of code is probably the part that makes a request to archive.org to request that a URL be archived:

{% highlight js %}
var request = require('request-promise');
var cheerio = require('cheerio');

module.exports = function(url) {
  return request(`https://web.archive.org/save/${url}`)
    .then(function() {
      return true
    })
    .error(function(err) {
      var $ = cheerio.load(err.message);
      err = new Error;
      err.message = $('#error').text().replace(/\s+/g, ' ').trim();
      err.learnMore = $('.wm-nav-link-div').html();
      throw err;
    });
};
{% endhighlight %}

To request a page be archived be the Way Back Machine, all that is required is a GET request to `https://web.archive.org/save/${url}` where `url` is the URL you want to archive. In the error handling, I do a little bit of HTML scrapping on the error page to get a meaningful error message in the case that the page could not be archived.

I have stood up an instance of this server running currently at <http://permalink.tobyho.com>. Please feel free to poke at it. 

## Ideas and Questions

As you must have gathered by the fact that the app has no styling on it of any kind, I didn't put too much effort into the implementation. This was a one day hack job and intentionally so. However, I can already think of additional potentially useful features. One would be a bookmarklet or browser extensions to make it a snap to create a permalink. Another is to actually store all the permalinks that were created through the service so that they can be exported in bulk.

One issue that I haven't figured out from a usability perspective is whether the permalink should always redirect to the live site, the latest archived version, or the archived version at the time that the author created the link. It's possible that different authors may want different things here, and that it would be made configurable. But even if that were the case, deciding what should be the sensible default is something that would benefit from more thoughtfulness.

Another explored idea in [Bret's post](http://worrydream.com/TheWebOfAlexandria/) is that of data replication - an idea that seems very underutilized in the current internet. Rather than asking the Internet Archive to take on all of the burden of archiving content and becoming a single point of failure, perhaps a better architecture would be to allow any author to easily stand up a server for archiving all the links he or she personally wants to share. And, as a second step, have some sort of confederation that will replicate data across multiple nodes on the network. Some prior art here is [Wallabag](https://www.wallabag.org/) - a self-hosted read-later bookmarking server, and the [Smallest Confederated Wiki](https://github.com/WardCunningham/Smallest-Federated-Wiki). I, for one, am all for more self-hosting in this age of SAAS.

## Feedback Please

I have no idea if anyone will actually find this useful or interesting, but I *would* appreciate your thoughts - I am talking to you, dear reader. Thanks for reading.



</content>
        </entry>,<entry>
            <title>Null Object For Lists</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2015/05/20/null-object-for-lists">
            <updated>2015-05-20T04:00:00.000Z</updated>
            <id>http://tobyho.com/2015/05/20/null-object-for-lists</li>
            <content type="text">
At RailsConf this year, I saw ["Nothing is Something" by Sandi Metz](https://www.youtube.com/watch?v=29MAL8pJImQ). In it, she explained the [Null Object Pattern](http://en.wikipedia.org/wiki/Null_Object_pattern). The example she used was:

A program looks through the database for a number of animals by their ID, and then prints the name of each animal. In the case that the animal for a particular ID is missing, it had to print "missing animal" instead.

The naive solution was:

{% highlight ruby %}
animals = ids.map { |id| Animal.find(id) }
animals.each do |animal|
  if animal.nil?
    puts "missing animal"
  else
    puts animal.name
  end
end
{% endhighlight %}

The prescription of the *Null Object Pattern* calls for substituting a "Null Animal" class, which Sandi calls `MissingAnimal`:

{% highlight ruby %}
class MissingAnimal
  def name
    "missing animal"
  end
end
{% endhighlight %}

Then, a wrapper class `GuaranteedAnimal` was created which will always return an animal, whether it be a real animal or a "missing" animal:

{% highlight ruby %}
class GuaranteedAnimal
  self.find(id)
    Animal.find(id) || MissingAnimal.new
  end
end
{% endhighlight %}

This allows the original code to be written as:

{% highlight ruby %}
animals = ids.map { |id| GuaranteedAnimal.find(id) }
animals.each {|animal| puts animal.name }
{% endhighlight %}

Notice that we've removed the need for any if statements. In fact, Sandi made a real big deal about not wanting to use if statements. If you watch the beginning of her talk, she goes into how to write if's without if statements, but only via message passing to the true and false classes - a style that Smalltalk uses.

## Null Object for Lists

I want to take this even further. Specifically, I would like to apply this principle to the following scenario:

You are writing a search page, and you display the list of results on the page as some `<li>`'s inside an `<ul>`. But what happens when no results are returned? To provide good user feedback, you want to display a message saying something like "No results were found."

The obvious way to implement this, usually in some sort of HTML templating language, is to use the equivalent of an if statement. In ERB, this would look like:

{% highlight erb %}
<h1>Search Results</h1>
<% if results.size == 0 %>
<p>No results were found.</p>
<% else %>
<ul>
  <% results.each do |result| %>
  <li><a href="<%= result.url %>"><%= result.title %></li>
  <% end %>
</ul>
<% end %>
{% endhighlight %}

Pretty standard, right? But, I want to do this without using if statements, can I use the null object pattern here?

It'll take a little thinking outside the box. In order to substitute a method invocation in place of an if statement, we'd have to make it so that in one case, the method is resolved in one class, while in the other case, the message is resolved in a different class. We can do this if the empty list has a different type than a non-empty list. So, we need:

{% highlight ruby %}
class EmptyList
...
end

class NonEmptyList
...
end
{% endhighlight %}

This has implications. It means that if an item were added to an empty list, then its type would have to change to an non-empty list. Can you change the type of an object in runtime? Maybe Ruby can, because Ruby can do pretty crazy things. But, I am not going to go there. What I will do is use an immutable list - a la Clojure, where in order to make a modification to the list, you must create a new list, because the old one ain't ever gonna change. The new one though, could be of a different type and you'd never know it - MUAHAHAHA! In other words:

{% highlight ruby %}
> list1 = EmptyList.new
<EmptyList>
> list2 = list.append(bob)
<NonEmptyList>[bob]  # list 2 gotten by appending bob to list 1
> list1
<EmptyList>          # original list stays empty
{% endhighlight %}

I am going to implement a [linked list](http://en.wikipedia.org/wiki/Linked_list) using this idea. A linked list implementation needs the operations `car`, `cdr`, and `cons` - in LISP speak, but I am going to use these less cryptic names:

* `first` - to get the first item of the list
* `rest` - to get a new list containing all but the first item of the list
* `append(item)` - to get a new list containing `item` plus the items that are in the original list

This is how it's going to work:

{% highlight ruby %}
class EmptyList
  def first
    nil
  end

  def rest
    self
  end

  def append(item)
    # if you append an item to an empty list, you
    # get an non-empty list, whose first item is the
    # item, and its "rest of the list" is an empty list
    NonEmptyList.new(item, self)
  end
end

class NonEmptyList
  def initialize(item, rest)
    @item = item
    @rest = rest
  end

  def first
    @item
  end

  def rest
    @rest
  end

  def append(item)
    NonEmptyList.new(item, self)
  end
end
{% endhighlight %}

To traverse a list, one would use recursion to iterate down the list through the `rest` method. For convinience, I will add an `each` method that works like `Array#each`. Here's `NonEmptyList`'s implementation of `each`:

{% highlight ruby %}
class NonEmptyList
  ...
  def each(&block)
    block.call(first) # call the block for the first item
    rest.each(&block) # defer to the rest of the list
  end
end
{% endhighlight %}

For `EmptyList#each`, it should simply do nothing:

{% highlight ruby %}
class EmptyList
  ...
  def each
  end
end
{% endhighlight %}

Now, that we have that, we can do:

{% highlight ruby %}
list = EmptyList.new.append(1).append(2)
list.each do |item|
  puts item
end
{% endhighlight %}

Sweet! Now that a basic list implementation is done, we can apply the null object pattern and vary the display of the list based on whether the list is empty or not:

{% highlight ruby %}
class EmptyList
  ...
  def render
    "<p>No results were found.</p>"
  end
end

class NonEmptyList
  ...
  def render
    items = []  # cheating here: convert to 
                # array to use its join method
    each do |item|
      items.push(
        "  <li>\n" + 
        %Q(    <a href="#{item.url}">#{item.title}</a>\n) + 
        "  </li>")
    end
    %Q(<ul>\n#{items.join("\n")}\n</ul>)
  end
end
{% endhighlight %}

Now let's exercise these render methods by creating some search results:

{% highlight ruby %}
Result = Struct.new(:title, :url)
results = EmptyList.new
  .append(Result.new("Null Object Pattern", "http://en.wikipedia.org/wiki/Null_Object_pattern"))
  .append(Result.new("Introduce Null Object", "http://refactoring.com/catalog/introduceNullObject.html"))
  .append(Result.new("Q & A: is nothing something?", "https://van.physics.illinois.edu/qa/listing.php?id=1235"))
{% endhighlight %}

Print them out, and...

{% highlight ruby %}
> puts results.render
<ul>
  <li>
    <a href="https://van.physics.illinois.edu/qa/listing.php?id=1235">Q & A: is nothing something?</a>
  </li>
  <li>
    <a href="http://refactoring.com/catalog/introduceNullObject.html">Introduce Null Object</a>
  </li>
  <li>
    <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">Null Object Pattern</a>
  </li>
</ul>
{% endhighlight %}

And now to render an empty list...

{% highlight ruby %}
> puts EmptyList.new.render
<p>No results were found.</p>
{% endhighlight %}

Sweet! We did it, and we did it without using a single if statement. You can find the [full source code here](https://gist.github.com/airportyh/47484cb736c285fe76f5).

## But...

There is something very troubling about this solution though. What if we wanted to use this linked list implementation to render anything other than search results? We are toast! A broader problem is that we now have presentation code inside of what is supposed to be a general data utility.

But in fact, this problem exists in Sandi's animal example as well. "missing animal" is not the name of any animal. The reason it was chosen as the replacement text is - I would assume - that the programmer knows it will be rendered onto some page where substituting that text would make sense for the user. Therefore, the animal example also has presentation logic inside its model layer.

How can we solve this? Funny you should ask that! That is the topic of the next post. See you then.</content>
        </entry>,<entry>
            <title>NodeSchool Atlanta 1</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2015/01/29/nodeschool-atlanta-1">
            <updated>2015-01-29T05:00:00.000Z</updated>
            <id>http://tobyho.com/2015/01/29/nodeschool-atlanta-1</li>
            <content type="text">
This past Tuesday we had the first NodeSchool workshop - Atlanta chapter of 2015. During the workshop, I help people with programming questions almost non-stop for 2 hours. By the end I was exausted, but in a good way - like after playing a three-set tennis match. In this post I'll recount

1. how the event was put together
2. how it went, and
3. what to improve for next time

## Time Of Day

I chose to do this in the middle of the day, from 2pm-4pm. I did this mostly due to personal reasons - I have children and associated responsibilities, therefore I am keeping night outings to a minimum. I realized that this would make it difficult for some people to come - I do plan to do something at night in the future, just not on a regular basis. This is a test to see if I can get a good turn out during daytime.

## Class Size

I have done workshops before, and 20 is an upper limit if you want to give students good one-on-one support when they are stuck. I didn't have any mentors helping me. I could have tried harder to ask for help, but I didn't because partly of dreading the coordination I'd have to do, and partly because I have devised a scheme which allows/encourages students to help each other, which - if it works, *and that's a big if* - would obviate the need for additional help.

So, I aimed for 20 students. I got a speakeasy room at Atlanta Tech Village with exactly that capacity. Then, I created an event on meetup.com (our group is [Atlanta JavaScript](http://atlantajavascript.com/)), where I capped the RSVPs to 38. Why 38? From experience, with free events done via meetup.com, in Atlanta, the actual turn out rate has pretty reliably been 50% of the RSVP count. Therefore, if I am aiming for 20 students, the reasonably thing to do is to cap it at 40. Then I subtracted 2 as a safety cushion - because after all, I have a venue with a capacity of 20. The RSVP's maxed out in 2 days! So yes, people *will* come during the day.

## The Setup Videos

Having been to many NodeSchool workshops at NodeConf and I know that setting up is often a huge drain of time. If every student had install the required software beforehand, how much better would the workshops go?

So I made screencasts instructing the students to install Node, the workshopper of their choice, and a text editor. There is

* [a video for Mac users](https://www.youtube.com/watch?v=4BShP9q0fz8)
* and [a video for Windows users](https://www.youtube.com/watch?v=3rQB5fr_5D4)

I emailed links to these to the members who RSVP'ed to the event 4 days prior to it.

## Methodology

I had a couple of tricks up my sleeve:

* Give each student a post-it note. Ask them to stick it on the back of their laptop when they need help - this one I stole from [@radishmouse](https://twitter.com/radishmouse).
* Give each of them a set of [post-it flags](http://www.staples.com/Post-it-1-2-inch-Assorted-Flags-100-Flags-Pack/product_512251?cid=PS:GooglePLAs:512251&ci_src=17588969&ci_sku=512251&KPID=512251&kpid=512251&gclid=CjwKEAiArqKmBRCOj_qfmuqinnYSJAAkAYwGt4J92OLzZCs0jDJguyXD2POxYpFrlCCqpHkNdYykiRoCIijw_wcB) - each time they complete a lesson, they will shout "yes!", throw their hands in the air, and then add a flag to the back of their laptop.

These strategies were devised to help me in case I got flooded with requests for help. If there were more than a few posted notes put up, I would enlist the help of a student who is ahead of the others. If the someone in need has a high flag count, I can prioritise him/her lower because they're already doing good in terms of confidence and remaining lessons vs remaining time.

## The Event Page

Check out the [event page](http://www.meetup.com/AtlantaJavaScript/events/219831150/). I allow the students a choice between the javascripting workshop and the learnyounode workshop.

## Day Of

I got there half an hour early to get set up. A few students showed up early too, enough time to chat a bit about learning to code and code bootcamps. I am happy to report that an early survey showed that 5 out of 6 students came prepared with the software already installed, Yes!

I wrote up the WIFI settings and instructions on my laptop, which was connected to two large displays. In retrospect I should have put them up on the whiteboard because when I left my laptop it quickly went to sleep.

Some students did follow my instructions and shout "yes!" when they solved one of the lessons - that's a really natural thing to do so all I had to do was give them permission. This lifted the mood in the room. I could see the flags being put up one by one as they complete the lessons. Some of them did really well!

I jumped from student to student almost non-stop, but I was never really overloaded. The students were pretty good about helping each other out, and I didn't have to tell them to. Some of the more experienced ones took charge and lead the inexperienced ones next to them.

## Software Hiccups

Software installation wise, we did pretty well. However, we did have some issues nevertheless:

* One student had a PowerPC iBook and simply could not get Node to run - I asked her to pair with someone else.
* For one student, the verify step was silent - it didn't print out anything at all. I started the workshopper in a different newly created directory, and that solved the problem.
* For another student, the verify step would print out just a generic "something went wrong" message whenever his answer failed validation.

I didn't take time to debug these issues further because I felt helping the students with code was a better use of my time at the moment.

## Issues With Workshopper

Here are some issues we experienced with the workshoppers, specifically "javascripting" and "learnyounode".

* For Windows users, students were told to use `NUL > introduction.js`, this didn't always work and sometimes resulted in cryptic errors.
* Some lessons were worded in a confusing way to the students, and one student said that more context would help. I also heard the sentiment that "this is harder than it has to be", reflecting the feeling that the final solution is simpler than the written instructions made it seem. I think that for some, it sometimes felt like a game of figuring out what the verifier program wants you to do rather than learning about a particular programing concept. Notably, from what I can remember - and there may be more - these lessons were problematic:
  * ROUNDING NUMBERS
  * NUMBER TO STRING
* For-loops were problematic for several students. I think while loops would be a better choice as an introduction to loops.
* When a validation fails for a student, the output message isn't always helpful. It sometimes displays the actual vs expected results, but it doesn't display what input values the test fed into the code.
* I recommended to the students to always run the script by itself using just the `node` command before trying to verify it. I think this makes it more clear what they are actually doing, gets them to experience the real process of programming in Node, and also makes debugging easier. I think the lessons should recommend this as well.

## High Points

At the end of the workshop, some students exclaimed more than once how amazing this workshop was to them. They had tried to learn on their own using various materials with incremental success at best, but this workshop was clearly a turning point for them. I attribute this to the act of doing over reading. Also, having mentors to help you is very important as well. Thanks to Substack, Max Ogden, Mikeal Rogers, Rod Vagg, and other contributors who made NodeSchool a thing!

## Improvements

For the next workshop, here are the things I would like to do better:

* Include a quick workthrough on lesson 0 in the screencast. This will show them what they should expect when they verify a problem and what they should expect from end to end.
* Put in some time to improve the workshoppers by addressing the issues I mentioned above.</content>
        </entry>,<entry>
            <title>Headless Browser Testing With Xvfb</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2015/01/09/headless-browser-testing-xvfb">
            <updated>2015-01-09T05:00:00.000Z</updated>
            <id>http://tobyho.com/2015/01/09/headless-browser-testing-xvfb</li>
            <content type="text">
These days, when the phrase "headless browser" is mentioned, you immediately think of [PhantomJS](http://phantomjs.org), but - there are alternatives. In this article, I am going to introduce a nice alternative you can use on Linux which allows you to run real browsers - Firefox and Chrome, headless - using [Xvfb](http://www.x.org/releases/X11R7.6/doc/man/man1/Xvfb.1.xhtml). 

## What's Wrong With PhantomJS?

PhantomJS is great tool and is widely used by companies and developers around the world. It has particularly been widely adopted for running JavaScript test suites. However, using PhantomJS isn't without drawbacks. Although it is built on top on WebKit - the same rendering engine both Safari and Chrome use, it still behaves in subtly different ways from those browsers, which can cause *false positives* (tests failing when there is not a real defect) and in some cases performance degradation of your test suite. Since PhantomJS isn't a real browser in the sense that no end-user actually use it, fixing these issues specifically for PhantomJS becomes an upkeep cost of the test suite, rather than something that directly improves the product. Getting developers to write tests consistently is hard enough, but if maintaining the tests becomes annoying - which false positives definitely are - it can become demoralizing.

## Run Real Browsers Headless

Because of the above reasons, at one point in my career I decided to use real browsers only to run JavaScript test suites. This has meant opening up a separate browser window to run the tests during development which I would simply hide in the background. I am okay with this. However, in many cases the continuous integration servers we use are Linux servers, and do not have displays. This is where Xvfb comes in.

[Xvfb](http://www.x.org/releases/X11R7.6/doc/man/man1/Xvfb.1.xhtml) is a virtual display framebuffer for *X* - the display system used by Linux. It provides a fake display buffer for graphical programs to write to, thus allowing any program to run headlessly.

### Installing Xvbf

If you are running Debian or Ubuntu and are using apt-get, installing is simply as:

    apt-get install xvfb

If you are on CentOS and using yum, it's

    yum install xorg-X11-server-Xvfb

### Installing the Browsers

On Ubuntu, I found installing Chrome and Firefox painless. 

* For Chrome simply go to the [Chrome download page](https://www.google.com/chrome/browser/desktop/), download the .deb file, then do `dpkg -i <the path to the .deb file>` to install.
* For Firefox, it's just `apt-get install firefox`.

On CentOS, I have had more trouble.

* For starters, Chrome is not supported on CentOS and I haven't even found a simply way to build Chrominum and I gave up.
* Installing firefox also had a little hiccup: I ran `yum install firefox`, but then running `firefox` resulted in an error, which I solved by also installing `gdk-pixbuf2` via `yum install gdk-pixbuf2`.

If you are on other Linux distros I haven't mentoned, checkout the [Chrome download page](https://www.google.com/chrome/browser/desktop/) and the [Firefox on Linux page](https://support.mozilla.org/en-US/kb/install-firefox-linux).

### Xvfb Usage

The usage of Xvfb is:

    xvfb-run <some command>

That's all you need to know! For example, you can run Firefox within Xvfb:

    xvfb-run firefox http://google.com

This should just start a firefox process in the background. You may see a cryptic warning in the terminal, but otherwise it's not very exciting because you don't actually see anything.

If you use [Testem](https://github.com/airportyh/testem) to run tests, you can do:

    xvfb-run testem -l firefox

to run your tests in Firefox or

    xvfb-run testem -l chrome

to run them in Chrome - headless!

Of course, this is not limited to Testem, you can use `xvfb-run` with Karma, Grunt, Gulp or any other test runner that spawns a real browser and it will *just work*.

## Implications

If you use Linux for development, this is an attractive solution. It allows you to run your tests without having an unwanted window and it's easy to setup and use. However, even if you don't use Linux for development, you may still use Linux for continuous integration, in which case, maybe you are currently using PhantomJS to run tests. If that's working well for you, great. But if PhantomJS is starting to create unwanted overhead for you, consider switching to this setup.</content>
        </entry>,<entry>
            <title>Attribute only valid on v:image</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2014/02/26/attribute-only-valid-on-v-image">
            <updated>2014-02-26T05:00:00.000Z</updated>
            <id>http://tobyho.com/2014/02/26/attribute-only-valid-on-v-image</li>
            <content type="text">
If you encountered the error "Attribute only valid on v:image" in IE, and would like to find the root cause, you are in luck!

First, here are some characteristics of the bug:

* It happens only in quirks mode - which means IE7 and below, but could also happen in newer IEs if the web page explicitly turns on EmulateIE7 mode by using the meta tag `<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />`
* It is associated with VML, which is Microsoft's old vector graphics markup engine, and which is no longer supported starting IE 10. This makes sense because VML only works in quirks mode.

## The Bug

Let's see an example page

{% highlight html %}
<html xmlns:v>
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
  <style>v\: * { behavior:url(#default#VML); display:inline-block }</style>
</head>
<body>
  <v:image src="x.gif" id="image" style="top:1px; left:1px; width:200px; height:200px"/>
  <v:rect id="rect" style="width:100pt;height:80pt;" strokecolor="red" strokeweight="2pt"/>
</body>
</html>
{% endhighlight %}

To test, render this page in IE7 or below or an emulated IE7. This renders an image `<image>` as well as a rectangle `<rect>`. The bug is triggered when access to the `src` property of the element `rect` is attempted:

{% highlight js %}
> rect.src // throws "Attribute only valid on v:image"
{% endhighlight %}

Okay, this is not the bug, it actually even makes sense that a rect shouldn't have a `src` property. The bug is that once this error occurs for any VML element, any property access for any VML element is poisoned with this same error message:

{% highlight js %}
> rect.id // throws "Attribute only valid on v:image"
> rect.nodeType // throws "Attribute only valid on v:image"
> rect.nodeName // throws "Attribute only valid on v:image"
> image.id // throws "Attribute only valid on v:image"
> image.nodeName // throws "Attribute only valid on v:image"
{% endhighlight %}

Amusingly, however, sanity can be restored if you now access a VML image element's `src` property

{% highlight js %}
> image.src // returns 'x.gif'
> rect.id // returns 'rect' again, as it should
{% endhighlight %}

## One More Thing

Actually, this bug is even more disastrous - it persists across page refreshes. If the VML system is in the poisoned state, refreshing the page, or even navigating to another page won't help. The poisoned state will only go away if one of the following happens

1. The `src` property of a VML image element as accessed, as previously described.
2. Restarted the browser.

The implication of this is that, your site - if implemented using VML - could exhibit this error even if it was another site that put the engine into the poisoned state.
</content>
        </entry>,<entry>
            <title>Small.JS the Blog</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2014/01/27/small-js-the-blog">
            <updated>2014-01-27T05:00:00.000Z</updated>
            <id>http://tobyho.com/2014/01/27/small-js-the-blog</li>
            <content type="text">
Since I've written the article - [Small.JS](http://tobyho.com/2013/10/20/smalljs/) - I have had conversations with various smart people about this topic, and I have realized that the way forward in order to foster more attention, discussion, and community around small JavaScript libraries is to get the word out about them. I have decided to take a first step: [Small.JS is now a blog](http://smalljs.org/).

This new blog will consist of articles mostly in tutorial format, and will focus on

1. Covering useful small modules.
2. Covering the major package managers.
3. Motivating the benefits of small modules.

The first article on the new blog is about [Component](http://smalljs.org/package-managers/component-part-1/). Enjoy!

I plan to focus more of my time and effort on the new blog, which means that posts on *this* blog will become sporadic - not that it hasn't always been that way :)</content>
        </entry>,<entry>
            <title>Static Analysis For CSS</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2014/01/16/static-analysis-for-css">
            <updated>2014-01-16T05:00:00.000Z</updated>
            <id>http://tobyho.com/2014/01/16/static-analysis-for-css</li>
            <content type="text">
I have had fun writing about [static](http://tobyho.com/2013/12/02/fun-with-esprima/) [analysis](http://tobyho.com/2013/12/20/falafel-source-rewriting-magicial-assert/) for [Javascript](http://tobyho.com/2014/01/07/js-trailing-comma-remover/) recently. This time, let's do something that's the same kinda thing, and yet different - static analysis for CSS.

## The CSS Module

The library we'll use is simply called [css](https://npmjs.org/package/css) and is found on npm. So, just do `npm install css` to install it. It contains both a parser and an emitter.

## Parsing CSS

Say you have a `sample.css`

{% highlight css %}
.btn:hover,
.btn:focus {
  color: #333333;
  text-decoration: none;
}
{% endhighlight %}

To parse it, write this

{% highlight js %}
var css = require('css');
var fs = require('fs');
var code = fs.readFileSync('sample.css') + '';
var ast = css.parse(code);
console.log(JSON.stringify(ast, null, '  '));
{% endhighlight %}

Run it, and you'd see its AST printed to the console:

    {
      "type": "stylesheet",
      "stylesheet": {
        "rules": [
          {
            "type": "rule",
            "selectors": [
              ".btn:hover",
              ".btn:focus"
            ],
            "declarations": [
              {
                "type": "declaration",
                "property": "color",
                "value": "#333333"
              },
              {
                "type": "declaration",
                "property": "text-decoration",
                "value": "none"
              }
            ]
          }
        ]
      }
    }

## Modifying the AST

Let's say that, for whatever reason, we want all the rules in the CSS file to only take effect for elements which are descendants of certain elements - specified by the class `root`. We can do that by prefixing every selector of every rule with: `.root `.

{% highlight js %}
ast.stylesheet.rules.forEach(function(rule){
  for (var i = 0; i < rule.selectors.length; i++){
    rule.selectors[i] = '.root ' + rule.selectors[i];
  }
});
{% endhighlight %}

## Emitting the Modified CSS

Now that we have modified the AST, we can use the `stringify()` method to regenerate the CSS from it

{% highlight js %}
console.log(css.stringify(ast))
{% endhighlight %}

And the output is

    .root .btn:hover,
    .root .btn:focus {
      color: #333333;
      text-decoration: none;
    }

Yah! Easy, right?

## Other Possibilities

What are other interesting things you can do? You are limited only by your imagination. If you want to automatically rename classes, you can do that. If you want to automatically sort or group rules by their selector, you can do that. If you want to automatially detect and remove unused rules (combined with html parsing), you can do that! <a href="http://www.youtube.com/watch?v=98nNpzE6gIs" target="_blank">You can do that!</a>

## Homework

It turns out that our code didn't cover all the cases. You homework is to run it on the CSS file that's bundle with [Bootstrap](http://getbootstrap.com/). Figure out what's broken, and fix it. Good luck!</content>
        </entry>,<entry>
            <title>JS Trailing Comma Remover</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2014/01/07/js-trailing-comma-remover">
            <updated>2014-01-07T05:00:00.000Z</updated>
            <id>http://tobyho.com/2014/01/07/js-trailing-comma-remover</li>
            <content type="text">
If you've ever written a JS-based webapp in a modern browser and *then* went back to test it on older IE versions, then you've undoubtedly experienced the pain of hitting one IE quirk after another. One of those many quirks you might have encountered is the weirdness in how IE 7 and below - a.k.a. quirks mode - handles trailing commas in array literals and object literals.

Trailing commas are popular with some programmers in other languages, because if you had a long array or object literal across multiple lines, for example

{% highlight js %}
var names = [
  'bobby',
  'catherine',
  'danny',
  'eric',
];
{% endhighlight %}

Adding a new entry doesn't require touching the last existing entry. However, in Javascript, trailing commas are mostly avoided because of the quirks.

## Trailing Comma in Array Literals

Given an array literal with a trailing comma

{% highlight js %}
var arr = [1, 2, 3, ];
{% endhighlight %}

In standards compliant browsers, this is an array with 3 elements. But in quirks mode, this is an array with 4 elements.

## Trailing Comma in Object Literals

Given an object literal with a trailing comma

{% highlight js %}
var obj = {
  foo: 'foo',
  bar: 'bar',
};
{% endhighlight %}

Standards compliant browsers are perfectly happy with this. While in quirks mode, IE blows up with a cryptic syntax error like `SCRIPT1028: Expected identifier, string or number`. What makes matters worse is that usually older IEs don't give an accurate line number for where the problem was, and so you would usually have to resort to the divid-and-conquer method, a.k.a the binary search method, a.k.a. comment out a half of your code repeatedly until you narrow it down to the place of the error.

## Solving It

If you have been [following](http://tobyho.com/2013/12/02/fun-with-esprima/) [along](http://tobyho.com/2013/12/20/falafel-source-rewriting-magicial-assert/), you might have guessed that we are going solve this using static analysis. While another Javascript parser might have thrown away that trailing comma because it contributes nothing to the semantic meaning of the program, Esprima, with the `raw` and `range` options, will allow you the ability to recreate the verbatim source of the original program. Falafel makes this easy by providing a `source()` method which returns the verbatim source for any given AST node.

Let's get falafeling!

## Fixing Arrays

First, we'll just detect array literal expressions

{% highlight js %}
var falafel = require('falafel');
var fs = require('fs');
var code = fs.readFileSync('sample.js') + '';

code = falafel(code, function(node){
  if (node.type === 'ArrayExpression'){
    processArrayExpression(node);
  }
});
{% endhighlight %}

What should `processArrayExpression()` do? As the first step, let's just print the expression and see that we can get the original source back.

{% highlight js %}
function processArrayExpression(node){
  console.log('Array expression:', node.source())
}
{% endhighlight %}

Make a `sample.js` containing

    var arr = [1, 2, 3,];
    var arr2 = ['a', 'b', 'c'];

Then run the falafel program and you'd get

    Array expression: [1, 2, 3,]
    Array expression: ['a', 'b', 'c']

So, as you can see, we can get the original source back. Now, we can detect the existence of the trailing comma via some regex hacking - ohhhh, look away now!

{% highlight js %}
function processArrayExpression(node){
  var src = node.source();
  if (src.match(/,\s*]$/)){
    console.log('Array has trailing comma:', src);
  }
}
{% endhighlight %}

Running the program now you should see that we've successfully filtered out the array expression without a trailing comma

    Array has trailing comma: [1, 2, 3,]

The next step is to fix it. Of course we'll use falafel's handy `update()` method. Regex to the rescue again! *Don't look!*

{% highlight js %}
node.update(src.replace(/,(\s*)]$/, '$1]'));
{% endhighlight %}

Finally, we'll print out the rewritten code to the console, and the full source is

{% highlight js %}
var falafel = require('falafel');
var fs = require('fs');
var code = fs.readFileSync('sample.js') + '';

code = falafel(code, function(node){
  if (node.type === 'ArrayExpression'){
    processArrayExpression(node);
  }
});

console.log(code);

function processArrayExpression(node){
  var src = node.source();
  if (src.match(/,\s*]$/)){
    node.update(src.replace(/,(\s*)]$/, '$1]'));
  }
}
{% endhighlight %}

Run this and we see the trailing comma *fixed*!

    var arr = [1, 2, 3];
    var arr2 = ['a', 'b', 'c'];

Wonderful.

## Homework - Fixing Objects

Your homework this time is to fix trailing commas for object literal as well. *Have fun, programmer!*</content>
        </entry>,<entry>
            <title>Falafel, Source Rewriting, and a Magicial Assert</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2013/12/20/falafel-source-rewriting-magicial-assert">
            <updated>2013-12-20T05:00:00.000Z</updated>
            <id>http://tobyho.com/2013/12/20/falafel-source-rewriting-magicial-assert</li>
            <content type="text">
A couple of weeks ago, I [wrote](http://tobyho.com/2013/12/02/fun-with-esprima/) about how to do some basic static analysis of Javascript source code using Esprima. This post is a follow up where I demonstrate how to write a program to transforms Javascript source code using an Esprima-based library - [falafel](https://github.com/substack/node-falafel).

## Hello, Falafel

Falafel is an AST traversal library like [estraverse](https://github.com/Constellation/estraverse). If you've read my [previous article](http://tobyho.com/2013/12/02/fun-with-esprima/), this is familiar territory. Instead of taking the AST as an argument, falafel takes the source code as a string.

{% highlight js %}
falafel('console.log("hello world");', function(node){
  console.log('Entered node', node.type);
});
{% endhighlight %}

In addition to traversal, Falafel also adds some interesting methods to the nodes being traversed:

* `update(newCode:string)` - replaces the source of the node with new code - a little like the DOM [replaceChild method](https://developer.mozilla.org/en-US/docs/Web/API/Node.replaceChild).
* `source():string` - returns the original source of the node.

Armed with these new weapons, let's write something. Let's say you want to see a timestamp with all your console.log statements. You could use a logging library, but you'd have to rewrite all your console.log statements. Or, you could write a program to automatically rewrite your source code!

So, for this problem, given the input

    console.log('hello');

we want the output - the rewritten program - to be

    console.log(new Date() + ':', 'hello');

First, we need to detect all <a href="http://esprima.org/demo/parse.html?code=console.log('hello')" target="_blank">console.log statements</a> in the program. We'll do that using this function

{% highlight js %}
function isConsoleLog(node){
  return node.type === 'CallExpression' &&
    node.callee.type === 'MemberExpression' &&
    node.callee.object.type === 'Identifier' &&
    node.callee.object.name === 'console' &&
    node.callee.property.type === 'Identifier' &&
    node.callee.property.name === 'log';
}
{% endhighlight %}

Then, it's just a matter of constructing the source we want and giving it to `update()`.

{% highlight js %}
code = falafel(code, function(node){
  if (isConsoleLog(node)){
    node.update('console.log(new Date() + ":", ' + 
      node.arguments.map(function(arg){
        return arg.source();
      }).join(', ') + ')');
  }
});
{% endhighlight %}

Notice that we use the `source()` method to get at each argument's original source code - unchanged.

[Full Source](https://github.com/airportyh/falafel_fun/blob/master/log_timestamp.js)

## Better Assertions

Now, that your feet are wet, let's get into something more involved - let's implement better [assertions](http://en.wikipedia.org/wiki/Assertion_\(software_development\)) by using source rewriting.

An assertion is a statement in the program containing a sole boolean expression  which is checked during its execution. If the expression is false at that point of program execution, the program will fail with an assertion error. Assertions are most commonly used in automated tests, but can also be used in production code. In fact, using assertions in your production code may have these benefits

1. Fail erroneous conditions early so that they have minimal negative impact on the state of the application.
2. Makes [post-mortem debugging](http://en.wikipedia.org/wiki/Debugging) easier by failing closer to the root cause.

Since Javascript does not have an assert statement, we resort to implementing an `assert()` function instead

{% highlight js %}
assert(n === 0);
{% endhighlight %}

which may be implemented as

{% highlight js %}
function assert(condition){
  if (!condition){
    throw new Error('Assertion failed.')
  }
}
{% endhighlight %}

If the assertion fails at this point, we'd get an error like this

    Error: Assertion failed.
    at assert (simple_assert.js:6:11)
    at Object.<anonymous> (simple_assert.js:2:1)
    ...

this output leaves something to be desired

1. Currently we have to track down the code that generated the assert statement using the line numbers in the stacktrace. It would be helpful to be able to see the source of the assert statement directly in the error message. [Insist](http://seanmonstar.com/post/69703845045/insist-better-assertions-for-nodejs) is a node modules that does this using some AST hackery.
2. It would be helpful to see the state of the program at the time the error occured, especially the variables and sub-expressions referenced in the assert statement. Various [assertion](http://nodejs.org/api/assert.html) [libraries](http://chaijs.com/) handle this by giving you access to comparison functions. For example, instead of `assert(n === 0)` you'd write `assert.equal(n, 0)`, which would yield an error message like:
        
        Assertion Error: Expected 1 to equal 0.

    but there are still downsides to this approach

    * although you see the the values on each side of the comparison, you don't see the names of the variables in the comparisons
    * you have to learn and depend on their API - which can be potentially large
    * you'll encounter things you want to check which are not in the API or are not comparisons at all, at which point you'd have to fallback to the simple assert form

## The Goal

If we add source code rewriting to the toolbox, new possibilities open up. Let's consider how we may want to rewrite an assert statement like

{% highlight js %}
assert(n === 0);
{% endhighlight %}

First, to implement just the assertion behavior, we can rewrite the above to

{% highlight js %}
if (!(n === 0)){
  throw new Error('Assertion failed.');
}
{% endhighlight %}

Next, we can embed the source of the assert statement into the error message - this satisfies requirement #1
 
{% highlight js %}
if (!(n === 0)){
  throw new Error('assert(n === 0) failed.');
}
{% endhighlight %}

For requirement #2, we want to display the state of the program, but which variables to display? At the minimium, we should display the values of sub-expressions in the assert statement itself. For our example, the sub-expression we care about is the variable n, so we'll display its value in a separate line within the error message.

{% highlight js %}
if (!(n === 0)){
  throw new Error(
    'assert(n === 0) failed.\n' + 
    '  n = ' + n);
}
{% endhighlight %}

Let's separate the above into 3 checkpoints:

1. Basic assertion.
2. Display assert statement source code in error message.
3. Display variables and sub-expressions in the assert statement.

Okay, now that we know where we are headed, let's get coding. If you don't want me to ruin the ending for you, *stop reading*, go implement it yourself and then come back. I'll wait.

## Checkpoint #1

First, to detect the <a href="http://esprima.org/demo/parse.html?code=assert(n%20%3D%3D%3D%200)" target="_blank">assert statement</a>, we'll have an `isAssert` function

{% highlight js %}
function isAssert(node){
  return node.type === 'CallExpression' &&
    node.callee.type === 'Identifier' &&
    node.callee.name === 'assert';
}
{% endhighlight %}

Rewriting it as an if statement then is as easy as this

{% highlight js %}
code = falafel(code, function(node){
  if (isAssert(node)){
    var predicate = node.arguments[0];
    node.update(
      'if (!(' + predicate.source() + ')){ ' +
      'throw new Error("Assertion failed.");' + 
      ' }');
  }
})
{% endhighlight %}

For this program as input

{% highlight js %}
var n = 1;
assert(n === 0);
{% endhighlight %}

we should get back the rewritten program as

{% highlight js %}
var n = 1
if (!(n === 0)){ throw new Error("Assertion failed."); };
{% endhighlight %}

And if we run it we'll get

    Error: Assertion failed.

[Full Source](https://github.com/airportyh/falafel_fun/blob/master/checkpoint1.js)

## Checkpoint #2

To embed the source from the assert statement into the error message isn't much more involved.

{% highlight js %}
code = falafel(code, function(node){
  if (isAssert(node)){
    var predicate = node.arguments[0];
    node.update(
      'if (!(' + predicate.source() + ')){ ' +
      'throw new Error("' + predicate.source() + ' failed.");' + 
      ' }');
  }
})
{% endhighlight %}

For the same example as checkpoint #1, we should now get back

{% highlight js %}
var n = 1
if (!(n === 0)){ throw new Error("n === 0 failed."); };
{% endhighlight %}

And the error now looks like

    Error: n === 0 failed.

[Full Source](https://github.com/airportyh/falafel_fun/blob/master/checkpoint2.js)

## Checkpoint #3

Displaying variables and sub-expressions in the assert statement's prediate will involve another AST traversal. Let's consider a few cases:

1. The predicate is a binary expression like <a href="http://esprima.org/demo/parse.html?code=n%20%3D%3D%3D%200" target="_blank">n === 0</a>. In this case, we want to show the sub-expressions on both sides, but not literals - because those are already apparent in the source.
2. The predicate is a function call like <a href="(http://esprima.org/demo/parse.html?code=isNaN(n))" target="_blank">isNaN(n)</a>. In this case we'll want to drill down into the argument(s) of the function and display its value.
3. The predicate is a method call like <a href="http://esprima.org/demo/parse.html?code=_.isArray(arr)" target="_blank">_.isArray(arr)</a>. As with case #2, we'll want to display the value of the argument(s).

After several attempts, I've come up with this code which balances cases covered and simplicity

{% highlight js %}
function subExpressions(predicate){
  var exprs = [];
  estraverse.traverse(predicate, {
    enter: function(node){
      if (
        predicate !== node &&   // exclude the original expression itself
        node.type !== 'Literal' // don't want string/number/etc literals
      ){
        exprs.push(node);
      }
      // Skip the nodes under MemberExpression
      // because it's property name as an identifier
      // will not be recognizable as a variable
      if (node.type === 'MemberExpression') this.skip();
    }
  });
  return exprs;
}
{% endhighlight %}

Then, it's just a matter of formatting the desired Javascript correctly.

{% highlight js %}
code = falafel(code, function(node){
  if (isAssert(node)){
    var predicate = node.arguments[0];
    var predicateSrc = predicate.source();
    var exprs = subExpressions(predicate);
    node.update(
      'if (!(' + predicateSrc + ')){ ' +
        'throw new Error("' + predicateSrc + ' failed."' + 
          ' + ' + 
          (exprs.map(function(expr){
            var src = expr.source();
            return '"\\n  ' + src + ' = " + ' + src;
          }).join(' + ') || '""') +
        ');' + 
      ' }');
  }
})
{% endhighlight %}

Okay, admittedly I've made a bit of a mess here. If you run this on the same example program, you'll now get

    Error: n === 0 failed.
      n = 1

Now we are getting somewhere! Here's another example

{% highlight js %}
var obj = {
  name: 'tom',
  getName: function(){
    return 'blah'
  }
}
assert(obj != null)
assert(obj.name === obj.getName())
{% endhighlight %}

If you convert this source and run it, you'll get this error:

    Error: obj.name === obj.getName() failed.
      obj.name = tom
      obj.getName() = blah
      obj.getName = function (){
        return 'blah'
      }

***So helpful!***

[Full Source](https://github.com/airportyh/falafel_fun/blob/master/checkpoint3.js)

## Homework

Not so fast! Did you think you could get away without any homework this time?

In postmortem debugging, any bit of information you can get your hands on may prove valuable for finding the root cause of the problem. So, it seems like a good idea to display the local variables when the assertion has failed. In fact, it may be valuable to display all the variables accessable at that point - in other words the entire variable scope chain. *Your mission, should you choose to accept it, is to make the code do exactly this.* Good luck!</content>
        </entry>,<entry>
            <title>Fun with Esprima and Static Analysis</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2013/12/02/fun-with-esprima">
            <updated>2013-12-02T05:00:00.000Z</updated>
            <id>http://tobyho.com/2013/12/02/fun-with-esprima</li>
            <content type="text">
Writing programs to do static analysis on Javascript is easier now than ever, thanks to [Esprima](http://esprima.org/) - the Javascript parser library. In this post, I'll demonstrate how to use Esprima to do something fairly simple - detect accidentally leaked global variables in a program.

Accidentally leaked global variables happen when a value is assigned to an identifier without declaring the identifier as a variable first. For example, this `g = 1a` accidentally makes `g` a global, but `var g = 1;` and `var g; g = 1;` do not.

To accomplish the task at hand we need to do two things

1. Find all assignment statements in the program
2. For each of those assignments, find out if the assign variable has already been defined within the scope

But before we do all that, let's start with the basics.

## The AST

Esprima's job is to turn a Javascript program into an AST - Abstract Syntax Tree. An AST is a tree representation of the source code that can be inspected programmatically. For example the AST for this program

{% highlight js %}
6 * 7
{% endhighlight %}

Would be something like

<div class="image">
<img src="/images/fun-with-esprima/ast-example.png" alt="AST Example">
</div>

The output you get from esprima is a bit more detailed, but is nothing more than a nested Javascript object
      
{% highlight js %}
{
    "type": "Program",
    "body": [
        {
            "type": "ExpressionStatement",
            "expression": {
                "type": "BinaryExpression",
                "operator": "*",
                "left": {
                    "type": "Literal",
                    "value": 6,
                    "raw": "6"
                },
                "right": {
                    "type": "Literal",
                    "value": 7,
                    "raw": "7"
                }
            }
        }
    ]
}
{% endhighlight %}

To get an even better idea, I recommend you go play with the <a href="http://esprima.org/demo/parse.html" target="blank">Esprima online parse</a> for a bit. When you type in a valid Javascript program on the left, and you'll immediately see its AST on the right.

## Traversing the AST

Back to the task at hand. If we want to find all the assignment statements, we'll need to be able to traverse the AST. AST traversing is slightly tricky because there isn't a unified interface for getting the children for a given node. For example, an `VariableDeclaration` has nested children nodes within `declarations` while an `IfStatement` has nested children within its `consequent` and its `alternate`. Moreover, some properties contain objects, some arrays, others contain strings.

Thanks to the power of Node modules, we'll just use the [Estraverse](https://github.com/Constellation/estraverse) module to do that for us. To use Estraverse:

{% highlight js %}
estraverse.traverse(ast, {
  enter: function(node){
    console.log('Entered node', node.type);
  }
});
{% endhighlight %}

## Find the Assignments

Now that we can traverse an AST, we need to know what to look for. What does an assignment look like? To find out, put into the online parser ["g = 1"](http://esprima.org/demo/parse.html?code=g%20%3D%201) and we find that we just have to find all nodes of type `AssignmentExpression`, and then get at its `left.name`. Let's try this.

First, let's create a new directory for this project, and install both Esprima and Estraverse.

    mkdir esprima_fun
    cd esprima_fun
    npm install esprima
    npm install estraverse

Now, create a `assignments.js` and write

{% highlight js %}
var fs = require('fs');
var esprima = require('esprima');
var estraverse = require('estraverse');

var filename = process.argv[2];
console.log('Processing', filename);
var ast = esprima.parse(fs.readFileSync(filename));
estraverse.traverse(ast, {
  enter: function(node){
    if (node.type === 'AssignmentExpression'){
      console.log('Encountered assignment to', node.left.name);
    }
  }
});
{% endhighlight %}

This program will take the input file name as its a parameter and report for each assignment in the program, which identifier was assigned to. As a test, make a file `example1.js`

{% highlight js %}
g = 1;
f = 2;
var h = 1, i;
{% endhighlight %}

Run `node assignments.js example1.js` and the output should be

    Processing example1.js
    Encountered assignment to g
    Encountered assignment to f

[Full Source](https://github.com/airportyh/esprima_fun/blob/master/assignments.js)

## Javascript Scoping 101

The next step is to find out whether a given identifier being assigned to has been defined as a variable within that scope. But first, let's revisit how variable scoping works in Javascript. In Javascript, other than the *global* scope - the default variable scope for code that doesn't belong to any function - the only thing that creates a new scope is a function.

{% highlight js %}
var a = 1, b = 2; // a and b are in the global scope
function f(){
  var c;  // c is in the scope of f, 
          // which is a child of the global scope
  (function g(){
    var d = 'yo'; // d is in the scope
                  // of g, 
                  // which is a child of the scope of f
  }());
}
{% endhighlight %}

Here's a way to visualize the scope chain above

<div class="image">
  <img src="/images/fun-with-esprima/scope-chain.png" alt="Scope Chain">
</div>

Within the scope of `g()`, all 4 variables `a`, `b`, `c`, and `d` are defined, because each of them either live in the scope of `g()` or its parent or ancestor scope. Within `f()`, only `a`, `b`, and `c` are defined, and then in the global scope only `a` and `b` are defined.

## Reverse-Engineering the Scope Chain

In order to figure out whether an identifier is defined within a particular scope, we need to not only collect all variables declared within the scope itself, but also of all its ancestors. In order to do this, we'll need to maintain our own scope chain as we traverse down the AST. *This will be fun.*

First, write a function that tells us whether a given node creates a new scope. We are interested in three types of nodes

1. `FunctionDeclarations` - such as <a href="http://esprima.org/demo/parse.html?code=function%20f()%7B%0A%7D" target="_blank">function f(){...}</a>
2. `FunctionExpressions` - such as <a href="http://esprima.org/demo/parse.html?code=var%20f%20%3D%20function()%7B%7D%3B" target="_blank">var f = function(){...};</a>
3. the top level program, which always has type of `Program`.

{% highlight js %}
function createsNewScope(node){
  return node.type === 'FunctionDeclaration' ||
    node.type === 'FunctionExpression' ||
    node.type === 'Program';
}
{% endhighlight %}

We'll use an array as a queue for storing the scope chain. 

{% highlight js %}
var scopeChain = [];
{% endhighlight %}

As we traverse each node, in the `enter` function, we add a new scope - for which we are just going to represent as an array of variable names - to the scope chain whenever we encounter a scope-creating node.

{% highlight js %}
if (createsNewScope(node)){
  scopeChain.push([]);
}
{% endhighlight %}

When we see a <a href="http://esprima.org/demo/parse.html?code=var%20a%20%3D%201%2C%20b%3B" target="_blank">variable declarator</a>, we'll push it into the current scope

{% highlight js %}
if (node.type === 'VariableDeclarator'){
  var currentScope = scopeChain[scopeChain.length - 1];
  currentScope.push(node.id.name);
}
{% endhighlight %}

Next, using the `leave` hook of Estraverse - called when all the children of a node have been traversed - we can find out what variables have been declared within that scope just by printing it out. We also dispose of the current scope using array's `pop()` method on the scope chain.

{% highlight js %}
function leave(node){
  if (createsNewScope(node)){
    var currentScope = scopeChain.pop();
    console.log(currentScope);
  }
}
{% endhighlight %}

But we can make the output give more context here if we also print out information about the node. So let's instead write a `printScope()` function and substitute `printScope(currentScope, node)` for `console.log(currentScope)`

{% highlight js %}
function printScope(scope, node){
  var varsDisplay = scope.join(', ');
  if (node.type === 'Program'){
    console.log('Variables declared in the global scope:', 
      varsDisplay);
  }else{
    if (node.id && node.id.name){
      console.log('Variables declared in the function ' + node.id.name + '():',
        varsDisplay);
    }else{
      console.log('Variables declared in anonymous function:',
        varsDisplay);
    }
  }
}
{% endhighlight %}

Now, if you run that script on this input program:

{% highlight js %}
var a = 1, b = 2; // a and b are in the global scope
function f(){
  var c;  // c is in the scope of f, 
          // which is a child of the global scope
  (function g(){
    var d = 'yo'; // d is in the scope
                  // of g, 
                  // which is a child of the scope of f
  }());
}
{% endhighlight %}

You should get the output of

    Variables declared in the function g(): d
    Variables declared in the function f(): c
    Variables declared in the global scope: a, b

Notice that the output starts with the innermost scope and ends with the outermost scope. This is because we finish collecting the variable declarations and print them out on leaving a node, rather than entering it.

[Full Source](https://github.com/airportyh/esprima_fun/blob/master/detect_leaks.js)

## Putting it All Together

Now that we have the scope chain reverse-engineered, we can query it to see whether an variable was define when it was assigned a value. We'll make a function `isVarDefined()` like so

{% highlight js %}
function isVarDefined(varname, scopeChain){
  for (var i = 0; i < scopeChain.length; i++){
    var scope = scopeChain[i];
    if (scope.indexOf(varname) !== -1){
      return true;
    }
  }
  return false;
}
{% endhighlight %}

After this, it's a matter of collecting all the <a href="http://esprima.org/demo/parse.html?code=some_variable%20%3D%206%3B%0A" target="_blank">assignment statements</a> within the current scope in an array, and then checking all of them for defined-ness.

We'll need an array to collect all the assignments done within the current scope, because the check must happen on leaving a node - the point when the scope chain fully materializes.

{% highlight js %}
var assignments = [];
{% endhighlight %}

Inside the `enter` function, we collect all the assignment expressions nodes into it

{% highlight js %}
if (node.type === 'AssignmentExpression'){
  assignments.push(node.left.name);
}
{% endhighlight %}

Then in the `leave` function, we check for any global variable leaks

{% highlight js %}
if (createsNewScope(node)){
  checkForLeaks(assns, scopeChain);
}
{% endhighlight %}

where `checkForLeaks()` is

{% highlight js %}
function checkForLeaks(assignments, scopeChain){
  for (var i = 0; i < assignments.length; i++){
    if (!isVarDefined(assignments[i], scopeChain)){
      console.log('Detected leaked global variable:', assignments[i]);
    }
  }
}
{% endhighlight %}

If you run the it against the following input program

{% highlight js %}
e = 1;
f = 2;
var h = 1, f;
function m(){
  k = 2;
}
{% endhighlight %}

You should get

    Detected leaked global variable: e
    Detected leaked global variable: k

[Full Source](https://github.com/airportyh/esprima_fun/blob/master/detect_leaks.js)

## Line Numbers

But, wait, there's more! Esprima can also give location information about each node in the AST, so that we can output the line number for each of the leaks we found. We just turn on this feature by passing in `{loc: true}` as the second argument to `esprima.parse()`. See [the docs](http://esprima.org/doc/index.html) for all esprima options.

Next we need to modify the code to keep track of all the leaking nodes so that we can actually get at their locations when we need to. So we change the line

{% highlight js %}
assns.push(node.left.name);
{% endhighlight %}

to

{% highlight js %}
assns.push(node);
{% endhighlight %}

And then we modify `checkForLeaks()` to print out the line information:

{% highlight js %}
function checkForLeaks(assignments, scopeChain){
  for (var i = 0; i < assignments.length; i++){
    var assignment = assignments[i];
    var varname = assignment.left.name;
    if (!isVarDefined(varname, scopeChain)){
      console.log('Leaked global', varname, 
        'on line', assignment.loc.start.line);
    }
  }
}
{% endhighlight %}

[Full Source](https://github.com/airportyh/esprima_fun/blob/master/detect_leaks_lineno.js)

## Homework

There are some additional problems with our code still:

1. a <a href="http://esprima.org/demo/parse.html?code=function%20f()%7B%0A%7D" target="_blank">function statement</a> implicitly declares a variable - these are currently not tracked
2. <a href="http://esprima.org/demo/parse.html?code=function%20f(a%2C%20b%2C%20c)%7B%0A%7D" target="_blank">a function's parameters</a> all become variables within the function's scope - these are currently not tracked

Your assignment is to make the global variable detector work with these two cases as well. To submit your homework, put your solution on Github and post it in the comments.

## Extra Credit!

*I can tell that you can't get enough of this static analysis stuff!!* Here are a couple more problems to satisfy that appetite

1. detect unused variables in a program.
2. detect referenced-but-undeclared globals - these would be globals variables that are used by the program but not declared by the program. This is not necessarily a problem, the DOM API exposes itself via global variables such as `window` and `document`, for example, but tracking these sometimes can help find typos.

As with the homework, please post your solutions in the comments.</content>
        </entry>,<entry>
            <title>JSDiff for Comparing Text</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2013/11/05/jsdiff-for-comparing-text">
            <updated>2013-11-05T05:00:00.000Z</updated>
            <id>http://tobyho.com/2013/11/05/jsdiff-for-comparing-text</li>
            <content type="text">
[JSDiff](https://github.com/kpdecker/jsdiff) is an implementing of text comparison in Javascript, it is used in Mocha to implement [colored diffs](http://visionmedia.github.io/mocha/#string-diffs), and it's fairly easy to use.

Let's say you have two strings: `oldString` and `newString`

{% highlight js %}
var oldString = 'beep boop';
var newString = 'beep boob blah';
{% endhighlight %}

To compare them you may use the `diffChars` method

{% highlight js %}
var diff = JsDiff.diffChars(oldString, newString);
{% endhighlight %}

This gives you `diff` which is an array of change objects. A change object represents a section of text which is has either been added, removed, or neither. It has the following properties

* `value`: text content
* `added`: whether the value was inserted into the new string
* `remove`: whether the value was removed from the old string

In the above example, if you'd log the `diff` object, you'd see

{% highlight js %}
[ { value: 'beep boo', added: undefined, removed: undefined },
  { value: 'b blah', added: true, removed: undefined },
  { value: 'p', added: undefined, removed: true } ]
{% endhighlight %}

To render this information visually, we can color code these text chunks. In Node, there's a module [colors](https://github.com/Marak/colors.js) which makes outputing colors to the terminal easy.

{% highlight js %}
diff.forEach(function(part){
  // green for additions, red for deletions
  // grey for common parts
  var color = part.added ? 'green' :
    part.removed ? 'red' : 'grey';
  process.stderr.write(part.value[color]);
});
{% endhighlight %}

If you run this program ([see full source code](https://github.com/airportyh/jsdiff/blob/docs/examples/node_example.js)) you should see

<img src="/images/jsdiff-for-comparing-text/node_example.png">

You can also use [JSDiff](https://github.com/kpdecker/jsdiff) on a web page by using browserify or just via `<script>` tag. To render the same diff using DOM elements - using the raw DOM API would look like

{% highlight js %}
var display = document.createElement('pre');
diff.forEach(function(part){
  // green for additions, red for deletions
  // grey for common parts
  var color = part.added ? 'green' :
    part.removed ? 'red' : 'grey';
  var span = document.createElement('span');
  span.style.color = color;
  span.appendChild(document
    .createTextNode(part.value));
  display.appendChild(span);
});
document.body.appendChild(display);
{% endhighlight %}

The result of that code ([full source](https://github.com/airportyh/jsdiff/blob/docs/examples/web_example.html), or [on requirebin](http://requirebin.com/?gist=7325660)) would look like

<img src="/images/jsdiff-for-comparing-text/web_example.png">

But wait, there's more. Take a look at JsDiff's [API](https://github.com/kpdecker/jsdiff#api), it can also

* compare by word.
* compare by line.
* compare CSS.
* create patch files for use with the [patch](http://en.wikipedia.org/wiki/Patch_\(Unix\)) program.</content>
        </entry>,<entry>
            <title>Small.JS</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2013/10/20/smalljs">
            <updated>2013-10-20T04:00:00.000Z</updated>
            <id>http://tobyho.com/2013/10/20/smalljs</li>
            <content type="text">

> Got Code?

Until recently, Javascript had not had much of a module story, i.e., a good way of sharing code with others. I would say it doesn't have a great one even today. 

## The Snippet

You google for how to throttle in Javascript, and you get a [blog post](http://remysharp.com/2010/07/21/throttling-function-calls/) with 11 lines of magic you can copy-n-paste. Copy-n-pasting code into your project seems a little yucky - maybe better to fetch a file to clearly delineate your own code versus 3rd party code. Plus, if the author were to fix a bug or add enhancements in the future, you could straight-forwardly update the code. But, is 11 lines really worth it?  Maybe not. It's almost faster to copy-n-paste those 11 lines than to download a `.js` file. You paste in the code and leave the blog url in a comment to let others and future you know where it's from.

## The .js File

Another possibility is you find the functionality you need from a more inclusive library. [Underscore.js](https://github.com/jashkenas/underscore) includes the `throttle` function out of the box. To use underscore.js in your project, you would:

1. download the file `underscore.js`.
2. copy it into a subdirectory in your project.
3. add a `<script>` tag in your page(s).

This workflow is good - compared to what it used to be. There was a time when using a Javascript library involved these steps

1. downloading a zip file.
2. unpacking it.
3. figuring out which files you need.
4. move them to the appropriate subdirectories in your project.
5. adding `<script>` tags to your page(s).

It was a hassle. Most libraries have gone away from that, opting for the all-you-have-to-download-is-the-one-js-file approach, because it's much easier for the user. Now the user only has to add one `<script>` tag, and there is no guessing as to which .js file it is. This is why many libraries put the .js suffix in their name. It is a marketing tactic. It signals that there is just one Javascript file, so using it will be super easy.

## Depend on No One

An unspoken rule in the world of .js files is *depend on no one* - that is, unless it's jQuery.

Today, you seldomly encounter a library that requires you to download other dependencies. People are impatient, and the more stuff you ask them to do before actually seeing things happen, the less likely they are to use the library in the first place.

If a library must have dependencies, what usually happens is: either they ask you to download a `.zip` file that contains all of the dependencies, or they concatenate the dependencies into a monolithic file along with the library itself. You'll see this with some libraries that depend on JSON parsing or base64 encoding, for example.

For the most part, we the library authors have shied away from depending on other libraries. This is a limitation. It makes it hard to stand on other's shoulders, but it also makes it hard to reuse our own code in multiple contexts - an effective way to remove code duplication. In this way, we have been handicapped for many years.

### We Make an Exception for jQuery

Depending on jQuery though, is OK, because

1. you're already using jQuery, right?
2. jQuery is rock solid, battled-tested, has a stable API, and it's only the most useful script in the world.
3. you *are* already using jQuery, right?

Although, even for jQuery plugins, the "depend on no one" rule holds - you will seldom find a jQuery plugin that depends on another jQuery plugin or a standalone library. jQuery is what I call a *god framework*.

## God Frameworks

I call jQuery a *god framework* because without it, the universe ceases to function. In other words, everything depends on it. A dependency graph of a typical jQuery-based project probably has most - if not all - of it's modules pointing to jQuery. The only hope of getting by without it is to replace it with something that works exactly like jQuery, a sort of clone. [Zepto](http://zeptojs.com/) is exactly that, and it exists probably because someone had gone to great pains to rid themselves of jQuery. 

jQuery is not the *only* god framework though, not by far, it just happens to have decisively won the *First Great Framework War*. All frameworks more or less want to be god-like. One *tell* is if it has plugins

> If you have a plugin ecosystem, you might be a framework.

## Framework-Heavy

The Javascript world is dominated by frameworks, and it is because of our reluctance to having dependencies in our libraries. If you are going to write a Javascript library, you have two options:

1. Depend on a proven framework.
2. Depend on no one.

If you choose option #1, you contribute to the worship of the framework.

If you choose option #2, you are faced with a problem. If you make it too small, it may not be useful enough to warrant a download (are you *download-worthy*?). What happens sometimes is a set of smaller functionalities get packaged up into a larger library to give users more value for the download. Another thing that tends to happen is established libraries get bigger over time as new techniques are discovered and new features invented, because this makes it easier for existing users. Examples of this are

1. the addition of [promises](http://api.jquery.com/promise/) into jQuery.
2. version 0.1.0 of underscore had 42 methods. Version 1.5.2 of underscore has 109 methods.

*This*. This is why the Javascript world is dominated by frameworks. There is good reason why jQuery is a [Swiss Army Knife](http://ajpiano.com/jquery-is-a-swiss-army-knife/): *tons of features in a single download equals convenience*.

## The Dream

As someone who likes to write small libraries, the dream for me, is this: *I want easy dependencies: regardless of how many dependencies and/or nested dependencies my project has, I want to be able tell people "using my library is as easy as 1-2-3."*

What I want is something like *NPM*.

## The Beauty of NPM

The rise of [Node.js](http://nodejs.org/) and with it, [NPM - the Node Package Registry](https://npmjs.org/) has been an important development. NPM is a joy to use, and has made publishing server-side Javascript modules really easy. It has made dependencies easy, both for module authors and users. 

If you want to add Express to your project, just install it with the command

    npm install express

and then in your code you'd just require it by the same name

{% highlight js %}
var express = require('express')
{% endhighlight %}

If the module depends on other modules, they are automatically fetched recursively for you - you may not even notice them if you don't pay attention to npm's console output. Node developers take full advantage of dependencies. This is the dependency graph of `express`, the server-side web framework.

<div class="image">
<img src="/images/smalljs/express_dependencies.png" alt="Express Dependencies"/>
</div>

*Visualization generated by <https://david-dm.org/visionmedia/express#info=dependencies&view=tree>*

NPM has re-taught us that modules do in fact, work, and that it works in Javascript. It has flourished beyond expectation. In just a few years, it surpassed CSPAN and PyPI in number of packages, and that number grows at a consistently higher rate than the module registries for any other programming language. ([source](http://modulecounts.com/))

## Small is Beautiful

The NPM community of modules embrace smallness. Small modules have these characteristics

1. *they are small* (duh), a good rule of thumb is ~200 LOC or less.
2. *they have a single-purpose*. This is actually good engineering practice in general - it aligns with the [Single Responsibility Principle](http://en.wikipedia.org/wiki/Single_responsibility_principle).
3. they have a small API and learning curve, given #2.
4. they are easy to make, given #1.
5. they are easy to get rid of - you can either rewrite the parts of your code that depend on it, or you can re-implement the API of the module, either way is easy given #1 and #2.

## NPM for Browser Code?

But NPM is for server-side Javascript. What about client-side Javascript? 

Short answer: *It's complicated.*

Medium answer: it's a race to the top, and the front runners at the time of writing are *NPM with Browserify* and *Bower*.

[Browserify](https://github.com/substack/node-browserify) is a tool that allows the CommonJS module system to be used in the browser. It does require a compilation step, but this step can be automated away. Browserify works great with NPM, and there is an increasing number of client-side modules on NPM.

[Bower](http://bower.io/) is a newer module registry for browser code. Bower does not have an opinion about module formats. To install a library, Bower simply fetches the contents of a git repository. It is up to the users to decide what module system they want to use and how they want to consume the fetched library, whether it's CommonJS, AMD with Require.js or simply `<script>` tags.

[Component](http://component.io/) is the contender in third place, but nevertheless has accumulated many useful modules. Like Node, it is based on CommonJS.

## Small Modules in the Wild

Despite the fragmentation in the frontend Javascript package manager space, their availability is giving rise to reusable modules in smaller chunks. Here are some examples of this at work

1. [hyperscript](https://github.com/dominictarr/hyperscript) - a tiny DOM builder that supports automatic two-way data binding via another tiny module [observable](https://github.com/dominictarr/observable). It depends on even tinier modules such as
    * [class-list](https://github.com/Raynos/class-list) - add and remove class names on an element
    * [data-set](https://github.com/Colingo/data-set) - set data attributes on an element
    * [browser-split](https://github.com/juliangruber/browser-split) - simply a cross-browser `String#split` implementation
2. [level.js](https://github.com/maxogden/level.js) - an implementation the [leveldb] api in the browser. It uses [IDBWrapper](https://github.com/jensarps/IDBWrapper), which provides a usable cross-browser interface for IndexedDB.
3. [superagent](https://github.com/visionmedia/superagent) - an elegant ajax library. It's dependencies
    * [emitter](https://github.com/component/emitter) - a browser version of Node's event emitter
    * [reduce-component](https://npmjs.org/package/reduce-component) - a cross-browser version of `Array#reduce`
4. [page.js](https://github.com/visionmedia/page.js) is a small client-side router inspired by Express designed to work with pushState.
5. [masonry](https://github.com/desandro/masonry) - Masonry is a cascading grid layout library. It works with or without jQuery, but what is interesting is that its author made it's internals very modular. The bulk of the work is of Masonry is actually done within another library [outlayer](https://github.com/metafizzy/outlayer) - which in turn has more dependencies like
    * [doc-ready](https://github.com/desandro/doc-ready) - the document ready event
    * [EventEmitter](https://github.com/Wolfy87/EventEmitter/) - an event emitter for the browser
    * [get-size](https://github.com/desandro/get-size) - a function to get the size of DOM elements
    * [get-style-property](https://github.com/desandro/get-style-property) - a function to add vendor-prefixes to CSS properties
    * [matches-selector](https://github.com/desandro/matches-selector) - a cross-browser version of `document.matchesSelector`
    * [jquery-bridget](https://github.com/desandro/jquery-bridget) - a utility for turning a Javascript class into a jQuery plugin
6. [lodash](https://github.com/lodash) - lodash started out as an underscore clone, but now has [features](https://github.com/lodash/lodash#features-not-in-underscore) all its own. Interestingly, Lodash has made each of its methods available as a separate module on NPM. For example, if all you needed were the `_.throttle` function you can install it via `npm install lodash.throttle` and you'd get the code needed for that function alone.
7. jQuery - maintainers have focused on making jQuery more modular internally. The jQuery source is now authored in AMD, and it is possible to create [custom builds](https://github.com/jquery/jquery#modules) of jQuery yourself which excludes the modules you don't need. It shouldn't be too much of a stretch from this to be able to include just the modules you need. Although, if you want small portions of jQuery's functionality, there already are modules for that
    * selector engines
        * [sizzle](https://github.com/jquery/sizzle) - jQuery's selector engine
        * [qwery](https://github.com/ded/qwery)
        * [zest](https://github.com/component/zest)
    * DOM manipulation
        * [domify](https://github.com/component/domify) - convert HTML to DOM nodes
        * [classes](https://github.com/component/classes) - add, remove, and toggle classes
        * [css](http://github.com/component/css) - set style properties
        * [bonzo](https://github.com/ded/bonzo)
    * DOM Events
        * [event](https://github.com/component/event) - event binding
        * [delegate](https://github.com/component/delegate) - event delegation
        * [bean](https://github.com/fat/bean)
    * document ready event
        * [domready](https://github.com/ded/domready)
        * [doc-ready](https://github.com/desandro/doc-ready)

## But the FUD

There are still many questions in the air, not to mention *fear, uncertainty, and doubt.* Questions like

1. Which is the one true package manager?
2. Module formats: CommonJS or AMD? *(or ES6 Harmony?)* Or nothing at all?
3. How to consume these modules? Require.js, Browserify or something else?

Some of the modules mentioned above use CommonJS while others use AMD, some support both, some neither. Without everyone agreeing on the one true way to write modules, how can we move forward?

## Go Forth and Publish

My answer to that question is: *do it anyway.* Pick the format/tool you like and go for it. The important thing is that you can

1. Start writing modular code right away, in production.
2. Publish the reusable parts of your app as modules, in small chunks.

The landscape of Javascript libraries is changing - it's becoming more modular. Once there is a lot of value in this newer space, consolidation will probably happen, but until then, let's put more value in there!

## Related Resources

* [microjs](http://microjs.com/) - a listing of small JS libraries
* [npm](https://npmjs.org/) - the Node Package Manager registry
* [bower](http://sindresorhus.com/bower-components/) - the Bower registry
* [require.js](http://requirejs.org/) - *the* AMD loader
* [component module list](https://github.com/component/component/wiki/Components) - all the components
</content>
        </entry>,<entry>
            <title>File Watching with Fireworm and Watch'em</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2013/08/22/file-watching-with-fireworm-and-watchem">
            <updated>2013-08-22T04:00:00.000Z</updated>
            <id>http://tobyho.com/2013/08/22/file-watching-with-fireworm-and-watchem</li>
            <content type="text">
Out of the box, [Node](http://nodejs.org/api/) comes with a [fs.watch](http://nodejs.org/api/fs.html#fs_fs_watch_filename_options_listener) function that watches for modifications on a file or directory. This function is superior to its older cousin [fs.watchFile](http://nodejs.org/api/fs.html#fs_fs_watchfile_filename_options_listener) because whereas `fs.watchFile` repeatedly polls the file's stat (every second or so) to check for modification, `fs.watch` uses [OS specific features](http://nodejs.org/api/fs.html#fs_availability) that signal the change back to the program immediately.

## The Problem

[Testem](https://github.com/airportyh/testem) uses `fs.watch` for file watching which yields a fast and responsive development experience. But an annoyance for users is that *it can't pickup newly created files*. As a consequence, users resort to closing out testem and then restarting it everytime they create, rename, or move a file.

### Challenge #1

`fs.watch` attaches a watcher to a file by it's [inode number](http://en.wikipedia.org/wiki/Inode)(or equivalent), not by it's path, therefore, just because you did

{% highlight js %}
var w = fs.watch('scripts/script.js')
{% endhighlight js %}

doesn't mean that you'll always get notified if the contents of `scripts/script.js` change - not if it was replaced by another file(which has a different inode number).

### Challenge #2

Another challenge is supporting [globs](http://en.wikipedia.org/wiki/Glob_\(programming\)), e.g. `*.js`, which require crawling directories and subdirectories and placing watchers on all the matching files, however, this means newly created files that match the desired pattern will not get watched, unless the directories get crawled again.

## The Fireworm

Which is why I started work on [fireworm](https://github.com/airportyh/fireworm) - a crawling file watcher. Fireworm crawls the directories and attaches watchers to the files, but in addition, it also watches relevant directories and recrawls them when their contents change. To use it, first you create a new file watcher:

{% highlight js %}
var fireworm = require('fireworm')
var fw = fireworm('start_dir') // specify the dir to watch
{% endhighlight %}

Then, add the files you want to watch for changes on (can be glob)

{% highlight js %}
fw.add('lib/**/*.js')
fw.add('tests/**/*.js')
{% endhighlight %}

You can ignore some patterns if you wish

{% highlight js %}
fw.ignore('tests/dontcare/*.js')
{% endhighlight %}

Lastly, register for the `change` event

{% highlight js %}
fw.on('change', function(filename){
    console.log(filename, 'just changed!')
})
{% endhighlight %}

And that's all there is to it.

## Watch'em

With fireworm it becomes very easy to write a program that monitors a directory for changes and responds in some way. For some time now, I've wanted a one-liner that I could type which just watches a directory and runs and reruns a command for me whenever the contents in the directory changed. I could use testem or guard or other watcher thingies, but they all still require some amount of configuration. So, I wrote [watch'em](https://github.com/airportyh/watchem).

With watchem, you can type on the command line

    watchem "Makefile,**/*.c,**/*.h" make

and it will watch the `Makefile`, and any `.c` or `.h` files within the current directory and within any of its subdirectories. It runs and re-runs `make` whenever any matching files change, even new ones that are created. I made a 3 minute screencast of it in action

<div class="video">
<iframe src="http://www.screenr.com/embed/VEXH" width="650" height="396" frameborder="0"></iframe>
</div>

If you are feeling lazy, you can just match against `**/*` and it will match any file in the directory (except for hidden files and the node_modules directory).

    watchem "**/*" make

## Test'em

Incidentally, testem also got an update which now allows it to automatically watch newly created files that match the file patterns specified.

## That's all folks

If you've read this far, thanks! I hope you give the tools and try and have fun!

</content>
        </entry>,<entry>
            <title>What Is This Thing Called Generators?</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2013/06/16/what-are-generators">
            <updated>2013-06-16T04:00:00.000Z</updated>
            <id>http://tobyho.com/2013/06/16/what-are-generators</li>
            <content type="text">

*Update: since this article was first published, the `send()` method has been removed from the spec. `send(value)` was replaced with calling next with a parameter value, i.e. `next(value)`. I have updated this post with this change.*

It looks like [generators](http://wiki.ecmascript.org/doku.php?id=harmony:generators) are actually going to make it into Javascript, **and** it has landed in V8. This is so exciting! [Lately](http://dailyjs.com/2013/05/31/suspend/) [it's](https://medium.com/code-adventures/174f1fe66127) [been](http://jlongster.com/A-Study-on-Solving-Callbacks-with-JavaScript-Generators) [all](https://gist.github.com/creationix/5761021) [the](https://github.com/jmar777/suspend) [rage](http://wingolog.org/archives/2013/05/08/generators-in-v8). But what is it? With this post I'll do my best to explain at a basic level what it is.

## Get It

Before we begin, let's make sure we can execute the code in the examples - **because code is no good unless you can run it**. You'd want to install an experimental version of Node (0.11.10+). I recommend:

1. First install [nvm](https://github.com/creationix/nvm)
2. then `nvm install v0.11.10` to install Node
3. now to run any of the examples, make sure you use the `--harmony` flag, i.e. `node --harmony` or `node --harmony myscript.js`

## The Basics

At its simplest form, a generator represents a sequence of values - essentially it is an iterator. In fact, the interface of a generator object is a just an iterator for which you'd keep calling `next()` on it until it runs out of values. What makes a generator special is the way you write it:

{% highlight js %}
function* naturalNumbers(){
  var n = 1;
  while (true){
    yield n++;
  }
}
{% endhighlight %}

In this example([source](https://github.com/airportyh/generators_hello/blob/master/iteration.js)), `naturalNumbers` is a *generator function* - or *generator* for short. It is written using the new * syntax as well as the new `yield` keyword introduced in ES6. This generator function returns *generator objects* that return the set of natural numbers, i.e. it is an infinite sequence. Each time `yield` is called, the yielded value becomes the next value in the sequence. To iterate the sequence, a `for-of` syntax has also been proposed in ES6, however this is not yet been implemented in V8:

{% highlight js %}
// this doesn't work yet. Also, it's an infinite loop ;P
for (var number of naturalNumbers()){
  console.log('number is ', n);
}
{% endhighlight %}

Don't fret, we can still make it do nice things. To create a new sequence, you'd call the generator function in order to get a live *generator object*:

    > var numbers = naturalNumbers();

Now, if you call `numbers.next()`, you get an object with the properties `value` and `done`.

    > numbers.next()
    { value: 0, done: false }

`value` is the next value in the sequence, and `done` is whether or not the sequence has stopped - the sequence stops when the code has reach the end of the generator function. But in the natural numbers example, the sequence would never stop, so to illustrate a stopped sequence let's make a simple sequence that just returns two numbers:

{% highlight js %}
function* two(){
  yield 1;
  yield 2;
}
{% endhighlight %}

Now, let it run:

    > var seq = two()
    > seq.next()
    { value: 1, done: false }
    > seq.next()
    { value: 2, done: false }
    > seq.next()
    { value: undefined, done: true }

As you can see, the third time we get `done` to be `true` and `value` to be `undefined`. If we call it a fourth time, we get an exception:

    > seq.next()
    Error: Generator has already finished

## Code Suspension

So you've seen the basics of generators, and using it to implement iterators. But the one thing that makes generators significant is this: **it is now possible to suspend code execution**. Once you instantiate a generator object, you have a handle on a function whose execution can start and stop, moreover, whenever it stops, you have control over **when** it restarts. To see this more concretely, let's create a generator that simply prints out strings to the console.

{% highlight js %}
function* haiku(){
  console.log('I kill an ant');
  yield null; // the yield keyword requires a value, so I put null
  console.log('and realize my three children');
  yield null;
  console.log('have been watching.');
  yield null;
  console.log('- Kato Shuson');
}
{% endhighlight %}

Now, if we iterate the generator object from this generator

    > var g = haiku()

and then iterate through it, line by line by calling `g.next()` on the command line

    > g.next()

You'll realize that

1. the code in the generator doesn't start executing until you say so
2. when the code encounters a `yield` statement, it suspends execution indefinitely, and doesn't start again until you tell it to

This opens possibilities for asychronicity: you can call `next()` after some asynchronous event has occurred. To see this, take a look at the following example which makes the poem display a line per second by combining the generator with an [async loop](http://tobyho.com/2011/11/03/delaying-repeatedly/).

{% highlight js %}
var g = haiku();
function next(){
  if (g.next().done) return;
  setTimeout(next, 1000);
}
next();
{% endhighlight %}

Note that the code in the generator `haiku` looks like straight line Javascript, and yet, asychronicity has occurred in the middle of that code - which was not possible before due to Javascript's general single threaded nature. More specifically, each time a yield is encountered, asychronicity has a chance to occur. Those yields are kind of like time warping wormholes. ([source](https://github.com/airportyh/generators_hello/blob/master/haiku.js))

## Send

Up until now we've looked at a generator objects only as a producer of a sequence of values, where information only goes one way - from the generator to you. It turns out that you can also send values to it by giving `next()` a parameter, in which case the yield statement actually returns a value! Let's see this by making a generator that consumers values:

{% highlight js %}
function* consumer(){
  while (true){
    var val = yield null;
    console.log('Got value', val);
  }
}
{% endhighlight %}

First instantiate a generator object

    > var c = consumer()

Next, let's try calling `next()` with a value:

    > c.next(1)
    { value: null, done: false }

This returns the expected object, but it also didn't `console.log()` anything, the reason being that initially, the generator wasn't yielding yet. If we call send again however, will see the `console.log` message:

    > c.next(2)
    Got value 2
    { value: null, done: false }
    > c.next(3)
    Got value 3
    { value: null, done: false }

## Throw

Cool! So we can both send and receive values from a generator, but guess what? You can also throw!

    > c.throw(new Error('blarg!'))
    Error: blarg!

When you `throw()` an error onto a generator object, the error actually propagates back up into the code of the generator, meaning you can actually use the `try` and `catch` statements to catch it. So, if we add try/catches to the last example:

{% highlight js %}
function* consumer(){
  while (true){
    try{
      var val = yield null;
      console.log('Got value', val);
    }catch(e){
      console.log('You threw an error but I caught it ;P')
    }
  }
}
{% endhighlight %}

This time, once we instantiate the generator object, we'll call `next()` first, because there's no way the generator can catch a error that's thrown at it before it even starts executing.

    > var c = consumer()
    > c.next()

After this point on, if we throw an error, it will catch the error and handle it gracefully:

    > c.throw(new Error('blarg!'))
    You threw an error but I caught it ;P

try/catch worked.

## Getting Fancy

Now that you know the basic mechanics of generators, what can you *really* do with it? Well, most folks are excited about them because it is seen as the **Ticket Out of Callback Hell &trade;**, so let's see how that can be done.

### The Premise

In Javascript, especially in Node, IO operations are generally done as asynchronous operations that require a callback. When you have to do multiple async operations one after another it looks like this:

{% highlight js %}
fs.readFile('blog_post_template.html', function(err, tpContent){
  fs.readFile('my_blog_post.md', function(err, mdContent){
    resp.end(template(tpContent, markdown(String(mdContent))));
  });
});
{% endhighlight %}

It gets worse when you add in error handling:

{% highlight js %}
fs.readFile('blog_post_template.html', function(err, tpContent){
  if (err){
    resp.end(err.message);
    return;
  }
  fs.readFile('my_blog_post.md', function(err, mdContent){
    if (err){
      resp.end(err.message);
      return;
    }
    resp.end(template(tpContent, markdown(String(mdContent))));
  });
});
{% endhighlight %}

The promise of generators is that you can now write the equivalent code in a straight-line fashion using generators

{% highlight js %}
try{
  var tpContent = yield readFile('blog_post_template.html');
  var mdContent = yield readFile('my_blog_post.md');
  resp.end(template(tpContent, markdown(String(mdContent))));
}catch(e){
  resp.end(e.message);
}
{% endhighlight %}

This is fantastic! Aside from less code and asthetics, it also has these benefits:

* Line independence: the code for one operation is no longer tied to the ones that come after it. If you want to reorder of operations, simply switching the lines. If you want to remove an operation, simply deleting the line.
* Simpler and DRY error handling: where as the callback-based style required error handling to be done for each individual async operation, with the generator-based style you can put one try/catch block around all the operations to handle errors uniformly - generators gives us back the power of try/catch exception handling.

### Make it Happen

You've seen what we are aiming for, now how do we implement it? If you are the type who wants to figure it out for yourself, I don't want to ruin it for you. Stop reading. Code away. Come back. I'll wait.

The first thing to realize is that the async operations need to take place outside of the generator function. This means that some sort of "controller" will need to handle the execution of the generator, fulfill async requests, and return the results back. So we'll need to pass the generator to this controller, for which we'll just make a `run()` function:

{% highlight js %}
run(function*(){
  try{
    var tpContent = yield readFile('blog_post_template.html');
    var mdContent = yield readFile('my_blog_post.md');
    resp.end(template(tpContent, markdown(String(mdContent))));
  }catch(e){
    resp.end(e.message);
  }
});
{% endhighlight %}

`run()` has the responsibility of calling the generator object repeatedly via `next()`, and fulfill a request each time a value is yielded. It will assume that the requests it receives are functions that take a single callback parameter which takes an `err`, and another `value` argument - conforming to the Node style callback convention. When `err` is present, it will call `throw()` on the generator object to propagate it back into the generator's code path. The code for `run()` looks like:

{% highlight js %}
function run(genfun){
  // instantiate the generator object
  var gen = genfun();
  // This is the async loop pattern
  function next(err, answer){
    var res;
    if (err){
      // if err, throw it into the wormhole
      return gen.throw(err);
    }else{
      // if good value, send it
      res = gen.next(answer);
    }
    if (!res.done){
      // if we are not at the end
      // we have an async request to
      // fulfill, we do this by calling 
      // `value` as a function
      // and passing it a callback
      // that receives err, answer
      // for which we'll just use `next()`
      res.value(next);
    }
  }
  // Kick off the async loop
  next();
}
{% endhighlight %}

Now given that, `readFile` takes the file path as parameter and needs to return a function

{% highlight js %}
function readFile(filepath){
  return function(callback){
    fs.readFile(filepath, callback);
  }
}
{% endhighlight %}

And that's it! If that went too fast, feel free to poke at the [full source code](https://github.com/airportyh/generators_hello/tree/master/blog).

## More Resources

To learn more about generators:

* The original post by [wingo](http://wingolog.org/archives/2013/05/08/generators-in-v8) when generators made it into V8
* [T.J. Holowaychuk's post](https://medium.com/code-adventures/174f1fe66127) and his [co library](https://github.com/visionmedia/co/) which is in concept similar to the `run` function I've demonstrated
* [Suspend](https://github.com/jmar777/suspend) and [genny](https://github.com/spion/genny) take a slightly different approach and has different tradeoffs than something like co
* [task.js](http://taskjs.org/) - Dave Herman's task library
* [Q](https://github.com/kriskowal/q) is a promise library which supports generators
* A [brilliant tutorial](http://www.dabeaz.com/coroutines/index.html) on generators in python by David Beazley
* The [original proposal](http://www.python.org/dev/peps/pep-0255/) that introduced generators to Python</content>
        </entry>,<entry>
            <title>A Subtle Difference Between Window Properties and Global Variables</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2013/03/13/window-prop-vs-global-var">
            <updated>2013-03-13T04:00:00.000Z</updated>
            <id>http://tobyho.com/2013/03/13/window-prop-vs-global-var</li>
            <content type="text">
Consider this piece code which initializes the `_gaq` object prior to loading the Google Analytics script. It is part of the Google Analytics page code which they ask you to put on your web page:

{% highlight html %}
<script>
var _gaq = _gaq || [];
// ...
</script>
{% endhighlight %}

This code looks innocent, but it was this very piece of code that sent me on a wild goose chase thanks to a very subtle difference in how it works on IE <= 8 vs other browsers.

First, what is the intent of this code? The right-hand-side of the assignment is `_gaq || []` which intends to use the existing value of `_gaq` if it exists, but falls back to the empty array. 

If _gaq was already a variable in the global scope - maybe you set it as a global variable by not using the `var` statement:

{% highlight html %}
<script>
_gaq = ['the', 'existing', 'array'];
</script>
{% endhighlight %}

then, our original code snippet would successfully use the existing array, because Javascript ignores the `var` statement in that case and works as if it was

{% highlight html %}
<script>
_gaq = _gaq || [];
</script>
{% endhighlight %}

In the case that `_gaq` is a property of the window object - maybe you initialized it like this:

{% highlight js %}
window._gaq = ['the', 'existing', 'array'];
{% endhighlight %}

most browsers will treat `_gaq` equivalent to a global variable, and for those browsers, it would work exactly the same, except for the case of IE8 and below.

For IE8, given that `_gaq` is a window property and not a global variable, and also given that the `var _gaq = _gaq || [];` GA snippet is pasted inside its own `<script>` tag, then the following applies.

Imagine that the code was instead this:

{% highlight js %}
;(function(){
  var _gaq = _gaq || [];
  // ...
}());
{% endhighlight %}

This is somewhat what IE8 behaves like. This code creates a new scope for the `_gaq` variable, within which it would be initialized with the value of `undefined`, and then be fallen back to the empty array. If you are confused, think of it like this

{% highlight js %}
;(function(){
  var _gaq;
  _gaq = _gaq || [];
  // ...
}());
{% endhighlight %}

Thus, `_gaq` in this scope will always be assigned the empty array, losing sight of what it was in the global scope.

It behaves like this code except that at the end, `_gaq` ends up as a global variable. The end result is that, `_gaq`, which had a value and used to be a property of the window object, has now been erased, and replaced with the new value of `_gaq` (empty array).

To test the code and see exactly what I mean, here is a [jsbin](http://jsbin.com/uxetod/1) - run it in IE8 vs another browser and see the difference in output.

</content>
        </entry>,<entry>
            <title>Performance Testing Views in Ember.js</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2013/03/12/perf-testing-ember.js-views">
            <updated>2013-03-12T04:00:00.000Z</updated>
            <id>http://tobyho.com/2013/03/12/perf-testing-ember.js-views</li>
            <content type="text">
I've been working on performance tuning an Ember.js app recently and one of the tricks I learned while hunting through `ember.js` - the go-to for Ember developers when they need to figure something out - is how to time the rendering of handlebars views. I am going to show a couple of code snippets, and then I am out - this post is going to be short and sweet.

The basic construct used is `Ember.subscribe`, which is used as follows

{% highlight js %}
Ember.subscribe("render", {
  before: function(name, timestamp, payload) {

  },

  after: function(name, timestamp, payload) {

  }
});
{% endhighlight %}

> The purpose of the Ember Instrumentation module is
  to provide efficient, general-purpose instrumentation
  for Ember.

After finding this it then took a little bit of experimentation to figure out that the template name can be retrieved from the `payload` as `payload.template`. Also, if you return a object from the `before` hook, it becomes the fourth parameter in your `after` hook, which is convinient for passing in beginning timestamp.

So, to see the time took to render any of the templates you might do this. 

{% highlight js %}
Ember.subscribe('render', {
  before: function(name, start, payload){
    return start
  },
  after: function(name, end, payload, start){
    var duration = Math.round(end - start)
    var template = payload.template
    if (template){ // this is to filter out anonymous templates
      console.log('rendered', template, 'took', duration, 'ms')
    }
  }
})
{% endhighlight %}

However, I get still way too much noise this way, so what I ended up doing when optimizing a specific view is to filter the output by the name of the view:

{% highlight js %}
  if (template === 'mytemplate'){
    console.log('rendered', template, 'took', duration, 'ms')
  }
{% endhighlight %}

</content>
        </entry>,<entry>
            <title>Javascript OO Without Constructors</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/10/21/javascript-OO-without-constructors">
            <updated>2012-10-21T04:00:00.000Z</updated>
            <id>http://tobyho.com/2012/10/21/javascript-OO-without-constructors</li>
            <content type="text">
Javascript's object model is not very well known. I've written about [them](http://tobyho.com/2011/11/11/js-object-inheritance/) a while back. One reason it is not well known is because it is the only widely used language that uses prototype inheritance. But I think another reason it is not well known is because it is complicated and confusing to explain. Why is it so complicated and confusing? Because Javascript tries to hide its true nature with a classical OOP facade - ending up a Jekyll and Hyde situation.

I believe that the inaccessibility of its object model is at least one of the reasons there's so much interest around compile-to-js languages like CoffeeScript, Dart, and TypeScript.

Javascript old-timers and die-hards believe that Javascript has a *better* object model and lament the fact that this may forever be forgotten. Even long time Javascript guru Nicholas Zakas welcomes the addition of the the [new *class* syntax](http://www.nczonline.net/blog/2012/10/16/does-javascript-need-classes/) - which is simply syntactical sugar for the prototypal style - to version 6 of the language. Alas, classical OOP has won.

A Thought Experiment
--------------------

However, just for fun, here's a thought experiment: let's suppose we turn back the clock on history, and that classical OOP hadn't gained wide adoption as it did, and instead, a prototype-based inheritance model received wide acceptance instead. What would have happened? What kind of design patterns would we have ended up with?

Here's another thought: what if Javascript did not have constructors, or the "new" keyword? How would things have turned out? Let's reinvent the wheel :)

First things first, to create a new object in Javascript, you can just use an object literal

{% highlight js %}
var felix = {
    name: 'Felix'
    , greet: function(){
        console.log('Hello, I am ' + this.name + '.')
    }
}
{% endhighlight %}

Now what if we want to generalize the greet function to a common place - a [pull-up](http://en.wikipedia.org/wiki/Pull_Up_refactoring), if you will - so that we can create multiple objects which share the greet function? We have a few options here, let's start with *the mixin*.

Mixin (Augmentation)
--------------------

In Javascript, mixins are embarrassingly simple. All you have to do is to copy the properties from the "mixin object" to the object you want to mix it into. We will use a function called "augment" to do this

{% highlight js %}
var Dude = {
    greet: function(){
        console.log('Hello, I am ' + this.name + '.')
    }
}
var felix = { name: 'Felix' }
augment(felix, Dude)
{% endhighlight %}

So `augment` applies the object `Dude` as a mixin into `felix`. In most libraries, the `augment` function is called "extend". I don't like extend because some languages use extend to mean inherit, and as a result it always confuses me. I like "augment" because it's not extend and because the syntax `augment(felix, Dude)` indicates very clearly that you are augmenting `felix` with what is in `Dude`.

As you might have guessed, the code for `augment` is simply

{% highlight js %}
function augment(obj, properties){
    for (var key in properties){
        obj[key] = properties[key]
    }
}
{% endhighlight %}

Cloning
-------

An alternative to using a mixin, is first to clone `Dude`, and then set the `name` property on the cloned version.

{% highlight js %}
var Dude = {
    greet: function(){
        console.log('Hello, I am ' + this.name + '.')
    }
}
var felix = clone(Dude)
felix.name = 'Felix'
{% endhighlight %}

The only difference here is the order in which the properties are applied. You might use this technique if you plan to override some methods in the cloned object.

{% highlight js %}
var felix = clone(Dude)
felix.name = 'Felix'
felix.greet = function(){
    console.log('Yo dawg!')
}
{% endhighlight %}

Calling back to *super*'s method is simple - just use the `apply` method

{% highlight js %}
felix.greet = function(){
    Dude.greet.apply(this)
    this.greetingCount++
}
{% endhighlight %}

This is nicer than the prototypal style because you don't have to go through the `.prototype` property of a constructor - we are not using any constructors. 

The implementation of clone is

{% highlight js %}
function clone(obj){
    var retval = {}
    augment(retval, obj)
    return retval
}
{% endhighlight %}

Inheritance
-----------

Finally we have inheritance. In my opinion, inheritance is overrated, but it does have the advantage over augmentation in that you can share properties between the "instance objects". Let's make an `inherit` function which takes an object as input and returns a new object that inherits the original object.

{% highlight js %}
var felix = inherit(Dude)
felix.name = 'Felix'
{% endhighlight %}

With inherit, you can have multiple objects inherit the same one, and the children will inherit the parent's properties in realtime.

{% highlight js %}
var garfield = inherit(Dude)
Dude.walk = function(){
    console.log('Step, step')
}
garfield.walk() // prints "Step, step"
felix.walk()    // also prints "Step, step"
{% endhighlight %}

The `inherit` function is where the prototype inheritance magic happens

{% highlight js %}
function inherit(proto){
    if (Object.create){
        // uses the ES5 Object.create method
        return Object.create(proto)
    }else if({}.__proto__){
        // uses the non-standard __proto__ property
        var ret = {}
        ret.__proto__ = proto
        return ret
    }else{
        // fallback to using a constructor if
        // neither of the above are available
        var f = function(){}
        f.prototype = proto
        return new f()
    }
}
{% endhighlight %}

It looks a little crazy because we are using feature detection to determine which of 3 ways to use.

Initialization
--------------

But what about constructors (a.k.a initializer method) ? How do you share initialization code between instances of objects? In the cases where all you are doing is setting a couple of properties, an initializer method is not necessary, as seen in the above examples. But if you have more code initialization code, you might just use a convention such as: a method called "initialize" is an initializer. Let's say you have an `initialize` method defined in `Dude`

{% highlight js %}
var Dude = {
    initialize: function(){
        this.greetingCount = 0
    }
    , greet: function(){
        console.log('Hello, I am ' + this.name + '.')
        this.greetingCount++
    }
}
{% endhighlight %}

Then, to initialize an object you would do

{% highlight js %}
var felix = clone(Dude)
felix.name = 'Felix'
felix.initialize()
{% endhighlight %}

or alternatively

{% highlight js %}
var felix = { name: 'Felix' }
felix.name = 'Felix'
augment(felix, Dude)
felix.initialize()
{% endhighlight %}

or alternitively still

{% highlight js %}
var felix = inherit(Dude)
felix.name = 'Felix'
felix.initialize()
{% endhighlight %}

Closing Thoughts
----------------

I claim that with the three functions defined above - `augment`, `clone`, and `inherit` - you can do anything  you might want to do with objects - without using any constructors or the "new" keyword. I also think that the semantics embodied by these functions are simpler and closer to Javascript's underlying object system.

</content>
        </entry>,<entry>
            <title>Better TDD Workflow via Exclusive Tests in Jasmine and Mocha</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/09/12/better-tdd-workflow-via-exclusive-tests-in-jasmine-and-mocha">
            <updated>2012-09-12T04:00:00.000Z</updated>
            <id>http://tobyho.com/2012/09/12/better-tdd-workflow-via-exclusive-tests-in-jasmine-and-mocha</li>
            <content type="text">
*This unit testing tip brought to you by Andy Murray: congrats Andy on winning your first grand slam title!*

The Problem
-----------

Once you do test driven development at a scale that's beyond the smallest of projects, your test suite's runtime will inevitably grow. Best practices say that you should do everything in your power to keep the runtime low, because if it takes a long time to run your tests, chances are you are not going to want to run them. Making the majority of the tests tests of small isolated units (that's why we call them *unit tests*) - sometimes with the help of mock objects - will do a lot to help your test suite's runtime. 

Still, it is hard to avoid long runtimes. Because

1. Integration tests are necessary, even though they should not be the majority of your tests.
2. It's simple mathematics: the more tests you have, the longer they will take to run. I have never seen the test suite of any project of significant size run under one second.

The Importance of the Runtime for TDD
----------------------------------------

When you are doing TDD, you are constantly re-running the tests to guide what to do next. Because of that, every second you can shave off of your runtime will speed up your workflow noticeably: *every second counts*. How much? Okay, let's say if you can reduce the test suite's runtime from 10 seconds to 1 second; and it takes you on the average of 5 seconds in between - the time it takes for you to think and edit the code between test runs. The total duration of your write->run loop has been reduced from 15 seconds to just 6 seconds, and so you've just increased your productivity by 2.5 times.

Breaking it Down
----------------

*Now, what if I told you that you can have ***sub-second*** runtime during your TDD workflow at all times, no matter how big your project gets?*

How? Simple: by running only a subset of the tests in the test suite. What's that? The title of the article already gave it away? Well, *shoot*!

Of course, which subset of the test suite you want to run depends on the module you are working on. If you are working on `moduleA`, then you probably want to run `test_moduleA`. Sometimes you may even want to only run one test: this is particularly useful when trying to isolate a bug. But, this technique is nothing new. It's been done&trade;, and I've seen different people do it different ways:

1. for command-line test runners: you specify a specific file or module or function to run on the command line
2. if you are code-editor-savvy, you bind a hot key to the test runner, and change the specificity of the runner command that's currently bound to the hot key as you want
3. if you are even more savvy, you write a text editor extension (or grab one someone else made) which figures out what tests to run based on where your cursor is in your editor. For example, if your cursor were in the function `test_foo_bar`, and you hit a certain hot key, then it would run only the test: `test_foo_bar`.
4. if you use an IDE like Eclipse, you can right click on your code, and click on a menu item like "run this test" and it will only run that individual test.
5. if you are using an in-browser testing framework like Jasmine, the test reporter generates a nice HTML report with links. You can click on these links to drill down and run only an individual test or sub-suite.

The technique I use with my Javascripts isn't any of these - and *that's* what I want to talk about. For the lack of a better name, it is called *exclusive tests*.

Exclusive Tests
---------------

Exclusive tests is *source-based* - in that to change the subset of the suite you want to run, you have to edit the source code to do it. 

### `ddescribe` and `iit` for Jasmine

For Jasmine, there is [ddescribe and iit](https://github.com/pivotal/jasmine/pull/181). With this fork of Jasmine, when any `ddescribe` is registered, only specs withing these exclusive suites will be run

{% highlight js %}
describe('normal', function() {
  ddescribe('exclusive', function() {
    // all specs here will be run
  });

  // nothing here will run
  it('should not run', function() {});
});
{% endhighlight %}

When any `iit` is registered, only these exclusive specs will be run (precedence over ddescribe) 

{% highlight js %}
it('should not run', function() {});
iit('should run', function() {});
it('should not run 2', function() {});
iit('should run as well', function() {});
{% endhighlight %}

The `ddescribe` and `iit` fork has not yet made it into Jasmine core, hopefully this will change in the future. But until then, you can peruse [the fork](https://github.com/vojtajina/jasmine) and you can get the pre-built source at <https://raw.github.com/vojtajina/jasmine/ddescribe-iit-build/lib/jasmine-core/jasmine.js>

### `describe.only` and `it.only` for Mocha

`ddescribe` and `iit` just recently landed in [Mocha](http://visionmedia.github.com/mocha/). Only it's been renamed to `describe.only` and `it.only`, which while is more verbose, makes 100% more sense. Plus, for Mocha, you can use it with non-bdd dialects too, i.e. `suite.only` and `test.only`.

The Workflow
------------

With exclusive tests, the workflow goes like this

1. Edit the test file for the module you want to work on to narrow it down to only running tests for that module.
2. Sometimes, you may use `iit` or `it.only` to restrict it down to one test to debug a particular problem, but you revert back once you are done fixing the problem.
3. When you are ready to commit, you *always* revert the exclusive test declarations so that 1) you see that you hadn't broken anything unexpectedly, and 2) the final checked-in version of the code will run the full test suite. 

Check Before You Commit
-----------------------

> What if you forget to revert and accidentally check-in the exclusive test declarations?

That's actually happened to me a few times. So, to prevent that from happening again, I use pre-commit git hooks to run a grep on the source code to make sure I don't check that in by accident. FWIW, here's my [pre-commit hook](http://codeinthehole.com/writing/tips-for-using-a-git-pre-commit-hook/) script that does that

{% highlight ruby %}
#! /usr/bin/env ruby

commands = [
    'grep -n ddescribe test/tests.js',
    'grep -n iit test/tests.js',
    'grep -n debugger $(find test -name "*.js")',
    'grep -n "console.log(" $(find src -name "*.js")',
    'grep -n debugger $(find src -name "*.js")',
]

commands.each do |command|
    output = `#{command}`
    if output.size > 0 then
        puts "*** ABORT COMMIT ***"
        puts command
        puts "#{output}"
        exit 1
    end
end
{% endhighlight %}

It's written in Ruby: *I find that 9 times out of 10 if I start writing a shell script, I end up writing it in Ruby.* The ruby should be pretty self explanatory: I have set up an array of grep commands to be run pre-commit (the command inside upticks actually runs the command and returns its output), if any of them return any output (and therefore something was matched), then we abort the commit by exiting with code 1. *Bonus: you will also notice that I have grep commands that prevent accidentally leaving `debugger` and `console.log` statements in my code.*

Advantages
----------

How is this technique better than the other methods I've listed of narrowing your test suite? 

1. **It's all about speed!**: you don't have to leave your editor to do it - just *edit and save*. This works especially great when you have a tool that reruns your tests on file-save (like [testem](https://github.com/airportyh/testem)).
2. **Text-editor agnostic**: this technique works independent of your choice of editor and therefore can be easily be shared among a team of different backgrounds/tastes.

Discussion: Is This Bad?
------------------------

Up to this point, I suspect that I have rubbed some of you the wrong way: this whole business of putting your code into a *temporary state* and then having to revert it back probably seems unnatural - is this *bad*? After all, this is the reason most test frameworks/runners opt-for using something that's external to the source code - the command-line, the IDE, the browser, etc.

*There are two opposing viewpoints here.* The **first viewpoint** is that the source code is sacred - it's an artifact. you are not supposed to just change it willy-nilly, it's your secret sauce, you've spend probably countless hours debugging it, and you don't want to risk accidently screwing it up. Debugging is hard.

The **second viewpoint** is that in order to remain agile and stay in control of your code base, you must constantly be flexing your coding muscles: *the worst thing that could happen is being afraid to make changes to your code* - at which point your code is in danger of slipping into legacy code status. Unit tests and pre-commit hooks and other checks you put in place act as a safety net to elevate your bravery.

So, if your opinion aligns more with the first viewpoint, then exclusive tests are probably not for you, but if you subscribe to the second viewpoint, then writing transient code probably isn't at all a big deal.

References
----------

* [ddescribe, iit for Jasmine](https://github.com/pivotal/jasmine/pull/181)
* [Mocha Exclusive Tests](http://visionmedia.github.com/mocha/)
* Prior art: [Cedar's Focused Specs](https://github.com/pivotal/cedar#focused-specs)

</content>
        </entry>,<entry>
            <title>Testem CI Mode Screencast</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/09/03/testem-ci-mode">
            <updated>2012-09-03T04:00:00.000Z</updated>
            <id>http://tobyho.com/2012/09/03/testem-ci-mode</li>
            <content type="text">
Hello all! Here's another screencast on [Testem](https://github.com/airportyh/testem). This one is on the *continous integration (CI)* mode. 

What is CI?
-----------

Continous integration is something that is great to do once you've gotten comfortable with the basics of TDD. With CI, you setup a separate machine - usually called the *CI server* - to run your tests automatically every time new code is checked in. If tests fail, the CI machine can be setup to notify members of the team by email. Once you set up the CI server, it's *set it and leave it*. CI takes test automation one step further and makes running your tests an even more frequent occurrence. 

But Do You Really Need CI?
--------------------------

Let's be the devil's advocate for a second.

> Why do you need CI if you already make your tests green before you check in code?

It's true that if you make passing the tests a prerequisite to committing code, CI is not as critical. However, there are at least two situations where CI is helpful.

### \#1: If not every member in your team is test conscious

A common situation is that not everyone in your team is on board with TDD yet and you are trying to champion it. Another is that some members will simply never get into TDD, maybe because they are already set in their ways or they don't really consider themselves developers - for example, designers often work in the same codebase with developers. CI will help you catch breakage introduced by these folks early.

### \#2: If you are coding for many platforms

When you are developing software for multiple platforms, whether it's Mac/Windows/Unix, Playstation/XBox/Wii, or IE/Firefox/Safari/Chrome, it's impractical to expect developers run their tests on each target platform before committing, this is where CI **really shines**.

The CI Mode
-----------

Testem has a CI mode - which rather than giving you a full-blown UI, simply launches each browser in succession and outputs the test results in the [TAP](http://en.wikipedia.org/wiki/Test_Anything_Protocol) format. There are already TAP plugins out there for popular CI servers like [Jenkins](http://jenkins-ci.org/) and [Teamcity](http://www.jetbrains.com/teamcity/) which parse the TAP output and format them into nice web pages, and so Testem can be straightforwardly integrated with them.

The Screencast (4:24)
---------------------

Without further ado, here's the screencast

<div class="video">
    <iframe width="640" height="360" src="http://www.youtube.com/embed/Js16Cj80HKY" frameborder="0" allowfullscreen></iframe>
</div>

More Info
---------

For more info checkout the [docs on CI](https://github.com/airportyh/testem#continuous-integration-mode).
</content>
        </entry>,<entry>
            <title>Testem 0.1.0 Released and Screencasts</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/08/29/testem-intro-screencast">
            <updated>2012-08-29T04:00:00.000Z</updated>
            <id>http://tobyho.com/2012/08/29/testem-intro-screencast</li>
            <content type="text">
I have been working pretty hard at updating [Testem](https://github.com/airportyh/testem) and is happy to announce a new release. Here are some new features

1. Auto-launch browsers - you can now have it automatically launch browsers for you
2. Custom Launchers - you can configure your own launchers, which will enable you to...
3. Run tests in [Node](http://nodejs.org/)! Yeah, this feature seems an obvious one to leave out from the initial release, but we have it now.
4. `console.log` display - all your `console.log` and `console.error` messages will now be display in real-time in the Testem UI.

I am redoing screencasts to showoff these new features and just to update the old one. I am breaking them up into 3 or 4 screencasts because there's a lot of stuff to cover.

Introductory Screencast (11:39)
-------------------------------

I am going to start off with a new introductory screencast, which shows me doing a [string calculator kata](http://osherove.com/tdd-kata-1/). This showcases the basic TDD workflow, also auto-launching a browser, and console-logging messages.

<div class="video">
    <iframe width="640" height="360" src="http://www.youtube.com/embed/-1mjv4yk5JM" frameborder="0" allowfullscreen></iframe>
</div>

Launchers Screencast (12:10)
----------------------------

I also made a screencast specifically about the newly architected launchers feature. The idea of a launcher is that a launcher can either launch a browser process, or it can launch any *arbitrary* process - which communicates with Testem by writing to `STDOUT` and `STDERR`. You can configure Testem to auto launch these launchers for you either in the config file or on the command line. This is the mechanism by which you can run Javascript tests in Node: there are examples of that in the screencast.

<div class="video">
    <iframe width="640" height="360" src="http://www.youtube.com/embed/Up0lVjWk9Rk" frameborder="0" allowfullscreen></iframe>
</div>

Feedback
--------

Please leave feedback in the comments or on [Github Issues](https://github.com/airportyh/testem/issues?state=open).</content>
        </entry>,<entry>
            <title>Taking Over console.log</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/07/27/taking-over-console-log">
            <updated>2012-07-27T04:00:00.000Z</updated>
            <id>http://tobyho.com/2012/07/27/taking-over-console-log</li>
            <content type="text">
Let's say you want to intercept all calls to `console.log`, `console.warn`, and `console.error`, do something sneaky, and then proxy the call back to the original methods so that the messages get printed out as normal and no one ever has to notice. How would you do that?

Attempt #1
----------

If you are a seasoned Javascript programmer, you would probably go to [monkeypatching](http://en.wikipedia.org/wiki/Monkey_patch) and maybe write something like

{% highlight js %}
function takeOverConsole(){
    var original = window.console
    window.console = {
        log: function(){
            // do sneaky stuff
            original.log.apply(original, arguments)
        }
        , warn: function(){
            // do sneaky stuff
            original.warn.apply(original, arguments)
        }
        , error: function(){
            // do sneaky stuff
            original.error.apply(original, arguments)
        }
    }
}
{% endhighlight %}

This works on all browsers except for IE. On IE, `console.log` is implemented as a native method, and as such doesn't support the `apply` method. This is illustrated if you try to run the following in IE

{% highlight js %}
> console.log.apply(console, ['blah']) 
"Object doesn't support property or method 'apply'" 
{% endhighlight %}

Attempt #2
----------

*What to do?* Well, for the case of `console.log`, we can punt on passing through the variable length arguments exactly as they are, because we already know what the `console.log` is going to do with them: join them. Actually the way the join happens varies by browser, but let's just do everyone a favor and make them consistent here by joining them with a space as the separator. Long story short, I ended up with

{% highlight js %}
function takeOverConsole(){
    var original = window.console
    function handle(method, args){
        var message = Array.prototype.slice.apply(args).join(' ')
        // do sneaky stuff
        if (original) original[method](message)
    }
    window.console = {
        log: function(){
            handle('log', arguments)
        }
        , warn: function(){
            handle('warn', arguments)
        }
        , error: function(){
            handle('error', arguments)
        }
    }
}
{% endhighlight %}

This is works everywhere that I have tested, but there is one big flaw - the console object in Chrome and Firebug has more features than just `log`, `warn` and `error`: there're useful things like `console.profile`, `console.timeStamp`, `console.trace`, and lots more. My code effectively removes these extra features - not very gentlemanly.

Attempt #3
----------

So, perhaps instead of replacing the `console` object, we should just replace the individual methods we want to intercept. I came up with this

{% highlight js %}
function takeOverConsole(){
    var console = window.console
    if (!console) return
    function intercept(method){
        var original = console[method]
        console[method] = function(){
            var message = Array.prototype.slice.apply(arguments).join(' ')
            // do sneaky stuff
            original.call(console, message)
        }
    }
    var methods = ['log', 'warn', 'error']
    for (var i = 0; i < methods.length; i++)
        intercept(methods[i])
}
{% endhighlight %}

But this broke on IE again, on the line `original.call(console, message)`. The function's `call` method, like `apply`, is not supported by `console.log`. However, curiously - unlike the other browsers - it can be called directly without having its context set to `console`, so we can say

{% highlight js %}
original(message) // this works on IE but breaks on Chrome
{% endhighlight %}

So the solution as is so often the case is to do one thing on normal browsers, and do another on IE.

{% highlight js %}
function takeOverConsole(){
    var console = window.console
    if (!console) return
    function intercept(method){
        var original = console[method]
        console[method] = function(){
            var message = Array.prototype.slice.apply(arguments).join(' ')
            // do sneaky stuff
            if (original.call){
                // Do this for normal browsers
                original.call(console, message)
            }else{
                // Do this for IE
                original(message)
            }
        }
    }
    var methods = ['log', 'warn', 'error']
    for (var i = 0; i < methods.length; i++)
        intercept(methods[i])
}
{% endhighlight %}

So that's how it's done! Or not: *if you find a flaw in my code, please let me know in the comments!*

*Update: Attempt #4*
--------------------

*Thanks to Jordan Reiter's comment*

> console.log does not really just concatenate; at least, it doesn't in Firefox, Safari, and Chrome. It keeps them as the objects, so you can expand them and see their children. It'll be immediately obvious that something has been changed. Fix is really easy, though -- IE *does* concatenate, so use original(message) for IE and original.apply(console, arguments) for Safari, Firefox, Chrome, etc. and then it will be undetectable.

Great catch, Jordan! The *improved* version is:

{% highlight js %}
function takeOverConsole(){
    var console = window.console
    if (!console) return
    function intercept(method){
        var original = console[method]
        console[method] = function(){
            // do sneaky stuff
            if (original.apply){
                // Do this for normal browsers
                original.apply(console, arguments)
            }else{
                // Do this for IE
                var message = Array.prototype.slice.apply(arguments).join(' ')
                original(message)
            }
        }
    }
    var methods = ['log', 'warn', 'error']
    for (var i = 0; i < methods.length; i++)
        intercept(methods[i])
}
{% endhighlight %}
</content>
        </entry>,<entry>
            <title>Building a Text-Based UI with Backbone and Charm</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/07/19/backbone-charm-text-based-ui">
            <updated>2012-07-19T04:00:00.000Z</updated>
            <id>http://tobyho.com/2012/07/19/backbone-charm-text-based-ui</li>
            <content type="text">

*I am a little framework averse.*

When I write a program, I like to build from scratch as far as it is practical. Not using a framework gives me the feeling that I am *so* in control of my own destiny. But having said that, I will sometimes succumb to using a framework when it's very clear that the use of the framework will result in 

1. significantly less code, and/or
2. significantly less complexity

I recently rewrote a text-based user interface using [Backbone](http://backbonejs.org/), and as far as I know, that is a framework. This is story of how that all went down.

The Problem
-----------

I was working on the user interface for [Testem](https://github.com/airportyh/testem) - a test runner for Javascripts written in [Node](http://nodejs.org). The UI looks like this (press "Play")

<div class="video">
    <iframe frameborder="0" allowfullscreen width="660" height="400" src="http://play.codestre.am/embed/b10afe825bf004d881c7ab0d0"></iframe>
</div>

The most interesting aspect of the UI is the tabbed interface. Each tab represents a browser, which may currently be running tests inside of it. It displays the name and version of that browser, and a test result summary - the number of tests passed vs the number of tests ran in total. The test summary updates in real-time as the test results are coming in from the browsers, and there is a little spinner widget next to the summary while the tests are being run. The panel just below the tabs is a text panel that shows any failed tests and their associated error messages or just a message saying that all tests have been passing or passed if that is the case. 

Here are some of the events the tab interface will have to handle

* when a new browser connects, add and render a new tab
* when a browser disconnects, remove its tab - potentially having to update the location of the tabs that come after the removed tab
* when a browser sends in a new test result, update the tab display to reflect it
* If the user changes the window size of the terminal, re-layout and re-render the entire app
* On each tab for which the browser is currently running tests, display an animated spinner, stop the spinner when the test suite has finished
* when the user switch tabs using the arrow keys, update the display to represent the current tab's display, and also update the text panel's text to the text out point of the new current browser's text display

In short, the UI is very event driven.

The "Before"
------------

First, I will get you acquainted with a piece of the code before the rewrite has taken place. But before that you'll need just a little background on a library called Charm.

### Charm

The text-based UI was written using Substack's excellent [Charm](https://github.com/substack/node-charm) library. In the old days, to code a terminal-based UI, you would use the curses library. There *is* a [curses binding](https://github.com/mscdex/node-ncurses) for Node, which I did use initially for this project, but the problems with using curses are the long compile time - which kills the user install experience, and the non-support for Windows. Charm is a dream because 1) it's just a couple hundred lines of Javascipt, 2) it works on Windows, and 3) it works great.

About 90% percent of the things I am going to do with Charm consists of two simple steps.

1. positioning the cursor at a specified position in the terminal using `charm.position(col, row)`
2. write out some text at the cursor using `charm.write(str)`

And that's it! There're other methods like to change the text color or display attributes, but those will be straightforward to follow along.

### Moving On

At this point, I had one method responsible for rendering each general section of the UI, which are illustrated below

<div class="image">
<img alt="Before UI Methods" src="/images/backbone-charm-text-based-ui/before_diagram.jpg">
</div>

These methods are also responsible for updating the part of the view they take up, so most of them take the approach of either clearing the canvas first and then render, or simply to pad spaces up to the end of the terminal for the empty areas so that any old text within them will get overwritten. Let's dive into the code a little bit, here are some code snippets from `renderTabs()`

{% highlight js %}
this.blankOutLine(4)
this.blankOutLine(5)
this.blankOutLine(6)
{% endhighlight %}

this code blanks out lines 4, 5, and 6 in the terminal - the lines which the tabs occupy on the screen - to get rid of any text that might have been there before. The implementation of `blankOutLine()` is simple

{% highlight js %}
...
blankOutLine: function(line){
    charm.position(0, line)
    charm.write(Array(this.cols + 1).join(' '))
},
...
{% endhighlight %}

Basically, `blankOutLine` moves to the beginning of said line, and blanks it out by writing out the exactly number of spaces that span the width of the terminal. 

Then on the line just below those 3 blanked lines, it draws a horizontal line compositing of the character `━` across the entire screen - this is to draw the tab line for all the tabs that are deselected. 

{% highlight js %}
charm.position(1, 7)
charm.write(Array(this.cols).join(Chars.horizontal))        
{% endhighlight %}

We now have a horizontal line, but no tabs. To actually make tabs, it iterates through the array of browsers and draws a tab for each of them

{% highlight js %}
browsers.forEach(function(browser, idx){
    // render tab content for this browser
    ...
})
{% endhighlight %}

With this loop, the code to draw the tab starts by calculating from what column in the terminal we should start drawing for this particular tab, based on the index, which we are calling `idx`

{% highlight js %}
    var colWidth = this.colWidth()
      , startCol = colWidth * idx + 1
{% endhighlight %}

The first thing to render is the browser name - which will be written on line 5. It also sets the color to the color we want - red for failed, green for passing, and then also setting the display setting to `bright` for the selected tab, and then finally, writes out the browser name to the screen while padding the string to the full width of the tab - I am using this [pad function](http://jsfromhell.com/string/pad)

{% highlight js %}
    charm.position(startCol, 5)
    var color = this.colorForTab(browser)
    if (color) charm.foreground(color)
    if (selected) charm.display('bright')

    // write browser name
    var str = pad(browser.name || '', this.colWidth(), ' ', 2)
    charm.write(str)
{% endhighlight %}

The next thing to render are the test result summary. That and a little spinner widget when the tests are running - which is informed by `!browser.results.all` (the "all" stands for "all results are in"). 

{% highlight js %}
    if (browser.results)
        str = browser.results.passed + '/' + browser.results.total
    else
        str = 'N/A'
    if (!browser.results.all){
        var spinnerIdx = browser.spinnerIdx
        str = '  ' + str + ' ' + this.spinnerChars[spinnerIdx++]
        if (spinnerIdx >= this.spinnerChars.length){
            spinnerIdx = 0
        }
        browser.spinnerIdx = spinnerIdx
    }else{
        str = '  ' + str + ' ' + (
            browser.results.failed > 0 ? Chars.fail : Chars.success)
    }
    charm.position(this.colWidth() * idx + 1, 6)
    charm.write(pad(str, this.colWidth(), ' ', 2))
{% endhighlight %}

Don't worry if you don't understand everything that's going on, just following the general gist is good enough. 

Lastly there is one more step - drawing a border for the selected tab using box drawing unicode characters. That part I'll leave to your imagination, but it's basically more of the same: positioning the cursor at the right places and writing out the characters.

This is a very simplistic way to render the tabs. I am a proponent of *do the simplest thing that could possibly work* - and this worked. There *was* a problem though: because all the tabs are drawn at the same time, all of the tabs get redrawn everytime any of the browser test results changed, so it's a bit inefficient. On top of that, because 1) on every update the background is cleared before redrawing, and 2) the test results come in very frequently when the tests are running, this resulted in flickering - the kind that's unwanted. This is when I decided to rewrite this UI rendering code using the MVC architecture.

Why MVC?
--------

MVC(Model-View-Controller) is a great fit for this problem because of the eventful nature of this UI - there are many different types of event occuring in the UI, and each different event type could cause a different part of the UI to update. For example

* When new test results come in from a browser, it should need to update the test result summary on that browser's tab, but nothing else
* When the user switches tabs from one browser to another using the arrow keys, it should need to update the display of the newly selected tab to look like the selected tab, and revert the display of the previously selected tab to look deselected, but it needn't update the actual contents of those tabs

MVC is a pattern that allows you to handle fine grained update rules like these in a straightforward manner.

### Models and Views

First let's start with the *models* and the *views*. *Models* are the domain objects in the problem space - in our problem, that would be the browsers and their associated test results. *Views* are the visual representations of the models, and usually this is a 1-to-1 mapping: one view for representing one model. The view is responsible for drawing the part of the UI that represents its model, and while doing this it will ask the model for information that it needs. 

But, the big idea in MVC is that the view listens for changes on its model, so when the information in the model changes, it will notify its view via a *change event* - which will in turn update the display to reflect correctly the new state of the model.

In our example, the browsers and their associated test results are the models. When new browsers are added, or when test results for a browser changes, the associated UI views must update to reflect the changes.

### C for Controller

The other kind of event is *external events* - such as user input via the keyboard, browsers connecting and disconnecting, and more (we actualy made an extensive list of these earlier). Some of these events may result in updates to the model objects, which would in turn trigger UI display updates. The job of the *controller* is to handle these events do it in a sane way. Usually, this is just a bunch of logic that takes the form of: when event X happens, do Y. Often times this logic is just written in an ad-hoc manner, other times they are written inside the views, still other times, they are separated out into a separate module.

Enter Backbone.js
-----------------

It seems a lot of people are in love with Backbone. I am a bit indifferent - like I said, I am framework averse. Nevertheless, I decided to give it a go because

1. everyone is talking about it and I feel left out - it's the same thing you'd feel if you missed the movie that everyone is talking about
2. it is lightweight, and does everything that I need. Although I could do MVC from scratch, the result probably won't have any palpable advantage vs using Backbone

The "After"
-----------

So, I set out to build this using Backbone. The first thing to do was to use Backbone's models to rewrite my models - which used to be plain ol` Javascript objects.

### My Models

When you inherit your own model objects from `Backbone.Model`, your objects will gain the ability of automatically notify other interested objects whenever its attributes change.

I have two central model objects

1. `BrowserClient` - which represents a browser that's connected to Testem
2. `TestResults` - which belongs to the `BrowserClient` and represents the current tests results associated to a `BrowserClient`. 

In Backbone, you make a subclass of `Backbone.Model` by calling `Backbone.Model.extend()`, like so

{% highlight js %}
var BrowserClient = Backbone.Model.extend({
    initialize: function(attrs){
        this.set({
             name: null
             , results: new TestResults
        })
    }
})
{% endhighlight %}

We've added an `initialize` method which in Backbone is the initialiser - it gets called when an instance is created initially. In there, we simply instantiate a couple of properties: `name` and `results`. Notice that we use the `set` method of `Backbone.Model` to set attributes rather than setting them directly on the object as properties, this is what allows Backbone to do its thing. To see it in action, you can create an instance of `BrowserClient` and then register a property change listener by listening on the event `change:name`

{% highlight js %}
var browserClient = new BrowserClient
browserClient.on('change:name', function(){
    console.log('You changed the name to ' + browserClient.get('name'))
})
{% endhighlight %}

At this point the callback function will be called anytime the `name` attribute of `browserClient` is changed.

Similarly, we have a second model called `TestResults`, which has the attributes `passed`, `failed`, `total`, among others

{% highlight js %}
var TestResults = Backbone.Model.extend({
     initialize: function(){
          this.set({
               passed: 0
               , failed: 0
               , total: 0
          })
     }
})
{% endhighlight %}

### My Views

The UI in Testem is composed of several different components, so I broken them down to different view objects.

<div class="image">
    <img alt="Views" src="/images/backbone-charm-text-based-ui/views.jpg">
</div>

The `AppView` is the top level view of the entire UI, handles drawing the title and instructions at the top and the bottom help instructions, and then it delegates the stuff in the middle to the `BrowserTabs` view object. `BrowserTabs` is responsible for drawing all the tabs (including the log panels within them), but delegates the drawing of each individual tab to a `BrowserTab` - `BrowserTabs` inherits from `Backbone.Collection`, which is nice because it automatically notifies listeners when an item is added or removed.

Traditional Backbone apps - if I can call them that - make use of Backbone's base view class `Backbone.View`. I cannot use `Backbone.View` because it is designed to work with the DOM, and I don't *have* a DOM. So, instead I've created my own base `View` class which all of my UI views inherit from. 

For the next code examples I will focus on the views that handle rendering the browser tabs. I made two classes: `BrowserTabs` - which is a `Backbone.Collection` but also acts as a composite view of all the tabs and `BrowserTab` which handles the rendering of a single tab.

#### Backbone.Collection

`Backbone.Collection` deserves some explanation: it is a special kind of model that contains a collection of models. Functionally it acts more or less like an array, but in addition, it gives you automatic notification to its listeners when new items are inserted to or removed from the collection, as the example below demonstrates

{% highlight js %}
var myCollection = new Backbone.Collection
myCollection.on('add', function(newItem){
    console.log('You added a new test result!')
    console.log(newItem)
})
myCollection.add(new TestResult)
{% endhighlight %}

#### BrowserTab

The `BrowserTab` is the view that is responsible for rendering a single browser tab, but it is also responsible for handling the various events that requires it to update the display of the tab, so the controller logic is embedded inside the view. Some maybe say this is not pure MVC, and that's okay - I am not big on purity.

{% highlight js %}
var BrowserTab = View.extend({
    initialize: function(attributes){
        var self = this
        var browser = this.browser = attributes.browser
        browser.on('change:name', function(){
             self.renderBrowserName()
        })
    },
    ...
    renderBrowserName: function(){
        ...
})
{% endhighlight %}

The above is a glimpse into how `BrowserTab` works. There is a `renderBrowserName` method which renders just the browser name on the tab. To ensure the name is always up-to-date, `BrowserTab` registers a listener on the `change:name` event so that it re-renders the browser name every time it is changed.

What's that? You want to see the implementation of `renderBrowserName`? (Sigh)...Okay...

{% highlight js %}
renderBrowserName: function(){
    var index = this.get('index')
      , col = this.col + index * width
    ...
    charm
        .position(col + 1, line + 1)
        .write(pad(browserName || '', width - 2, ' ', 2))
        .display('reset')
}
{% endhighlight %}

I've simplify the code down to the essiential. The `BrowserTab` object has an `index` attribute which corresponds to its position in the list of tabs, starting with 0 for the leftest tab. Keeping this `index` attribute up-to-date is the job of `BrowserTabs`. Based on this `index`, `BrowserTab` knows how to calculate the starting column `col` from where to draw itself.

Let's keep going. The next thing that needs to be rendered on the tab is the test result summary plus a little spinner widget on the same line. The following methods are of interest

* `renderResults` - renders the second line of the tab header, which includes the test summary and the spinner widget
* `startSpinner` - starts spinning the spinner
* `stopSpinner` - stops the spinner

For this case, because there's some animation going on, in order to keep the animation smooth I need to re-render the text at regular intervals instead of simply updating whenever the test results change. So we go to our trusty `setTimeout`. `startSpinner` looks like this

{% highlight js %}
...
startSpinner: function(){
    // stop the spinner just in case it's still running
    this.stopSpinner()
    var self = this
    // "Async Loop" pattern to repeatedly call the `renderResults` method every 150ms
    function render(){
        self.renderResults()
        self.setTimeoutID = setTimeout(render, 150)
    }
    // Kick off the loop
    render()
}
...
{% endhighlight %}

The main part of this method is the [async loop](http://tobyho.com/2011/11/03/delaying-repeatedly/) that calls `renderResults` every 150ms. `renderResults` knows to rotate through 4 different spinner characters so that the user see a spinner effect. `stopSpinner` is simply clearing the last timeout ID.

{% highlight js %}
...
stopSpinner: function(){
    if (this.setTimeoutID) clearTimeout(this.setTimeoutID)
}
...
{% endhighlight %}

When do `startSpinner` and `stopSpinner` get called? Well, see this code

{% highlight js %}
var BrowserTab = View.extend({
    initialize: function(attributes){
        var self = this
        var browser = this.browser = attributes.browser
        ...
        browser.on('tests-start', function(){
            self.startSpinner()
        })
        browser.get('results').on('change:all', function(){
            self.stopSpinner()
            self.renderResults()
        })
    },
    ...
})
{% endhighlight %}

The `BrowserClient` object actually emits a custom event `tests-start` when the tests start running. So, we setup a listener on that event and call `startSpinner` in response. For stopping, I know that the `results` object's `all` attribute gets changed to true when all test results have come in, so I can register to listen for the `change:all` event of the TestResults object.

### More on My Base View Class

I mentioned earlier that I wrote my own base `View` class - I want to go into that a little bit too because there are a couple of key insights in there.

#### Stateful Views

The first insight is that for rich UIs, view objects are stateful. Think about the widgets you might find in typical rich UIs: scrollable panels have state - the scroll offset, tabbed panels have state - the selected tab index. These are state that decidedly belong to the view - it wouldn't make sense to store the scroll offset, for example, in the model for most applications. For this reason, my `View` extends `Backbone.Model` - giving it the ability to notify others of its state changes. Examples of view state in my app are the current tab index of the browser tabs; the scroll offset in the log message panel; and the dimension of the terminal - which can be changed by the user by resizing his terminal window.

When you have stateful views, some call them *view-models*, and then they may say the architecture is [MVVM](http://en.wikipedia.org/wiki/Model_View_ViewModel) (Model-View-View-Model) rather than MVC. This is fine, I am not too concerned about what to call things, especially since MVC is such an overloaded term, but I do believe that in general rich UIs have stateful views.

#### Event Handler Cleanup Helper

There are occassions when you have to destroy view objects - usually when you are deleting the view's corresponding model. Destroying views is tedious because you have to take care to remove all of the listeners that it has registered on its model, and anything else. The way I refactored away this tedium is by adding a couple of helper methods on the base `View` class: `observe` and `removeObservers`. I am sure almost every other developer using Backbone has done more or less the same. Here's an example of `observe` in action

{% highlight js %}
this.observe(results, {
    'change': function(){
        var results = self.browser.get('results')
          , passed = results.get('passed')
          , total = results.get('total')
          , allPassed = passed === total
          , topLevelError = results.get('topLevelError')
        self.set('allPassed', allPassed && !topLevelError)
    }
    , 'change:all': function(){
        self.stopSpinner()
        self.renderResults()
    }
})
{% endhighlight %}

This will add event listeners on `results` for the events `change` and `change:all`. All listeners registered using `observe` are removed when `removeObservers` is called.

Here's the full source code for my `View` class

{% highlight js %}
var View = exports.View = Backbone.Model.extend({
    charm: charm
    , observe: function(model, thing){
        var eventMap
        if (typeof thing === 'string' && arguments.length === 3){
            eventMap = {}
            eventMap[thing] = arguments[2]
        }else{
            eventMap = thing
        }
        for (var event in eventMap){
            model.on(event, eventMap[event])
        }
        if (!this.observers)
            this.observers = []
        this.observers.push([model, eventMap])
    }
    , destroy: function(){
        this.removeObservers()
    }
    , removeObservers: function(){
        if (!this.observers) return
        this.observers.forEach(function(observer){
            var model = observer[0]
              , eventMap = observer[1]
            for (var event in eventMap){
                model.off(event, eventMap[event])
            }
        })
    }
})
{% endhighlight %}

#### Computed Attributes

A computed attribute of an object is a synthetic attribute that is computed from a combination of other existing attributes. Backbone does not support this out of the box, so I use a poor man's way of doing this - by manually updating the "computed attribute" whenever the dependent attributes change. For example 

{% highlight js %}
this.observe(results, {
    'change': function(){
        var results = self.browser.get('results')
          , passed = results.get('passed')
          , total = results.get('total')
          , allPassed = passed === total
          , topLevelError = results.get('topLevelError')
        self.set('allPassed', allPassed && !topLevelError)
    }
    ...
})
{% endhighlight %}

This code listens for any changes in the `results` object, and then computes its own `allPassed` attribute - based on several attributes of `results`. The `allPassed` attribute mainly informs whether to render the tab in red or green

{% highlight js %}
...
, color: function(){
    return this.get('allPassed') ? 'green' : 'red'
}
...
{% endhighlight %}

Then later on, I can have a listener on `change:allPassed` which re-renders a part of the screen, which will render it in the correct color

{% highlight js %}
this.observe(this, {
    ...
    , 'change:allPassed': function(){
        self.renderBrowserName()
        self.renderResults()
    }
})
{% endhighlight %}

More Code
---------

That's all the code examples that's fit to print. But if you just can't get enough, you can always see the full source code because Testem is an *open source project*. Check out [appview.js](https://github.com/airportyh/testem/blob/master/lib/appview.js), [browserclient.js](https://github.com/airportyh/testem/blob/master/lib/browserclient.js), and the [project's github page](https://github.com/airportyh/testem) itself. If you want to see the code before the refactor, see the [prebackbone branch](https://github.com/airportyh/testem/tree/prebackbone).

Was It Worth It?
----------------

Rewriting this UI had four main benefits

1. it fixed the pressing issue of *flickering*. Could it have been fixed without this rewrite? Yes, but we have 3 more benefits...
2. keeping the UI display up-to-date is now done much more efficiently because it only updates the parts that are outdated at a fine grain level
3. the code now has better structure. Methods are smaller and grouped into a handful of classes. The objects are more decoupled - meaning that changes in one part of the application is less likely to break or affect something in another part - thus making the project itself easier to work with overall
4. *I know Backbone!!!*

So, yes. I am quite happy with the rewrite. Of course, as usual, you can ask questions in the comments.

</content>
        </entry>,<entry>
            <title>Testem: Interactive JS Test Runner</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/06/24/testem-interactive-js-test-runner">
            <updated>2012-06-24T04:00:00.000Z</updated>
            <id>http://tobyho.com/2012/06/24/testem-interactive-js-test-runner</li>
            <content type="text">
About a week ago I released my Javascript test runner - [Testem](http://github.com/airportyh/testem). It provides a text-based UI and auto-re-run-on-save for the test driven development(TDD) usecase as well as a simple command-line interface for continuous integration (CI). It supports [QUnit](http://docs.jquery.com/QUnit), [Jasmine](http://pivotal.github.com/jasmine/), and [Mocha](http://visionmedia.github.com/mocha/) to boot. To understand how the UI works, you really have to see it in action, I've made a screencast:

<div class="video">
	<iframe width="640" height="360" src="http://www.youtube.com/embed/ZyUN__C3xgY" frameborder="0" allowfullscreen></iframe>
</div>

There's also plenty of info on the Github [README page](https://github.com/airportyh/testem) which should be adequate for getting you started with it.

How I've been Using it
----------------------

I have been using Testem regularly for client work for a few months. I use the TDD mode to add new features and fix bugs to a project that consists of about 2.5k lines of Javascript. I have ~230 tests in Jasmine which takes ~50 seconds to run on Chrome (I know that's quite slow). I use the [odescribe](https://groups.google.com/forum/#!topic/jasmine-js/MV6lkeLRqFE/discussion) branch of Jasmine to easily narrow my tests so that most of the time, my tests run sub-second. On check-in, a Windows Server 2008 EC2 instance running Jenkins will run the tests on IE7, IE8, IE9, Firefox, Chrome and Safari and notify me when there is breakage.

The Tech
--------

Testem was built using [node.js](http://nodejs.org) and along the way of building it I've encountered some very interesting techonology and have had to solve some very interesting problems.

### Text-Based UI

The text-based UI

<div class="image">
    <img alt="Testem Text-based UI" src="https://github.com/airportyh/testem/raw/master/images/red.png">
</div>

has evolved over time and was rewritten at least 4 times. At first the text was simply displayed mostly using `console.log`. There was one trick I used which employed printing a carriage return `/r` to move the cursor back to the beginning of the current line, allowing me to replace the text of the current line:

{% highlight javascript %}
process.stdout.write('Some text')
process.stdout.write('\rSome other text') // 'Some text' will now be replaced
										  // by 'Some other text'
{% endhighlight %}

After that, I decided I wanted a rich UI and so required the full power of ncurses and rewrote it using Mscdex's [node-ncurses](https://github.com/mscdex/node-ncurses). This is when I concieved of the tabbed interface, more or less like what I have now.

Then at some point [Substack](http://substack.net/) wrote [Charm](https://github.com/substack/node-charm) and I rewrote it in that because ncurses takes a long time to compile (for users who have to install Testem), it was a little buggy, and there was no way it was going to work for Windows, and as Substack says, nowadays everyone is ANSI anyway. Charm is *so* lightweight in comparison, it is basically ~300 lines of Javascript.

#### Backbone Rewrite

When I got the UI working and looking the way I wanted, I encountered one more problem: *flickering*. When repainting the tabs, the UI would blank out the space it needs to paint to before painting the text(to get rid of old traces of text), and it refreshed all the tab headers everytime the test results for any browser changed, as a result, I was seeing some unwanted flickering. I decided I needed to use the MVC pattern, where when some state on a model changed (i.e. the test results for a paricular browser), I only have to update the view which represents that model (the tab for that browser). I could have written this on my own, but with all the talk about [Backbone.js](http://backbonejs.org/) I was beginning to feel left out - like how everyone's talking about the new movie that you haven't seen and so you finally give in and go see it. The Backbone rewrite worked out very well, and is what I have stuck with now.

#### Tidbits

Some more interesting tidbits about the UI:

1. The tabs are rendered using [box drawing characters](http://en.wikipedia.org/wiki/Box-drawing_character)
2. The spinners (one on each tab for when tests are running) are rendered using the circular arc unicode characters found on [this page](http://en.wikipedia.org/wiki/Geometric_Shapes) - I stole that from Mocha
3. To support window resizing by the user, the UI queries the terminal size(# of lines and columns) twice every second, and redraws the entire UI if it has changed
3. Because unicode characters does not work by default on Windows, I fall back to ascii characters there. 
4. Although Windows support ANSI terminal codes for the most part, it does not certain features like text scrolling, which I had to work around.

### Server Side

Testem uses [Express](http://expressjs.com/) and [Socket.IO](http://socket.io/) (stables for Node programs) for the HTTP server that serves up the necessary HTML, JS, CSS, and WebSocket goodness require to run the tests in the browser. The serve will basically serve any file in the current directory via HTTP. It sets `Cache-Control` to `No-cache` and ignores headers `if-modified-since` and `if-none-match` in order to avoid the browser caching anything. 

To serve the client side `testem.js` used to integrate with the test framework on the page and report back test results, it concatenates all the required Javascript files on the fly. Why? I am lazy and prefer not to have to worry about a build step.

{% highlight js %}
exp.get('/testem.js', function(req, res){

    res.setHeader('Content-Type', 'text/javascript')

    res.write(';(function(){')
    var files = [
        __dirname + '/../public/testem/socket.io.js'
        , __dirname + '/../public/testem/jasmine_adapter.js'
        , __dirname + '/../public/testem/qunit_adapter.js'
        , __dirname + '/../public/testem/mocha_adapter.js'
        , __dirname + '/../public/testem/testem_client.js'
    ]
    async.forEachSeries(files, function(file, done){
        fs.readFile(file, function(err, data){
            if (err){
                res.write('// Error reading ' + file + ': ' + err)
            }else{
                res.write('\n//============== ' + path.basename(file) + ' ==================\n\n')
                res.write(data)
            }
            done()
        })
    }, function(){
        res.write('}());')
        res.end()
    })
    
})
{% endhighlight %}

### File Watcher

There are some existing file watcher libs out there but I wrote by own because most of them were still not using the fast `fs.watch` at the time that I looked. I am also using `node-glob` to allow specifying glob patterns in your `testem.yml` file. Unfortunately, I found out later that `fs.watch` is [not reliable when using vim to edit the files in question](https://github.com/joyent/node/issues/3172), for that reason, I also use `fs.watchFile` in addition to `fs.watch` as a fallback.

### Browser Launcher

Getting the browser launcher to work for various browsers on various platform was just a tedious process of installing and testing. For some browsers I had to use extra tricks like telling it to create a new user profile directory and then deleting that directory after it's done. To test code on IE7 and IE8, I would use IE9's compatibility mode, but rather than using a `<meta>` tag, I used the `X-UA-Compatible` header, which means I can use the same HTML markup.

I found Caolan's async library to be great for doing mapping and filtering for arrays in an async manner, it dramatically simplified my code browser launcher code.

What's Next?
------------

1. Getting feedback from other folks using Testem in the real world, and then improve the user experience as much as possible.
2. [BrowserStack](http://www.browserstack.com/user/dashboard) integration - after seeing [Bunyip](http://www.thecssninja.com/javascript/bunyip) I was like oh snap! I need to get on this. 

For more go to my [roadmap](https://github.com/airportyh/testem#roadmap)

Other Folks Working on this Problem
-----------------------------------

I am not the only person working on this problem. Actually I am just one of many. Competition is good, and hopefully we'll end up with something great that benefits everyone. Here are other projects that are trying to tackle this

<ul>
<li><a href="http://www.thecssninja.com/javascript/bunyip">Bunyip</a></li>
<li><a href="http://busterjs.org/" target="_blank">Buster.js</a></li>
<li><a href="http://www.testling.com/" target="_blank">Testling</a></li>
<li><a href="http://code.google.com/p/js-test-driver/" target="_blank">JSTestDriver</a></li>
<li><a href="http://swarm.jquery.org/" target="_blank">TestSwarm</a></li>
<li><a href="https://github.com/azer/lowkick" target="_blank">Lowkick</a></li>
</ul>
</content>
        </entry>,<entry>
            <title>3 Ways to Discourage Copy-n-Pasting Code in Teaching</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/04/10/3-ways-to-discourage-copy-n-paste-code">
            <updated>2012-04-10T04:00:00.000Z</updated>
            <id>http://tobyho.com/2012/04/10/3-ways-to-discourage-copy-n-paste-code</li>
            <content type="text">
While chatting with some fellow programmers on the subject of teaching others to program, a great point was brought up by [Marginhound](http://www.marginhound.com/). I don't remember the exact quote, but I'll paraphrase

> Although it is helpful to use existing programs as examples, you should nevertheless type every character yourself, rather than to copy-n-paste.

*Right on!* The reliance on Copy-n-paste-programming is what keeps amateur programmers from getting to the next level. It is also one of the premises of the [Learn Code the Hard Way](http://learncodethehardway.org/) series by Zed Shaw.

Make it Hard
------------

I came home and this idea hit me: *why not make it difficult to copy-n-paste in your teaching materials?* The code should be readable, but hard to copy-n-paste. What are some ways to do that?

Idea #1: Images
---------------

The first idea is obvious - use images. If you try to select the code below, you'd be dragging an image around.

<div style="background-color: #333; margin-left: 0; margin-right: 0">
<img src="/images/code_snippet.png" alt="Code Snippet">
</div>

The disadvantage of using images is that it is harder for the author: you'll have to take a screenshot every time you want to update a code snippet, or some tooling will have to be built.

Idea #2: Invisible Letters for Spaces
-------------------------------------

Replace all space characters in the program with some ugly character such as "@", but hide them by making their color the same as the background color. So, for example if you try to copy this code
<div>
    <style>
        #invisible_letters i{
            color: #333;
        }
    </style>
</div>
<pre id="invisible_letters">
for<i>@</i>(var<i>@</i>i<i>@</i>=<i>@</i>0;<i>@</i>i<i>@</i><<i>@</i>array.length;<i>@</i>i++){
<i>@@@@</i>sum<i>@</i>+=<i>@</i>array[i];
}
</pre>
    
you'll get copious "@" characters in your editor. This technique could be easier to author because you can easily write some Javascript to insert those elements/characters. It could also apply to pdfs, although some tooling will have to be built.

Idea #3: `user-select: none`
----------------------------

Set the [user-select](http://css-tricks.com/almanac/properties/u/user-select/) CSS property to `none` for the container of the code snippet. If this works on your browser, you should not be able to select the text in the following code snippet

<pre style="-webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none">
for (var i = 0; i < array.length; i++){
    sum += array[i];
}
</pre>

This is the easiest technique to use and affects the author minimally. Although the user might still figure out a workaround to copy the text - that's okay - we just want to set a road block, not a barricade. The drawback to this approach is that it is HTML-only and works only on certain newer browsers.

Other Ideas?
------------

I'd love to hear critiques on the techniques presented as well as other better ideas for accomplishing this. Please leave a comment!</content>
        </entry>,<entry>
            <title>My js1k Entry: Making Music with the Audio Data API</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/03/19/my-jsk1-entry">
            <updated>2012-03-19T04:00:00.000Z</updated>
            <id>http://tobyho.com/2012/03/19/my-jsk1-entry</li>
            <content type="text">
I participated in the [js1k](http://js1k.com/) this year, it was lot of fun. I got disqualified for using a Firefox-specific feature though, so I will share my account here because otherwise I would have nothing at all to show for it, which would be very sad.

I've never entered this competition before and so didn't know exactly what to expect, but I thought it would be fun. Each year, there's a different theme. This year's theme is *love*. I brainstormed various ideas and I ended up deciding to write a program that plays a love song - this is actually not easy because the competition rules disallow linking to any asset - no mp3, no wav, no flash. I am a music geek at heart and this appealed to me - also, I happen to be listening to a lot of old-fashioned love songs recently.

Goals
-----

Here are my goals for this competition - what I want to get out of it

- compete and be a part of the JS community
- learn something new
- do something different and cutting edge
- be myself and have fun

Song Choice
-----------

Although I was initially partial to *You Ain't Living' Till You're Lovin'* by Tammi Terrell and Marvin Gaye, I later chose *Unchained Melody* by the Righteous Brothers - every one knows it, it's a pretty song, and also a simpler song - with fewer notes (thus saving me bytes).

Working with the "Enhanced" Audio API
-------------------------------------

I decided to use the Firefox-only [Audio data API](https://wiki.mozilla.org/Audio_Data_API) (currently under review). I knew this was against the rules - the program has to run on all the major browsers except IE. I decided to do it anyway because my idea was *so cool* and also my belief that using this API was the only way to do what I wanted (this turned out not to be true - more on that later).

So, Firefox has a [set of APIs](https://wiki.mozilla.org/Audio_Data_API#Writing_Audio) for writing raw audio data to your speakers. There's `mozSetup(channels, sampleRate)` which tells the `Audio` element how many channels it has (2 for stereo, 1 for mono), and the sampling frequency(44100 for 44.1KHz).

To write data to the buffer you'd use the `mozWriteAudio(buffer)` method and you'd want to pass it a buffer of type `Float32Array`. The whole process might look something like this

{% highlight js %}
var audio = new Audio
audio.mozSetup(2, 44100)
var samples = new Float32Array([0.242, 0.127, 0.0, -0.058, -0.242, ...])
audio.mozWriteAudio(samples)
{% endhighlight %}

Simple, right? *Except it's not.* I first tried to write out the samples for the entire song at once using the `mozWriteAudio` call. This didn't work because it can only write so much data at once - and the method returns you the amount of data samples it wrote, so you can continue from the point it left off the next time you write. What their example(under "Complete Example: Creating a Web Based Tone Generator") tells you to do is to periodically write samples(using an [async loop](http://tobyho.com/2011/11/03/delaying-repeatedly/) up to a fixed-size buffer ahead of the current playhead. You'd use

{% highlight js %}
audio.mozCurrentSampleOffset()
{% endhighlight %}
    
To get the current play head. Then what you'd do is calculate the amount of data you need to write to fill up to your pre-buffer size

{% highlight js %}
var toWrite = audio.mozCurrentSampleOffset() + prebufferSize - writePos
{% endhighlight %}

Where `writePos` is the return value of the last `mozWriteAudio` call you made. The resulting code would be something like this

{% highlight js %}
function writeBits(){
    // toWrite is the amount to write to fill up our pre-buffer
    var toWrite = audio.mozCurrentSampleOffset() + prebufferSize - writePos
    if (toWrite){
        var data = new Float32Array(toWrite)
        for (var i = 0; i < toWrite; i++, writePos++){
            // write your samples to the `data` array here
        }
        audio.mozWriteAudio(data)
    }
    // Feed it data every 100ms
    setTimeout(writeBits, 100)
}

writeBits() // kick off the async loop
{% endhighlight %}

Generating the Song Samples
---------------------------

At first I tried using actual samples of the recordings. I would down-sample a small section of the song and format it into a Javascript array literal. This failed miserably as even when severely down-sampled, the data was still way to big to fit into 1k. The next approach was generating the song notes from sine waves - this is more fun anyways!

### Sine Waves

The formula for generating a sine wave of a curtain frequency should look more or less like

{% highlight js %}
for (var i = 0; i < toWrite; i++){
    buffer[i] = Math.sin(writePos * Math.PI * 2 * freq / sampleRate)
}
{% endhighlight %}

this is for one single frequency, i.e. one note. If you want multiple notes (or tracks) to be playing at the same time, you'd just add the samples all together.

{% highlight js %}
for (var i = 0; i < toWrite; i++, writePos++){
    for (var j = 0; j < notes.length; j++){
        buffer[i] += Math.sin(writePos * Math.PI * 2 * notes[j] / sampleRate)
    }
}
{% endhighlight %}

### Note Representation

When I figured out that I can't just generate the samples for the entire song at once, I decided to go to an event-based approach where for each note I wanted to play I would have a note-on event to start it, and then a note-off event to stop it - at any instant I wound keep track of the current notes that are being played. This is just like the way midi works. So, I would have an event list like

{% highlight js %}
var events = [
    [0, 440],
    [11500, 440],
    [11500, 523.25],
    [22500, 523.25]
]
{% endhighlight %}

Each tuple in the `events` array has two values: a start time(here it's the sample number) and a frequency. I didn't bother encoding whether the event is a note-on or note-off because if the note isn't being played I can assume it's a note-on and vice versa for note-off. One advantage of this format is that supporting multiple notes playing at the same time is trivial.

I started laying out the melody using this format but I quickly found that not only was it not space efficient(I quickly went over the 1k limit), but it was inconvenient from the song writer perspective: I had to make several calculations each time I needed to add or modify a note. Also, it was very hard to move melodies around because all the start times would have to be changed.

Because of these limitations, I rewrote the algorithm to take a format which not only was easier for the song writer, but also would yield much better compression. The new format would consist of an array of tracks, and each track would be an array of notes. A track looks like this

{% highlight js %}
var trackA = [
    [11, 523.25],
    [1, 587.33],
    [12, 523.25],
    ...
]
{% endhighlight %}

The first value of the tuple here is the duration of the note, not the start time, and the second value is the frequency - this enables the writer to move melodies around without having to modify them. The unit of duration is the *triplet*. I chose the triplet because Unchained Melody has a triplet-ized feel - so, the `[12, 523.25]` entry is a whole note, for example, because each measure of a 4/4 signature has 12 triplets.

### Sound Envelope

When I got the song finished and showed it to a friend, he mentioned that he hears some clicking noise at the start of each note. I noticed this too, and it was because the start and end of the sine wave of each note is abrupt. To remove this sound artifact I needed to make sure that the note edges were gradual, i.e. the volume of a note shouldn't go straight from 0 to 5 with no in-between. 

To do this I added a *taper* factor to the beginning and end of each note. But before this, I needed to keep track of for each note that is being played, how long it has been playing for, and how much longer before it ends. I stored this info in a `noteDur` tuple where the first value is the time played so far, and the second value is the time till note-off. So the sample calculation now looks like

{% highlight js %}
buffer[i] = Math.sin(writePos * Math.PI * 2 * notes[j] / sampleRate) *
    (
        (noteDur[0] < taper ? noteDur[0] / taper : 1) *
        (noteDur[1] < taper ? noteDur[1] / taper : 1)
    )
{% endhighlight %}

`taper` is hardcoded to `5000` in unit of samples, which equates to about a tenth of a second for 44.1Khz. This got rid of the sound artifact.

Byte Saving Techniques
----------------------

I am by no means an expert on shaving bytes off of Javascript programs. I first used a naive approach of just making it work first, and then making it fit. 

### Minification

I used [Uglify](https://github.com/mishoo/UglifyJS) to shrink my code - which was performing consistently better than the closure compiler. But, here are a couple of tricks I used in conjunction with the minifier.

#### The Wrap/Unwrap Trick

One good way to evaluate how well your minifier did is to prettify the minified source using [jsbeautifier](http://tobyho.com/2012/03/08/jsbeautifier/). I found that the minifier does't rename global variables, so I wrapped all my code inside of an [iife](http://benalman.com/news/2010/11/immediately-invoked-function-expression/).

{% highlight js %}
!function(){
    // my code
}()
{% endhighlight %}

This got the minifier to rename all the variable names to one character. But, I then remove the iife in the minified source to save me all of 15 bytes!

#### Go to the Dark Side - Get Rid of `var`

When I really got stuck on squeezing out the last few bytes to get it down within the 1k limit, inspiration struck: what if I just got rid of all these `var` statements? It would certainly still work, all the variables would just become globals, *what's the harm in that?* So, in the minified source, I used search/replace to remove all the `var` statements in the program. Of course, then I re-ran the program to make sure it still worked.

### Get Rid of Functions

I found that in all cases that I've encountered, using functions increases file size. So, I removed all functions except where it's absolutely necessary(like for an async loop).

### Get Rid of Variables

Getting rid of any variable that's used only once will save you bytes.

### Try Different Approaches and Compare

If you are unsure if a technique will save bytes, try it and compare with what you have.

### Be Willing to Kill Code

Give up code that's not "pulling its weight". In my case, I used to have a function that translates a note number on the musically scale to it's corresponding frequency. This was overkill as the song didn't really use that many notes and so just using variables as the translation layer worked just as well, and allowed me to get rid of that code.

Results
-------

The code

{% highlight js %}
!function(){
    // note frequencies stored for reuse
    var dol = 523.25
      , re = 587.33
      , mi = 659.26
      , so = 394.995
      , fa = 349.23
      , mib = 311.13
      , la_ = 220
      , ti = 246.94
      , mi_ = mi / 2
      , dol_ = dol / 2
      , la = la_ * 2
      
    // Melody sections
    var sectionA = [
        [11, dol],
        [1, re],
        [12, dol],
        [1, re],
        [1, mi],
        [9, dol],
        [1, dol],
        [8, so],
        [1, so],
        [2, mi],
        [1, re],
        [11, dol],
        [1, re],
        [9, dol],
        [2, mi_],
        [1, fa],
        [24, so]
    ]
    
    var sectionB = [
        [2, fa],
        [2, so],
        [1, la],
        [1, dol],
        [4, ti*2],
        [1, dol],
        [1, ti*2],
        [4, la],
        [1, fa],
        [1, la],
        [6, so],
        [2, fa],
        [2, so],
        [1, la],
        [1, dol],
        [4, re],
        [1, re],
        [1, dol],
        [1, mi],
        [11, so*2]
    ]
    
    var notes = [].concat(sectionA, sectionB, sectionB, sectionA)
    
    // Chords!
    var I = [dol_, mi_, so, mi_]
      , VIII = [la_, dol_, mi_, la]
      , IV = [fa/2, la_, dol_, fa]
      , V = [so/2, ti, re/2, ti]
    
    var compA = [I, I, VIII, VIII, IV, IV, V, V, I, I, VIII, VIII, V, V, V, V]
      , compB = [IV, V, IV, V, IV, V, I, I]
      , comp = []
    ![].concat(compA, compB, compB, compA).forEach(function(chord){
        [0,1,2,3,2,1].forEach(function(i){
            comp.push([1, chord[i]])
        })
    })
    
    var tracks = [notes, comp] // 2 tracks, melody and accompaniment
    
    var audio = new Audio()
      , sampleRate = 44100
      , trackCursors = [0, 0] // for each track, the index to the current note being played
      , currNoteDur = [] // This is to get at note duration info for the current notes being played
                         // to implement note envelope tapering
      , writePos = 0     // write position for the sample data
      , taper = 5000
      
    audio.mozSetup(1, sampleRate)

    function writeBits(){
        // toWrite is the amount to write to fill up our pre-buffer
        var toWrite = audio.mozCurrentSampleOffset() + sampleRate / 2 - writePos
        if (toWrite){
            var data = new Float32Array(toWrite)
            for (var i = 0; i < toWrite; i++, writePos++){
                for (var j = 0; j < 2; j++){
                    var cursor = trackCursors[j]
                      , currNote = tracks[j][cursor]
                    if (!currNote){ // no more notes to play
                        trackCursors[j] = 0 // return to of the track
                        continue
                    }
                    var noteDur = currNoteDur[j]
                    if (!noteDur){
                        noteDur = currNoteDur[j] = [0, currNote[0] * sampleRate / 3]
                    }else if (!noteDur[1]){
                        trackCursors[j]++
                        currNoteDur[j] = null
                        break
                    }else{
                        noteDur[1]--
                        noteDur[0]++
                    }
                    data[i] += Math.sin(writePos * Math.PI * 2 * currNote[1] / sampleRate) * 0.3 *
                        ( // Note envelope tapering to prevent artifacts at note edges
                            (noteDur[0] < taper ? noteDur[0] / taper : 1) *
                            (noteDur[1] < taper ? noteDur[1] / taper : 1)
                        )
                }
            }
            audio.mozWriteAudio(data)
        }
        // Feed it data every 100ms
        setTimeout(writeBits, 100)
    }

    writeBits() // kick off the async loop

}()
{% endhighlight %}

Minified code: 979 bytes

    function C(){a=w.mozCurrentSampleOffset()+x/2-A;if(a){b=new Float32Array(a);for(c=0;c<a;c++,A++)for(d=0;d<2;d++){e=y[d],f=v[d][e];if(!f){y[d]=0;continue}g=z[d];if(!g)g=z[d]=[0,f[0]*x/3];else{if(!g[1]){y[d]++,z[d]=null;break}g[1]--,g[0]++}b[c]+=Math.sin(A*Math.PI*2*f[1]/x)*.5*(g[0]<B?g[0]/B:1)*(g[1]<B?g[1]/B:1)}w.mozWriteAudio(b)}setTimeout(C,100)}a=523.25,b=587.33,c=659.26,d=394.995,e=349.23,f=311.13,g=220,h=246.94,i=c/2,j=a/2,k=g*2,l=[[11,a],[1,b],[12,a],[1,b],[1,c],[9,a],[1,a],[8,d],[1,d],[2,c],[1,b],[11,a],[1,b],[9,a],[2,i],[1,e],[24,d]],m=[[2,e],[2,d],[1,k],[1,a],[4,h*2],[1,a],[1,h*2],[4,k],[1,e],[1,k],[6,d],[2,e],[2,d],[1,k],[1,a],[4,b],[1,b],[1,a],[1,c],[11,d*2]],n=[].concat(l,m,m,l),o=[j,i,d,i],p=[g,j,i,k],q=[e/2,g,j,e],r=[d/2,h,b/2,h],s=[o,o,p,p,q,q,r,r,o,o,p,p,r,r,r,r],t=[q,r,q,r,q,r,o,o],u=[];![].concat(s,t,t,s).forEach(function(a){[0,1,2,3,2,1].forEach(function(b){u.push([1,a[b]])})});v=[n,u],w=new Audio,x=44100,y=[0,0],z=[],A=0,B=5e3;w.mozSetup(1,x),C()

Here's the [demo page (Firefox only)](/js1k/2012/).

After I finished my project. I browsed other projects in the competition, and found that [several](http://js1k.com/2012-love/demo/1274) [of](http://js1k.com/2012-love/demo/1265) [the](http://js1k.com/2012-love/demo/1209) [entries](http://js1k.com/2012-love/demo/1110) also had an audio component. They did this by outputing a wav file in base64 format as a data url and feeding it to the `Audio` object constructor

{% highlight js %}
// from Chime Hero <http://js1k.com/2012-love/demo/1265>
player = new Audio('data:audio/wav;base64,UklGRqSIFQBXQVZFZm10IBAAAAA\
BAAEARKwAAESsAAABAAgAZGF0YYCI' + btoa('\0'+track+track+track+track));
{% endhighlight %}

*Gee, I wish I'd have thought of that!* Well, there's always next year, but I have no regrets!
This project has been a lot of fun - it let me exercise both my creative and analytical sides, and I learned a lot from it. And, by virtue of writing this up and sharing the code, I have contributed something to the community.

Links
-----

* [js1k website](http://js1k.com/)
* [Byte-saving Techniques](https://github.com/jed/140bytes/wiki/Byte-saving-techniques) from Jed Schmitt
* [Bouncing Beholder](http://marijnhaverbeke.nl/js1k/) - the winner of the 1st js1k
* [Audio Data API](https://wiki.mozilla.org/Audio_Data_API)</content>
        </entry>,<entry>
            <title>JSBeautifier - De-minifier of Javascripts(video: 5:46)</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/03/08/jsbeautifier">
            <updated>2012-03-08T05:00:00.000Z</updated>
            <id>http://tobyho.com/2012/03/08/jsbeautifier</li>
            <content type="text">
I made a screencast on [JSBeautifier](http://jsbeautifier.org/) - a tool that de-minifies Javascript. It covers using the online tool as well as how to install it as command line script and how to use it within Textmate.

<div class="video">
    <iframe src="http://player.vimeo.com/video/38141364?title=0&amp;byline=0&amp;portrait=0" width="400" height="395" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
</div>

Or, if you prefer to read, then read on...

To use the online version of the tool, go to [jsbeautifier.org](http://jsbeautifier.org). Copy some minified Javascript and paste it into the large textarea on the left side of the screen and hit the button on the top labeled "Beautify JavaScript or HTML". *Voila!*

To install it as a command line tool, you'll want to go to their [Github page](https://github.com/einars/js-beautify) and clone their repo

    git clone https://github.com/einars/js-beautify.git
    
Then go into the `js-beautify/python` directory, and do

    python setup.py install
    
This should install the `js-beautify` executable. Try executing `js-beautify` to see that it worked.

Textmate Integration
--------------------

To use js-beautify inside of Textmate, first ensure `js-beautify` is in the `PATH` variable for the environment that's setup for Textmate. To do that, open up Preferences -> Advanced -> Shell Variables, and edit the `PATH` variable. You can do `which js-beautify` on your command line to find out where it was installed.

Now, paste some minified Javascript in a new Textmate window, use the Cmd+Opt+R shortcut to bring out the "Filter Through Command" dialog, and put `js-beauify -i` in the Command field. If the minified Javascript is the only thing in your window, then just select "Document" for the input and "Replace Document" for the output. Hit "Execute" and see it de-minify! 



</content>
        </entry>,<entry>
            <title>Fun With Formatting Async Code</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/03/07/fun-with-formatting-async-callbacks">
            <updated>2012-03-07T05:00:00.000Z</updated>
            <id>http://tobyho.com/2012/03/07/fun-with-formatting-async-callbacks</li>
            <content type="text">
*Note: This post may be more about personal taste than anything.*

Everyone encounters the [pyramid of doom problem](https://groups.google.com/d/msg/jsmentors/jKrr05Lk-Ic/NNCCtJkuFe8J) at some point when working with [Node](http://nodejs.com). One popular way to address this by using an async flow control library such as caolan's [async](https://github.com/caolan/async). So, I got on board with this library and used it to write some unit tests which needed to deal with a series of file accesses. In particular, I was writing a file watcher. One of the tests looked like this

{% highlight js %}
async.series([
    function(next){
        test.touchFile('one.txt', next)
    }, 
    function(next){
        test.touchFile('two.txt', next)
    }, 
    function(next){
        watcher.add(test.filePath('*.txt'))
        next()
    }, 
    function(next){
        setTimeout(next, 200)
    }, 
    function(next){
        test.touchFile('one.txt', next)
    }, 
    function(next){
        expect(changed.args[0])
            .to.be.eql(['change', test.filePath('one.txt')])
        next()
    }, 
    function(next){
        test.touchFile('two.txt', next)
    }, 
    function(next){
        expect(changed.args[1])
            .to.be.eql(['change', test.filePath('two.txt')])
        done()
    }
])
{% endhighlight %}

Something about this code doesn't sit well with me, and it's not just that it's verbose - which it definitely is. It is the fact that the actual code of interest, for example

{% highlight js %}
    test.touchFile('one.txt', next)
{% endhighlight %}

is indented underneath this uninteresting line of boilerplate

{% highlight js %}
function(next){
{% endhighlight %}

It's *burying the lead*, and this makes scanning the code difficult. Maybe we can format the code in a way that makes the interesting lines more prominent. Something like this

{% highlight js %}
async.series([function(next){
    test.touchFile('one.txt', next) }, function(next){
    test.touchFile('two.txt', next) }, function(next){
    watcher.add(test.filePath('*.txt')), next() }, function(next){
    setTimeout(next, 200) }, function(next){
    test.touchFile('one.txt', next) }, function(next){
    expect(changed.args[0])
      .to.be.eql(['change', test.filePath('one.txt')]), next() }, function(next){
    test.touchFile('two.txt', next) }, function(next){
    expect(changed.args[1])
      .to.be.eql(['change', test.filePath('two.txt')])
    done() }
])
{% endhighlight %}

By tucking the uninteresting part: `function(next){` to the back, the interesting parts emerge to the beginning and now the program is easily scannable. At first glance, it almost looks like normal straight line Javascript.
    
However, there are a couple of things I don't like about this

1. maybe it looks too much like normal script, having it look somewhat different would make the async style code stand out
2. the fact that most lines end in a curly brace looks kinda noisy

So, I moved the curly down a line.

{% highlight js %}

async.series([function(next)

{ test.touchFile('one.txt', next) }, function(next)
{ test.touchFile('two.txt', next) }, function(next)
{ watcher.add(test.filePath('*.txt')), next() }, function(next)
{ setTimeout(next, 200) }, function(next)
{ test.touchFile('one.txt', next) }, function(next)
{ expect(changed.args[0])
      .to.be.eql(['change', test.filePath('one.txt')]), next() }, function(next)
{ test.touchFile('two.txt', next) }, function(next)
{ expect(changed.args[1])
      .to.be.eql(['change', test.filePath('two.txt')])
  done() }

])
{% endhighlight %}

Now, this looks interesting. Each line is a line of Javascript wrapped by curly braces. This looks foreign and familiar at the same time - almost like another language. A good analogy is the IO Monad in Haskell, or the method chaining syntax of jQuery. And it also looks cleaner than my last attempt because there are no braces left unclosed on any line. I like it and I am going to try it out.

</content>
        </entry>,<entry>
            <title>Magic Arguments</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/02/19/magic-arguments-js">
            <updated>2012-02-19T05:00:00.000Z</updated>
            <id>http://tobyho.com/2012/02/19/magic-arguments-js</li>
            <content type="text">
In this post I am going to talk about an interesting pattern in Javascript which I will call: *magic arguments*. I will give two examples of where it's been used.

`$super` argument in Prototype
------------------------------

The [Prototype](http://www.prototypejs.org/) library uses this technique to implement the `$super` special argument - which an overriding method can use to reference the method of the same name implemented by the super class.

For instance, this is how you'd write a class and methods using Prototype

{% highlight js %}
var Person = Class.create({
  initialize: function(name) {
    this.name = name;
  },
  say: function(message) {
    return this.name + ': ' + message;
  }
});
{% endhighlight %}
    

If you override the `say` method to say something else, this is what you'd do

{% highlight js %}
var Pirate = Class.create(Person, {
  // redefine the speak method
  say: function(message) {
    return this.name + ': ' + message + ', yarr!';
  }
});
{% endhighlight %} 
   
And, *this* is how you would override the `say` method *and* allow it to call the `say` method of `Person`:

{% highlight js %}
var Pirate = Class.create(Person, {
  // redefine the speak method
  say: function($super, message) {
    return $super(message) + ', yarr!';
  }
});
{% endhighlight %}

Now, you should be suspicious at this point, because: how is it that when `$super` is the first argument, it knows to supply the super-method as the first argument rather than `message` - as it normally would be the case?

If you peek into the [source](https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js) and searched for `$super` you'd find the answer

{% highlight js %}
if (ancestor && Object.isFunction(value) &&
          value.argumentNames()[0] == "$super") {
{% endhighlight %}

Here, `value` is a function(the first part of the if verifies that), and the method `value.argumentNames()` is called to get at the argument names of that function. Then with that information at hand, it does a conditional to say: if the name of the first argument is `$super`, insert the overridden method as the first argument, otherwise just leave the argument list alone. The code for `argumentNames` is actually not that bad, it is this

{% highlight js %}
function argumentNames() {
  var names = this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1]
    .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
    .replace(/\s+/g, '').split(',');
  return names.length == 1 && !names[0] ? [] : names;
}
{% endhighlight %}

Basically, calling the `toString()` method on a function returns the actual Javascript source code for that function (try it!) - from which you can parse out the argument names.

For reference, here is more on [class-style inheritance in Prototype](http://www.prototypejs.org/learn/class-inheritance). Now, let's move on to the next example.

Mocha
-----

The [Mocha Test Framework](http://visionmedia.github.com/mocha/) also uses magic arguments as part of its arsenal. In Mocha, a test function can either be run synchronously or asynchronously. Let's see them both. First, sync

{% highlight js %}
describe('Array', function(){
  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      [1,2,3].indexOf(5).should.equal(-1);
      [1,2,3].indexOf(0).should.equal(-1);
    })
  })
})
{% endhighlight %}

Now async

{% highlight js %}
describe('User', function(){
  describe('#save()', function(){
    it('should save without error', function(done){
      var user = new User('Luna');
      user.save(function(err){
        if (err) throw err;
        done();
      });
    })
  })
})
{% endhighlight %}

Can you tell the difference? *Right!* The async version has a `done` argument in the test function where as the sync version has *no* arguments. (Sorry, been watching too much *Dora the Explorer*). In the async version, the `done` callback must be called at some point by the test code to signal the end of the test, but that's not true of the sync version - which just ends when the function finishes executing.

So, the presence of the argument is important. As you'd find out if you try to write a sync test, but left a `done` argument in there

{% highlight js %}
describe('Array', function(){
  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(done){
      [1,2,3].indexOf(5).should.equal(-1);
      [1,2,3].indexOf(0).should.equal(-1);
    })
  })
})
{% endhighlight %}

This test will not finish normally and will be timed out by Mocha after 2 seconds because although the `done` callback was supplied and expecting to be called, the test code does not call it.

Like Prototype, Mocha determines what to do by introspecting the function's argument list. But it does not resort to parsing out the argument names from the function source, it just uses the `length` property to find out the arity of the function. Which works like this

{% highlight js %}
function myfunc(arg1){
}
myfunc.length // gives 1
{% endhighlight %}

The offending line in the [Mocha source](https://github.com/visionmedia/mocha/blob/master/mocha.js) is 

{% highlight js %}
this.async = fn && fn.length;
{% endhighlight %}

So, if the length is 0, it is sync, otherwise it is async.

Should I Do This?
-----------------

This is a neat trick you can employ if you are writing a JS library and want to tweak the appearance of the client code for reducing code clutter or just to make it look a certain way. It has the downside that if the people using your library is not aware of the trick, they could experience behavior that they are not expecting and don't know where to look. In my opinion, you generally should not use this. That doesn't mean don't use it, it just means: when you use it, you should have a damn good reason.
</content>
        </entry>,<entry>
            <title>Tour of npm</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/02/09/tour-of-npm">
            <updated>2012-02-09T05:00:00.000Z</updated>
            <id>http://tobyho.com/2012/02/09/tour-of-npm</li>
            <content type="text">
*Hello and welcome to the npm tour!*

[npm](http://npmjs.org/) stands for Node Package Manager, written by [Isaac Schlueter](http://foohack.com/) - it is the program you use to install third party Node modules. As of Node 0.6.x, you no longer have to install npm separately - it comes with Node! Thanks to that, we will skip the installation step.

Part I: Installing Things
-------------------------

Installing packages is npm's primary job. But before even doing anything, you should understand the difference between installing *locally* vs installing *globally*. 

### Installing Locally

npm always assumes you are working within the project directory of a Node project, let's call this directory the *project root*. When you are installing packages locally (this is the default behavior)

    npm install <package name>

The installed package goes under

    <project root>/node_modules
    
The way npm determines your *project root* is the following (paraphrasing from `npm help folders`)

> Starting at the current directory, npm will walk up the folder tree checking for a folder that  contains
> either  a `package.json` file, or a `node_modules` folder.  If such a directory is found, then that
> is treated as the effective "project root" for the purpose of  running  npm  commands.
>
> If no such directory is found, then fallback to using the current directory as the project root.

In the case that the project root does not already have a `node_modules` directory, one will be created for you when you next install a package.

If you are not confident what the current project root is, type

    npm prefix
    
to find out.

### Installing Globally

Installing a package globally puts the package into a global location, usually `/usr/local/lib/node_modules` for unix, and for Windows it's the `node_modules` directory under the same place where `node.exe` is installed. In order to install packages globally, you have to use the `-g` flag.

    npm install <package name> -g
    
### Should I install Locally or Globally?

The recommendation is to always install locally the libraries you `require()` - doing this keeps separate
the dependencies of different projects, so that the requirements of one project can never interfere with another (npm actually prevents you from *requiring* packages that are not installed locally). Install globally command line utilities you commonly use such as coffeescript and docco - they will generally be installed to `/usr/local/bin`.

### Examples of Installing

The most common usage of npm is to install a package that's been published to the npm registry. For example to install express, you'd do

    npm install express
    
If you want a specific version of express, do like this

    npm install express@2.4.0
    
You could also install by tag name

    npm install express@latest
    
Or restrict the version by range

    npm install express@">=2.4.7"
    
You can install private packages too. Any directory containing a valid `package.json` file (more on that later) is a valid npm package

    npm install ~/mypackage
    
Same goes for a tarball that contains the contents of the above directory

    npm install mypackage.tgz
    
or a github repo that contains that directory

    npm install git://github.com/airportyh/mypackage.git
    
Last, but *definitely* not least

    npm install
    
Will install all the packages that are required by your current project as defined in your `package.json`.

I highly recommend reading the output of `npm help install` and `npm help folders`.

Part II: Making Things
----------------------

These section will cover various useful commands npm has to help you with developing a Node program or library - in both of these cases you'd be making a Node package.

### `package.json`

I have mentioned `package.json` a couple of times, and now finally I will explain what it is. This file is a manifest of your Node project and should be placed at your project root. It contains various information that is specific to your project. Among these things are

* The name, description and version of this package
* Names and email addresses of authors and contributors to the project
* Web page of the project
* Repository URL of the project
* A list of executables provided by the package, if any
* The versions of Node this package works on
* A list of other packages that this package depends on

A very basic `package.json` looks like this

    {
       "name": "Blerg",
       "description": "Blerg blerg blerg.",
       "version": "0.0.1",
       "author": {
          "name" : "John Doe", 
          "email" : "john.doe@gmail.com"
       },
       "repository": {
           "type": "git",
           "url": "http://github.com/johndoe/blerg.git"
       },
       "engines": [
           "node >= 0.6.2"
       ],
       "license" : "MIT",
       "dependencies": {
           "express": ">= 2.5.6",
           "mustache": "0.4.0",
           "commander": "0.5.2"
       },
       "bin" : {
           "blerg" : "./cli.js"
       }
    }
    
To save you some typing when creating a new `package.json` initially, 

    npm init
    
will ask you a series of questions and generate a `package.json` for you based on your answers.

#### Dependencies

Of particular interest is the "dependencies" property in `package.json`. This is a set of key/value pairs

    "dependencies": {
        "express": ">= 2.5.6",
        "mustache": "0.4.0",
        "commander": "*"
    },
    
On the left is the name of the package and on the right is a version specification, which could specify a specific version(`0.5.2`), a range of versions(`>= 2.5.6`) or any version(`*`). When you do

    npm install
    
in your project, this is what npm looks at to install all of your project's dependencies.

For more on the semantics of `package.json` read `npm help json`
    
### Updating a Package

    npm update <package name>
    
will update a package to its current latest version, or the latest version that is allowable by the version specification defined in `package.json`.

### List Installed Packages

    npm list
    
Will show you all the packages you have currently installed for your project as well a their sub-packages, visually formatted as a nested tree

    express@3.0.0alpha1-pre /Users/airportyh/Home/Code/express
    ├── commander@0.5.1 
    ├─┬ connect@2.0.0alpha1 
    │ ├── formidable@1.0.8 
    │ └── qs@0.4.2 
    ├─┬ connect-redis@1.2.0 
    │ └── redis@0.7.1 
    ├── debug@0.5.0 
    ├── ejs@0.6.1 
    ├── jade@0.20.1 
    ├── mime@1.2.4 
    ├── mkdirp@0.3.0 
    ├─┬ mocha@0.12.0 
    │ └── growl@1.4.1 
    ├── should@0.5.1 
    └─┬ stylus@0.23.0 
      ├── cssom@0.2.1 
      ├── growl@1.1.0 
      └── mkdirp@0.0.7 

### List Outdated Packages

    npm outdated
    
will tell you which of the packages that you have installed is outdated with respect to what is current in the npm registry but allowable by the version definition in `package.json`.

### Prune Unneeded Packages

    npm prune
    
Will you remove any packages you have installed but is not depended on by your project according to your `package.json`.

### Link

    npm link ../myothernodeproject
    
The `link` command installs a package not by copying its contents, but rather by creating a symlink to a directory that contains the package. This is quite useful for when you are concurrently working on more than one Node project. It does not work on Windows, however.

### Rebuild Native Modules

Some Node packages contain native code that's written in C++, which require compilation. If you ever need to recompile them - often the case when you upgrade to a new version of Node, do

    npm rebuild

### Commands

You can tell npm about commonly used shell scripts in your project via the `scripts` property in `package.json`. For example, writing this

    "scripts": {
        "myscript": "node myscript.js"
    }
    
will allow me to run `node myscript.js` by saying

    npm run-script myscript
    
Four common tasks that are common to many projects - `start`, `stop`, `test` and `restart` - are made even easier to get to. If you have a script specified for `start`, for example, then you can run it by typing

    npm start
    
### Pack a Tarball

    npm pack
    
The `pack` command packages your project into a tarball - good for if you need to email someone your package.

Part III: Becoming Famous
-------------------------

This section will cover commands for publishing and managing your Node package in the public npm registry. 

In order to publish a package to the registery, you first need to register yourself as a user.

    npm adduser
    
This will prompt for a username, a password and an email address. You'd also use this command to login to an existing user account in the case you are on a machine that does not have your npm login information yet (the info is saved in `~/.npmrc`).

Once you are logged in, you can publish your package. In your project root directory do

    npm publish
    
will do the trick. If your package name has already been taken, this won't work - you'll have to use another name. To publish again, use `npm version <version>` or update the version number by hand in `package.json` and then publish again.
    
It is possible to remove your package from the registry

    npm unpublish <package name>[@<version>]
    
But this is *discouraged*. The better alternative is to deprecate it

    npm deprecate <package name>[@<version>] <message>
    
which will show a deprecation warning message to anyone who installs it.

    npm tag <name>@<version> [<tag>]
    
will give a particular version of a package a tag - which is a string, so that now people can install it via the tag name, such as
    
    npm install blerg@stable
    
The `author` command manages the list of users that can publish a particular package.

    npm author ls blerg
    
Lists the users who admin the blerg package.

    npm author add johndoe blerg
    
Adds `johndoe` to the blerg package.

    npm author rm johndoe blerg
    
Removes `johndoe` from the blerg package.

Part IV: Discovery
------------------

npm also has facilities for discovering public packages in the registry.

    npm search <search term>
    
Will list all packages whose name, description, or keywords match the provided search term.

    npm home <package name>
    
Will open the project's home page in your browser.

npm has social features too, you can *star* and *unstar* a package

    npm [star|unstar] <package name>

At the moment, social data is not used on the npm web site, but it will be at some point to make discovering good packages easier.

Part V: Getting Help
--------------------

    npm
    
lists all available commands. *Note: some of those listed are aliases.*

    npm help <command>
    
To get help on a particular command.

    npm help-search <word>
    
searches all the command help pages for occurrence of a particular word, reverse sorted by the frequency of word occurrence. If you use `npm help <command>` and the command does not exist, it will fallback to `help-search`, so actually you'd be okay just using `npm help`.

And, last not least

    npm faq
    
Bonus Tip
---------
    
    npm completion
    
Outputs some shell script which you can put into your `.bashrc` or `.bash_profile` to enable tab completion of npm commands.
    
Online Resources
----------------

- [npm home page](http://npmjs.org/)
- [npm registry](http://search.npmjs.org/)
- [npm source code](https://github.com/isaacs/npm)
- [npm mailing list](http://groups.google.com/group/npm-)



    




</content>
        </entry>,<entry>
            <title>Let's Write a Jasmine Matcher!</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/01/30/write-a-jasmine-matcher">
            <updated>2012-01-30T05:00:00.000Z</updated>
            <id>http://tobyho.com/2012/01/30/write-a-jasmine-matcher</li>
            <content type="text">
Let's write a Jasmine matcher! 

> I know what [Jasmine](http://pivotal.github.com/jasmine/) is, but what is a matcher?

A [matcher](https://github.com/pivotal/jasmine/wiki/Matchers) is used to evaluate an assertion on an object. If the object matches, the assertion passes, if it doesn't match, the assertion fails.

> Okay, so it's like when you say `expect(x).toEqual(y)`.

Right, in this case `toEqual` is the matcher being used. There's already a useful list of [built-in matchers](https://github.com/pivotal/jasmine/wiki/Matchers), but now we want to write one of our own.

> Okay, so what should our matcher do?

Well, I want to be able to say

{% highlight js %}
expect(saidArray).toHaveItemsBeInThisOrder([4, 5, 6])
{% endhighlight %}

and that means `saidArray` has each of `4`, `5`, and `6` as elements *and* that the index of `4` should precede that of `5`, and the index of `5` should in turn precede that of `6`.

First Attempt
-------------

Although in the [documentation](https://github.com/pivotal/jasmine/wiki/Matchers) it says to add the matcher within the context of a spec using the `addMatchers` method, for this case I think it makes sense to add the matcher globally, and, to do that, we simply add a method to the prototype of `jasmine.Matchers`.

{% highlight js %}
jasmine.Matchers.prototype.toHaveItemsBeInThisOrder = function(){
    // implementation here
}
{% endhighlight %}

A matcher method should take `this.actual` - the value that is being verified, and match it against the expected value - the method's arguments. Our first attempt looks like this

{% highlight js %}
jasmine.Matchers.prototype.toHaveItemsBeInThisOrder = function(){
    var arr = this.actual
      , expectedItems = arguments
    for (var i = 0, len = expectedItems.length - 1; i < len; i++){
        var first = expectedItems[i]
          , second = expectedItems[i + 1]
        if (arr.indexOf(first) === -1 || arr.indexOf(second) === -1)
            return false
        if (arr.indexOf(first) >= arr.indexOf(second)) return false
    }
    return true
}
{% endhighlight %}

In this code, we loop through the expected items(from `arguments`) and make sure that 

1. each element from the `expectedItems` array belongs in the actual array(using `indexOf`).
2. for each pair of adjacent items in `expectedItems`, the index of the first in the actual array is before that of the second - this ensures the expected ordering.

Now to test this. First we test for presence

{% highlight js %}
expect([1,2,3,4]).toHaveItemsBeInThisOrder(1) // pass
expect([1,2,3,4]).toHaveItemsBeInThisOrder(2) // pass
expect([1,2,3,4]).toHaveItemsBeInThisOrder(5) // fail
{% endhighlight %}

Next we test for ordering

{% highlight js %}
expect([1,2,3,4]).toHaveItemsBeInThisOrder(1,2,3,4) // pass
expect([1,2,3,4]).toHaveItemsBeInThisOrder(1,3,4) // pass
expect([1,2,3,4]).toHaveItemsBeInThisOrder(2,3,4) // pass
expect([1,2,3,4]).toHaveItemsBeInThisOrder(1,4,3) // fail
{% endhighlight %}

Second Attempt
--------------

Okay, cool. But there's something I am uncomfortable about - in particular the use of `Array.prototype.indexOf`: it poses a couple of problems

1. `Array.prototype.indexOf` is not supported in older IEs
2. I would like to use Jasmine's `toEqual` matcher's equality test to match items in the array, with which equivalent array literals and object literals can be matched and also you could match classes of objects using `jasmine.any(clazz)` - where clazz is a Javascript type such as `Number`, `String`, `Function` or a Javascript function acting as a constructor.

I looked up Jasmine's source and found where the equality test for `toEqual` were implemented - it was under `jasmine.Env.prototype.equals_`. Jasmine has an `Env` object which is the global configuration object for the test suite to be run within. Turns out, it is also the place where various helper methods are placed - including `equals_`. I felt it would make sense to attach my own helper method `indexOf_` to it

{% highlight js %}
jasmine.Env.prototype.indexOf_ = function(arr, item){
    for (var i = 0, len = arr.length; i < len; i++){
        if (this.equals_(arr[i], item))
            return i
    }
    return -1
}
{% endhighlight %}

Because I wrote `indexOf_` as a method of `jasmine.Env`, I could easily make use of its `equals_` method just by accessing it through `this`. 

Now, let's integrate this method into our matcher

{% highlight js %}
jasmine.Matchers.prototype.toHaveItemsBeInThisOrder = function(){
    var arr = this.actual
      , expectedItems = arguments
      , env = this.env
    for (var i = 0, len = expectedItems.length - 1; i < len; i++){
        var idxFirst = env.indexOf(arr, expectedItems[i])
          , idxSecond = env.indexOf(arr, expectedItems[i + 1])
        if (idxFirst === -1 || idxSecond === -1)
            return false
        if (idxFirst >= idxSecond) return false
    }
    return true
}
{% endhighlight %}

Notice that the `env` was readily accessed through the current context - which is an instance of matcher. Now, let's see if that worked - it should now match identical array literals

{% highlight js %}
expect([[1,2],[3,4]]).toHaveItemsBeInThisOrder([1,2],[3,4]) // pass
expect([[1,2],[3,4]]).toHaveItemsBeInThisOrder([3,4],[1,2]) // fail
{% endhighlight %}

Cool.

Third Attempt
-------------

That was great, but now I want to write another matcher. In this matcher I would write

{% highlight js %}
expect(saidSpy).toHaveCallArgsBeInThisOrder(['foo'], ['bar'])
{% endhighlight %}

and it should verify that `saidSpy` - a Jasmine [spy](https://github.com/pivotal/jasmine/wiki/Spies) - was first called with the arguments `'foo'`, and then with `'bar'`.

Even though this matcher should be easily derived from the one we just wrote - `toHaveItemsBeInThisOrder` - I couldn't find an easy way to reuse it directly. The cleanest solution I've found to reuse code was to refactor the matcher logic out to a helper method on `jasmine.Env.prototype`

{% highlight js %}
jasmine.Env.prototype.arrayItemsInThisOrder_ = function(arr, expectedItems){
    for (var i = 0, len = expectedItems.length - 1; i < len; i++){
        var idxFirst = this.indexOf(arr, expectedItems[i])
          , idxSecond = this.indexOf(arr, expectedItems[i + 1])
        if (idxFirst === -1 || idxSecond === -1)
            return false
        if (idxFirst >= idxSecond) return false
    }
    return true    
}
jasmine.Matchers.prototype.toHaveItemsBeInThisOrder = function(){
    return this.env.arrayItemsInThisOrder_(this.actual, arguments)
}
{% endhighlight %}

The matcher method `toHaveItemsBeInThisOrder` now simply makes use of the new helper method `arrayItemsInThisOrder_`. Now, this enables us to write the new matcher method as

{% highlight js %}
jasmine.Matchers.prototype.toHaveCallArgsBeInThisOrder = function(){
    return this.env.arrayItemsInThisOrder_(this.actual.argsForCall, arguments)
}
{% endhighlight %}

Where `argsForCall` is where the spy's call arguments are stored as an array. Test it out and we get

{% highlight js %}
var f = jasmine.createSpy('f')
f('foo')
f('bar')
expect(f).toHaveCallArgsBeInThisOrder('foo', 'bar') // pass
expect(f).toHaveCallArgsBeInThisOrder('bar', 'foo') // fail
{% endhighlight %}

Fourth Attempt
--------------

Almost done, but not quite. At this point, when an assertion fails with our matcher, you get output like this

    Expected spy on push to have call args be in this order [ ['bar'], ['foo'] ]
    
but it doesn't tell us what the actual values were. To show the actual values also, we will need to customize the error messages, and to *that*, we attach a `message` method to the matcher instance
inside the matcher method like this

{% highlight js %}
jasmine.Matchers.prototype.toHaveCallArgsBeInThisOrder = function(){
    this.message = function() {
        var args = Array.prototype.slice.apply(arguments)
        return [
            'Expected spy ' + this.actual.identity + ' to have call args be in this order ' + jasmine.pp(args) +
            ' but they were ' + jasmine.pp(this.actual.argsForCall),
            'Expected spy ' + this.actual.identity + ' to have call args not be in this order ' + jasmine.pp(args) +
            ' but they were ' + jasmine.pp(this.actual.argsForCall)
        ]
    }
    
    return this.env.arrayItemsInThisOrder_(this.actual.argsForCall, arguments)
}
{% endhighlight %}
    
The `message` method should return an array of two values: an error message for the positive matcher (expected it to be...) and another for the negative matcher (expected it not to be...). With this, the error message will look like this

    Expected spy on push to have call args be in this order [ ['bar'], ['foo'] ] but they were [ ['foo'], ['bar'] ].

Very nice. I am happy with this.

Conclusion
----------

To recap, we have

1. Written a simple Jasmine matcher.
2. Made use of existing helper methods attached to Jasmine's `env` object.
3. Written a custom helper method attached to `jasmine.Env.prototype`.
4. Refactored matcher logic as another helper method to allow reuse of logic by more than one matcher.
</content>
        </entry>,<entry>
            <title>Responsive Web Design</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/01/25/responsive-web-design">
            <updated>2012-01-25T05:00:00.000Z</updated>
            <id>http://tobyho.com/2012/01/25/responsive-web-design</li>
            <content type="text">
I spoke at a local meetup recently about [Responsive Web Design](http://www.alistapart.com/articles/responsive-web-design/) and I'll repurpose the content here as a blog post.

The Problem
-----------

In 2007, Steve gave us the iPhone

<div class="image">
<img src="/images/responsive_web_design/steve_jobs.jpg" alt="The Steve">
</div>

The success and popularity of the iPhone was incredible. Many companies wanted their website to look good on the device. "Okay," said the web developers, "we will build another website that's optimized for the iPhone, but it'll cost you extra."

<div class="image">
<img src="/images/responsive_web_design/iphoneApp.jpg" alt="iPhone optimized app">
</div>

Fast forward now to the present: today there are hundreds of different consumer smart phones and tablets. They all have different shapes and sizes, different screen resolutions and aspect ratios, 
and are meant to be held at different orientations. It no longer makes sense to design a website
specifically for a device anymore - there are too many of them.

What are we going to do?
------------------------

We take inspiration from Mr. Bruce Lee.

<div class="video">
<iframe width="480" height="360" src="http://www.youtube.com/embed/USlnfTGlhXc" frameborder="0" allowfullscreen></iframe>
</div>

Be formless and shapeless like water. When you put it in a phone, it *becomes* the phone, when you put it in a tablet, it
*becomes* the tablet, when you put it in a window, it *becomes* the window.

Seeing Is Believing
-------------------

*Seeing is believing*. Here I showcase a couple of websites that do this really well. The layout of these sites will actually change as you resize your browser window, so you can see what they *would* look like at different screen resolutions.

### [WebDesignerWall.com](http://webdesignerwall.com)

<div class="image">
    <img src="/images/responsive_web_design/webdesignerwall.gif" alt="WebDesignerWall">
</div>

[Web Designer Wall](http://webdesignerwall.com) switches between 3 different layouts as you change the screen resolution: 1-column, 2-column and 3-column. So no matter what your screen size, you'll have a nice viewing experience(and no scrolling!).

### [CSS-Tricks.com](http://css-tricks.com)

<div class="image">
    <img src="/images/responsive_web_design/css-tricks.gif" alt="CSS-Tricks">
</div>

[CSS Tricks](http://css-tricks.com) is an even more dynamic website - it's like the Bruce Lee of websites! I leave it as an exercise for the reader to find all the layout changes and fun easter eggs hidden in this website.

How'd They Do That?
-------------------

What techniques did they use to achieve these dynamic and fluid websites?

### Technique 1: Meta Viewport Tag

The first thing that you have to do is something called the *meta viewport tag*.
By default, iOS and Android browsers try to render your page as if it were
designed for the desktop. It does so by pretending it has a view port of 980px wide
in the case of iOS and 800px wide in the case of Android. So when you open the web page initially it'll be zoomed out like this

<div class="image">
<img src="/images/responsive_web_design/mobileZoomedOut.jpg" alt="Mobile Zoomed Out">
</div>

and you can't read the text so the first thing you do is you double tap to zoom in.
This is a bad nice user experience, so we have to fix that. The fix is to put this in your `<head>`
    
{% highlight html %}
<code><meta name="viewport" 
    content="width=device-width"></code>
{% endhighlight %}

This sets the viewport size to the real size of the device. Don't worry, this tag
has no effect on desktop browsers.

### Technique 2: Fluid Layout

*Fluid Layout* means that your content grows and shrinks with the size of the window.
You achieve that effect by using percentage widths. 

{% highlight css %}
#content{
    float: left;
    width: 80%;
}

#sidebar{
    float: right;
    width: 20%;
}
{% endhighlight %}

This example is a simple two column layout where the content takes up 80% of the 
horizontal space and the side bar takes up 20%.

<div>
<style>
.demoButton {
   border-top: 1px solid #96d1f8;
   background: #65a9d7;
   background: -webkit-gradient(linear, left top, left bottom, from(#3e779d), to(#65a9d7));
   background: -webkit-linear-gradient(top, #3e779d, #65a9d7);
   background: -moz-linear-gradient(top, #3e779d, #65a9d7);
   background: -ms-linear-gradient(top, #3e779d, #65a9d7);
   background: -o-linear-gradient(top, #3e779d, #65a9d7);
   padding: 12px 24px;
   -webkit-border-radius: 8px;
   -moz-border-radius: 8px;
   border-radius: 8px;
   -webkit-box-shadow: rgba(0,0,0,1) 0 1px 0;
   -moz-box-shadow: rgba(0,0,0,1) 0 1px 0;
   box-shadow: rgba(0,0,0,1) 0 1px 0;
   text-shadow: rgba(0,0,0,.4) 0 1px 0;
   color: white !important;
   font-size: 18px;
   text-decoration: none;
   vertical-align: middle;
   }
.demoButton:hover {
   border-top-color: #28597a;
   background: #28597a;
   color: #ccc;
   }
.demoButton:active {
   border-top-color: #1b435e;
   background: #1b435e;
   }
</style>
</div>

<a href="/responsive_web_design/fluiddemo.html" target="_blank" class="demoButton">DEMO (fluiddemo.html)</a>

The two boxes will stretch or shrink to take up all the available space. The limitation 
of this approach is that for smaller screens - such as those for mobile phones - the 2 column layout is still going to be really cramped. Which brings us to the 3rd technique: media queries.

### Technique 3: Media Queries

Media queries allow you to
have conditional CSS rules that target screen sizes of a specific
range.

{% highlight css %}
@media screen and (max-width: 640px) {
    #content{
        float: none;
        width: 100%;
    }
    
    #sidebar{
        /* just make sidebar go on top */
        float: none;
        width: 100%;
    }
}
{% endhighlight %}

This code says any browser with a display width of 640 pixels or
less will apply these two CSS rules. The purpose of the two rules here
is to override the 2-column layout CSS rules and make a one-column layout
instead.

<a href="/responsive_web_design/mediaquerydemo.html" target="_blank" class="demoButton">DEMO (mediaquerydemo.html)</a>

If you open up the demo and play with changing the window size(if you are on IE, make sure 
you are on version 9 or above), you will see that the layout changes when you cross the
640-pixel width boundary. Note that I also added some extra CSS so that the navigation also
switches from vertical to horizontal in the one-column layout.

#### Media Queries on `<link>`

Media queries can also be declared on the link tag, so that you can
have conditionally linked css files as well. If you prefer to roll 
like that.

{% highlight css %}
<link rel="stylesheet" 
    media="screen and (max-width: 640px)" 
    href="small.css" />
{% endhighlight %}

Browser Support
---------------

While percentage widths have been around forever and work on all browsers, media queries
are still relatively new. 

### Mobile Support

<div>
<style>
ul.support li{
    list-style: none;
}
ul.support li.yes:before{
    content: "✔ ";
}
ul.support li.no:before{
    content: "✘ ";
}
</style>
</div>

Here's what the support landscape looks like for mobile OS'es

<ul class="support">
    <li class="yes">iOS</li>
    <li class="yes">Android</li>
    <li class="yes">WebOS</li>
    <li class="yes">Opera Mini</li>
    <li class="yes">Newer Blackberry</li>
    <li class="no">Windows Phone<li>
</ul>

Windows Phone is the only OS that still doesn't support - more on that later.

### Desktop Support

On the desktop, media queries are supported on the latest version of all major browsers.

<ul class="support">
    <li class="yes">IE 9+</li>
    <li class="yes">Firefox 3.5+</li>
    <li class="yes">Chrome 4.0+</li>
    <li class="yes">Safari 4.0+</li>
    <li class="yes">Opera 9.5+</li>
</ul>

But of course due to the slow adoption rate of newer IE versions, some of us still have
to worry about

<ul class="support">
    <li class="no">IE 8 and below</li>
</ul>

[caniuse.com](http://caniuse.com) has more [detailed browser support info](http://caniuse.com/css-mediaqueries).

Workarounds for Older Browsers
------------------------------

What to do for older browsers that don't support media queries?

### Sensible Fallback

Often times, simply having a sensible fallback is good enough. The older browsers
will simply ignore the rules declared inside of media queries, and if you make sure
it will be usable despite of that, it is often enough.

### IE Conditional Comments

IE conditional comments is another option, specifically for older IEs. For Windows 
Phone in particular, it seems the current best practice is to use IE conditional comments
to specifically target `IEMobile`

    <![if !IEMobile]>
    <link rel="stylesheet" 
        href="windowsphone.css">
    <![endif]>

Which: Microsoft, *get with the program* :)

### Javascript Fallback

Yet another option is to employ a Javascript-based solution that emulates
the media query functionality. A good one is [Respond.js](https://github.com/scottjehl/Respond), where you just include the script, and
boom! Media queries will start working in all the older browsers.

Images and Videos
-----------------

Now, let's switch gears to images and videos. Here are a couple of problems
images and videos pose when used in fluid and responsive layouts

- they doesn't look good when it has a different width than the rest
of the content
- when the width is small, part of the image or video is occluded

The first stab at a solution to this is to stretch the image to 100% width so it fits perfectly to its parent container

{% highlight css %}
#content img{
    width: 100%;
}
{% endhighlight %}

But this could cause a lower resolution to scale all the way up and look blurry. So instead
I like to use `max-width` in addition to centering it.

{% highlight css %}
#content img{
    max-width: 100%;
}
{% endhighlight %}

<a href="/responsive_web_design/fluidimage.html" class="demoButton">DEMO(fluidimage.html)</a>

Fluid Third Party Videos
------------------------

For the `<video>` tag, you can use the same `max-width` technique, but most people don't use `<video>`, it's too hard. Instead people tend more to use third-party video services like YouTube and Vimeo. When you embed a video from these video services, the video is encased inside of an `<iframe>`. 
    
<a href="/responsive_web_design/naivevideo.html" class="demoButton">DEMO(naivevideo.html)</a>

The problem is, if you give the `<iframe>` a percentage width, it will mess up its aspect ratio, which could in turn screw up the video's aspect ratio. To fix this problem, there is [FitVids.js](http://fitvidsjs.com/). Using FitVids.js is as simple as 
    
{% highlight html %}
<script src="path/to/jquery.min.js"></script>
<script src="path/to/jquery.fitvids.js"></script>
<script>
  $(document).ready(function(){
    // Target your .container, .wrapper, .post, etc.
    $("#thing-with-videos").fitVids();
  });
</script>
{% endhighlight %}

Here is the result.

<a href="/responsive_web_design/naivevideo.html" class="demoButton">DEMO(naivevideo.html)</a>
    
Banner Texts
------------

Lastly, there is banner texts. Sometimes you want to make your text really really big
so as to maximize its impact. But big text for a large screen could go complete off-screen for small 
screens, and a big text for a small screen won't be so big for large screens. [FitText.js](http://fittextjs.com/) can help you with that. It will size the text size of a banner depending on the size of the display.

References and Resources
------------------------

- The [original responsive design article](http://www.alistapart.com/articles/responsive-web-design/) by Ethan Marcotte
- The [book](http://www.abookapart.com/products/responsive-web-design)
- [HTML5 Please](http://html5please.us/) recommends using media queries
- [Beginners Guide](http://thinkvitamin.com/design/beginners-guide-to-responsive-web-design/) from Think Vitamin
- [Super Showcase](http://designmodo.com/responsive-design-examples/) from Designmode</content>
        </entry>,<entry>
            <title>Fun with ASTs and Uglify</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2012/01/04/fun-with-asts-and-uglify">
            <updated>2012-01-04T05:00:00.000Z</updated>
            <id>http://tobyho.com/2012/01/04/fun-with-asts-and-uglify</li>
            <content type="text">
Pop quiz, hot shot! You got some unit-tests. You want to know whether it's written in QUnit or Jasmine. What do you do? *What do you do?*

Get a Javascript parser... [Uglify](https://github.com/mishoo/UglifyJS)! Install it for node

    npm install uglify-js
    
Read in the file and parse it to get an AST

{% highlight js %}
var parser = require('uglify-js').parser
  , fs = require('fs')
  , filename = process.argv[0]
var ast = parser.parse(String(fs.readFileSync(filename)))
{% endhighlight %}

Print out the AST

{% highlight js %}
console.log(JSON.stringify(ast))
{% endhighlight %}

Look at the AST for an example QUnit test file

{% highlight js %}
[
  "toplevel",
  [
    [
      "stat",
      [
        "call",
        [
          "name",
          "test"
        ],
        [
          [
            "string",
            "validate phone #"
          ],
          [
            "function",
            null,
            [],
            [
              [
                "stat",
                [
                  "call",
                  [
                    "name",
                    "ok"
                  ],
                  [
                    [
                      "call",
                      [
                        "name",
                        "validatePhone"
                      ],
                      [
                        [
                          "string",
                          "770 123 4567"
                        ]
                      ]
                    ],
                    [
                      "string",
                      "basic"
                    ]
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ],
    [
      "stat",
      [
        "call",
        [
          "name",
          "test"
        ],
        [
          [
            "string",
            "no non-numbers"
          ],
          [
            "function",
            null,
            [],
            [
              [
                "stat",
                [
                  "call",
                  [
                    "name",
                    "equal"
                  ],
                  [
                    [
                      "name",
                      "false"
                    ],
                    [
                      "call",
                      [
                        "name",
                        "validatePhone"
                      ],
                      [
                        [
                          "string",
                          "a"
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                "stat",
                [
                  "call",
                  [
                    "name",
                    "equal"
                  ],
                  [
                    [
                      "name",
                      "false"
                    ],
                    [
                      "call",
                      [
                        "name",
                        "validatePhone"
                      ],
                      [
                        [
                          "string",
                          "?"
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ],
    [
      "stat",
      [
        "call",
        [
          "name",
          "test"
        ],
        [
          [
            "string",
            "must be in right grouping"
          ],
          [
            "function",
            null,
            [],
            [
              [
                "stat",
                [
                  "call",
                  [
                    "name",
                    "equal"
                  ],
                  [
                    [
                      "name",
                      "false"
                    ],
                    [
                      "call",
                      [
                        "name",
                        "validatePhone"
                      ],
                      [
                        [
                          "string",
                          " 3 9 3"
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                "stat",
                [
                  "call",
                  [
                    "name",
                    "equal"
                  ],
                  [
                    [
                      "name",
                      "false"
                    ],
                    [
                      "call",
                      [
                        "name",
                        "validatePhone"
                      ],
                      [
                        [
                          "string",
                          "12 23 2345 3 thuno"
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ],
    [
      "stat",
      [
        "call",
        [
          "name",
          "test"
        ],
        [
          [
            "string",
            "dashes are ok"
          ],
          [
            "function",
            null,
            [],
            [
              [
                "stat",
                [
                  "call",
                  [
                    "name",
                    "ok"
                  ],
                  [
                    [
                      "call",
                      [
                        "name",
                        "validatePhone"
                      ],
                      [
                        [
                          "string",
                          "770-123-4567e"
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ]
  ]
]
{% endhighlight %}

Do the same for an example Jasmine test file

{% highlight js %}
[
  "toplevel",
  [
    [
      "stat",
      [
        "call",
        [
          "name",
          "describe"
        ],
        [
          [
            "string",
            "hello"
          ],
          [
            "function",
            null,
            [],
            [
              [
                "stat",
                [
                  "call",
                  [
                    "name",
                    "it"
                  ],
                  [
                    [
                      "string",
                      "should say hello"
                    ],
                    [
                      "function",
                      null,
                      [],
                      [
                        [
                          "stat",
                          [
                            "call",
                            [
                              "dot",
                              [
                                "call",
                                [
                                  "name",
                                  "expect"
                                ],
                                [
                                  [
                                    "call",
                                    [
                                      "name",
                                      "hello"
                                    ],
                                    []
                                  ]
                                ]
                              ],
                              "toBe"
                            ],
                            [
                              [
                                "string",
                                "hello world"
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                "stat",
                [
                  "call",
                  [
                    "name",
                    "it"
                  ],
                  [
                    [
                      "string",
                      "should not say not hello"
                    ],
                    [
                      "function",
                      null,
                      [],
                      [
                        [
                          "stat",
                          [
                            "call",
                            [
                              "dot",
                              [
                                "call",
                                [
                                  "name",
                                  "expect"
                                ],
                                [
                                  [
                                    "call",
                                    [
                                      "name",
                                      "hello"
                                    ],
                                    []
                                  ]
                                ]
                              ],
                              "toNotBe"
                            ],
                            [
                              [
                                "string",
                                "not hello world"
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                "stat",
                [
                  "call",
                  [
                    "name",
                    "it"
                  ],
                  [
                    [
                      "string",
                      "should throw exception"
                    ],
                    [
                      "function",
                      null,
                      [],
                      [
                        [
                          "throw",
                          [
                            "new",
                            [
                              "name",
                              "Error"
                            ],
                            [
                              [
                                "string",
                                "Crap"
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                "stat",
                [
                  "call",
                  [
                    "name",
                    "it"
                  ],
                  [
                    [
                      "string",
                      "should throw another exception"
                    ],
                    [
                      "function",
                      null,
                      [],
                      [
                        [
                          "throw",
                          [
                            "new",
                            [
                              "name",
                              "Error"
                            ],
                            [
                              [
                                "string",
                                "Blah"
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                "stat",
                [
                  "call",
                  [
                    "name",
                    "it"
                  ],
                  [
                    [
                      "string",
                      "should throw even more exceptions"
                    ],
                    [
                      "function",
                      null,
                      [],
                      [
                        [
                          "throw",
                          [
                            "new",
                            [
                              "name",
                              "Error"
                            ],
                            [
                              [
                                "string",
                                "Foobar"
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                "stat",
                [
                  "call",
                  [
                    "name",
                    "it"
                  ],
                  [
                    [
                      "string",
                      "should be firefox"
                    ],
                    [
                      "function",
                      null,
                      [],
                      [
                        [
                          "stat",
                          [
                            "call",
                            [
                              "dot",
                              [
                                "call",
                                [
                                  "name",
                                  "expect"
                                ],
                                [
                                  [
                                    "dot",
                                    [
                                      "name",
                                      "navigator"
                                    ],
                                    "userAgent"
                                  ]
                                ]
                              ],
                              "toMatch"
                            ],
                            [
                              [
                                "regexp",
                                "Firefox",
                                ""
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                "stat",
                [
                  "call",
                  [
                    "name",
                    "it"
                  ],
                  [
                    [
                      "string",
                      "should do async"
                    ],
                    [
                      "function",
                      null,
                      [],
                      [
                        [
                          "stat",
                          [
                            "call",
                            [
                              "name",
                              "waits"
                            ],
                            [
                              [
                                "num",
                                1000
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ]
  ]
]
{% endhighlight %}

List some common patterns for the AST for the QUnit example

    "call",
    [
      "name",
      "test"
    ],
    [
      [
        "string",
        
,

    "call",
    [
      "name",
      "ok"
    ],
    
and

    "call",
    [
      "name",
      "equal"
    ],
        
List some common patterns for the AST for the Jasmine example

    "call",
    [
      "name",
      "describe"
    ],
    [
      [
        "string",
        
,
    
    "call",
    [
      "name",
      "it"
    ],
    [
      [
        "string",
        
and
    
    "call",
    [
      "name",
      "expect"
    ],
        
Traverse the ASTs and match against these patterns and count the occurances of all patterns, grouping by framework.

So, first a function to traverse the AST

{% highlight js %}
function traverse(node, visit){
    visit(node)
    if (node instanceof Array){
        for (var i = 0, len = node.length; i < len; i++)
            traverse(node[i], visit)
    }
}
{% endhighlight %}

Write the pattern detectors as functions

{% highlight js %}
var patterns = {
    jasmine: [
        function(node){
            return node[0] === 'call' &&
                node[1][0] === 'name' &&
                node[1][1] === 'describe' &&
                node[2][0][0] === 'string'
        },
        function(node){
            return node[0] === 'call' &&
                node[1][0] === 'name' &&
                node[1][1] === 'it' &&
                node[2][0][0] === 'string'
        },
        function(node){
            return node[0] === 'call' &&
                node[1][0] === 'name' &&
                node[1][1] === 'expect'
        }
    ],
    qunit: [
        function(node){
            return node[0] === 'call' &&
                node[1][0] === 'name' &&
                node[1][1] === 'test' &&
                node[2][0][0] === 'string'
        },
        function(node){
            return node[0] === 'call' &&
                node[1][0] === 'name' &&
                node[1][1] === 'ok'
        },
        function(node){
            return node[0] === 'call' &&
                node[1][0] === 'name' &&
                node[1][1] === 'equal'
        }
    ]
}
{% endhighlight %}

Keep a tally

{% highlight js %}
var tally = {
    jasmine: 0,
    qunit: 0
}
{% endhighlight %}

Now actually traverse the AST, try to match the patterns and count the number of hits

{% highlight js %}
function patternMatches(node, test){
    try{
        return test(node)
    }catch(e){
        return false
    }
}

function detectPatterns(node){
    for (var framework in patterns){
        patterns[framework].forEach(function(pat, idx){
            if (patternMatches(node, pat)){
                tally[framework]++
            }
        })
    }
}

traverse(ast, detectPatterns)
{% endhighlight %}

How many hits did we get for QUnit vs Jasmine?

{% highlight js %}
for (var key in tally){
    console.log(tally[key] + ' points for ' + key + '.')
}
{% endhighlight %}

Is that your final answer?

{% highlight js %}
console.log('Tests were written in ' + (tally.qunit > tally.jasmine ?
    'QUnit': 'Jasmine') + '.')
{% endhighlight %}

Sample output

    airportyh$ node detect.js tests.js
    0 points for jasmine.
    10 points for qunit.
    Tests were written in QUnit.
    airportyh$ node detect.js specs.js
    11 points for jasmine.
    0 points for qunit.
    Tests were written in Jasmine.
    
Full script at [this gist](https://gist.github.com/1558769).</content>
        </entry>,<entry>
            <title>Cisco VPN Setup on OSX</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/12/22/cisco-vpn-osx">
            <updated>2011-12-22T05:00:00.000Z</updated>
            <id>http://tobyho.com/2011/12/22/cisco-vpn-osx</li>
            <content type="text">
For working remotely I've been using the Cisco VPN Client on OSX for about 3 years. 
What recollections I have about the installation procedure is that
*the installation file for OSX is extremely hard to find on the Cisco web site*.
After registering as a user and then clicking on a series of navigation trees and 
links and download buttons, sometimes you still had no luck, and if I had to do it all over 
again, I probably still would have a hard time just finding the file.

Recently, I had to help someone else set this up on Snow Leopard, and to my chagrin, failed
to locate that file on the Cisco web site - who knows, maybe they've removed it completely: 
their Mac version already seem far behind 3 years ago. 
Then I tried copying over the CiscoVPN application - that did not work. It was an overall failure.
But, I had a second
crack at this when I got a new laptop myself. I am the first in my family to have the Lion OS,
so I decided to have a go at Google adding "lion" in the search term, i.e. "cisco vpn osx lion". 
It turned up [this StackExchange post](http://apple.stackexchange.com/questions/17823/how-can-i-make-the-cisco-vpn-client-work-with-lion)which turned up [a solution](http://apple.stackexchange.com/a/18511/9196) that's ten times better
then Cisco's crappy website and software.

The [SE answer](http://apple.stackexchange.com/a/18511/9196) is great, but I'll repeat it here
nonetheless because I am so outraged this isn't more widely known and there are still
unsuspecting folks out there trying to go through the hideous trap that is the crappy Cisco 
web site.

*As it turns out, you don't even have to install anything.* OSX has a Cisco-compatible VPN protocol built-in. Here's how you set it up.

Step 1
------
Make sure you have the VPN connection info, you should have gotten this from your IT department.
This should include a *server IP address*, a *group name* and a *secret*. Also make sure you
have your *user name* and *password* - this should be the normal login you use day-to-day
at the office.

Step 2
------
Go to `System Preferences`, click on `Network`.

Step 3
------
Click on the `+` button on the bottom left to add a network. In the popup: select `VPN` for *Interface*, and then `Cisco IPSec` for *VPN Type*. Choose a memorable name for yourself for *Service Name*. Click `Create`.

Step 4
------
Type in your *Server Address*, *Account name* (user name) and *Password*. Then click on `Authentication Settings...` and fill out *Group name* and *Shared Secret*. Click `OK`.

Step 5
------
Click on `Connect` to test the connection. I also like to check *Show VPN status in menu bar*,
that way I can always see the status and be able to connect and disconnect from right there.

Did That Work For You?
----------------------
If you are running into this problem, I hope this procedure did the trick for you. If not,
check the [SE answer](http://apple.stackexchange.com/a/18511/9196) for more clues, or 
leave a comment, and maybe I can help.
</content>
        </entry>,<entry>
            <title>Simple Markdown-based Presentation Tool: Preston</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/12/21/preston-presentation-tool">
            <updated>2011-12-21T05:00:00.000Z</updated>
            <id>http://tobyho.com/2011/12/21/preston-presentation-tool</li>
            <content type="text">
Recently, while preparing for a presentation, I decided to build yet another presentation tool
(*yak-shaving*, I know). 

I had been using [my S5-based hack](https://github.com/airportyh/QuickSlides) so far, but 
the pain points I came across were

1. I tend to to do [Takahashi style](http://en.wikipedia.org/wiki/Takahashi_method) presentations
(big text, big graphics), which S5's layout is not tailored for.
2. I found I spend a lot of time memorizing what I am going to say during the presentation.

Demo
----

The result is Preston. Let's **[see it in action](http://airportyh.github.com/Preston/)**.

In the demo I have a mock demo of a presentation for Preston itself. Once you "Start Presentation",
a second window appears which runs the slides. The original window has the contents of the slides
and your notes side-by-side. So, during the presentation, I would choose to have
the projector **not** mirror my laptop screen, put the presentation window on the projector screen,
and leave the notes window in my laptop screen, so that I can see it but not the audience.

Writing the Presentation
------------------------

The format of the presentation file looks like this

    Slide 1

        (these are the notes) Hello, this is slide 1 where I will
        talk about topic one for about 10 seconds.

    Slide 2

        Now I will talk about slide 2 for a few seconds as well.
            
Here we have two slides. The first slide will consist of the text "Slide 1" and the second
"Slide 2". The indented text below each of them are the notes for that slide, which
will be on your second screen and invisible to the audience during the presentation.

Markdown
--------

Both the content for the slides and the notes are run through Markdown,
so you can use things like links and images, and a lot more.

More Info
---------

Go to Github and checkout the [README](http://github.com/airportyh/Preston) for more info if 
you are thinking about actually using this.



</content>
        </entry>,<entry>
            <title>The Jasmine Spy Cheatsheet</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/12/15/jasmine-spy-cheatsheet">
            <updated>2011-12-15T05:00:00.000Z</updated>
            <id>http://tobyho.com/2011/12/15/jasmine-spy-cheatsheet</li>
            <content type="text">

*Update: If you are using Jasmine 2.0 or above, the information here is out of date! Please go to <http://jasmine.github.io/2.0/introduction.html#section-Spies> instead.*

*Wanna be a spy fast? Well you are in luck!*

Just kidding! This is actually a cheatsheet for [Jasmine](http://pivotal.github.com/jasmine/) [Spies](https://github.com/pivotal/jasmine/wiki/Spies). 

See, while Jasmine itself is very intuitive to use, every time use spies I have to look up [the](https://github.com/pivotal/jasmine/wiki/Spies) [docs](http://pivotal.github.com/jasmine/jsdoc/symbols/jasmine.Spy.html). I would blame it on the poorly chosen method/property names, but I won't. Instead I finally wrote myself a cheatsheet. I hope it helps other folks too.

How to spy on a method?
-----------------------

{% highlight js %}
spyOn(obj, 'method') // assumes obj.method is a function
{% endhighlight %}   
    
How to verify it was called?
----------------------------

{% highlight js %}
expect(obj.method).toHaveBeenCalled()
{% endhighlight %}
    
How to verify it was called with specific arguments?
----------------------------------------------------
    
{% highlight js %}
expect(obj.method).toHaveBeenCalledWith('foo', 'bar')
{% endhighlight %}

How many times was it called?
-----------------------------

{% highlight js %}
obj.method.callCount
{% endhighlight %}
    
What were the arguments to the last call?
----------------------------------------

{% highlight js %}
obj.method.mostRecentCall.args
{% endhighlight %}
    
How to reset all the calls made to the spy so far?
--------------------------------------------------

{% highlight js %}
obj.method.reset()
{% endhighlight %}
    
How to make a standalone spy function?
--------------------------------------

{% highlight js %}
var dummy = jasmine.createSpy('dummy')
$('button#mybutton').click(dummy)
{% endhighlight %}
    
How to have spied method also calls through to the real function?
-----------------------------------------------------------------

{% highlight js %}
spyOn(obj, 'method').andCallThrough()
{% endhighlight %}

*Update: if you are using Jasmine 2, `andCallThrough()` has been changed to `and.callThrough()`.*
    
How to get all arguments for all calls that have been made to the spy?
----------------------------------------------------------------------

{% highlight js %}
obj.method.argsForCall // this is an array
{% endhighlight %}
    
How do I fix the return value of a spy?
---------------------------------------

{% highlight js %}
spyOn(obj, 'method').andReturn('Pow!')
{% endhighlight %}

*Update: if you are using Jasmine 2, `andReturn(value)` has been changed to `and.returnValue(value)`.*</content>
        </entry>,<entry>
            <title>7 Common Javascript Mistakes or Confusions</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/11/16/7-common-js-mistakes-or-confusions">
            <updated>2011-11-16T05:00:00.000Z</updated>
            <id>http://tobyho.com/2011/11/16/7-common-js-mistakes-or-confusions</li>
            <content type="text">
While helping folks with Javascript on [Stackoverflow](http://stackoverflow.com/) or IRC, I've noticed some common mistakes or confusions. I've made a list of these in my little notebook and have been covering each of them in a different blog post over the last month or so. This post wraps up this series: and the *7 common Javascript mistakes or confusions* are:

1. **Not using `var` to declare your variables.** This will work but will make your variables global, which will likely become a source of strange errors later down the road. [Always use `var`.](/2011/10/25/js-accidental-global-variables/)

2. **Calling your callbacks before you mean to.** certain browser API's or libraries expect functions as arguments, don't [prematurely call the function](/2011/10/26/js-premature-invocation/) before passing it in.

3. **Expecting `this` to be something else.** Often when you create a callback function within another function, the value that's bound to `this` - or the *context* - changes. Understanding how context is bound is helpful here, and often, the simplest fix is to [save `this` into a variable](/2011/10/27/save-this-for-later/) just outside the callback.

4. **Incorrectly making callback functions in loops.** Creating callback functions - such as event handlers inside of a loop can get tricky - it may not do what you'd expect if it depends on the loop counter. The [solution](/2011/11/02/callbacks-in-loops/) is to introduce yet another function to act as a closure.

5. **Processing intensive tasks without locking up the browser.** Sooner or later in a Javascripter's life, you will encounter a case when you need to process a lot of data, and the processing takes so long that the entire browser becomes unresponsive. But, in Javascript you can't simply use a `sleep(1)` like some other languages to yield execution in the loop. The solution is a mix of [task queuing and async programming](/2011/11/03/delaying-repeatedly/) using `setTimeout`.

6. **Coping with life without a compiler.** Programmers coming from a background of a compiled programming language will often find it frustrating that there isn't a compiler to catch errors for you in Javascript. The solution is to use the [interactive console](/2011/11/09/life-without-compiler/) to aid your development process - *I also made an [8-minute screencast](/2011/11/09/life-without-compiler/) on using the console.*

7. **Grokking OOP in Javascript.** Object-oriented programming in Javascript is very different from pretty much any mainstream programming language, and is a big source of confusion for new Javascripters. No worries, this [crash course on Javascript object inheritance](/2011/11/11/js-object-inheritance/) will guide you through it, starting with first principles.

*Happy coding!*</content>
        </entry>,<entry>
            <title>Objects and Inheritance in Javascript</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/11/11/js-object-inheritance">
            <updated>2011-11-11T05:00:00.000Z</updated>
            <id>http://tobyho.com/2011/11/11/js-object-inheritance</li>
            <content type="text">
While some Javascript users may never have to know about prototypes or the object-oriented nature of the language, those coming from a traditional object-oriented programming language will poke around, and then find the inheritance model *very* odd. What confuses the matter more is the fact that different JS frameworks have their own [convenience](http://mootools.net/docs/core/Class/Class) [helpers](http://dojotoolkit.org/reference-guide/dojo/declare.html) for writing *class-like* code, the result of which is that

1. there isn't *one standard way* to do it, and
2. the underlying concepts are not as well known as they should be.

### Prototype Inheritance

Prototype Inheritance is actually a very simple concept. Its essence is this:

1. An object `a` can inherit from another object `b`. `b` is said to be `a`'s *prototype*.
2. `a` inherits all of `b`'s properties, i.e. if `b.x` is 1, then `a.x` is also 1 automatically.
3. `a`'s own properties override those of `b`. 

Let's see that in action. Let's say we have a John Smith and a Jane that inherits John.

{% highlight js %}
> var john = {firstName: 'John', lastName: 'Smith'}
> var jane = {firstName: 'Jane'}
jane.__proto__ = john
{% endhighlight %}

at this point, we say `john` is `jane`'s prototype, and `jane` inherits `john`'s properties

{% highlight js %}
> jane.lastName
"Smith"
{% endhighlight %}

`jane`'s own property takes precedence though

{% highlight js %}
> jane.firstName
"Jane"
{% endhighlight %}

Even if you add a property to `john` after the fact, `jane` will still inherit it - *dynamically*

{% highlight js %}
> john.hair = 'brown'
> jane.hair
"brown"
{% endhighlight %}

Now, let's say Jane gets married - and therefore a new last name.

{% highlight js %}
> jane.lastName = 'Doe'
{% endhighlight %}

Again, it will override `john`'s `lastName`

{% highlight js%}
> jane.lastName
"Doe"
{% endhighlight %}

but if we delete `jane`'s `lastName` now

{% highlight js %}
> delete jane.lastName
{% endhighlight %}

it will revert to being inherited from `john`

{% highlight js %}
> jane.lastName
"Smith"
{% endhighlight %}

Now, `john` can inherit from other objects too. There can be any number of inheritances in this chain, which we call the *prototype chain*. In fact, `john` *does* has a prototype

{% highlight js %}
> john.__proto__
Object { }
{% endhighlight %}

The result of `john.__proto__` is rendered as `Object { }` in the [Firebug console](http://getfirebug.com/), but it represents the object `Object.prototype` - the ancestor of all objects.

So, that is prototype inheritance in a nutshell. There! That wasn't so bad, was it?

### Well, actually... we can't use `__proto__`

*I've got bad news...*

`__proto__` isn't supported in IE. In fact, `__proto__` isn't in the ECMAScript spec and Mozilla is even thinking about dropping it in an upcoming version of Firefox. 

That doesn't mean it doesn't exist though. Even on browsers where `__proto__` is inaccessible, it is still there under the covers, and we still have to deal with it, just in a more roundabout way.

### Classes and Inheritance

So, Javascript doesn't have classes.

Repeat after me: *Javascript doesn't have classes.*

> Okay, then how do methods and inheritance work?

By using prototypes. Whereas in classic OO languages, methods hang off of classes, in Javascript, methods hang off of the prototype of the object, *and*, the prototype in question is tied to the constructor of the object.

In Javascript, functions double as constructors. You call a function *as a constructor* by using the `new` operator. For example if we create a `Cat` function

{% highlight js %}
> function Cat(name){  // <- just a regular function
    this.name = name   // `this` refers to the object instance being made
}
{% endhighlight %}

a new object `Cat.prototype` gets created automatically.

{% highlight js %}
> Cat.prototype
Cat { }
{% endhighlight %}

we can create a new instance of `Cat` using `new`

{% highlight js %}
var garfield = new Cat('Garfield')   // makes a cat - acts as a constructor
{% endhighlight %}

now, `Cat.prototype` becomes the prototype of each object that's created via `new Cat()`, e.g. `garfield`.

{% highlight js %}
> garfield.__proto__ === Cat.prototype
true // see? `Cat.prototype` is now garfield's prototype
{% endhighlight %}

Now we can hang a method off of `Cat.prototype` and it will be available for `garfield`.

{% highlight js %}
> Cat.prototype.greet = function(){
    console.log('Meow, I am ' + this.name)
}
> garfield.greet()
"Meow, I am Garfield"
{% endhighlight %}

It will be available for other cats too

{% highlight js %}
var felix = new Cat('Felix')
felix.greet()
"Meow, I am Felix"
{% endhighlight %}

So, in Javascript, methods live on the object's prototype.

Well actually, you can hang methods off of `garfield` itself too; it will override the one on `Cat.prototype`

{% highlight js %}
> garfield.greet = function(){
    console.log("What's new?")
}
> garfield.greet()
"What's new?"
{% endhighlight %}

But it won't affect the other cats

{% highlight js %}
> felix.greet()
"Meow, I am Felix"
{% endhighlight %}

So, a method can live directly on an object itself, a method can live on an object's prototype. A method can also live on any ancestor of an object, i.e. any part of the *prototype chain*. This is how inheritance is achieved.

To create a second level prototype chain, we first need to create another constructor. How about `Animal`?

{% highlight js %}
> function Animal(){
}
{% endhighlight %}

Okay, now we need `Cat.prototype`'s prototype to be an animal, so that a cat will inherit any of animal's methods as well. To do this, we set `Cat.prototype` to an instance of `Animal`.

{% highlight js %}
> Cat.prototype = new Animal
{% endhighlight %}

One more thing: we also want to tell our new `Cat.prototype` that it is, in fact, an instance of `Cat`

{% highlight js %}
> Cat.prototype.constructor = Cat    // letting `Cat.prototype` 
                                     // know that it is a cat
{% endhighlight %}

This is done mainly for housekeeping purposes, but necessary in general.

Now, since an animal inherits from `Animal.prototype` and `Cat.prototype` is an animal, all cats also inherit `Animal.prototype` indirectly. We can add a method to `Animal.prototype` and it will be available to any cat instance.

{% highlight js %}
> Animal.prototype.breed = function(){
    console.log('Making a new animal!')
    return new this.constructor()
}
> var kitty = garfield.breed()
Making a new animal!
{% endhighlight %}

Cool, we just did inheritance!

Conclusion
----------

Prototype inheritance in Javascript is pretty strange and will take some getting used to, but it is simple at heart. As long as you understand the underlying concepts you will be able to navigate OO Javascript code in the wild (both good and bad) with confidence.</content>
        </entry>,<entry>
            <title>Coping with Life Without The Compiler</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/11/09/life-without-compiler">
            <updated>2011-11-09T05:00:00.000Z</updated>
            <id>http://tobyho.com/2011/11/09/life-without-compiler</li>
            <content type="text">
For developers who are used to compiled programming languages like Java, C#, or C++, Javascript's loosely-typed nature can be off-putting. Common complaints I've heard are

1. it doesn't catch obvious errors like parameter type mismatch or misspelled names
2. some popular libraries - like jQuery - silently ignore bad inputs rather than throwing exceptions/errors

Invariably, discussions turn into laments on why Javascript is so bad, and what we can do to improve the language, and that maybe we should all just use Coffeescript, or Dart, or Objective-J, etc, etc.

I have a different take on this, which is best expressed with a quote from the great Steve Jobs

> You're holding it wrong.

Dynamic languages have different affordances than compiled languages, and their users tend to have different usage patterns. If you are programming Javascript the same way you were programming Java, chances are, you are missing out.

Compiled vs Dynamic (100% Unbiased)
---------------------------------

Compiled languages are... *compiled*. To test your program, you have to first compile it, and then run it. Compiling is sometimes a lengthy process, but the good news is the compiler can find errors for you - using type checking for example, *and*, it will stop at the first error encountered, so that you don't have to wait through an otherwise lengthy compile. So, for compiled languages: *the more mistakes the compiler can catch for you, the more pleasant life will be.*

Dynamic languages on the other hand, are interpreted - there is no compile step. In order to check your program for mistakes, you have to run it. Although there is no compilation step, it is still true that the earlier you can catch your mistakes the better. A syntax error is better than a runtime error, and a runtime error that appears right away is far better than one that appears after several interactions with the UI. It turns out there's a shortcut to uncover your mistakes earlier - the *interactive console*.

The Interactive Console
-----------------------

The interactive console, a.k.a. REPL(read-eval-print-loop) allows you to execute small snippets of code and see their results quickly. It works very much like a command line shell for any unix or Windows: you type in a command, hit enter, it executes the command, prints out the result, and then you start over again.

When should you use the console? *All the time.* It's great for figuring out small bits of code that are tricky to get right, like regular expressions, or for examining the DOM on the page using the DOM API. It is also great for figuring out how to use a certain API in a third party library like jQuery.

[Firebug](http://getfirebug.com/) has a Javascript console, and all other major browsers have one built-in as well. But seeing is believing, so here is a video of Firebug in action.

<div class="video">
<iframe src="http://player.vimeo.com/video/31849127?title=0&amp;byline=0&amp;portrait=0" width="550" height="413" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>  
</div>

Conclusion
----------

If you haven't already, integrating the JS console into your workflow will give you a big productivity boost. If you find yourself feeling frustrated that Javascript or jQuery is not catching errors earlier for you, you are probably not using the interactive console nearly enough. Use it. Use it a *lot!*

</content>
        </entry>,<entry>
            <title>Delaying Repeatedly</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/11/03/delaying-repeatedly">
            <updated>2011-11-03T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/11/03/delaying-repeatedly</li>
            <content type="text">
Sooner or later, a Javascripter will eventually encounter a situation where they have a loop that takes so long to process that the browser becomes unresponsive. To solve this, you have some options

1. optimize the loop so that it always runs under 100ms - the [maximum response time](http://www.mattson.com.au/robert/files/Miller1968.pdf) that doesn't affect user experience
2. offload the processing to the server
3. Use [webworker](https://developer.mozilla.org/en/Using_web_workers), but it doesn't yet have [great browser support](http://caniuse.com/webworkers), and they can't touch the DOM
4. put a wait inside the body of the loop so as to let the browser *breath*

If you've exhausted options #1-3, read on.

To do #4, most people would approach it this way

{% highlight js %}
for (var i = 0, len = items.length; i < len; i++){
    processItem(items[i])
    sleep(10)   // sleep to yield
}
{% endhighlight %}
This would work in C or Python, but not Javascript. Javascript does not have a `sleep` or equivalent function that would just halt program execution. In fact, a function like this wouldn't work in the browser because Javascript is single threaded, and a function that blocks execution like that will freeze up the browser right away.

So, to achieve the same thing in Javascript, we have to use the [`setTimeout` function](https://developer.mozilla.org/en/window.setTimeout) - which using the non-blocking IO paradigm.

Easy right? So we just replace the `sleep` call with `setTimeout`.

{% highlight js %}
for (var i = 0, len = items.length; i < len; i++){
    setTimeout(function(){
        processItem(items[i])
    }, 10)   // sleep to yield
}
{% endhighlight %}

There are two problem with this code. Let's address the first one [else where](http://tobyho.com/2011/11/02/callbacks-in-loops/). The second problem is: rather than spacing out the function calls with pauses in between them, this will schedule a bunch of jobs(one for each item) to be performed on the event queue all at once, the event queue will have to work just as hard as if we had just done the processing within the loop.

`setTimeout`
------------

The `setTimeout` function

1. is asynchronous
2. uses the callback style of control flow, [do you grok callbacks](http://tobyho.com/2011/10/26/js-premature-invocation/)?

In order to cope with this non-synchronous style, we'll have to do away with the *for-loop* altogether. Here is how we'd do that

{% highlight js %}
var queue = items.slice(0)              // 1. make a copy of the array, because
                                        //    we are going to modify it
function processNextItem(){             
    var nextItem = queue.shift()        // 2. take the next item off the array
    if (nextItem){
        processItem(nextItem)           // 3. process this item
        setTimeout(processNextItem, 10) // 4. give the browser a little time to breath
                                        //    start again in 10ms
    }
}
processNextItem()                       // 5. kick it off with the first
                                        //    call to this function
{% endhighlight %}

This "loop" will give you the desired result: processing all the items without locking up the browser. Great!

Improving the Running Time
--------------------------

However, the problem with this approach is that it would lengthen the total processing time substantially. For example, let's say you need to process 10000 items, and it takes 1ms to process each item. If you had process them all within a loop(with no breathing), it would take you 10000 x 1ms = 10000ms. But, using the above method, because of the added 10ms delay for each item, it would take you 10000 x (10ms + 1ms) = 110000ms. So, while the browser isn't totally frozen and the user can still interact with the page, it will take more than 10 times as long to finish processing, and as a result, the user could very well be watching an interminable progress bar.

We can improve this by processing the items in batches. Process 100 items at a time, for example. This would reduce the total process time to (10000 / 100) * (10ms + 100 * 1ms) = 11000ms: *much better* - only 10% slower than processing with no breathing.

Dynamic Batch Sizes
-------------------

Now, about the batch size of 100, we chose 100 because we know the processing time for a batch will stay within the 100ms threshold of responsiveness. But what if the processing time of an item is not easily predictable? Or, what if we wanted to write a generic processing routine that would work well with different types of jobs? What if we can dynamically figure out the batch size for which the processing time will stay within 100ms? We can do all of the above with a timer

{% highlight js %}
var queue = items.slice(0)                                 
function processNextBatch(){
    var nextItem,
        startTime = +new Date
    while(startTime + 100 >= +new Date){
        nextItem = queue.shift()
        if (!nextItem) return
        processItem(nextItem)
    }
    setTimeout(processNextBatch, 10)
}
processNextBatch()                          
{% endhighlight %}

*Cool!* We can generalize this more still by turning it into a reusable function

{% highlight js %}
function processItems(items, processItem, delay){
    delay = delay || 10
    var queue = items.slice(0)                                 
    function processNextBatch(){
        var nextItem,
            startTime = +new Date
        while(startTime + 100 >= +new Date){
            nextItem = queue.shift()
            if (!nextItem) return
            processItem(nextItem)
        }
        setTimeout(processNextBatch, delay)
    }
    processNextBatch()
}
{% endhighlight %}

So now we can go crazy with it
{% highlight js %}
processItems(locations, plotOnGoogleMap)
{% endhighlight %}
or
{% highlight js %}
processItems(polygons, drawOnCanvas)
{% endhighlight %}

Reference
---------

- [Book: High Performance Javascript (Chapter 6)](http://www.amazon.com/Performance-JavaScript-Faster-Application-Interfaces/dp/059680279X)
- Paper: Response time in man-computer transactions - Robert Miller</content>
        </entry>,<entry>
            <title>Callbacks in Loops</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/11/02/callbacks-in-loops">
            <updated>2011-11-02T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/11/02/callbacks-in-loops</li>
            <content type="text">
Once every so often, you'll need to create a callback function while inside a loop. Let's say you are trying to register a click handler for every link you have in the page.

{% highlight js %}
var links = documnet.getElementsByTagName('a')
for (var i = 0, len = links.length; i < len; i++){
    // Note: `addEventListener` is standard compliant browsers only
    links[i].addEventListener('click', function(e){
        alert('You clicked on link ' + i)
    }, false)
}
{% endhighlight %}

Any time a link is clicked, you'll open an alert popup dialog telling them the index of the link that was clicked on. Pretty useful. Except, it *doesn't work*.

What will *actually* happen is the alert popup will say "You clicked on link 5" every time - supposing that you have 5 links on your page. The reason this happens is because each callback function you created(one for each loop iteration) refers to the same the variable `i`. That is, although `var i` is declared at the beginning of the *for-loop*, it is not lexically scoped, i.e. a new version of `i` does not get creating for each iteration of the loop. In fact, `i` could have been declared outside of the loop and it wouldn't have made a difference

{% highlight js %}
var links = documnet.getElementsByTagName('a')
var i
for (i = 0, len = links.length; i < len; i++){
    /* blah blah */
}
{% endhighlight %}

The workaround for this problem is to create an `outer` function and pass the parameter `i` to it - immediately executing it.

{% highlight js %}
var links = documnet.getElementsByTagName('a')
for (var i = 0, len = links.length; i < len; i++){
    !function outer(i){
        links[i].addEventListener('click', function inner(e){
            alert('You clicked on link ' + i)
        }, false)
    }(i)
}
{% endhighlight %}

*Note: We also labeled the callback handler function `inner` so as to distinguish the two functions.*

The `outer` function is also called an [IIFE](http://benalman.com/news/2010/11/immediately-invoked-function-expression/) - it get created and then immediately executed, and then thrown away. (There are [other ways](http://benalman.com/news/2010/11/immediately-invoked-function-expression/) to write it - I just prefer the version with the *!*) The reason we need it is because we need a new variable scope, and in Javascript, a function is the only way to create one.

It is important to note that outside of `outer`, `i` still resolves to the same `i` that was declared at the beginning of the *for-loop*, but inside the function, `i` is declared as a function parameter, making it a local variable of the function - which take precedence over the outside `i`.

{% highlight js %}
!function(i){  // <-- inside `i`
    /* here, `i` refers to inside `i` */
}(i) // <-- still outside `i`
{% endhighlight %}

In fact, let's rename the *inside `i`* to `ii` to make it clearer

{% highlight js %}
var links = documnet.getElementsByTagName('a')
for (var i = 0, len = links.length; i < len; i++){
    !function outer(ii){
        links[i].addEventListener('click', function inner(e){
            alert('You clicked on link ' + ii)
        }, false)
    }(i)
}
{% endhighlight %}

Now `ii` is local to `outer` and `i` is on the outside. Because of *closure*, `ii` will stick around even when the execution of `outer` has finished - a click event will happen much later. In other words, `inner` will hold on to an `ii` that's been orphaned - which no other code can access. But, *that* is what makes it all work.

### *Update*

Jonprins made the comment that creating functions can be expensive and so the outer function is best taken outside of the loop. I agree. So with that optimization the code becomes

{% highlight js %}
function addClickHandler(link, i){
    link.addEventListener('click', function(e){
        alert('You clicked on link ' + i)
    }, false)
}
var links = documnet.getElementsByTagName('a')
for (var i = 0, len = links.length; i < len; i++)
    addClickHandler(links[i], i)
{% endhighlight %}

It's faster and cleaner too!

Conclusion
----------

If you've followed along this far, you should know just a little more about how *closures* work and to watch out for the common problem described in this article associated with loops and callbacks. If you are confused or still unconvinced, drop me a comment.</content>
        </entry>,<entry>
            <title>Save this for Later</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/10/27/save-this-for-later">
            <updated>2011-10-27T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/10/27/save-this-for-later</li>
            <content type="text">
The `this` variable in Javascript is sometimes a source of confusion and frustration for newcomers to the language. If you don't know exactly how binding works, you are never quite sure what `this` refers to.

A commonly made mistake is when you need to create an inlined function within another function. This is commonly needed to make an ajax call, for example

{% highlight js %}
$('#myButton').click(function(){
    $.get(url, function(data){
        render(data)
        $(this).hide() // try to hide the button
    })
})
{% endhighlight %}

Here, the attempt to hide the button will fail, because while `this` did refer to the button within the outer function, it no longer refers to it within the inner function. The solution to this problem is to save `this` into a variable while still within the scope of the outer function

{% highlight js %}
$('#myButton').click(function(){
    var button = this
    $.get(url, function(data){
        render(data)
        $(button).hide() // now, hide the button
    })
})
{% endhighlight %}

> *Great!* We are done, right?

*Not so fast!* Don't you want to know how binding works in its entirety? Allllllllrighty then. 

What in the H is `this`?
------------------------

Let's say we have an object `bob` that has a `name` property

{% highlight js %}
var bob = {name: 'Bob'}
{% endhighlight %}

Let's say you then attach a function to it, like so

{% highlight js %}
bob.greet = function(){
    console.log("Hello, I am " + this.name)
}
{% endhighlight %}

Now, binding will occur - binding `this` to `bob` - whenever you call the function *through* the object `bob`

{% highlight js %}
bob.greet() // prints "Hello, I am Bob"
{% endhighlight %}

which is how the `greet` function was able to access `bob`'s `name` property. `this` is also called the *context*, which I will start referring to it as.

### Auto-bind to `window`

If you call the function all by itself, its context will instead bind to the global `window` object

{% highlight js %}
var greet = bob.greet
greet() // prints "Hello, I am "
{% endhighlight %}

`window` *does* have a `name` property, however most of the time it contains the empty string, which explains why calling `greet()` prints out `"Hello, I am "`.

### Changing the Context with `call` and `apply`

The two ways of calling a function shown above allow you to set the context to either the object that the function is attached to, or the `window` object. But, Javascript also allows you to set the context to any other object you want, using one of the two methods: `call` and `apply`. *This is where it gets interesting.*

{% highlight js %}
var jane = {name: 'Jane'}
greet.call(jane)  // prints "Hello, I am Jane"
greet.apply(jane) // prints "Hello, I am Jane"
{% endhighlight %}

The `call` and `apply` methods are available for all Javascript functions. Both of them execute the function, taking the *context* as their first argument. 

The difference between the two is in how they receive regular arguments to the function. So for example, if our `greet` function also took a normal parameter

{% highlight js %}
function greet(other){
    console.log('Hello ' + other + ', I am ' + this.name)
}
{% endhighlight %}

To pass the `other` parameter to `call()`, we must list it as the second parameter, like so (let's set it to `bob`)

{% highlight js %}
greet.call(jane, bob) // prints "Hello Bob, I am Jane"
{% endhighlight %}

But with `apply` we would instead wrap the argument list with an array - in this case just the element `bob` - and pass the array as the second parameter

{% highlight js %}
greet.apply(jane, [bob])
{% endhighlight %}

This is *real cool!* `call` and `apply` give JS programmers a great deal of flexibility in how they can design their libraries.

But still, how do you *know* what `this` is?
------------------------------------------

Sometimes, as is the case with our jQuery example

{% highlight js %}
$('#myButton').click(function(){
    var button = this
    $.get(url, function(data){
        render(data)
        $(button).hide() // now, hide the button
    })
})
{% endhighlight %}

you can't tell what the context is going to be bound to just by looking at the code. When you pass a function into a library, like jQuery, you need to know what the library will bind the context to - this is part of the contract between the API and its user: so we have to *read the docs*.

In jQuery, [event handlers(look under "Event Handlers"](http://api.jquery.com/bind/) are always bound to the DOM element that triggered the event - this is how we know `this` will be bound to the element `#myButton` within the `click` handler. 

As for the Ajax handler for `$.get`, I actually could not find any documentation on the jQuery site as to what its context is bound to, however, upon runtime inspection, it appears to be a hash of the Ajax parameters that are used for the request. In any case, it doesn't help us, and so we resort to saving the context as a variable in the scope of the click handler when we still can.

Conclusion
----------

Always be sure you know what the `this` is when you need to use it. Don't just assume. *Because when you assume...*</content>
        </entry>,<entry>
            <title>Premature Invocation (or "Not Grokking Callbacks")</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/10/26/js-premature-invocation">
            <updated>2011-10-26T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/10/26/js-premature-invocation</li>
            <content type="text">
Often on Q&A forums you'll see code snippets like
{% highlight js %}
window.onload = letsDoThis()
{% endhighlight %}
or
{% highlight js %}
google.setOnLoadCallback(plotMyCharts(chartData))
{% endhighlight %}
or
{% highlight js %}
$('#my-button').click(console.log('You clicked me!'))
{% endhighlight %}
All of these have the same problem, which I shall call - *Premature Invocation*, i.e. code is run before it's intended to. 

### Functions. Callbacks.

Before explaining what's wrong with the 3 above code snippets, let's take a step back and take a look at functions and the use of them as callbacks.

This is a function
{% highlight js %}
function hello(){
    return "Hello world!"
}
{% endhighlight %}
Saying `hello` by itself gets you back the function
{% highlight js %}
hello  // gives the function `hello` again
{% endhighlight %}
You call the function like this
{% highlight js %}
hello() // gives "Hello world!"
{% endhighlight %}
The addition of the paranthese `()` to the right of the function name invokes the function immediately. *This is important.*

This function can be assigned to a variable like any other value,
{% highlight js %}
var justAnotherFunction = hello
{% endhighlight %}
and can be invoked via their new handle too!
{% highlight js %}
justAnotherFunction()
{% endhighlight %}
they can also be passed to other functions
{% highlight js %}
setTimeout(hello, 1000) // Will call `hello` a second later
{% endhighlight %}
or attached to objects
{% highlight js %}
window.onload = hello   // Will call `hello` when page loads
{% endhighlight %}
In both of last two examples, the function is said to be a *callback*. A callback is usually used for time-delayed events or asynchronous events.

> Don't call me. I'll call you.

They are callbacks in the sense that we give up control of when and how the function will be called, if it gets called at all.

*Note: in both **callback** examples, we do not invoke `hello` directly(there are no parentheses to the right of it), but rather, it gets invoked indirectly - by the taker of our function. Take a deep breath. **It's okay.***

### Callbacks as Strings

In defense of programmers who make this mistake, there's is something about browser programming that contributes greatly to this confusion - the fact that in various places, callbacks can also be given as strings *instead of* functions, as a short-hand. One such example is `setTimeout` - the first argument of `setTimeout` can optionally be a string containing Javascript

{% highlight js %}
setTimeout("hello()", 1000)
{% endhighlight %}

*Note:* this code is *severely* different from `setTimeout(hello(), 1000)` - which as we already discussed, will execute `hello` immediately. When you put quotes around `hello()` as the example above, it will instead be equivalent to wrapping an inline anonymous function around the code in the string

{% highlight js %}
setTimeout(function()
    hello()
}, 1000)
{% endhighlight %}

Another place this happens is when you write callback handlers as tag attributes in your markup, like this

{% highlight html %}
<body onload="letsDoThis()">
{% endhighlight %}

or this

{% highlight html %}
<a id="a" href="#" onclick="someFunc(3.1415926); return false;">
    Click here!
</a>
{% endhighlight %}

that gets converted to

{% highlight js %}
window.onload = function(){
    letsDoThis()
}
{% endhighlight %}

and

{% highlight js %}
a.onclick = function(){
    someFunc(3.1415926); return false;
}
{% endhighlight %}

respectively. You *cannot* assign a string to a handler like that in Javascript though, i.e. this

{% highlight js %}
window.onload = "letsDoThis()"
{% endhighlight %}

will not work.

### Solutions to Premature Invocation

Now, let's come back to the 3 problematic code snippets.
{% highlight js %}
window.onload = letsDoThis()
{% endhighlight %}
*Now do you know what to do?* That's right, let go of those parentheses and be free!
{% highlight js %}
window.onload = letsDoThis
{% endhighlight %}
Okay, now let's look at the second one
{% highlight js %}
google.setOnLoadCallback(plotMyCharts(chartData))
{% endhighlight %}
This one is trickier because we need to pass a parameter to the `plotMyChart`, we can't just do
{% highlight js %}
google.setOnLoadCallback(plotMyCharts)
{% endhighlight %}
because then `google.setOnLoadCallback` won't know to supply our `plotMyChart` with the `chartData`. So, what do we do?
{% highlight js %}
google.setOnLoadCallback(function(){
    plotMyCharts(chartData)
})
{% endhighlight %}
The solution is to introduce a new, unnamed function that wraps around the code we want to execute. Now, the unnamed function can be called without any parameters, and yet `plotMyCharts` is supplied with the correct `chartData` whenever our unnamed function is called(btw, this works because a nifty thing called *closure*). 

The function being unnamed isn't a requirement though, you just as well could have named it
{% highlight js %}
function onGoogleLoad(){
    plotMyCharts(chartData)
}
google.setOnLoadCallback(onGoogleLoad)
{% endhighlight %}
On to example 3
{% highlight js %}
$('#my-button').click(console.log('You clicked me!'))
{% endhighlight %}
*You got this right?*
{% highlight js %}
$('#my-button').click(function(){
    console.log('You clicked me!')
})
{% endhighlight %}
*Great!* You grokked callbacks, and may you never prematurely invocate ever again.</content>
        </entry>,<entry>
            <title>Accidental Global Variables</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/10/25/js-accidental-global-variables">
            <updated>2011-10-25T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/10/25/js-accidental-global-variables</li>
            <content type="text">
*Recently I've been helping folks out with Javascript problems online or in person a fair bit. Some common problems or mistakes crop up repeatedly and I've kept a list of them. I am going to write about these common problems in a series of articles, starting with this one. The first problem is **accidentally leaking global variables**, let's get started!*

As I already mentioned in a [recent post](http://tobyho.com/2011/10/14/checking-for-global-leaks-in-unit-tests/), global variables are easily leaked in Javascript. A variable `i` declared within a function like this
{% highlight js %}
function f(){
    i = 1
}
f()
console.log("I can still see i: " + i)
{% endhighlight %}
The solution is to declare `i` as a local variable using the `var` statement.
{% highlight js %}
function f(){
    var i = 1
}
f()
console.log("Now I can't see i: " + i)
{% endhighlight %}
The same thing happens in the *for* clause of for-loops.
{% highlight js %}
for (i = 0; i < array.length; i++){
    ...
}
{% endhighlight %}
Don't think just because it's a for-loop, it is some how different. I can understand feeling a little funny about declaring a `var` inside the *for* clause, but it totally works!
{% highlight js %}
for (var i = 0; i < array.length; i++) {
{% endhighlight %}

*Recommendation:* *Always* declare your variables using the `var` statement, no matter what. Using a static analysis tool like [JSHint](http://www.jshint.com/) will help you catch global variable leaks.

*Don't miss the entire series: [7 Common Javascript Mistakes or Confusions](http://tobyho.com/2011/11/16/7-common-js-mistakes-or-confusions/)*</content>
        </entry>,<entry>
            <title>Getting the Terminal Size in Node</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/10/15/getting-terminal-size-in-node">
            <updated>2011-10-15T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/10/15/getting-terminal-size-in-node</li>
            <content type="text">
For a terminal-UI that I am working on - written in [Node](http://nodejs.org) - I needed to get the size of the terminal so that I can appropriately make calculations for drawing the UI. This is easy using the [ncurses-library](https://github.com/mscdex/node-ncurses), but I am using [Charm](https://github.com/substack/node-charm) instead(I have good reasons...I think). 

Attempt 1: $COLUMNS and $LINES
------------------------------

The first possible solution is using the shell variables `$COLS` and `$LINES`.

{% highlight bash %}
$ echo $COLUMNS
88
$ echo $LINES
22
{% endhighlight %}

The problem with this is it doesn't work inside a node process, because apparently, shell variables are only accessible to the shell.

Attempt 2: TPUT
---------------

The next thing I tried is using the `tput` command:

{% highlight bash %}
$ tput cols
88
$ tput lines
22
{% endhighlight %}

Okay, I'll just `child_process.spawn` to shell out to the command and get the results back.

{% highlight js %}
var spawn = require('child_process').spawn
function getTermSize(cb){
    var cols, lines
    spawn('tput', ['cols']).stdout.on('data', function(data){
        cols = Number(data)
        if (cols && lines && cb)
            cb(cols, lines)
    })
    spawn('tput', ['lines']).stdout.on('data', function(data){
        lines = Number(data)
        if (cols && lines && cb)
            cb(cols, lines)
    })
}
{% endhighlight %}

At first glance, this seemed to work. Except that it always returned `80, 24` when run from a node process. I have no idea why, since it works inside a ruby process. If someone knows, please tell me.

Attempt 3: RESIZE
-----------------

Researching further still, I found a command called `resize`. `resize` apparently sets the `$COLUMN` and `$LINES` shell variables, so that they become available. But in the process, it also prints the dimensions to the screen.

{% highlight bash %}
$ resize
COLUMNS=82;
LINES=10;
export COLUMNS LINES;
{% endhighlight %}

So, again, I'll shell out and parse the output. Parsing this output is a little more involved, but no worries, I am no stranger to regex.

{% highlight js %}
var spawn = require('child_process').spawn
function getTermSize(cb){
    spawn('resize').stdout.on('data', function(data){
        data = String(data)
        var lines = data.split('\n'),
            cols = Number(lines[0].match(/^COLUMNS=([0-9]+);$/)[1]),
            lines = Number(lines[1].match(/^LINES=([0-9]+);$/)[1])
        if (cb)
            cb(cols, lines)
    })
}
{% endhighlight %}

And voila! This method seems to work for my purposes. Usage of this function - in case you haven't figured it out

{% highlight js %}
getTermSize(function(cols, lines){
    // You have the terminal size!
})
{% endhighlight %}

Notes
-----

I've only tested this on my Macbook Air. I am pretty sure `resize` runs on Linux, possible pre-installed. But I would guess no luck on Windows. If there's a better way to do this, please let me know.</content>
        </entry>,<entry>
            <title>Checking for Global Variable Leaks in Unit Tests</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/10/14/checking-for-global-leaks-in-unit-tests">
            <updated>2011-10-14T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/10/14/checking-for-global-leaks-in-unit-tests</li>
            <content type="text">
Javascript is notorious for making it easy to leak global variables. For example, if you forget to use the `var` keyword when declaring a variable `i`:
    
{% highlight js %}
function f(){
    i = 1
}
f()
{% endhighlight %}
    
The same thing happens with variables declared in the `for` clause of for loops:

{% highlight js %}
for (i = 0; i < array.length; i++){
    ...
}
{% endhighlight %}
    
`i` becomes a global variable rather than staying within the function scope. I found that some beginners in Javascript often make this mistake. I once had to work with a codebase which had numerous such errors and I tasked myself with fixing these "global variable leaks".

I decided that I would write unit tests(with [Jasmine](http://pivotal.github.com/jasmine/)) and I would put in code in the setup and teardown phases on the tests to track if any global variables were leaked during the execution of each test:

{% highlight js %}
describe('stuff', function(){
    var globalsBefore = {}
    beforeEach(function(){
        for (var key in window)
            globalsBefore[key] = true
    })
    afterEach(function(){
        var leaked = []
        for (var key in window)
            if (!key in globalsBefore)
                leaked.push(key)
        if (leaked.length > 0)
            throw new Error('Leaked global variables: [' + leaked.join(', ') + ']')
    })
})
{% endhighlight %}

The above code checks takes an inventory of all of the global variables that are present `beforeEach` test, and then rechecks them `afterEach` test to see if any new variable was introduced, and throws an exception to fail the test if that was indeed the case.

It turned out that this simplistic method didn't always work out because sometimes, a test actually does want to create global variables legitimately. For example some browsers make iframes on the pages directly indexable on the window object:

{% highlight js %}
window[0] // this gives you the first iframe in the page!
{% endhighlight %}

Well, I guess we can specify a list of global variable names to ignore:

{% highlight js %}
var globalsToIgnore = ['0']
{% endhighlight %}

and then `afterEach` test we'll check that array as well:

{% highlight js %}
for (var key in window)
    if (!key in globalsBefore && globalsToIngnore.indexOf(key) === -1)
        leaked.push(key)
{% endhighlight %}

*Note that Array's `indexOf` method is not supported on older IE's.* 

Conclusion
----------

Using this method, I found all global variable leaks in the codebase once I wrote sufficient tests. It will also prevent future incidents.</content>
        </entry>,<entry>
            <title>Test-Driven Development with Javascript (Screencast 21:50)</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/10/07/tdd-with-js">
            <updated>2011-10-07T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/10/07/tdd-with-js</li>
            <content type="text">
Test-Driver Development(TDD) and Javascript. This screencast is for those who only know one or the other, or know both only shallowly. It will cover what TDD is, motivate its reason for being, demo what it is like in action using [QUnit](http://docs.jquery.com/Qunit), and demo how to write tests to deal with asynchronous events.

<div class="video">
<iframe src="http://player.vimeo.com/video/30173510?title=0&amp;byline=0&amp;portrait=0" width="400" height="250" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>
</div>

References
----------

- [Test-Driven Development](http://en.wikipedia.org/wiki/Test-driven_development)
- [QUnit](http://docs.jquery.com/Qunit) - Javascript Unit-Testing Framework</content>
        </entry>,<entry>
            <title>Real-time Web with Socket.IO (Screencast 17:20)</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/09/28/real-time-web-with-socket.io">
            <updated>2011-09-28T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/09/28/real-time-web-with-socket.io</li>
            <content type="text">
I redid/redesigned my blog! It now uses [Jekyll](https://github.com/mojombo/jekyll) to generate the site, vs before: a custom written Rails 1.2.x app. I also did the design by myself, with some much needed advice from my friend [Jarrod](http://twitter.com/#!/studiofellow). To kick-off this new hotness, I thought I'd start putting out a couple screencasts. This year I did several presentations on Javascript and Python at local meetups. I thought some of them would translate well as screencasts. And heck, I put so much work into these presentations I might as well get more mileage out of them, right?

Real-time Web and Socket.IO
---------------------------
I gave a ~15 minute intro on Socket.IO at [atljs](http://twitter.com/ATLJavaScript) a few months back. If you don't yet know about [Socket.IO](http://socket.io), it is mind-blowingly awesome.

<div class="video"><iframe src="http://player.vimeo.com/video/29706399?title=0&amp;byline=0&amp;portrait=0" width="400" height="250" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe></div>

References
----------

- [Real-time web](http://en.wikipedia.org/wiki/Real-time_web)
- [Comet](http://en.wikipedia.org/wiki/Comet_(programming))
- [Socket.IO](http://socket.io)
- [node.js](http://nodejs.org/)
- [NPM](http://npmjs.org/)
- [My Chat Example on github](https://github.com/airportyh/Socket.IO.atljs)

<a href="http://github.com/you"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://a248.e.akamai.net/assets.github.com/img/71eeaab9d563c2b3c590319b398dd35683265e85/687474703a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f677261795f3664366436642e706e67" alt="Fork me on GitHub"></a></content>
        </entry>,<entry>
            <title>Node Knockout 2011 and Twends</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/08/29/node-knockout-2011-and-twends">
            <updated>2011-08-29T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/08/29/node-knockout-2011-and-twends</li>
            <content type="text">
<p>This past weekend I participated in the  <a href="http://nodeknockout.com/">Node Knockout</a> - a programming competition where teams of 1 - 4 members build something using <a href="http://nodejs.org/">node.js</a> in 48 hours. I was very fortunate to have worked with <a href="http://twitter.com/#!/robfaraj">@robfaraj</a> on this, it was a fun couple of days! The end result is what we call <s><a href="http://cubespace.nko2.nodeknockout.com/">Twends</a></s> Twends: new location is now <a href="http://twends.us">twends.us</a>. Twends is a real-time Twitter trend visualization...app. It looks like this</p>
<div><div class="image">
	<img title="Twends" alt="Twends" src="https://lh4.googleusercontent.com/-FYvHuvGFjdM/TlxSDd765JI/AAAAAAAAR00/mZeQg0h5R9o/s800/twends.jpg">
</div><br></div>
<p>First, you either select a trending topic or type in a term of your own, then you will see this word visualization based on a series of packed circles. The larger the circle and the redder it is, the more frequently the word is being said at the moment. All the while, birds are fly across the screen. Each bird on the screen represents a tweet that's been written, now...ish. Just sit back, relax and watch the pretty circles changing shape and the birds flying across your screen. By reading the words you can often learn interesting things. For example, I learned while reading Twends that Justin Beiber fans are called beliebers, while Taylor Swift fans are called swifies. </p>
<p>Oh! And here's a video of it in action</p>
<div><div class="video">
	<iframe src="http://www.screenr.com/embed/pSWs" width="650" height="396" frameborder="0">
	
	</iframe>
</div><br></div>
<h2>The Tech</h2>
<p>Twends was built using client-side Javascript with the help of some great libraries and the <a href="https://dev.twitter.com/docs/api">Twitter REST API</a>. <a href="http://mbostock.github.com/d3/">d3.js</a> is without a doubt the most valuable library(MVL). We used it to layout the circles as well as animate them from their old positions to the new positions each time new data comes in. We also used <a href="http://html5boilerplate.com/">HTML5 Boilerplate</a> and <a href="http://jquery.com/">jQuery</a>. On the server side, we used <a href="http://expressjs.com/">express</a> and the <a href="http://jade-lang.com/">jade</a> templating language.</p>
<p>Graphics is done using SVG, which d3.js works very well with - although is independent of. IE8 and below do no support SVG so Twends do not work there. Twends could have worked on IE9 but it doesn't. IE9 supports SVG, so that was not the problem. The problem was that IE9 was blocking the JSONP requests I was making to the Twitter API due to <a href="https://dev.twitter.com/discussions/1232">this problem</a>, of which the blame is half on Microsoft and half on Twitter. So, if you go to the site with IE, it will greet you with a friendly(?) message and prompt you to install Google Chrome Frame, yea!</p>
<h2>The Aftermath</h2>
<p>The competition is still being judged at the moment, so I don't know what's the aftermath just yet. I guess I'll update this part of the post another time.</p>
<p>Node knockout came to an end and the&nbsp;<a href="http://nodeknockout.com/">winners</a>&nbsp;were victorious! Congrats to them. I am a little disappointed/surprised that one of my favorite entries:&nbsp;<a href="http://kibu.nko2.nodeknockout.com/">Pitchography</a>&nbsp;didn't win anything, here's a demo of their&nbsp;<a href="http://www.youtube.com/watch?v=a4gy1s1RzS8">awesome presentation tool</a>. As for Twends, well we were decidedly better than half of the entries out there :) We also presented it at the&nbsp;<a href="http://www.meetup.com/AtlantaJavaScript/">Atlanta Javascript Users Group</a>&nbsp;and got some good feedback. I've made the source code&nbsp;<a href="https://github.com/airportyh/twends">public on github</a>&nbsp;as well.</p>
<p>Node Knockout was a great experience. The organizers did a superb job of allowing the contestants to focus on writing code rather than dealing with setting up servers or administrative stuff. I enjoyed everything from the planning stages where we threw around random ideas, to the actually coding and then to the showing it off to people and seeing their reactions and comments. If you love code, then I highly recommend that you try a hackathon like this one.</p>
<a href="http://github.com/airportyh/twends"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://a248.e.akamai.net/assets.github.com/img/30f550e0d38ceb6ef5b81500c64d970b7fb0f028/687474703a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6f72616e67655f6666373630302e706e67" alt="Fork me on GitHub"></a></content>
        </entry>,<entry>
            <title>My JSConf Talk in Video</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/08/19/my-jsconf-talk-in-video">
            <updated>2011-08-19T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/08/19/my-jsconf-talk-in-video</li>
            <content type="text">
<p>The awesome folks behind JSConf just released a <a href="http://blip.tv/jsconf">whole bunch of great talks in video form</a> from the Portland event. Great chance to catch up on the talks whether you were there or not! They even put mine up there, which since this is my website, I am obliged to embed here. Wow I sound so very Chinese.</p>

<div class="video">
	<iframe src="http://blip.tv/play/g_Mngs6pEwI.html" width="550" height="393" frameborder="0" allowfullscreen="">
	
	</iframe>
</div></content>
        </entry>,<entry>
            <title>Book Review: Python Testing Cookbook</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/08/02/book-review:-python-testing">
            <updated>2011-08-02T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/08/02/book-review:-python-testing</li>
            <content type="text">
<p>This is the second of 2 Python book reviews. The book is Python Test Cookbook. </p>
<p>This book is a very complete overview of all aspects of testing with Python. It starts out with simple unit tests, then moves on to nose, BDD, Doctest, acceptance testing, coverage, continuous integration, and smoke tests and load tests. The last chapter of the book gives you a number of advices for starting out with testing.</p>
<h2>The Good</h2>
<p>I enjoyed this book in that it gave me a birds-eye view of all the tools and techniques that are there for Python, many of which I didn't know about before. I also learn new things about things that I had already used before. Lastly, I liked the last chapter in which the author gives us his heart-felt experiences with testing. Although I don't agree with everything he says(running your tests once a day is way too few), there is a lot of good advice there as well as good stories.</p>
<h2>The Bad</h2>
<p>One thing that I don't like about this book is that it's too code heavy. Pages and pages of code are print onto the page with only interleaving explanations. I mostly skimmed those parts because reading code line-by-line like that is just too boring. Code is simply not meant to be read in a linear fashion. When you read code, you jump between different files rapidly in order to fill the in missing context as you try to gain an understanding of the code. An even better aid in reading code is the ability to execute the code and instrument it with print statements or stop it with the debugger and inspect the program state. So, in summary, code-heavy books just doesn't make sense. Perhaps instead of writing this as a book, we should just point the readers at a code repository?</p>
<p>The second problem is that not enough was done to motivate each technique that was used. The author didn't properly motivate why one should write unit tests at all. Or why use a given technique listed in the book. Only cursory introduction is given for each technique or tool, and then it was straight to the code. We dwelled too much time on the how and not on the why, which makes this book very unfriendly to beginners.</p>
<h2>Summing Up</h2>
<p>Overall, I would not recommend this book to beginners or people who are looking for an introduction to testing. I am on the fence about recommending it at all, but it might be helpful for people who are already familiar with test driven development but just haven't been doing it with Python.</p></content>
        </entry>,<entry>
            <title>Book Review: Python 3 Web Development - Beginners Guide</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/07/22/book-review:-python-3-web">
            <updated>2011-07-22T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/07/22/book-review:-python-3-web</li>
            <content type="text">
<p><i>I just finished reading Python 3 Web Development - Beginners Guide by Michel Anders and here is my book review.</i></p>
<p>Michel Anders is no doubt a brilliant programmer. He has managed to go through HTML, Javascript, jQuery, jQuery plugins(both using and writing), jQuery UI, CSS selectors, CSS 3, Python, CherryPy, SQL and SQLite, unit testing, writing your own ORM, and Python meta-classes all in one book! Which is the problem with this book. I doubt any one who qualifies as a beginner will be able to get any further than chapter 2. I believe the author made the mistake of not putting in enough thought about his audience when writing. But, before making my final remarks, I'll give it proper treatment by commenting on each of the chapters.</p>
<h2>Chapter 1<br></h2>
<p>Chapter 1 explained the authors reasons for choosing the tools that he did, and <i>boy</i> were there a lot of choices to be made. Here were the choices:</p>
<div>
	<ul>
		<li>Web framework: CherryPy</li>
		<li>Language: Python 3</li>
		<li>Javascript Library: jQuery and jQuery UI</li>
		<li>Database: SQLLite</li>
		<li>ORM: None. He's rolling his own</li>
		<li>Revision Control: svn</li>
	</ul>
</div>
<p>There are a lot of high level talk about the rationale of each choice and why he made them. It was a bit strange that he put the choice of using Python <i>after</i> the choice of using CherryPy. The first chapter is quite intimidating for beginners - there is really lots to consider when building a web app. He admits it too, but he puts in a lot of encouraging words to encourage the reader to stay focused.</p>
<h2>Chapter 2</h2>
<p>Chapter 2 went through the exercise of building a web-based spreadsheet application, a la Google Docs. The goal is ambitious, especially for a "hello world" program. I wondered how he was going to pull it off. </p>
<p>The Author covered CherryPy, jQuery/CSS selectors, a jQuery plugin called jEditable, wrote his own jQuery plugin that builds a spreadsheet which uses jEditable, CSS 3 and HTML all in this chapter. The amount of Javascript in this chapter really surprised me because in the who-is-this-book-for section, it says "introductory level knowledge of JavaScript might be useful, but is not strictly necessary". He simply tried to cram too many things in, explaining each technology only cursorily as he encounters them. <i>I am pretty sure that he lost almost all readers in his audience with this chapter</i>. </p>
<div>
	<h2>The Rest of the Chapters</h2>
	<div>Since we've already lost almost all readers I will place less emphasis on chapters 3-10. Basically, it is more of the same: trying to cram too much information into his readers' minds too quickly. These chapters whirl-wind tour the following:</div>
	<div>
		<ul>
			<li>Writing an authentication handler, and then later authorization within CherryPy</li>
			<li>Using the file system as storage</li>
			<li>Using SQLite to replace the file system as as storage</li>
			<li>Using SQL directly to manipulate and query the database</li>
			<li>Ajax and lots more of jQuery and jQuery UI</li>
			<li>Unit testing in Python</li>
			<li>Building a hand-rolled ORM, and then improving it using meta-classes, where the phrase "make your head explode" was used</li>
			<li>Adding a CRUD interface to the system for his CRM, and then refining the CRM.</li>
		</ul>
		<div>The further you get in the book, the larger blocks of code were put on the page, and the author just tries to talk through what is going on. I skimmed most of these chapters because when you are explaining code that is so dense, it is easier to read the code itself - which I often resorted to - than to read the prose.</div>
	</div>
	<h2>Conclusion</h2>
	<div>Unfortunately, I cannot recommend this book. Reading from the book title, the audience is a Python programmer, perhaps beginner to intermediate, who is beginning in building web applications. This book will send this programmer away crying. I think perhaps a more fitting title for this book is "A Coding Cowboy's Journey In Web Development with Python 3".</div>
</div></content>
        </entry>,<entry>
            <title>Python Book Reviews Forthcoming</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/07/15/python-book-reviews">
            <updated>2011-07-15T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/07/15/python-book-reviews</li>
            <content type="text">
<p>The kind folks at <a href="http://www.PacktPub.com">PacktPub</a> are letting me review a couple of Python books. Hooray! They are</p>
<div>
	<ol>
		<li><span><a href="http://www.packtpub.com/python-3-web-development-beginners-guide/book" target="_blank">Python 3 Web Development Beginner's Guide</a></span></li>
		<li><span><a href="http://www.packtpub.com/python-testing-cookbook/book" target="_blank">Python Testing Cookbook</a></span><br></li>
	</ol>
</div>
<p>Look for my reviews of them in the near future.</p></content>
        </entry>,<entry>
            <title>The Javascript Stacktrace Blog Post</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/06/08/the-javascript-stacktrace-blog">
            <updated>2011-06-08T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/06/08/the-javascript-stacktrace-blog</li>
            <content type="text">
<p>For the past week or so I did some research on how best to include scripts in <a href="http://tuttijs.com">Tutti</a>'s sandbox environment and still get the best stacktraces possible. I got sucked in deeper and deeper and it just got uglier and uglier. This post will attempt to summarize all the knowledge that I've uncovered.</p>
<h2>What's a Stacktrace?<br></h2>
<p>When I say stacktrace, I mean it in the context an exception being thrown in your code, and getting the information about where exactly in your code the exception was thrown. This is what a exception might look like</p>
<pre><code>Error: Buck stops here.
at failInlined (http://localhost:8000/error_object/:16:11)
at catchError (http://localhost:8000/util.js:77:26)
at http://localhost:8000/error_object/:49:1
</code></pre>
<p>First, there is an error message. Then, the stacktrace. The stacktrace basically represents the state of the program's <a href="http://en.wikipedia.org/wiki/Call_stack">call stack</a> at the point when the exception was thrown. The stacktrace also contains the location(file URL and line number) of each call in the stack, which is extremely useful for debugging.</p>
<h2>So What's the Problem?</h2>
<p>The problem, is that not all browsers give you informative stacktraces. Not only that, different browsers give you the information in different ways. </p>
<p>Most browsers today give you the stacktrace information in the Error object that was thrown. In Firefox, Chrome and Opera, for example, the Error object contains a <i>stack</i> property which is a string representation of the stacktrace, much like the example shown above.</p>
<pre><code>// Get stacktrace on Firefox, Chrome and Opera
try{
   throw new Error('Buck stops here')
}catch(e){
   console.log(e.stack) // Yea!
}</code></pre>
<p>In Safari, however, the stack property is non-existent: it does not give you the full stacktrace. Instead it gives you the location for the top stack frame only. This is gotten from the properties <i>sourceURL</i> and <i>line</i>.</p>
<pre><code>// Get 1-level stacktrace on Safari
try{
  throw new Error('Buck stops here')
}catch(e){
  console.log(e.sourceURL + ': ' + e.line) // Meh
}</code></pre>
<p>On IE, you are out of luck. There is no stacktrace information available on the Error object.</p>
<h2>Going Deeper</h2>
<p>Javascript can be executed in various different ways/techniques, and not all of them yield good stacktraces. My next objective was to see what the stacktraces look like for the different techniques</p>
<h3>Technique 1: Script Tag Includes</h3>
<p>The script tag include is probably the most common way to execute Javascript on a webpage.</p>
<pre><code>&lt;script src="myscript.js"&gt;&lt;/script&gt;</code></pre>
<h3>Technique 2: Inlined Script Tag</h3>
<p>Alternatively you can inlined Javascript code inside of the script tag.</p>
<pre><code>&lt;script&gt;
console.log('Hello world')
&lt;/script&gt;</code></pre>
<h3>Technique 3: Dynamically Inserted Script Tag</h3>
<p>You can also create a script element dynamically in Javascript and load some Javascript into it.</p>
<pre><code>var script = document.createElement('script')
if (&lt;IE sucks and you are it&gt;)
  script.text = jsCode
else
  script.appendChild(document.createTextNode(jsCode))
document.body.appendChild(script)
document.body.removeChild(script)</code></pre>
<h3>Technique 4: Eval</h3>
<p>Use eval to execute the Javascript in Javascript. You probably want to <a href="http://perfectionkills.com/global-eval-what-are-the-options/">global eval</a> it.</p>
<pre><code>// This code for global eval stolen from jQuery 1.6.1
(window.execScript || function(jsCode) {
	window["eval"].call(window, jsCode);
} )(data);</code></pre>
<h3>Technique 5: Data URL in the Script Tag<br></h3>
<p>Using a data URL in a script tag is...I am not sure if anyone actually does this, and I am not entirely sure it's useful, but what the heck.</p>
<pre><code>&lt;script url="data:application/javascript,console.log('hello%20world')"&gt;&lt;/script&gt;</code></pre>
<h3>Summary: Stacktrace Information From Error Object</h3>
<p>Long story short, I tested the stacktrace output for each of these five techniques in different browsers. I summarized the results in this here table (that's right, geek out!)</p>
<div>
	<style>
		
		table#support,
		#definitions
		{
		    font-family: Helvetica, "sans serif";
		}
		table#support{
		    width: 100%;
		    border-collapse: collapse;
		}
		table#support th,
		table#support td{
		    border: 1px solid #aaa;
		    text-align: center;
		}
		
		#definitions dt, 
		#definitions dd{
		}
		#definitions dt{
		    float: left;
		    clear: left;
		    font-weight: bold;
		}
		#definitions dd{
		    margin-left: 5em;
		}
	</style>
	<table id="support">
		<tbody>
			<tr><th rowspan="2">Browser</th>
			        <th colspan="4" title="Script tag with `src` URL attribute">Include</th>
			        <th colspan="4" title="Inlined script tag">Inlined</th>
			        <th colspan="4" title="Dynamically inserted inlined script tag">Dynamic</th>
			        <th colspan="4" title="Global Eval'ed Javascript">Eval'ed</th>
			        <th colspan="4" title="Script tag with `src` as a Data URL">Data URL</th>
			    </tr>
			<tr><th title="Line Number">LN</th>
			        <th title="Source File URL">SR</th>
			        <th title="Stacktrace">ST</th>
			        <th title="Call arguments in Stacktrace">AG</th>
			        <th title="Line Number">LN</th>
			        <th title="Source File URL">SR</th>
			        <th title="Stacktrace">ST</th>
			        <th title="Call arguments in Stacktrace">AG</th>
			        <th title="Line Number">LN</th>
			        <th title="Source File URL">SR</th>
			        <th title="Stacktrace">ST</th>
			        <th title="Call arguments in Stacktrace">AG</th>
			        <th title="Line Number">LN</th>
			        <th title="Source File URL">SR</th>
			        <th title="Stacktrace">ST</th>
			        <th title="Call arguments in Stacktrace">AG</th>
			        <th title="Line Number">LN</th>
			        <th title="Source File URL">SR</th>
			        <th title="Stacktrace">ST</th>
			        <th title="Call arguments in Stacktrace">AG</th>
			    </tr>
			<tr><td>IE 6 - 8</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td colspan="4">Unsupported</td>
			    </tr>
			<tr><td>IE 9</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			    </tr>
			<tr><td>Safari 5</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>Y*</td>
			        <td>Y</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>Y</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>Y*</td>
			        <td>Y</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			    </tr>
			<tr><td>Chrome 11</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>
			
			</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>
			
			</td>
			        <td>Y*</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>
			
			</td>
			        <td>Y*</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>
			
			</td>
			        <td>Y*</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>
			
			</td>
			    </tr>
			<tr><td>Firefox 3.6 - 4</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y*</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y*</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y*</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y</td>
			    </tr>
			<tr><td>Opera 11</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>
			
			</td>
			        <td>Y*</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>
			
			</td>
			        <td>Y*</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>
			
			</td>
			        <td>Y</td>
			        <td>
			
			</td>
			        <td>Y*</td>
			        <td>Y</td>
			        <td>Y</td>
			        <td>
			
			</td>
			    </tr>
		</tbody>
	</table>
	<dl id="definitions"><dt>*</dt><dd>Line number may not be helpful</dd>
	    <dt>LN</dt><dd>Line numbers</dd>
	    <dt>SR</dt><dd>Source file URL</dd>
	    <dt>ST</dt><dd>Full stacktrace</dd>
	    <dt>AG</dt><dd>Call arguments in stacktrace</dd>
	    <dt>Include</dt><dd>Script tag with <code>src</code> set to a Javasrcipt file URL</dd>
	    <dt>Inlined</dt><dd>Script tag with inlined Javascript</dd>
	    <dt>Dynamic</dt><dd>Dynamically inserted script tag with inlined Javascript</dd>
	    <dt>Eval'ed</dt><dd>Global eval'ed Javascript</dd>
	    <dt>Data URL</dt><dd>Script tag with <code>src</code> set to a Data URL containing Javascript</dd></dl>
</div>
<p>A straightforward script tag include yields the best stacktrace information. As the asterisk(*) indicates, the dynamic script element, global eval, and data URL techniques can yield stacktraces with non-helpful line numbers. The data URL technique actually gives correct line numbers, it's just that all the newlines have been encoded and the entire source jammed onto a single line - so, I can't really say the line numbers are all that helpful. Strangly, Opera yields non-helpful line numbers even with the Javascript-inline-in-a-script tag technique. </p>
<h2>So That's it? No IE?</h2>
<p>There's no way to get stack information on IE, not unless you want to do the other thing, but you don't want to know about that.</p>
<p>What's that? You <i>do</i> want to know? No you do not! Just forget I said anything.</p>
<p>Okay! I'll tell you, but you are going to regret it.</p>
<h3>window.onerror<br></h3>
<p>On IE - and as it happens on Firefox and Chrome as well - you can register an onerror handler on the window object, like so</p>
<pre><code>window.onerror = function(message, fileURL, lineNumber){
  log(message + ': ' + fileURL + ': ' + lineNumber)
}</code></pre>
<p>The handler will be called anytime a thrown exception is uncaught: propagates all the way to the bottom of the call stack with no catchers. Catching the exception will cause the handler not to be called, unless you rethrow it, but even then, there are other complications. When the handler is called, there is no error object, only the error message, file URL, and the line number.</p>
<h3>Bad News: IE<br></h3>
<p>Because of various IE bugs, the fileURL and line number passed into the <i>onerror</i> handler isn't always accurate or helpful. After some research, I've isolated these bugs:</p>
<div>
	<ul>
		<li>In IE 7 and below, if an exception is thrown from within the code of an included script, <i>fileURL</i> will erroneously be set to the URL of the current HTML document even though the lineNumber will be set to the correct line number from within the script.</li>
		<li>In IE 8 and below, if an exception is thrown using the throw statement, (i.e. <i>throw new Error()</i> ) and is caught, and then re-thrown, and then propagates all the way up, the line number reported will be the the place it was re-thrown, rather than the place it was first thrown. This bug does not surface when the error is triggered otherwise, such as with type and reference errors.</li>
	</ul>
</div>
<p>IE 9 has both of these bugs fixed, even when it emulates older versions of the browser.</p>
<h2>What Can You Throw</h2>
<p>The "throw" statement lets you throw just about any old value - even numbers and strings! But this is not recommended as you won't be able to get any line numbers or stacktraces if the value thrown isn't an object - except for in IE, where you <i>can</i> get line numbers using <i>onerror</i>. In IE, throwing anything other than a pre-defined error object(Error, TypeError, etc) will result in the loss of a meaningful message in both the caught error object and in the <i>onerror</i> handler - where it will just say "Exception thrown and not caught".</p>
<p>So, the simplest recommendation here is to only throw the pre-defined <i>Error</i> object when you want to explicitly throw an error using the "throw" statement.</p>
<pre><code>throw new Error('Buck stops here.')</code></pre>
<p>or better yet, don't use the throw statement at all(this avoids the second IE bug mentioned earlier).</p>
<h2>The DIY Stacktrace</h2>
<p>The DIY stacktrace was pioneered by <a href="http://eriwen.com/javascript/js-stack-trace/">Eric Wendelin</a> among others. It first looks up argument.callee to get the current function being executed, then it walks the call stack by accessing the function's <i>caller</i> attribute recursively. For example:</p>
<pre><code>&gt; function f(){
    g()
  }
&gt; function g(){
    h()
  }
&gt; function h(){
    console.log(arguments.callee.caller.caller)
  }
&gt; f()
function f(){
  g()
}</code></pre>
<p>In the example, we are able to access the function <i>f</i> from with the body of <i>h</i>'s execution by walking two levels up the call stack using the caller attribute.</p>
<h3>Pros and Cons of the DIY Stacktrace<br></h3>
<p>The advantage of the DIY stacktrace is that it will work in any browser.</p>
<p>The disadvantages are</p>
<div>
	<ol>
		<li>It will not get you file locations/line numbers.</li>
		<li>It does not work with thrown errors - either implicitly or explicitly - because the building of the stacktrace needs to be explicited done as its own statement, say, <i>printStackTrace</i>, for example. So, you cannot have a stacktrace <i>and</i> an error thrown - <i>you cannot have your cake and eat it too</i>.</li>
	</ol>
</div>
<h2>Conclusion</h2>
<p>Sorry I don't have a better conclusion than: <i>It's a great big mess</i>. However, with the knowledge covered here, I think it is possible to employ some sophisticated hackery to recover at least <i>some</i> stacktrace info for each browser - the hardest case being IE. Such a technique - if made practical - would be useful for unit test frameworks and crash reporting.</p>
<h2>References<br></h2>
<div>
	<ul>
		<li>Eric Wendelin's <a href="http://eriwen.com/javascript/js-stack-trace/">Javascript Stacktrace</a> ( <a href="https://github.com/eriwen/javascript-stacktrace">GitHub repo</a> )<br></li>
		<li><a href="http://helephant.com/2007/05/12/diy-javascript-stack-trace/">DIY Stacktrace</a> - Helen Emerson</li>
		<li><a href="http://blog.yoursway.com/2009/07/3-painful-ways-to-obtain-stack-trace-in.html">3 painful ways to obtain a stacktrace</a> from Your Sway/CrashKit</li>
	</ul>
</div></content>
        </entry>,<entry>
            <title>A Different Approach to Email</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/06/08/a-different-approach-to-email">
            <updated>2011-06-08T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/06/08/a-different-approach-to-email</li>
            <content type="text">
<p>In Tim Ferris' book the Four Hour Work Week he shared the tip of minimizing the number of times you check email in a day. One reason that this approach is beneficial is because it will minimize the distraction from looking at the inbox. </p>

<h2>Yes! The Inbox is Distracting</h2>
<p>Let me give you an example. You want to write someone an email. So you open up Gmail(or your mail program of choice). The first thing you see is your inbox. Oh! An old pal just added you on Facebook! Or, oh! Someone sent you a pull request! Your next impulse is to go add your friend on Facebook or to take a look at the pull request: <i>it'd only take a couple of minutes</i>. If you are someone who can resist that urge, good for you. But I usually can't. And even when I can resist the urge to actually do those things, I usually can't resist thinking about them. Half an hour later, I am usually serving the web or writing an email to someone else and have forgotten what I was doing in the first place.</p>
<p>Maybe the problem is the high level of <i>in-your-face</i> which the inbox possesses. My first attempt was <a href="http://userscripts.org/scripts/show/103652">Gmail Peepshow</a>: a Greasemonkey script that initially blocks the view to your inbox. This solution didn't end up working very well, both because of how hard it is to manipulate the Gmail dom and its inflexibility, as I will explain.</p>
<h2>Only Check Once A Day</h2>
<p>One solution is to minimize your email checking frequency to say, once a day, as Ferris suggests. For me at least, this works out well most of the time, and keeps me focused. I have turned off push notifications on my phone(if you are hooked on push, you might try doing w/o it again, you might feel liberated), and only check email once a day, and try to take action right away at that sitting. </p>
<h2>But...</h2>
<p>However, there are occasions  when the thing you are working on requires you to correspond with someone via email, and worse, because you want to close the loop on the task ASAP, sometimes you want to be quickly notified when the correspondent replies. So, that means repeatedly checking your inbox again.</p>
<p>It dawned on me that the solution was to separate the urgent correspondents from the rest of your inbox. Even better would be if push notification only notified you if the urgent email comes in. After chatting with my wife about this, she seems to think I can implement this behavior using only Gmail filters, and so I got to work. </p>
<h2>The Solution</h2>
<p>The first thing to do is make a filter rule that removes everything from the inbox except for ones that come from the urgent correspondents.</p>
<pre><code>Matches: -from:{ vip@superimportant.com }
Do this: Skip Inbox</code></pre>
<div>This rules says for anything but emails coming from vip@superimportant.com: skip the inbox. If you need to add another correspondent, you can just add them one by one within the {}'s.</div>
<pre><code>Matches: -from:{ vip@superimportant.com vip@alsoimportant.com }
Do this: Skip Inbox</code></pre>
<p>What we've done is reserved our inbox only for our VIP's. But now, what about the other unread mail? I am going to create a label to simulate a second inbox - the one I check once a day. I will call it @daily (The @ sign is just so it will be sorted to the top). Basically, everything can go into @daily, so my rule could be</p>
<pre><code>Matches: from:(*)
Do this: Apply label "@daily"</code></pre>
<p>But, here I could add a rule to filter out the <a href="http://en.wikipedia.org/wiki/Bacn">bacn</a> I get from Delta and Borders, for example</p>
<pre><code>Matches: -from:{ e.delta.com e.borders.com }
Do this: Apply label "@daily"</code></pre>
<p>If I want, I could add yet another rule/label, maybe @weekly, for all the bacn or less important stuff that I might still want to look at at a lower frequency.</p>
<h2>Pros. Cons.</h2>
<p>An advantage to using the main inbox for only the urgent stuff is</p>
<p>
	<ol>
		<li>you will only see the urgent stuff when you open up Gmail - nothing that distracts</li>
		<li>you can use push notification on your phone now and only get urgent notifications - for my iPhone, I've turned off the sound for whenever <i>any</i> mail is received(so I am not distracted), but the little number at the corner of the "Mail" icon shows me the inbox number <div>
			<img title="Inbox Number" alt="Inbox Number" src="https://lh3.googleusercontent.com/-UhN97_sxStU/Te8IKNFrZgI/AAAAAAAARnQ/P8Y1s0clkfg/s800/Screen%252520shot%2525202011-06-08%252520at%2525201.26.30%252520AM.jpg">
		</div>. For Android I hear the integration is even better.</li>
	</ol>
</p>
<p>The only drawback of this approach is that you will have to maintain the "Skip Inbox" filter rule - every time you change who your urgent correspondent(s) is/are, you need to go in and change it. For me, this would be every time I start an urgent task that requires a correspondent, and when I finish that task.</p>
<h2>Conclusion</h2>
<p>I think this is a novel approach to approaching email. But there's no conclusion yet because I have only begun using this. Will blog updates if I learn anything new in the process.</p>
</content>
        </entry>,<entry>
            <title>Try Traceur</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/05/19/try-traceur">
            <updated>2011-05-19T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/05/19/try-traceur</li>
            <content type="text">
<p>I screwed around with <a href="http://code.google.com/p/traceur-compiler/">Traceur</a> last night and this morning. Then I built this thing called <a href="http://trytraceur.tobyho.com/">Try Traceur</a> to make it easy for folk to screw around with it too. Try it! You know you want to.</p></content>
        </entry>,<entry>
            <title>JSConf Summary and My Codez</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/05/06/jsconf-summary-and-my-codez">
            <updated>2011-05-06T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/05/06/jsconf-summary-and-my-codez</li>
            <content type="text">
<p>JSConf 2011 Portland was truly amazing experience for me, personally. Not only did I meet some fantastic people in the community - some of whom I've long wanted to meet, I also got to show off <a href="http://tuttijs.com/">my stuff</a>, and it didn't totally suck. Also, add to that, Portland is a fantastic city! I want to thank Chris Williams again for motivating me, and everybody involved for such a great event!</p>
<p>My talk was on <a href="http://tuttijs.com/">Tutti</a> and most of its time was occupied by demos, so rather than posting the slides I thought I would just post the <a href="https://github.com/airportyh/Tutti-JSConf-Code-Examples">example code</a> for the demos. I hope this is helpful to people!</p></content>
        </entry>,<entry>
            <title>String Difference in Ruby</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/03/26/string-difference-in-ruby">
            <updated>2011-03-26T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/03/26/string-difference-in-ruby</li>
            <content type="text">
<pre><code>class String

  def -(other)
    self.index(other) == 0 ? self[other.size..self.size] : nil
  end
end</code></pre>
<p>This snippet gives the Ruby <i>String</i> class a minus operator. Which works like</p>
<pre><code>&gt; 'abcde' - 'abc'
=&gt; "de"
&gt; '    ' - '  '
=&gt; "  "

&gt; 'abc' - 'de'
=&gt; nil
</code></pre>
<p>Meh.</p></content>
        </entry>,<entry>
            <title>Indent Your Code the Way You Want with Indentinator</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/03/26/indent-your-code-the-way-you">
            <updated>2011-03-26T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/03/26/indent-your-code-the-way-you</li>
            <content type="text">
<p>Indentinator is a script that inspects and changes the indentation in
your source code. It is language-agnostic. <i>"Indent your code the way you want."</i></p>
<p>

</p>
<h2>Install</h2>
<p>

</p>
<p>Assuming you have ruby and rubygem installed, you can</p>
<p>

</p>
<pre><code>gem install Indentinator
</code></pre>
<p>

</p>
<p>to install it.</p>
<p>

</p>
<h2>Usage </h2>
<p>

</p>
<pre><code>indentinator [-c INDENT_AMOUNT] &lt;file&gt; [&lt;file2&gt;...]
</code></pre>
<p>

</p>
<h2>Examples<br></h2>
<p>

</p>
<p>Using <code>indentinator</code> with a file argument will tell you what amount of indentation the file uses.</p>
<p>

</p>
<pre id="scroll_to_here"><code>$ indentinator lib/myapp.rb 
lib/myapp.rb uses 2 spaces.
</code></pre>
<p>

</p>
<p>Using with the <code>-c</code> option will convert the file to the desired indentation amount, and print the result to <code>stdout</code>.</p>
<p>

</p>
<pre><code>$ indentinator -c 4 lib/myapp.rb
</code></pre>
<p>

</p>
<p>The <code>-r</code> option will overwrite the original file with the output.</p>
<p>

</p>
<pre><code>$ indentinator -rc 4 lib/myapp.rb
</code></pre>
<p>

</p>
<p>Make sure you have the file backed up or source controlled first! I am not
responsible for any damages.</p>
<p>

</p>
<p>If you want to read the input from <code>stdin</code>, use the -i option</p>
<p>

</p>
<pre><code>$ cat lib/myapp.rb | indentinator -ic 4
</code></pre>
<p>

</p>
<p>If you use a mixture of indentation sizes in your source file, indentinator may guess wrong, which will in turn affect the conversion output. To tell it
explicitly the original indentation amount for it to use during the conversion 
process use the <code>-a</code> option</p>
<p>

</p>
<pre><code>$ indentinator -a 4 -c lib/myapp.rb
</code></pre>
<p>

</p>
<h2>Totally Use it Inside TextMate and Stuff</h2>
<p>

</p>
<p>If you copied a snippet of code from the internets, and it uses a different
indentation then you, it will be helpful to use indentinator from within TextMate. To do this, follow these steps:</p>
<p>

</p>
<ol><li>Go to <code>TextMate-&gt;Preferences...-&gt;Advanced-&gt;Shell Variables</code>, and make sure
the <code>PATH</code> variable contains the location of the <code>indentinator</code> executable.</li>
<li>Paste the code snippet into TextMate, select that snippet and hit Command-Option-R. </li>
<li>In the <code>Command:</code> text field type in the indentinator command to use, for
example <code>indentinator -ic 2</code>, which will take the selected text as input
(from <code>stdin</code>) and output it with an indentation of 2 spaces.</li>
<li>Click <code>Execute</code>.</li></ol>
<h2>Codez</h2>
<p><a href="https://github.com/airportyh/Indentinator">Source code for Indentinator</a> is distributed on GitHub. <a href="https://github.com/airportyh/Indentinator/issues">Submit me an issue</a> if you have one, thanks ;)</p>
<ul>

</ul></content>
        </entry>,<entry>
            <title>Smart Parameter Checks in Python</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/03/24/smart-parameter-checks-in">
            <updated>2011-03-24T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/03/24/smart-parameter-checks-in</li>
            <content type="text">
<p>While I really enjoy using Michael Foord's <a href="http://www.voidspace.org.uk/python/mock/">Mock library</a>, there is one thing missing and I thought would be a fun project to add - which is the subject of this post.</p>
<h2>Fun with Parameters</h2>
<p>Python has the most sophisticated function parameter calling mechanics I've ever seen. Given a function f</p>
<div>
	<pre><code>def f(a, b):</code></pre>
	<pre><code>    return a + b</code></pre>
</div>
<p>You can either call it like normal(positional parameters)</p>
<pre><code>f(1, 2)</code></pre>
<p>or by keyword parameter</p>
<pre><code>f(a=1, b=2)</code></pre>
<p>With keyword parameters, the position doesn't matter anymore, so the above call is equivalent to</p>
<pre><code>f(b=2, a=1)</code></pre>
<p>You can even mix positional and keyword parameters, as long as you put all the positionals first</p>
<pre><code>f(1, b=2)</code></pre>
<p>So, all the ways I've listed of calling the function f with the parameter a as 1 and b as 2 will have the same functional behavior, given what we know of the signature of the function. So, it would be logical that the mock library would consider</p>
<pre><code>f.assert_called_with(a=1, b=2)</code></pre>
<p>a passing assertion even though in reality it was called as</p>
<pre><code>f(1, 2)</code></pre>
<p>but alas, it does not.</p>
<p>With that, it was my mission to make this happen!</p>
<h2>Proof-of-Concept</h2>
<p>First I created a prototype/proof-of-concept. See <a href="https://github.com/airportyh/smart_param_check.py">code here</a>. Using</p>
<pre><code>inspect.getargspec(self.func)
</code></pre>
<p>I was able to get all the info about the signature of a function I needed. When a function call actually comes in, my callable receives them as</p>
<pre><code>def __call__(self, *args, **kwds):
</code></pre>
<p>at which point, I resolve all the parameters with the parameter list in the function signature(I called this "combining" the args)</p>
<div>
	<ol>
		<li>First, by walking the actual positionals (the <i>args</i> array coming in) and cross referencing them with the ones in the function signature. After this is done, we basically converted the positionals into named form - as a dict.</li>
		<li>Then merge everything in <i>kwds</i> into the same dict. So we have one unified dict with all the actually parameters and keyed by parameter name.</li>
		<li>If there are any left over from the variable position args, they are stored in an <i>extras</i> list.</li>
	</ol>
	<div>Now, with this information handy, we can actually do our own safe parameter checking, and we should! So when a call is made, I also check if all the required params have been provided, whether there are any unexpected params and so forth, and actually raise some TypeErrors like a real function if need be.</div>
</div>
<p>But the better part is what comes next - we can now implement the <i>assert_called_with</i> with these new semantics. When a call to <i>assert_called_with</i> is called, I "combine" the args coming into that call, and check if they match the previously made function call. It's that simple!</p>
<h2>Working in Python-Mock</h2>
<p>Well great. But we still can't use for the Mock library. So I did some more hacking on a <a href="http://code.google.com/r/airportyh-python-mock/source/browse/?r=smart-param-check">branch of Foord's code</a>. Not sure it's the cleanest code, but it now works if you want to try it out</p>
<pre><code>hg clone https://airportyh-python-mock.googlecode.com/hg/ airportyh-python-mock 
</code></pre>
<p>The way you use it with the Mock library is through <i>mocksignature</i>. </p>
<pre><code>from mock import mocksignature</code></pre>
<p><i>mocksignature</i> wraps a function that you pass it and uses the signature of that function as a guide. Given the function <i>f</i> that we had previously, you can do</p>
<pre><code>f = mocksignature(f)</code></pre>
<p>now call it</p>
<pre><code>f(1, 2)</code></pre>
<p>and then checking the associated mock with a different call style</p>
<pre><code>f.mock.assert_called_with(a=1, b=2)</code></pre>
<p>should now pass.</p>
<p>Cheers!</p></content>
        </entry>,<entry>
            <title>Memories of PyCon 2011</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/03/17/memories-of-pycon-2011">
            <updated>2011-03-17T04:00:00.000Z</updated>
            <id>http://tobyho.com/2011/03/17/memories-of-pycon-2011</li>
            <content type="text">
<p>2011 is my second PyCon and easily the best one. This time, rather than focusing on the talks, I focus on the social activities outside of the talks - open spaces sessions, sprints, going to lunch and dinner with folks, and just hanging out - this has really paid off! I met, hung out and worked with some of my heros, and this made me very happy :)</p>
<h2>Some Highlights<br></h2>
<div>
	<ul>
		<li>Dining with some of the smartest people and biggest Python open source contributors - many thanks to <a href="http://dunderboss.blogspot.com/">Phil</a> for the invite!</li>
		<li>Participating in a open spaces chat about music and tech and showing off my Noteboard program</li>
		<li>David Beazly's - as usual - makes programming fun with his superb presentation and geeking out</li>
		<li>Getting some insight on teaching programming to kids at one of the talks on education with Python</li>
		<li>Sprinting and hanging out with Michael Bayer, the SQLAlchemy team and other teams of sprinters and learning some useful things along the way</li>
		<li>Balancing family time and going to PyCon beautifully during the weekend</li>
		<li>Hanging out with Zed Shaw</li>
		<li>Feihong Hsu's hilarious presentation in front of a bunch of drunk hecklers at the Testing BOF. It was really inspiring because it's rare to see a fellow Chinese man be so entertaining and articulate.</li>
	</ul>
	<div>I miss you PyCon, and I'll do my best to make it out to Santa Clara next year.</div>
</div></content>
        </entry>,<entry>
            <title>Tuttiterm - Tutti for your Terminal</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/03/04/tuttiterm---tutti-for-your">
            <updated>2011-03-04T05:00:00.000Z</updated>
            <id>http://tobyho.com/2011/03/04/tuttiterm---tutti-for-your</li>
            <content type="text">
<p>I've created <a href="https://github.com/airportyh/tuttiterm">Tuttiterm</a> - which allows you to control browsers via <a href="http://tutti.tobyho.com">Tutti</a>. See the project <a href="https://github.com/airportyh/tuttiterm">README</a>. Here's a screenshot:</p>
<p><span><div class="image">
	<img title="Screenshot" alt="Screenshot" src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TXUF6UN4C4I/AAAAAAAARlk/Z2koe-4Nn-A/s800/Screen%20shot%202011-03-07%20at%2010.05.08%20AM.jpg">
</div><br></span></p></content>
        </entry>,<entry>
            <title>Testing Tip: The Dummy Function</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/02/25/testing-tip:-the-dummy">
            <updated>2011-02-25T05:00:00.000Z</updated>
            <id>http://tobyho.com/2011/02/25/testing-tip:-the-dummy</li>
            <content type="text">
<p>Sometimes when you are writing tests, you find yourself testing whether a particular callback has been called. For example, you might write a test like this</p>
<pre><code>var lastCalledWithfunction
callback(e){
    lastCalledWith = e
}
obj.bind('someevent', callback)
obj.doSomethingThatShouldTriggerEvent()
expect(lastCalledWith.type).toBe('someevent') // check that callback was called</code></pre>
<p>This is slightly tedious and the code ungainly because you need to introduce a variable in your test, and store the arguments to it so that you can check the result. We can do better</p>
<pre><code>function $dummy(){
    arguments.callee.lastCalledWith = arguments
}
obj.bind('someevent', $dummy)
obj.doSomethingThatShouldTriggerEvent()
expect($dummy.lastCalledWith[0].type).toBe('someevent')</code></pre>
<p>This is a nice and generic, but we have to reset the lastCalledWith attribute before each test, something like</p>
<pre><code>delete $dummy.lastCalledWith</code></pre>
<p>But let's make it more painless</p>
<pre><code>$dummy.reset()</code></pre>
<p>By adding this reset function</p>
<pre><code>$dummy.reset = function(){
    delete this.lastCalledWith
    return this
}
</code></pre>
<p>Moreover, reset returns back the dummy function itself, so, now you can write the test like so</p>
<pre><code>obj.bind('someevent', $dummy.reset())
obj.doSomethingThatShouldTriggerEvent()
expect($dummy.lastCalledWith[0].type).toBe('someevent')</code></pre>
<p>Very nice. I like.</p></content>
        </entry>,<entry>
            <title>Making a Morning Checklist out of HTML</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/02/25/making-a-morning-checklist-out">
            <updated>2011-02-25T05:00:00.000Z</updated>
            <id>http://tobyho.com/2011/02/25/making-a-morning-checklist-out</li>
            <content type="text">
<p>While <a href="http://boingboing.net/2011/02/17/reduce-stress-by-mak.html">Mark Frauenfelder’s morning checklist</a> was inspiring and relevant for me, the solution didn’t work for me because</p>
<p>

</p>
<ol><li>It does not save the trees!</li>
<li>An iPhone would work better for me best because I always have it with me.</li>
<li>It’s not made with HTML5.</li>
</ol>
<p>So right. If you are an iOS hacker you’d probably reach for xcode right away, but for a task like this, it’s simply orders of magnitude faster to do using plain HTML. Let’s get started. First thing to do is fire up a text editor and type in your check list of a <code>&lt;ul&gt;</code> of <code>&lt;li&gt;'s</code> with <code>&lt;input type="checkbox"&gt;'s</code> in each of them.</p>
<p>

</p>
<pre id="scroll_to_here"><code>&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;&lt;title&gt;Morning Checklist&lt;/title&gt;&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Morning Checklist&lt;/h1&gt;
&lt;ul&gt;
&lt;li&gt;&lt;input type="checkbox"/&gt;&lt;label&gt;Change&lt;/label&gt;&lt;/li&gt;
&lt;li&gt;&lt;input type="checkbox"/&gt;&lt;label&gt;Contacts&lt;/label&gt;&lt;/li&gt;
&lt;li&gt;&lt;input type="checkbox"/&gt;&lt;label&gt;Potty&lt;/label&gt;&lt;/li&gt;
&lt;li&gt;&lt;input type="checkbox"/&gt;&lt;label&gt;Rinse Mouth&lt;/label&gt;&lt;/li&gt;
&lt;li&gt;&lt;input type="checkbox"/&gt;&lt;label&gt;Laptop, wallet and keys&lt;/label&gt;&lt;/li&gt;
&lt;li&gt;&lt;input type="checkbox"/&gt;&lt;label&gt;Shoes & Coat&lt;/label&gt;&lt;/li&gt;
&lt;li&gt;&lt;input type="checkbox"/&gt;&lt;label&gt;Backpack&lt;/label&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>

</p>
<p>Cool, this is functional, but will look like this</p>
<p>

</p>
<p>
	<div class="image">
		<img src="https://lh4.googleusercontent.com/_1m4jxPGXQAo/TWhnnvP9iiI/AAAAAAAARj4/b9gqwJ0c_FQ/s800/step1.jpg" alt="Step 1" title="">
	</div>
</p>
<p>

</p>
<p>Okay, that doesn’t look great. You’ll need to pinch zoom in order to see anything. What we need to do is to format the web page specifically for the iPhone screen. To do that, add this line inside of your <code>&lt;head&gt;</code></p>
<p>

</p>
<pre><code>&lt;meta name="viewport"
content="width=device-width,
minimum-scale=1.0, maximum-scale=1.0" /&gt;
</code></pre>
<p>

</p>
<p>This will tell your iPhone to set the page’s viewport to exactly the same as the width of its screen, and also to disallow pinch to zoom. The result is this</p>
<p>

</p>
<p>
	<div class="image">
		<img src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TWhnn-s3IzI/AAAAAAAARj8/vpkjrADkLho/s800/step2.jpg" alt="Step 2" title="">
	</div>
</p>
<p>

</p>
<p>Okay, nice! Now let’s make it look non-ugly with some CSS. First, change to the font to something san-serif. Take away the bullet points from the list items, remove the unnecessary margins and paddings. Make the font bigger and the checkboxes themselves bigger because we want them and each row to be big enough for Mr. Fatfinger. While we are at it, might as well stripe the rows, you can actually do it using just CSS in a non-crappy browser such as Mobile Safari. After some playing around, I added the following styles</p>
<p>

</p>
<pre><code>&lt;style&gt;
body{
    font-family: Helvetica, Arial, Verdana, sans-serif;
    padding: 0px;
    margin: 0px;
}

ul{
    list-style: none;
    padding: 0px;
    margin: 0px;
}

li{
    clear: left;
    font-size: 25px;
    padding: 3px 0px 3px 10px;
    margin: 0px;
}

li input{
    float: left;
    margin-right: 15px;
    width: 25px;
    height: 25px;
}

li:nth-child(even){
    background-color: #eee;
}

h1{
    font-size: 20px;
    padding: 0.2em 0.5em;
    border-bottom: solid 1px #aaa;
    background-color: #eee;
    margin: 0;
}
&lt;/style&gt;
</code></pre>
<p>

</p>
<p>stick these inside the <code>&lt;head&gt;</code> and now it looks like</p>
<p>

</p>
<p>
	<div class="image">
		<img src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TWhnoP8aroI/AAAAAAAARkA/FBDaVSG48To/s800/step3.jpg" alt="Step 3" title="">
	</div>
</p>
<p>

</p>
<p>Great! Are we done? Well, there’s one usability problem: you have to click on the checkbox itself to check it. Id’d be nice if you could check it by click anywhere on the row. Let’s drop some Javascript on this</p>
<p>

</p>
<pre><code>&lt;script&gt;
Array.prototype.slice.call(document.getElementsByTagName('li'))
    .forEach(function(li){
        var cb = li.childNodes[0]
        cb.addEventListener('click', function(e){
            e.stopPropagation()
        })
        li.addEventListener('click', function(){
            cb.checked = !cb.checked
        }, false)
    })
&lt;/script&gt;
</code></pre>
<p>

</p>
<p><em>Note: if you see me writing some non-IE-compatible code that’s because I am only writing for the iPhone</em>. Nice, now you can click anywhere on a row to check or uncheck the box. Are we done? Now let’s add it as a shortcut on your <em>Home Screen</em>. To do that, click on the <code>+</code> sign on the bottom middle of the screen, and tap on <em>Add to Home Screen</em>. Edit the name of the button if you need to (I called it <em>Checklist</em>), and tap <em>Add</em>. Now you’ll get </p>
<p>

</p>
<p>
	<div class="image">
		<img src="https://lh4.googleusercontent.com/_1m4jxPGXQAo/TWhnoVMKFzI/AAAAAAAARkE/op1sFnwlFbE/s800/Home%20Screen.jpg" alt="Home Screen" title="">
	</div>
</p>
<p>

</p>
<p>If you tap on it, the checklist opens right up. But, it’d be nice to get rid of the browser chrome and buttons, that way we have less clutter and it also looks more like a real app. To do this, stick this</p>
<p>

</p>
<pre><code>&lt;meta name="apple-mobile-web-app-capable" content="yes" /&gt;
</code></pre>
<p>

</p>
<p>into your <code>&lt;head&gt;</code>. Unfortunately, you’ll have to re-create your Home Screen button, so delete it and go back and create again. Now, when you tab on it you’ll get</p>
<p>

</p>
<p>
	<div class="image">
		<img src="https://lh4.googleusercontent.com/_1m4jxPGXQAo/TWhnooLNoyI/AAAAAAAARkI/wRxrwMETcB4/s800/step4.jpg" alt="Step 4" title="">
	</div>
</p>
<p>

</p>
<p>Great, we are almost done! One more thing though. Now that we are serving the checklist from a web server, if it goes down or we lose our internet connection, we won’t be able to access it. Granted this will be rare since I’ll be at home when using this, but it can happen. So we use HTML5’s <code>applicationCache</code> to make this page offline capable. To do this, we’ll make a cache manifest file and point our HTML page to it. First, in the <code>&lt;html&gt;</code>
tag of the file add the <code>manifest</code> attribute like so</p>
<p>

</p>
<pre><code>&lt;html manifest="/cache.manifest"&gt;
</code></pre>
<p>

</p>
<p>Next, create the <code>cache.manifest</code> file in the same directory. With the following content.</p>
<p>

</p>
<pre><code>CACHE MANIFEST
index.html
# version 1
</code></pre>
<p>

</p>
<p>the cache manifest is in a simple text format that lists all the resources that this page depends on. Our checklist only has one file. Also, we put a version number there in comments because the next time you’d want to change the checklist, in order for the browser to update the file in its cache, you’ll have to change the content of the cache manifest - so we’ll just update the version number when that happens. Next, there’s one more thing you have to do: in order for the browser to recognize the cache manifest as such, your web server must send with it a special header <code>text/cache-manifest</code>. If you or your web host is using Apache you can simply put the following line</p>
<p>

</p>
<pre><code>AddType text/cache-manifest .manifest
</code></pre>
<p>

</p>
<p>inside the <code>.htaccess</code> file in the same directory - create it if it’s not there. There, try refreshing the page now. And then, to test offline mode, set your phone into Airplane mode, and then refresh the page again, it should still work.</p>
<p>

</p>
<p>There we have it. We built a checklist application for the iPhone using just HTML.</p></content>
        </entry>,<entry>
            <title>Playing With Self</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/02/18/playing-with-self">
            <updated>2011-02-18T05:00:00.000Z</updated>
            <id>http://tobyho.com/2011/02/18/playing-with-self</li>
            <content type="text">
<p>The <a href="http://selflanguage.org/">Self Language</a> is a descendant of Smalltalk, and is the language that introduced the concept of prototype inheritance. To get a historical perspective, I wanted to try it out, and luckily, it is still available online <a href="http://selflanguage.org/">despite</a> Sun killing the project in '95.</p>
<h2>Install</h2>
<p>To install Self, go to its <a href="http://selflanguage.org/download/index.html">download page</a> and follow the instructions. In short, first, you need to install the VM by running the installer. Next, you need to download a snapshot image. There are two to choose from: the <a href="http://selflanguage.org/files/releases/4.4/Clean-4.4.snap">clean</a>(spic 'n span) and the <a href="http://selflanguage.org/files/releases/4.4/Demo-4.4.snap">demo</a>(kitchen sink). Next, double click on the image that you downloaded, and you should be good to go.</p>
<p>I am going to do a walkthrough using the clean image because I just want to try out some basic language features. When the environment - or "world" - finishes launching, you are greeted with a large gray space with a shell window on the top left, and a trash can on the top right.</p>
<div><div class="image">
	<img title="Clean Image" alt="Clean Image" src="https://lh6.googleusercontent.com/_1m4jxPGXQAo/TV8qdaQJQBI/AAAAAAAARdo/XS3Mrc_LXvA/s800/Screen%20shot%202011-02-18%20at%209.26.28%20PM.jpg">
</div><br></div>
<p>So, let's play around and see how prototype inheritance works in Self. To create a new empty object, type</p>
<pre><code>()</code></pre>
<p>into the shell window and then click the "Get it" button. You should see a new expandable window that says "a slots object". If you expand it, it should look like</p>
<p><i><div class="image">
	<img title="New Empty Object" alt="New Empty Object" src="https://lh6.googleusercontent.com/_1m4jxPGXQAo/TV8rKl2I53I/AAAAAAAARds/QfqTfuGZhYM/s800/Screen%20shot%202011-02-18%20at%209.29.46%20PM.jpg">
</div></i><br></p>
<p>This is an empty object, the equivalent of <i>{}</i> in Javascript. </p>
<h2>Slots</h2>
<p>Now let's add some attributes to it, except in Self, we call them <i>slots</i>. Right-click on the header of this window and select "Add Slot". You should see this</p>
<div><div class="image">
	<img title="Adding a Slot" alt="Adding a Slot" src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TV8r5a8SAvI/AAAAAAAARd8/-DTDjSTsZl0/s800/Screen%20shot%202011-02-18%20at%209.32.55%20PM.jpg">
</div><br></div>
<p>This textarea is where you would write the code for either a value slot or a method slot. The textarea preloads with some examples of what you can write here.</p>
<p>We are going to just add a read-only slot</p>
<div><div class="image">
	<img title="Thelonious" alt="Thelonious" src="https://lh4.googleusercontent.com/_1m4jxPGXQAo/TV8s0vHOFII/AAAAAAAAReQ/MJWXbe2ASKI/s800/Screen%20shot%202011-02-18%20at%209.36.27%20PM.jpg">
</div><br></div>
<p>Just so you know, a read/write value slot would be written as</p>
<pre><code>name &lt;- 'Thelonious'</code></pre>
<p>When you are done, click on the thin green vertical bar on the left side of the window, and it should except the code. If your code has a syntax error, it will complain, and you'll need to try again. If you got it right, you should see this</p>
<div><div class="image">
	<img title="Thelonious Success" alt="Thelonious Success" src="https://lh4.googleusercontent.com/_1m4jxPGXQAo/TV8tcsN-MdI/AAAAAAAAReg/R8y32gI3mi4/s800/Screen%20shot%202011-02-18%20at%209.39.29%20PM.jpg">
</div><br></div>
<p>For fun, let's make a few more slots. Repeat the "Add Slot" procedure, but this time add a <i>hair</i> slot and set it to 'dark and curly', add a <i>plays</i> slot and set it to 'piano'. If things go right you should see</p>
<div><div class="image">
	<img title="Slots" alt="Slots" src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TV8125mM-QI/AAAAAAAARhE/rb_20xeaNi4/s800/Screen%20shot%202011-02-18%20at%2010.15.19%20PM.jpg">
</div><br></div>
<p>Now, click on the "E" button to get an evaluation console. If you type</p>
<pre><code>plays</code></pre>
<p>into it and click "Get it", you should get the string 'piano' to come out</p>
<div><div class="image">
	<img title="Get Slot Value" alt="Get Slot Value" src="https://lh6.googleusercontent.com/_1m4jxPGXQAo/TV82Fa7dmwI/AAAAAAAARhU/o5xPTK76Xjc/s800/Screen%20shot%202011-02-18%20at%2010.16.20%20PM.jpg">
</div><br></div>
<p>Okay, so it gets the value correctly.</p>
<h2>Inheritance</h2>
<p>Cool. Next we are going to create the inheritance link. First, we create an empty object again to represent the child.</p>
<div><div class="image">
	<img title="Empty Object" alt="Empty Object" src="https://lh6.googleusercontent.com/_1m4jxPGXQAo/TV8rKl2I53I/AAAAAAAARds/QfqTfuGZhYM/s800/Screen%20shot%202011-02-18%20at%209.29.46%20PM.jpg">
</div><br></div>
<p>Now, we add a special slot and call it <i>parent*</i>. </p>
<div><div class="image">
	<img title="Parent link" alt="Parent link" src="https://lh6.googleusercontent.com/_1m4jxPGXQAo/TV8xt5NX5PI/AAAAAAAARfQ/PRjq3wdfzJ8/s800/Screen%20shot%202011-02-18%20at%209.55.17%20PM.jpg">
</div><br></div>
<p>We don't set it to a value so that it defaults to <i>nil</i></p>
<div><div class="image">
	<img title="Made parent link" alt="Made parent link" src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TV8yCyAUW0I/AAAAAAAARfo/zIT768Zc2pE/s800/Screen%20shot%202011-02-18%20at%209.58.35%20PM.jpg">
</div><br></div>
<p>Next, we need to link it to <i>Thelonious</i>. First click on the little button with two small dots just to the right of the <i>nil</i>. The <i>nil</i> object will come out and you'll see a link from your <i>parent*</i> slot to it.</p>
<div><div class="image">
	<img title="nil" alt="nil" src="https://lh6.googleusercontent.com/_1m4jxPGXQAo/TV8ypdNJbaI/AAAAAAAARfs/VXousvCEERs/s800/Screen%20shot%202011-02-18%20at%2010.01.40%20PM.jpg">
</div><br></div>
<p>In Self, any slot that ends in * is a parent link. So, in fact, it supports <i>multiple inheritance</i>! Anyway, we are close to completing the inheritance. Now just drag the link to <i>Thelonious. </i>If you got it, you'll see this</p>
<div><div class="image">
	<img title="Linked" alt="Linked" src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TV82UAODeeI/AAAAAAAARhY/w89LNExdx_g/s800/Screen%20shot%202011-02-18%20at%2010.17.21%20PM.jpg">
</div><br></div>
<p>Now, to test that it worked, click on "E" in the child object and type</p>
<pre><code>hair</code></pre>
<div><div class="image">
	<img title="Inheritance at work" alt="Inheritance at work" src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TV81WrjZ2xI/AAAAAAAARg0/BZ2f1YwUB_E/s800/Screen%20shot%202011-02-18%20at%2010.13.04%20PM.jpg">
</div><br></div>
<p>Sweet! Now, we can override slots in the child, right?</p>
<div><div class="image">
	<img title="Slot override" alt="Slot override" src="https://lh4.googleusercontent.com/_1m4jxPGXQAo/TV821FEwjOI/AAAAAAAARho/YT5Rq-J8h9w/s800/Screen%20shot%202011-02-18%20at%2010.19.19%20PM.jpg">
</div><br></div>
<p>Yup. While we are at it, we'll change the name to 'Thelonious Jr.' too.</p>
<h2>Methods</h2>
<p>Next, let's create a method. Let's create a <i>greet</i> method on the parent. The <i>greet</i> method will simply popup an alert dialog with the message. It does this using the <i>report:</i> method of <i>userQuery</i>.</p>
<pre><code>userQuery report: 'Hi, I am ', name, ', I have ', hair, 
   ' hair and I play the ', plays, '.'
</code></pre>
<p>But, this won't work. Try running it - by clicking "Do it" will give you</p>
<div><div class="image">
	<img title="Error userQuery" alt="Error userQuery" src="https://lh4.googleusercontent.com/_1m4jxPGXQAo/TV8_o7fR2QI/AAAAAAAARh8/iVFmXzX3vjI/s800/Screen%20shot%202011-02-18%20at%2010.57.08%20PM.jpg">
</div><br></div>
<p>It couldn't find the <i>userQuery </i>object within its slots. In Self, the normal convention is to have your object inherit the <i>lobby</i> object in order to have access to all the global variables(this is like the global object in Javascript, aka the <i>public restroom</i>). So okay, we have 'Thelonious' inherit lobby using a link called <i>lobby*</i>. To do this, we first get hold of the lobby object by typing in the shell</p>
<pre><code>lobby</code></pre>
<p>and clicking "Get it". Then, create a slot on 'Thelonious' called <i>lobby*</i> and like to it. You should end up with this</p>
<div><div class="image">
	<img title="link to lobby" alt="link to lobby" src="https://lh4.googleusercontent.com/_1m4jxPGXQAo/TV9A7BW0CzI/AAAAAAAARiQ/XhiBaE5RnGY/s800/Screen%20shot%202011-02-18%20at%2011.02.38%20PM.jpg">
</div><br></div>
<p>Now, if you try "Do it" on <i>greet</i> it should give you</p>
<div><div class="image">
	<img title="Greet" alt="Greet" src="https://lh6.googleusercontent.com/_1m4jxPGXQAo/TV9EYoWwz-I/AAAAAAAARjE/oJM87SljTyg/s800/Screen%20shot%202011-02-18%20at%2011.17.23%20PM.jpg">
</div><br></div>
<p>And 'Thelonious Jr.' should also be able to do this</p>
<div><div class="image">
	<img title="Jr Greet" alt="Jr Greet" src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TV9Em_tI1xI/AAAAAAAARjU/NektO3o-05c/s800/Screen%20shot%202011-02-18%20at%2011.18.23%20PM.jpg">
</div><br></div>
<p>Sweet!</p>
<h2>Comparison With Javascript</h2>
<p>With a cursory look at the language Self, here are some of the differences between it and Javascript:</p>
<div>
	<ol>
		<li>It supports multiple inheritance, name clashes will result in a runtime error.</li>
		<li>Implicit self. No need to write "<i>this."</i> within the method body like Javascript.</li>
		<li>It differentiates between methods and blocks(in Javascript they are both functions). For this reason, you won't have the ugly Javascript problem of having to manually store a reference to <i>this</i> when you want to use it in inner blocks within a method.</li>
		<li>There's no constructor. You construct object using literals or by cloning another object.</li>
		<li>Reflection is done with a special mirror object attached each object's <i>_Mirror</i> slot.</li>
		<li>There is support for referencing a <i>super </i>method using a special <i>resend </i>syntax.</li>
	</ol>
</div></content>
        </entry>,<entry>
            <title>Checking Types in Javascript</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/01/28/checking-types-in-javascript">
            <updated>2011-01-28T05:00:00.000Z</updated>
            <id>http://tobyho.com/2011/01/28/checking-types-in-javascript</li>
            <content type="text">
<p>Have you ever wondered: <i>what is the correct way to check if a Javascript variable is an Array?</i></p>
<p><i><br></i></p>
<p>Do a Google search and you will get a great variety of answers. And, unfortunately, there's <i>is</i> no correct answer. This is one of the sad things about Javascript, not only are there many varying implementations of the language, there are also many varying opinions about how things should be done.</p>
<p>Enough philosophizing and feeling sorry about the state of things. With this article, I will trying to give a comprehensive overview of the different techniques of checking-types in Javascript, the pros and cons of each and why they exist.</p>
<h2><i>typeof</i> operator</h2>
<p>In the beginning, there was <i>typeof. </i>This handy operator gives you the "type" of a Javascript value:</p>
<pre><code>typeof 3 // "number"
typeof "abc" // "string"
typeof {} // "object"
typeof true // "boolean"
typeof undefined // "undefined"
typeof function(){} // "function"</code></pre>
<p>All is fine 'n dandy until</p>
<pre><code>typeof [] // "object"</code></pre>
<p>Huh? An array's type is <i>object</i>? I guess it <i>is</i>, if you want to get technical about it, but still, what the...</p>
<pre><code>typeof null // "object"</code></pre>
<p>Okay, <i>now</i> that's just <i>wrong!</i></p>
<p><i><br></i></p>
<p>Also, <i>typeof</i> will return "object" for Dates, RegExp, user defined objects, DOM elements, and pretty much anything else. So, <i>typeof</i> is pretty good at distinguishing between different kind of primitive values, and distinguish between them and <i>objects</i>, but is completely useless when it comes to distinguishing between different kinds of objects - <i>which includes arrays and nulls(WTF?!)</i>.</p>
<h2><i>instanceof</i> operator</h2>
<p>The <i>instanceof </i>operator tells you whether a object is an instance of a certain type. The so-called "type" is a constructor. For example</p>
<pre><code>function Animal(){}
var a = new Animal()
a instanceof Animal // true</code></pre>
<p>Alternatively, you could make this check using the <i>constructor</i> property of an object</p>
<pre><code>a.constructor === Animal // true</code></pre>
<p>However, the constructor check has two problems. First, it does not walk up the prototype chain</p>
<pre><code>function Cat(){}
Cat.prototype = new Animal
Cat.prototype.constructor = Cat
var felix = new Cat
felix instanceof Cat // true
felix instanceof Animal // true
felix.constructor === Cat // true
felix.constructor === Animal // false</code></pre>

<p>The second problem is that it will bomb out if the object in question is null or undefined.</p>
<pre><code>felix = null
felix instanceof Animal // true
felix.constructor === Animal // throws TypeError</code></pre>
<div><i>instanceof </i>works for <i>all</i> native types!</div>

<pre><code>[1, 2, 3] instanceof Array // true
/abc/ instanceof RegExp // true
({}) instanceof Object // true
(function(){}) instanceof Function // true</code></pre>
<p>or does it?</p>
<pre><code>3 instanceof Number // false
true instanceof Boolean // false
'abc' instanceof String // false</code></pre>
<p>Okay, what is going on here? It turns out that <i>instanceof</i> does not work with primitive values. The primitive types in Javascript are: <i>strings</i>, <i>numbers</i>, <i>booleans</i>, <i>null</i>, and <i>undefined</i> - (Oh good! You can count them all on one hand!) Well actually, I should have said it does not work with primitives with the exception of <i>null</i> and <i>undefined</i>, because they are not an instance of anything, and so <i>instanceof</i> correctly returns false when either is used on the left hand side.</p>
<pre><code>null instanceof Boolean // false
undefined instanceof Array // false</code></pre>
<p>To top that off though, checking for the constructor property <i>will </i>work for the primitive types <i>number, string</i> and <i>boolean</i>.</p>
<pre><code>(3).constructor === Number // true
true.constructor === Boolean // true
'abc'.constructor === String // true</code></pre>
<p>This works because whenever you reference a property on a primitive value, Javascript will automatically wrap the value with an object wrapper, like so</p>
<pre><code>var wrapper = new Number(3)</code></pre>
<p>except you don't see this - it happens behind the scenes. The wrapper then will be an instance of - in this case <i>Number</i> - or a <i>Boolean</i> or a <i>String</i> depending on the type of the primitive value, at which point it can walk up the prototype-chain and get at the properties of the Number prototype, etc. So, for example, creating a wrapper manually will make the <i>instanceof</i> operator work</p>
<pre><code>new Number(3) instanceof Number // true
new Boolean(true) instanceof Boolean // true
new String('abc') instanceof String // true</code></pre>
<p>But doing that would be pointless because it requires you to already know the type of the value of which you are asking whether or not it is of the type that you already know it is.</p>
<h3>Cross-window Issues of <i>instanceof</i></h3>
<p>It turns out that <i>instanceof</i> has another problem. It breaks down when you try to test an object coming from another window. You know? The ones that are created for each &lt;iframe&gt;, &lt;frame&gt; or popup window that you create. </p>
<pre><code>var iframe = document.createElement('iframe')
document.body.appendChild(iframe)
var iWindow = iframe.contentWindow // get a reference to the window object of the iframe
iWindow.document.write('&lt;script&gt;var arr = [1, 2, 3]&lt;/script&gt;') // create an array var in iframe's window
iWindow.arr // [1, 2, 3]
iWindow.arr instanceof Array // false</code></pre>
<p>Above, we created a variable <i>arr</i> inside the context of the iframe and set it to the array <i>[1, 2, 3]</i>. However, we get <i>false</i> when we ask whether it is a instance of Array. What is happening?!! Behold.</p>
<pre><code>Array === iWindow.Array // false</code></pre>
<p>The Array in the iframe is <i>not</i> the same Array as our Array! This is true for all built-in objects: there are two versions of all of them! Basically, we have parallel universes! OMG!</p>
<p>What this means is that an array created within the iframe is only an instance of the Array constructor within the iframe</p>
<pre><code>iWindow.arr instanceof iWindow.Array // true</code></pre>
<p>The same phenomenon happens with windows created using the <i>open()</i> function.<i> </i>It is because of this cross-window problem that the use of <i>instanceof</i> is somewhat limited and discouraged within the Javascript community.</p>
<h3>Duck-Typing</h3>
<p>Because neither <i>typeof</i> or <i>instanceof </i>are satisfactory, many resort to duck-typing. This means checking the behavior: i<i>f it looks like a duck and quacks like a duck, then it is a duck as far as I am concerned</i>. Pretty sure I misquoted that...oh well.</p>
<p>So, using duck-typing, an isArray check might look like</p>
<pre><code>// source: http://forums.devshed.com/javascript-development-115/javascript-test-whether-a-variable-is-array-or-not-33051.html
function isArray(obj){
    return (typeof(obj.length)=="undefined") ?
        false:true;
}</code></pre>
<p>or </p>
<pre><code>// source: http://www.hunlock.com/blogs/Ten_Javascript_Tools_Everyone_Should_Have
function isArray(testObject) {
    return testObject &&
	!(testObject.propertyIsEnumerable('length')) &&
	typeof testObject === 'object' &&
	typeof testObject.length === 'number';
}</code></pre>
<p>in jQuery, the function to check whether an object is a window is</p>
<pre><code>isWindow: function( obj ) {
    return obj && typeof obj === "object" && "setInterval" in obj;
}
</code></pre>
<p>You could easily trick this function into returning true</p>
<pre><code>$.isWindow({setInterval: 'bah!'}) // true</code></pre>
<p>Clearly, the problem with this approach is that</p>
<div>
	<ol>
		<li>it is inexact and can have false positives</li>
		<li>the set of properties of the object to test is arbitrary, and so it's unlikely for different people to agree on one way of doing it</li>
	</ol>
	<div>For the record, I don't like this approach.</div>
</div>
<h3><i>Object.prototype.toString</i> method</h3>
<p>It turns out that, you can get type information about an object by using the <i>Object.prototype.toString</i> method.</p>
<pre><code>Object.prototype.toString.call(3) // "[object Number]"
Object.prototype.toString.call([1, 2, 3]) // "[object Array]"
Object.prototype.toString.call({}) // "[object Object]"</code></pre>
<p>This native method is rarely encountered normally because it's usually shadowed by another toString method lower down in the prototype chain(Array.prototype.toString, Number.prototype.toString, etc.). This method reliably differentiates between native types, however, will return "[object Object]" for all user-defined types</p>
<pre><code>Object.prototype.toString.call(new Animal) // "[object Object]"</code></pre>
<p>It does, however, work across different window contexts</p>
<pre><code>Object.prototype.toString.call(iWindow.arr) === "[object Array]" // true
</code></pre>
<p>with one exception: different windows(as in popup window) in IE.<br></p>
<pre><code>var pWindow = open("")
pWindow.document.write('&lt;script&gt;var arr = [1, 2, 3]&lt;/script&gt;')
Object.prototype.toString.call(pWindow.arr) // you get "[object Object]" in IE; "[object Array]" else where.</code></pre>
<p>This is strange because for <i>iframes</i> it works just fine, bummer! This method has become somewhat of a preferred way to differentiate native types despite the IE bug. <i>Ehh, nobody uses popup windows anymore anyway.</i></p>
<h3><i>Function.prototype.toString</i> method</h3>
<p>Yet another way to test for type information is by using the <i>Function.prototype.toString </i>method.</p>
<pre><code>Function.prototype.toString.call((3).constructor)
// "function Number() {
//    [native code]
// }"</code></pre>
<p>The method gives you the complete source of a function. In the case of native functions, it just says "[native code]" in the body. One could easily parse out the name of the function to figure out type of the object using this helper function</p>
<pre><code>function type(obj){
	var text = Function.prototype.toString.call(obj.constructor)
	return text.match(/function (.*)\(/)[1]
}
type("abc") // "String"</code></pre>
<p>This one will work for user-defined types too</p>
<pre><code>type(new Animal) // "Animal"</code></pre>
<p>this code has a problem wrt popup windows in IE just like <i>instanceof.</i> It's because when <i>Function.prototype.toString</i> is called with a constructor from another parallel universe, it can only discern the constructor as an object("[object Object]"), and thus rejects the argument and throws a "Function expected" error. This problem can actually be worked around by referencing the toString method indirectly</p>
<pre><code>function type(obj){
	var text = obj.constructor.toString()
	return text.match(/function (.*)\(/)[1]
}</code></pre>
<p>Now, it works for popup windows in IE too! This fix makes it susceptible to shadowing</p>
<pre><code>Array.toString = function(){ return "function NotArray(){ }" }
type([1,2,3]) // "NotArray"</code></pre>
<p>but still, I'd say this is pretty cool.</p>
<p>Now, let's return to user-defined types for a minute. With this approach, there's no way to distinguish between two different user-defined types with the same name</p>
<pre><code>var f = function Animal(){ "something" }

var g = function Animal(){ "something entirely different" }
type(new f) // "Animal"
type(new g) // "Animal"</code></pre>
<p>For this reason, this method is inferior to <i>instanceof</i> for user-defined types. Another seemingly obvious problem with this approach is performance, but I'd have to benchmark it(jsperf!) to make a real claim.</p>
<h2>DOM Elements and Host Objects</h2>
<p>So far, I have not mentioned type checking for DOM elements and host objects. That's because it's <i>hard</i>. With the exception of duck-typing, none of the methods mentioned above will work for all browsers. If you drop IE7 and below, however, you can actually get some of the things to work. The output below were created using <a href="http://tutti.tobyho.com">Tutti</a></p>
<pre><code>&gt; var div = document.createElement('div')
&gt; typeof div
Safari 5.0 =&gt; object
Firefox 3.6 =&gt; object
IE 7.0 =&gt; object
IE 8.0 =&gt; object
Opera 11.01 =&gt; object
&gt; div instanceof Element
Safari 5.0 =&gt; true
Firefox 3.6 =&gt; true
IE 7.0 =&gt; Error: 'Element' is undefined
IE 8.0 =&gt; true
Opera 11.01 =&gt; true
&gt; div instanceof HTMLDivElement
Safari 5.0 =&gt; true
Firefox 3.6 =&gt; true
IE 8.0 =&gt; true
IE 7.0 =&gt; Error: 'HTMLDivElement' is undefined
Opera 11.01 =&gt; true
</code></pre>
<p>First up, <i>typeof</i> is useless, that was expected. Next, everyone but IE 7 recognizes that a div is an instance of <i>Element</i> as well as an <i>HTMLDivElem</i>ent<i>. </i>In IE7, those constructors aren't even present. Next,</p>
<pre><code>&gt; Object.prototype.toString.call(div)
Safari 5.0 =&gt; [object HTMLDivElement]
Firefox 3.6 =&gt; [object HTMLDivElement]
IE 7.0 =&gt; [object Object]
IE 8.0 =&gt; [object Object]
Opera 11.01 =&gt; [object HTMLDivElement]
</code></pre>
<p>The result of <i>Object.prototype.toString</i> in IE - even IE 8 - is particularly <i>un</i>helpful. What about</p>
<pre><code>&gt; div.constructor.toString()
Safari 5.0 =&gt; [object HTMLDivElementConstructor]
Firefox 3.6 =&gt; [object HTMLDivElement]
IE 7.0 =&gt; Error: 'div.constructor' is null or not an object
IE 8.0 =&gt; [object HTMLDivElement]
Opera 11.01 =&gt; function HTMLDivElement() { [native code] }
</code></pre>
<p><i>Function.prototype.toString: </i>it gives us something useful for IE8, but every browser has a slightly different output.</p>
<p>Fun! Try another one? Allllllllllllllllrrrighty then!</p>
<pre><code>&gt; typeof window
Safari 5.0 =&gt; object
Firefox 3.6 =&gt; object
IE 8.0 =&gt; object
IE 7.0 =&gt; object
Opera 11.01 =&gt; object
&gt; window instanceof Window
Safari 5.0 =&gt; ReferenceError: Can't find variable: Window
Firefox 3.6 =&gt; true
IE 8.0 =&gt; true
IE 7.0 =&gt; Error: 'Window' is undefined
Opera 11.01 =&gt; ReferenceError: Undefined variable: Window
&gt; Object.prototype.toString.call(window)
Safari 5.0 =&gt; [object DOMWindow]
Firefox 3.6 =&gt; [object Object]
IE 8.0 =&gt; [object Object]
IE 7.0 =&gt; [object Object]
Opera 11.01 =&gt; [object Window]
&gt; window.constructor
Safari 5.0 =&gt; function Object() {
    [native code]
}
Firefox 3.6 =&gt; function Object() {
    [native code]
}
IE 8.0 =&gt; [object Window]
IE 7.0 =&gt; undefined
Opera 11.01 =&gt; function Object() { [native code] }
</code></pre>
<p>With <i>window</i> it is just <i>all</i> over the place, none of these methods worked for all browsers. You can try testing out some other host objects if you want, but in general it doesn't look doable. However, in my testing, the XMLHttpRequest object and DOM and Text elements look doable using <i>instanceof</i>, if you can drop support for IE7 and below.</p>
<h2>What We've Learned</h2>
<p>Checking types in Javascript is a big mess. Although it's really not that hard to check for any one particular type, it is definitely not consistent across types, and you probably have had to make a lot of choices along the way. So it helps to know about all the different options. In an upcoming post, I will try to make all of this easier with a small piece of code. Stay tuned.</p>
<h2>Sources</h2>
<div>
	<ul>
		<li><a href="http://javascript.crockford.com/remedial.html">Remedial Javascript</a> by Crockford</li>
		<li><a href="http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/">instanceof considered harmful</a><br></li>
		<li><a href="http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript">An SO question w some helpful info</a><br></li>
		<li>Crockford <a href="http://groups.google.com/group/comp.lang.javascript/msg/1afbcb0da1cd4aef">calling instanceof useless</a></li>
	</ul>
</div></content>
        </entry>,<entry>
            <title>Questioning Windows and Tabs</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2011/01/06/questioning-windows-and-tabs">
            <updated>2011-01-06T05:00:00.000Z</updated>
            <id>http://tobyho.com/2011/01/06/questioning-windows-and-tabs</li>
            <content type="text">
<p><i>How many application windows do you have open right now? What about the number of browser tabs?</i></p>
<div>
	<div>
		<h2>The Limits of the Multiple-Window Paradigm</h2>
		<div>The multiple-window user interface paradigm that we all know and love was invented at Xerox Parc. Both Apple and Microsoft used it in their products and now every computer user in the world lives it and breaths it. </div>
		<div>More recently, there was the rise in popularity of the tab-based user interface. In particular, every major browser now supports tabbed browsing. To me, this indicates that the multiple-window paradigm isn't working well. In particular, it just doesn't scale when there are many open windows. Let's back up: it's not the <i>having</i> of the windows themselves that don't scale, the OS is happy to open as many windows as you want</div>
		<div><div class="image">
			<img title="Too Many Windows" alt="Too Many Windows" src="http://lh4.ggpht.com/_1m4jxPGXQAo/TSisXCw_c9I/AAAAAAAAROo/6vSFX-2zlV8/s800/Screen%20shot%202011-01-08%20at%201.25.50%20PM.jpg">
		</div><br></div>
		<div>but it's you who don't scale. Human beings can only hold a maximum of 7 things in their head at any one time.</div>
		<h2>Strategies for Taming Many Windows</h2>
		<div>When you have lots of application windows open at the same time. What are some strategies for making sense of them?</div>
		<h3>Alt-Tab and Cmd-Tab</h3>
		<p>On Windows, the Alt-Tab keyboard shortcut cycles through all of your opened app windows on Windows. On Mac,  there's the Cmd-Tab shortcut, which rather cycles through all of your opened applications; then the Cmd-` shortcut cycles through all your windows within the current application.</span><span> In practice, Alt-Tab or Cmd-Tab switching only works well if you are switching between 2 or 3 windows at most. Also, b</span><span>oth of these implementations appear to be inadequate for power users for there exists the <a href="http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx">Alt-Tab Replacement Task Switcher</a> for Windows and <a href="http://manytricks.com/witch/">Witch</a> for Mac.</p>
		<h3>Taskbar and the Dock</h3>
		<p>On Windows XP, the Taskbar lists all opened application windows and lets you switch between the windows with a click. If there are too many of them, similar windows will be grouped into one - clicking on the item will slide out a list from where you can choose from within the group. In Windows 7, there's a new interface which I have only seen, not used, so I won't comment. </p>
		<p>On Mac, there's the Dock. In contrast to the Taskbar, the Dock does not show all open windows. Instead it lists the currently opened <i>applications</i> as well as the currently <i>minimized</i> application windows. Neither the Dock or Taskbar scale up well when there's a large number of windows.</p>
		<h3>Exposé</h3>
		<p>On Mac, there's something called E<span>xposé, which is yet another indication that neither the Dock or Cmd-Tab are cutting it</span></p>
		<div><div class="image">
			<img title="Exposé" alt="Exposé" src="http://lh6.ggpht.com/_1m4jxPGXQAo/TSihCmSbJvI/AAAAAAAARNw/jz8pxDjBkcM/s800/Screen%20shot%202011-01-08%20at%2012.37.56%20PM.jpg">
		</div><br></div>
		<div>E<span>xposé shows all your open application windows on the screen by scaling them down to the point that they can all by laid out side by side together in a sort of mosaic. </span>You can click one of the thumbnails in the mosaic to switch to it. E<span>xposé works well up to a point, but if you have too many windows open</span></div>
		<div><span><div class="image">
			<img title="Expose with Many Windows" alt="Expose with Many Windows" src="http://lh6.ggpht.com/_1m4jxPGXQAo/TSiidiYbn6I/AAAAAAAAROE/TBbmVVYZzkY/s800/Screen%20shot%202011-01-08%20at%2012.43.47%20PM.jpg">
		</div><br></span></div>
		<div><span> you won't be able to make out which is which because the size of each window in </span>E<span>xposé will too small to read.</span></div>
		<div><span><br></span></div>
		<div><span>So, we have seen three strategies for handling many windows, but not <i>one</i> of them is up to the task.</span></div>
		<h2>Tab-Based Interfaces</h2>
		<div>At this point in time, all major web browsers have a tab-based interface. I don't know when exactly tabs first came into the scene. I want to say it was popularized by Firefox, let's pretend that it was. I am not entirely convinced that they are better than multiple-windows, but they seem to have taken over as the standard for web browsers and even text-editors and IDEs. These are some ways in which tabs may be superior than windows<br></div>
		<div>
			<ol>
				<li>Switching between tabs is easier because all tabs are readily readable and available at the top, whereas windows can easily occlude each other and although the Windows Taskbar has a similar function as tabs, it can easily fill up to the point of unmanageable if you have many application/windows open.</li>
				<li>Tabs live within the space of that window only, isolating them from other applications and windows. You could take advantage of this to better organize your stuff or just to have a clean slate to work with despite the other mess lying on your computer.</li>
			</ol>
		</div>
		<h2>Tab is the New Window<br></h2>
	</div>
	<div><div class="image">
		<img title="Chrome with Too Many Tabs" alt="Chrome with Too Many Tabs" src="http://lh5.ggpht.com/_1m4jxPGXQAo/TC8ETmlbVFI/AAAAAAAAQUw/cIPhJ7dhCCg/s800/Chrome.jpg">
	</div><br></div>
	<div>It is not uncommon nowadays to see people having more than 10 tabs open in their browser. My typical usage pattern is this: I usually start out with one or two tabs that are opened all the time, such as my todo list and email; then as I need to research something or am distracted by a link I'll add new tabs to the mix. This continues until I have too many tabs(my threshold is about 10 or so), at which point I decide to either create a <i>new</i> <i>window</i> and start over again or clean up the existing tabs. If I go for the <i>tab clean up</i>, I will go through each one, decide whether it's<i> save-worthy</i>, save to a bookmarking service if so, or close the tab if not.</div>
	<div>It is as if I need to do periodic garbage collection as part of my web browsing experience. <i>This. Is. Not. Okay.</i></div>
	<div>People even less disciplined than myself do tab cleanups less frequently than I, and they come to rely on the state of the browser. If the browser crashed and lost its state, they would get upset, because they'd lost track of their work. The fact that most browsers now also restore their states across restarts helps them, but also further perpetuates this behavior.</div>
	<div>Tabs may or may not be a improvement to multiple windows, but they do not scale either.</div>
	<h2>
	
	</h2>
	<h2>Multiple Windows and Tabs are Overrated<br></h2>
	<div>So if there's no way to work effectively with many windows or tabs, what is a user to do?<i> Reduce, reduce, reduce.</i> Most of the time, multiple windows and tabs are just not necessary. Some evidence of this are</div>
	<div>
		<ul>
			<li>many non-tech-savvy computer users - who don't even know about tabs - maximize their windows by default</li>
			<li>smart phones and tablets of today don't have multiple windows and people - both tech-savvy and non-tech-savvy - find them usable</li>
			<li><span>overlapping windows might look cool, </span><span><span>but are pretty much useless</span></span></li>
		</ul>
		<div>The only time when multiple windows are necessary is when you have a complex task at hand. We will talk about that a little later.</div>
	</div>
	<h2>Why We Need So Much Stuff Open<br></h2>
	<div>
		<title>
		
		</title>
		<style type="text/css">
			
			p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px 'Andale Mono'}
			p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px 'Andale Mono'; min-height: 15.0px}
		</style>
		<p><span>Why do we - the computer users of today - have the tendency to open up an abundance of windows and tabs? Here is me trying to explain</span><br><br></p>
		<ul>
			<li><span>slow start of applications: <i>might as well leave them running so that we don't have to wait for them to start the next time around.</i></span></li>
			<li><span>some apps just run in the background because they have to constantly check for or be notified by external events and react to them(chat apps, twitter, facebook, calendar reminders, mail notifiers, etc).</span><br></li>
			<li><span>non-linear nature of thought processes: thoughts can easily change direction, either because of external events(a phone call, a Facebook reply, someone walking into your office) or internal events(a great new super-duper awesome idea).</span></li>
			<li>sometimes, to efficiently perform a particular task, you simply have to switch rapidly between a small number of windows. For example, you are writing a program and you have constantly switch between your editor and some terminals from which you compile your code, run your code, debug your code, and so forth.</li>
		</ul>
		<div>I'll go into more detail about each of these as well as strategies to counter them so that you don't have to go insane.</div>
		<h3>Slow Start of Applications</h3>
		<div><span>There is no escaping the fact that when an application is already in memory, it will start faster because to start it from scratch will mean reading from the disk, which is way slower than reading from memory. Furthermore, when you close the application, you usually lose the application state. So if you restart the program you'd have to start over: for example, re-opening files or projects or a re-navigating the app in a specific way. For these reasons, many people opt to just leave applications open even after they are done using them - this will allow them to switch back to the application more quickly should they ever need to use it again. In my experience, however, application start times have improved greatly in recent years both due to better hardware and better written software, so app start time is now much less of a problem than before. Many applications even restore to their previous state on startup (ex. Firefox, Chrome, Textmate), so the problem with application state is mitigated as well.</span></div>
		<h3>Background Applications</h3>
		<div>Some applications are simply designed to sit around indefinitely and alert you whenever they feel like it. An instant messaging application is one such application - it waits for incoming messages, and alerts you when it happens. There's nothing really you can do about these applications being open other to stop using them altogether - for some apps, this is not a bad idea at all. My recommendation is to use these applications very judiciously. For alert-based applications such as GMail and GCalendar Notifier, make sure you set it up so that only the events that truly deserve your attention trigger alerts. As an example, I personally have mail alerts disabled, but the inbox number displays in my menu bar so I can check it when I want to. Another example is, if you use Growl(Mac only) for notifications, you can configure which applications you allow alerts to come from.</div>
		<h3>Non-linear Nature of Thought Processes and <i>Stacks</i><br></h3>
		<div>People's minds wander around constantly, this is what makes us creative and adaptive. However, it also makes us unfocused and scatterbrained. If you allow yourself to mindlessly wander to wherever you please, you won't get anything done. Furthermore, it's been shown that <a href="http://www.tampabay.com/features/humaninterest/article1136239.ece">focusing on what you are doing directly increases your happiness</a>(for more on that, you want to read <a href="http://www.amazon.com/Flow-Psychology-Experience-Mihaly-Csikszentmihalyi/dp/0060920432">Flow: the psychology of optimal experience</a>). So, although thoughts tend to be non-linear, you want to establish some form of structure so as to prevent it from going astray. A logical solution is a stack. You first start with a top-level task; if there is something else you need to do - a subtask(research an API), or just a general digression(check twitter) - you push that task onto the stack; when you are done with the subtask on the top of the stack, pop the stack and return to the previous task. Neither the tab-based UI or the multiple-window paradigm directly supports this <i>stack</i> mode of operation that I've described. What that means is you are going to have to be disciplined and always close the window or tab behind you when you are done with a subtask.</div>
		<h3>Rapid Switching and <i>Registers</i></h3>
		<p>There are certainly times you find yourself in a situation where you have to constantly switch between two or three overlapping windows. </span><span>In contrast to the <i>stack</i>, I will call this mode of operation the <i>registers </i>mode of operation, because like registers in a CPU, you have to access a small number of things very frequently. If the windows in your "register" are overlapping, you could be in a sea of hurt because when the content of a large area of your screen completely changes, it takes a second or two to orient yourself to the new content. When you are switching windows rapidly, those one or two seconds really add up. </p>
		<p>You can <i>greatly</i> ease the pain by tiling the windows in a non-overlapping way. </span><span><div class="image">
			<img title="Tiling Windows" alt="Tiling Windows" src="http://lh6.ggpht.com/_1m4jxPGXQAo/TSvKz50LwOI/AAAAAAAARQs/r-gLgPOocoI/s800/Screen%20shot%202011-01-10%20at%2010.12.53%20PM.jpg">
		</div></span><span>A prime example of this is the IDE. Most IDEs divide the available real estate up into tiles, which allows you to see all the pieces of information all the time. Another example is a graphics editor - which includes a tool bar, a tool options panel, a layers panel, the image to be edited, and more. These two examples indicate that the </span><span><i>register</i></span><span> mode of operation is often needed for highly complex tasks. Note: when you are using one application that satisfies all your needs, you don't need multiple windows anymore. It's only when you don't have an application specifically built for your task that you need to use the window tiling strategy.</p>
		<p></span><span>Previously, we made the assumption that you only have a <i>small</i> number of windows in your register. What if there are more than a few windows you need to switch between? Again, people can only hold about 7 things in their head, so you are not likely going to work well with a large number of windows anyway. But, if by chance you are a genius and can handle it, you can get a bigger monitor or <a href="http://tradermike.net/2011/01/tools-of-the-trade-how-i-work-2011-version/">use more monitors like Trader Mike</a>.</p>
		<h2>Experiment to Try</h2>
		<div>I've said some bold things: am I full of bull? You can test it out yourself. Try this experiment</div>
		<div>
			<ul>
				<li>Never leave any more than one browser tab <i>or </i> browser window open</li>
				<li>Only leave open the applications that you are currently using. When you are done with a task, close out any applications that you are no longer using.</li>
			</ul>
			<div>Do this for a minimun of 48 hours on regular work days and see if you are missing anything. At first, this may take some getting used to, here are some tips to smooth out some rough edges<br></div>
		</div>
		<div>
			<ul>
				<li>If you are using applications that can restore their state, configure them to do so.</li>
				<li>Many advanced web applications(like GMail) can restore their previous state as well and work perfectly with the back button - so there's no reason for you to have to leave them open all the time. </li>
				<li>If you need a reminder to return to something, rather than leaving a tab or window open, use a todo list. If you don't have a todo list app that you already use, you can just use a text editor. You should be able to open and close this todo list quickly.</li>
				<li>If you can afford to, stop using applications which take a long time to start or do not restore their previous state.</li>
			</ul>
			<div>If it doesn't work, I'll <i>give you your money back.</i> That's right, I'll pay you back in entirety the amount of money that you paid me, no questions asked ;) Happy working!</div>
		</div>
		<p>
		
		</p>
	</div>
</div></content>
        </entry>,<entry>
            <title>A Little LOGO</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/12/21/a-little-logo">
            <updated>2010-12-21T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/12/21/a-little-logo</li>
            <content type="text">
<p>You may remember the <a href="http://en.wikipedia.org/wiki/Logo_(programming_language)">LOGO programming language</a> from the old days of Turtle Graphics. If you are like me, you probably remember drawing polygons and stars by typing a command like:</p>
<pre><code>repeat 5 [forward 100 right 72]</code></pre>
<p>This draws a pentagon, and with different numbers plugged in the 3 different places, you can get a infinite variation of shapes.</p>
<p>But it turns out LOGO is more than just <i>forward</i>, <i>turn left</i>, <i>turn right</i>, and <i>repeat -</i> it actually is a pretty powerful language having its roots in LISP.</p>
<p>Much like LISP, the <i>list</i> data type is central to the language. As an example, let's write a <i>sumlist</i> function which just sums the numbers in a list. A list is written like</p>
<pre><code>[1 2 3 4]</code></pre>
<p>So calling the function looks like</p>
<pre><code>print sumlist [1 2 3 4]</code></pre>
<p>This should print 10 as the result.</p>
<p>Like LISP again, LOGO uses linked lists, so the most basic way to iterate a list would be to use tail recursion. We can write <i>sumlist</i> like this</p>
<pre><code>to sumlist :list
	ifelse equal? 0 (count :list)
		[0]
		[(first :list) + (sumlist butfirst :list)]
end
</code></pre>
<p>Declaring a function has a nice down-to-earth syntax</p>
<pre><code>to func :param1 :param2 ... statement1 statement2 ... end
</code></pre>
<p>The <i>ifelse</i> function simulates an if-else statement, taking 3 parameters, the test condition, a statement block to execute for true and another for false. So here we are saying if the list is empty, return zero, otherwise return the first element of the list plus the sum of the rest(<i>butfirst)</i> of the list. Notice that the statement blocks passed as the second and third arguments to the <i>ifelse </i>function are nothing more than lists. Lists, in addition to acting as literal lists of element, also double as lazily evaluated statement blocks.</p>
<p>Writing recursive functions is usually kinda tedious like the <i>sumlist</i> function that we wrote above, but if you knew a little about functional programming, you know that you can use <i>foldr </i>or <i>reduce</i> to simplify your code. Well, you can do that in LOGO too</p>
<pre><code>to sumlist :list (reduce "sum :list 0) end
</code></pre>
<p>Sweet! Now we have a one-liner. You can read up on <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">foldr or reduce</a> if you don't know it - I won't explain it in depth here. Essentially, the reduce function allowed us to refactor our recursive function into a much more succinct form.</p>
<p>Great! But we aren't done yet. There's a yet simpler way to write the function. It turns out that there's already a <i>sum</i> function in UCBLogo - perhaps the most popular implementation of LOGO. It does not act exactly the way we want though. You can sum two numbers together</p>
<pre><code>print sum 1 2</code></pre>
<p>prints 3.</p>
<p>But if you try adding more parameters it'll just ignore them</p>
<pre><code>print sum 1 2 3</code></pre>
<p>still prints 3.</p>
<p>Turns out you <i>can</i> use variable number of parameters, you just have to write it differently</p>
<pre><code>print (sum 1 2 3)</code></pre>
<p>prints 6. This is called the LISP-style call syntax. Notice that a function has a natural arity(number of parameters). In the case of <i>sum</i> the natural arity is 2, but the arity can be changed if you use the LISP-style call syntax. Using the natural arity of the function for lookahead is the reason why LOGO code doesn't have as much parentheses as LISP code. You can write</p>
<pre><code>forward 100 right 45 forward 50 left 80</code></pre>
<p>There is no ambiguity as to what is the correct grouping for this expression because each of the functions <i>forward, right, left</i> take one parameter, and the interpreter uses that information for disambiguation during parsing.</p>
<p>Anyway, I digress. Now, back to the <i>sum</i> function. It turns out we can also call the function using the <i>apply</i> function, much like Javascript's <i>Function.prototype.apply</i>. And so, our final version of <i>sumlist</i> looks like</p>
<pre><code>to sumlist :list apply "sum :list end
</code></pre>
<p>Nice!<i> apply</i> takes two arguments: the name of the function to call and the parameter list. We prepend a double quote to <i>sum</i> to make it a string literal to prevent it from being applied as a function.</p>
<p>There's a counterpart for Function.prototype.call in Javascript too, it's called invoke.</p>
<pre><code>print (invoke "sum 1 2 3)</code></pre>
<p>But like Javascript's call() it's also less useful than <i>apply</i>.</p>
<h2>Going Further</h2>
<p>Joshua Bell wrote a <a href="http://www.calormen.com/logo/">LOGO interpreter in Javascript</a>. That's where you'd go if you want to <a href="http://www.calormen.com/logo/">try out some LOGO</a> right away. Alternatively, download <a href="http://www.cs.berkeley.edu/~bh/logo.html">UCBLogo</a>.</p></content>
        </entry>,<entry>
            <title>Trampolines in Javascript and the Quest for Fewer Nested Callbacks</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/12/10/trampolines-in-javascript-and">
            <updated>2010-12-10T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/12/10/trampolines-in-javascript-and</li>
            <content type="text">
<p>The problem of Javascript coders often having to deal with more than the desired number of nested callback functions have never really went away. <a href="Continuation-Passing Style: Don't Overdo it">My complaint</a> has been stated not long ago. Lately, with the raise of <a href="http://nodejs.org">node.js</a>, the complaints seemed to have gotten louder, or just more <i>numerous</i>. At <a href="http://jsconf.eu/2010/">JSConf EU 2010</a>, there were <a href="http://jsconf.eu/2010/speaker/dont_write_spaghetti_code_in_s.html">no</a> <a href="http://jsconf.eu/2010/speaker/loopage_by_douglas_crockford.html">fewer</a> <a href="http://jsconf.eu/2010/speaker/techniques_and_tools_for_tamin.html">than</a> <a href="http://jsconf.eu/2010/speaker/techniques_for_a_single_stack.html">5</a> <a href="http://jsconf.eu/2010/speaker/getting_functional_with_fab.html">talks</a> addressing this issue, each in their own unique way. </p>
<div><br><div>
	<ul>
		<li>Crockford himself, for example, thinks that this is just the way it should be, and people who don't like it are just grumpy (Waa!)<br></li>
		<li>Ryan Dahl glossed over the problem of losing the stack, and suggested that you just roll your own solution for remembering state across your series of function contexts.</li>
		<li>Jed Schmidt revealed his fantastic hack: program in continuables/streams. The solution is actually very close to Haskell's I/O Monad, and is both clever and beautiful, but it requires you to change your mind-set completely and therefore is unlikely to gain a lot of mindshare.</li>
		<li>Tim Caswell introduced a helper library called <i>Step</i> which allows you to chain your functions rather than nest them.</li>
		<li>Tom Hughes-Croucher recommended using named functions, for the stacktraces will display them names and therefore be more helpful.</li>
	</ul>
	<div>More recently, Kyle Simpson(Getify) started a twitter thread and <a href="http://blog.getify.com/2010/12/native-javascript-sync-async/">blog post</a> with his own proposed addition to the language, which boils down to an @ operator that cooperates with dojo-style promises.</div>
</div><div>Clearly, we are far from reaching consensus.</div></div>
<h2>Generators</h2>
<p>One thing that was brought up over and over again in <a href="http://www.mail-archive.com/es-discuss%40mozilla.org/msg05317.html">Kyle's thread</a> is generators. My take is this: generators have existed in Spidermonkey ever since Firefox 2, so if you are open to new language features, generators have already been around the block, we just have to get it into the standard, at which point I believe node.js - and just Javascript programmers in general - can really benefit. I have long been using generators in Python, so I know that they are very powerful. All of this motivated me to go deeper and see how far it can go in the<i> Quest for Fewer Nested Callbacks</i>.</p>
<h3>First, the Punchline!</h3>
<p>Let's see the punchline now because it may take a while before we can get through all the steps necessary to arrive at it: with the help of generators and a bit of support code, this(code taken directly from Kyle's post)</p>
<pre><code>setTimeout(function(){
   xhr("/something.ajax?greeting", function(greeting) {
      xhr("/else.ajax?who&greeting="+greeting, function(who) {
         console.log(greeting+" "+who);
      });
   });
}, 1000);
</code></pre>
<p>can be written as</p>
<pre><code>yield sleep(1000)
var greeting = yield xhr('/something.ajax?greeting')
var who = yield xhr('/else.ajax?who&greeting=' + greeting)
console.log(greeting + ' ' + who)
</code></pre>
<p>The supporting function</p>
<pre><code>function xhr(url, callback) {
   var x = new XMLHttpRequest();
   x.onreadystatechange = function(){
      if (x.readyState == 4) {
         callback(x.responseText);
      }
   };
   x.open("GET",url);
   x.send();
}
</code></pre>
<p>almost remains unchanged, all it needs is to be wrapped like so</p>
<pre><code>function _xhr(url, callback) {
   var x = new XMLHttpRequest();
   x.onreadystatechange = function(){
      if (x.readyState == 4) {
         callback(x.responseText);
      }
   };
   x.open("GET",url);
   x.send();
}function xhr(url){   _xhr(url, (yield Continuation))   yield Suspend}</code></pre>
<p>and, sleep() is implemented as</p>
<pre><code>function sleep(ms){
    setTimeout((yield Continuation), ms)
    yield Suspend
}
</code></pre>
<p>Are you intrigued? Read on, then.</p>
<h3>Gentle Introduction to Generators<br></h3>
<p><i>What are generators? How do they work? How can I use them?</i></p>
<p>Let's start with<i> "How can I use them?"</i>. You have to be running Firefox 2 or above, or alternatively you can download Spidermonkey by itself.</p>
<p>For my code samples I'll assume you are using Firefox.</p>
<p>Next, you have to use type="application/javascript;version=1.7" in your script tag. I guess Mozilla was sheepish about this feature when they released it, given that it introduced a new keyword.</p>
<p>So, a hello world example for generators would be:</p>
<pre><code>&lt;script type="application/javascript;version=1.7"&gt;
// This is a generator function
function naturalNumbers(){
    var i = 0
    while (true){
        yield i++
    }
}
var N = naturalNumbers() // N is now a generator
console.log(N.next()) // prints 0
console.log(N.next()) // prints 1
console.log(N.next()) // prints 2
// and so forth
&lt;/script&gt;
</code></pre>
<p>First things first, a generator function is not the same as a function. Repeat after me: <i>a generator function is not a function</i>. Within a generator function, you have <i>yield</i> statements; within a function, you have <i>return</i> statements - you <i>cannot</i> have both.</p>
<p><span>The generator object has a few methods, here we are only demonstrating next() - which executes the code within the generator function until a </span><span><i>yield</i></span><span> statement is reached, and returns the value being yielded. If you call next() on it again, it will continue from where it left off, and once again execute till the next yield</span><span> is reached. In our natural numbers example, since we are yielding the counter within an infinite loop, we can keep calling next() on the generator object to get the next number forever...</span></p>
<h3>Receiving Values</h3>
<p>It turns out that in addition to <i>yielding</i> values, the yield statement can also <i>receive</i> values(proud of myself that I avoided using the word<i> </i>"return" in this sentence).</p>
<p>For a yield statement to receive a value, the holder of the generator must call the send() method with a value instead of the next() function</p>
<pre><code>function makePrinter(){
    while(true){
        var message = (yield)
        console.log(message)
    }
}
var printer = makePrinter()
printer.next() // You may not send a value to a newly created generator
printer.send('Hello')
printer.send('I am sending this message')
printer.send('into the generator')
printer.send('and it be received and get printed')
</code></pre>
<p>Here we created a printer generator whose job is only to print the objects that it receives from the <i>yields</i>. You can't send in a value for the first invocation of the generator because it hasn't had a chance to yield yet, but after that, you can send as many as you want, since it yields infinite times.</p>
<p>As you can see, we are switching back and forth between two separate threads of execution(but not Threads ;).</p>
<h3>Trampolining</h3>
<p>Now that you understand generators, the next step is to put it together to get rid of our nested callbacks. To do that, we need to know a technique called trampolining. Neil Mix's <a href="http://www.neilmix.com/2007/02/07/threading-in-javascript-17/">article</a> has some brilliant code that shows you how to do it in Javascript, but it was David Beazley's <a href="http://www.dabeaz.com/coroutines/trampoline.py">gentle example in Python</a> that helped me understand what's going on.</p>
<p>Let me translate his code to Javascript, and put in some comments for ya</p>
<pre><code>function add(x,y){
    yield x + y             // yield the result of addition
}
function main(){
    var r = yield add(2,2)      // yield the result of add(2,2): a generator
    console.log(r)
    yield
}
function run(){
    var m = main()
    var sub = m.next()      // start the code execution in main()
                             // sub is now generator from calling add()
    var result = sub.next() // start execution of sub
                             // result now has the value of 2 + 2: 4
    m.send(result)           // send back to generator
}
run()</code></pre>
<p>The main feature of trampolining is that a value yielded by a generator is yet another generator, such is the case on this line</p>
<pre><code>var r = yield add(2,2)      // yield the result of add(2,2): a generator</code></pre>
<p>In this example the thread of execution is bouncing between 3 different contexts, namely the run() function and the add() and main() generator functions. We started within run(), bounced to main(), then back to run(), then to add(), then back to run(), then back to main() again, and then finally exiting in run() again.</p>
<p>Here's a picture so we can visualize what's happening</p>
<div><div class="image">
	<img title="Trampoline Example" alt="Trampoline Example" src="http://lh3.ggpht.com/_1m4jxPGXQAo/TQLjLF94AEI/AAAAAAAAREw/teMTn0UstOU/s800/Screen%20shot%202010-12-10%20at%209.33.58%20PM.jpg">
</div><br></div>
<p>But, right now the run() function is inflexible. We can generalize it to handle arbitrary levels of nested generator execution - with a stack</p>
<pre><code>function run(gen){
    // is object a generator?
    function isGenerator(obj){
        return String(obj) === '[object Generator]'
    }
    // last element of array
    function last(arr){
        return arr[arr.length - 1]
    }
    var stack = []
    var retval = gen
    try{
        while (true){
            if (isGenerator(retval)){   // if a generator
                stack.push(retval)      // push it onto the stack
                retval = undefined
            }else{
                stack.pop().close()     // if we got a normal value
                                        // pop the stack and
            }
            gen = last(stack)           // get the generator at top of the stack
            if (!gen) break
            retval = gen.send(retval)   // send retval to the generator
                                        // if retval is undefined, it acts just
                                        // like next()
        }
    }catch(e if e === StopIteration){
        console.log('Program ended.')
    }
}
</code></pre>
<p>We have a stack which starts out containing the generator from which we are starting execution - <i>gen</i>. Then, we keep on executing the generator at the top of the stack. If the received value is also a generator, we push it onto the stack and keep going; if we receive a normal value, then we pop the generator off the stack and, on the next iteration of the loop - send the value to previous generator one level down in the stack.</p>
<p>To call the new and improved the run() function you pass it the entry level generator like so</p>
<pre><code>run(main())</code></pre>
<p>Let's take the same example again, but executing with the generic run() function instead. This time, let's visualize it as a stack. First we start with main() at the bottom</p>
<div><div class="image">
	<img title="1-level stack" alt="1-level stack" src="http://lh5.ggpht.com/_1m4jxPGXQAo/TQLm38LvegI/AAAAAAAARFE/PFMe3FhcdHY/s800/Screen%20shot%202010-12-10%20at%209.49.22%20PM.jpg">
</div><br></div>
<p>next,</p>
<pre><code>var r = yield add(2,2)
</code></pre>
<p>add(2, 2) is pushed onto the stack, because it is a generator. The parameters x and y are both assigned to 2 inside the scope and also go on the stack.</p>
<div><div class="image">
	<img title="2-level Stack" alt="2-level Stack" src="http://lh4.ggpht.com/_1m4jxPGXQAo/TQO3OpBCjAI/AAAAAAAARGg/CL2-b1YQp8M/s800/Screen%20shot%202010-12-11%20at%2012.38.36%20PM.jpg">
</div><br></div>
<p>add() then executes and </p>
<pre><code>yield x + y</code></pre>
<p>yields a numerical value: 4. Because, this is not a generator, we pop() the stack, then send the 4 back to main()</p>
<pre><code>var r = yield add(2,2)</code></pre>
<p>where 4 is assigned to <i>r</i>. </p>
<div><div class="image">
	<img title="1-level stack again" alt="1-level stack again" src="http://lh4.ggpht.com/_1m4jxPGXQAo/TQLoTls3hmI/AAAAAAAARFc/ixOdUkSDMC0/s800/Screen%20shot%202010-12-10%20at%209.55.59%20PM.jpg">
</div><br></div>
<p>main() then prints the value via console.log and then</p>
<pre><code>yield</code></pre>
<p>again, which ends the execution.</p>
<h3>Wait, I've Seen That Before!</h3>
<p>This... stack, it looks almost like... <i>an execution stack</i>! The interpreter maintains a stack when it's executing code and handling the execution of function calls - <i>and we've just reimplemented it using generators.</i></p>
<p>To see it another way, the only difference between the trampoline style code and normal functional code is the use of the yield statements. If you take out the yields - and substitute <i>return</i> when appropriate, you'd have</p>
<pre><code>function add(x,y){
    return x + y
}
function main(){
    var r = add(2,2)      // yield the result of add(2,2): a generator
    console.log(r)    return
}</code></pre>
<p>Now that we have a generalized run() function that handles the stack generically, we can handle recursion</p>
<pre><code>// the Fibonacci sequence using recursion - don't try this at home!
function fib(n){
    if (n == 1 || n == 2)
        yield 1
    else
        yield (yield fib(n-1)) + (yield fib(n-2))
}
function main(){
    console.log(yield fib(10))
}</code></pre>
<p>This actually works!</p>
<h3>Wrapping Asynchronous Execution</h3>
<p>Okay, that's all fine and good, but we still haven't address the problem of making asynchronous code less onerous. In order to tackle that problem, we need to do a little bit more.</p>
<p>By keeping a stack of all of the generators we have in progress, we can restart them back at any time. However, we need to be able to suspend the execution of a generator if we are waiting for an asynchronous response. We also need to pass a function as the callback handler for the async function call, <i>only</i> by which can we know when to resume execution of the thread.</p>
<p>The solution is demonstrated by the implementation of sleep()</p>
<pre><code>function sleep(millis) {
    setTimeout((yield Continuation), millis)
    yield Suspend
}
</code></pre>
<p><i>Continuation</i> and <i>Suspend</i> are special constants - that we created - used as signals to run().</p>
<p>Here's how this works:</p>
<pre><code>(yield Continuation)</code></pre>
<p>will receive a function as a callback handler to setTimeout. Let's call this function the <i>continuation</i>.</p>
<pre><code>yield Suspend</code></pre>
<p>will suspend the execution of this generator, and therefore also suspending this thread of execution until the continuation has been called by setTimeout(). When the continuation eventually gets called, it will resume execution of this generator, which starts back up again after the line</p>
<pre><code>yield Suspend</code></pre>
<p>Our new run() function that handles all of this looks like</p>
<pre><code>function run(gen){
    function isGenerator(obj){
        return String(obj) === '[object Generator]'
    }
    function last(arr){
        return arr[arr.length - 1]
    }
    function startBouncing(retval){
        try{
            while (true){
                if (isGenerator(retval)){
                    stack.push(retval)
                    retval = undefined
                }else if (retval === Suspend){
                    break                       // to suspend execution:
                                                // just break out of this
                                                // while-loop.
                                                // we can later resume
                                                // by re-starting another
                                                // while-loop by calling
                                                // startBouncing() again
                }else if (retval === Continuation){
                    retval = startBouncing      // send startBouncing
                                                // back as the callback
                                                // handler to the async
                                                // function call
                }else{
                    stack.pop().close()
                }
                gen = last(stack)
                if (!gen) break
                retval = gen.send(retval)
            }
        }catch(e if e === StopIteration){
            console.log('Program ended.')
        }
    }    
    var stack = []
    var retval
    startBouncing(gen)
}
</code></pre>
<p>We've refactored the while-loop inside of a function: startBouncing(). When we need to suspend, we just break out of the while-loop. When we need to resume, we just call startBouncing() to start the while-loop all over again. All the while we still have the stack in tact. The callback handler we send as the continuation is none other than the startBouncing() function. Notice that startBouncing() also takes a retval as argument. This enables us to send the first argument of the callback back to the generator, as the XHR example shows</p>
<pre><code>function _xhr(url, callback){
    var xhr = new XMLHttpRequest()
    xhr.open('GET', url)
    xhr.onreadystatechange = function(){
        if (this.readyState == 4){
            // send the responseText as the first arg of the continuation
            callback(this.responseText)
        }
    }
    xhr.send()
}
function xhr(url){
    _xhr(url, (yield Continuation))
    yield Suspend
}</code></pre>
<p>Because we are passing the responseText as the first argument to the callback(the continuation) - by our made up convention - it will be the value that's sent back to the caller of this generator function. So</p>
<pre><code>var responseText = yield xhr('/something.ajax')</code></pre>
<p>Just works!</p>
<h3>Adding Back Exceptions</h3>
<p>Async-style calls don't really throw any exceptions. That's because if there <i>were</i> problems with the request, you <i>could</i> only be notified asynchronously - the original execution has already past! However, now that we have something that looks like synchronous code again, we can put exceptions back into play. We will use the convention that if an instance of Error is passed as the first argument of the continuation, then we will throw it. Thus for our xhr function</p>
<pre><code>function _xhr(url, callback){
    var xhr = new XMLHttpRequest()
    xhr.open('GET', url)
    xhr.onreadystatechange = function(){
        if (this.readyState == 4){
            if (this.status === 200)
                callback(this.responseText)
            else{
                var ex = new Error("XMLHttpRequest Error: " + 
                    this.statusText + ': ' + this.status)
                // pass in an error object to the continuable to throw it
                callback(ex)
            }
        }
    }
    xhr.send()
}</code></pre>
<p>To throw an exception from within a generator you actually have to call the throw() method on the generator object. We just need to add an extra else-if inside of our big if statement inside of the while-loop in run()</p>
<pre><code>else if (retval instanceof Error){
    stack.pop().close()
    last(stack).throw(retval)
}</code></pre>
<p>Now we can get exceptions throw from the xhr() generator function</p>
<pre><code>function main(){
    try{
        var result = yield xhr('/doesnotexist.ajax')
        console.log('blah')
    }catch(e){
        console.log('exception caught: ' + e)
    }
}
</code></pre>
<h2>Conclusion</h2>
<p>I think the trampolining technique is very compelling, perhaps even more compelling than the continuables in fab.js. The only thing we need is support for generators in more engines. As far as I know, Spidermonkey and Rhino are the only 2 that support it right now.</p>
<h2>Source Code</h2>
<p>You can download all of the <a href="https://github.com/airportyh/trampoline.js">code examples</a> shown in this post.</p>
<h2>References<br></h2>
<div>
	<ol>
		<li><a href="http://www.dabeaz.com/coroutines/index.html"> A Curious Course on Coroutines and Concurrency</a> brilliant tutorial on generators by David Beazley<br></li>
		<li><a href="https://developer.mozilla.org/en/New_in_JavaScript_1.7">Introduction to Generators and Iterators in JavaScript 1.7</a> - from MDN<br></li>
		<li><a href="http://www.neilmix.com/2007/02/07/threading-in-javascript-17/">Threading in JavaScript 1.7</a> by Neil Mix<br></li>
	</ol>
</div></content>
        </entry>,<entry>
            <title>Tutti - Multiple Browser Interactive Javascript Shell</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/12/09/tutti---multiple-browser">
            <updated>2010-12-09T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/12/09/tutti---multiple-browser</li>
            <content type="text">
<p><i>Cough, cough...</i></p>
<p>Have you ever wished that the Firebug console or <i>&lt;insert your favorite Javascript Shell&gt;</i> could execute the piece of Javascript you typed in on IE, or maybe some other browsers as well - <i>at the same time?</i></p>
<p><i>Well, now you can! Now</i> there's <a href="http://tuttijs.com">Tutti</a> - a Javascript Shell that will lets you execute Javascript on multiple browsers - <i>all at the same time!</i></p>

<p><i></i>Here's how it works: to get started, </p>
<ol>
	<li>Open <a href="http://tuttijs.com">tuttijs.com</a> in your browser</li>
	<li>Create a new room <i>(click)</i>.</li>
	<li>Copy-n-paste the URL from your current browser window to another browser of your choice, say, IE 8.</li>
	<li>Repeat step two for each browser you you want to test.</li>
	<li>Type in some Javascript, hit ENTER, and see them results from all your browsers!</li>
</ol>
<p>Tutti uses <a href="http://socket.io/">Socket.IO</a>, <a href="http://nodejs.org/">node.js</a>, and <a href="http://en.wikipedia.org/wiki/WebSockets">WebSocket</a> technology - <i>it's so just cloud™</i>!</p>
<p>Tutti supports on all major browsers, including</p>
<ul>
	<li>Firefox 3.6 and 4<br></li>
	<li>Chrome 8.0<br></li>
	<li>Safari 5.0<br></li>
	<li>Safari 4 Mobile for iPad<br></li>
	<li>Opera 10<br></li>
	<li>Internet Explorer 6, 7, and 8<br></li>
</ul>
<p>Tutti is open source, but <i>that's not all</i>, it's also <a href="http://github.com/airportyh/tutti">hosted on GitHub</a> so you can download it and run it on your own machine, or better yet: <i>fork it</i> and hack on it to your heart's content!</p>
<p>Try it <i>now!</i></p>
<p><i>To try it go to </i><a href="http://tuttijs.com">tuttijs.com</a><i>, or get the source at </i><i><a href="http://github.com/airportyh/tutti">http://github.com/airportyh/tutti</a>. Remember dependencies such as Socket.IO-node, ExpressJS, node.js are installed separately.</i></p>
<p><i>Update: I've changed the domain to tuttijs.com. The old domain is still accessible though.</i></p>

<p><i>Update: for those interested in using this for Javascript testing, I have created a new tool called [Testem](http://tobyho.com/2012/06/24/testem-interactive-js-test-runner/).</i></p></content>
        </entry>,<entry>
            <title>Running More Than One Version of Firefox At the Same Time</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/12/06/running-more-than-one-version">
            <updated>2010-12-06T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/12/06/running-more-than-one-version</li>
            <content type="text">
<p><i>Finally figured out how to run multiple versions of Firefox simultaneously. </i></p>
<p>First, you need to create some profiles, one for each Firefox version you want to run. Run</p>
<pre><code>&lt;path-to-firefox&gt;/firefox-bin -ProfileManager</code></pre>
<p>On Mac that's usually:<br></p>
<pre><code>/Applications/Firefox.app/Contents/MacOS/firefox-bin -ProfileManager
</code></pre>
<p>Doesn't matter which version you use to open the profile manager because the profiles are shared between all the versions, and so you only have to create the profiles once. I called my profiles: FF4, FF3, and FF2 respectively.<br></p>
<p>I installed my different versions under these locations</p>
<div>
	<ul>
		<li>/Applications/Firefox4b.app<br></li>
		<li>/Applications/Firefox3.app<br></li>
		<li>/Applications/Firefox2.app<br></li>
	</ul>
</div>
<p>Once you have the profiles created, you can launch each version like such:</p>
<pre><code>/Applications/Firefox4b.app/Contents/MacOS/firefox-bin -P FF4 -no-remote &</code></pre>
<p>for Firefox 4 beta,<br></p>
<pre><code>/Applications/Firefox3.app/Contents/MacOS/firefox-bin -P FF3 -no-remote &
</code></pre>
<p>for Firefox 3, and</p>
<pre><code>/Applications/Firefox2.app/Contents/MacOS/firefox-bin -P FF2 -no-remote &
</code></pre>
<p>for Firefox 2, <i>just cuz I can</i>.</p>
<p>Now of course, that's quite a lot of typing to have to do each time you want to launch the browser so I put those one-liners into handy little shell scripts which you can do too.</p>
<div><div class="image">
	<img title="More Than One Version of Firefox" alt="More Than One Version of Firefox" src="http://lh5.ggpht.com/_1m4jxPGXQAo/TP0RvLhvBMI/AAAAAAAARAo/IaGcVu80yQ0/s800/Screen%20shot%202010-12-06%20at%2011.38.40%20AM.jpg">
</div><br></div>
<p><i>Happy happy joy joy!</i></p>
<p>For other platforms it's more or less the same thing, just the installation paths would be different.</p>
<div><br><div>See more detailed info about <a href="http://robertnyman.com/2009/07/01/firefox-35-is-released-information-about-having-multiple-firefox-versions-and-web-developer-extension-compatibility/">running multiple versions of Firefox on different platforms</a>.</div></div></content>
        </entry>,<entry>
            <title>Two Strategies for Avoiding Tedious Null-Checks</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/11/30/two-strategies-for-avoiding">
            <updated>2010-11-30T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/11/30/two-strategies-for-avoiding</li>
            <content type="text">
<p>Programmers have been plagued by having to write numerous checks for null values ever since the <em>dawn of time</em>. Consider this example,</p>

<pre><code>var customer = database.get(id)
var customerLastName = customer.name.last
</code></pre>

<p>What if I told you that, any of <code>customer</code>, <code>customer.name</code>, and <code>customer.name.last</code> could be <code>null</code> at runtime? And if any of them are <code>null</code> just set <code>customerLastName</code> to <code>"Unknown"</code>. You’d probably do something like</p>

<pre><code>var customerLastName = "Unknown"
var customer = database.get(id)
if (customer && customer.name && customer.name.last){
    customerLastName = customer.name.last
}
</code></pre>

<p>This is an awful lot of repetitive code, and you really don’t want to be writing it over and over again. But, what’s worse than having to write it, is actually having to read it later on.</p>

<p>To see the amount of repetition in the above code, let’s break down the word frequency. The top repeated words are</p>

<ul><li><code>customer</code>: 5</li>
<li><code>name</code>: 3</li>
<li><code>last</code>: 2</li>
<li><code>customerLastName</code>: 2</li>
</ul><p>If you count phrases too,</p>

<ul><li><code>customer.name</code>: 3</li>
<li><code>customer.name.last</code>: 2</li>
</ul><p>There are actually <a href="http://weblog.raganwald.com/2008/01/objectandand-objectme-in-ruby.html">numerous</a> <a href="http://ozmm.org/posts/try.html">hacks</a> <a href="http://weavejester.com/node/10">out</a> <a href="http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator%28%3F.%29">there</a> already dedicated to solving this problem for ruby, groovy, and other various programming languages.</p>

<p>In this post, I am going to investigate two approaches to tackling this in Javascript.</p>

<h2>Approach 1</h2>

<p>Because <code>null</code> isn’t an object in Javascript, approaches like <a href="http://weblog.raganwald.com/2008/01/objectandand-objectme-in-ruby.html">andand</a> won’t work. So, what do we do when we want to extend something but can’t modify it? Right! We wrap it! This approach is called <em>NullSafe</em>. Basically, like jQuery, you wrap the object you want to <em>query</em>, and then chain method calls to it until you get the result you are looking for. At the end, you have to unwrap it to get the computed value. What I came up with is this:</p>

<pre><code>var customer = database.get(id)
var customerLastName = NullSafe(customer)._('name')._('last').val() || "Unknown"
</code></pre>

<p>Actually, I made it a little more powerful than that, even. In addition to getting an object’s properties, you can also call methods:</p>

<pre><code>var customerLastName = NullSafe(database).$('get', id)._('name')._('last').val() || "Unknown"
</code></pre>

<p>Then I added just a bit more convenience with the variable length arguments for getting a chain of properties:</p>

<pre><code>var customerLastName = NullSafe(database).$('get', id)._('name', 'last').val() || "Unknown"
</code></pre>

<p>How is this? Is this good? The syntax takes a little getting used to, but the advantage is that you only have write each thing just once, rather than the big repetitive mess you saw above. Also, chaining allows you to write everything in one line.</p>

<p>The implementation of <code>NullSafe</code> is pretty simple too, all but 30-plus LOC,</p>

<pre><code>function NullSafe(obj){
    function NullSafe(obj){
        this.obj = obj
    }
    Wrapper = NullSafe
    var proto = Wrapper.prototype
    proto.call = proto.$ = function(){
        var name = arguments[0]
        var args = Array.prototype.slice.call(arguments, 1)
        var obj = null
        if (this.obj){
            var func = this.obj[name]
            if (this.obj && func){
                obj = func.apply(this.obj, args)
            }
        }
        return new Wrapper(obj)
    }
    proto.get = proto._ = function(){
        var curr = this.obj
        for (var i = 0; i &lt; arguments.length; i++){
            if (curr != null){
                curr = curr[arguments[i]]
            }
        }
        return new Wrapper(curr)
    }
    proto.val = function(){
        return this.obj
    }
    proto.toString = function(){
        return String(this.obj)
    }
    return new Wrapper(obj || this)
}
</code></pre>

<p>But then you might wonder why in the world I didn’t just use a <code>try</code>-<code>catch</code> block?</p>

<pre><code>var customerLastName = "Unknown"
try{
    customerLastName = database.get(id).name.last
}catch(e){}
</code></pre>

<h2>Approach 2</h2>

<p>As you saw, the <code>try</code>-<code>catch</code> approach isn’t so bad. It is a bit verbose, and spans multiple lines, but we can fix that. </p>

<pre><code>var customerLastName = $try(function(){return database.get(id).name.last}) || "Unknown"
</code></pre>

<p>Pretty nice! Although the actually code is slightly longer than <em>NullSafe</em>, this is easier to understand because within the inline function you are just writing what you would have normally written anyway if you hadn’t had to do the null checks. </p>

<p>The implementation is even simpler,</p>

<pre id="scroll_to_here"><code>function $try(func){
    try{
        return func()
    }catch(e){
        return null
    }
}
</code></pre>

<h2>Performance</h2>

<p>I normally don't prematurely optimize, but with jsperf.com, I thought I’d be fun to compare. Intuitively, <code>$try</code> should be faster because it’s doing less, but then again, exception handling <em>can</em> be slow.</p>

<p>I created two separate tests, one in which the chain would <em>have</em> values <a href="http://jsperf.com/2-approachs-to-avoid-null-checks-a">all the way through to the end</a>, and another in which it would null-out early.</p>

<h3>Results</h3>

<p>The results were - drum roll please - <code>$try</code> was significantly faster in almost all browsers, the only exceptions where is the <em>null-out early</em> case for Chrome and Firefox, where it was only slightly slower - 20% - 40%. But in all the other cases, <code>$try</code> was faster, in some cases, much faster - almost 7 times in Safari.</p>

<h2>Conclusion</h2>

<p>With that, I will conclude that <code>$try</code> is my preferred approach, given that it is easier to implement, produces easier to understand code, and executes faster that <code>NullSafe</code>. </p></content>
        </entry>,<entry>
            <title>Javascript Constructors and Prototypes</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/11/22/javascript-constructors-and">
            <updated>2010-11-22T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/11/22/javascript-constructors-and</li>
            <content type="text">

<p>If you didn’t already know, Javascript functions double as object constructors. For example, to simulate a <em>class</em> in object-oriented programming, you would write</p>
{% highlight js %}
function Person(name){
    this.name = name
}
{% endhighlight %}
<p><em>Note: I avoid using semicolons because I am a heretic! Mislav argues my point for me <a href="http://mislav.uniqpath.com/2010/05/semicolons/">here</a></em>. </p>

<p>Anyway, now that you have a function, you’d use the <code>new</code> statement to create a <code>Person</code></p>

{% highlight js %}
var bob = new Person('Bob')
// {name: 'Bob'}
{% endhighlight %}

<p>Just to be sure that <code>bob</code> is indeed a <code>Person</code>, we can ask </p>

{% highlight js %}bob instanceof Person
// true
{% endhighlight %}

<p>You <em>could</em> also call <code>Person</code> as a function - without the <code>new</code>,</p>

{% highlight js %}Person('Bob')
// undefined
{% endhighlight %}

<p>but that just returns <code>undefined</code>. Also, you really don’t want to do this, because you’ve
just unintentionally created a <code>name</code> global variable</p>

{% highlight js %}name
// 'Bob'
{% endhighlight %}

<p>Uh… that’s not good, especially if I already had a variable called <code>name</code>, it would have been
overwritten. The reason this happens is because when you call a function as a function(without <code>new</code>), <code>this</code> is set to the <em>global object</em> - in the browser, this is the <code>window</code> object, see</p>

{% highlight js %}window.name
// 'Bob'
this === window
// true
{% endhighlight %}

<p>So… if you want to write a constructor, use it <em>like</em> a constructor, if you want to write a function, use it <em>like</em> a function, don’t mix and match.</p>

<p>Someone pointed out though, that you can prevent this <em>polluting of the namespace</em>(those are just big words for <em>creating global variables</em>) by using this trick</p>

{% highlight js %}function Person(name){
    if (!(this instanceof Person))
        return new Person(name)
    this.name = name
}
{% endhighlight %}

<p>What this does is:</p>

<ol><li>Check whether <code>this</code> is really a <code>Person</code> - which it would be if called using <code>new</code>.</li>
<li>If it indeed is a <code>Person</code>, go on your merry way.</li>
<li>If it is not a <code>Person</code>, use a <code>new</code> to create a <code>Person</code> - the correct way, and return it.</li>
</ol>
<p>This allows calling it as a function to return a <code>Person</code>, <em>and</em> it doesn’t pollute the namespace.</p>

{% highlight js %}Person('Bob')
// {name: 'Bob'}
name
// undefined
{% endhighlight %}

<p>But what is surprising is that calling it with <code>new</code> still works too</p>

{% highlight js %}new Person('Bob')
// {name: 'Bob'}
{% endhighlight %}

<p>Why? It turns out that if you return a value in a <em>constructor</em>, Javascript will honor it, and return <em>it</em> as the newly created object when you use a <code>new</code>. But, you might be thinking, can I return a non-<code>Person</code>? That would be kind of like lying.</p>

{% highlight js %}function Cat(name){
    this.name = name
}
function Person(name){
    return new Cat(name)
}
var bob = new Person('Bob')
bob instanceof Person
// false
bob instanceof Cat
// true
{% endhighlight %}

<p>So, I ask for a <code>Person</code> and I get a <code>Cat</code>? Well, in Javascript it <em>can</em> happen. You can even return an <code>Array</code>.</p>

{% highlight js %}function Person(name){
    return [name]
}
new Person('Bob')
// ['Bob']
{% endhighlight %}

<p>There are limits to this madness though: if you return a value of a primitive type, this won’t work.</p>

{% highlight js %}function Person(name){
    this.name = name
    return 5
}
new Person('Bob')
// {name: 'Bob'}
{% endhighlight %}

<p><code>Number</code>, <code>String</code>, <code>Boolean</code>, are all primitive types. If you return one of these types of values 
from a constructor, it would be ignored and the constructor would go back to its normal behavior of returning
the <code>this</code> object.</p>

<h2>Methods</h2>

<p>In the beginning, I said that functions double as constructors, well, actually, they more like <em>triple</em>. Functions also act as <em>methods</em>.</p>

<p>If you know OOP, you know that methods
are the behaviors of the object - what the object can do. In Javascript, methods are just functions attached to an object - you can create methods simply by creating functions and assigning them to the object</p>
{% highlight js %}function Person(name){
    this.name = name
    this.sayHi = function(){
        return 'Hi, I am ' + this.name
    }
}
{% endhighlight %}

<p>Bob can now say “Hi”</p>
{% highlight js %}var bob = new Person('Bob')
bob.sayHi()
// 'Hi, I am Bob'
{% endhighlight %}

<p>Actually, we can attach methods to objects without even bothering with this constructor crap and instead create an object out right</p>
{% highlight js %}var bob = {name: 'Bob'} // this is a Javascript object!
bob.sayHi = function(){
    return 'Hi, I am ' + this.name
}
{% endhighlight %}

<p>This would work just as well. Or, if you prefer, write it as one big object</p>
{% highlight js %}var bob = {
    name: 'Bob',
    sayHi: function(){
        return 'Hi, I am ' + this.name
    }
}
{% endhighlight %}

<p>So, why are we bothering with <em>constructors</em> in the first place? Answer: <em>inheritance</em>.</p>

<h2>Inheritance and the <em>Prototype</em></h2>

<p>Right, so inheritance. You know inheritance, right? You know how in Java, for
example, you can have one class inherit another and automatically <em>get</em> all the
methods and variables of the parent class?</p>
{% highlight js %}public class Mammal{
    public void breathe(){
        // do some breathing
    }
}
public class Cat extends Mammal{
    // now cat too can breathe!
}
{% endhighlight %}

<p>Well, in Javascript, we have the same thing, just <em>different</em>. For starters, we don’t even have classes! Instead, we have something called the
<em>prototype</em>. Here’s how we write the equivalent of the above Java code in Javascript</p>
{% highlight js %}function Mammal(){
}
Mammal.prototype.breathe = function(){
    // do some breathing
}
function Cat(){
}
Cat.prototype = new Mammal()
Cat.prototype.constructor = Cat
// now cat too can breathe!
{% endhighlight %}

<blockquote>
  <p><em>What’s this <code>prototype</code>? That’s just a bunch of gibberish!</em></p>
</blockquote>

<p>Javascript is different from traditional object-oriented languages in that it
uses <em>prototype inheritance</em>. In a nutshell, prototype inheritance in Javascript works like this:</p>

<ol><li>An object has a number of properties. <em>This includes any attributes or functions(methods).</em></li>
<li>An object has a special parent property, this is also called the prototype of the object(<code>__proto__</code>). An object inherits all the properties of its parent. </li>
<li>An object can override a property of its parent by setting the property on itself.</li>
<li>A constructor creates objects. Each constructor has an associated <code>prototype</code>
object, which is simply another object.</li>
<li>When an object is created, it’s parent is set to the prototype object
associated with the constructor that created it.</li>
</ol>
<p>Okay! Now that you understand everything there is to know about prototype inheritance, let’s look at our <em>Cat</em> example more closely and break it down.</p>

<p>First, we create a constructor for <code>Mammal</code></p>
{% highlight js %}function Mammal(){
}
{% endhighlight %}

<p>At this point, <code>Mammal</code> already has an associated prototype</p>
{% highlight js %}Mammal.prototype
// {}
{% endhighlight %}

<p>Let’s create an instance</p>
{% highlight js %}var mammal = new Mammal()
{% endhighlight %}

<p>Now, let’s verify the <em>second law of prototype inheritence</em>(it’s just the second bullet from the list)</p>
{% highlight js %}mammal.__proto__ === Mammal.prototype
// true
{% endhighlight %}

<p>Next, we add the <code>breathe</code> function to the <code>prototype</code> of <code>Mammal</code></p>
{% highlight js %}Mammal.prototype.breathe = function(){
    // do some breathing
}
{% endhighlight %}

<p>At this point, <code>mammal</code> the instance can breathe</p>
{% highlight js %}mammal.breathe()
{% endhighlight %}

<p>because it inherits from <code>Mammal.prototype</code>. Next,</p>
{% highlight js %}function Cat(){
}
Cat.prototype = new Mammal()
{% endhighlight %}

<p><code>Cat</code> constructor is created and we set <code>Cat.prototype</code> to a new instance of <code>Mammal</code>. Why do we do this?</p>
{% highlight js %}var garfield = new Cat()
garfield.breathe()
{% endhighlight %}

<p>because now any cat instance inherits <code>Mammal</code> and will therefore be able to breathe as well. Next,</p>
{% highlight js %}Cat.prototype.constructor = Cat
{% endhighlight %}

<p>Ensures that cats know that they are cats:</p>
{% highlight js %}garfield.__proto__ === Cat.prototype
// true
Cat.prototype.constructor === Cat
// true
garfield instanceof Cat
// true
{% endhighlight %}

<p>Each time you create a new instance of <code>Cat</code>, you create a 2-level chain, in that <code>garfield</code> is now parented by <code>Cat.prototype</code> which, since it is
an instance of <code>Mammal</code>, is in turn parented by <code>Mammal.prototype</code>.</p>

<p>Now, guess who’s the parent of <code>Mammal.prototype</code>? Yeah, you guessed it, <code>Object.prototype</code>. So actually, it’s a 3-level chain</p>

<blockquote>
  <p><code>garfield</code> -> <code>Cat.prototype</code> -> <code>Mammal.prototype</code> -> <code>Object.prototype</code></p>
</blockquote>

<p>You can add properties to any of <code>garfield</code>’s parents, and <code>garfield</code> would
magically gain those properties too, even <em>after</em> <code>garfield</code> has already been
created!</p>
{% highlight js %}Cat.prototype.isCat = true
Mammal.prototype.isMammal = true
Object.prototype.isObject = true
garfield.isCat // true
garfield.isMammal // true
garfield.isObject // true
{% endhighlight %}

<p>You can ask whether he has a given property</p>
{% highlight js %}'isMammal' in garfield
// true
{% endhighlight %}

<p>and you can also distinguish between <em>own</em> properties vs <em>inherited</em> properties</p>
{% highlight js %}garfield.name = 'Garfield'
garfield.hasOwnProperty('name')
// true
garfield.hasOwnProperty('breathe')
// false
{% endhighlight %}

<h2>Setting Methods on the Prototype</h2>

<p>Now that you <em>really</em> understand prototypes, let’s go back to the very first
example of defining methods on objects</p>
{% highlight js %}function Person(name){
    this.name = name
    this.sayHi = function(){
        return 'Hi, I am ' + this.name
    }
}
{% endhighlight %}

<p>This is actually not the optimal way to do it. A better way is to define the
method on <code>Person.prototype</code></p>
{% highlight js %}function Person(name){
    this.name = name
}
Person.prototype.sayHi = function(){
    return 'Hi, I am ' + this.name
}
{% endhighlight %}

<p><em>Why</em> is this better? Anyone? Anyone? Beuller?</p>

<p>In the first version, each time you create a person, a new <code>sayHi</code> function will be created for him, where as in the second version, only one <code>sayHi</code> function is ever created, and is shared amongst all persons that are created - because <code>Person.prototype</code> is their parent. Thus, declaring methods on the prototype is more memory efficient.</p>

<h2>Apply and Call</h2>

<p>As you can see, functions become methods just by virtue of being attached to objects, at which point the <code>this</code> within that function refers to the object which it is attached to, right? Well… not exactly. Look at our previous example</p>
{% highlight js %}function Person(name){
    this.name = name
}
Person.prototype.sayHi = function(){
    return 'Hi, I am ' + this.name
}
{% endhighlight %}

<p>Now, if you create 2 people, <code>jack</code> and <code>jill</code></p>

{% highlight js %}var jack = new Person('Jack')
var jill = new Person('Jill')
jack.sayHi()
// 'Hi, I am Jack'
jill.sayHi()
// 'Hi, I am Jill'
{% endhighlight %}

<p>Here, <code>sayHi</code> is not attached to <code>jack</code> or <code>jill</code>, rather, it’s attached to their prototype: <code>Person.prototype</code>. How does the function <code>sayHi</code> know <code>jack</code> and <code>jill</code>’s names?</p>

<blockquote>
  <p>Answer: <code>this</code> is not bound to any particular object <em>until</em> you call the function.</p>
</blockquote>

<p>When you call <code>jack.sayHi()</code>, <code>sayHi</code>’s <code>this</code> will be bound to <code>jack</code>; when you call <code>jill.sayHi()</code>, it will be bound to <code>jill</code> instead, but binding does <em>not</em> change anything about the function itself - it’s still the same function!</p>

<p>It turns out that you can explicitly bind a function to an object yourself.</p>
{% highlight js %}function sing(){
    return this.name + ' sings!'
}
sing.apply(jack)
// 'Jack sings!'
{% endhighlight %}

<p>The <code>apply</code> method belongs to <code>Function.prototype</code>(yeah, that’s right, functions are objects and have prototypes too and can also have properties!). So, you can use <code>apply</code> with any function to call it while binding it to the object of your choosing, even if the function is not attached to it. In fact, you can <em>even</em> apply the method to an object of a different type</p>
{% highlight js %}function Flower(name){
    this.name = name
}
var tulip = new Flower('Tulip')
jack.sayHi.apply(tulip)
// 'Hi, I am Tulip'
{% endhighlight %}

<p>You might say</p>

<blockquote>
  <p><em>Wait a minute! A Tulip is not supposed to say hi!</em></p>
</blockquote>

<p>To that, I would say</p>

<blockquote>
  <p><em>Everything is everybody. Everybody is everything. We all cool! Just…chill, man!</em></p>
</blockquote>

<p>As long as the object has a <code>name</code> property, <code>sayHi</code> is happy to print it out. This is the principle of <em>duck typing</em></p>

<blockquote>
  <p>If it quacks like a duck and it walks like a duck - it’s a duck to me.</p>
</blockquote>

<p>I am sure I misquoted that, but whatever. </p>

<p>Now back to the <code>apply</code> function: if you want to include parameters you can pass them as an array as the second parameter to <code>apply</code>.</p>
{% highlight js %}function singTo(other){
    return this.name + ' sings for ' + other.name
}
singTo.apply(jack, [jill])
// 'Jack sings for Jill'
{% endhighlight %}

<p><code>Function.prototype</code> also has a <code>call</code> function, which works very much like <code>apply</code>. The only difference is in that rather than passing the parameters as an array in the second parameter, you would just add them to the end:</p>
{% highlight js %}sing.call(jack, jill)
// 'Jack sings for Jill'
{% endhighlight %}

<h2>The <code>new</code> method</h2>

<p>Now, for something <em>fun</em>…</p>

<p><code>apply</code> is really handy for certain situations when you want to call a function with a variable list of arguments. For example, the <code>Math.max</code> function takes a variable number of arguments</p>
{% highlight js %}Math.max(4, 1, 8, 9, 2)
// 9
{% endhighlight %}

<p>This is nice, but it’s not generic. By using <code>apply</code> you can get the max for an arbitrary array,</p>
{% highlight js %}Math.max.apply(Math, myarray)
{% endhighlight %}

<p>Much more useful!</p>

<p>Now, given that <code>apply</code> is so useful, there may come times when you want to use it, but rather than call-as-function,</p>
{% highlight js %}Math.max.apply(Math, args)
{% endhighlight %}

<p>you want to call-as-constructor.</p>
{% highlight js %}new Person.apply(Person, args)
{% endhighlight %}

<p>Sadly, this doesn’t work. It’ll think you are calling <code>Person.apply</code> as a constructor. How about this</p>
{% highlight js %}(new Person).apply(Person, args)
{% endhighlight %}

<p>That doesn’t work either, because it will first construct a person, and then try calling the <code>apply</code> method on that person.</p>

<p>What to do? Thanks to an idea presented on <a href="http://stackoverflow.com/questions/813383/how-can-i-construct-an-object-using-an-array-of-values-for-parameters-rather-tha#answer-813401">this answer on StackOverflow</a>, there is a way!</p>

<p>We can create a <code>new</code> method for <code>Function.prototype</code>.</p>
{% highlight js %}Function.prototype.new = function(){
    var args = arguments
    var constructor = this
    function Fake(){
         constructor.apply(this, args)
    }
    Fake.prototype = constructor.prototype
    return new Fake
}
{% endhighlight %}

<p>With this, we can call constructors with the <code>new</code> method rather than the <code>new</code> statement</p>
{% highlight js %}var bob = Person.new('Bob')
{% endhighlight %}

<p>Let’s go through how the <code>new</code> method works.</p>

<p>First,</p>
{% highlight js %}var args = arguments
var constructor = this
function Fake(){
     constructor.apply(this, args)
}
{% endhighlight %}

<p>we create a <code>Fake</code> constructor which will <code>apply</code> our real constructor as a method when created. In the context of the <code>new</code> method, <code>this</code> is the <em>real</em> constructor - we save it to be used in the <code>Fake</code> constructor. We also save the arguments with which <code>new</code> was called to reuse in the <code>Fake</code> constructor. Next,</p>
{% highlight js %}Fake.prototype = constructor.prototype
{% endhighlight %}

<p>we set <code>Fake.prototype</code> to the original constructor. Since the prototype’s <code>constructor</code> property is still set to the original constructor, any object created by <code>Fake</code> will still be an <code>instanceof</code> the original constructor. Finally,</p>
{% highlight js %}return new Fake
{% endhighlight %}

<p>Create the object using the <code>Fake</code> constructor and return it.</p>

<p>Did you get all that? It’s okay if you don’t get it the first time; just look it over and poke at it a few more times.</p>

<p>Anyways, the point of all of that was that now you can do things like</p>
{% highlight js %}var children = [new Person('Ben'), new Person('Dan')]
var args = ['Bob'].concat(children)
var bob = Person.new.apply(Person, args)
{% endhighlight %}

<p>Nice! But why do we have to write <code>Person</code> twice? We can probably write a helper method</p>
{% highlight js %}Function.prototype.applyNew = function(){
     return this.new.apply(this, arguments)
}
{% endhighlight %}

<p>So you can do</p>
{% highlight js %}var bob = Person.applyNew(args)
{% endhighlight %}

<p>Nice, slightly better!</p>

<blockquote>
  <p>What’s the point of this exercise anyway?</p>
</blockquote>

<p>Well, it shows that Javascript is a flexible little language. Even if it doesn’t do the things you want, you can probably mold it into doing them.</p>

<h2>Summary</h2>

<p>This is the end of this lesson/article/blog post. It was nice having you! Today we learned about:</p>

<ol><li>Constructors</li>
<li>Methods and Prototypes</li>
<li><code>apply</code> and <code>call</code></li>
<li>Implementing the <code>new</code> method</li>
</ol></content>
        </entry>,<entry>
            <title>5 Great Resources for Learning Javascript Fundamentals</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/11/10/5-great-resources-for-learning">
            <updated>2010-11-10T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/11/10/5-great-resources-for-learning</li>
            <content type="text">
<p>In the spirit of <a href="http://voodootikigod.com/jsconf-eu-2010-speech">PromoteJS</a>, I researched and collected a short list of good resources for learning Javascript fundamentals - <i>no frameworks, just Javascript</i>:</p>
<div>
	<ol>
		<li><a href="https://developer.mozilla.org/en/JavaScript/A_re-introduction_to_JavaScript">A re-introduction to JavaScript</a> - an excellent article covering all the important stuff in a digestible manner.<br></li>
		<li><a href="http://ejohn.org/apps/learn/">Resig's interactive "Advanced Javascript" tutorial</a> - although it is for <i>Javascript Ninjas</i>, it is nevertheless very approachable.<br></li>
		<li><a href="http://phrogz.net/js/classes/OOPinJS2.html">Prototype Inheritance in JS</a> - a concise and well written article about one of the most interesting aspects of Javascript.<br></li>
		<li><a href="http://stackoverflow.com/questions/11246/best-resources-to-learn-javascript">Best resources to learn JavaScript</a> - SO's Q&A. The bests answers are overwhelmingly: the Douglas Crockford videos. Which I agree: if you are serious about learning Javascript, grab some popcorn, sit down and listen to this man talk.<br></li>
		<li>Just in case you are a n00b and don't know about <a href="http://getfirebug.com/">Firebug</a>, you <i>must</i> get it. Having an interactive console will make a huge difference in the speed of your learning progress.</li>
	</ol>
</div>
<p>Bonus: Rebecca Murphy's <a href="http://jqfundamentals.com/">jQuery Fundamentals</a>.</p></content>
        </entry>,<entry>
            <title>Quick-and-Dirty Presentations in Markdown</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/11/08/quick-and-dirty-presentations">
            <updated>2010-11-08T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/11/08/quick-and-dirty-presentations</li>
            <content type="text">
<p><i>Update: because the showdown.js link is dead, I've created a <a href="https://github.com/airportyh/QuickSlides">github repo</a> for this.</i></p>
<p>Introducing <a href="http://tobyho.com/slides">QuickSlides</a>: Quick and Dirty Presentations in Markdown using <a href="http://www.w3.org/Talks/Tools/Slidy2/">Slidy</a> and <a href="http://attacklab.net/showdown/">Showdown</a>.</p>
<div>In nutshell: First, <s>you download this </s><a href="http://tobyho.com/slides/template.html"><s>template file</s></a><s>.</s> clone my repo:</div>
<pre><code>git clone git@github.com:airportyh/QuickSlides.git name
</code></pre>
<p>where <i>name</i> is the directory name you want for your presentation.</p>
<p>Then, edit presentation.html and write your slides in Markdown within the <script type=text/markdown> tag, separating the slides by Markdown's horizontal rule expression, such as:</p>
<pre><code>***</code></pre>
<p>Open it in your browser, and boom! Here is the <a href="http://tobyho.com/slides">full intro</a> in slide format.<br></p>
<p>The idea came to me to write presentation slides in <a href="http://daringfireball.net/projects/markdown/">Markdown</a> after I've been writing documentation in Markdown using a documentation generation tool I based off of <a href="http://fitzgen.github.com/pycco/">Pycco</a>/<a href="http://jashkenas.github.com/docco/">Docco</a>. I had used <a href="http://meyerweb.com/eric/tools/s5/">S5</a> before, and remember what a pain it was to write in HTML, so Markdown is perfect for this job.</p>
<p>I googled around and found a few tools: </p>
<div>
	<ul>
		<li><a href="https://github.com/schacon/showoff">ShowOff</a><br></li>
		<li><a href="https://github.com/nakajima/slidedown">Slidedown</a><br></li>
	</ul>
</div>
<p>But both required ruby, and thus some sort of installation process. I figured it couldn't be too hard extending something like s5/slidy with showdown.js, which is what I did.</p>
<p><i><span><br></span></i></p></content>
        </entry>,<entry>
            <title>Sencha Touch Overview</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/09/17/sencha-touch-overview">
            <updated>2010-09-17T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/09/17/sencha-touch-overview</li>
            <content type="text">
<p>In June of this year, ExtJS made the big announcement that they were changing their name to <a href="http://www.sencha.com/">Sencha</a>. Also, they recruited some Javascript rockstars and release a new UI framework called <a href="http://www.sencha.com/products/touch/">Sencha Touch</a>.</p>
<p>Sencha Touch is a high-level Javascript UI framework designed to run on touch-based devices. Currently, it targets the iPhone, the iPad, and Android based phones. What is interesting is that because its targeted devices are running WebKit, the framework can use all the features that HTML5 and CSS3 have to offer. It features beautiful interactive UI elements which mirror native iPhone interfaces, but not in a pixel-by-pixel way - they put their own touches into it.</p>
<p>I jumped in and used it to build the iPhone version of a Todo-list app I had been building. Here are my impressions of the framework so far.</p>
<div>
	<ol>
		<li>There are a plethora of UI controls and they look great. Go see their <a href="http://dev.sencha.com/deploy/touch/examples/kitchensink/">kitchen sink demo</a> for all of them. Some still need polishing in places. </li>
		<li>The framework is more like ExtJS/YUI/Dojo than jQuery in that it's a high-level MVC/widget-based framework.</li>
		<li>Documentation is very lacking right now.</li>
		<li>Code is beta and very unstable.</li>
		<li>There are plenty of sample code and is open source, so you can get into it if you are good at reading code and willing to do some digging.</li>
		<li>Not super lightweight. Latest version 0.95 is 295kb. (jQuery is 24kb)</li>
		<li>GPLv3 license. Commercial licence is $99 per developer seat. No per domain or per app license required.</li>
		<li>Have a somewhat rigid MVC model which requires you to code your models on their terms: I don't particularly like this.</li>
		<li>Has an interesting prototype-inheritance-based approach to configuring and instantiating widgets.</li>
		<li>There is a template language called xtemplate.</li>
	</ol>
</div>
<p>Now for some code!</p>
<p><span><span><br></span></span></p>
<h3>App Initialization</h3>
<p>The html of Sencha Touch apps generally have an empty body tag - everything is create on the fly from Javascript. The app init happens in: <i>Ext.setup</i>. Here's an example:</p>
<pre><code>Ext.setup({
    tabletStartupScreen: 'tablet_startup.png',
    phoneStartupScreen: 'phone_startup.png',
    icon: 'icon.png',
    glossOnIcon: true,
    onReady: function() {
        // write your setup code here
    }
});
</code></pre>
<p>As arguments to <i>setup</i>, you provide the various different launch icons for different devices, and an <a href="/OnReady_In_A_Smaller_Package">onReady</a> function. The onReady function would usually instantiate UI widgets and run other setup code.</p>
<h3>Make the Widgets</h3>
<p>Within <i>onReady</i>, you would instantiate the top-level widget for the app. Here's an example:</p>
<pre><code>var tabs = new Ext.TabPanel({
    fullscreen: true,
    type: 'dark',
    sortable: true,
    items: [{
        title: 'Tab 1',
        html: '1',
        cls: 'card1'
    }, {
        title: 'Tab 2',
        html: '2',
        cls: 'card2'
    }, {
        title: 'Tab 3',
        html: '3',
        cls: 'card3'
    }]
});
</code></pre>
<p>This creates a <i>TabPanel</i>, which has three items - each corresponding to a tab, with their respective <i>title, html, </i>and <i>cls</i> attributes. In this simple example, we just specify the contents of each tab via simple html. The key-value pairs that are passed to the TabPanel into the constructor will all be set onto the TabPanel itself. So, that means <i>tabs</i> will have the attributes: <i>fullscreen</i>, <i>type</i>, <i>sortable</i>, and <i>items</i> - although <i>items</i> will be transformed into an event-capable array: Ext.util.MixedCollection, and each item will be transformed into a Panel. The <i>items</i> attribute generally contain the children of a container in Sencha Touch.</p>
<h3>Using xtype to Instantiate Children</h3>
<p>As you can see from the above example, instantiating a widget usually involve passing a nested object into its constructor, and the constructor will actually convert some of these specifications into child widgets. You can use the <i>xtype</i> attribute to specify the type of the child widget. One example of this is in creating a FormPanel:</p>
<pre><code>var form = new Ext.form.FormPanel({
    scroll: 'vertical',
    title: 'Enter URL',
    items: [
        {
            xtype: 'fieldset',
            defaults: {
                labelAlign: 'left'
            },
            items: [{
                xtype: 'textfield',
                name : 'url',
                label: 'URL'
            }],
            instructions: 'Enter a valid URL.'
        }
    ]})
</code></pre>
<p>The form is a big nested structure of fieldsets, labels, textfields, and what-have-you's. By using <i>xtype</i> to specify the types of subcontrols, you can instantiate all the children of a panel simply by writing a big nested tree of objects and arrays. In his example, the type 'fieldset' gets mapped to Ext.form.FieldSet, and 'textfield' is mapped to Ext.form.TextField. Alternatively, you could instantiate each child control manually, like this:</p>
<pre><code>var form = new Ext.form.FormPanel({
    scroll: 'vertical',
    title: 'Enter URL',
    items: [
        new Ext.form.FieldSet({
            defaults: {
                labelAlign: 'left'
            },
            items: [new Ext.form.TextField({
                name : 'url',
                label: 'URL'
            })],
            instructions: 'Enter a valid URL.'
        }
    ]}))</code></pre>
<h3>The Data Model</h3>
<p>For data-driven controls - such as Lists and Trees, Sencha Touch requires that you use their data model abstraction. This means you can either implement their protocol on your existing data, or just use some helpers to do the conversion. I chose the latter approach because I am lazy.</p>
<p>To create a data model for use, you first need to register a model, like this:</p>
<pre><code>Ext.regModel('Task', {
    fields: ['name', 'description']
});
</code></pre>
<p>You could also give it type metadata such as:</p>
<pre><code>Ext.regModel('Task', {
    fields: [        {name: 'name', type: 'string'},        {name: 'description', type: 'string'}    ]
})</code></pre>
<p>To convert an array of objects(with the prescribed fields) into an Ext data store, you would do:</p>
<pre><code>var dataStore = new Ext.data.Store({
    model: 'Task',
    data: tasks
})
</code></pre>
<p>This will wrap both the array <i>tasks</i> and the objects included in the array to give them the ability to notify change listeners and so forth.</p>
<p>To bind <i>dataStore</i> to a List control, you would do:</p>
<pre><code>var listControl = new Ext.List({
    store: dataStore
})</code></pre>
<p>or bind it after the fact with bindStore:</p>
<pre><code>listControl.bindStore(dataStore)</code></pre>
<p>To create a Task object, you need to ask the model manager:</p>
<pre><code>var task = Ext.ModelMgr.create({
    name: 'clean up',
    desc: 'About time.'
}, 'Task')
</code></pre>
<div>
	<h3>Template Language</h3>
</div>
<p>Sencha Touch includes a template language, which notably is used to render list items in the Ext.List control. A template may looks like this:</p>
<pre><code>'&lt;tpl for="."&gt;&lt;div class="task"&gt;&lt;strong&gt;&lt;span style="float: right"&gt;\
{count}&lt;/span&gt;{name}&lt;/strong&gt;&lt;/div&gt;&lt;/tpl&gt;'</code></pre>
<p>Curlies are used to inject variable substitution. The <i>for="."</i> tells the template engine to start at the top level of an item in the data store. So <i>count</i> would resolve to <i>item.count</i>, and <i>name</i> resolves to <i>item.name</i>. The language is pretty featureful, more information <a href="http://dev.sencha.com/deploy/touch/docs/source/XTemplate.html#cls-Ext.XTemplate">here</a>.</p>
<h3>Wrap Up</h3>
<p>This concludes a brief overview of Sencha Touch. If you want to learn more, dig into the samples and source code and start hacking.</p>
<h2><i>You Might Also Like</i></h2>
<div>
	<ul>
		<li><i><a href="/How_Much_of_the_Web_Actually_Work_Without_Javascript">How Much of the Web Actually Work Without Javascript</a><br></i></li>
		<li><a href="/Javascript_Constructors_and_Prototypes"><i>Javascript Constructors and Prototypes</i></a><br></li>
	</ul>
</div></content>
        </entry>,<entry>
            <title>MOG vs Thumbplay</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/07/21/mog-vs-thumbplay">
            <updated>2010-07-21T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/07/21/mog-vs-thumbplay</li>
            <content type="text">
<p>I just learned about these two new-ish online streaming music services. This post will be a comparison of the two, in much the style of my old<a href="e-music vs rhapsody"> e-music vs rhapsody post</a>. </p>
<p>First a word about my experience with Rhapsody. The verdict is: I tried it for a few months, and then cancelled. Ultimately not being about to play on my iPod(the iPod Classic, that is - actually this was before it was branded <i>Classic</i>), was the deal breaker. </p>
<p>The landscape has changed, on-demand streaming is the new model - it's just a matter of time. Why streaming? Well, downloading music and managing your own music library introduces several problems:</p>
<div>
	<ol>
		<li>the overhand of managing the library</li>
		<li>the overhead of syncing the music to and between different devices(mobile devices, home media center)</li>
		<li>finite disk space - although harddrives are pretty cheap nowadays, the space on mobile phones are still very limited, this makes syncing even more problematic because now you need to decide on what subset of your library you want to put on your phone</li>
	</ol>
</div>
<p>On-demand streaming services promise to deliver huge music collections to you anywhere you go for a flat monthly subscription fee. You are always just a search and click away from listening to music you've never heard before - music discovery is going to blossom like never before.</p>
<h2>Pricing<br></h2>
<p>Anyways, enough philosophizing. What is the bottom line? Both of the services cost $9.99 a month with unlimited streaming and downloading. MOG also has a $4.99 PC-only plan.</p>
<h2>Selection<br></h2>
<p>I made a list of several lesser known artists whom I love, and used them as the benchmark for testing the breath of the two services' music library. Here are the results:</p>
<div><div class="video">
	<iframe width="500" height="480" frameborder="0" src="http://spreadsheets.google.com/pub?key=0AvuDADmGj683dHlvRTJueDN2ZjNUeTh6eU40cjd2NVE&hl=en&single=true&gid=0&output=html&widget=true">
	
	</iframe>
</div><br></div>
<p>The table tallies the number of albums that were listed under each artist on each of the music services. The result in terms of total albums was a tie: 86 to 86. However, MOG faired better in the number of artists with at least one album: 16 to 13.</p>
<h2>iPhone App</h2>
<p>Thumbplay's iPhone app is more polished, but MOG's was just released a couple of days ago, and they are actively working on it.</p>
<h2>Intangibles</h2>
<p>The race is tight so far, but how does each service stand out and how do they differ? Short answer: MOG is focus on the web experience while Thumbplay is more focused on the desktop experience. MOG has a web-based UI, and social features such as sharable playlists, and blog posts. Thumbplay has a native UI, which should integrate better with the Apple Remote, but seems to lag behind in social features. I personally like the social features in MOG, and am thinking about doing a music listening blog within it.</p>
<div>
	<h2>Sound</h2>
	<div>I did a side-by-side comparison of "Let's Do It Again" by The Brand New Heavies on both services. To my ears, MOG has the better sound quality - both the bass and tremble sound crisper than Thumbplay with my Bose headphones.</div>
</div>
<h2>Streaming Limit</h2>
<p>Both services do not seem to limit the number of computers or devices you use with it, however, both of them allow you to stream to only one of them at a time.</p>
<h2>Verdict</h2>
<p>As of now, MOG is my favorite. However, it's still early days. There are big players waiting to get into the game(Apple, Spotify), and it's anyone's game. </p></content>
        </entry>,<entry>
            <title>UI Round Up: Too Many Tabs</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/07/03/ui-round-up:-too-many-tabs">
            <updated>2010-07-03T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/07/03/ui-round-up:-too-many-tabs</li>
            <content type="text">
<p>The UI paradigm of layout out things horizontally - such as tabs or the toolbars - is by now commonplace. But with this design there is a painful drawback: what do you do when you run out of horizontal space? Since, I am about to have to implement something like this for work, I did a little research on how this problem is handled. The representative sample I chose are Firefox, Safari, IE 7</p>
<div>, Chrome, and TextMate. <div>
	<h3>Firefox</h3>
	<div><div class="image">
		<img title="Firefox Tabs" alt="Firefox Tabs" src="http://lh6.ggpht.com/_1m4jxPGXQAo/TC8EV6WnFxI/AAAAAAAAQU4/aF85bFsFTfo/s800/Firefox.jpg">
	</div><br></div>
	<div>In Firefox, there's a minimum width beyond which the tabs will not shrink. Tabs that cannot fit into the real estate are hidden, but can be gotten to via the left and right scroll arrows(on the left and right of the tabs) or via the tab drop-down icon on the far right.</div>
	<h3>Safari</h3>
	<div><div class="image">
		<img title="Safari Tabs" alt="Safari Tabs" src="http://lh6.ggpht.com/_1m4jxPGXQAo/TC8EWmp8xnI/AAAAAAAAQU8/7I6pyEOfN7A/s800/Safari.jpg">
	</div><br></div>
</div><div>Safari works similar to Firefox, except that it does not have the left and right arrows.</div><h3>IE 7<br></h3><div><div class="image">
	<img title="IE 7 Tabs" alt="IE 7 Tabs" src="http://lh5.ggpht.com/_1m4jxPGXQAo/TC8EXbG4CVI/AAAAAAAAQVA/p4p8yolME2w/s800/IE.jpg">
</div><br></div></div>
<p>IE 7 has everything Firefox has, plus a thumbnail view button on the far left, which when clicked will show you all your tabs as thumbnails in the content area.</p>
<h3>Chrome</h3>
<div><div class="image">
	<img title="Chrome Tabs" alt="Chrome Tabs" src="http://lh5.ggpht.com/_1m4jxPGXQAo/TC8ETmlbVFI/AAAAAAAAQUw/cIPhJ7dhCCg/s800/Chrome.jpg">
</div><br></div>
<p>Chrome is the most curious of all. It will display all of your tabs, regardless of how many of them you have opened, or whether or not you can read the title of the tabs.</p>
<h3>TextMate</h3>
<div><div class="image">
	<img title="TextMate Tabs" alt="TextMate Tabs" src="http://lh5.ggpht.com/_1m4jxPGXQAo/TC8EVB_ZZZI/AAAAAAAAQU0/6elG0hym6FU/s800/TextMate.jpg">
</div><br></div>
<p>TextMate - the only non-browser in my sample set - handles this much like Safari, except that in the "extra tabs" drop-down, checkmarks next to an item indicates that the file is the one currently displayed in the editor, whereas in all the browser UIs we've seen, the currently displayed tab is always made visible on top.</p></content>
        </entry>,<entry>
            <title>Reading On the iPad</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/07/01/reading-on-the-ipad">
            <updated>2010-07-01T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/07/01/reading-on-the-ipad</li>
            <content type="text">
<p>First up, iBooks didn't work for me. Most of the books on my reading list were not available there. However, most of them <i>were</i> available on Kindle, and you can read any Kindle book on the iPad by downloading the free Kindle app. Does Amazon care that you are not reading them on a Kindle? No at all, since you are still paying for every book that you read.</p>
<p>So I tried reading a Kindle book: <i>Emotional Design by Donald A. Norman</i>. What I found is that reading on the iPad is the best reading experience there has ever been: far better than physical books of any form factor. Molly Wood did not do it any justice.</p>
<h3>Why I Disagree With Molly</h3>
<p>Molly's main complaint was that the iPad is too heavy to hold like a book - with two hands holding in front of your face. </p>
<div><div class="image">
	<img title="Holding Up-Right" alt="Holding Up-Right" src="http://lh5.ggpht.com/_1m4jxPGXQAo/TC7-q3QbFFI/AAAAAAAAQUY/CbZR1nb6Dp4/s800/upright.jpg">
</div><br></div>
<p>My answer to this is simple: don't hold it like that! What I have found to work best for me is to set the display at a larger font size, so you don't have to hold the device close to your face in order to read it comfortably. I usually put the iPad on my lap flat:</p>
<div><div class="image">
	<img title="Lap Flat" alt="Lap Flat" src="http://lh3.ggpht.com/_1m4jxPGXQAo/TC7-qfqrL0I/AAAAAAAAQUU/DSYjtdrKMcs/s800/sitting_on_bed.jpg">
</div><br></div>
<p>or slightly till it toward me by crossing my legs:</p>
<div><div class="image">
	<img title="Crossed Legs" alt="Crossed Legs" src="http://lh3.ggpht.com/_1m4jxPGXQAo/TC7-pl9mrbI/AAAAAAAAQUI/8SyYUH6nB3s/s800/crossed_legs.jpg">
</div><br></div>
<p>or propping up my legs:</p>
<div><div class="image">
	<img title="Crouched Legs" alt="Crouched Legs" src="http://lh3.ggpht.com/_1m4jxPGXQAo/TC7-pyBtZHI/AAAAAAAAQUM/E5SDKPpQ8hM/s800/crouched_legs.jpg">
</div><br></div>
<p>This works so nice because one of the nicest features of the iPad is it's cool operational temperature - I would never do this with my Macbook Air. If I feel real lazy, sometimes I lie all the way down on my side and hold it up side ways with one hand.</p>
<div><div class="image">
	<img title="Lying Down" alt="Lying Down" src="http://lh5.ggpht.com/_1m4jxPGXQAo/TC7-qPr-eJI/AAAAAAAAQUQ/_ouB6W7eLWs/s800/lying_down.jpg">
</div><br></div>
<h3>Why it's Better Than a Book</h3>
<p>The reading experience of the iPad is decidedly better than a real book. With a book, well, you usually have to hold it up with two hands, which puts strain on your arms and your palm. If you decide to hold it with one hand, you will contort your fingers in a strange way to try to hold the pages down which will strain your palm even more, to turn a page you'd most likely still require two hands. If you hold the iPad the way I prescribed, you are not really holding it with your hands at all, so no strain, but even better than that, turning a page is a matter of a tap or a flick of a thumb! In fact, when you are sitting comfortably reading with an iPad, the only thing you'll ever have to move is <i>one finger</i>.</p>
<p>Another advantage that the iPad - and eReaders in general - have over books that is rarely mentioned is their accessibility for the visually impaired. In short: old people don't read so good. My mom returned a paperback book because the print was too small for her to read. With an eReader you can set the font size to what's the most comfortable for you.</p>
<h3>It's All eBooks From Here</h3>
<p>That's it. I've decided. I will never buy a book again unless I absolutely have to.</p></content>
        </entry>,<entry>
            <title>Your Tests' Worth</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/06/28/your-tests'-worth">
            <updated>2010-06-28T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/06/28/your-tests'-worth</li>
            <content type="text">
<p>What I don't like about the TDD(Test-Driven Development) movement is how fervently religious its practitioners can sometimes be. I like TDD just fine, but like anything else - it's just a tool. I write tests for some situations, for others, I don't - and I've spoken to many who are like me in this respect. I've also seen TDD done badly - which if persisted - is counter-productive. What I'd like, is to have some way to evaluate how well or poorly you are doing TDD and whether it makes sense at all for the given situation. Put succinctly: when is TDD worth it? If you are already writing tests, this is a small set of criteria that keeps you focused on what should be the desired outcome. If you are thinking about writing tests, these should help you decide whether you want to start getting serious.</p>
<p>The criteria I've come up with are <i>cost</i>, <i>test-time</i>, and <i>regression</i>-<i>fail-rate</i>.</p>
<h2>Cost</h2>
<p>Obviously, the cost of writing the tests is a big factor and must be minimised. How much are you investing into writing and maintaining the tests? How easy is it to add a new test? How often do existing tests have to be modified? To minimise these costs, you often make use of or build frameworks and tools to make testing easier, but there is a trade-off: how much are you investing into building or integrating testing frameworks and tools?</p>
<h2>Test-Time<br></h2>
<p><i>Test-time</i> is the amount of time it takes for your test suite to run. This is a number you want to minimise because a large test-time slows down a developer's development cycle and will be a large on-going tax to the cost of writing/maintaining tests. This is the reason seasoned TDD'ers will prefer unit tests to functional tests, and also the reason they like to use mock frameworks - these are techniques that can reduce test-time.</p>
<h2>Regression-Fail-Rate<br></h2>
<p>The core benefit of TDD is that it gives you the safety to make big changes in your software little time, so how well are you making use of it? <i>Regression-fail-rate</i> is the rate at which your <i>previous</i> testcases fail. <i>Previous</i> meaning all but the testcase you just added and are working on passing. A high number means you are making large changes in your code consistently. If your regression-fail-rate is very low, it means you may not be using the full benefit of TDD. </p>
<h2>Conclusion</h2>
<p>To get the most out of TDD, you need to keep its maintenance cost to a minimum while changing your software at a rapid rate.</p></content>
        </entry>,<entry>
            <title>Python-Style OO in Javascript</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/06/17/python-style-oo-in-javascript">
            <updated>2010-06-17T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/06/17/python-style-oo-in-javascript</li>
            <content type="text">
<p>A while a go I wrote a post on <a href="http://tobyho.com/Prototype_Inheritence_in_Python">Prototype Inheritence in Python</a>. This time, I am somewhat going the opposite direction. That's right: <i>Python-Style OO in Javascript</i>.</p>
<p>Now, I don't think I am the first one who thought of this. In fact, prototype.js does something like this for their method extensions to DOM objects. The main idea is this: if you specify <i>self</i> as the first argument to a method explicitly, you will be able to use <i>self</i> inside of nested closures within the method without having to create a <i>self</i> variable manually, i.e.:</p>
<pre><code>var self = this</code></pre>
<p>or doing something like Function.prototype.bind, or pass the context explicitly around like the <i><a href="http://github.com/airportyh/ecma5array/blob/master/ecma5array.js">Array methods forEach, map, every, etc</a>.</i></p>
<p><i><br></i></p>
<p>This is but a small proof-of-concept. The result is you can write a class like this:</p>
<pre><code>var Man = Class(Object)({
  __init__: function(self, name){
    self.name = name
  },
  greeting: function(self, other){
    setTimeout(function(){
      self.say("Hello, " + other.name + ", my name is " + self.name)
    }, 100)
  },
  say: function(self, msg){
    sys.puts(msg)
  }
})
</code></pre>
<p>Take it for a spin:</p>
<pre><code>var dan = new Man('Dan')
var john = new Man('John')
dan.greeting(john)
john.say('How do?')
</code></pre>
<p>Output:</p>
<pre><code>How do?
Hello, John, my name is Dan
</code></pre>
<p>The implementation of <i>Class</i> looks like this:</p>
<pre><code>function toArray(args){
  var ret = []
  for (var i = 0; i &lt; args.length; i++)
    ret.push(args[i])
  return ret
}

function Class(parent){
  function bind(func, obj){
    var ret = function(){
      var args = toArray(arguments)
      args.splice(0, 0, obj)
      return func.apply(undefined, args)
    }
    return ret
  }
  
  return function(attrs){
    return function(){
      for (var name in attrs){
        var value = attrs[name]
        if (typeof(value) == 'function'){
          this[name] = bind(value, this)
          this[name].name = name
        }else{
          this[name] = value
        }
      }
      this.__init__.apply(this, arguments)
    }
  }
}
</code></pre>
<p>Full source can be found <a href="http://github.com/airportyh/misc/blob/master/python_like_oo/play.js">here</a>. I ran it in <a href="http://nodejs.org/">node</a>. This could be an interesting approach to avoiding "<i>this-</i>hell".</p>
<p><i><span><br></span></i></p></content>
        </entry>,<entry>
            <title>Quick And Dirty JSONP</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/06/06/quick-and-dirty-jsonp">
            <updated>2010-06-06T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/06/06/quick-and-dirty-jsonp</li>
            <content type="text">
<p>I needed <a href="http://en.wikipedia.org/wiki/JSON#JSONP">JSONP</a> for WordyClouds, and since I am trying not to have to use jQuery, I just rolled my own. JSONP is a simple hack, so this is but a short little snippet:</p>
<pre><code>var JSONP = {}
JSONP.get = function(url, callback){
    var scriptTag = document.createElement('script')
    var callbackName = '_' + new Date().getTime()
    JSONP[callbackName] = function(){
        callback.apply(null, arguments)
        delete JSONP[callbackName]
        document.head.removeChild(scriptTag)
    }
    if (url.indexOf('?') != -1)
        url += '&callback=JSONP.' + callbackName
    else
        url += '?callback=JSONP.' + callbackName
    scriptTag.src = url
    document.head.appendChild(scriptTag)
}
</code></pre>
<p>Example usage:</p>
<pre><code>JSONP.get('http://feeds.delicious.com/feeds/json/tags/your_username', function(data){
    // Woohoo! You got data!
})</code></pre></content>
        </entry>,<entry>
            <title>WordCloud - I am Coming After Wordle</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/06/05/wordcloud---i-am-coming-after">
            <updated>2010-06-05T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/06/05/wordcloud---i-am-coming-after</li>
            <content type="text">
<p>After playing around a bit with create word clouds I've decided to write an HTML 5 version of Wordle.net. I am calling it WordyClouds. I've started the beginnings of the <a href="http://github.com/airportyh/WordCloud">code on github</a>.</p>
<p>Also, here's the <a href="javascript:(function(){var%20CommonWords%3D%7B%7D%3BCommonWords.english%3D%22a%20about%20after%20again%20against%20all%20an%20another%20any%20and%20are%20as%20at%20be%20being%20been%20before%20but%20by%20can%20could%20did%20do%20don%27t%20down%20each%20few%20from%20for%20get%20got%20great%20had%20has%20have%20he%20her%20here%20his%20him%20himself%20hers%20how%20i%20if%20i%27m%20in%20into%20is%20it%20it%27s%20just%20like%20made%20me%20more%20most%20my%20no%20not%20of%20off%20on%20once%20one%20only%20or%20other%20our%20out%20over%20own%20said%20she%20should%20so%20some%20such%20than%20that%20the%20their%20them%20then%20there%20these%20they%20this%20those%20through%20to%20too%20under%20until%20up%20very%20was%20wasn%27t%20we%20were%20we%27re%20what%20when%20where%20which%20while%20who%20why%20will%20with%20would%20wouldn%27t%20you%20your%22.split%28%22%20%22%29%3Bvar%20ColorPalates%3D%7B%7D%3BColorPalates.autumn%3D%5B%5B255%2C136%2C64%5D%2C%5B149%2C141%2C79%5D%2C%5B115%2C123%2C85%5D%2C%5B89%2C85%2C64%5D%2C%5B81%2C62%2C56%5D%5D%3Bfunction%20getText%28d%2Cc%29%7Bif%28d.nodeType%3D%3D3%29%7Breturn%20d.nodeValue%7Dif%28c%26%26d.tagName%26%26c.indexOf%28d.tagName.toLowerCase%28%29%29%21%3D-1%29%7Breturn%22%22%7Dvar%20a%3D%22%22%3Bfor%28var%20b%3D0%3Bb%3Cd.childNodes.length%3Bb%2B%2B%29%7Ba%2B%3DgetText%28d.childNodes%5Bb%5D%2Cc%29%7Dreturn%20a%7Dfunction%20keys%28c%29%7Bvar%20a%3D%5B%5D%3Bfor%28var%20b%20in%20c%29%7Ba.push%28b%29%7Dreturn%20a%7Dfunction%20tokenize%28b%2Ca%29%7Breturn%20b.replace%28/%5B%5E%5C%27a-zA-Z%5D/g%2C%22%20%22%29.split%28%22%20%22%29.filter%28function%28c%29%7Breturn%20c%21%3D%22%22%7D%29.map%28function%28c%29%7Breturn%20c.toLowerCase%28%29%7D%29.filter%28function%28c%29%7Breturn%20a.indexOf%28c%29%3D%3D-1%7D%29%7Dfunction%20wordSummary%28d%2Cc%29%7Bvar%20b%3Dtokenize%28d%2Cc%29%3Bvar%20a%3D%7B%7D%3Bb.forEach%28function%28e%29%7Ba%5Be%5D%3D%28a%5Be%5D%7C%7C0%29%2B1%7D%29%3Breturn%20a%7Dfunction%20calculateSizeScale%28b%29%7Bvar%20a%3D0%3Bkeys%28b%29.forEach%28function%28c%29%7Bif%28b%5Bc%5D%3Ea%29%7Ba%3Db%5Bc%5D%7D%7D%29%3Breturn%20150/a%7Dvar%20Layouts%3D%7B%7D%3BLayouts.random%3Dfunction%20RandomLayout%28e%2Cc%2Cb%29%7Bvar%20d%3Dc.getContext%28%222d%22%29%3Bvar%20a%3DcalculateSizeScale%28e%29%3Bkeys%28e%29.forEach%28function%28g%29%7Bvar%20f%3DMath.random%28%29%2Ac.width%3Bvar%20i%3DMath.random%28%29%2Ac.height%3Bvar%20h%3DMath.floor%28Math.random%28%29%2Ab.length%29%3Bconsole.log%28%22color%20index%3A%20%22%2Bh%29%3Bvar%20h%3Db%5Bh%5D%3Bd.fillStyle%3D%22rgba%28%22%2Bh%5B0%5D%2B%22%2C%20%22%2Bh%5B1%5D%2B%22%2C%20%22%2Bh%5B2%5D%2B%22%2C%200.6%29%22%3Bd.font%3D%28e%5Bg%5D%2Aa%29%2B%22px%20Arial%22%3Bd.fillText%28g%2Cf%2Ci%29%7D%29%7D%3BLayouts.packed%3Dfunction%20PackedLayout%28e%2Cc%2Cb%29%7Bvar%20d%3Dc.getContext%28%222d%22%29%3Bvar%20a%3DcalculateSizeScale%28e%29%3Bkeys%28e%29.forEach%28function%28h%29%7Bvar%20g%3DboxHeight%3De%5Bh%5D%2Aa%3Bd.font%3Dg%2B%22px%20Arial%22%3Bvar%20f%3Dd.measureText%28h%29%7D%29%7D%3Bfunction%20main%28%29%7Bvar%20c%3DLayouts.random%3Bvar%20f%3DgetText%28document.body%2C%5B%22script%22%5D%29%3Bvar%20e%3DCommonWords.english%3Bvar%20d%3DwordSummary%28f%2Ce%29%3Bvar%20a%3DColorPalates.autumn%3Bvar%20b%3Ddocument.createElement%28%22canvas%22%29%3Bb.width%3Dwindow.innerWidth%3Bb.height%3Dwindow.innerHeight%3Bdocument.body.innerHTML%3D%22%22%3Bdocument.body.appendChild%28b%29%3Bdocument.body.style.padding%3D%220%22%3Bdocument.body.style.margin%3D%220%22%3Bdocument.body.style.overflow%3D%22hidden%22%3Bc%28d%2Cb%2Ca%29%7D%3Bmain%28%29%3Binit%28String%28window.location%29%29%3B})()">updated bookmarklet</a> <-- drag to toolbar to install. It does a uniformly randomized algorithm rather than Wordle's advanced packing algorithm.</p>
<p>As for that algorithm, I've done some research to how I might implement something close to Wordle's algorithm. I need to be able to make the best use of space - e.g. allowing tiny words to go inside of the holes inside larger letters. To do that I need the actual shape representation of all of the characters for a given font. After looking at the Canvas api, typeface.js and some cursory research into SVG, I've settled - for now - on using Canvas's <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#pixel-manipulation">bitmap feature</a>: I would render each character required for the word cloud on a temporary scratch-pad-canvas, and then read its bitmap representation via the Canvas interface. A prove-of-concept was done and the code is here: <a href="http://github.com/airportyh/WordCloud/blob/master/glyphshapes.js">glyphshapes.js</a>.</p>
<p>Obviously, still big challenges lie ahead. How will the algorithm work? I am not exactly sure.</p>
<p><i>Update: I have written a naive non-overlapping algorithm. Here's the </i><a href="javascript:(function(){var%20CommonWords%3D%7B%7D%3BCommonWords.english%3D%22a%20about%20after%20again%20against%20all%20an%20another%20any%20and%20are%20as%20at%20be%20being%20been%20before%20but%20by%20can%20could%20did%20do%20don%27t%20down%20each%20few%20from%20for%20get%20got%20great%20had%20has%20have%20he%20her%20here%20his%20him%20himself%20hers%20how%20i%20if%20i%27m%20in%20into%20is%20it%20it%27s%20just%20like%20made%20me%20more%20most%20my%20no%20not%20of%20off%20on%20once%20one%20only%20or%20other%20our%20out%20over%20own%20said%20she%20should%20so%20some%20such%20than%20that%20the%20their%20them%20then%20there%20these%20they%20this%20those%20through%20to%20too%20under%20until%20up%20very%20was%20wasn%27t%20we%20were%20we%27re%20what%20when%20where%20which%20while%20who%20why%20will%20with%20would%20wouldn%27t%20you%20your%22.split%28%22%20%22%29%3Bvar%20ColorPalates%3D%7B%7D%3BColorPalates.autumn%3D%5B%5B255%2C136%2C64%5D%2C%5B149%2C141%2C79%5D%2C%5B115%2C123%2C85%5D%2C%5B89%2C85%2C64%5D%2C%5B81%2C62%2C56%5D%5D%3Bfunction%20getText%28d%2Cc%29%7Bif%28d.nodeType%3D%3D3%29%7Breturn%20d.nodeValue%7Dif%28c%26%26d.tagName%26%26c.indexOf%28d.tagName.toLowerCase%28%29%29%21%3D-1%29%7Breturn%22%22%7Dvar%20a%3D%22%22%3Bfor%28var%20b%3D0%3Bb%3Cd.childNodes.length%3Bb%2B%2B%29%7Ba%2B%3DgetText%28d.childNodes%5Bb%5D%2Cc%29%7Dreturn%20a%7Dfunction%20keys%28c%29%7Bvar%20a%3D%5B%5D%3Bfor%28var%20b%20in%20c%29%7Ba.push%28b%29%7Dreturn%20a%7Dfunction%20tokenize%28b%2Ca%29%7Breturn%20b.replace%28/%5B%5E%5C%27a-zA-Z%5D/g%2C%22%20%22%29.split%28%22%20%22%29.filter%28function%28c%29%7Breturn%20c%21%3D%22%22%7D%29.map%28function%28c%29%7Breturn%20c.toLowerCase%28%29%7D%29.filter%28function%28c%29%7Breturn%20a.indexOf%28c%29%3D%3D-1%7D%29%7Dfunction%20wordSummary%28d%2Cc%29%7Bvar%20b%3Dtokenize%28d%2Cc%29%3Bvar%20a%3D%7B%7D%3Bb.forEach%28function%28e%29%7Ba%5Be%5D%3D%28a%5Be%5D%7C%7C0%29%2B1%7D%29%3Breturn%20a%7Dfunction%20calculateSizeScale%28b%29%7Bvar%20a%3D0%3Bkeys%28b%29.forEach%28function%28c%29%7Bif%28b%5Bc%5D%3Ea%29%7Ba%3Db%5Bc%5D%7D%7D%29%3Breturn%20110/a%7Dfunction%20boxesOverlap%28a%2Ci%2Cb%2Ch%2Cf%2Ce%2Cg%2Cd%29%7Bvar%20c%3D10%3Bif%28a%2Bb%2Bc%3Cf%29%7Breturn%20false%7Dif%28f%2Bg%2Bc%3Ca%29%7Breturn%20false%7Dif%28i%2Bh%2A0.5%2Bc%3Ce-d%29%7Breturn%20false%7Dif%28e%2Bd%2A0.5%2Bc%3Ci-h%29%7Breturn%20false%7Dreturn%20true%7Dvar%20Layouts%3D%7B%7D%3BLayouts.random%3Dfunction%20RandomLayout%28f%2Cc%2Cb%29%7Bvar%20e%3D100%3Bvar%20d%3Dc.getContext%28%222d%22%29%3Bvar%20a%3DcalculateSizeScale%28f%29%3Bkeys%28f%29.forEach%28function%28h%29%7Bvar%20g%3De%2BMath.random%28%29%2A%28c.width-3%2Ae%29%3Bvar%20j%3De%2BMath.random%28%29%2A%28c.height-2%2Ae%29%3Bvar%20i%3DMath.floor%28Math.random%28%29%2Ab.length%29%3Bvar%20i%3Db%5Bi%5D%3Bd.fillStyle%3D%22rgba%28%22%2Bi.join%28%22%2C%22%29%2B%22%2C%200.6%29%22%3Bd.font%3D%28f%5Bh%5D%2Aa%29%2B%22px%20Arial%22%3Bd.fillText%28h%2Cg%2Cj%29%7D%29%7D%3BLayouts.randomAvoid%3Dfunction%20RandomAvoidLayout%28c%2Ce%2Ca%2Cb%29%7Bfunction%20i%28m%2Cn%2Cr%29%7Bvar%20o%3D0%3Bvar%20p%3D0%3Bfor%28var%20k%20in%20m%29%7Bvar%20s%3Dm%5Bk%5D%3Bvar%20q%3D%28s%2A1.2%2A%28k.length%2As%2A0.8%29%29%3Bo%2B%3Dq%3Bp%2B%2B%7Dvar%20l%3D%28n-3%2Aj%29%2A%28r-2%2Aj%29%3Breturn%20Math.sqrt%28l/o%29%7Dvar%20j%3D100%3Bvar%20d%3De.getContext%28%222d%22%29%3Bvar%20f%3Di%28c%2Ce.width%2Ce.height%29%3Bconsole.log%28%22sizeScale%3A%20%22%2Bf%29%3Bvar%20g%3D%5B%5D%3Bvar%20h%3Dkeys%28c%29.sort%28function%28l%2Ck%29%7Breturn%20c%5Bk%5D-c%5Bl%5D%7D%29%3Bh.forEach%28function%28k%29%7Bvar%20v%3Dc%5Bk%5D%2Af%3Bd.font%3Dv%2B%22px%20%22%2Bb%3Bvar%20s%3Dd.measureText%28k%29.width%3Bvar%20w%2Cu%3Bvar%20m%3D10000%2Cz%3Dtrue%3Bwhile%28m%3E0%26%26z%29%7Bw%3Dj%2BMath.random%28%29%2A%28e.width-3%2Aj%29%3Bu%3Dj%2BMath.random%28%29%2A%28e.height-2%2Aj%29%3Bif%28false%29%7Bz%3Dg.reduce%28function%28y%2Cx%29%7Breturn%20y%7C%7CboxesOverlap%28x%5B0%5D%2Cx%5B1%5D%2Cx%5B2%5D%2Cx%5B3%5D%2Cw%2Cu%2Cs%2Cv%29%7D%2Cfalse%29%7Delse%7Bvar%20o%3D5%3Bvar%20l%3Dd.getImageData%28w-o%2Cu-v-o%2Cs%2B2%2Ao%2Cv%2B2%2Ao%29%3Bvar%20n%3Dl.data%3Bvar%20p%3Dfalse%3Bfor%28var%20q%3D0%3Bq%3Cn.length%3Bq%2B%2B%29%7Bif%28n%5Bq%5D%3E0%29%7Bp%3Dtrue%3Bbreak%7D%7Dz%3Dp%7Dm--%7Dif%28m%3D%3D0%29%7Bconsole.log%28%22Failed%20to%20avoid%20overlap%20for%20%5B%22%2Bk%2B%22%5D%22%29%7Dvar%20t%3DMath.floor%28Math.random%28%29%2Aa.length%29%3Bvar%20t%3Da%5Bt%5D%3Bd.fillStyle%3D%22rgba%28%22%2Bt.join%28%22%2C%22%29%2B%22%2C%201%29%22%3Bd.font%3Dv%2B%22px%20%22%2Bb%3Bd.fillText%28k%2Cw%2Cu%29%3Bvar%20r%3D%5Bw%2Cu%2Cs%2Cv%5D%3Bg.push%28r%29%7D%29%7D%3Bfunction%20main%28%29%7Bvar%20d%3DLayouts.randomAvoid%3Bvar%20g%3DgetText%28document.body%2C%5B%22script%22%5D%29%3Bvar%20f%3DCommonWords.english%3Bvar%20e%3DwordSummary%28g%2Cf%29%3Bvar%20a%3DColorPalates.autumn%3Bvar%20c%3DgetComputedStyle%28document.body%29%5B%22font-family%22%5D%3Bvar%20b%3Ddocument.createElement%28%22canvas%22%29%3Bb.width%3Dwindow.innerWidth%3Bb.height%3Dwindow.innerHeight%3Bdocument.body.innerHTML%3D%22%22%3Bdocument.body.appendChild%28b%29%3Bdocument.body.style.padding%3D%220%22%3Bdocument.body.style.margin%3D%220%22%3Bdocument.body.style.overflow%3D%22hidden%22%3Bd%28e%2Cb%2Ca%2Cc%29%7D%3Bmain%28%29%3Binit%28String%28window.location%29%29%3B})()"><i>new bookmarklet</i></a><i> <-- drag to toolbar to install.</i></p>
<p><i><br></i></p>
<p><i>Update 2: Added vertical word placement: <em><a href="javascript:(function(){var%20CommonWords%3D%7B%7D%3BCommonWords.english%3D%22a%20about%20after%20again%20against%20all%20an%20another%20any%20and%20are%20as%20at%20be%20being%20been%20before%20but%20by%20can%20could%20did%20do%20don%27t%20down%20each%20few%20from%20for%20get%20got%20great%20had%20has%20have%20he%20her%20here%20his%20him%20himself%20hers%20how%20i%20if%20i%27m%20in%20into%20is%20it%20it%27s%20just%20like%20made%20me%20more%20most%20my%20no%20not%20of%20off%20on%20once%20one%20only%20or%20other%20our%20out%20over%20own%20said%20she%20should%20so%20some%20such%20than%20that%20the%20their%20them%20then%20there%20these%20they%20this%20those%20through%20to%20too%20under%20until%20up%20very%20was%20wasn%27t%20we%20were%20we%27re%20what%20when%20where%20which%20while%20who%20why%20will%20with%20would%20wouldn%27t%20you%20your%22.split%28%22%20%22%29%3Bvar%20ColorPalates%3D%7B%7D%3BColorPalates.autumn%3D%5B%5B255%2C136%2C64%5D%2C%5B149%2C141%2C79%5D%2C%5B115%2C123%2C85%5D%2C%5B89%2C85%2C64%5D%2C%5B81%2C62%2C56%5D%5D%3Bfunction%20getText%28d%2Cc%29%7Bif%28d.nodeType%3D%3D3%29%7Breturn%20d.nodeValue%7Dif%28c%26%26d.tagName%26%26c.indexOf%28d.tagName.toLowerCase%28%29%29%21%3D-1%29%7Breturn%22%22%7Dvar%20a%3D%22%22%3Bfor%28var%20b%3D0%3Bb%3Cd.childNodes.length%3Bb%2B%2B%29%7Ba%2B%3DgetText%28d.childNodes%5Bb%5D%2Cc%29%7Dreturn%20a%7Dfunction%20keys%28c%29%7Bvar%20a%3D%5B%5D%3Bfor%28var%20b%20in%20c%29%7Ba.push%28b%29%7Dreturn%20a%7Dfunction%20tokenize%28b%2Ca%29%7Breturn%20b.replace%28/%5B%5E%5C%27a-zA-Z%5D/g%2C%22%20%22%29.split%28%22%20%22%29.filter%28function%28c%29%7Breturn%20c%21%3D%22%22%7D%29.map%28function%28c%29%7Breturn%20c.toLowerCase%28%29%7D%29.filter%28function%28c%29%7Breturn%20a.indexOf%28c%29%3D%3D-1%7D%29%7Dfunction%20wordSummary%28d%2Cc%29%7Bvar%20b%3Dtokenize%28d%2Cc%29%3Bvar%20a%3D%7B%7D%3Bb.forEach%28function%28e%29%7Ba%5Be%5D%3D%28a%5Be%5D%7C%7C0%29%2B1%7D%29%3Breturn%20a%7Dfunction%20calculateSizeScale%28b%29%7Bvar%20a%3D0%3Bkeys%28b%29.forEach%28function%28c%29%7Bif%28b%5Bc%5D%3Ea%29%7Ba%3Db%5Bc%5D%7D%7D%29%3Breturn%20110/a%7Dfunction%20boxesOverlap%28a%2Ci%2Cb%2Ch%2Cf%2Ce%2Cg%2Cd%29%7Bvar%20c%3D10%3Bif%28a%2Bb%2Bc%3Cf%29%7Breturn%20false%7Dif%28f%2Bg%2Bc%3Ca%29%7Breturn%20false%7Dif%28i%2Bh%2A0.5%2Bc%3Ce-d%29%7Breturn%20false%7Dif%28e%2Bd%2A0.5%2Bc%3Ci-h%29%7Breturn%20false%7Dreturn%20true%7Dfunction%20stripHTML%28a%29%7Bvar%20d%3D%5B%5D%3Bvar%20e%3Dfalse%3Bfor%28var%20b%3D0%3Bb%3Ca.length%3Bb%2B%2B%29%7Bvar%20c%3Da.charAt%28b%29%3Bif%28c%3D%3D%22%3C%22%29%7Be%3Dtrue%7Dif%28c%3D%3D%22%3E%22%29%7Be%3Dfalse%7Dif%28%21e%29%7Bd.push%28c%29%7D%7Dreturn%20d.join%28%22%22%29%7Dvar%20Layouts%3D%7B%7D%3BLayouts.random%3Dfunction%20RandomLayout%28f%2Cc%2Cb%29%7Bvar%20e%3D100%3Bvar%20d%3Dc.getContext%28%222d%22%29%3Bvar%20a%3DcalculateSizeScale%28f%29%3Bkeys%28f%29.forEach%28function%28h%29%7Bvar%20g%3De%2BMath.random%28%29%2A%28c.width-3%2Ae%29%3Bvar%20j%3De%2BMath.random%28%29%2A%28c.height-2%2Ae%29%3Bvar%20i%3DMath.floor%28Math.random%28%29%2Ab.length%29%3Bvar%20i%3Db%5Bi%5D%3Bd.fillStyle%3D%22rgba%28%22%2Bi.join%28%22%2C%22%29%2B%22%2C%200.6%29%22%3Bd.font%3D%28f%5Bh%5D%2Aa%29%2B%22px%20Arial%22%3Bd.fillText%28h%2Cg%2Cj%29%7D%29%7D%3BLayouts.randomAvoid%3Dfunction%20RandomAvoidLayout%28c%2Ce%2Ca%2Cb%29%7Bfunction%20h%28l%2Cm%2Cq%29%7Bvar%20n%3D0%3Bvar%20o%3D0%3Bfor%28var%20j%20in%20l%29%7Bvar%20r%3Dl%5Bj%5D%3Bvar%20p%3D%28r%2A1.5%2A%28j.length%2Ar%2A0.8%29%29%3Bn%2B%3Dp%3Bo%2B%2B%7Dvar%20k%3D%28m-2%2Ai%29%2A%28q-2%2Ai%29%3Breturn%20Math.sqrt%28k/n%29%7Dvar%20i%3D20%3Bvar%20d%3De.getContext%28%222d%22%29%3Bvar%20f%3Dh%28c%2Ce.width%2Ce.height%29%3Bconsole.log%28%22sizeScale%3A%20%22%2Bf%29%3Bvar%20g%3Dkeys%28c%29.sort%28function%28k%2Cj%29%7Breturn%20c%5Bj%5D-c%5Bk%5D%7D%29%3Bg.forEach%28function%28j%29%7Bvar%20u%3Dc%5Bj%5D%2Af%3Bif%28u%3C5%29%7Breturn%7Dd.font%3Du%2B%22px%20%22%2Bb%3Bvar%20r%3Dd.measureText%28j%29.width%3Bvar%20o%3DMath.random%28%29%3E0.5%3Bvar%20v%2Ct%3Bvar%20l%3D10000%2Cw%3Dtrue%3Bwhile%28l%3E0%26%26w%29%7Bvar%20n%3D5%3Bvar%20k%3Bif%28o%29%7Bv%3Di%2Bu%2A1.5%2BMath.random%28%29%2A%28e.width-u%2A1.5-2%2Ai%29%3Bt%3Di%2Br%2BMath.random%28%29%2A%28e.height-r-2%2Ai%29%3Bk%3Dd.getImageData%28v-u%2A1.5-n%2Ct-r-n%2Cu%2A1.5%2B2%2An%2Cr%2B2%2An%29%7Delse%7Bv%3Di%2BMath.random%28%29%2A%28e.width-r-2%2Ai%29%3Bt%3Di%2Bu%2BMath.random%28%29%2A%28e.height-u%2A1.5-2%2Ai%29%3Bk%3Dd.getImageData%28v-n%2Ct-u-n%2Cr%2B2%2An%2Cu%2A1.5%2B2%2An%29%7Dvar%20m%3Dk.data%3Bvar%20p%3Dfalse%3Bfor%28var%20q%3D3%3Bq%3Cm.length%3Bq%2B%3D4%29%7Bif%28m%5Bq%5D%3E0%29%7Bp%3Dtrue%3Bbreak%7D%7Dw%3Dp%3Bl--%7Dif%28l%3D%3D0%29%7Bconsole.log%28%22Failed%20to%20avoid%20overlap%20for%20%5B%22%2Bj%2B%22%5D%22%29%7Dvar%20s%3DMath.floor%28Math.random%28%29%2Aa.length%29%3Bvar%20s%3Da%5Bs%5D%3Bd.fillStyle%3D%22rgba%28%22%2Bs.join%28%22%2C%22%29%2B%22%2C%201%29%22%3Bd.font%3Du%2B%22px%20%22%2Bb%3Bif%28o%29%7Bd.save%28%29%3Bd.translate%28v%2Ct%29%3Bd.rotate%28-Math.PI/2%29%3Bd.fillText%28j%2C0%2C0%29%3Bd.restore%28%29%7Delse%7Bd.fillText%28j%2Cv%2Ct%29%7D%7D%29%7D%3BWordyClouds%3D%7B%7D%3BWordyClouds.loadFromText%3Dfunction%28c%29%7Bvar%20b%3DCommonWords.english%3Bvar%20a%3DwordSummary%28c%2Cb%29%3Bthis.loadFromWordFreq%28a%29%7D%3BWordyClouds.loadFromWordFreq%3Dfunction%28e%29%7Bvar%20d%3DLayouts.randomAvoid%3Bvar%20a%3DColorPalates.autumn%3Bvar%20c%3DgetComputedStyle%28document.body%29%5B%22font-family%22%5D%3Bvar%20b%3Ddocument.createElement%28%22canvas%22%29%3Bb.width%3Dwindow.innerWidth%3Bb.height%3Dwindow.innerHeight%3Bdocument.body.innerHTML%3D%22%22%3Bdocument.body.appendChild%28b%29%3Bdocument.body.style.padding%3D%220%22%3Bdocument.body.style.margin%3D%220%22%3Bdocument.body.style.overflow%3D%22hidden%22%3Bd%28e%2Cb%2Ca%2Cc%29%7D%3BWordyClouds.runBookmarklet%3Dfunction%28%29%7Bvar%20a%3DgetText%28document.body%2C%5B%22script%22%5D%29%3Bthis.loadFromText%28a%29%7D%3BWordyClouds.loadFromDelicious%3Dfunction%28a%29%7BJSONP.get%28%22http%3A//feeds.delicious.com/feeds/json/tags/%22%2Ba%2Cfunction%28b%29%7BWordyClouds.loadFromWordFreq%28b%29%7D%29%7D%3BWordyClouds.loadFromFeed%3Dfunction%28a%2Cc%29%7Bc%3Dc%7C%7C10%3Bvar%20b%3Dnew%20Date%28%29.getTime%28%29%3BJSONP.get%28%22http%3A//www.google.com/uds/GlookupFeed%3Fcontext%3D0%26hl%3Den%26q%3D%22%2BencodeURI%28a%29%2B%22%26v%3D1.0%26nocache%3D%22%2Bb%2Cfunction%28d%2Ce%29%7Bb%3Dnew%20Date%28%29.getTime%28%29%3BJSONP.get%28%22http%3A//www.google.com/uds/Gfeeds%3Fcontext%3D1%26num%3D%22%2Bc%2B%22%26hl%3Den%26output%3Djson%26q%3D%22%2BencodeURI%28e.url%29%2B%22%26v%3D1.0%26nocache%3D%22%2Bb%2Cfunction%28g%2Ch%29%7Bvar%20f%3Dh.feed.entries%3Bvar%20i%3D%22%22%3Bf.forEach%28function%28j%29%7Bi%2B%3Dj.title%2B%22%5Cn%22%3Bi%2B%3DstripHTML%28j.content%29%2B%22%5Cn%22%7D%29%3BWordyClouds.loadFromText%28i%29%7D%29%7D%29%7D%3BWordyClouds.runBookmarklet%28%29%3Binit%28String%28window.location%29%29%3B})()">WordCloud</a></em> <-- drag to toolbar to install.</i></p>
<p><i><br></i></p></content>
        </entry>,<entry>
            <title>Word Cloud Bookmarklet</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/06/04/word-cloud-bookmarklet">
            <updated>2010-06-04T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/06/04/word-cloud-bookmarklet</li>
            <content type="text">
<p>Inspired by <a href="http://wordle.net">Wordle.net</a>, I wrote a bookmarklet that generates a word cloud based on the text of the page you are on. Here it is: <a href="javascript:function%20getText(elm,%20excludeTags){if%20(elm.nodeType%20==%203)%20return%20elm.nodeValue;if%20(excludeTags%20&&%20elm.tagName%20&&%20excludeTags.indexOf(elm.tagName.toLowerCase())%20!=%20-1)%20return%20%27%27;var%20ret%20=%20%27%27;for%20(var%20i%20=%200;%20i%20<%20elm.childNodes.length;%20i++){ret%20+=%20getText(elm.childNodes[i],%20excludeTags);}return%20ret;}function%20keys(obj){var%20ret%20=%20[];for%20(var%20key%20in%20obj)%20ret.push(key);return%20ret;}var%20text%20=%20getText(document.body,%20[%27script%27]);var%20commonWords%20=%20[%27a%27,%20%27the%27,%20%27and%27,%20%27of%27,%20%27is%27,%20%27in%27,%20%27this%27,%20%27it%27,%20%27to%27];var%20words%20=%20text.replace(/[^a-zA-Z]/g,%20%27%20%27).split(%27%20%27).filter(function(p){return%20p%20!=%20%27%27});words%20=%20words.filter(function(word){return%20commonWords.indexOf(word)%20==%20-1;});var%20freq%20=%20{};words.forEach(function(word){freq[word]%20=%20(freq[word]%20||%200)%20+%201;});var%20markup%20=%20keys(freq).map(function(word){return%20%27<span%20style=%22font-size:%20%27%20+%20(freq[word]%20/%204)%20+%20%27em%22>%27%20+%20word%20+%20%27</span>%27;}).join(%27%20%27);document.body.innerHTML%20=%20markup;">WordCloud</a> <- (drag to your toolbar to install). The uncompressed source is as follows:</p>
<pre><code>function getText(elm, excludeTags){
	if (elm.nodeType == 3) return elm.nodeValue;
	if (excludeTags && elm.tagName && excludeTags.indexOf(elm.tagName.toLowerCase()) != -1) return '';
	var ret = '';
	for (var i = 0; i &lt; elm.childNodes.length; i++){
		ret += getText(elm.childNodes[i], excludeTags);
	}
	return ret;
}

function keys(obj){
    var ret = [];
    for (var key in obj) ret.push(key);
    return ret;
}

var text = getText(document.body, ['script']);
var commonWords = ['a', 'the', 'and', 'of', 'is', 'in', 'this', 'it', 'to'];
var words = text.replace(/[^a-zA-Z]/g, ' ').split(' ').filter(function(p){return p != ''});
words = words.filter(function(word){
	return commonWords.indexOf(word) == -1;
});
var freq = {};
words.forEach(function(word){ 
    freq[word] = (freq[word] || 0) + 1;
});

var markup = keys(freq).map(function(word){
	return '&lt;span style="font-size: ' + (freq[word] / 4) + 'em"&gt;' + word + '&lt;/span&gt;';
}).join(' ');
document.body.innerHTML = markup;
</code></pre>

<p>Enjoy! As a next step, I plan to use Canvas and implement more advanced layouts like the ones on Wordle.</p></content>
        </entry>,<entry>
            <title>Continuation-Passing Style: Don't Overdo it</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/06/02/continuation-passing-style:">
            <updated>2010-06-02T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/06/02/continuation-passing-style:</li>
            <content type="text">
<p><a href="http://en.wikipedia.org/wiki/Continuation-passing_style">Continuation-Passing Style</a>(CPS) is a style of programming that's useful for a number of use-cases, but you shouldn't get carried away and start writing all your programs in this style. Here, I am going to list 3 disadvantages of programming in this style.</p>
<h3>Code Size<br></h3>
<p>Unless your language has specific language support for writing in Continuations(e.g. Haskell), your code will have more bloat.</p>
<p>Example, here's a sqrt function in <i>direct</i> <i>style</i>:</p>
<pre><code>function sqrt(a, b){
    return a * 2 + b * 2;
}</code></pre>
<p>Here it is in CPS:</p>
<div>
	<pre><code>function sqrt(a, b, callback){</code></pre>
	<pre><code>    multiply(a, 2, function(a2){</code></pre>
	<pre><code>        multiply(b, 2, function(b2){</code></pre>
	<pre><code>            add(a2, b2, callback);</code></pre>
	<pre><code>        });</code></pre>
	<pre><code>    });</code></pre>
	<pre><code>}</code></pre>
</div>
<h3>Readability<br></h3>
<p>The direct style is generally easier to read/understand. Take the previous sqrt example, the CPS version introduces 2 extra variable names: a2 and b2, which increases the mental load of somebody trying to read the program.</p>
<h3>Code is Coupled to Ordering of Operations</h3>
<p>With CPS-Style code, the order of your operation affects the structure of your code. Again, taking the sqrt example. This time, let's rewrite the direct-style version to:</p>
<pre><code>function sqrt(a, b){    var a2 = a * 2;    var b2 = b * 2;    return a2 * b2;}</code></pre>
<p>Here, the statements <span>var a2 = a * 2;</span> and <span>var b2 = b * 2;</span> are completely separate and independent. I could swap their order without changing the code's behavior. In the CPS-Style, the whole thing is one big statement, and therefore, to reorder the sequence of operations, it is necessary to mentally unwrap the layers of closure functions and pull out just the right ones and then put them back together. In this simple example, it wasn't actually that hard, but imagine if the code was more like this:<br></p>
<pre><code>function sqrt(a, b, callback){    multiply(a, 2, function(a2){        /* code */        multiply(b, 2, function(b2){            /* code */        });        /* more code here */    });}</code></pre>
<p>Basically, code in this style is much harder to decouple into smaller independent parts. Libraries like <a href="http://github.com/creationix/do">Do</a> and <a href="http://github.com/kriszyp/node-promise">node-promise</a> exist to compensate for this problem, but they IMO are still a far cry from the plain ol' direct style.</p>
<p>The point here is that there are definite disadvantages to writing code in the Continuation-Passing Style. I am not saying that you should not use CPS, but that you should have good reasons for using it - good enough to offset its disadvantages.</p></content>
        </entry>,<entry>
            <title>Convert a Function to Continuation-Passing Style</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/06/01/convert-a-function-to">
            <updated>2010-06-01T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/06/01/convert-a-function-to</li>
            <content type="text">
<p>Here's a snippet that converts a normal Javascript function to its <a href="http://en.wikipedia.org/wiki/Continuation-passing_style">Continuation-Passing style</a> equivalent:</p>
<pre><code>function asCPS(f){
  var _f = function(){
    var callback = arguments[arguments.length - 1];
    var args = Array
      .prototype.slice
      .call(arguments, 0, arguments.length - 1)
    var retVal = f.apply(this, args)
    if (callback) callback(retVal)
  }
  _f.name = f.name
  return _f
}
</code></pre>
<p>So you have a normal function, say add():<br></p>
<pre><code>function add(one, other){
  return one + other;
}
</code></pre>
<p>Convert it:</p>
<pre><code>add = asCPS(add)
</code></pre>
<p>Now you can call it and get the result inside a callback, like so:</p>
<pre><code>add(1, 2, function(sum){
  console.log('sum: ' + sum)
})</code></pre></content>
        </entry>,<entry>
            <title>One-Liner WebServer with Python</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/04/26/one-liner-webserver-with">
            <updated>2010-04-26T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/04/26/one-liner-webserver-with</li>
            <content type="text">
<p>Turns out, even better than my <a href="HTTP Server in 5 Lines With Webrick">HTTP Server in 5 Lines With Webrick</a> is this one-liner:</p>
<pre><code>python -m SimpleHTTPServer
</code></pre>
<p>This will serve on port 8000 by default, but you can add the port number as the last argument to override. Nice! Credits go to <a href="http://www.catonmat.net/blog/top-ten-one-liners-from-commandlinefu-explained">this article</a>.</p></content>
        </entry>,<entry>
            <title>Shape-Shifting in Javascript</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/04/26/shape-shifting-in-javascript">
            <updated>2010-04-26T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/04/26/shape-shifting-in-javascript</li>
            <content type="text">
<p><a href="http://www.somethingnimble.com/bliki/mixology">Mixology</a> is a Ruby library for what I call <i>shape-shifting</i> objects. </p>
<div><b>shape</b><span><b>·</b><span><b>shifting</b></span></span></div>
<p><i>n. </i>the act of changing the shape of an object's inheritance hierarchy during runtime.</p>
<div>It turns out that shape-shifting is incredibly easy to do in Javascript.<pre><code>ClosedDoor = {
  isClosed: function(){
    return true
  },
  isOpen: function(){
    return false
  }
}

OpenDoor = {
  isClosed: function(){
    return false
  },
  isOpen: function(){
    return true
  }
}

function Door(){
  this.__proto__ = ClosedDoor
  this.open = function(){
    this.__proto__ = OpenDoor
  }
  this.close = function(){
    this.__proto__ = ClosedDoor
  }
}
</code></pre><div>Let's give it a go:</div><pre><code>&gt; door = new Door()
Object
&gt; door.isClosed()
true
&gt; door.isOpen()
false
&gt; door.open()
&gt; door.isOpen()
true
&gt; door.isClosed()
false
</code></pre><div>In Javascript, "inheritance" is nothing but a link from the child to the parent: the <i>__proto__</i> property. Once you have this link established, the child inherits all of the properties of the parent. You can change the <i>__proto__</i> property at runtime. What the example did is simply to change the parent of the door instance to a ClosedDoor or an OpenDoor whenever the state of the door changes. This make for a nice way to implement states. +2 points for prototype inheritance!</div></div>
<p><i>Update: caution, this code - in particular the __proto__ attribute, will not work in IE and is also deprecated in Mozilla.</i></p></content>
        </entry>,<entry>
            <title>Dark Desktop and Productivity Tools for Mac</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/04/09/dark-desktop-and-productivity">
            <updated>2010-04-09T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/04/09/dark-desktop-and-productivity</li>
            <content type="text">
<p>I "Went Mac" exactly one year ago. For the most part, I am a happy camper. Mac is not without its problems, but it clearly has smoother edges than Windows. This post will be reminiscent of my <a href="http://tobyho.com/Cleaner_Desktop_and_moving_to_Opera">Desktop Cleaning</a> post, only now "I am a Mac".</p>
<p>Today I decided that I was tired of spending time resizing windows on my Mac. It wasn't great in Windows either, but at least it was easier in that you could drag any of three sides of the window. On Mac, the only way to resize a window is to drag its lower right corner.  What I needed was a tiling window manager, something like <a href="http://xmonad.org/">xmonad</a>. Unfortunately, xmonad is only for Linux. <i>Yes, you could get it to run on Mac, but it'll only work for X11-based applications - which are the minority of what I use on a day to day basis.</i> I did some research and found an app called <a href="http://www.irradiatedsoftware.com/sizeup/">SizeUp</a>. SizeUp allows you to tile windows using keyboard shortcuts. For example, you can make the current window occupy the left; right; top or bottom halves of the screen. You can also make it occupy each of the four quarters of the screen. You can also center a window, full screen a window, etc. If you use multiple screens, there are also shortcuts to move a window between the screens. All the shortcuts are configureable, and you will want to play around with configuring them to know what works for you, because honestly, the defaults are "a bit shit".</p>
<div><br><div><div class="image">
	<img title="SizeUp Screenshot" alt="SizeUp Screenshot" src="http://lh6.ggpht.com/_1m4jxPGXQAo/S7_ftmec5oI/AAAAAAAAPFM/QNZasGcQY4E/s800/Screen%20shot%202010-04-09%20at%2010.09.48%20PM.jpg">
</div><br></div></div>
<p>Another problem I have been having with the Mac experience is task switching. In Mac, the task switcher can switch between different programs, but not between the different windows within programs - unlike in Windows. You can switch windows within the <i>active</i> program using Cmd-`, but it's not as nice an experience as there isn't any indication of how many windows there are or what their names are. For this problem, <a href="http://manytricks.com/witch/">Witch</a> fits the bill. Witch is basically an advanced task switcher for Mac (for Windows there is the <a href="http://www.microsoft.com/windowsxp/Downloads/powertoys/Xppowertoys.mspx">Power Toys Task Switcher</a>). It <i>does </i>let you cycle through all the windows of all the active applications. It also shows you the names of all the windows.</p>
<div><div class="image">
	<img title="Witch Screenshot" alt="Witch Screenshot" src="http://lh4.ggpht.com/_1m4jxPGXQAo/S7_mGz252_I/AAAAAAAAPFQ/BjNelCJiKHo/s800/Screen%20shot%202010-04-09%20at%2010.44.14%20PM.jpg">
</div><br></div>
<p>Well, those are two Mac productivity apps that I think are worth the money. But last and not least here's a tip for making your desktop dark. If you go into System Preference -> Desktop & Screen Saver, you'll see Solid Colors as an folder under what you can select to be your wallpaper. Unfortunately for me, <i>black</i> is not an option. To make a dark wallpaper - well, it's obvious really - I just created a one-pixel-sized black image and used it as the wallpaper. There you go. Here's a screenshot of my dark desktop with Witch opened on top of it:</p>
<div>
	<div class="image">
		<img title="Dark Desktop Screenshot" alt="Dark Desktop Screenshot" src="http://lh4.ggpht.com/_1m4jxPGXQAo/S7_ohKFI2hI/AAAAAAAAPFs/AsxjXlTS1cY/s800/Screen%20shot%202010-04-09%20at%2010.54.39%20PM.jpg">
	</div>
</div></content>
        </entry>,<entry>
            <title>Multiple Class Selectors Don't Work in IE6</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/03/31/multiple-class-selectors-don't">
            <updated>2010-03-31T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/03/31/multiple-class-selectors-don't</li>
            <content type="text">
<p>This is well-known knowledge, but I since it was not to me, I'll still catalogue it here. When you use a CSS selector with multiple class names on the same element, i.e.:</p>
<pre><code>.class1.class2{
   ...
}</code></pre>
<p>IE 6 will interpret this as:</p>
<pre><code>.class2{
  ...
}</code></pre>
<p>That's right, the first class will get ignored.</p></content>
        </entry>,<entry>
            <title>OnReady In A Smaller Package</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/03/21/onready-in-a-smaller-package">
            <updated>2010-03-21T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/03/21/onready-in-a-smaller-package</li>
            <content type="text">
<p>I am sure most Javascript hackers are accustomed to the onready event. It is a pseudo-event that indicates the DOM of the pages has been loaded. <i>document.onload</i> is not as good as it won't fire until all the linked resources such as images are loaded as well, and if you have Javascript you want to run that can modify the appearance of the page, you would get an unwanted flicker at the beginning of the page. jQuery provides hooks to onready via <a href="http://api.jquery.com/ready/">$.ready()</a>, and for prototype.js users, <a href="http://www.danwebb.net/2006/9/3/low-pro-unobtrusive-scripting-for-prototype">lowpro.js</a> provides this via Element.onReady(). But, for hackers who don't want to use a large framework, I've created <a href="http://github.com/airportyh/onready">onready</a>: the barebone implementation of the onready event. This might be useful if you want to write your own framework, or just need to write something that is very small or that has very few dependencies.</p>
<p><span><br></span></p>
<div><span>Usage:</span><div><span><ol>
	<li>
		<p>Include file:</p>
		<pre><code>&lt;script type="text/javascript" src="onready.js"&gt;&lt;/script&gt;</code></pre>
	</li>
	<li>
		<p>Use:</p>
		<pre><code>OnReady(function(){ alert('DOM is now ready!'); })</code></pre>
	</li>
</ol></span></div></div></content>
        </entry>,<entry>
            <title>SuperRefresh Bookmarklet</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/03/18/superrefresh-bookmarklet">
            <updated>2010-03-18T04:00:00.000Z</updated>
            <id>http://tobyho.com/2010/03/18/superrefresh-bookmarklet</li>
            <content type="text">
<p>SuperRefresh is a bookmarklet I wrote. Here is the README:</p>
<div>
	<div>SuperRefresh Bookmarklet</div>
	<div>========================</div>
	<div>A bookmarklet that automatically refreshes your page as you are designing it.</div>
	<div>Usage: </div>
	<div>1. Navigate to the page that you are developing in your browser - this can be either a local file or a served file.</div>
	<div>2. Click on the bookmarklet - your page will be replaced with the </div>
	<div>SuperRefresh page, which will contain an iframe pointed back at your page.</div>
	<div>3. Edit your page and save. The changes will almost immediately update within the iframe.</div>
	<div><a href="javascript:(function(){function%20sha1Hash%28k%29%7Bvar%20o%3D%5B1518500249%2C1859775393%2C2400959708%2C3395469782%5D%3Bk%2B%3DString.fromCharCode%28128%29%3Bvar%20y%3Dk.length/4%2B2%3Bvar%20m%3DMath.ceil%28y/16%29%3Bvar%20n%3Dnew%20Array%28m%29%3Bfor%28var%20A%3D0%3BA%3Cm%3BA%2B%2B%29%7Bn%5BA%5D%3Dnew%20Array%2816%29%3Bfor%28var%20z%3D0%3Bz%3C16%3Bz%2B%2B%29%7Bn%5BA%5D%5Bz%5D%3D%28k.charCodeAt%28A%2A64%2Bz%2A4%29%3C%3C24%29%7C%28k.charCodeAt%28A%2A64%2Bz%2A4%2B1%29%3C%3C16%29%7C%28k.charCodeAt%28A%2A64%2Bz%2A4%2B2%29%3C%3C8%29%7C%28k.charCodeAt%28A%2A64%2Bz%2A4%2B3%29%29%7D%7Dn%5Bm-1%5D%5B14%5D%3D%28%28k.length-1%29%2A8%29/Math.pow%282%2C32%29%3Bn%5Bm-1%5D%5B14%5D%3DMath.floor%28n%5Bm-1%5D%5B14%5D%29%3Bn%5Bm-1%5D%5B15%5D%3D%28%28k.length-1%29%2A8%29%264294967295%3Bvar%20v%3D1732584193%3Bvar%20u%3D4023233417%3Bvar%20r%3D2562383102%3Bvar%20q%3D271733878%3Bvar%20p%3D3285377520%3Bvar%20g%3Dnew%20Array%2880%29%3Bvar%20F%2CE%2CD%2CC%2CB%3Bfor%28var%20A%3D0%3BA%3Cm%3BA%2B%2B%29%7Bfor%28var%20w%3D0%3Bw%3C16%3Bw%2B%2B%29%7Bg%5Bw%5D%3Dn%5BA%5D%5Bw%5D%7Dfor%28var%20w%3D16%3Bw%3C80%3Bw%2B%2B%29%7Bg%5Bw%5D%3DROTL%28g%5Bw-3%5D%5Eg%5Bw-8%5D%5Eg%5Bw-14%5D%5Eg%5Bw-16%5D%2C1%29%7DF%3Dv%3BE%3Du%3BD%3Dr%3BC%3Dq%3BB%3Dp%3Bfor%28var%20w%3D0%3Bw%3C80%3Bw%2B%2B%29%7Bvar%20x%3DMath.floor%28w/20%29%3Bvar%20h%3D%28ROTL%28F%2C5%29%2Bf%28x%2CE%2CD%2CC%29%2BB%2Bo%5Bx%5D%2Bg%5Bw%5D%29%264294967295%3BB%3DC%3BC%3DD%3BD%3DROTL%28E%2C30%29%3BE%3DF%3BF%3Dh%7Dv%3D%28v%2BF%29%264294967295%3Bu%3D%28u%2BE%29%264294967295%3Br%3D%28r%2BD%29%264294967295%3Bq%3D%28q%2BC%29%264294967295%3Bp%3D%28p%2BB%29%264294967295%7Dreturn%20v.toHexStr%28%29%2Bu.toHexStr%28%29%2Br.toHexStr%28%29%2Bq.toHexStr%28%29%2Bp.toHexStr%28%29%7Dfunction%20f%28b%2Ca%2Cd%2Cc%29%7Bswitch%28b%29%7Bcase%200%3Areturn%28a%26d%29%5E%28%7Ea%26c%29%3Bcase%201%3Areturn%20a%5Ed%5Ec%3Bcase%202%3Areturn%28a%26d%29%5E%28a%26c%29%5E%28d%26c%29%3Bcase%203%3Areturn%20a%5Ed%5Ec%7D%7Dfunction%20ROTL%28a%2Cb%29%7Breturn%28a%3C%3Cb%29%7C%28a%3E%3E%3E%2832-b%29%29%7DNumber.prototype.toHexStr%3Dfunction%28%29%7Bvar%20c%3D%22%22%2Ca%3Bfor%28var%20b%3D7%3Bb%3E%3D0%3Bb--%29%7Ba%3D%28this%3E%3E%3E%28b%2A4%29%29%2615%3Bc%2B%3Da.toString%2816%29%7Dreturn%20c%7D%3Bvar%20mainURL%2CurlBar%2Cframe%2CscriptTags%2CcssLinkTags%3Bvar%20frameLoadTime%2CintervalID%3Bvar%20lastFetchedTimes%3D%7B%7D%3Bvar%20contentHashes%3D%7B%7D%3Bvar%20compareMode%3D%22Content%22%3Bvar%20scrollOffset%3Bif%28%21window.console%29%7Bwindow.console%3D%7Blog%3Afunction%28%29%7B%7D%7D%7Dfunction%20toArray%28b%29%7Bvar%20a%3D%5B%5D%3Bfor%28var%20c%3D0%3Bc%3Cb.length%3Bc%2B%2B%29%7Ba.push%28b%5Bc%5D%29%7Dreturn%20a%7Dfunction%20addTS%28b%2Ca%29%7Breturn%20b%2B%22%3F%22%2B%28a.getTime%28%29%29%7Dfunction%20addRandom%28b%29%7Bvar%20a%3DMath.random%28%29%3Ba%3DMath.round%28a%2A10000000%29%3Breturn%20b%2B%22%3F%22%2Ba%7Dfunction%20ajax%28a%2Cd%2Cc%29%7Bvar%20b%3Dnew%20XMLHttpRequest%28%29%3Bb.onreadystatechange%3Dc%3Bb.open%28d%2Ca%2Ctrue%29%3Bb.send%28%29%7Dfunction%20stripQS%28a%29%7Bvar%20b%3Da.indexOf%28%22%3F%22%29%3Bif%28b%3C0%29%7Breturn%20a%7Dreturn%20a.substring%280%2Cb%29%7Dfunction%20ifModified%28b%2Cc%29%7Bb%3DstripQS%28b%29%3Bvar%20a%3DaddRandom%28b%29%3Bajax%28a%2C%22GET%22%2Cfunction%28%29%7Bif%28this.readyState%3D%3D4%29%7Bif%28compareMode%3D%3D%22LastModified%22%29%7Bvar%20e%3Dnew%20Date%28this.getResponseHeader%28%22Last-Modified%22%29%29%3Bvar%20d%3DlastFetchedTimes%5Bb%5D%7C%7CframeLoadTime%3Bif%28e.getTime%28%29%3Ed.getTime%28%29%29%7Bc%28addTS%28b%2Ce%29%29%3BlastFetchedTimes%5Bb%5D%3De%7D%7Delse%7Bvar%20f%3Dsha1Hash%28this.responseText%29%3Bif%28contentHashes%5Bb%5D%21%3Df%29%7Bc%28a%29%3BcontentHashes%5Bb%5D%3Df%7D%7D%7D%7D%29%7Dfunction%20refresh%28%29%7Bconsole.log%28%22refresh%28%29%22%29%3BifModified%28mainURL%2Cfunction%28a%29%7Bframe.src%3Da%7D%29%3BcssLinkTags.forEach%28function%28b%29%7Bvar%20a%3Db.href%3BifModified%28a%2Cfunction%28c%29%7Bb.href%3Dc%7D%29%7D%29%7Dfunction%20setFrameHeight%28%29%7Bframe.style.height%3D%28window.innerHeight-frame.offsetTop%29%2B%22px%22%7Dfunction%20onWindowResize%28%29%7BsetFrameHeight%28%29%7Dfunction%20setTitle%28%29%7Bdocument.title%3D%22SuperRefresh%20-%20%22%2Bframe.contentDocument.title%7Dfunction%20onFrameLoaded%28c%29%7Bconsole.log%28%22onFrameLoaded%22%29%3BmainURL%3Dframe.contentWindow.location.toString%28%29%3BurlBar.innerHTML%3DstripQS%28mainURL%29%3BframeLoadTime%3Dnew%20Date%28%29%3BsetTitle%28%29%3Bvar%20b%3Dframe.contentDocument%3Bvar%20d%3Dframe.contentWindow%3Bvar%20a%3Dframe.contentDocument%3BcssLinkTags%3DtoArray%28a.getElementsByTagName%28%22link%22%29%29.filter%28function%28e%29%7Breturn%20e.rel%3D%3D%22stylesheet%22%7D%29%3Bif%28scrollOffset%29%7Bd.scrollTo%28scrollOffset.x%2CscrollOffset.y%29%7Dd.addEventListener%28%22scroll%22%2Cfunction%28%29%7BscrollOffset%3D%7Bx%3Ad.pageXOffset%2Cy%3Ad.pageYOffset%7D%7D%2Cfalse%29%3Bif%28%21intervalID%29%7BintervalID%3DsetInterval%28refresh%2C1000%29%7D%7Dfunction%20removeChildren%28a%29%7BtoArray%28a.childNodes%29.forEach%28function%28b%29%7Ba.removeChild%28b%29%7D%29%7Dfunction%20blankOutPage%28%29%7Bvar%20a%3Ddocument.getElementsByTagName%28%22head%22%29%5B0%5D%3BremoveChildren%28a%29%3Bdocument.body.innerHTML%3D%22%22%7Dfunction%20buildPage%28%29%7Bvar%20b%3D%27%23frame%7B%09position%3A%20fixed%3B%09top%3A%2024px%3B%09width%3A%20100%25%3B%09border%3A%20none%200px%3B%09border-top%3A%201px%20solid%20%23888%3B%7Dbody%7B%09font-family%3A%20%22Helvetica%22%2C%20%22Arial%22%3B%09margin%3A%200%3B%09padding%3A%200%3B%09overflow%3A%20hidden%3B%7Dh1%7B%20%20%20%20font-size%3A%2020px%3B%20%20%20%20margin%3A%200%3B%20padding%3A%200%3B%09color%3A%20%238cc21f%3B%09margin-left%3A%200.2em%3B%7Dh1%20span%7B%09color%3A%20%234ca1cc%3B%7D%23urlBar%7B%20%20%20%20position%3A%20absolute%3B%20%20%20%20right%3A%205px%3B%20%20%20%20top%3A%200px%3B%20%20%20%20color%3A%20%23888%3B%20%20%20%20padding-top%3A%208px%3B%20%20%20%20font-size%3A%2012px%7D%27%3Bvar%20c%3Ddocument.createElement%28%22style%22%29%3Bc.type%3D%22text/css%22%3Bc.appendChild%28document.createTextNode%28b%29%29%3Bvar%20a%3Ddocument.getElementsByTagName%28%22head%22%29%5B0%5D%3Bvar%20d%3Ddocument.createElement%28%22title%22%29%3Bd.appendChild%28document.createTextNode%28%22SuperRefresh%22%29%29%3Ba.appendChild%28d%29%3Ba.appendChild%28c%29%3Bdocument.body.innerHTML%3D%27%3Ch1%3E%3Cspan%3Esuper%3C/span%3Erefresh%3C/h1%3E%3Cdiv%20id%3D%22urlBar%22%3E%3C/div%3E%3Ciframe%20id%3D%22frame%22%3E%3C/iframe%3E%27%3Bframe%3Ddocument.getElementById%28%22frame%22%29%3BurlBar%3Ddocument.getElementById%28%22urlBar%22%29%3BsetFrameHeight%28%29%3Bwindow.addEventListener%28%22resize%22%2ConWindowResize%2Cfalse%29%7Dfunction%20init%28a%29%7BmainURL%3Da%3BblankOutPage%28%29%3BbuildPage%28%29%3Bframe%3Ddocument.getElementById%28%22frame%22%29%3Bframe.addEventListener%28%22load%22%2ConFrameLoaded%2Cfalse%29%3Bframe.src%3DaddRandom%28mainURL%29%7D%3Binit%28String%28window.location%29%29%3B})()">Click here to Try it!</a> Bookmark it to save it for use later. Enjoy. Currently, it works for Safari, Chrome, and Firefox.<br></div>
	<div>The source code is posted at <a href="http://github.com/airportyh/SuperRefresh">GitHub</a>.</div>
</div></content>
        </entry>,<entry>
            <title>How Much of the Web Actually Work Without Javascript</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/03/11/how-much-of-the-web-actually">
            <updated>2010-03-11T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/03/11/how-much-of-the-web-actually</li>
            <content type="text">
<p>Recently Paul Boag <a href="http://boagworld.com/accessibility/ecommerce-failure">showed dissatisfaction</a> at the fact that most ecommerce sites don't work without Javascript, which stand against progress enhancement. Coincidentally, I am just now in the middle of working on a <a href="http://github.com/airportyh/CSS.Features">Javascript library</a> that aims to make using CSS3 features and writing cross-browser CSS easier. So this got me thinking...</p>
<p>I <i>love</i> Javascript! I won't make any secret of this. I also love writing ajaxy web applications. Although I allow that there's value to making your site work without Javascript, to me, at least, it bares a lower priority. Of course, as is always the case, the answer depends very much on your target audience. Google Docs, for example, is more of a software tool than a web site, and so it wouldn't really make sense to make it work without Javascript - the result probably wouldn't be very useful anyway, because the essence of Google Docs, <i>is </i>the UI.</p>
<p>However, to consider the applicability of my Javascript library, I must consider whether it is acceptable to web designers that their design requires their users to have Javascript enabled.</p>
<p>And so, I resolved to survey how some of the major web sites and web applications look like and work like with Javascript disabled, so as to get a sense of what is the accepted norm on the web today.</p>
<h2>The Contenders<br></h2>
<p>I want to survey really popular sites. I also want to survey some content-centric sites, as well as some utility-type web-apps. The list has a Web 2.0 slant to it, but also include some old timers. Without further ado, the list is:</p>
<div>
	<ul>
		<li><a href="http://www.nytimes.com/">The New York Times</a><br></li>
		<li><a href="digg.com">Digg.com</a><br></li>
		<li><a href="facebook.com">Facebook</a><br></li>
		<li><a href="twitter.com">Twitter</a><br></li>
		<li><a href="stackoverflow.com">Stack Overflow</a><br></li>
		<li><a href="google.com">Google Search</a><br></li>
		<li><a href="cnn.com">CNN</a><br></li>
		<li><a href="amazon.com">Amazon</a><br></li>
		<li><a href="ebay.com">Ebay</a><br></li>
		<li><a href="boagworld.com">BoagWorld</a><br></li>
		<li><a href="maps.google.com">Google Maps</a><br></li>
		<li><a href="docs.google.com">Google Docs</a><br></li>
		<li><a href="gmail.com">Google Mail</a><br></li>
		<li><a href="rememberthemilk.com">Remember The Milk</a><br></li>
		<li><a href="flickr.com">Flickr</a><br></li>
		<li><a href="picasaweb.com">Picasa Web</a><br></li>
		<li><a href="youtube.com">YouTube</a></li>
		<li><a href="wordpress.com">Wordpress</a><br></li>
		<li><a href="github.com">GitHub</a></li>
	</ul>
	<h2>Scoring System<br></h2>
	<div>To evaluate how well each site works with Javascript disabled, I will use a scoring metric. The scoring will be based on the following 6 questions, each account for 1 point of the total score. Thus, 6 out of 6 is the perfect score.</div>
	<div>
		<ol>
			<li>Can users navigate the site? (1 point)<br></li>
			<li>Can users read/view the content? (1 point)<br></li>
			<li>Is the site free of broken visual elements? (1 point)<br></li>
			<li>Can users perform the key tasks of the site? (1 point)<br></li>
			<li>Is the site free of broken input elements? (1 point)<br></li>
			<li>If things are broken, are users made aware of it? (1 point)<br></li>
		</ol>
		<div>
			<div>
				<div>Let's get started!</div>
				<h3>The New York Times<br></h3>
				<div>
					<div class="image">
						<img title="Times Screenshot" alt="Times Screenshot" src="http://lh3.ggpht.com/_1m4jxPGXQAo/S5iV7EyeHoI/AAAAAAAAOS8/pAd6P0ZlC34/s400/Screen%20shot%202010-03-11%20at%202.03.53%20AM.jpg">
					</div>
				</div>
				<div>As expected, the New York Times looked great. Visually it didn't look much different from a Javascript enabled version. Flash ads are replaced by static image ads. One minor hiccup is a twitter widget which appears to spin indefinitely. The video section does not work at all, and there's is no message telling you you need Javascript to run it.</div>
			</div>
		</div>
	</div>
	<div>
		<ol>
			<li>Can users navigate the site? YES<br></li>
			<li>Can users read/view the content? YES<br></li>
			<li>Is the site free of broken visual elements? NO<br></li>
			<li>Can users perform the key tasks of the site? YES<br></li>
			<li>Is the site free of broken input elements? NO(video section)<br></li>
			<li>If things are broken, are users made aware of it? NO(video section)</li>
		</ol>
		<div>Score 3/6 for the Times.</div>
		<h3>Digg<br></h3>
		<div>
			<div class="image">
				<img title="Digg Screenshot" alt="Digg Screenshot" src="http://lh6.ggpht.com/_1m4jxPGXQAo/S5iUrbQkxbI/AAAAAAAAOSI/blqjKTLbhh0/s400/Screen%20shot%202010-03-11%20at%201.58.38%20AM.jpg">
			</div>
		</div>
		<div>Digg's page looks okay. The flash ads have disappeared, leaving whitespace in their place. You can navigate the site and view articles just fine. However, you cannot "digg" or "bury" articles, which I think is a pretty <i>key</i> task of the site. </div>
		<div>
			<ol>
				<li>Can users navigate the site? YES<br></li>
				<li>Can users read/view the content? YES<br></li>
				<li>Is the site free of broken visual elements? NO<br></li>
				<li>Can users perform the key tasks of the site? NO<br></li>
				<li>Is the site free of broken input elements? NO(digg button broken)<br></li>
				<li>If things are broken, are users made aware of it? NO</li>
			</ol>
		</div>
		<div>Digg gets a 2/6.</div>
		<h3>Facebook<br></h3>
		<div>
			<div class="image">
				<img title="Facebook Screenshot" alt="Facebook Screenshot" src="http://lh3.ggpht.com/_1m4jxPGXQAo/S5iXFHCGluI/AAAAAAAAOTc/u1zJ63oyA-8/s400/Screen%20shot%202010-03-11%20at%202.07.00%20AM.jpg">
			</div>
		</div>
		<div>From a visual stand point, Facebook looks perfect. You can navigate and read most of the content of Facebook, including viewing photo albums. You cannot update your status; you cannot edit your profile; you cannot record videos of yourself, and there's no warning. </div>
		<div>
			<ol>
				<li>Can users navigate the site? YES<br></li>
				<li>Can users read/view the content? YES<br></li>
				<li>Is the site free of broken visual elements? YES<br></li>
				<li>Can users perform the key tasks of the site? NO(can't update status)<br></li>
				<li>Is the site free of broken input elements? NO<br></li>
				<li>If things are broken, are users made aware of it? NO</li>
			</ol>
		</div>
	</div>
</div>
<p>Facebook's score: 3/6.</p>
<h3>Twitter<br></h3>
<div>
	<div class="image">
		<img title="Twitter Screenshot" alt="Twitter Screenshot" src="http://lh6.ggpht.com/_1m4jxPGXQAo/S5ibEQUQ5QI/AAAAAAAAOTk/pRYQpeAabUs/s400/Screen%20shot%202010-03-11%20at%202.25.41%20AM.jpg">
	</div>
</div>
<p>Twitter looks great without Javascript, but guess what? You cannot tweet! Bummer. You also can't edit some of the settings in your profile.</p>
<div>
	<ol>
		<li>Can users navigate the site? YES<br></li>
		<li>Can users read/view the content? YES<br></li>
		<li>Is the site free of broken visual elements? YES<br></li>
		<li>Can users perform the key tasks of the site? NO<br></li>
		<li>Is the site free of broken input elements? NO<br></li>
		<li>If things are broken, are users made aware of it? NO</li>
	</ol>
	<div>3/6 for Twitter.</div>
	<h3>Stack Overflow<br></h3>
	<div>
		<div class="image">
			<img title="Stack Overflow Screenshot" alt="Stack Overflow Screenshot" src="http://lh4.ggpht.com/_1m4jxPGXQAo/S5ibUBgXzPI/AAAAAAAAOTo/mWxlZ-Mo5-g/s400/Screen%20shot%202010-03-11%20at%202.26.51%20AM.jpg">
		</div>
	</div>
	<div>When you go the SO, a flash banner informs you that the site works best with Javascript enabled: nice, how refreshing! Navigation works, even asking questions, editing and posting works. However, voting does not work. For this one, I'll allow that the key tasks work, because I think the most important things are asking and answering questions; voting, although important, is secondary to those two things.</div>
	<div>
		<ol>
			<li>Can users navigate the site? YES<br></li>
			<li>Can users read/view the content? YES<br></li>
			<li>Is the site free of broken visual elements? YES<br></li>
			<li>Can users perform the key tasks of the site? YES<br></li>
			<li>Is the site free of broken input elements? NO<br></li>
			<li>If things are broken, are users made aware of it? YES</li>
		</ol>
		<div>5/6. Wow! Way to go, Jeff!</div>
		<h3>Google Search<br></h3>
		<div>
			<div class="image">
				<img title="Google Screenshot" alt="Google Screenshot" src="http://lh5.ggpht.com/_1m4jxPGXQAo/S5idMm6mOUI/AAAAAAAAOTw/Keqz_8vXZ-A/s400/Screen%20shot%202010-03-11%20at%202.34.54%20AM.jpg">
			</div>
		</div>
		<div>Google Search works well, however, Image results that come up on the top of the search results show up blank. I gotta say I am very surprised that this doesn't work perfectly. I mean, this is <i>the Google</i>!</div>
		<div>
			<ol>
				<li>Can users navigate the site? YES<br></li>
				<li>Can users read/view the content? YES<br></li>
				<li>Is the site free of broken visual elements? NO<br></li>
				<li>Can users perform the key tasks of the site? YES<br></li>
				<li>Is the site free of broken input elements? YES<br></li>
				<li>If things are broken, are users made aware of it? NO</li>
			</ol>
			<div>4/6 for Google Search.</div>
			<h3>CNN<br></h3>
			<div>
				<div class="image">
					<img title="CNN Screenshot" alt="CNN Screenshot" src="http://lh6.ggpht.com/_1m4jxPGXQAo/S5ieLrhX6kI/AAAAAAAAOT4/d1FGHWMiC7Q/s400/Screen%20shot%202010-03-11%20at%202.39.06%20AM.jpg">
				</div>
			</div>
			<div>CNN worked about as well as the Times. Navigation and reading content worked but not the videos. Although the videos on CNN are more prominent than on the Times, and also break more spectacularly:</div>
			<div><div class="image">
				<img title="CNN Broken Video Screenshot" alt="CNN Broken Video Screenshot" src="http://lh3.ggpht.com/_1m4jxPGXQAo/S5ifKwo_0xI/AAAAAAAAOT8/1F2WZDTT1mU/s400/Screen%20shot%202010-03-11%20at%202.43.21%20AM.jpg">
			</div><br></div>
			<div>
				<ol>
					<li>Can users navigate the site? YES<br></li>
					<li>Can users read/view the content? YES<br></li>
					<li>Is the site free of broken visual elements? NO<br></li>
					<li>Can users perform the key tasks of the site? YES<br></li>
					<li>Is the site free of broken input elements? NO<br></li>
					<li>If things are broken, are users made aware of it? NO</li>
				</ol>
				<div>3/6 for CNN.</div>
				<h3>Amazon<br></h3>
				<div>
					<div class="image">
						<img title="Amazon Screenshot" alt="Amazon Screenshot" src="http://lh4.ggpht.com/_1m4jxPGXQAo/S5ifnO0_urI/AAAAAAAAOUA/E3yXMK0iwqQ/s400/Screen%20shot%202010-03-11%20at%202.45.14%20AM.jpg">
					</div>
				</div>
				<div>Amazon is the one you gotta count on to do well in this. The site looks perfect. I've tested adding and update the shopping cart, which worked perfectly. I haven't actually gone all the way through and purchased something for this test, but I feel confident that everything would work.</div>
				<div>
					<ol>
						<li>Can users navigate the site? YES<br></li>
						<li>Can users read/view the content? YES<br></li>
						<li>Is the site free of broken visual elements? YES<br></li>
						<li>Can users perform the key tasks of the site? YES<br></li>
						<li>Is the site free of broken input elements? YES<br></li>
						<li>If things are broken, are users made aware of it? N/A</li>
					</ol>
					<div>6/6! Perfect for Amazon!</div>
					<h3>Ebay<br></h3>
					<div>
						<div class="image">
							<img title="Ebay Screenshot" alt="Ebay Screenshot" src="http://lh4.ggpht.com/_1m4jxPGXQAo/S5ihxR8mvjI/AAAAAAAAOUI/ujEt4ezIFZ4/s400/Screen%20shot%202010-03-11%20at%202.54.29%20AM.jpg">
						</div>
					</div>
					<div>Ebay is also an old timer ecommerce site. I don't see how it could fail any of these.</div>
					<div>
						<ol>
							<li>Can users navigate the site? YES<br></li>
							<li>Can users read/view the content? YES<br></li>
							<li>Is the site free of broken visual elements? YES<br></li>
							<li>Can users perform the key tasks of the site? YES<br></li>
							<li>Is the site free of broken input elements? YES<br></li>
							<li>If things are broken, are users made aware of it? N/A</li>
						</ol>
					</div>
					<div>6/6 for Ebay.</div>
					<h3>Boagworld<br></h3>
					<div>
						<div class="image">
							<img title="BoagWorld Screenshot" alt="BoagWorld Screenshot" src="http://lh3.ggpht.com/_1m4jxPGXQAo/S5iiRH5KOAI/AAAAAAAAOUQ/jpRNglRMLA0/s400/Screen%20shot%202010-03-11%20at%202.56.32%20AM.jpg">
						</div>
					</div>
					<div>Let's see if Paul puts his money where his mouth is. Boagworld looks perfect. forums work. Even the flash videos and audio work! That's pretty amazing. This is the first site I've seen where video works without Javascript.</div>
					<div>
						<ol>
							<li>Can users navigate the site? YES<br></li>
							<li>Can users read/view the content? YES<br></li>
							<li>Is the site free of broken visual elements? YES<br></li>
							<li>Can users perform the key tasks of the site? YES<br></li>
							<li>Is the site free of broken input elements? YES<br></li>
							<li>If things are broken, are users made aware of it? N/A</li>
						</ol>
						<div>6/6. Good On Ya! Paul Boag!</div>
						<h3>Google Maps<br></h3>
						<div>
							<div class="image">
								<img title="Google Maps Screenshot" alt="Google Maps Screenshot" src="http://lh4.ggpht.com/_1m4jxPGXQAo/S5ijj_JgaEI/AAAAAAAAOUY/4ed2KI52Dgo/s400/Screen%20shot%202010-03-11%20at%203.02.06%20AM.jpg">
							</div>
						</div>
						<div>Google Maps is the web application that gave life to Ajax. But much to my surprise, it actually works with Javascript turned off. Well... kinda sorta. You can plot an address on the map - even zoom and pan - but you cannot get directions. This is a tough one. On the one hand, it degrades 100% gracefully; on the other hand, without being able to give directions, it's all but crippled. </div>
						<div>
							<ol>
								<li>Can users navigate the site? YES<br></li>
								<li>Can users read/view the content? YES<br></li>
								<li>Is the site free of broken visual elements? YES<br></li>
								<li>Can users perform the key tasks of the site? NO<br></li>
								<li>Is the site free of broken input elements? YES<br></li>
								<li>If things are broken, are users made aware of it? N/A</li>
							</ol>
							<div>5/6 for you, Google Maps. Hey, don't be sad, 5/6 is pretty damn good!</div>
							<h3>Google Docs<br></h3>
							<div>
								<div class="image">
									<img title="Google Docs Screenshot" alt="Google Docs Screenshot" src="http://lh3.ggpht.com/_1m4jxPGXQAo/S5ilUPqizpI/AAAAAAAAOUg/Brwo1WjgQaU/s400/Screen%20shot%202010-03-11%20at%203.09.20%20AM.jpg">
								</div>
							</div>
							<div>Ouch! That's not a pretty picture. None of the buttons or sidebar items did anything when clicked. The loading indicators are just stuck there. This thing is pretty much...dead.</div>
							<div>
								<ol>
									<li>Can users navigate the site? NO<br></li>
									<li>Can users read/view the content? NO<br></li>
									<li>Is the site free of broken visual elements? NO<br></li>
									<li>Can users perform the key tasks of the site? NO<br></li>
									<li>Is the site free of broken input elements? NO<br></li>
									<li>If things are broken, are users made aware of it? NO</li>
								</ol>
								<div>Wow! Our first - and possible <i>only</i> - 0/6. Congrats Google Docs!</div>
								<h3>Gmail<br></h3>
								<div>
									<div class="image">
										<img title="Gmail Screenshot" alt="Gmail Screenshot" src="http://lh4.ggpht.com/_1m4jxPGXQAo/S5imxzAQlaI/AAAAAAAAOUo/yo7sJVokFLw/s400/Screen%20shot%202010-03-11%20at%203.15.52%20AM.jpg">
									</div>
								</div>
								<div>Two epic fails in a row from Google? Are you kidding me? Oh, but wait! What's this? On the bottom right there's a "Load basic HTML" link. You click on it and...</div>
								<div><div class="image">
									<img title="Gmail Screenshot 2" alt="Gmail Screenshot 2" src="http://lh5.ggpht.com/_1m4jxPGXQAo/S5inYl0ag6I/AAAAAAAAOUs/0fFqNBCyQaw/s400/Screen%20shot%202010-03-11%20at%203.17.51%20AM.jpg">
								</div><br></div>
								<div>Tada! Talk about drama! That's like a last second Hail-Mary pass for a TD or something. The functionality is all there for the basic HTML version. The only thing I'd pick on is the fact that it's not made very apparent that this option is available. In other words, the degradation ain't so graceful. I guess you could call it clumsy degradation?</div>
								<div>
									<ol>
										<li>Can users navigate the site? YES<br></li>
										<li>Can users read/view the content? YES<br></li>
										<li>Is the site free of broken visual elements? NO<br></li>
										<li>Can users perform the key tasks of the site? YES<br></li>
										<li>Is the site free of broken input elements? YES<br></li>
										<li>If things are broken, are users made aware of it? NO</li>
									</ol>
									<div>4/6 is all you get, Gmail!</div>
									<h3>Remember The Milk<br></h3>
									<div>
										
											<div class="image">
												<img title="Milk Screenshot" alt="Milk Screenshot" src="http://lh3.ggpht.com/_1m4jxPGXQAo/S5ipJiwM1kI/AAAAAAAAOU0/sSoe8mVJvI4/s400/Screen%20shot%202010-03-11%20at%203.26.02%20AM.jpg">
											</div>
										
									</div>
									<div>Well, at least they are up-front about it...</div>
									<div>
										<ol>
											<li>Can users navigate the site? NO<br></li>
											<li>Can users read/view the content? NO<br></li>
											<li>Is the site free of broken visual elements? YES<br></li>
											<li>Can users perform the key tasks of the site? NO<br></li>
											<li>Is the site free of broken input elements? YES<br></li>
											<li>If things are broken, are users made aware of it? YES</li>
										</ol>
										<div>3/6. Wow, you can not work at all, and <i>still</i> get 3/6!</div>
										<h3>Flickr<br></h3>
										<div>
											<div class="image">
												<img title="Flickr Screenshot" alt="Flickr Screenshot" src="http://lh5.ggpht.com/_1m4jxPGXQAo/S5ip0xAJQsI/AAAAAAAAOU4/FKCueIhrAeM/s400/Screen%20shot%202010-03-11%20at%203.28.54%20AM.jpg">
											</div>
										</div>
										<div>Flickr looks great, and mostly works. The things that don't work are in-place photo editing features, adding tags and people.</div>
										<div>
											<ol>
												<li>Can users navigate the site? YES<br></li>
												<li>Can users read/view the content? YES<br></li>
												<li>Is the site free of broken visual elements? YES<br></li>
												<li>Can users perform the key tasks of the site? YES<br></li>
												<li>Is the site free of broken input elements? NO<br></li>
												<li>If things are broken, are users made aware of it? NO</li>
											</ol>
											<div>4/6 for Flickr.</div>
											<h3>Picasa Web<br></h3>
											<div>
												<div class="image">
													<img title="Picasa Web Screenshot" alt="Picasa Web Screenshot" src="http://lh5.ggpht.com/_1m4jxPGXQAo/S5iqq92BeTI/AAAAAAAAOVA/3ExI8nEMYNI/s400/Screen%20shot%202010-03-11%20at%203.32.23%20AM.jpg">
												</div>
											</div>
											<div>Picasa Web informs you that your browser is not fully supported, but you are welcome to have a look around. You can see some pictures under the "Explore" tab, but not your own pictures. You also cannot upload your own pictures. It's basically crippled.</div>
											<div>
												<ol>
													<li>Can users navigate the site? NO<br></li>
													<li>Can users read/view the content? NO<br></li>
													<li>Is the site free of broken visual elements? NO<br></li>
													<li>Can users perform the key tasks of the site? NO<br></li>
													<li>Is the site free of broken input elements? NO<br></li>
													<li>If things are broken, are users made aware of it? YES</li>
												</ol>
												<div>1/6. Google, Google. Not doing so well, are you?</div>
												<h3>YouTube<br></h3>
												<div>
													<div class="image">
														<img title="YouTube Screenshot" alt="YouTube Screenshot" src="http://lh5.ggpht.com/_1m4jxPGXQAo/S5iruOWcFAI/AAAAAAAAOVI/AZpMCoxM_Po/s400/Screen%20shot%202010-03-11%20at%203.36.59%20AM.jpg">
													</div>
												</div>
												<div>Hate to rub it in, but YouTube is a FAIL as well. You can still navigate the site, but not play any videos.</div>
												<div>
													<span><ol>
														<li>Can users navigate the site? YES<br></li>
														<li>Can users read/view the content? NO<br></li>
														<li>Is the site free of broken visual elements? NO<br></li>
														<li>Can users perform the key tasks of the site? NO<br></li>
														<li>Is the site free of broken input elements? NO<br></li>
														<li>If things are broken, are users made aware of it? NO</li>
													</ol>
													<div>1/6 for YouTube.</div>
													<h3>WordPress<br></h3>
													<div>
														<div class="image">
															<img title="Wordpress Screenshot" alt="Wordpress Screenshot" src="http://lh3.ggpht.com/_1m4jxPGXQAo/S5itCWPldHI/AAAAAAAAOVQ/lX2peaMRdM8/s400/Screen%20shot%202010-03-11%20at%203.42.36%20AM.jpg">
														</div>
													</div>
													<div>WordPress works for the most part, but the parts that don't work do not degrade gracefully. Comments are broken. "Visual" editing is also broken, but you <i>can</i> write posts.</div>
													<div>
														<span><ol>
															<li>Can users navigate the site? YES<br></li>
															<li>Can users read/view the content? YES<br></li>
															<li>Is the site free of broken visual elements? YES<br></li>
															<li>Can users perform the key tasks of the site? YES<br></li>
															<li>Is the site free of broken input elements? NO<br></li>
															<li>If things are broken, are users made aware of it? NO</li>
														</ol>
														<div>4/6 for Wordpress.</div>
														<h3>GitHub<br></h3>
														<div>
															<div class="image">
																<img title="GitHub Screenshot" alt="GitHub Screenshot" src="http://lh6.ggpht.com/_1m4jxPGXQAo/S5iuKLzxVtI/AAAAAAAAOVY/SAUEyX31kwo/s400/Screen%20shot%202010-03-11%20at%203.47.17%20AM.jpg">
															</div><br>
														</div>
														<div>Last but not least, GitHub. I am, after all, the geek's geek. GitHub actually works very well. The only hiccups are small UI elements like the URL box, and the "Add File" button of the Gist dialog.</div>
														<div>
															<span><div>
																<span><ol>
																	<li>Can users navigate the site? YES<br></li>
																	<li>Can users read/view the content? YES<br></li>
																	<li>Is the site free of broken visual elements? YES<br></li>
																	<li>Can users perform the key tasks of the site? YES<br></li>
																	<li>Is the site free of broken input elements? NO<br></li>
																	<li>If things are broken, are users made aware of it? NO</li>
																</ol>
																<div>4/6 for GitHub.</div>
																<h2>Final Tally<br></h2>
																<div>Here is a summary of all the scores:</div>
																<div><div class="image">
																	<img title="Site vs Score Chart" alt="Site vs Score Chart" src="https://spreadsheets.google.com/oimg?key=0AvuDADmGj683dGRGbTQwMVRRNmh1QklIWTcteGZwR0E&oid=1&v=1268299001872">
																</div><br></div>
																<div>
																	<span><div>
																		<span><div>
																			<span><div>
																				<span><div>The winners were Amazon, Ebay, and Boag World. <span><div>
																					<span><div>
																						<span><div>
																							<span><div>
																								<span><div>
																									<span><div>
																										<span><div>
																											<span><span><div>
																												<span><div>
																													<span><div>
																														<span><div>
																															<span><div>
																																<span><div>
																																	<span><div>
																																		<span><div>The average score for all the sites surveyed is 3.52. Only 26% of the sites had a score of 5 or higher. What this practically means is that 74% of the sites had something broken about them when Javascript is disabled.</div></span>
																																	</div></span>
																																</div></span>
																															</div></span>
																														</div></span>
																													</div></span>
																												</div></span>
																											</div></span></span>
																										</div></span>
																									</div></span>
																								</div></span>
																							</div></span>
																						</div></span>
																					</div></span>
																				</div></span></div></span>
																			</div></span>
																		</div></span>
																	</div></span>
																</div>
																<h2>Summary By Metric<br></h2>
																<div>
																	<div class="image">
																		<img title="Summary By Metric Chart" alt="Summary By Metric Chart" src="https://spreadsheets.google.com/oimg?key=0AvuDADmGj683dGRGbTQwMVRRNmh1QklIWTcteGZwR0E&oid=2&v=1268299387172">
																	</div><br>
																</div>
																<div>What <i>this</i> chart shows is that most sites allow users to navigate and/or view the content on the site, in fact around 80% of them do. But, I think it's important to note that only 58% allowed users to perform the key tasks of the site. In other words, the other 42% are basically crippled. Another thing to note is that only 16% of sites that are broken let their users know that the site is broken without Javascript in some form or fashion - this is actually a really easy thing to fix, one could do what Stack Overflow does and just put up a flash banner on the top of the page, and be done with it. What this shows is that the developers of these sites either didn't tested the site with Javascript off, or just didn't think this was important enough to fix.</div>
																<div>See <a href="http://spreadsheets.google.com/pub?key=tdFm401TQ6huBIHY7-xfpGA&single=true&gid=0&output=html">this spreadsheet</a> for all the data in one place.</div>
																<h2>Conclusion<br></h2>
																<div>What have we learned? Well, if you insist on turning off Javascript, the web isn't going to be much fun. It should be noted however that the ecommerce sites (and serious web designers) are the ones that take this very seriously.</div>
																<div>As for the Javascript library that I am building: I plan on releasing it soon. I think maybe what I'll do is to let Javascript-enabled be the default mode of operation, but given a fallback option, albeit somewhat more complexed one.</div></span>
															</div></span>
														</div></span>
													</div></span>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div></content>
        </entry>,<entry>
            <title>My Work Mail Filter</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/03/09/my-work-mail-filter">
            <updated>2010-03-09T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/03/09/my-work-mail-filter</li>
            <content type="text">
<p>My company recently switched to Google Apps. One of the implications of this is that I can use Gmail's mail filters. Since - like many company - I get a daily plethora of list emails, I thought I'd create a simple rule to filter them down to only the ones that require my attention.</p>
<h3>Attempt #1:<br></h3>
<pre><code>Matches: -{Toby}
Do this: Skip Inbox
</code></pre>
<p>This rule says that if the email does not have my name in it anywhere, then skip the Inbox(like Google Search, "-" is the NOT operator). This worked fairly well, but I found that there were some false positives after a week or so of using it. So it needed some tuning up.</p>
<h3>Attempt #2:<br></h3>
<pre><code>Matches: to:(-my@company.email) -{Toby Birthday}
Do this: Skip Inbox
</code></pre>
<p>I found that once in a while, there'd be a message addressed to me directly, but would not have my name in the message. I fixed this by putting <i>-my@company.email</i> in the <i>To</i> field of the filter(replace <i>my@company.email</i> with your own email). So, this filter will only apply to mail not addressed directly to me - the ones sent to mailing lists, basically. Also, I'd like to be notified of people's birthday, so I added the word <i>Birthday</i> to the <i>doesn't-have</i> list.</p>
<h3>Attempt #3:<br></h3>
<p>Whenever I request support, I always first get a message first that says: <i>Thank you for your support request. </i>This is pretty uninformative, so I don't need to be alerted to them. So I added the rule:</p>
<pre><code>Matches: from:(our@support.email) Thank you for your support request.
Do this: Skip Inbox
</code></pre>
<p>That's what I've got so far. This post will be updated as I further fine tune my mail filters.</p>
<p><i>Update: I found that it's a bad idea to ignore the email HR sends out the the mailing list, so I modified the first rule to let her in:</i></p>
<h3>Attempt #4:</h3>
<pre><code>Matches: to:(-my@company.email) -{Toby Birthday} from:(-hr@company.email}
Do this: Skip Inbox</code></pre>
<p><i><br></i></p></content>
        </entry>,<entry>
            <title>60s Music from Lost</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/03/06/60s-music-from-lost">
            <updated>2010-03-06T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/03/06/60s-music-from-lost</li>
            <content type="text">
<p>My latest obsession: 60's music from <a href="http://en.wikipedia.org/wiki/Lost_(TV_series)">Lost</a>. In particular, Desmond's song from the very beginning of the first episode of Season 2: <a href="http://www.google.com/search?hl=en&client=safari&rls=en&q=cass+elliot+make+your+own+kind+of+music&aq=0&aqi=g2&aql=&oq=cass+elliot+make+you">Make Your Own Kind of Music by Cass Elliot</a>; and Juliet's intro on the first episode of the 3rd season: <a href="http://www.google.com/search?client=safari&rls=en&q=petula+clark+downtown&ie=UTF-8&oe=UTF-8">Downtown by Petula Clark</a>. I found these songs by Googling the lyrics. Never heard of these folks before. I bought Cass Elliot's Mama's Big Ones and Petula Clark's Downtown, and have been listening for a few weeks, and am enjoying them. My favorite song is Cass Elliot's <i>Ain't Nobody Else Like You</i>. Cass is a big woman who has a sweet and somewhat childish voice which I like, I also like the music style which has some "hip" brass accompaniment. Petula Clark's voice somewhat resembles Julie Andrews, <i>Don't Sleep In The Subway</i> and <i>I Couldn't Live Without Your Love</i> on the album are quite catchy.</p></content>
        </entry>,<entry>
            <title>Javascript sort() Gotcha</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/03/04/javascript-sort()-gotcha">
            <updated>2010-03-04T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/03/04/javascript-sort()-gotcha</li>
            <content type="text">
<p><i>Javascript pop quiz!</i></p>
<p><i>What is the result of this code?</i></p>
<p><i><span><pre><code>var arr = [12, 3, 24]</code></pre>
<pre><code>arr.sort()</code></pre>
<pre><code>arr</code></pre></span></i></p>
<p><i>You: [3, 12, 24]</i></p>
<p><i>Me: Wrong, You get an F! The correct answer is: [12, 24, 3].</i></p>
<p><i>You: WTF?</i></p>
<p><i>Me: Array.prototype.sort() uses lexical ordering by default. That is to say, it converts everything to string before comparing them. Thus, '12' comes before '24' comes before '3'.</i></p>
<p><i>You: So how do you make it sort numbers?</i></p>
<p><i>Me: You pass it a comparator function as an argument:</i></p>
<pre><code>arr.sort(function(a, b){
  return a - b
})</code></pre>
<p><i>You: That makes sense, I guess. But still...that is pretty messed up.</i></p>
<p><i><br></i></p></content>
        </entry>,<entry>
            <title>Memoize for Javascript</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/03/04/memoize-for-javascript">
            <updated>2010-03-04T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/03/04/memoize-for-javascript</li>
            <content type="text">
<p>I wrote a memoize function for Javascript today to cache file timestamps. I thought I would share it with the world. Here is the code:</p>
<pre><code>function memoize(f){
    var cache = {}
    return function(){
        var keys = []
        for (var i = 0; i &lt; arguments.length; i++){
            keys.push(typeof(arguments[i]) + ':' + String(arguments[i]))
        }
        var key = keys.join('/')
        if (key in cache){
            return cache[key]   
        }else{
            var val = f.apply(null, arguments)
            cache[key] = val
            return val
        }
    }
}
</code></pre>
<p>Let's say you have a function:</p>
<pre><code>function f(x, y){
  return x + y * 2
}</code></pre>
<p>If you memoize it:</p>
<pre><code>f = memoize(f)</code></pre>
<p>The first time you call f with arguments (3, 4):</p>
<pre><code>f(3, 4) =&gt; 11</code></pre>
<p>It will compute it, but the second time:</p>
<pre><code>f(3, 4) =&gt; 11</code></pre>
<p>It will merely return the cached value computed from the last time.</p>
<p>Note about the implementation: the equality metric used by this memoize function is: 2 objects are equal iff they are of the same type:</p>
<pre><code>typeof(one) == typeof(other)</code></pre>
<p>and, they have the same string represention:</p>
<pre><code>String(one) == String(other)</code></pre>
<p>That is it. Enjoy!</p></content>
        </entry>,<entry>
            <title>Say No to Syncing</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/02/12/say-no-to-syncing">
            <updated>2010-02-12T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/02/12/say-no-to-syncing</li>
            <content type="text">
<p>If you are a podcast listener like me, you have probably accustomed yourself to connecting your iPod to your computer everyday to get your new podcast episodes. This is a big hassle, but in the age of the iPod, this made a lot of sense. You sync your podcasts, just like you would sync your music collection, because the only way to get your media onto the iPod was through the USB cable. Apple also did a great job of integrating the podcast experience into iTunes and the iPod, their podcast listening experience was second to none.</p>
<p><i>Enter the iPhone</i>. And later the iPod Touch as well as other smartphones which came into the market to compete with the iPhone. These new devices are internet enabled, and so they possessed the power to download the new podcast episodes by themselves, and thus the daily chore of syncing podcasts can be eliminated. With the <a href="http://rssplayer.blogspot.com/">RSS Player app</a> you can catch new podcast episodes for your favorite podcasts directly on the device - no need to connect to a computer or go through iTunes at all. On the Android platform, there is <i>Listen</i> and a handful of other apps which do the same thing, and so G1, Droid, and other Android phone users can enjoy this convenience as well. But my guess is that most people are still syncing podcasts. <i>Why is that? You ask.</i></p>
<p>Apple <a href="http://arstechnica.com/apple/news/2008/09/apple-denies-iphone-podcast-app-for-duplicating-itunes.ars">rejected</a> what came to be the RSS Player app at first. They saw it as stepping on their own turf. Not long after that, they allowed users to download specific podcast episodes directly from their device, but still no automatic updates. Why they didn't add that feature is very puzzling to me. To me, Apple is still hanging on their dock-n-USB paradigm, which - in my opinion - will go out of fashion very soon. Case and point: the iPad. Why would the iPad need a dock connector? It's freakin' ridiculous. You may say: <i>they want you to use iTunes.</i> To that I say: <i>you can use iTunes on the iPad.</i> You may say: <i>it needs to sync with the music collection</i>. Then I say: <i>you should be able to sync over wi-fi!</i> I also predict - and I am not the only one by far - that on-demand music streaming is going to obviate the need for the syncing of even your music collection in probably 2-3 years. Who knows, Apple might even be the one pioneering that movement, given that they've bought <a href="http://www.lala.com/">Lala</a>. </p>
<p>And so, to smartphone or iPod Touch users who are still syncing podcasts, I'd say this:</p>
<p><i>Stop pushing the button.</i></p>
<div>
	<div class="image">
		<img title="The Button" alt="The Button" src="http://lh4.ggpht.com/_1m4jxPGXQAo/S3XgGfeNXlI/AAAAAAAANUw/c_Z4P1XjG6g/s800/the-button.jpg">
	</div>
</div></content>
        </entry>,<entry>
            <title>My Thoughts on the iPad</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/01/29/my-thoughts-on-the-ipad">
            <updated>2010-01-29T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/01/29/my-thoughts-on-the-ipad</li>
            <content type="text">
<div><div class="image">
	<img title="iPad" alt="iPad" src="http://lh5.ggpht.com/_1m4jxPGXQAo/S2J5DkVcX_I/AAAAAAAAMzw/ugNLdjGv_zQ/s800/iPad.jpg">
</div><br></div>
<p>I've followed <a href="http://www.engadget.com/2010/01/27/live-from-the-apple-tablet-latest-creation-event/">engadget's live blog</a>, seen the <a href="http://www.apple.com/ipad/">keynote video</a>, listened to <a href="http://www.cnet.com/8301-19709_1-10442812-10.html">Tom and Molly talk about it</a>, even read others' opinions on <a href="http://www.engadget.com/2010/01/27/editorial-engadget-on-the-ipad/">engadget</a>, <a href="http://discuss.gdgt.com/apple/ipad/">gdgt</a> and <a href="http://twitter.com/#search?q=ipad">twitter</a>, etc etc. I guess you could say I am pretty excited. </p>
<p>The tech savy(engadget, gdgt, BOL, etc) are in general underwhelmed or disappointed. Below are some of the complaints I have heard:</p>
<div>
	<ul>
		<li>No Webcam or microphone - which pretty much rules out using Skype on it, which would have been a great killer app at this form factor. I think they will add these to the iPad in the future. <i>Update: actually, there IS a built-in microphone, so at least you can make audio calls with Skype.</i></li>
		<li>Still No Flash Support - you cannot seriously claim it has the <i>best</i> web browsing experience when it doesn't support Flash! Apple has not allowed Flash to run on the iPhone all this time. Now that they are doing the  same with the iPad - which with it's larger screen you would think would be much better suited to run Flash apps, and add to it the fact that Flash has never ran great on <a href="http://stackoverflow.com/questions/2148424/flash-flex-runs-slower-on-mac">Macs</a>, it's becoming obvious that this is political. Apple wants to fight a format war with Adobe. Why would you need flash when you can buy great apps from the app store and buy TV shows and movies from iTunes? On the other hand, I can also see the concern that almost all of the flash apps out there(possibly with the exception of Flash ads) just aren't designed for the touch screen, and having users run them on the iPhone or the iPad degrades the user experience and therefore could hurt the products' reputation. Apple's PR, however, is going with: <a href="http://www.macnn.com/articles/10/01/28/tablet.locks.ibooks.to.apple.hardware.adobe.says/">"it could rapidly drain battery life"</a>, which I think is probably in reality 3rd or 4th down on their list of concerns.</li>
		<li>No multiple tasks/apps/windows - this is a pretty big one: given the iPad's screen real estate, it seems artificially limiting to not allow multiple apps to be running in separate windows. I believe the iPad will eventually have this feature. How the UI will turn out will be interesting to see. </li>
		<li>The App Store Sucks - Apple prevents certain types of applications from entering its App Store. One example is programming language interpreters; another is any app that Apple views as overstepping their core apps' boundaries. Given that the iPad is even more of a computer than the iPhone, these limitations may become even more glaring.</li>
		<li>I just don't see the need - "I already have a laptop and a smartphone, there just isn't any more room for yet another device!" I think that at the moment the iPad is more exciting for developers than consumers, but that will change.</li>
	</ul>
	<div>All the negatives are well and good, but I overlook all of them, because, from my point of view, the iPad - and what it will lead to - is <i>much</i> bigger. All of the tablet computers I've seen in stores in the past - HP's, Fujitsu's, etc: they all suck. These computer manufacturers created tablet computers but installed on them an Operating System which is design from the ground up for use with a mouse and a keyboard. They figured: "A tablet computer has a stylus. We can use it as a pointing device in the same way that a mouse is a pointing device. We just hook up the stylus driver to control the pointer, and boom! We got ourselves a tablet Operating System! Brilliant!" This is understandable, because it is the nature of software engineers to want to build solutions that solve as many problems as possible - and Windows is a very very big solution indeed. However, this tendency also causes brilliant people to routinely produce crap. The tablet form factor is more versatile than the mouse, and can be much more natural to use from a UI standpoint, but dumbing it down and retrofitting it to an inferior UI paradigm caused it to be marginal. Yes, you could use a tablet to draw, sign documents, take notes, etc, but when it came to interacting with the UI elements, it was usually very kludgy. </div>
	<div>iPad is the first tablet I've seen that comes close to realizing the potential of the tablet form factor. Why? It's all about the software, stupid! The software that come with the iPad were designed and written  specifically for the large multi-touch screen device. This is to take nothing away from the amazing hardware. Multi-touch was ground breaking when it <a href="http://cs.nyu.edu/~jhan/ftirtouch/">first surfaced</a>. When the iPad comes to market, it will be the single best showcase of multi-touch technology. But, the software is what brings it all together, and you can tell Apple put a lot of time and effort into the software. Okay, enough of my rambling. What am I really trying to say? </div>
	<div><i><br></i></div>
	<div><i>iPad marks a historical step towards our liberation from mouse pointers and a paradigm shift in computer technology.</i></div>
	<div><i><br></i></div>
	<div>I hereby reiterate my <a href="/Simulating_a_Tablet_Using_the_Touchpad">prediction</a> that in 5 to 10 years, mice will be on the way to extinction.</div>
</div></content>
        </entry>,<entry>
            <title>Simulating a Tablet Using the Touchpad</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2010/01/24/simulating-a-tablet-using-the">
            <updated>2010-01-24T05:00:00.000Z</updated>
            <id>http://tobyho.com/2010/01/24/simulating-a-tablet-using-the</li>
            <content type="text">
<p><span><div class="image">
	<img alt="Chinese Handwriting" src="http://lh3.ggpht.com/_1m4jxPGXQAo/S1yxKuywYwI/AAAAAAAAMok/o6PMh12gwQI/s800/Screen%20shot%202010-01-24%20at%201.09.38%20PM.jpg">
</div><br></span></p>
<p>I came across OS X's Chinese Trackpad Handwriting input method the other day, and was really impressed. Once you activate the handwriting mode(hotkey: Ctrl-Shift-Space), the mouse pointer disappears, and you can use write your chinese character on your trackpad using your finger. The UI looks like this:</p>
<div><br><div>
	<div class="image">
		<img alt="Handwriting UI" src="http://lh6.ggpht.com/_1m4jxPGXQAo/S1y0yVhw2RI/AAAAAAAAMow/PmE0k18GzQU/s800/Screen%20shot%202010-01-24%20at%203.57.56%20PM.jpg">
	</div>
</div><div>What's interesting to me is the buttons on the left and right of the character recognition area. It took me a while to figure out how to use them at first, but after some experimentation, I figured it out: basically, the pretty gray box corresponds to your trackpad, and so to press a button on the upper left corner, you would tap the area in the upper left corner of your trackpad, and so on and so forth. It is very intuitive really. I would even say brilliant. Essentially, the trackpad has been made to work just like the <a href="http://tobyho.com/书法with_Vistablet">Vistablet</a> or any of the tablet accessories you can get from the Apple store these days. </div><div>Which got me thinking, how far can we take this? Can we use this to say...draw? A couple of google searches later, I discovered the <a href="http://tenonedesign.com/inklet.php">Inklet</a> from <i>Ten One Design</i>. The Inklet is an application, which is primarily used with a stylus you can buy from the same company called the Pogo Sketch. </div><div><div class="image">
	<img alt="Pogo Sketch Stylus" src="http://lh3.ggpht.com/_1m4jxPGXQAo/S1y-Eb6pjoI/AAAAAAAAMpU/yZNzLrDZkMc/s800/Screen%20shot%202010-01-24%20at%204.39.17%20PM.jpg">
</div><br></div><div>The Pogo Sketch is a pressure sensitive stylus that works with the Apple trackpads as well as the iphone and ipod touch. With Inklet and the Pogo Sketch together, you basically have the features of Vistablet. Here's their demo using Photoshop:</div><div>
	<div><span>Embedded Content</span><object width="560" height="340">
		<param name="movie" value="http://www.youtube.com/v/7KVFmE8la6w&hl=en_US&fs=1&">
		
		</param>
		<param name="allowFullScreen" value="true">
		
		</param>
		<param name="allowscriptaccess" value="always">
		
		</param>
		<embed src="http://www.youtube.com/v/7KVFmE8la6w&hl=en_US&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="560" height="340">
		
		</embed>
	</object></div>
</div><div><br><div><br><div>Brilliant, brilliant stuff. Another why-didn't-I-think-of-that moment for me. The lesson from all of this is that, at least for the new Macs, you can do a lot more with the trackpad than you thought(or at least I thought). For some types of applications, it may make sense to completely do away with the mouse pointer and use a tablet-style interface instead, and we can do this NOW! (Yes, now - three days before the imminent release of the Apple Tablet). Tablet doubters, just you wait, tablets <a href="/Tablets_are_the_way_of_the_future">will</a> be the way of the future. In 5-10 years(oh this could be another <a href="http://tobyho.com/tag/fourcast">Fourcast prediction</a>), the mice could be heading towards extinction. Just you wait.</div></div></div></div></content>
        </entry>,<entry>
            <title>Working From the Future</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/12/19/working-from-the-future">
            <updated>2009-12-19T05:00:00.000Z</updated>
            <id>http://tobyho.com/2009/12/19/working-from-the-future</li>
            <content type="text">
<p>This is my second FourCast style prediction. It is the "long term" prediction.</p>
<p><i>In the year 2110, 80%> of the earth's workers will work remotely. <span><i> Even physical tasks like surgery, construction, or mechanical repair: you can do by logging into a robot remotely and controlling in via a VR-type interface.<span><i> Moreover, many of the reasons for needing to get out of the house have been eliminated, among them:</i></span></i></span></i></p>
<div>
	<ul>
		<li><i>groceries - groceries will be delivered to your fridge. You will order them online - usually on a display on your fridge, or just by talking to it and the groceries will be delivered within a couple of hours.</i></li>
		<li><i>social activities - 80% > of social activities will be done via virtual worlds like Second-Life. So you can connect with all of your friends no matter where they are or where you are.</i></li>
	</ul>
	<div><i><br></i></div>
	<div><i>The implications of this are:</i></div>
	<div>
		<ul>
			<li><i>Because people are not tied to the location where they work, they can be traveling on a day-to-day basis and still not miss a day of work: tourism flourishes.</i></li>
			<li><i>By the same logic, people can live where they want to live, not where they have to live, therefore, they move their residence from place to place in a much higher frequency. People who love traveling live in RVs permanently.</i></li>
			<li><i>The real estate market will sky rocket, because there will be a large influx of potential buyers from all over the world.</i></li>
			<li><i>Most jobs will be short-term contracts because for whom you work is no longer tied to where you live, and so there's less of a need for stability and also you have a much larger pool of openings to choose from.</i></li>
			<li><i>There will be one global currency to facilitate workers and employers in different countries to do business with one another.</i></li>
			<li><i>There will only be 2 or 3 languages in common use throughout the world, and the majority of the people know at least 2 of them.</i></li>
			<li><i>90% of dating will happen virtually. Meeting IRL will be considered a major step in a relationship.</i></li>
		</ul>
	</div>
</div></content>
        </entry>,<entry>
            <title>The Future of TV</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/12/17/the-future-of-tv">
            <updated>2009-12-17T05:00:00.000Z</updated>
            <id>http://tobyho.com/2009/12/17/the-future-of-tv</li>
            <content type="text">
<p>I've been enjoying <a href="http://www.fourcastpodcast.com/">Tom and Scott's FourCast Podcast</a> and decided that I would make my own predictions in the FourCast style. This post is my first prediction and will be the <i>short term</i> prediction. Here goes:</p>
<p><i>In the year 2020, TV will work completely wirelessly. Devices like Apple TV, Roku, Boxee Box, etc. will be merged into the TV itself. HDMI, DVI, Component inputs are only optional features and will be seen as outdated or niche. Apple Inc. will have the best selling TV which will have not a single hole or button on it. TV programming will be IP based and a la carte. TV shows will be delivered via a framework/standard like RSS but which allows for streaming, ad placement as well as paid shows in the form of a la carte or subscription. TV networks have a much smaller role and their main purpose will be to getting advertisers for shows. Google/YouTube will become the biggest TV network and will use ad-sense to place ads for shows anyone can make. Other competing networks will crop up and some of the old TV networks will move to this model but will not over take YouTube. TV channels will become a concept distinct from TV networks, and will be collections of shows/videos created by the TV networks or individual users(kinda like playlists). </i></p></content>
        </entry>,<entry>
            <title>Flex Compiler Slower on 64bit Mode Java on Snow Leopard</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/11/17/flex-compiler-slower-on-64bit">
            <updated>2009-11-17T05:00:00.000Z</updated>
            <id>http://tobyho.com/2009/11/17/flex-compiler-slower-on-64bit</li>
            <content type="text">
<p>Ever since I upgraded to Snow Leopard, the my flex apps seemed to compile slower. Today, I finally had enough and took a look into this problem. First, there was the weirdness with Java on Mac in that even though the compiler is a command line application(non-GUI), it creates a application menu. I cracked open the <i>mxmlc</i> script, and added:</p>
<pre><code>-Djava.awt.headless=true
</code></pre>
<p>to <i>VMARGS</i>. This solved that issue, but didn't make it compile much faster.</p>
<p>Then, after a bit of fiddling around, it turned out that putting java into 32bit mode:</p>
<pre><code>-d32</code></pre>
<p>fixed the problem! The difference was significant. I tested this in 2 different apps. For App 1, it took 45 seconds to compile on 64bit mode, only 9 seconds on 32bit mode. For App 2, it took 30 seconds on 64bit mode, only 7 seconds on 32bit mode. So, <i>mxmlc</i> performs 4-5 times slower on 64bit java than 32bit, java. Why would this be the case, I have no idea. If anyone has an idea, I'd love to be enlightened. If you come across this problem, the fix is to open up <i>mxmlc</i>, and edit the line that says:</p>
<pre><code>VMARGS="-Xmx1024m -Dsun.io.useCanonCaches=false"
</code></pre>
<p>and change it to:</p>
<pre><code>VMARGS="-Xmx1024m -Dsun.io.useCanonCaches=false -Djava.awt.headless=true -d32"
</code></pre>
<p>I hope that helps someone.</p></content>
        </entry>,<entry>
            <title>Taking an Average in CouchDB</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/10/07/taking-an-average-in-couchdb">
            <updated>2009-10-07T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/10/07/taking-an-average-in-couchdb</li>
            <content type="text">
<p>More fun with CouchDB, this time taking an average of something:</p>
<pre><code>// map
function(doc){
    emit(null, doc.info.size) // in place of doc.info.size, you'd put whatever
                               // value you want averaged here
}
// reduce
function(keys, values, rereduce) {
    if (!rereduce){
        var length = values.length
        return [sum(values) / length, length]
    }else{
        var length = sum(values.map(function(v){return v[1]}))
        var avg = sum(values.map(function(v){
            return v[0] * (v[1] / length)
            }))
        return [avg, length]
    }
}</code></pre>
<p>The end result will be 2 values, the first is the average, the second is the total number of values that we took an average of. Phew! Who woulda thought taking an average would be so <i>involved!</i></p></content>
        </entry>,<entry>
            <title>Retrieve The Top N Tags in CouchDB</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/10/07/retrieve-the-top-n-tags-in">
            <updated>2009-10-07T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/10/07/retrieve-the-top-n-tags-in</li>
            <content type="text">
<p>I am reading up on how map/reduce works in CouchDB, think I am getting the hang of it now, thanks to <a href="http://labs.mudynamics.com/wp-content/uploads/2009/04/icouch.html">this great tool</a>. I tried the "Retrieve the top N tags" example on <a href="http://wiki.apache.org/couchdb/View_Snippets">this page</a>. It didn't work for me at all. So I wrote my own as an exercise. Here's my code:</p>
<pre><code>// the map function
function(doc){
    for(var i in doc.tags)
    {
        emit(null, doc.tags[i]);
    }
}

// the reduce function
function(key, values, rereduce){
    var hash = {}
    if (!rereduce){
        for (var i in values){
            var tag = values[i]
            hash[tag] = (hash[tag] || 0) + 1
        }
    }else{
        for (var i in values){
            var topN = values[i]
            for (var i in topN){
                var pair = topN[i]
                var tag = pair[0]
                hash[tag] = (hash[tag] || 0) + pair[1]
            }
        }
    }
    var all = []
    for (var key in hash)
        all.push([key, hash[key]])
    return all.sort(function(one, other){
        return other[1] - one[1]
    }).slice(0, 3)
}</code></pre>
<p>The approach I took was different one from the one from the example page, but I believe it to be the more <i>correct</i> one: rather than returning the results keyed by the tag in the <i>map</i> step, I would emit every occurrence of every tag instead. Then in the <i>reduce</i> step, I would calculate the aggregation values grouped by tag using a hash, transform it into an array, sort it, and choose the top 3. For the rereduce case, I would combine a set of top 3 choices and then again pick the top 3 among them.</p></content>
        </entry>,<entry>
            <title>Adding Real Properties to FABridge</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/10/06/adding-real-properties-to">
            <updated>2009-10-06T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/10/06/adding-real-properties-to</li>
            <content type="text">
<p>Although <a href="http://tobyho.com/Using_the_Flex-Ajax_Bridge">FABridge is a nice tool</a>, it's got its shortcomings. I am going to fix one of them now, namely that it doesn't give you real properties, but uses Java's getter setter convention instead. In 3 out 4 browsers, the <i>__defineSetter__</i> and <i>__defineGetter__</i> methods are already usable, so why not take advantage? It's really easy as it turned out. Change the <i>addPropertyToType</i> method to:</p>
<pre><code>    addPropertyToType: function(ty, propName)
    {
        var c = propName.charAt(0);
        var setterName;
        var getterName;
        if(c &gt;= "a" && c &lt;= "z")
        {
            getterName = "get" + c.toUpperCase() + propName.substr(1);
            setterName = "set" + c.toUpperCase() + propName.substr(1);
        }
        else
        {
            getterName = "get" + propName;
            setterName = "set" + propName;
        }
        function setter(val)
        {
            this.bridge.setPropertyInAS(this.fb_instance_id, propName, val);
        }
        ty[setterName] = setter;
        function getter()
        {
            return this.bridge.deserialize(this.bridge.getPropertyFromAS(this.fb_instance_id, propName));
        }
        ty[getterName] = getter;
        if (ty.__defineGetter__)
            ty.__defineGetter__(propName, getter);
        if (ty.__defineSetter__)
            ty.__defineSetter__(propName, setter);
    },
</code></pre>
<p> And..., <i>voila</i>! You got yourself real properties. Now instead of writing:</p>
<pre><code>app.getTextBox()</code></pre>
<p>You will be much happier writting:</p>
<pre><code>app.textBox</code></pre>
<p>On non-sucky browsers that is.</p></content>
        </entry>,<entry>
            <title>Vector for ActionScript3</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/10/02/vector-for-actionscript3">
            <updated>2009-10-02T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/10/02/vector-for-actionscript3</li>
            <content type="text">
<p>I just <a href="http://stackoverflow.com/questions/1510231/how-to-use-vector-in-flex">learned about</a> <a href="http://livedocs.adobe.com/flex/3/langref/Vector.html">Vector</a>, it's a typed Array for Actionscript 3, like generics in Java or C#. However, in Actionscript 3, Vector is a one-off: it's the only class that uses the generics syntax, and developers cannot use generics in their own classes. Nevertheless, Vector gives a type-safe alternative to Array and promises big performance gains. Given that it can also <a href="http://stackoverflow.com/questions/1510231/how-to-use-vector-in-flex/1510568#1510568">give the type</a> of the containing elements at runtime, I can use it now to drive JSON deserialization into objects too.</p></content>
        </entry>,<entry>
            <title>Typed Deserialization with JSON</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/10/02/typed-deserialization-with">
            <updated>2009-10-02T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/10/02/typed-deserialization-with</li>
            <content type="text">
<p>JSON is nice, but if you use it extensively, you go against the OO style of object modeling, which says that behaviors should be attached to objects themselves. Even if you are not an OO bigot, the OO way is sometimes just far more convenient and structures your code better, IMHO. Given my past work with <a href="http://jyaml.sourceforge.net/">JYaml</a>, it can't be that hard to read in some JSON and directly deserialize it into a typed object can it?</p>
<p>Say you have a <i>Person</i> type:<br></p>
<div>
	<pre><code>function Person(name){</code></pre>
	<pre><code>    this.name = name</code></pre>
	<pre><code>}</code></pre>
	<pre><code>Person.prototype.sayHi = function(){</code></pre>
	<pre><code>    return "Hi! I am " + this.name</code></pre>
	<pre><code>}</code></pre>
	<div>You create an instance called <i>tommy</i>:</div>
	<pre><code>&gt; tommy = new Person('Tommy')</code></pre>
	<pre><code>&gt; tommy.sayHi()</code></pre>
	<pre><code>Hi! I am Tommy</code></pre>
	<div>With a little magic from a <i>toJson</i> function that I whipped up:</div>
	<pre><code>&gt; tommyJson = toJson(tommy)</code></pre>
	<pre><code>&gt; tommyJson</code></pre>
	<pre><code>{__proto__: Person.prototype, name: "Tommy"}</code></pre>
	<div><i>tommyJson</i> is now a string representation of <i>tommy</i>. You can see that it sets the special <i>__proto__</i> link to <i>Person.prototype</i>, which will do its magic when it's deserialized. Now let's deserialize it back:</div>
	<pre><code>&gt; tommyCopy = fromJson(tommyJson)&gt; tommyCopy.sayHi()Hi! I am Tommy&gt; tommyCopy.constructorfunction Person(name){    this.name = name;}&gt; tommyCopy === tommyfalse</code></pre>
	<div>As you can see, the deserialized object <i>tommyCopy </i>is not just a plain object literal, but has all of the behaviors of <i>Person</i>.</div>
	<div>
		<div>The code for <i>toJson</i> and <i>fromJson</i> is so small I don't even bother putting it on github, so I'll just post it here(You may need <a href="http://github.com/airportyh/ecma5array">ecma5array</a> if you want to run it on a sucky browser):</div>
		<pre><code>function toJson(obj){
		    function keys(o){
		        var ret = []
		        for (var key in o){
		            var val = o[key]
		            if (o.hasOwnProperty(key)) // exclude attributes in the parent
		                ret.push(key)
		        }
		        return ret
		    }
		    function quote(str){
		        return '"' + str + '"'
		    }
		    if (obj === null || obj === undefined)
		        return String(obj)
		    else if (obj.constructor === String)
		        return quote(obj)
		    else if (obj.constructor === Array)
		        return '[' + obj.map(toJson).join(', ') + ']'
		    else if (obj.constructor === Object)
		        return '{' + keys(obj).map(function(key){return key + ': ' + toJson(obj[key])}).join(', ') + '}'
		    else if (obj.constructor && obj.constructor.name)
		        return '{' + ['__proto__: ' + obj.constructor.name + '.prototype'].concat(
		            keys(obj).map(function(key){return key + ': ' + toJson(obj[key])})).join(', ') + '}'
		    else
		        return String(obj)
		}
		function fromJson(str){
		    return eval('(' + str + ')')
		}</code></pre>
	</div>
</div></content>
        </entry>,<entry>
            <title>Google Chrome Frame to the Rescue!</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/09/25/google-chrome-frame-to-the">
            <updated>2009-09-25T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/09/25/google-chrome-frame-to-the</li>
            <content type="text">
<p><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=266136">Bruce Eckel's prediction</a> came true! Chrome is now an <a href="http://code.google.com/chrome/chromeframe/">IE plugin</a>! There's a lot of talk about it at the moment about security concerns and accessibility, but both of these discussions miss the point. The real story here, is what Google Chrome Frame means for <i>developers</i>. Web developers like me have longed for the following:</p>
<div>
	<ul>
		<li>CSS 3 support</li>
	</ul>
	<div>
		<ul>
			<li>Canvas</li>
			<li>SVG</li>
			<li>Properties and other advanced features in Javascript</li>
			<li>HTML 5</li>
		</ul>
		<ul>
			<li>Not having to develop for a browser that sucks</li>
		</ul>
		<div>Now, rather than resorting to <a href="http://www.explorerdestroyer.com/">campaigns</a> <a href="http://ie6update.com/">like</a> <a href="http://www.end6.org/">these</a>, you can instead ask your users to install a plugin - much like with the <a href="http://get.adobe.com/flashplayer/">Flash plugin</a> - that will essentially run Chrome's engine inside IE 6, 7, or 8, and give you all of the benefits in the list above. The average end-user will hardly notice the difference because IE's interface will stay the same, the only things that are different are within the content pane of the browser. Given Flash's <a href="http://www.adobe.com/products/player_census/flashplayer/version_penetration.html">ubiquity</a> with its browser plugin install model, it is certainly not unconceivable for Chrome Frame to become wide spread among IE users. Go back a few years: <i>How did Flash gain this level of penetration in the first place?</i> Answer: <i>YouTube</i>! Who owns YouTube now? <i>Oops!</i> Yes, Google could totally drop Flash from YouTube and <a href="http://www.w3schools.com/tags/html5_video.asp">go HTML 5 only</a>. I doubt they would do that in reality, but that card is there for them, if they want to play it. The more probable Google strategy will be <a href="http://wave.google.com/">Wave</a>, which, I gather from Google's positioning, will <i>definitely not</i> support IE natively. So, if Wave hits a home run and becomes the <i>next big thing</i>, Chrome Frame - and thus HTML 5 - will become a very viable RIA environment. Heck, some other company could very well come into the picture at this point and develop a killer app in HTML 5 that pushes it over the top also. When we get to that point - and here's me praying - it's bye bye to developing for the IE platform, <i>forever</i>!</div>
	</div>
</div></content>
        </entry>,<entry>
            <title>HTTP Server in 5 Lines With Webrick</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/09/16/http-server-in-5-lines-with">
            <updated>2009-09-16T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/09/16/http-server-in-5-lines-with</li>
            <content type="text">
<p>Usually when I am prototyping a web UI - either in Javascript or Flex, I would just write a static html, because that's the simplest thing that works. But, once in a while, it doesn't work because of the security restrictions that the browser imposes on local files. Maybe you want to use ajax calls(which is sometimes problematic on IE), trying to use the google maps api, or the FABridge, whatever the reason may be. Well, you can get around this problem easily using this ruby script:</p>
<pre><code>require 'webrick'
server = WEBrick::HTTPServer.new :Port =&gt; 1234
server.mount "/", WEBrick::HTTPServlet::FileHandler, './'
trap('INT') { server.stop }
server.start
</code></pre>
<p>This runs a web server at <a href="http://localhost:1234/">http://localhost:1234/</a> which mounts the top level directory to your current directory.</p>
<p><i>Update: Oops, it's not exactly that easy after all. In order to prevent caching - which you will want to do if you are doing development - you will want to write an extra class. The modified script:</i></p>
<pre><code>require 'webrick'
class NonCachingFileHandler &lt; WEBrick::HTTPServlet::FileHandler
  def prevent_caching(res)
    res['ETag']          = nil
    res['Last-Modified'] = Time.now + 100**4
    res['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'
    res['Pragma']        = 'no-cache'
    res['Expires']       = Time.now - 100**4
  end
  
  def do_GET(req, res)
    super
    prevent_caching(res)
  end

end

server = WEBrick::HTTPServer.new :Port =&gt; 1234
server.mount "/", NonCachingFileHandler , './'
trap('INT') { server.stop }
server.start
</code></pre>
<p><i>Not 5 lines anymore, bummer! The code for NonCachingFileHandler was stolen  from unittest_js.</i></p></content>
        </entry>,<entry>
            <title>Great Overview of GTD by Boag</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/08/25/great-overview-of-gtd-by-boag">
            <updated>2009-08-25T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/08/25/great-overview-of-gtd-by-boag</li>
            <content type="text">
</content>
        </entry>,<entry>
            <title>I Learned Something About Scala</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/08/11/i-learned-something-about">
            <updated>2009-08-11T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/08/11/i-learned-something-about</li>
            <content type="text">
<p>I am trying to learn Scala. <a href="http://stackoverflow.com/questions/1252915/scala-how-to-define-generic-function-parameters">Here's me trying</a>. Don't forget to look for my write up at the end where I answer my own question.</p></content>
        </entry>,<entry>
            <title>The New-Found-Love for Dynamic Languages</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/08/04/the-new-found-love-for-dynamic">
            <updated>2009-08-04T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/08/04/the-new-found-love-for-dynamic</li>
            <content type="text">
<p><a href="http://stackoverflow.com/questions/42934/whats-with-the-love-of-dynamic-languages/1228619#1228619">My response to a SO question.</a><br></p></content>
        </entry>,<entry>
            <title>Describing "with"</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/07/31/describing-"with"">
            <updated>2009-07-31T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/07/31/describing-"with"</li>
            <content type="text">
<p>The <i>with</i> statement of javascript got a lot of hate from Douglas Crockford in his famous Javascript lecture videos, as well as in <a href="http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/">this blog post</a>. Now it gets hated on by the Ecmascript 5 spec too, where its use is disallowed in strict mode. The general consensus is that, you should never use <i>with</i>, ever.<br></p>
<p>But, it is so very tempting - once in a while - to make use of this forbidden feature. So I decided to write a spec for <i>with</i> which will uncover exactly what all the pitfalls of using it are. Then, you will decide for yourself whether you want to use it or not. Without further ado(comments are inlined with the code):</p>
<pre><code>describe('with')
  .beforeEach(function(){
    this.name = 'Houston'
    this.age = 18
    this.eyes = null
    this.lips = undefined
    window.name = "window's name"
  })
  .should('get attr', function(){
    with(this){
      expect(name).toBe('Houston')
      expect(age).toBe(18)
      expect(eyes).toBe(null)
      expect(lips).toBe(undefined)
    }
  })
  .should('raise if doesn\'t exist', function(){
    with(this){
      expect(function(){namee}).toRaise()
      this.namee // but write "this." and doesn't raise
    }
  })
  .should('reference variable from outside with scope', function(){
    var hair = 'dark'
    with(this){
      expect(hair).toBe('dark')
    }
  })
  .should('do assignment', function(){
    with(this){
      name = 'Kenny'
    }
    expect(this.name).toBe('Kenny')
  })
  .should('not do assignment if attr does exist yet', function(){
    /*
    when you make an assignment to an attribute of the object in 
    question(the one you are working *with*), that attribute must 
    already exist(been assigned some value), otherwise, it will 
    behave like it would outside the with scope and assign the 
    attribute to the window object.
    */
    with(this){
      hair = 'dark'
    }
    expect(this.hair).toBe(undefined)
    expect(hair).toBe('dark')
    expect(window.hair).toBe('dark')
  })
  .should('do assignment if attr is defined to be undefined', function(){
    /*
    I had always thought that assigning undefined to an attribute 
    is the same as it having never been assigned a value at all. 
    I was wrong. But deleting the attribute will revert it to the 
    state of non-existence, as the next test shows.
    */
    with(this){
      lips = 'pink'
    }
    expect(this.lips).toBe('pink')
  })
  .should('not do assignment if attr has been ' +
    'deleted(deleting makes it "not exist")', function(){
    /*
    Deleting the attribute will revert it to the 
    state of non-existence, which makes unassignable from within
    the 'with' scope again
    */
    delete this.name
    with(this){
      name = 'tony' // this sets window.name to 'tony'
    }
    expect(this.name).toBe(undefined)
    expect(window.name).toBe('tony')
  })
  .should('delete', function(){
    with(this){
      delete name
    }
    expect(this.name).toBe(undefined)
  })
  .should('deleting makes the attribute go away, and you are' +
    'again accessing window\'s attrs', function(){
    with(this){
      expect(name).toBe('Houston')
      delete name
      expect(name).toBe("window's name")
    }
  })
  .should('be silent if deleting non-existing attr', function(){
    with(this){
      delete hands
    }
    expect(this.hands).toBe(undefined)
  })
  .should('do assignment if attr is null', function(){
    with(this){
      eyes = 'brown'
    }
    expect(this.eyes).toBe('brown')
  })
  .should('do assignment using this if attr does not exist', function(){
    with(this){
      this.hair = 'dark'
    }
    expect(this.hair).toBe('dark')
  })
  .should('var outside with scope does not override', function(){
    /*
    variables defined outside the with scope has lower precedence 
    than attributes of the object in question.
    */
    var name = 'Jen'
    with(this){
      expect(name).toBe('Houston')
    }
  })
  .should('var outside with scope does not override (2)', function(){
    this.window = 'Not window'
    with(this){
      expect(window).toBe('Not window')
    }
  })
  .should('var inside scope overrides', function(){
    with(this){
      var name = 'Jen'
      expect(name).toBe('Jen')
    }
  })
  .should('have no lexical scoping', function(){
    var instrument = 'sax'
    with(this){
      var instrument = 'trumpet'
      expect(instrument).toBe('trumpet')
    }
    expect(instrument).toBe('trumpet')
  })
  .should('erase vars after the with scope closes', function(){
    var name = 'blah'
    with(this){
      expect(name).toBe('Houston')
    }
    expect(name).toBe('blah')
  })
</code></pre>
<p>Full source is at <a href="http://github.com/airportyh/misc/tree/834aa657fd64eb7a05e4d5fa557628d6b1ac7168/with">github</a>.</p></content>
        </entry>,<entry>
            <title>ThinAir: Create DOM Elements Without Sweating</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/07/30/thinair:-create-dom-elements">
            <updated>2009-07-30T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/07/30/thinair:-create-dom-elements</li>
            <content type="text">
<p><i>Announcing yet another tiny javascript library: <a href="http://github.com/airportyh/thinair/tree/master">ThinAir</a>.</i></p>
<p>ThinAir is a DSL for creating DOM elements on-the-fly. Example, if you want to create a text input:</p>
<pre><code>var elm = thinair.input({type: 'text', name: 'name', value: 'Bobby'})
</code></pre>
<p>But, having to write "thinair." everywhere makes the code pretty cluttered as soon as you start doing some complicated stuff. One way to avoid having to write the namespace is using the <i>with</i> keyword:</p>
<pre><code>with(thinair){  var elm = input({type: 'text', name: 'name', value: 'Bobby'})}</code></pre>
<p>Within the scope of the <i>with</i> statement you can use all the tag-named methods unadorned. Now, let's try something else... A paragraph containing a checkbox and a label? You got it:</p>
<pre><code>var elm =
  p(
    input({type: 'checkbox', name: 'checkme'}),
    label('Check me, please!')
  )</code></pre>
<p>At this point <i>elm</i> is a jQuery wrapped element, so you can add it to the DOM by using one of <a href="http://docs.jquery.com/Manipulation">jQuery's standard ways of inserting it</a>, for example:</p>
<pre><code>$(document.body).append(elm)</code></pre>
<p>To generate a unordered list out of an array of elements:</p>
<pre><code>ul(['bobby', 'timmy', 'barry'].map(function(name){
  return li(name)
})</code></pre>
<p>A more elaborate example is <a href="http://github.com/airportyh/thinair/tree/8907472195f9e457264a7d852cc09c180478987c/examples">here</a>. That's really about all I wanted to show. The code/project page is on <a href="http://github.com/airportyh/thinair/tree/master">github</a>.</p></content>
        </entry>,<entry>
            <title>MacFusion and MacFUSE: ftp mounts on Mac</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/07/29/macfusion-and-macfuse:-ftp">
            <updated>2009-07-29T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/07/29/macfusion-and-macfuse:-ftp</li>
            <content type="text">
<p>I you need an easy and <i>free</i> way to mount an ftp or ssh-fs service as a drive on your filesystem on Mac, <a href="http://www.macfusionapp.org/">MacFusion</a> is the way to go. It is free and open source, and requires another piece of software: MacFUSE, which is also free and open source.</p></content>
        </entry>,<entry>
            <title>Use grep with tail</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/07/28/use-grep-with-tail">
            <updated>2009-07-28T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/07/28/use-grep-with-tail</li>
            <content type="text">
<p>When debugging, if you are tailing a log file that has way too much output, don't forget about the trusty grep:</p>
<pre><code>tail -f log.txt|grep "stuff I care about"</code></pre>
<p>or:</p>
<pre><code>tail -f log.txt|grep -v "stuff I don't care about"</code></pre></content>
        </entry>,<entry>
            <title>First Encounter with IE8</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/07/19/first-encounter-with-ie8">
            <updated>2009-07-19T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/07/19/first-encounter-with-ie8</li>
            <content type="text">
<p>If you are like me, you have been just ignoring IE8 all this time. What you didn't know is that, chances are, your app(or javascript library) doesn't work on it. Sure, I had heard about how it breaks sites all over the place and they worked around it by using an database of sites for which they override the browser to use the IE7 compatibility mode. That's right, before rendering any web page, IE8 actually makes a request back to Microsoft headquarters to find out whether it should render the page in regular mode, or IE7 compatibility mode. Wow, kill me now...</p>
<p>Anyway, so I didn't think too much of that. Until today, when I had the pleasure of "porting" some code to work in IE8. To be fair, this app hasn't been tested much on IE period, before today. So, here's me dutifully reporting my findings.</p>
<p>First, of all, if you are using a non-core<i>(unlike jQuery, prototype, mootools, etc., which would be core)</i> third party Javascript library, it probably does not work with IE8. The Google Visualization API is one example. Because of this, we ended up explicitly telling it to use IE7 compat mode. The way you do this is to put this meta tag inside of your <i><head></i> element:</p>
<pre><code>&lt;meta http-equiv="X-UA-Compatible" content="IE=7" /&gt;
</code></pre>
<p>Second, make sure you specify the doctype. We used html 4.01 strict. If you don't specify it, standard things like transparencies won't work. This should be obvious.</p>
<p>Third, even if you do all the <i>right</i> things, transparencies still may not work... See <a href="http://realtech.burningbird.net/graphics/css/opacity-returns-ie8">this gem</a> to read all about it. In my situation, I had some semi-transparent pngs inside some div that had its opacity value set. It turns out that in IE8, this causes the png transparency to not work <i>at all</i>. You could fix it the hard way in javascript as described in <a href="http://realtech.burningbird.net/graphics/css/opacity-returns-ie8">Bb's article</a>, or you could just use IE7 compat mode, which is what I did, sigh...</p>
<p>One more thing that was interesting was that forgetting to write <i>var</i> in front of a new variable caused an error to be throw. That looks a lot like <a href="http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/">strict mode </a>behavior. I'll have to take a second look at this to verify, but it is worth mentioning.</p>
<p>Oh, almost forgot: on the positive side, MS did a great job with the built-in developer tool, which opens in a separate window via F12. I used it to inspect the DOM and change css attributes on the fly. I am sure it can do more that I haven't tried. Kudos to the IE team for that.</p></content>
        </entry>,<entry>
            <title>Radio Buttons Simplified</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/07/19/radio-buttons-simplified">
            <updated>2009-07-19T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/07/19/radio-buttons-simplified</li>
            <content type="text">
<p>Working with radio buttons in javascript has always been a pain, even with the help of jQuery. For example, if you have something like:</p>
<pre><code>&lt;label&gt;Yes: &lt;/label&gt;
&lt;input type="radio" name="yes_no" value="yes"&gt;&lt;br&gt;
&lt;label&gt;No: &lt;/label&gt;
&lt;input type="radio" name="yes_no" value="no"&gt;</code></pre>
<p>First, it is tedious, bordering non-trivial to get the get the current value of this radio selection group: <i>is it yes or no?</i></p>
<p>Second, it is also tedious, bordering non-trivial to listen for changes to the value, especially given the different behaviors of different browsers(<i>IE does not emit a change event when you click on a radio button to change it until you blur from it</i>).</p>
<p>I wrote a tiny jQuery library to make this easier, with which you can do:</p>
<pre><code>&gt; $.radio('yes_no').val()
'yes'</code></pre>
<p>to get the selected value, and to listen for changes:</p>
<pre><code>&gt; $.radio('yes_no').change(function(ui){
    console.log('yes_no value changed to ' + ui.val());
})</code></pre>
<p>That's as simple as it gets. Code is as usual, on <a href="http://github.com/airportyh/jRadio/tree/master">github</a>.</p></content>
        </entry>,<entry>
            <title>ColorCode Lineup - A Color-Code Scheme Editor</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/07/11/colorcode-lineup---a-color">
            <updated>2009-07-11T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/07/11/colorcode-lineup---a-color</li>
            <content type="text">
<p>For my work I had the need to dynamically color code many objects, and I have to make sure that all the colors used are both distinguishable and the text inside them legible. So, I whipped up a little jQuery and built a tool for making and editing color-code schemes: <a href="http://tobyho.com/ColorCode-Lineup/app.html">ColorCode Lineup</a>. You can <i>view source</i> to see the code, but it's also hosted on <a href="http://github.com/airportyh/ColorCode-Lineup/tree/master">github</a>.</p></content>
        </entry>,<entry>
            <title>The New ECMAScript5 Array Methods - NOW</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/07/06/the-new-ecmascript5-array">
            <updated>2009-07-06T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/07/06/the-new-ecmascript5-array</li>
            <content type="text">
<p>I am more or less a convert from Prototype.js to jQuery. But the thing I found missing the most in jQuery is the functional style Array methods that are provided in <a href="http://www.prototypejs.org/api/enumerable">Prototype.js</a>. The methods that I normally use are simple, and I have been just recreating them myself in my projects: like <i>collect</i>, <i>select</i>, <i>each</i>, etc. But it's getting a bit tedious to do this for every new project and so I want a very lightweight library that just has these array methods. However, now that ECMAScript 5 is coming close to fruition, it makes a lot sense to use their method names and semantics. I have found that Safari, Firefox, and Flex all provide these methods already, so why not just jump on the bandwagon?</p>
<p>So, I have implemented these methods for environments that do not have them, as best I can to the <a href="http://www.ecma-international.org/publications/files/drafts/tc39-2009-025.pdf">spec</a>. The methods are <i>forEach</i>, <i>reduce</i>, <i>reduceRight</i>, <i>map</i>, <i>filter</i>, <i>every</i>, <i>some</i>, <i>indexOf</i>, and <i>lastIndexOf.</i></p>
<p><i><br></i></p>
<p>The code and more info is at github and this project shall be named: <a href="http://github.com/airportyh/ecma5array/tree/master">ecma5array</a>. Only less than 70 LOC.</p>
<p><i><br></i></p></content>
        </entry>,<entry>
            <title>Get Argumentative with Javascript</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/06/30/get-argumentative-with">
            <updated>2009-06-30T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/06/30/get-argumentative-with</li>
            <content type="text">
<p>When I looked at the Google Maps API for Javascript, I couldn't help but notice that all the functions in the API Reference look kinda Pythonic. Functions call be call with a positional argument list like normal, i.e.:</p>
<pre><code>new GMap2(mynode, myopts)</code></pre>
<p>or by name with an object literal:</p>
<pre><code>new GMap2({node: mynode, opts: myopts})</code></pre>
<p>Moreover, arguments can be optional, and they are denoted in the doc with a <i>?</i> at the end. Finally, the type of each argument is specified.</p>
<p>Here is an example of their API:</p>
<pre><code>GMap2(container:Node, opts?:GMapOptions)
</code></pre>
<p>I thought: <i>How cool is this!!?? I want this!!</i> But, as the Maps API is proprietary, I couldn't get hold of their source. So, it was time for a little hacking...</p>
<p>My immediate goals were: <i>argument validation</i>, <i>named argument passing</i>, <i>and optional arguments.</i> Now I have a prototype with these three things working.</p>
<div>
	<b><i>Argument Validation</i></b>
</div>
<p>Argument validation in my terms means checking the input arguments to a function when it is called to see if they are valid. The most basic of these checks is whether the number of arguments is correct. Example, we start with a simple <i>add</i> function:</p>
<pre><code>function add(one, other){
  return one + other;
}</code></pre>
<p>Then we <i>enhance</i> it by wrapping in with the $f function:</p>
<pre><code>add = $f(add);</code></pre>
<p>The new enhanced add function now will require the argument list to match up with what is expected:</p>
<pre><code>&gt; add(1,1)
  2
&gt; add(1)
  Error: Argument 'other' of function add(one, other) was not specified.
&gt; add(1,2,3)
  Error: function add(one, other) expected 2 arguments but got 3: (1, 2, 3).
</code></pre>
<div>
	<b><i>Named Argument Passing</i></b>
</div>
<p>Named argument passing is something that Python programmers enjoy, but in Javascript you can simulate it using map literals. For example, given the add function defined above, you can now also write:</p>
<pre><code>&gt; add({one: 1, other: 2});
  3</code></pre>
<p>The order does not matter because it is a map, so the above is equivalent to:</p>
<pre><code>&gt; add({other: 2, one: 1});

  3</code></pre>
<p>You can also mix positional and named arguments just like in Python:</p>
<pre><code>&gt; add(1, {other: 2});
  3</code></pre>
<p><i><b>Optional Arguments</b></i></p>
<p>Optional arguments is another great Python feature. It is really the feature that makes named argument passing worthwhile. In Python we have a nice syntax to specify the default value for an optional argument:</p>
<pre><code>def f(x=0):
  return x * 2</code></pre>
<p>In Javascript, not so lucky. I had to resort to this:</p>
<pre><code>f = $f(
  {x: 0},
  function f(x){
    return x * 2;
  }
)</code></pre>
<p>Not so bad? Maybe? I am trying to make it look like a decorator/annotation. So, with this code, you can do:</p>
<pre><code>&gt; f()
  0</code></pre>
<p>Just what you'd expect.</p>
<p>The combination of named argument passing and optional arguments enable very concise code in some situations. Example, let's say you have a function that generates an html input element given a bunch of parameters:</p>
<pre><code>function input(type, name, value, classes){
  return '&lt;input \
    type="' + type + '" \
    name="' + name + '" \
    value="' + value + '" \
    class="' + classes.join(' ') + '"&gt;';
}
</code></pre>
<p>In this case, <i>type</i> and <i>name</i> are required. <i>V</i><i>alue</i> is required by the spec but we can just default it to ''. <i>Classes</i> is optional and we'll just default it to [] to avoid a check for null.</p>
<p>So the code to do that is:</p>
<pre><code>input = $f({value: '', classes: []}, input)
</code></pre>
<p>And now you call call the function in these variety of ways:</p>
<pre><code>&gt; input('text', 'age')
  &lt;input     type="text"     name="age"     value=""     class=""&gt;
&gt; input({type: 'text', name: 'age'})
  &lt;input     type="text"     name="age"     value=""     class=""&gt;
&gt; input({type: 'text', name: 'age', classes:['text', 'age']})
  &lt;input     type="text"     name="age"     value=""     class="text age"&gt;
</code></pre>
<p>Nice!</p>
<p>The code for this prototype is as usual <a href="http://github.com/airportyh/misc/tree/557762272d670370ed172f75f0e041c3a67b2d38/argumentative">on github</a>. The next on my todo list is to implement variable length argument list and extra keyword argument lists. So stay tuned.</p></content>
        </entry>,<entry>
            <title>Oracle, Python, Mac</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/06/24/oracle,-python,-mac">
            <updated>2009-06-24T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/06/24/oracle,-python,-mac</li>
            <content type="text">
<p>I pieced together the instructions for <a href="http://pedro.emanuel.familiasalgado.org/?p=103">a couple</a> of <a href="http://www.pixellatedvisions.com/2009/03/25/rails-on-oracle-part-1-installing-the-oracle-instant-client-on-mac-os-x">blog posts</a>. The Pixellated Visions one ended up being more helpful.</p>
<div>
	<div><i>Update: Actually, Lorcan's Wiki has the best information on getting </i><a href="http://lorcancoyle.org/wiki/public/cxoracle"><i>Python to work with Oracle on the Mac</i></a><i>.</i></div>
</div></content>
        </entry>,<entry>
            <title>Time Capsule Printer Sharing on Windows</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/06/22/time-capsule-printer-sharing">
            <updated>2009-06-22T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/06/22/time-capsule-printer-sharing</li>
            <content type="text">
<p>On your Windows PC, go download <a href="http://support.apple.com/downloads/Bonjour_for_Windows">Bonjour for Windows</a>. Run the setup program to install it. When finished, it should add a desktop icon called <i>Bonjour Printer Wizard</i>, run that. It should walk you through the rest.</p></content>
        </entry>,<entry>
            <title>JSON with Special Characters fails in IE</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/05/27/json-with-special-characters">
            <updated>2009-05-27T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/05/27/json-with-special-characters</li>
            <content type="text">
<p>If you try to eval a JSON string that has special characters in it(non-ascii, or chr > 127), it will error out. The other browsers work fine.</p></content>
        </entry>,<entry>
            <title>Trying to Index Strings in IE</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/05/26/trying-to-index-strings-in-ie">
            <updated>2009-05-26T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/05/26/trying-to-index-strings-in-ie</li>
            <content type="text">
<pre><code>'abc'[0]
</code></pre>
<p>gets you <i>undefined</i> in IE. The correct way is to do 'abc'.charAt(0).</p></content>
        </entry>,<entry>
            <title>Prototype Inheritence in Python</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/05/23/prototype-inheritence-in">
            <updated>2009-05-23T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/05/23/prototype-inheritence-in</li>
            <content type="text">
<p><span>One of Toby's favorite pastimes is to take concepts from one language and realize it in another.</span> <span>In this episode: Toby implements Javascript-style prototype inheritence in Python.</span></p>
<p><span><br></span></p>
<p>One thing that is super cool about Javascript is the fact that objects are just maps. Not only can you add attributes dynamically at any point, you can also add methods dynamically. In Python, you can add methods dynamically, but normally you'd have to add it into the class. But there are cases when you don't want to bother making a class. This inspired me to see how far I can go in making Python behave more like Javascript.</p>
<h2>Introducing prototype.py<br></h2>
<p>prototype.py lets you write code in Python with Javascript-style prototype inheritence semantics. If you are not familiar with prototype inheritence, just read on for now. I will link to some resources at the end. Now, let's see how to use this bad boy. First you import the module:</p>
<pre><code>&gt;&gt;&gt; from prototype import *</code></pre>
<p>To create a <span>constructor(we don't really have classes anymore)</span>, you write a function with the <span>@constructor</span> decorator:</p>
<pre><code>&gt;&gt;&gt; @constructor
... def Person(this, first, last):
...   this.firstName = first
...   this.lastName = last
...
&gt;&gt;&gt; Person
&lt;constructor 'Person'&gt;
</code></pre>
<p>I am going to use <span>this</span> rather than <span>self</span> and <span>camelCase</span> rather than <span>under_scores</span> for prototype-style code, because, well...Dorothy, we are not in Kansas anymore.</p>
<p>Now you can do:</p>
<pre><code>&gt;&gt;&gt; bird = Person('Charlie', 'Parker')
&gt;&gt;&gt; bird.firstName
'Charlie'
&gt;&gt;&gt; bird.lastName
'Parker'
</code></pre>
<p>You can add attributes to the object just like in normal Python. But unlike in normal Python, which would raise an <span>AttributeError</span> when trying to access non-existent attributes, in prototype-land it merely returns None:</p>
<pre><code>&gt;&gt;&gt; print bird.age
None</code></pre>
<p>You can dynamically add a method to the instance just by tagging on a function:</p>
<pre><code>&gt;&gt;&gt; def sing(this):
...   print '%s sings!!' % this.lastName
...
&gt;&gt;&gt; bird.sing = sing
&gt;&gt;&gt; bird.sing()
Parker sings!!
</code></pre>
<p>This affects only the <span>bird</span> instance. If you want the method to be added to all instances of <span>Person</span> however, you can add it to the <span>prototype</span> of <span>Person</span>.</p>
<pre><code>&gt;&gt;&gt; Person.prototype.sing = sing
&gt;&gt;&gt; monk = Person('Thelonious', 'Monk')
&gt;&gt;&gt; monk.sing()
Monk sings!!</code></pre>
<p>This works because <span>Person.prototype</span> is the <span>prototype</span> of the <span>monk</span> instance. In code, this means:</p>
<pre><code>&gt;&gt;&gt; monk.__proto__ == Person.prototype
True</code></pre>
<p>When the <span>sing</span> attribute is not found on the <span>monk</span> instance itself, it will follow the <span>__proto__</span> reference and look it up in its<span> </span>prototype, which is also referred to as its <span>parent</span>. We can manipulate the parent link:</p>
<pre><code>&gt;&gt;&gt; monkJr = Person('T.S.', 'Monk')
&gt;&gt;&gt; monkJr.__proto__ = monk</code></pre>
<p>so that now <span>monkJr</span> inherits all of <span>monk's </span>attributes:</p>
<pre><code>&gt;&gt;&gt; monk.hair = 'black and curly'
&gt;&gt;&gt; monkJr.hair
'black and curly'</code></pre>
<p>The following are some other properties demonstrating the prototype inheritence model:</p>
<pre><code>&gt;&gt;&gt; assert monkJr.constructor == monk.constructor == Person
&gt;&gt;&gt; assert Object.prototype.constructor == Object
&gt;&gt;&gt; assert Person.prototype.constructor == Person
&gt;&gt;&gt; assert Person.prototype.__proto__ == Object.prototype</code></pre>
<p>If this seems confusing, remember that in prototype-land, there are two kinds of things: <span>constructors</span> and <span>instances</span>. The prototype of a constructor is nothing more than an instance of the type that the constructor represents. A new instance returned from calling a constructor will have its parent set to the prototype of the constructor.</p>
<h2>Things You Can't Do in Javascript, i.e. the 1+1>2 Effect<br></h2>
<p>Python is a more powerful and flexible language than Javascript, so, why am I dumbbing it down to Javascript's level? To show that I am <span>not</span> trying to do that at all, let me point out that there are at least a couple of really cool things you can do with prototype.py that you can't with Javascript, simply due to the fact that it is in Python.</p>
<p>The first thing is properties. With prototype.py, you can add properties to objects like so:</p>
<pre><code>&gt;&gt;&gt; def getName(this):
...   return '%s %s' % (this.firstName, this.lastName)
...
&gt;&gt;&gt; Person.prototype.name = property(getName)
&gt;&gt;&gt; bird.name
'Charlie Parker'
</code></pre>
<p>You can also specify setters and deleters in the way you'd expect:</p>
<pre><code>&gt;&gt;&gt; def setName(this, name):
...   first, last = name.split(' ')
...   this.firstName = first
...   this.lastName = last
...
&gt;&gt;&gt; def deleteName(this):
...   del this.firstName
...   del this.lastName
...
&gt;&gt;&gt; Person.prototype.name = property(getName, setName, deleteName)
&gt;&gt;&gt; bird.name = 'Dizzy Gillespie'
&gt;&gt;&gt; bird.name
'Dizzy Gillespie'
&gt;&gt;&gt; del bird.name
&gt;&gt;&gt; bird.name
'None None'
</code></pre>
<p>The second thing is <a href="/Parameter_List_Chaining_in_Python">named parameters, keyword parameters and optional parameters</a>. Let's just do an example with keyword parameters. Let's say I just wanted a way to easily create ad-hoc objects as key-value pairs, I could write:</p>
<pre><code>&gt;&gt;&gt; @constructor
... def Data(this, **kwargs):
...   for key in kwargs.keys():
...     setattr(this, key, kwargs[key])
...</code></pre>
<p>Which lets me write:</p>
<pre><code>&gt;&gt;&gt; project = Data(project='prototype.py', language='python')
</code></pre>
<p>But, I could also define methods and properties in this way:</p>
<pre><code>&gt;&gt;&gt; file = Data(fileName='prototype.py', fileExt=property(getExt), 
                    read=read, write=write)</code></pre>
<p><span>Sweet!</span></p>
<h2>A Note About the Implementation<br></h2>
<p>The implementation of prototype.py is only about 60 lines of Python at time of writing, would have gone down to 40 without property support. The code can be found <a href="http://github.com/airportyh/misc/tree/86d360ef5b449f4d2ceb795fbf6015341a82d491/prototype.py">here.</a> </p>
<p>A big discovery that enabled me to do this was the <a href="http://docs.python.org/library/new.html">new</a> module. It allowed me to take a function and make it into an instance method by binding it to an object:</p>
<pre><code>method = new.instancemethod(function, object)
</code></pre>
<p>Another note is that I made the design decision that for methods, I chose to store the unbound function rather than the bound method in the <span>__dict__</span> of the object. I would then bind the function on the fly when it's asked for. This made it very easily to inherit methods because you don't have to worry that the method is really bound to the parent rather than the instance in question.</p>
<h2>Further Reading About Prototype Inheritence<br></h2>
<p>If you want to learn more about prototype inheritence, try:</p>
<div>
	<ul>
		<li><a href="http://mckoss.com/jscript/object.htm">Mike Koss' article</a><br></li>
		<li>the <a href="http://en.wikipedia.org/wiki/Prototype-based_programming">Wikipedia article</a></li>
		<li>my short post trying to <a href="/2008/12/08/dissecting-the-prototype-chain/">Dissect the Prototype Chaining</a></li>
		<li>or if you have a lot of time, <a href="http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html">this lengthy essay from Stevey.</a> <br></li>
	</ul>
</div></content>
        </entry>,<entry>
            <title>Null in 10 Languages</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/05/11/null-in-10-languages">
            <updated>2009-05-11T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/05/11/null-in-10-languages</li>
            <content type="text">
<ul>
	<li>Java, Javascript, C#: null</li>
	<li>Ruby, Smalltalk, Lisp, OCaml: nil</li>
	<li>Lisp: ()</li>
	<li>Python: None</li>
	<li>Haskell: Nothing</li>
	<li>C: 0</li>
</ul></content>
        </entry>,<entry>
            <title>Modifying Core Types in ActionScript 3 Using the Prototype Object</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/05/02/modifying-core-types-in">
            <updated>2009-05-02T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/05/02/modifying-core-types-in</li>
            <content type="text">
<p>ActionScript 3 has a Javascript lineage. It was essentially a fork of Ecmascript. Plus, the Adobe team has worked hard on making the language a proper superset of the Ecmascript specification. This is why although ActionScript 3 was a major architechtural change from 2, and as a result became much more like Java than Javascript, it still has support for the <a href="Dissecting the Prototype Chaining">prototype object</a>. </p>
<p>When I learned about the prototype object, it was a fresh air from traditional class-based OOP. Studying cool libraries like <a href="http://prototypejs.org">prototype.js</a> made me realize that the prototype model makes javascript far more flexible than some other strictly class-based OO languages.</p>
<p>One of the cool things you can do with the prototype object in javascript is modify the core classes of the language, like <span>Array, String, </span>and <span>Date</span>. You can do this in ActionScript 3 too, for it conforms to Ecmascript 4. For example, let's say you want to write the <span>collect</span> function for arrays <span>a la</span> ruby. You would do:</p>
<pre><code>Array.prototype.collect = function(f){
  var ret = [];
  for each(var it in this) ret.push(f(it));
  return ret;
}</code></pre>
<p>There you see me using the nice  <span>for each</span> syntax. But, this is going to break the behavior of the array, because now the <span>collect</span> function is going to show up in the enumeration in the <span>for each</span> loops. We don't want that, so to fix that we are going to set the <span>collect</span> attribute of <span>Array.prototype</span> to not be enumerable:</p>
<pre><code>Array.prototype.setPropertyIsEnumerable('collect', false);</code></pre>
<p>This allows you to write the following code:</p>
<pre><code>[1,2,3].collect(function(i){ return i * 2; });
// result would be [2,4,6]</code></pre>
<p>It's kinda tedious to have to <span>setPropertyIsEnumerable </span>for every time we add a function to an existing type, so I wrote a convience function:<br></p>
<pre><code>function addMethodsTo(cls:Class, methods){
    for (var name:String in methods){
        cls.prototype[name] = methods[name];
        cls.prototype.setPropertyIsEnumerable(name, false);
    }
}
</code></pre>
<p>Which you can use like so:</p>
<pre><code>addMethodsTo(Array, {
    collect: function(f){
        var ret = [];
        for each(var it in this) ret.push(f(it));
        return ret;
    },
    anotherMethod: function(){
        ...
    },
    ...
});</code></pre>
<p>This is sort of like the style prototype.js uses for extending/creating classes.</p>
<h2>A Word of Caution<br></h2>
<p>Before you consider going further with this, I must advice you to think twice before using this technique(however, I hope you <span>do</span> decide to use it afterwards ;). There are several caveats:</p>
<div>
	<ol>
		<li>The prototype-based style is a second-class citizen in the world of ActionScript 3 and Flex. The Adobe team as well as the community seem to be much more committed to the class-based approach. I will describe some of the rough edges below.</li>
		<li>You will give up compile time type checking for the portions of your code that use this style.</li>
		<li>Prototype inheritence is handled by a completely different mechanism than class-based inheritence in the Flash VM and is not as performant.</li>
	</ol>
	<h2>Where to put this Code?<br></h2>
	<div>You saw the code example above, but, where do you put it? Since I decided to use a helper function(<span>addMethodsTo)</span>, the code cannot be directly pasted inside the class scope of a class unless the <span>addMethodsTo</span> function is declared to be static(you can only make a method call directly inside class scope if it is a class method). As, a general solution, I'd rather the code be portable. So it should be includable in both class and function scope, and also, I'd like it not to pollute any namespaces.</div>
	<div>My current solution is to put this bit of code inside an anonymous function which immediately gets executed:</div>
	<pre><code>// contents of includes/Array.as</code></pre>
	<pre><code>(function(){
	    include 'addMethodsTo.as';
	    addMethodsTo(Array, {
	        collect: function(f){
	            var ret = [];
	            for each(var it in this) ret.push(f(it));
	            return ret;
	        }
	    });
	})();
	</code></pre>
	<div>The <span>addMethodTo </span>function is pulled into a separate file to be easily includable else where.</div>
	<div>So, with this, I would do the following to include this Array functionality:</div>
	<pre><code>include 'includes/Array.as';</code></pre>
	<div>Head over to <a href="http://github.com/airportyh/misc/tree/aff1496c9f99ff890801e5ecacdefdbf78be1016/prototype_in_as">Github</a> for the complete structure of the files.</div>
	<div>These methods are added during runtime - at exactly the time the above line of included code is executed, and not a moment before. I like to do the include at the top level of the application, this way the entire program has immediate access to the new methods. Oh, and when I said <span>entire program</span>, I do mean the entire program - not just the files that happen to include the file. Well, this is good <span>and</span> bad. This means if you create components that use the array extensions you've created without explicitly including it(you've included it at the entry point of your program), then you have created an <span>invisible dependency</span>. If you try to take the component and use it in a different project without the array extensions, it will not work. Of course, you could also make the dependency explicit by including the file everywhere you are using them, but 1) that's kinda tedious/repetitious, and 2) there's nothing enforcing you to do this.</div>
	<h2>Pitfalls and Gotchas<br></h2>
	<div>As I mentioned, the prototype-based programming style is a second-class citizen in the ActionScript 3 world, and so, its use is not particularly well supported. First of all, the compiler does not recognize any of the methods added via the prototype mechanism, and thus cannot perform static type checking on them. But what is funny is the way the compiler copes with this - it depends...on the type in question. For Arrays, the compiler simply allows all method calls - you can call any method on an array, even if it doesn't exist, the compiler won't complain. So, for a call like:</div>
	<pre><code>[1, 2, 3].collect(...);</code></pre>
	<div>The compiler won't even say a word. But for Dates, it gives a warning message. This:</div>
	<pre><code>new Date().format()
	</code></pre>
	<div>would trigger this warning:</div>
	<pre><code>Warning: format is not a recognized method of the dynamic class Date.
	</code></pre>
	<div>But, for strings, it's a different story still:</div>
	<pre><code>'one, two, three'.csv2Array()
	</code></pre>
	<div>compiler says:</div>
	<pre><code>Error: Call to a possibly undefined method csv2Array through a </code></pre>
	<pre><code>    reference with static type String.
	</code></pre>
	<div>And the same thing with numbers:</div>
	<pre><code>(2).minutes().ago()
	</code></pre>
	<div>compiler says:</div>
	<pre><code>Error: Call to a possibly undefined method minutes through a </code></pre>
	<pre><code>    reference with static type int.
	</code></pre>
	<div>The work around for strings and numbers is to upcast it to an Object:</div>
	<pre><code>Object('one, two, three').csv2Array();
	</code></pre>
	<pre><code>Object(2).minutes().ago();
	</code></pre>
	<div>or if you just have an untyped variable, it'll work just fine:</div>
	<pre><code>var x = 2;</code></pre>
	<pre><code>x.minutes().ago();</code></pre>
	<div>See the full code example <a href="http://github.com/airportyh/misc/blob/366479f05b6ef862bd48a83654b511fcd18b3b20/prototype_in_as/ex1.mxml">here</a>, and the <a href="http://tobyho.com/uploads/flex_examples/prototype/ex1.swf">demo</a> here.</div>
	<div>What about runtime error handling? So let's see what happens if you don't include the extensions and run the code. When I took out the array extension methods, the runtime dutifully throw me the:</div>
	<pre><code>TypeError: Error #1006: collect is not a function.
	</code></pre>
	<div>This is good, just what I would expect. For Date, it works the same way. Now let's try taking out the string extensions:</div>
	<pre><code>TypeError: Error #1006: value is not a function.
	</code></pre>
	<div><span>Uhh, what? Not really sure what you mean.</span> And as you would expect, it works like this for Number as well.</div>
	<div>I have also seen cases where the runtime simply completely <span>muffles</span> an error when there's an undefined method being tried as someone documented <a href="http://turbidwater.blogspot.com/2007/12/flex-sucks-ass.html">here</a>. But I am not able to reproduce this just now. Also on another note, the error stacktrace from the flash player(debug version) is not very helpful because although it gives the call stack, there are no line numbers. I am sure that you'd get a better experience using Flex Builder, however.</div>
	<div>I think that about wraps it up. Although extending core types is fun, powerful, and elegent, it's also full of holes and flying scissors everywhere. Are <span>you</span> ready to jump into this brave new world?</div>
	<div><span>A message to the Adobe Flex/ActionScript team: I implore you to put more effort into the prototype-based side of the language. It allows for many possibilities which its class-based counterpart cannot offer. I don't dislike the class-based approach. I think the two each have their own strengths and weakness. Which is why I love this hybrid aspect of ActionScript 3 which allows me to use either style in the same environment. I believe that if the prototype-based aspect of ActionScript were to improve and get more exposure, it would not only become a better language, but also a more wide spread language.</span></div>
</div>
<p><span><br></span></p>
<h2>Other Flex-related Articles on my Site</h2>
<div>
	<ul>
		<li><a href="http://tobyho.com/Making_Flex_Suck_Less">Making Flex Suck Less</a><br></li>
		<li><a href="http://tobyho.com/Property_Binding_in_Flex">Property Binding in Flex</a></li>
		<li><a href="http://tobyho.com/Adding_Real_Properties_to_FABridge">Adding Real Properties to the FABridge</a></li>
	</ul>
</div></content>
        </entry>,<entry>
            <title>ActiveRecord Gotcha</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/05/02/activerecord-gotcha">
            <updated>2009-05-02T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/05/02/activerecord-gotcha</li>
            <content type="text">
<p>I came across this interesting gotcha while debugging through someone else's rails code. When you set a model's one-to-many attribute(an perhaps other association types as well), let's say:</p>
<pre><code>user.friends = new_friend_list</code></pre>
<p>It doesn't always set it. As far as I can figure from my blackbox testing, it does an equal check first between the old value and the new value, and then sets only if they are different.</p>
<p>Now, in Ruby's == is easily overridable, you can easily make it do anything you want. It happens that Array#== returns true iff both arrays have the same number of elements and each element in one array is == to the element of the other array in the same position. It also happens that ActiveRecord's base class' == returns true as long as the objects are of the same class and the primary keys equal.</p>
<p>Which brings us to the gotcha of the day. The code in question built an array, say <span>new_</span><span>friend_list</span> independently, starting with an id list passed in from a from, finding each <span>friend</span> in the database and adding them to the array, but, in the meantime, modifying a field in each of the friends, say...<span>friend.charma++</span>. It then goes on to set the <span>friends</span> attribute in the manner you'd already seen above, and saves <span>user</span>. Well, the <span>charma</span> field that was modified in each of the friends retrieved did not get saved, because the set did not happen: the <span>new_friend_list </span>pointed to the same list of friends <span>user</span> was already associated to.</p>
<p>Hmm..., yeah. Watch out for this one. Debugging this one was not fun. It definitely didn't fit with the principle of least surprise.</p></content>
        </entry>,<entry>
            <title>Start Pidgin on Windows Startup</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/04/26/start-pidgin-on-windows">
            <updated>2009-04-26T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/04/26/start-pidgin-on-windows</li>
            <content type="text">
<p>This took me forever to figure out how to do, even when I'd figured it out some time before, so I thought I'd better document it here.</p>
<p>To get Pidgin to start on startup on Windows, go to <span>Tools -> Plugins </span>(yeah, that's right, it's a plugin)<span>. </span>Find<span> Windows Pidgin Options</span> in the list, check it off, and click the <span>Configure Plugin</span> button. Now you should see the <span>Start Pidgin on Windows Startup</span> option.</p></content>
        </entry>,<entry>
            <title>Using the Flex-Ajax Bridge</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/04/23/using-the-flex-ajax-bridge">
            <updated>2009-04-23T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/04/23/using-the-flex-ajax-bridge</li>
            <content type="text">
<p>The <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=ajaxbridge_1.html">Flex-Ajax Bridge</a> is a little javascript library bundled with the Flex SDK that allows you to use javascript to drive your Flex app. It can be really handy for debugging or experimentation when you use it with Firebug's console. For complete setup up instructions, <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=ajaxbridge_3.html#194300">see here</a>. You <span>do</span> need to modify your Flex code to get the bridge to work. It's just a one-liner though.</p>
<p>To use it, first you get a reference to your flex app:</p>
<pre><code>app = FABridge.flash.root()</code></pre>
<p>To get a component by ID, you would do something like:</p>
<pre><code>app.get('myDataGrid')</code></pre>
<p>To find out the type of the component:</p>
<pre><code>app.get('myDataGrid').typeName</code></pre>
<p>You can call the methods of the component as you would in normal ActionScript. To access the component's properties though, you need to use the Java getter/setter convention:</p>
<pre><code>app.get('myDataGrid').getSelectedItems()</code></pre>
<p>This isn't so nice. Ideally, a seamless experience would allow you to write:</p>
<pre><code>app.myDataGrid.selectedItems</code></pre>
<p>I guess this is where the weakness of Javascript is coming through. There's no language support for properties(like those in ActionScript, C# Python, etc.) and also no way to do method interception(<span>method_missing</span> in ruby). But I digress.</p>
<p>To instantiate an object of a class in Flex-land, you'd do something like:</p>
<pre><code>sprite = FABridge.flash.create("flash.display.Sprite");
</code></pre>
<p>This would call the default constructor. I am not sure how you'd call a constructor with arguments, probably just add on the arguments to <span>create()</span>?</p>
<p>A really cool and useful thing you can do is pass functions as event handlers to into Flex-land. Try this:</p>
<pre><code>app.get('myButton').addEventListener('click', function(e){
    console.log('button clicked!');
});</code></pre>
<p>Now go click that button...cool, heh?</p>
<p>Anyway...in conclusion, the Flex-Ajax Bridge is really nice...especially when combined with Firebug.</p></content>
        </entry>,<entry>
            <title>Different Ways of Including Functions in ActionScript</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/04/23/different-ways-of-including">
            <updated>2009-04-23T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/04/23/different-ways-of-including</li>
            <content type="text">
<p>This is another example of something that would have been a blog post <a href="http://stackoverflow.com/questions/775093/one-file-per-function-really/782330">creeping over to SO</a>.</p></content>
        </entry>,<entry>
            <title>Redirect 301</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/04/19/redirect-301">
            <updated>2009-04-19T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/04/19/redirect-301</li>
            <content type="text">
<p>I was looking at Google Analytics today and found that I was getting a bunch of traffic on <a href="Use delicious with chrome">Use Delicious with Chrome</a> as well as some programming/technical articles, but on the wiki.futuretoby.com domain rather than on the tobyho.com domain. </p>
<p>For those of you who don't know(probably all of you, because...why would you?), this <span>"wiki/blog"</span> runs the on 2 separate domains, but with a different <span>facade</span> over each one, if you will. One is for my family/personal stuff, for which most of the content it is intended for has access restrictions. The other is the tobyho.com domain, which I created more recently and is mainly for my public content. But all of the content can be accessed in exactly the same way on either domain.</p>
<p>So, basically, the former domain is still more visible on the Google search engine than the latter, and so people are coming to my articles on that one, rather than where I <span>want</span> them to go: tobyho.com. </p>
<p>How to fix it? Well, it turns out that for things like this, a 301 redirect(as supposed to a 302) is the way to go. It will tell the search engine that the content has moved permantly, and so prompt it to update its index. The code I ended up putting together was pretty simple:</p>
<pre><code>    tag_names = @page.tag_names
    if request.host != 'tobyho.com' and
        @page.authors.include?(toby) and 
        not tag_names.include?('family') and 
        (tag_names.include?('programming') or 
         tag_names.include?('tech') or 
         tag_names.include?('gadgets')) then
        headers["Status"] = "301 Moved Permanently"
        redirect_to("http://tobyho.com/#{@page.title_for_link}", :status =&gt; 301)
        return
    end</code></pre>
<p>So, basically, if a visitor comes to an article from the other domain, I want to redirect to the tobyho.com domain if 1) I am the author, 2) the article is tagged with one of <span>programming, tech, and gadgets</span> and 3) the article is <span>not</span> tagged with <span>family</span>. The line:</p>
<pre><code>headers["Status"] = "301 Moved Permanently"  
</code></pre>
<p>Is not needed if you're on a newer version of rails, for which setting <span>:status => 301</span> on the next line would suffice. I embarrassed to say that I am still on 1.2.x.</p></content>
        </entry>,<entry>
            <title>Dabbling in Dabble</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/04/05/dabbling-in-dabble">
            <updated>2009-04-05T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/04/05/dabbling-in-dabble</li>
            <content type="text">
<p>I'd been really impressed with <a href="http://dabbledb.com">Dabbledb</a> just from seeing the <a href="http://dabbledb.com/demo/">video demo</a>. I eventually decided to try using it to organize my music collection. I am mostly a jazz listener when it comes to music, and I have had this idea of building an extended jazz catalog for a while now - just in my back burner. So the idea was to see if Dabble is a good fit for this project.</p>
<p>Dabble is really awesome, and one of the really awesome things about it is the import.</p>
<p><span>Me: You know how I imported my iTunes library into dabble?</span></p>
<p><span>You: Um, probably parsed the itunes library xml file, and converted it to a format dabble takes - maybe a rest service of some sort...</span></p>
<p><span>Me: Wrong! I opened up itunes, pressed Ctrl-A to select all files in my library, Ctrl-C to copy, then Ctrl-V to paste into the import textarea of Dabble, click "Import", and BAM!</span></p>
<p>Well, okay, in reality there's a bit more to it. In iTunes, you want to add all the columns you want to export into the display. This is easy: just right-click on the column header and it will should you all the available fields and which ones are currently displayed. Check and uncheck as you see fit. Now, after the copy-and-past and a clicking <span>Import</span> inside Dabble, it should parse the tab delimited text correctly, and present you with a table view of the fields and a few rows of the data that it got. You can now tweak the field types before you finally do the final import.</p>
<p>Now, the next great feature of Dabble - in my opinion the greatest - is that you can just refactor the schema as you go. iTunes gives you a flat list of tracks - the artist and album fields for example, are just string fields. The obvious next step for me is convert these to related models, so that I can add additional information to the artists and albums and so that I can navigate my catalogue by album or artist, etc. In Dabble, this is dead simple. It's a one step process, you convert the string field into a link to a related category(your model, or entity in O/R speak), you can create the new category, say <span>Album</span> on the fly. The process will iterate over all the values of the field, group the common ones, and create an entry in the new category for each unique value. This feature, plus others which I will mention, means that your data model in Dabble are extremely malleable, which is not like the rigid O/R databases you are used to at all. I started out with one model: <span>Track</span>, and have since been refactoring it incrementally into more and more models. At this point I have 8 models: <span>Album, Artist, Company, Instrument, Organization, Personnel, Song, </span>and <span>Track</span>. Some of these models required additional data from other sources, but most were taken straight from the iTunes export. I must mention also, that changing your data model with actual data is very different from just drawing boxes and lines. Because the data is so concrete - ex: <span>Bill Evans(Piano), My Foolish Heart - </span>you see a realistic view of how well your data model fits with the actual data. I think it's a better data modelling tool than your standard O/R diagramming tools, of course, provided that you have actual data to work with.</p>
<p>Dabble has a one level undo for all operations. You can still screw up though if you go on to something else before you realize you need to undo - I already did this once. If you screw up, you can restore to a previous snapshot of your db. Dabble automatically snapshots your data about 5 times a day. You can also manually tell it to take the snapshot in the admin page. The restore process is just 2 clicks.</p>
<p>Also, you can change the field type of a column very painlessly. You just select configure -> change field type -> select the type you want -> done. It will convert the data for you semi-intelligently. For most cases this works okay. If not you can always undo or revert to your previous type. But I wish the data conversion was a little bit more configurable. For example, Dabble looked at the <span>duration</span> field of the track - for which the values looked like 6:23 - and assigned it the <span>Duration</span> type by default. This is exactly correct excepted that it interpreted 6:23 as 6 hours and 23 minutes. Another issue I had was the track number field. iTunes outputs the track number in the format <span>1 of 7</span>, for example. I would like to convert this to just a number, getting rid of the <span>of 7</span> part, and making it a <span>Number</span> field. Currently, there aren't sufficient options in the type dialogs for me to do that.</p>
<p>The UI is very well done. It's intuitive, all the possible actions are close by and just 1 or 2 clicks away. Search/filtering works nice. Mass edit is a useful feature. I especially like the <span>merge</span> feature, which I use a lot to clean up duplicate data. I like how one-to-many and many-to-many associations are displayed comma separated by default. You can customize almost everything about the views. There is still room for improvement, however. It is still quite tedious to enter large amounts of data, especially when there are many related models. I think they could make use of Ajax a bit more to reduce the number of full page loads. If it were me, I would make the core of the app(where you view, search, configure fields and edit data) a one page app.</p>
<p>Overall, I am loving Dabble. Avi Bryant is my hero. I'm going to be working on the music catalogue for a while, and I definitely see myself using this for other projects in the future.</p></content>
        </entry>,<entry>
            <title>A Custom Drag-n-Drop List Control</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/03/26/a-custom-drag-n-drop-list">
            <updated>2009-03-26T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/03/26/a-custom-drag-n-drop-list</li>
            <content type="text">
<p>The <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=dpcontrols_2.html">List</a> control supports drag-n-drop support out of the box - just not the way I want. What it does is allow you to drag something from another list or other type control and drop onto it there by transfering the object dragged into the list control itself. What I want is for something to be dropped onto an item in the list in question. This is how I ended up doing that.</p>
<div><br><div>By looking at the implementation of ListBase.as in the flex framework source code, I found that I needed to override some methods. So I create a MyList.as file which subclasses the List control. The methods I first needed to override were <span>dragEnterHandler</span> and <span>dragOverHandler</span>.<span> </span>Both of these methods in ListBase.as look almost identical, here is the source for dragOverHandler:</div><pre><code>    protected function dragEnterHandler(event:DragEvent):void
    {
        if (event.isDefaultPrevented())
            return;

        lastDragEvent = event;

        if (enabled && iteratorValid && event.dragSource.hasFormat("items"))
        {
            DragManager.acceptDragDrop(this);
            DragManager.showFeedback(event.ctrlKey ? DragManager.COPY : </code></pre><pre><code>		DragManager.MOVE);
            showDropFeedback(event);
            return;
        }

        hideDropFeedback(event);
        
        DragManager.showFeedback(DragManager.NONE);
    }
</code></pre><div>The <span>showDropFeedback</span> method draws a line in the List control that indicates where the new item would be inserted into the List. This doesn't apply to us anymore, so I overrode the showDropFeedback method, to just highlight the item under the cursor instead:</div><pre><code>        override public function showDropFeedback(event:DragEvent):void{
            var item = findItemForDragEvent(event);
            var uid:String = itemToUID(item.data);
            if (item){
                drawItem(item, isItemSelected(item.data), true, </code></pre><pre><code>			uid == caretUID);
            }
        }
</code></pre><div>Moreover, now we want to accept the drop only if the cursor is over a list item, whereas before it allowed for drops on empty parts of the List area. This what I did:</div><pre><code>        override protected function dragEnterHandler(event:DragEvent):void{
            _dragOverHandler(event);
        }
        
        override protected function dragOverHandler(event:DragEvent):void{
            _dragOverHandler(event);
        }
        
        public function findItemForDragEvent(event:DragEvent):Object{
            var item;
            var lastItem;
            var pt:Point = new Point(event.localX, event.localY);
            pt = DisplayObject(event.target).localToGlobal(pt);
            pt = listContent.globalToLocal(pt);
            var rc:int = listItems.length;
            for (var i:int = 0; i &lt; rc; i++)
            {
                if (listItems[i][0])
                    lastItem = listItems[i][0];

                if (rowInfo[i].y &lt;= pt.y && </code></pre><pre><code>			pt.y &lt; rowInfo[i].y + rowInfo[i].height)
                {
                    item = listItems[i][0];
                    break;
                }
            }
            return item;
        }
        
        protected function _dragOverHandler(event:DragEvent):void{
            var item = findItemForDragEvent(event);
            if (item){
                DragManager.acceptDragDrop(this);
                DragManager.showFeedback(</code></pre><pre><code>			event.ctrlKey ? DragManager.COPY : </code></pre><pre><code>				DragManager.MOVE);
                showDropFeedback(event);
            }else{
                DragManager.showFeedback(DragManager.NONE);
            }
        }
</code></pre><div>I wrote a findItemForDragEvent method to find the item that the cursor is currently under or null if none exist - the code was mostly stolen from the calculateDropIndex method in ListBase.as - then I accept the drop if I get a non-null value from it.<br></div><div>I think that's pretty much it. Here's the <a href="http://tobyho.com/uploads/flex_examples/dnd.swf">demo</a> and the <a href="http://github.com/airportyh/misc/tree/d133657cfe979ea0e5c7a2e1da962dc0005d9854/flex_custom_dnd_list">code</a>.</div></div></content>
        </entry>,<entry>
            <title>Getting Things Done</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/03/25/getting-things-done">
            <updated>2009-03-25T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/03/25/getting-things-done</li>
            <content type="text">
<p>I finished my copy of <span>Getting Things Done</span> by David Allen. Given how extremely influential this book was, it was a bit surprising that it wasn't more well written. My main problem with it is that it wasn't organized very well: duplicate information was scattered in different parts of the book - it felt a bit rambling at places. Because of this, I want to write a couple of articles on GTD, summarizing the book.</p>
<p>So..., here I go. This will be the first article of the sort.</p>
<p>I think that the second to last chapter of the book is the best chapter and really summarizes best what GTD is all about. It should probably have been the first chapter. And so, I am going to talk about it first. The three principles of GTD:</p>
<div>
	<ol>
		<li>The power of capture</li>
		<li>The power of the next action decision</li>
		<li>The power of outcome focusing</li>
	</ol>
	<div><span>The Power of Capture</span></div>
	<div><span><br></span></div>
	<div>GTD is based first on the principle of capturing <span>all</span> your "stuff". S<span>tuff</span> is just anything your mind thinks of that requires your attention - not just limited to just things you have to do. If you put all of you <span>stuff</span> into the physical world, you relieve your mind of the responsibility to remember them, freeing up your <span>phychic RAM</span>, thus you can focus your mind on other things, like executing on the things you need to do and being creative when you are brainingstorming. The state of having your phychic RAM empty is refered to as <span>mind like water</span>, in that you are ready for anything, because you have <span>all</span> of your mind to work with. Using the computer analogy, when you have more RAM, your program just runs much faster. While the human mind is great at recognition, it is not nearly as good as computers in sequential retrieval of memory, i.e. going from top to bottom through a list of stuff. For example, it's very hard to remember a list of unrelated things. This is why it's a good idea to dump your memory into the physical world, by making lists, either on paper or on the computer.</div>
	<div>When you capture all aspects of your life, you end up with a hugh repository of <span>stuff. S</span>o you'd better have a good system to keep it all organized. GTD provides a system for organizing your stuff which comprises of several lists and a workflow to systematically sort your stuff into these lists. I will go into more details in describing this system in a later article.</div>
	<div><span>The Power of the Next Action Decision</span></div>
	<div><span><br></span></div>
	<div>GTD is about directing your energy towards...well, getting things done. For example, the technique of sorting your task by context - or where you are at the moment - is designed to streamline your work. Many of the principles of GTD are rooted in psychology, which I really like about this book. The <span>principle of the next action decision</span> is one such principle. People - especially smart people - tend to procrastinate. This is because we tend to <span>visualize</span> and <span>imagine</span> when ideas are brought to our attention. When a non-trivial project is brought to our attention, chances are we are thinking of all the difficulties involved in finishing the project. This thinking discourages you from the actual doing, because you can not easily visualize the end to the project, nor the reward - the satisfaction of getting it done. If on the other hand, you split out the projects into very small tasks, each individual task becomes readily doable. And so, rather than filling your todo lists with project titles like:</div>
	<div>
		<ol>
			<li>get in shape</li>
			<li>fix car</li>
		</ol>
		<div>Replace them with the very next action for in the series of actions required to complete the project, like:</div>
		<div>
			<ol>
				<li>research gym memberships in the area on Google</li>
				<li>call mechanic to make an appointment</li>
			</ol>
			<div>When you look at these next action items, you no longer feel overwhelmed, and you possibly even <span>want</span> to do a task because you can very easily visualize it being done, and getting the satisfaction of having it finished. <span>That's</span> the power of the next action decision, and why you should figure out the next action ahead of time - when you write your list, and not when you are about to do it.</div>
			<div><span>The Power of Outcome Focusing</span></div>
			<div><span><br></span></div>
			<div>Third and finally, since GTD allows you to be so efficient at plowing through your tasks, you run the danger of losing focus and wasting your energy on non-essential or even irrelevant tasks. This is prevented by thinking about your goals and envisioning the outcomes you want at multiple perspectives regularly. GTD suggests weekly reviews of all your lists as wells as bigger reviews staged at bigger intervals.</div>
			<div>To me, these are the three most important take aways from the GTD book. For the next article, I will describe the system of lists and the workflow as laid out in the book.</div>
		</div>
	</div>
</div></content>
        </entry>,<entry>
            <title>Auto-focus the Window Under the Pointer on Windows</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/03/18/auto-focus-the-window-under">
            <updated>2009-03-18T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/03/18/auto-focus-the-window-under</li>
            <content type="text">
<p>Nice! I didn't know you could do <a href="http://miknight.blogspot.com/2005/09/windows-window-focus-changing-with.html">this on windows</a>. All it took was a google search.</p></content>
        </entry>,<entry>
            <title>Parameterizing Your Tests</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/03/12/parameterizing-your-tests">
            <updated>2009-03-12T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/03/12/parameterizing-your-tests</li>
            <content type="text">
<p>I use <a href="http://seleniumhq.org/">Selenium</a> at work to write browser tests. I use the Python bindings with Selenium Remote Control to drive the tests. Now, once you have written a test suite, it is not unreasonable to want to run the same set of tests over different browsers. Now that the browser space is getting interesting again, you'd better test your app on 5 or 6 browsers. So how do I write my tests once, and run them on different browsers? In the Python unittest framework, tests are written as classes that extend <span>unittest.TestCase</span>. So, to parameterize them, you can can subclass the test dynamically and set the <span>browser</span> attribute onto it:</p>
<pre><code>import unittest

class TestPages(unittest.TestCase):
    def testPage(self):
        print("testing page on %s" % self.browser)

TestPagesOnFirefox = type('TestPagesOnFirefox', 
                                 (TestPages,), dict(browser='firefox'))

if __name__ == '__main__':
    unittest.main()
</code></pre>
<p>So, we are subclassing <span>TestPages</span> calling it <span>TestPagesOnFirefox</span> and at the same time setting its browser attribute to <span>'firefox'</span>.<br></p>
<div>
	<div>We run it and get this error:</div>
	<pre><code>AttributeError: 'TestPages' object has no attribute 'browser'</code></pre>
</div>
<p>This is because <span>TestPages</span> does not have the <span>browser</span> property defined. What do we do? Let's erase it:</p>
<pre><code>del TestPages</code></pre>
<p>After that it runs okay and we get the output we want:</p>
<pre><code>testing page on firefox
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
</code></pre>
<p>So we can generalize that and expand all the browsers you want to. We write an <span>expand_browsers</span> function like so:</p>
<pre><code>def expand_browsers(gls, browsers=['firefox', 'ie6', 'ie7', 'safari', 'chrome', 'opera']):
    original_test_classes = filter(
        lambda o: isinstance(o, type) and issubclass(o, unittest.TestCase), 
        gls.values())
    
    for cls in original_test_classes:
        for browser in browsers:
            new_class = type('%sOn%s' % (cls.__name__, browser), (cls,), dict(browser=browser))
            gls[new_class.__name__] = new_class
        del gls[cls.__name__]
</code></pre>
<p>After you declare all you tests you call the function like so:</p>
<pre><code>expand_browsers(globals())
</code></pre>
<p>This goes through the namespace of your module and for each class that is a subclass of <span>unittest.TestCase</span>(You can choose a different subclass as marker here if you want), it subclasses it and specifies the <span>browser</span> property in it. After that, it erases the original testcase class so that it can't be found, like we did above.</p>
<p>Final complete example:</p>
<pre><code>import unittest

class TestPages(unittest.TestCase):
    def testPage(self):
        print("testing page on %s" % self.browser)

class TestMorePages(unittest.TestCase):
    def testPageTwo(self):
        print("testing page two on %s" % self.browser)

def expand_browsers(gls, browsers=['firefox', 'ie6', 'ie7', 'safari', 'chrome', 'opera']):
    original_test_classes = filter(
        lambda o: isinstance(o, type) and issubclass(o, unittest.TestCase), 
        gls.values())
    
    for cls in original_test_classes:
        for browser in browsers:
            new_class = type('%sOn%s' % (cls.__name__, browser), (cls,), dict(browser=browser))
            gls[new_class.__name__] = new_class
        del gls[cls.__name__]

expand_browsers(globals())

if __name__ == '__main__':
    unittest.main()
</code></pre>
<p>Output:</p>
<pre><code>.testing page two on firefox
.testing page two on ie6
.testing page two on ie7
.testing page two on opera
.testing page two on safari
.testing page on chrome
.testing page on firefox
.testing page on ie6
.testing page on ie7
.testing page on opera
.testing page on safari
.
----------------------------------------------------------------------
Ran 12 tests in 0.000s

OK
</code></pre>
<p>Code examples also <a href="http://github.com/airportyh/misc/tree/9e54618329e9eca9694dcebd60827dbbacd63fab/parameterized_tests">on github</a>.</p></content>
        </entry>,<entry>
            <title>Property Binding in Flex</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/03/11/property-binding-in-flex">
            <updated>2009-03-11T04:00:00.000Z</updated>
            <id>http://tobyho.com/2009/03/11/property-binding-in-flex</li>
            <content type="text">
<p>I have been working more with Flex now, and I have to say: the data binding features(covered <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_1.html">here</a>) in Flex is beautiful. It's light years ahead of anything I've ever seen before. </p>
<div><br><div>Example 1: You want a Text element to show the full name of current selected state from a drop down: <pre><code>    &lt;List id="stateList" labelField="abrv"&gt;
        &lt;ArrayCollection&gt;
            &lt;Object abrv="NJ" full="New Jersey"/&gt;
            &lt;Object abrv="MA" full="Massachusetts"/&gt;
            &lt;Object abrv="NY" full="New York"/&gt;
            &lt;Object abrv="NC" full="North Carolina"/&gt;
        &lt;/ArrayCollection&gt;
    &lt;/List&gt;
    &lt;Text text="{stateList.selectedItem.full}"/&gt;
</code></pre><div>The code in the curly braces is some ActionScript code, but it doesn't just get executed once, oh no, you can look at it as an invariant, i.e. the content of the said text element will <span>always </span>contain the value expressed by <span>stateList.selectedItem.full. </span>Therefore, when you change the selection of <span>stateList</span>, the text element will immediately change with it. Here's the <a href="http://github.com/airportyh/misc/blob/ed1d453849a6a876aa8763357016201b06dcb98d/flex_binding/ex1.mxml">code</a> and <a href="http://tobyho.com/uploads/flex_examples/ex1.swf">live demo</a> for example 1.</div><div><br><div>Example 2: Let's try binding to a custom variable rather than to another control. We first make our <span>counter</span> variable public and bindable:</div><pre><code>    &lt;Script&gt;
    [Bindable]
    public var counter:int = 0;
</code></pre><div>Then, we can bind a text control to it:</div><pre><code>    &lt;Text text="{counter}"/&gt;
</code></pre><div>Next, we can periodically increment the variable like so:</div><pre><code>        setInterval(function(){
            counter++;
        }, 1000);
</code></pre><div>And you will see the number in the text display count up: the display in the text element is syncronized with the actually value of <span>counter</span>. The <a href="http://github.com/airportyh/misc/blob/ed1d453849a6a876aa8763357016201b06dcb98d/flex_binding/ex2.mxml">code</a> and <a href="http://tobyho.com/uploads/flex_examples/ex2.swf">live demo </a>for example 2.</div><div>Next, let's try creating our own properties. ActionScript has support for Java-style OOP(as supposed to Javascript style), but, <span>more </span>interestingly, it's got direct support for properties. Add direct support of property change event bindings, and it's a beautiful thing. </div><div>Example 3: You have a Page object that manages the details of paginating a set of data, and you need some controls to navigate between the pages as well as display what page you are on. You create a Page object:</div><pre><code>    class Page extends EventDispatcher{
        public var number:int;
        public var size:int;
        public var total:int;
</code></pre><pre><code>        ...</code></pre><pre><code>    }</code></pre><div>A page has a page number, a page size, and the total size of the data set(used to tell whether a page exists). I instantiate a Page object:</div><pre><code>    &lt;Script&gt;
    [Bindable]
    public var currentPage:Page = new Page(0, 10, 100);
    &lt;/Script&gt;
</code></pre><div>I need a label that tells me the range of results currently being viewed:</div><pre><code>    &lt;Label text="{currentPage.from} to {currentPage.to}"/&gt;
</code></pre><div>Here, the label binds to 2 properties: <span>from</span> and <span>to</span>. Let's implement these properties:</div><pre><code>    class Page extends EventDispatcher{
</code></pre><pre><code>        ...</code></pre><pre><code>        [Bindable]
        public function get from():int{
            return number * size + 1;
        }
        [Bindable]
        public function get to():int{
            return (number + 1) * size;
        }
</code></pre><pre><code>        ...</code></pre><pre><code>    }</code></pre><div>Notice the <span>get</span> syntax: this in ActionScript turns the function into a getter for a property of the same name. Also notice that I made these properties bindable.</div><div>Next, I need the <span>previous</span> and <span>next</span> buttons. I choose to sandwich the label in between them:</div><pre><code>    &lt;Button label="Previous" click="currentPage.prev()"/&gt;
    &lt;Label text="{currentPage.from} to {currentPage.to}"/&gt;
    &lt;Button label="Next" click="currentPage.next()"/&gt;
</code></pre><div>Clicking on P<span>revious</span> will call the <span>prev </span>method and clicking on <span>Next</span> will call the <span>next</span> method. Simple. Here is the code:</div><pre><code>        public function next(){
            number++;
        }
        
        public function prev(){
            number--;
        }
</code></pre><div>Compiled it, but it doesn't work. Clicking on <span>Previous</span> and <span>Next</span> does no change the display on the label at all. Oh! We need to fire the events! To fire a property change event, you'd do something like:</div><pre><code>                this.dispatchEvent(new PropertyChangeEvent(
                    "propertyChange", true, true, 
                    PropertyChangeEventKind.UPDATE,
                    propertyName, null, null, this));
</code></pre><div>In our case, we are going to fire the change events for both <span>from </span>and <span>to</span>, because both of those must change after you flip a page. So we fire the changes:</div><pre><code>        private function fireChanges(){
            var toFire = ['from', 'to'];
            for (var i = 0; i &lt; toFire.length; i++)
                this.dispatchEvent(new PropertyChangeEvent(
                    "propertyChange", true, true, 
                    PropertyChangeEventKind.UPDATE,
                    toFire[i], null, null, this));
        }
        public function next(){
            number++;
            fireChanges();
        }
        public function prev(){
            number--;
            fireChanges();
        }
</code></pre><div>Ok, but I would like to disable the <span>Previous</span> or <span>Next</span> button when we are at the begining or the end of the dataset. No problem! We create a couple more bindable properties: <span>hasNext</span> and <span>hasPrev</span>:</div><pre><code>        [Bindable]
        public function get hasNext():Boolean{
            return to &lt; total;
        }
        [Bindable]
        public function get hasPrev():Boolean{
            return number &gt; 0;
        }
</code></pre><div>Bind the buttons' <span>enabled</span> property to them:</div><pre><code>    &lt;Button label="Previous" click="currentPage.prev()" </code></pre><pre><code>        enabled="{currentPage.hasPrev}"/&gt;
    &lt;Label text="{currentPage.from} to {currentPage.to}"/&gt;
    &lt;Button label="Next" click="currentPage.next()"</code></pre><pre><code>        enabled="{currentPage.hasNext}"/&gt;
</code></pre><div>Make sure to fire the change events for them too when you are flipping pages(add them to <span>toFire </span>in the implementation of <span>fireChanges</span>) and we are done. The code: <a href="http://github.com/airportyh/misc/blob/ed1d453849a6a876aa8763357016201b06dcb98d/flex_binding/ex3.mxml">ex3.mxml</a>, <a href="http://github.com/airportyh/misc/blob/ed1d453849a6a876aa8763357016201b06dcb98d/flex_binding/Page.as">Page.as</a> and <a href="http://tobyho.com/uploads/flex_examples/ex3.swf">live demo</a> for example 3.</div><div>The end result of this is that you have very well separated MVC code. There isn't any code whose sole purpose is to sync the display like you get with jQuery code, for example. The code to do this is very minimal and naturally readable.</div><div>All code examples can be found <a href="http://github.com/airportyh/misc/tree/ed1d453849a6a876aa8763357016201b06dcb98d/flex_binding">here</a> on Github.</div><div>Btw, I should mention that, the code inside of the curly braces does not allow any arbitrary ActionScript. There is some amount of flexibility, but not a lot. You can read more <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_2.html">here</a>.</div></div></div></div></content>
        </entry>,<entry>
            <title>jQuery Style BDD</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/02/19/jquery-style-bdd">
            <updated>2009-02-19T05:00:00.000Z</updated>
            <id>http://tobyho.com/2009/02/19/jquery-style-bdd</li>
            <content type="text">
<p>I have been warming up to the jQuery style of using <a href="http://docs.jquery.com/How_jQuery_Works#Chainability_.28The_Magic_of_jQuery.29">method chaining</a>. Then I thought: why are most unit test frameworks class based? There's no reason why we can't do it in the jQuery style...</p>
<p>Something like this:</p>
<pre><code>$.describe('Bowling')
	.beforeEach(function(){
		this.bowling = new Bowling();
	})
	.should('score 0 for gutter game', function(){
		for (var i = 0; i &lt; 20; i++)
			this.bowling.hit(i);
		this.bowling.score.shouldEqual(0);
	})
	.should('accumulate score', function(){
		this.bowling.hit(20);
		this.bowling.hit(10);
		this.bowling.score.shouldEqual(30);
	});</code></pre>
<p>I am liking this syntax. The full bowling example is <a href="http://github.com/airportyh/misc/blob/4b820f346331e7098af83c88a5868e6627bb6b1a/jquery_bdd/bowling.html">here</a>. I guess I'll call this <a href="http://github.com/airportyh/misc/tree/4b820f346331e7098af83c88a5868e6627bb6b1a/jquery_bdd">jquery.bdd</a>. I just started using git/github btw. This is one of my first projects on it. Fork me. Fork me please.</p>
<p><i>Update:</i> jquery.bdd has been replaced by another project of mine called <a href="http://github.com/airportyh/describe">describe</a> - which is agnostic to Javascript framework and could be used with server-side Javascript environments like <a href="http://nodejs.org/">node.js</a>. Other Javascript BDD testing frameworks include:</p>
<div>
	<ol>
		<li><a href="http://github.com/pivotal/jasmine">jasmine</a> from Pivotal Labs</li>
		<li><a href="http://visionmedia.github.com/jspec/">jspec</a> from Visionmedia</li>
		<li><a href="http://github.com/visionmedia/expresso">expresso</a> from Visionmedia</li>
		<li><a href="http://github.com/technoweenie/ntest">ntest</a> from technoweenie</li>
	</ol>
</div></content>
        </entry>,<entry>
            <title>Being Dynamic in Statically Typed Languages</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/02/19/being-dynamic-in-statically">
            <updated>2009-02-19T05:00:00.000Z</updated>
            <id>http://tobyho.com/2009/02/19/being-dynamic-in-statically</li>
            <content type="text">
<p>Finally! Looks like we are all starting to get along:</p>
<div>
	<ul>
		<li><a href="http://mschnlnine.vo.llnwd.net/d1/pdc08/WMV-HQ/TL16.wmv">Anders' Future of C# presentation</a><br></li>
		<li><a href="http://eigenclass.org/R2/writings/typesafe-prototype-based-ocaml">Prototype-based programming in OCaml</a></li>
	</ul>
</div></content>
        </entry>,<entry>
            <title>Programming Without Braces</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/02/01/programming-without-braces">
            <updated>2009-02-01T05:00:00.000Z</updated>
            <id>http://tobyho.com/2009/02/01/programming-without-braces</li>
            <content type="text">
<p>I was looking at this snippet of Javascript I wrote</p>
<pre><code>	if (minutes) return minutes.minutes();
	else if (hours) return hours.hours();
	else if (days) return days.days();
	else if (weeks) return weeks.weeks();
	else return 0;
</code></pre>
<p>and noticed a certain beauty in this if-then-else statement in the fact that it doesn't contain any braces. Removing the braces de-clutters this code and makes it look...Zen.</p>
<p>The idea of using no braces was flashed out by Alan C Francis in his <a href="http://cardboardsoftware.com/2007/5/27/redefining-simple.html">Redefining Simple </a>article. So maybe I was subconciously affected by his article. What does this tell us about the use of braces though? Braces are not so nice. <span>begin</span> and <span>end </span>keywords and square brackets aren't so nice either...<br></p>
<p>I would also add that not using indentation at all also helps the beauty of the snippet. So this</p>
<pre><code>	if (minutes)             return minutes.minutes();
	else if (hours)            return hours.hours();
	else if (days)             return days.days();
	else if (weeks)             return weeks.weeks();
	else             return 0;</code></pre>
<p>does not look as good as the original above. In fact I would say this is approaching ugly, with the beginning if the lines jumping back and forth. So this tells us that indentation isn't necessarily the answer either.</p>
<p>Another thing I would say about the original snippet is that it looks almost like ML or LISP, which is probably why I like it.</p></content>
        </entry>,<entry>
            <title>Wow! Whatever you do - do NOT use IE</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/01/30/wow!-whatever-you-do---do-not">
            <updated>2009-01-30T05:00:00.000Z</updated>
            <id>http://tobyho.com/2009/01/30/wow!-whatever-you-do---do-not</li>
            <content type="text">
<div><span>Embedded Content</span><object width="512" height="296">
	<param name="movie" value="http://www.hulu.com/embed/80wKsvQyK6WrwF6f2S-fFA/30/137">
	
	</param>
	<param name="allowFullScreen" value="true">
	
	</param>
	<embed src="http://www.hulu.com/embed/80wKsvQyK6WrwF6f2S-fFA/30/137" type="application/x-shockwave-flash" allowfullscreen="true" width="512" height="296">
	
	</embed>
</object></div></content>
        </entry>,<entry>
            <title>Interactive Features on Youtube Being Put to Interesting Use</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/01/28/interactive-features-on">
            <updated>2009-01-28T05:00:00.000Z</updated>
            <id>http://tobyho.com/2009/01/28/interactive-features-on</li>
            <content type="text">
<p>I spent some time last couple of days on Youtube to see what the Youtubers are up to nowadays. Increasingly, I am seeing the interactive features of Youtube being utilized. The interactive features I am talking about is the ability to put message boxes and hyperlinks in the middle of your video. Many Youtubers are using the message boxes to ask viewers to subscribe to their channel, but more interestingly, <span>some </span>are using them to build an interactive experience. One example of this is Barack, Paper and Scissors:</p>
<div>
	<div><span>Embedded Content</span><object width="425" height="344">
		<param name="movie" value="http://www.youtube.com/v/l2mcdS6ioo8&hl=en&fs=1">
		
		</param>
		<param name="allowFullScreen" value="true">
		
		</param>
		<param name="allowscriptaccess" value="always">
		
		</param>
		<embed src="http://www.youtube.com/v/l2mcdS6ioo8&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344">
		
		</embed>
	</object></div>
</div>
<p>where viewers are challenged to play an interactive game of, well, Barack, Paper and Scissors. Another example is an interactive dating game called Jacuzzi Girl:</p>
<div>
	<div><span>Embedded Content</span><object width="480" height="295">
		<param name="movie" value="http://www.youtube.com/v/X5Qn8-w12p0&hl=en&fs=1">
		
		</param>
		<param name="allowFullScreen" value="true">
		
		</param>
		<param name="allowscriptaccess" value="always">
		
		</param>
		<embed src="http://www.youtube.com/v/X5Qn8-w12p0&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="295">
		
		</embed>
	</object></div>
</div>
<p>These are exciting possibilities for the Youtube platform and I am sure you are going to see many more content creators using this feature to create interesting stuff.</p></content>
        </entry>,<entry>
            <title>goodday dot py</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/01/22/goodday-dot-py">
            <updated>2009-01-22T05:00:00.000Z</updated>
            <id>http://tobyho.com/2009/01/22/goodday-dot-py</li>
            <content type="text">
<p>Looking at rails and the <a href="http://www.datejs.com">datejs library</a>, I can't help but feel bummed that Python doesn't have an expressive date library like that. So I started one. I've put up my code on <a href="http://code.google.com/p/goodday/">google code</a>. </p></content>
        </entry>,<entry>
            <title>TDD is Really Painful When Your Tests are Slow</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/01/18/tdd-is-really-painful-when">
            <updated>2009-01-18T05:00:00.000Z</updated>
            <id>http://tobyho.com/2009/01/18/tdd-is-really-painful-when</li>
            <content type="text">
<p>I have been on and off the TDD bandwagon and now I understand why. In order to have an enjoyable TDD experience, your tests must 1) be easy to write, 2) easy to debug and 3) finish running in seconds. Easy to write: that's mostly a process of structuring your code to be testable, something that is - although not always easy - at least straightforward. Easy to debug: very much depends on the language and framework(s) you are using. But if your tests run long, you starting waiting around for the tests to finish, and before you know it you are <a href="http://xkcd.com/303/">checking twitter and listening to podcasts(from Giles Bowkett)</a>. Your productivity go way down, and you get miserable - that is, if you care about your productivity. The hardcore TDD guys are big into using mocks, and the reason they give is the running time of the tests. Because with mocks they don't have to actually run any significant portion of code - the code is very hollow - the tests can run really fast. But, although I like mocks, they don't work everywhere. One example is Selenium. You may say, Selenium is not for TDD! It's for functional testing. Yeah, but why not? Selenium is starting to work well for me. It runs your tests against real browsers, and it can run your tests across different browsers automatically. Since, we have a lot of javascript in our app, I don't think any test suite that doesn't actually test your js against the actual browser gives you any real assurance. The problem with selenium, of course, is that it runs slow. Thus, my challenge, shall be to make my selenium tests run fast enough that I'd no longer have to wait around for my tests to finish(probably under 10 seconds). The first strategy I am going to use is to reuse test fixtures across tests in a fine grain way, so we can save much of the time used for setUp/tearDown.</p></content>
        </entry>,<entry>
            <title>Auto-mixin in Python</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/01/18/auto-mixin-in-python">
            <updated>2009-01-18T05:00:00.000Z</updated>
            <id>http://tobyho.com/2009/01/18/auto-mixin-in-python</li>
            <content type="text">
<p>Python has multiple inheritence - a feature that's really handy because it allows the programing idiom called <span>mixins</span> - where you write a a bunch of methods on a "mixin" class and then later on attaching all of those methods onto another class simply by mixin-it-in. In Python, the process of mixin-it-in is simply to add it to the parent list of the class:</p>
<div>
	<pre><code>class MyObject(MyParent, MyMixin):</code></pre>
	<pre><code>   ...</code></pre>
</div>
<p>In Ruby, you can automatically mix in a mixin programmatically because the mix-it-in is done within the class definition, and because of its open classes. This is how the rails helpers are automatically found in a directory and mixed into the controllers for example.</p>
<p>How would you do this in Python? Let's say we simplify the problem to this: For a given Controller subclass named ProductController, for example, if there exists a helper class by naming convention: ProductControllerHelper, then we mix it in. Here's my solution:</p>
<pre><code>class Meta(type):
    def __new__(cls, name, bases, dct):
        helper_mixin = globals().get('%sHelper' % name)
        if helper_mixin:
            bases = list(bases)
            bases.append(helper_mixin)
            return type.__new__(cls, name, tuple(bases), dct)
        else:
            return type.__new__(cls, name, bases, dct)
        
class Controller(object):
    __metaclass__ = Meta
        
class ProductControllerHelper(object):
    def method1(self):
        print "method1 invoked"
        
class ProductController(Controller):
    def index(self):
        self.method1()
        
        
if __name__ == '__main__':
    ProductController().index()
</code></pre>
<p>Output:</p>
<pre><code>method1 invoked
</code></pre>
<p>It worked!</p>
<p>But! We are not done. What if what you want to mix in depends on how you configure the class inside the class definition? In my case, I wanted to mix in a bunch of classes when I write a DSL-like declaration like this:</p>
<pre><code>class MyTestCase(TestCase):
    all = fixture(SeleniumRCServer, BrowserSession, DBData, Login)
    each = fixture(AddDelivery)

    ...</code></pre>
<p>This is for a testing framework I am working on. I have a test case, and I want to specify its test context(fixtures) in the manner shown. Each object in the fixture(..) definition is a mixin. So I want to mix them all into MyTestCase.</p>
<p>This case is harder than the previous case because when __new__ is invoked, the class definition hasn't been processed yet, and therefore you won't have access to the class attributes <span>all </span>and <span>each</span>. The hack I came up with is this:</p>
<pre><code>class TestCaseMetaClass(type):
    def __init__(cls, name, bases, dct):
        if len(bases) == 1 and bases[0] != unittest.TestCase:
            bases = list(bases)
            bases.extend(cls.all)
            bases.extend(cls.each)
            cls.__real__ = type(name, tuple(bases), dct)
        else:
            type.__init__(name, bases, dct)
        
    def __call__(cls, *params, **kws):
        if hasattr(cls, '__real__'):
            return cls.__real__(*params, **kws)
        else:
            return type.__call__(cls, *params, **kws)
            
class TestCase(unittest.TestCase):
    __metaclass__ = TestCaseMetaClass
</code></pre>
<p>Basically, I first override __init__ of the metaclass(rather than __new__) in order to record what was declared in <span>all </span>and <span>each</span>, and create a new class on the fly mixing in all the mixins defined in the fixture(..) definitions. We store that class in an attribute __real__ attached to the class. Then we override __call__ for the metaclass to return an instance of the class held in the __real__ attribute instead of the actual class. Oh yes, this is really ugly, but it worked, at least for what I was doing. If you can write to a classes' __bases__ attribute(which defines the parents of the class), then this would be much easier, but I haven't figured out how to do it if it can be done at all. But because of this limitation, it looks unlikely you can do something like Ruby's <a href="http://www.somethingnimble.com/bliki/mixology">mixology</a> in Python.</p>
<p>U<span>pdate: the better solution to the second part is found:</span></p>
<pre><code>class Meta2(type):
    def __new__(cls, name, bases, dct):
        mixins = []
        all = dct.get('all')
        if all:
            mixins.extend(all)
        each = dct.get('each')
        if each:
            mixins.extend(each)
        bases = list(bases)
        bases.extend(mixins)
        return type.__new__(cls, name, tuple(bases), dct)
        
class TestCase(object):
    __metaclass__ = Meta2
    
class Fixture1(object):
    def method2(self):
        print "method2 invoked"
    
class Fixture2(object):
    def method3(self):
        print "method3 invoked"
        
class BlahBlahTest(TestCase):
    all = [Fixture1]
    each = [Fixture2]
    def blah_test(self):
        self.method2()
        self.method3()
</code></pre></content>
        </entry>,<entry>
            <title>HP Mini vs Eee PC</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/01/08/hp-mini-vs-eee-pc">
            <updated>2009-01-08T05:00:00.000Z</updated>
            <id>http://tobyho.com/2009/01/08/hp-mini-vs-eee-pc</li>
            <content type="text">
<p>Netbooks are the new ipods this year! The took up 8 of the 10 spots on Amazon's top seller list towards the end of the year. I am going to share my experiences with the HP Mini and the Eee PC.</p>
<p>We first bought the Eee PC at target. They just had it laying around at the end of an aisle - they were still there the last time I was there. They go for only $299! The one we got was the 901 I believe and had a forked version of debian on it called Xandros. The out-of-the-box experience was pretty good. Firefox 2 , Skype, and a bunch of other apps were preinstalled. There were also launchers for gmail and google docs. I also give them credit for doing a great job integrating with the hardware. Most stuff worked fairly painlessly, by Linux standards at least. However, the we never could get it to work with our brothers 210c printer because the device driver wasn't on the list. Also, the wireless was flaky at times. Sometimes when it starts up from sleep mode, it takes a while for the wireless to connect, sometimes you have to even manually restart the connection. During our vacation, we could never get it to connect to the access point at the resort, whereas the windows XP machine was able to connect. The community for the Eee PC is pretty good, I figured out how to install a program someone wrote to add custom launchers to my desktop. Surprisingly, it had ruby and python preinstalled. I installed a whole rails dev environment on it too. It had only 4G of on-board storage(flash, no harddisk) so we had to be careful what to install. At the end though, the keyboard was too small and the touch pad buttons were too hard to press. It really wasn't comfortable doing dev work on it.</p>
<p>So, a couple of month in to using the Eee PC, we saw the HP Mini at Costco. The main thing that attracted us to it was - it looked <span>good</span>! We decide to get it, and if we liked it, we would return the Eee PC(Target and Costco both have 90 return policies for electronics). The Mini's keyboard is much larger than that of the Eee and much more comfortable. The mouse buttons are placed strangly on the left and right vertical sides of the touch pad. The operating system is Window XP, not Vista, what a relief! We are very familiar with XP so that's a plus. It's got a 60G harddrive in it, much more spacious, so we can put pictures on it, unlike the Eee. It's got USB and an SD-mini slot, good for use with our camera. The form factor of the Mini is lengthier than the Eee because it's a wide screen. The Mini is very fast coming out of sleep mode, and the wireless works much more reliably than the Eee. But I have had once when the wireless couldn't connect and I had to manually repair it. We like the HP Mini, and looks like we are going to stick with it.</p></content>
        </entry>,<entry>
            <title>How to set up a Private Key for svn ssh for Tortoisesvn</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/01/08/how-to-set-up-a-private-key">
            <updated>2009-01-08T05:00:00.000Z</updated>
            <id>http://tobyho.com/2009/01/08/how-to-set-up-a-private-key</li>
            <content type="text">
<p>I have been having to enter my password everytime I access the svn server with tortoisesvn and it was finally getting annoying enough that I did something about it. I already knew how to set up a public/private key pair for the command line svn client. To do the same for tortoisesvn you follow the steps detailed here<-(link broken see below), in the section: <span>SSH key generation and connection check (client).<br></span></p>
<p><span><br></span></p>
<p><span><i>Update: Here's a </i><a href="http://jaybyjayfresh.com/2009/02/04/logging-in-without-a-password-certificates-ssh/"><i>new good link</i></a><i>.</i></span></p></content>
        </entry>,<entry>
            <title>Setting up Phusion Passenger on my slice</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2009/01/06/setting-up-phusion-passenger">
            <updated>2009-01-06T05:00:00.000Z</updated>
            <id>http://tobyho.com/2009/01/06/setting-up-phusion-passenger</li>
            <content type="text">
<p>As my slice is running low on memory, running multiply mongrel processes really isn't an option any more(I am too cheap to pay for more memory, in these trying economic times). Phusion passenger comes to the rescue! Phusion passenger is exactly what the rails community needed for its deployment story. </p>
<p>So I follow the instructions:</p>
<pre><code>gem install passenger
</code></pre>
<p>When I did this my slice just hung indefinitely. It turns out that when gem updates the index of ruby gems, it downloads the entire index and puts it in memory, and this didn't fit in my tiny 256m I had on my slice. <a href="http://www.mail-archive.com/rubygems-developers@rubyforge.org/msg00925.html">This thread</a> ended up saving the day for me. I was able to do:</p>
<pre><code>gem install passenger -B 1000000
</code></pre>
<p>it was slow but it worked.</p>
<p>Next up was installing the apache2 module:</p>
<pre><code>passenger-install-apache2-module
</code></pre>
<p>First, it failed to find my apache2 installation and asked my to install it. I told it where it was by doing:</p>
<pre><code>export APXS2=/usr/local/apache2/bin/apxs
</code></pre>
<p>Next, it didn't find the Apache Portable Runtime(APR). I told it where it was by doing:</p>
<pre><code>export APR_CONFIG=/usr/local/apache2/bin/apr-1-config
</code></pre>
<p>Then, it didn't find the APU(whatever that is, I stopped caring). I did:</p>
<pre><code>export APU_CONFIG=/usr/local/apache2/bin/apu-1-config
</code></pre>
<p>After all that, and running passenger-install-apache2-module again, it worked! </p>
<p>Next I setup the virtual host entries. I created the file /usr/local/apache2/conf/apps/tobyho.conf with these contents:</p>
<div>
	<pre><code>&lt;VirtualHost *:80&gt;
	</code></pre>
	<pre><code>        ServerName tobyho.com
	</code></pre>
	<pre><code>        DocumentRoot /var/www/apps/mywiki/public
	</code></pre>
	<pre><code>        &lt;Directory "/var/www/apps/mywiki/public"&gt;
	</code></pre>
	<pre><code>                Options FollowSymLinks
	</code></pre>
	<pre><code>                AllowOverride None
	</code></pre>
	<pre><code>                Order allow,deny
	</code></pre>
	<pre><code>                Allow from all
	</code></pre>
	<pre><code>        &lt;/Directory&gt;
	</code></pre>
	<pre><code>&lt;/VirtualHost&gt;
	</code></pre>
</div>
<p>And now I got the wiki running on mod_rails. Yea!<br></p></content>
        </entry>,<entry>
            <title>Ruby Gotcha of the Day</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/12/26/ruby-gotcha-of-the-day">
            <updated>2008-12-26T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/12/26/ruby-gotcha-of-the-day</li>
            <content type="text">
<p>Okay, so in ruby:<br></p>
<pre><code>&gt;&gt; nil or 'value'

=&gt; "value"</code></pre>
<p>because nil acts as false when used with boolean operators and any other object acts as true. Now let's assign the result to a temp variable a:<br></p>
<pre><code>&gt;&gt; a = nil or 'value'
</code></pre>
<p><pre><code>=&gt; "value"
</code></pre><pre><code>&gt;&gt; a
</code></pre><pre><code>=&gt; nil
</code></pre>Whoa?? Can you guess? In ruby the assignment operator is not special. It acts just like any other operator and does not have a lower precedence than the <i>or</i> operator. Therefore the expression<br></p>
<pre><code>a = nil
</code></pre>
<p>executes first, which evaluates to <i>nil</i>, and assigns the value <i>nil</i> to <i>a</i>, and then the result <i>nil</i> is used in the expression <i>nil or 'value'</i>. Therefore to do what we intended we need to do:<br></p>
<pre><code>&gt;&gt; a = (nil or 'value')
</code></pre>
<p><pre><code>=&gt; "value"
</code></pre>Wow! That is messed up. <br></p></content>
        </entry>,<entry>
            <title>Multiline Strings in Javascript</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/12/21/multiline-strings-in">
            <updated>2008-12-21T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/12/21/multiline-strings-in</li>
            <content type="text">
<p>I was looking through the code in facebox.js(a jQuery plugin) and I saw this:</p>
<div><pre><code>'\
</code></pre><pre><code>    &lt;div id="facebox" style="display:none;"&gt; \
</code></pre><pre><code>      &lt;div class="popup"&gt; \
</code></pre><pre><code>        &lt;table&gt; \
</code></pre><pre><code>          &lt;tbody&gt; \
</code></pre><pre><code>            &lt;tr&gt; \
</code></pre><pre><code>              &lt;td class="tl"/&gt;&lt;td class="b"/&gt;&lt;td class="tr"/&gt; \
</code></pre><pre><code>            &lt;/tr&gt; \
</code></pre><pre><code>            &lt;tr&gt; \
</code></pre><pre><code>              &lt;td class="b"/&gt; \
</code></pre><pre><code>              &lt;td class="body"&gt; \
</code></pre><pre><code>                &lt;div class="content"&gt; \
</code></pre><pre><code>                &lt;/div&gt; \
</code></pre><pre><code>                &lt;div class="footer"&gt; \
</code></pre><pre><code>                  &lt;a href="#" class="close"&gt; \
</code></pre><pre><code>                    &lt;img src="/facebox/closelabel.gif" title="close" class="close_image" /&gt; \
</code></pre><pre><code>                  &lt;/a&gt; \
</code></pre><pre><code>                &lt;/div&gt; \
</code></pre><pre><code>              &lt;/td&gt; \
</code></pre><pre><code>              &lt;td class="b"/&gt; \
</code></pre><pre><code>            &lt;/tr&gt; \
</code></pre><pre><code>            &lt;tr&gt; \
</code></pre><pre><code>              &lt;td class="bl"/&gt;&lt;td class="b"/&gt;&lt;td class="br"/&gt; \
</code></pre><pre><code>            &lt;/tr&gt; \
</code></pre><pre><code>          &lt;/tbody&gt; \
</code></pre><pre><code>        &lt;/table&gt; \
</code></pre><pre><code>      &lt;/div&gt; \
</code></pre><pre><code>    &lt;/div&gt;'
</code></pre>Wow, I am ashamed I didn't know you could do multi-line strings like this earlier!! Although not as nice as multi-line strings in Ruby/Python/Perl, this definitely beats quotes and plus signs.<br></div></content>
        </entry>,<entry>
            <title>Developing in AIR just got a little suckier</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/12/18/developing-in-air-just-got-a">
            <updated>2008-12-18T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/12/18/developing-in-air-just-got-a</li>
            <content type="text">
<p>I wanted to try putting a javascript console inside an AIR app to aid development. I tried firebug lite, which I've been using a lot to debug IE. When I started up the app and hit F12, the console came up and everything, '1+2' gave 3, so time to rejoice? Not so fast, if you try to type 'window', or 'document', you get this error:<br></p>
<pre><code>Error: Adobe AIR runtime security violation for JavaScript
</code></pre>
<div><pre><code> code in the application security sandbox (eval)
</code></pre><br>So they sandboxed eval and restricted access the dom and any other api that's available. And it's for... security reasons. What does Adobe have against eval? This sucks!<br></div></content>
        </entry>,<entry>
            <title>Compiler should have did-you-mean feature</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/12/18/compiler-should-have-did-you">
            <updated>2008-12-18T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/12/18/compiler-should-have-did-you</li>
            <content type="text">
<p>Idea: When you misspell things in your program, the compiler messages should say something like:<br></p>
<pre><code>Error: Call to a possibly undefined method listChange, 

did you mean listChanged?</code></pre></content>
        </entry>,<entry>
            <title>IE getElementById looks up "name"</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/12/09/ie-getelementbyid-looks-up">
            <updated>2008-12-09T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/12/09/ie-getelementbyid-looks-up</li>
            <content type="text">
<p>IE, <a href="http://www.456bereastreet.com/archive/200802/beware_of_id_and_name_attribute_mixups_when_using_getelementbyid_in_internet_explorer/">are you kidding me</a>?<br></p></content>
        </entry>,<entry>
            <title>IE Woes: One</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/12/09/ie-woes:-one">
            <updated>2008-12-09T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/12/09/ie-woes:-one</li>
            <content type="text">
<p>Man! Have I been at war with IE lately. I have been holding back a lot of blog posts related to debug IE problems, and I going to start spewing them out now one by one. For the first installment I'll talk about one I encountered these couple of days...<br><br>Ever get this IE error?</p>
<div class="image">
	<img src="/uploads/ie_error.png?1228873829" mce_src="/uploads/ie_error.png?1228873829" name="ie_error.png" width="593">
</div>
<p><br>When you click "Ok", this is what you see:<br></p>
<div class="image">
	<img src="/uploads/ie_error2.png?1228873932" mce_src="/uploads/ie_error2.png?1228873932" name="ie_error2.png" width="522">
</div>
<p><br>Ouch! Can this <i>be</i> any more catastrophic?(Yeah, that's my Chandler impression.)<br><br>According to <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2247375&SiteID=1" mce_href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2247375&SiteID=1">this forum post</a>, this happens if you have script tags in your document that's modifying other parts of the dom before the document finishes loading. Umm, okay, but I still had a hard time finding out the exact point this caused the problem. I used the comment-out-code-and-see-if-it-still-breaks-binary-search methodology, and came up with some work arounds which involved delaying the execution of some setup code. But, this catastrophic error came back to haunt be time and time again. Clearly I didn't find the root cause of this error or I wouldn't be committing it repeatedly. <br><br>But finally, I found it(I think, well at least one of the root causes). I am using <a href="http://getfirebug.com/lite.html" mce_href="http://getfirebug.com/lite.html">firebug lite</a> in development, which creates iframes and panels in the pages that pops out and in just like firebug. When you call console.log with firebug lite, guess what happens? Yeah, it modifies the console output window - a part of the dom that is outside of where the script tag is. Got rid of those console.log statements and fixed it.<br><br>In conclusion, <i>do not</i> do what I did!<br></p></content>
        </entry>,<entry>
            <title>Dissecting the Prototype Chain</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/12/08/dissecting-the-prototype-chain">
            <updated>2008-12-08T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/12/08/dissecting-the-prototype-chain</li>
            <content type="text">
<p>I realized when I was trying to explain the prototype chain to my wife the other day that I didn't get it completely. So I went back to the drawing board and this is the example that I came up with:<br><br></p>
<pre><code>function inherit(parent){

    var obj = function(){};
    obj.prototype = parent;
    return new obj();
}

toby = {};
toby.name = 'Toby';
toby.age = 27;
toby.eyeColor = 'brown';
toby.hairColor = 'dark';

console.log(toby);
// Object name=Toby age=27 eyeColor=brown hairColor=dark

emma = inherit(toby);
emma.name = 'Emma';
emma.age = 1

console.log(emma);
// Object name=Emma age=1 eyeColor=brown hairColor=dark

console.log("Toby is Emma's parent: " + 
	(emma.__proto__ == toby));
// true</code></pre></content>
        </entry>,<entry>
            <title>Windows XP tip: Hide Desktop Icons</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/12/06/windows-xp-tip:-hide-desktop">
            <updated>2008-12-06T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/12/06/windows-xp-tip:-hide-desktop</li>
            <content type="text">
<p>You can hide your desktop icons in XP by right clicking on your desktop and unchecking Arrange Icons by -> Show Desktop Icons.<br></p></content>
        </entry>,<entry>
            <title>Great Break Down Of the Coolest Languages</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/11/27/great-break-down-of-the">
            <updated>2008-11-27T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/11/27/great-break-down-of-the</li>
            <content type="text">
<p>This is a <a href="http://matt.might.net/articles/best-programming-languages/">great great read</a>.<br></p></content>
        </entry>,<entry>
            <title>Y Combinator</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/11/27/y-combinator">
            <updated>2008-11-27T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/11/27/y-combinator</li>
            <content type="text">
<p>This is a <a href="http://matt.might.net/articles/implementation-of-recursive-fixed-point-y-combinator-in-javascript-for-memoization/">great article</a> on the Y-Combinator. It talks in laymans terms. I understand now what it does and why it is useful. However, I still have no clue how the code for the Y-Combinator works.<br></p></content>
        </entry>,<entry>
            <title>Making Flex Suck Less</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/11/26/making-flex-suck-less">
            <updated>2008-11-26T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/11/26/making-flex-suck-less</li>
            <content type="text">
<p>This is a follow up to <a href="/FLEX:_first_impressions" mce_href="/FLEX:_first_impressions">my last Flex post</a>. As I am learning more about Flex I have learned ways to address all 3 of the items in the <i>cons </i>list.<br></p>
<ol>
	<li><i>Development feedback - not as instant.</i> I mentioned that Flex has a compile step in the development process, this cannot be fixed. But the lack of an interactive console can be addressed by using the Javascript bridge, with which you can use Firebug to script your Flex app. There are inevitably some limitations, of course(like, I don't think you can pass functions to and from Flex land; and you can't modify the existing code), but by and large it is extremely useful. The scripting ability alleviates the slower feedback problem even though it does not eliminate it.</li>
	<li><i>Mandatory Static Typing.</i> I misspoke on this one. Actually the static typing isn't mandatory at all. I mistook the warnings from the compiler to be errors. You have the option of turning off the warnings. Now I can eliminate a lot of what I dim the unnecessary type declarations from my code. However, I will not remove type declarations entirely, because I believe static type checking <span>is</span> immensely useful for situations where 1) it takes some time for the program to start up, and 2) it takes some user navigation actions to get to the place you want to test. The type checker will catch a class of stupid errors, which if you encounter only after waiting and performing a series of mouse clicks and key presses, can make you irritated quickly. My rule of thumb for type declaration in ActionScript is: 1) declare function input and output types; 2) declare global variable types; 3) local variables may or may not be declared, depending on the situation(if the variable is used extensively in the function, then declare); 4) do not declare if the type is void(i.e. nothing). I've never <i>really </i>worked with a language that has optional type checking, this is fresh! The browsers in the future will have this too in Ecmascript 4. Another language that has this is Groovy, and I heard <a href="http://blogs.msdn.com/charlie/archive/2008/11/13/anders-hejlsberg-video-on-c-dynamic.aspx" mce_href="http://blogs.msdn.com/charlie/archive/2008/11/13/anders-hejlsberg-video-on-c-dynamic.aspx">C# is adding this too</a>, how exciting! I SOOO admire Anders Hejlsberg. <i>(after seeing the video it seems it's more like a bridge to scripting languages/libraries)</i> </li>
	<li>As for the mx: prefix, I've <a href="http://stackoverflow.com/questions/284530/is-it-a-bad-idea-to-get-rid-of-the-mx-in-your-flex-code" mce_href="http://stackoverflow.com/questions/284530/is-it-a-bad-idea-to-get-rid-of-the-mx-in-your-flex-code">already figured out how to do without it</a>. So you can write <Panel ...> rather than <mx:Panel...></li>
</ol>
<p>In conclusion, Flex is actually an even better development environment than I gave it credit for last time. <br></p></content>
        </entry>,<entry>
            <title>Hitting Better Now</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/11/23/hitting-better-now">
            <updated>2008-11-23T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/11/23/hitting-better-now</li>
            <content type="text">
<p>I had a realization recently playing tennis - <i>quit trying to hit like Roger Federer or Rafeal Nadal every time, it's going to wear out your arm</i>. <br><br>I had a match a while ago against a slow hitting grinder. He returned nice deep loopy balls back to me all the time, while I try to hit hugh forehands through him with all my force. I won the first set smoothly, but a couple of mishaps on my part and we were 5-5 in the second set. It was then I realized my right arm was worn out. I couldn't go for winners anymore: trying to do so would likely result in an error due to the lack of strength in my arm to control the racque - this is not the first time this has happened either: I have played this same player
before and it resulted in a thrilling third set tie breaker with me
lossing mostly due to my losing my forehand. I still won this time though by a bit of luck while playing more defensively at the end. At the time I thought: <i>I need much much more endurance.</i><br><br>But now I realized the bottleneck is not the endurance, but rather that I've been hitting too many unorthodoxed - though pretty - shots - trying to mimick Roger Federer or Rafeal Nadal(mostly Roger). A lot of times I would hit the ball on my back foot; many times when I have a slow ball I would wind up my whole body <i>to jump into the ball</i> on the swing(like the pros). These shots, while good looking, and can be effective, can also be extremely demanding on your arm and even the rest of your body.<br><br>But more recently I have come to embraced a much more energy efficient, and possibly more textbook style of hitting the forehand. Swing the racque the way you throw a punch in Taekwondo, i.e. start with a wide stance(but usually facing about 90 degrees away from the opponent's baseline rather than being parallel to it), when you hit the ball, lead in with a hard turn of your hips, which is helped with a push from your back leg. This, oh this, is the shot of optimal power generation. I have been using this shot more now in my matchs, and time and time again it has proven worth while. Not only does it take less force to generate more power, I also hit it with more consistency than with the unorthodoxed shots.<br><br>How did I discover(rediscover) this shot? We bought some foam training balls on the suggestion from a friend - who is a 4.5 level player. He said he bought the training balls to teach his son, but found it was too early to teach his son and so practiced with the balls himself instead. He found it to be enormously helpful to his game. The foam ball travels much slower than a tennis ball, and so it is very hard to hit a foam ball out of bounce. Thus, when you are hitting with a foam ball, you tend to excert much more energy hitting the ball to make it travel farther. Now, when you have to consistently hit with more power, the natural thing you body and mind tend to do is find the most energy efficient way to do it(cause you get worn out quick otherwise). And that's basically how this shot was rediscovered.<br><br>As for Roger and Rafa? They both have a level of endurance that is just incredible. I don't think I would be getting there any time soon.<br></p></content>
        </entry>,<entry>
            <title>What Hulu Needs</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/11/23/what-hulu-needs">
            <updated>2008-11-23T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/11/23/what-hulu-needs</li>
            <content type="text">
<ol>
	<li>Remote control - I want to be able to choose and watch shows, skip, etc. with a remote. So that I can channelsurf it while feeding my baby or at the dinner table(a keyboard is way too clunky).</li>
	<li>Channel captions, sometimes I need to watch my show at low volume because the baby is sleeping or we don't want to draw her attention to the TV.</li>
</ol>
<p>I was going to say continous playing too, but they already have this in the form of your queue. Still, they should improve this functionality by automatically choosing shows/episodes for you based on your preference.<br></p></content>
        </entry>,<entry>
            <title>FLEX: first impressions</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/11/20/flex:-first-impressions">
            <updated>2008-11-20T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/11/20/flex:-first-impressions</li>
            <content type="text">
<p>At work I am required to write a web UI that has a rich-desktop kind of interface. Without getting into too much details, it's layout will look a bit like an older email application(e.g. outlook, the older versions). It also need to have drag-n-drop capabilities. I whipped up a prototype of the UI using prototype and scriptaculous, since that's what I've been getting fluent with. A couple of things about my prototype made me decide to give Flex a try.<br></p>
<ol>
	<li>No draggable divider. The draggable divider - although not essential - is something that seasoned computer users have learned to expect when you give them interfaces that have multiple panels jammed onto one screen. Scriptaculous didn't have an draggable divider widget. YUI and ExtJS did, and I am not against learing a new library. But I get the vibe that their implementations might not be rock solid.<br></li>
	<li>Buggy drag-n-drop libary. Scriptaculous comes with a drag-n-drop library. I've used it in multiple occations. It's also been buggy for me on multiple occations. A lot of the bugs are attributed to differences in browsers.</li>
</ol>
<p>I decided that I was tired of chasing down cross browser bugs, which will only grow exponentially the more complex my UI gets. Therefore, Flex could really be the answer to these problems.<br><br>I am probably 60% done with my port of the UI prototype from Javascript/prototype/scriptaculous to Flex. I am happy with it for the most part. Here are my first impressions of Flex. First the pros:<br></p>
<ol>
	<li>Programming in Flex is suprisingly similar to programming in HTML/javascript/CSS. (Well, not as suprising as it could have been since I've heard Charles Lowe say the same on DrunkAndRetired.com podcast). You write a mxml file, which is like your markup - in place of your HTML; you write ActionScript inplace of Javascript; and there's a css 3 compliant stylesheet you can use to style the UI.</li>
	<li>Flex has a rich UI component model that similar to many of the desktop UI toolkits(Swing, GTK, MFC, etc), which is a departure from the HTML/Javascript model. This is a plus because you get a lot of widgets you can use out of the box with very little code. Using third party Javascript widgets is usually <i>more involved</i>.</li>
	<li>ActionScript is not much different from Javascript, so people literate in Javascript should pick it up easily. The only significant difference I've noticed so far is the type declaration syntax - ActionScript is statically typed. I believe ActionScript is compatible with a newer version of Ecmascript which has optional type declaration for variables and parameters. Type declaration in ActionScript(as far I can tell) is required on function parameters and global variables(errors out if you leave it), and optional on local variables(warns you if you leave it).<br></li>
	<li>Yes, you have to write XML, but it's not <i>that</i> bad. I have expressed my hatred for making programmers read and write XML by hand in the past. It's inhumane! Flex makes you do that. Yes. But! It's used in a way that's not as bad as some other ways in which XML have been used(build scripts, web configuration, for example). In Flex, XML is used for Markup (wow! a markup language used for markup? what a concept?). The XML declaratively defines the UI(such as in HTML), which, I my opinion, is the way UI's ought to be written, and not in a procedure way(such as in Swing).<br></li>
	<li>Flex components look good by default. For HTML/CSS you always have to design your own theme - even if you just want it to look half way decent. No such BS in Flex. Flex components look good out of the box(no CSS tweaks or includes required), because of this I believe you can prototype Flex UIs faster.</li>
	<li>A Flex app runs exactly the same on any browser it supports. This was the main sell for me. Nothing more needs to be said.</li>
</ol>
<p>Now the cons:<br></p>
<ol>
	<li>Development feedback - not as instant. Developer feedback loop is slower because of the compile step. ActionScript is a compiled language, and you need to compile your Flex programing to get a SWF file. Also, in Flex 3, they <a href="http://www.colettas.org/?p=17" mce_href="http://www.colettas.org/?p=17">took away the eval() function</a>(why oh why???). This means you cannot create an interactive shell in Flex like Firebug or the python shell.</li>
	<li>Mandatory Static typing. Although I have nothing against static typing in general. I don't like mandatory static typing(such as exists in Java, C#, C++). Haskell is a staticly typed language, it verifies all your types for you, and yet it doesn't require you to specify the types of all you variables and parameters because it can infer them all for you. I like that. This is not a big issue for me, it's just not as kosher as Javascript in this respect.</li>
	<li><strike>It's annoying that you have to write mx: to begin all Flex component tags in the mxml spec. No such BS in HTML. I tried a <a href="http://stackoverflow.com/questions/284530/is-it-a-bad-idea-to-get-rid-of-the-mx-in-your-flex-code" mce_href="http://stackoverflow.com/questions/284530/is-it-a-bad-idea-to-get-rid-of-the-mx-in-your-flex-code">hack to do without it</a>, it didn't work so well.</strike><br><i>Update: Looks like I have <a href="http://stackoverflow.com/questions/284530/is-it-a-bad-idea-to-get-rid-of-the-mx-in-your-flex-code">gotten rid of the mx: problem</a>. I guess I showed </i><i>them ;)</i><br></li>
</ol>
<p>Overall, the pros are worth more than the cons. Linguistically, I prefer Javascript to ActionScript and HTML to MXML, so it's not going to <a href="http://tv.winelibrary.com/" mce_href="http://tv.winelibrary.com/">Change My Life(TM)</a>. But the UI component model and cross browser compatibility greatly outweigh those nags.<br><br></p></content>
        </entry>,<entry>
            <title>Radio button change event firing</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/11/10/radio-button-change-event">
            <updated>2008-11-10T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/11/10/radio-button-change-event</li>
            <content type="text">
<p>If you register the <i>change </i>event for a radio button, they fire at different times between IE and FF. FF fires the event immediately when you click on the radio button to change its value. IE does not, it fires <i>changed </i>only when you <i>blur </i>the element.<br></p></content>
        </entry>,<entry>
            <title>IE bug: input endtags show up as nodes</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/11/10/ie-bug:-input-endtags-show-up">
            <updated>2008-11-10T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/11/10/ie-bug:-input-endtags-show-up</li>
            <content type="text">
<p>If you write an input element like this:<span><br></span></p>
<pre><code>&lt;input type="text" id="name" name="name" value="&gt;&lt;/input&gt;
</code></pre>
<p>In IE, if you try to traverse the dom, you will get the end-tag as a separate element /input. Ex. with prototype: $('name').next() should get you /input.<br></p></content>
        </entry>,<entry>
            <title>REST stuff in GAE</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/11/02/rest-stuff-in-gae">
            <updated>2008-11-02T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/11/02/rest-stuff-in-gae</li>
            <content type="text">
<p>I've been working on getting justtodolist.com to use REST style URLs. It feels like I increasingly post my technical stuff on stackoverflow.com though, as was the case this time. So I'll just post a link to <a href="http://stackoverflow.com/questions/255157/how-to-override-http-request-verb-in-gae">my stackoverflow question</a>.<br></p></content>
        </entry>,<entry>
            <title>Python Optional Arguments Gotcha</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/10/15/python-optional-arguments">
            <updated>2008-10-15T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/10/15/python-optional-arguments</li>
            <content type="text">
<p>When you use Python optional arguments you should know that the default value you set is static, it is set at the time the function is defined, and does not change after that. If you a mutable type as the default value, you need to be careful. <br>Ex:<br><br></p>
<pre><code>&gt;&gt;&gt; def enlist(n, lst=[]):
...   lst.append(n)
...   return lst
...
&gt;&gt;&gt; enlist(3)
[3]
&gt;&gt;&gt; enlist(4)
[3, 4]
&gt;&gt;&gt; enlist(5)
[3, 4, 5]
&gt;&gt;&gt; enlist(6)
[3, 4, 5, 6]
</code></pre>
<p>Everytime you call the enlist function, the list gets bigger, because lst is never reset to the empty list. It is set to the empty list only once, when enlist was defined. After that it references the same instance everytime you don't supply a lst argument.<br></p></content>
        </entry>,<entry>
            <title>justtodolist in the wild</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/10/10/justtodolist-in-the-wild">
            <updated>2008-10-10T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/10/10/justtodolist-in-the-wild</li>
            <content type="text">
<p><a href="http://justtodolist.com">justtodolist.com</a> is another side project of mine. I have now released it to the public. Go take a look, tell your firends, and I hope it becomes useful to you.<br></p></content>
        </entry>,<entry>
            <title>tadalist is unsecured</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/10/06/tadalist-is-unsecured">
            <updated>2008-10-06T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/10/06/tadalist-is-unsecured</li>
            <content type="text">
<p>I always look to 37signals when I need design ideas or looking for precedence for how to solve certain problems. My problem this time was: how to gracefully handle your Ajax calls failing due to your login session expiring? I looked at tadalist. To my surprise, even after I deleted the session cookie, modifying the list still worked. I looked at the request headers and it seemed like they simply weren't securing the app at all. I wrote a quick socket program to verify this, and it was true: any one who has the ID of your list and/or items can make modifications to them. I guess they just felt this app is not mission critical enough to worry about this kind of stuff. What about the todolist in basecamp? Hmm... let me check... result: they don't really handle this gracefully in Basecamp. If you try to check off a list without auth, it just hangs there foreever. I guess I'll have to creative and come up with my own solution here.<br></p></content>
        </entry>,<entry>
            <title>Ditching e texteditor and komodo edit for SciTE and Launchy</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/10/02/ditching-e-texteditor-and">
            <updated>2008-10-02T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/10/02/ditching-e-texteditor-and</li>
            <content type="text">
<p>I have had it with e-texteditor and Komodo Edit! I wrote a <a href="/Komodo_Edit_vs_E_texteditor" mce_href="/Komodo_Edit_vs_E_texteditor">comparison</a> of the two and have been switching back and forth between the two since then. While both editors have really great features, the basics are JUST NOT THERE. E-texteditor: each new version just crashes more and more, now everytime I use tortoise SVN from the project pane it crashes, it's not as snappy as I want either in general. Komodo Edit: the file browser filter is just too painfully slow! The textbox on top of the file browser is a live search, except if you want a live search to work, it better load FAST, otherwise every key I type is going to cause me to wait. Plus, the filter is not smart, it doesn't allow typos, I have type the name right or I am going to miss the file I want(E-texteditor doesn't have this problem, they have a pretty good quick launch).<br><br>SciTE is a pretty popular open source code editor. It's lightweight and it's fast. It's not as featureful as the other two, but it opens REALLY fast. When I first decided to switch to it, I thought, oh great, now I have to use a file explorer as my project pane and drag files onto my editor to open it? That's kind of a hassel too. So I changed my file associations so that most of my project files .py, .html, .mak etc open with SciTE by default. Now I can just click on the file and it opens in the editor. But then it hit me, I can open them with <a href="http://www.launchy.net/" mce_href="http://www.launchy.net/">Launchy</a>! Launchy is a great launcher app for Windows and I have been using it for a long time and have been very happy with it. I configured it to scan my project directory, and vola! Now I can open any file in the project at thought speed! Under a second, definitely. Way, way faster than I could do in e-texteditor or Komodo Edit. All I do is hit Alt-SPACE start typing the name of the file I want to open until it shows up as the selected choice, and then hit Enter. Usually it doesn't take but 3-5 key strokes to get the file you want to show up, and typos are ok, I can type shgrp for example and it'll give me show_group. I am really loving this way of working, I can get to stuff so much quicker. The reason it's so quick, is because of the speed of both Launchy and SciTE. Launchy runs in the background, and is really fast and responsive to your keystrokes. SciTE launches instantly.<br><br>The only problem now though, is that since launching a file using SciTE opens a new SciTE window instead of in a tab in the existing one, I now end up with a lot of SciTE windows open and they can be hard to manage. If those windows are grouped in the task bar(which XP does for you when there are many similar windows), it will help, but having it open as a tab would be even better. I might just dig into their code one day and see if I can make this happen.<br><br><i>BTW: To give you an idea how fast SciTE is compared to the other two. E-texteditor took 8 seconds to start up, after which there was still a popup dialog I had to click, which frozen it up for another 5-10 seconds, but my first click didn't work so I had to click again to get rid of the dialog to make it go away before I can start working. Komodo Edit took 25 seconds just to come up but about 32 seconds for it to be interactive(stopped loading). SciTE opens in 1 second or less everytime.</i><br></p></content>
        </entry>,<entry>
            <title>Selenium-RC Proxy Server War Story</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/10/02/selenium-rc-proxy-server-war">
            <updated>2008-10-02T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/10/02/selenium-rc-proxy-server-war</li>
            <content type="text">
<p>I am trying out selenium yet again to help our non-existent QA team. I have to admit that I kinda flaked out on unit testing too(I kinda got sick of TDD in rails bogging me down to be honest), which I mean to catch up on, but, for now, I wanted to focus on selenium, since, with an ajax app like ours, too many things could go wrong, it could be either client side or server side or a combination, so intergration testing I think can really buy us a lot. Besides, I really wanted to know if selenium works well or not.<br><br>Anyway, this is not a post about selenium, exactly, I'll probably dedicate another to it later, when I have had sufficient experience with it. The problem I faced in this episode is that when I run the app through the selenium-rc proxy server, my flash messages aren't showing up! Yes, the proxy server is muffling my flash messages, what could it be? This first thought was it had to be a cookie issue since the flash message is implemented as a one-time use cookie, but the other cookies worked fine, or I wouldn't have been able to login to the app.<br><br>From looking at the cherrypy code, it looks like it's setting 2 cookies, one for auth, the other for the flash message, and it generates 2 Set-Cookie headers. I suspected that this was screwing up the selenium proxy server. I decided to dig into the selenium server code and put in some debug statements.<br><br>Aww! Getting the selenium-rc source and then building it with maven 2 is back to the painful slow Java days. Man! Maven, do you really have to download the entire internet just to build the project? Maven just symbolizes all that I hate about Java. It's bloated; it's framework heavy; it forces things on you that you don't need; running a build with it is glacial; build plugins is a big hassel, did I leave out anything? I think Maven may be the worst thing that has happened to the Java community...but I digress. <br><br>Basically I tracked it down to the part where the proxy server gets the header fields from the HttpURLConnection object(part of the standard Java API), but it drop the flash message cookie somehow. I suspected it was because that API just doesn't cope with duplicate header names in the response, but that seems strange that this has never come up. Googling found that people have been able to get dupliately named headers using the getHeaderFieldKey(int n) and getHeaderField(int n) methods, which take in a positional parameter. This is what the proxy server was doing, but yet it didn't work.<br><br>I used wireshark to look at the packets to confirm my theory, it did, but I also found another interesting thing - there is an empty line between the first Set-Cookie header and the second. I came to me that this is probably what tripped up the HttpURLConnection code, and I was right. I changed the Cookie code in the standard library to use \n instead of \r\n(so it interpreted as an empty line) as the separator and it solved the problem.<br><br>But I don't want to just patch a standard python library like that, it's not deployable. Don't know whether I should fix this in selenium-rc or not, in which case <a href="http://stackoverflow.com/questions/156514/java-httpurlconnection-can-it-cope-with-duplicate-header-names" mce_href="http://stackoverflow.com/questions/156514/java-httpurlconnection-can-it-cope-with-duplicate-header-names">someone suggested</a> I use the apache httpclient in place of HttpURLConnection.<br><br>Update: It turns out you can use the same trick as I displayed <a href="/The_Hidden_Singleton_with_Javascript">here</a> to patch Python libraries, which is what I did:<br></p>
<pre><code>    import Cookie
    def make_myoutput():
        org = Cookie.BaseCookie.output
        def myoutput(self, attrs=None, header='Set-Cookie: ', sep='\n'):
            return org(self, attrs, header, sep=sep)
        return myoutput
    Cookie.BaseCookie.output = make_myoutput()</code></pre></content>
        </entry>,<entry>
            <title>button's value attribute</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/09/29/button's-value-attribute">
            <updated>2008-09-29T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/09/29/button's-value-attribute</li>
            <content type="text">
<p>If you use a button element as a submit button in a form, like:<br><button id="mybutton">My Button</button><br>$('mybutton').value in FF will get you an empty string whereas in IE you would get "My Button"<br></p></content>
        </entry>,<entry>
            <title>justtodolist updates and appengine stuff</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/09/06/justtodolist-updates-and">
            <updated>2008-09-06T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/09/06/justtodolist-updates-and</li>
            <content type="text">
<p>I made some enhancements again to <a href="http://justtodolist.appspot.com">justtodolist</a>. There's a couple of interesting points I came across so I thought I would jot it down.<br><br></p>
<b>The stateful interactive shell sample app. </b>
<p><br>This is a must for any app engine developer! It's leaps and bounds closer to the python shell than the default interactive shell. Get it from <a href="http://code.google.com/p/google-app-engine-samples/downloads/list">here</a>. It needs some tweaking to get it working along side your app. <i>Hint, aside from modifying your app.yaml, you will likely have to modify the app config in shell.py as well.</i><br><br></p>
<b>Again, simplicity works! </b>
<p><br>I made a simplification in my model in the in workings of the ordering of the lists, and the result was much less/simpler and less buggy code.<br><br></p>
<b>Data model migration.<br></b>
<p>So as <a href="/Web_Dev_with_Google_App_Engine">I pointed out before</a>, migration in app engine is not really well supported, essentially, you are on your own. If you want to change the type of a property - for example, I wanted to change a ListProperty(int) to a ListProperty(db.Key) - you will likely completely break your app, because the data will no validate. There is no way to migrate the data, because there's no way to access the existing data. The only workaround that I could come up with was to rename the property(well, actually, adding a new one and leaving the old one, at least temporarily). After that I could write a migration script. Now that I had the interactive shell on production as well(the default shell was only available for development), I could run it easily through the shell instead of writing a handler with the sole purpose of running the migration script.<br><br>My co-worker pointed out to me that an automatic migration scheme might be the future for the appengine data store and similar object oriented datastores. The idea was very interesting. Basically, we could come up with a scheme for migrating data models using renaming mechanisms like what I did above. But, we could do it all behind the scenes inside a framework. I can see how it would work and how it could be done: <br></p>
<ol>
	<li>you would have a global schema version number. Everytime you modify the schema the version number would increment, ideally, the framework would somehow detect the change you made and up the version automatically.</li>
	<li>you would have a sort of version control for every property of every object, and have a numbered naming scheme for them, so: name_1, name_2, for example. Every change to the property would up the property version number.</li>
	<li>Each object would have a version property. This means that the system can operate with objects that have different schema versions at the same time without breaking.</li>
	<li>Removing a property is easy, nothing more really needs to be done. Unless you want to provide a way derive a value to the old missing property, in which case you can provide a property descriptor of the existing object to do it.</li>
	<li>Adding a property is easy too, you can provide a function of the existing object to provide an initial value if you want, which will be invoked the first time that the property is used.</li>
	<li>Renaming a property can be done by specifying the property with an old_name directive like: new_name = db.StringProperty(old_name="old_name") then the code just has to create the new property and initialize it to the value of the old property the first time it is used.<br></li>
	<li>Change the type of a property can be done by using an old_type directive much like the old_name directive for renaming, and then you may provide a conversion function of the existing object that returns the new initial value. Behind the scenes, the property version number will be incremented, so you are really adding a new property, which is aliased somehow back to the same name later.<br></li>
</ol>
<p>Sounds good...There's one problem though, as you edit the schema in your .py file with directives like old_name and initial value functions which only apply to the most recent migration. But, since as we've seen, migration happens on the fly(as the data is accessed), there needs to be a historical archive of all migration directives, i.e. real version control. One way to do it would be to write explicit migration definitions as in rails migration. So something like:<br></p>
<pre><code>add_property(Person, 'age', db.IntegerProperty())</code></pre>
<p>instead of editing the models directly. I think this way is sufficient. I was kinda hoping I could just edit the models directly willy-nilly though. Maybe you can write tool that inspects your model definition and diffs it with the last version and generate a migration definition?<br><br>Anyway, better get some sleep. This is definitely an interesting idea and a very concrete one for a project.<br><br><br></p></content>
        </entry>,<entry>
            <title>Use Delicious with Chrome</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/09/05/use-delicious-with-chrome">
            <updated>2008-09-05T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/09/05/use-delicious-with-chrome</li>
            <content type="text">
<div><i>Update #2: Delicious has released their official version of the </i><a href="https://chrome.google.com/extensions/detail/lnejbeiilmbliffhdepeobjemekgdnok">Delicious Chrome Extension</a>.<br></div>
<div><i>Update: There's now a </i><i><a href="https://chrome.google.com/extensions/detail/gclkcflnjahgejhappicbhcpllkpakej">Chrome Extension for Delicious</a>. Try that!</i><br></div>
<p>Chrome has no add-on archecture so there's no way people can build a delicious plugin for it. The alternative is a bookmarklet, there's one for delicious: <a href="http://delicious.com/help/bookmarklets">http://delicious.com/help/bookmarklets</a>.<br></p>
<p><i><br></i></p>
<p><i><br></i></p>
<p><i><br></i></p></content>
        </entry>,<entry>
            <title>Making justtodolist work for chrome and safari</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/09/03/making-justtodolist-work-for">
            <updated>2008-09-03T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/09/03/making-justtodolist-work-for</li>
            <content type="text">
<p>Since <a href="/Google_Chrome">Chrome </a>is so great, I wanted to use it for all my browser needs. But the apps I've been working on myself have not been targeted for WebKit - the rendering engine used by chrome, and also used my Safari. This is mostly due to laziness on my part - having to handle two browsers at a time is chaos enough. But Safari compatibility is on my todo list for more than one of my projects, and chrome is a good push for this cause. And so I went in today and made <a href="http://justtodolist.appspot.com"><i>just todo list. </i></a>compatible with Chrome and Safari. The differences I encountered were:<br></p>
<ol>
	<li>This is really prototype specific - prototype adds an empty underscore parameter for all Ajax request for WebKit browsers. Because apparently, Safari errors out when you try to post with an empty body on XHR calls. And, who knows, this might already be fixed in WebKit. I happened to have code that was not handling this fact on the server side. This was no biggy.</li>
	<li>This is an error on my part really, but I had a form with a text input inside. But also registered for the key events on the text input so that when enter is pressed I called form.submit(). The key event code is really unnecessary because an enter on the text input triggers the form submit on both FF and IE. So, although on the other 2 browsers this was no problem, in WebKit this triggers 2 posts. So... just DON'T do this.<br></li>
</ol></content>
        </entry>,<entry>
            <title>Google Chrome</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/09/02/google-chrome">
            <updated>2008-09-02T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/09/02/google-chrome</li>
            <content type="text">
<p>Google just released this <a href="http://www.google.com/chrome" mce_href="http://www.google.com/chrome">awesome browser</a>. They have a <a href="http://www.google.com/googlebooks/chrome/" mce_href="http://www.google.com/googlebooks/chrome/">great comic strip</a> walking you through what the big deal is about, which is a must read for web developers. I've been using the browser for half a day and it's been pretty rock solid for all the sites I normally use. Javascript is clearly MUCH faster thanks to the v8 engine, which I think <a href="http://steve-yegge.blogspot.com/2008/05/dynamic-languages-strike-back.html" mce_href="http://steve-yegge.blogspot.com/2008/05/dynamic-languages-strike-back.html">Steve Yegge alluded</a> to a while ago. I like many of it's different features, and think it's a great boost to the browser world as well as javascript, i.e. the <a href="http://steve-yegge.blogspot.com/2007/02/next-big-language.html">NBL(Next Big Language)</a>.<br></p></content>
        </entry>,<entry>
            <title>Play Date with jQuery</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/09/01/play-date-with-jquery">
            <updated>2008-09-01T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/09/01/play-date-with-jquery</li>
            <content type="text">
<p>I had a new toy project and started out with my trusty sidekick: prototype.js but a bit of the way in i decide to try my hand at jQuery instead, since I've already read a lot about jQuery and really like the <a href="http://osteele.com/archives/2008/02/inlined-frommaybe" mce_href="http://osteele.com/archives/2008/02/inlined-frommaybe">monad-like paradigm</a> which allows you to write elegant "flow" code without having to worry about null values anywhere in the chain.<br><br>It was quite easy translating my existing prototype.js code to jQuery(probably just around 30 lines). <br></p>
<ul>
	<li>The end result was probably 20% more succient.</li>
	<li>I love the css 3 capable selectors, it's very refreshing to be able to use attribute and partial string match selectors which normally you don't get to use for your work. </li>
	<li>I also like the way attributes are set as chained methods(again, in the monad flavor), you do something like $('#myid').attr('value') to get the value and $('#myid').attr('value', 1) to set the value to 1. This again, allows you to chain stuff together. What's the point of this? ...I guess I just like the monad thing.</li>
	<li>I think the jQuery syntax for behavioral javascript is prettier than prototype.js + lowpro.js<br></li>
</ul>
<p>I really have nothing bad to say about jQuery. Even the UI components seem pretty on par with prototype.js, there's jqueryui, from which I used the autocomplete plugin. It's a little bit unfortunate that I had already invested about 1800 lines of javascript code on writing javascript components based on prototype.js and scriptaculous at work, otherwise had I started over I would very probably use jQuery. I will definitely go jQuery for my other projects.<br><br>Are there anything from prototype.js that I miss? Well, yes, I miss the array extensions from prototype, which lets you use ruby/smalltalk/lisp-like internal iterator style list operations. jQuery has a $.each, but it's not quite as pretty... but it gets the job done. And I haven't looked, but I am not sure there's an equivalent to prototype's Event.KEY_RETURN, Event.KEY_BACKSPACE and such in jQuery. Also, I had gotten comfortable to the OO model from prototype, and doing without it will be different, but then again I am adaptable. Plus, there's nothing at all stopping you from using jQuery and prototype.js together.<br></p></content>
        </entry>,<entry>
            <title>The z-index IE bug</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/08/23/the-z-index-ie-bug">
            <updated>2008-08-23T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/08/23/the-z-index-ie-bug</li>
            <content type="text">
<p>Yeah, the <a href="http://www.quirksmode.org/bugreports/archives/2006/01/Explorer_z_index_bug.html" mce_href="http://www.quirksmode.org/bugreports/archives/2006/01/Explorer_z_index_bug.html">z-index IE bug</a>, have you heard of it? I was bitten by it a couple of days ago. In my case, I had a list of text fields in a form layed out from top to bottom. The problem is, I have these interactive drop downs on that can activate just under the text fields when you focus on the field and there is a validation error, which I use <a href="http://tobyho.com/Relativize%20that%20thing:%20todays%20CSS%20war%20story" mce_href="http://tobyho.com/Relativize%20that%20thing:%20todays%20CSS%20war%20story">relative/absolute positioning</a> to get in the right place, and so the position: relative declaration triggers the IE bug which causes the text field beneath the one that has the focus to occlude its drop down. My solution? I now have a javascript snippet that runs as the dom is ready that sets the z-index of all the containers(the one that has position: relative) of the text fields in descending order. So for example, if you have 10 text fields, the first one would have its z-index: 10 and the last one would have z-index: 1.<br><br>In a related note, if you use the relative/absolute positioning technique, the child element that has position:
absolute is considered the child of the parent element that has position: relative in terms of z-index, which if you then have overflow: hidden on the parent element or its ancestors, the child element would get cut out if it's position is out of bounds, vs if you didn't have position: relative set on the parent element then the child would not get cut out because it's considered to be the child of the root element in terms of z-index.<br></p></content>
        </entry>,<entry>
            <title>The Hidden Singleton with Javascript</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/08/23/the-hidden-singleton-with">
            <updated>2008-08-23T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/08/23/the-hidden-singleton-with</li>
            <content type="text">
<p>This pattern is well documented else where, I think I first saw it in the Definitive Javascript book. Let's say you want to provide a function that does stuff with a static variable, but don't want that static variable to be global(visible to the outside)? You would do this:<br><br></p>
<pre><code>myfunction = function(){
    var mysingleton = new Singleton();
    return function(x, y){
        return mysingleton.doit(x,y);
    };
}();</code></pre>
<p><br>so now you can do myfunction(1,2) which in reality calls the doit method of the same instance of Singleton everytime. As a more concrete example, you can create a counter function like this:<br><br></p>
<pre><code>counter = function(){
    var i = 0;
    return function(){
        return i++;
    };
}();</code></pre>
<p><br>Each time you call counter() the result increases by 1.<br><br>A variation of this pattern is to extend an existing function/method by replacement. This is similar to the ruby practice of aliasing a method to a different name and then sticking a new method in it's place that at some point calls the original version. Anyway, for example, let's say you have an existing function from an existing library... say scriptaculous effects' Effect.Shake. You want to change the default options without having to rename the function(so that all your existing code that depends on it doesn't not need to change), you would do:<br><br></p>
<pre><code>    Effect.Shake = function(){
        var original = Effect.Shake;
        return function(element, options){
            original(element, Object.extend({
                distance: 5,
                duration: 0.5
              }, options || {}));
        };
    }();</code></pre>
<p><br>So I've changed the default distance to 5 and duration to 0.5 throughout my app for any calls to shake() by adding this in one place only.<br></p></content>
        </entry>,<entry>
            <title>Relativize that thing: todays CSS war story</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/08/22/relativize-that-thing:-todays">
            <updated>2008-08-22T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/08/22/relativize-that-thing:-todays</li>
            <content type="text">
<p>Today, I had a seemingly simple problem: position a floating label element inside of a text input field, inside a elastic layout. To achieve an effect like:</p>
<div class="image">
	<img src="/uploads/tf.gif?1219608644" name="tf.gif" width="275">
</div>
<p><br><br>Moreover, I wanted to implement this as a generic javascript widget that I can reuse throughout the application. This was hard, real hard.<br><br>At first, I just used position: absolute and set the position of the label relative the the root document, getting the coordinates required from the position and dimension of the companion text field. Well, this didn't work so well when the window is resized. Too bad we got an elastic layout, if we had a fixed width one I would have been done. My quick and dirty solution was to register the window.onresize callback and reset the positions of the labels whenever the window is resized. This actually worked well in IE, but not so in FF. The problem with FF is that the callback is invoked too sparsely, it's just not responsive enough when you are just dragging the corner of the window around, but you see these labels in all the wrong places while you are dragging around the corner of the browser until you leave your mouse still for a second, at which point the labels receive the event and jump to where they should be. This just plain looks bad, and although your users probably won't resize the window too much, I think it will definitely give the impression of a cheesy app. <br><br>So, my first attempt at a work around is a brute force one. I wrote my onresize callback functionality for FF that is more responsive. Here was the code.<br></p>
<pre><code> /* this is a funny hack in FF to get window resize events more often */
var ffonresize = function(){
    var listeners = [];
    var dim = document.viewport.getDimensions();
    var pe = null;
    pe = new PeriodicalExecuter(function(pe) {
        var nd = document.viewport.getDimensions();
        if (!(nd.width == dim.width && nd.height == dim.height)){
            dim = nd;
            listeners.each(function(l){l(nd)});
        }
    }, 0.2);
    return function(listener){
        listeners.push(listener);
    }
}();
/*
...
*/
if (Prototype.Browser.Gecko)
    ffonresize(this.__onResize);
else
    Event.observe(window, 'resize', this.__onResize);
</code></pre>
<p>This improved the situation, but... not good enough. Then I thought, there must be a way with position: relative to do it. After all, isn't that what it's for?<br><br>I tried making the label element position: relative, but this didn't work: you could shift the position of the element relative to where it would have been, but the space for where it would have been is still taken up, and now it's an empty space...<br>I did some research. One of the best resources is <a href="http://www.quirksmode.org/css/position.html" mce_href="http://www.quirksmode.org/css/position.html">quirksmode </a>again, <a href="http://www.barelyfitz.com/screencast/html-training/css/positioning/" mce_href="http://www.barelyfitz.com/screencast/html-training/css/positioning/">this</a> is also a helpful article. It turns out the common practice to use is to have a container that is relative and then a child under it that is absolute, which will cause the child to use the parent's position as the reference point. But trying the things out didn't work at first. After some trial and error, I figured out that, not only does the parent have to be position: relative, it also had to be display: block. My parent container happened to be table cells, so I either had to set their display to block or add a div under them. Setting their display to block didn't work for me because it completely messed up the layout of the table, so I had to go with the second method.<br><br>Adding the div was annoying because not only did I have to go to a few different places in the app to add the markup, it also made my widget depend on more. Of course, I guess I could inject the div dynamically, but I haven't tried that yet. So, this worked, I no longer had to use the onresize callback and reset the position of the labels, I just set:<br><br></p>
<pre><code>position: absolute;
top: 2px;
right: 5%;</code></pre>
<p><br>Top of 2px to give the top some space, right of 5% to give enough space for the label. Both are relative to the divs I newly added. Well, this kinda worked... except for my short textfields. See, I had long text fields that take up almost 100% of the width of the parent, but also shorter ones that take up about 60%, so while it worked well for the long textfield, sitting right inside it on the right edge, it was well outside of the short textfields. I wanted to use javascript to figure out what's the % of the width of the text field, which I could use to calculate where the label should be, but that number is in my css, and using javascript you can only get dimensions in terms of pixels, i.e., all the percentage info is lost.<br><br>What to do? Well, I calculated the percentage by doing a division between the text field and its parent's width in pixels, this is my code(using prototype.js):<br></p>
<pre><code>right: (1 + 100 * (1 - this.field.getWidth() / 
    this.field.up().getWidth())) + "%"</code></pre>
<p><br>Yeah, it's pretty crazy, but it worked, beautifully. It works in IE7, FF3, and Safari, didn't work in Opera, but that could have been because other javascript bugs I had wrt Opera.<br></p></content>
        </entry>,<entry>
            <title>Maintaining Order in GAE</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/08/15/maintaining-order-in-gae">
            <updated>2008-08-15T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/08/15/maintaining-order-in-gae</li>
            <content type="text">
<p>In a <a href="/Web_Dev_with_Google_App_Engine" mce_href="/Web_Dev_with_Google_App_Engine">previous post</a> I alluded to problems I encountered with using GAE's object model. This is the follow up to that.<br><br>In my todo list app, a main feature was to make reordering your todo list a breeze. When I wrote it with mysql, I used the standard relational database pattern to store an ordered list: create a field SEQ in the items table which holds the a sequence number(integer) that represents the order of the item in the list. But this means for every reordering I do, I have to update all active items in the list. I figured since I am only going to have small lists, it shouldn't matter, and it worked fine with mysql. When I did a port of this to GAE, reordering became terribly slow. A friend of mind told me that this is just a characteristic of object databases. My solution was to create a list field in the parent object(list), which remaps the sequence numbers into the correct order for the items. This way, updating the order only took saving the list object. Of course, this approach is more complicated. There are a couple of other possible approaches:<br></p>
<ol>
	<li>As my friend mentioned: do a link list in the database. Instead of a SEQ field you would have a NEXT field which points to the item that's next to this one. This would make small reorderings(of the type: you take one object and move it to a different place in the list), a constant time operation, in terms of number of updates(3 updates total).</li>
	<li>Make the SEQ field a float, which would allow you to insert a item in between 2 other items with only one update. But because of numerical precision issues, sooner or later you would have to relabel the whole list for the SEQ numbers to be not too close together, which would be triggered like a garbage collection operation would be.</li>
</ol>
<p>My current approach I think is about on par with these 2 in terms of complexity. I like the linked list solution because it's more scalable, you can really reorder/maintain arbitrarily large lists without missing a beat. For my app though, I only need to handle small lists, so I have no reason to switch for now</p></content>
        </entry>,<entry>
            <title>The Best Way to Watch the Olympics</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/08/12/the-best-way-to-watch-the">
            <updated>2008-08-12T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/08/12/the-best-way-to-watch-the</li>
            <content type="text">
<p>Okay, here's the best way to watch the Beijing Olympics(in the US):<br></p>
<ol>
	<li>On a Mac-mini that's hooked up to a 50" DLP Samsung TV or larger...</li>
	<li>Go to nbcolympics.com and click on "TV & Online Listings".</li>
	<li>Fill out some forms to go through which asks what's your TV provider... it's really BS. Don't choose Cablevision or From the Air and you'll be okay.</li>
	<li>When you are through, choose the Online Listings tab, this will list by sport. Live events will show with the listing, so if there are live events you want to watch, just click on that. Otherwise, click on the sport that you are interested in watching and you will get a listing of the prerecorded events that you can watch, click on one and video will start.<br></li>
	<li>The Video player requires Microsoft Silverlight, just follow the steps to install it. It works with Mac too.</li>
	<li>Once the video player is working, and the main content (after the ads) is going, you can click the "Enlarge Video" button on the bottom right.</li>
	<li>There is no fullscreen mode, but that's where the Mac's zoom function comes in. Do Cmd-Option-8 to enable zooming if it isn't already, and then Cmd-Option-=(or plus) to zoom in to the desired size, (Cmd-Option-(minus) to zoom out).</li>
	<li>One last step to hide the mouse cursor by pressing shift-Cmd-4 and the moving the cursor away from the center. Curtesy of this <a href="http://www.macworld.com/article/59809/2007/09/hidecursor.html">article</a>.<br></li>
	<li>That's it! Perfect! Resolution is pretty good, I'd say on par with analog TV. The selection is MUCH MUCH better than on NBC's TV line up. There's no commentary, which could be good and bad, I personally like it. AND, MOST importantly, No Ads! 'nuff said.<br></li>
</ol></content>
        </entry>,<entry>
            <title>Komodo Edit vs E texteditor</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/08/05/komodo-edit-vs-e-texteditor">
            <updated>2008-08-05T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/08/05/komodo-edit-vs-e-texteditor</li>
            <content type="text">
<p>I tried out Komodo Edit - IDE for scripting languages like python and ruby. For work now, I am doing python/turbogears/javascript development, and I have been using E texteditor - a textmate clone for windows, which I have been happy with, but also have a few problems with.<br><br>Komodo Edit is a polished IDE. It has auto-code-complete for python, ruby and javascript libraries out of the box, which E texteditor does not(E texteditor does not support code complete at all). It's code highlighting and code assist support is much more polish than E texteditor's, which I must say, is pretty buggy. It also has one feature that's close to my heart - split view on the same file - which I have enjoyed in my emacs days but have yet to find one editor I liked since which has it. It has a good mako template plugin, which is very important to me since that's what I am using for work, and E texteditor does not yet have. It is not sluggish like Eclipse but actually quite snappy. It is written on Mozilla's XUL framework, and uses the same extension framework that Firefox uses. There's an open source version of Komodo Edit, which you can't say the same about E texteditor.<br><br>So, Komodo Edit is pretty good, but there are some disadvantages wrt E texteditor. The most annoying one, is the crashiness. Sometimes Komodo Edit just crashes without any warning. This can quickly dissuade its users...me...from using it. E texteditor is not free of crashing, but I feel it's more stable. There are also some E texteditor features(mostly from textmate) that I have grown to love and are helpful but are missing from Komodo Edit. One is multiple selection and multiple line selection, these features are huge once you learn to use them. The search and replace feature in E texteditor is much handier and less cluggy, Komodo Edit is this area of UI design is a bit behind. Also, although Komodo Edit's project panel on the left hand side is nice, the search/filter feature is way too slow and so the lack of a "jump to file..." shortcut is inexcusable(plus, E texteditor's jump to file dialog is really nice, it has as-you-type style filtering that permits spelling errors, like Firefox' awesome bar and Launchy).<br><br>So, which one will I use? I am really torn. The two editors are so different in style and philosophy, and each have very compelling advantages over the other. I will probably switch back and forth between the two for a short time before settling on one.<br></p></content>
        </entry>,<entry>
            <title>Web Dev with Google App Engine</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/07/29/web-dev-with-google-app-engine">
            <updated>2008-07-29T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/07/29/web-dev-with-google-app-engine</li>
            <content type="text">
<p>I wrote my first Google App Engine app! It's located at <a href="http://justtodolist.appspot.com">justtodolist.appspot.com</a>. It's yet another todo list - I have been a tadalist user for a while and thought I could make it slightly better, and so I did. Here is to jot down some thoughts on GAE.<br><br>First up, the things I like. <br></p>
<ol>
	<li>The number one benefit of GAE for me is definitely one step deployment. No that you couldn't step up one step deployment for rails apps, but it just takes a lot of work to set this stuff up the first time. With GAE, it's one step deploy the first time. I would say it's easier even than php. A large part because of benefit number two</li>
	<li>there is no database to set up. As most people know by now, you use GQL/Big Table on GAE, and it is very different from relational databases. Setting up is really minimal. You specify your model in a DSL similar to what you'd write with SQLObject or Elixir, or Data Mapper for Ruby folks. And then boom! you are running.</li>
	<li>There's no user authentication to setup either, it's basically Gmail authentication, if you are willing to go along, that is. The User API is very simple, and you can start using it right away</li>
	<li>Development server is nice, it picks up changes immediately when you save any project file</li>
	<li>The number of projects files you have is very minimal, it's very non-cluttery.<br></li>
</ol>
<p>So as you can see GAE is great for rapid prototyping. Now for things I am not that crazy about. Actually, most of the benefits I spoke of has some caveats:<br></p>
<ol>
	<li>Although deployment is easy. Sometimes issues arise from the fact that things work slightly
	differently in production vs development. Such as, you need indices to build fully in production for the app to be ready to run, or for some reason, transaction rules work differently in production vs development(I haven't dug down to this fully, but it might be a bug)</li>
	<li>Big Table is cool, it's supposed to be super scalable, but there are a couple of things that are annoying about it. I can get over the fact that it's fundamentally different from relational databases: things like you can't do aggregate queries, joins and so forth. For performance too, some things you will just have to do differently than you would normally with relation databases. I am okay with that. What pains me is that there is no proper data migration path. When you change your models(add or remove fields, and so forth), the old stuff just stick around. To migrate the old data, you basically have to manually write a script that loops over the existing data structures and modify them, but the script has to be triggered from an http request just like everything else because that's the only way to run your code on GAE on the production server... getto! Also, I am extremely annoyed that while in development you can just clear your datastore. There is no analog in production. I realize though that this is a work in progress and that things will get better in the future.<br></li>
	<li>Well, the caveat for using Gmail authentication is that... your users must have a Gmail account, duh... I am sure you can use other authentication schemes if you want, I don't see anything preventing that</li>
	<li>Yes the development server is nice, but for some reason it was progressively running slower on my company Dell D820 laptop. This is so especially if you perform extensive modification of the data models.</li>
</ol>
<p>Here are some other thoughs:<br></p>
<ol>
	<li>The development console is not good, man! It's no where near the usability of the python interactive shell. I've heard of an alternative but haven't seen it yet.</li>
	<li>I haven't dug into how to do TDD with it yet, but I've read it's possible.</li>
	<li>Again, Big Table is VERY different from relational databases. I originally ported my todo list app from a SQLObject -> MySQL backend, with only 2 data models: TodoList and TodoItem. In Big Table we still have the 2, but they look kinda different. I had to change it because of performance reasons. I'll put the discussion of that on a separate post.</li>
	<li>I haven't got a great handle of how transaction/entity groups work. I thought I did, until my transaction code didn't work, will have to look closer into it. Documentation on this is kinda sparse. Right now my code is non-transactional.</li>
</ol>
<b>Open Source GAE Apps</b>
<p>?<br><br>Here's another thought. Will it be possible to popularize open source GAE apps? I think the most important reason for the popularity of open source php apps is the ease of deployment. With the ease of deployment of GAE, I think conditions might be ripe for there to emerge a movement of good open source GAE apps. Then again though, people might resist the vendor specific/non-open source nature of GAE. We will see.<br><br></p></content>
        </entry>,<entry>
            <title>Impressions of Turbogears 4 months in</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/07/17/impressions-of-turbogears-4">
            <updated>2008-07-17T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/07/17/impressions-of-turbogears-4</li>
            <content type="text">
<p>I've been a user of Turbogears for 4 months now, working on a client facing app. The app has not gone production yet, so I don't have much insight on deployment, but I have a lot of experience on the development side - I started from scratch - and here is what I learned so far.<br><br></p>
<b>Freedom of Choice</b>
<p><br>Turbogears as a framework is pretty agnostic of different components such as ORM, or template engine. Although there is a default choice, I found it wasn't hard to stray away from it. <br><br></p>
<b>Mako</b>
<p><br>I ended up choosing Mako as the template engine because, coming from rails, I felt kid and genshi were too heavyweight for my taste since they are based on XSLT and requires your markup to be valid XML before it can do anything, which obviously means there's an XML parsing step it has to do. Mako is more like erb in that it's "text-based", e.i. it's perfectly fine to render non-valid XML code. But Mako turned out to be much more than another erb. With Mako you can easily write helper template functions and reuse them everywhere. You can also write inversion-of-control template style functions which take in a partial template and calls it inside its body. It always puzzled me why you couldn't do that with erb or haml or most of the ruby template engines easily. With erb, you have to write a partial view as a separate file, but calling a partial with local parameters is inconvient, you have to write something like:<br><br></p>
<pre><code>render :partial =&gt; 'my_control', :locals =&gt; {:control_id =&gt; 'con', 
    :height=&gt; '50px'}</code></pre>
<p><br>and since this is so inconvient, i usually end up wrapping it with a helper method like:<br><br></p>
<pre><code>def my_control(control_id, height)
    render :partial =&gt; 'my_control', :locals =&gt; {        :control_id =&gt; control_id, :height=&gt; height}
end</code></pre>
<p><br>Of course this is partially due to the culture in rails that you normally write helpers in ruby rather than in a template language. In Mako you <a href="http://www.makotemplates.org/docs/syntax.html#syntax_tags_def" mce_href="http://www.makotemplates.org/docs/syntax.html#syntax_tags_def">don't have to do this extra step</a>, which makes me happy. Now if you want to do the inversion of control thing, in erb it's <a href="http://www.igvita.com/2007/03/15/block-helpers-and-dry-views-in-rails/" mce_href="http://www.igvita.com/2007/03/15/block-helpers-and-dry-views-in-rails/">even worse</a>! In mako you would just <a href="http://www.makotemplates.org/docs/defs.html#defs_defswithcontent" mce_href="http://www.makotemplates.org/docs/defs.html#defs_defswithcontent">do this</a>. So, in general, I am able to refactor my views a lot easier with mako and therefore I find myself doing it a lot more often.<br><br></p>
<b>SQLAlchemy</b>
<p><br>SQLAlchemy is a main stream ORM in the python community. It's direction is different from that of ActiveRecord and is a lot more similar to Hibernate of Java but also has similarities to Ambition of Ruby and Linq of .NET. It is similar to Hibernate in that it is very fully featured, has sessional transaction management, and can coupe with a large variety of schemas. It is similar to ambition and linq in that you can contruct queries in your host language in a very succint and elegant way(I know you can build queries in Hibernate's criteria API too, but it's not quite elegant). I like SQLAlchemy a lot! Here's a couple of sqlalchemy tricks I like. First one:<br><br></p>
<pre><code>    fields = [
        User.user_name,
        User.display_name,
        User.email_address
    ]
    results = User.query.filter(or_(*[f.ilike('%' + q + '%')         for f in fields]))</code></pre>
<p><br>The above code does a wildcard partial string match of the string q against any of the three fields listed in the fields list. Second example:<br><br></p>
<pre><code>    page = User.query[10:20]</code></pre>
<p>            <br>This looks like array slicing, but no, it's slicing against the query results! It's smart enough to build the query using OFFSET and LIMIT or equivalent. You can easily do pagination with this technique.<br><br></p>
<b>Python's Named Parameters</b>
<p><br>Another thing I like when working with turbogears is python's <a href="http://tobyho.com/parameter_list_chaining_in_python">named parameters</a>. Whereas rubists use the hash as the poor man's name parameters, python has real named parameters, which is not only <a href="/How_safe_is_your_programming_language" mce_href="/How_safe_is_your_programming_language">safer</a>, but more elegant.<br><br></p>
<b>Python's Polluted Name Space</b>
<p><br>I run into this problem once in a while, but I hit on it 2 or 3 times in the last week! In python, <i>list</i>, <i>dict</i>, <i>str</i>, <i>int</i>, etc. are the names of fundamental types in the language, therefore you can't(actually you can, but don't want to) use them as variable names. More than once I've tried to use <i>list</i> as a variable name, which python doesn't complain about immediately but causes a cryptic error down the road. <br>I've also tried use <i>from</i> as a variable name, which turns out to be a keyword in the language, this causes a syntax error, which you don't see until you realize it's a keyword. Now, of course, more languages suffer from this problem, ruby isn't any different, but I think ruby has better error messages for these syntax errors: it will tell you the symbol that is unexpected and what symbols it was expecting.<br><br></p>
<b>Little Verbosity</b>
<p><br>Turbogears is more verbose than rails most prominently in 2 areas: import statements and method decorators. Rails files, usually have at most 2 requires(counterpart of import in python), most of the time none at all. My TG controller files and the model.py(the file with all the model objects) usually have about 10 to 15 lines of includes, my Mako template files usually 2 to 4 lines of includes. This has a lot to do with the design of the language. The python interpreter requires each .py file to act like a module, and as a module, it must identify all of its dependences, the ruby interpreter does not require this and so your controller code, for example, doesn't need to explicitly require anything before it has what it needs to do its work.<br>I think method decorators are cool, but they can also be overused and become cluttery. Some of my controller methods have more than 4 or 5 lines of decorators, consisting of the mandatory expose(), access restriction spec, and form parameter validators. That's a bit much. I also don't like the fact that you need an expose() decorator for every single controller method. Rails has no such thing and usually specifies such things at the top of the class, which has pros and cons vs TG's approach, but is at the end less cluttery.<br><br></p></content>
        </entry>,<entry>
            <title>function dot toString()</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/07/15/function-dot-tostring()">
            <updated>2008-07-15T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/07/15/function-dot-tostring()</li>
            <content type="text">
<p>function.toString() has different behavior between IE and FF. FF collapses the parameter list onto one line, while IE leaves it untouched. Ex:<br></p>
<pre><code>function f(
  param1,
  param2,
  param3){
  ...
}
f.toString();</code></pre>
<p>In FF you would get something like: <br></p>
<pre><code>function(param1, param2, param3){
...
}</code></pre>
<p>in IE:<br></p>
<pre><code>function f(
  param1,
  param2,
  param3){
...
}</code></pre>
<p><br>In IE, this breaks function.argumentNames() in prototype.js, so don't break the parameter list into multiple lines if you are using prototype.js, or until they fix it. Also, notice that FF removes the name of the function in the toString() output.<br></p></content>
        </entry>,<entry>
            <title>Parameter List Chaining in Python</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/07/15/parameter-list-chaining-in">
            <updated>2008-07-15T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/07/15/parameter-list-chaining-in</li>
            <content type="text">
<p>Python has great support for variable length parameter lists, you have optional parameters:<br><br></p>
<pre><code>&gt;&gt;&gt; def o(opt=1):
...   print opt
...
&gt;&gt;&gt; o()
1
&gt;&gt;&gt; o(2)
2
&gt;&gt;&gt; o(opt=3)
3</code></pre>
<p><br><br>then you have the one star for any number of parameters:<br><br></p>
<pre><code>&gt;&gt;&gt; def f(*params):
...   for p in params: # params is a list
...     print p
...
&gt;&gt;&gt; f(1)
1
&gt;&gt;&gt; f(1,2,3,4)
1
2
3
4</code></pre>
<p><br>and you got two stars for keyword parameters:<br><br></p>
<pre><code>&gt;&gt;&gt; def g(**kws):
...   for item in kws.items(): # kws is a dict
...     print item
...
&gt;&gt;&gt; g(one=1)
('one', 1)
&gt;&gt;&gt; g(one=1, two=2, three=3)
('three', 3)
('two', 2)
('one', 1)</code></pre>
<p><br>You can also use them together along with regular parameters and optional parameters as long as they follow the ordering: regular > optional > single star(varargs) > double star(keyword args):<br><br></p>
<pre><code>&gt;&gt;&gt; def h(req, opt=None, *params, **kws):
...   print 'req=', req
...   print 'opt=', opt
...   print 'params=', params
...   print 'kws=', kws
...
&gt;&gt;&gt; h(1,2,3,4)
req= 1
opt= 2
params= (3, 4)
kws= {}
&gt;&gt;&gt; h(1,two=2,three=3,four=4)
req= 1
opt= None
params= ()
kws= {'four': 4, 'two': 2, 'three': 3}
&gt;&gt;&gt; h(1,two=2,three=3,opt=4)
req= 1
opt= 4
params= ()
kws= {'two': 2, 'three': 3}
</code></pre>
<p>If you have a handle on a list or a dict object, you can use it/them directly as the parameter list when you call a function:<br><br></p>
<pre><code>&gt;&gt;&gt; lst = [1,2,3]
&gt;&gt;&gt; f(*lst)
1
2
3
&gt;&gt;&gt; dct = dict(one=1,two=2,three=3)
&gt;&gt;&gt; g(**dct)
('one', 1)
('three', 3)
('two', 2)</code></pre>
<p><br>A techique I developed is to chain function calls lazily, sort of a poor man's <a href="http://oakwinter.com/code/functional/" mce_href="http://oakwinter.com/code/functional/">partial function application</a>. Say I have a function that takes a lot of optional parameters, let's say it generates a text field of some sort:<br><br></p>
<pre><code>def textfield(label, name, size=10, classname='', id=None, 
    onclick=None, onkeypress=None):
    # blah</code></pre>
<p><br>Now for my specific screen I want to specify a number of these parameters by default, and only vary the label and name parameters the rest of the way, so I do something like:<br><br></p>
<pre><code>def tf(*params, **kws):
    textfield(size=20, classname='cool-field', *params, **kws)</code></pre>
<p><br>now I can call it like this:<br></p>
<pre><code>tf('Name', 'name')
tf('Birthdate', 'birthdate', onkeypress="checkBirthdate(this)")</code></pre>
<p><br>The cool part about this is that I can add new optional parameters to textfield without having to change tf and yet still be able to use the new parameters from tf. I could have just as well use the partial function from the <a href="http://oakwinter.com/code/functional/" mce_href="http://oakwinter.com/code/functional/">functional library</a>, but this is pretty easy too.<br></p></content>
        </entry>,<entry>
            <title>prototype descendantsOf works different in FF than IE</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/30/prototype-descendantsof-works">
            <updated>2008-06-30T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/30/prototype-descendantsof-works</li>
            <content type="text">
<p>I haven't dug down to the bottom of this but basically Element.descendantOf(elm, ans) gives different results from IE vs FF.<br></p></content>
        </entry>,<entry>
            <title>button element in IE - set type</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/30/button-element-in-ie---set">
            <updated>2008-06-30T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/30/button-element-in-ie---set</li>
            <content type="text">
<p>If you use the button element, make sure you set the type attribute:<br><button type="submit">Submit</button><br><br>Otherwise, it won't submit it's parent form when clicked in IE.<br></p></content>
        </entry>,<entry>
            <title>FF3 vs FF2 setting of position and width</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/23/ff3-vs-ff2-setting-of-position">
            <updated>2008-06-23T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/23/ff3-vs-ff2-setting-of-position</li>
            <content type="text">
<p>Wow, FF3 broke my app!<br><br>I had a line like this(sorry this code uses prototype.js, but it's not specific to it):<br>myDiv.setStyle({<br>
    position: 'absolute',<br>
    top: elmPos.top + elm.offsetHeight,<br>
    left: elmPos.left,<br>
    width: elm.offsetWidth - 5});<br><br>This won't work anymore because starting FF3, you can't set the attributes: top, left, width, height to numeric values anymore, they have to labeled with a unit, like so:<br>myDiv.setStyle({<br>    position: 'absolute',<br>    top: asPx(elmPos.top + elm.offsetHeight),<br>    left: asPx(elmPos.left),<br>    width: asPx(elm.offsetWidth - 5)});<br><br>Where asPx is:<br>function asPx(n){<br>    return n + 'px';<br>}<br></p></content>
        </entry>,<entry>
            <title>How to Remove the Scrollbar from your Browser Window</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/18/how-to-remove-the-scrollbar">
            <updated>2008-06-18T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/18/how-to-remove-the-scrollbar</li>
            <content type="text">
<p>In your body tag, do this:<br><br></p>
<pre><code>&lt;body scroll="no" style="overflow: hidden"&gt;
</code></pre></content>
        </entry>,<entry>
            <title>pyatl functional programming talk</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/17/pyatl-functional-programming">
            <updated>2008-06-17T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/17/pyatl-functional-programming</li>
            <content type="text">
<p>The talk went pretty well I thought, I listened to the audio that I recorded of it, and it wasn't lame =) <a href="http://docs.google.com/Presentation?id=dc9b9pxs_60dhqd5ths">Here are the slides</a>.<br></p></content>
        </entry>,<entry>
            <title>Setting a multiline value of Text Input Field</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/13/setting-a-multiline-value-of">
            <updated>2008-06-13T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/13/setting-a-multiline-value-of</li>
            <content type="text">
<p>This behaves differently on FF vs IE. If you do:<br><br></p>
<pre><code>textInput.value = "line one\nline two";
</code></pre>
<p><br>Where textInput is an input element with type="text". FF ignores the second line and sets the value to the contents of the first line, whereas IE removes the newlines and merges all the lines into one.<br><br></p></content>
        </entry>,<entry>
            <title>Beef with Frog!</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/10/beef-with-frog!">
            <updated>2008-06-10T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/10/beef-with-frog!</li>
            <content type="text">
<p>Dang! Frogger! You no behave right!<br><br>I am getting proficient enough with the black USB froggie to start doing some real work, but this bug that I finally uncovered make using it really painful. Whenever I use the ctrl-s combination on the frogpad, the ctrl key will lock, eventhough the ctrl indicator does not show it. This kinda makes everything you do after that difficult. No, this does not have the feel of a polished product.<br></p></content>
        </entry>,<entry>
            <title>Calling for a Change in How Fouls Are Penalized in the NBA</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/09/calling-for-a-change-in-how">
            <updated>2008-06-09T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/09/calling-for-a-change-in-how</li>
            <content type="text">
<p>I think that the rules for penalizing fouls in the NBA are fundamentally flawed. Let me explain. Increasingly, teams are using intentional foul as a tool. These are some of the ways they are used:<br></p>
<ol>
	<li>Near the end of the game, the losing team often fouls the opposing team in order to get the ball back for a chance to pull closer. Here they are hoping that the opponent miss their free throws, or that even if the free throws are made, they can make a 3-pointer the next time to close the lead by 1.<br></li>
	<li>A new practice called hack-a-shaq is when a team intentionally fouls a bad free throw shooter on the opposing team, usually to prevent them from getting a better shot.</li>
	<li>Very near the end of the game, when the defending team is up by 3 or 4 points. The other team has say 20 seconds to make a shot. The defending team will sometimes intentionally foul even not in the act of shooting when the clock goes down to around 5 seconds. The logic is that although the opponents can pull within one with the free throws, they will have no time to get any closer because they would have to give up the ball after the free throws.</li>
	<li>The prevent-a-sure-shot foul: in any good defensive team, it is common sense that you should not give up any easy shots, and that means fouling intentionally is encouraged when you see your opponent on his way to an easy lay-up, dunk, break away, or just a routine shot by a hot shooter. Again, the defending team hopes that in sending the shooter to the free throw line, he may miss, in which case the opposing team would have gained fewer points. In fact, it's a duty of the players to commit these fouls in order to prevent easy shots in defensive minded teams.</li>
</ol>
<p>What's the problem with this?<br></p>
<ol>
	<li>It distracts from playing the real game, and slows down the tempo of the game.<br></li>
	<li>A high number of fouls adversely affect the spirit of the game, it encourages unsportsman behavior, and sets bad examples for children, not to mention the sportsmanship spirit of the nation/world as a whole.</li>
	<li>Fouls should be penalized, and in no circumstance should they be rewarded, but, judging from the fact that intentional fouls are so prevalently used, this is clearly not the case.<br></li>
</ol>
<p>Regarding point #3. Let's take a look at how other sports handle this.<br></p>
<ol>
	<li>Football: I am not a big fan of football rules either, but at least they got this one right. Fouls such as <i>unnecessary roughness</i> and <i>face mask</i> are penalized heavily - 15 yards - and they replay the down. Plus, the team that was fouled has the option of letting the penalty go if they happened to make a big play dispite the foul.</li>
	<li>Soccer: the team that was fouled gets possesion of the ball. You get carded for violent fouls which could put you out of the game. If you foul inside the penalty box the opponent gets a penalty shot.<br></li>
</ol>
<p>Intentionally fouling is unheard-of in these sports because there is no incentive in fouling, and that's how it should be in all sports. The fact that it is not so in basketball reflects how convoluted its rules are.<br><br>What can be done?<br><br>I think that there's a very simple solution to this: we change the rules so that <i>you always get the ball back after being fouled, whether or not you get any free throw attempts</i>. All the above problems would be gone. Plus, as a result, we will have a much faster paced game.<br><i><br>Update: alternatively, we could take NFL's approach and make it an option for the team who's fouled: you can either take the free throw or keep possession of the ball.</i></p></content>
        </entry>,<entry>
            <title>Update on the Frogpad</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/05/update-on-the-frogpad">
            <updated>2008-06-05T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/05/update-on-the-frogpad</li>
            <content type="text">
<p>Here's the latest on the frogpad. I exchanged my bluetooth frogpad for a USB one, and the reason is: the USB one had a <a href="/Love_hate_relationship_with_the_frog">non-sticky symbol key</a>: so, the latest product(the bluetooth version) is worse than the earlier one(the USB), at least from my perspective. The USB one works a look better in terms of typing in symbols, at I expected. I am still using only on and off though, so I really need a lot more practice before I can use it for normal work. I do use it at work some times, and it's quite easy to switch back and forth, and/or have a different key input for different windows.<br></p></content>
        </entry>,<entry>
            <title>Prototype's Element dot extend</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/04/prototype's-element-dot-extend">
            <updated>2008-06-04T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/04/prototype's-element-dot-extend</li>
            <content type="text">
<p>Element.extend is an important method is the prototype framework. It adds all the helper/mixin methods to a dom element, like this:<br>Element.extend(myElem);<br>If for some reason you have to do this manually(probably in IE), this is what you need.<br></p></content>
        </entry>,<entry>
            <title>Use up() instead of parentNode</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/04/use-up()-instead-of-parentnode">
            <updated>2008-06-04T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/04/use-up()-instead-of-parentnode</li>
            <content type="text">
<p>With prototype.js, you should use element.up() instead of element.parentNode. This is again because of <a href="/FF%27s_built_in_Element_class">this browser difference</a>.<br></p></content>
        </entry>,<entry>
            <title>FF's built in Element class</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/04/ff's-built-in-element-class">
            <updated>2008-06-04T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/04/ff's-built-in-element-class</li>
            <content type="text">
<p>FF has a built-in Element "class". Which means that you can extend it like this:<br>Element.prototype.mymethod = function(){<br>  //blah<br>}<br>and have the method be available from any dom element, no prototype.js needed.<br>document.getElementById('myDiv').mymethod();<br>This is what explains <a href="/FF%27s_built_in_Element_class">this previous post</a>.<br></p></content>
        </entry>,<entry>
            <title>childNodes: FF gives you text objects for empty space and newlines IE does not</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/04/childnodes:-ff-gives-you-text">
            <updated>2008-06-04T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/04/childnodes:-ff-gives-you-text</li>
            <content type="text">
<p>Let's say you have markup like follows:<br><div id="foo"><br>        <div id="bar">hey</div><br></div><br>In IE, document.getElementById('foo').childNodes.length gives you 1, but FF gives you 3, with the first and last items being text elements representing the newline and white space in between. This means you cannot rely on accessing childNodes directly by index.<br><br>Solution:<br>If you are using prototype.js, use firstDescendant() instead of childNodes[0]. Use select() to get select the elements you want instead of traversing childNodes directly.<br></p></content>
        </entry>,<entry>
            <title>Non-standard attributes show up in innerHTML in IE but not in FF</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/04/non-standard-attributes-show">
            <updated>2008-06-04T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/04/non-standard-attributes-show</li>
            <content type="text">
<p>Phew! This one bug took me hours to track down the root cause. Which is this: If you set a non-standard attribute on a dom element, say _eventID, like so:<br>$('myDiv')._eventID = 12<br>Now, the _eventID attribute will be displayed inside the innerHTML of any of its ancestors in IE, but not in FF:<br>$('myDiv').parentNode.innerHTML<br>in IE you'd see something like:<br><div id=myDiv _eventID="12">...</div><br>in FF(keep in mind the value is still saved, just doesn't show up in the innerHTML):<br><div id="myDiv">...</div><br></p></content>
        </entry>,<entry>
            <title>Microsoft Script Debugger</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/03/microsoft-script-debugger">
            <updated>2008-06-03T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/03/microsoft-script-debugger</li>
            <content type="text">
<p>I've finally gotten the hang of the Microsoft Script Debugger. I can now debug Ajax code in IE with relative ease. Before this, the error line number IE gives is always wrong, so there's no good way to know what is wrong with your code. I tried firebug lite, which provides the console, and is handy, but it has no debugging capability. The Script Debugger is very different from firebug, so you have to get use to it, and even maybe read the help pages. But once you figure out, it's very helpful, well because you are comparing it to having not debugger or a use full stacktrace message at all. It does have a command window, which is kinda different from firebug also, but once again, you can get used to it. And the call stack window is very useful for spotting where an error has occured.<br><br>Negatives: it does crash a lot, as with everything Microsoft. And once it had a bug where the included javascript files in the page would not show up at all. It was eventually fixed I think after a reboot. Still, better than nothing.<br></p></content>
        </entry>,<entry>
            <title>Cannot set innerHTML of a tr element</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/03/cannot-set-innerhtml-of-a-tr">
            <updated>2008-06-03T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/03/cannot-set-innerhtml-of-a-tr</li>
            <content type="text">
<p>Dude, this is wrong. According to <a href="http://msdn.microsoft.com/en-us/library/ms532998%28VS.85%29.aspx" mce_href="http://msdn.microsoft.com/en-us/library/ms532998%28VS.85%29.aspx">this </a>and <a href="http://lists.evolt.org/archive/Week-of-Mon-20060403/181426.html" mce_href="http://lists.evolt.org/archive/Week-of-Mon-20060403/181426.html">other resources</a>, plus my own experimentation has confirmed, you cannot set the innerHTML of a TR element in a table in IE. In FF this works fine, provided it maintains the integrity of the table structure. But in IE it throws an </p>
<b>"Unknown runtime error"</b>
<p>. This breaks the whole strategy used in my collection widget...definitely not fun.<br></p></content>
        </entry>,<entry>
            <title>Acrobat dot com</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/03/acrobat-dot-com">
            <updated>2008-06-03T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/03/acrobat-dot-com</li>
            <content type="text">
<p>Wow! Adobe rolled out a competitor to netmeeting, and google word doc: <a href="https://acrobat.com/">acrobat.com</a>. All flash based, the screen sharing part requires an extra plugin install. The UI is just amazing. I played with it and it is very usable. There's a shared whiteboard, and you can also share your monitor. In addition, you can do web cam, audio, chat, live document editing. It's just a super cool app.<br></p></content>
        </entry>,<entry>
            <title>class is a keyword in IE</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/03/class-is-a-keyword-in-ie">
            <updated>2008-06-03T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/03/class-is-a-keyword-in-ie</li>
            <content type="text">
<p>You can't use it as the name of a variable or 'naked' as the key of a hash. Both are allowed in FF.<br></p></content>
        </entry>,<entry>
            <title>innerHTML browser differences</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/02/innerhtml-browser-differences">
            <updated>2008-06-02T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/02/innerhtml-browser-differences</li>
            <content type="text">
<p>I have been fixing some IE7 bugs with my Ajax code lately and I am going to start documenting some of the problems I've encountered and their solution. These will be tagged <i>crossbrowser</i>. The first one is innerHTML. FF gives a different result than IE given the same dom structure. For example: <br>FF:<br><span class="info">blah</span><br>IE7:<br><SPAN class=info>blah</SPAN><br><br>Right off the bat the case on the tag names is different. And secondly the attributes in FF is quoted while in IE they are not. For these reasons, it's not smart to do string comparisons on the innerHTML of elements.<br></p></content>
        </entry>,<entry>
            <title>Arrays with extra commas at the end</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/02/arrays-with-extra-commas-at">
            <updated>2008-06-02T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/02/arrays-with-extra-commas-at</li>
            <content type="text">
<p>In FF:<br>[1,2,3,].length<br>gives you 3, but in IE:<br>[1,2,3,].length<br>gives you 4, and <br>[1,2,3,][3]<br>gives you undefined<br></p></content>
        </entry>,<entry>
            <title>Prototype extension methods load time difference</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/06/02/prototype-extension-methods">
            <updated>2008-06-02T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/06/02/prototype-extension-methods</li>
            <content type="text">
<p>If you use prototype.js, you know that the library adds many helper methods to the standard types. But for the Element type(i.e. elements in a page), did you know that these methods are loaded at different times depending on which browser it is. FF loads the methods at the time of creation, so as soon as you do:<br>myDiv = document.createElement('div');<br>all the helpers are available to you from myDiv.<br>But, in IE, this is not the case. </p>
<strike>Instead IE loads the methods at the time you insert the elemnet into the page:<br>parent.insert(myDiv);</strike>
<p><br><i><br>Correction:</i><i> In IE you must either manually extend the element, <a href="/Prototype%27s_Element_dot_extend">see here</a>, or locate the element using $() or other locate function in prototype.js in order to get the helper methods.</i><br></p></content>
        </entry>,<entry>
            <title>The Music Chair Podcast</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/05/31/the-music-chair-podcast">
            <updated>2008-05-31T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/05/31/the-music-chair-podcast</li>
            <content type="text">
<p>I am proud to announce the first episode of my podcast: <a href="http://musicchair.org">The Music Chair</a>. I am now a podcaster! I have done two interviews so far. But, one of them is till not out due to technical issues. I am excited about this project, because I love the music, the personalities, and also I realized this will help improve my speaking skills tremedously. Please go and subscribe using iTunes, and give my suggestions and feedback.<br></p></content>
        </entry>,<entry>
            <title>e-texteditor: getting my ctrl-z back</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/05/28/e-texteditor:-getting-my-ctrl">
            <updated>2008-05-28T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/05/28/e-texteditor:-getting-my-ctrl</li>
            <content type="text">
<p>As I mentioned in a <a href="/Dvorak_layout_with_QWERTY_shortcuts_for_windows">previous post</a>, I am now using the dvorak keyboard with hacked in qwerty shortcuts. But recently, my e-texteditor ctrl-z shortcut key doesn't work anymore and instead keeps inserting an error message in my buffer... how annoying is that? I don't see any circumcetance when it's okay to insert an error message directly into your working document, that is just wrong! But, that's not the point. I found out that the ctrl-z combination is somehow triggering the spellchecker command instead of undo...how could this be? I did a little detective work an AH-HA! It turns out that in the text-bundle, the ctrl-; combination triggers the spellcheck, and ; in dvorak is z in qwerty... removed that key combination and everything was fine...phew...<br></p></content>
        </entry>,<entry>
            <title>Getting the Argument Names of Your Function</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/05/21/getting-the-argument-names-of">
            <updated>2008-05-21T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/05/21/getting-the-argument-names-of</li>
            <content type="text">
<p>In Javascript:<br>myfunction.toString()<br>This gives you the entire definition of the function as a string, with which you can parse to get the argument names, or in prototype.js you can just do:<br>myfunction.argumentNames()<br><br>In Python:<br>myfunction.func_code.co_varnames<br><br>In Ruby, there is no easy way to do this, although there is A way, which involves setting a trace function on the function and then executing it to get at the local variables at execution time, see <a href="http://eigenclass.org/hiki/method+arguments+via+introspection" mce_href="http://eigenclass.org/hiki/method+arguments+via+introspection">here</a>.<br><br><br><br><br></p></content>
        </entry>,<entry>
            <title>Constructor Chaining in Prototype</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/05/20/constructor-chaining-in">
            <updated>2008-05-20T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/05/20/constructor-chaining-in</li>
            <content type="text">
<p>Ever wonder how to do constructor chaining in prototype.js?<br>Here's how:<br><br></p>
<pre><code>var Person = Class.create({

  initialize: function(){
    console.log('hello world!');
  }
});
var Pirate = Class.create(Person,{
  initialize: function($super){
    console.log('before super');
    $super();
    console.log('after super');
  }
});
new Person();
new Pirate();</code></pre>
<p><br>The $super parameter is "special", and is detected by the library. It gives you a reference to the method of the same name defined in the super class(Ruby style, basically). Notice that unlike Java, you can do stuff before super's constructor is called. For more, see <a href="http://www.prototypejs.org/learn/class-inheritance" mce_href="http://www.prototypejs.org/learn/class-inheritance">here</a>.<br></p></content>
        </entry>,<entry>
            <title>Dvorak layout with QWERTY shortcuts for windows</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/05/20/dvorak-layout-with-qwerty">
            <updated>2008-05-20T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/05/20/dvorak-layout-with-qwerty</li>
            <content type="text">
<p>Finally, this is what I've been looking for. Having to switch to the Dvorak Keyboard layout means that you have to give up the convinent one handed QWERTY shortcuts: ctl-x, ctl-z, ctl-v and ctl-c. Now I've found that Mac and now Ubuntu let's you have dvorak but QWERTY shortcuts at the same time! Where's the Windows equivalent of that? <a href="http://send2adtc.googlepages.com/dvqwmod">Here it is</a>.<br><br><i>Update: Hmm, interestingly, this doesn't work at all inside firefox...</i><br></p></content>
        </entry>,<entry>
            <title>Installing Ubuntu on the Old Sony Vaio without a CDROM</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/05/19/installing-ubuntu-on-the-old">
            <updated>2008-05-19T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/05/19/installing-ubuntu-on-the-old</li>
            <content type="text">
<p>Now that Weilai had to return her dell laptop, she had the idea to resurrect her old Sony Vaio PCG-R505DL laptop(She didn't like my wide screen HP because it's too big). Since the CDROM for this laptop - which is on the dock - is broken, I've had to install linux on it the last time I resurrected it by starting out with a floppy to boot and then going to the network - it was a Mandrake install. This time I wanted to install Ubuntu on it since it's the best distribution nowadays. However, installing Ubuntu from floppy isn't very well documented. I also looked at installing fro a USB stick, but unfortunately my BIOS didn't supporting booting from it. I've had to dig around for this one. The solution to my problem was found <a href="http://efod.se/blog/archive/2006/11/29/installing-ubuntu-on-a-machine-with-no-cdrom-drive">here</a> - network booting using PXE. The steps were essentially: <br></p>
<ol>
	<li>make a gPXE boot floppy</li>
	<li>setup a tftp server that serves a subdirectory of the contents of the ubuntu CD - which has the boot file needed for the client to boot<br></li>
	<li>runand configure your own dhcpd server on the local network which will tell the client - our vaio in this case - where to get the boot file when it boots up<br></li>
	<li>boot the client with the floppy</li>
</ol>
<p>What you need to understand is that the network communications are all going to be happening in levels lower than IP and TCP. They are happening at the DHCP and UDP level (although you have the option of using http in place of tftpd now with gPXE). So, all that's required for the discovery is for your intranet to have one dhcp server running which is configured to tell the client that's booting the right boot file. The discovery is done is a broadcast fashion because it's part of the dhcp protocol. I am explaining this because this was confusing to me. <br><br>For me, I had to change a couple of steps. First, I didn't have a linux box at home, only a Mac. But getting dhcpd installed was not hard, I found step-by-step instructions <a href="http://macosx.com/forums/howto-faqs/14022-howto-setup-dhcpd-server-mac-os-x-workstation.html">here</a>. And tftpd already comes with OSX, to my surprise, so I simply had to turn it on:<br>sudo launchctl load -w /System/Library/LaunchDaemons/tftp.plist<br><a href="http://www.macosxhints.com/article.php?story=20070218233806794">This page</a> was helpful there. The tftp server is serving files from /private/tftpboot, so I copied the boot files into that directory - which I found from <br>http://archive.ubuntu.com/ubuntu/dists/hardy/main/installer-i386/current/images/netboot/<br><br>Also, it turns out that I did not need a floppy for my installation at all - eventhough I uselessly made one. The BIOS already had the ability to network boot using the PXE protocol, I just had to turn the option on.<br><br>After that, the laptop booted straight to the ubuntu install prompt, and it installed as normal. Brilliant! This really opened my eyes to how cool network booting is, I wonder if you could run the laptop as a thin terminal running say OSX... I am sure you can, actually, but I just don't know how to set up the boot images on the servers side. Hmm...<br></p></content>
        </entry>,<entry>
            <title>书法with Vistablet</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/05/11/书法with-vistablet">
            <updated>2008-05-11T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/05/11/书法with-vistablet</li>
            <content type="text">
<p> I bought a<a href="https://www.vistablet.net/catalog/product_info.php?products_id=28">vistablet</a> today.  And I found that with it you can write 书法，and I am taking advantage of it. Here's my first attempt.<br><br></p>
<div class="image">
	<img src="http://wiki.futuretoby.com/uploads/chun%20xiao.png?1210476776" mce_src="http://wiki.futuretoby.com/uploads/chun%20xiao.png?1210476776" name="chun xiao.png" width="650">
</div></content>
        </entry>,<entry>
            <title>Change File Associations in E-TextEditor</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/04/29/change-file-associations-in-e">
            <updated>2008-04-29T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/04/29/change-file-associations-in-e</li>
            <content type="text">
<p>To add a file extension to have a bundle autoloaded for it. You would go to the file:<br>C:\Program Files\e\Bundles\<i>blah.tmbundle</i>\Syntaxes\<i>blah.plist<br><br></i>And add an entry under:<br><dict><br>    <key>fileTypes</key><br>    <array><br>        <string>html</string><br>        <string>htm</string><br>        <string>shtml</string><br>        <string>xhtml</string><br>        <string>phtml</string><br>        <string>php</string><br>        <string>inc</string><br>        <string>tmpl</string><br>        <string>tpl</string><br>        <string>ctp</string><br><br>Restart e and you are done.<br></p></content>
        </entry>,<entry>
            <title>Love hate relationship with the frog</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/04/24/love-hate-relationship-with">
            <updated>2008-04-24T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/04/24/love-hate-relationship-with</li>
            <content type="text">
<p>Sigh... I like typing on the frog. But till now, I haven't been able to use it for my programing work because, while it is quite good for typing in English, it is lousy for typing programs. This is because symbols on the frog are a pain to type. You have to hit one key to go into symbol mode(it's modal) hit your symbol, and then another key stroke to go out of symbol mode. In most programming langages(except maybe COBOL), you alternate between letters and symbols quite often, this is why the frog may not be suitable for programming. Can you reprogram the keys? I don't know, haven't found any resources on it yet. I later found that the USB version of the frog is better in this respect because the symbol key is non-modal(like the shift key). No word yet on whether I can get my Bluetooth version to do that though. Keeping an eye on this <a href="http://frogpad.zeroforum.com/zerothread?id=1057">thread</a>.<br></p></content>
        </entry>,<entry>
            <title>How to unset the style in your DOM element</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/04/18/how-to-unset-the-style-in-your">
            <updated>2008-04-18T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/04/18/how-to-unset-the-style-in-your</li>
            <content type="text">
<p>element.setAttribute('style',' ')<br><br>Notice the second argument is a space, NOT the empty string. The empty string will not work, it will just ignore it. I've only tested this on FF so far.<br></p></content>
        </entry>,<entry>
            <title>Belkin Stereo iPod Microphone</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/04/18/belkin-stereo-ipod-microphone">
            <updated>2008-04-18T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/04/18/belkin-stereo-ipod-microphone</li>
            <content type="text">
<p>I got my microphone in the mail yesterday, now I can use it to record interviews or music. It did take some effort to set up, though, mostly because of the fact that I have a Mac and Windows setup. I have been syncing my ipod with my Mac machine, and now I want to be able to access my voice recordings from my windows laptop. This is a problem because my ipod was formated in the mac format, googling found that I can reformat it to fat32 and have it work for both mac and windows, so that's what I did. I also set enable-hard-disk-usage to true and start-itunes-when-ipod-plugged-in to false so that from windows I can get at the voice memo wav files without having to go through itunes. I still use the mac machine to sync my music, this works just like before.<br></p></content>
        </entry>,<entry>
            <title>Sunday Brunch at Pisces Seafood and Jazz</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/04/13/sunday-brunch-at-pisces">
            <updated>2008-04-13T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/04/13/sunday-brunch-at-pisces</li>
            <content type="text">
<p>We paid Ike Stubblefield's band a visit today at Pisces today. Dave Frackenpohl was there accompanying him, it was a classic hammond B3 - guitar trio, just like the Jimmy Smith and Wes Montgomery band, what a great sound! This is a nice location for us, and Sunday is a nice place too, so we'll definitely be caming back.<br></p></content>
        </entry>,<entry>
            <title>My Jazz Calendar</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/04/12/my-jazz-calendar">
            <updated>2008-04-12T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/04/12/my-jazz-calendar</li>
            <content type="text">
<p><a href="http://www.google.com/calendar/embed?src=5m3ev72ushfqdvbnnb3pne6eps%40group.calendar.google.com&ctz=America/New_York">Jazz Jam Sessions and Shows.</a><br><br><br></p></content>
        </entry>,<entry>
            <title>Blogging on my Frogpad</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/04/08/blogging-on-my-frogpad">
            <updated>2008-04-08T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/04/08/blogging-on-my-frogpad</li>
            <content type="text">
<p>So I've had my frogpad for about half a month now. I've been practicing on it about a hour every two or three days, and.. this is my first blog post on it! I still obiviously need a lot more practice, but it's coming along.<br>I tell ya, not having to switch back and forth between the keyword and the mouse does change the way you do things a lot. You'll find that you'll be able to use the mouse in a lot more situations where you normally wouldn't. This is cool! As for my normal typing, because I've been switch back to it for my normal usage, I've sort of overcome the <a href="/Frogpad_growing_pains" mce_href="/Frogpad_growing_pains">skill deteriation</a> there. <br></p></content>
        </entry>,<entry>
            <title>Bulls Blood of Eger 2003</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/04/05/bulls-blood-of-eger-2003">
            <updated>2008-04-05T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/04/05/bulls-blood-of-eger-2003</li>
            <content type="text">
<p>Thought we'd give hungarian wine a try. This wine started out very candy-like on the nose, but after decanting for a couple of hours that died down a bit and it became a very veggie nose, very bland, almost smelled like tea. On the palette was very bland as well, again, veggie, almost like a V8 drink. I thought the taste just didn't integrate well for me. Weilai and I both give it a 70.<br></p></content>
        </entry>,<entry>
            <title>Twitter Script with Snarl</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/04/04/twitter-script-with-snarl">
            <updated>2008-04-04T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/04/04/twitter-script-with-snarl</li>
            <content type="text">
<p>I am going to start following some people on twitter. I haven't found any twitter clients that just notify you when new status come in -- the way that I want, so I wrote one. To use, you need ruby, Snarl, and you see the ruby gem dependencies(twitter, ruby-snarl, json, hpricot). And curl, you'll need curl, you can get it <a href="http://curl.haxx.se/download.html#Win32">here </a>or get it with cygwin. And then you need a .twitter a the top of your home directory that is a YAML doc consisting of email and password key and value pairs, then you need up set up a scheduled job to run it periodically(btw, make sure you use rubyw.exe instead of ruby.exe so that the command window doesn't showup...yes, this is windows only) =):</p>
<pre><code>require 'rubygems'
require 'twitter'
 'snarl'
require 'json'
require 'yaml'
require 'fileutils'

home = (ENV['USERPROFILE'] || ENV['HOMEPATH']).gsub(/\\/, '/')
TWITTERME_DIR = home + '/.twitterme'
config = YAML::load open(home + "/.twitter")
SAVE_FILE = TWITTERME_DIR + '/current_statuses'

def save status
    open(SAVE_FILE,'w') do |f|
        f.write(to_map(status).to_json)
    end
end

def to_map current
    map = {}
    current.each do |f|
        map[f.id] = { :user =&gt; f.name, :status =&gt; f.status.text, :status_id =&gt; f.status.id }
    end
    map
end

def whats_new old, current
    if old.nil? then return current end
    new_stuff = []
    current.each do |f|
        if old[f.id].nil? or old[f.id]['status'] != f.status.text
            new_stuff &lt;&lt; f
        end
    end
    new_stuff
end

def picture_path friend
    "#{TWITTERME_DIR}/#{friend.id}.png"
end

def download_picture friend
    puts "downloading picture for #{friend.name}"
    system %|curl "#{friend.profile_image_url}" &gt; "#{TWITTERME_DIR}/#{friend.id}.png"|
end

def has_picture? friend
    File.exist?("#{TWITTERME_DIR}/#{friend.id}.png")
end

def initAppDir
    if not File.exist?(TWITTERME_DIR) then
        FileUtils.mkdir(TWITTERME_DIR)
    end
end

begin
    initAppDir
    friends = Twitter::Base.new(config['email'], config['password']).friends
    friends.each do |f|
       if not has_picture?(f) then
           download_picture f
       end
    end
    saved_status = JSON.parse(open(SAVE_FILE) { |f|f.read() }) unless not File.exist?(SAVE_FILE)
    save(friends)
    whats_new(saved_status, friends).each do |u|    
        Snarl.show_message u.name, u.status.text, picture_path(u), 40
    end
rescue Exception
    Snarl.show_message 'TwitterMe Error', ($!).to_s, nil, Snarl::NO_TIMEOUT
end
</code></pre>
<p><i>Update: Added support for profile images<br>Update #2: bug fix(adding new friend breaks it), added error handling if something goes wrong - it gives you a popup to let you know</i></p></content>
        </entry>,<entry>
            <title>Good People Day</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/04/03/good-people-day">
            <updated>2008-04-03T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/04/03/good-people-day</li>
            <content type="text">
<p>Gary Vaynerchuk has made a call to action to talk about good people today. Obviously, Gary is good people - my obsolute favorite wine personality, kudos to you, Gary! My other nominees:<br></p>
<ul>
	<li>Leonard Leo - my golf buddy and all around great guy</li>
	<li>Scott Hanselman - host of Hanselminutes, .NET developer but very open minded about other languages and cultures, and does very interesting interviews</li>
	<li>Sylvester Spann - Atlanta local veteran saxophonist, he's a great musician and always so encouraging to young musicians like me<br></li>
</ul></content>
        </entry>,<entry>
            <title>How Safe is Your Programming Language</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/30/how-safe-is-your-programming">
            <updated>2008-03-30T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/30/how-safe-is-your-programming</li>
            <content type="text">
<p>First, let me define what <i>I</i> mean by safe: <i>the earlier a programming language catches a programming error for you, the safer it is</i>. Haskell is extremely safe, whereas php is extremely unsafe. Some examples:<br></p>
<ul>
	<li>Errors can be caught at compile time, such as mispelling of function names</li>
	<li>Errors can be caught at runtime, such as NullPointerExceptions, but it may be caught early or later in runtime, there's a continum</li>
	<li>Errors can be caught a type time if you have a method completion capable IDE, for exmple</li>
	<li>Errors can be caught a unit test time, but that out of the scope for this article, because I want to talk about languages and not testing practices</li>
	<li>Errors can be caught at QA testing time vs in production, these are also a bit out of scope</li>
</ul>
<p>How do you measure the safety of a programming language? One can take specfic classes of errors and see how and when a language catches them. I will use the notation <i>>></i> to mean <i>safer than</i>. A score is given for each language for each type of error corresponding to how safe they are.<br><br></p>
<b>Null Pointers</b>
<ul>
	<li>Java, Ruby, Python, C#, Smalltalk, Javascript, LISP - catch at runtime when you try to derefernce the pointer</li>
	<li>C, C++ - never catches it, they merely core dump, which does not tell you what the specific error was</li>
	<li>Haskell, OCaml - catches it at compile time, because you cannot have Null values unless you specifically define it in the type, and the compiler requires you to handle the null case</li>
</ul>
<p>    So in this case: </p>
<b>Haskell, OCaml (2) >> Java, Ruby, Python, C#, Smalltalk, Javascript, LISP (1) >> C, C++ (0)</b>
<p><br><br></p>
<b>Array Index Out Of Bounds</b>
<ul>
	<li>Java, Python, C#, Smalltalk - catch at runtime when you try to index the array</li>
	<li>Ruby, Javascript - never catches it, merely returns null if you try to index an array with an out of bounds index</li>
	<li>C, C++ - never catches it, may or may not core dump.<br></li>
	<li>Haskell, LISP, OCaml - although you can use Arrays if you really want/need to, in which case the error is caught at runtime like Java, etc. The prefered practice of these languages is to use linked-lists instead, which will never have index out of bounds errors</li>
</ul>
<p>    So: </p>
<b>Haskell, LISP, OCaml (2) >> Java, Python, C#, Smalltalk (1) >> Ruby, Javascript, C, C++ (0)</b>
<p><br><br></p>
<b>Type Errors</b>
<ul>
	<li>Java, C# - these are caught at compile time <i>if</i> you never use casting in your program. <i>But</i> if you do use casting, these will be caught at runtime as ClassCastExceptions at time of cast.</li>
	<li>Ruby, Python, Javascript, Smalltalk, LISP - caught at runtime when a method on the object is accessed</li>
	<li>C, C++ - Compile time if you don't use casting. Never caught and possible core dumps if you do.</li>
	<li>Haskell, OCaml - Compile time always, casting is not allowed.</li>
</ul>
<p>    </p>
<b>Haskell, OCaml (3) >> Java, C# (2) >> Ruby, Python, Javascript, Smalltalk, LISP (1) >> C, C++ (0)</b>
<p><br><br></p>
<b>Mispelled Named Parameters</b>
<ul>
	<li>Java, C#, C, C++, Haskell, Javascript - these languages do not have this feature</li>
	<li>Python, Smalltalk - caught at time of method invocation</li>
	<li>Ruby - rubists employ a poor-man's named parameters by just passing in a Hash to methods, the languages supports syntactic sugar that make this style of method calling look like named parameters, but mispelled keys are never caught</li>
	<li>OCaml - caught at compile time</li>
</ul>
<p>    </p>
<b>OCaml (2) >> Python, Smalltalk (1) >> Ruby (0)</b>
<p><br><br></p>
<b>Wrong Number of Parameters</b>
<ul>
	<li>Python, Smalltalk, LISP - caught at method invocation</li>
	<li>Javascript - never caught, unsupplied parameters an simple set to null, and it never hurts to use too many parameters</li>
	<li>Ruby - caught at method invocation time for the normal cases, but blocks are a special type of parameter which is always optional. So if you supply a block to a method that does not require it, ruby does not complain</li>
	<li>Haskell, Java, C#, C, C++ - compile time</li>
</ul>
<p>    </p>
<b>Haskell, OCaml, Java, C#, C, C++ (3) >> Python, Smalltalk, LISP (2) >> Ruby (1) >> Javascript (0)</b>
<p><br><br>So a language can be safer or less safe under different contexts. There obviously are other types of errors that I have not listed, but this will do for a simple comparison. I've already given scores for each language for each error type. Since some languages do not have the named parameters feature, I will average the score for each language over the error types that are relevant to it. So the Tally is:<br></p>
<ol>
	<li>Haskell - scores: [2, 2, 3, 3], average: 2.5</li>
	<li>OCaml - scores: [2,2,3,2,3], average: 2.4<br></li>
	<li>Java, C# - scores: [1,1,2,3], average: 1.75</li>
	<li>LISP - scores: [1,2,1,2], average: 1.5<br></li>
	<li>Python, Smalltalk - scores: [1,1,1,1,2], average: 1.2</li>
	<li>C, C++ - scores: [0,0,0,3], average: 0.75<br></li>
	<li>Ruby - scores: [1,0,1,0,1], average: 0.6</li>
	<li>Javascript - [1,0,1,0], average: 0.5<br></li>
</ol>
<p>It's not really fair that OCaml is scoring lower than Haskell, they should be the same, the difference is because Haskell doesn't have named parameters so the average is skewed - my scoring system is not perfect. Haskell is safer than OCaml in one aspect though. Which is that in Haskell, purely functional code is guaranteed to have no side effects and will never throw exceptions.<br></p></content>
        </entry>,<entry>
            <title>Ideas for Listening Session</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/30/ideas-for-listening-session">
            <updated>2008-03-30T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/30/ideas-for-listening-session</li>
            <content type="text">
<ul>
	<li>What are you listening to now?<br></li>
	<li>Hidden Gems</li>
	<li>What turned you on to Jazz?</li>
	<li>Music that makes you want to shout</li>
	<li>Pretty vocals</li>
	<li>guilty pleasures</li>
	<li>hated it then, love it now<br></li>
	<li>Accidental Discoveries</li>
	<li>John Coltrane</li>
	<li>Blind Listening(Surprise me!)</li>
	<li>South America</li>
	<li>Atlanta Locals</li>
	<li>Europe</li>
	<li>Musicians you've meet<br></li>
</ul></content>
        </entry>,<entry>
            <title>Frogpad growing pains</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/29/frogpad-growing-pains">
            <updated>2008-03-29T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/29/frogpad-growing-pains</li>
            <content type="text">
<p>I've been training with the Frogpad now about a hour every other day or so. And I've found it's negatively affected my normal keyboard typing. Basically it's causing a confusion in the circuitry in my brain that responds to what to do when I want to type a certain letter. Whereas before it "hardcoded" on what to do, now it has to first know whether I am typing on a regular keyboard or a Frogpad. There's a term for it in cognitive science, but I can't remember it now. When I learned DVORAK I had the luxury that I intended to give up QWERTY completely, but now with the frogpad I am not sure that's the case. I guess right now I'll just try to learn the frogpad while still staying proficient with DVORAK by switching back and forth. Crossing my fingers...<br></p></content>
        </entry>,<entry>
            <title>Get Pidgin to Stop Notifying your Friends when you Close the Conversation Window</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/28/get-pidgin-to-stop-notifying">
            <updated>2008-03-28T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/28/get-pidgin-to-stop-notifying</li>
            <content type="text">
<p>This just annoys the hell out of me. Especially if I was on the receiving end of it:<br>"<i>your friend</i> has left the conversation"<br>Is that a downer or what?? To turn it off. Go to preferences -> Conversations tab -> Uncheck "Close IMs immediately when the tab is closed", and you are set. I have to say, that option is very poorly named.<br></p></content>
        </entry>,<entry>
            <title>BDD Style Mocks in Javascript</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/27/bdd-style-mocks-in-javascript">
            <updated>2008-03-27T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/27/bdd-style-mocks-in-javascript</li>
            <content type="text">
<p>I was tasked with researching Javascript testing in the browser. Saw <a href="http://video.google.com/videoplay?docid=4378663232897374824" mce_href="http://video.google.com/videoplay?docid=4378663232897374824">this video</a>, whose message is simple: decouple your code to be more testable. This is a testing 1.0 concept put in the context of Javascript/Ajax. So I set out to try out their methodology. I wrote a piece of code to do live updating in respond to keypresses in a field. It started out very ad-hoc so I refactored it to be an object:<br>function LiveUpdater(inputField, resultElement, url){<br>    this.inputField = inputField;<br>    this.url = url;<br>    this.lastValue = null;<br>    this.resultElement = resultElement;<br>    var self = this;<br>    this.pe = new PeriodicalExecuter(function(){<br>        if (self.lastValue != self.inputField.value){<br>            self.lastValue = self.inputField.value<br>            new Ajax.Updater(self.resultElement, self.url, {<br>              method: 'get',<br>              parameters: { query: self.inputField.value }<br>            });<br>        }<br>    }, 0.5);<br><br>But this still isn't testable. To follow their methodology, I would have to break this up into 3 objects: the view, the controller, and the data source. I started out on that path - using jsMock(those guys used a home grown mock library) - but it soon became apparent that my little chunk of managable code would have to more than double in size just to be testable, it was to heavy for my taste.<br><br>But it doesn't have to be this way. jsMock has the limitation that you cannot mock only certain methods on an object, it's basically all or nothing. Therefore, if you want to test the expectation or stub out a method, you must refactor it out as an object on its own. I've long gotten used to rspec and it doesn't have this limitation. It turns out it's not hard to fix this for jsMock, it's a small library - merely 300 some lines of code - and I was able to add this ability and give it a more rspec style of writing stubs and expectations. Long story short, here's my new code:<br>function LiveUpdater(inputField, resultElement, queryParameterKey, url){<br>    this.lastValue = null;<br>    var self = this;<br>    this.getParams = function(){<br>        var params = {}<br>        params[queryParameterKey] = inputField.value<br>        return params<br>    }<br>    this.update = function(){<br>        new Ajax.Updater(resultElement, url, {<br>          method: 'get',<br>          parameters: self.getParams()<br>        });        <br>    }<br>    this.check = function(){<br>        if (self.lastValue != inputField.value){<br>            self.lastValue = inputField.value<br>            self.update();<br>        }<br>    }<br>    this.start = function(){<br>        new PeriodicalExecuter(self.check, 0.5);<br>    }<br>}<br><br>And my tests(using Thomas Fuchs' unittest framework, although you could also use jsUnit):<br>new Test.Unit.Runner({<br>setup: function() {<br>    JSMock.extend(this)<br>    myField = {value:"hello"}<br>    this.lu = this.makeMockable(new LiveUpdater(myField, document.createElement('div'), 'query', ''))<br>},<br><br>teardown: function() {<br>    this.verifyMocks()<br>},<br><br>testCheckShouldUpdateInitially: function() { with(this) {<br>    lu.shouldReceive('update').with_no_args()<br>    lu.check()<br>}},<br><br>testCheckShouldNotUpdateWhenNothingHasChangedTheSecondTime: function() { with(this) {<br>    lu.stub('update').andReturn(null)<br>    lu.check()<br>    lu.shouldNotReceive('update').with_no_args()<br>    lu.check()  <br>}},<br><br>testParamsShouldBeRight: function() { with(this) {<br>    assert(mapEqu({query:'hello'}, lu.getParams()))<br>}}<br>  <br>}, {testLog: "testlog"}); <br><br>As you can see I refactored the activity into 4 methods. Only 2 of them are tested: check() and getParams(), there other 2 are basically direct third party library calls. <br><br>To show off some other things you can do:<br>function Robot(){<br>    var self = this<br>    this.move = function(){<br>        if (self.facingWall())<br>            self.turnToTheLeft()<br>        else<br>            self.goStraight()<br>    }<br>    this.goStraight = function(){<br>        <br>    }<br>    this.facingWall = function(){<br>    }<br>    this.turnToTheLeft = function(){<br>    }<br>}<br><br>...<br>testShouldTurnToTheLeftWhenFacingWall: function() { with(this) {<br>    robot.stub('facingWall').andReturn(true)<br>    robot.shouldReceive('turnToTheLeft').with_no_args()<br>    robot.move()        <br>}},<br>testShouldNotGoStraightWhenFacingWall: function() { with(this) {<br>    robot.stub('facingWall').andReturn(true)<br>    robot.shouldNotReceive('goStraight').with_no_args()<br>    robot.move()<br>}},<br>...<br>function Boxer(){<br>    var self = this<br>    this.health = 10<br>    this.hit = function(opponent, power){<br>        opponent.hurt(power)<br>    }<br>    this.hurt = function(points){<br>        self.health -= points<br>    }<br>}<br>...<br>testGettingHitShouldHurtOpponentBySameAmountAsPower2: function(){ with(this){<br>    boxer.shouldReceive('hurt').with(5)<br>    new Boxer().hit(boxer, 5)<br>}},<br><br>Here's a zip file for the code: <a href="http://wiki.futuretoby.com/uploads/jsMockB.zip?1206630385">jsMockB.zip</a>. I may put it up on svn somewhere later.<br></p></content>
        </entry>,<entry>
            <title>I got my Frogpad!!</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/26/i-got-my-frogpad!!">
            <updated>2008-03-26T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/26/i-got-my-frogpad!!</li>
            <content type="text">
<p>Yea!!! Pictures to come. I love my shiny new gadget! Starting to practice...can type some sentences slowly now...<br></p></content>
        </entry>,<entry>
            <title>Frogpad</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/22/frogpad">
            <updated>2008-03-22T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/22/frogpad</li>
            <content type="text">
<p>I ordered one of these today, can't wait to try it out!!<br></p>
<object height="355" width="425">
	<param name="movie" value="http://www.youtube.com/v/QSDMahnw0_g&hl=en">
	
	</param>
	<param name="wmode" value="transparent">
	
	</param>
	<embed src="http://www.youtube.com/v/QSDMahnw0_g&hl=en" type="application/x-shockwave-flash" wmode="transparent" height="355" width="425">
	
	</embed>
</object></content>
        </entry>,<entry>
            <title>Embedding Hulu content</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/22/embedding-hulu-content">
            <updated>2008-03-22T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/22/embedding-hulu-content</li>
            <content type="text">
<p>Embedding hulu content is really cool! You can take any video offered there, and cut out any clip segment of it, and shared it on your blog/wiki/whatever. Let me pick a good one... let's see...<br></p>
<object height="295" width="510">
	<param name="movie" value="http://www.hulu.com/embed/3ZTVkhg3y0ylHrshkAYaDw">
	
	</param>
	<param name="flashvars" value="st=0&et=68">
	
	</param>
	<embed src="http://www.hulu.com/embed/3ZTVkhg3y0ylHrshkAYaDw" type="application/x-shockwave-flash" flashvars="st=0&et=68" height="295" width="510">
	
	</embed>
</object></content>
        </entry>,<entry>
            <title>iTunes WTF</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/22/itunes-wtf">
            <updated>2008-03-22T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/22/itunes-wtf</li>
            <content type="text">
<div class="image">
	<img src="/uploads/itunes-WTF.jpg?1206237138" name="itunes-WTF.jpg" width="594">
</div></content>
        </entry>,<entry>
            <title>Turbogears and ReML</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/20/turbogears-and-reml">
            <updated>2008-03-20T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/20/turbogears-and-reml</li>
            <content type="text">
<p>I followed the Turbogears 20 minute tutorial <a href="http://docs.turbogears.org/1.0/Wiki20/Page1" mce_href="http://docs.turbogears.org/1.0/Wiki20/Page1">here</a>. The first impressions of Turbogears are:<br></p>
<ol>
	<li>It's a bit more verbose than rails: there's more plumbing - you have to explicitly define which view you want to use for each action, as supposed to doing everything based on convention.<br></li>
	<li>you explicitly pass the local variables to the view as a hash, as supposed to using class or global variables</li>
	<li>Turbogears uses a template engine called kid by default, which is very different from rails' erb in philosophy, there's more emphesis on designer friendliness and higher level support for template inheritence</li>
	<li>Python/Turbogears in general is safer than ruby/rails - <a href="http://wiki.futuretoby.com/Ruby:%20Extremely%20Unsafe" mce_href="http://wiki.futuretoby.com/Ruby:%20Extremely%20Unsafe">see my last post</a>, in that you usually get more informative errors, such as NameError: global name 'pag' is not defined rather than nil when you didn't expect it</li>
	<li>The development feedback is not <i>quite </i>as good as rails. Turbogears requires a restart everytime you make a change. The restart is automatically triggered everytime you save a file in the project, and it is very fast, but it still takes about 5 seconds to rails' 0(ruby has this luxury because of its open classes)<br></li>
</ol>
<p>I am hip to Haml so I had to see if I could get it working with Turbogears. I found a couple of implementations: <a href="http://reml.wikidot.com/documentation" mce_href="http://reml.wikidot.com/documentation">ReML</a> and <a href="http://lucumr.pocoo.org/cogitations/2008/02/15/ghrml-haml-for-genshi/" mce_href="http://lucumr.pocoo.org/cogitations/2008/02/15/ghrml-haml-for-genshi/">GHRML</a>. Tried them both, ReML was simpler and more approachable, so I wrote a <a href="http://docs.turbogears.org/1.0/TemplatePlugins" mce_href="http://docs.turbogears.org/1.0/TemplatePlugins">Turbogears plugin</a> for it. The important bit of the plugin code is here:<br><br>from reml import TemplateLoader<br><br>class RemlTg(object):<br>  <br>  def __init__(self, extra_vars_func=None, options=None):<br>    pass<br><br>  def load_template(self, templatename):<br>    "Find a template specified in python 'dot' notation."<br>    parts = templatename.split('.')<br>    return TemplateLoader('/'.join(parts[0:len(parts)-1])).load(parts[len(parts)-1] + '.reml')<br><br>  def render(self, info, format="html", fragment=False, template=None):<br>    "Renders the template to a string using the provided info."<br>    return self.load_template(template).render(info)<br><br>After that, I converted the views in the tutorial into ReML. Let me do a wc on them for comparison, wait just a minute...<br><br>$ wc wiki20/templates/*.kid<br>  25   76 1068 wiki20/templates/edit.kid<br>  71  173 2802 wiki20/templates/master.kid<br>  21   56  773 wiki20/templates/page.kid<br>  21   50  705 wiki20/templates/pagelist.kid<br> 138  355 5348 total<br>airport@wedding-singer ~/documents/play/turbogears/Wiki-20<br>$ wc wiki20/templates/*.reml<br>  16   41  492 wiki20/templates/edit.reml<br>  38   86 1338 wiki20/templates/master.reml<br>  12   30  327 wiki20/templates/page.reml<br>   8   24  190 wiki20/templates/pagelist.reml<br>  74  181 2347 total<br><br>So that's about a 50% code reduction, not bad. Here's a Sample for comparison:<br><br></p>
<b>page.kid:</b>
<p><br><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"<br>          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br><html xmlns="http://www.w3.org/1999/xhtml"<br>      xmlns:py="http://purl.org/kid/ns#"<br>      py:extends="'master.kid'"><br><head><br><title> ${page.pagename} - 20 Minute Wiki </title><br></head><br><body><br>    <div class="main_content"><br>        <div style="float:right; width: 10em"><br>            Viewing <span py:replace="page.pagename">Page Name Goes Here</span><br>            <br/><br>            You can return to the <a href="/">FrontPage</a>.<br>        </div><br><br>        <div py:replace="XML(data)">Page text goes here.</div><br>        <p><a href="${tg.url('/edit', pagename=page.pagename)}">Edit this page</a></p><br><br>    </div><br></body><br></html><br><br></p>
<b>page.reml</b>
<p><br>- append('master.reml')<br>- def title():<br>  =page.pagename<br>- def content():<br>  %div: 'style':'float:right; width: 10em'<br>    Viewing<br>    %span=page.pagename<br>    You can return to the<br>    %a: 'href':tg.url('/')<br>      Frontpage<br>  %div=unescaped(data)<br>  %a: 'href':tg.url('/edit', pagename=page.pagename)<br>    Edit this page<br><br><br></p></content>
        </entry>,<entry>
            <title>Last FM Scrobbler and displaying my feeds on facebook</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/18/last-fm-scrobbler-and">
            <updated>2008-03-18T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/18/last-fm-scrobbler-and</li>
            <content type="text">
<p>I got excited about last fm today and setup the scrobblers for both <a href="http://www.last.fm/group/iScrobbler/forum/35555/_/134630" mce_href="http://www.last.fm/group/iScrobbler/forum/35555/_/134630">itunes</a> and <a href="http://www.atlansky.com/dev/download.html" mce_href="http://www.atlansky.com/dev/download.html">rhapsody</a>, since, after all, I have impeccable musical taste;) So, if you would like to see what music I am listening to, <a href="http://www.last.fm/user/airportyh/">click here</a>. After that, I was still excited, and wanted to display my recently played tracks as a widget the one you can generate using <a href="http://wigitize.com/">widgitize</a>. But my blog/wiki does not yet have the ability to embed widgets(it's coming, though, heh...). So I thought it'd be nice to put it on facebook. If first tried the last.fm app, but it didn't display my recently played tracks like I wanted to do. I got the <a href="http://apps.facebook.com/blogrssreader/">Blog RSS Feed Reader</a> instead(man, what a boring name). It did just what I wanted:<br></p>
<div class="image">
	<img src="http://wiki.futuretoby.com/uploads/blog_rss_feed_reader.jpg?1205874166" name="blog_rss_feed_reader.jpg" width="424">
</div>
<p><br><br>The above now shows up in my profile page. And since it supports multiple feeds, I added some feeds from this blog as well.<br><br><i>Update: It turns out that there's an app called <a href="http://apps.facebook.com/listening/">What I'm Listening to</a> for precisely what I wanted to do with last.fm, I've switched over to that. I still use blog rss feed reader to display my blog feeds.</i><br><br></p></content>
        </entry>,<entry>
            <title>Ruby: Extremely Unsafe</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/15/ruby:-extremely-unsafe">
            <updated>2008-03-15T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/15/ruby:-extremely-unsafe</li>
            <content type="text">
<p>I have been making the same mistake a few times recently: instead of writing<br>things.each do |thing| ... end<br>Where things is a method, not a variable, I would write:<br>things do |thing| ... end<br>which has the end result of doing nothing. And I would have a hard time tracking down the bug - even when I have tests written which are failing because of it. I think it's because you just don't <i>see </i>a mistake like this, it's just one of those things where you can stare at the line all day and still not have a clue. Admittedly, this is a stupid mistake, but I also blame ruby for being extremely lose in its method invocation behavior when dealing with blocks. A block on a method is like an optional argument on ALL methods, not just the ones where you mean to use blocks. So this mean you can pass a block to any method, even if it's as simple as:<br>def hello<br>  'hello'<br>end<br>I have enumerated a handful of other languages including Smalltalk, Python, Haskell, Lisp, Java, and none of them behave this way. This is just one example of why Ruby is on the <i>extremely unsafe</i> end of the language spectrum. And this is also why there's a bigger need for automated testing in Ruby software, because the intepreter is so forgiving that even little mistakes like these - which are normally easily caught at runtime, if not compile time - can go through undetected.<br><br>Another unsafe thing about Ruby software is the frequent use of hashes as the poor man's <i>named parameters</i>. If you misspell the name of the key, there would be no complaint. And when you find out something's wrong, you wouldn't know where to look first.<br><br>Yet another is the fact that arrays simply return nil when you give it an out-of-bounds index:<br>>> [][7]<br>=> nil<br><br>I guess being unsafe is just part of the Ruby culture. In related news: Javascript is extremely unsafe too, arguably even more so than Ruby, since, for example it's not strict about enforcing the number of parameters you can pass into a function..<br><br></p></content>
        </entry>,<entry>
            <title>Data mining and KDD</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/15/data-mining-and-kdd">
            <updated>2008-03-15T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/15/data-mining-and-kdd</li>
            <content type="text">
<p>For the longest time I have known about data mining, I thought it's the same as KDD　(knowledge discovery in database). Until today, I read some papers, did I find out they're actually two different things. "<i>KDD refers to the overall process of discovering useful knowledge from data, and data mining refers to a particular step in this process</i>". <br>Data mining is the application of specific algorithms for extracting patterns from data. KDD has evolved, and continues to evolve, from the intersection of research fields such as machine learning, pattern recognition, databases, statistics, AI, knowledge acquisition for expert systems, data visualization, and high-performance computing. The unifying goal is extracting high-level knowledge from low-level data in the context of large data sets. <br><br>The data-mining component of KDD currently relies heavily on known techniquesfrom machine learning, pattern recognition, and statistics to find patterns from data in the data-mining step of the KDD process. A natural question is, How is KDD different from pattern recognition or machine learning (and related fields)? The answer is that these fields provide some of the data-mining methods that are used in the data-mining step of the KDD process.<br>The KDD process can be viewed as a multidisciplinary activity that encompasses techniques beyond the scope of any one particular discipline such as machine learning.<br></p></content>
        </entry>,<entry>
            <title>Four Month Pictures</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/14/four-month-pictures">
            <updated>2008-03-14T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/14/four-month-pictures</li>
            <content type="text">
<p>Uploaded some new pictures, <a href="http://picasaweb.google.com/airportyh/FourMonthsOld?authkey=Z7b9DwDxj7Y">enjoy</a>. I'm waiting for y'alls comments =)<br></p></content>
        </entry>,<entry>
            <title>Autotest popup notifications with Snarl</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/14/autotest-popup-notifications">
            <updated>2008-03-14T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/14/autotest-popup-notifications</li>
            <content type="text">
<p>After learning of growl from <a href="http://blog.aisleten.com/2008/02/21/installing-growlnotify-and-autotest-for-bdd-use-with-rspec-on-leopard/" mce_href="http://blog.aisleten.com/2008/02/21/installing-growlnotify-and-autotest-for-bdd-use-with-rspec-on-leopard/">Micah's post</a>, I decided to port it to the windows equivalent: snarl. It was pretty easy:<br></p>
<ol>
	<li>Follow Micah's instructions except for the growl bits<br></li>
	<li>Install Snarl from their website, this is a setup .exe</li>
	<li>gem install ruby-snarl</li>
	<li>get the icon images from Micah's post and put them some where. I put them in c:/devtools/autotest redgreen icons/</li>
	<li>Put the code below in your .autotest, in place of the stuff for growl:</li>
</ol>
<p><br>require 'autotest/redgreen' <br>require 'snarl'<br>module Autotest::Growl <br>  def self.notify title, msg, img<br>    Snarl.show_message title, msg, img<br>  end <br> <br>  Autotest.add_hook :ran_command do |autotest| <br>    icon_path = 'c:/devtools/autotest redgreen icons/'<br>    output = autotest.results.grep(/\d+\s.*examples?/).last.slice(/(\d+)\s.*examples?,\s(\d+)\s.*failures?(?:,\s(\d+)\s.*pending)?/) <br>    if output =~ /[1-9]\sfailures?/ <br>      notify "Test Results", "#{output}", "#{icon_path}rails_fail.png" <br>    elsif output =~ /pending/ <br>      notify "Test Results", "#{output}", "#{icon_path}rails_pending.png" <br>    else<br>      notify "Test Results", "#{output}", "#{icon_path}rails_ok.png" <br>    end<br>  end<br>     <br>end <br><br><br>Screenshot:<br></p>
<div class="image">
	<img src="http://wiki.futuretoby.com/uploads/snarl.jpg?1205507866" name="snarl.jpg" width="364">
</div></content>
        </entry>,<entry>
            <title>Jam Session at Apres Diem</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/13/jam-session-at-apres-diem">
            <updated>2008-03-13T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/13/jam-session-at-apres-diem</li>
            <content type="text">
<p>I attended this jam session last night and it was really fun. Syl was there, whom I haven't spoke to in years. I had a lot of fun playing some straight-ahead jazz and met a lot of talented musicians as well. I'll definitely be back.<br></p></content>
        </entry>,<entry>
            <title>e-music vs rhapsody</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/12/e-music-vs-rhapsody">
            <updated>2008-03-12T04:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/12/e-music-vs-rhapsody</li>
            <content type="text">
<p>I learned today that e-music: the indie music online store is has some major label music and is getting more and more of it. I had subscribed to the rhapsody service for a couple on months now and have been liking it. The only drawback of course, is that the music is DRM'ed, and I can't put it on my ipod. With e-music, everything is DRM-free, which is a major plus for me, since, after all, I am an ipod user(we actually own 4 ipods, if you count shuffles).<br><br>e-music has 3 plans: <br></p>
<ul>
	<li>Basic: 30 downloads for $9.99 per month</li>
	<li>Plus: 50 downloads for $14.99 per month</li>
	<li>Premium: $19.99 for 75 downloads per month</li>
</ul>
<p>compared to rhapsody:<br></p>
<ul>
	<li>Unlimited: unlimited downloads/listens for $12.99</li>
	<li>To Go: you can also download it to your non-ipod mp3 player for $14.99</li>
</ul>
<p>But how do they compare in terms of their music collection? I search for some of my favorite artists:<br><br></p>
<b>Wes Montgomery</b>
<ul>
	<li>e-music: 19 albums</li>
	<li>rhapsody: 50 albums</li>
</ul>
<b>Lee Konitz</b>
<ul>
	<li>e-music: 14 albums</li>
	<li>rhapsody: 38 albums</li>
</ul>
<b>Bill Evans</b>
<ul>
	<li>e-music: 37 albums</li>
	<li>rhapsody: estimated about 200 albums<br></li>
</ul>
<b>Booker Little</b>
<ul>
	<li>e-music: 1 album(under booker little and max roach)<br></li>
	<li>rhapsody: 3 albums</li>
</ul>
<b>Warne Marsh</b>
<ul>
	<li>e-music: 3 albums</li>
	<li>rhapsody: 8 albums</li>
</ul>
<b>John Coltrane</b>
<ul>
	<li>e-music: 27 albums<br></li>
	<li>rhapsody: estimated over 200 albums<br></li>
</ul>
<p>Clearly rhapsody has the edge. But the situation isn't that bad for e-music, and if they are still working on expanding their collection they could always catch up, since I think all the major music labels have pretty much dropped their DRM requirements. I shall check back in a couple of months and see if any of these numbers change.<br></p></content>
        </entry>,<entry>
            <title>Fujisu Tablet</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/07/fujisu-tablet">
            <updated>2008-03-07T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/07/fujisu-tablet</li>
            <content type="text">
<p>I went to fry's today and was able to play a bit with the Fujisu tablet there. I was quite impressed. One thing I learned what that you can actually "pen over" the screen. The pointer follows your pen as you hover it over the screen as long as it's sufficiently close to the screen(probably about an inch). The Fujisu tablet goes for about 2k, almost 1k more than the hp.<br></p></content>
        </entry>,<entry>
            <title>Sonny Rollins</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/07/sonny-rollins">
            <updated>2008-03-07T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/07/sonny-rollins</li>
            <content type="text">
<p>I have to dig deeper into Sonny Rollins. I have always though he was a great improviser, but just never for one reason or another dug deep. I am going to do it now. I blogged it, so I have to =) What I love about Sonny is that whenever he improvises he is so free! Just does whatever comes to him, he is not afraid to go in any direction - not afraid to stretch beyond the confines of the progression. Listening to Come, Gone on the Way Out West album at this moment.<br></p></content>
        </entry>,<entry>
            <title>Downloading MP3 from CDBaby</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/05/downloading-mp3-from-cdbaby">
            <updated>2008-03-05T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/05/downloading-mp3-from-cdbaby</li>
            <content type="text">
<p>I bought some music from CDBaby today for the first time, and they support MP3 downloads now. What's even better than that, is that the artifact that you download(a zip file) contains album art as well as a text file containing the track information, personnel, as well as liner notes! Wow, what a concept? Amazon? Apple? Why can't you do the same?<br></p></content>
        </entry>,<entry>
            <title>ffmpeg</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/02/ffmpeg">
            <updated>2008-03-02T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/02/ffmpeg</li>
            <content type="text">
<p>For a long time I couldn't figure out why I couldn't use ffmpeg to convert my videos from my sony handycam. When I open it with Windows Movie Maker it messes up the aspect ratio, so I didn't want to do that, either. More recently my mom had trouble playing the files because she doesn't have the mpeg-2 codec installed. I went digging through the internet for some sort of software video converter, but, finally, I decided to give ffmpeg another try. After reading the error message more carefully(ah duh), the problem was not the aspect ratio or that it's mpeg-2, but audio related. I guess mpeg-1 doesn't support 5:1 surround sound, so just forcing it to 2 audio channels did the trick. Man, I feel genuinely stupid. The command I ended up using(or similar) was:<br>ffmpeg -i emma\ roll\ over.mpg -b 900 -s 360x240 -ac 2 emma_roll_over_web2.mpg<br><br><i>Update: you might want to make the bitrate(-b) higher, maybe 900k instead of 900 ;)</i><br></p></content>
        </entry>,<entry>
            <title>My Artist Page on the 61</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/02/my-artist-page-on-the-61">
            <updated>2008-03-02T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/02/my-artist-page-on-the-61</li>
            <content type="text">
<p>Haha, I am officially an internet artist now: <a href="http://www.thesixtyone.com/airportyh">http://www.thesixtyone.com/airportyh</a><br>I guess this will be another creative outlet.<br></p></content>
        </entry>,<entry>
            <title>MapIt</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/03/02/mapit">
            <updated>2008-03-02T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/03/02/mapit</li>
            <content type="text">
<p>Looks like I forgot about my MapIt firefox plugin when I migrated my wiki. Well, here it is: <a href="/uploads/mapit.xpi?1204484819">mapit.xpi</a>.<br></p></content>
        </entry>,<entry>
            <title>Review of Google Sites</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/02/29/review-of-google-sites">
            <updated>2008-02-29T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/02/29/review-of-google-sites</li>
            <content type="text">
<p>In order to try out Google Sites today, I signed up for a Google Apps account. Some background/definitions first:<br></p>
<ul>
	<li>Google Apps: a suite of google applications: email, docs, and now sites, for groups and organizations, which can run on the top level of your domain. So for example I could have toby@futuretoby.com which actually uses the gmail service, or use google sites to run futuretoby.com</li>
	<li>Google Sites: Google's new hosted wiki service. This has been brewing for a while seen they acquired JotSpot, and frankly I've expecting this for a long time. And in many ways, Google Sites is similar to my wiki.</li>
</ul>
<p><br>There's been long a need for an easy to use mainstream wiki implementation, and Google is the obvious candidate to try to do it. Editing in Google Sites is all WYSWYG, unless you want to drop down to HTML editing. They have in-place editing - similar to mine - meaning that the text is in the same place whether you are in view mode or edit mode, plus there's no refresh of the page. But unlike mine, <i>save </i>always brings you back to view mode, and going into edit mode is quite slow. They have directory structures, meaning you can nest pages under other pages, making the parent page like directories. Permission control is full featured. There are many embeddable widgets, including a picasa slideshow widget! For video, there's only google video and youtube. I think you can probably write your own widgets for it though.<br><br>Here are some screen shots:<br></p>
<div class="image">
	<img src="/uploads/google_sites_front.jpg?1204305175" mce_src="/uploads/google_sites_front.jpg?1204305175" name="google_sites_front.jpg" align="left" width="600">
</div>
<p><i>Front page</i><br></p>
<div class="image">
	<img src="/uploads/google_sites_edit.jpg?1204305185" mce_src="/uploads/google_sites_edit.jpg?1204305185" name="google_sites_edit.jpg" width="600">
</div>
<p><i>Edit Screen</i><br></p>
<div class="image">
	<img src="/uploads/google_sites_blog.jpg?1204305193" mce_src="/uploads/google_sites_blog.jpg?1204305193" name="google_sites_blog.jpg" width="600">
</div>
<p><i>Blog Page</i><br></p>
<p><br>Overall, I think it's a very good solution to many people, but there are still a couple of things keeping me from migrating to it right now. <br></p>
<ol>
	<li>Editing/Blogging is sluggish - I want a snappy feeling when using the site and it's definitely not there. Granted my wiki can be slow to load at times, but that's something I can fix myself, at least.</li>
	<li>A bit too many dialog popups for my taste, again contributes to non-snappiness<br></li>
	<li>The theme system does not look at good as I want and does not seem to be flexible enough for me to change it.</li>
	<li>This is more minor, but there are tags/labels?</li>
</ol>
<p>My wiki has been running a bit slow, I thought I had fixed that, will investigate that as soon as I get some time.<br><br>Also a thought about the business model behind Google Sites. You have to have Google Apps to use sites, which means its audience will be much more limited than any other similar google product(not everyone has there own "organization"). That's an interesting business decision. One way to look at it is that they are trying to beef up their Google Apps offering to try to get more people signing up and then hopefully paying for it. But that this means is that Google Sites probably won't get to be the mainstream wiki.<br></p></content>
        </entry>,<entry>
            <title>Alyse Black</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/02/28/alyse-black">
            <updated>2008-02-28T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/02/28/alyse-black</li>
            <content type="text">
<p>As I've said, I've been listening to music on thesixtyone.com, and
found some music well worth listening to. One of the really superb
artists I've found from there is named Alyse Black(alyseblack.com, you
can hear her at <a href="http://www.thesixtyone.com/#/AlyseBlack/">sixtyone.com</a>). Her sound(I think sound is more fitting than voice here) is exquisite.<br></p></content>
        </entry>,<entry>
            <title>ditching ferret and going to mysql fulltext search</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/02/27/ditching-ferret-and-going-to">
            <updated>2008-02-27T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/02/27/ditching-ferret-and-going-to</li>
            <content type="text">
<p>Although usually you can get it to work somehow, Ferret's always been a pain to use. It also feels very slow on a shared host, much faster on slicehost though. However, I've ran into the problem recently of it crashing on trying to index some Chinese characters. I guess this was as good a time as any to ditch it. I knew mysql had very simple to use fulltext search capabilities, but I did look into sphinx first, which, to my dissappointment, I couldn't get working on my windows development laptop at all. So I fellback to mysql fulltext indexing, which worked great. It was super easy to implement, and the performance is good so far. I guess only time will tell if it can scale to larger datasets. For now, I am very happy with it: no hassel, no fuss.<br></p></content>
        </entry>,<entry>
            <title>capistrano and deprec</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/02/27/capistrano-and-deprec">
            <updated>2008-02-27T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/02/27/capistrano-and-deprec</li>
            <content type="text">
<p>I got slicehost recently to host osspinions, and started getting into using capistrano and deprec to deploy the app and set up the box. You can think of capistrano as a remote control enabled make, and deprec as bunch of tasks build on capistrano that automates the setting up of everything from your user account to deploying your rails app - for ubuntu only. I was really impressed, just 4 commands installed everything up to the rails stack. But the deployment of the app was harder, a lot harder, in fact. I had to install ferret(which I just more recently ditched), FreeImage for image science, and rcov as a gem, and ruby-openid as a gem as well. These things are the ones that I could not stuff into the vendor directory and have it work. After that, for ferret I had to use symlinks to share the index directory, and for uploaded files I had to symlink them too because the deprec setup is such that every deployment you do creates a brand new directory for the new release. This is good in many ways, but it also creates some complications. I heard the guys on the <a href="http://blog.slicehost.com/articles/category/podcast">slicehost podcast</a> talk about this and they pretty much confirmed as much: it's hard to make deprec work for everybody because everybody does things differently, Oh well. Capistrano, on the other hand, is pretty nice. I wrote a python script at my last job to build and deploy a Java app, and if I had came across capistrano then, I would have definitely used it instead and would have saved me a lot of work.<br></p></content>
        </entry>,<entry>
            <title>thesixtyone</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/02/25/thesixtyone">
            <updated>2008-02-25T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/02/25/thesixtyone</li>
            <content type="text">
<p>I came across this website(<a href="http://www.thesixtyone.com" mce_href="http://www.thesixtyone.com">www.thesixtyone.com</a>) today and it's one of the most innovative and well done websites I've seen in a long time. Musicians can upload their music to be listened to and voted for by listeners on the site - sort of a digg.com for music. Musicians also have their own page which they can use to promote their concerts and events. The experience of using the site is really nice, the music keeps playing no matter where you click, so you can feel free to explore, and it's really a lot of fun.<br><br>This is a indie music site, so you won't find mainstream music here, but I've already found a lot of music worth listening to. That may mean the voting system is working if you asked me.<br></p></content>
        </entry>,<entry>
            <title>OSSpinions Major Update</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/02/24/osspinions-major-update">
            <updated>2008-02-24T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/02/24/osspinions-major-update</li>
            <content type="text">
<p><a href="http://osspinions.org">OSSpinions.org</a> has undergone a major update. I've been working very hard on this, but there's still a lot of work left to be done. Interested parties please take a look and give me some feedback.<br></p></content>
        </entry>,<entry>
            <title>Gigantic Rails Log File Slows Down App</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/02/21/gigantic-rails-log-file-slows">
            <updated>2008-02-21T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/02/21/gigantic-rails-log-file-slows</li>
            <content type="text">
<p>My Wiki has been mysterious getting slower and slow and I didn't have a clue why. Today I happened to check the log file's size, it was over 10m. So I removed it and the Wiki was back to normal. Conclusion: you have to have a way to manage the size of rails applications. Some people just turn off logging altogether. I opted to set the log level to error. Another option would be to have a cron job remove the file periodically.<br><br><i>Update: Not so sure the large log file was the cause anymore. I still don't know what caused it, may a memory leak of some sort, or maybe this is just the woes of using a shared host. The problem hasn't come back so far, so I haven't been able to look further.</i><br></p></content>
        </entry>,<entry>
            <title>Future of Jazz Competition</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/02/20/future-of-jazz-competition">
            <updated>2008-02-20T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/02/20/future-of-jazz-competition</li>
            <content type="text">
<p>I've been hearing about the <a href="http://www.futureofjazz.com/live/" mce_href="http://www.futureofjazz.com/live/">Future of Jazz Competition</a> that Tammy Allen organized. Last week when I went to Tammy's Jam Session at Londzell's, I met a Chicago alto sax player named Danny Lerman. He said he was here for the Future of Jazz Competition. There were a lot of other great artists at Londzell's that night, many of whom were also at the competition. The competition runs every tuesday night from Feb 12th to March 4th, so it's still going on, there are 2 more left.<br><br>So, at the competition last night - which was held at Star Jazz and Blues - I hadn't been hanging around the Atlanta Jazz Scene for a long while, and felt quite ignorant: All three of the lead artists playing were great, and yet I didn't know any of them. The first artist was Leeland Davis on keyboard, who played long, intricate and exciting lines in his solos, as well as a solo piano piece. But Ryan Whitehead and his band really blew me away. He had amazing chops on the tenor, and the notes that he played all sounded really "right" to me, maybe that means we have similar tastes. However, Dave Ellington, who played hammand B3 organ in Ryan's band, was a force in his own right. I love how that organ can play 3 or 4 parts simultaneously together. The two of them also really played off of each other during their solos, which created some very nice effects. Lastly was Mace Hibbard on alto and soprano saxes, who ended up winning the event. Me personally was more impressed with Ryan though, it's just personal preference. I think Ryan probably had more of a call-and-answer style to his playing, which I dig.<br><br>It's very encouraging to find these great musicians in Atlanta, I will be seeking them out it the future. Tammy is always hosting great events. I think from now on I'll just follow her whereever she goes =)<br></p></content>
        </entry>,<entry>
            <title>Google Calendar is an acceptable Outlook</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/02/12/google-calendar-is-an">
            <updated>2008-02-12T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/02/12/google-calendar-is-an</li>
            <content type="text">
<p>I finally am starting to use google calendar more for my day to day appointments, and it really shines. Appointment request works perfectly with or without Outlook(like if the recipient uses Outlook or someone uses Outlook to send you a meeting request). The calendar app itself is awesome. You can create multiple calendars, even subscribe to public calendars that are in iCal format, I have done this with all my meetup groups. There's also calendars for US holidays as well as Chinese holidays.<br></p></content>
        </entry>,<entry>
            <title>Google Spreadsheet Forms</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/02/10/google-spreadsheet-forms">
            <updated>2008-02-10T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/02/10/google-spreadsheet-forms</li>
            <content type="text">
<p><a href="http://googledocs.blogspot.com/2008/02/stop-sharing-spreadsheets-start.html" mce_href="http://googledocs.blogspot.com/2008/02/stop-sharing-spreadsheets-start.html">Google Spreadsheet Forms</a> is superly awesome! Try it out and add it to your repitoire if you haven't.<br></p></content>
        </entry>,<entry>
            <title>Tablets are the way of the future</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/02/07/tablets-are-the-way-of-the">
            <updated>2008-02-07T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/02/07/tablets-are-the-way-of-the</li>
            <content type="text">
<p>After watching some old <a href="http://video.google.com/videosearch?q=alan+kay&ie=UTF-8&oe=utf-8&rls=org.mozilla:en-US:official&client=firefox-a&um=1&sa=N&tab=iv" mce_href="http://video.google.com/videosearch?q=alan+kay&ie=UTF-8&oe=utf-8&rls=org.mozilla:en-US:official&client=firefox-a&um=1&sa=N&tab=iv">Alan Kay videos</a>, I started thinking about modeless interfaces and tablet PC's. I think that the tablet PC has been largely under-appreciated, but is a form factor that has a lot of potential. The reason that it was under-appreciated, in my opinion, is - at least partly - because of the software. The operating system on most of the tablet PCs in the market is windows, but the version of windows installed on the machines is not any different from any other windows. Aside from some duck-tape-like software to allow for hand writting recogition and a few other features, there's really very little work that's been put into making the software working great with the form factor. With the hype of multi-touch screens, I think conditions are ripe for a comeback for tablets if the right things happen. Apple has the best chance of making it work: doing with tablets what they did with mobile phones, plus they already have multitouch technology on their side, so it's a natural match.<br><br>Now, why tablets? How did I settle on that? I guess it started with a <a href="http://video.google.com/videoplay?docid=-533537336174204822&q=alan+kay&total=427&start=0&num=10&so=0&type=search&plindex=1">video </a>Kay show of a modeless interactive system which uses a stylus. It was some sort of flow-chart editor. The main thing is that it was modeless. To create a box, you didn't have to go and select the box tool, no, you just draw a box in the shape of a rectangle. And to make a port on the box, you just draw it on the edge of the box. To write text in the box you just scribble it. To connect 2 boxes you just draw a line from the edge on one to a edge of another. Why don't we have more interfaces like this today? In photoshop, in order to do anything at all, you usually have to be aware of being in a combination of at least 3 different kinds of modes: your selection, your tool selection, and the current layer. Plus, with many of the actions you take, modal dialogs popup afterwards to asks you for parameters you want before anything actually happens. This is why doing anything in Photoshop <i>feels</i> like such a hassle. Well, okay, that's more of a user interface issue than about the tablet, but that's what inspired it. What's special about the tablet form factor, I think, is that the stylus gives you better control of fine movements than the mouse, and therefore allows you to draw more accurate shapes, which allows you to better articulate what you mean to the machine, with which programs can better detect gestures. That's why graphic artists prefer tablets to regular laptops, after all. You may have concerns that using a stylus freehand tires your wrist, but there's no reason why you cannot rest your palm on the surface: in fact I tried out the HP tablets at Fry's the other day and resting your palm while writting does not interfere at all. The second thing that's major about the tablet form factor is the emergence of multi-touch. There isn't a major multi-touch tablet in the market today, but Apple already has the iphone and the Macboox Air - which allows you to use iphone-like gestures on the touchpad. If you haven't played with the iphone, the multi-touch hand gestures like swipe, flick, pinch, and spread, are phenomnonal in terms of user-happiness. These gestures are intuitive, easy to use, immersive, and...<i>modeless</i>. Many iphone users have complained after going back to their macbook, that they can't use these gestures anymore. It's pretty obivious now that macbooks from now on will all have multi-touch enabled touch pads. Now, you might ask me, you like the stylus, and then you are talking about multi-touch, are we going to use the stylus or our fingers? I am just saying...we use both. In fact, one hand could be using the stylus while the other could be making gestures. Imagine, for example, editing a long document using the stylus like a pen, and swiping with the other hand to scroll the document. Now, you may object and say: you still need a keyboard. Well, I agree, and the reason is that you can type faster with a keyboard than you can write with a pen. But, with the asterisk that this is not the case with everyone, only people who can type well. If you can't type faster than you can write, then you don't need a keyboard at all! Wow! Then all you need is a giant size touch-screen. But for touch typists, yes, you will need a keyboard, otherwise you will be sacreficing a lot of speed. I don't know, will this be a slide out, or a fold up? Not really sure. What about one handed keyboard? I personally have a thing for one-handed keyboards.<br><br>Anyway, that's my vision of the future, and I think Apple obiviously stands the best chance of making it happen, but personally I don't really care who does it. Will it happen? Well, I <i>was </i>right about the iphone before, so...</p></content>
        </entry>,<entry>
            <title>Atlanta Jazz Musicians</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/02/05/atlanta-jazz-musicians">
            <updated>2008-02-05T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/02/05/atlanta-jazz-musicians</li>
            <content type="text">
<p>Atlanta has plenty of talented Jazz musicians. Here's a list of people I know of:<br></p>
<ul>
	<li>Derek(trumbone)</li>
	<li>Craig Shaw(bass)</li>
	<li>Danny Harper(trumpet)</li>
	<li>Philip Harper(trumpet)</li>
	<li>Teri Harper(piano, vocals)</li>
	<li><a href="http://www.joegransden.com/">Joe Gransden</a>(trumpet, vocals)</li>
	<li><a href="http://www.tammyallen.com/live/" mce_href="http://www.tammyallen.com/live/">Tammy Allen</a>(vocals)</li>
	<li><a href="http://soholounge.com/takana/" mce_href="http://soholounge.com/takana/">Takana Miyamoto</a>(piano)</li>
	<li><a href="http://www.danfurman.com/store.html" mce_href="http://www.danfurman.com/store.html">Dan Furman</a>(piano) - now in NYC</li>
	<li><a href="http://www.myspace.com/68607131" mce_href="http://www.myspace.com/68607131">Russell Gunn</a>(trumpet)</li>
	<li><a href="http://www.bernardlinnette.com/" mce_href="http://www.bernardlinnette.com/" title="Bernard Linnette" target="_blank">Bernard Linnette</a>(drums)</li>
	<li>Cody Stein(piano)</li>
	<li><a href="http://profile.myspace.com/index.cfm?fuseaction=user.viewprofile&friendid=62710160">Ryan Whitehead(tenor sax)<br></a></li>
	<li><a href="http://profile.myspace.com/index.cfm?fuseaction=user.viewprofile&friendid=36556304">Mace Hibbard(sax)</a></li>
	<li><a href="http://profile.myspace.com/index.cfm?fuseaction=user.viewprofile&friendid=58097304">Leeland Davis(keys)</a></li>
	<li><a href="http://www.davidellington.com/">Dave Ellington</a>(hammond B3, keys)</li>
	<li>Dave Bass</li>
	<li>Dave Frackenpohl</li>
	<li>Syvester Spann</li>
</ul></content>
        </entry>,<entry>
            <title>Compiling a windows application as supposed a console application from haskell</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/02/04/compiling-a-windows">
            <updated>2008-02-04T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/02/04/compiling-a-windows</li>
            <content type="text">
<p>The fact that my haskell application always runs in a command window(Windows land here) was really nagging me. I happened to be fiddling with C# express studio last night, and found out that the difference between a "console application" (one what always invokes a command window to run itself) and a "windows application" is but a compiler flag. So I thought, there must be an analogous thing in haskell, but first in gcc. I hunted down this gcc flag, and it turned out to be -mwindows. For compiling haskell using ghc, you'd use -optl-mwindows. This compiled at first, but didn't run, because it turns out that any time you try to print something to the console, it bombs out - this is the case for haskell only, for c, it just simply doesn't print anything on the screen. So I had to write a quiet version of my program that doesn't make use the putStr functions - err, actions - at all. Luckily this wasn't very hard because I had already separated out all my lib stuff that doesn't do any console IO to a separate file. Once that was done, it all worked. So now every time the scheduler runs my backup program there won't be an annoying window popping up. This is great!<br></p></content>
        </entry>,<entry>
            <title>Haml support for e-texteditor</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/02/04/haml-support-for-e-texteditor">
            <updated>2008-02-04T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/02/04/haml-support-for-e-texteditor</li>
            <content type="text">
<p>I finally got the syntax highlighting support for haml and sass in e-texteditor. There isn't a lot of documentation for e-texteditor, but the textmate bundles are supposed to work for e-texteditor. So I just followed the directions <a href="http://wincent.com/knowledge-base/Installing_the_Haml_TextMate_bundle">here</a> with the exception that I first cd to something like c:\Program Files\e\Bundles. After restarting the editor, syntax highlighting now works. Btw, I also looked into Netbeans, the problem was: a couple of things I thought I would get/really needed were not there:<br></p>
<ol>
	<li>Good Haml support - there is some Haml support now, but you can't jump- to-definition on a method call like you can in erb</li>
	<li>There's no way to go back to previous buffer I was in? There are back buttons for last edited and so forth, but I didn't find one for simply getting back to the last file I was at, weird. I really enjoyed this feature in Eclipse<br></li>
</ol></content>
        </entry>,<entry>
            <title>Hello Haskell</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/01/21/hello-haskell">
            <updated>2008-01-21T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/01/21/hello-haskell</li>
            <content type="text">
<p>For the past four days I've been learning Haskell. As my first real program, I wrote a file backup utility - essentially a command line wrapper to rsync. The program was probably around 200 lines, just large enough for me to get comfortable with the language. There are many things I like about the language, and some that I don't, let's get started.<br><br></p>
<b>Safety of the Type System</b>
<p><br>After working mainly with ruby for a while it's refreshing to go back to a statically typed language. But Haskell's type system is way better than that in Java. Now, I've used OCaml before, but that was a long time ago and I had a lot of trouble with it, so I must say I didn't "get it" at that time. This is the first time I've really gotten comfortable with this kind of type system, and I love it. When you have a type system like this, you have less need for writting tests, because the compiler catches a large class of errors for you. Like in Ruby, I write tests almost religiously sometimes because I want the luxury of the safety provided by the test suite: so that I can safely refactor my code later. Well, in haskell it's like you <i>have </i>that safety without having to write those tests. Granted, there are still cases when you should test for logic, but you will never have your code fail due to nil-when-you-didn't-expect-it or no-such-method(with Java it's NullPointerExceptions and ClassCastExceptions). In my short experience, it's mostly true that once you get the program to compile, "It's just works!"<br><br></p>
<b>Type Inferencing</b>
<p><br>This works great in practice, not just in theory. All the discussions of static vs dynamic usually ignore type systems with type inference, and so are more of comparisons between <i>old </i>type systems and dynamic languages, and the dynamic advocates usually point out that it's easier for them to make refactorings involving changing the type of a variable. It's easier to show with an example. Let's say you have a piece of information that you need to pass to many different places in your code. At the beginning you use just a string to store it:<br>String filepath;<br>processFile(String filepath) ...<br>copyFile(String filepath, String filepath) ...<br>updateFile(String filepath) ...<br>processFiles(String[] filepaths) ...<br>Now let's say at a later time you find that a string is not enough, you need some more information to go along with each file path. you need:<br>FilePath filepath;<br>Now you are screwed. Even Eclipse can't help you with this type of refactoring. You need to make probably hundreds of changes all through out your code base, including: 1) every method/constructor declaration  that references filepath; 2) every instance variable that holds a filepath; 3) every local variable that holds a filepath; 4) all the places where you create a filepath; and 5) all the places where you need to actually perform operations with filepaths. In dynamic languages, you would only have to make changes for items 4 and 5, because type information is not explicitly declared at function and variable definitions. <i>But</i>, this is true also for type inferencing languages like haskell. Therefore, if you are using one of these languages, the refactoring argument for dynamically typed languages is a moo point. Haskell is like the best of both worlds. What's more, the compiler guides you through the refactorings, whereas with dynamic languages, you need to rely on testing to make sure your refactoring didn't break any thing.<br><br></p>
<b>The Infamous IO Monad</b>
<p><br>To do any kind of IO in Haskell, you have to first grok the IO Monad. This is a scary proposition, but once you get it, you will be fine, and you'll be better for it. The way I look at it, there are 2 programming styles in Haskell: the functional style and the imperative style. The imperative style is required for any kind of IO operations, because IO operations are <i>tainted</i>, 'cause IO is a side effect, and functions shouldn't have side effects in the pure functional sense. To program in Haskell, you will need to be fluent in both programming styles. Now, the imperative style can be use for more than just programming IO, it's used for all monads. What's a monad, you ask? Oh brother, you'll have to ask me another day.<br><br></p>
<b>Runtime Errors</b>
<p><br>Now, even though with all it's safety, you can still have runtime exceptions in Haskell. But exceptions can't happen in functional code, only imperative code. So, an example would be file-not-found. Unlike the interpreted languages though, you don't get a stacktrace when you have an exception, so this is actually a minus for Haskell.<br><br></p>
<b>Weak Regex Support</b>
<p><br>I found the regex support a lot weaker than say perl/ruby/javascript, in fact even than python and Java. There's no syntax support for it, and the regex library in the standard distro is a bit hard to use. I was told that regex is not in the spirit of Haskell. Haskell hackers are more hip to something called Parsec. Fair enough, but I think having good regex support will help Haskell's popularity.<br><br></p>
<b>Third Party Libraries</b>
<p><br>In Haskell, the package system is Cabal. It's closer to Python's Eggs, I would say, but slightly lower level. Because Haskell is a compiled language at heart(although there is a bytecode mode), there are more C-isms in Cabal. Many third party libraries require compiling C code, and I've had problems with many of these on cygwin.<br><br></p>
<b>Interactive Shell</b>
<p><br>Give me my interactive shell or give me death! Thank god there's an interactive shell for Haskell. Again, best of both worlds. Although, the shell is limited - not like in ruby or python where you can pretty much type in any thing, in Haskell, you don't really have access to the full power of Haskell at the prompt. But still, it's a very very useful tool during rapid prototyping.<br><br></p>
<b>Haskell Deserves a Great IDE</b>
<p><br>It's my opinion that a compiled language nowadays really need an IDE to be pleasant to work with. If for nothing else than the ease of getting error markers inside your code editor; clicking an error to jump to its line number; and having it auto-compile when you save a file. I used the haskell plugin for Eclipse briefly, but it stopped working after the first session - some Java runtime exception =( There's no reason that Haskell can't have all the features of the cool Java IDEs out there and more, other than manpower.<br><br></p>
<b>Namespace Polution</b>
<p><br>Haskell is not an OO system. And as such it's more vulnerable to namespace polution, because objects act like little namespaces. This shows up in some of the standard library code for example: hGetContents, hGetLine are actions that read from a file handle. Those are not pretty names. I guess h stands for handle. In an OO system, this could have been h.GetContents. The problem of namespace collison is handled at compile time. If you imported 2 modules that both have a function called map, for example, you'd have to prefix "map" with the name of the module, like Data.List.map. But needless to say, that is not nice. You could alleviate this somewhat by passing functions around as values(ah, caught myself before I said variables).<br><br>Overall, I really dig Haskell and I plan to use it for more of my work as well as play, and I am sure I will have more to say about it as I learn more. Like, I haven't even dug into testing in Haskell, and QuickTest looks really cool.<br></p></content>
        </entry>,<entry>
            <title>foldr exercises</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/01/18/foldr-exercises">
            <updated>2008-01-18T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/01/18/foldr-exercises</li>
            <content type="text">
<p>I implemented some common ruby list operations in haskell using foldr:<br><br>import Data.Maybe<br>-- find f [] = Nothing<br>-- find f (x:xs) = if f x then Just x else find f xs<br>find f = foldr (\a b -> if f a then Just a else b) Nothing<br><br>-- select f [] = []<br>-- select f (x:xs) = (if f x then [x] else []) ++ select f xs<br>select f = foldr (\a b -> if f a then a:b else b) []<br><br>-- collect f [] = []<br>-- collect f (x:xs) = (f x) : (collect f xs)<br>collect f = foldr (\a b -> f a : b) []<br><br>main = do<br>  putStrLn $ show $ find (==1) <strike>(\x -> x == 1)</strike> [3, 3, 5, 6, 2]<br>  putStrLn $ show $ find (==1) <strike>(\x -> x == 1)</strike> [3, 3, 5, 6, 2, 1]<br>  putStrLn $ show $ select (==1) <strike>(\x -> x == 1)</strike> [2,3,3,33]<br>  putStrLn $ show $ select (==1) <strike>(\x -> x == 1)</strike> [2,3,3,33,1]<br>  putStrLn $ show $ collect (*2) <strike>(\x -> x * 2)</strike> [1,2,3]<br>  <br>The commented out lines are the normal way of implementing the function while the line below is the foldr way. All 3 of these functions are already available in the the standard library Data.List as find, filter, and map respectively.<br><br><i>Update: made use of sections to make the code prettier.</i><br></p></content>
        </entry>,<entry>
            <title>a little haskell</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/01/17/a-little-haskell">
            <updated>2008-01-17T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/01/17/a-little-haskell</li>
            <content type="text">
<p>In the process of learning haskell today I found <a href="http://www.haskell.org/haskellwiki/Tutorials/Programming_Haskell/String_IO" mce_href="http://www.haskell.org/haskellwiki/Tutorials/Programming_Haskell/String_IO">this tutorial</a> and followed it and wrote my own version of wc. Here's the code:<br><br>import System.Environment<br>import Data.List<br>data Countable = CList [String] | CString String<br>count (CList s) = length s<br>count (CString s) = length s<br>main = do<br>  [f] <- getArgs<br>  s   <- readFile f<br>  putStr (wc s)<br>  putStrLn (" " ++ f)<br>wc s= unwords (map (show . count) [CList (lines s), CList (words s), CString s])<br><br>I made use of a few haskell-ism already. The main work is in the last line, which is written in a pure functional way, while the main = do block is the imperative file IO stuff. I made use of functional composition: show . count. The length function, although works for either strings or lists, cannot in itself be used with the map function because in haskell members of a list must have the same type. This is why I also created my own datatype Countable with a count method for counting either lists of strings or the size of a string.<br><br>It's interesting that when you take a step back from this, you realize that most people coming from the imperative world would not understand what this program is doing at all.<br></p></content>
        </entry>,<entry>
            <title>Regex in e-texteditor</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/01/15/regex-in-e-texteditor">
            <updated>2008-01-15T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/01/15/regex-in-e-texteditor</li>
            <content type="text">
<p>Today I was faced with the task of converting my existing stylesheet to <a href="http://haml.hamptoncatlin.com/">sass</a>. But my stylesheet is so big! I really didn't want to do this by hand. Now, I had heard somewhere, and half suspected you could use search and replace with regex in e-texteditor(the textmate equivalent on windows). Wow! was I blown away and cursed myself for not knowing to use this earlier. So what I ended up doing was a version of this:<br></p>
<ol>
	<li>replace ([^ ]+)\: with :$1 to change font-size: to :font-size</li>
	<li>replace [^ ]*{[^ ]*\n with \n to remove all open braces</li>
	<li>replace }[^ ]*\n with \n to remove all closing braces</li>
</ol>
<p>This feature really made my day.<br><br>Now sass and haml, I think they are still a bit buggy: they don't handle bad input very well. But I hope that it improves.<br></p></content>
        </entry>,<entry>
            <title>Are Choices Good Or Bad</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/01/15/are-choices-good-or-bad">
            <updated>2008-01-15T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/01/15/are-choices-good-or-bad</li>
            <content type="text">
<p>This post is inspired by this <a href="http://www.screaming-penguin.com/node/7390" mce_href="http://www.screaming-penguin.com/node/7390">Charlie Collins post</a>. Also partly inspired by a talk I heard - probably on IT conversations - in which the speaker(I had forgotten the name) proclaimed that choice is overrated. I think it's clear that there are times when having more choices is better, and there are times when having fewer choices is better. But we can do better than that. I think A good rule of thumb to use is: have more choices if you care, and have less choices if you don't.<br></p>
<b><br>Some examples</b>
<p><br>buying jam: are you passionate about jam? Do you love a certain kind of jam/fruit(Apricot)? Or do you simply want some jam to put on the table because your wife told you to get some?<br>buying cars: are you passionate about cars? Do you want a great looking car? A super fast car? A cute car? A car that is safe? A car that is "green"? A car that's cheap? Because a car affects your life in so many areas(driving pleasure, self esteem, financially, quality of life, etc), people are invested in their decision of buying cars.<br>software frameworks: some people are very invested in how the write software and what frameworks/tools they use, others only care about using their craft to pay the bills and therefore go after the most widely adopted frameworks.<br>You get the idea. <br><br>But then what about the example of patients when faced with the decision of surgery, most would rather defer the decision to their doctors? Well, there's a second component to this: do you have enough knowledge about the issue to make a good decision? If you don't, and you don't have enough resources, time, will, or ability to do the research yourself, then it makes more sense to defer the decision to a more knowledgeable person, even if it's a life-or-death situation.<br><br>But what about the problem of choosing software frameworks? First, how does the problem of analysis paralysis manifest itself? In the case of analysis paralysis, we also have a life-or-death situation(sort of, it really shouldn't be, but many view it so), but the decision maker(s) thinks he has the resources, time, will and ability to do the research for himself, and thus goes off and does the research. But the research is taking too long, partly because there are many choices, but really because it's hard to pick a clear winner.<br><br>In the software framework space, especially open source, there is another issue in play: manpower. The more popular your framework is, the more contributors you will have, either actually contributing code, submitting bug reports, writting documentation or simply blogging about how to do a certain thing. If your framework has popularity/manpower, it has a better chance of becoming great and coming out on top because it will improve faster than the competitors who do not have a lot of manpower. When you don't have any clear winners, as I think is the case right now for Java and Python, sometimes people give up their analysis and do their own thing - as Neal Ford mentioned, or just live without any fancy framework. This takes manpower away from the would-be winners.<br><br>But, in the Java space, I predict that there will eventually be an emerging winner. I just hope it isn't JSF =) Also, I like some of the things Neal wrote in the past, but he's coming off too much like a rails pimp to my tastes.<br></p></content>
        </entry>,<entry>
            <title>Epiphanies: Emacs</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/01/15/epiphanies:-emacs">
            <updated>2008-01-15T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/01/15/epiphanies:-emacs</li>
            <content type="text">
<p>This is a second is my series of epiphanies in software development, and the subject is: Emacs. I used Emacs for programming when I was in college, and I would say I was probably more into customizing my .emacs then about 80% of everyone. I customize the keys so that I can use i, j, k, l as arrow keys, and then one more key over to get to the previous word and then another over to get to beginnig/end of line. I also programmed macros in Elisp, things like getters and setters in java, for example. At my high-on-emacs period, I would routinely digress from my project at hand to write elisp functions instead. I also loved the way you can record macros, and then tell it no run the macro n times, that's an ability that I've never regained after abandoning emacs. Why did I abandon Emacs, you might ask? It was partly because of Eclipse, which I will post about later. For more fun about emacs, read <a href="http://steve.yegge.googlepages.com/you-should-write-blogs">Stevey's Emacs is to a lightsaber as Eclipse is to a laser blaster</a> post.<br></p></content>
        </entry>,<entry>
            <title>Styling Links</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/01/06/styling-links">
            <updated>2008-01-06T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/01/06/styling-links</li>
            <content type="text">
<p>Whenever you are styling links - like with background images, make sure you set display to block, otherwise things just won't work.<br></p></content>
        </entry>,<entry>
            <title>How to make your inner frame extend all the way to the bottom of the window-you can't</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/01/04/how-to-make-your-inner-frame">
            <updated>2008-01-04T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/01/04/how-to-make-your-inner-frame</li>
            <content type="text">
<p>This problem has come up a couple of times for me in the past. I shruged it off the last time, but this time I decided to do some research. What I found - as to the best of my knowledge, is that you can't. The problem is this:<br>
I have a horizontal column that is centered in the middle of the window in my design, sort of like <a href="http://www.csszengarden.com/?cssfile=/205/205.css&page=0">this</a>. But what if the content is too short to fill up the entire screen? The bottom of the column abruptly ends and you end up with a discontinuity. There's no good way of fixing this that I am aware of. I've concluded the best way is just to use a background image at the bottom of the column to soften it's ending. Another thing I've done is to use the min-height hack to make short pages not so short. And in actuality you can use the min-height hack to make sure it always extends beyond the max of the screen, but I don't think it makes sense to create that much empty space at the bottom.<br></p></content>
        </entry>,<entry>
            <title>Changing the rendering for displaying exceptions</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/01/04/changing-the-rendering-for">
            <updated>2008-01-04T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/01/04/changing-the-rendering-for</li>
            <content type="text">
<p>I just added autofresh support for the stacktrace pages, now you get get the benefits of autofresh while you are refactoring your code, which can cause temporary breakage, for example. It was easy, altough not at first easy to find. The answer was found in the comments of actionpack/lib/action_controller/rescue.rb. It bascially said you just need to override the rescue_action_in_public - for "public" errors - and rescue_action_locally - for local errors, which shows the stacktraces. I just copied the existing rescue_action_locally method over and swapped in my template file instead(changed code in orange):<br><br>module ActionController<br>  class Base<br>    def rescue_action_locally(exception)<br>      render :text => 'it bombed'<br>      add_variables_to_assigns<br>      @template.instance_variable_set("@exception", exception)<br>      @template.instance_variable_set("@rescues_path", File.dirname(rescues_path("stub")))<br>      @template.send!(:assign_variables_from_controller)<br>  <br>      @template.instance_variable_set("@contents", @template.render_file(template_path_for_local_rescue(exception), false))<br>  <br>      response.content_type = Mime::HTML<br>      render_for_file("<b>#{File.dirname(__FILE__)}/templates/layout.erb</b>", response_code_for_rescue(exception))<br>    end<br>  end<br>end<br><br>This will tell it to find the layout.erb in my plugin directory instead of the one buried deep inside rails.<br></p></content>
        </entry>,<entry>
            <title>Autofresh</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/01/03/autofresh">
            <updated>2008-01-03T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/01/03/autofresh</li>
            <content type="text">
<p>Out of frustration with the work I was doing, I decided to switch gears a tiny bit and work on this idea I had, and <a href="http://autofresh.rubyforge.org/" mce_href="http://autofresh.rubyforge.org/">Autofresh</a> was the result. I enjoyed this experiment, it did not take much to make it work - I just based it on the rspec_autotest plugin by Nick Sieger, but it turned out to be very useful, Yeh!<br></p></content>
        </entry>,<entry>
            <title>CSS recipes: min-height hack</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2008/01/03/css-recipes:-min-height-hack">
            <updated>2008-01-03T05:00:00.000Z</updated>
            <id>http://tobyho.com/2008/01/03/css-recipes:-min-height-hack</li>
            <content type="text">
<p><a href="http://www.dustindiaz.com/min-height-fast-hack/" mce_href="http://www.dustindiaz.com/min-height-fast-hack/">This really helped me out</a><br>And the order of the lines is important, make sure it's:<br>  height:auto !important;<br>  height:640px;<br>and no the other way around. And one more thing: Do not use overflow: hidden with this.<br></p></content>
        </entry>,<entry>
            <title>Mock Testing and stub everything</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/12/28/mock-testing-and-stub">
            <updated>2007-12-28T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/12/28/mock-testing-and-stub</li>
            <content type="text">
<p>This is a follow up to <a href="/Adventures_in_Testing_with_Mocks" mce_href="/Adventures_in_Testing_with_Mocks">Advantures in Testing with Mocks</a>. I have been growing dissatisfied with the mockist style of testing recently. The reason is, I was trying to learn it, but it just required me to stub out everything that was called. Not only was it tedious, it also cause the test code to be way too dependent on the implementation code. It got to the point where to write a test, I first have to look at the implementation to see what are the methods that are called. I was all but ready to call it quits on the mockist style. <br><br>But, yesterday I found stub_everything, which allowed me to find a way to embrace mocks once again. Basically, stub_everything('my object') is used in place of mock('my object'), which gives you a mock object that will return nil for any message sent to it that it doesn't understand without bombing out. This means that I can escape specifying every method call that has to go on during the tested method invocation.<br><br>Also, I realized that mocks are not to be used in all situations, but should rather be used strategically in certain spots. Basically, you want to avoid having your tests be dependent on your code. To give an example, let's say you want to test a controller method that looks up a user from a user ID. Naturally, you would stub out User.find, right? But what if the implementation used User.find_by_id instead? The problem is that there's more than one way to do this, and therefore the implementation is too maliable. Therefore, if it were me, I would not use a mock for a situation like this. Mocks and stubs are to be used only for cases where the method call - or message - is stable, there's only one method available to accomplish the given task, and when theh message is meaningful. For all messages that are not meaningful to be tested for the particular behavior, use stub_everything to ignore them. Here's an example:<br>describe "audit" do<br>  controller_name :project<br>  before :each do<br>    setup_projects # load data into db<br>    @user = stub_everything('user')<br>  end<br>    <br>  it "should audit when user is logged in" do<br>    controller.stub!(:current_user).and_return(@user)<br>    @user.should_receive(:audit).once<br>    get :show, {:id => @project.id}, {:user => 1}<br>  end<br>end<br>Here, I justify stubing out the controller's current_user method because that's the only way to get at the current_user that the authentication system provides. As for the expectation for audit, it's also a stable and non-aliased method. But even more importantly, that's exactly what I want to test! This is a case when I want to test the fact that the :audit method was called more so than I want to test its outcome as encoded in the database, because as I change the implementation of audit, its database representation could very well change, heck, audit info might not even <i>be </i>store in the database. As for the rest of the data - how project is looked up - that's retrieved from the database like normal. Real mockist testing people would say that db accesses are slow. There's a point to be made that project look up can also use a stub_everything, but one drawback of that is if the implementation does a multi-level object traversal like: project.name.length, then returning nil for name won't work, and you have to write some extra mocking code. Hmm, perhaps what is needed is a really_stub_everything which instead of returning nils for everything, returns itself instead, then you can really ignore all interactions with this object. Hmm..., that's a thought.<br><br>And so, I think that from now on, my mock testing approach - which is not really the mockist way - is to still use fixtures or other db setup templates by default, but only use mocks at select places where it makes sense.<br></p></content>
        </entry>,<entry>
            <title>Why We Want Solutions That Work For All Problems</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/12/27/why-we-want-solutions-that">
            <updated>2007-12-27T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/12/27/why-we-want-solutions-that</li>
            <content type="text">
<p>In software development(and I am sure this applies to areas other than software development, I just am not knowledgable enough to point out which ones), there is a culture of <i>solutions that work for all problems</i>. Let me first elaborate what I mean. For some this means being sold on a particular technology or methodology - the <i>solution</i>, but no, I should rephrase, not sold, but being really excited, to the point that they see the solution as the solution to <i>all </i>their problems. For others this means that on any given problem that he is trying to solve, he is likely to seek a solution that solves the entire class of problems related to the problem at hand, and only after that, work on the problem at hand.<br><br>These are perhaps two different problems, and so this is probably two blog posts jammed into one. Is there a connection between the two? Well, yes, I am sure, but in what way? That's what I am going to try to explore a bit later.<br><br>Of course, I am probably the first to point out that these practices/approaches are bad, that you shouldn't base an architecture on a single technology - example: building an XSLT centric reporting engine even though your data isn't in XML to begin with, or making your domain model <a href="http://martinfowler.com/bliki/AnemicDomainModel.html" mce_href="http://martinfowler.com/bliki/AnemicDomainModel.html">anemic</a> just so that it would be more webservices-friendly. That you also shouldn't build your framework before you build your application, but rather build your application first - perhaps a couple of them - and then see what is useful that you can extract from them along the way or afterwards. These are things that I have learned over time through my experiences, and they are what I believe to be true now but it hasn't always been the case. But instead of making these criticisms and risk beating a dead horse too many times I will instead try to explore the psychology of why we take these approaches.<br><br>First, I will try to tackle the second phenomenon. <i>Why is it that good software engineers tend to overgeneralize?</i> One word that comes to mind is <i>reuse</i>. Reuse is widely accepted in the industry as good practice. Almost all software developers, at one point or another - most of them early on in their career - has come to the realisation - quite possibly in some form of <i>rude awakening</i>(as an aside, I think that many developers learn important lessons in this way. These lessons cut deep, and that's the reason why they voice their opinions oh so strongly) - that a copy-n-paste style of code reuse doesn't cut it, and therefore advocate <i>real</i> code reuse - in the form of shared functions or objects or modules or other types of abstractions. To focus a bit more on this <i>rude awakening</i> that was experienced: they very probably ended up with some code that was brittle and very painful to maintain. Bad experiences have a very lasting effect. Therefore, after that point in their career, developers become more cautious, not wanting to repeat the mistake once made. Ones that were especially affected watch their every step when writing code to stay true to code reuse, and code reuse, at it's core, is all about generalization. As a consequence of this, all good programmers value generalization. In fact, the Gof book: Design Patterns, is a book of recipes for how to generalize your code. Therefore, being able to generalize your code has become synonymous with being a good programmer. Good programmers want to show that they are good by making their code very general, sometimes to the point where they are anticipating things that don't even exist yet or situations that aren't possible yet, and sometimes making the code more complex than necessary because it having to account for many more different cases. <br><br>So there we have it. I have painted a picture of why programmers tend to overgeneralize. As for the first phenomenon, I have thought more about it and decided it more fitting to put in a separate post.</p></content>
        </entry>,<entry>
            <title>Maven: Broken By Design</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/12/23/maven:-broken-by-design">
            <updated>2007-12-23T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/12/23/maven:-broken-by-design</li>
            <content type="text">
<p><a href="http://fishbowl.pastiche.org/2007/12/20/maven_broken_by_design">Well said.</a></p></content>
        </entry>,<entry>
            <title>When You Think You Are All That</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/12/22/when-you-think-you-are-all">
            <updated>2007-12-22T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/12/22/when-you-think-you-are-all</li>
            <content type="text">
<p>You learn the ropes. You start with the basics. You learn to walk the walk before you talk the talk. But you learn fast, and you learn often, and very soon you learn to do interesting things. You get beyond the basics. You learn the tools of the trade. But beyond that, slowly, you learn to talk to talk, and not just walk the walk. You learn the frame of reference, the state of mind, the philosophy - if you will - of your beautiful craft(not art) - that's right, <i>your</i> beautiful craft(not art). It is so called yours, because of all the time you put into it. It is yours because all the thought you put into it. It is yours because you enjoy it, but even more so, because you live and breath it. At this point, you are an expert. You are an elite among your peers. You are no longer a fish in a pond. You are somebody. You grow satisfied with yourself. And you begin to think: that your are <i>all that</i>.<br><br>It is at this point, that you stop learning. You stop learning because you don't need to anymore. You think you've seen it all. When new things come along, you dismiss them. Because you <i>know </i>it all, you can <i>do </i>it all, and you've been doing it right all along, and so why would you need something else that you haven't heard before? The problem is, as time progresses, other practitioners developed new techniques, new frames of reference, new states of mind, new philosophies, what may seem alien - at first glance - to your own - the one that you had known. Now they all embrace new techniques you ignored, ever since the day when you thought you knew it all. You see that your expert status could be weakened, so you belittle the new, and promote the old. You attack with logic, you attack with examples, you attack with stories that you heard - second hand from your sources. The problem is that since you decided to stop learning, you don't know the new techniques, you refused to learn them. You can speak ill of them but it won't convince the others, because you - although the expert that you are - do not have the benefit of knowing both sides of the story - you know only one.<br></p></content>
        </entry>,<entry>
            <title>Code's Worst Enemy</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/12/21/code's-worst-enemy">
            <updated>2007-12-21T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/12/21/code's-worst-enemy</li>
            <content type="text">
<p><a href="http://steve-yegge.blogspot.com/2007/12/codes-worst-enemy.html" mce_href="http://steve-yegge.blogspot.com/2007/12/codes-worst-enemy.html">Right on, Stevey</a>! Stevey confirms what has been in the back of my head for a long time. But he definitely has more say than me not only because he has a huge reputation, but also that he has single-handed created a codebase of half a million lines. I, on the other hand, have only <i>seen </i>(well, and worked with)<i> </i>codebases of such size.</p></content>
        </entry>,<entry>
            <title>Hulu</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/12/17/hulu">
            <updated>2007-12-17T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/12/17/hulu</li>
            <content type="text">
<p>I got an invitation from Hulu today and tried it out. I signed in and got a whole bunch of free TV shows at my disposal. It doesn't have <i>all </i>TV shows of course, let's say <i>select </i>shows. I gone on to watch an episode of chuck and the quality was really good. Full screen didn't work for me - there were lots of jitters, but they went away at regular size - probably about 3 times the size of youtube videos. The selection is medium sized, there are a lot of interesting shows on there, lots that I haven't seen before - I am not a big TV guy, but definitely not big enough that you can pick any title out of the sky and expect it to be there. Like Battlestar isn't on there - although the classic version is, and Threshold which I kind of left on a cliffhanger, isn't there either. The comercials are much quicker than in a real TV show, and are inserted in fixed length segments, I like this - it's much less intrusive. In conclusion, Hulu is really impressive technologically, the selection menu is probably similar to Joost right now.<br></p></content>
        </entry>,<entry>
            <title>Epiphanies: Java</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/12/05/epiphanies:-java">
            <updated>2007-12-05T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/12/05/epiphanies:-java</li>
            <content type="text">
<p>I've decided to write a series on that software development epiphanies that I have had in my career, roughly chronologically - starting with Epiphany I: Java.<br><br>What is so special about Java? To understand that, you must understand where I was coming from - C. This was not uncommon at all, many(most?) people had this same epiphany coming from C to Java, in fact, it is the reason why Java is so popular - there were a lot of C programmers and many of them converted to Java. The fact that Java had a very C-like syntax was very much a factor in its popularity. But what is the epiphany? C is brittle, has sharp edges, Java is warm and fuzzy. If programming in C is like running with sissors, then programming is Java is like driving in bumper cars.<br><br>What gives Java the warm and fuzzy factor? Let's break it down. <br><br>Is it because of "write once, run anywhere"? Um, good try but no, it's got nothing at all to do with it.<br><br>Java is safer than C because you can never have core dumps! That's why! Although C is typed, it's got no type safety of any kind. Core dumps suck because they are hard to diagnose, basically, when you get a core dump, it means your program crashed, too bad, the os will dump the program's memory into a file, but that's all you got. Getting any information from this file - also called the "core dump" - is hard, I personally have never tried to look at a core dump file. Java doesn't have core dumps because it's an interpreted language. If something bad happens in your program, the worst that can happen is it drops back to the VM which catches the error. What's even nicer is it shows you the stacktrace of where the error occured, complete with line numbers. Raganwald had a <a href="http://weblog.raganwald.com/2006/03/fair-and-balanced-look-at-static-vs.html" mce_href="http://weblog.raganwald.com/2006/03/fair-and-balanced-look-at-static-vs.html">nice post</a> on this.<br><br>Secondarily, Java is safer than C because it has strong typing. C, although it has static typing, also has weak typing(Make sure you understand the difference between strong/weak vs static/dynamic). Because Java has strong typing, it can generally catch more problems/ambiguities at compile type, and thus, reducing the amount of mistakes encountered during runtime. <i>Update: <a href="http://zestyping.livejournal.com/124503.html">here's an example</a> of what </i><i><b>can </b>happen when you have weak typing.</i><br><br>Third, Java is safer than dynamically typed languages like Python because it has static typing. I had the chance of working with both languages in the same project using Jython. The project was a GUI and I felt that it was a big inconvience of Python that if there was a misspelling error, you would only find it much later after running the GUI program(this was magnified because Swing was slow, and especially slow on Mac, at the time). If I had coded the GUI in Java, I get the benefits of compile time checking for simple errors like these.<br><br>So, what is the lesson I learned from Java? That safety is warm and fuzzy. Note that this is not <i>just </i>about static vs dynamic, as you can see from the three preceding examples of safety. Safely is incontroversially good, and all languages, frameworks or what-not should provide some sort of safety, because, more safety => more warm and fuzziness.<br></p></content>
        </entry>,<entry>
            <title>Design Patterns Revisited: Iterators II</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/12/03/design-patterns-revisited:">
            <updated>2007-12-03T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/12/03/design-patterns-revisited:</li>
            <content type="text">
<p>I am learning Haskell afresh now, and it turns out that the iterator pattern is <a href="http://community.livejournal.com/evan_tech/206250.html" mce_href="http://community.livejournal.com/evan_tech/206250.html">REALLY invisible</a> in Haskell. This is a departure from other languages that claim to make iterators invisible like python, ruby and smalltalk, where although the syntax is minimal, you still need to understand the concept of iterators to use them. In Haskell, all expressions are lazily evaluated,
so there's never even a need for the CONCEPT of iterators. Lazy evaluation
of objects in lists or any collection - or any expression, for that matter -  is given to you by default.</p></content>
        </entry>,<entry>
            <title>firefox 1 dot 5</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/11/28/firefox-1-dot-5">
            <updated>2007-11-28T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/11/28/firefox-1-dot-5</li>
            <content type="text">
<p>I've decided to revert back to firefox 1.5 because 2.0 is just too slow and crashy. I found it on: <a href="http://oldapps.com/firefox.htm">http://oldapps.com/firefox.htm</a></p></content>
        </entry>,<entry>
            <title>steve vinoski: productivity</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/11/27/steve-vinoski:-productivity">
            <updated>2007-11-27T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/11/27/steve-vinoski:-productivity</li>
            <content type="text">
<p>Another <a href="http://steve.vinoski.net/blog/2007/11/24/productivity/">great find</a> by Raganwald in the same thread. Which mentions <a href="http://www.joelonsoftware.com/items/2006/08/01.html">this post</a> by Joel, which is great to revisit.<br></p></content>
        </entry>,<entry>
            <title>static vs dynamic = mediocre vs talented</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/11/26/static-vs-dynamic-=-mediocre">
            <updated>2007-11-26T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/11/26/static-vs-dynamic-=-mediocre</li>
            <content type="text">
<p>Raganwald shared this <a href="http://service-architecture.blogspot.com/2007/05/engineering-v-art-challenge-of-masses-v.html" mce_href="http://service-architecture.blogspot.com/2007/05/engineering-v-art-challenge-of-masses-v.html">great piece</a> by Steve Jones, in which Steve basically takes the exact opposite position as I did in a <a href="http://wiki.futuretoby.com/power_vs_protection">previous post</a>. Raganwald points out that it's not as clear cut as that: you have to consider the haskels and the MLs and the fact that limiting-the-ways-that-you-can-screw-up is not only a feature of statically typed languages but are present in some dynamic languages as well. <br>I would like to follow up Raganwald's point that the static vs dynamic debates are often misguided. I will use ruby as the example, because, let's be honest, ruby is what caused all these heated debates.<br></p>
<ul>
	<li>Many people like ruby because of its <i>expressiveness</i>, which does not require it to be dynamic, it's been pointed out for example that <a href="http://memeagora.blogspot.com/2007/11/ruby-matters-frameworks-dsls-and.html" mce_href="http://memeagora.blogspot.com/2007/11/ruby-matters-frameworks-dsls-and.html">haskell can be very expressive</a></li>
	<li>Many people like ruby because of its <i>responsiveness</i>(as seen in rails and the interactive shell), which may seem like it requires it to be dynamic, but is definitely not the case: if you use Eclipse for Java, for example, you know that you can modify code and run it very quickly with the touch of a button because Eclipse compiles code incrementally<br></li>
	<li>Many people dislike ruby because it's does not have statically type checking, which helps to catch their mistakes. I think that people who choose ruby do not necessarily dislike statically type checking, they merely see the gains of expressiveness and responsiveness etc. to outweight the lost in the warm and fuzziness of static type checking<br></li>
</ul></content>
        </entry>,<entry>
            <title>making your ipod more like tv</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/11/26/making-your-ipod-more-like-tv">
            <updated>2007-11-26T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/11/26/making-your-ipod-more-like-tv</li>
            <content type="text">
<p>Today I explored using video playlists on the ipod: so that I can play video clips(video podcasts in my case) one after another without stop or me having to do anything in between. It's sad, but I found the need for this as I often have lunch by myself and watch video podcasts. But by default on the ipod after a video finishes, it just goes back the menu and stops. If I want to watch something else I have to go look for something and click on it again. This sucks. What I want is a continous stream of videos. You can do this on the ipod but it's an obscure feature. What you do is you create a playlist or smart playlist containing videos - in my case I created a smart playist of all the video podcasts that I follow: the episodes of which I haven't seen. If you are doing a smart playlist you could use a filter like: <i>kind contains Video</i>, <i>kind contains Movie</i>, or <i>Video Kind is Movie</i> to filter in all the videos. To sync it to the ipod - this is the tricky part - you go to the music tab(yes, you that's right, <i>music tab</i>), and make sure the playlist is included in ones to sync. <i>You would have thought they would put that in a videos tab or something, but this just shows that it's not just Microsoft: Apple produces a lot of UI WTF as well - and trust me, this isn't the only example.</i> Anyway, back to the ipod, select Videos, and then Video Playlists, and you should see the video playlist you created, click the play button and there you have it!<br>Major bummer: this doesn't work in front row, so my podcasts-as-if-it-were-tv experience is limited to the ipod for now, I hope this changes in the future.<br><i>update: This ipod feature only works when shuffling is OFF, and this setting applies for the entire ipod, not just videos. Also, I think the videos that I skip while watching the stream should not be revisited again in the stream, but the way it is now, ipod always starts from the top of the list and then down.</i><br></p></content>
        </entry>,<entry>
            <title>being functional with ruby</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/11/21/being-functional-with-ruby">
            <updated>2007-11-21T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/11/21/being-functional-with-ruby</li>
            <content type="text">
<p>Ola <a href="http://ola-bini.blogspot.com/2007/11/accumulators-in-ruby.html" mce_href="http://ola-bini.blogspot.com/2007/11/accumulators-in-ruby.html">wrote</a> about writting functional style accumulators in ruby. I knew there was a better solution to his using <a href="http://caos.di.uminho.pt/%7Eulisses/blog/2007/11/20/foldr-the-magic-function/" mce_href="http://caos.di.uminho.pt/%7Eulisses/blog/2007/11/20/foldr-the-magic-function/">fold</a>, which in ruby it's called inject, one of the commenters did mention this. The solution was this: <br></p>
<p>    [1,2,3,4,5].inject([]) {|a,b| [b] + a}<br></p>
<p>this is a one liner but it doesn't create the accumulator for us, so, to be really functional, would you do this?:<br>    reverse = lambda {|l| l.inject([]) {|a,b| [b] + a}}<br>at this point you have a proc object called <i>reverse</i> that performs the reverse. But the syntax for calling a proc is awkward =(. You can do either:<br>    reverse.call [1,2,3,4,5]<br>or, alternatively:<br>    reverse [[1,2,3,4,5]]<br>I am not making this up ;) Ack! This aspect of Ruby - that procs are not the same as methods - is annoying. I guess you COULD do this instead:<br>    Kernel.send(:define_method, :reverse) {|l| l.inject([]) {|a,b| [b] + a}}<br>this gives you a method at the Kernel level which would look just like a function. So you can now do:<br>    reverse [1, 2, 3, 4, 5]<br>But in the Rubyish OO paradigm you'd probably put it in the Array class:<br>    Array.send(:define_method, :reverse) { self.inject([]) {|a, b| [b] + a}}<br>so now you can do: <br>    [1, 2, 3, 4, 5].reverse<br>Actually, ruby already comes with an reverse method for the Array so this is only an exercise.</p></content>
        </entry>,<entry>
            <title>power vs protection</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/11/21/power-vs-protection">
            <updated>2007-11-21T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/11/21/power-vs-protection</li>
            <content type="text">
<p>Time and time again I have heard complaints of ruby that it's too
dangerous because of it's power and that there's more than one way to
do something, but I really hadn't thought about how to respond. I just
felt that it's been okay for me, and different folks have different
tastes. Neal Ford made a comment towards the end of this <a href="http://www.javaworld.com/podcasts/jtech/2007/112007jtech006.html">podcast</a>
that made a great response to it. This is not a new idea, I am
sure Paul Graham has written about it many times. To paraphrase:
building barriers to keep mediocre programmers from doing the wrong
things has the adverse effect of getting in the way of good developers. He also makes the point that <i>"bad developers will move heaven and earth to write bad code</i>". I think that a corollary to that is: <i>mediocre programmers will invariably write mediocre code</i>, i.e., they will never produce anything great. With a <a href="http://www.paulgraham.com/icad.html">powerful or expressive language</a>, every line of code can be and should be great. Therefore, in my view, you should either not work with mediocre/bad programmers in the first place or really bring them up to speed(where code reviews/pair programming can help).<br></p></content>
        </entry>,<entry>
            <title>Amazon Kindle</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/11/20/amazon-kindle">
            <updated>2007-11-20T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/11/20/amazon-kindle</li>
            <content type="text">
<p>Amazon's Kindle actually looks <a href="http://amazon.com/gp/product/B000FI73MA/sr=53-1/qid=1195568085/ref=tr_359161" mce_href="http://amazon.com/gp/product/B000FI73MA/sr=53-1/qid=1195568085/ref=tr_359161">pretty impressive</a>(watch the 2nd video on the page). What impressed me most is that the store connects to the internet via satellite(not wi-fi) for free! Yes! Free! You can do the following things online: buy books, read newspapers and blogs, and search wikipedia. The idea is that amazon is providing you internet access for free because you are supposedly paying for it by buying their books. I already read tons of blogs and new regularly and I know reading it on an e-reader will be much more pleasant for my eyes, so this is something I might actually consider. I don't read books a lot now but that's mostly because it's so troublesome to carry a book around. There is a downside to this device though: it is UGLY! It's definitely not an iphone.<br><i><br>update: there are other negatives, actually:<br></i></p>
<ol>
	<li><i>the price $399 is pretty steep</i></li>
	<li><i>you have to PAY to subscribe to magazines and BLOGS? I am NOT paying to read blogs if I haven't had to do it otherwise</i><br></li>
</ol></content>
        </entry>,<entry>
            <title>Design Patterns Revisited: Iterator</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/11/06/design-patterns-revisited:">
            <updated>2007-11-06T05:00:00.000Z</updated>
            <id>http://tobyho.com/2007/11/06/design-patterns-revisited:</li>
            <content type="text">
<p>The Iterator Pattern came <a href="http://perl.plover.com/yak/design/samples/slide004.html" mce_href="http://perl.plover.com/yak/design/samples/slide004.html">under attack</a>. I shall take on the task of defending the Gof(as it's turning out)! So, okay, yes, yes, the iterator pattern as implemented in the way the class diagram describes...sucks - there's no better way to say it. This is the way the Iterator is implemented in the standard Java library. People hip to dynamic languages like python and smalltalk will point out that the iterator pattern looks much sexier in those languages. Yes, yes. The criticism in the "Design Patterns aren't" slide is that people copy and paste the code samples over and over again into their own code base. There are a few holes in this criticism.<br></p>
<ol>
	<li>the "do it over and over again" retoric is not entirely correct. The concrete implementations of the iterator has to be implemented over and over, but not the Iterator interface itself. In fact, in the Java standard library, there's only one universal Iterator interface.</li>
	<li>If the only stuff that has to be done over and over again is the iterator implementations, this is not any different in dynamic languages</li>
	<li>The Gof does mention very specifically the different kinds of iterator patterns, in particular:<ol>
		<li>external iterator - where the client of the iterator controls the iteration(generally how it's done in Java, C++ and python)<br></li>
		<li>internal iteration - where the client passes the iterator a code block, or closure, and the iterator controls the iteration(smalltalk, ruby)</li>
		<li>Some languages have iterators built right into the language(python, ruby)</li>
	</ol></li>
	<li>Although the code samples were in C++ only, Gof did give examples for both external and internal iterators, although internal iterators in C++ still suck, so it wasn't a good example(they used a template method pattern to do it, which is not very generic)</li>
</ol>
<p>So, basically, I find the criticism in these slides unfair. Of course, all I have to go on are the slides, I don't have a clue as to what was said by the presenter. To give him the benefit of the doubt, he could just be saying that people are mis-using the Gof book. But then again, in the next few slides he starts to show off how iterator is done in perl and lisp, so probably not.<br><br>What does this all mean? People, if you have the Gof book, <i>read it</i>! Really read it, before you really go attacking it. I mean to say something about Christopher Alexander, but will leave it for a later post.<br><br><i>Update: However, I do agree with the point that much of what the book covers is how to implement the patterns in C++, which is much cluggier than in many dynamic languages. But there's a reason for this: some people just don't have a choice to which the language they use. This was more so in the 90s when C/C++ was the fastest platform but is still the case today where Java dominates the enterprise.</i><br></p></content>
        </entry>,<entry>
            <title>Design Patterns Revisited: State</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/11/04/design-patterns-revisited:">
            <updated>2007-11-04T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/11/04/design-patterns-revisited:</li>
            <content type="text">
<p>Design Patterns have come under mild attact lately, as seen <a href="http://perl.plover.com/yak/design/" mce_href="http://perl.plover.com/yak/design/">here</a>, and <a href="http://norvig.com/design-patterns/" mce_href="http://norvig.com/design-patterns/">here(well, this one's not exactly recent).</a> As a result, I decided to revisit some of the design patterns to tell truth from myth for myself.<br><br>I am going to start with the State Pattern, <i>just because</i>. Here we go. Straight from the Gof:<br><i><br><b>Intent</b><br>Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.</i><br><br>Back up a minute! The object will appear to change its class? Sounds like voodoo. A TCPConnection implementation is used here as an example. A TCPConnection behaves differently depending on which state it's in. So how do you encapsulate the state-specific behavior? Basically you abstract it out into a class hierarchy, which has TCPState as the abstract parent, and the specific states as the children: listening, connection established, and closed, as the the concrete state implementations. A TCPConnection object will dispatch to one of these three State strategies depending on which state it's actually in whenever it's gets an event that needs attention. In that sense, I guess TCPConnection can "appear to change its class", okay, doesn't sound that impressive after you explain it... You could always implement this by having switch statements all over the place, but this doesn't isolate all the behaviors of a state into one place - Gof mentions this in the consequences section. BTW, the consequences section is one of the best features of this book, the problem is, until you can gasp the pattern(whichever one), you probably won't understand this section. The second consequence Gof lists is that this pattern makes state transitions explicit, okay, valid, there are other ways to make this explicit(like having a state enum variable), but this is certainly one way. The third consequence is that the state object, if it has no variables, can be shared amongst any number of context objects(the holder of the states, in the example this would be TCPConnection).<br><br>Does this pattern stand on it's own? I give it a resounding yes! Does "modern" dynamic language features make this pattern unnecessary? No. <br><br>Now, with that out of the way, let's explore something a bit more exciting...<br><br>Here's an example, which was brought up by a former co-worker of mine. He had such a problem: a User could be a RemoteUser or a LocalUser, but a RemoteUser could become a LocalUser and vice versa. He wanted to know the best way to model this in the database. From his design, User would be the parent class and the other two the subclasses. I was quick to tell him to put everything in one table and use one field to specify the state of remote or local. I also thought that requiring an object to change it's type(notice that this is essentially what the State Pattern is trying to do, or to workaround not being able to do) was a ridiculous notion because the OO system just doesn't allow for that. So, clearly, changing the type of an object is something that people want to be able to do. The problem is that "remote" and "local" are really adjectives. In OO, there are only nouns and verbs. Conventionally, adjectives are represented by instance variables inside objects, in this case the variable would probably be named "state" or be a boolean named either "remote" or "local". But, the behavior of the object has to change depending on the state of this variable. The State Pattern is a way of simulating this, or to put it another way - a workaround. Workaround denotes clugginess and accidental complexity, is there any other way to do this?<br><br>Enter <a href="http://www.somethingnimble.com/bliki/mixology" mce_href="http://www.somethingnimble.com/bliki/mixology">Mixology</a>. This is a small ruby library from Something Nimble. It gives you the ability to unmix your mixins. Why would you want to do that? Why, it allows for a complete different way to implement the State Pattern! Just read the article in the link. I'll wait...<br><br>Basically, the way I see it, Mixology is turning the assumption of favoring composition to inheritence up side down. Well, it's not just Mixology, it's also multiple inheritence/mixins. Why? Well, why is composition more flexible than inheritence? Because 1) you can once use inheritence once(one parent) - but this problem goes away with multiple inheritence; 2) you can not change child parent relationships during runtime - Mixology fixes that. Wow! So does that mean we can start using inheritence everywhere we've been using composition? What would the world come to? Okay... I left out one reason, perhaps the most important one... 3) <i>There's a  tight coupling between the base class and the subclass, because of the implicit context in  which the subclass code I plug in will be called</i> - Erich Gamma. I can't argue with that one. But, still, inheritence has become much more powerful, with the addition of multiple inheritence and runtime switching of inheritence relationships. <br><br>Stepping back now to address the issue of design patterns being attacked. So, are design patterns bogus? I think that I have shown it's not. The example of Mixology is not meant to degrade the State Pattern but rather it serves to show that the Gof book is not the last word on design patterns and that there is room to add to and/or improve them(or worsen, if for example, switching inheritence relationships at runtime is not your cup of tea). It is much like how the Constitution was not the last word on how the government should behave.</p></content>
        </entry>,<entry>
            <title>Wario's Smooth Moves</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/11/03/wario's-smooth-moves">
            <updated>2007-11-03T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/11/03/wario's-smooth-moves</li>
            <content type="text">
<p>This WII game is highly recommended. It really shows you all the different possiblities of using the wiimote. Other than wii sports this is the best game I've encountered yet.<br></p></content>
        </entry>,<entry>
            <title>Mauricio's statically checked sql query builder in OCaml</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/31/mauricio's-statically-checked">
            <updated>2007-10-31T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/31/mauricio's-statically-checked</li>
            <content type="text">
<p>Wow! This really blew me away: <a href="http://eigenclass.org/hiki/addressing-orm-problem-typed-relational-algebra" mce_href="http://eigenclass.org/hiki/addressing-orm-problem-typed-relational-algebra">http://eigenclass.org/hiki/addressing-orm-problem-typed-relational-algebra</a><br><br>It is one thing to do crazy metaprogramming stuff during runtime to inspect database schemas(ActiveRecord), it's quite another to do it during compile time! What it actually does is uses a pre-processor called camlp4, which allows you to write your own extensions to the OCaml language. Hmm, when you look at it that way, I guess it doesn't seem THAT amazing, I suppose you could do that with any language if you add a pre-processing step. For dynamic languages, this would suck because it adds a build step where there were none). But for a compiled language like OCaml, you don't notice it at all, but cause you are already used to having to compile the code. Pretty much like the C macro-processor in terms of building. But! I think that to call it a pre-processor is really not fair at all. It can do things that most pre-processors can only dream of. What it's doing is not merely a straight text replace, but it hooks into OCaml directly and controls the way it does type checking and type inference, so that the functions that it returns you are typed both in the inputs and outputs: the types which are mapped from the database schema. And because it directly hooks into OCaml, you can use it with the interactive shell too. I haven't seen any code posted yet, so it's pretty much vaporware as of now, but I'll keep an eye on this development.<br><br></p></content>
        </entry>,<entry>
            <title>Little Ruby Book: Metaprogramming</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/26/little-ruby-book:">
            <updated>2007-10-26T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/26/little-ruby-book:</li>
            <content type="text">
<p>This <a href="http://www.visibleworkings.com/little-ruby/Chapter3.pdf">book chapter</a> is a must-read for rubyists. A picture is worth a thousand words... a few pictures with words that explain them is even better... yeah. I also dig the conversational style of this writing, has a Java Puzzlers kind of vibe(apparently was actually adopted from the book The Little Schemer, the url to the book in progress is <a href="http://www.visibleworkings.com/little-ruby/">here</a>).<br></p></content>
        </entry>,<entry>
            <title>My Laptop Bag</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/24/my-laptop-bag">
            <updated>2007-10-24T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/24/my-laptop-bag</li>
            <content type="text">
<p>My DIY laptop case! The idea is courtesy <i></i>of <a href="http://www.makezine.com/blog/archive/2007/09/how_to_make_a_minimalist.html?CMP=OTC-0D6B48984890">Make Magazine</a>.<br><br></p>
<div><b><div class="image">
	<img src="/uploads/house_remodeling__laptop_bag_066.jpg?1193270716" name="house_remodeling__laptop_bag_066.jpg" width="320">
</div><br><br><div class="image">
	<img src="/uploads/house_remodeling__laptop_bag_067.jpg?1193270733" name="house_remodeling__laptop_bag_067.jpg" width="320">
</div><br><br></b><div><div class="image">
	<img src="/uploads/house_remodeling__laptop_bag_068.jpg?1193270747" name="house_remodeling__laptop_bag_068.jpg" width="320">
</div><br></div><br></div></content>
        </entry>,<entry>
            <title>Green Red and Yellow Code</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/19/green-red-and-yellow-code">
            <updated>2007-10-19T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/19/green-red-and-yellow-code</li>
            <content type="text">
<p>Found a </p>
<strike>great </strike>
<p>must-read article by <a href="http://weblog.raganwald.com/2006/12/economizing-can-be-penny-wise-and.html">raganwald</a>. What a simple and intuitive way to look at software design!<br></p></content>
        </entry>,<entry>
            <title>Sax Scenes in The Conversation</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/18/sax-scenes-in-the-conversation">
            <updated>2007-10-18T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/18/sax-scenes-in-the-conversation</li>
            <content type="text">
<p>That's right, sax scenes as in Saxophone. Man! When I saw Gene Hackman playing the sax to the records it was like watching myself in the mirror... that's what I did when I was lonely. Did it a lot when I was in college. Didn't think anyone else did that too, at least not in mainstream media. What year is this? 1974. I guess mainstream media WAS different back then.<br></p></content>
        </entry>,<entry>
            <title>Debugger Support Considered Harmful</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/18/debugger-support-considered">
            <updated>2007-10-18T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/18/debugger-support-considered</li>
            <content type="text">
<p>Yum! I love Ruby vs Smalltalk flame wars. This one is about whether TDD renders debuggers useless. <a href="http://gilesbowkett.blogspot.com/2007/10/debugger-support-considered-harmful.html" mce_href="http://gilesbowkett.blogspot.com/2007/10/debugger-support-considered-harmful.html">Giles Bowkett of Ruby</a> vs <a href="http://www.cincomsmalltalk.com/blog/blogView?showComments=true&printTitle=When_your_tools_suck...&entry=3370104583" mce_href="http://www.cincomsmalltalk.com/blog/blogView?showComments=true&printTitle=When_your_tools_suck...&entry=3370104583">James Robertson</a> of Smalltalk. I would have to talk James' side here. Although great TDD/BDD can remove the need for the debugger, it's not easy to do great TDD/BDD. It's an art, and takes a good amount of commitment and effort to do, as well as training(I am sure I still don't know the best ways to test in some situations). Basically, TDD is something you have to go out of your way in order to do well, and to say that everyone should do great TDD is a bit like forcing a religion down someone's throat. I think I do OK TDD/BDD. I don't use the debugger on Ruby projects, but would I use it if there were a good one? Yes.<br></p></content>
        </entry>,<entry>
            <title>Barcamp Pictures</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/18/barcamp-pictures">
            <updated>2007-10-18T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/18/barcamp-pictures</li>
            <content type="text">
<p>Cool! Found some barcamp pictures on <a href="http://nali.org">Nick Ali's blog</a>. The flickr group is <a href="http://www.flickr.com/groups/barcampatlanta">here</a>. I actually got in a few of the pictures.<br></p></content>
        </entry>,<entry>
            <title>Meta-programmming in Ruby vs Smalltalk</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/17/meta-programmming-in-ruby-vs">
            <updated>2007-10-17T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/17/meta-programmming-in-ruby-vs</li>
            <content type="text">
<p>Stumbled into Neal Ford's <a href="http://memeagora.blogspot.com/2007/09/ruby-matters-meta-programming-synthesis.html" mce_href="http://memeagora.blogspot.com/2007/09/ruby-matters-meta-programming-synthesis.html">post </a>today which spawn off several other blog posts else where too, including Avi Bryant's new blog. How timely(this was actually one month ago)! I was just musing about this very thing and that's how I found the this blog post. Smalltalk has an adventage over Ruby(an pretty much any other language) because the runtime is always running. Runtime = development time = compile time. This allows for a lot of introspection to occur during development. Things like code completion, for example, are done by inspecting the objects in the runtime, rather than by inspecting the source code like in modern Java IDEs. Of course it can do more than that: things like excuting arbitrary code when you are at a breakpoint, to give another example. You could also query the system for the object class hierarchies to do anything you want with them, including creating new classes and methods on the fly.<br><br>Now, one thing about the Ruby metaprogramming techniques some complain about is the fact that they are hard to debug, because you can't see the code that you are executing. In contrast, you can get the source code to any method during runtime, which means you can easily debug through it(yes, but aside from that, debugging in Ruby still sucks anyway). It's the explicit vs implicit thing again. But the advantage of the Ruby approach is that it's more dry - you specify the declaration once, and that's it, the code that's generated is never seen anywhere, it removes the issue that all code generating tools have: that there's a versioning problem between the generated code and the spec that feeds into the generator.<br><br>Which way is better? Clearly(how can you argue with "clearly"? you can't), neither one is. Is there a best of both worlds? Hard to say.<br><br>It's worth pointing out that Ruby metaprogramming techniques are a very new development. Although it has it's roots in LISP, I think it is a new twist in the ways it is used in the context of OOP. Can these techniques be applicable to other languages? Yes, they are being adopted in many other languages, including Groovy, Python, and Javascript. Also, these techniques are usually used in programming frameworks, in which the ultimate end-user interface is a programming API. And, thus, the goal of all(most?) of these techniques is to automatically generate code that a developer writes code against. From a single programmer's perspective, these are just refactoring techniques, or design patterns, because they don't really give you anything you didn't have before in terms of what you can do(power?), but rather lets you structure your code in a way that's even more dry than what was possible before. As a result you can create very consice APIs with very little code.<br><br>Going back to the ActiveRecord has_many example, some have mentioned that this can be done without using code generation. In Smalltalk, apparently this is done by using an annotation. The class code can then presumably query the annotation information when it needs to get an association, I assume using something like method_missing(I'll have to check this), which you could do the exact same thing in Ruby, only in place of the annotation you'd still have the class initializer. In deed, that is how Hibernate does it for Java as well. So why do the Ruby guys like to use code generation in that case? It's just their style! If someone develops a new kung fu style that kicks your ass, are you going to say he's doing it wrong? Also, in Ruby method_missing is slow, so there's an incentive to avoid it.<br></p></content>
        </entry>,<entry>
            <title>Barcamp Atlanta 07</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/15/barcamp-atlanta-07">
            <updated>2007-10-15T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/15/barcamp-atlanta-07</li>
            <content type="text">
<p>I was lucky to attend the first(I believe so?) barcamp in Atlanta. What is a barcamp? It is essentially a geek-fest. Geeks come together to have an ah-hoc conference on any topic that they want. At the beginning of the event, an empty schedule is put up, and anybody can fill it out by allocating a block of the time to talk about a specified topic, which is called a session. There are multiple rooms, so multiple sessions can occur at the same time. The Atlanta barcamp lasted from Friday evening to Saturday afternoon at the new Georgia Tech ATDC building, some camped overnight prepared with their sleeping bag(in door), others went home to sleep and then came back in the morning the next day(that's me), and some others still did not sleep at all. <br><br>This was the first such event I've been to and I enjoyed it a lot. Some notable sessions for me were: Stephen Flemmings talk on trying to privatize space exploration and his experiences... and the <a href="http://en.wikipedia.org/wiki/Vomit_Comet" mce_href="http://en.wikipedia.org/wiki/Vomit_Comet">vomit comet</a>, I learned about the availability of webcomics , saw a demo on and saw up-close the one-laptop-per-child laptop, and a talk about marketing for geeks. I hosted a session with <a href="http://tmoenk.typepad.com/">Timothy Moenk</a>(whom I only just met) on opening up social networking, or the "social graph". Also I learned to play the Settlers of Catan(a German board game) from Mikah.<br></p>
<b><br>Some take backs</b>
<p><br>I felt that most of the sessions were scripted(guy with ppt presentation), and also a bit too short(30 minutes) to allow any free form discussions since most of the time would be used up just going through the slides(sometimes not even). What ended up happening was that the topics that I attended with which I was already familiar would not teach me anything new(like the one on Javascript and code coverage, for example), what I would have prefered was to have another half hour at least for free form discussion about each others' experiences about the techology/methodology. So what ended up happening was I went to more talks that were about things I didn't know much about, and I got a lot out of those. <br><br>Another problem I ran into was that sometimes 2 of the sessions I was interested occured at the same time, which forced me to miss one of them, others have had the same issue as well. Don't know what to do really about that... maybe we all share the same gmail calender and use a chat feature to resolve any conflicts?<br><br>I met a lot of really smart and geeky people, and had some beers, pizza, and a good time. Cooper: I would have like to see your Gwittir session, but had to leave early on Saturday because someone's installing granite counter tops in our kitchen.<br></p></content>
        </entry>,<entry>
            <title>Who is Bennie Wallace</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/11/who-is-bennie-wallace">
            <updated>2007-10-11T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/11/who-is-bennie-wallace</li>
            <content type="text">
<p>I heard this guy last night as I was getting to atlrug, on my ipod, and
was completely blown away. I looked at my ipod to find out who it was,
and it was Bennie Wallace. Ben Wallace? As in big ben? The former Detroit Pistons center? Obviously not. I hadn't heard of this guy! How can I not know an artist that's in my music collection, you might ask? Well let me just say that parts of my collection were "gifts" from friends. <br><br>Bennie Wallace had me really intrigued. He played Monk tones and played them with an avon-garde southern playful flavor. He's technique was impecable, he could say just about anything he wanted to say, and he brought something different to the table, he wasn't just another Coltrane or Sonny Rollins immitator.<br><br>I googled him this morning and it turns out he's white. I really expected him to be black. And it also turned out that he is still alive and well. His latest CD was produced on January of this year. And he has a jazzy website. Nice! Bennie Wallace: another path of musical exploration for me to go down. Yipee!!<br></p></content>
        </entry>,<entry>
            <title>Sixapart Open Social Networks Manifesto</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/11/sixapart-open-social-networks">
            <updated>2007-10-11T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/11/sixapart-open-social-networks</li>
            <content type="text">
<p><a href="http://www.sixapart.com/about/news/2007/09/were_opening_th.html">http://www.sixapart.com/about/news/2007/09/were_opening_th.html</a></p></content>
        </entry>,<entry>
            <title>Metaprogramming Patterns</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/11/metaprogramming-patterns">
            <updated>2007-10-11T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/11/metaprogramming-patterns</li>
            <content type="text">
<p>I want to catalogue the ruby metaprogramming patterns that are used in the ruby community. Here are some blog links:<br></p>
<ol>
	<li><a href="http://devel.touset.org/blog/articles/2007/06/25/all-i-do-is-bitch-bitch-bitch">Inheriting class methods from modules</a></li>
	<li><a href="http://ola-bini.blogspot.com/2006/09/ruby-metaprogramming-techniques.html">Ola bini's list of 10 techniques</a></li>
</ol></content>
        </entry>,<entry>
            <title>Jazz Impersonation Candidates</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/08/jazz-impersonation-candidates">
            <updated>2007-10-08T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/08/jazz-impersonation-candidates</li>
            <content type="text">
<ul>
	<li> Paul Gonsalves
	</li>
	<li> Coleman Hawkins
	</li>
	<li> Paul Desmond
	</li>
	<li> Cannonball Adderley
	</li>
	<li> Eric Dolphy
	</li>
	<li> John Coltrane
	</li>
	<li> Miles Davis
	</li>
	<li> Charlie Parker
	</li>
	<li> Thelonious Monk
	</li>
	<li> Jimmy Smith (looks like <a href="http://www.b3monaco.com/" title="http://www.b3monaco.com/" rel="nofollow">someone's</a> already doing this)
	</li>
	<li> Mulgrew Miller
	</li>
	<li> Wes Montgomery
	</li>
</ul></content>
        </entry>,<entry>
            <title>Nagging Lighty to cache my Javascripts</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/06/nagging-lighty-to-cache-my">
            <updated>2007-10-06T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/06/nagging-lighty-to-cache-my</li>
            <content type="text">
<p>The title is not exact... it should be nagging lighty to let the
browser cache my Javascripts. For one reason or another, my Javascript
and css files were not getting cached by the browser. I asked around
and was told to that in production mode the query parameters shouldn't
show up after the javascript includes, like so:<br><script type="text/javascript" src="blah.js?28372901"/><br>This
turned out to be false, the query parameter will be there even if you
are in production mode - I know this definitively from reading the
source. My friend turned me on to the asset packager, which I tried
next. The asset packager was very helpful, it solved the Yslow
complaint that I have too many includes to external files. Asset
package can combine all your javascript files into one, and all your
css files into one, so that your browser only has minimal external
files to fetch and loads the page much faster. It also minfied my
javascript using Doug Crockford's jsmin tool, which required me to go
through and add end-of-line semicolons in all my code, ack! Anyway,
asset package solved one of my problems, but not the one I was
originally after - the files were still not getting cached!<br><br>Again
thanks to Yslow(thank you Scott Hanselman for recommending this tool)
told me the Expired header was not being set(I had already known this
but thought it could be solved with other more round about ways). I did
a search on "expired header lighttpd" and I had the <a href="http://www.cyberciti.biz/tips/lighttpd-client-side-cache-with-mod_expire.html" mce_href="http://www.cyberciti.biz/tips/lighttpd-client-side-cache-with-mod_expire.html">answer to my problem</a>.
It turns out I had my mod_expire(lighty specific) configured wrong
because I have /wiki/ prepended to all paths in the wiki app, so in the
expired.url declarations: /javascripts/ didn't match my javascript
directory. I changed to /wiki/javascripts/ and it all worked. I set the
expired to one year later to match Yslow's recommendations. The wiki is
so much faster than before, yipee!</p></content>
        </entry>,<entry>
            <title>Amazon online music store</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/04/amazon-online-music-store">
            <updated>2007-10-04T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/04/amazon-online-music-store</li>
            <content type="text">
<p>I tried out the Amazon online music store the other day. Ironically, I used it to buy the new Feist album which I learned about from apple's new ipod nano commercial(Ha, sorry Apple, whom I am a stockholder of, I kinda screwed you). In the Amazon online music store all songs are in the DRM-free mp3 format. The price 89 cents per song undercuts Apple's 99 cents per song. The price per album $8.99 also undercuts Apple's $9.99 per album...dang! The buying experience was ok, not much surprises. You checkout as you would as other amazon purchase, and you have to </p>
<strike>buy </strike>
<p>install their downloader to download the tracks. And then of course if you use iTunes you still have to import them to the library. I like it. Apple, you better do something quick.<br></p></content>
        </entry>,<entry>
            <title>Software on the windows platform</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/01/software-on-the-windows">
            <updated>2007-10-01T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/01/software-on-the-windows</li>
            <content type="text">
<p>List of software that have the following criteria:<br></p>
<ol>
	<li>Enjoyable to use</li>
	<li>Written on the windows platform(C++/Visual Studio, not on an interpreted language, Java or depend on GPL'ed software)<br></li>
</ol>
<p>Here it goes:<br></p>
<ol>
	<li>Opera</li>
	<li>Firefox</li>
	<li>Eclipse(partially)</li>
	<li>Pidgin(this uses gtk? Is gtk gpl?)<br></li>
	<li>Picasa</li>
	<li>e-texteditor</li>
	<li>console</li>
	<li>putty</li>
	<li>sqlfront</li>
	<li>winscp</li>
	<li>humanized enso</li>
	<li>launchy(c#)</li>
	<li>CSDiff<br></li>
</ol></content>
        </entry>,<entry>
            <title>Random Ideas</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/01/random-ideas">
            <updated>2007-10-01T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/01/random-ideas</li>
            <content type="text">
<p>This page was migrated from the old wiki:<br><br></p>
<b>no more files</b>
<p><br><br>Let's get rid of the file abstraction. In my opinion, the file is not something that is necessary to all applications and in a lot of cases it gets in our way. Take the example of eclipse, for example. Eclipse does a lot of things amazingly well. It loads the semantic model of programming objects into a form that it can reason with, and do cool things with them like dynamic compiling, refactoring, hints, etc. But why is eclipse slow sometimes? Because it always has to synchronize with the file system. Whenever you make major modifications to the filesystem: deleting, editing or moving a large amount of files, eclipse is going to take a long time adjusting to the change because it basically has to clear out all the knowledge it has about the code and reload from the new file structure. If eclipse didn't have to sync to the filesystem it would be much much faster, and its underlying programming model maybe simpler too. Basically, I think a simpler model would be to let the user only have access to what the user interfaces allows him to do: "immerse in the user interface". The filesystem is nothing but a legacy system. Something that came with the operating system. Such is the way it works with web based systems like Gmail. The user doesn't know which object are files, and he doesn't have a need to. The underlying system may be persisted using files, or more likely, using a relational database, but none of that really matters to the user. All he wants is an easy to use and efficent user interface that lets him do what he wants. Now, I am not saying not to use files. I am just saying not to use the file abstraction. In other words, you could be using files for persistance, but you don't need your user to know about it. In the web application realm, this really doesn't apply, since most of them use relational databases instead of files, but in the desktop realm, this may be a new way of looking at applications. - toby 11:30, 19 February 2006 (CST) <br><br></p>
<b>code generation? how about no-generation-needed code generation? </b>
<p><br><br>I am of the opinion that if you have to write code generators to write programs for you because the programming tasks you have to do are too tedius and repetitive, it's problemly because your programming language isn't expressive enough to allow you to refactor together the common aspects of your code. For example, Java made a big leap when it introduced generics. Let's take a real world example. I was asked to write a data access layer, full of DAO objects. Adhereing to the spring framework frame of mind, there were to be a DAO interface for each entity. An example of one of the DAOs would be: <br>public interface CustomerDao {<br>    <br>    public List findAll();<br><br>    public void save(Collection customers);<br><br>    public void save(Customer customer);<br>    <br>    public void delete(Collection customers);<br><br>    public void delete(Customer customer);<br>    <br>    public void deleteAll();<br>    <br>    public int count();<br>}<br><br>Now, every DAO interface looks very much like this one. The only difference is the entity type - in this case Customer. The same kind of situation applies to the DAO implementation as well as the unit tests. There were about 10 entity types in total. Yes, I could have just put Object in place of Customer, and I got myself generic DAOs, and even their implementations. But that wouldn't be nice, because this is an API, and I want the signatures exposed to be type-meaningful. True, I could have just typed them all out, but normally, even 3 is too many for me. So I wrote a very small and extremely simple template engine to generate these classes for me (later I found out about velocity and freemaker, maybe I'll use those next time). Were I allowed to use Java 5 syntax, however, I could have done better. I could have written: <br>public interface Dao<T> {<br>    <br>    public List findAll();<br><br>    public void save(Collection<T> objs);<br><br>    public void save(T obj);<br>    <br>    public void delete(Collection<T> objs);<br><br>    public void delete(T objs);<br>    <br>    public void deleteAll();<br>    <br>    public int count();<br>}<br><br>This looks much better and there needs only to be one file(instead of 10). I can do this for the implementation too! Although, yes, there is one thing you can't do - say what if you wanted the CustomerDao to be special and have one extra findXXX method? Then the only thing you can do in Java is add another interface that extends Dao<Customer>. But anyway, the point is, one cool language feature could reduce your redundant code ten-fold. I think the way of the future is, instead of there being lots of cool code generation tools, there should be much cooler languages that eliminate the need to do any code generation at all. - toby 15:47, 22 February 2006 (CST) <br><br>Another example, Ruby on Rails. The reason I was so impressed by rails isn't it's code generation - which it does - but rather, it's lack of code generation. In rails, you use ActiveRecord to map objects directly to database tables, but you don't see one line of generated code devoted to listing table columns, or the object properties that they are mapped to. The relationships are all infered during runtime. Now, if you were using hibernate, you'd probably have to update 4 to 5 artifacts everytime you need to add a column or change a column name, you may use code generation tools so that you only have to change one of the artifacts and then simply sync the rest, but all the same. In rails, you don't have to a thing, you just add the column to the physical database, and that's it. You can start access the new column in your code. Now that's is some cool non-code-generation. - toby 15:58, 22 February 2006 (CST) <br><br></p>
<b>Components across all layers </b>
<p><br><br>With all this hype about annotations - which is basically just Xdoclet that got integrated into the language - what is really the problem they are trying to solve? I think the reason this came about is because of the rise of the layered architecture in todays applications. Even before you start a project, it is broken down into the data layer, the business layer, and the presentation layer, and the layers have strict boundaries as to what code is allowed to reference what code. For example, usually, only the business layer can reference the data layer, not vice versa, and only the presentation layer can reference the business layer, not vice versa. But sometimes components need to exist across all layers, such as DOs or data objects. Most of the time, to reduce redundancy, the designers allow the presentation layer to reference the data objects too, which are in the data layer. The problem comes when the presentation layer needs to add more information about the data objects then is available from the data layer. Like, for example, which attributes of the DOs are needed to be displayed to the client, or how to display a particular attribute of a particular DO. Because of the peculiar nature of most requirements, there are usually many special cases like these that the presentation layer needs to handle. So what people do sometimes is create a configuration object or XML file in the presentation layer to create a mapping between each attribute in each DO and what needs to be done with it to display it. What is bad about this is that you now have 2 separate listings of the same DOs and the same attributes, once in the data layer and another once in the presentation layer, and if the business layer happens to have anything it needs to tag on, you would have 3 separate listings. So now, each time you add or modify a DO, you will also have to modify 2 other configuration files. In my opinion, things that are logically together, should stay physically together. Xdoclets is designed to handle these kind of senario for you. You would put all of these information into the DOs themselves, but the business and presentation information would be put inside comments in the code. Then with some tool, you read in the DO source files, parse out the extra information in the comments, and generate the configuration files you need in the business and presentation layers. The big trick(or hack) is that because the extra information is in comments, the DOs, which are in the data layer, do not have to make any real reference to the business or the presentation layers. When you really think about it, the reference is still made, it's just not made in a way that the compiler can pick up, and therefore "It's Okay" - i.e. it does not violate the strict boundaries of the layers. This is a hack. Yes, in my opinion, Xdoclet, annotations, these are all hacks. But they do highlight a weakness in the Java language and/or the architectural model we employ. As I said, things that are conceptually together should stay together, and that is what Xdoclet and annotations try to achieve, but can't we do it in a way that is not... a hack? What alternatives do we have? Well, one of them, of course, is to simply get rid of the boundaries. Isn't the DO a component that's used across all layers of the application? So the DOs should not be restricted to any single layer. Put all the presentation related information into the DOs themselves, not as annotations or Xdoclets but as real code, meta information, etc. But the downside of this is that your DOs may become harder to reuse because all of the extra stuff it depends on. Like for example, if you use the display tag library, you may want to map each DO to the decorator you want to use with it. If you put that into the DO, the next project you want to start may not even be a web project, which means your DOs are either unusable as is, or just has extra info that you don't care for. There's a cool feature in Ruby, which is guess is sort of old school in that I think it's originally a feature in C++. The feature: you can define things for the same class in different files, even if they are part of different libraries. This is cool because now we can define different aspects of the same DO in different layers(libraries) without interfering with other layers. But also, we've separated the info into separate files again =). What are we going to do? Well, one thought is to put these declarations into the same file, with markers indicating which declarations belong to which library(of course, we are now talking about a language that doesn't exist yet, as far as I know). But this is cludgey too, I mean, yes, you can filter out the parts that you don't need to use, but you still see them because they are in the same file. I think this is where the "no more files" idea will come in play(see previous entry). In an environment that doesn't let the file abstraction sip through, the extra information you don't need can be filtered for you before you see it, you don't really need to care about how the code is stored on disk, just worry about how it is organized to you. With that in mind, I think the BeanInfo stuff in Java would be better served if there were a language construct that allows you to define bean info side the same file, rather than in a separate file. - toby 18:10, 26 March 2006 (CST)</p></content>
        </entry>,<entry>
            <title>artists I love</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/10/01/artists-i-love">
            <updated>2007-10-01T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/10/01/artists-i-love</li>
            <content type="text">
<ul>
	<li>karrin allyson </li>
	<li>patricia barber </li>
	<li>deanna witkowski </li>
	<li>dena derose </li>
	<li>brad mehldau </li>
	<li>richard tabnik </li>
	<li>connie crothers </li>
	<li>keith jarrett </li>
	<li>mulgrew miller </li>
	<li>Ahmad Jamal </li>
	<li>Pat Martino </li>
	<li>Chick Corea </li>
	<li>geoff keezer </li>
	<li>kelly broadway </li>
	<li>jimmy smith </li>
	<li>lee konitz </li>
	<li>rene marie </li>
	<li>charles mingus </li>
	<li>billie holiday </li>
	<li>johnny hartman</li>
	<li>nancy wilson<br></li>
	<li>sarah vaughn </li>
	<li>bill evans </li>
	<li>lennie tristano </li>
	<li>warne marsh </li>
	<li>sal mosca </li>
	<li>Gerry Mulligan </li>
	<li>Thelonious Monk </li>
	<li>Chet Baker </li>
	<li>Wes Montgomery </li>
	<li>art tatum </li>
	<li>johan strauss </li>
	<li>paul hindemith </li>
	<li>johannes brahms </li>
	<li>Django Reinhardt </li>
	<li>Tadd Dameron </li>
	<li>Charlie Byrd </li>
	<li>Eric Dolphy </li>
	<li>Bill Charlap </li>
	<li>Barney Kessel </li>
	<li>jacky terresan </li>
	<li>mike ledon </li>
	<li>benny green </li>
	<li>johnny hodges </li>
	<li>coleman hawkins </li>
	<li>lionel hampton </li>
	<li>slam steward </li>
	<li>scott lefaro </li>
	<li>red mitchel </li>
	<li>lars gullin </li>
	<li>woody allen </li>
	<li>david fincher </li>
	<li>mary lou williams </li>
	<li>jimmy lyons </li>
	<li>steve lacy </li>
	<li>johnny costa </li>
	<li>tete montoliu </li>
	<li>milt jackson </li>
	<li>les double six </li>
	<li>frank lo </li>
	<li>benny golson </li>
	<li>fred hershe</li>
	<li>bennie wallace<br></li>
</ul></content>
        </entry>,<entry>
            <title>Adventures in Testing with Mocks</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/09/28/adventures-in-testing-with">
            <updated>2007-09-28T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/09/28/adventures-in-testing-with</li>
            <content type="text">
<p>I have recently gotten the mock testing bug. The biggest driving force to do this is that I find some things just too hard to test: in two cases I have to interact with the filesystem, and in another case I have to deal with third party Javascript UIs. I am trying it out in 2 different projects right now. So far I have played with Rspec with ruby, jsMock with Javascript and jMock with Java. <br><br></p>
<b>Observation #1</b>
<p><br><br>Rspec is the most enjoyable of the three, and it has one convinence feature that neither of the other 2 has: you can mock individual methods of a objects while still leaving the other methods intact. So, for example:<br><br>class MyObject<br>    def do_this<br>        ...<br>       do_that<br>    end<br><br>    def do_that<br>        ...<br>    end<br>end<br><br>What you can do in Rspec is mock out the method do_that, but still leave do_this intact. Then what you do is call do_this and verify that the mocked out do_that was called. Below is how it's done:<br><br>my_object.should_receive(:do_that)<br>my_object.do_this<br><br>This is impossible with jMock, as far as I can tell, once you mock out an object, all of its methods are mocked out, you pretty much have to create another object to interact with the first object in order to do any kind of mock testing. With jsMock in Javascript, this is not the default behavior, but you can still do it very simply:<br><br>var control = new MockControl()<br>var mock = control.createMock(MyObject)<br>mock.expects().doThis().andStub(MyObject.prototype.doThis)<br>mock.expects().doThat()<br>control.verify()<br><br>The magic happens on line 3 which replaces the doThis() method of the mock with the real doThis() method coming from MyObject's prototype(If you don't know that a prototype is, watch <a href="http://futuretoby.dyndns.org/wiki/Douglas_Crockford_on_Javascript" mce_href="http://futuretoby.dyndns.org/wiki/Douglas_Crockford_on_Javascript">Douglas Crockford's videos</a>).<br><br></p>
<b>Observation #2<br><br></b>
<p>Mockist testing in Java really sucks compared to Ruby, this is because you have to create a interface for everything single method that you want to mock independently. This causes interface-iitis(as promoted by the spring people and practiced my the eclipse people), which I really detest.<br><br></p>
<b>Lessons Learned for Now<br><br></b>
<p>There are things that are not that easy to test still with mocks. This is especially true for Java. What I did with Java was extract 3 or 4 interfaces just so that I could test them, but there are methods that I wish to against each other in the same class independently but just don't want to extract yet another interface, for that I really don't know what to do, maybe I'll just have to do that as an integration test.<br><br>Testing with rspec is a lot better. There are some things that I am still not sure how to do though, such as mocking a method and stubbing a return value at the same time. Javascript is not as nice. I had to refactor my Javascript to be more OO in order to test them: a procedural programming style does not yield well to mock testing.<br><br>I also reread Martin Fowler's essay: <a href="http://martinfowler.com/articles/mocksArentStubs.html" mce_href="http://martinfowler.com/articles/mocksArentStubs.html">Stubs Ain't Mocks</a> which gave me a lot of insight and reaffirmed some of the experiences I was having(the first read was quite confusing not having any hands on experience). I think at the end there's a balance somewhere about which approach to take(classic or mockist), and it depends on the situation.<br><br>More updates to come. I have just gotten started with this, so I am sure I'll learn more as I go.<br><br></p></content>
        </entry>,<entry>
            <title>Stop Complaining for 21 straight days</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/09/24/stop-complaining-for-21">
            <updated>2007-09-24T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/09/24/stop-complaining-for-21</li>
            <content type="text">
<p>Tim Ferriss informs me of the following lifestyle experiment:<br><br><i>And it was. The author was Will Bowen, a Kansas City minister who had recognized—as I have in a previous post—that word choice determines thought choice, which determines emotions and actions. It’s not enough to just decide you’ll stop using certain words, though. It requires conditioning.<br><br>Will designed a solution in the form of a simple purple bracelet, which he offered to his congregation with a challenge: go 21 days without complaining. Each time one of them complained, they had to switch the bracelet to their other wrist and start again from day 0. It was simple but effective metacognitive awareness training.<br><br></i>Please read Tim's entire post <a href="http://www.fourhourworkweek.com/blog/2007/09/18/real-mind-control-the-21-day-no-complaint-experiment/#more-139" mce_href="http://www.fourhourworkweek.com/blog/2007/09/18/real-mind-control-the-21-day-no-complaint-experiment/#more-139">here</a>. Very interesting, and definitely worth a try I think, no matter who you are. I think that the basic premise is this: complaining doesn't help, and only causes grief and anger, and so there's no place for it. Replace it with actions or suggestion, and the outcome will be better. Would the world be a better place if everyone stopped complaining? I'd believe it.<br></p></content>
        </entry>,<entry>
            <title>Morale Driven Development</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/09/20/morale-driven-development">
            <updated>2007-09-20T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/09/20/morale-driven-development</li>
            <content type="text">
<p>The happier you are while working on a project, the more productive you are likely to be, the more likely that you are going to keep the project going, and the more likely that the project is going to go well. This is the principle behind what I am going to call Morale Driven Development(MDD). In MDD, you always work on short term goals - much like most agile processes, but the short term goals you choose are based on what - if accomplished - will make you the most happy, or more specifically - will make you feel good about the project the most.<br><br></p>
<b>Requirements</b>
<p><br>As I have mentioned in a previous blog post, the projects that I most
like working on are the ones in which I create something for myself. I have only applied MDD to projects of this type. It's not to say that MDD can't be applied to other settings, but just that I haven't tried it. Having said that, being the boss of the project is a definite requirement since you need to be able to prioritize tasks as you see fit.<br><br></p>
<b>Prioritizing Tasks</b>
<p><br>Given a list of tasks, there are many ways to prioritze them. In my senario, I will reduce tasks to 3 categories. A task can be either a <i>bug</i>, an <i>enhancement</i>, or a</p>
<b> </b>
<p><i>development task</i>.  Some people like to do the hardest tasks first, others like to do the easiest first, others just don't prioritize at all, they just work from the top of the list, treating each task as equal. Most people would probably prioritize based on what is the most important. But there are different opinions about what the most important thing is. For example, some think that having a unified framework in place first is the most important, others think that looking good in demos is the most important. With MDD, the most important thing is your own happiness. You prioritize the tasks by how much impact each would make to your happiness. <br><br>For <i>bugs</i>, this means picking the most annoying bugs. If you are developing a product for yourself, and you have been using the product yourself regularly, then you know what the annoying bugs are. Getting rid of these bugs will definitely make you happier the next time you use it.<br><br>For <i>enhancements</i>, select features that you are going to make use of or see the results of most immediately and most frequently, or to put it another way, features that make a visible impact. Features that are not frequently used or are only applicable to corner cases should be low on your list. <br><br><i>Development tasks</i> can include: refactoring your code, integrating a new development tool or framework, writing tests, etc., basically anything dealing with development that is not directly tied to a bug fix or a feature. For these you want to select the ones that would improve your development experience the most, because being happy developing the product is just as important as being happy using the product. For example, if you have been falling behind in writting tests, then writting the tests could improve your development experience because they help you to feel at ease about making big changes to the code by acting as a safety net. Or if the code quality is worsening, refactoring the code to be more DRY would make both reading the code and making enhancements easier.  Having good development tools is very important for making you feel good as well. <br><br>If you need to compare task in different categories, you just have to ask yourself, which task(out of 2), if accomplished, would make me happier? And that's it. At the end, tasks are prioritized, and you start working from the top. You can of course reorder the task list as conditions(your feelings) change.<br><br></p>
<b>Responsiveness => Happiness<br></b>
<p>I have found that in general, a responsive system makes you happy. Why? My theory is that responsiveness makes the user feel more in control, and being in control makes people happy. This principle applies to both the user experience and the developer experience.<br><br>Making your UI responsive makes a big difference in your user experience, so it should be high in your priority list. For example, a good trick to use is to displaying animation when you are waiting on computation or network communication to finish, because visual feedback conveys to the user that the system is alive eventhough it hasn't finished its job. In general, the most important principle to keep in mind is to always give immediate visual feedback to the user after he takes any action.<br><br>In case of development, for example, ruby on rails makes me happy because codes changes take effect immediately when you hit save, there's no compile or deploy step the feedback cycle is fast. Working with GWT makes me depressed because after every code change, I have to restart the hosted browser, which could take in some case an entire minute to start up, or alternatively compile the Java code into Javascript, which could take even longer(in some cases half an hour!).<br><br></p>
<b>Case Study</b>
<p><br>As a case study, I will use my work on this wiki/blog as an example. I worked long and hard to get the wiki to a working stage, but the code quality wasn't good and I hadn't written any tests. It was kinda usable but there were bugs, some of which were hard to fix, but I was reluctant to make big changes to it to fix them because I didn't have any tests. Also, the wiki looked quite hideous at the time, and I hadn't bothered to do anything about it because I thought it had a somewhat low priority - presentation should be separate from design, after all, right? But as time went on, the hideousness of the site nagged me more, and I felt worse and worse about the project. At one point I considered abandoning it and just use an open source blog tool like wordpress. But then one day I decided to applied the principle: do the thing that makes me feel good the most. I re-did the layout and fonts of the site, used just a little bit of graphics, it now looks much better than before, and it really made me feel better about this project, which fueled me to keep making improvements to it. Because of the improvements in the look and feel of the site, I made posts a lot more frequently, which also drove development on it. I have written tests for the project now and had made lots of bug fixes and enhancements since then, and feel good about the progress of the project. I would say that this was a case when MDD really made a dramatic difference in the outcome.<br></p></content>
        </entry>,<entry>
            <title>Presentations</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/09/19/presentations">
            <updated>2007-09-19T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/09/19/presentations</li>
            <content type="text">
<p>We talked about presentations at work a couple of times and today google docs released their presentation tool. This is a great development as I have been doing some presentations outside work and since I don't have MS office and I don't like Open Office, I have been using S5, and now Opera Show since I've been trying out Opera. With S5 or Opera show you have to write your presentation in XML, which is okay, but not particularly nice. The google presentation tool will make this go away(for me anyway), so I can't wait to do my next presentation so I can try it out.<br><br>Also, someone at work mentioned that someone found the average powerpoint-bullet-point-style presentation to be not so good for learning retention. That's not to say Pointpoint-the software is bad, it's just how people have been using it. A new presentation style seems to be gaining adoption lately, namely the - <a href="http://presentationzen.blogs.com/presentationzen/2005/09/living_large_ta.html" mce_href="http://presentationzen.blogs.com/presentationzen/2005/09/living_large_ta.html">Takahashi style</a>. Some have mentioned <a href="http://presentationzen.blogs.com/presentationzen/2005/10/the_lessig_meth.html" mce_href="http://presentationzen.blogs.com/presentationzen/2005/10/the_lessig_meth.html">Larry Lessig</a> have also been doing this for a while now. In a Takahashi style presentation, there are no bullet points, only headlines, graphics or animations. Actually the Steve Jobs keynotes are a little like that too. See this <a href="http://www.rubycolor.org/takahashi/takahashi/img0.html" mce_href="http://www.rubycolor.org/takahashi/takahashi/img0.html">presentation</a> by Takahashi himself as an example. Another great presentation I have stumbled across is <a href="http://mir.aculo.us/stuff/AdventuresInJavaScriptTesting.pdf" mce_href="http://mir.aculo.us/stuff/AdventuresInJavaScriptTesting.pdf">this one about Javascript testing</a>. It also employs the same style, using only big headlines and images(some comic-style headlines thrown in there too), this one had more content in the slides themselves than most Takahashi style presentation, but I think it's also effective, maybe even more so. Also, check out <a href="http://identity20.com/media/OSCON2005/">Dick Hardt's presentation</a>.<br><br>I am psyched about this and I will definitely give this a try the next time I give a presentation.<br></p></content>
        </entry>,<entry>
            <title>Cleaner Desktop and moving to Opera</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/09/07/cleaner-desktop-and-moving-to">
            <updated>2007-09-07T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/09/07/cleaner-desktop-and-moving-to</li>
            <content type="text">
<p>I spent some time today cleaning out my desktop(computer desktop, that is), removing some unused programs, getting a dark looking theme for some frequently used web sites, and switching to Opera.<br><br></p>
<h3>Cleaning out my desktop<br></h3>
<p>I have removed all desktop icons - that's right, ALL, including the recycle bin(for context, I use windows XP). The bit with the recycle bin required a registry hack, as did removing the bluetooth icon. With my completely dark desktop, it looks so peaceful. Oh, and I also set the taskbar to auto-hide to maximize this effect.<br><br></p>
<h3>Removed Unused Programs<br></h3>
<p>Did an uninstall on many programs that I don't use anymore. This frees a bit of disk space but more importantly de-clutters the start menu.<br><br></p>
<h3>Getting some dark themes<br></h3>
<p>Seeing how nice the dark desktop is, I wanted to go farther and get some more "darkness" into my routine. The Obvious places to start were google reader and gmail. I started investigating using greasemonkey to re-style these pages. But it turned out there was an easier way for firefox with the <a href="https://addons.mozilla.org/firefox/addon/2108" mce_href="https://addons.mozilla.org/firefox/addon/2108">Stylish</a> plugin, and people have already written themes for it. I picked up a couple and got the dark effects I wanted for those 2 pages.<br><br></p>
<b>Switching to Opera</b>
<p><br>Next, I decided to give Opera another try. Opera is becoming more and more of a contender to Firefox in terms of functionality, especially now that Firefox is constantly eating up most of my cpu. Opera renders noticably faster than firefox, it runs google reader and gmail just fine, I think it still does not run google docs, I haven't tried just now. There is a greasemonkey counterpart for Opera which the themes I found firefox also works for, this is great. The only hiccup now is that this wiki does not seem to work with Opera. Being that I wrote it myself though, I should be able to fix it. I am not done with this evaluation of Opera, but it looks good so far. Btw, Opera also has themes you can download.<br><br><i>Update: I didn't follow up with this because Opera doesn't work with my Wiki, or is it the other way around?</i><br></p></content>
        </entry>,<entry>
            <title>New iPod Touch and Wireless iTunes Store</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/09/05/new-ipod-touch-and-wireless">
            <updated>2007-09-05T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/09/05/new-ipod-touch-and-wireless</li>
            <content type="text">
<p>The iPhone-like iPod is out today. But even more importantly, you can now buy songs and download them directly to your ipod if you have a wireless internet connection. They are calling it the Wireless iTunes Store. I wonder if you can download podcasts the same way? That way you can sample them a lot easier. This is a hugh feature that lots of people's been wanting, and it's great that they got it out there. </p></content>
        </entry>,<entry>
            <title>Hackety Hack</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/09/05/hackety-hack">
            <updated>2007-09-05T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/09/05/hackety-hack</li>
            <content type="text">
<b><i>Why's Lucky Stiff</i></b>
<p>(one of the most well known and definitely the most weird personality in the ruby community) developed this new educational tool called <a href="http://hacketyhack.net/" mce_href="http://hacketyhack.net/">Hackety Hack</a>(I learn about this from the Atlanta Ruby User Group meeting I went to yesterday). It's for kids age 13 and up to learn how it program. I love it, the interface is cool, you can do cool thing with very few lines of code, and 7 lesson come preloaded with it. What a fun way to learn. It's like a much simpler Squeak, or a nicer JES(explained below). I wondered if my professor Mark Guzdial would be interested, he had his students develop a similar environment for an Intro to CS class called JES(I worked on this), so I wrote him an email. Waiting to hear back. <br><br>Whereas JES was very media centric(you can easily read and manipulate pictures, audio files, movies, etc.), Hackety Hack is web centric, you can easily download files, web pages, and even youtube videos from the web. This has got to keep the kids excited, right?<br><br>If you are new to programming and would like to learn, give it a try.<br><br>Update: Mark replied and sent me this <a href="http://coweb.cc.gatech.edu/mediaComp-teach">link</a> to the Media Computation course.<br></p></content>
        </entry>,<entry>
            <title>Javascript Gotcha</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/09/04/javascript-gotcha">
            <updated>2007-09-04T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/09/04/javascript-gotcha</li>
            <content type="text">
<p><strong>offsetTop</strong><br>element.offsetTop does different things in gecko than IE, best bet is to use the function listed here: <a href="http://www.quirksmode.org/js/findpos.html">http://www.quirksmode.org/js/findpos.html</a>, the code: <br><br><pre><code>function findPos(obj) {
</code></pre><pre><code>  var curleft = curtop = 0;
</code></pre><pre><code>  if (obj.offsetParent) {
</code></pre><pre><code>    curleft = obj.offsetLeft
</code></pre><pre><code>    curtop = obj.offsetTop
</code></pre><pre><code>    while (obj = obj.offsetParent) {
</code></pre><pre><code>      curleft += obj.offsetLeft
</code></pre><pre><code>      curtop += obj.offsetTop
</code></pre><pre><code>    }
</code></pre><pre><code>  }
</code></pre><pre><code>  return [curleft,curtop];
</code></pre><pre><code>}
</code></pre></p></content>
        </entry>,<entry>
            <title>Hanselman's Tool List</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/08/28/hanselman's-tool-list">
            <updated>2007-08-28T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/08/28/hanselman's-tool-list</li>
            <content type="text">
<p>Scott Hanselman released his latest Tools List:<br><a href="http://www.hanselman.com/tools">http://www.hanselman.com/tools</a><br>He also talks about it on his podcast also, which I listen to regularly.</p></content>
        </entry>,<entry>
            <title>Why Java Is A Different Beast</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/08/08/why-java-is-a-different-beast">
            <updated>2007-08-08T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/08/08/why-java-is-a-different-beast</li>
            <content type="text">
<p>Cote made the following blog post: <a href="http://www.redmonk.com/cote/2007/07/25/javas-fear-of-commitment/">http://www.redmonk.com/cote/2007/07/25/javas-fear-of-commitment/</a>. And here's my thoughts on it:<br>Great post Cote. This post is not so much about Java the language, but about Java the community and the Java philosophy/mindset. I wholeheartedly agree with Cote's point, it's something that I have felt as well, and I think he articulated it well. <br><br>Java gurus tend to get interface-happy: look at the Springframework and Eclipse sourcecode for instance: where almost every class has a corresponding interface. Do all those classes really need several different implementations? I doubt it. <br>They also tend to get subproject-happy: applications must have layers and these layers must be clearly separated; The "presentation layer" must not touch "data objects" directly, we need "domain models"; or, Let's have a subproject for each layer of the application to reduce coupling, parts of it can also be reused in other projects. Does the reuse really happen down the road? I won't say never, but I think rarely.<br>In general terms, the Java Philosophy is this: keep modules isolated, so that they can be resistant to change. Because you never know when you are going to need to swap out your UI layer, business layer, data access layer, or your persistence engine, or your database, or your JMS provider, or your J2EE container, or your OS, etc, etc. <br>I am not dissing this philosophy, it is very useful to be able to swap out some of these components, but others, not so much. There's a balance somewhere. I think that in a lot of cases simply refactoring code is enough to cope with change. It really isn't hard if you keep your code DRY, and have good test coverage. Java folks in general are just too in love with the idea that their finished code should work with every imaginable situation that can arise to do it this way. </p></content>
        </entry>,<entry>
            <title>Demo at Atlanta Python Users Group</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/07/28/demo-at-atlanta-python-users">
            <updated>2007-07-28T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/07/28/demo-at-atlanta-python-users</li>
            <content type="text">
<p>I am going to speak at the Atlanta Python Users Group about TDD(Test driven programming). I am going to do a live coding demo. It's 20 minute demo. Hope it goes well.<br><br>Update: I did the presentation last night and it went quite well. I got the sense that most people were new to what I was presenting but were interested and learned quite a lot.<br></p></content>
        </entry>,<entry>
            <title>QuickTime Java Woes</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/07/25/quicktime-java-woes">
            <updated>2007-07-25T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/07/25/quicktime-java-woes</li>
            <content type="text">
<p>I coded my TextSync application using QuickTime for Java a while ago, and I found that about a week or so ago that it ceased to work!!! Why? I asked. I finally had some time to fix the problem today. After a lot of digging and experimentation, it turns out that the newest version of QuickTime removed the QTJava.dll that is required for the thing to work. Why would Apple do that??? These people are mean!!! Luckily, I was able to revert to an older version of quicktime from <a href="http://www.oldversion.com">oldversion.com</a> which fixed everything. Ohhh..., that Steve Jobs...</p></content>
        </entry>,<entry>
            <title>Ruby is clay Java is Marble</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/07/13/ruby-is-clay-java-is-marble">
            <updated>2007-07-13T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/07/13/ruby-is-clay-java-is-marble</li>
            <content type="text">
<p>Ola Bini quote: Ruby is like clay, it can be formed into whatever you want, and Java is marble.<br><br><a href="http://www.akitaonrails.com/pages/olabini">http://www.akitaonrails.com/pages/olabini</a></p></content>
        </entry>,<entry>
            <title>Jyaml 1.0 final released</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/06/12/jyaml-1.0-final-released">
            <updated>2007-06-12T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/06/12/jyaml-1.0-final-released</li>
            <content type="text">
<p>After almost a year of inactivity. I have updated the Jyaml project on sourceforge now. To my surprise, many people reported bugs/feature requests/patchs on the sourceforge project site, and I have only recently took notice of them and went through each one and incorporate it in to the code. Going through it was a bit tedious, but not as bad as I thought. I made Jyaml slightly more robust and I add the YAML4DbUnit, and also soon to add YAML4Spring as well. Here's the link to the project: <a href="http://jyaml.sourceforge.net/">http://jyaml.sourceforge.net/</a></p></content>
        </entry>,<entry>
            <title>Free Culture 4-1</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/06/01/free-culture-4-1">
            <updated>2007-06-01T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/06/01/free-culture-4-1</li>
            <content type="text">
<p>I have finished reading Larry Lessig's Free Culture. Towards the end of the book, Lessig described in detail the battles he faced in court trying to overturn the Sonny Bono Act(which extended the copyright terms even longer), and he's mistake which may have costed him the victory. It's a very sad truth, for had things turned out differently, we would have had much more literature in the public domain for the artists of today to freely study and build their works upon. For example, we would have already had all of Bird's recordings in the public domain(since 2005, 50 after his death). This would include all of his recording(I could publish them all on a website somewhere for example, or create films with his music in them, or create my renditions of his musical compositions). Instead, the copyright term has now been extended another 20 years, and of course, what is to say they wouldn't extend it the next time the limit comes around?<br><br>Some thoughts about Lessig's "mistake". I think that indeed it was a wrong decision on his part. He decided to make his arguments based on some technical logic related to the constitution and prior court decisions rather than the real issue, i.e. -- why is extending the copyright indefinitely a bad thing. He needs to take on the salesman's approach more, and trim down his arguments down to 3 main points or less(3 is the typical number of points/features in any Apple presentation on any of it's products). The big picture, as I see it, is that an unlimited copyright term means that 1) artists will have less freedom because anything they create has high potential to infringe on other works under a copyright, and 2) it give the large media publisher -- who control most of the artists in the world -- even more power, and thus restricting the artists themselves even more. Both of these lead to the same thing, artists lossing freedom: freedom of speech, freedom of expression(point to the first amendment already!). Lessig really needed to make this point to the judges above anything else, IMHO. I think that Lessig is now wiser for this mistake, but he still tends to go in logic circles too much for my taste. I think that he needs to change his mindset into a more skeptical one. Very few people can or <em>care to</em> reason and think logically in the manner that Lessig does(he tends to go back and forth, check and recheck his arguments to make sure he didn't make any mistakes along the way of his reasoning), the more he does this, the more people lose interest in what he is saying. Logical arguments are fine, but they have to be short and to the point. He needs to keep his focus on the big picture and not get lost in the details.<br><br>What I like most about this book were the stories. The store of Cauchy vs RCA and the FM radio; how copyright came to be in England;  the Sonny Bono Act; the Sony and the VCR; CD's, etc. I how have a much better sense of the history behind copyrights and the understanding that government is supposed to balance an artist's incentive to create with the creative freedom and knowledge of the public, and that intellectual property is <em><strong>not at all </strong></em>the same as regular property.</p></content>
        </entry>,<entry>
            <title>Free Culture</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/06/01/free-culture">
            <updated>2007-06-01T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/06/01/free-culture</li>
            <content type="text">
<p>I am reading <a href="http://www.free-culture.cc/">"Free Culture" by Larry Lessig</a>(it's to download free online), and I am learning a lot about the history of copyrights and how it came to be, and what were the original goals of copyrights. Now that I am more interested in content on the net, and possibly creating content on the net, IP issues will be important to understand so I can steer clear of trouble. I am also hopeful that what Larry is fighting for will come to fruitation and that the world will be a freer place for ideas, on the net, well, as well as in other places. </p></content>
        </entry>,<entry>
            <title>Dreaming in Code</title>
            <author>Toby Ho</author>
            <link href="http://tobyho.com/2007/06/01/dreaming-in-code">
            <updated>2007-06-01T04:00:00.000Z</updated>
            <id>http://tobyho.com/2007/06/01/dreaming-in-code</li>
            <content type="text">
<p>I've been reading <em>Dreaming in Code</em> by Scott Rosenberg. This book is supposedly the new <em><strong>must read</strong></em> for software programmers. I am half way through it, but can't say I particularly like the book much so far. It's about the Chandler project, which aimed to replace Outlook in the desktop world, and ended up being an utter failure. To my surprise, Andy Hertzfield was in that project. Basically, Kapor(the founder and funder of the project) was way to ambitious and therefore created a situation where deciding on the spec was near impossible and therefore actually coding happened extremely slowly. I think that this is something that the agile people have learned to avoid though, so I don't really feel that I have learned anything new. Basically it feels like that I have already learned the lesson of this book. But you never know, I'll finish the book first.<br><br>I do have some thought about what to do and what to avoid when you tackle a programming project, so let me share them here:<br></p>
<ol>
	<li>Eat your own dog food - I think this is probably the most important rule of all. But it is especially when you first consider persuing a project. Is this something that <em><strong>you</strong></em> will use and will enjoy using? Don't work on a project the product of which you will not use, because 1) you will not enjoy working on it and 2)it will not be good(because of the first reason and the fact that you will not have a fast feedback loop to make sure it's high quality).</li>
	<li>Be agile - being agile is important because 1) you want to get things going quickly so that you can "Eat your own dog food" asap 2) you want a very quick feed back loop from the user (you) back to the programmer(you again). What this means is that you don't want to design everything up front before you start coding. You want to code just enough so you can start using it, then come up with a list of things that are wrong with it, prioritize the list, and then go redesign/fix them, because a lot of ideas don't come up until you have had the experience of using something, and it should feed directly back into the design.</li>
	<li>Don't aim too high - this is related to being agile also, but basically, start small, and don't try to solve too many problems at once, because it won't work and you will get bogged down on failing to put the big picture together and get depressed and lose interest for the project.<br></li>
</ol></content>
        </entry>

</feed>
    