all things web and not web

allskonar

What is Team handball?

August 22nd, 2008

“team” handball [is played] on a basketball court (but longer) with a volleyball (but smaller) and hockey nets (but taller). It’s like lacrosse (without sticks) or water-polo (without water).

quote from wsj

Born to Code ~ in C

July 31st, 2008

This has to be one of the best book covers ever. You really have to focus on all the little details:

How the floppy disk is casually resting on the keyboard as if the coder had to leave in a hurry to do some coding else where. How the books logo is stamped on the back of the leather jacket left behind on the chair.

I know I shouldn’t keep poking fun at some applications since I bet there is plenty people can find where I goofed up … but this one is truly precious.

When I write web apps I try my best to keep my urls clean and legible. One thing that has always troubled me is how to handle label creation of named things web users key into the app. For example if a user enters a name of a restaurant Alicanté Café the uri safe for of that (if there is no intervention) ‘Alicant%C3%A9%20Caf%C3%A9’, which is total gobblygoo and one might as well show a uid or something of that nature since at least that doesn’t physically hurt the eye. As someone who has worked on a lot of Restaurant related apps this has always been something I wanted there to be an easy solution to. This weekend I decided it was worth trying once again to see what would work best. And after reading the “Internationalization in Ruby” in The Ruby Way. Here is the super simple trick


require 'iconv'
strange_name = "Alicanté Café" 
converter = Iconv.new('ASCII//TRANSLIT', 'UTF-8')
converter.iconv(strange_name)
"Alicant'e Caf'e" 

It leaves some odd ’ and “sfor some reason but they will get stripped away with all the other potential weird stuff out (”,’,etc). Still this discovery makes me stop complaining about pretentious foreign sounding restaurant names.

Here is an excellent case of a big problem … with a incredible simple solution. I upgraded my slicehost ubunto vpn from dapper to hardy. A risky business with nothing real in jeopardy except for the pride of a 380 days up time on the server. I shut down everything running on the server and upgrade to hardy. All is fine except that I realize that when I am starting all the services that small things tab completion doesn’t work among other annoyances and doing work on a server without that is practically unbearable. So I figured I would make some time to fix it… the best place to go on these issues is slicehost … THE ROCK. Tony on the slicehost campfire chat immediately identified the problem and it was fixed within 5 minutes.

*Tony | try just running “bash”

And as he said that I was like shit and ran echo $SHELL only to realize that I was in “sh” but now everything is fixed and dandy and I have my tab completion back along with other normal bashy things … thank god. Did I mention that slicehost rocks!

Using AWS::S3

Now setting a object to :public_read is trivial if it’s done when you store it to S3. That doesn’t seem to be the case if you want to change on an object that already has been stored privately. After banging my head against it a bit I finally “got it” and I figured I would share it to either show off or try to be helpful.

dial into s3sh session see url above for details on how to store keys in environment variables etc.

once in there get a bucket object

  • my_bucket = Bucket.find(‘foo’)

now get the s3obj that you want to become public

  • s3obj = my_bucket[‘object_name’]
  • policy = s3obj.acl
  • grant = ACL::Grant.new
  • grant.permission = ‘READ’
  • grantee = ACL::Grantee.new
  • grantee.group = ‘AllUsers’
  • grant.grantee = grantee
  • policy.grants << grant
  • s3obj.acl(policy)

The access control on the buckets must be very rich since it’s this tricky make things public. I must be overlooking something.

Bad Mephisto Move

July 10th, 2008

A while back I decided to get fancy and start hosting this blog on ec2 cloud just to sort of get the hang of working on that kind of a system. This of course involved moving database over and the works. Everything seemed to be going fine until I started posting… things were just busted bad. I kept getting

ActiveRecord::StatementInvalid (Mysql::Error: Duplicate entry ‘0’ for key 1

errors and for the longest time I just ignored it since I was able to post by using a some of my masterpiece drafts that I wasn’t going to use any how… but then I ran out of those and I felt an urge to post but that meant I needed to tackle the problem and as it turned out it was a simple fix after I had done the research. The primary key fields had lost the AUTO_INCREMENT magic during my db move and the solution was simply to go in and ad them where a appropriate.

ALTER TABLE `contents` CHANGE `id` `id` INT NOT NULL AUTO_INCREMENT;

Boy is that place a rats nest… haven’t looked at the site for a year now and decided to see how long it would take me to upgrade to rails 2. Remarkable enough it was really not that tricky to do which speaks to the level of my knowledge of rails at the time which was fairly slim so all my upgrading tasks where fairly light. So to make things more exciting I decided make it more rest-y … which also was remarkable light task except for a few minor issues such as lack of tests which makes it terribly difficult to even know if the site is working at all except for the fact that I clicked around a bit … (god I wish I had known testing better a year ago). So before I would dive into upping the test coverage I decided to save the very little traffic I get from google by issuing a 301 for the urls that changed. So as an former mod_rewrite ninja (oh did I mention that I deployed the site before I fell in love with nginx) I fired up .htaccess and wrote all the rules for the rewrites … then after 30 minutes of cursing and moaning I read somewhere that .htaccess doesn’t take on rails app jez. Not to worry I just stuffed the rules into my virtualhost config and things are flying.

respond_to block

June 5th, 2008

Don’t you just hate those gotchas out there that will consume some of too much of your time?


respond_to do |wants|
  format.js
  format.html
  format.xml
end

This snippet will run fine on everything except IE browsers which will try to download the .js file. This is because IE doesn’t specify ‘text/html’ mime type explicitly in the HTTP ACCEPT header. So for it to work on IE .html needs to be defined first.

Firefox “text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,/*;q=0.5”

on IE “image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, */

To fix it the order just needs to be changed.


respond_to do |wants|
  format.html
  format.js
  format.xml
end

It’s a continues struggle to become efficient in using VIM, especially if one ventures outside of what one regularly needs to do. It’s well worth it though since it might be the last text editor that you’ll ever need to master.

I was faced with having to produce pdf with selected code snippets.

Here is the fastest approach… be warned this example is for macs but I am sure it can work in other Li/Unix environments as well.

Install CUPS PDF and setup a virtual printer as is described on that page. Make sure that it’s the default printer after you have set it up.

The command to print in vim is :ha which is a short for :hardcopy this will spool the whole file to the print que for that driver and ultimately drop a pdf in cups-pdf folder on your desktop. To print out a selection simply highlight some text before issuing :ha command. I needed the line-numers of the code samples and this can be achieved by setting printoptions.

set printoptions=number:y

Now to be a complete terminal snob you should check out pdftk

Javascript Event Handling evolved

February 21st, 2008

Just this week, motionbox the company I work for released it’s first open source code the Motionbox EventHandler spearheaded by Topping Bowers with contributions from the rest of us in the group. The javascript library implements event delegation techniques and is built on the prototype library. There are other such libraries for yui which this was in part inspired by.

One of the kewlest thing about the library is the ability to subscribe dom elements to events before they even show up in the dom. Don’t take my word for it it was written up in ajaxian. There you have it: Topper, me and my colleges are almost famous now. If you are using prototype go and get the source and try it out it’s totally brilliant.

I have written about event handling before: The evolution of body onload Unobtrusive Javascript which might give some context on the topic of event handling in javascript.

It’s not uncommon that databases are filled with duplicate data sets. And it’s even more common that you want to clear it out so you don’t have to bothered with duplicates. This is obviously the sort of thing you want to fix at the entrance, on the way in to the database and not collect duplicates, but this solution works well if that is too late.

To get things started let’s write up a file that we can play with. I am using MySQL and I don’t know the SQL standard well enough to say but I am sure this example can be modified to work on other database servers. I generally just keep a file open and then retrieve it on the mysql console. Download the example file.


mysql>  \. dup_tutorial.sql

Creating a simple table to play with. And stuffing it with some data.

CREATE TABLE peoples (
  id int(11) NOT NULL auto_increment,
  f_name varchar(128) NOT NULL default '',
  l_name varchar(128) NOT NULL default '',
  age text NOT NULL,
  updated_on timestamp NOT NULL default
       CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  PRIMARY KEY  (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO peoples (f_name, l_name, age) 
   VALUES ('baldur', 'gudbjornsson', 28);
INSERT INTO peoples (f_name, l_name, age) 
   VALUES ('baldur', 'gudbjornsson', 28);
INSERT INTO peoples (f_name, l_name, age) 
   VALUES ('baldur', 'gudbjornsson', 28);
INSERT INTO peoples (f_name, l_name, age) 
   VALUES ('baldur', 'gudbjornsson', 31);

In this sample we have 4 rows and but there are only 2 rows unique if updated_on and id fields are not taken into the account. Now the way to query this to only receive the unique set group by can be used or SELECT DISTINCT.


SELECT *
FROM peoples 
GROUP BY f_name, l_name, age

And here is the trick to collect the others to dispose of them. First we’ll join the peoples table with a unique rows from it self in a sub query to retrieve the ones that don’t match.


SELECT o_peoples.id 
FROM peoples o_peoples
LEFT OUTER JOIN 
  (SELECT id 
   FROM peoples 
   GROUP BY f_name, l_name, age) u_peoples 
ON o_peoples.id = u_peoples.id
WHERE u_peoples.id IS NULL;

Then we’ll delete those extra rows from the database. Do this at your own risk and obviously back up your database five times and have a quick recovery plan it things go south.


DELETE o_peoples 
FROM peoples o_peoples
LEFT OUTER JOIN 
  (SELECT Id FROM peoples 
   GROUP BY f_name, l_name, age) u_peoples
ON o_peoples.id = u_peoples.id
WHERE u_peoples.id IS NULL;

jslint from the terminal

November 29th, 2007

Once you get into the habit of using jslint it’s hard not to, it’s just so satisfying when it passes and all the lint has been cleared away. The first few times I used I went to the web application and pasted the file in there and looked at the results, fixed what was wrong and pasted it back into the original file. This is especially inconvenient if you use vim or emacs since pasting from an external environment has always been a bit of a challenge. But fear not, Douglas Crowford, best known for his work on the json spec, has an extended version that works with rhino the java javascript interpreter. The advantage of using jslint through rhino is that you can inspect your javascript files from the terminal. Installing it on a mac is trivial just follow Peters Michaux Install instructions

Here is the short version:


$> curl -O ftp://ftp.mozilla.org/pub/mozilla.org/js/rhino1_6R7.zip
$> unzip rhino1_6R7.zip
$> cp rhino1_6R7/js.jar /Library/java/Extensions/

Download the jslint file


$> curl -O http://www.jslint.com/rhino/jslint.js

And then you should be able to:


$> java org.mozilla.javascript.tools.shell.Main jslint.js your_program.js

Object of the Day

November 19th, 2007

It has been a while since I have added a game to the Office Games section. This one is very simple and entertaining.

Object of the Day can be played with virtual object such as photographs and also with actual physical objects.

The game requires two or more players. One player brings an obscure object for others to guess the purpose of that object. The goal is to bring an object that is obscure enough that it will take the others a while to guess what it is and what it’s used for.

The rules are very simple! don’t bring an object that is too obscure or from a field that is very specialized, and people will have to understand what it is after it is explained. The object has to be intact and cannot have been tempered with. Here are two examples of great objects.

Now try to guess what these objects and what their purpose could be?

11/12 2007

November 12th, 2007

One cool thing I learned today was that you can set the columns when you generate the rails migration from the terminal. The prepopulates the tabel generation code with the table names and datatype. This isn’t such a big find since it’s well documented in script/generate model—help. But here is how it looks.


 script/generate model members name:string age:integer
 script/generate model portfolio member_id:integer body:text

Another thing I just came to realize is that defining explicit foreign_key constraint to the database is probably a good idea. I don’t know too much about database administration but if I understand it correctly it helps with dataintegrity and probably performance if the table grows big. Adding indexes is also a plus. A little specifity never hurt anyone. This example is for MYSQL with the InnoDB engine which I believe is the default for rails now.


. . .
def self.up
  create_table :members do |t|
    t.column :name, :string
    t.column :age, :integer
  end
end
. . .

def self.up
  create_table :portfolios do |t|
    t.column :member_id, :integer
    t.column :body, :text
  end
  execute 'ALTER TABLE portfolios ADD CONSTRAINT fk_portfolios_member \\
     FOREIGN KEY (member_id) REFERENCES members(id)'
end 
. . .


		
		
	
 
allskonar Powered by Mephisto