Sunday, September 21, 2014

First Look at the Future OR How Seeing the Wolfram Language Reminded Me of Watching ECW

"Arms, and the man I sing, who, forc'd by fate, 
And haughty Juno's unrelenting hate,
Expell'd and exil'd, left the Trojan shore.
Long labors, both by sea and land, he bore,
And in the doubtful war, before he won
The Latian realm, and built the destin'd town;
His banish'd gods restor'd to rites divine,
And settled sure succession in his line,
From whence the race of Alban fathers come,
And the long glories of majestic Rome.
"
-- The Aeneid, Virgil
Translated by John Dryden
Book I, Lines 1-10

"Wow!" that is what I have down as the main take-away in my notes for Strange Loop 2014's session, "Inside the Wolfram Language".  I walked away feeling, as I believe, Hegel felt as he famously saw Napoleon, "I have just seen the world sprit".*



In a time when designers are aiming for yet smaller and smaller frameworks and languages, Stephan Wolfram proudly shows what one can do if they think different.  The Wolfram Language combines language, algorithms, and data into one complete platform (I can assure you I have not nor expect to get anything for these words), giving the user a lot of power in one console.

What would a Hello World look like in such a language?



Yes, that is both code and execution in a tweet!

That is nice and all but how about something more in-depth?

Here is my own "Hello World" Wolfram Language tweet.



I used the build-in text of the Aeneid and computed a histogram on the length of the words used in the english translation.

Histogram[StringLength[ToLowerCase[ExampleData[{"Text","AeneidEnglish"}, "Words"]]]]

Let's break this line down.

First we get the words of the Aeneid in a data structure.

ExampleData[{"Text","AeneidEnglish"}, "Words"]

Next we convert all the words to lower case so we do not have to worry about "The" not matching "the".

ToLowerCase[ExampleData[{"Text","AeneidEnglish"}, "Words"]]

Then we calculate the length of the different words.

StringLength[ToLowerCase[ExampleData[{"Text","AeneidEnglish"}, "Words"]]]

Last, we graph the data as a histogram.

Histogram[StringLength[ToLowerCase[ExampleData[{"Text","AeneidEnglish"}, "Words"]]]]

Deploy.

CloudDeploy[Histogram[StringLength[ToLowerCase[ExampleData[{"Text","AeneidEnglish"}, "Words"]]]]]

https://www.wolframcloud.com/objects/de6c8dd1-d974-491b-91ca-996fc20af4cc

Done.

Not bad for a one-liner.

Just one more thing, if we tweet to the program to @wolframtap it will tweet back the results.




Very nice.


* Actual text from Hegel's correspondence to Niethammer, "I saw the Emperor -this soul of the world- go out from the city to survey his reign; it is a truly wonderful sensation to see such an individual, who, concentrating on one point while seated on a horse, stretches over the world and dominates it." (as quoted here)

Sunday, September 7, 2014

JavaScript Scopes to Functions Not Files

"The cloud-capped towers, the gorgeous palaces,
The solemn temples, the great globe itself,
Yea, all which it inherit, shall dissolve,
And, like this insubstantial pageant faded,
"Shakespeare, The Tempest
Act IV, Scene I, Lines 152-155

While taking this Pluralsight class by Joe Eames I saw a short demo of how in JavaScript variables are scoped to functions and not to files.  I kind-of-all-ready knew this but have not really looked into it.

Here is a quick demo to show what it means to the browser.


See this Plunker if you want to play around with the code.

The browser loads the index.html file which cause it to load and execute a.js, b.js, and c.js.

  • index.html
    • a.js
    • b.js
    • c.js
The browser executes the JavaScript in the following order.
  1. a.js executes adding the variable a to the global name space (which in the browser is window)
  2. b.js executes calling console.log with the variable a
  3. c.js executes adding the function f to the global name space
  4. c.js then executes the function f (this is called an iffe
    1. which adds the variable x to function f's scope
    2. then calls console.log with the variable x
  5. c.js then tries to call console.log with a variable x but there is not an x in the global name space
With the scope looking like the following.
  • window
    • variable a
      • "this is from a.js"
    • function f
      • variable x
        • "scoped to function f"
Looking at the scope it is easy to see why the call to console.log with a in the file b.js works but the call to console.log with x in the c.js outside of the function f fails.

This is nothing new, but with JavaScript taking off in popularity this is something to keep in mind since it is very different than how most programming languages work.

Sunday, August 24, 2014

Functional Programming All the Things OR How to Use Curry to Make Your Test More Readable

"I read in's looks"
-- Shakespeare, Henry VIII
Act I, Scene I, Line 125.2

We, the software craftsmen, understand that tests are a first class citizen.  If the system code was deleted it would be a great opportunity to rewrite the system and know once all the tests pass that the system has all the same functionality.  The question is should tests have the same style as the system code?

Say you have the Coin Changer kata and you want to use a function which takes both the coin value and the amount of change to be given.

If we wrote this in a C-style interface it look something like the following:

int[] changeFor(int[] coins, int amount)

While testing this we have a choice: we can either pass in the coins each time in the test thus violating the DRY principle or we could some how fill in the coins we want to use on each test in a testing series.  The second choice is very interesting since it is screaming for currying the coins per testing series.  Following this idea we have the following for the Coin Changer kata using AngularJS.



We have the following for the system code of the changeFor function.

    $scope.changeFor = function(coins, amount) {
      if (_.isEmpty(coins)) return [];

      return _.reduce(coins, function(m, coin) {
        m.change.push(Math.floor(m.amount / coin));
        m.amount %= coin;
        return m;
      }, {
        amount: amount,
        change: []
      }).change;
    };

We see that lodash's isEmpty makes sure that we have an array of coins before we go to the aggregation using the reduce function.  In the reduce we create an object with the current amount and change calculated so that we do not have to mutate the values passed in to the changeFor function.

We test the cases when we have no coins being passed in with the following code from appSpec.js.

describe('given no coins', function() {
var noCoinsFor;
beforeEach(function() {
noCoinsFor = _.curry($scope.changeFor)([]);
});
it('should return nothing for 0 cents', function() {
expect(noCoinsFor(0)).toEqual([]);
});
it('should return nothing for 99 cents', function() {
expect(noCoinsFor(99)).toEqual([]);
});
});

We set up changeFor function by currying with an empty array for the coins in the beforeEach in the top level describe.  Using curry in the beforeEach we do not have to pass in the empty array on each call in the its.  This makes the test a bit more readable.

Similarly when we test the penny series we can curry the penny.

describe('given pennies', function(){
var penniesFor;
beforeEach(function(){
penniesFor = _.curry($scope.changeFor)([1]);
});
it('should return nothing for 0 cents', function(){
expect(penniesFor(0)).toEqual([0]);
});
it('should return 1 penny for 1 cents', function(){
expect(penniesFor(1)).toEqual([1]);
});
it('should return 2 pennies for 2 cents', function(){
expect(penniesFor(2)).toEqual([2]);
});
});

This makes the grouping in the describe seem more logical and the test more readable.

The same with the nickel and penny.

describe('given nickels and pennies', function(){
var nickelsPenniesFor;
beforeEach(function(){
nickelsPenniesFor = _.curry($scope.changeFor)([5, 1]);
});
it('should return nothing for 0 cents', function(){
expect(nickelsPenniesFor(0)).toEqual([0, 0]);
});
it('should return 1 penny for 1 cents', function(){
expect(nickelsPenniesFor(1)).toEqual([0, 1]);
});
it('should return 1 nickel and 1 penny for 6 cents', function(){
expect(nickelsPenniesFor(6)).toEqual([1, 1]);
});
});

Finally our integration tests for US coins.

describe('given quarters, dimes, nickels, and pennies', function(){
var changeFor;
beforeEach(function(){
changeFor = _.curry($scope.changeFor)([25, 10, 5, 1]);
});
it('should return nothing for 0 cents', function(){
expect(changeFor(0)).toEqual([0, 0, 0, 0]);
});
it('should return 1 penny for 1 cents', function(){
expect(changeFor(1)).toEqual([0, 0, 0, 1]);
});
it('should return 3 quarters, 2 dimes, 0 nickels and 4 pennies for 99 cents', function(){
expect(changeFor(99)).toEqual([3, 2, 0, 4]);
});
});

By using the curry function we have added to the readability of the Jasmine tests.  This style is a bit different than the system code in the AngularJS application.

Check out the plunker which goes with this post.


Thursday, August 14, 2014

Continuous Learning - How to Get Your Knowledge Share On OR Notes from That Conference 2014 Open Space

"And have my learning from some true reports"
-- Shakespeare, Antony and Cleopatra
Act II, Scene II, Line 51

Here is a summary of my experience running an Open Space on Continuous Learning at my third That Conference

Ways to Share Knowledge at an Organization

  • Scheduled reports / presentation which are record 
    It is very important that they are scheduled as a recurrent event so that everyone will feel the need to take part in them.  It is also very important that they are recorded so that they can be used in on-boarding.
  • Tech Talks
    Part of being in IT is knowing about what is happening in technology.  Have your new people and interns talk about what they use to communicate with their friends, I bet they use things you have not even heard of.
  • Project Show and Tell
    Every project big or small has interesting challenges, share your solutions since they will more than likely be face again and again by others.
  • Tech and Try
    Have someone do a quick 5 to 10 minute talk on a topic and then have everyone do what was just talked about.  An example of this would be have someone present on a framework then have everyone do a code kata using that framework, you now have a bunch of people who have at least used that framework a little.

Ways to Learn More on Your Own

  • Code Kata
    Try doing the FizzBuzz kata in a bunch of different ways with a bunch of different frameworks and languages, then compare implementations.
  • Online Classes
    Pluralsight, Egghead.io, Codecademy, ... all have different ways to learn new things, find the one which works best for you.
  • User Groups
    I am a bit bias since I am a co-lead for an User Group, but there is more-likely-than-not a group of people that get together and talk about something you are interested in, join them.  If you cannot find any existing group, start one, all you need is a place to meet and other people.
  • Present at a Conference
    There is no better way to learn something than teaching others.  I know presenting and coding are two very different skill sets, but developing the ability to present and develop software will open all kinds of doors.

Saturday, July 26, 2014

Look Mom I'm FizzBuzzing in Chrome OR Intro to AngularJS

"Like captives bound to a triumphant car."
-- Shakespeare, Henry VI Part I
Act I, Scene I, Line 22

Tell me what you program in and I'll tell you how to FizzBuzz in it.

Not being an "UI guy" but wanting to become a Full Stack Developer the question came up, how do I do Code Katas using a more full stack approach?  How would I do FizzBuzz using AngularJS?

The great thing about AngularJS is that you can simply add it to whatever HTML you currently have meaning you can add it to your html tag, body, or even just a simple div.

Say you have some HTML like the following.


<html> <head> <link href="style.css" rel="stylesheet"></link> </head> <body> <h1> ng-fizzbuzz</h1> <div> <input /> <h1> FIZZBUZZ_RESULT</h1> </div> </body> </html>
You would like have an input box which will display the FizzBuzz value, thus given 3 in the input box will display Fizz and likewise 2 would give 2.  Let's add some simple JavaScript using AngularJS to FizzBuzz this.



Looking at this gist we see the following in the HTML:



We see we have three parts

  • ng-app => which Angular application are we going to use
  • ng-controller => which controller on the application are we going to use
  • ng-model => what data on the controller are we going to use
These parts align with the JavaScript code:


var app = angular.module('fizzbuzzApp', []);
 

names the application


app.controller('FizzBuzzCtrl', ['$scope',
function($scope) {
$scope.translate = function(value) {
var ret = "";
if (!value) return "";
if (value % 3 === 0) ret += "Fizz";
if (value % 5 === 0) ret += "Buzz";
return ret || value;
};
}
]);


defines the function for the controller

We do not see the value defined in the ng-model anywhere in the JavaScript code, so what gives?

{{translate(value)}}

calls the translate on the controller giving it the value of value bound in the ng-model on the input tag

This is one of the easier ways to do FizzBuzz with AngularJS.

This code is on Plunker: http://plnkr.co/edit/HMxS8H?p=info

Enjoy.