Archive for March, 2008

How to Teach Programming?

Tuesday, March 25th, 2008

I might be wrong about this, but I’m partial to the gauntlet method of teaching introductory programming courses. You make the class as challenging and difficult on purpose and make the students sweat. Hit them hard and as early as possible so that the slackers get the idea and withdraw from the course. Every lecture should raise the bar, and anyone who can’t keep up or is struggling should be encouraged to drop the course and change their major. It is harsh, but I do believe that a large percentage of people in every programming class will just never get it. No matter what you do, they will always struggle and will demand your help and attention which would be better spent supporting the students who actually get this stuff and are progressing at a fast pace.

I can probably tell you which people will do well, and which will struggle and just waste your time. You can see when you assign a really difficult problem they haven’t encountered before. The students that get energized, and excited by the challenge - who ask meaningful questions, furiously jot down notes, or start coding before you even finish explaining it - they are your star players. They should get all your attention and you should make sure they are sufficiently challenged, and that they have adequate support to meet the challenge head on.

Then there are those other students who raise their hand and say “I don’t understand this” or “I don’t know how do I do this” - they are most likely a dead weight. And yet, you will end up spending inordinate amounts of time basically holding their hand, and pretty much debugging their code for them. You end up purposefully dumbing down the course, and choosing idiot-friendly tools for their sake and in the end your star pupils get bored, and frustrated with the glacial progress of the course. In the end everyone loses.

The talented students make little progress, and end up ill prepared for the next programming course in the curriculum. The non-programmers barely pass with a C or a D (or if you made enough concession for their sake even a B) and leave your class without actually learning one damn thing. Or rather, the only thing they learned in your class was that they can slip through the cracks and pass a programming class without actually learning how to code or solve problems.

I think that the use of tools like BlueJ in the classroom is an outgrowth of this “cuddle the hopeless students while ignoring the talented ones” approach. Personally I think we do not need tools like that - not at the college level. But this seems to be a minority opinion, and many people disagree with it. Same could be said for the gauntlet approach.

The thing about the gauntlet thing is that it is actually very difficult to implement. It requires tons of experience, and absolute confidence in your teaching ability and methodology. When I notice that large number of my students is lost, I usually blame myself and try to review and re-iterate the difficult parts over and over again. More than once however I found that the people who were most vocal about the difficult material, and who got the most help from me actually got it wrong on the test, while the silent majority actually understood it. So I essentially wasted my time, spinning my wheels in place instead of going forward or covering other areas in more depth. It’s easy to spot these pitfalls in retrospect but not when you are lecturing. When I have 4 or 5 students who seem to be completely baffled by something that I just said, and loudly voice their confusion it is sometimes hard to realize they are actually not speaking for the whole class. The remaining 30 students who are quietly taking notes might not be confused at all.

Experience helps here - and so do a time tested lesson plans and delivery methods. Identifying and subsequently ignoring the dead weight also helps. But it is very hard to do because it means you are essentially giving up on some students and allow them to fall behind. And that is a horrible thing to do. Most teachers won’t willingly do something like that. Personally I refuse to do it and I really try to help people out when I see they are struggling. But often that means I’m essentially the one doing all the work - I’m literally pushing, and dragging them that’s passing grade. Would they make it if I didn’t actually force them to do work? Would they pass if I didn’t extend their deadlines ad infinitum? Probably not, and by helping them so much I actually allow them to slip through the cracks without actually working for the grade or even trying very hard. This is why gauntlet is a good idea, but I’m the wrong person to run it. I couldn’t do it. But there are people who can and do run their classes this way.

It takes the right instructor - someone who is approachable, supportive, but at the same time tough and demanding. And most importantly someone who knows what he/she is doing.

But IMHO there should be no cuddling, and no tolerance for ignorance or technological incompetence. But above all, there should be a zero tolerance policy for students who say one of the following lines:

  1. I hate computers
  2. I hate programming
  3. I hate [language you are teaching]

The only response to any of these statements should be: You should not be here! You will not do well! Drop this class! Drop this class! Drop this class immediately!

If you are confused by technology, programming bores you, and you dread every single coding assignment why are you subjecting yourself to this whole ordeal? I do not understand why people do this, but they do. When I was in college, I stayed the hell away from the Business School building because economics and finance classes bored me to death. I did not enjoy them so I didn’t take them. The Computer Science program at my school offered us a choice when picking required auxiliary courses - you could either do the science route (2 science classes - chem or physics) or the business route (3 business classes - micro/macro economics and some other stuff). I immediately signed up for science because it sounded much more interesting, and much more challenging. Most of my friends picked economics because it was easier.

Computer Science should never be the easy or fun course. It should be the class that evokes the sentiment in the majority of student body: “You are taking Computer Science? Are you insane?”. Only the students who are crazy enough, motivated enough or just love the subject should be taking the class.

Unfortunately, if you don’t get 20-30 warm bodies to register for your course at my university, the Dean will shut it down. And this is a problem at a school where we only offer 2-3 introductory programming sections per semester due to low student frequency.

3 Value Checkbox with JQuery

Monday, March 24th, 2008

Few days ago I did that whole 3-value checkbox thing basing it on some script I found online. I went back and I re-implemented it using some JQuery magic. I’m not going to reiterate the whole setup here. I recommend that you check the linked post for details. You can find the JQuery-fied code below:

$(document).ready(function() 
{
   checked = '/path/to/checked.jpg';
   unchecked = '/path/to/unchecked.jpg';
   na = '/path/to/na.jpg';
   i = 0;
 
   // replace the checkboxes with images    
   $("form.funky_form > fieldset.funky_set :checkbox.funky_box").hide().each(function() {
 
      img = document.createElement('img');
      img.className = "funky_image";
 
      switch($(this).val())
      {
         case "0":
            img.src = unchecked;
            $(this).attr("checked", "false");
            break;
         case "1":
            img.src = checked;
            $(this).attr("checked", "true");
            break;
         case "2":
            img.src = na;
            $(this).attr("checked", "true");
      }
 
      // these will let us identify which image was clicked
      // and which checkbox does it belong to
      $(this).attr("id", "input" + i + "image" + i);
      $(img).attr("id", "" + i + "image" + i);
 
      i++;
 
      $(this).before(img);
   });
 
   // add onClick functionality to the new images
   $(".funky_image").click(function() {
 
      // select the checkbox corresponding to the clicked img
      t = $("#input" + $(this).attr("id"));
 
      switch(t.val())
      {
         case "0":
            $(this).attr("src", na);
            t.val(2).attr("checked", "true");
            break;
         case "1":
            $(this).attr("src", unchecked);
            t.val(0).removeAttr("checked");
            break;
         case "2":
            $(this).attr("src", checked);
            t.val(1).removeAttr("chekced");
      }             
   });
});

The major difference from the other version is that I’m much more discerning in which checkboxes get converted. The code will select only a box that is of the class funky_box and is inside a fieldset with a class of funky_set and inside a form with a class of funky_form. I’m mostly doing that to show power of JQuery - this is all specified in that very first select statement. I was trying to do something similar in the old code, but I was getting hung up on the silly DOM gotchas. JQuery makes this easy.

Also note the chaining functions. The first line after I declere i both hides all the selected check-boxes and begins the each block. Similarly, check out the second switch statement. In several places I set the value of t and change the checked attribute on the same time. It’s very expressive, and lends itself toward very compact and concise code.

Here is the HTML for the form to go with the code above (note the inclusion of the fieldset tag):

<form name="funky_form" method="POST">
      <fieldset class='funky_set'>
         <label for="c1">
            <input type="checkbox" name="c1" value="1" class="funky_box" checked>
            Some Important Task
         </label><br>
 
         <label for="c2">
            <input type="checkbox" name="c2" value="1" class="funky_box" checked>
            Some Important Task #2
         </label>
      </fieldset>
 
      <label for="c3">
         <input type="checkbox" name="c3" value="1" class="funky_box" checked>
         This is a checkbox with the funky_box class outside the funky_set
      </label><br><br>
 
   <input type="submit" value="Submit">
</form>

How readable is this version? To me it is actually better because it’s smaller, and more compact. To someone who never worked with JQuery it might be a bit confusing at first but I think you get used to the weirdness pretty quickly. I find the selection statements much more elegant than nested loops for example, even if they might The more code I can see on my screen the better. I’m not golfing though - all the methods and most variables have meaningful names (well, except stuff like t and i but you know how it goes).

Which version do you like better?

KOTOR 2: Broken Jedi

Saturday, March 22nd, 2008

KOTOR 2 uses an interesting plot device to explain why your battle scarred, world weary Jedi character has such meager stats and force powers at the beginning of the game. In the original there was no such excuse because you simply started as a oridinary, human being and only gained force powers after going through the training on Dantoine.

KOTOR 2 on the other hand insists that you were a Jedi once, and that you are actually one of the last of the living Jedi knights in the galaxy. So why the poor starting characteristics? It turns out that you were exiled from the order, and the Jedi Council somehow severed your connection to the force. Ha! Clever stuff. Unfortunately while it does make some sense on the surface, and does make for a good story (why did they do it and how?) I don’t totally buy this explanation. It’s not very consistent with what we know about the Star Wars universe. If the Jedi Council had this power all along and could elect to neuter a Jedi knight at a whim by severing him from the force why was it done to your character (a virtual nobody), and not to the big bad Sith Lords that threatened the galaxy in the past? Someone is probably going to say they were to powerful to be dealt with that way or that the Sith training includes techniques that help one protect himself from such an attack, and I guess it is an explanation of sorts. Still it has not been addressed in the game yet. I will suspend my judgment on this until I finish the game but I’m not entirely happy with the forceful force removal idea.

On the other hand, I kinda like the idea of a failed, broken Jedi character. If I remember correctly the D6 Star Wars rulebook we used way back when (long log ago, in a galaxy far far away) actually included something similar as a playable character archetype. I think it was dubbed as the “Fallen Jedi”. The fallen bit was not referring to falling to the Dark Side though. In fact it was about failing more about falling. A fallen Jedi was simply a washed out failure and a nobody. The rulebook had this great sketch of a unshaved, unkempt inebriated drunkard slouching on a bar stool, with a drink in one hand, gambling cards in the other, the lightsaber hilt sticking out of some odd pocket of his jacket.

k2_00007.jpg

The idea was simple - you were taught to be a Jedi but you were either never really good at it, or your personal opinions clashed with the Jedi code - or perhaps you somehow dishonored yourself. Either way, you have no affiliation with the Jedi Council anymore and your life went down the drain. Now you spend most of your time getting drunk trying to drown out the past. And if you are not drinking you hire yourself out to do odd jobs here and there in order to afford the booze. Even if you were semi competent at using force in the past, these days you are rarely sober enough to actually actually be able to concentrate.

Not so long ago, Shamus had an interesting discussion about the difficulties of running a Star Wars campaign when someone in the party insist on playing a Jedi. I think the washed out Jedi is the ideal archetype to stick into a more traditional party of smugglers and bounty hunters. He would have similar motivations and aspirations as the rest of his company - money, booze and loot. His social and political influence would be diminished since most of NPC’s would be able to tell he has no backing of the Council and essentially is no more than some hired gun with a toy lightsaber. Additional bonus is that this character could actually have a good excuse to dabble in the dark side powers.

k2_00009.jpg

But let me get back to KOTOR. The game did take a turn for the better after leaving the initial area, and the Telos Orbital Station section was actually fun and interesting. I liked how the game allowed you to either work for the corrupt Czherka Corporation, or against it by help out the Ichtorian planet restoration efforts. There were some interesting missions there, and I liked how they were all clustered in the relatively small area of the base. Since the same locales were reused, or previously blocked areas became available it made the base seem more dynamic and alive. It was much better than running in the endless corridors of the mining station fighting hordes nameless droids at the begining.

That said, the story I still makes me cringe at times. For example, nearly every time you board some kind of a ship or shuttle you either get shot down or locked out and end up trapped in the new area. When you start the game your ship is sealed off in a differed section of the station, and you need to run around for hours before you can unlock it. Then you reach the Telos Orbital Station, and your ship gets confiscated, and then stolen. So you board a shuttle to the planet surface, which gets shot down and you end up trapped on the semi-hospitable planet. Somehow you manage to find another shuttle on the surface, only to get shot down again, and ending up trapped in the polar region of the planet. WTF?

k2_00018.jpg

It seems repetitive, to the point that I’m now actually expecting it to happen every time I travel from one area to another. Furthermore the game seems to alternate between seemingly open ended game play mode and interludes of very linear progress and story exposition. Which I guess is ok. I’m once again at a point in the game where I can once again choose my own quests. I also did so many good deeds that my character’s portrait is actually glowing now. P

The dialogs seem to be a bit glitchy in this game. Sometimes the game will randomly skip a spoken line and you notice it because they usually change the camera angle after a full stop. When a line is skipped you can still see the change in scenery, and it just quickly cuts away to the next scene/line. It doesn’t happen very often, but it is noticeable. Also, the timing is sometimes off when you talk with aliens that speak in their own language. It’s almost like that subtitle gag in which you hear a character speak in a foreign language for a full minute, only to see this lengthy tirade translated to a single word in the subtitles. This actually sometimes happen here - the subtitle says something like “I will think about this…” but the spoken part in the alien language seems to be going on and on and on. It’s a little bit silly.

k2_00014.jpg

As I progress through the game, combat starts to become more strategic and the behaviors/stances you set for the party members you are not currently controlling actually do matter. For example, on the surface of Telos there are big open areas with enemies scattered all over the place. I left all my characters in the aggressive stance only to watch them scatter in all directions and aggro just about every single enemy on the map. After that fiasco I tend to keep the old lady as a force support character, and whoever else I have in the party as ranged. This usually keeps them following my main character who is in aggressive stance and prevents them from doing to much aggro all around. When needed I can switch to these characters and give them direct commands. I just wish I could have more than 3 people traveling with me at a time - if for nothing else just to exploit all the different stances at the same time.

As characters go, there are few new faces at this point in the game. There is a Zabrak mechanic and an Echani fighter. While I don’t care either way for the former, the later seems interesting. While she was trained to shield her mind against the force, she seems to be genuinely interested in it. She also has interesting concepts on combat as a form of expression. If you ask her to train you she will insist that you both strip down to your underoos. Yes, this is a character that I can grow to like. mrgreen

k2_00022.jpg

Despite all the complaining above, I’m actually enjoying this game. The story is slowly unfolding and the missions are interesting and not very repetitive, even if all but the most important NPC’s look the same using the 20-30 same models colorized in different ways. So far I haven’t been tempted to put it down which is a good sign. P

JQuery Quirks

Friday, March 21st, 2008

Here are two interesting quirks in the way JQuery works. Let’s say you want to check all the check-boxes on the page - how do you do it? It’s trivial:

$(":checkbox").attr("checked", "true");

Now quickly, how do you un-check all the check boxes on the page? If you said:

$(":checkbox").attr("checked", "false");

You are wrong. Despite the fact that if you use a more standard notation and say for example:

document.myform.mycheckbox.checked = false;

it will give you the desired result. The JQuery call however does not work. In fact, it does the exact opposite - it will set all the check-boxes on the page to their checked state. Apparently for the few funky attributes like “checked” and “selected” the second argument of the attr() method call can be any non-empty string. It makes sense because you actually don’t have to give these attributes an explicit value in your HTML code for them to work. So how do you un-check a box in JQuery? There are two ways. First one, and the more sure-fire one is to remove the checked attribute altogether:

$(":checkbox").removeAttr("checked");

Second one which has worked for me for some reason was to set the attribute to the empty string:

$(":checkbox").attr("checked", "");

Same goes for select attributes in combo boxes and list boxes. You need to remove them or set them to an empty string, or they won’t go away.

Quirk number two: axjax weirdness. Look at the code below:

$("a").hover(function() {// do something});
$("#sometrigger").click(function() { 
   $("#container").load("/some/page.html #links"); });

What am I doing here? I’m adding some hover functionality to all the links on the page. Then I add an on-click even to #sometrigger element. When it is clicked I want to load the contents of #links from /some/page.html into #container asynchronously. Where is the quirk? The hover functionality will not apply to the dynamically loaded links. It’s weird, but that’s just how it works. So if you want this functionality on all your links you will need to reapply them:

$("a").hover(function() {// do something});
$("#sometrigger").click(function() { 
   $("#container").load("/some/page.html #links", 
      $("#container > a").hover(function() {// do something});
         });
   );

It’s a little bit silly, but it kinda makes sense. You may not always want to apply the same events and formating to newly loaded html. But if you don’t expect it, it may throw you off. One you know about it however you learn to compensate for it. I’m being told that folks coming from the Prototype community are hitting this little quirk like a brick wall because their framework behaves in the opposite way (ie. the effects and behaviors are applied to the ajax loaded html).

Apostrophe in the Email Address?

Thursday, March 20th, 2008

Here is a question for my IT/Sysadmin readers out there. When you get a user who has an apostrophe, or an unusual character in their last name, how do you go about setting up his or her email address? Do you:

  1. Drop the apostrophe and special characters and/or replace them with the closest ASCII equivalent to keep it easy
  2. Keep the special characters and force everyone in the world to struggle as they try to email that user

Apparently IT people at a certain bank that I will not name (but let me just say it’s initials are HSBC) think that option #2 is a good idea. Why? Let’s think about a hypothetical scenario in which, for example and apostrophe in the email could be a problem. Again, this is just a make believe situation that has never actually happened yesterday at my company.

So, hypothetically speaking a made up user JC calls me up yesterday and tells me that she can’t send email to one Frogurt D’mangello who works at the said bank. Why can’t she do it? Because Mr. Frogurt’s email looks like this:

frogurt.d’mangello@we.like.subdomains.in.our.emails.hsbc.com

On the surface this is ok - after all apostrophes are allowed to be part of the email address according to the RFC, right? I know this, you know this but apparently whoever hacked together SquirrelMail didn’t. So when you try to send an email to Mr. Frogurt via this popular and widely used webmail application his address becomes:

frogurt.d\’mangello@we.like.subdomains.in.our.emails.hsbc.com

Yes, someone is running mysql_escape_string method on all input fields, even those which legally are allowed to contain MySQL unfriendly characters. I should be mad at SquirrelMail but you know what - they are doing the right thing. I sanitize all my input fields too when I work on a web application. Better be safe than sorry. Naturally, they could use strip_slashes just before actually sending the email but what are you going to do. It’s a bug (which might have been already patched in then newest release), but I can’t fix it because I do not maintain the SquirelMails server. (

But the situation is now a conundrum because JC is behind some draconian firewall which blocks all outgoing ports save for port 80 meaning she can’t use Outlook to send emails. She also can’t use SquirrelMail due to this peculiar bug. So how do they communicate?

This could have been easily avoided if certain IT department simply had a policy which said “only dots and alphanumeric ASCII characters in usernames”. And not just because certain email packages may not support all the different addressing formats as specified in the RFC. It’s also because everyone thinks they know how to validate emails but they don’t. Half the validation scripts out there is just plain wrong. You actually need a 6.4K regular expression to cover all the different addressing schemes covered by the RFC. So if Mr. Frogurt wants to subscribe to some mailing list, or sign into some popular web application he might at one point be told his email is not valid. Remove the apostrophe, and even the most broken email validator will let it through.

Not to mention the hassle of emphasizing the apostrophe every time he tries to dictate his email address to someone over the phone. So really, other than blindly following the RFC, what other benefits are there of putting that non alphanumeric character in his email? Would Mr. Frogurt really mind if his email started with frogurt.dmangello? Would it really make his life a living hell, or would it actually spare him some potential hassles, misunderstandings and unnecessary tech support calls?

I too have a non-standar letter in my name. If I wanted, I could set up my email as: Ɓukasz@example.com. It would be legal under RFC but I would probably spend the rest of my days explaining to people what that “weird L” is and how to get it in Outlook. Oh, and no iPhone user would probably ever email me because these poor schmucks can’t copy and paste yet. ;P

I say stick to alphanumeric ASCII and dots. Anything more is just asking for trouble.