2D Head with a clock as an eyeball.
 Friday, August 22, 2008

I've always loved vi and vim with a passion, and when after reading a post from JP Boodoo about ViEmu I felt compelled to give it a whirl. ViEmu integrates vi/vim functionality with Visual Studio. Yes.... you too can :wq code files. Initially, I was concerned that it would hinder rather than help, mainly due to a discordance between the editing paradigms of vi and Visual Studio. Vi uses discreet editing, navigation and selection modes to maximise the usefulness of the keyboard in light of traditional console based terminals.

With advent of the graphical text editor, this paradigm fell from favour as keyboard usage was gradually overtaken by ever increasing armies of icons and other visual metaphors.

In spite of this, coders generally pride themselves as 'shortcut-smiths' and I found that my vi skillset was proving useful even with Visual Studio. I should also point out that at home I run Resharper and at work I use Refactor Pro and CodeRush, and that Viemu for the most part appears to play very nicely alongside them. ViEmu also works from Word, Outlook and SQL Management Studio.

So what more could I possibly get out of Visual Studio using a tool like viemu? I'd like to share some of the things I like the most about Viemu.

Navigation

In short, and without giving a course on vi usage, we can move around a and edit code files in ways that other editors don't even bother with. The following is a small sample of the possibilities.

  • Want to move 10 lines down from your current position? 10j
  • 5 words to the left? 5w
  • End of a word? e
  • Next line of whitespace? }
  • Move up to the closing parenthesis? %
  • Now move to the matching opening parenthesis? % again
  • Move to the 5th instance of the , character? 5f,

Editing

  • Delete the next 10 lines? d10d
  • Change the next 5 words? c5w
  • Append to the end of the current word? a
  • Append to the end of the line? A
  • Delete everything up to the closing parenthesis (a personal fave)? d%
  • Change the text upto and including the 3rd ) character? c3f)

I'm often confronted with the comment "But who deletes 10 lines of code?" Well, for starters, I work with line numbering ON. Let's say I don't want 3 methods anymore. I look at my current line position, I look at the line the last method ends on. I subtract the two values in my head, that comes to 43 lines. I then type d43d and I'm done.

The point is, that you begin to notice patterns in code. Assignments are usually at least three words long. A method with no parameters in C# takes 3 words to move to the opening bracket. Hitting %% gets me to the same place in that case also. Having the ability to add numbering and repetition to navigational and editing tasks is very powerful, and now I'll show you just one of the myriad way you can harness it.

Vi Macros

Once you have familiarized yourself with the toolset, it becomes quite easy to record macros for repetitive tasks. We use SQL scripts to deploy test data at work and every now and again I'll hear the repetitive tap-tap-tap of somebody hitting the following sequence of keys: END, CTRL+V, DOWN ARROW over and over and over again. Here is an example:

PRINT 'Employees.'

INSERT INTO dbo.Employees
(EmployeeNumber, EntityGuid, DomainLogin)
	SELECT 'EM001', '018B163B-7D4F-49E1-A640-6BD9B65073FF', 'DOMAIN\EM001'
UNION	SELECT 'EM002', '3D3201F8-523D-43B1-89BC-F2FF8CAEBD56', 'DOMAIN\EM002'
UNION	SELECT 'EM003', '48EC5825-374F-4043-849D-308B2C8AA093', 'DOMAIN\EM003'

--repeat 50 more times		

GO

The usual goal might be that a role column was added, and for starters we want to assign each employee to the same role. First we go to the insert line and add the Role column at the end. Now to begin the macro that will do the heavy lifting.

First I enter normal mode by hitting escape or ctrl+[. Next I type qa to start recording a macro to register 'a'. I then type A to append to the end of the line. I'm now in insert mode, so I type , 'Users'. I exit insert mode with escape or ctrl+[ and then move to the next line with j. Finally, to finish the macro I hit q.

To recap, all I typed was: <esc>qaA,'Users'<esc>jq Thats a whopping 15 keystrokes including the string I had to write anyway.

I now have a macro I can reuse by simply using the recall macro command @. To recall macro 'a' I actually have to type @a.

'So what', you say, 'That only does it once and having to type @a over and over again is just as tedious as paste, end, down??'

Well the final trick is that to do it 52 times over I type 52@a. Repetition of commands is definitely one of vi's strengths and you can use it pretty much everywhere. 

Variation: I want the the Role column to be the 3rd column in my insert. Simple.. a few minor changes like instead of using A I would use ^2f, to move to the second comma. I would have to write: <esc>qa^2f,i'Users', <esc>jq then finally 52@a and I'm done.

I'll admit, there is a bit of thinking going on there, and I might not be typing at 80 wpm, but I'm saving myself a whole lot of RSI. Oh... and looking totally l33t when I run that macro 52 times.

So is it worth it?

Well, I think so, but I think it really depends on the type of person you are. If you've already fallen for vi, and Visual Studio seems only bearable with Resharper installed, then I'd say absolutely get Viemu. It doesn't cost much and you can utilize almost everything vim has to offer. If not, the learning curve isn't huge, but its significant. Thankfully, Viemu maps Ctrl+shift+alt+V to instantly turn it on or off, so if it starts hurting your head, you can escape the pain. It plays nicely with existing productivity tools, and caches any keyboard mappings that it steals during operation, and it will put them back if you switch it off.

Still, vi is a cryptic way of editing code, so if you struggle with remembering the keyboard shortcuts for Build, Step Into & Step Over, then I'd suggest that this product isn't for you. But if you want to add a new light sabre to your existing Jedi toolkit, then I'd encourage you to give it a try. Maybe even install gvim for a while to replace notepad, to help get used the whole vi thing.


Filed under:  | 
 Sunday, July 13, 2008

So after a great day yesterday of presentations and, ultimately pizza, I'm sitting here in a Lecture Theatre at the University of South Australia in Adelaide enjoying presentations for Code Camp SA, day 2.

Personally, I've been very impressed with the quality of presentations, and some highlights for me thus far have been:

I'm also keenly awaiting a presentation by Corneliu I. Tusnea on CLR Production Debugging. This particular topic should be dear to all our hearts as developers, and Corneliu really knows his stuff.

Hopefully in the next day or two I'll have some information regarding a presentation that Jason Stangroome and I gave, we decided to give a bit of a feature comparison of Subversion and TFS SCCMs smackdown style. I'm grateful to Paul Stovell for helping Jason and I polish our ideas and giving us plenty of inspiration and motivation.

So another big thankyou should go to Peter Griffith and ADNUG for making CCSA a reality, and yeah the pizza last night was awesome. I must say its nice to sit back today and not worry about my own material, and I look forward to the rest of the day. And if your at CCSA08 today, collar me at lunch and say hi!


Filed under:
 Wednesday, June 11, 2008

Today Resharper 4.0 goes RTM, if you haven't been following the EAP, you might be interested to know that we now have full C# 3.0 language and LINQ support.

That's not all we get, there are a swag of cool new refactorings, solution wide code analysis, extra framework annotations, camel humps in code completion....the list just goes on.

There are some improvements to the VB experience like new refactorings only previously supported in C# 2.0:

  • Convert Method to Property
  • Convert Property to Method
  • Pull Members Up
  • Push Members Down
  • Extract Interface
  • Extract Superclass
  • Convert Interface to Abstract Class
  • Convert Abstract Class to Interface
  • Extract Class from Parameters
  • Use Base Type Where Possible
  • Replace Constructor with Factory Method
  • The ASP.NET guys don't miss out either, amongst other things - a performance increase to page analysis, which has been a real problem for large ASP.NET pages in the past.

    Personally, I find Resharper to be the best C# productivity tool out there for the money, and they are paying more and more attention to VB.NET. Combined with Viemu its my productivity suite of choice and I encourage you to give them both a try.


    Filed under:  |  |  | 
     Wednesday, May 21, 2008

    Drought. Heat. Life.

    MexicanSun_thumb

    1280x1024

    2560x1024

    1920x1080

    3840x1080

    Its been almost a year, I wish I had done more desktops, but life has been tough. 

    Suitable as a diptych or just a single monitor. Let me know if you want the original for your own cropping pleasure (60MB @ 5120x4096)

    If you haven't seen my previous desktops, you can find them here.


    Filed under:  | 
     Wednesday, May 14, 2008

    Recently I discovered the xUnit.NET framework for unit testing, and it is a very nice minimalist framework for TDD. I especially like writing tests for F# code using it. It allows me to write very short test suites against any CLR library, in most .NET languages. For example:

    #light

    open Xunit
    open NT.Model

    let sut = new Person("Jim")

    [<Fact>]
    let jim_is_a_geek() = Assert.True(sut.IsAGeek)

    The Person class could be written in C# or VB and used here. Also note that the ultimate class name of this test is inferred by the filename. I could add explicit module and namespace information if necessary.

    In something like MbUnit / NUnit / Gallio I have to use the following OO style syntax...

    #light
    namespace NT.Model.Specs
    module PersonSpecs
    
    open MbUnit 
    open NT.Model
    
    [<TestFixture>]
    type jims_behaviours() =
      let sut = new Person("Jim")
      [<Test>]
      member j.is_a_geek() = Assert.True(sut.IsAGeek)
    

    Note that the namespace and module must be declared in order for the gallio runner to discover the tests. I think this might be a bug...

    However, regardless of the framework you use, F# also lends itself well to setting up for customized approaches to testing. I feel this has some potential for BDD testing in F#. Take the following example:

    #light open Xunit let MustEqual expected actual = Assert.Equal(expected, actual) [<Fact>]let a_fluent_assertion() = 0 |> MustEqual 0

     

    Taking this one step further we can take advantage of operator overloading to provide extremely terse tests. Note that I don't actually advocate doing this, only pointing out that its possible:

    #light open Xunit let (&=) expected actual = Assert.Equal(expected, actual) let (&!=) notExpected actual = Assert.NotEqual(notExpected, actual) [<Fact>] let an_obscure_assertion() = 0 &!= 1

    Based on these samples, I think it is clear that without much effort, a fluent specification interface could be arrived at, perhaps even a domain specific one at that.

    F# record types are readily testable also:

    #light

    open Xunit

    type Person =
      { name : string;
        age  : int;
      }

    let Jim = { name="Jim"; age=28 }
    let Fred = { name="Fred"; age=52 }

    let IsNot expected actual = Assert.NotEqual(expected, actual)

    [<Fact>]
    let jim_is_not_fred() = Jim |> IsNot Fred

    Sometimes, the assertion framework isn't needed, but having a test runner is still obviously handy. For the next example I setup a discriminated union and then use pattern matching to determine the outcome of the test simply using the built in failwith keyword:

    #light
    
    open Xunit
    
    type Animal =
      | Dog
      | Cat
    
    type Person =
      { name : string;
        age : int;
        pet : Animal; }
    
    let Jim = { name="Jim"; age=28; pet=Cat; }
    
    [<Fact>]
    let Jim_cannot_own_cats() = 
      match Jim.pet with
        | Cat -> failwith("Jim owns a cat!")
        | _ -> ()
    

    A snippet from the xUnit console runner output for this failing test:

    Tests failed:
    
    1) Jims_specifications.jim_cannot_own_cats : Microsoft.FSharp.Core.FailureException : Jim owns a cat!

    On that...hopefully soon tools like Gallio will provide us with some F# support in Visual Studio for the Resharper test runner or even MSTest. At current support for xUnit testing with Gallio in F# projects appears to be a non starter. Alternatively, latest SharpDevelop betas have inbuilt F# and NUnit support which I find to be quite good.

    In the meantime we can go all 'old school' on VS 2008 to provide some ease of use.

    In the following screen shot I've added the xUnit.NET console runner to external tools by selecting from the menu, Tools, External Tools...

    externalTools

    Next I like to map this to a keyboard chord, say Ctrl+R,Ctrl+X:

    MappingToKeyBoard 

    So that now after building, I can run my entire test suite using my keyboard shortcut to yield a testing experience that is 'good enough' for TDD/BDD development in F#, well, that's my opinion of course :)

     testResult


    Filed under:  |  |  | 
     Wednesday, May 07, 2008

    Ayende recently posted his feelings about how Twitter can be misused from time to time.

    You cannot have a meaningful discussion in Twitter or IM, the conventions and limitations of the platform. Email is a better medium to expression complex concepts, but voice or video are far better methods of communication.

    I'm inclined to agree, though some people will indeed be able to have discussion with some meaning, its hard to have a discussion about a complicated set of ideas.

    I'm fine with a discussion between two people going forever and a day on Twitter. I'm not having a go at anybody who does. As Chuck says: let the tweets flow. It's just that the discussion is bound to be fairly light and easy.Sorry, but I dont like reading from bottom to top.

    I do think there are a few circumstances where Twitter's weaknesses as a communication medium/archive are exposed.

    Firstly, if things are busy in your twitterhood, spanning tweets may have the opposite effect that your looking for; if other people tweet in between your tweets, it will dilute your message.

    Secondly when you need to use around 5+ consecutive tweets to get your point across, it becomes clear that you simply need more characters per message. Spanning across multiple tweets to get an idea across is fighting against the tool.

    Should Twitter increase the char count? I feel the higher the char count goes, the less Twitter looks like a microblog engine and the more it looks like usenet anarchy. I happen to like SMS updates too so I feel it would break out of the SMS boundary.

    Lastly, for conversations that occurred while I wasn't obsessively staring at Witty, its kludgy to find the beginning of the discussion and then skip other peoples tweets that occurred in between. To be fair, that's not the fault of Twitter, and hashtags certainly make it easier to listen in to particular topics (much like IRC Channels) but most clients behave the same way.

    These few problems alone make Twitter a deal breaker *for me* when it comes to heady topics. Emails, blogs, and wiki's are ways in which I like to escalate such things. But if you like to contemplate quantum computing in 140 char chunks, more power to you.

    Incidentally, this was around 2200 characters or if you prefer, 16 consecutive tweets.


    Filed under:  | 
     Monday, April 28, 2008

    ...Other Project Euler posts...

    Today, my mission is to solve Project Euler Question #2:

    Find the sum of all the even-valued terms in the fibonacci sequence which do not exceed four million.

    The obvious solution is to use a brute force approach:

    public static int Problem2() {
      var fib = 0;
      var sum = 0;

      for (var n = 0; fib < 4000000; n++)
      {
        fib = Fibonacci(n);
        if (fib % 2 == 0)
          sum += fib;
      }

      return sum;
    }

    private static int Fibonacci(int n) {
      return n < 2 ? 1 : Fibonacci(n - 2) + Fibonacci(n - 1);
    }

    Lazy evaluation

    Slightly more elegant solutions do exist. For starters, F# allows us to use lazy evaluation to create sequences of values. This has the advantage of sequence values only being evaluated when necessary. Robert Pickering's "Foundations of F#" gives us the following example for generating fibonacci numbers using lazy evaluation. In fact, the example here is one of an infinite list.

    #light
    let fibs = (1, 1) |> Seq.unfold(fun (n0, n1) -> Some(n0, (n1, n0 + n1)))

    Initially, a pair of values (named a tuple) 1 and 1 is piped through to the Seq.unfold function. The unfold function allows us to define how we want our list to be generated. It returns a disciminated union type called Option which in this case is called with a tuple, the first value in the tuple being the value applied to the list, the second value is the accumulator.  The accumulator basically allows you to pass some state into next round of calculations. Option types are there own blog post, as they are a totally awesome example of applied discriminated unions.

    To put the fibs function into english: fibs takes a tuple of integers (n0, n1), and always returns the first member in the tuple, however when we evaluate the next item in the sequence, the first member of the tuple will be n1 and the second will be n0 + n1. This will go on and on even once we hit the 32bit limit and starting looking at negative integers.

    Pattern matching

    So how does this help us to solve question two? Using a similar approach as the C# version we could alter the way the list is generated before we summate:

    #light

    let summate x = x |> Seq.sumByInt (fun n -> n)
    let Question2 =
      (1, 1)
      |> Seq.unfold(fun (n0, n1) ->
        match n0 with
          | n0 when n0 % 2 = 0 -> Some(n0, (n1, n0 + n1))
          | n0 when n0 > 4000000 -> None
          | _ -> Some(0, (n1, n0 + n1)))
          |> summate

    Here, I'm using simple pattern matching to do two things, make sure any numbers that arent even are mapped to 0, and also to ensure that once n0 exceeeds 4 million, we stop generating values in the list. This is the power of the unfold function at play: the ability to lazily evaluate the members of the list and also to define the condition to terminate the list.

    A Mathematical approachFibonacci green - by Mark Strozier

    However, this is still a brute force approach, although dressed up a little. Since the fibonacci set is full of patterns and properties surely we can take advantage of one or three? Of course, each 3rd term in the fibonacci set happens to be even. We also have an approximate ratio between two consequetive terms: Phi. Therefore, the ratio between even terms is approximately Phi to the power of 3. Using these properties we should be able to come up with the same answer as our brute force approach: 

    #light
    let summate x = x |> Seq.sumByFloat (fun n -> n)
    let PhiCubed = ((sqrt(5.0) + 1.0) / 2.0) ** 3.0
    let Question2 =
      2.0
      |> Seq.unfold (fun x -> match x with
        | x when x < 4000000.0 -> Some(x, Math.Round(x * PhiCubed))
        | _ -> None)
        |> summate

    So with a starting point of 2.0 I simply round the result of x * (Phi ^ 3) to yield each value in my list which is then summed. The C# interpretation as follows:

    public static double Problem2() {
      return EvenFibsBelowFourMillion().Sum();
    }
    private static IEnumerable<double> EvenFibsBelowFourMillion() {
      var phiCubed = Math.Pow(((Math.Sqrt(5D) + 1D) / 2D), 3);
      var fib = 2D;
      do {
        yield return fib;
        fib = Math.Round(fib * phiCubed);
      } while (fib < 4000000);
    }

    In Summary 

    C# still outperforms F# ever so slightly on my machine, C# taking an average 0.002 milliseconds, F# taking an average 0.003 milliseconds. So far I feel that F# lives up to the promise of a 'similar performance profile as C#'. I'm starting to appreciate the 'point and shoot' nature of F# syntax. Having said that, the C# solution is equally nice and easy to read. I cant wait to get into some of the meatier questions.


    Filed under:  |  |  |  | 
     Sunday, April 06, 2008

    One of the languages I have decided to learn this year is F Sharp. F# is a multi paradigm programming language; it is capable of expressing ideas in an imperative, functional and object oriented fashion. It is the result of some very hard work by Microsoft Research and integrates into VS2005 and 2008. F# rounds out the MS language ecosystem quite nicely i think, as it provides a solid platform for mathematical solutions, as well as maintaining the ability to be used to create windows applications of all types.

    I decided to get my head around using it by reading Foundations in F# and by undertaking Project Euler, a series of mathematical puzzles. I'm certainly not alone, and to set myself apart from those who have trod before me, I've decided to compare the solutions in F# to possible solutions in to my favourite language: C# 3.0. Since I am no maths expert, this could be a real trainwreck...

    Question 1: Find the sum of all the multiples of 3 or 5 below 1000.

    Sounds simple enough. We can use mod 3 and mod 5 to filter a list of positive numbers below 1000 and sum the result. One approach might be:

    static int Problem1()
    {
      return MultiplesOfThreeAndFiveBelow(1000).Sum();
    }

    static IEnumerable<int> MultiplesOfThreeAndFiveBelow(int n)
    {
      for (var i = 0; i < n; i++)
      {
        if (i % 3 == 0 || i % 5 == 0)
        yield return i;
      }
    }

    OK, so thats a little expensive, I've used a generic list instead of an array, but hey it works. Its main strength is that its readable. So how about a functional approach? 

    let solution = Array.init 1000 (fun x -> if x % 3 = 0 || x % 5 = 0 then x else 0 )
                   |> Array.fold_left (+) 0

    Array.fold_left is a higher order function, since it accepts a function as a parameter. I am passing it the addition operator (a function in its own right) and an accumulator initialized to 0. The first iteration of the fold function will take the value of first element of the sequence and add it to zero. The result is then added to the value of the next element in the sequence to produce a new result and so on. Essentially, it provides the summation required to complete this problem. The downside with this approach is that it naively overestimates the size of the array required, and folding left doesnt immediately lead the reader to think of summation.

    I can do better though, F# provides us some constructs for more efficient array initialisations; a comprehension syntax:

    let solution = Array.fold1_left (+) [|
                                           for x in 1 .. 999 
                                           when x % 3 = 0 || x % 5 = 0 -> x
                                        |]

    While this is readable, some might complain that Array.fold1_left is a cryptic way to summate, and is therefore hard to maintain, so without much effort we can curry it to look like this:

    let summate a = Array.fold1_left (+) a
    let solution = summate [|
                               for x in 1 .. 999 
                               when x % 3 = 0 || x % 5 = 0 -> x
                           |]

    I've split the array initialization over 4 lines for extra readability but in essence its only 1-2 lines of readable code to solve Project Euler Problem 1 using F#.

    So, for those of you interested in speed, using the time honored technique of taking the average execution time over 1 million executions, the C# implementation came in at around 10 times faster than the final F# one. The first F# implementation was faster but was still two times slower than C#. The main bottleneck seemed to be the array initialization; using the comprehension syntax is a little pricey. But, who cares about optimization anyway? It was only the difference between fractions of a millisecond anyhow :)


    Filed under:  |  |  |  | 
    © Copyright 2008 Jim Burger