Category Archives: Programming

Standing Desk for Tall People and Multiple Monitors

I’m a tall person and like many developers, I sit. A lot. I’ve been feeling a pain in my back for some time now and I’m determined to do something about it. As usual Scott Hanselman has already been there and done it for you. Buy this man a beer and find a way to keep him alive. He’s our Obi-Wan. OK! Enough gushing.

  1. Exercise. I plan to work out 3 times a week during lunch so as to strengthen my core.
  2. Eating. I already eat health. I weight myself everyday, allowing for slight variations that tend to occur. The idea is to notice any drastic changes. I lost 15 pounds in 1 month due to a thyroid storm but luckily it was temporary.
  3. Standing and Posture. Sitting, hunched over at ill fitting desks and chairs has been my undoing. There have been lots of studies and developers talking about how switching from sitting to standing has helped them so I won’t bore you with the details. Needless to say, tall people are SOL when it comes to office furniture (unless you happen to work at a very nice company that makes an effort to adhere to ergonomic standards).

Did I mention I code? That’s important because we’re inherently lazy (hence the back pain). So, I researched some standing desks. Then I researched some that would fit me. Geekdesk has really nice desks and I was willing to splurge on a desk but waiting 6-7 weeks for it to ship and then paying 300+ on shipping is just not worth it.

Did I mention I’m lazy? That’s important. Because laziness breeds invention. Over my lunch break today, I finally had enough of my back pain and decided to just make my standing desk, even if it is just boxes stacked together in Jenga form. I walked around the house and found 2 things that could immediately help me.

  1. Expedit Workstation –
  2. Lack Coffee Table –

Stack these two together and you get a standing desk that works for a tall person (> 6′ 4″). Benefits include:

  • Simple
  • Works for tall people
  • No carpentry required
  • No separate keyboard tray necessary
  • No furniture destroyed (easy to put the coffee table back when guests come)
  • Supports Dual Monitors (multiple monitors is the only way to work and any solution you use should utilize this)

Standing Desk For Tall people with Multiple Monitors
This is what the result looks like. The laptop is below the desk and makes it easier to sit down when I need a few minutes to rest. I do hope you get to utilize this multi monitor solution. If you’re still hell bent on carpentry and building, take a look at the IKEA Hackers page.

//ToDo Look into getting some cushioning for the feet. I used a yoga mat today and it felt great. Only problem is that my feet started sticking on the mat after an hour. Donn Felker recommended the GelPro mat in one of his tweets and I might need to look into that too.

Tagged , , , , , , , ,

Developer Professionalism

There are numerous articles on the net about “developer professionalism” but I keep coming back to “Software Engineering Code of Ethics and Professional Practice“. You see, just about anyone can call themselves a developer, read a few books, accrue work experience at sub-par companies (those that do not demand professionalism) and end up as part of your organization.

As a professional in charge of hiring, it is your responsibility, to find developers who meet a certain level of professionalism. Junior developers are rarely held up to the same standards and I feel this does them a disservice. There are some things the junior dev will not be able to talk about but asking them questions like, “Give me an example of how you took responsibility for your code/work?” is a good way to get them talking about ethics and to find out just how professional they are. I have rarely come across any question that tried to ascertain your professionalism in interviews and that is both sad and scary.

If I find a problem with your code that would take you 10 min to fix and take me 30, don’t ever pass your faulty code to me to fix because you’re busy. Take responsibility [1.01, 6.08]. Fix it yourself.  And on the other side of the coin, if you find fault with my code, bring it to me to fix. Give me the chance to learn what I did wrong so that I don’t make the same mistake again.

So the next time you run into a problem, be it hiring a new dev, or an issue in code, ask yourself, “What would a professional dev do?”

Tagged , , ,

F# Image Processing – Get Background Color

I recently had the need to get the background color of an image. The algorithm used to perform this is simple:

Get the image and find the color that occurs at least 3/4 of the time more than the next most occurring color in the image.

Here are some examples of images and what we would expect as a result.


The background image color is white.


The background image color is red.


The background image color is white.

Now, without further ado, here is the F# code. It should be relatively easy to follow.


open System
open System.Text.RegularExpressions
open System.IO
open System.Windows.Forms
open System.Windows.Forms.DataVisualization.Charting
open System.Diagnostics

let main (args: string[]) = 

    let sw = new System.Diagnostics.Stopwatch()
    for i = 21 to 21 do
        let img = "C:\\Temp\\ImageSamples\\" + Convert.ToString(i) + ".jpg"
        // get the image
        let bitmap = new System.Drawing.Bitmap(img)
        // process image
        let background = AboutDev.ImageProcessing.GetBackgroundColor(bitmap)
        printfn "%A is: %i, %i, %i" i background.R background.G background.B

    printfn "Time elapsed: %A" sw.Elapsed



namespace AboutDev

    #nowarn "9"
    open System
    open Microsoft.FSharp.NativeInterop
    open Microsoft.FSharp.Collections
    open System.Drawing
    open System.Drawing.Imaging 
    open System.Collections.Generic

    module ImageProcessing = begin

        let GetBackgroundColor (image:Bitmap) =

            // Get a Color from RGB values
            let GetColor x  = Color.FromArgb(Convert.ToInt32(int16 (NativePtr.get x 0)) , Convert.ToInt32(int16 (NativePtr.get x 1)) , Convert.ToInt32(int16 (NativePtr.get x 2)))

            // Check for grayscale images
            let IsGrayscale (x:Color) = x.R < 128uy && x.G < 128uy && x.B < 128uy

            // Create a thumbnail only if the image is more that the allowable size of 300 * 300 pixels
            let ToThumbnailOrNot (b:Bitmap) = 
                let maxAllowedDimensions = 300

                // Create a thumbnail that is sized proportionately to the original
                let CreateThumbnail (b:Bitmap) = 
                    let maxPixels = 100.0

                    // compute the scaling factor of the original image to our max allowed pixels
                    let scaling = if(b.Width > b.Height) then maxPixels / Convert.ToDouble(b.Width)
                                  else maxPixels / Convert.ToDouble(b.Height)
                    // compute the size of the new image as a sequence
                    let size = (Convert.ToInt32(Convert.ToDouble(b.Width) * scaling), Convert.ToInt32(Convert.ToDouble(b.Height) * scaling))
                    // create the thumbnail
                    new System.Drawing.Bitmap(b.GetThumbnailImage(fst size, snd size, null, IntPtr.Zero))

                if b.Width > maxAllowedDimensions && b.Height > maxAllowedDimensions then CreateThumbnail b
                else b

            // Get a thumbnail of the image if it is big or use the original image
            let img =  ToThumbnailOrNot image

            // dispose the original image because a copy was made in the previous statement

            // The array that is going to contain argb values to then do counts on
            let items = List<int32>()

            // lockbits on image so that the image can be processed quicker using unsafe means
            let bd = img.LockBits(Rectangle(0,0,img.Width,img.Height),ImageLockMode.ReadWrite,PixelFormat.Format32bppArgb)

            // pointer to use to go through the image
            let mutable (p:nativeptr<byte>) = NativePtr.ofNativeInt (bd.Scan0)
            for i=0 to img.Height-1 do
                for j=0 to img.Width-1 do
                    // Get the color of the [x,y] pixel
                    let colo = (GetColor p).ToArgb()
                    // add the ARGB value to our list
                    // move to the next pixel on the row
                    p <- NativePtr.add p 4
                // The stride - the whole length (multiplied by four to account for the fact that we are looking at 4 byte pixels
                p <- NativePtr.add p (bd.Stride - bd.Width*4)

            // Unlock the image bytes

            // test code to see the image we worked on
            //img.Save("C:\\temp\\result.jpg",  System.Drawing.Imaging.ImageFormat.Jpeg)

            // dispose the image that we worked on

            //List.ofSeq items |> Seq.countBy id |> Seq.sortBy (fun x -> (~-)(snd x) ) |> Seq.take 10 |> Seq.iter (printfn "%A")

            // get the first two item that occur the most in the array as a sequence
            let res = List.ofSeq items |> Seq.countBy id |> Seq.sortBy (fun x -> (~-)(snd x) )

            // Check to see that we have at least 2 colors
            if ( (Seq.length res) < 2) then res |> Seq.head |> fst |> Color.FromArgb

                let zero = Seq.head res     // first item in the sequence
                let one = Seq.nth 1 res     // second item in the sequence

                // Get the most prominent color
                let background = fst zero |> Color.FromArgb
                let background2 = fst one |> Color.FromArgb

                // Make sure the image is not grayscale and
                // the background color occurs at least 3/4 as much as the next closest color

                if( (IsGrayscale background) || (((Convert.ToDouble (snd zero)) * 0.75) < (Convert.ToDouble (snd one)))) 
                    then //printfn "Cannot determine color"
                         //printfn "First color is: %A, %A, %A" background.R background.G background.B
                         //printfn "Second color is: %A, %A, %A" background2.R background2.G background2.B
                    //printfn "%A, %A, %A" background.R background.G background.B
                    // Return the color

    end // End Module
NOTE: The sample code above is just that, a sample. You will need to play with it to do your bidding.

To set this up this comparison, I had a sample size of 20 images. The original code without my algorithm optimizations took 31.62 seconds to run. The F# code took 0.78 seconds.

Original Code F# Code
image image

Optimizations I made over the original code:

1. Use of LockBits

2. Creating thumbnails of the original image to work on instead of the original image when that image is large.

During my testing, I also created an image that was 13,648 * 7,912 and it took [00:00:01.2340651] to process it in my F# code. I had to stop the original C# code running on that image after 10 min! When I implemented my algorithm in C#, I was able to get the speed of the 20 images to 7.88 seconds. Still faster in F#.



F# allowed me to play with the algorithm very easily and tweak away until I got it just right.

You have to love the power of a language that lets you focus on the algorithm rather than on the minutiae of the language.

Tagged , , , , , , ,

Poor Man’s Validation

Does your validation drive you crazy? Are you writing too much validator code? Have you lost your sense of humor?


Well, not to worry because now, there’s a little hack to make Validation easier.

Lets say I had a Company class as defined by:

    public class Company
        public string Title

Now, say I wanted to add validation to this so that the

  • Title is Required
  • Title must be up to 10 characters
  • Title can only be Alpha and space

In order to achieve this quickly, you can add the System.ComponentModel.DataAnnotations.dll file to your project (Make sure its the latest one from Codeplex). Then update your class definition as follows:

    public class Company
        public string Title

Now you can run the following code to validate your class instance as follows:

    // Test instantiation
    ValidationContext vc = null;
    bool bCanCreate = false;
    List<ValidationResult> validationResults = new List<ValidationResult>();
    Company _company = new Company();

    // Test 1 : Acceptable test undeo 10 characters and alpha.
    _company.Title = "The Title";
    vc = new ValidationContext(_company, null, null);
    bCanCreate = Validator.TryValidateObject(_company, vc, validationResults, true);
    Debug.Assert(bCanCreate == true);

    // Test 2: Failure test 
    _company.Title = "32 Pan";
    vc = new ValidationContext(_company, null, null);
    bCanCreate = Validator.TryValidateObject(_company, vc, validationResults, true);
    Debug.Assert(bCanCreate == false);

    // Test 3: Failure test 
    _company.Title = "";
    vc = new ValidationContext(_company, null, null);
    bCanCreate = Validator.TryValidateObject(_company, vc, validationResults, true);
    Debug.Assert(bCanCreate == false);

    // Test 4: Failure test 
    _company.Title = "abcdefghijklm nopqrstuvwxyz";
    vc = new ValidationContext(_company, null, null);
    bCanCreate = Validator.TryValidateObject(_company, vc, validationResults, true);
    Debug.Assert(bCanCreate == false);

So now you’re bound to be validator approved.


Tagged , , , , ,

Excelcification: Brain Teaser Code

Problem: Someone at work recently asked me how you would go about converting excel header rows into integers. In the image below, you see each column and its corresponding integer value.


Thus, A = 0, B = 1, C = 2 and so on. Since I have no better word to describe this process, I’m going to call it Excelcification.

Def: Excelcification. The act of converting a alpha column into its numeric representation.

However, Excel cells go from A to Z and then become AA, AB, AC etc. So if Z = 25, AA = 26, AB = 27 and so on.

Your mission is to create a method that takes a string that corresponds to the excel column (don’t have to worry about spaces etc for now) and change that to its integer value.


In case you didn’t know, the largest column in Excel 2010 that I could see was XFD.


So what is the Excelcification of “XFD”?


[Jeopardy theme music plays…]


[Some time later…]


[Some more time later…]


Are you done? How did you do it?


My process was to recognize that this is going to be Base 26 arithmetic, also know as Hexavigesimal. But you didn’t need to know that. If you know how base 2 (binary) works, you can extrapolate it to work for base 26.  So how does base 2 work. If you remember your truth tables from high school/college, you would know that in binary:

01 = 2^0

10 = 2^1

11 = 2^1 + 2^0


Now extrapolate this for base 26 and realize that in binary, your digits are only 0 and 1 whereas in hexavigesimal, your digits are 0 through 25. (See the link there to A through Z).


A = (26^0) * Numeric_Value(A)

B = (26^0) * Numeric_Value(B)



So if you create a method for this your code should be:

         public static class ExtensionMethods
        /// <summary>
        /// Converts a string into its hexavigesical (base 26) representation.
        /// </summary>
        /// <param name="sxCol">Input string of letters.</param>
        /// <returns>-1 if input is null or empty, base 26 integer representation of input otherwise.</returns>
        public static int Excelcify(this string sxCol)
            int result = -1;
            sxCol = sxCol.ToUpper();

            if (string.IsNullOrEmpty(sxCol))
                return result;

            for (int i = sxCol.Length; i > 0; i--)
                char _c = sxCol[i-1];
                // Function =>  (26 ^ reversed_char_index) * char_value
                //          A = 1 ------ Z = 26 ------ AA = 27 ------ AZ = 54
                // 64 because there 'A' starts at index 65 and we want to give 'A' the value 1.
                result += Math.Pow(26, sxCol.Length - i).ToSafeInt() *  (_c.ToSafeInt() - 64);

            return result;

And you would call your code as such:

 int iResult = “A”.Excelcify();
Debug.Assert(res == 0);
iResult = "Z".Excelcify();
Debug.Assert(res == 25);
iResult = "AA".Excelcify();
Debug.Assert(res == 26);


Thus “AAA” = 702, and “XFD” = 16383.

That is exactly 2^14 cells for those binary folk!

Tagged , , , , ,