<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>SteveCooper.org</title>
	<atom:link href="http://www.stevecooper.org/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.stevecooper.org</link>
	<description>Just another WordPress site</description>
	<lastBuildDate>Sun, 18 Sep 2011 15:46:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Fun with Graph Theory</title>
		<link>http://www.stevecooper.org/index.php/2011/09/09/fun-with-graph-theory/</link>
		<comments>http://www.stevecooper.org/index.php/2011/09/09/fun-with-graph-theory/#comments</comments>
		<pubDate>Fri, 09 Sep 2011 21:54:11 +0000</pubDate>
		<dc:creator>Steve Cooper</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.stevecooper.org/?p=321</guid>
		<description><![CDATA[I asked a question in twitter about graph theory the other day. Unsurprisingly, it was tricky to convey what I wanted to know in such a short span. So this explains what i was wondering in more depth. I&#8217;ve got a problem involving graph layouts (think dot and graphviz) I want to write a GUI [...]]]></description>
			<content:encoded><![CDATA[<p>I asked a question in twitter about graph theory the other day. Unsurprisingly, it was tricky to convey what I wanted to know in such a short span. So this explains what i was wondering in more depth.</p>

<p>I&#8217;ve got a problem involving graph layouts (think dot and graphviz) I want to write a GUI program that lets the user draw directed graphs interactively. That is, they start with a single node. Then, to modify that graph, there are five basic operations:</p>

<ul>
<li>add a node above: that is, a node <em>A</em> becomes the graph <em>B</em> -> <em>A</em></li>
<li>add a graph below: <em>A</em> -> <em>B</em></li>
<li>add an edge between two nodes</li>
<li>delete an edge</li>
<li>delete a node, and all connecting edges </li>
</ul>

<p>And what I&#8217;d like to know is; to keep the UI responsive, can I precalculate the positions of every possible graph ahead of time? When the user makes a change, I can refer to the precalculated positions and keep the UI experience really fast.</p>

<p>This depends on how many possible nodes there are. If I am only ever going to see, say, 500,000 possible layouts, it is possible to just spend a couple of days chugging through all the possible configurations and saving them in a database.</p>

<p>Without any more limits, this is impossible &#8212; there are an infinite number of graphs. But I think I can make reasonable guesses about the types of graph I&#8217;m likely to see in my app. For instance;</p>

<ul>
<li>the graph is always connected</li>
<li>no two nodes have a duplicate edge</li>
<li>the graph has no cycles</li>
<li>Nodes generally won&#8217;t have more than about five incoming nodes and five outgoing nodes</li>
<li>A graph probably won&#8217;t have more than about 100 nodes in it</li>
</ul>

<p>So here&#8217;s how I formulated the problem;</p>

<p>Given a directed acyclic graph with <em>N</em> nodes, where no node has more than <em>E</em> total incoming and outgoing nodes, how many possible graphs are there?</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.stevecooper.org%2Findex.php%2F2011%2F09%2F09%2Ffun-with-graph-theory%2F&amp;title=Fun%20with%20Graph%20Theory" id="wpa2a_2">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.stevecooper.org/index.php/2011/09/09/fun-with-graph-theory/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Chess Problem &#8211; eh?</title>
		<link>http://www.stevecooper.org/index.php/2011/08/24/chess-problem-eh/</link>
		<comments>http://www.stevecooper.org/index.php/2011/08/24/chess-problem-eh/#comments</comments>
		<pubDate>Wed, 24 Aug 2011 12:38:14 +0000</pubDate>
		<dc:creator>Steve Cooper</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Chess]]></category>
		<category><![CDATA[Tactics]]></category>

		<guid isPermaLink="false">http://www.stevecooper.org/index.php/2011/08/24/chess-problem-eh/</guid>
		<description><![CDATA[I&#8217;m struggling to see why a chess problem has the answer it does. Does anyone see why Nf6 is the right answer here? Looks crazy to me. Surely the knight can be taken without consequence by g7 or Nf5? Pgn is: [Event ""] [Site ""] [Date "2011.08.24"] [Round ""] [White "Player 1"] [Black "Player 2"] [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m struggling to see why a chess problem has the answer it does. Does anyone see why Nf6 is the right answer here? Looks crazy to me. Surely the knight can be taken without consequence by g7 or Nf5?</p>

<p>Pgn is:</p>

<pre><code>[Event ""]
[Site ""]
[Date "2011.08.24"]
[Round ""]
[White "Player 1"]
[Black "Player 2"]
[Result "*"]
[ECO ""]
[SetUp "1"]
[FEN "3r4/2rN1ppk/4p3/1Rp2n1n/2P2P1p/1P3P2/5B1P/3R1K2 w - -"]

1. Nf6+ * { isn't the knight here simply undefended? }
</code></pre>

<p><a href="http://www.stevecooper.org/wp-content/uploads/2011/08/20110824-133818.jpg"><img src="http://www.stevecooper.org/wp-content/uploads/2011/08/20110824-133818.jpg" alt="20110824-133818.jpg" class="alignnone size-full" /></a><br /><br /><a href="http://www.stevecooper.org/wp-content/uploads/2011/08/20110824-133840.jpg"><img src="http://www.stevecooper.org/wp-content/uploads/2011/08/20110824-133840.jpg" alt="20110824-133840.jpg" class="alignnone size-full" /></a></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.stevecooper.org%2Findex.php%2F2011%2F08%2F24%2Fchess-problem-eh%2F&amp;title=Chess%20Problem%20%26%238211%3B%20eh%3F" id="wpa2a_4">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.stevecooper.org/index.php/2011/08/24/chess-problem-eh/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Mother&#8217;s Day Flash Fiction: Thorsday Teatime</title>
		<link>http://www.stevecooper.org/index.php/2011/03/31/mothers-day-flash-fiction-thorsday-teatime/</link>
		<comments>http://www.stevecooper.org/index.php/2011/03/31/mothers-day-flash-fiction-thorsday-teatime/#comments</comments>
		<pubDate>Thu, 31 Mar 2011 10:27:29 +0000</pubDate>
		<dc:creator>Steve Cooper</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.stevecooper.org/?p=310</guid>
		<description><![CDATA[Jord stood at the gates of Odin&#8217;s hall, and rapped the knuckles of her callused hands against the ancient black-oak door. &#8220;Odin! Odin! Open your gates, One-eye! I have come to kill your son!&#8221; Through the gates, she could hear the sound of a feast. Deep inside the hall, a bard&#8217;s rich voice would sing [...]]]></description>
			<content:encoded><![CDATA[<p>Jord stood at the gates of Odin&#8217;s hall, and rapped the knuckles of her callused hands against the ancient black-oak door. &#8220;Odin! Odin! Open your gates, One-eye! I have come to kill your son!&#8221;</p>

<p>Through the gates, she could hear the sound of a feast. Deep inside the hall, a bard&#8217;s rich voice would sing a line, and a hundred hundred voices would roar a response. Nearer the door, she heard someone vomit.</p>

<p>&#8220;Do you hear me, old man? I have come for your son! I gave him life, and I shall take it back! Bring me Thor, that I might kill him!&#8221; She took up a stone from the ground, and brought it hard against the door. The sound reverberated into the hall. &#8220;Bring!&#8221; Bash. &#8220;Me!&#8221; Bash. &#8220;My!&#8221; Bash. &#8220;Son!&#8221;</p>

<p>The bard had stopped singing, and the sounds of laughter from inside had ceased. Jord could hear footsteps, then the doors of Valhalla, opened only for the souls of the battle-fallen, swung open. Inside, a great brown-haired Viking, fur-clad and looking for all the world like a bear, regarded her. Ten thousand pairs of eyes watched them both.</p>

<p>&#8220;Woman!&#8221; he bellowed. &#8220;This is Valhalla! The hall of Odin, Great and Grey-eyed Gallows-Lord!&#8221; Behind him, a chorus of drunken cheers.</p>

<p>&#8220;And here are the greatest bloodletters, beserkers, bonesplitters and throat-slitters who ever lived! Drinking bright mead and eagerly waiting for the Fenris-wolf and Ragnarok.&#8221; Behind him the great cheer swelled again.</p>

<p>&#8220;Inside also is Thor, Strong and Stalwart Sky-King! Far-famed Fighter in Battle!&#8221; To the jeers and cheers was added the thumping of tables and smacking of shields. The herald continued, heartened by the noise.</p>

<p>&#8220;Thor, the Friend of Fat-Feasting Ravens! Thor, the Spiller of Seas of Slaughter-dew! Thor, The Hard Hammer-Handed Warrior!&#8221; He took a long breath. &#8220;Who are <em>you</em>, that comes here, to this great host, and challenges the Lord of the Leaping Lightning and the Thunder-din?&#8221;</p>

<p>&#8220;I&#8217;m his mum.&#8221;</p>

<p>&#8220;&#8230; Ah.&#8221;</p>

<p>Jord pushed the man aside, and strode into the hall. Her eyes peered into and through the smoke, past the long trestles bursting with food, past the many thousands of men, battle-proved and strong, who sat at the tables. Each one regarded the small woman in silence. She ignored them and walked straight down the central aisle towards the top table.</p>

<p>Through the haze she could make out the great fire pit, over which was roasting the great cosmic boar Saehrimnir, cooked every night and returned to life every morning. She walked past it, looking on towards the great central table where the king of the gods sat with his favoured retinue.</p>

<p>As she passed the great cooking fire, and its brightness was at her back, she could see Odin, the god-king, sitting at the centre of his table. In one hand he held a great ham hock; in the other, a jewelled eating-knife. He was old, and scarred, and an eyepatch covered his vacant eye-socket. His hair was grey and white and black and wiry. On his right hand side sat Thor, the great blond god who could strike a man down with his mighty hammer, Mjolnir, or with lightning from the sky itself. The huge god sat there, with something like a smirk on his face. Behind that smile, though, Jord could see the slightest glimmer of fear. He knew he had done something, but he did not know what.</p>

<p>&#8220;Thor, my miserable son,&#8221; Jord said, &#8220;do you know what day of the week it is?&#8221;</p>

<p>He regarded her for a moment. &#8220;Mother, it is my day &#8212; Thorsday.&#8221;</p>

<p>&#8220;That&#8217;s right. And the day before?&#8221;</p>

<p>&#8220;Wodin&#8217;s day. In honour of my father.&#8221;</p>

<p>&#8220;Keep going. The days before that?&#8221;</p>

<p>&#8220;Tyr&#8217;s day, after Tyr One-Handed, who struggled with the great wolf Fenrir.&#8221; Jord sat watching him, waiting. &#8220;And Mani&#8217;s day before that, and then the day of Sunne, goddess of the Sun.&#8221;</p>

<p>&#8220;The first Sunday of spring&#8230;&#8221; she said, waiting for him to continue. Thor wrinkled his wide brows in thought. For long seconds he pondered.</p>

<p>&#8220;Mothering Sunday! By Freya&#8217;s freckly buttocks! I forgot!&#8221; His confusion changed to realisation, then near-panic. His voice dropped low, so that only those at the table could hear. &#8220;I&#8217;ll make it up to you,&#8221; he said. &#8220;I shall travel to the netherworld Svartalfaheim, and steal for you a great black pearl from the dwarves!&#8221;</p>

<p>&#8220;Not good enough.&#8221;</p>

<p>&#8220;I shall have my daughter, Thrud, weave you lace from threads of pure moonlight!&#8221;</p>

<p>&#8220;Not good enough.&#8221;</p>

<p>&#8220;I shall go to icy Niflheim, and wrestle from Hel her great cloak made from night and stars. &#8220;</p>

<p>&#8220;Not good enough.&#8221;</p>

<p>&#8220;I shall&#8230; I&#8230;&#8221;</p>

<p>&#8220;There&#8217;s only one way you&#8217;re going to make up for it.&#8221;</p>

<p>Thor looked at her with a suspicious eye. &#8220;And&#8230; And how is that?&#8221;</p>

<p>She leaned forward, mouth next to Thor&#8217;s ear, and whispered &#8220;Give me a cuddle.&#8221;</p>

<p>Thor looked at her then, aghast, then at the horde of Odin, ten thousand warriors looking to their role model, waiting expectantly for the thunder-god&#8217;s response to the unknown request.</p>

<p>What else could he do? He gave his mum a hug.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.stevecooper.org%2Findex.php%2F2011%2F03%2F31%2Fmothers-day-flash-fiction-thorsday-teatime%2F&amp;title=Mother%26%238217%3Bs%20Day%20Flash%20Fiction%3A%20Thorsday%20Teatime" id="wpa2a_6">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.stevecooper.org/index.php/2011/03/31/mothers-day-flash-fiction-thorsday-teatime/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>VB.NET and Python equivalence</title>
		<link>http://www.stevecooper.org/index.php/2010/11/10/vb-net-and-python-equivalence/</link>
		<comments>http://www.stevecooper.org/index.php/2010/11/10/vb-net-and-python-equivalence/#comments</comments>
		<pubDate>Wed, 10 Nov 2010 15:19:05 +0000</pubDate>
		<dc:creator>Steve Cooper</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.stevecooper.org/?p=304</guid>
		<description><![CDATA[A recent post on Hacker News made me wonder if &#60;inflammatory&#62;Python is just VB.NET without &#8216;End If&#8217;. &#60;/inflammatory&#62; I thought I&#8217;d try to translate Peter Norvig&#8217;s masterful spellchecker program in Python into VB.NET 2008. Could his beautiful little program be converted line-by-line into VB? The answer is yes. Here&#8217;s the original program; import re, collections [...]]]></description>
			<content:encoded><![CDATA[<p>A <a href="http://news.ycombinator.com/item?id=1885594">recent post on Hacker News</a> made me wonder if <strong>&lt;inflammatory&gt;Python is just VB.NET without &#8216;End If&#8217;. &lt;/inflammatory&gt;</strong></p>

<p>I thought I&#8217;d try to translate Peter Norvig&#8217;s masterful spellchecker program in Python into VB.NET 2008. Could his beautiful little program be converted line-by-line into VB? The answer is <em>yes.</em></p>

<p>Here&#8217;s the <a href="http://norvig.com/spell-correct.html">original program</a>;</p>

<pre><code>import re, collections

def words(text): return re.findall('[a-z]+', text.lower()) 

def train(features):
    model = collections.defaultdict(lambda: 1)
    for f in features:
        model[f] += 1
    return model

NWORDS = train(words(file('big.txt').read()))

alphabet = 'abcdefghijklmnopqrstuvwxyz'

def edits1(word):
   splits     = [(word[:i], word[i:]) for i in range(len(word) + 1)]
   deletes    = [a + b[1:] for a, b in splits if b]
   transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)&gt;1]
   replaces   = [a + c + b[1:] for a, b in splits for c in alphabet if b]
   inserts    = [a + c + b     for a, b in splits for c in alphabet]
   return set(deletes + transposes + replaces + inserts)

def known_edits2(word):
    return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)

def known(words): return set(w for w in words if w in NWORDS)

def correct(word):
    candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]
    return max(candidates, key=NWORDS.get)
</code></pre>

<p>And here&#8217;s the equivalent VB;</p>

<pre><code>Option Strict Off
Imports System.Text.RegularExpressions
Imports System.Collections.Generic

Module NorvigSpellChecker

    Dim NWORDS

    Dim alphabet As String = "abcdefghijklmnopqrstuvwxyz"

    Function words(ByVal text)
        Return From match In Regex.Matches(text.ToLower(), "[a-z]+") Select match.Value
    End Function

    Function train(ByVal features)
        Dim model = New DefaultDict(Function() 1)
        For Each f In features
            model(f) += 1
        Next
        Return model
    End Function

    Function edits1(ByVal word) As IEnumerable(Of Object)
        Dim splits = From i In Enumerable.Range(0, len(word)) Let a = word.Substring(0, i), b = word.Substring(i) Select a, b
        Dim deletes = From split In splits Where ifs(split.b) Select split.a + split.b.Substring(1)
        Dim transposes = From split In splits Where len(split.b) &gt; 1 Select split.a + split.b.Substring(1, 1) + split.b.Substring(0, 1) + split.b.Substring(2)
        Dim replaces = From split In splits From c In alphabet Where ifs(split.b) Select split.a + c + split.b.Substring(1)
        Dim inserts = From split In splits From c In alphabet Select split.a + c + split.b
        Return deletes.Union(transposes).Union(replaces).Union(inserts).Distinct()
    End Function

    Function known_edits2(ByVal word)
        Return edits1(word).SelectMany(Function(e1) edits1(e1)).Distinct().Where(Function(e) NWORDS.ContainsKey(e))
    End Function

    Function known(ByVal words As IEnumerable)
        Return From w In words Where NWORDS.ContainsKey(w) Select w
    End Function

    Function correct(ByVal word)
        Dim candidates = ORR(Function() known(New String() {word}), Function() known(edits1(word)), Function() known_edits2(word), Function() New String() {word})
        Return candidates.OrderBy(Function(candidate) NWORDS(candidate)).FirstOrDefault()
    End Function

End Module
</code></pre>

<p>Because I needed to define some python-equivalents, like the <code>len(string)</code> function, I ended up writing a bit more code, just to try to get a more exact match. Also, LINQ expressions need to know that certain things are enumerable, so I needed to litter a few type declarations through the code; about half a dozen. But overall I&#8217;m happy with the result. Take off the block terminators &#8212; &#8216;End Function&#8217;, &#8216;Next&#8217;, and &#8216;End Module&#8217; &#8212; and you end up with a line-perfect equivalent.</p>

<p>Full source code <a href="https://github.com/stevecooperorg/Norvig-Spelling-Corrector-in-VB.NET/blob/master/NorvigSpellChecker.vb">on github</a></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.stevecooper.org%2Findex.php%2F2010%2F11%2F10%2Fvb-net-and-python-equivalence%2F&amp;title=VB.NET%20and%20Python%20equivalence" id="wpa2a_8">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.stevecooper.org/index.php/2010/11/10/vb-net-and-python-equivalence/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quick phone topup hack</title>
		<link>http://www.stevecooper.org/index.php/2010/10/14/quick-phone-topup-hack/</link>
		<comments>http://www.stevecooper.org/index.php/2010/10/14/quick-phone-topup-hack/#comments</comments>
		<pubDate>Thu, 14 Oct 2010 08:48:11 +0000</pubDate>
		<dc:creator>Steve Cooper</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.stevecooper.org/?p=295</guid>
		<description><![CDATA[I have discovered a neat little hack for topping up you mobile on pay and go. Most companies use a fixed menu system. If your phone allows you to store phone numbers including hashes and pauses, you can create a contact that navigates the menu system like a robot rat. Here is the phone number [...]]]></description>
			<content:encoded><![CDATA[<p>I have discovered a neat little hack for topping up you mobile on pay and go. Most companies use a fixed menu system. If your phone allows you to store phone numbers including hashes and pauses, you can create a contact that navigates the menu system like a robot rat. Here is the phone number you use on 02 to top up by £15;</p>

<p>44 44 ,#,1,#,1,#,#,9876#,543#,15#</p>

<p>You&#8217;ll need to swap &#8217;9876&#8242; with the last digits of your debit card, and &#8217;543&#8242; with the security code on the back. </p>

<p>If that&#8217;s a useful trick and you use another mobile provider or phone, feel free to post your own patterns in the comments. </p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.stevecooper.org%2Findex.php%2F2010%2F10%2F14%2Fquick-phone-topup-hack%2F&amp;title=Quick%20phone%20topup%20hack" id="wpa2a_10">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.stevecooper.org/index.php/2010/10/14/quick-phone-topup-hack/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Databinding a System.Drawing.Image into a WPF System.Windows.Image</title>
		<link>http://www.stevecooper.org/index.php/2010/08/06/databinding-a-system-drawing-image-into-a-wpf-system-windows-image/</link>
		<comments>http://www.stevecooper.org/index.php/2010/08/06/databinding-a-system-drawing-image-into-a-wpf-system-windows-image/#comments</comments>
		<pubDate>Fri, 06 Aug 2010 21:01:34 +0000</pubDate>
		<dc:creator>Steve Cooper</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.stevecooper.org/?p=296</guid>
		<description><![CDATA[I&#8217;m learning WPF, very slowly, as a background thing. I&#8217;m working very slowly through some WPF at the moment, and discovered something I thought was really odd. The classic .Net Image class &#8212; System.Drawing.Image &#8212; can&#8217;t be easily databound into the WPF Image control. That seemed crazy to me &#8212; it&#8217;s like having a PictureBox [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m learning WPF, very slowly, as a background thing.</p>

<p>I&#8217;m working very slowly through some WPF at the moment, and discovered something I thought was really odd. The classic .Net Image class &#8212; System.Drawing.Image &#8212; can&#8217;t be easily databound into the WPF Image control.</p>

<p>That seemed crazy to me &#8212; it&#8217;s like having a <code>PictureBox</code> control without an <code>Image</code> property. I resolved to fix it in the most &#8216;WPFy&#8217; way I could.</p>

<p>What I&#8217;d tried was binding a ListView to a list of objects, like so;</p>

<pre><code>&lt;ListView 
    ItemsSource="{ Binding Path=. }"
    ItemTemplate="{DynamicResource EventTemplate}"&gt;   
</code></pre>

<p>Id bound to an object which declares two properties;</p>

<pre><code>string DisplayName { get; }
System.Drawing.Image Image { get; set; }
</code></pre>

<p>I wanted to populate a <code>DataTemplate</code> but if I did this in my template;</p>

<pre><code>&lt;StackPanel Orientation="Horizontal"&gt;
    &lt;Image Source="{ Binding Path=Image }" /&gt;
    &lt;TextBlock Text="{ Binding Path=DisplayName }" /&gt;
&lt;/StackPanel&gt;      
</code></pre>

<p>The text appears but the image does not. It turns out that WPF can&#8217;t find a suitable converter.</p>

<p>So, thanks to <a href="http://reedcopsey.com/">Reed Copsey</a> and his very helpful <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/833ca60f-6a11-4836-bb2b-ef779dfe3ff0/">pointer on Stack Overflow</a>, and <a href="http://www.switchonthecode.com/tutorials/wpf-tutorial-binding-converters">this tutorial</a>, I&#8217;ve found a way I&#8217;m happy with; one that doesn&#8217;t involve c# code-behind.</p>

<p>I&#8217;ve created an <code>IValueConverter</code> which does the conversion from <code>System.Drawing.Image</code> to <code>System.Windows.Media.ImageSource</code>. A big thank-you to <a href="http://social.msdn.microsoft.com/profile/matt%20galbraith%20-%20msft">Matt Galbraith of Microsoft</a> for providing the core code;</p>

<pre><code>using System;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Windows.Data;

namespace System.Windows.Media
{
    /// &lt;summary&gt;
    /// One-way converter from System.Drawing.Image to System.Windows.Media.ImageSource
    /// &lt;/summary&gt;
    [ValueConversion(typeof(System.Drawing.Image), typeof(System.Windows.Media.ImageSource))]
    public class ImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType,
            object parameter, CultureInfo culture)
        {
            // empty images are empty...
            if (value == null) { return null; }

            var image = (System.Drawing.Image)value;
            // Winforms Image we want to get the WPF Image from...
            var bitmap = new System.Windows.Media.Imaging.BitmapImage();
            bitmap.BeginInit();
            MemoryStream memoryStream = new MemoryStream();
            // Save to a memory stream...
            image.Save(memoryStream, image.RawFormat);
            // Rewind the stream...
            memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
            bitmap.StreamSource = memoryStream;
            bitmap.EndInit();
            return bitmap;
        }

        public object ConvertBack(object value, Type targetType,
            object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}
</code></pre>

<p>Then you need to bring the image converter into XAML as a resource. Add the namespace declaration to the window;</p>

<pre><code>xmlns:med="clr-namespace:System.Windows.Media"
</code></pre>

<p>Stick an instance of the <code>ImageConverter</code> into a static resource;</p>

<pre><code>&lt;ListView.Resources&gt;
    &lt;med:ImageConverter x:Key="imageConverter" /&gt;
&lt;/ListView.Resources&gt;
</code></pre>

<p>Then you can use it in XAML to bind directly to the Image, using the new converter;</p>

<pre><code>&lt;Image Source="{ Binding Path=Image, Converter={StaticResource imageConverter} }" /&gt;
</code></pre>

<p>So. A re-usable converter which allows databinding directly to GDI image objects.</p>

<p>Originally discussed <a href="http://stackoverflow.com/questions/3427034/using-xaml-to-bind-to-a-system-drawing-image-into-a-system-windows-image-control">on stack overflow</a></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.stevecooper.org%2Findex.php%2F2010%2F08%2F06%2Fdatabinding-a-system-drawing-image-into-a-wpf-system-windows-image%2F&amp;title=Databinding%20a%20System.Drawing.Image%20into%20a%20WPF%20System.Windows.Image" id="wpa2a_12">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.stevecooper.org/index.php/2010/08/06/databinding-a-system-drawing-image-into-a-wpf-system-windows-image/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Popular Ajax Libraries &#8212; jQuery far in the lead in July 2010</title>
		<link>http://www.stevecooper.org/index.php/2010/07/19/popular-ajax-libraries-jquery-far-in-the-lead-in-july-2010/</link>
		<comments>http://www.stevecooper.org/index.php/2010/07/19/popular-ajax-libraries-jquery-far-in-the-lead-in-july-2010/#comments</comments>
		<pubDate>Mon, 19 Jul 2010 07:31:05 +0000</pubDate>
		<dc:creator>Steve Cooper</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.stevecooper.org/?p=277</guid>
		<description><![CDATA[http://2tbsp.com/node/100 suggests using google trends to judge popularity of ajax libraries; looking at the current data, it looks like jQuery is the clear winner so far in the AJAX library stakes. The current trends can be found here]]></description>
			<content:encoded><![CDATA[<p><a href="http://2tbsp.com/node/100">http://2tbsp.com/node/100</a> suggests using google trends to judge popularity of ajax libraries; looking at the current data, it looks like jQuery is the clear winner so far in the AJAX library stakes. The current trends can be found <a href="http://trends.google.com/websites?q=dojotoolkit.org%2C+jquery.com%2C+prototypejs.org%2C+mootools.net%2C+http%3A%2F%2Fdeveloper.yahoo.com%2Fyui%2F&amp;geo=all&amp;date=all&amp;sort=2">here</a>
<a href="http://www.stevecooper.org/wp-content/uploads/2010/07/ajax-popularity-chart.png"><img src="http://www.stevecooper.org/wp-content/uploads/2010/07/ajax-popularity-chart.png" alt="" title="ajax-popularity-chart" width="612" height="232" class="aligncenter size-full wp-image-291" /></a></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.stevecooper.org%2Findex.php%2F2010%2F07%2F19%2Fpopular-ajax-libraries-jquery-far-in-the-lead-in-july-2010%2F&amp;title=Popular%20Ajax%20Libraries%20%26%238212%3B%20jQuery%20far%20in%20the%20lead%20in%20July%202010" id="wpa2a_14">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.stevecooper.org/index.php/2010/07/19/popular-ajax-libraries-jquery-far-in-the-lead-in-july-2010/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learning Languages Followup; Test Languages</title>
		<link>http://www.stevecooper.org/index.php/2010/07/06/learning-languages-followup-test-languages/</link>
		<comments>http://www.stevecooper.org/index.php/2010/07/06/learning-languages-followup-test-languages/#comments</comments>
		<pubDate>Tue, 06 Jul 2010 10:54:24 +0000</pubDate>
		<dc:creator>Steve Cooper</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[markup languages]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Programming Languages]]></category>

		<guid isPermaLink="false">http://www.stevecooper.org/?p=3</guid>
		<description><![CDATA[I managed to write a new language, and 135 unit tests in that language, in a single day. When I talked about big wins coming from writing in the correct language, this is what I meant. So, the language is a test language for a function library. We have arithmentic, date, string, and other functions [...]]]></description>
			<content:encoded><![CDATA[<p>I managed to write a new language, and 135 unit tests in that language, in a single day. When I talked about big wins coming from writing in the correct language, this is what I meant.</p>

<p>So, the language is a test language for a function library. We have arithmentic, date, string, and other functions that we need to test. Each function is identified internally by a GUID, and may be configured. So the language looks like;</p>

<pre><code>01 #
02 # Check Array Sum function
03 #
04 declare Sum = {11669A5A-45BA-46c0-A6F6-97CDE4F5CAA5}
05 Sum(null) = null
06 Sum([]) = 0
07 Sum([1.0, 2.0]) = 3.0
</code></pre>

<p>In this short script, I add comments, give a function a name (binding the name <code>Sum</code> to the function identified with the id <code>{11669A5A-45BA-46c0-A6F6-97CDE4F5CAA5}</code>. Then, I define three tests; <code>Sum(null) = null</code> means what you would expect; call the sum function, passing in a single null parameter; the result should be null.</p>

<p>Having defined this language (which, I think, took me about an hour) I was then able to write about 135 tests with relative ease. The equivalent C# unit tests would be full of repetition and would not express their meaning anywhere near as fully. You&#8217;ve have something like;</p>

<pre><code>[TestMethod]
public void TestSumNullIsNull()
{
  var expected = (double)null;
  var thefunction = FieldModifierHost.Instance()["{11669A5A-45BA-46c0-A6F6-97CDE4F5CAA5}"];
  var maker = thefunction.MakeMethod();
  var instance = maker(new object[]{});
  var result = instance(null);
  Assert.AreEqual(expected, result);
}
</code></pre>

<p>Which is frankly impenetrable.</p>

<p>PS: I&#8217;ve just had a colleague add a number of tests, without any instruction, and he&#8217;s managed to put confidence tests around a function he wants to change in minutes. Unit test languages FTW!</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.stevecooper.org%2Findex.php%2F2010%2F07%2F06%2Flearning-languages-followup-test-languages%2F&amp;title=Learning%20Languages%20Followup%3B%20Test%20Languages" id="wpa2a_16">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.stevecooper.org/index.php/2010/07/06/learning-languages-followup-test-languages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How long have you been at work? A Windows Hack.</title>
		<link>http://www.stevecooper.org/index.php/2010/06/28/how-long-have-you-been-at-work-a-windows-hack/</link>
		<comments>http://www.stevecooper.org/index.php/2010/06/28/how-long-have-you-been-at-work-a-windows-hack/#comments</comments>
		<pubDate>Mon, 28 Jun 2010 12:44:22 +0000</pubDate>
		<dc:creator>Steve Cooper</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.stevecooper.org/?p=266</guid>
		<description><![CDATA[I get into work anywhere between 8:00am and 9:30am. As the end of the day draws on, I&#8217;m sometimes not sure whether I&#8217;ve served my time. To make sure I don&#8217;t go home too early, I use this little trick. Windows tracks your logons in the event log. So to find out when you came [...]]]></description>
			<content:encoded><![CDATA[<p>I get into work anywhere between 8:00am and 9:30am. As the end of the day draws on, I&#8217;m sometimes not sure whether I&#8217;ve served my time. To make sure I don&#8217;t go home too early, I use this little trick.</p>

<p>Windows tracks your logons in the event log. So to find out when you came in;</p>

<ol>
    <li>Open the event viewer; *windows+r, &#8216;eventvwr&#8217;, enter*</li>
    <li>Select &#8216;Custom Views&#8217;</li>
    <li>Right-click and choose &#8216;Create custom view&#8230;&#8217;</li>
    <li>Open the &#8216;XML&#8217; tab</li>
    <li>Check &#8216;Edit query manually&#8217;</li>
    <li>Enter this XML;
<code>
&lt;QueryList&gt;
&lt;Query Id="0" Path="Security"&gt;
&lt;Select Path="Security"&gt;*[System[(EventID=4672)] and EventData[Data[@Name='SubjectUserName'] = 'your-name-here']]&lt;/Select&gt;
&lt;/Query&gt;
&lt;/QueryList&gt;</code></li>
    <li>Replace &#8216;your-name-here&#8217; with your domain username</li>
    <li>Choose &#8216;OK&#8217;.</li>
    <li>Set the name to &#8216;Logins&#8217;</li>
    <li>Hit &#8216;OK&#8217;.</li>
</ol>

<p>And there you go. There in Custom Views will be a list of your login events. Find the earliest one in the day and that&#8217;s when you first logged in.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.stevecooper.org%2Findex.php%2F2010%2F06%2F28%2Fhow-long-have-you-been-at-work-a-windows-hack%2F&amp;title=How%20long%20have%20you%20been%20at%20work%3F%20A%20Windows%20Hack." id="wpa2a_18">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.stevecooper.org/index.php/2010/06/28/how-long-have-you-been-at-work-a-windows-hack/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>On Learning to Write Languages</title>
		<link>http://www.stevecooper.org/index.php/2010/06/27/on-learning-to-write-languages/</link>
		<comments>http://www.stevecooper.org/index.php/2010/06/27/on-learning-to-write-languages/#comments</comments>
		<pubDate>Sun, 27 Jun 2010 11:02:46 +0000</pubDate>
		<dc:creator>Steve Cooper</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Programming Languages]]></category>

		<guid isPermaLink="false">http://www.stevecooper.org/?p=256</guid>
		<description><![CDATA[I&#8217;ve been learning to write languages recently. I read Steve Yegge&#8217;s thought-provoking post, in which he talks about how, if you know how to deal with language problems like lexing, parsing, translating, and compiling, then you know how to solve a large number of common programming problems. I&#8217;ve been using very simple custom languages at [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been learning to write languages recently.</p>

<p>I read Steve Yegge&#8217;s <a href="http://steve-yegge.blogspot.com/2007/06/rich-programmer-food.html">thought-provoking post,</a> in which he talks about how, if you know how to deal with language problems like lexing, parsing, translating, and compiling, then you know how to solve a large number of common programming problems.</p>

<p>I&#8217;ve been using very simple custom languages at work to write integration tests. Just little bits of work, but they&#8217;ve really helped quality by allowing us to write loads and loads of tests quickly and confidently. I think we have about 500 integration tests written which rely on small setup languages.</p>

<p>I think this has become possible because the system we&#8217;re writing against is pretty stable. The underlying classes and database tables we&#8217;re writing against don&#8217;t change too often.</p>

<p>This seems to be the key time for writing your own languages; the underlying libraries have reaches a point of stability, and you are being asked to do complex things to the underlying data.</p>

<p>So if you deal with classes or database tables called &#8216;Document&#8217;, &#8216;Alert&#8217;, and &#8216;Error&#8217;, then you can start making statements using those objects; things like</p>

<p><i>&#8216;When the document is saved, if the document is not Signed Off, alert the document owner and log an error&#8217;</i></p>

<p>Now, it should be possible to write a translator that turns this into c-sharp; something like;</p>

<pre><code>public void OnSaved(Document document)
{
    if (document.State != DocumentState.SignedOff)
    {
        SendAlert(document.Owner);
        LogError(document);
    }
}
</code></pre>

<p>The first version is significantly easier to understand and write. You can show this to your customer and ask if he agrees with the statement. The language helps communication. The c-sharp is no help at all in communicating.</p>

<p>So, custom languages can help put together systems that are easier to understand, because the language is tuned to the problem, and easier to modify, because the code is invariably shorter than it would be in the general-purpose programming language.</p>

<p>To my mind, if I can learn to write interpreters, compilers, and translators, it allows me to write software in a way that is significantly more easy to maintain.</p>

<p>There are, however, two big problems;</p>

<p>First, learning to write languages is not trivial. It&#8217;s a significant investment of time. Your manager is not going to be happy about a proposal that starts &#8220;Can I spend the next month learning about languages and not writing production code&#8230;&#8221; so I think you have to learn about these things in your own time.</p>

<p>Second, once you know how to write interpreters, they are themselves fairly hefty beasts. If it takes you 300 lines and a day of work to write a lexer and parser, you&#8217;d better be certain you save more than 300 lines and a day of work in the course in writing scripts in the new language &#8212; otherwise what was the point? So you have to pick your battles, picking only those areas that are ripe for better automation.</p>

<p>If you meet these two criteria &#8212; you&#8217;ve learned languages on your own time and you&#8217;re picking an area that&#8217;ll benefit from it &#8212; I think writing your own languages is a very valuable ability.</p>

<p>So, I&#8217;m now reading heavily in the area, writing my own lexers and parser by hand, and starting to look at automated tools like <a href="http://www.antlr.org">ANTLR</a> and Irony. <a href="http://irony.codeplex.com/">Irony .Net Language Implementation Kit</a></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.stevecooper.org%2Findex.php%2F2010%2F06%2F27%2Fon-learning-to-write-languages%2F&amp;title=On%20Learning%20to%20Write%20Languages" id="wpa2a_20">Share/Bookmark</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.stevecooper.org/index.php/2010/06/27/on-learning-to-write-languages/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

