Saturday, December 31, 2011


That's the cumulative cycling mileage at the end of the year, passing the 3200 target I wanted to hit (~2170 over the year, plus the 90-odd on a hired bike to make over 2250 total). That's omitting those miles where I'd forgotten to put the widget back in place to count the distance; but that is unlikely to be more than about 5 miles total, and could be made up with distances pushed anyway.

I think it goes to show how dry the weather was for much of the year.

Anime -- 2011 in review (part 1)

In total, I have watched all through just 3 series from the last year, am in the middle of two that have completed, one that hasn't and am about to start on one that has. Plus a scattering of older shows finished or in train. This post, old shows considered.

Mobile Suit Gundam

I remember when the future looked like Gundam - O'Neill colonies throughout the Earth-Moon system, but no internet. Now add brutal robot combat, the usual Tomino level of named character futile deaths, mixed with toy commercials. Like the following year's Space Runaway Ideon, this has an element of a treadmill, where each episode the enemy -- here the L2-based Principality of Zeon -- uprates its mobile suits each episode and our guys with their carrier and mobile suits continue to level up to meet them.

After ten episodes of this, the action moves ground-side, with a long meander from south-east Asia, through to the Black Sea (with a number of side trips -- "we need to reprovision with salt"; our hero has an angst attack and has wandered off with the Gundam; ...) thence to Ireland (where we meet a traditional red-headed Irish girl, with the traditional Irish name of Miharu), then across the Atlantic to a Federation base in South America, having circumnavigated the globe rather than going direct.

Then, finally, we return to space for a series of skirmishes, culminating in an escalating final battle where pretty much everything gets destroyed; but the power of Zeon is broken and all seems well (until the next series).

Even after 30 years, and with an indifferent American dub, the series holds up as more than just a piece of history. The anti-war message may be unsubtle, but there is a feeling of how even the significant players like the Gundam team are just a part of a larger concern; and the daring and charismatic recurring antagonist, Char Aznable is in turn just a minor, though equally significant, character on the Zeon side.


A quirky little flash series about a down-and-out in an alternate Canada peopled by anthropomorphic cats. It's slice of life anime done right. That means without any cute girls, school, or even cake, but with a whole lot of drinking, swearing, bowling, getting beaten up, and freezing to death on the street. And catchy ska BGM from the Planet Smashers.


Images quoted for purpose of review.

A series I passed by back in the busy year of 2008, as another cute girls at school series like Hidamari Sketch or Sketchbook Full Colours; but which turned out to have rather more energy and enthusiasm about what it's doing. We start by having the ditzy bonde Ayumi as the first viewpoint character lost in her vast new school, then accumulate the oujo-sama Tatsuki (also lost), and the core group is then completed by the sudden eruption from an upper storey window of the tomboyish Torako, followed by her constant companion, Suzume (who are solving the navigation problem by heading in a straight line).

The series takes a little time finding its feet, and goes thematically all over the place, from out and out comedy, to amped-up melodrama; but as we learn about the quartet and the rest of the class of equally idiosyncratic types, everyone is refreshingly nice (except for the boys in the senior years, who are jerks, and Torako's family, who exist mainly for injecting drama).

Not an undying classic of the ages, but still a nice feel-good series to have watched over the holidays; especially as it was set in early summer, sunny and bright, a perfect antidote to the midwinter blues; the one exception, the April rainstorm that opens the final flashback episode, where the melancholy dawn of the first day of the school year breaks. That scene was the one where the incidental music was most noticeable, and it seemed to fit the bitter-sweet flavour of the whole episode.

Natsume Yuujinchou -- seasons 1 and 2

Another series from 2008 (and then 2009); somewhat like Mushishi, in that Natsume Takashi has the ability to see spirits that pass by normal people unobserved. However, unlike the competent adult Ginko, who has to deal with fungal or insectile mushi, the youkai that highschooler Natsume can see are people of a sort.

This unsettling aspect of his life, reactions to and conversations with the unseen, has left him shuffled from relative to relative. This time he also stumbles across some of his late grandmother's possessions -- including the eponymous book in which she inscribed the true names of many youkai; and into a shrine where a powerful spirit is bound who Natsume accidentally frees.

Having spent many years bound in the form of a lucky cat, the spirit now appears as a human-visible cat most of the time; and sets himself up as Natsume's bodyguard : no-one else is getting that book but him.

So with the rascally Nyanko-sensei to guide and protect him, he starts to find and unbind some of the youkai in the Book of Friends. The series thus starts as a simple monster of the week; but as the extended cast is gathered, it becomes as much about resolving problems amongst the youkai, and Natsume worrying about how his life is balanced between the two worlds.

While being much the typical anime protagonist most of the time, the show avoids getting Natsume into any of the usual romance clichés, without actively excluding girls from his social circle (such as it is). The fact that many of them are spirits, and one explicitly declares that she was much more interested in his grandmother, helps avoid that sort of thing.

So a quiet and delightful little series; and in the new year, I shall move onto the recently aired 3rd season, and the about to air 4th.

Wednesday, December 28, 2011

Film -- The Adventures Of Tintin: Secret Of The Unicorn

Last cinema visit of the year, catching the holiday re-run of the film.

Not having read any of the source material in decades, I didn't worry about anything that might offend purists, but enjoyed the cartoony inter-war era high adventure in the style of what I did recall.

We will know that the CGI medium, especially in its 3D expression, is mature when they stop showing off gratuitous mirrors and lenses.

Tuesday, December 27, 2011

Writing StyleCop rules in F#

Alas not "Writing StyleCop rules for F#" (or should that be StyleFop?), which would be nice, but a true job of work...

I don't see much need for more StyleCop rules for C# (except one to harness the FxCop spellcheck facilities to scan comments, which would have to be done via much dodgy reflection to winkle out internal types, and would anyway give issues for being tied to 32-bit native executables), so haven't tried this before. But, like mountains, it's there...

So, you have StyleCop 4.5 or 4.6 installed, and start by creating an empty class library targeted at the .net 3.5 environment, with added references to the StyleCop and StyleCop.CSharp assemblies. The bare rule class looks like

and to go with it, add an XML file as an Embedded Resource with name My.Namespace.MyRules.xml -- first gotcha : the long name needs to be given in full because the default namespace doesn't get applied in the build like it would for C#. That can then be filled in as per the instructions in the StyleCop SDK documentation. Then just override the AnalyzeDocument method and go wild:

where I'm using the concept from the StyleCop+ rule SP2000 as an example of a new rule not yet present in the core tool.

Unlike FxCop, there is not a "one class = one rule" model here; the classes exist to group related rules, and you control how each scans the current source file of interest, and, indeed, how distinct they are in the code -- a closely related set of rules could be checked off a single scan, and in some ways StyleCop rules are more akin to the distinct named resolutions that can be defined within a single FxCop rule.

Another consequent difference from FxCop is how the object graph is visited. In FxCop, there are VisitXxx methods to override that will be called for every object of type Xxx, in an essentially stateless manner (your rule class is responsible for maintaining state between calls); here the equivalent methods are passed to a WalkXxx graph walker method as a callback, provide a mutable state object argument, and can signal through their return value whether the traversal should continue.

This approach of using a mutable object, needing down-casting, to carry inputs into each call, and contain the resultant outputs, feels a bit odd in a functional environment; fortunately it is possible to bypass this in many cases by representing the tree-walk as a seq and operating on that. For the trailing whitespace rule, where the offending lines are most easily found by scanning the raw source line by line, all we need the traversal for is to find an ICodeElement context object matching that line number. A simple walk of the code element tree looks like

which we apply to the document RootElement and from the result find the last (so most deeply nested, and hence most constrained) item whose Location has a span that includes the line number of interest (skip while the end is before the line of interest, take while the start includes the line, reverse, get head), the line number being a value that the operation can close over.

For deployment onto machines that don't have F# installed, static linkage of the runtime via the --standalone build flag can be used rather than having to explicitly drop the F# runtime assembly into the StyleCop folder (second gotcha).

Monday, December 26, 2011

A mild Christmas, a welcome change

Friday, with the temperature about 5C, and strong sou'westerly blowing, I cycled to work, thinking all the while that I was mad for doing so, with a weather forecast for rain, mainly heavy, in the afternoon. Unlike last year, there wasn't the need to wear anything over my spandex shorts for warmth, so that would be enough to mitigate the worst of cycling in the rain. As it turned out, when I set off home a while after 2, it was starting to sprinkle with rain; eventually getting heavy enough to want a waterproof, but not really uncomfortable at all.

Saturday, a muntjac wandered into the garden, and ate some of the remaining windfall apples, the ones too small or damaged to have harvested. The cats were not amused by this thing invading their territory, and kept a wary eye on it from a distance, and well away as it wandered off again. At least it was too big to fit through the cat-flap, unlike pigeons or the various rodents whose entrails at times have decorated the kitchen floor; more like the pheasant that was left on the doorstep, with just a clear cat-inflicted bare patch on its neck a couple of weeks ago.

Yesterday began with the exchange of presents -- where I got Vinge's latest, novel, The Children of the Sky, the long awaited sequel to 1993 Hugo winner, A Fire Upon the Deep; and Tim Worstall's book of essays on economy and the environment Chasing Rainbows, which metaphorically in text is like suikawari without the blindfold; and then lunch.

Having not thought to book until 5 weeks ago, we had a simple enough choice of places where there were still slots to be had -- lunch at the Carpenters Arms.

This was a leisurely affair, 12:30 for 1, canapés, starters, then buffet style mains, where I was unable to take up the offer of a third helping, before the cheese board, a little Xmas pudding, and coffee with petites-fours; and so home in gentle fashion by not too long after 5pm.

So today could be pure R&R, with just a little bit of pottering in the garden for some fresh air -- clearing the tomato plants out of the greenhouse, hoovering the lawn (to get rid of fallen leaves), trimming where it had straggled over the borders, and clearing the few places where plants had stopped for the winter and obligingly dried up (the marigolds are still in flower, as are the antirrhinums; not just the viburnum which I'd expect to be flowering now); leaving a little space in the green bin for more gardening later in the week.

Some of the sunflower heads that haven't already been stripped of seeds, I hung up for the birds; and the last handful of rosebuds are in a vase by the fireplace. And so the garden remains in a late-autumn limbo, until I really can't postpone pruning the roses and apple trees any more.

Wednesday, December 14, 2011

An approximate type-based solution to the strings problem

As ever, neat ideas coded in Haskell can be almost but not quite ported to F#, foiled at the last moment by the fact that the .net type system cannot represent constructs that are expressed as Haskell type classes : there's always a run-time type coercion and some leakage of abstractions that have to be coded around.

One such is this idea of type-safe strings for representing structured data like XML -- which would require a little more mutually recursive and self-encapsulating type definitions than I think F# can manage. It gets close, though, and could probably be embellished a little further:

Deleting files, keeping a few -- in Python

And the same again, only as a script, just because:

If there wasn't that comparison function to write, it'd be terser...

Tuesday, December 13, 2011

Deleting files, keeping a few

Inspired by this post, how it works in PowerShell:

will delete all but the most recent 3 files ending in ".log"; and it would be the same sort of thing in any scripting language.

Sunday, December 04, 2011

Lovely weather for the time of year

The garden today

The garden today

A year ago

A year ago

Yesterday was a mild and sunny day, so I took a spin out in the countryside, stopping at the Carpenters Arms for a light lunch, of pumpkin and parsnip soup and a ham and cheese toasted sandwich. It was great to enjoy the chance to get out on the bike again -- as it seemed did a number of the lycra crowd, though fortunately they don't seem to hunt in packs at this time of year.

What a contrast with a year ago, when needing to go into town, I wrapped up with long-johns, heavy gloves, multiple layers, goggles, just leaving my nose exposed -- and regretting that for the first couple of miles before getting properly warmed up.

Monday, November 28, 2011

PowerShell and GTK-Server

Another little five-finger exercise, porting the example VBScript stdin driver to PowerShell. The only annoying thing is that the Start-Process cmdlet doesn't give you direct access to the streams, so we have to drop into .net to fire up the GTK server process.

Friday, November 18, 2011

Another PowerShell egg-timer (using events)

Recording a learning exercise for how PowerShell handles events, and how to communicate into event handlers

Note that every registered event must be unregistered (otherwise running the script leaves droppings in your PowerShell session in the form of those claims on events). The events that are handled -- the timer 250ms wake-ups -- are consumed by being handled; but the one that is merely waited on remains latched after triggering the wait to release and must be explicitly cleared.

Additional AV frills would be the same as any of the polling loop timer examples out there.

Sunday, November 06, 2011

C# : The null object pattern and the poor man's Maybe Monad

Lots of people have re-invented the Maybe monad in C#, as a simple search will show, usually as a way of bypassing null checking if statements and to be able to write code like

But we have the tools given to us already if we observe that null has no type -- as we can see when

reports a length of zero!

So our Some<T> is just a length-1 IEnumerable<T>; and None<T> an empty one -- the null object pattern, in fact.

For the price of having to specify types at each stage -- as we would anyway have had to in the past for declaring intermediate the values to test against null -- we can use existing methods to finesse the null check. Returning to the borrowed example, it would be

The monadic return monad extraction operation is just FirstOrDefault(); which is fine for reference types. Value types are different in any case as we wouldn't be null checking those -- as the later steps in a chain though, stopping at the filtering to the value type and making an Any test may be preferred.

Looking at value types, switching to this example, the code looks like:

which leaks a little bit in that we have to do the monadic return monad extraction by hand at the end, but otherwise behaves exactly as the explicit monad implementation.

Monday, October 31, 2011


That's the cycle odo at the end of the month, well over my stretch goal for the month of hitting of 3000. The question now is how far over 3100 by the end of the year.

And then to see what I can do by the end of next June : in order of difficulty, 2000 miles in the year, to 4000 recorded, to 1000 miles in the half year.

Saturday, October 29, 2011

F# -- where has our Roslyn been?

The big thing about the new Roslyn CTP is that it's a C# compiler built in C#, so accessible simply from C# code via a standardized set of APIs; including ones that permit parse tree rewriting (and hence DIY language extensions) as well as giving a more official mechanism for such things as source-level inspection (e.g. StyleCop). Indeed, the lack of any such managed language service for VB is a reason that there's no StyleCop equivalent for the other major managed language.

F# has had the managed compiler from the start -- but presumably (as I've not noticed anything being done with it by way of meta-programming or suggesting coding conventions in the manner of StyleCop) not the suitable APIs. There is a project or several here for someone to take up.

F# under the covers XIV -- Match expressions : Does my complexity look big in this?

The code generation in F# in debug builds is fond of adding plenty of extra branch points that will confuse any naive computation of code complexity based on counting branch instructions at the IL level. Let us take the innocent method

The instructions that map to the match alist with context include

where the first branch could be replaced with a brfalse.s IL_0044 and the code at offsets 0xb, 0xc replaced by nops with no change in the semantics -- but as given it adds an extra cycle to the flow of control graph, and hence false complexity.

The release build of the code retains the first two instructions, but then rather than jumping to get and return an empty list, it in-lines that fraction of the code. If we look at it in C#, the release build looks like

where the debug version has a goto in that if clause that jumps to a statement that returns the empty list.

As an aside, it's also worth noting that nowhere in the .pdb information is there a map to any of the match expressions : there is never a source context which matches the | h :: tail -> or | [] ->; it's all collapsed into the match ... with fragment.

For more complex match expressions such as

the debug IL organizes into trying each of the branch criteria in turn, then jumping ahead to the matched expression; this ends up with a series of redundant branches like

culminating in a final triple burst

whereas the release build treats it more as an if..elseif..elseif..else construct.

As I noted yesterday, this means that there can be a factor of at least two difference in the naively computed cyclomatic complexity of a method depending whether the release or debug build is chosen.

Friday, October 28, 2011

Computing cyclomatic complexity with PowerShell and FxCop

A measure of the cyclomatic complexity of a .net method can be gauged by counting the number of IL branch instructions that do nor branch to the next instruction, and which have a distinct target from any other branch -- this is essentially the algorithm used in NDepend 1.x to make the computation. The introspection mechanism of FxCop provides enough decompilation of the IL that getting the instruction type and offset, and the target offset of a branch. An actual FxCop rule, though feasible to write, however, would be less useful than one could hope.

For one thing, FxCop itself doesn't provide any convenient way of passing parameters to custom rules (to e.g. set a trigger threshold); and for another, any analysis is likely to be run over a debug build (DEBUG and CODE_ANALYSIS variables defined there to not contaminate the released code with [SuppressMessage] annotations), which is likely to have a different underlying complexity to a release build (this is especially true in F# debug builds where there are a lot of sequences that look like

which can be replaced by

which, as it turns out, is pretty much what the release build does.

A more configurable and flexible way of performing the operation is to drive the FxCop facilities from a script -- these days I'm doing a lot of my .net scripting in PowerShell, but it could equally well be done with IronPython or similar .net scripting language. The result looks like this:

and running it over a set of F# code shows that the reported complexity of the release build of a method halves (or more) what is reported for a debug build. I haven't made a comparison over an significant amount of C# as yet, to see how much complexity the compiler removes between the two configurations.

Wednesday, October 26, 2011

End of Season Cycling

View Autumn 2011 in a larger map

The autumn having settled to being bright, mild and breezy, a last chance to have a cycle break before winter -- indeed I was apparently the last customer of the season at Suffolk Cyclebreaks; going through the south of Suffolk and the north of Essex, which I haven't done as much as places further north in the region.

An early start on Sunday took me most of the way past Ipswich by shortly after midday; though having been pointed at the restaurant at Wherstead Hall, I'd aimed for that, rather than again to the Butt and Oyster at Pin Mill, taking the bridlepath past Jimmy's Farm to cut the corner, and only have to do a little way along the main road until diving off into Wherstead village. The concrete track past the church brings you to the "hall" -- a large modern building, housing a local produce market, garden centre, and restaurant serving locally sourced food -- for me, a cheeseburger with local beef and cheese, plus a bottle of the local lager.

A14 bridge over the Orwell

A14 bridge over the Orwell

From there, I carried on along the coast, deciding as the hour was advancing (past 1:30, but in the low sun, feeling later) not to detour to the Butt and Oyster for more beer; but carried on, until suddenly happening upon the Baker's Arms at Harkstead, which advertised food still being served, let alone beer, so had a pint of Wherry, before carrying on. The official route as I took it last weaves a long way to fit through crossings of the Stour and the A12. This time I decided that being a quiet Sunday afternoon, the main road through Manningtree would be a simpler route, arriving at Dedham by 4pm -- and the Sun Inn was open, and serving amongst others, Arizona Bitter (Phoenix Brewery) and Wolf Bitter (Wolf Brewery). Thus fortified, I reached Milsoms (which in the last three years has realised that it makes no more sense to charge separately for wifi than it does for hot water).

Dinner was bresaola, king prawn and green mango curry, and lemon cheesecake, with lots of mineral water; and then with the windows closed in the cool night, not even the steady drone of traffic on the A12 disturbed me.

Morning, fortified with a full English, etc, I decided to avoid the rather unpleasant country between Dedham and Stoke-by-Nayland, and head rather directly to Hadleigh (where I got tricked by the cyclepath again), pushed up the long grind after crossing the A1071, then with most of the pubs mentioned in the guide being closed Mondays, struck straight cross country to Sudbury (cadging a coffee from my surprised parents), before taking a loop west on the way to the night's rest at Lavenham.

Partly guided by the OS map's PH markers, I struck through Glemsford, to find the first two pubs closed at lunchtime, and as it was close upon 2pm, I was despairing of finding a place to pause, when suddenly, the Cherry Tree Inn "Open all day for quaff and scoff". There was one other customer there when I went in, but more regulars drifted in as I committed a couple of pints of shandy, and I ended up joining in the attack on the Times' crossword.

Then when I could justify hanging around indoors on a glorious sunny afternoon no longer, made the last leg to Lavenham, parking up at the Angel. I took a bit of a wander around, including a pint at the Greyhound (where a greyhound wandered out from behind the bar and looked for attention), before dining at the hotel -- potted duck with Agen prunes, shepherds' pie with peas and spinach, then the cheeseboard; which I was ready for, having not actually felt the need for lunch.

The rain, which long range forecasts had suggested might wash the whole holiday out, went over in the night, leaving it somewhat raw but otherwise fair cycling weather in the morning. Approaching Gedding, there were some diversion signs, and I saw that the route I was planning to take was marked as road closed. But then I saw that the other end of the closure was a few yards away, and between, just a fenced off hole with more than ample room to cycle past; so I went on as I intended, until just after midday, when the Brewer's Arms called.

A burger of local red poll beef, and a pint later, and the sheet of cloud that had been hanging overhead all morning gone, I decided to amble north of the A14, then loop through the lanes back to Alder Carr farm. This time I ran into a rather more serious road closure on the approved route, but fortunately I could back off and take a separate cycle path through the new development.

And then, shortly after crossing the A1120, a sudden rattle rattle pop! as a bulge near the valve on the back wheel finally wore through and the inner-tube burst spectacularly. At least it was warm and sunny, and the road quiet, as I replaced the inner tube, moved the tyre around, and pumped up to do the last couple of miles. I suspect the tyre may be a little narrow for the wheel, as the new tube is also bulging in the same way. Still, now it'll soon be past the end of BST, and cycling to work, I can put it in for a service and get everything replaced that needs it.

With all this under the wheels, my odo is now well over the 3000 mile mark, getting me well past my stretch goal for the month.

Tuesday, October 18, 2011


Back at the end of June, I was hoping to have managed another 1000 miles on my bike by the end of the year.

Tonight getting home, on a clear if breezy day, the odo was showing 2908.4, or 1001.6 miles since then. The question now becomes whether I can roll it over the 3000 mile mark before the end of the month, let alone the end of the year!

Harnessing the PowerShell command line parser in .net

One of the annoying niggles about the .net framework is the lack of an intrinsic command line parser -- yes, there's Mono.Options or the F# power-pack, but they're not always just there to hand. PowerShell is there on Win7 and up, and is likely to be there on machines with older OS versions in a suitably technical environment, So if you just want to whip up a simple command line tool, and you're not writing it in PowerShell, why not at least borrow its features?

First, we want to get the argument list as provided -- for this we have to get the semi-raw line via Win32 (semi-raw as the shell will already have processed escapes -- in PowerShell that means that backticks, semi-colons and double-dashes are significant):

This uses the PowerShell tokenizer to strip out the executable name. We also want to be able to describe what the command line parameters are like, and other usage text

Then we can build a PowerShell function that takes the parameters we've defined, and just places them in a hash : this is the meat of the exercise

For producing a usage description, we can ask PowerShell for one, flatten it to a sequence of strings, and then strip out the unwanted PowerShell-isms

Finally, we can parse a supplied command-line, writing a failure reason and usage info if things fail

A simple example driver would be

There are some quirks -- Mandatory positional parameters and arbitrary nameless options don't mix : the current example program if given a command line "-Val hello -N 23 -S a b c" will yield

"$args" -> [|"a"; "b"; "c"|]
"ValueArg" -> "hello"
"SwitchArg" -> True
"NextArg" -> 23

Make NextArg mandatory, and instead it goes

A positional parameter cannot be found that accepts argument 'a'.


    This is the synopsis

    ConsoleApplication1.exe [[-ValueArg] <string>] [-NextArg] <int32> [-SwitchArg]...

So, perhaps not industrial strength; but suited to gentle use when there's nothing else to hand.

Sunday, October 09, 2011

Links for 9-Oct

The world has moved on, have you? Xml APIs you should avoid using. (Microsoft XML Team's WebLog) -- tl;dr = XmlText* classes should be retired in favour of objects minted by Xml*.Create() factories.

5 Awesome Free jQuery Plugins -- toast, sliders, tickers...

What you see vs what you get : matching source and IL with Mono.Cecil and PowerShell

Following on from yesterday, looking at how Mono.Cecil pairs up debug information in the .pdb file with just the sequence points the IL -- which follows the approach taken by coverage tools such as dot-net-coverage. The code is much the same as before:

with the addition of the line/column data in SequencePoint ("null" if the values are not given, "0xfeefee" for the well-known compiler generated fake line number).

Saturday, October 08, 2011

Launching PowerShell 2.0 into .net4 via F# Interactive or IronPython 2.7

With .net4 being 18 months old, and the Win8/PowerShell 3.0 being both in CTP and only for Win7+, it's a drag having to do things with .net 4 code when you really could do them faster and better in PowerShell. So, why not bootstrap ourselves from out of the box PowerShell 2.0 into the .net 4 world with a little help from another scripting language which is .net 4 aware? This saves messing about with environment activation variables, centralized registry settings or application config files, and takes advantage of the fact that PowerShell, like other scripting languages, can be hosted by another .net process.

The recipe is based around Bart de Smet's Option 2 – Hosting Windows PowerShell yourself.

Via F# interactive:

Via IronPython 2.7 (augmented to take command line arguments via the -Options parameter):

Since we can't pipe into Start-Process, the inner script is written to a temporary file; and then the initial PowerShell process waits so that it can safely delete it. If you would rather, it's reasonable to save the script to a constant .fsx or .py, replace $source with the path to that file, then the -Wait and Remove-Item -Force $source can be removed.

Replacing the fixed command line arguments for the F# interactive launched PowerShell with ones input to the script as per IronPython follows the same pattern. In either case, care has to be taken with getting your quotation marks right, and the IPy example is rather rough-and-ready. Besides, doing appropriate quotation parsing and escaping would obscure the real point of the exercise.

Note: Launching PowerShell directly from the .net4 command line launches PowerShell in the plain old .net 2 configuration; it is, alas, not sticky.

Note: These scripts are intended to give you a .net4 based interactive session; an alternative approach aimed at running individual commands can be found on Jason Stangroome's GitHub.

What you see vs what you get : matching source and IL with FxCop and PowerShell

The mapping between the code you write and the object code that gets generated is not always a simple one; F# code in particular is heavily restructured in the compilation phase. So when trying to perform code analysis to detect source level artefacts in the compiled code, some guide is useful to navigate between the two representations.

So, here is a PowerShell script to do just that, looking at the IL instructions or logical statements for a method and the corresponding source code as given via the .pdb debugging information -- PowerShell rather than F# interactive because the former has a much nicer user interaction model, especially when asking the user to resolve which overloaded method name was really intended.

As the script writes rich objects in the successful output to pipeline, it can be used as a starting point for further analysis; or the output can be piped into e.g. Out-GridView for inspection.

Sunday, October 02, 2011

Summer at last

So, we get the hottest days of the year at the start of October : it's like summer was put on back to front, going from warm, to April showers, to autumn, to high summer.

After clocking up to ~2705 miles in Q3 -- 800 miles in the quarter -- I took a ~40 mile spin on the bike yesterday, with lunch at the Carpenter's Arms in Gt. Wilbraham, then carrying on out past Six Mile Bottom, West Wratting, Balsham and back. With the lack of wind, and low humidity, it was a beguilingly easy ride (apart from the long grinds up out of Six Mile Bottom towards Brinkley; and from West Wratting to Balsham). So easy, that it wasn't obvious quite how much I was sweating, and thus how much I needed to rehydrate, until I finished a 75cl bottle of Lucozade Sport in pretty much one gulp.

In the evening, it was still so warm that we sat out in the garden until well after sunset, something that we never had weather for over the nominal summer.

Thursday, September 22, 2011

Recent reading

Kethani by Eric Brown

Aliens send artefacts to Earth to enslave the human race, as told through the perspective of the inhabitants of a Yorkshire village with an unusually high rate of cancer and suicide. Nobody seems to notice what the aliens are doing, not even the author.

Cosy British SF as it is done at the start of the new century.

Yellow Blue Tibia by Adam Roberts

Cold War nostalgia in a tale of an SF writer given an unusual assignment by Stalin, and then being told to forget everything, which works for the next 30-some years. Spends a long time setting up the mood, then infodumps a not-quite-resolution.

Rocket Girls and Rocket Girls: The Last Planet by Housuke Norjiri

The two light novels (each slim enough to finish during one bathtime) that were the original source of 2007's delightful anime series, now available in English. The anime was a very faithful adaptation of the source material -- just omitting the by then very dated visit to Mir at the end of the first book, and segueing that mission into the one at the start of the second.

Ouroboros Wave by Jyouji Hayashi

A series of almost puzzle-driven hard-SF shorts scattered across several decades in a fairly standard Earth vs space colonists setting -- a very modern execution of something that was at one time almost the backbone of the genre.

Friday, September 02, 2011

A summer evening at last

After work, along with a couple of colleagues, I cycled to the Toft Beer Festival, where we sat at the table outside in the warm evening sunshine and enjoyed the beer, until it came sunset, and time to be heading home.

For the first time this year, the warmth lingered as the light went. It was pleasant cycling in shorts and T-shirt; and even just a few minutes ago, going out to drop tea-bags and apple cores into the compost bin, wearing nothing but a towel around my waist, the paving was warm underfoot, and the air mild long after sunset.

I had in the past come to expect the light to be going before the warmth through July, but not so in recent years. Now that is a most unusual thing to happen until an Indian Summer day like today.

Sunday, August 28, 2011

Cambridge Film Festival

I pretty much started this blog as as a home for "My Cambridge Film Festival film reviews", however much my blogging has mutated over the years. And this weekend, the programme for this year's CFF is out -- and even more than last year, I'm feeling underwhelmed by the torrent of gritty and edgy features, right-on documentaries, and the usual run of "there's adultery in it, so it must be artistic". It's like it was all set out with a ground rule of "No fun allowed, SRS BZNS ONLY". Oh, and they're exhuming and showing the totally abysmal Silent Running (down there near the nadir of my list of the worst movies I've watched). Twice.

I suppose I could go watch The Seventh Seal and The Day the Earth Caught Fire again; but apart from being in two minds about this locally produced film, Dimensions (which could be another Time Crimes, but could equally well be artsy tosh with a few bits of stage dressing like non-genre writers generate when thinking they're doing SF), the new material singularly failed to catch my eye.

Thursday, August 25, 2011

Late summer cycling break

Same sort of gig as last year, only with different weather.

View August 2011 in a larger map

This time I arrived in Great Bircham about 10:30 on a beautiful summer's day, and headed out on the long run I'd meant to do last year, without the interruption by squall lines.

With the later start, I reached Little Walsingham after the first course of packed lunch (stopping for a pint at the Black Lion), and then kept going east as far as Binham (another pint at the Chequers Inn -- which, despite the name, does not seem to offer accommodation, but would have made a good base for another time), then looping back.

Second course of lunch -- cheesy rolls and a beefsteak tomato from the greenhouse -- at 15:00, partway along the coastal cyclepath, before heading for the first time through the grounds of Holkham Hall from the north. I'd steered clear of it, having previously taken other paths from the south which didn't make good cycling.

This side, the paths were properly made, easy going up and over the rolling terrain, then rolling downhill most of the way to Burnham Market; then the grind up the Ringstead road was where my legs started to tire, but still back to base not long after 17:00, having done about 48 miles.

Tuesday was wet, so read, did internet and generally rested up, with a little stroll around the local area late afternoon.

Wednesday was dry, if cool and generally cloudy, so another clockwise loop through the area (with one misstep when the path I'd meant to take was less obvious on the ground than the one I didn't), through lanes I'd mainly not taken before, with the goal of lunch at the Gin Trap Inn at Ringstead.

After their substantial club sandwich and chocolate mousse, I didn't want to take the rather punishing direct route to Sedgeford, but instead detoured out to Heacham, before finally ambling back (with a number of pauses where a full stomach made it more comfortable to get off and push rather than grind an uphill).

So that was about 28 miles; but between the end-of-day fade on Monday, and the push while digesting, my logged average speed went down from a steady 11 mph as it had been all summer, to only 10.8 :(

Monday, August 15, 2011

Powershell -- higher order functions with arguments that take arguments

Dead simple example based on this:

which results in

Name                                                  Prop                                                 
----                                                  ----                                                 
Junku                                                 **junku+junku**                                      

Also -- reminder to self : ShowUI -- WPF in PowerShell


At end of day 11-Aug the car was reading 3474 miles; at the hour that I picked it up last year, 3485. Subtracting the 14 that were on the clock when I picked it up, 3460 or 3471 miles -- a lot less than in previous years.

Sunday evening, the bike was showing 2280 miles; 373 miles in the first 6 weeks of the new year, which is in keeping with last year's rate

The new guided busway cyclepath is a great new way into the town centre avoiding traffic, even though I have to do a mile and a bit on bridlepath or detour twice that distance to get onto the cyclepath feeding to it. If only there were paved spurs to the neighbouring villages. And even though the last hundred yards or so at the station end aren't finished yet.

In the garden, the plums have been in full flood for a couple of weeks -- much earlier than the usual Bank Holiday peak I usually plan for; indeed everything has been early, ever since the early onset of last winter.

Friday, August 05, 2011

What do you get when you iterate null?

In most cases, an exception; but in PowerShell you get $null.

Suppose I have folders with 0, 1 and more than 1 file in (called empty, full and two, say) and I want to enumerate the names of the files contained in each, with some general purpose code.

That should be no problem --

and let's write a little reporting function

When we report on the folders in descending order of contained files we get

test (2).txt
++test (2).txt++
Split-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\Users\Steve\Documents\scratch\Untitled1.ps1:6 char:15
+     Split-Path <<<<  -Leaf $file
    + CategoryInfo          : InvalidData: (:) [Split-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.Split 
You cannot call a method on a null-valued expression.
At C:\Users\Steve\Documents\scratch\Untitled1.ps1:12 char:15
+   $arg.GetType <<<< ().FullName
    + CategoryInfo          : InvalidOperation: (GetType:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Not happy.

The first error is what you get when you work on the foreach over $null, yielding $null; and calling code has to special-case the single item return -- getting the .Length property of the return is not the number of files! For that replace $arg.Length by $arg | Measure-Object | % {write-host $_.Count} .

So try this

where we fight PowerShell's fragmentation of sequences all the way. Now we get what we expected

test (2).txt
++test (2).txt++

Oh, yeah -- the more PowerShell way of doing all this: