Just enough Markdown

This is a quick tutorial on Markdown. It is meant to cover the 80% most commonly used scenarios. This guide is based on my experience. This takes care of most of my markup needs. Hopefully it will take care of yours too.

This page is heavily based on the wikipedia's markdown article. If you want to experiment with the syntax and see feedback right away, please visit Jon Combe’s markdown online editor. Using his editor and reading any guide will lead to the fastest learning.

Reference pages:
Wikipedia’s markdown page
Markdown syntax

I need a linebreak

Use two spaces at the end of a line

I need headings

Uses hashes #

 # What I did this summer
 ## Staring at the ocean

I need lists

Use stars * for undordered lists.
Nest them with a space.

 * Groceries
  * Milk
  * Bread
  * National Review

Use numbers for ordered lists

 * Why my mother-in-law is zany
 1. She loves rape stories
 2. She believes TV hype
 3. She is into the English royal family, yet is an anti-monarchist

I need italics and bold text

For italics, use * or _ around the word

  "Hello, *sweetheart*."
  "Umm, I have to go _now_."

For bold, use double ** or __ around the word

   He was **lying**. 
   He met the __president of the United States__.

Use the parens-braket format [link text here](url_here)
[Sexy stuff that floats your boat on youtube!](http://youtu.be/b1WWpKEPdT4)

I need an image

Use a modified link markup of ![alternate text](url to image)
![Honey Boo Boo](awesome_pics/honeybb.jpeg)

I need a blockquote

Use a > in front of the quote
> One word: finance! The future is all about finance! If I had to do it again, I would latch on it, son.

I need to add code

Use 4 spaces indent before the text with an empty line above it

Video Review: Building a light theramin

A person in twitter brought to my attention this great series of arduino videos by one of the co-creators of Arduino, Massimo Banzi.

I decided to use U.S.'s Thanksgiving day to build circuits with my kids. So after looking at the list of available videos, I decided to build the theremin one.


Massimo is one of the most charming tutorial hosts that I have seen. His explanations of how to build the circuit are clear. I watched and built along with my 7-year-old. If you have the parts, then you should be able to build something within 30 minutes. It took me longer since I had to forage in my junk drawer for some parts. I also had my son build the circuit, so that slowed things down a bit.

He loved the whole experience. We first got the speakers out from some JetBlue earphones that I got at some point. He enjoyed seeing the speakers coming out of the case. Then he played a little bit with the cases. He was very intent and focused while we were putting the circuit together, but he lost a bit of interest when I was writing the code, which I expected. He did love to change the noise that was coming from the speaker. For some reason it sounded like R2D2. This made my son jump with happiness.

There was a minor glitch with the code describing the variables not matching Massimo's description of them, but his description was enough to include the right values in it. It would be nice to have the circuit diagram and code, even if it were just the image, but Massimo explained in the youtube comments that that information comes in RS's Arduino Started Kit. RS created these videos to support their kit, and were kind enough to share them with the world.

Still, if you are starting with the arduino or you want to help someone else to get started, these videos are a great resource to get cool project quickly done and to feed your imagination for things to do later.

Vagrant, Ruby, Cygwin: Script that writes an easy vagrant ssh file to use in Windows

The script will create a bash script that will ease using ssh to log into a Vagrant box in Windows.
The dependencies for this script are: Cygwin, cygwin's open-ssh, ruby 1.9.3, Vagrant, and Windows

The cheerful, but longer story

When you install Vagrant in a unix-based machine, and that is linux and macs, Vagrant automatically gives you the command "vagrant ssh" to log into your machine. It is so beautiful! Unfortunately Windows doesn't ship with an ssh client that the maintainers of Vagrant can use to create that automatically configured script. So their solution is not to create that script at all. Instead they give you some nice instructions on what to you.

I use cygwin as my command line shell when working on windows. That means I am using cygwin all the time. So I installed open-ssh via cygwin. So everything should be fine, right? No. It ends up being a huge drag to write the command line to get vagrant working. After doing searches twice to get ssh and vagrant working, and I decided that instead I would write a little script that would parse the vagrant output with the instructions for logging into vagrant.

To run it this script, you go to the directory name, start the vagrant box, and run the script. I called it easy_vagrant_ssh.

cd <vagrant directory name>
vagrant up
ruby easy_vagrant_ssh

require 'open3'
# This is where the magic happens!!!
# In other words, it took me a while to figure out what I was doing here
# right before I wrote this blog post.
# I am executing the shell command "vagrant ssh" and returning the output.
def get_input()
  command = "vagrant ssh"
  stdin, stdout, stderr = Open3.popen3 command
  result = stderr.readlines
# This method parses the  output that vagrant gives you with instructions on 
# how to ssh into the vagrant box
def gather_values(input)
  result = {}
  input.each do |line|
     words = line.split ": "
     if words.first =~ /^Host/
       result[:host] = words[1].chomp
     if words.first =~ /^Port/
       result[:port] = words[1].chomp
     if words.first =~ /^Username/
       result[:username] = words[1].chomp
     if words.first =~ /^Private key/
       result[:private_key] = words[1].chomp
def create_command(values)
  result = "ssh #{values[:username]}@#{values[:host]} -p #{values[:port]} -i #{values[:private_key]}"
def create_file(command)
  file = File.open "vagrant_ssh", "w"
  file << command
def run_script()
  input = get_input
  values = gather_values input
  create_file create_command(values)

Now you only have to run the bash file that it is created, which is called "vagrant_ssh". Not as nice as typing "vagrant ssh" but close enough.

Eclipse PDT: Creating project at existing location (from existing source) doesn't work

You probably need to move code in an existing folder to Eclipse. This is the work around for starting to work with existing php code in Eclipse PDT in Windows 7. Don't follow these steps if you have your code in a VCS; there are other steps for dealing with that scenario, and those steps are not covered here.

Moving existing source code into a new project in Eclipse

1. Set the workspace one directory above where your existing code lives.
2. Create a new PHP project via File->New->PHP project
3. Create a new project with a different name from your current folder. Make sure to select Create new project in workspace under Contents. Don't pick Create project from existing location. It doesn't work
4. Once your project is created, go to File->Import. Select General-> File System.
5. At the From directory field, pick the folder where your current code exists. Then click Select All. Click on Finish

The long story

I want to like eclipse. I really do. I like the idea of it. I like it how it is open source and how anyone can create a new distribution for different languages.

Yet Eclipse makes it so hard to be loved. It turns what should be a thoughtless task into a research project.

At least I believe that setting up a new project and importing existing files into it should be easy. And when UIs don't actually work as they claim they should, the experience of using eclipse is a mixture of confusion and frustration.

So look at this UI for creating a new project. The UI is clearly telling the user that one should be able to create a project from existing source files. Excellent! That is what I want!


However, when you try it, it won't work. It will give you an error that says, " Cannot create project." Below is a warning that says, "The specified external location already exists".

Why doesn't it work? Search the internet, and maybe you will be looking to find this page:


Where several people describe how the UI does work in linux for java, or that it is only meant for folders under the web server root. It is unclear what is going on. The bottom line is that it just doesn't work. It wasn't working in 2006, and it isn't working now. The thread has several workarounds, but the only one that worked with the current version is the one that I shared at the beginning of this entry.

Drupal: Hiding CCK fields with fieldgroups in hook_form_alter

So the task I had was to conditionally hide two fields in drupal CCK custom content type. When the record had one of three values in a select field, it should show the upload file fields. Otherwise it should hide it.

This is pretty straightforward in a regular module. One makes the changes in hook_form_alter. To hide, we would unset the fields.

function random_module_form_alter(&$form, $form_state, $form_id) {
    // make your changes here: change values, set defaults, hide fields
    // the easy life!

This won't work if one is using CCK. The reason for that, as webchick explains in her blog entry, is that CCK fields are not present at hook_form_alter. She then presents the right approach, which is to use form API #after_build.

* Implementation of hook_form_alter().
function example_form_alter(&$form, $form_state, $form_id) {
  // Check for a particular content type's node form.
  if ($form_id == 'example_node_form') {
    // Add an after_build function to process when everything's complete.
    $form['#after_build'][] = 'example_after_build';
* Modify CCK form elements on the example node form.
function example_after_build($form, &$form_state) {
  // TODO: Stuff!
  return $form;

This is the basic code structure for solving this problem. From this point, it should have been easy, right? Wrong. I ran into two problems: getting the values from the form and reaching the right form field to turn off.

The most natural solution for getting a value and setting a field to hide is to just reach for that field in the form

$value = $form["height"][0]["value"];

However, when dealing with CCK fields, the first one won't work, and the second one, in drupal 6, according to a stack overflow thread, can be dangerous since it can do unpredictable things.

So I examined the form object via print_r($form); followed by an exit; statement. There I saw that I could reach for the field that I wanted via $form["#node"]. This returns the node object.

$value = $form["#node"]->height[0]["value"];

Then I attempted to hide the field by unsetting the node values. This was a mistake, since the node object doesn't have anything to do with the form. Yet I couldn't find the form entry for the fields that I needed. Reading through the comments of webchick's entry, someone mentioned the field groups. Ah! Looking back, it seems self evident. I needed to reach the field via the group field first. And following the direction given in the stack overflow page, hiding the field uses the following syntax.

$form["measurements_group"]["height"][0]["#access"] = false;

Altogether, the code to hide a field in a CCK content type form looks like this:

function example_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'measurements_node_form') {
    // Add an after_build function to process when everything's complete.
    $form['#after_build'][] = 'example_after_build';
function example_after_build($form, &$form_state) {
  $show = array("Edit more", "Incorrect");
  $term_id = $form["#node"]->height[0]["value"];
  $term = taxonomy_get_term($term_id);
  if ($term->name != "" && !in_array($term->name, $show)){
     $form["measurements_group"]["height"]["#access"] = false;
  return $form;

drupal 6 api on hook_form_alter
stack overflow
webchick's blog on hook_form_alter and CCK on drupal.org

Windows Forms: programmatic assignment to control will register in data binding

I just ran into an interesting issue related to data binding. I have a custom control in a windows forms application that manages the app's configuration. I also have a configuration object. The control is the view for the configuration object.

I had bound the object properties to controls using the following idiom

        private void bind()
            SeeRectangle.DataBindings.Add("Checked", configuration, "ShowAnswer");                           // Checkbox
            OrderingTypeSelection.DataBindings.Add("SelectedItem", configuration, "OrderingMode");   // ComboBox
            AnswerPath.DataBindings.Add("Text", configuration, "AnswerPath");                                    // TextBox

When adding a data biding via the Add() method of the DataBinding specialized collection, the arguments are the property of the control that will be bound, followed by the object that we will bind with, followed by the property of the object that is binding. The checkbox and combobox worked fine. I wasn't getting expected results with the textbox binding.

I had tried to assign the value of the Text property of the textbox with the following code

            var openDirectory = new FolderBrowserDialog();
            var answer = openDirectory.ShowDialog();
            if (answer == DialogResult.OK)
                if (configuration != null)
                    AnswerPath.Text = openDirectory.SelectedPath;

And the textbox was correctly assigned. However, the binding with the configuration object kept failing. What I discovered was that there must be an event that is not triggered when assigning values via code. If I changed the values in the textbox, the assignment would happen.

So the workaround was to explicitly assign the value from the FolderBroswerDialog to the configuration object.

            var openDirectory = new FolderBrowserDialog();
            var answer = openDirectory.ShowDialog();
            if (answer == DialogResult.OK)
                if (configuration != null)
                    AnswerPath.Text = openDirectory.SelectedPath;
                    configuration.AnswerPath = openDirectory.SelectedPath; // <--- the solution

Happiness day 17: Learning how to solder for real

Last week we went to the Science and Engineering festival in DC. Among the great swag that we got was a couple of circuit kits from sparkfun designed to teach one how to solder. My daughter had done the Parallax "learn how to solder" activity at the festival, so we donated some money and got two kits, one for her, and one for me.

I did mine today. It is a Simon Says game, and I was pretty pleased with how well I was soldering. I had tried it before, but I think I kept missing the right combination of soldering iron and the correct solder with for electronics. Most of my dots were pretty, except for some necessary big blobs that I needed to make to connect the battery holders; those were horrible. Admitting that fault, I was pretty happy with my job soldering the micro-controller. I had previously had problems soldering a 555 chip, so to be able to solder way more leads successfully made me happy.

Haskell, C#: map, filter, and fold in C# via linq

Looping is a fundamental concept in computer programming. And to most programmers familiar with imperative c-syntax languages, it looks something like this:

  foreach (var s in stringList)

The idiom is simple: we are going to go through each item in the list, and we will process that element in some manner. In most cases, we are either transforming each element, we are filtering the elements, or we are carrying out some sort of accumulation. To know which of these actions is being carried out we would have to read carefully what is happening in between the curly brackets.

So, looking at the code, we instantly know that we are doing something with every element. But at a glance we don\'t know what that something is.

Functional programming gives us three (3) functions to loop through lists. These are map(), filter(), and fold(). The final result between imperative looping and the functional functions is the same, but we gain semantic clues with the functional functions to what the looping id doing.

C# is a remarkable language. Although it was born as an imperative language, it has been supporting more and more functional operations through linq. Below I will briefly describe the three looping functions, and then I will show its imperative equivalent, followed by its equivalent in using linq.

map() will take a function followed by a list. Each element in the list will be transformed by the function, and the output will be a list of transformed values. In haskell it looks like this

x = map (* 5) [3,4,5,6,3]

Translated into imperative C# code it looks like this:

var result = new List<int>();
var list = new list<int> { 3,4,5,6,3};
foreach (var n in list)
  result.Add(5 * n);

In linq, to express the above function, we us the select query thingy and write

  var query_result = (from n in new List<int> { 1, 2, 3, 4, 5 }
                           select n * 5).ToList();

Sometimes we use loops to filter values out. Functional programming languages have filter(), which takes a predicate function, one with a condition, and a list, and returns a list that meets the filter condition.

x = filter (> 5) [3,4,5,6,3]

Its procedural code in C#:

var result = new List<int>();
var list = new list<int> { 3,4,5,6,3};
foreach (var n in list)
  if (n > 5)
    result.Add( n);

And its functional version in C# via linq. For filter, we mainly use the where clause in a linq query.

   var query_result = (from n in new List<int>() { 1, 2, 3, 4, 5 }
                                  where n > 5
                                  select n).ToList();

The final looping case that I will show is aggregating a value, such as a total from all of the numbers in a list. This operation is called fold in functional programming, since the person naming the function imagined a paper list of values being folded one at a time. foldl takes a function, a list, and an initial value.

x = foldl (+) 0 [3,4,5,6,3]

This is equivalent to procedural C# to

var result = 0;
var list = new list<int>{ 3,4,5,6,3};
foreach (var n in list)
   result += n;

In functional C# via linq we write:

  var query_result = (from n in new List<int>{ 1, 2, 3, 4, 5 }
                                select n).Sum() ;

The above was shown to keep the parallelism between the examples. In actual use, one would most likely use a IEnumerable extension method in the following form:

  var result =  new List<int> { 1, 2, 3, 4, 5 }.Sum();

As we have seen, the functional methods map, filter, and fold have an semantic advantage over procedural looping in that they clearly tell you what the looping is doing. C# has the capabilities of doing functional statements. Although not giving the same terse syntax or its immediate semantic meaning, the linq functional-like methods approximate functional terseness and reduces, although not eliminates, the semantic ambiguity the semantic ambiguity that procedural loops have.

Ruby: first adventures into metaprogramming

While working on a personal project, I ran into the following case. I wanted method load() to take a hash with values. If a key in the hash exists as an instance method, then assign the value from the input hash to it. I could have coded around it using an array with the names of instance variables and working from there, but, where is the fun in that? Besides, I knew that I could use this as a concrete meta programming exercise for myself.

1. I made sure that accessors create an instance method
I started irb and tested whether a class with an accessor would create an instance variable automatically. I tried the following:

class A
 attr_accessor x
y = A.new
y.instance_variable_set "@x", "wow"
puts y.x # => "wow"

So far, it seems like it works! So back to the text editor, and I wrote the method.

2. Something isn't right

def load(data = nil)
   if data.instance_of? Hash
     data.keys.each do |key|
      if self.instance_variables.include? key
        attr_name = "@#{key}"
        self.instance_variable_set attr_name , data[key]

So I write the code above. I expect that my tests would pass. But they didn't. The if clause was never true, so there was never an assignment. What? I looked back at the class description. The accessor names were there. What was going on? After a few minutes, I remembered a lunch discussion that I listened to at Ruby Nation. It was discussed that ruby starts with an empty object, and it builds members and methods as they are declared or needed. To begin with, there isn't anything in an object beyond the Object methods themselves, or so I understood. So, that means that until there is any assignment to a member accessor, the instance variable that the accessor provides the getter and setter for method doesn't exist yet.

Since the instance variable wasn't there, I decided to check for whether the object could respond to its getter/setter method.

3. Getting it to work

def load(data = nil)
   if data.instance_of? Hash
     data.keys.each do |key|
      if self.respond_to? key
        attr_name = "@#{key}"
        self.instance_variable_set attr_name , data[key]

the difference happens on line 4. It went from

 if self.instance_variables.include? key
where I was checking for the existence of the instance variable (which doesn't exist until assignment) to
 if self.respond_to? key
which checks for whether the object would respond to the method. This fix the problem.

rspec: Some quick notes on exception testing

I ran into some strange issues with exception testing in rspec when working on cygwin using rspec 2.6.4. These more more than anything else a collection of notes.

I am writing an object Room. It should have an optional hash argument. So I have two scenarios to test: that it should quietly create the Room object when no arguments were given to the initializer, and that, if there is an argument, it should only be a hash. Here are the tests that eventually worked:

 describe "initialize" do
    it "should accept an optional argument" do
      expect { @r.init {} }.should_not raise_error
    it "should accept only a hash" do
      expect { @r.init [] }.to raise_error ArgumentError

And the following are the steps that I took when I was getting there, and what I learned on the way.

1. I can't test object creation, Room.new, tests will consistently pass
When using this code:

  expect { Room.new [] }.should raise_error 

rather than getting the error that I was expecting, it would silently pass, which is not good when the whole point of testing is to convince yourself and others that the object is behaving as expected.

2. room.initialize() is invisible
I thought to myself that even though it is a bit annoying, not being able to test via object creation is not that horrible. I would just test initialize() instead.

  expect { @r.initialize [] }.should raise_error 

When running it, I did get those expected errors. however the error was because it couldn't find the initialize(). Not the error that I wanted. So it seems that initialize() becomes invisible when running rspec.

3. room.init works
So what I had to do was to create a init() method that would handle the code that otherwise would be found in initialize(). A bit clunky, but it works.

Now, the only reason why I spent so much time on it was because I thought it was an important logic. This logic would have been taken cared of by the compiler in a static language. Since that is not available, it would be nice to be able to be able to test the constructor. Maybe there is a way. Maybe I missed it. But for the moment, this is what I found.

Syndicate content