Monday, 2 July 2012

Programming languages should be self documenting

Perl 5.16.0, the latest and most greatest release in Perl's 20+ year history of being awesome added a new keyword that I never knew I wanted. I will illustrate by starting in the past.

The following is a complicated way to calculate triangular numbers, that uses recursion, the best technique in computer science:

sub triangle {
  my $num = shift;
  return 1 if $num == 1;
  return $num + triangle($num-1);
}


That's all very trivial, and in this short example it's very obvious that we're using recursion as the subroutine is so short that the name is very close to our recursive call.

Now, the technique of recursion is very useful in more complex problems, especially those operating on graphs, where the subroutine body might be more than a couple of lines long, in which case I'd have to add the annoying comment to remind the reader what's going on:

sub triangle {
  my $num = shift;
  return 1 if $num == 1;
  return $num + triangle($num-1); # recurses!
}

and, if and when I decide to refactor this subroutine, I need to remember to change the name of the subroutine, and the name I use when I call it. This is entirely pointless busywork.

Instead, now, Perl has introduced the __SUB__ keyword which magically turns into the subroutine you're currently in:

use v5.16;
sub triangle {
  my $num = shift;
  return 1 if $num == 1;
  return $num + __SUB__->($num-1);
}

which is both clearer to read and immune to me changing the name of the routine, and, as a bonus, it's helpful if Perl wants to transform the subroutine for the sake of efficiency.

I never missed this little feature, but now it exists it's so natural that I'm surprised that it never existed until now. That's the sign of a perfect addition to a language.

Monday, 9 April 2012

Cracked is getting lazier by 1 thing every year

I was wondering, for no reason whatsoever, if the process of panflation (where, for instance, the sizes of clothes and cups of coffee have tended to increase since the 70s) also affected the amount of funny conveyed by an article on Cracked.com, a sometimes funny site on the internet.

In recent years, a typical article title might be "5 Ways Explosions are Secretly Trying to Kill You". I wondered if the number of ways discussed in an article had changed in time, and had a vague, unconfirmed feeling that the number might be on the decrease.

Perl, as ever, came to the rescue, so I crawled all article and blog titles and extracted the article title and year of publication. I've ignored the more recent 'photoplasty' posts, because they're simply not funny (proven fact). I then swept through looking for single or double digit numbers in the titles, and did a plot:


The best fit to those points indeed shows a decline, of -1 (+- 0.2) things in a title per year. At that rate, by 2022 there's a chance that Cracked will publish articles on how there are "0 Ways Facebook has Stolen Your Powertools (and what to do about it)". I, for one, look forward to this bright future.

(Of course, this isn't really a linear trend, they instead seem to be bottoming out at 5 things, presumably so that they can fit the intro + two things on one page, and three on the next, and so serve up double the Ads and gain some information on engagement by tracking clicks to the second page.)

Saturday, 3 March 2012

Delving into the past, accidents on the sea ice

I've been digging through the Internet (of which there is a lot) looking for previously missed observations of the sort of sea ice I study, mostly so I can add a star to a map where previously there had been only a blank space of 'not-sure'. In doing so, I came across some oral history gems, including this one where Brian Shoemaker interviews Stephen DenHartog about his work supporting Crary in his work at the Little America Station, on the Ross Ice Shelf, Antarctica.

In this interview, we learn that not only did Crary (for whom the science labs at McMurdo are named) drop all his oceanographic gear to the ocean as a cable wasn't attached to a winch, he also nearly lost himself into the ocean when the bit of ice shelf he was using to set up a hut fell 70 feet into the ocean below:

SD: Went out with Bert [Crary] and tried to do some oceanography.

BS: How'd that go?

SD: Well, that led to one of the more infamous stories of things happening in the Antarctic. We went out and we were installing an A-frame at the edge of the Ross Ice Shelf to lower oceanographic equipment over the side. Had the A-frame all pocketed in a couple of holes we had chopped in. Bert's holding the A-frame while I go back to fasten the anchor to it and then we adjusted the angle so it was over the edge. When there was a little noise, you've never seen this little boy run so fast because part of the iceberg calved off with Bert on top of it. It was reasonably high at that point. I think he probably fell 70 feet.

The story continues with Crary doing knee-bends on an ice floe while rescue efforts are put underway. No one tells the helicopter crew they're needed for a rescue as they want to keep this quiet, so they go and make a cup of tea instead of starting up the chopper, and eventually a rubber boat is lowered off the ice shelf and two more people go down and get in it, including the person in charge of local activities. In the end everyone comes out ok and uses the event as an excuse to break into the stores of alcohol.

Meanwhile, I get my hands on one more forgotten datapoint, scholarship is advanced a tiny step further, and I'm a little happy with modern standards of health and safety, if also less satisfied with modern outlets for adventure.

Friday, 4 November 2011

Making single eps file from latex figure

Journals, being the cash-strapped money-printing machines that they are, like to have submissions written in LaTeX, but only in the simplest LaTeX possible.

I like to use LaTeX as much as possible when annotating figures produced by other programs, as then the fonts in my document match those in my figures. This makes it sensible to compose figures within the LateX figure environment. A simple example which collects some sub-figures then labels them would be:

\begin{figure}
\begin{picture}(86,175)(0,0)
  \put(0,140){\includegraphics[width=86mm]{figures-a}}%
  \put(80,144){a}
  \put(0,75){\includegraphics[width=86mm]{figures-b}}%
  \put(80,78){b}
  \put(0,108){\includegraphics[width=86mm]{figures-c}}%
  \put(80,111){c}
\end{picture}
\caption{A multi-figure figure}
\label{f-FigureLabel}
\end{figure}

For final submission, journals like to have single eps files for each figure, so we need a way to make a single eps file from this. The trick is to use the preview and standalone environments. Create a file for the figure (e.g. fig-01.tex) with contents:

\documentclass{standalone}
\usepackage[dvips]{graphicx}
\usepackage[T1]{fontenc}
\usepackage[active,tightpage]{preview}

\begin{document}%
\begin{preview}%
%
\resizebox{86mm}{!}{%
% put \picture{} here
}%
%
\end{preview}%
\end{document}

do not include the \caption or \label, just the code for the figure itself.

Now run:

latex fig-01.tex --output-format=dvi
dvips -E -I 3c -o fig-01.eps fig-01.dvi

to produce a single eps file with cropped boundaries. This can then be included in the main document's figure directly.

Wednesday, 14 September 2011

Review: The Longest Winter: Scott's other Heroes (Meredith Hooper)

I've just finished reading: The Longest Winter: Scott's Other Heroes by Meredith Cooper.

The Longest Winter concerns the activities of the member's of Scott's expedition that were tagged on to make it look like some serious science and exploration was included in his plans. Initially the group of six were to be deposited on the Ross Ice Shelf to explore to the East, but this was foiled by the lack of a suitable landing site at the Eastern edge of the ice shelf, and the subsequent occupation of the Bay of Whales by Amundsen's expedition.

Instead, the party was sent West, initially spending a comfortable winter at Cape Adare, far to the North of Ross Island, at the same site occupied by Borchgrevink in 1899, and where a small ruined hut remains to this day. This was a disappointment for the party as they had hoped to be installed mid-way along the Victoria land coast from which they could explore routes to the plateau and collect useful geological information. The Cape Adare site was unsuited to exploration as the sea ice was uncertain (being affected by frequent storms, and having few points on which to be pinned), and rocky mountains prevented sledging access to the interior.

At the end of this first winter, the party was collected by the Discovery and moved to a site at Terra Nova bay, close to the Drygalski ice tongue, to spend a few weeks exploring before being picked up and returned to the main expedition at the end of the summer. Instead, the ship was unable to access their landing site on its return, and the six men were left with no choice but to make do. This is where the real story starts, but also where the least information is available from the men, and, in fact, where very little actually happens.

The party found that winter brings terrible katabatic winds, similar to those that would be experienced by Mawson during his first winter. Terra Nova bay, in fact, is now known to be one of the windiest, and least hospitable places to be outside of the short sunny months of summer. Lacking in supplies and shelter, a snow cave was excavated, a seal-blubber stove constructed, and as much meat hunted as possible. Survival was slight, and the winter passed with little activity and much suffering. At its end, the men resolved to make their own way out of their situation, and begun to sledge back over the uncertain terrain of the Drygalski ice tongue, and along the sea ice of the Victoria Land coast to safety at Ross Island. Somehow, mainly through the good leadership of Campbell and the wise planning of Priestley, supplies were made to last, and sufficient strength was obtained for the men to struggle back to the main party, only to meet the sad news that Scott was dead.

The book has its good parts. For the reader experienced in the literature much will not be new, as the story Campbell's party is interleaved with that of the other portions of the expedition, and it was not always easy to skip over the parts I'd read many times before elsewhere. The parts concentrating on the men stuck out near Inexpressible island are good, well researched, and tied together to make a strong story. I would have been happier had the book been shorter, and concentrated only on this strong material, but I can see the use of the wider context to those not already steeped in the story. Hooper also uses the same names as the expedition used to place the action. This is a shame as it misses much of the later lore lain over the land, and makes it harder for me to know where anyone ever is, but then I am very familiar with the modern geography.

Finally, some parts of the book will make you feel very cold, so I'd suggest reading it while in a warm bath...

Tuesday, 6 September 2011

Where to go in Antarctica?

Well, where to go if you can only go to Scott Base or McMurdo. Sounds obvious, right?

Maybe not... if you're a sun lover (and who isn't), you'll soak up slightly more rays at McMurdo than at Scott Base (assuming that you even go outside).

The following plot was generated by taking the sunshine energy arriving at Arrival Heights (just above McMurdo) and subtracting the sunshine energy arriving at Scott Base. Positive numbers (blue) correspond to McMurdo being sunnier, negative (green) mean SB was best. The red running line shows the 5 times exaggerated 7 day average of all years from 2000 to the present.


So, if you want to sunbathe, McMurdo's the place to pick, especially while the light is going or coming.

Monday, 13 June 2011

The Earthquake that killed Twitter?

[For New Zealand visitors, the quick solution is probably to use geographical searching, although sometimes Twitter cannot keep up with the work that it needs to do: (eqnz near:"new zealand"). Or use a filter you'll have to keep updating.]

There was another earthquake in Christchurch today, strong enough that I felt long period shaking four hours' drive away in Dunedin, which made me very worried about my many friends up the coast. I did what everyone does in these situations, popped #eqnz into Twitter, and found myself connected to the stream of reports and rumours.

Initially I was a little concerned as most of the reports were from outside Christchurch, with few from the city itself, but this cleared up as networks, phones and power quickly came back to life. For about twenty minutes I, and the world, had a great source of news on the happenings, and a great sense of relief that, basically, everything was fine.

Then, just as we wondered why this thing wasn't trending, even in New Zealand, the #eqnz tag finally got noticed by Twitter and the inevitable happened.

Spam.

Rapidly created accounts with nonsense but early in the alphabet names flooded the tag, and those for popular movies and memes, with links to modestly disgusting porn and SEO sites. Fine, try to scam some movie or the latest tween obsession, but an Earthquake? Please.

Anyway, these people, we already know, have no compunction about their activities, and merrily waste bits and oxygen as they usually waste our time, but when they instead clobber a useful utility in a time of crisis, well, that utility is less useful.

And this is where this is Twitter's problem. Me, and a hoard of well-meaning Kiwis did our best to block these bloodsucking scum from the feed, but, and this amazes me, it takes four clicks to get from the search feed to finally reporting an account, and then, of course, it's too late anyway, as the spammer's gone and made ten or twenty more.

Twitter could do something useful here. First, they can fix the reporting for spam by adding a single big button to press, right there in with the search results.

Second, while people found they could get better news by using geographical filtering (eqnz near:"new zealand"), this still hides a lot of useful information. Twitter need to provide a way to search based on the reputation and activity of users, allowing and making it easy to only see tweets from the trusted, from accounts that have existed for more than three minutes, and which have activity profiles consistent with their belonging to real people.

If Twitter can fix that, they might survive, but if they cannot, the whole service is going down the drain...

Update: It gets much better once the tag isn't trending globally. I really hope twitter can sort something out for the next big distaster.

Tramp: Roaring Meg Hut

So I was thinking to myself that there aren't enough tramps available on the internet, so there will be summaries of my tramps on here from now on.


Roaring Meg Hut

Target: Roaring Meg Hut
Start: Roaring Meg Picnic area / lookout on Cromwell-Queenstown road.
Time (Doc): 6-7 hours each way
Time (Me): 4.5 hours in, 3.5 hours out.
GPX (approx): http://the.earth.li/~alex/tmp/roaring-meg.gpx

Basically, you start at the Roaring Meg lookout, where there is plenty of parking and you can probably sneak in an overnight stay if you're tidy, walk past the sign in the picnic area and through the forest for fifteen minutes. You pop out on the 4WD track to the Roaring Meg dam/hydro scheme and follow this up the side of the Roaring Meg for about an hour, climbing gradually. After a couple of switchbacks to gain height in a small block of forest, the 4WD track descends to the dam, but you stay high and follow a thin trail above the true left of the Roaring Meg.

This trail is pretty easy to follow and has poles every couple of hundred meters. After another hour, you descend to the stream where you must cross the stream. I couldn't find anywhere to jump over the stream without getting my feet wet, and on the way out after some rain was wading to my knees. You now leave the stream and head a short distance along the side-gorge then turn right, climbing steeply for a little way to exit the gorge. A trail runs roughly parallel to the Roaring Meg, but a few hundred meters to its right, over rolling tussock covered hills. After about fourty minutes you descend slightly back to the Roaring Meg and a flat with a small musterers hut.

From here you have two choices. You can follow the poled route, which climbs an old farm track to the crest of the range, or you can leave the poled route and simply sidle along the gorge of the Roaring Meg.

If you chose to stick to the poled route, you ascend fairly steeply, following the course of a wee burn. At the crest of the ridge, you turn right and leave the roaring meg pack track (which continues down to Cardrona), and follow along the ridge for about a hundred meters before turning east and dropping down a track, reaching the flat with the roaring meg hut after about twenty minutes.

If you chose to follow the gorge, there is a faint track but you may sometimes find it easier to wade up the stream. The best route is usually about twenty meters above the level of the stream, on its right. After about fourty minutes you'll get to a flat and may need to cross the stream once or twice to avoid steep sides or miss out curves. The hut in on the left of the stream just above the old gold tailings.

The hut itself has 12 sleeping spaces, including a sort of double-bed type space. There is a fire and nearby poisoned pine trees for fuel. If you are lucky someone will have left you some dry wood, if not, you can get chopping.

I imagine this trip might have some hairy moments if there was a covering of snow between 800 and 1000 meters. From the hut you can go back to the Roaring Meg carpark, continue to Cardrona via Touhey's Gulley (the continuation of the Roaring Meg pack track) or follow a poled route away from the hut which goes over the tops to Lowburn.


Crossing the Roaring Meg



See also: http://www.smiths.net.nz/meg.html.

Friday, 3 June 2011

Saving me from myself

The great thing about using Perl to schedule the generation of your LaTeX documents, is that you can also use the Perl to catch a bunch of little mistakes that make life unpleasant in non-obvious ways. One of my favourites is to put the \label before the \caption in the figure environment, because, of course, in any sane world you could do that, but not in LaTeX. Thus, Perl to the rescue:

method check_figure_labels {
    my $file = $self->src;
    my ($in_figure, $seen_caption) = 0;
    foreach my $line (read_file($file)) {
      $line =~ s/%.*$//; # strip comments
      given ($line) {
        when (/\\end{document}/) {
          last;
        }
        when (/\\begin{figure}/) {
          $in_figure = 1;
        }
        when (/\\end{figure}/) {
          $seen_caption = 0;
          $in_figure = 0;
        }
        next unless $in_figure;
        when (/\\caption/) {
          $seen_caption = 1;
        }
        when (/\\label{(.*?)}/) {
          die "Label for LATEX figure $1 comes before the \\caption you will hate yourself later\n"
            unless $seen_caption;
        }
      }
    }
}

Also, sometimes I cannot spell the names of famous (and awesome) physicists:

method check_rayleigh {
    my $file = $self->src;
    my $latex = read_file($file);
    if ($latex =~ /raleigh/i) {
       die "YOU ARE A MORON! RAYLEIGH HAS A Y IN IT!";
    }
    return;
}

Tuesday, 31 May 2011

Perl needs another compile/run cycle hook

In my ongoing interest in Moose I see that you can make a class, thus;

use Moose;
has attr => (is => 'rw', isa => 'Str');
1;

and having made a class, you can make it be much faster by inlining a lot of the things that Moose makes, by declaring that the class is immutable:

__PACKAGE__->meta->make_immutable;

You can also use
namespace::autoclean
to remove the sugar that Moose provides so that your users can't call the sugar as useless methods. This is all a bit ugly, so I wanted a way to hide these in something you put at the top of your code, together, a bit like this:

package MooseX::autoclean;
use Check::UnitCheck;
sub import {
    my $caller = caller();
    Check::UnitCheck::unitcheckify(sub {
 "$importer"->meta->make_immutable;
 });
}    

which would push a UNITCHECK block into my caller's UNITCHECK queue and have it be executed once the caller's code was compiled.

This does not work, of course (in fact sometimes it segfaults, which is a whole different problem), because the caller (the Moose class you are declaring as you do this) has only been compiled by Perl at UNITCHECK stage. The compiled unit has not yet been executed to generate the class. Some other means is required to cause a block of code to be executed once your importing unit has finished executing, this might require the addition of another hook to Perl (er, UNITEND, I suppose) or some other tomfoolery.

Sunday, 29 May 2011

Moose the revenge

19:56 I continued my immersion in things Moose and dived past MooseX::Method::Signatures which was quite the groovy and on into MooseX::Declare. MooseX::Declare seemed like such a wonderful thing, until I wrapped it around my otherwise perfectly functioning class and BOOM! four thousand lines of errors and no idea why or where. Long story short, I'd coincidentally deleted the leading { in "$ENV{HOME}/blah" so the code inside the class was invalid. Fine, don't compile, but please DON'T JUST EXPLODE perhaps say why you've decided to explode and provide a useful error. I like Moose a lot, I'll be using it, but I'll be very cautious of any programming language (for that is what Moose is) which won't tell me where I've gone wrong.

20:00 Right, so now I'm going to go home and eat.

In which Alex learns Moose

Today I have decided to learn Moose.  I shall do this by converting my spider-web latex generation master script, now existing in four different incarnations, into an application class.  It will be easy! Or will it?  I liveblog myself, thus:

15:00 Finally decide to be productive (it is Sunday).
15:01 Decide to re-write generate.pl
15:02 type 'perl -MCPAN -e shell' 'install MooseX::Getopt'
15:12 While waiting for Moose to install, decide to liveblog myself.  The install is taking a whole long while...
15:16 Meanwhile, I have written this, which I hope will work:

package MyApp::Generate;
use Moose;
with 'MooseX::Getopt';

has small => (is => 'rw', isa => 'Int', default => 0);

1;

15:23 Still waiting for Moose to build and test and install. I'd like to at least run perl -c on my snippet to see if I'm a fool or not, but as yet, I'm ignorant even of my foolishness.

15:29 Oh, there we are, installed. Time to try the very basic:

use 5.12.0;
use lib "$ENV{HOME}/alexwork/perl/";
use MyApp::Generate;

my $app = MyApp::Generate->new_from_opts();

15:33 Well, that works at least. Now, to make things work. (This might take a while).
15:38 So, I want a list of somethings, but not have it be commandline-able, this can be done using an attribute with a leading underscore:

has '_lib' => (accessor => 'lib', isa => 'ArrayRef[Str]', default => ['lib']);

15:47 Well, that didn't work, an enormous error (can I stop these enormous traces?) tells me I can't have a reference as a default, but I can have a sub to wrap it, so I do that.
16:12 Importing the crufty methods and changing the million script-local my variables into attributes of the class. How do I get a the entries of a HashRef attribute?
16:15 By which I mean, get in a tidy manner. For now I'll just grab it and use it.
16:28 still bashing in methods. Wondering what the output of an 'ArrayRef' attribute will be, a list or a reference. Not immediately clear.
16:35 well, it runs, but I want to have my options just as '--nopdf'. Maybe I can't do this, that would be sad.
16:39 Ah, I need to make the attributes be 'Bool' then MooseX::Getopt figures it out fine. Not all sad, happy even.
16:41 Now having trouble with a builder method. It's getting called, I'm going to find out what with.
16:45 As expected, I'm now in a confused state where I'm not quite sure why this method is being called.
16:46 so it looks like it's being called as part of the ->new_with_options during object construction, so maybe the builder is called when a default value is created...
16:48 Yes, this is so. I've added a guard for the default case.
16:50 I've constructed my object, now I fail to access an ArrayRef attribute correctly. What should it be?
16:51 It is indeed an array reference.
16:53 Now it seems I don't understand what a builder is for. Perhaps I really just need to write my own set_foo which then sets other things (I have an option which sets lots of things).
17:03 Well, I didn't. A builder is a different way to set a default, but to be able to override this in subclasses. I really want a trigger which will then go and set the other attributes.
17:06 Hmm, I can't suggest a trigger to be a method. For now this isn't a problem.

has src => (is => 'rw', isa => 'Str', default => '', trigger => \&_src_set);
sub _src_set {
    my $self = shift;
    my $val = shift;
    return unless defined($val);
    $val =~ s/\.tex$//;
    $self->out($val);
}

17:14 This now works for the first script, let's see if I can impose the class on the other generation routines without too much crying...
17:25 Different journals have their quirks, so it's time for a subclass instead of a slightly different but otherwise the same script.
17:35 Well, that was nice and easy.

Moral of the story: That was really very easy.

Next is to use more than just Moose. I think I like MooseX::Method::Signatures; One trouble, with picking all this up, it's that it's not clear what's worth picking up.

Wednesday, 4 May 2011

Putting comments next to paragraphs in latex and emacs (fix fill-paragraph)

Again, this is just to save this for the edification of my future self.  For the rest of you, do avoid using 30 year old technology if you value achieving anything on a Wednesday.

So, I like to put little comments by my paragraphs in papers I'm writing:

% this is rubbish
blah blah blah


% this is just plain wrong
blah blah blah


% I have checked this and it is ok
dobedobedo bedadadada

Which is very useful, because this is the way to annotate the latex source so that I can understand why I've written what I did.  Now, the annoying thing is that I also like to bounce on M-q when I can't think of anything else to say, so my lovely paragraphs get turned into comments by the default emacs fill-paragraph command:

% I have checked this and it is ok debedobedo
% bedadadada

At which point the text disappears from my output, and I get cranky.

The solution is, of course, very simple but impossible to actually find (get it together google, you are now officially beyond being useless):

Get filladapt.el

Put it into site_lisp

And put this into ~/.emacs:

(require 'filladapt)
(add-hook 'text-mode-hook 'turn-on-filladapt-mode)

Also useful, discovered in an aside, is to associate files not with 'runemacs.exe', but with 'emacsclientw.exe' but then you have to set the environment variable to 'ALTERNATE_EDITOR' to 'path\to\runemacs.exe' OR IT WILL LAUGH AT YOU.

Friday, 11 March 2011

Sea ice breakup in McMurdo Sound, 2011

Our group installed an ice tethered profiler in the sea ice by Scott Base, close to where we spent much of the winter of 2009 working on the sea ice. If we'd been down there now, we'd have quite wet feet as the sea ice which had been in place since about 1998 has finally succumbed to a well-timed storm and has broken out. This is bad news for our ITP, as it has drifted to a position where the ocean depth is too shallow for the length of cable, so the poor unit is spending a lot of time acting as an anchor in the mud. Hopefully it will clear the coast and start working again...

Here are a series of satellite images taken around the time of the breakout, with the path of the ITP superimposed on them.


2011-02-20 (a big storm makes lots of waves, you can see the road from McMurdo to Pegasus as a white line near the profiler, with a tongue of water crossing it...)


2011-02-22 (the ice edge moves towards the profiler)


2011-02-23 (moved, stuck by the ice shelf)


2011-02-24



2011-02-25 (escapes from the ice shelf edge)


2011-03-03 (a few days later)

Monday, 10 January 2011

Antarctic exploration eBooks

Being a geek of all things Antarctic, and most things Arctic, I've dug out a number of out of copyright accounts of the early exploration, some of which are really quite good:

Worth actually reading:

Roald AMUNDSEN
Apsley CHERRY-GARRARD
Worth reading if you obsess:


Sir Douglass MAWSON
James COOK
Charles TURLEY

Sunday, 9 January 2011

What to do with your shiny Kindle

I have a Kindle, it hasn't changed my life, but it has changed how I'm reading.

After a couple of months of use and some experimenting, I've settled on a few useful things related to the Kindle which extend what it can do.

  • Calibre
    • Calibre organises eBooks and can download and format news to put on the Kindle.  This lets you add content without paying Amazon to do it through one of their subscription packages.
  • Instapaper
    • Instapaper collects together long articles from the web and will send them to the Kindle as a newspaper.  This works as a 'read it later' service.  It cannot deal with articles on subscription sites (eg. Nature.com) but otherwise does a good job of moving this type of reading off the web and onto a suitable device.
  • Economist print subscription
    • The cheapest way to read the economist in New Zealand is to get a UK print subscription.  This also gives you a web access code which, combined with Calibre, gets you a weekly delivery of the Economist to the Kindle.  Amazon's Kindle subscription is somewhat more expensive.
  • Make an  eBook
    • If you want to understand the Kindle's insides, it's useful to make a book.  Sigil is the best software I have found for this.
  • US/UK registration
    • Amazon restricts content available depending on your region, but does not know when you've gone on holiday.  If you're not in the UK or US you probably still want to have your Kindle registered to an address there, so that you can access the whole of the catalog.
The main pleasure of using the Kindle, instead of a bright PC screen, to read magazines and books, is that I can fall asleep while reading from the Kindle.  The passive screen and almost-book feel put my mind into night mode, while a bright PC screen with distractions keeps me awake.  You can also leave it out in the wind and not lose your page, very important in Dunedin.

Next crazy project is to use publicly available mapping data to generate custom map pages to take tramping with me.  Combined with some sort of waterproofing, this could be very useful...

Monday, 3 January 2011

You know you're not a real programming language when...

So, you want to do this:

myf = @(key, dir) if (ls('dir')) do_store(key, dir) end;

But you can't, as the syntax is only:

myf = @(args) expr


And expr can't be a conditional.

What you can do, to fake this, and display to the world that you are covered with infectious language lice, is hide the if statement inside an eval() call.

myf = @(key,dir) eval('if (ls(dir)); do_store(key, dir); end');

This, of course, only works for some use cases.

Now, most real languages have a ? : operator, so this isn't even an issue, but most languages with anonymous functions (lambdas, whatever) let you specify a whole code block, and even let you run it over multiple lines.

my $func = sub { ... };

If matlab let you define script local functions, this would also be less of a problem, as you could put the function body in the script file and reference its name, but you can't.  Nor can you access private/ functions from a script file.  Madness! And people wonder why scientists write disturbing code.  We really have no choice, sometimes.

Thursday, 11 November 2010

Everyone in New Zealand should get a Kindle

Yes, yes, I know, you could get a Kobo from Whitcoulis, but, you see, Whitcoulis are the problem. You pay far too much for books in New Zealand. So much, in fact, that in living here for two and a half years I've only purchased one full price book, and that was a present for someone. It's not that I don't read, back in a sensible country I'd spend the cost of a New Zealand book every couple of weeks, but I'd get three or four books for that. I just feel that by buying a book here I'm being screwed. No longer, though, a Kindle, or another foreign e-reader, lets me get something worth reading, right now, for less.

With this in mind, I make the following prediction: all middlemen in New Zealand selling something I could just as easily download, should get themselves a new job. Bookshops, music shops, DVD shops, computer games shops: you're all doomed. Second hand bookshops, second hand CD sellers, second hand DVD and second hand computer games shops: you're even more doomed. Convert your premises to sell fluffy sheep keyrings to tourists, set up something better than the 4-D trout experience, or morph into a coffee shop and you might just have a livelihood. Continue to sell things in a cold shop with no natural light and surly attitude that I can get more cheaply without even getting out of bed, and you're doomed.

And don't even get me started on supermarkets and the price of cheese.

(Update: 2011-02-18: NZ Herald - Whitcoulls in Administration)

Friday, 29 October 2010

proj4 and Perl for windows

All amazing people the world over use Perl to get stuff done. Sometimes the world conspires to make this a tiny bit harder than it should be. Today I want to convert coordinates using the proj4 library, but could not because the geo::proj4 library doesn't build nicely under windows. But, ugly to the rescue:

2) Do the ugly:

# this works, would you adam and eve it
sub coords2pols {
my ($lat, $lon) = @_;
if ($lon > -50) {
($lon, $lat) = ($lat, $lon);
}

open my $fhi, '>tmp.txt' or die "tmp file $!";
print $fhi "$lon $lat\n";
close $fhi;

system('cs2cs +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +to +proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs tmp.txt > tmp.out.txt') and die "$@";
open my $fh, '
my $line = <$fh>;
close($fh);
chomp($line);
my ($x, $y) = split(/\s+/, $line);
unlink('tmp.txt');
unlink('tmp.out.txt');
($x, $y);
}

Tuesday, 5 October 2010

LaTeX and windows

Oh yes we hate it we do. LaTeX + Windows = Pain. Well, actually, writing large documents anywhere = pain. Here, though, a trick to make some of the pain go away! (Posted for my future reference.)

First: Perl! Emacs! (If not, this will be senseless...)

Use a perl script to generate your pdf. Easier than a makefile, better than a punch in the face.

When running pdflatex, use the '-synctex=-1' option.

Then, at the end of the generate script, use SumatraPDF to view the file:

exec($pdfview,
'-reuse-instance',
'-inverse-search',
'"c:\\Program Files (x86)\\Emacs\\emacs-23.1\\bin\\emacsclientw.exe +%l %f"',
"$out.pdf"
);

This is fantastic, as it will reopen the pdf where you last looked at it (which is what you probably want) and you get to clicky on bits of the file and get them come up in emacs (which is also what you want to do).

Oh yes.