Archive

Posts Tagged ‘Programming’

SWT “Event model”

July 6th, 2010

Have a look at this documentation for a VerifyEvent in SWT:

void VerifyListener() {…}.verifyText(VerifyEvent e)
Sent when the text is about to be modified.

A verify event occurs after the user has done something to modify the text (typically typed a key), but before the text is modified. The doit field in the verify event indicates whether or not to modify the text.

Wait, what?

What we basically want is a simple predicate function that returns true if the Contents of a Text Field are still valid after a change. What SWT gives us is this awkward event model where we have to modify the event that has just been generated. (In my opinion, events should be immutable, since they represent a historical occurence.) Next SWT will have a peek in the event to see how to proceed.

SWT is full of weird bagbiters like this.

Programming ,

while true: Compile; Run; Debug

June 1st, 2010

The more I go through this cycle the more it amazes me that this is the development paradigm that won out. That back in the golden era people sat down and decided that this was the model of the future.

For large applications it’s a major pain – much time spent compiling, starting up the program anew and returning it to the state you need in order to test your latest fix. Even for a fairly trivial change or a bit of experimentation, this is a huge timesink.

And yet there is an alternative approach – incremental compilation, à la Lisp. When the Lisp environment hits a bug it pauses. It shows you the location of the bug, it gives you a full stack trace at the time of breakage. You can inspect just about everything. Here’s the kicker: you can fix the code while the debugger is waiting. Then you can load that fixed code right back into the running program and continue on your merry way.

Let me repeat that last bit: You compile only the code that needed fixed and load it into the running program. The running program then continues using the new code. No stopping, compiling, running, getting back to where you were, debugging.

This is special. It’s not even that new. Lot’s of hip, young, dynamic languages are attempting to copy it. Let’s now, in 2010, make an attempt to catch up to the technology of 50 years ago. We owe the founding hackers that much, right?

Self , ,

Eclipse Development Lossitude

May 28th, 2010

Here are two things about Eclipse which recently annoyed me. (I imagine it’s Eclipse’s fault, I guess It may be Java’s.)

1) When you reach an exceptional condition, the correct response in debug mode is to freeze the program and allow the developer a chance to inspect the current state. Stack, Heap, location, all that good stuff.

Throwing your arms in the air, screaming bloody murder and throwing away all the useful information when an error occurs is not useful. It turns debugging java into a game of “How close can you get to an error, without actually reaching the error.”

If you reach the error you lose the game, along with any useful data that might help you fix it.

2) You only seem to allow me to put breakpoints on lines on code. This implies that I already know where an error is. If I did, I’d probably fix it.

Why can’t you let me break on more useful things like when a particular variable has a particular value. This is similar to the previous point where I don’t want the program to drop everything and run away before I can look into it.

3) In 2010, the best way to debug a Java program is to pepper it with Print statements. This is sad.

Self , , ,

Fibonacci Optimisation

May 6th, 2010

Just some stuff I thought about today. Here’s a fibonacci function expressed in Lisp:

  1. (defun fibonacci (n)
  2.   (if (<= n 1)
  3.        n
  4.        (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))

It can be used to compute the fibonacci sequence:

  1. => (mapcar #’fibonacci ‘(1 2 3 4 5 6 7 8 9 10))
  2. (1 1 2 3 5 8 13 21 34 55)

It’s simplicity is elegant, but, frightfully inefficient. In fact, the recursive definition of fibonacci is often used as an example of an inefficient method. Let’s look at why it’s poor. When fibonacci is called for a value of n there are two possible paths the program can take:

  1. If n <= 1 give back the value of n
  2. otherwise return the sum of the previous two numbers in the sequence

So, if n is 0 or 1 then the value is simply 0 or 1 respectively. This is the base case of the function. In other words, from this piece of concrete knowledge, we can derive the remaining values. If n is any value higher than 1, then we need to actually compute what it is. Notice that this case requires fibonacci to be called another two times.

This imposes significant overhead on the machine. In addition to this, the results of these two function calls must be added together. That means we need to hold onto some space in memory to store the results. Simplistically, we refer to the number of significant function calls as the time complexity of the program, and the amount of memory required as the space complexity. Fibonacci sure is expensive.

Anyway, this got me to thinking. What is the main problem with fibonacci? It’s the fact that it must repeat a lot of its calculations. If we want to find the value of Fib(5), we must call Fib(4) and Fib(3). But wait: To find the value of Fib(4) we must call Fib(3). Hence, we do the same operation twice. What if we could tell the program to remember a value once it had been found? Wouldn’t this speed things up? Can this be done without sacrificing the simplicity of a recursive method?

Here’s a modified, partial fibonacci function:

  1. (defun hashed-fibonacci (n)
  2.   (defvar fib-lookup (make-hash-table))
  3.   (let ((val (gethash n fib-lookup)))
  4.     (cond ((not (equal val nil)) val)
  5.           ((<= n 1) n)
  6.           (t (let ((new-val (+ (hashed-fibonacci (- n 1)) (hashed-fibonacci (- n 2)))))
  7.              (progn (puthash n fib-lookup nil new-val)
  8.                                 new-val))))))

This one is a little more involved, but don’t panic: It still does the same thing, in much the same way. It has an extra trick though: Before it attempts to compute the value of n, it check to see if it already has a value. It looks in a structure called a hash table (any type of lookup table should do). Think of this like a telephone directory. If you know someone’s name, you can look it up in a phone directory and it will tell you their number. In our hash table, if you know a value of n, you can look it up and find its fibonacci value. Of course, some fibonacci values won’t be listed just yet. If there is no value in the table, we continue with our normal process: If n <= 2 then return 1. If n is greater than 2 then we find it’s value by adding the previous 2 fibonacci numbers. Now we have one more change to make: Having just found this new value of Fib(n) we store it in the hashtable. This means we won’t have to do the hard work of finding it again later – It’s already there!

Now, this act of remembering our previous work means that we must use a bit more memory, but the gain is a remarkable improvement in speed. Today, memory is pretty cheap, so this is not a bad thing. Look at the method we used. We start with a function that must call itself with a smaller value in order to discover a new value. When we discover a new value, we store it in a table so that we can quickly find it later.

This could most likely be generalised for any function that follows this pattern. There’s another blog post for when I get time to look into that aspect of it. If this post was about the optimisation, the next will be about abstracting that into a common pattern.

I hope this was of some interest. It was just a little thing I thought about this afternoon then decided to try it out. After I tried it I thought it might make a quick, informal blog entry.

Update: It seems that I have inadvertently stumbled across the definition of memoization which was conceived in 1968! It’s fun to try something out and then learn about a formal definition of the same principle. The act of developing an example gives it more meaning. (Further reading: http://en.wikipedia.org/wiki/Memoization).

Programming , , , , ,

C++ Templates for XCode 3.2

November 19th, 2009

Here are a couple of Project templates I made for XCode 3.2. One for a WxWidgets based project (wxMac 2.8), and one for a GLUT project. Hope they work.

  • GLUT C++ Project – Initializes GLUT and creates a scene containing a cube which can be rotated using the keyboard arrow keys. toggle an axis widget using ‘w’, toggle fullscreen using ‘o’ and exit using ESC. The FPS is displayed in the titlebar.
  • WxWidgets C++ Project – Initializes a WxWidgets based app with an empty frame.

Programming , , ,

Nethack on OS X 10.6 (Snow Leopard)

November 13th, 2009

O.K. So, this is kind of a followup to a previous post I did about how I like to setup Nethack on my Mac. However, more recently, some of the patches I had used stopped working on later versions of Mac OS (10.5 and 10.6). So I spent a bit of time looking into this today and I got some positive results. (update: I think the problem I had with Menucolor compiling was that it didn’t like the regexp method – I changed this to simply use the wildcard matching.)

Nethack with Status Colors and Menu Colors

Nethack with Status Colors and Menu Colors

Unfortunately, because the two patches I’m applying have resulting conflicts- it meant manually applying the patches to the source code in some cases (also: I’m lazy). I, therefore, don’t have an elegant method of actually applying the two patches that I can pass on. What I am doing instead is providing two things: The complete refined archive of the patched Nethack source which should be ready-to-compile on OS 10.6; And also the .diff file produced from a vanilla copy of the source and my own patched version. I will also provide my new updated nethackrc file. (ok… 3 things :-) )

Here’s some details about the setup this provides:

  1. The Status Colors patch is applied. This is a configurable patch allowing you to color code status effects – hunger, blindness, HP, Gold, AC, etc. It’s very, very cool! :-)
  2. Menucolors patch applied. This is a configurable patch that let’s you apply colors to popup menus. e.g. inventory items can be red for cursed, green for blessed, etc. Again, this patch is very neat!
  3. The initial configuration for getting Nethack to build on mac has been taken care of.

So Here are the links to get everything up and running. I should say at this point that this stuff works on my machine and YMMV. If something is broken and you want my to take a look at it just leave a comment of send an email – I’ll try to fix it if I have time. You may also want to dig through the changes in the patch.

  1. nethack-3.4.3-patched.zip
  2. nh343-_menustatus_orig.diff
  3. .nethackrc

I hope this is useful for someone who wants a nice shiny setup of Nethack on Snow Leopard. :-)

Programming , , , , ,

Snow Leopard can DIAF

September 16th, 2009

Hurray! Apple fanboys should be pleased with the release of OS X, version 10.6. Snow Leopard panders to their desire for an all Apple platform. For the rest of us sensible users, Apple have screwed the pooch.

Okay, we have new shiny toys like Quicktime X and – well, that’s about the height of noticeable changes. I’m all for enhancing the user experience, but in this case, in my opinion, it has come at the expense of developer comfort.

What I’m referring to here is the lack of Java support in the new XCode 3.2. I’ve always felt that XCode was a fairly elegant environment for writing all C/C++, Java and Objective-C projects. So- why, Apple, would you arbitrarily drop support for a language? Out of spite? You didn’t even drop support – you just made it frigging irritating to use. Do you enjoy kicking your users in the nuts with each new release?

I’m not even surprised at this stage. I guess I could add the XCode templates back in manually but I’m more in favour of adopting a more portable command line build process… It seems the best way to get away from Apple’s user abuse.

Programming , , , ,

Quick Org-Mode Hacks

February 25th, 2009

Recently , I’ve come to rely on Emacs for more or less everything I do on a computer. Of course, in work there are some exceptions: We must use Outlook for emails (the bulk), various windows only business tools (the cruft), etc.

But, as far as possible I will use Emacs because I love the simplicity, speed and extensibility.

In particular, I have discovered org-mode which has now taken over my personal scheduling routine. Org-mode is a personal planner for emacs which allows the user to: Create todo lists, schedule items for certain dates, mark items complete, use checklists, add tables. It’s impressive the amount of features this small, text-based operating system can offer.

So here’s some quickie hacks I’ve started working at for org mode. My wishlist is as follows:

  • [X] Store all org-mode schedules together
  • [X] Custom org save function (facilitating above)
  • [   ] Strip TODO/BUG/FIXME lines from source code and:
    • Store in org file called “<project name>”
    • insert links back to source file
    • add tags based on: language, filename, type

The third item is still in progress but I’ll explain my current org setup now and provide some expressions for the customisation:

;; Org Mode
(global-set-key "\C-cl" 'org-store-link)
(global-set-key "\C-ca" 'org-agenda)
(add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
(setq org-log-done t) ;timestamp on completion

The first two lines create global keyboard shortcuts (key-bindings) which are available from anywhere within Emacs. ‘Ctrl-c l’ will store a link to a url or file, ‘Ctrl-c a’ will open your org-mode agenda (where you can view your calendar, appointments, todo items. This is the thing I have come to rely on :-) )

the add-to-list command tells Emacs to use org-mode by default for any file with a .org extension. the last line sets the org-log-done variable to true: This means that when we mark a todo item as complete it will be timestamped with the completion date. I like this feature.

So that’s just a bit of simple customisation. Now I’ll add a couple of functions that take care of saving my tasks.

(setq org-mode-file-dir "~/.emacs.d/org-files")
(setq org-agenda-files (append (list org-mode-file-dir)
org-agenda-files))

These two functions set variables telling emacs where to find org-mode files containing agenda items. The first is my own private directory added to behave as a default location for saving.

(defun smh-org-mode-save-buffer ()
(interactive)
(if (equal nil (buffer-filename))
(let ((input (read-from-minibuffer "Org Topic: " (buffer-name))))
(write-file (concat org-mode-file-dir input ".org")))
(save-buffer)))

Next I added a custom save function which simplifies the process of saving. If the current buffer is not already linked to a file (buffer-filename is nil) then it will prompt for an Org Topic. I like to think of organising things by topic. The default topic will be the name of the buffer if you supplied one previously. When a topic is given it will store the file as .org in the org-mode-file-dir. One the other hand, if the buffer is already linked to a file it will simple save as normal.

(add-hook 'org-mode-hook
(lambda () (define-key 'org-mode-map "\C-x\C-s"
'smh-org-mode-save-buffer)))

Finally I created a mode-specific key binding: I do this by adding a hook to org-mode… This means whenever org-mode gets called the hooked functions will also be evaluated. I have redefined the ‘save’ keystroke for org-mode to call my custom save function.

This is what I have so far and I find it quite helpful for organising Tasks and Todos manually.  My next step is to analyse source code and look for TODO, BUG or FIXME lines and create org-mode files automatically.

Programming , , , , , , ,

Protecting Code from Uncertainty

February 3rd, 2009

if (2 > 5) {
fprintf( stderr, "This shouldn't happen!\n" );
} else {
//continue as normal
}

It really amuses me when I see code sections commented as “This shouldn’t happen” … It usually means that the programmer is about 98% certain that no condition will occur in which the code is executed. However, just in case the fundamental laws of the universe suddenly collapse, that particularly obscure error will be correctly handled.

Programmers care about the correctness of programs even under the most unlikely scenarios.

Programming , ,

GLUT on Mac OS X

January 30th, 2009

I was having a problem using Glut (GL Utility Toolkit) on my Mac today – despite the number of sites saying that it was a snap to set up:  ”Just add the GLUT.Framework to your project and compile.”  – Well, my program was compiling OK, but running it would always result in a “bus error” and drop into the debugger.  I tried various combinations of compiling from command line, running under X11, trying port and fink for different libraries – What could this weird problem be?

I eventually came across the root of the problem and since I haven’t seen it posted anywhere on the web I decided to add my own contribution to the “GLUT on OS X” billboard.  I’ll try to give the complete setup I used to start a Glut project in XCode.

Setup XCode Project

Like many others will suggest, open XCode (or project builder) and create a Standard Tool (or C++ Application or whatever). I recommend a Standard Tool because you just get a basic main.c file and that’s enough. Add the GL.Framework and GLUT.Framework files from /System/Library/Frameworks.  (This is where they are on my Mac)

Rename the file main.cpp/m to main.c for a basic C application.  (I’ll stick with this for now as it is sufficient)

Modifying the standard code

Headers need to be changed from gl/ to OpenGL/ and GLUT/ in order to correctly locate the headers in OS X’s frameworks.  The top of main.c should read as follows:

  1. #include <OpenGL/gl.h>
  2. #include <OpenGL/glu.h>
  3. #include <GLUT/glut.h>

And here’s the bit that was killing me.  Most of my glut code is based on the skeleton provided from NeHe’s tutorials which initialise glut then initialise opengl then sets up glut’s window properties. like so:

  1. int main ( int argc, char** argv ){
  2.     glutInit ( &amp;argc, argv );
  3.     initGL ( );
  4.     glutInitDisplayMode ( GLUT_RGBA | GLUT_DOUBLE );
  5.     glutInitWindowSize ( 500, 500 );
  6.     glutCreateWindow ( "NeHe’s OpenGL Framework" );
  7.     glutDisplayFunc ( display );
  8.     glutReshapeFunc ( reshape );
  9.     glutKeyboardFunc ( keyboard );
  10.     glutSpecialFunc ( arrow_keys );
  11.     glutMainLoop ( );
  12.     return 0;
  13. }

OK, everything looks good right?  Not for OS X apparently.  Maybe this is obvious for some people but I had to trace a bit to see what was causing my problem.  As it turns out I was able to fix it by moving the initGL call after all the glutInit*/glutCreate* calls.  Thus, my new main looks as follows:

  1. int main ( int argc, char** argv ){
  2.     glutInit ( &amp;argc, argv );
  3.     glutInitDisplayMode ( GLUT_RGBA | GLUT_DOUBLE );
  4.     glutInitWindowSize ( 500, 500 );
  5.     glutCreateWindow ( "NeHe’s OpenGL Framework" );
  6.     initGL ( );
  7.     glutDisplayFunc ( display );
  8.     glutReshapeFunc ( reshape );
  9.     glutKeyboardFunc ( keyboard );
  10.     glutSpecialFunc ( arrow_keys );
  11.     glutMainLoop ( );
  12.     return 0;
  13. }

I hope this is helpful to someone else since it seems to be a rather obscure error (that only affects Mac OS?).  I’m glad I caught it though – as much as I intend to use Cocoa in the future, it’s nice to know a simple framework is still available. :-)

Programming , , , , ,