31 August, 2007 | Written by Vincent Tan Leave a Comment

Code responsibly or your work can haunt you

Have you ever written code that was below your average quality? I have, and sometimes I wish I could have write it better then.

There had been times when I came across some of my older work, and I’ll be tempted to rewrite or refactor or rework the code or logic. Then I told myself that I did the best I could then, and I should let it go. Focusing my energy on future projects is a better use.

That said, sometimes your creations can come back and haunt you. Like in this animator versus animation video.

30 August, 2007 | Written by Vincent Tan Leave a Comment

A void in humanity

With the advent of more powerful communication tools enabled by technology, will the congregation of social groups suddenly create voids in our humanity? Let’s time travel to the past for a while.

I remember a time when connecting with family and friends was done either face to face or using the phone (the landed one). Then people around me started carrying these things called mobile phones, and it was considered hip to actually own one. I was oblivious to this accessory, since I haven’t found a need to be constantly contactable.

Then I started studying in a university, and through force of pressure, I was strongly persuaded to get a mobile phone. It was a flip phone, one of the earlier models that I got from a friend.

I also found out about the Internet. The hip thing then was ICQ and MSN Messenger, two instant messaging software available. Through peer pressure, I was again strongly persuaded to sign up, so I could go home and chat with my friends online. The conversation usually degenerated into near-monosyllabic words and arcane short forms like gtg (got to go) and lol (laugh out loud).

When we’re free in between attending lessons or doing homework and research, my friends (and I, you got it, strongly persuaded) logged on to Neopets, and practically bashed on the refresh button on the web browser so we could get our virtual hands on the store items when the Neopets server restocked.

Then people found the Internet to be a fantastic communication medium. Community web sites sprung forth, empowering people to reach beyond to the world. Forums and other online groups became connecting points.

Technology advanced. Better features. Faster upload/download speeds. And Web 2.0 came. Digg, Reddit, Technorati, StumbleUpon, Facebook, MySpace, Flickr, YouTube and other social media sites appeared. And people flocked to them in droves.

We seem to have this innate need to connect with other people. Like this elderly gentlemen whom Darren met while shopping for inspiration. Text and images on web sites aren’t enough anymore. We want to see and hear people through the Internet too. Audio and video are becoming more important. My blogging mentor, Yaro Starak, is also experimenting with more video posts, along with Darren and other bloggers.

Then I read about this article on a hole in the universe. Astronomers found a void in space, and their explanation was that gravity from high density masses are attracting nearby matter. When enough of these attractors came together, a void was formed because of the absence of matter between the attractors.

Will this happen to us? Will our new generation social media groups unwittingly create voids in our humanity, by pulling in masses of people to them?

29 August, 2007 | Written by Vincent Tan 1 Comment

Beginning C# - Reading Input Writing Output

There’s a saying in programming that goes something like this

Be liberal with what you receive. Be strict with what you produce.

What it means is that your program should be lenient with the input it receives, to assume that all sorts of rubbish data can (and will be) fed to your program, and it’s your duty to make sure your program can handle it.

BUT, your program must adhere strictly to the output format it’s supposed to produce. If your program’s supposed to write out integers, it better write out only integers.

It’s not fair, I know. It also makes it easier for programs to talk to each other, since input and output of programs are what they communicate with. The most common communication methods is through file input/output or file IO as they’re usually referred to.

I personally find the StreamReader and StreamWriter classes to be easy to use for file IO. The .NET framework views file IO as a form of data stream. Other classes dealing with data streams include NetworkStream (working with data across networks) and MemoryStream (working with data within computer memory).

So how do we read input and write output? Let’s look at some source code first. [code formatting looks better from web site]

StreamWriter sw;
sw = new StreamWriter("greetings.txt");
sw.WriteLine("Hi!");
sw.WriteLine("Good morning!");
sw.WriteLine("Splendid day isn't it?");
sw.Close();

string[] flowerlist = new string[] { "daffodil", "lily", "orchid", "rose" };
sw = new StreamWriter("flowers.txt");
foreach (string s in flowerlist)
{
    sw.WriteLine(s);
}
sw.Close();

// the second parameter indicates if file should be appended or not.
// If the second parameter is false, it would have overwritten the
// contents from above, and flowers.txt would only have 2 flowers.
sw = new StreamWriter("flowers.txt", true);
sw.WriteLine("sunflower");
sw.WriteLine("tulip");
sw.Close();

File.WriteAllLines("greetings2.txt", new string[] { "Hello!", "How are you doing?" });

// we start reading the files and writing their content here
sw = new StreamWriter("result.txt");
StreamReader sr;

sw.WriteLine("{0}Reading from greetings.txt", "=".PadRight(20, '='));
sr = new StreamReader("greetings.txt");
while (sr.Peek() > -1)
{
   // we read one line and write one line
   sw.WriteLine(sr.ReadLine());
}
sr.Close();
sw.WriteLine("{0}End of greetings.txt", "=".PadRight(20, '='));

sw.WriteLine("{0}Reading from flowers.txt", "=".PadRight(20, '='));
sr = new StreamReader("flowers.txt");
// we use sw.Write() instead of sw.WriteLine() because
// flowers.txt already contained a newline character at the end.
sw.Write(sr.ReadToEnd());
sr.Close();
sw.WriteLine("{0}End of flowers.txt", "=".PadRight(20, '='));

sw.WriteLine("{0}Reading from greetings2.txt", "=".PadRight(20, '='));
sw.WriteLine(File.ReadAllText("greetings2.txt"));
sw.WriteLine("{0}End of greetings2.txt", "=".PadRight(20, '='));

sw.Close();

Console.WriteLine("End of program");
Console.ReadLine();

The code’s quite straight forward. I want to highlight a small code section

"=".PadRight(20, '=')

This is a shortcut to generate 20 equal signs. It beats writing a for loop or manually typing in 20 equal signs.

The StreamReader.Peek() function returns the next character but doesn’t read it into memory. If there’s nothing left to read, like End Of File (EOF), then a -1 is returned. This makes the function a suitable termination condition for a while loop reading in file content.

The StreamReader.ReadLine() function reads in input until it hits a newline character, and returns all input read thus far in a string. The StreamReader.ReadToEnd() function basically dumps the entire file content into a string.

With .NET framework 2.0 comes another way to rapidly and easily read data from files. The File class has been beefed up with some nifty new functions. The following functions allow reading in input from a file with just one line of code

  • File.ReadAllBytes() - returns file content in a byte array
  • File.ReadAllLines() - returns file content in a string array
  • File.ReadAllText() - returns file content in just one string (newlines and all)

Then there’s the corresponding one-liners for writing output

  • File.WriteAllBytes()
  • File.WriteAllLines()
  • File.WriteAllText()

These one-liners read/write content to/from a file and closes the file, all in that one line. It’s basically a shortcut compressing one line to open a file, one line to read/write file content, and one line to close the file.

As always, you are encouraged to explore the (online) MSDN documentation for more details. Study how to instantiate a class and what are the public properties and functions available.

You don’t have to memorise and learn how to use every single function. Just remember what kinds of functions are available. Then when the time comes where you need a particular feature, you’ll know where to look.

Download the source code.

28 August, 2007 | Written by Vincent Tan 1 Comment

Paint.NET Review

I remember a time when I didn’t have any image editing software available on my computer, and I needed to create some images for my web site. The image editing software I knew then were Adobe Photoshop and Corel Paint Shop Pro (formerly from Jasc). I was a student then, and cash was tight, and the money saved could be used on something more important. Like feeding myself.

So I used the only available free software I had: Windows Paint. Oh it was terrible! I wanted to draw some circles with antialiasing, and I painstakingly drew each differently shaded pixel in. I moved close to the screen to see the pixels and moved away to see the general effect. Have I mentioned it was terrible?

If only I had Paint.NET then! Well, the .NET framework wasn’t out then, so Paint.NET won’t be too. But YOU! You now have the power to edit images to your heart’s content. Now go download the FREE Paint.NET software and come back here so I can tell you more.

Done downloading and installing?

Ok, so Paint.NET has the basic features provided by Windows Paint, such as colour picker/dropper, pixel pencil and line/curve drawing. I miss the spray can in Windows Paint though… it gave me tons of fun, and if it could be combined with the Gaussian blurs… *sigh*

Anyway, now that I’m a full-blown programmer slash web developer slash designer slash tech documenter, I need to work with images more often. Windows Paint wasn’t cutting it anymore… So what does a polymath programmer who has to juggle many different roles need in an image editing software?

  • Layers
  • Colour selection
  • Nifty effects out-of-the-box
  • Colour swapping
  • Text and arrows

Layer upon layer
Once a secret hoarded by the corporate image editing software companies, and heralded as a distinctive advantage, Paint.NET also grants you this special and mysterious power.

Paint.NET layer panel

Frankly speaking, I don’t know what the big fuss is about. I’ve only maybe used up to 3 layers at any one go. Then again, I’m just trying to create an image that looks good enough in a web application so my work isn’t totally disgraceful.

Perhaps there will come a time where I need to blend transparency, match gradients and create colour swatches with several images to create a final masterpiece. … Just thinking about it makes my head hurl…

Ooohh, look at the purty colours
In my work, I need to rapidly select colours and see how they affect the image I have in my head. Paint.NET does this beautifully, where I can choose from a colour wheel, a standard colour block, or enter the exact RGB or HSV values.

Paint.NET colour panel

I also bring your attention to the hexadecimal input/output box. Very useful for CSS colour values. It was so inconvenient for me to translate red, green and blue values into #rrggbb format at one point in time, that I wrote a program to help me do the translation. This is an awesome feature for me.

Cool effects to liven up your images
There’s a whole range of image effects to give your drab image an extreme makeover. There are blurs and distortions, red eye removal and portrait softening plus edge detection and embossing. Two of my favourite effects are frosting and oil painting, taking this
Clock photograph
To frosted glass
Frosted glass clock photo
Or turn it into an oil painting like this
Oil painting of clock photo

Colour swapping
I have code to write, emails to reply, phone calls to answer, web pages to develop, bugs to squash and documents to create. The last thing I want is to spend half an hour trying to get the colour of a background image for a web application just right.

Sometimes I just need to see how a different colour looks and feels. Paint.NET gives me an easy way, using a slider to shift say a blue gradient
Colour swapping - from blue
To maybe a pink one
Colour swapping - to pink

It’s a quick, easy and painless test for that elusive perfect colour shade.

Words and pointy things
Despite my distaste for writing documents that no one will ever read again (but have to be created to satisfy business requirements), I have found that screenshots alleviate most of the drudgery of presenting information.

Why give your users a screenshot
Choosing an option
And then tell them to click [Effects], then click [Distort] and then choose [Twist]? You can simply provide in-image instructions like this
Choosing options - with inline help

The pointy arrows are a lifesaver. You have no idea how hard it is to draw a line pointing to an area in the image, and then try to draw two short lines to form the arrow head. And it is a simple effective way to communicate to your users the instructions you need them to follow.

Conclusion
Paint.NET is easy to use, and you can quickly learn to apply simple steps to create jaw-droppingly-gorgeous images. For programmers like me, whose companies have uh, limited budgets, Paint.NET is a must-have.

From creating simple icons and backdrops for web pages to creating descriptive screenshots for documentation, Paint.NET takes away your imaging tasks and lets you focus on coding.

I’ve been a follower of Paint.NET since its version 1 point somethings. At my work place, I actually felt sad when Paint.NET moved to .NET framework 2.0. I only had Visual Studio 2003 installed then, which runs on version 1.1, and I couldn’t risk installing version 2.0 in case something happened to my computer. A lot of people depended on my computer in working condition, even if they don’t know it.

So I breathed a sigh of relief when I got the approval from the powers that be, to buy Visual Studio 2005, and hence I can upgrade to .NET framework 2.0 and hence upgrade to the latest version of Paint.NET with all its new and nifty features! I doubt the powers that be read my 15 page proposal, but hey, I got the result I wanted.

So go download Paint.NET now! And did I mention it’s free?

27 August, 2007 | Written by Vincent Tan 7 Comments

Path of a Polymath Programmer Part 1

What is a polymath programmer? First, you need to know Merriam-Webster’s definition of a polymath, who is

a person of encyclopedic learning

Wikipedia says a polymath

may be a person who knows a great deal about several fields of study, a person who has proficiency and competence in multiple fields, or even a person who has excelled in multiple fields.

And to answer the very first question:

A polymath programmer is a person who has proficiency and competence in many programming related activities or tasks. More importantly, a polymath programmer can apply knowledge and expertise from non-programming fields to programming.

After reading the above definitions, your first thought might be, “Oh, a jack of all trades”, followed by “and a master of none”. There’s actually a third line to the phrase, and is particularly important to programming.

A jack of all trades
And a master of none
Though ofttimes better than master of one

In fact, being a master of only one programming skill will get you fired faster than you can say “Sacrebleu“. Technology moves fast, and by the time you understand a new language or technique or concept, another one is invented. If you can’t keep up, you’ll be left behind. Doing one thing well isn’t enough anymore. And this is particularly true in our programming field.

What you need is a broad and stable base of knowledge and skills to support you when you travel the shifting sands of the IT landscape. This base of knowledge must be relatively impervious to change, so you need minimal learning time when a new change is invented. And this is why a polymath programmer will thrive, while the average programmer strives to survive.

So how do you become a polymath programmer? I don’t believe there’s one true path to becoming one, but I can guess. Let me start by asking a question. Have you noticed how some physicists and mathematicians make better programmers? They aren’t any better at programming than regular programmers. In fact, some mathematicians write code that’s an abomination to even look at.

So what’s the secret? They can think. And they have an insatiable curiosity about the world around them, whether it’s related to their field of study or not.

Now let me tell you my journey of becoming a polymath programmer. I have to tell you that it didn’t happen overnight. In fact, it took years. And I didn’t even realise I was slowly becoming one.

It started when I was maybe 9 years old. I remember learning and memorising the multiplication tables. I also learned to play chess, Chinese chess and checkers.

I read voraciously. I adventured with Tin Tin, met characters of Enid Blyton, sleuthed with the Hardy Boys and solved mysteries with Encyclopedia Brown. My parents bought me an encyclopedia set, and hours passed by as I browsed through the books, particularly the ones on science and mathematics. The Norse and Greek gods also provided me with tons of legends about heroes and villains.

I also remember this fascinating story explaining why the earth was bountiful for about 6 months only, because Persephone ate 6 pomegranate seeds given by Hades, so she’s forced to stay in the underworld for 6 months. Persephone’s mother, Demeter, the goddess controlling seasons, wept whenever her daughter went underground, and thus the unfruitful and harsh seasons of fall and winter.

Great, but what does all this mean for you? It fires up the imagination, and as Albert Einstein says, “Imagination is more important than knowledge“. You’ve got to be able to imagine and visualise a problem before you could solve it. Then you’ve got to imagine and visualise a solution before you could distill it into programming logic, and subsequently into code.

Then came the part that might interest you more. I got a toy computer. Yes, it was a toy, because my parents bought it from Toys R Us. The other programmer geniuses I read about usually had some ancient artifact of a computer like an XT86 or something. I still got an XT86, but that was later on.

Oh yes, back to my toy computer. It had the standard keyboard. No mouse. And a one line output screen. No graphics. Its play functions included

  • questions and answers about general knowledge, math and science (amongst others)
  • games like hangman
  • typing practice

And the most significant one of all? It included a BASIC compiler! Not that I knew what a compiler was then. I was just ecstatic that I could print a “Hello World!“. I pored over the instruction manual, learning all the BASIC commands listed. I learned the concept of commenting by starting a line of code with REM. I learned that numbering the lines of code makes the code run in sequential order. I questioned the practice of numbering in multiples of ten, even though BASIC code ran perfectly fine so long as the numbers were in increasing order.

Then something happened that jump-started my learning process. There was a book fair in my school, and as I browsed through the offerings, I found and bought two distinct sets of books. The first set included 3 (I think) books called Dragon Warriors, a series of role playing games (RPG) with instructions on playing and game mastering. The second set included a few books from the micro adventure series, where you play Orion, an adolescent secret spy whose area of expertise was programming!

How did those two sets of books propel me towards being a polymath programmer? I’ll tell you more in the next part of this series of posts. … Alright, fine, I’ll give you a preview. Both sets of books wove story plots, game problem mechanics and code tuning/tinkering together.

See you on our path to becoming polymath programmers!

Continue to part 2

Next Page →