Categories
Technology

Learn By Do. Part II

In the first installment, we discovered, from the eyes of a noob, a handful of basic concepts about the Ruby language. In this episode, we’ll complete the functions for mean, median, variance and hence standard deviation and discover something you might consider magic…

The mean. It’s the average and so it’s calculation is simple. Add up all the elements and divide by the number of elements. The sum:

    @sum = 0.0
    @elements.each{ |i| @sum += i }

The mean:

  def mean
    if 0 == @elements.length
      return 0
    end
    return @sum / @elements.length
  end

Straightforward and fairly clean. The median is also pretty straightforward; you want the middle element, in the case of an odd-numbered quantity and the average of the middle elements in the case of an even-numbered quantity.

  def median
    if 0 == @elements.length
      return 0
    end
    if 0 == (@elements.length % 2)
      return even_median
    else
      return odd_median
    end
  end

I used the modulus operator to determine if the quantity of elements is odd or even, and it’s pretty much the same as almost every other language i’ve used. There is another way, using the remainder method:
any_even_number.remainder(2) is equal to 0
any_odd_number.remainder(2) is equal to 1
The even/odd_median methods just return the appropriate middle element. First the odd_median:

  def odd_median
    return @elements[(@elements.length/2).floor]
  end

It might seem a little odd, at first, to not use the calculation (n+1)/2:

return @elements[(@elements.length + 1 )/2]

The reason we use the floor is because we know the number of elements divided by 2 will always yield a n.5 and we take the index down form that because we’re using a ZERO-based index in the array. (n+1)/2 works perfectly for a ONE-based index array. We could still use that approach however, but keeping in mind to subtract 1 from the result to get the correct index: ((n+1)/2) -1.

  def even_median
    top = @elements.length/2;
    bottom = top -1
    agg = @elements[bottom] + @elements[top]
    return agg / 2.0
  end

Again, because we’re working with ZERO-based index arrays, the calculations are slightly different to what you’d expect or do in “normal mathematics” (if there can ever be such a term?). Easy, peasy, japaneasy, right?

Variance is a slightly more complicated, although, not complex by any stretch of the imagination. There are two different algorithms for calculating the variance and in the provided code, i have implemented both. Armed with the knowledge of the equations and a decent grip on how to perform some calculations, the implementation is left to you as an exercise in applying your learning.

The magic. At last, the magic. (from Ruby-coloured glasses)

class Float
  def prec(x)
    mult = 10 ** x
    return (self * mult).truncate.to_f / mult
  end
end

The almost crazy thing happening here is that you have the ability to extend built-in types without much fuss. With this definition, you now have the prec method available to all your Floats. Try it in your console too.

irb(main):006:0> class Fixnum
irb(main):007:1> def plus10
irb(main):008:2> return self + 10
irb(main):009:2> end
irb(main):010:1> end
=> nil
irb(main):011:0> 43.plus10
=> 53

Now that’s cool. Strings, Times, Fixnums, Floats… If your domain requires a specific handling on a particular type; the ability to extend and make that appear “normal” for the remainder of the coding experience is easy. It just slides right in.

And that about wraps up Part II, save one small little detail you’ll find in the code but not elaborated just yet: the accessor. The Ruby User’s Guide has a great explanation, and now you also know about that website too!

The full source code for Learn By Do is available for download: sample_data.rb

Categories
Rants Technology

World’s Most Annoying Dialog

No matter how many times you say “later” it just keeps on asking the same question.. over and over and over…

most_annoying_dialog.png

Categories
Technology

Learn By Do. Part I

If you want to learn to code, the best way is to code… lots. No getting around it, and for me, my fingers seem to remember more than my brain. So keeping that in mind, here begins a short series of code snippets and samples which i’ve used to help myself learn the Ruby language. Hopefully, this helps you out a little as well as you start exploring the language for yourself. Of course, a lot of the information is also gleaned from around the web. I’ll endeavour to give credit where it’s due, if i forget or leave anyone out, it’s not intentional. Please feel free to prompt me a kind “ahem”. And also, i ain’t no matter expert, so if you spot an inefficiency somewhere, i’d appreciate a little pointer too. Thank you.

So, the key things that i want to learn are:
* language syntax
* keeping with lessons learned in oop
* how to write/test logic

And then of course, i also want to write something relatively “useful”. Not some imaginary and contrived Product-Catalogue relationship or Animal, Dog, Cat hierarchy, thank you very much.

That’s it, really. So essentially i want to capitalize on the two main languages i’ve spent a lot time in and what they taught me: C++ => OO principles, and then C++/C# => TDD. Armed with the basics, i, and by extension that is, you too, can pretty much tackle just about any problem within my (your) comprehension.

So the first challenge is writing a class that can handle finding the mean, median, variance and standard deviation for an array of numbers (integers or floats). Fits all my criteria and will certainly help me determine and check answers while i study through my courses at uni. That is to say, it’s very useful for me. So, with further ado…

TDD

require ‘test/unit’ at the top of your file and inherit from Test::Unit::TestCase.
If you’re familiar with TDD in general and been exposed to xUnit frameworks, that’s about all you need to know, the rest is straightforward.
So i want to test my new class SampleData which is initialized with an array of numbers and sports three basic methods: mean, median and variance (for now). The first thing i did was create TestSampleData

class TestSampleData < Test::Unit::TestCaseend

First task; make sure you can’t declare SampleData.new without passing in an array of numbers; that is, i want to force usage to always supply an array of numbers when you construct it. Hey, it’s my design so i get to choose the why.

class SampleData
private
  def initialize()
  end
public
  def initialize(elements)
  end
end

Almost like C++, the public and private sections of the class definition are straightforward. Nothing tricky there. Now i’m forced to, at minimum declare instances with a parameter: SampleData.new([]). It’s what i wanted.

Next concern was making sure the parameter passed in is what i expect it to be (defensive programming). Make sure it’s an array of either Fixnum or Float. If it’s not, i want the constructor to raise an exception.
The exception is the easy bit:

raise ArgumentError.new("message")

. Checking the type of the parameter is also easy with the class method.

  def initialize(elements)
    if Array != elements.class
      raise ArgumentError.new("Can only initialize sample data with an array of floating points or integers")
    end
  end

And then checking the type of each element in the array also turns out to be pretty straightforward

    elements.each do |e|
      if (!(Fixnum == e.class) || (Float == e.class))
        raise ArgumentError.new("Array can only contain floating points or integers: item " + e.to_s + " is a " + e.class.to_s)
      end
    end

Of course, all this is verified with a bunch of tests declared by the test case:

  def test_must_init_with_array
    assert_raise(ArgumentError) { SampleData.new("string") }
  end
  def test_must_init_with_array_of_numbers
    assert_raise(ArgumentError) { SampleData.new(['ll', 'llkj']) }
    assert_raise(ArgumentError) { SampleData.new([0, 8, 'll', 9, 7, 'llkj']) }
  end

The code reads for itself. All i need to do to verify is, from the commandline, run ruby filename.rb.

bryan@noah:~/src/sandbox/ruby/medians$ ruby sample_data.rb
Loaded suite sample_data
Started
......
Finished in 0.002402 seconds.

6 tests, 16 assertions, 0 failures, 0 errors

That’ll do it for Part I. Key things learned:
* public, private sections of a class definition and the syntax thereof
* writing a test case
* raising exceptions, and testing for expected exceptions
* checking types and forcing class usage
* a little tight looping and boolean logic

So far so good, and really nothing too different or difficult to grasp coming from either C++/C#. Part II to follow shortly…

Categories
Technology

SharpDevelop + Monorail

Monorail rocks, but getting going in #Develop can be cumbersome in that you need to create a lot of placeholders. Fortunately, you can create a template which you can drop into your data/templates/project/CSharp sub-path of your #develop installation
for example: C:\Program Files\SharpDevelop\2.2\data\templates\project\CSharp
Using this template, you can now

Create a “MonoRails” web project

create.png

Have it create all the skeletal placeholders

created.png

Build (change relevant config settings) and view when hosting it locally

running.png

This template in it’s current form references the Castle binaries from the install directory. You might want to change that bit of detail if your installation is not “standard” (ie. next > agree > all > next > finish).

Download Template

Categories
Technology

Subversion and Bzr

Subversion has been a friend of mine for some time now. Given the order of environments I have been required to work in, it’s more than suited our needs… anyhooo. Then there’s Bzr which has really grown on me, especially for offline version control. But what is really cool, is using both of them. I probably could set up a bzr server, but the subversion repository is already in place… incremental adoption always works smoother.

How easy is it? Just run bzr branch <svn:uri> and you’re set. Easy. Then you can run multiple ‘bzr commit’ commands to keep a local versioned control record of code changes, and when you’re within connectivity with the subversion repository, just ‘bzr push’ and Robert is your father’s brother. ‘Bzr update’ will check out changes from the repository.

For straightforward environments, this should suit you just fine with minimal fuss for a lot of satisfaction.

Categories
Technology

Will it Scale?

When Ruby/Rails is mentioned as a web development platform, the most common response is related to scalability and performance; usually with a liberal dash of skepticism. Fear, uncertainty and doubt, along with a couple of honest posts and reviews, all point to the perception that Rails has some sort of performance problem.

300 million page views per month anyone?

Good to hear about the success stories, no matter the tech, but particularly heartening to see the RoR tech maturing into something more than just a “toy”.

Categories
Life

Lords of the Acronymn (or LOTA)

While i was having my foot scratched and scraped clean by the on-duty doctor at the hospital, a colleague of his walks by and a quick “hallway discussion” ensues. What i overheard could have easily been mistaken for a geek conversation. More TLAs, FLAs and AIGs bubbled along than i could follow.

We geeks have nothing on doctors and surgeons. We’re just poser wannabes 😉

Categories
Technology

Open Source on Launchpad

A synergistic moment if there ever was one.

I love my OS. I don’t dislike my XP. It’s been good to me (and continues to be) but i *really* enjoy working on my ubuntu. And i’m still discovering things about it, which is half the fun right there. And as a result, i was introduced to launchpad.

And i really enjoy working on launchpad. I don’t dislike sourceforge. It’s been good to (and continues to be) but i *really* enjoy working on launchpad. And i’m still discovering things about it, which is half the fun right there. (Codeplex hasn’t really shaken my boots much in any form or manner yet).

I love programming. I don’t dislike .NET. It’s been good to (and continues to be) but i *really* enjoy working with Ruby, and in particular, with Rails. And i’m still discovering things about it, which is half the fun right there. And in all my discovery and learning, it was about time to bring the 3 together, in a practical way which helps me be more productive, first and foremost in keeping a tab on my new adventure as an entrepreneur.

Introducing… timesheet. Nothing new, nothing too fancy. It’s Rails, developed on ubuntu, using *nix editors and IDEs where i could scour them, and hosted on launchpad. It works, it’s functional (and i can even port it sans changes to my XP environment) and readily available. Probably has enough bugs (certainly more roadmap expected) to keep me busy exploring features in launchpad, but at least it looks marginally better than my excel spreadsheet (lol)

timesheet.png

Categories
Business Technology

IT vs Business

Who’s gonna win?

Judging from the insights that are developing, not only within myself, but also from more prominent journalism, i would say business will eventually catch onto how IT’s supposed to be managed and augmented into adding value to the core focus of the business. Obviously, IT-centric business will be oh so slightly different. But the point is, if you’re a developer (as an example), you should be thinking of how to join the company, not the development team. Your approach and your skill-set should be centered on supporting the core business and not just how good you are at coding. This is a marked difference, and while some have been getting it right, it won’t take long before everyone is forced to get it right. Again, IT-centric (or technologically oriented) organisations will have their subtle differences.

What does that mean in the short term? Don’t think of business as ‘them’. It’s ‘us’. And there’s also no ‘us’ when it comes to the dev team. The ‘us’ is the company.

How do you identify with the change? Well, think of the any other division within your organisation. Accounts, procurement, call-center; any of them, all of them, see themselves as the business or aiding the business directly. They don’t have this distinction (by and large) of ‘there’s us’ and then ‘there’s the business’. It’s the same thing.

Getting this mindshift entrenched as part and parcel of IT as being within the company and not external to the company will certainly be a much needed move forward. The technological advances (again, programming wise) are not that radical; the improvements do need to come from another aspect, and this change looks to be it.

Categories
Business Rants Technology

IT “Industry”

I say “industry” but there’s no real regulation put in by the government (at least here) which keeps the industry in check. For one, it’s not illegal to provide IT services or build software without a licence, while in more established industries, it is illegal to, for example, provide medical, financial, engineering or manufacturing services (where people’s lives are at risk) without a licence. Anyway, that’s not a formal classification or rule, just an idea that appeals to me. Why the necessity to make the distinction?

Over the last decade of building software, i’ve seen a fair share of hair-brained ideas. I’ve also seen some brilliant ones. What i haven’t seen much of though, is brilliant management. I’ve seen some, but these generally come from the business-oriented bunch who just happen to end up in IT; very rarely from tech-savvy management trying to keep a business going. In fact, most of the time, tech-savvy management who try to run their business without business-focused partners end up either working way too much overtime (work = life =work) or going belly up. Somehow, there exists this hype perpetuated by punctuated newsworthy stories of geeks-in-a-garage-cashing-in. So if they can do it, why can’t we? ‘Cos not every story turns out that way.

And particularly software. Manufacturing, distribution or sales, whether it’s IT or food, is the same thing, mostly. That is, the science and art of management has been established and the discipline is well understood. Software, on the other hand, doesn’t fit the mould. Yes, it’s plain manufacturing, distributing and selling, but therein lies the rub. You approach it with business fundamentals, and it works, but if you don’t adapt some of those implementations; you get left behind- and quickly. You toss out the fundamentals in order to keep up; you get dropped behind- even quicker.

As an example, my last company just liquidated. There are lots of different stories as to why, how, when, where or who. Bottom line, no more business. I can only comment on the software aspect; not the rest of the operation. So the only thing i do know is that it was very tricky getting the software strategy just right. Everyone pushed and pulled and chewed on this one all the time trying to get it to work. Maybe, with a little more time, it could have worked out ok in the end? Next time 🙂

More evidence supporting the notion that “software is hard”. And it makes me wonder how different things would be if you had to be officially licenced/qualified, by law, to operate in providing a software writing service. Not a fly-by-night programming course. Not a dummy’s guide to programming. Something professionally trustworthy and legally accountable. I wonder just how far would that go towards stabilising the “industry”? Make it more reputable and have governing bodies presiding over fair exchange between vendors and clients; also ultimately curbing the number of software businesses that just don’t make it.

Neh. Where would we be without the hype? It’s part of the magic of this little world 😉