Thursday, September 9, 2010

Tumblr

Moved to tumblr: http://urlencode.tumblr.com/

Friday, August 20, 2010

Restoring Browser Functions to Clickable DIVs Without Javascript

Occasionally the situation comes up in web development where you have a highly styled tag such as
<div> or <li> that you want to make clickable.  This often happens when you have a list of items in which you want to make the entire item clickble instead of just the title for example.  The standard fare for doing so is to set { cursor: pointer; } with CSS then to bind the .click event to the tag (in jQuery as so)....

$('#myDivTag').click(function() {
    // your code here
});

Don't get me wrong -- this does work.  However, in doing this what you loose is the standard functionality that most viewers are used to; things like middle clicking to open in a new tab, right-click to copy URL address, and so on.  There is also the lag between when the page renders visibly to the user but the javascript hasn't downloaded and $(document).ready hasn't yet fired.  In this case the tag will not be clickable but the mouse cursor will indicate that it should be.

I've been dealing with this more so lately and there are a couple of ways to solve this problem.

The first is to wrap the <div> (or li or whatever else) tag in an anchor tag <a> and set that anchor tag to { display: block; }.

<style type="text/css">
   #myDivWrapper { display: block; }
   #myDiv {  }
</style>

<a id="myDivWrapper">
    <div id="myDiv">
       ... content ...
    </div>
</a>

By wrapping the div tag in an anchor you've restored the default functionality viewers are used to with a clickable item.  This works in most browsers but for the most part things like <div> and <li> are not allowed inside of an anchor tag per HTML language specifications.  In a sense in doing something like this you are rolling the dice that the next version of IE9 strict mode won't render when it hits this.

It also feels kind of  weird, because all of the styling that was on #myDiv, things like height, width, float, etc., now need to be applied to the anchor tag instead.  And no one likes wrappers. They just clutter things up.

The 2nd way to solve this problem which I've started using lately is to have an absolutely positioned anchor overlay the area of the div.  Consider the following...

<style type="text/css">
    #myDiv { position: relative; }
    a.clickable-overlay {
        position: absolute;
        top: 0;
        left: 0;
        height: 100%;
        width: 100%;
        z-index: 1;
        display: block;
        background-color: transparent;
    }
</style>

<div id="myDiv">
    ... content ...
    <a class="clickable-overlay" href="#wherever"></a>
</div>

Here's what's happening:  At the end of the <div> (or li or whatever) we're adding an anchor tag.  The parent div is set to { position: relative }, and the anchor tag to { position: absolute; }.  If you're not familiar with position absolute you're missing out.  The way it is designed to work is that any element positioned absolutely is done so in relation to it's parent (or any parent's parent) that is positioned either relatively or absolutely.  What this means is that in setting our <div> tag to position: relative the anchor tag with position absolute will be positioned relative to the div.  Top 0 and left 0 will be the top left of the div,  and height 100%, width 100% will cause the anchor to fill out the area of the div.

The result is that we are left with a transparent anchor tag that completely overlays the area of the div, providing the default clickable behavior users expect.  The last CSS trick to making this work is to set z-index to 1, forcing the browser to always render the anchor tag over whatever content is in the div.

The positives to this method are that 1. we restore the expected clickable behavior without javascript (meaning it also works as soon as that markup is rendered and not when $(document).ready is fired) and 2. we're using correct HTML syntax.

I should point out there is a downside to this method, in that because the anchor overlays the div, the contents of the div are no longer selectable or clickable.  Depending on your application this may be negligible.

Thursday, August 12, 2010

Top 10 Programming T-Shirts That Don't Make Sense

mind.location = unknown
http://www.zazzle.com/javascript_mind_tshirt-235892961444457742
I wonder what the value of the variable unknown is?

import_soul
http://www.zazzle.com/import_soul_tshirt-235715645595867505

What is import_soul?  It's written as a keyword.  If it were a function it should be import_soul(), however the keywords for this shirt include "python" which makes me thinking they meant import soul.

Function Check_Drunk()
Where do I begin with this one... drink is treated as a global variable but never declared globally.  Then there's the awesome conditional if "bra = true" which will always return true because a single = is assignment not evaluation.  Lastly, none of the functions are ever called, they're just declarations of.

Programmers Cool Club
No comment needed.

.ninja { color: black; }
This one's amusing and almost worth getting, but the behavior of visibility: hidden; is such that it keeps screen space allocated for the element and simply does not render it.  I personally believe a true ninja would { display: none; }.

Geek Power
No geek would ever intentionally rip the cord to their keyboard like that

Computers are Only Human
Apparently I didn't get that memo.

SELECT TOP 25
Aside from using the vendor-specific "TOP 25" (MS SQL), the comment at the bottom brings to light the poor execution of this SQL:  It should be sorted DESCENDING

Do You Speak Code

There's No Crying in Programming

Friday, August 6, 2010

Python Templating For the Web (Random Ideas)

Well it's past midnight and I'm musing about web templating in Python for Tornado or AppEngine.   The thing about most Python templating engines that I notice is...

  • There's kind of an obsession with being agnostic about everything.  You can render JSON and XML and whatever else you want with our engine!  When is someone just going to make a really awesome templating engine for the web and not try to be everything to everyone?
  • The value in a template engine to me is how easy it is to allow the template to include logic that's independent of the controller that's generating it.  For example, you might want a server-side ad manager on every page, but you don't necessarily want to put the code for that in every controller.  Solution?  Some engines call it modules, some call it template tags, but whatever the name there is some type of logic that's independent of the controller.  The problem is that most of these pieces of independent logic are needlessly complicated.  (side note: Django has gotten a bit better about this since I first used it two years ago).
  • Maybe some better support for lazy-loaded values which are available for all templates... things like static URL, etc.
So it's late and I'm thinking, what if there was a template engine, and I mean one specifically for the web, which represented an HTML document more so as a Python class.  Every root element or element with an ID is a property of the document.  Tags can interact with each other... Maybe this is turning out to be too much of a DOM implementation in Python.  Maybe this is a bad idea.  Or maybe I should try coding up a prototype just to see what it's like.

But it's not quite a DOM.  The DOM is concerned with specific structure, where as we're only concerned with a loose abstract structure.  It doesn't matter of the area where scripts are printed too is in the or right above , what's important is that there is a scripts area which sub-modules can access.

Instead of {% extends "some_html_file.html %}, it could be {% extends templates.master %} where templates.master is a python module.


(15 minutes later)... you know it kind of sounds like I'm trying to re-invent ASP.NET WebForms...

Tuesday, July 27, 2010

Komodo Edit

I like Komodo Edit. It's simple but at the same time functional enough to be useful. It also does code completion, supports Python, and is cross-platform. (Side note: If only it supported Scala, then it would be like the **aaaaahhh** perfect editor).

I've had this idea kicking around for a while of starting a Komodo color themes/schemes website. The idea is simple. You create a theme, then share it on the site. Other people can download it or Vote/"Like" it. Most-liked themes bubble to the top. I'm thinking of a simple architecture using Google App Engine (python) + Tornado. We'll see.

In the mean time I sure did waste like 2 hours of what should have been productive programming time putting together a bunch of themes for Komodo Edit. Here are some previews of them...


"Heart Dry"


"Fancy Terminal"

 "Happy Day" (currently used)


 "Monokai"


"Phoenix"


"Transformers"


"Work Scheme"

Friday, June 4, 2010

Formatting Console Output in Scala

So it's midnight and I'm programming Scala (heh).  I'm actually starting to be able to write little scripts in Scala.  Here's a quick one that I put together, inspired by Chapter 3 of "Programming Scala" which reads a source code file and formats the file to the screen with line numbers.



I tried to be as functional as possible.  The "formatSourceLine" I felt was getting close to the concept, using recursion, immutable values, and always returning a value (avoiding the side effect of printing from within the function).

The actual output from this script is:

D:\Development\Scala>scala file.scala file.scala

    1 | import scala.io.Source
    2 |
    3 | if (args.length > 0) {
    4 |
    5 |     def formatSourcePrefix(line: Int, suffix: String, max: Int = 5):
    6 |         var prefix: String = ""
    7 |         for (i <- 1 to (max - line.toString.length))
    8 |             prefix += " "
    9 |         prefix + line.toString + suffix
   10 |     }
   11 |
   12 |     def formatSourceLine(lines: List[String], line: Int = 1, 
   13 |         val out = output + formatSourcePrefix(line, " | ")
   14 |         if (lines.length > 1)
   15 |             formatSourceLine(lines.tail, line + 1, out)
   16 |         else
   17 |             out
   18 |     }
   19 |
   20 |     // Read file from disk
   21 |     val lines = Source.fromPath(args(0)).getLines().toList
   22 |
   23 |     // Print results to screen
   24 |     println
   25 |     print(formatSourceLine(lines))
   26 |
   27 | }
   28 | else {
   29 |     // Print out proper syntax
   30 |     Console.err.println
   31 |     Console.err.println("scala file.scala [filename]")
   32 | }

Saturday, May 29, 2010

The Difference a Space Can Make

How can you print the string value of a floating point value of 5 in Scala?

scala> 5.toString  // Wrong!
res16: java.lang.String = 5

scala> 5. toString
res17: java.lang.String = 5.0

In the first line scala counts the "." as syntax for "toString method of Integer 5".  The second line uses the "toString" method in infix notation, applying the toString method against the floating point value of 5.0.

Here's another example where a space can make a big difference in type:

scala> 4.+(1)
res20: Double = 5.0

scala> 4 .+(1)
res21: Int = 5

Abstract Types in Scala

Whenever I learn new programming languages, there is invariably features of the language that will surprise me.  One of those in Scala (one of many actually) is abstract types.  When I first read the textual description of an abstract type, I wondered what use it would ever entail.  However, the authors of Programming Scala gave a very clear example of proper use.

This code snippet comes from Chapter 2 of the book.

Starting with an abstract class, we can declare an abstract type.  In this case, type "In" on our class "BulkReader" is abstract.  It's there, but it does not have a concrete type associated with it.  Yet, our value "Source" is typed as type "In".  How can this be?

abstract class BulkReader {
  type In
  val source: In
  def read: String
}
The magic comes when we declare a concrete version of "BulkReader" and can assign a concrete type to "In":

class StringBulkReader(val source: String) extends BulkReader {
  type In = String
  def read = source
}

class FileBulkReader(val source: File) extends BulkReader {
  type In = File
  def read = {
    val in = new BufferedInputStream(new FileInputStream(source))
    val numBytes = in.available()
    val bytes = new Array[Byte](numBytes)
    in.read(bytes, 0, numBytes)
    new String(bytes)
  }
}
Very cool!  In our two concrete instances of "BulkReader" we assigned two different types to our abstract type "In".  Note that the value typed as In, "source" is actually part of the concrete class's constructor which is, at this point for me, completely mind bending in terms of flexibility towards class design.

I have a feeling it will take me some time to get used to this notion and power before I really start to design code that makes use of it.

Wednesday, May 26, 2010

Language of the Summer: Scala?

I've been quite fascinated with Haskell as a language.  It's purely functional, ridiculously strict typing, and algebraic syntax were completely foreign to me before I began learning about it.  I wouldn't say that I learned Haskell, but I did learn about it.  I learned enough to know that it's a bit over my head at this point and that I need a better theoretical foundation before I attempt to tackle it again.

So in the mean time I wanted to take on something more transitional.  I had considered F#.  It seems like a great choice, especially since I already know C# and am familiar with the .NET platform.  But it's a Microsoft language and I was hoping for something more portable (actually, I'm harboring a secret desire to use a functional programming language to one day code for Lego Mindstorms NXT with).

I happened to stumble upon Lift again yesterday.  I had heard about it before when I was looking at other web frameworks after watching a keynote from the author of Seaside at Djangocon.

However, I realized something important about Lift and Scala which I had never caught before: Scala compiles to java bytecode.  Java can be run on Google App Engine.  I can use Scala/Lift to write for App Engine.

Suddenly I'm hooked.  Oh, awesome, and the book "Programming Scala" is available freely online.  Mmmm... looks like I have my reading for my traveling this summer.

Tuesday, May 25, 2010

Getting a Python/Django Job

Getting a job doesn't seem like a fun activity to many people.  I'm in the thick of it right now.  The problem is when you have a skill set that you really like and that you feel confident with that no company wants.  I feel like I'm in that place with Python/Django.

Sure, I've worked on the "corporaty" systems, ASP.NET, MVC, C#, etc., but what I'd really prefer to work on is python/Django on the web.  It doesn't seem like there are any companies hiring for that in Denver (or maybe I need to come up with a better way to find them?).  So I end up in an odd place where I wonder if it would be worth a.) going back to the corporaty things that get jobs (MSSQL, ASP, etc.) or b.) learning a newer but similar technology (RoR), and gamble that someone will hire me because I have previous experience in Django.

No one in Colorado needs Django work done?

Tuesday, May 11, 2010

I Bought It at Ross!

I was waiting on the wife at Ross Dress for Less the other day, when I happened to notice something:  They sell laptop bags!  Since when did Ross start carrying those?  Surprisingly they had a selection of name brands at, you guessed it, discount prices.

I ended up buying a Targus Messenger Fusion in dark gray/green for the Toshiba 13.3" I got a few months ago.  It was marked down to $18.99 (compared to $26.50 online).  It's a pretty nice looking laptop bag with built-in padding and tons of pockets/storage.  It has an interesting feature in that it comes with multiple straps so you can keep the green one out for a young/hip look, or put the dark one one for a more serious professional look.

Thursday, January 14, 2010

Accessing Inherited Models from the Parent in Django

One of the neat features of Django's ORM is Model inheritance (table-level). It allows several neat data design patterns to occur. Here's an example. Let's say we're developing a website for a game company. The company sells two types of products: board games and video games. All of the products will share some data in common, name and product_id for example, but we also need to store specific details about each. Using model inheritance we can do something as follows.

class Product(models.Model):
name = models.CharField(max_length=75)
product_id = models.SmallIntegerField()
price = models.DecimalField()

class BoardGame(Product):
num_of_players = models.SmallIntegerField()
game_type = models.CharField(max_length=50)

class VideoGame(Product):
PLATFORM_CHOICES = (
('wii', 'Wii),
('xb3', 'Xbox 360'),
('ps3', 'Playstation 3'),
)
platform = models.CharField(max_length=3, choices=PLATFORM_CHOICES)
In a real use-case scenario you'd most likely have more than 1 field per, but for this example I wanted to keep things simple.

The way Django implements this, if you were to query one of the child models, you'd be able to access the methods from the parent models...
b = BoardGame.objects.all()[1]
print b.name

>>> 'Djangopoly'
Another thing that's cool is child instances have a parent instance record. Using the "Djangopoloy" game from above, which is technically type BoardGame, one could still query Product and retrieve it.
p = Product.objects.get(name='Djangopoly')
This is really useful, but sometimes you need to go the opposite direction, and this is where Django's implementation stops. The link can't go from a Product model instance to a BoardGame. It can't retrieve state as if it was of type BoardGame.
print p.platform

>>> CAN'T DO THAT!
Because the need for this seems to be arising more often than not lately for me, I put together a re-usbale bit of code to overcome this limitation. I'll post the code below (a GitHub gist), but using it is actually quite simple.

It works by providing an abstract model that the parent model inherits from instead of models.Model:
from inheritance.models import ChildAwareModel

class Product(ChildAwareModel):
...

pass
Then, an inner class "Inheritance" is supplied to describe children of the model.
class Product(ChildAwareModel):
...

class Inheritance:
children = (
'myapp.models.BoardGame',
'myapp.mdoels.VideoGame',
)
Only children that need to be reversed to should be set. Once that is configured, a method "get_child_model()" will become available, and can be used like so:
p = Product.objects.get(name='Djangopoly')
b = p.get_child_model()
print b.num_of_players

>>> 4
I'm finding this particularly useful when I've created an aggregate type page -- that is a page that shows a summary of all the generic types (Product) -- but need to on user-click show them some type of product-specific detail.

The implementation for ChildAwareModel is below. Save it somewhere on your python path and enjoy. :)


ChildAwareModel Gist

Tuesday, January 12, 2010

Version Control Commit Messages

Soooooo... I think I'm going to put in a proposal at work. All commit messages for our Mercurial DVCS need to be in 16-year-old girl language....

  • "Like, the JSON api is totally updated"
  • "fixed the buggies kk thx bai <3"
  • "this import module is sooooo cuties!!!!!11`1"

Sunday, January 10, 2010

Meh @reading (but Yay to reading on the iPod)

I can't be the only programmer who finds reading a chore? And what about those 5-billion page programming tomes? Am I the only one who never finishes those?


It happens to be that I just found something about reading that totally rocks: Reading on the iPhone/iPod Touch is totally different (better different). HA! I bet you didn't know I was going to say that (well if you read the title of this post you probably did.. that was totally a spoiler).

Now it seems that I am finding I actually enjoy reading again (did I just write that?). I ended up landing a very fetching iPod touch for Christmas which has been having it's battery drained near non-stop since the package was opened. As a curiosity of sorts, I threw a lot of the big name apps onto it, including Kindle for Ipod, and purchased a book I had been eying for a while, Javascript: The Good Parts (Douglas Crockford), to try out the experience of reading on the iPod.

It seems so wrong but I found I actually prefer reading on the iPod. I've read a number of paper books, and I've tried reading eBook/PDFs on the computer, but neither of them really jump out at me. But the iPod... the iPod I like.

The reason for this, I suspect, is that reading on the iPod is not intimidating. The screen only shows 2 paragraphs at a time. I don't need to be worried about the rest of the book, I'm only looking at these 2 paragraphs. What I think this does for me is it allows me to read the book without feeling like I have to rush to get to the end.

My wife thinks it's silly, but whatever -- I'm already on my 2nd book.... Real World Haskell (Donald Stewart). Oooooh yes, it's Haskell time! Expect some really weirded out blog posts from me in the future about functional programming.

  © Blogger template 'Minimalist G' by Ourblogtemplates.com 2008

Back to TOP