Saturday, 28 February 2009

Maestro: A new .Net language for parallel programming from Microsoft

How did I miss this? At PDC 2008 (in the Parallel Symposium, apparently), Microsoft started talking about a new language that may be joining the .Net family. Continuing the musical theme of certain other languages, this one is called Maestro.

According to an article in Dr Dobbs Journal, Maestro is a special purpose language designed to simplify the writing of scalable parallel programs. It will integrate with other .Net components, and it seems that the intention is for the compute-intensive parts of applications to be written in Maestro, while the staple .Net languages continue to power the rest.

It’s based around the idea of agents in isolated domains passing messages to each other. On the new Maestro blog there’s an article giving some examples of the funky syntax they’re introducing:

  • The forwarding operator, ==> which is used to indicate that messages should be passed from a source to a target
  • The broadcast operator, –<< that broadcasts messages to a number of targets
  • The multiplex operator, >>- which combines messages from several sources before passing them to a single target

Don’t get too excited just yet: Maestro is being described as an “incubation project”. That appears to mean that it’s a bit more than a research project, but not one that anybody has yet committed to shipping. I don’t think they’ve even released a version of this yet – I certainly can’t find a download.

Once you’ve read the book, see the film on Channel 9.

Update (16/4/2009): Maestro has been renamed to Axum

As Mary-Jo reported, Maestro has now been given the less musical code name of “Axum”. This is possibly due to a code-name clash with another Microsoft project, that one to do with business intelligence.

Thursday, 26 February 2009

Observing a bug in the dorsolateral prefrontal cortex

Just occasionally the self-censorship feature in my wife’s brain malfunctions, with amusing consequences: it kicks in the instant after she has spoken, so that her next words are “don’t tell anybody I said that!”

But I’m sure she won’t mind my sharing a few choice moments with you.

First I should point out that my wife graduated with honours from one of the top medical schools in the UK, so there’s clearly nothing lacking in the rest of her brain. I speculate that Auto Update got turned off in this one area.

The most recent example was when we were discussing a diagram of the solar system with our daughter. “So did the Greeks and Romans know what the planets are called when they named their gods?”, my wife asked me – then immediately put her hand over her mouth in embarrassment.

But the funniest was a few years ago as we were driving through our neighbourhood at night, after there had been a power cut. The houses on either side of the road were eerily dark, and we were suddenly dazzled as another vehicle went past us in the opposite direction. My wife piped up,

“So how come that car’s headlights are still working?”

Thursday, 19 February 2009

Practical LINQ: Generating the next default name

Pleasurable as it is, constructing LINQ queries to solve abstruse Mathematical problems, a developer’s real purpose in life, as his boss reminds him often enough, is creating business value. Happily I’ve found that that can be done using LINQ too.

Here’s an example that came up recently.

I was writing a Widget editor dialog box with functionality to create new Widgets. Being the helpful soul I am, I wanted to give the new widgets default names, “Widget1”, “Widget2” and so on (I can be helpful or imaginative, but not both!). But the names also needed to be unique: if “Widget1” and “Widget2” were already in the list, the next new widget should be called “Widget3”.

This is the method I came up with:

public static class NamingExtensions
{
    public static string GetNextDefaultName(this IEnumerable<string> existingNames, string defaultNamePrefix)
    {
        if (existingNames == null)
        {
            throw new ArgumentNullException("existingNames");
        }

        defaultNamePrefix = defaultNamePrefix ?? string.Empty;
        string matchNumberInDefaultNamePattern = "^" + defaultNamePrefix + @"(\d+)$";

        const RegexOptions regexOptions = RegexOptions.IgnoreCase | RegexOptions.Singleline;

        int nextNumber = existingNames.Select(name => Regex.Match(name, matchNumberInDefaultNamePattern, regexOptions) )
            .Where(match => match.Success)
            .Select(match => match.Groups[1].Value)
            .Select(matchValue => int.Parse(matchValue, CultureInfo.InvariantCulture))
            .Aggregate(0, Math.Max, max => max + 1);

        return defaultNamePrefix + nextNumber.ToString(CultureInfo.InvariantCulture);
    }
}

Since I wrote it as an extension method, I can use it like this:

var existingNames = new[] { "Widget1", "Widget2" };
var nextName = existingNames.GetNextDefaultName("Widget");

You might wonder why, in line 19, I use Aggregate instead of a straightforward Max()? That’s because Max() throws an exception if you try using it on an empty sequence, which might happen if none of the existing names match the “Widget[n]” pattern. Also, Aggregate has the nice overload that allows you to apply a result selector function to the final aggregate: as you see, I take advantage of this to return the next number in the sequence, rather than the max itself.

Isn’t LINQ lovely?

Monday, 16 February 2009

The most frustrating “feature” in Visual Studio…

… is the “Waste 1 minute of my life” command – otherwise known as “F1”.

You know how it is: you’re in the zone, refactoring merrily – finger reaches instinctively to F2 to rename a variable, but misses the target, hit its left-hand neighbour, and … Visual Studio hangs. That is, it refuses to respond for a period of time that’s long enough to derail one train of thought, but too short to board another.

Come on Microsoft! If you can’t make Help load faster, at least do it asynchronously. Don’t slap my fat fingers!

Thursday, 12 February 2009

How to Databind to a SelectedItems property in WPF

Many moons ago, I asked on the WPF forums if anybody had a way of data-binding the SelectedItems property of a ListBox. Standard data binding doesn’t work, because the SelectedItems property is read-only, and understandably so: how would you like it if I injected an arbitrary collection into your ListBox and expected you to keep it up to date as the selection changed?

As no one gave me an answer, I was forced to use my gray-matter and invent a solution of my own. Since a similar question came up again recently on Stack Overflow, I thought I’d share what I came up with.

In my solution, I define an attached property that you attach to a ListBox (or DataGrid, or anything that inherits from MultiSelector) and allows you to specify a collection (via data binding, of course) that you want to be kept in sync with the SelectedItems collection of the target. To work properly, the collection you give should implement INotifyCollectionChanged – using ObservableCollection<T> should do the trick. When you set the property, I instantiate another class of my invention, a TwoListSynchronizer. This listens to CollectionChanged events in both collections, and when either changes, it updates the other.

To help me demonstrate, I’ve knocked up a toy ViewModel: it has on it an AvailableNames property that will be the data source for the ListBox, a SelectedNames property which is the reason we’re going through the whole exercise, and a Summary property which displays the number of selected items to prove that the data binding is working correctly.  I won’t bore you with the code – see the download link below.

The XAML looks like this:

<Window x:Class="SelectedItemsBindingDemo.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="clr-namespace:SelectedItemsBindingDemo"
  xmlns:ff="clr-namespace:FunctionalFun.UI.Behaviours"
  Title="SelectedItems Binding Demo" Height="300" Width="300"
      >
<Window.DataContext>
  <d:ViewModel/>
</Window.DataContext>
  <Grid Margin="5">
    <Grid.RowDefinitions>
      <RowDefinition Height="*"/>
      <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <TextBlock Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center"
               Text="{Binding Summary}" FontWeight="Bold" Margin ="0,5,5,5"/>
    <Button Content="Select All" Command="{Binding SelectAll}" Grid.Row="1"
            HorizontalAlignment="Right" VerticalAlignment="Center"/>
    <ListBox Grid.Row="0"
             ItemsSource="{Binding AvailableNames}"
             ff:MultiSelectorBehaviours.SynchronizedSelectedItems="{Binding SelectedNames}"
             SelectionMode="Extended" />
  </Grid>
</Window>

All the magic is initiated by line 22 where I set the attached property MultiSelectorBehaviours.SynchronizedSelectedItems using a data binding to my SelectedNames property. With that in place the SelectedNames collection in my ViewModel is updated whenever SelectedItems on the ListBox changes. And to prove it works the other way to, I’ve created a SelectAll command on the ViewModel that puts all available names into the SelectedNames collection. When you press the button you’ll see that the ListBox obediently updates to show all items selected.

The TwoListSynchronizer code does not make especially thrilling reading, so I won’t show it here. If you should peruse it however, there are a couple of things you might wonder about:

  • I’ve made it implement IWeakEventListener so that it can subscribe to CollectionChanged events using weak events. This means I don’t have to worry about creating managed memory leaks if the source SelectedItems collection has a longer lifetime than the ListBox.
  • The code occasionally refers to something called a IListItemConverter. I’m not make use of this in this application of the TwoListSynchronizer, but it might have uses elsewhere. The scenario I had in mind was where there is some kind of mapping between the items in the two collections that need to be synchronized.

Update (25/07/2013): All the code is now available on Github (under a Public Domain License). Download a zip file directly here.

Monday, 9 February 2009

My first FreeCycle

This evening I completed my first FreeCycle. Unfortunately, this did nothing to improve my fitness levels, but it did bring us three black bags closer to our target of emptying our Junk room by the end of February. 

FreeCycle is a an organisation that is all about “reuse and keeping good stuff out of landfills”. It currently claims 6.5 million members in almost 5 thousand local groups worldwide. If my non-descript medium size home town has a FreeCycle group, then there’s a good chance yours does to.

Once you’ve signed up, you can list items that you want to get rid of – things that you might otherwise dump at the household waste site. Fellow Freecyclers express an interest, you choose who you want to donate to, then make mutually agreeable arrangements to transfer ownership.

I had an assortment of Lever Arch files (formerly housing my University Lecture notes – sniff, sniff!), and two aged Colour Inkjet printers to dispose of. Previously, I probably would have taken these to landfill – albeit rather guiltily. But within a couple of hours of listing these on my local FreeCycle group more than five people had expressed an interest in taking one or both items off my hands. Following a brief email exchange this morning, a gentleman called in a few moments ago and took the lot: said he was setting up a new office!

I first heard about Freecycle more than a year ago. What put me off back then is the technology (or lack thereof) powering the scheme. Things still haven’t moved on, so, in the interests of decluttering my life, I had to put my technological prejudices on one side, wind the clock back several years and immerse myself in the world of Mailing lists. You send mails to an alias with “OFFERED:” in the subject line, together with a description of the white elephant which needs rehousing; once the item has been collected you mail again, this time flagging your mail with “TAKEN”. There’s even a convention using “WANTED:” and “RECIEVED:” for optimists, though etiquette forbids subject lines requesting brand new Mercedes Benz and such like.

But as I proved today, it works. All in all, a simple, foolproof, scheme for making the world a better place one black bag at a time.

Saturday, 7 February 2009

Disposing of memories

Today I did a very difficult thing: I threw away my University Lecture notes.

It was all part of the Great Junk Room Clear-out. I had folders in there which I hadn’t looked at since the jubilant day of my final exam, five and a half years ago.

After I’d had stern words with myself, I conceded that I was unlikely to need them again: my career has led me down a path in which the finer points of Representation Theory are no longer of practical use. Besides this, my handwriting could justly be described as write-only; scrawling the notes helped the content stick in my memory during the exams, but it certainly doesn’t serve for archive purposes.

I must confess to flicking through the pages nostalgically before consigning them to the recycling bag. I have fond memories of the days when I understood those Theorems, Lemmas and Corollaries.

Friday, 6 February 2009

functional => prizes #1: We have a winner

TrophyThe closing date of the the inaugural Functional Fun programming competition has passed, and I’m relieved to say I actually had some judging to do. Further to my post on Monday, two bits are now required to hold the number of submissions I have to choose between - though not used to full capacity.

The Winner

Our winner is Jamie, a High School Student from Massachusetts, whose code surpasses in elegance my attempt at solving my own problem. Jamie gets the prize of £25 in Amazon gift vouchers. Honourable mention goes to Dan Dumitru who was the first to submit a solution.

Congratulations to Jamie, and thanks to all 10 of you who entered!

The Solution

The puzzle that Jamie and Dan solved was as follows;

Which Mathematicians have found themselves prime positions in the grid below?

HiddenMathematiciansImage

So who were the coy Mathematicians, and how did they conceal themselves? Well, given the maths connection, “prime positions” must surely have something to do with prime numbers? So what happens if we count along the cells of the grid (wrapping over from the end of one row to the beginning of the following row) and note down the characters we find at indices which are prime-numbered?

Interesting! We get the string

tinyurl#teyuir#gqrtyh#hyirtq##

Teyuir? What theorem did he prove? must be Slovakian with a name like that. Now tinyurl – that rings a bell. Hey! I wonder what tinyurl.com/ teyuir looks like?

WikipediaRestApiResult

Huh! XML?

But wait: Leonhard Euler. There’s a name I recognise. Didn’t he dabble in mathematics, and prove a lemma or two?

And having reasoned thus, all that remains is to craft a handful of LINQ queries to winkle all three mathematicians out of the hiding places: Euler, Euclid and Cantor.

Here’s Jamie’s solution in its entirety. The code speaks for itself.

// Gets all the nonwhitespace characters
var rawChars = from ch in File.ReadAllText("HiddenMathematicians.txt") 
               where !char.IsWhiteSpace(ch)
               select ch;

// Gets only the chars at prime indices (char[0] is at index 1)
var primeChars = from num in Enumerable.Range(2, rawChars.Count() - 1) // creates all indices from 1 to numRawChars
                 let divisors = Enumerable.Range(2, num - 2) // all possible divisors, 2 to num - 1
                 let isPrime = !divisors.Any(div => num % div == 0)
                 where isPrime
                 select rawChars.ElementAt(num - 1);

// All the words, including the beginning hint
var words = from str in primeChars.Aggregate(string.Empty, (str, ch) => str += ch).Split('#')
            where !string.IsNullOrEmpty(str)
            select str;

var names = from word in words.Skip(1)
            let url = "http://" + words.First() + ".com/" + word
            let xmlData = XDocument.Load(url)
            let element = xmlData.XPathSelectElement("./api/query/pages/page")
            let attribute = element.Attribute("title")
            select attribute.Value;

foreach (var name in names)
    Console.WriteLine(name);

Console.ReadLine();

Thursday, 5 February 2009

My brother the blogger

I’ve just discovered that my brother has started a blog; he began writing it back in January (my family communicates well, as you see!). He’s writing about life from the point of view of a Herbal Medicine Student.

My favourite post so far: The Time Monster.

Monday, 2 February 2009

Deadline fast approaching

Don’t forget that Wednesday Noon o’clock sharp GMT is the deadline for functional => prizes #1.

So far the number of entries I’ve received can be recorded in one bit: if you enter you have a statistically very good chance of walking away with the lavish prize.

Don’t let the riddle put you off. Dan, in the comments gives you a clue that is more or less along the right lines, though you might find that the Mathematicians are rather coy about using their names.