Wednesday, September 19, 2012

Getting SignalR and PhoneGap Working Under Windows Phone Emulator

I am learning both PhoneGap and SignalR and figured out tonight how to enable both polling and message sending under PhoneGap, at least within the Windows Phone emulator. I have not tried on my Android phone yet. That will wait until I deploy the server hub.


Server Side Code

using SignalR.Hubs;

namespace Vocab.SignalR.SignalR.Sample
{
    public class Chat : Hub
    {
        public void Send(string message)
        {
            // Call the addMessage method on all clients
            Clients.addMessage(message);
        }
    }
}

Yes. That is all. That means when any JavaScript client calls the Send method, the server will dispatch the message to all connected clients by calling their "addMessage" JavaScript method. Clients is declared as dynamic to allow this to work.

HTML & JavaScript Code Under PhoneGap and Windows Phone Emulator

Pay attention most to the blue italicized lines. That's what I had to do in order for the Windows Phone emulator and/or PhoneGap to work properly. At one point before both of those lines, I had it able to get new messages when sent by the server, but it would not send messages to the server. Now it all works! See the section underneath for a standard HTML client that I run within a web browser on the desktop, which has nothing to do with PhoneGap or mobile jQuery whatsoever. But, both the phone app and the page are able to send and receive messages from and to each other now.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>Chat</title>
    <link rel="stylesheet" href="jquery.mobile-1.0.1.css" />
    <script type="text/javascript" src="jquery-1.7.1.js"></script>
    <script type="text/javascript" src="jquery.mobile-1.0.1.js"></script>
    <script type="text/javascript" src="http://jgough/SignalR/Scripts/jquery.signalR-0.5.3.js"></script>
    <script type="text/javascript" src="http://jgough/SignalR/signalr/hubs"></script>
    <script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
    <style type="text/css">
        .ui-title
        {
            font-weight: bold;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            $.connection.hub.url = "http://jgough/SignalR/signalr";

            // Grab the hub by name, the same name as specified on the server
            var chat = $.connection.chat;

            chat.addMessage = function (message) {
                $('#chatMessages').append('<li>' + message + '</li>');
            };

            $.connection.hub.start({ jsonp: true });

            $("#sendChatMessage").click(function () {
                var message = $("#chatMessage").val();
                console.log("Message: " + message);
                chat.send(message);
            });
        });
    </script>
</head>
<body>
    <div id="home" data-role="page">
        <div data-role="header">
            <h1>
                Chat!</h1>
        </div>
        <div data-role="content">
            <h2>
                Chat your heart out...</h2>
            <div>
                <textarea id="chatMessage"></textarea>
                <br />
                <a id="sendChatMessage" data-role="button">Send Chat Message</a>
            </div>
            <ul id="chatMessages">
            </ul>
        </div>
        <div data-role="footer" data-position="fixed">
            Thank you for chatting
        </div>
    </div>
</body>
</html>

Regular HTML / JavaSript Page for Desktop Browsers

You may notice that not all the variable names or page elements have the same names. This is fine. The only important part is that the chat instance have an "addMessage" function, and that when the #broadcat button is clicked it calls client.send, as both of these correspond to what we saw above in the server hub code.

<html>
<head>
    <script src="../Scripts/jquery-1.8.1.js" type="text/javascript"></script>
    <script src="../Scripts/jquery.signalR-0.5.3.js" type="text/javascript"></script>
    <script src="../signalr/hubs" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            // Proxy created on the fly
            var chat = $.connection.chat;

            // Declare a function on the chat hub so the server can invoke it
            chat.addMessage = function (message) {
                $('#messages').append('<li>' + message + '</li>');
            };

            $("#broadcast").click(function () {
                // Call the chat method on the server
                chat.send($('#msg').val());
            });

            // Start the connection
            $.connection.hub.start();
        });
    </script>
</head>
<body>
    <input type="text" id="msg" />
    <input type="button" id="broadcast" value="broadcast" />
    <ul id="messages">
    </ul>
</body>
</html>







Sunday, September 16, 2012

The Fragile Managerfesto Patterns: Bad Boss Behaviors

This is a video in draft form of what I want to become a launching pad for demonstrating many "Bad Boss Behaviors" and the remedies for them that agile practices bring.

So far in this one we have:
  1. Barge In Boss: Manager, unaware of what an employee is working on, interrupts him.
    1. Agile Remedy: Visible Workspace and Tools
  2. Belittler Boss: Denigrates the employee's desire to improve the customer experience
    1. Agile Remedy: clear values and an outward, customer focus
  3. Pinheaded Policy Pushing Boss: Imposes strict, top-down, and very draconian policy requirements on the employee.
    1. Agile Remedy: living standards and openness to modern and changing realities
  4. I'm Louder = More Power Boss: the boss, when his thinking is challenged, responds by speaking louder, emphasizing he has more power than the employee.
    1. Agile Remedy: a flatter structure, managers who are not bosses, but service-oriented leaders and hands-on
  5. Priorities Ping Pong Boss: this boss exercises his control by shifting employees from one priority project to another at will, often leaving a trail of unfinished work behind.
    1. Agile Remedy: singluar focus until completion on tasks and projects, not rapid reassignment based on a "fighting fires" approach.
  6. Everything's Easy and Instant Boss: this boss assures you that your new assignment is simple, will not take long, and must be done instantly, no matter what. These bosses continually assign a fixed, non-negotiable amount of work to someone and require that it be completed by a fixed, non-negotiable, and arbitrary deadline. In software development, this is a typical "waterfall" or "big bang all at once" approach.
 This list is a simple draft too. But, I really like having short-hand names for these bad behavior patterns, so it would also be nice to have short-hand names for the good behaviors.

We're going to record the results of what happens with an Everything's Easy and Instant Boss does push his a arbitrary deadline onto a much smaller scale: that of reading a couple of paragraphs. It's kind of an obvious failure case, isn't it? But, if a human being cannot predict with any accuracy how long a couple of paragraphs will take to read aloud, then why do they keep getting away with telling customers that a project can be "complete with high quality and correctness" by an arbitrary deadline?

Things that make you go Hmmmmmm.

Tuesday, August 28, 2012

More Thoughts on Compressed Schedules: 151 hours in 3 weeks; followed by 9 days off

When briefly discussing the topic of compressing multiple weeks worth of work into fewer weeks, followed by more lengthy time off with VersionOne CTO Ian Culling today, he asked me: "Have you read that book?"


I asked, "What? There's a book about it?"

He said, "Yes, the Seven Day Weekend. I've read it and will bring it for you to borrow."

The book is written by Ricardo Semler, CEO of a Brazilian company, Semco, which has been very successful through the application of many non-traditional practices. 

Learn more here:


A typical year's worth of work is considered 2,080 hours. If you have 3 paid weeks of vacation, then the number of hours you actually work will be 1960.

Now, what's 1960 / 52? It's 37.69231.

So, if you spread your vacation into each week, your 40-hour week would be 37 hours and 42 minutes, about.

Ok, great. How much is 37h 42m times 4 then? Answer: 150.76923

For argument's sake, we'll call this 151 hours.

Now, what if we worked these hours in 3 weeks instead of 4? Would that be so hard?

51, 50, 50 = 151.

Here's a possible schedule:

Week 1:

Mon: 12 hours: 7:30 - 5:30 = 9 hr work, 1hr lunch, and 9 pm - 12 pm = 3 hr work
Tue: 10 hours: 8:30 - 7:30 = 10 hr work, 1 hr lunch
Wed: 12 hours: same as Monday (12 hr work)
Thu: 9 hours : 8:30 - 6:30 = 9 hr work, 1 hr lunch
Fri: 8 hours : 8:30 - 5:30 = 8 hr work, 1 hr lunch

For week 1, this ends up at 51 hours.

For weeks 2 and 3, you do the same thing, except replace Tuesday with 8:30 - 6:30, for only 9 hours.

Or, maybe you'd prefer to do two heavy days back-to-back and get them over with. Fine, go for it. Swap Tuesday and Wednesday. Maybe you have the flexibility, and desire, to do 4 hours on Sunday evening, or Saturday morning. Great, then chop off 4 from Mon or Tue, or turn them into simple 10 hour days. It's up to you and your employer.

Anyway, if we think of the two twelves in the original example, this makes for just two days that are longer than the ordinary day, Monday, and Wednesday.

Now, by spreading out our 3 weeks of vacation to reduce our work week to 37.69 hours a week, we can work the fourth week's hours ahead of time in just "ten extra" hours a week, from the point of view of the traditional "40 hour" work week.

Just think about this: what would having a 9 day vacation every single month enable you to do for your life, for your family, your community, and yes, even for your career and employer?

Working "around the clock" with a cell-phone, internet and VPN access may be the norm now, but if we're going to be doing that, then why not make 50 hours a week be the new norm, except follow it by one week off every month?

As the "next step down", but perhaps more palatable all around, consider the 5 week schedule compressed into 4 weeks.

Here, we have 37.69 hours times 5 = 188.46 hours.
So, divided by 4 = 47.12 hours per week, or 9.42 hours a day.

9.42 hours a day? That's almost nothing, right? It's 9 hours, 25 minutes, and 12 seconds actually :)

Big deal. Work from 8 am to 6:15, with, a 40 minute lunch break. That still gives you about 4 to 5 hours after work, assuming you get home around 7 and want to go to bed at 11.

With this schedule, you end up with pretty much regular hours, regular evenings, and regular, full weekends. Want to leave early on Fridays? Have at it. Work 2 to 4 hours from home in the evening, and leave on Friday at 2:15.

Yet, again, most importantly, is that after working this schedule for four weeks, you've already worked the same number of hours you would have worked in 5 weeks had you worked 8 hours a day.

Because you did it this way, you should now take 9 straight days off for a mini vacation. 

With 52 weeks in a year, the pattern is something like 40 working weeks, and 10 9-day mini vacations.

That's 200 days working, 90 days off.  But, add 10 more days and 4 more weekend days:
210 / 94 + 61 more weekend days from the other weekends.

We end up with 210 working days and 155 days off. Not bad.

Will the company shut down if people are out a week after working 4 straight weeks? I doubt it. Rotate the schedule so that not everyone is out the same week. Or don't. Shut the whole thing down. Be creative. Go for it.

Maybe my math is off a bit, but you get the picture.

Perhaps there are other, even better options. Maybe 10 weeks on, 2 weeks off (16 days straight!) is the ticket? For example: if you worked the same schedule as above, 9.42 hours a day, you'd have to work 10 weeks in a row, but then could take two full weeks off + 6 weekend days. Since, there are 4 groups of 12 in 52 weeks, you could it 4 times a year!

It all boils down to the fact that there are multiple ways to work toward this goal of both satisfying your obligations to your career, and of carving out more continuous blocks of time off for rest and recreation.


Sunday, August 26, 2012

Learning CoffeeScript, F#, and Haskell (and brushing up on math)

I've started to get very interested in new programming languages, as a result of working with people at http://www.VersionOne.com. At V1, they use CoffeeScript for some of the UI features. While also brushing up on some of my math fundamentals, I started watching this old (but good) video series:  http://www.learner.org/resources/series66.html?pop=yes&pid=189


The three algorithms I wanted to implement are factorial, the permutations algorithm, and combinations algorithm. The mathematical short hands for these are typically:
  • n!
  • P(n, r)
  • C(n, r)
To read more about these, you can find thousands of pages on the internet, including http://en.wikipedia.org/wiki/Permutation. But, I like http://www.MathIsFun.com in the algebra section.

Anyway, it's easier for me to memorize math concepts when I write my own functions to give me conceptual, hands-on grounding.

CoffeeScript:

factorial = (number) -> 
total = { Value : 1 }
iteration = (number, total) ->
unless number is 0 
total.Value = total.Value * number
iteration number - 1, total
total.Value
iteration number, total
factorialSplit = (number) -> 
total = { Value : 1 }
factorialSplit_iteration number, total
total.Value
factorialSplit_iteration = (number, total) ->
unless number is 0 
total.Value = total.Value * number
factorialSplit_iteration number - 1, total
total.Value

permutations = (totalNumberOfItems, numberOfItemsToChoose) ->
unless numberOfItemsToChoose <= totalNumberOfItems
throw "numberOfItemsToChoose cannot exceed totalNumberOfItems"
total = factorial totalNumberOfItems
divisorBase = totalNumberOfItems - numberOfItemsToChoose
divisorTotal = factorial divisorBase
total / divisorTotal

combinations = (totalNumberOfItems, numberOfItemsToChoose) ->
unless numberOfItemsToChoose <= totalNumberOfItems
throw "numberOfItemsToChoose cannot exceed totalNumberOfItems"
total = factorial totalNumberOfItems
divisorBase = totalNumberOfItems - numberOfItemsToChoose
divisorSubTotal = factorial divisorBase
divisorAdditionalToReduceBy = factorial numberOfItemsToChoose
divisorTotal = divisorSubTotal * divisorAdditionalToReduceBy
total / divisorTotal
console.log factorial 5
console.log factorial 10

console.log factorialSplit 5
console.log factorialSplit 10

console.log permutations 5, 3
console.log permutations 12, 4

console.log combinations 15, 5
console.log combinations 5, 3

Syntax Explanation

The syntax is a simplification of JavaScript, and is inspired by languages like Ruby and Python, for example. A few key highlights:
  • The "->" syntax just means that what follows will be the definition of a function.
  • Whitespace is significant (get over it).
  • The last statement in a function is the return value, though you can return values earlier by using the return statement.
  • I made two versions of factorial, one with an embedded function defined within the first, and split one that uses a call to a separately defined function.
You can learn more about the CoffeeScript by reading a few good resources:

Testing with Node.js was trivial. I ran "npm install coffee-script -g" then after creating JMath.coffee, ran "coffee -c JMath.coffee", and finally typed "node JMath.js".

The output was:

120
3628800
120
3628800
60
11880
3003
10

Running the coffee -c command generates the following JavaScript code:

// Generated by CoffeeScript 1.3.3
(function() {
  var combinations, factorial, factorialSplit, factorialSplit_iteration, permutations;

  factorial = function(number) {
    var iteration, total;
    total = {
      Value: 1
    };
    iteration = function(number, total) {
      if (number !== 0) {
        total.Value = total.Value * number;
        iteration(number - 1, total);
      }
      return total.Value;
    };
    return iteration(number, total);
  };

  factorialSplit = function(number) {
    var total;
    total = {
      Value: 1
    };
    factorialSplit_iteration(number, total);
    return total.Value;
  };

  factorialSplit_iteration = function(number, total) {
    if (number !== 0) {
      total.Value = total.Value * number;
      factorialSplit_iteration(number - 1, total);
    }
    return total.Value;
  };

  permutations = function(totalNumberOfItems, numberOfItemsToChoose) {
    var divisorBase, divisorTotal, numberOfEvents, total;
    if (!(numberOfItemsToChoose <= totalNumberOfItems)) {
      throw "numberOfItemsToChoose cannot exceed totalNumberOfItems";
    }
    total =  factorial(totalNumberOfItems);
    divisorBase = totalNumberOfItems - numberOfItemsToChoose;
    divisorTotal = factorial(divisorBase);
    return total / divisorTotal;
  };

  combinations = function(totalNumberOfItems, numberOfItemsToChoose) {
    var divisorAdditionalToReduceBy, divisorBase, divisorSubTotal, divisorTotal, numberOfEvents, total;
    if (!(numberOfItemsToChoose <= totalNumberOfItems)) {
      throw "numberOfItemsToChoose cannot exceed totalNumberOfItems";
    }
    total = factorial(totalNumberOfItems);
    divisorBase = totalNumberOfItems - numberOfItemsToChoose;
    divisorSubTotal = factorial(divisorBase);
    divisorAdditionalToReduceBy = factorial(numberOfItemsToChoose);
    divisorTotal = divisorSubTotal * divisorAdditionalToReduceBy;
    return total / divisorTotal;
  };

  console.log(factorial(5));

  console.log(factorial(10));

  console.log(factorialSplit(5));

  console.log(factorialSplit(10));

  console.log(permutations(5, 3));

  console.log(permutations(12, 4));

  console.log(combinations(15, 5));

  console.log(combinations(5, 3));

}).call(this);

F# and Haskell:

I've been working with Joe Koberg at V1, and he's been exploring a lot of functional languages, which has sparked my interest. Here are my first attempts at writing the same functions in F# and in Haskell:

F#:


open System

let rec factorial (n : uint64) =
    if n = 0UL then
        1UL
    else
        n * factorial (n - 1UL)

let permutations totalNumberOfItems numberOfItemstoChoose =
    let total = factorial totalNumberOfItems
    let divisorBase = totalNumberOfItems - numberOfItemstoChoose
    let divisorTotal = factorial divisorBase
    total / divisorTotal

let combinations totalNumberOfItems numberOfItemsToChoose =
    let total = factorial totalNumberOfItems
    let divisorBase = totalNumberOfItems - numberOfItemsToChoose
    let divisorSubTotal = factorial divisorBase
    let divisorAdditionalToReduceBy = factorial numberOfItemsToChoose
    let divisorTotal = (divisorSubTotal * divisorAdditionalToReduceBy)
    let result = total / divisorTotal
    result

printfn "%A" (factorial 5UL)
printfn "%A" (factorial 10UL)

printfn "%A" (permutations 5UL 3UL)
printfn "%A" (permutations 12UL 4UL)

printfn "%A" (combinations 15UL 5UL)
printfn "%A" (combinations 5UL 3UL)

Console.Read()


Haskell


-- n!
factorial number =
if number < 1 then
1
else
number * factorial (number - 1)

factorial2 0 = 1
factorial2 n = n * factorial (n - 1)

-- P(n, r)
permutations totalNumberOfItems itemsToChoose =
(factorial totalNumberOfItems) / (factorial (totalNumberOfItems - itemsToChoose) )

permutations2 n r =
fac_n / fac_n_minus_r
where
fac_n = factorial n
fac_n_minus_r = factorial (n - r)

-- C(n, r)
combinations totalNumberOfItems itemsToChoose =
(factorial totalNumberOfItems) / ((factorial (totalNumberOfItems - itemsToChoose) ) * (factorial itemsToChoose) )

combinations2 n r =
fac_n / ( fac_n_minus_r * fac_r )
where
fac_n = factorial n
fac_n_minus_r = factorial (n - r)
fac_r = factorial r

Now, in the Haskell version there are a couple of versions of each, but it's still less code than any of the others. What I love about this is the minimal number of parentheses, no curly braces, and the where clause that assigns "local definitions" for the permutations2 and combinations2 functions. I'll admit that until I read http://en.wikibooks.org/wiki/Haskell/Variables_and_functions, I was a bit miffed as to how to do this without defining a constant outside the function, which would have made no sense at all for reusability.

Thus, while I like all three of these languages so far, I'm most intrigued by the Haskell program and its economy of syntax.

Learn more about these two languages:





Thursday, August 23, 2012

Working 40 Hours in 3 Days? Possibilities for Making it Work

I've been thinking about different kinds of work schedules. I found this poll interesting:

http://boards.straightdope.com/sdmb/showthread.php?t=608388

Question: If you could choose your own work week hours

Responses:

5 hours, 42 minutes/day, 7 days a week 0 0%
6 hours, 40 minutes/day, 6 days a week 0 0%
8 hours/day, 5 consecutive days a week 10 12.35%
8 hours/day, 5 non-consecutive days a week 2 2.47%
10 hours/day, 4 consecutive days a week 32 39.51%
10 hours/day, 4 non-consecutive days a week 9 11.11%
13 hours, 20 minutes/day, 3 consecutive days a week 13 16.05%
13 hours, 20 minutes/day, 3 non-consecutive days a week 1 1.23%
20 hours/day, 2 consecutive days a week 0 0%
20 hours/day, 2 non-consecutive days a week 0 0%
40 consecutive hours a week 0 0%
40 varyingly distributed hours (i.e. something else) 11 13.58%
I'm retired 3 3.70%

So, is it really possible to do 3 straight days, 13.20 each, and then have 4 days off each week?

Of course, it is possible if you can swing it and really want to.

Some variations:

12:05 - 6:05 AM sleep
7:00 - 1:30 6.5 hours work
1:30 - 2:15 lunch
2:15 - 3:15 nap
3:15 - 6:45 3.5 hours work
6:45 - 8:45 dinner, socialize/family, exercise (whatever you want)
8:45 - 12:05 3 hours, 20 minutes work

Maybe you'd prefer to exercise from 2:15 to 3:15 instead of nap, and do an evening nap later before the last sprint, but whatever.

If you could get by on 6 hours nightly sleep PLUS the nap during the day or evening.

Or maybe you could try two 6:40 segments from 7 to 1:40 and 5:20 to midnight.

Alternative to three day: 3 big days, 1 tiny day

The more I think about it, the more I like the idea, in general, but 13:20 seems to push it a bit too far.

How about:

7:30 - 1:30 work (You can eat some snacks while working to tide you over before lunch; besides, isn't it said you should have small meals throughout the day anyway?)

1:30 - 6:00 free time. Eat, drink, visit friends, family, do errands, and take a nap after an earlyish dinner. Sleep from 5 to 6 to get your second wind ready.

6:00 - 12 work

This ends up at 12 hours. Or maybe you could handle 7:30 to 3:30, followed by 8 - 12. You get the picture.

The Numbers Game

After 3 days, it's 36 hours worked. On Thursday morning, you do 4 hours of review and preparation for the next week's worth of work.

But, the big benefit is now it's noon on Thursday, and you have 3 and a half days completely to yourself, your family and friends, and your own goals.

Lots of small excursions or even just local travels can be done in 3.5 days. 

Suppose you have 3 weeks off and 10 holidays. You probably still end up working something like 1,880 hours a year.

There are 8760 hours in a full year. Subtract 8 a day for sleep. You're still left with 5840.

So, you already have about 3960 to yourself. That's 100 more than twice 1,880!

The Trouble With Today's Work Environments

So, why is it so difficult these days to actually feel like you're not working all the time? Maybe it's because you actually are, in your brain.

It's not always possible to "just turn off" your brain when you're working on difficult, and interesting, problems to solve.

And, when you work in technology, sometimes a "schedule" like 9-5 is a ridiculous thing to even talk about. Creative problem solving work is not the same thing as assembling parts in a factory that have *already been creatively designed by someone else long ago and made into a formulaic process to follow*. It can, and should, be mentally exhausting work to create technological products and services properly.

Poorly designed technologies often result when people are completely burnt out and treated as if they belong in the long out-dated stereotypical factories of the 19th and 20th century.

Work Hard, Recover Harder

A lot of self-styled "rugged" or "progressive" companies adore the phrase "Work Hard, Play Hard", or something like that. Often this works out to something more like:

"We own this company, and you work for us, but we also like to have fun -- at least, the kind of fun that we deem to be fun, and therefore you also should deem to be fun. Therefore, when you are here, you will work hard, and we will inject our form of 'fun' into the day in order for you to see us as a company that also 'plays hard'."

Needless to say, this is misguided.

Daniel Pink's Drive and the Results Only Work Environment

Have you read Drive, by Daniel Pink? If not, have you heard what BestBuy's corporate office did? They turned themselves into what they call a ROWE, a results-only work environment. Here's more about the people who pioneered the concept:


Results-Only Work Environment goes beyond telework. It's a management strategy where employees are evaluated on performance, not presence. In a ROWE, people focus on results and only results – increasing  the  organization's performance while cultivating the right environment for people to manage all the demands in their lives...including work.

Think this is just a gimmick, that BestBuy is a fluke? Think again. How about these companies:


Are they flukes too? Gap, Banana Republic, etc. 

Personal Summation

In the modern age, it's ridiculous to expect creative, skilled knowledge and information workers to want to work the "routines" of the 19th and 20th centuries. Obviously, companies like BestBuy Corporate, GAP, etc have found better ways of working and retaining talented thinkers and leaders.

Working 9 to 5 (or 7 to 5, or whatever) 5 days a week is not a badge of honor. It's often a curse, because many of us do not, cannot, simply be "present" for x number of hours and turn off our brains and attend to "the rest of life". We are goal and results-oriented, and want to create valuable results by working long hours that require intense concentration and attention to details that often get overlooked.

So, in a culture that, at large, has not yet adapted to the mental and creative demands of the 21st century, we must find ways to "put in our 40" creatively, and in a sustainable way.

For me, that definitely means giving a short at "4 10s", or even "3 12s and a 4".

Wish me luck.