nu42.com: That's number 42 to you. A blog about programming and technology

Sunday, July 25, 2010

Displaying LaTeX formulae on web pages

For a while now, I have been pondering about the best way to display to LaTeX formulae in web pages.

There are many web sites which will take your LaTeX equation and turn it into a PNG image. There are also a bunch of programs that will allow you to create those equation images offline.

However, I did not find those solutions to be satisfactory (based on purely subjective taste criteria which I am not willing to try to enumerate ;-)

Today, I found out that Google's chart API also allows you to render LaTeX equations.

The logo I used on this page was generated using the URL http://chart.apis.google.com/chart?cht=tx&chl=%5cLaTeX&chs=18&chf=bg,s,dadada. The style on the IMG element is simply:

.post img.inline {
  border:0;
  padding:0;
  margin:0;
  vertical-align:text-bottom;
}

And, here is a utility maximization problem:

[ Maximize utility subject to the budget and nonnegativity constraints ]

I like it.

Thursday, July 8, 2010

The beauty of Moose: Enforcing an interface

I must admit, I was reluctant to jump into Moose straightaway. I watched from the sidelines for a long time. Then, finally, I decided to jump in. Right now, I am only using pretty basic Moose features with none of the facilities provided by the various extensions in the MooseX:: namespace.

I am still working on writing economics experiments with Dancer Yes, I know, I need to post some slides, I haven't forgotten.

I chose to implement every route handler, response/view and significant method as a role. To show what I mean, I am going to consider a simple contact form handler (so as not to bother you with the experimental economics specific details). Here is how the main class for the application looks:

package My::App;

use Moose;
use namespace::autoclean;

with 'My::Handler::get::contact_form';
with 'My::Handler::get::contact_form_submitted';
with 'My::Handler::post::contact_form';
with 'My::View::contact_form';
with 'My::View::contact_form_submitted';
with 'My::View::redirect::contact_form::submitted';

__PACKAGE__->meta->make_immutable;
1;

In this case, My::Handler::get::contact_form is a role that supplies the get_contact_form method which is wired using Dancer's syntax helpers to be invoked when an HTTP GET request is made to the URL /contact_form. get_contact_form finishes by invoking view_contact_form which is supplied by the role My::View::contact_form.

All this looked pretty neat to me (although, it might be a completely insane way of doing things given that this is my first attempt to use Moose in a project). I like it because tweaking one aspect of the application can be achieved very simply by composing a different role in a subclass:

package My::App::Neater;

use Moose;
use namespace::autoclean;

extends 'My::App';

with 'Neater::Handler::post::contact_form';

__PACKAGE__->meta->make_immutable;
1;

However, I was bothered by the fact that I did not get an error until run time if I forgot to pull in a role that provided a required method. (The base application class for an experiment mixes in tens of such roles).

If I were programming in Java, I would have written an interface and have My::App implement that. While I do not like Java's verbosity, I do like interfaces. Fortunately, that can be achieved very easily, again, using Moose roles. Defining the interface is straightforward:

package My::Interface;

use Moose::Role;
use namespace::autoclean;

requires 'get_contact_form';
requires 'get_contact_form_submitted';
requires 'post_contact_form';
requires 'view_contact_form';
requires 'view_contact_form_submitted';
requires 'view_redirect_contact_sumitted';

1;

Then, I can simply add with 'My::Interface'; to My::App:

package My::App;

use Moose;
use namespace::autoclean;

with 'My::Interface';

# lines composing the various roles
# omitted for testing

__PACKAGE__->meta->make_immutable;
1;

Note that I commented out all the with lines to see what happens when I invoked the following short script:

#!/usr/bin/perl

use strict; use warnings;

use lib 'lib';
use My::App;

my $x = My::App->new;

And, It Works! I get the following error message:

C:\Temp> roles
'My::Interface' requires the methods 'get_contact_form',
'get_contact_form_submitted', 'post_contact_form', 
'view_contact_form', and 'view_redirect_contact_form_submitted' 
to be implemented by 'My::App' …

followed by a long stack trace making for a very Java-like experience ;-)

Monday, June 28, 2010

Use your own configuration file with Dancer

Dancer has a command line option called --environment which allows you to specify the path to an application specific configuration file.

You can put both Dancer specific options and settings related to your own application in this file. For example, you can put:

app_setting: 42

and then use

my $setting = config->{app_setting};

to access the value.

All this is convenient, but sometimes you need to put some of the more transitory settings into their own files, separately from more permanent settings that describe the environment in which the program operates. For example, the multiplier in a public goods experiment is at a higher level of abstraction and is valid for a shorter duration than the port number for the underlying server. Those two simply do not belong in the same file.

Dancer uses Getopt::Long to parse command line options. However, it does not enable the pass_through option which means options unknown to Dancer are flagged as errors.

The solution? Simple. Use Getopt::Long with pass_through before Dancer gets a chance to call it:

#!/usr/bin/perl
use strict; use warnings;
use Getopt::Long;

my $param_file;

BEGIN {
    Getopt::Long::Configure('pass_through');
    GetOptions("param=s" => \$param_file);
}

use lib 'lib';

use Config::Std;
use My::Experiment::App;
use Dancer;

load_app 'My::Experiment::App::Dancer';

my %param;

die "Must supply a parameter file using --param\n"
    unless defined $param_file;

read_config $param_file => %param;

This way, experiment specific parameters can be specified generically and independently of the underlying application settings.

YAPC::NA 2010

I have been programming in Perl since late 2002. Since then, I have interacted with many people online and learned a lot from their willingness to share their hard-earned wisdom.

But, I never went to a Perl conference. In fact, I never went to a programming related conference at all. There is no one reason for my lack for participation: It just never happened.

Then, earlier this year, brian d foy, whom I admire both as a writer and a programmer, suggested that it was time for me to attend one. I finally mustered the courage, submitted a talk proposal and started dreaming.

I arrived in Columbus in the evening on Sunday, June 20 for YAPC::NA 2010. I felt welcome from the first moment thanks to Steven Lembark, his gracious wife and Larry Wall allowed me to crash their table ;-) The next morning, I realized what a great effort Heath Bair and the rest of the local organizers in Columbus had put into making the conference a wonderful opportunity to expand our horizons and interact.

The next couple of days was a whirlwind as I got to meet people whose work has not only helped me get my work done but literally saved my back side many times over.

If you want to meet people who are not only smart and get things done, but also a blast to listen to, chat or just have lunch with, you owe it to yourself to attend the next YAPC.

I know I will.

Thank you everyone.

Friday, June 4, 2010

The decline and fall of programmers

I get a lot of stuff from eWeek in my inbox (don't ask), but this morning's email lead me to despair.

eWEEK takes a look not at the nifty applications programmers have cooked up, but at the new trend in slang for today's programmers. This list, inspired by the Stack Overflow Web site and the Global Nerdy Web blog, includes such gems as the "Mad Girlfriend" bug, the "Drug Report," bug bait and ghetto code. If you are a programming nerd, you will know how to speak this language.

The subject line said: Master Geekspeak: Cracking Code-Jockey Jargon.

I immediately felt nostalgic. Back in junior high and high school, I used to kill time in class by writing small routines in Z80 machine code. No, I do not mean assembly. I mean, I was trying to memorize the opcode table, so I would write stuff like DB 00 47 DB 01 80 D3 00 C9 on scraps of paper while the teacher talked about this, that, and the other.

It turns out, so called geekspeak has changed in the intervening years. I went through their presentation slide-by-slide, and let me tell you, it was no Jargon file.

You mean banana banana banana has replaced the venerable lorem ipsum? Barack Obama is a Code-Jockey term? We are supposed to say bugfoot instead of a Heisenbug? Baklava code instead of spaghetti code?

Give me a break!

I guess this is what a code monkey wannabe thinks real programmers must talk like.

Head on over to The Daily WTF. No soup for you Darryl K. Taft!

Thursday, May 27, 2010

Why can't I get Dancer's version when invoking perl from the command line on Windows?

Recently, I decided to upgrade Dancer on my Windows XP laptop (hint, hint) to the most recent version. The ppm repositories I was using did not have the latest. Not to worry, though, because I had installed the mingw package to be able to build and install CPAN packages by hand.

From that point on, it was simply a matter of:

perl Makefile.PL
dmake test
dmake install

However, I was bothered by some messages along the lines of unable to determine version information from Dancer.pm.

I decided to investigate.

C:\> perl -MDancer -e "print $Dancer::VERSION"
-e: No such file or directory at c:/opt/Perl/site/lib/Dancer.pm line 161
BEGIN failed--compilation aborted at c:/opt/Perl/site/lib/Dancer.pm line 161, 
 line 16.
Compilation failed in require,  line 16.
BEGIN failed--compilation aborted,  line 16.

Hmmmm … What is that all about? After all, my programs using Dancer still worked fine.

Here is the offending piece of code:

sub load_app {
    for my $app (@_) {
        Dancer::Logger->core("loading application $app");

        use lib path(dirname(abs_path($0)), 'lib');

The use lib pragma is trying to add the directory in which the script lives to @INC during the compile phase.

Now, when you invoke perl with the -e switch, $0 contains the string -e. I thought A-ha! and filed a lousy report.

The response I got from xsawyerx made me realize that there was a difference between perl on Windows and perl on Linux. Indeed, testing on one of the ancient desktops I have with ArchLinux installed confirmed it:

[sinan@kas ~]$ perl -MDancer -e 'print "$Dancer::VERSION\n"'
1.1803

My attention quickly focused on Cwd::abs_path. Here is what Cwd::abs_path does on Windows. First, abs_path is aliased to fast_abs_path. Second, fast_abs_path contains:

my $Curdir;
sub fast_abs_path {
    local $ENV{PWD} = $ENV{PWD} || ''; # Guard against clobberage
    my $cwd = getcwd();
    require File::Spec;
    my $path = @_ ? shift : ($Curdir ||= File::Spec->curdir);

    # …

    unless (-e $path) {
  _croak("$path: No such file or directory");
    }

As you can see from the debugger output, that's where the problem is:

-e: No such file or directory at c:/opt/Perl/site/lib/Dancer.pm line 161
 at c:/opt/Perl/lib/Cwd.pm line 357 
Cwd::_croak('-e: No such file or directory') called at c:/opt/Perl/lib/Cwd.pm 
line 633 
Cwd::fast_abs_path('-e') called at c:/opt/Perl/site/lib/Dancer.pm line 161

On Unix, abs_path is an XS routine. It calls bsd_realpath in Cwd.xs. Something, somewhere, in that execution path results in something that works.

Now, one might say, this does not matter if it only happens on Windows. On the other hand, command line tools rely on being able to require a module and deduce version information from the module.

As I thought about this more, I realized the delayed loading fix I recommended in the original bug report was the wrong solution. IMHO, the right solution would be to change Dancer::load_app like so:

require File::Spec;
use lib path(dirname(File::Spec->rel2abs($0)), 'lib');

Update: The patch will be included in the next release of Dancer. Now, that's what I call responsiveness.

Wednesday, May 26, 2010

Internationalization fail

The Turkish alphabet presents some issues for programmers. Jeff Atwood discussed similar issues in his humorous blog post What's wrong with Turkey?

When discussing internationalization issues, self-conscious American programmers tend to defensively remark on their ignorance of other cultures and non-American programmers tend to pile on frequently remarking that Americans should be called U.S.-Americans because, you know, the continent is much bigger than the USA. Well, live with it!

Lately, I have been seeing interesting captions under video thumbnails on the web site of a major Turkish newspaper, Hürriyet.

Here is an example:

Hurriyet internationalization fail

Here is what the caption under the image says: DÜEN ASKER UÇAIN LK GÖRÜNTÜLERİ. It should say DÜŞEN ASKERİ UÇAĞIN İLK GÖRÜNTÜLERİ It can be loosely translated as first photos from the scene of the military plane crash.

Notice the infamous Turkish dotted capital I (İ)s are missing from the text. Also missing are Ş and Ğ.

I don't know why (I am guessing some OEM or Windows codepage involved somewhere) but Michael Kaplan would.

I am also not sure this is an internationalization issue: After all, this is the web site of a major Turkish newspaper and the application fails to display Turkish correctly. For the last month or so, I have been wondering when someone is going to notice and fix it but either no one cares or no one knows.