Python loops: the else clause

The else statement is commonly used in association with an if statement, but it can also be used in with loops.

Else is used when you need a piece of code to be executed only if the loop terminates due to an exhaustion of the list when using a for loop or when the condition becomes false when using a while loop.

This is pretty useful when you need to check for something inside your loop and execute some code if your condition never finds anything.

More in this topic in the Python documentation.

Tagged , , , , , , , , , , ,

On printing arrays

Here’s something interesting. In one of my courses we’re learning Java, and have had a few exercises in which we’re asked to write some small programs that do very basic things (generating arrays, ordering words, joining arrays, etc). One of the questions was to write a method that takes an array as input and prints it. It’s a fairly simple exercise but there are some small things that might be overlooked. Of course you’re going to use a for loop to do this, but you’ve got to be careful. If the array is empty, you don’t want to get an ArrayIndexOutOfBoundsException and you don’t want a comma printed after the last member of the array.

To answer the question, I wrote the following code:

public static void printArray(int[] args)
{
    int len = args.length;
    System.out.print("{");
    if (len != 0)
    {
        for (int x = 0; x < (len-1); x++)
            System.out.print(args[x] + ", ");
        System.out.print(args[len-1]);
    }
    System.out.print("}");
}

The if statement accounts for empty strings, and the fact that I only use the for loop for all the elements except the last makes sure that it doesn’t print a comma after the last element.

The professor wrote a different piece of code, however:

public static void printArray(int[] array)
{
    System.out.print("{");
    for (int i = 0; i < array.length; i++)
    {
        System.out.print(array[i]);
        if (i < array.length-1)
            System.out.print(", ");
    }
    System.out.print("}");
}

His code also accounts for empty arrays, but instead of an if statement, it uses the for loop. Since variable i < array.length evaluates to false for an empty lists (whose array.length == 0), the for loop never executes. Also interesting is how he made sure that there is no trailing comma. He makes sure the index value is one less than the last element before printing a comma.

Of course, both answers are valid and have the same end result, but I really like his solution more. The for loop is clever and fairly obvious once you think about it, and the solution for the trailing comma problem is also pretty smart. One thing that I’m interested is to see if the if statement in the for loop affects execution time on very large arrays. My code only has one if statement which gets executed only once. The prof’s if statement gets executed at each iteration of the for loop.

Anyways, I just wanted to show two solutions to the same problem, and some interesting ways of thinking. I’ll look into benchmarking the two pieces of code on very large arrays just for fun. The results won’t mean anything on such a small problem, but it’d be interesting to see if an if statement inside a loop affects performance in any way.

Tagged , , , , , ,

Taking a photo of a flower with a white background

Untitled, originally uploaded by Vlad003.

This photo was taken outside in the sun. The flower was in a vase with a few other tulips.

I used my on camera flash to act as a fill flash. I had the flash exposure comp to +1/3; I tried both 1st and 2nd curtain flash but due to the fast shutter speed, there was no perceptible difference.

As can be seen from the shadow at the top of the flower, the sun was from to the of the picture. The vase of flowers was on the ground and my camera was on a tripod looking down at it.

The set-up

I wanted a white background and I played with various ways of having holding a piece of paper behind the flower. A side shot of the flower, however, wasn’t what I wanted, so I came up with the following set up.

I cut half way into a piece of paper and made a small hole in the center for the stem of the flower to fit through; I then taped the cut in the paper back together. The paper, however, didn’t stay flat so I taped a wire along one edge; a side effect of this was that I could bend the wire and make the paper stay at any height and angle I needed.

Post processing

Post processing was very easy. All I needed to do was

  • use the magic wand with a threshold of 50 to select the white paper (the paper was very shadowy)
  • blur the selection using 10px so that I get a smooth selection around the flower
  • fill the selection with white

I, of course, sharpened the photo a bit as well.

Conclusion

This was an interesting photo to take. I’m really happy with how it turned out; now that I think about it, a year ago, I wouldn’t have thought of doing this at all. I’m actually quite happy with how far my photography’s improved over the last 2 years :D (I was looking at very old photos on flickr)

Oh and “Where there’s a will, there’s a way!” :)

Remembering the Apple I (via Technologizer)

A nice read. I enjoy reading about computer history :)

Remembering the Apple I Thirty-five years ago this month, a couple of geeky young members of Silicon Valley's Homebrew Computer Club founded a company to sell a new type of device–which almost nobody had heard of yet–known as a personal computer. The geeks were Steve Wozniak and Steve Jobs, the computer was the Apple I, and the rest is history. Only two hundred or so Apple Is were built; maybe a quarter of them survive. But it was an significant machine in its day, an … Read More

via Technologizer

Disqus and the Simple Things theme on Tumblr

I recently changed my tumblr theme, and I noticed the Disqus comments didn’t work properly. Looking at the HTML, I noticed that there was the code needed to have the Disqus comments, but for some strange reason, it wasn’t working as intended.

Here’s my fix.

1. Put this right above the {block:Permalink}, replacing “SHORTNAME” with your Disqus shortname :

// <![CDATA[
javascript">var disqus_url = "{Permalink}"; var disqus_title ="{block:PostTitle}{PostTitle}{/block:PostTitle}";
// ]]>

2. Replace the stuff in the {block:IfDisqusShortname} (after the {/block:Posts}) with this:

<div id="disqus_thread"></div>
<script type="text/javascript">
/**
* var disqus_identifier; [Optional but recommended: Define a unique identifier (e.g. post id or slug) for this thread]
*/
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://SHORTNAME.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<div class="disqus-credit">
{lang:Blog comments powered by Disqus 2}
</div>

NOTE: I also got rid of all the {block:IfDisqusShortname} (and close blocks) because I noticed that for some reason it didn’t show. It seems that tumblr just uses that to only show things that are relevant (if you don’t have a Disqus shortname, you don’t need to show Disqus comments). I’d suggest trying the above without deleting the block declarations, but if that doesn’t work, remove the declarations.

NOTE2: Wherever it says {text: Disqus Shortname}, replace that with your shortname. Tumblr should do it automatically, but it seems that it doesn’t, and breaks the code.

WARNING: If you delete the “share-links” div, it’ll make all your text go red. I’ve got no idea why, but it just does.

Tagged , , , , , , , , ,

Testing Tumblr feed reader

Disregard this post. It’s just a test to see if the Tumblr “post rss feed” feature works properly. I’m not sure if I did it right, so I’m testing it.

Raindrop photo

Untitled, originally uploaded by Vlad003.

So this is another shot I took a while ago (Feb 6th). I really like how the focus turned out here. It was fairly difficult to focus properly because I had a small depth of field and it was a small object I was focusing on.

I love my 50mm because it can keep the rain drop in perfect focus while blurring everything around. I’m currently learning about how lenses work in Physics so I may actually understand why the branches in the raindrop are in focus :)

Plant photo on flickr

Untitled, originally uploaded by Vlad003.

This is an older photo I took and uploaded on flickr, but I never posted on here.

I did a bit more editing with the color curves on this one and added a bit more blue.

I took this with my 50mm f/1.8 lens and I’m actually quite happy with how it turned out :)

Save and Quit

So it seems that by default, Firefox 4 doesn’t have the “Save and Quit” option enabled. This is when you quit fire from through File > Quit or CTR + Q, it would ask you if you want to Quit or save the current tabs and then quit:

Firefox 4 simply quits when you close it. This is really annoying since I regularly use CTRL + W for closing tabs and the Q is right beside it.

How to fix it

  1. Type about:config into the address bar and hit ENTER.
  2. In the filter box, type browser.showQuitWarning.
  3. Double click browser.showQuitWarning so that the Value field becomes true

And then you’re all set!

One thing to note: If in your preferences you say that when you start Firefox, you want it to open all the tabs from before, it won’t show the Save and Quit dialog. It’ll just quit.

Firefox 4

I recently installed Firefox 4, and I must say I love it!

There are 2 main things that make it so awesome: app tabs and tab groups.

App tabs

So the first thing I really like about this new version of Firefox is app tabs. You make an a tab into an app tab by right-click > Pin as App Tab. The tab then gets moved to the left of the tab bar and you only see its icon.

Advantages of app tabs over regular tabs:

  • CTRL + W doesn’t close it. That’s the shortcut that closes a tab, but it doesn’t affect app tabs. You can still close the app tab by the regular Right-click > Close tab. This is nice because I use the shortcut all the time, but I want the app tabs to be there all the time, and I don’t want to accidentally close them.
  • It turns blue when there’s a change on the page. So if I get a notification or someone chats with me on facebook, the tab turns blue to alert me. If I’ve got GMail open and I get a new email, the tab turns blue as well (this only happens if I’m on the inbox or priority inbox page. If I’ve got an email open and I get a new one, the tab doesn’t turn blue)
  • They’re there in each tab group (more on this below!)

Tab groups

Although app tabs are awesome and useful themselves, they certainly don’t beat the usefulness of tab groups.

I’m the kind of person that has 30 – 40 tabs open at once (if you’ve got less than 10 tabs open, you’re using the internet wrong.) The worst part of having this many tabs open (if you’ve only got 1 window open) is that you have to scroll through all of them to find the one you’re looking for. Most of the time, I never look at the ones near the beginning so I don’t actually read them. I just open new tabs. (I click on any link that seems interesting but I never actually get a chance to read any of them).

With tab groups, you can just group all the tabs so you only see relevant on the screen at once. The app tabs are there on each tab group as well.

I’ve noticed that I’m actually reading and closing more of the tabs. I’ve got a tab group with a few Craigslist pages that I just refresh every once in a while to see if anyone’s selling anything interesting. In that group, there are only Craigslist ads so they don’t clutter my other tab groups.

Screenies!

So here’s what the tab groups look like. And look! There’s a search button (top right). You can search the names of your tabs so you can find that one tab quickly!

And this is what it looks when you’re looking at one tab alone. Note the app tabs on the left.

Follow

Get every new post delivered to your Inbox.