Wed, 02 Jul 2008
Tonight on the Telephone.
Its a little after 7pm and the phone rings. I answer.
Me : Hello.
Faint music on the other end.
Me : Hello!
Music continues.
Me : Hello !!!
Some Marketer : Yes, good morning, blah, blah, blah. Would you be interested in cheap holidays, blah, blah, blah.
Me : Tell me more.
Marketer : Well, you can go here and you can go there. Blah, blah, blah.
Me : That sounds interesting.
Marketer : Blah, blah, blah.
Me : That sounds good.
Marketer : Blah, blah, blah.
Pause.
Me : Can I bring my pony?
Marketer : Excuse me?
Me : Can I bring my pony?
Clunk, the marketer hangs up.
I managed to waste 1 minute 38 seconds of his time. I need to do better next time.
Posted at: 21:48 | Category: | Permalink
Sun, 29 Jun 2008
Goodbye Old Car.
For the last 8 or 9 years I've been driving this very nice 1985 BMW 323i.
However, the new apartment has off-street parking but not under cover parking. An old car like this would simply not survive being parked out in the open so I've had to sell it rather than see it rust away. It was sold a little over a week ago.
Goodbye old car.
Posted at: 14:29 | Category: NewHouse | Permalink
Mon, 16 Jun 2008
Goodbye Old House.
For the last eight years, my wife and I have enjoyed the room in this picture (with that view) as our main living area. This apartment was more than big enough for the two of us, but with the arrival of our daughter five and a half years ago, it has been increasingly cramped.
After a long, long search, we found and bought a new apartment a couple of months ago and we take possession of the new place this week. We'll have about 5 days to move between houses and then we'll have to say goodbye to this wonderful home which we have enjoyed so much.
Posted at: 19:22 | Category: NewHouse | Permalink
Fri, 06 Jun 2008
FP-Syd #4.
Last night was the 4th meeting of FP-Syd, the Sydney Functional Programming group. First up I'd like to thank Shane, James and the other Googlers who organised the use of one of Google's Sydney meeting rooms and laid on drinks and a bunch of tasty snacks. Another big thanks goes to our speakers for the evening and the 32 (!!!) people who showed up.
Unfortunately one of our planned speakers for the night had to drop out at the last minute. This meant that as people arrived I was asking them if anyone had a short talk they could give at very short notice. The thing that impressed me the most was that we got two offers.
First up we had Sean Seefried talk about using Ocaml at Nicta to write Nicta's Goanna static type checking tool for C and C++ code. It was interesting that they were using an existing commercial C and C++ parser and the converting the C abstract syntax tree (AST) produced to an Ocaml AST where they work on it further. Also interesting was that the chose Ocaml because it was a good language for writing compilers as well as having reasonably good and highly predictable performance. This was an excellent talk considering that Sean had about 10 minutes to prepare. Thanks Sean.
The next speaker was Scott Kilpatrick who also had about 10 minutes to prepare as well as being our first international speaker. Scott has just recently completed two B.S. degrees (one in Computer Science, the other in Mathematics) from the University of Texas at Austin and will be starting a Masters there in September. He's is currently interning at Google here in Sydney working on the Google Maps project.
Scott gave us a very interesting introduction to SUN's Fortress language. Scott is working on implementing the type checking system for the Fortress compiler rather than being a dedicated user of the language. He was however able to give us a brief overview of the language, which is designed to replace Fortran in high performance computation tasks. Fortress seems to have a huge array of interesting features and is definitely something to keep an eye on. Thanks Scott.
Finally we had Tim Docker speaking about writing a Tuple Server in Haskell using the State Transactional Memory monads in concurrent Haskell. Tim did a great job explaining what Tuple Servers are and what they are used for where he works at Maquarie Bank. He then talked about the monads in Haskell, in particular the STM monad and its use in his tuple space server. It was a great talk and I mid way through it, I realised that a tuple space server is a nice solution to an architectural problem I have. Thanks Tim.
After the talks we retired to the Redoak hotel for a few beers and a chat. Since a couple of people had missed the previous meeting, Ben Lippmeier, was kind enough to pull out his laptop and give his talk on "The Disciplined Disciple Compiler" again. Interestingly for me, he went into a little more detail on areas that he glossed over in the last meeting. DDC is a really interesting piece of work, being a strictly evaluated dialect of Haskell, with optional lazy evaluation (far more elegant than the way Ocaml does it) and with side effects and destructive updates looked after in the type system. The ideas behind DDC are really compelling. I look forward to seeing it progress. Thanks Ben.
Posted at: 22:18 | Category: FP-Syd | Permalink
Thu, 29 May 2008
Keeping Up With ....
Here's my pathetic attempt at keeping up with Steve Hanley, Jon Oxer and Mike Beattie.
From left to right:
- My Dell Latitude X1 laptop running Enlightenment E17 on an Ubuntu Hardy base system. The desktop background is a picture of my lovely daughter.
- A windows machine which is used mainly as a host for Firefox and the Tortoise SVN client. I spent the first six months in this job doing windows development. Fortunately that is all in the past.
- My Linux desktop system, again running E17, but on an Ubuntu Gutsy base system.
- One of our very cute bCODE scanners, which has just been PXE booted to a slightly modified Ubuntu Dapper installation, but before having over 100 of bCODE's own Debian packages installed on it.
- A second bCODE scanner running its Adobe Flash GUI on top of an Ubuntu Dapper install done by cloning a disk image.
The Linux and windows machine share a keyboard and a mouse via the magic of Synergy2. The keyboard is my favourite Dell Enhanced USB Multimedia Keyboard.
The one thing missing from the above photo (two separate pictures taken and stitched together by my colleague Peter) is the whiteboard which is directly behind my seat. Yes, I have my own personal whiteboard and I love it.
Posted at: 21:54 | Category: Tech | Permalink
Sat, 24 May 2008
Objects vs Modules.
Although I've been using Ocaml for a several years now, I've not yet been in a situation where I've needed to write an Ocaml class to define a C++/Java/Python/Smalltalk/OO style object. I've found that most of the problems I encountered could be easily solved using functional code and that Ocaml's objects didn't provide an obviously better solution. Until now (or so I thought).
The problem was one of moving around the filesystem keeping track of the old directories so they were easy to return to. The obvious model for this was the pushd and popd built-ins in command shells like GNU Bash. This functionality can be easily wrapped up in an Ocaml object as in the following example and demo code (which needs to be linked to the Unix module):
class dirstack = object
val mutable stack = []
method push dirname =
(* Find the current working directory. *)
let cwd = Unix.getcwd () in
(* Change to the new directory. *)
Unix.chdir dirname ;
(* If successful, push old cwd onto the stack. *)
stack <- cwd :: stack
method pop () =
match stack with
| [] -> failwith "Directory stack is empty."
| head :: tail ->
Unix.chdir head
end
let () =
print_endline (Unix.getcwd ()) ;
let dstack = new dirstack in
dstack#push "/tmp" ;
print_endline (Unix.getcwd ()) ;
dstack#push "/bin" ;
print_endline (Unix.getcwd ()) ;
dstack#pop () ;
print_endline (Unix.getcwd ()) ;
dstack#pop () ;
print_endline (Unix.getcwd ())
However, there are some problems with the above code. Firstly, if the push and pop methods need to be used throughout the program, the dstack object needs to be made more widely accessible using one of the following three methods:
- Being placed in the global scope.
- Being made into a Singleton objecct.
- Being passed around as a parameter to whatever function may need it.
Yuck! Yuck! Double yuck! Suddenly, this object oriented solution didn't look like such a great idea.
Then it struck me. This object can be easily transformed into an Ocaml module like this:
module Dirstack = struct
let stack = ref []
let push dirname =
(* Find the current working directory. *)
let cwd = Unix.getcwd () in
(* Change to the new directory. *)
Unix.chdir dirname ;
(* If successful, push old cwd onto the stack. *)
stack := cwd :: !stack
let pop () =
match !stack with
| [] -> failwith "Directory stack is empty."
| head :: tail ->
stack := tail ;
Unix.chdir head
end
let () =
print_endline (Unix.getcwd ()) ;
Dirstack.push "/tmp" ;
print_endline (Unix.getcwd ()) ;
Dirstack.push "/bin" ;
print_endline (Unix.getcwd ()) ;
Dirstack.pop () ;
print_endline (Unix.getcwd ()) ;
Dirstack.pop () ;
print_endline (Unix.getcwd ())
This solution using a module is much better than the one using an object. The Dirstack module itself is globally accessible and is already a singleton while the stack used to hold past directories is implemented as a list whose scope is limited to the module itself. (Furthermore, if Dirstack is implemented in its own file instead of using a module defined within a larger file, then the stack variable can be hidden completely by not listing it in the Dirstack interface file.)
So while I'm pleased with this solution, it does mean that I'll have to continue my hunt for a problem where an object provides a better solution than any other feature of the Ocaml language. This is particularly ironic because when choosing between two strict statically typed languages, Haskell and Ocaml, I chose Ocaml because I thought I needed objects. However, I stuck with Ocaml because of its pragmatism.
Posted at: 07:45 | Category: CodeHacking/Ocaml | Permalink
Sun, 20 Apr 2008
Cross Compiling for Legacy Win32 Systems (Part 2).
Cross compiling from Linux to Windows requires the installation of a couple of packages. On a Debian or Ubuntu system this can be done using:
sudo apt-get install build-essential sudo apt-get install mingw32 mingw32-binutils mingw32-runtime wine
I'm running Ubuntu's Hardy Heron pre-release and the following is known to work with these versions:
mingw32 4.2.1.dfsg-1ubuntu1 mingw32-binutils 2.17.50-20070129.1-1 mingw32-runtime 3.13-1 wine 0.9.59-0ubuntu5
For an example of a project which can be successfully cross-compiled, I have chosen libogg which is one of the two libraries required to encode and decode Ogg/Vorbis files. I also happen to know that the current libogg sources in the Xiph Foundation's SVN repository cross-compile from Linux to Windows correctly because I committed the patch to make it possible.
However, we need to look ahead a little. After we have cross compiled libogg we will also want to cross compile the associated libvorbis library which relies on libogg. We therefore need to configure libogg so that when we install it, it can be found by the libvorbis configure script.
For me that meant creating a MinGW32 directory in my home directory:
mkdir $HOME/MinGW32
The next step to to grab the libogg source code from the Xiph SVN server. This can be achieved using the command:
svn co http://svn.xiph.org/trunk/ogg libogg
Changing into the libogg directory, we are now ready to configure, test and install the library. That can be done using:
./autogen.sh
./configure --host=i586-mingw32msvc --target=i586-mingw32msvc \
--build=i586-linux --prefix=$HOME/MinGW32
make
make check
make install
The first command above, runs the auto tools to generate that configure script. The second command, configure is broken across two lines. It sets up the generated Makefiles to compile Windows binaries from a Linux host, with the install directory we set up before. The third line builds the windows version of libogg, the fourth line runs the test suite, with the windows executables being run under WINE and the final line installs everything in the MinGW32 directory created earlier.
All of the above commands should pass without errors. If they don't, check your versions of of the mingw cross compiler tools and/or WINE.
Posted at: 20:51 | Category: CodeHacking/MinGWCross | Permalink
Fri, 18 Apr 2008
FP-Syd #3.
Wow! Just Wow! I've just arrived home after another FP-Syd meeting.
First up we had Jeremy Apthorp with a short talk titled "My Favourite Bugs (that don't exist in functional languages)". Jeremy gave us all a good reminder of why we were all there. It was also a good warm up the second talk.
Ben Lippmeier, gave us a talk titled "The Disciplined Disciple Compiler" which is something he's working on as part of his PhD at Australian National University. Ben's DDC is a compiler for a Haskell dialect named Disciple that uses effect typing to deal with issues like side effects and destructive updates. Unlike Haskell, Disciple is strictly evaluated with optional, explicit lazy evaluation. This was a really thought provoking talk. Thanks Ben.
I would also like to send out a big thanks to Tom and Scott of Atlassian's Sydney office for providing the venue.
After the meeting we headed off the to Readoak hotel for beers and more FP discussion. By 10:30pm we were just about to leave the Redoak when I ran into Damana who used to work at bCODE and who had organized Sydney Geek Girl get together that same night.
Posted at: 00:44 | Category: FP-Syd | Permalink
Wed, 16 Apr 2008
Cross Compiling for Legacy Win32 Systems (Part 1).
My main two FOSS projects, libsndfile and libsamplerate have significant numbers of users that are tied to that particularly odious legacy system, Microsoft Windows. Since I don't normally use Windows myself, maintaining support for that OS has always been a huge pain in the neck.
Originally I shipped Microsoft project files for libsndfile, but that became unworkable because the different versions of the Microsoft tools (Visual C++ 5, Visual C++ 6, Visual Studio 2003, Visual Studio 2005 etc) used different and incompatible project file formats. I solved this by shipping a simple Makefile that used Microsoft's nmake and the command line compilers to build libsndfile. However, by about 2004, the Microsoft compiler's complete lack of support for the 1999 ISO C Standard made maintaining support too much trouble, so it was dropped.
Instead, I started using Cygwin and MinGW to compile libsndfile on Windows. Both of these tool-sets use a version of the GNU GCC compiler just like Linux and building libsndfile using these two tool-sets was trivial:
./configure make make check
Of course there were howls of protest from Windows users, but since they (with a small number of exceptions) had contributed so little, I didn't fell like I owed them anything. I also started releasing pre-compiled Windows binaries at the same time as the source code tarballs were released.
However, while the MinGW compiler was a huge improvement over the Microsoft one it was still a huge pain in the neck. I had to keep a Windows machine and keep it updated and patched against vulnerabilities. Furthermore, installing and updating MinGW was a painful manual process. Oh how I longed for a Debian/Ubuntu style apt-get command to look for and install updates. Finally, copying source code back and forth between Linux and Windows while debugging Windows issues was another pain point because version control systems like GNU Arch and bzr simply didn't work very well on Windows.
In about 2004, I tried the MinGW Linux to Windows cross compiler, a compiler that runs on Linux but generates binaries for Windows. This compiler worked, but left one rather large problem; how do I run libsndfile's rather large and comprehensive test suite? Compiling libsndfile without running the test suite is a waste of time. I did try to run the tests under WINE (the Windows emulator), but at the time tests were failing under WINE that didn't fail on Windows.
From that time on, I would try running the cross-compiled test suite under WINE once or twice a year. Then, some time in the last year or so, the number of problems with the test suite dropped to one, which was only a FIXME message. A little hacking on the WINE sources resulted in a patch that was sent to the WINE mailing list and has since been applied to the main WINE source tree.
With that bug fixed, I can now cross compile from Linux to Windows and run the full libsndfile test suite under WINE. That means that Windows has just become that little bit less relevant that it was before.
A future post will explain how to set up the cross compiler and WINE and walk through compiling and testing of a standard FOSS project.
Posted at: 23:12 | Category: CodeHacking/MinGWCross | Permalink
Fri, 11 Apr 2008
You Stupid Git!
As far as I can tell, the absolute, canonical, got-to-first documentation for the git distributed version control system (DVCS) can be found here:
This documentation seems comprehensive and well laid out. It explains commits, manipulating-branches, merging, collaborative development and the pretty damn interesting rebase and bisect commands. This documentation is called a user manual but it contains sufficient examples to make it a pretty damn fine tutorial.
Normally something like "here's a link to the documentation" would not be worthy of a blog post. However, failure to find the canonical user manual could lead a person (ie me) to post messages to mailing lists saying things like:
"I'm sure git is very clever and all, but its UI and documentation is probably the most user hateful thing I have seen [since] sendmail's cf files."
or, on finding a one hour long video screen-cast tutorial (apparently aimed at all those Ruby on Rails writing Mac OSX users):
"This makes me wonder, how fscked up does a DVCS have to be that you need tens of megabytes of video to show how it works when Bzr and many others can do it with less than ten kilobytes of html text?"
So while I was wrong about the documentation I still have huge reservations about git's user interface and stand by this statement:
"I am currently trying to learn git and I can see very clearly that git is designed by kernel programmers whose normal approach to a user interface is something like a Unix system call."
I'm sure git is a powerful tool and the rebase feature is something I've been wishing for in other systems for some time, but git's UI is already starting to grate.
Posted at: 20:02 | Category: CodeHacking | Permalink
Sun, 06 Apr 2008
Ocaml : Exception Back Traces in Native Code.
Some time ago I wrote a blog post about exception back traces which at the time of that post only existed for the Ocaml byte code compiler.
However, version 3.10 of the Ocaml compiler which was released about a year ago, included exception back traces for native code as well as byte code. With the imminent release of Ubuntu's Hardy Heron, version 3.10 of the compiler is about to become much more widely available .
Enabling exception back traces is as simple as adding the "-g" option to the ocamlopt command line and then setting a single environment variable as follows.
export OCAMLRUNPARAM="b1"
Posted at: 12:48 | Category: CodeHacking/Ocaml | Permalink
Wed, 02 Apr 2008
Goodbye People Telecom.
I don't want to be accused of blogorrhea but I really need to get this off my chest.
I've been a customer of People Telecom since they took over Swiftel in 2004. Since this connection is paid for by revenue generated by SecretRabbitCode I have been on one of their most expensive and highest bandwidth plans. I have been a good customer; my bills were paid by direct debit from an account that always had sufficient funds, I rarely go anywhere near my download limits and as a moderately advanced Linux user rarely, if ever, call their technical support.
However, I am about to end my relationship with People Telecom and this is what led up to it:
- My father needed a new ISP so I suggested that he ring People Telecom. He made the call on the morning of Tuesday, March 25th and signed up. He was told that someone would contact him within 4 days to finalize things.
- On Monday March 30th, over 4 working days after the initial call he rang them again and was told that they had determined him to be a bad credit risk. Now firstly, it was just plain rude for them to have decided this and not told him and stupid for not informing him and trying to find an alternative payment solution. Secondly, my father is not a bad credit risk. He's a self funded retiree, paid off his mortgage over 15 years ago and has never had a credit card. As a credit risk, you don't get much better than this.
- After hearing about this, I rang People Telecom at about 10am to see if there was some way to get my father connected. After negotiating their phone robot and listening to their on-hold music I finally spoke to someone and explained the situation. They said I needed to talk the credit department and switched me though, first to listen to the on-hold music and then to voice mail. I left my details and a message asking them to call me.
- By 6pm that day I still hadn't received a call from the credit department so I called again, negotiated the phone robot, got transferred to the credit department, listened to the on-hold music and then got put through to voice mail. I left a second message.
- At around 8pm I thought I might try and contact them via their web site to try and get this sorted out. Unfortunately, their web site was down and giving SQL errors.
- On Tuesday April 1st at about 9:30 am, I rang again, negotiate the phone robot and got put on hold, but this time there is no music. Thinking their phone system was broken I hung up.
- I try again at about 10am, negotiate the phone robot and got put on hold, but again, no music so again, I hung up. I then tried again to contact them via their web site and this time it worked. Since the web mail form only allowed a limited number of characters I just asked for them to contact me and left my mobile number.
- By lunch time I still hadn't been contacted so I tried to ring again. I negotiated the phone robot, got put on hold, ignored the fact that there was nothing to indicate that I actually was on hold and finally got through to a person.
- I explained the situation briefly and the tech support guy on the other end told me I need to talk to the credit department. I explained that I've tried to talk to the credit department and they didn't return my calls. The tech support guy suggested I talk to the billing department, promises I won't get put on hold, puts me though and I go on hold. Silence.
- After a short period of time a woman picked up the phone and says she has read the case notes but there's not a lot she can do because its a issue with the credit department. I explain my problems with their credit department and ask to be put through to her manager. She agreed and I got put on hold again. Silence.
- I finally got to talk to a manager named Eric. I explain the situation, explain that I have now spent over an hour of my very valuable time and suggest that its time for People Telecom to get this sorted out.
- Eric, the manager suggests I put my fathers connection on my bill. I reply that this is not a good solution because my bill is a company bill, not my personal bill and having my father's bill on my company's bill would complicate accounting.
- I asked if it was possible to direct debit my father's account and if for some reason his account isn't paid, they bill my personal credit card as a fallback. The manager responds that their system isn't able to do this.
- Finally, I suggest that they need to come up with a decent solution to this or they lose me as a customer.
- No solution followed so I told Eric the manager that some time over the next couple of months I will be changing ISPs and then I said goodbye.
- Late Tuesday afternoon I received an email stating that the issue had been escalated to the Manager of the Credit Department and that I should receive a call tomorrow. By the end of Wednesday that call still hadn't come.
I am dumbfounded. I simply cannot remember ever having this kind of run-around and pig-headed intransigence from any other company ever.
I am now searching for a new ISP; one with something like my current 8000k down, 384k up link, about 10 gigs a month with a static IP address and reverse DNS.
Posted at: 20:09 | Category: Tech | Permalink
Sun, 30 Mar 2008
libsamplerate 0.1.3.
About a week ago I released a new version of SecretRabbitCode (aka libsamplerate).
The major change was that the new improved SINC based converters I blogged about here are now the default. There were also a couple of minor bug fixes.
The fine people at Infinitewave have now updated their test results to include the new converter and it shows Secret Rabbit Code comes very close to the best of the commercial converters in terms of quality.
Posted at: 15:11 | Category: CodeHacking/SecretRabbitCode | Permalink
Thu, 27 Mar 2008
FP-Syd #2.
Tonight was the second meeting of fp-syd, the Sydney functional programming group. We had a much more focused group this time with 24 attendees.
First up I gave a short talk on a data structure I had come up with for handling data in a text editor. This data structure was very much inspired by the book, "Purely Functional Data Structures" by Chris Okasaki. All data in the data structure is treated as immutable which means that it is very easy to store past state and to implement undo / redo.
The main talk was split into two parts. First up Manuel Chakravarty gave a talk titled "Monads are Not Scary" and he gave us all an excellent introduction to the topic which I'm pretty sure has convinced all the monad skeptics in the room that monads really aren't anything to be afraid of.
The second part of the main talk, was presented by André Pang who built on Manuel's monad introduction and covered Haskell's Parsec monadic parser combinator library. This too was an excellent talk which explained what seems to be a really elegant tool.
Since the group this week was well over 20 people, we are going to have to look for a bigger venue. Dave Peterson of Orbitec has been a great host for the last two meetings and we would sincerely like to thank him for making his offices available for this bunch of crazy people.
Posted at: 11:54 | Category: FP-Syd | Permalink
Mon, 24 Mar 2008
Cross Compiling with pkg-config.
I'm currently playing with the MinGW cross compiler versions of the GNU C and C++ compilers available via apt-get on Debian and Ubuntu systems. These cross compilers generate windows binaries from a Linux host system which is potentially a much less painful way turning FOSS code into binaries for that particularly odious legacy platform.
Most of the software I'm compiling uses the GNU tools; autoconf, automake, libtool and pkg-config for configuring the software before compiling. Autoconf already has good support for cross compiling and automake and libtool just do what autoconf tells them to do. Pkg-config however is the odd one out.
Pkg-config's job is to retrieve information about installed libraries so that the compiler can find the required header files for inclusion and libraries for linking. For instance, if you wanted compile a program that uses the gconf-2.0 library you could find out the required CFLAGS to be passed to the C compiler and required libraries for linking, by doing something like the following in the Makefile.
GCONF_CFLAGS = $(shell pkg-config --cflags gconf-2.0) GCONF_LIBS = $(shell pkg-config --libs gconf-2.0)
In the above example, when pkg-config is run, it looks in the directory /usr/lib/pkg-config/ and reads information from the file gconf-2.0.pc (each installed library should have one or more of these pkg-config files) which then gets printed out. While the information given by pkg-config would be correct for a native build, it is unlikely to be correct for the cross compiling case.
This issue came up as early as 2003 and there is even a wiki page which suggests some quite extensive changes to pkg-config. Unfortunately I think these suggestions are somewhat fragile and pkg-config itself (I'm using version 0.22) already has features for a better solution.
Like many Unix programs, pkg-config's behaviour can be modified by manipulating certain environment variables. The pkg-config man page explains these variables very well. The first one is PKG_CONFIG_LIBDIR which modifies the default location where pkg-config looks for its per installed library config file. Secondly, the PKG_CONFIG_PATH variable can be set to allow additional pkg-config search paths.
Overriding these two variables results in a MinGW cross pkg-config bash script which I have named i586-mingw32msvc-pkg-config and which looks like this:
#!/bin/bash # This file has no copyright assigned and is placed in the Public Domain. # No warranty is given. # When using the mingw32msvc cross compiler tools, the native Linux # pkg-config executable works fine as long as the default PKG_CONFIG_LIBDIR # is overridden. export PKG_CONFIG_LIBDIR=/usr/i586-mingw32msvc/lib/pkgconfig # Also want to override the standard user defined PKG_CONFIG_PATH with # a mingw32msvc specific one. export PKG_CONFIG_PATH=$PKG_CONFIG_PATH_MINGW32MSVC # Now just execute pkg-config with the given command line args. pkg-config $@
Now autoconf generated configure scripts that realise that the i586-mingw32msvc-gcc cross compiler is being used will run the above script and get suitable information for the cross compiler rather than the native compiler.
The only downside to this solution is that a separate script is required for each cross compiler which uses pkg-config. This however is a minor price to pay and it is unlikely that people will end up with huge numbers of XXXX-pkg-config scripts like was common before the widespread use of pkg-config.
Until a better solution becomes available, this is what I will be using.
Posted at: 13:24 | Category: CodeHacking/MinGWCross | Permalink
Sat, 08 Mar 2008
Progress on the Rabbit.
For over three years now, I have been working on (on and off, but mostly off) a new algorithm for doing audio sample rate conversion in Secret Rabbit Code. The idea for the new algorithm has been rattling around in my head for most of that time, but the problem was always the implementation. While I am making progress it has been slow.
However, a public comparison between a large collection of converters showed that while the conversion quality of Secret Rabbit Code was good, it was nowhere near state of the art.
In order to see if I could get Secret Rabbit Code closer to state of the art quickly, I decided to revisit the existing converter during the xmas/new-year break.
The existing converter had a set of digital filters whose coefficients were generated by a small program written in GNU Octave. My first task was to convert that program to Ocaml which has become my favourite language for technical computing. I then spent quite a bit of time finding and analyzing where the filter design program was loosing precision and finding work arounds. Finally, I spent even more time looking at how the different filter design parameters interact with one another and with the conversion algorithm itself.
Fortunately, all this work has paid off. The result is new versions of the SRC_SINC_MEDIUM_QUALITY and SRC_SINC_BEST_QUALITY converters. The old versions of these converters have been renamed to SRC_OLD_SINC_MEDIUM_QUALITY and SRC_OLD_SINC_BEST_QUALITY. The old versions will be removed once the new versions have been fully validated.
So far, the new converters seem to have significantly improved signal to noise ratio as can be seen from the following to spectrograms (using the methodology described here). It should be obvious from these plots that the new versions of the converters have significantly less artifacts (the purple and blue bits) than the old converters.
Obviously, conversion quality is not the only criterion to evaluate sample rate converters; conversion speed can also be important in some situations. In my preliminary testing, the updated Best SINC converter runs up to 25% slower than the old one. The new best converter also uses significantly more memory than the old one. Storage of filter coefficients has gone up by a factor of 20, which is now over a megabyte for best quality converter alone.
In the tables below I've listed the SNR, throughput speeds and bandwidths as measured by the test suite (the snr_bw_test and throughput_test programs) distributed with the code for a couple of different CPU types.
1.1 GHz Intel Pentium M (32 bit) with 2048 KB cache
| Converter Name | SNR | Throughput | Bandwidth |
|---|---|---|---|
| SRC_OLD_SINC_MEDIUM_QUALITY | |||
| SRC_SINC_MEDIUM_QUALITY | |||
| SRC_OLD_SINC_BEST_QUALITY | |||
| SRC_SINC_BEST_QUALITY |
|
1.8 GHz AMD Opteron 265 (64 bit) with 1024 KB cache
| Converter Name | SNR | Throughput | Bandwidth |
|---|---|---|---|
| SRC_OLD_SINC_MEDIUM_QUALITY | |||
| SRC_SINC_MEDIUM_QUALITY | |||
| SRC_OLD_SINC_BEST_QUALITY | |||
| SRC_SINC_BEST_QUALITY |
|
1.86GHz Intel Core Duo (32 bit) with 2048 KB cache
| Converter Name | SNR | Throughput | Bandwidth |
|---|---|---|---|
| SRC_OLD_SINC_MEDIUM_QUALITY | |||
| SRC_SINC_MEDIUM_QUALITY | |||
| SRC_OLD_SINC_BEST_QUALITY | |||
| SRC_SINC_BEST_QUALITY |
|
A pre-release containing these updated converters is available for download here. Once they have been tested a little more widely I intend to replace the old versions of the converters with the new, higher specification ones.
Anybody who wants to discuss this further should join the SRC mailing list and discuss it there.
Finally, once a version of Secret Rabbit Code with these new converters has been officially released I can get back to the new converter algorithm which should at least match the what I have here in terms of quality but run significantly faster and use at least an order of magnitude less RAM.
Posted at: 14:50 | Category: CodeHacking/SecretRabbitCode | Permalink
Thu, 28 Feb 2008
Inaugural Meeting of FP-Syd.
Tonight was the inaugural meeting of fp-syd, the Sydney functional programming group. Here's a somewhat blurry (sorry, my bad) picture of the attendees.
Across the back from left to right we have; Eric, Ben, Ondrej, Dave, Manuel, Rahul, Shane, André and Ben. At the front, left to right we have Sean, Scott, James and Erik.
I think the night was an absolutely rip roaring success. We met at about 6:30, we each gave an approximately 10 minute each intro of ourselves and our interests in functional program. The meeting then evolved into a general discussion and then at about 8:30 we moved on to Bazaar Beer Cafe for a beer.
Thanks to everyone who attended. It was a huge buzz and I look forward to meeting on a regular basis.
Posted at: 22:51 | Category: FP-Syd | Permalink
Sun, 24 Feb 2008
Functional Programming and Testing.
I read quite a lot of programming related blogs, but its rare for me to find one as muddle headed as this one titled "Quality Begs for Object-Orientation" on the O'Reilly network.
The author, Michael Feathers, starts the post by mentioning that he is dabbling in Ocaml and then makes the assertion that:
"I think that most functional programming languages are fundamentally broken with respect to the software lifecycle."
Now I'm not too sure why he brings up software lifecycle, because all he talks about is testing. However, he does give an example in Java involving testing and wraps up his post by saying that his Java solution is difficult to do in Ocaml, Haskell and Erlang.
Feathers gets two things wrong. Firstly he seems to be writing Java code using Ocaml's syntax and then complains that Ocaml is not enough like Java. His conclusion is hardly surprising. Ocaml is simply not designed for writing Java-like object oriented code.
The second problem is his claim that testing in functional languages is more difficult than with Java. While this may be true when writing Java code with Ocaml's syntax, it is not true for the more general case of writing idiomatic Ocaml or functional code.
So lets look at the testing of Object Oriented code in comparison to Functional code.
With the object orientated approach, a bunch of data fields are bundled up together in an object and methods defined some of which may mutate the state of the object's data fields. When testing objects with mutable fields, its important to test that the state transitions are correct under mutation.
By way of contrast, when doing functional programming, one attempts to write pure functions; functions which have no internal state and where outputs depend only on inputs and constants.
The really nice thing about pure functions is that they are so easy to test. The absence of internal state means that there are no state transitions to test. The only testing left is to collect a bunch of inputs that test for all the boundary conditions, pass each through the function under test and validate the output.
Since testing pure functions is easier that testing objects with mutable state, I would suggest that assuring quality using automated testing is easier for functional code than for object oriented code. This conclusion directly contradicts the title of Feathers' blog post: "Quality Begs for Object-Orientation".
The lesson to be learned here is that if anyone with a purely Java background wants to learn Ocaml or any other functional language, they have to be prepared for a rather large paradigm shift. Old habits and ways of thinking need to be discarded. For Ocaml, that means ignoring Ocaml's object oriented and imperative programming features for as long as possible and attempting to write nothing but pure stateless functions.
Update : 2008-02-26 17:04
Conrad Parker posted this to to reddit and the ensuing discussion was quite interesting.
Posted at: 23:26 | Category: CodeHacking/Ocaml | Permalink
Sat, 23 Feb 2008
Dear Dell
I am customer of yours. I own a Dell Latitude X1 laptop, my wife has an Inspiron 6400 and on my recommendation, my father bought a Dell Dimension 5150 desktop system.
Dell, I think its important for you to know that none of these machines run windows. All of them run Linux exclusively and have from the day they came into our possession. However for all of these systems we had to pay money to Microsoft for operating systems we have never used.
The reason I am writing this now is that the warranty on my Latitude X1 runs out in November of this year. That means that some time between now and November I will be purchasing a new laptop. One candidate for my new machine is the very, very attractive Dell XPS M1330:
When I buy my new laptop, I would like to buy it either with Linux pre-installed or without any OS at all. Since I know Linux very, very well indeed, I do not need Dell to support Linux, just the hardware.
For me as long time, devoted Linux user and developer (professionally as well as FOSS), having to pay money for a Microsoft operating system I don't use is rather offensive. Microsoft has run a long term campaign to thwart the progress of Linux and my money is being used to fund that campaign. For me, this situation in unconscionable.
Apart from the not being able to buy machines without a Microsoft operating system, my experience with Dell has been very good. If I was able to buy a machine from Dell without a Microsoft operating system, buying from Dell would be a no-brainer.
So Dell, here is my challenge for you. Offer me a good looking, high end laptop with lots of juicy options like the XPS with either Linux pre-installed or with no operating system and make sure that these options are reflected in the pricing (ie the Linux or no-OS options should be cheaper than the windows option). If you can do that you are almost guaranteed of keeping me as a customer. If not, I will be looking elsewhere for a company that can meet my requirements. If Dell loses this sale, it will likely lose other sales from my immediate family, friends and employers.
Dell, the ball is in your court. Thanks for listening.
Update : 16:47
Someone posted this to programming.reddit.com and it seems that if you are in the US at least, you can indeed get a Dell XPS with Ubuntu pre-installed. One good thing about the machine offered is that its got an Intel video chipset which I prefer to the Nvidia one. On the downside, its missing some of the options that I can get in the windows version like the solid state disk.
I've just looked again at the Dell Austalia website and I simply cannot find a page where I can get a similar machine. So Dell Australia or Asia/Pacific, what about making Ubuntu an option for the Dell XPS available here in Australia?
Posted at: 10:09 | Category: Tech | Permalink
Tue, 05 Feb 2008
Designing Library APIs.
At Linux.conf.au 2008 I gave a presentation titled "Designing Library APIs: How to Make Users Love Your Library". The presentation went reasonably well and the marvelous people on the LCA08 audio visual team have already posted the Ogg Video.
During the presentation I mentioned a couple of other resources but due to time limitations I never managed to get to that slide. Those resources are:
- Rusty Russell's Interface Simplicity Spectrum.
- Joshua Bloch's "How to Design a Good API and Why it Matters" which is available as a Google video and a set of slides. Although this presentation is geared towards Java, don't dismiss it because the principles are general enough to apply to all languages.
Finally, Brad Hards, one of the attendees at my presentation pointed me to this paper, Designing Qt-Style C++ APIs which seems to be pretty good.
Posted at: 21:40 | Category: | Permalink
Fri, 11 Jan 2008
Microsoft and the POSIX Standard.
POSIX defines a set of functions for retrieving information, such as file size, creation date, last modification date, ownership etc about files on disk. Two commonly used functions in this set are defined as follows:
int stat (const char *path, struct stat *buf) ; int fstat (int filedes, struct stat *buf) ;
The first operates on the filename, and the second operates on a pre-existing file descriptor. Both functions interrogate the file system and fill in a bunch of fields of a struct supplied by the caller.
Microsoft also provides these functions in its C run time library and even documents them here and here. However, stat, the function that is probably more commonly used than fstat, does not always work as expected. In particular, the following scenario:
- Create a new file using the open function.
- Write N bytes to the file descriptor returned by open.
- Call stat on the file using the file name used during file creation.
- Call fstat on the file descriptor returned by open.
On any sane system, the file length field of the struct filled in by stat and fstat calls in the above scenario should be the same. On windows however, they are not, fstat returns the correct value N, while stat returns zero.
With the help from a kind volunteer on the libsndfile-devel mailing list this broken-ness was confirmed on Win2k, WinXP and Vista.
Microsoft; bringing new and improved versions of the DeathStation 9000 to the desk and laptop bag of every programmer. From that wiki page:
DeathStation 9000 (often abbreviated DS9K) is a fictional computer architecture often used as part of a discussion about the portability of computer code (often C code). It is imagined to be as obstructive and unhelpful as possible, whilst still conforming to any relevant standards, deliberately acting unexpectedly whenever possible.
Posted at: 23:21 | Category: Windiots | Permalink
Mon, 17 Dec 2007
Caught up with Anand and Bruce.
I was in London recently and managed to catch up with Anand Kumria and Bruce Badger for a pint and a curry in the Barbican area. I was rather jet-lagged but it was great to catch up with the guys and say hi!
The colors in this picture are a bit weird.
Blame Bruce's camera
.
Posted at: 22:02 | Category: | Permalink
Tue, 04 Dec 2007
Microsoft and the 1999 ISO C Standard.
Any programmer with a better than passing familiarity with the C programming language would know that the current standard for C is the ISO/IEC 9899:1999 standard published in 1999. If they program on Linux systems or use the GNU C compiler they might also know that while GCC is not fully C99 compliant, it does however come pretty damn close. In particular, many of the things listed as broken on the status page are mostly working (Complex, math.h, stdint.h, inline etc) and the things listed as missing are missing because there is probably not a huge demand for them.
In the world of Microsoft however, Visual Studio still has no serious attempt at support for C99 even eight years after the standard was released. Microsoft claims conformance with the 1989 C standard but seems to show little to no interest in even attempting to pursue conformance with the later standard.
In particular, the Microsoft compiler has the following C99 issues:
- snprintf. Microsoft does have a function _snprintf, but its behavior does not comply with the requirements of C99.
- C99 maths functions. The new standard introduced a bunch of new functions including the lrint family of functions.
- A couple of new header files including <stdint.h>. See here for a fix.
- The inline keyword. Microsoft of course has a non standard __inline keyword instead.
- Pre-defined macros like __func__. Again Microsoft has a non- standard __FUNCTION__ macro.
- Variable length arrays.
- Variadic macros.
- The long long type.
These short comings of the Microsoft compiler can make compiling Free Software written in standards conforming C rather difficult with that compiler.
The one that hits me worst with respect to compiling libsndfile and libsamplerate on windows is the lack of C99 maths functions, in particular lrint and lrintf. My current solution for these functions are inline assembler functions. However, Microsoft has just recently joined the world of 64 bit operating systems and their compiler for that platform supports neither the lrint family of functions nor inline assembler functions. WTF?
However, just today, I found out that the GNU GCC, GNU Binutils and MinGW teams have just released MinGW for windows 64. That should make things a little easier.
Posted at: 21:54 | Category: Windiots | Permalink
Sat, 24 Nov 2007
Ocaml Snippet : Sqlite3.
One of the really nice things about using Ocaml on Debian and Ubuntu is the large number of really well packaged third party libraries.
Most of these libraries are also well documented from doc strings extracted from the source code files using ocamldoc. However, the documentation for most ocaml libraries is purely reference documentation and its not always obvious how to use the library simply from reading the reference docs. What's really needed is example code to be read in conjunction with the reference docs.
I'm working on a program where I needed a small, fast easy to administer database. With those requitements, Sqlite is really hard to beat and best of all, someone has already written Ocaml bindings. On Debian or Ubuntu, the Ocaml Sqlite bindings can be installed using:
sudo apt-get install libsqlite3-ocaml-dev
In order to get a feel for using it and take my first steps into the world of SQL (which I'd had very minimal exposure to before now), I wrote a small program to test out the features provided by the library.
The following stand alone program should be taken as an example of how to access a Sqlite database from Ocaml. Since I am not an SQL expert, the actual SQL usage should be taken with a grain of salt.
exception E of string
let create_tables db =
(* Create two tables in the database. *)
let tables =
[ "people", "pkey INTEGER PRIMARY KEY, first TEXT, last TEXT, age INTEGER" ;
"cars", "pkey INTEGER PRIMARY KEY, make TEXT, model TEXT" ;
]
in
let make_table (name, layout) =
let stmt = Printf.sprintf "CREATE TABLE %s (%s);" name layout in
match Sqlite3.exec db stmt with
| Sqlite3.Rc.OK -> Printf.printf "Table '%s' created.\n" name
| x -> raise (E (Sqlite3.Rc.to_string x))
in
List.iter make_table tables
let insert_data db =
(* Insert data in both the tables. *)
let people_data =
[ "John", "Smith", 23;
"Helen", "Jones", 29 ;
"Adam", "Von Schmitt", 32 ;
]
in
let car_data =
[ "bugatti", "veyron" ;
"porsche", "911" ;
]
in
let insert_people (first, last, age) =
(* Use NULL for primary key and Sqlite will generate a unique key. *)
let stmt = Printf.sprintf "INSERT INTO people values (NULL, '%s', '%s', %d);"
first last age
in
match Sqlite3.exec db stmt with
| Sqlite3.Rc.OK -> ()
| x -> raise (E (Sqlite3.Rc.to_string x))
in
let insert_car (make, model) =
let stmt = Printf.sprintf "INSERT INTO cars values (NULL, '%s', '%s');"
make model
in
match Sqlite3.exec db stmt with
| Sqlite3.Rc.OK -> ()
| x -> raise (E (Sqlite3.Rc.to_string x))
in
List.iter insert_people people_data ;
List.iter insert_car car_data ;
print_endline "Data inserted."
let list_tables db =
(* List the table names of the given database. *)
let lister row headers =
Printf.printf " %s : '%s'\n" headers.(0) row.(0)
in
print_endline "Tables :" ;
let code = Sqlite3.exec_not_null db ~cb:lister
"SELECT name FROM sqlite_master;"
in
( match code with
| Sqlite3.Rc.OK -> ()
| x -> raise (E (Sqlite3.Rc.to_string x))
) ;
print_endline "------------------------------------------------"
let search_callback db =
(* Perform a simple search using a callback. *)
let print_headers = ref true in
let lister row headers =
if !print_headers then
( Array.iter (fun s -> Printf.printf " %-12s" s) headers ;
print_newline () ;
print_headers := false
) ;
Array.iter (Printf.printf " %-12s") row ;
print_newline ()
in
print_endline "People under 30 years of age :" ;
let code = Sqlite3.exec_not_null db ~cb:lister
"SELECT * FROM people WHERE age < 30;"
in
match code with
| Sqlite3.Rc.OK -> ()
| x -> raise (E (Sqlite3.Rc.to_string x))
let search_iterator db =
(* Perform a simple search. *)
let str_of_rc rc =
match rc with
| Sqlite3.Data.NONE -> "none"
| Sqlite3.Data.NULL -> "null"
| Sqlite3.Data.INT i -> Int64.to_string i
| Sqlite3.Data.FLOAT f -> string_of_float f
| Sqlite3.Data.TEXT s -> s
| Sqlite3.Data.BLOB _ -> "blob"
in
let dump_output s =
Printf.printf " Row Col ColName Type Value\n%!" ;
let row = ref 0 in
while Sqlite3.step s = Sqlite3.Rc.ROW do
for col = 0 to Sqlite3.data_count s - 1 do
let type_name = Sqlite3.column_decltype s col in
let val_str = str_of_rc (Sqlite3.column s col) in
let col_name = Sqlite3.column_name s col in
Printf.printf " %2d %4d %-10s %-8s %s\n%!"
!row col col_name type_name val_str ;
done ;
row := succ !row ;
done
in
print_endline "People over 25 years of age :" ;
let stmt = Sqlite3.prepare db "SELECT * FROM people WHERE age > 25;" in
dump_output stmt ;
match Sqlite3.finalize stmt with
| Sqlite3.Rc.OK -> ()
| x -> raise (E (Sqlite3.Rc.to_string x))
let update db =
print_endline "Helen Jones has just turned 30, so update table." ;
print_endline "Should now only be one person under 30." ;
let stmt = "UPDATE people SET age = 30 WHERE " ^
"first = 'Helen' AND last = 'Jones';"
in
( match Sqlite3.exec db stmt with
| Sqlite3.Rc.OK -> ()
| x -> raise (E (Sqlite3.Rc.to_string x))
) ;
search_callback db
let delete_from db =
print_endline "Bugattis are too expensive, so drop that entry." ;
let stmt = "DELETE FROM cars WHERE make = 'bugatti';" in
match Sqlite3.exec db stmt with
| Sqlite3.Rc.OK -> ()
| x -> raise (E (Sqlite3.Rc.to_string x))
let play_with_database db =
print_endline "" ;
create_tables db ;
print_endline "------------------------------------------------" ;
list_tables db ;
insert_data db ;
print_endline "------------------------------------------------" ;
search_callback db ;
print_endline "------------------------------------------------" ;
search_iterator db ;
print_endline "------------------------------------------------" ;
update db ;
print_endline "------------------------------------------------" ;
delete_from db ;
print_endline "------------------------------------------------"
(* Program main. *)
let () =
(* The database is called test.db. Delete it if it already exists. *)
let db_filename = "test.db" in
( try Unix.unlink db_filename
with _ -> ()
) ;
(* Create a new database. *)
let db = Sqlite3.db_open db_filename in
play_with_database db ;
(* Close database when done. *)
if Sqlite3.db_close db then print_endline "All done.\n"
else print_endline "Cannot close database.\n"
The above code can be run as a script using:
ocaml -I +sqlite3 sqlite3.cma unix.cma sqlite_test.ml
or compiled to a native binary using:
ocamlopt -I +sqlite3 sqlite3.cmxa unix.cmxa sqlite_test.ml -o sqlite_test
When run, the output should look like this:
Table 'people' created.
Table 'cars' created.
------------------------------------------------
Tables :
name : 'people'
name : 'cars'
------------------------------------------------
Data inserted.
------------------------------------------------
People under 30 years of age :
pkey first last age
1 John Smith 23
2 Helen Jones 29
------------------------------------------------
People over 25 years of age :
Row Col ColName Type Value
0 0 pkey INTEGER 2
0 1 first TEXT Helen
0 2 last TEXT Jones
0 3 age INTEGER 29
1 0 pkey INTEGER 3
1 1 first TEXT Adam
1 2 last TEXT Von Schmitt
1 3 age INTEGER 32
------------------------------------------------
Helen Jones has just turned 30, so update table.
Should now only be one person under 30.
People under 30 years of age :
pkey first last age
1 John Smith 23
------------------------------------------------
Bugattis are too expensive, so drop that entry.
------------------------------------------------
All done.
Posted at: 14:20 | Category: CodeHacking/Ocaml | Permalink
Thu, 13 Sep 2007
GNU gcc and -Wmissing-prototypes.
Many people who code in C consider warning messages optional or if they do enable warnings, use gcc's -Wall warning flag and leave it at that. However, there are a number of problems that gcc can warn about but doesn't unless it is specifically told to do so.
For example, consider a rather trivial example consisting of a main program file (main.c) like this:
#include <stdio.h>
#include "other.h"
int
main (void)
{
printf ("two cubed : %f\n", int_power (2.0, 3)) ;
return 0 ;
}
a second C file (other.c) like this:
double
int_power (int pow, double value)
{
double output = value ;
for ( ; pow > 1 ; pow --)
output *= value ;
return output ;
}
and the header file for the above C file (other.h) like this:
double int_power (double value, int pow) ;
Simple.
Compiling this code at the command line can be done like this:
gcc -Wall -Wextra main.c other.c -o program
which gives no warnings. However, when the resulting executable is run, it gives an obviously wrong result:
two cubed : 0.000000
What the ..... ?
Looking at the code to this rather trivial example, its pretty easy to figure out that the error is caused by the main program and the implementation of the function int_power disagreeing on the order of the two parameters.
In a more complicated real world situation, this can lead to seriously difficult to debug problems. The solution of course is to add the -Wmissing-prototype flag to the gcc command line:
gcc -Wall -Wextra -Wmissing-prototypes main.c other.c -o program
Now the compiler gives us a warning message:
other.c:3: warning: no previous prototype for 'int_power'
To get rid of this warning, the file other.c should include other.h. When we do that, we get a compile error telling us that there is a conflict between the function implementation in other.c and the function prototype in other.h:
other.c:6: error: conflicting types for 'int_power' other.h:1: error: previous declaration of 'int_power' was here
The fix of course is to make the implementation of int_power in other.c match the function prototype. Once that is done, the program compiles and even gives the correct result.
But we're not quite done yet. The behavior of the original broken code is slightly different when compiled with a C++ compiler. Compiling with g++:
g++ -Wall -Wextra main.c other.c -o program
results in an error message:
/tmp/cccTLc2H.o: In function `main': main.c:(.text+0x23): undefined reference to `int_power(double, int)' collect2: ld returned 1 exit status
So how does the C++ compiler know that something is wrong here when the C compiler didn't?
The most important thing to notice is that the error is produced by the linker. Secondly, one needs to remember that C++ (unlike C) allows function name overloading; that is, two (or more) functions can have the same name as long as they all have a unique (ordered) set of function argument types.
In the case above, the C++ linker (which may be the same as the C linker but behaves differently when linking C++ object files) knows the function called from main.c takes two parameters, a double followed by an int. However, the file other.c has a function of the same name, but with the order of the parameters reversed and hence can't be used. Since there is no other function of that name the linker gives an error.
Interestingly, the C++ compiler does not accept the -Wmissing-prototypes warning flag. Personally, I think it should, because obvious warnings from the parser stage of the compiler are an order of magnitude better than obscure error messages from the linker.
Finally, some C++ fan-boys might give this as an example of why C++ is a safer language than C. The question I would ask of those people is, "if you are so concerned with programming safety, why are you using C++ instead of Ocaml or Haskell?". I would also suggest that using a good C compiler like GNU gcc with every warning message you can find turned on is just as safe as running the same code through a C++ compiler.
Posted at: 07:03 | Category: CodeHacking | Permalink
Sat, 25 Aug 2007
Reading List.
I've just received a bundle of books from Amazon. This is going to keep me busy for some time.
Posted at: 11:19 | Category: | Permalink
Mon, 30 Jul 2007
A Simple Introduction to Parsing with Flex and Bison.
On Friday night I gave a presentation at SLUG with title above. Unfortunately the SLUG video recording people weren't there on the night so no video was captured. I am however making the slides and code available for download here. The code examples demonstrate a simple email date header parser written in both C and Ocaml. The C code is in five different stages so people can see how the parser was developed.
If anyone has any questions about the code, or more generally with the techniques of parsing, I'd be happy to discuss them on the SLUG coders mailing list.
Posted at: 20:35 | Category: CodeHacking | Permalink
Thu, 17 May 2007
Telstra NextG and Sierra Wireless Aircard 875.
At my day job we needed to connect our Ubuntu based appliance to Telstra's NextG broadband wireless network using the Telstra supplied Sierra Wireless Aircard 875. These things are PCMCIA cards but internally, they present as a USB serial device. According to lsusb:
Bus 006 Device 002: ID 1199:6820 Sierra Wireless, Inc.
Kernels after about 2.6.20 will recognize this device and automatically load an appropriate driver and set up three /dev/ttyUSB* devices. For kernels that don't recognize the card do:
modeprobe usbserial vendor=0x1199 product=0x6820
Once the /dev/ttyUSB* devices are set up correctly create the files /etc/ppp/peers/telstra_aircard_875 and /etc/ppp/peers/telstra_aircard_875_chat.
New file : /etc/ppp/peers/telstra_aircard_875. The username and password below need to be there but can be anything, including the exact same ones as I have here.
lock crtscts modem hide-password noauth /dev/ttyUSB0 460800 defaultroute replacedefaultroute noipdefault usepeerdns noipdefault user anyname password anypassword noauth connect '/usr/sbin/chat -v -f /etc/ppp/peers/telstra_aircard_875_chat'
New file : /etc/ppp/peers/telstra_aircard_875_chat The XXXX below should be replaced with the Telstra supplied PIN number that should be unique for each card.
ABORT BUSY ABORT 'NO CARRIER' ABORT VOICE ABORT 'NO DIALTONE' ABORT 'NO DIAL TONE' ABORT 'NO ANSWER' ABORT DELAYED ABORT ERROR TIMEOUT 20 "" "AT+CPIN?" READY-AT+CPIN=XXXX-OK "AT&F" OK "ATE1" TIMEOUT 20 OK "ATDT*99***1#" CONNECT \d
Finally, edit the file /etc/ppp/pap-secrets, and add the following entry. Again, this needs to be there, but will be the same for everyone.
# For telstra_aircard_875 user@telstra.internet * telstra
Getting connected should now be as easy as:
pppd call telstra_aircard_875
One of the slightly odd things about this card and Telstra's NextG network is that if the four digit PIN number isn't sent during the CHAT session the CHAT session will connect and pppd will try to negotiate an IP address but get no response, eventually timing out. Anyone who experiences this problem should first make sure that the service has been activated from the Telstra end (possibly by making sure it works under windoze) and then turn on debugging for both chat and pppd.
Posted at: 20:27 | Category: Tech | Permalink
Sun, 08 Apr 2007
Horses For Courses.
In my day job, I work with a hardware engineer named Joe. A couple of months ago, he had to do some C coding to talk to a serial port and came to me for pointers. He was basically on the right track, but was using too many global variables, not checking the return values of system calls etc. These weren't horrible problems, but I explained why practices like this can lead to problems later, showed him better solutions to the same problems and introduced him to the gcc warning flags and Valgrind. He was very grateful for my help and was a quick to pick up all the tips I'd given him.
More recently Joe came to me with another programming problem; he had to parse some numerical data out of a plain text log file. He already had about 60 lines of C code that opened a file based on a hard coded filename and he was starting to fiddle around with the fgetc function but was a little stuck on how to go further.
I had a look at his code and since Joe's a nice Irish chap, his predicament brought to mind a joke I once heard:
It is said that there was once an English motorist in Ireland who stopped his car to ask the way to Kilkenny. "Sure and to goodness," replied the Irishman., "If I wanted to go to Kilkenny, I wouldn't be starting from here."
The problem is that C is not a very good language for parsing text data. I told Joe that writing his log file parser in C could certainly be done, but that it would be painful, time consuming and error prone in comparison to other programming languages. So I told him that for this particular task Python would be a much better fit and asked him if he'd like me to teach him the basics of Python. Joe's no dummy; he agreed without hesitation.
First up I showed him the Python Tutorial, the Python Module index and how to used Google Groups advanced search to find Python specific answers from the comp.lang.python Usenet group. I then showed him the basic hello world program in Python:
#!/usr/bin/python print "Hello world!"
Over the next hour we built up a good portion of his program. We used used the sys module to get the file name of the log file to parse, the built in Python file handling functions and the regular expression module. We even used a list comprehension to remove outliers from his data set.
In the end we had about 30 lines of Python code that was very much closer to Joe's end goal than his original 60 lines of C code. Joe was really, really impressed with how easy Python was in comparison to C. It was at this point that I warned Joe about the Blub Paradox. He was well aware that when he only knew C, C was his first choice for this programming task. However, now that he knows Python as well, he'll be able to pick between C and Python depending on the task. I also told him that many Python programmers see Python as the ultimate programming language and are really Blub programmers even if they don't know it.
In my own programming I'm currently using:
- C : The first language I really became proficient in. Its great for low level hacking, good for libraries and wherever speed of execution is an important aspect. I still love C even if it does seem rather archaic in comparison to the others.
- C++ : I'm not real keen on C++ even though I do use it for most of the coding I do at my day job. As a language its incredibly complex and unforgiving. There are a million ways to shoot yourself in the foot and no one lives long enough to experience them all. Its a language that can harbor the most obscure bugs that can be exceedingly difficult to track down. This is a language that as far as I am concerned is long past its use by date.
- Python : Python is a great language for teaching and a great language for small scripts. Some people also use it for bigger projects like Bzr but for me personally, I find its dynamic type system too problematic for use on larger projects.
- Ocaml : This is my current favorite for general purpose programming. It can be run as a script just like Python, but can also be compiled to a really fast native binary. It uses strict static type checking to find coding errors at compile time and run time array bounds checking. It has variant types and pattern matching which are powerful constructs that programmers who have only used mainstream languages like C, C++, Java, Perl, Python etc could only dream about.
- Erlang : Lately I've been learning Erlang, both for a project of my own and for a project at work. I'm learning it because it does parallel, concurrent and distributed programming better than any of the above, probably better than any other language in existence. Its also been pretty easy to pick up because, like Ocaml, its a functional programming language. Like Python, it uses dynamic type checking, but also has quite a lot of static checking in the compiler.
So, with the above languages at my disposal, I can match a programming language to the task at hand. For numerical and mathematical programming I use Ocaml, for low level programming I use C and from now on, for multi-threaded and concurrent programming I will chose Erlang.
More importantly, correctly matching the language to the problem should make the task of developing a solution to the problem far easier than using an inappropriate language.
Posted at: 20:16 | Category: CodeHacking | Permalink
Wed, 04 Apr 2007
Learning Erlang.
The decision has been made, I'm going to learn the Erlang programming language. The main reason for this decision is that Erlang does one thing better than any other programming language I am aware of; parallel, concurrent and distributed processing.
The big problem with parallel and concurrent processing in other languages is that the standard method of communication between threads in most languages is shared data protected by mutexes or semaphores which are difficult to get right when there are a lot of threads or a lot of data to be protected. The standard solution to the problems of dealing with parallelism simply doesn't scale well.
Erlang excels at parallel processing because it forgoes the use of semaphores, mutexes and other synchronisation primitives. It replaces these shared data synchronisation methods with message passing; a much simpler mechanism which is much easier to reason about and much harder, maybe even impossible, to get wrong.
When learning, a new language, my usual approach is to write lots of small demo programs, with each one demonstrating a different feature. These programs come in really useful later as an easy to reference catalogue of language features.
Here's my first complete Erlang program, which takes any number of integer parameters on the command line and prints the factorial of each one:
#!/usr/bin/env escript
-export ([main/1]).
% Naive factorial function.
fac (0) -> 1 ;
fac (N) when N > 0 -> N * fac (N - 1).
% Function to print the factorial of each list element.
print_fact_list ([]) -> ok ;
print_fact_list ([Head | Tail]) ->
% Convert the Head from a string to an int.
Int = list_to_integer (Head),
% Calculate the factorial.
Fact = fac (Int),
% Print the result.
io:format ("fac ~w : ~w~n", [Int, Fact]),
% Call the function recursively with the tail of the list.
print_fact_list (Tail).
% Main function, accepts a list of strings contain argv [1], argv [2] etc.
main (List) ->
case length (List) of
0 -> io:format ("Usage : factorial.erl <number>\n") ;
_ -> print_fact_list (List)
end.
To me, this Erlang code looks a little like Ocaml and a little like Prolog which I used briefly at university over a decade ago. A couple of things to note:
- Comments begin with the percent character.
- All variable names have a leading upper case letter.
- Functions can be defined multiple times and pattern matching is used to decide which function variant is called.
- Strings are stored as lists of characters and converted to integers using the list_to_integer function.
To run this program requires Erlang, which on Debian and Ubuntu means the packages erlang, erlang-base, erlang-dev and erlang-manpages. It also uses escript, which comes standard with Erlang R11b4 and can be obtained here for earlier versions (Ubuntu Feisty has R11b2). Escript allows Erlang code to be run as a script, just like Python or Ruby.
The output of this program when passed the numbers 10, 20 and 30 results in the following output:
fac 10 : 3628800 fac 20 : 2432902008176640000 fac 30 : 265252859812191058636308480000000
Yep, Erlang uses arbitrary precision integers by default. Thats pretty cool.
Posted at: 23:07 | Category: CodeHacking/Erlang | Permalink
Wed, 28 Mar 2007
Tridge Was Right.
At Linux.conf.au 2005, Tridge gave a keynote talk about some of the issues the Samba team had run into when designing Samba4. While discussing the problems of writing a complex server which has to serve multiple simultaneous requests he put up a series of three slides. The first said:
Threads suck!
Having used OS level threads in the past, I was in complete agreement with this. The problems of sharing data across threads and locking/unlocking of that data to make sure the accesses are safe is simply too difficult for mere mortals to get right in anything other than trivial cases.
Tridges' second slide said:
Processes suck!
Splitting multi threaded code into multiple processes fixes the locking problems by removing the ability of the processes to share data (ignoring IPC shared memory of course). Obviously for a server program like Samba, this is not a solution.
The third slide in the series said:
State machines suck!
At the time of Tridge's keynote, I didn't really appreciate what he was saying.
The idea is really quite simple; everything is done in a single process so no locking is required. All I/O is multiplexed using the Unix select system call and a state machine keeps track of state of all of the I/O channels.
The problem with this is that any blocking I/O operation must be replaced with a non-blocking operation. Failure to do this will mean that a single I/O call that blocks will prevent the servicing of all other I/O operations until the blocked operation decides to complete and return control to the state machine.
However, the state machine model does work relatively well for simple examples. Unfortunately, non-blocking I/O leads to a second problem; writing code to do non-blocking I/O is significantly more difficult than for regular blocking I/O.
In my day job I've been working on some C++ classes which talk to a web server using HTTP POST operations over a keep-alive connection. This code had a couple of requirements:
- Must be non-blocking to fit in with the rest of the code.
- Must be capable of HTTPS connections using OpenSSL (which is a particularly nasty to get working in non-blocking mode).
- Must be able to connect via a HTTP proxy in both HTTP and HTTPS modes.
- Must be able to detect a connection that gets broken and gracefully re-establish it.
I now have code that fits these requirements and a pretty comprehensive test suite. With this experience behind me I have to say that getting this working was a royal pain in the neck. I also agree with Tridge; state machines suck almost as much as threads.
Maybe its time for me to learn Erlang.
Posted at: 22:36 | Category: CodeHacking | Permalink
Thu, 22 Mar 2007
Lazy Lists.
Lazy evaluation is a default feature of the Haskell programming language and an optional feature of Ocaml. Most programming languages (Ocaml, C, C++, Perl, Python, Java etc) use eager evaluation; where a result specified by a line of code is calculated as soon as the program gets to that line. Lazy evaluation on the other hand, defers the calculation of a result until that result is needed.
The real beauty of lazy evaluation is that a result that is never used is never
evaluated.
Lazy evaluation also allows the specification of lists which are effectively
infinite, as long as the programmer doesn't actually try to access every element
in the list.
Obviously, attempting to do so would take infinite time and and require infinite
memory to actually hold the list
.
While searching for information on Ocaml's lazy programming features I came across a post at the enchanted mind blog. That post is ok, but the code is just snippets and when put together as it is, doesn't actually work.
After a bit of fiddling around, I managed to get it working. However, once I understood it, I didn't think the example was as good as it could be. Firstly, the input to the lazy list is just a standard finite length Ocaml list, but more importantly it doesn't give any idea of how to do a potentially infinite list which is a much more interesting case.
That left the field open for a nice blog post demonstrating lazy lists in Ocaml. Read on.
Anybody who has done high school or higher mathematics would probably have come across recurrence relations the most well know of which is the Fibonacci sequence.
The Fibonacci sequence is often used as example for teaching the concept of recursion in computer science (even if some people think there are better examples). The Fibonacci sequence can be expressed recursively in Ocaml like this:
let rec fibonacci n =
match n with
| 1 -> 1
| 2 -> 1
| x -> (fibonacci (n - 1)) + (fibonacci (n - 2))
If one wanted to generate a list containing say the first 20 Fibonacci numbers using the above recursive function, the 19th number in the sequence would be calculated twice, the 18th number three times so on. Its simply not efficient.
A better solution is to use a lazy list, which calculates new values of the sequence as they are needed, based on entries already in the list. Here's an example that creates a lazy list of the fibonacci numbers:
type lazy_fib_t =
Node of int * lazy_fib_t Lazy.t
let create_fib_list () =
let rec fib_n minus_2 minus_1 =
let n = minus_1 + minus_2 in
Printf.printf "fib_n %d %d -> %d\n" minus_2 minus_1 n ;
Node (n, lazy (fib_n minus_1 n))
in
lazy (Node (1, lazy (Node (1, lazy (fib_n 1 1)))))
let print_fib_list depth lst =
let rec sub_print current remaining =
if current > depth then ()
else
match Lazy.force remaining with
| Node (head, tail) ->
Printf.printf "%3d : %d\n" current head ;
sub_print (current + 1) tail
in
sub_print 0 lst
let _ =
let fib_list = create_fib_list () in
print_fib_list 4 fib_list ;
print_endline "------------" ;
print_fib_list 6 fib_list ;
This is a complete working Ocaml program. To run it, just save the text to a file, say "lazy_fib.ml" and then do:
ocaml lazy_fib.ml
We'll look at the output in detail later. First lets break it down; looking at the program, from top to bottom we have:
type lazy_fib_t =
Node of int * lazy_fib_t Lazy.t
The above two lines define a recursive type called lazy_fib_t, which has a single variant called Node which contains a tuple of an integer and the head of a lazy list.
let create_fib_list () =
let rec fib_n minus_2 minus_1 =
let n = minus_1 + minus_2 in
Printf.printf "fib_n %d %d -> %d\n" minus_2 minus_1 n ;
Node (n, lazy (fib_n minus_1 n))
in
lazy (Node (1, lazy (Node (1, lazy (fib_n 1 1)))))
The function above, create_fib_list, creates a lazy list. It also contains an internal function, fib_n, which we'll look at later. The last line of the function is where all the magic is; it creates three nodes of a lazy list, the first two containing the first two integers of the Fibonacci sequence and a third node which is a closure, containing a call to the internal function fib_n with the correct parameters to generate the next number in the sequence.
The internal function fib_n takes two parameters, the values of the sequence for n - 1 and n - 2. From these two values, it generates the value for n, prints a message and then constructs a new Node containing the value for n and a lazy evaluation for the next value.
The next function is the function which prints the first n elements of a lazy list. It looks like this:
let print_fib_list depth lst =
let rec sub_print current remaining =
if current > depth then ()
else
match Lazy.force remaining with
| Node (head, tail) ->
Printf.printf "%3d : %d\n" current head ;
sub_print (current + 1) tail
in
sub_print 0 lst
The print_fib_list function contains an internal function sub_print which is called with a current depth of zero and the head of the lazy list to be printed. The internal function recursively moves down the list until current is greater than depth, which cause the recursion to complete and unwind.
At each node of the lazy list where current is less than or equal to depth, the function forces the evaluation of the node. The forcing will only evaluate a node if it hasn't already been evaluated. Once the node has been force evaluated, the value is printed and the function is called recursively.
Finally, the main function of the program is this:
let _ =
let fib_list = create_fib_list () in
print_fib_list 4 fib_list ;
print_endline "------------" ;
print_fib_list 6 fib_list ;
All it does is call the function create_fib_list, and then print the first four Fibonacci numbers of the list, prints a dashed line and then prints the first six Fibonacci numbers of the list. Its important to note that the print function is called with the same list on both occasions.
When the program is run, the output should look like this:
0 : 1
1 : 1
fib_n 1 1 -> 2
2 : 2
fib_n 1 2 -> 3
3 : 3
fib_n 2 3 -> 5
4 : 5
------------
0 : 1
1 : 1
2 : 2
3 : 3
4 : 5
fib_n 3 5 -> 8
5 : 8
fib_n 5 8 -> 13
6 : 13
As can be seen above, the first time the print function is called, the fib_n closure is called for all values of n greater than one. Each time fib_n is called a new node is generated in the list. When the print function is called the second time, it fib_n is only called for values that weren't evaluated on the first call to the print function just as was expected.
One of the few problems with the above implementation is that it uses integers which in Ocaml on 32 bit CPU platforms is only a 31 bit integer. It would however be relatively easy to use Ocaml's Big_int module which provides arbitrary length integers.
Posted at: 21:43 | Category: CodeHacking/Ocaml | Permalink
Wed, 21 Mar 2007
Xtreme Numerical Accuracy.
I'm working on a digital filter design program in Ocaml which was suffering from some numerical issues with Ocaml's native 64 bit floats. The problem was that the algorithm operates on both large floating point numbers and small floating point numbers. These numbers eventually end up in a matrix, and I then use Gaussian elimination to solve a set of simultaneous equations.
Anyone who has done any numerical computation will know that adding large floating point numbers to small floating numbers is a recipe for numerical inaccuracy. For me, the numerical issues were screwing things up badly.
When faced with a problem like this there are two possible solutions:
- Do all the computations symbolically, and only substitute numbers at the very last stage and then being careful to process the numerical parts in a way to minimize rounding and truncation error.
- Replace the floating point operations with operations on a number type which can provide higher (and maybe even arbitrary) precision.
The first option, doing all the computations symbolically was not practical due to the complexity of the computation. That left only the second option.
Looking around for what was available for Ocaml, I found the contfrac project on Sourceforge. As all the math geeks (hi Mark) have probably guessed by now, contfrac expresses numbers in terms of a really cool mathematical concept called continued fractions.
The idea is that any number can be represented by a (potentially infinite) list of integers [ a0 ; a1, a2, a3, ...]. Given the list of integers, the number itself can be calculated using:
All rational numbers have a finite length continued fraction expansion. For example, the rational number 75/99 is expressed as [ 0 ; 1, 3, 8 ].
Not surprisingly, all the irrational numbers have infinite length continued fraction expansions. The surprising thing (for me at least) is that many of the irrational numbers have CF expansions that are surprisingly regular. The square root of two is expressed as [ 1 ; 2, 2, 2, ...] with an infinitely repeating list of 2s. The natural logarithm e is expressed as [ 2 ; 1, 2, 1, 1, 4, 1, 1, 6, ...] which again has a regular pattern, as does the golden ratio, [ 1 ; 1, 1, 1, ...]. While all the previous CF expansions have a degree of regularity, the expansion of pi, is [ 3 ; 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 2, 1, 1, 2, 2, 2, 2, 1, 84, 2, 1, 1, 15, 3, 13,...], which looks completely random.
With numbers expressed as continued fractions, the Ocaml contfrac module then implements addition, subtraction, multiplication and division. Once the four arithmetic operations are defined, contfrac then implements a number of trigonometric and transcendental functions in terms of the same continued fractions.
Unfortunately, the module doesn't implement everything I need so I'm going to have to hack on some extra functionality. The actual Ocaml implementation uses Ocaml's lazy lists which is an aspect of Ocaml I hadn't played with yet. Time for some fiddling with lazy lists.
Posted at: 20:49 | Category: CodeHacking/Ocaml | Permalink
Tue, 20 Mar 2007
Go Silvia!
Local Sydney geek Silvia Pfeiffer has a story and photo in the Sydney Morning Herald's tech section.
Congratulations Silvia!
Posted at: 11:21 | Category: | Permalink
Mon, 26 Feb 2007
Master of Recording Arts.
Tonight, and for the next 6 weeks I'll be teaching the digital audio theory component of "MUS801: Studio Technique and Practice" which is part of Macquarie University's Master of Recording Arts degree program.
The course is run by the Department of Contemporary Music Studies and the students come from a music or humanities background. My job is teach them about the theory behind recording technology, the basics of how sound is recorded and processed by computers and the workings of the main studio effects.
Judging from how much I enjoyed teaching this last year its going to be a lot of fun. Thanks to Denis Crowdy for inviting to me to do this for the first time last year and inviting me back again this year.
Posted at: 22:48 | Category: | Permalink
Thu, 22 Feb 2007
Came off my Bike.
On the way home from work today I came off my bike.
I was coming down a hill when someone parked at the left hand side of the road decided to do a U turn across my path. As soon as I realised they were doing something stupid I slammed on my brakes. Because it was raining I was going slower than usual but I still didn't have much time to pull up without sliding the bike sideways.
Unfortunately that didn't work as planned. The bike started sliding sideways, but then flipped me over onto my back and the bike flew through the air and over the top of me.
That sounds like a pretty nasty fall, but I was lucky. My only injuries are a nasty bruise to my inside left thigh, another to my left buttock and a sore neck. I didn't loose any skin or blood.
I was very fortunate to be wearing a backpack containing my laptop inside its own padded backpack. The backpack took most of the fall and the laptop is unharmed. I also wear a BMX helmet instead of the lighter more flimsy racing style helmet but in this case the helmet only came into contact with the road as I slumped into my final position. I stood up again within about 10 seconds of hitting the ground.
I was pretty shaken, but well enough to go to my yoga class at 6:15 pm.
Update 2007-02-23 07:59 : Since writing the above last night I realised that I have a couple more bruises, that the bike did not fly over the top of me, but that I did flip over it so that I landed between the bike and the car and finally that my laptop did sustain some damage; one corner is slightly smashed in.
Posted at: 20:51 | Category: Cycling | Permalink
Wed, 14 Feb 2007
GNU gcc Stack Protection.
Wow, this is new. Version 4.1 of GNU gcc compiler shipped with Ubuntu Feisty includes stack smashing protection by default!
Consider the following code containing a buffer overflow of a stack based buffer :
#include <stdio.h>
static void
kill_my_stack (void)
{
char buffer [10] ;
int k ;
for (k = 0 ; k < 20 ; k++)
buffer [k] = 'a' + k ;
} /* kill_my_stack */
int
main (void)
{
kill_my_stack () ;
return 0 ;
} /* main */
Compiling this with the default gcc compiler in Feisty produces an executable which when run gives the following error:
*** stack smashing detected ***: /home/erikd/stack-protect-demo terminated
Aborted
Obviously, for an error as simple as this even basic static analysis should find it, but we know that the vast majority of people don't use static analysis. In fact many don't even compile with a sensible set of compiler flags turned on. Well now, those people are protected from themselves.
Posted at: 19:13 | Category: CodeHacking | Permalink
Mon, 12 Feb 2007
The Windoze tmpfile Implementation.
During a discussion on the libsndfile-devel mailing list it was brought to my attention that although windows does have an implementation of the POSIX function tmpfile:
#include <stdio.h>
FILE *tmpfile (void) ;
the temporary file created on windows is placed in the root directory of the C:\ drive. Couldn't possibly be true you think? Think again. From microsoft's own documentation
The tmpfile function creates a temporary file and returns a pointer to that stream. The temporary file is created in the root directory. To create a temporary file in a directory other than the root, use tmpnam or tempnam in conjunction with fopen.
So the global village idiots of microsoft implemented tmpfile so they could say that windows was POSIX compliant, but did so in a way that is so broken that nobody in their right mind would actually want to use it.
But its actually worse than that. According to microsoft, the tmpfile function is deprecated because it supposedly isn't secure. From the same page:
Creates a temporary file. This function is deprecated because a more secure version is available; see tmpfile_s.
(Note : I wonder if microsoft bothered to tell the people responsible for the POSIX Standards that microsoft has deprecated a function in their standard.)
The fact that the GNU libc version of tmpfile is secure means that it is possible to write a secure version of this function. That means that the only reason microsoft could have had for deprecating it was because their version was insecure. They deprecated a POSIX standard function to replace it with a their own non standard function tmpfile_s:
errno_t tmpfile (FILE** pFilePtr);
Now I for one, cannot see any reason why this version of the function is any more secure than the POSIX version. It also far easier to do the wrong thing with this function than it is with the original.
Once again, microsoft shows that it employs people who are probably too stupid to feed themselves or crap in a toilet without help, in spite of the fact that is also employs some really smart people.
Posted at: 12:53 | Category: Windiots | Permalink
Sun, 04 Feb 2007
Microsoft Executive Recommends Apple Mac.
This is too beautiful. In a 2004 email to Bill Gates, Jim Allchin a high level Microsoft executive says:
"I would buy a Mac today if I was not working at Microsoft."
The rest of the email is here and more emails here.
Posted at: 08:55 | Category: Tech | Permalink
Thu, 01 Feb 2007
Spectrogram Fun!
Inspired by the spectrograms used in the SRC Comparison I decided to write a program that generates similar spectrograms from any given sound file. The program is now basically working and when run over a full song (the song "Vehicle" by the band "Golden Section") it produced this, which I think is quite beautiful:
The program is written in C and uses libsndfile (of course) for reading the sound file, FFTW for generating the spectrum data and the wonderful Cairo library for the image generation back-end.
I intend to release the code for this under the GPL as soon as I can clean it up a bit, add handling for multi-channel files and improve the command line option handling.
Posted at: 22:03 | Category: CodeHacking | Permalink