Wednesday, April 25, 2012

Div and CSS formatting

This is a topic that has proven a pain in the ass for just about every web developer I've ever known.  How the hell do the various display options for divs truly work.

Googling this today, I found a page that has both good explanations, and also a demo at the bottom that you can mess around with to figure it out through experimentation.  Perfect:


Tuesday, April 24, 2012

On recursion - a bit more

I have to say that the more I use recursion to solve simple problems the more it makes sense and the easier it becomes.  The simple things in life are often where I find joy, and today's joy comes from perhaps a very silly but necessary piece of code.  When you entity encode UTF-8 in HTML entities, you and up with strings that have thinks like Ӓ in them.  This entity represents a single character for the purpose of considering string "length".  All the standard String functions return length not understanding that the content of the string is encoded.  Decoding it could lead to nasty unintended vulnerabilities, so I have created a function that copes with these functions.  In a previous life (or about a year ago), I would have solved this with what I would now consider a kind of ugly for loop.  Today, I prefer to solve more functionally:


 String.prototype.lengthDecoded = function(){
  return (this.length==0 ? 0 : 
     1 + (this.substring(0,1)=="&" ? this.substring(this.indexOf(";")+1).lengthDecoded() : this.substring(1).lengthDecoded()));
 }

I'm not convinced I have the best name yet, but in terms of brevity and clarity I think this is a massive improvement over a for loop which will always be in danger of off-by-one errors and simple verbosity.

Here we have what amounts to a single line of code, formatted for clarity that "eats" a string calculating its length as it goes.  Simple recursive solutions I'm finding are easier and clearer than their declarative counter-parts.  Other than the fact that I'm sitting here writing a blog post about it!

I have considered the idea of creating a subclass of string to do this too, but I'm not convinced the extra complexity that it would bring, and potential to simply not get the correct type in the right place versus using a different function would be better.  I could easily make an argument for either.

Thursday, March 29, 2012

Play and Heroku

I've been messing around with Play, and decided that I'd push it up to Heroku based on the tutorial and things I've heard about Heroku.

I'm going to expand on this later but, if you forget the Procfile when deploying your Play application, it may cause your app to get totally jammed and never be able to start.  I spent the next hour or two trying to figure out why my app wouldn't start, even after I'd put the Procfile in.

I solved the problem by deleting my app on Heroku and creating a new one.  Then it started fine.

The docs on pushing a Play 2.0 app to Heroku all disagree with one another too, so I hope I can find a few to post a tutorial based on how I got it working!

Saturday, March 24, 2012

First day with Play

I started looking at play 2.0 for the first time today.  I got a few hours with it at least, and I've been impressed with a few things.

The first and biggest thing is perhaps the most simple: compile on the fly.  Grails does this, but very badly, and if I'm observing right, I think I can see why.  It seems that Play compile checks at request time, not at file save time.  As one who grew up computing, Ctrl-S or it's equivalent has become a nervous tick.  Grails recompiling at save time almost always just ends up trashing the environment as I save about ten times a minute, and I end up having to restart it, which is very slow.

With FSC, Play compiles changes very quickly and I barely notice a lag at all.  It doesn't get stuck anywhere I've noticed yet either like Grails can.

I feel like within a couple of hours, I got pretty far into having a functional, albeit basic web app going.  Working with Anorm is interesting too, I'm not sure if I like how they've done it yet, but after years living with JPA and Hibernate's arcane query structures and unexpected query stupidity (although there was always a good reason, it was still annoying), I find this way of integrating SQL and code better than most.  It has some similarity with O/R Broker which is what I've been using with Jersey so far, but Anorm is more sophisticated and I think easier to work with.

The error reporting in Play is also excellent.  You can see quickly and precisely what went wrong with your code, there's no guesswork and decrypting enigmatic error messages, it just tells you with your source code right there: this is where it's broken!

Friday, March 23, 2012

Scripting in Scala


Today was the first time I've felt comfortable using Scala to write a true script.  Something simple like taking an HTML file, and extracting certain anchor tags which can occur multiple times per line is surprisingly annoying to do in many scripting languages like python or perl.  You often end up with a regex from hell, and I'm not really one for regexes from hell and the declarative style ends up taking far more code that it really should.  You can do this in Perl in a sort of quick way, but it looks pretty damn ugly, and besides, it's 2012, surely we have something that can do this almost as well or better than Perl!

So, with no further ado, I give you my very simple script:


import io._
import java.io.File

println(Source.fromFile(new File(args(0))).getLines.filter(_.contains("http://www.foo.org/")).flatMap {x=>x.split("<")}.map {x=>
  (x.indexOf("href=")>0 match {
    case true => x.substring(x.indexOf("href=")).dropWhile("'\"".contains(_)).takeWhile(_!='>')
    case false => ""
})}.filter(x=>{x!="" && x.endsWith(".html\"")}).map {x=>x.dropWhile(_!='"').drop(1).takeWhile(_!='"')}.reduce(_+"\n"+_))

Is this the best way, the easiest or the most elegant, no. It's a script that I needed to write in ten minutes or less.  Almost a throw-away piece of code.

The big thing for me was that I've finally become familiar enough with Scala syntax that I could achieve this is less than ten minutes.  No wandering off to stack overflow to looks something up, or struggling with one of the erasures for the list comprehensions; I could just sit here and type and make it work with minimal debugging fuss.

When I think about the pure horror of trying to do this in Java, I shudder.  If I removed most of the newlines and the imports, this could exists on just two lines (I'm not sure if I can terminate a case clause with a semi-colon or not).  It is probably possible to write this as an immediate script right on the command line, and still be able to read it (well, mostly).

Today is a good day.

Thursday, March 22, 2012

Update on anonymous functions

I am an idiot.  I left out perhaps one of the most fun things about anonymous functions: return data.

I'm still getting used to working in a functional way of thinking, but this is perhaps one of the most fun ways to use an anonymous function.  It might be a little be evil, I'm not sure yet, but it's certainly interesting.  take a simple string concatenation:
function getThingie(x) {
  var a = "I would like to buy";
  var b = "for a good price.";
  var c = "nothing";

  if (x == 1) {
    c = "a dog";
  }
  else if (x == 2) {
    c = "a cat";
  }
  else if (x == 3) {
    c = "a bath";
  }

  return a + " " + c + " " + b;
}

If we replace this with an anonymous function it can then look like this:
function getThingie(whatThing) {
  return "I would like to buy " + (function(x) {
    if (x == 1) {
      return "a dog";
    }
    else if (x == 2) {
      return "a cat";
    }
    else if (x == 3) {
      return "a bath";
    }
    else {
      return "nothing";
    }
  })(whatThing) + " for a good price.";
}

I'm not 100% sure which is 'better', but for my money, I find the flow of having the conditional inline as a function more clear. If this were a language like Scala, we could have a match clause here, or a partially applied chain. Ultimately, it puts shit where it goes, and that's my number one rule of programming.  In this case, it means you don't have an assignment somewhere that has a chain of logic that is basically out-of-line of the program flow.  When we read a sentence, we scan along the sentence and piece together information in our head in the order we read it, whether that's left to right or right to left, it's just easier to digest if we don't have to skip around to figure out what is going on in a story, or, in a piece of code.  So, in that way, I think this obeys "put shit where it goes" pretty well.
To give an example, here's one way it might look in Scala:

def getThingie(whatThing) = {
  "I would like to buy " + (x match {
    case 1 => "a dog"
    case 2 => "a cat"
    case 3 => "a bath"
    case _ => "nothing"
  ) + " for a good price"
}

Arguably this would be an interesting case to use a partially applied function:

def mapMeMyPurhcaseItem : PartialFunction[Int, String] = { 
  case 1 => "a dog"
  case 2 => "a cat"
  case 3 => "a bath"
}

def getThingie(whatThing) = {
  return "I would like to buy " + 
    (mapMeMyPurchaseItem(x) getOrElse "nothing") + 
    " for a good price.";
}

Why would you want to do this?  It could be argued that this obeys the "put shit where it goes" rule even better.  The function only returns if the arguments is within the domain of the function, otherwise you must provide an alternative.   It means the fall-through clause is explicit and local so the fall through case isn't hidden inside a function.  Partially applied function are extremely powerful constructs I'm beginning to learn, and I think I'm going to find them to be a good friend in building extremely robust programs, but that's a story for another time!

Tuesday, March 6, 2012

Programmers, guns and analogies

An analogy I've heard bandied around over the years, not just by the Ruby folks, is the programmers and guns analogy.  Give people freedom and they won't destroy the world, they'll be happy.  Give a bunch of programmers the proverbial AK47 and they'll not start shooting each other.

For all the ways this is a bad analogy, and a bad model, none is worse than the fact that it's basis it completely flawed.

Bad code is not something you have to pull the trigger on, it's the default.  It's like bad art, or bad bricklaying.  When you don't know any different, you make bad art, lay crooked bricks and write crappy code.  People don't get born into a state of understanding and skill.  To extend this analogy thing, the gun is already firing, and you have to work to dodge it.  Giving programmers the proverbial gun isn't giving them a tool.  It's like a gun that once you've pulled the trigger, it won't stop firing, you just better hope you figure out how to aim it so it doesn't hit anyone else.  Friendly fire in a war zone is a leading cause of death.  Only extreme training will reduce it, and it's rarely eliminated.

Of course, it's coding so there aren't lives at risk right?  Well, unless you're writing the software that flies a 747 through the sky, or a system that measured medication for the pilot who's flying the 747, or perhaps the code that set his smartphone alarm off two hours early and now he's low on sleep when the emergency happens.  It might feel like an edge case, until you consider all the possible ways the human part of that system, or it's dependent systems, like the flight crew, the ground staff, the air traffic controllers might have been affected by a simple code bug which could end up being just as serious as a malfunction in the guidance system of a 747.

Hyperbole?  A little, but also, not entirely.