Howcast on TV! - iPhone App

Posted by sudothinker on April 06, 2009

The Howcast Application for iPhone that I’ve been working on is featured in the new iPhone commercial!

If this video doesn’t work you can view it on the Apple site, under ‘Itchy’.

Download the app

twtbox - a jukebox powered by tweets

Posted by sudothinker on March 28, 2009

Expanding on the idea of twitter being a command line tool for the web – I’ve been working on a twitter powered jukebox – http://twtbox.com (with help from jesse and henry).

The idea is to have a community jukebox where requests are done via twitter. Tweet @twtbox with the song you want to hear and it’ll be queued on the jukebox – simple as that.

Its a working prototype right now but some cool stuff is in the works to make it even more fun.

Addition to acts_as_state_machine: on_transition

Posted by sudothinker on March 04, 2009

Here is a small addition to the acts_as_state_machine plugin to add an on_transition event.

acts_as_state_machine already allows you to specify :enter and :exit events which get triggered when a model enters or leaves a particular state. However, I ran into a situation where there were multiple ways to enter a particular state and I only wanted to call a method whenever a particular event transition happened.

Code is available on github: http://github.com/sudothinker/acts_as_state_machine/tree/master

Thanks to Scott Barron for writing the original acts_as_state_machine.

Here is an example usecase:

class Order < ActiveRecord::Base
   acts_as_state_machine :initial => :opened

   state :opened
   state :closed, :enter => Proc.new {|o| Mailer.send_notice(o)}
   state :returned

   event :close do
     transitions :to => :closed, :from => :opened
   end

   event :return do
     transitions :to => :returned, :from => :closed
   end

   event :return_with_email do
     transitions :to => :returned, :from => :closed, :on_transition => :email_user
   end

   def email_user
      Notifier.deliver_order_returned(self)
   end
 end

Erlang Exercises: Interaction between processes, Concurrency: Star of Processes

Posted by sudothinker on March 02, 2009

Here is my solution to the last of the 3 Erlang ‘Interaction between processes, concurrency’ problems here: http://erlang.org/course/exercises.html#conc. It is definitely much shorter than my ring code.

Here are some things I assumed from the problem statement:

  • The center node is the main process and is not spawned.
  • The center node continues to send messages to the star nodes regardless of the response. It doesn’t wait for the response to send another message.
-module(star).
-export([star/2, star_node/1]).

% Write a function which starts N processes in a star, 
% and sends a message to each of them M times. 
% After the messages have been sent the processes should terminate gracefully.
star(N, M) ->
  Nodes = lists:map(fun(X) -> spawn(star, star_node, [self()]) end, lists:seq(1, N)),
  io:format("Built nodes ~w~n", [Nodes]),    
  send(M, Nodes).

% Sends a ping +M+ times to each of the nodes in +Nodes+
send(0, Nodes) ->
  lists:flatmap(fun(X) -> X ! {self(), stop}, [X] end, Nodes);
send(M, Nodes) when M > 0 ->
  lists:flatmap(fun(X) -> X ! {self(), ping}, [X] end, Nodes),
  send(M - 1, Nodes).

% An element of the star, receives messages from +Center+ and sends them back
star_node(Center) ->
  receive
    {Center, ping} ->
      io:format("~w recieved a ping, sending it back to ~w~n", [self(), Center]),
      Center ! ping,
      star_node(Center);
    {Center, stop} ->
      io:format("~w recieved a stop~n", [self()]),
      true
  end.

Rails 2.3 Upgrade Problems and Solutions

Posted by sudothinker on March 01, 2009

Cucumber

This fix will address “undefined method `visits’ for # (NoMethodError)”

# features/env.rb

require 'webrat/rails'
Webrat.configure do |config|
  config.mode = :rails
end

Gems

This fix will address “uninitialized constant RedCloth (NameError)”

# config/environment.rb

config.gem "RedCloth", :lib => "redcloth", :source => "http://code.whytheluckystiff.net" 
rake gems:unpack
rake gems:build

Forms

Fields for now should be called on the outter form, before I had

fields_for 'video[ingredient_attributes][]', ingredient do |i_form|

which used the Multimodel Forms plugin.

Now this becomes:

video_form.fields_for :ingredients do |i_form|

See http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes for more information.

Try

The version of try I had was this:


class Object
  def try(method)
    send method if respond_to? method
  end
end

in rails 2.3 though the try method is changed to this:


class Object
  def try(method, *args, &block)
    send(method, *args, &block)
  end
end

class NilClass
   def try(method, *args, &block)
     nil
   end
end

So I got a bunch of undefined method errors which I had to change around to use respond_to, or move the try up the chain so it gets called on nil.

SimplyHelpful

Get rid of this, the functionality has been added to rails. You might see “uninitialized constant SimplyHelpful::Record Identifier (ActionView::TemplateError)” otherwise.

route_for

After a change to edge rails broke our monkey-patched #route_for method, I decided to just delegate to rails’ #assert_generates method. For most cases, this will not present a problem, but for some it might. You’ll know if you upgrade and see any newly failing, route-related examples. Here are the things that you might need to change.

  • Make sure IDs are strings

If you had :id => 1 before, you need to change that to :id => “1”


#old
route_for(:controller => 'things', :action => 'show', :id => 1).should == "/things/1" 

#new
route_for(:controller => 'things', :action => 'show', :id => "1").should == "/things/1" 
  • Convert paths for non-get methods to hashes

If you had an example with a route that requires post, put, or delete, you’ll need to declare that explicitly.


#old
route_for(:controller => 'things', :action => 'create').should == "/things" 

#new
route_for(:controller => 'things', :action => 'create').should == {:path => "/things", :method => :post}

assert_select

I was using assert_select (should have_tag) in rspec in model specs to verify to_xml representations of models. This isn’t really recommended as have_tag should really only be used for html. Instead I used Hpricot to parse the xml (Hpricot.XML) and then verified the contents of the hpricot object.

Twitter: Command Line for the Web

Posted by sudothinker on February 27, 2009

Twitter bots: The basic idea is that there are twitter bots which have twitter accounts. When they receive direct messages, they lookup who they are from and perform the action in the message for the twitter user who sent the message. They might even reply back with some options, responses or confirmations.

@comcast record entourage tonight
@netflix add 'slumdog millionaire' to my queue
@amazon I want an iPhone armband

Amazon bot could maybe respond back to me with some choices?

@reddit whats the top link?
@laundry are you free?
@ticketmaster I want 2 tickets to see the redsox this saturday
@weather tomorrow in tahoe?
@home preheat the oven to 400

Hmm..

@twitter I'm making some coffee

Erlang Exercises: Interaction between processes, Concurrency: Ring Code

Posted by sudothinker on February 26, 2009

Solution to the Erlang ring problem: Write a function which starts N processes in a ring, and sends a message M times around all the processes in the ring. After the messages have been sent the processes should terminate gracefully.

This solution is perhaps more complex than other solutions on the web, one of the reasons is that each node knows about the node before and after it (other solutions just make each node know about the node after it). The reason is so that we can be sure that the message is making the correct path around the ring.

This is also a first attempt, I am sure there are cleanups and optimizations that could be done (after looking around it looks like foldl would have been handy).

-module(ring).
-export([ring/2, node/0]).

% The algorithm, is to first create a list of the N processes.
% For each process we need to hook it up to the before and after process in the ring.
% Then we have hooked everything up:
%   we send the message from the first node in the ring
%   and wait until there is a response (went all the way around the ring)
%   we then repeat M times
% When we have repeated this M times, then we use the infastructure to pass around a stop
% message which will terminate the processes gracefully.

% We also include checks to make sure that the message came from the process before it in the ring
% and only advance it if it did.

% Starts N processes in a ring, and sends a message M times around all the nodes in the ring.
ring(N, M) ->
  Nodes = spawn_nodes(N),
  io:format("Built nodes ~w~n", [Nodes]),  
  ring(N, M, Nodes, []).

% This will be in charge of spawning +N+ nodes and adding them to +Nodes+
spawn_nodes(N) when N > 0 -> 
  [spawn(ring, node, [])] ++ spawn_nodes(N - 1);
spawn_nodes(0) -> [].

% When there are no nodes ordered yet then we make a from Node at the start
ring(N, M, [X,Y|Nodes], []) when N > 2 ->
  X ! {to, Y},
  ring(N - 1, M, [Y] ++ Nodes, [X]);

% Recursive case when there are full nodes to hook up
ring(N, M, [X,Y|Nodes], Ordered_nodes) when N > 2 ->
  X ! {lists:last(Ordered_nodes), Y},
  ring(N - 1, M, [Y] ++ Nodes, Ordered_nodes ++ [X]);

% When there are 2 nodes left to hook up we make a to Node at the end
ring(2, M, [X|Y], Ordered_nodes) when length(Ordered_nodes) > 0 ->
  X ! {from, lists:last(Ordered_nodes)},
  ring(1, M, Y, Ordered_nodes ++ [X]);

% Special case whenever we just want a ring of 2 nodes
ring(2, M, [X, Y], []) ->
  Y ! {X, X},
  X ! {Y, Y, M};

% Special case ring of 1
ring(1, M, [X], []) ->
  X ! {X, X, M};

% 1 node left to build which will be the instigator of the pinging  
ring(1, M, [Node], [X|Ordered_nodes]) ->
  % hook up the 2 ends with Node
  X ! {from, Node},  
  lists:last(Ordered_nodes) ! {to, Node},
  % Kick it all off
  Node ! {lists:last(Ordered_nodes), X, M}.

% Intermediary nodes which don't have a From and To hooked up yet
% Can be upgraded to a full node by passing in {from/to, From/To}
to(To) -> receive {from, From} -> node(From, To) end.
from(From) -> receive {to, To} -> node(From, To) end.

% Starting point for all nodes, from there they can be made into a 
% From/To/Full From,To pair  
node() ->
  receive
    {to, To} -> to(To);
    {from, From} -> from(From);
    {From, To} -> node(From, To);
    % A driver node
    {From, To, M} -> node(From, To, M)
  end.

% Will receive a ping from +From+ and will pass it on to +To+
% If it receives a stop it will pass that on to +To+ and then stop
node(From, To) ->
  receive
    {From, ping} ->
      io:format("Passing along a ping from ~w to ~w~n", [self(), To]),
      To ! {self(), ping},
      node(From, To);
    {From, stop} ->
      io:format("Passing along a stop from ~w to ~w~n", [self(), To]),      
      To ! {self(), stop},
      true;
    Other -> node(From, To)
  end.

% The driver node, this will ping +To+ +M+ times 
% It will only ping +To+ again whenever it gets a ping back from its +From+  
node(From, To, M) when M > 0 ->
  io:format("Sending around a ping starting from ~w to ~w, ~w left~n", [self(), To, M]),
  To ! {self(), ping},
  receive {From, ping} -> node(From, To, M - 1) end;

% Base case for driver node, we're done sending it around so just stop all the nodes
% Each node in the ring is responsible for passing along a stop.
node(From, To, 0) ->
  io:format("Sending around a stop starting from ~w to ~w~n", [self(), To]),  
  To ! {self(), stop},
  receive {From, stop} -> true end.

Erlang Exercises: Interaction between processes, Concurrency

Posted by sudothinker on February 24, 2009

From http://erlang.org/course/exercises.html#conc.

1. Write a function which starts 2 processes, and sends a message M times forewards and backwards between them. After the messages have been sent the processes should terminate gracefully.

-module(bouncer).
-export([bounce/1, ping/2, ponger/0]).

% Spawn a pinger and a ponger and message back and forth +M+ times
bounce(M) ->
  Ponger = spawn(bouncer, ponger, []),
  spawn(bouncer, ping, [Ponger, M]).

% I'm going to ping +Ponger+ +M+ times  
% When I've done that I'm going to tell Ponger to stop, and I'll stop
ping(Ponger, M) when M > 0 ->
  Ponger ! {self(), ping},
  receive
    {Ponger, pong} ->
      io:format("Ponged"),
      ping(Ponger, M - 1);
    stop ->
      true;
    % This is a safe guard, we only want to count pong's from +Ponger+
    Other ->
      ping(Ponger, M)
  end;
ping(Ponger, 0) ->
  Ponger ! stop.

% If I get a ping, im going to pong back  
ponger() ->
  receive
    {From, ping} ->
      io:format("Pinged"),
      From ! {self(), pong},
      ponger();
    stop ->
      true;
    % We'll ping anyone back, but it has to be in form {From, ping}
    Other ->
      ponger()
  end.

Erlang Exercises: Simple recursive programs

Posted by sudothinker on February 23, 2009

My solutions to simple sequential program exercises: http://erlang.org/course/exercises.html#recurs

-module(lists1).
-export([min/1, max/1, min_max/1]).

min([H|L]) -> 
  min(H, L).
min(M, []) ->
  M;
min(M, [H|L]) when M < H ->
  min(M, L);
min(_M, [H|L]) ->
  min(H, L).

max([H|L]) -> 
  max(H, L).
max(M, []) ->
  M;
max(M, [H|L]) when M > H ->
  max(M, L);
max(_M, [H|L]) ->
  max(H, L).  

min_max(L) ->
  {min(L), max(L)}.
-module(time).
-export([swedish_date/0]).

swedish_date() ->
  string:substr(integer_to_list(element(1, date())), 3, 4) ++ pad_string(integer_to_list(element(2, date()))) ++ pad_string(integer_to_list(element(3, date()))). 

pad_string(A_string) ->
  if 
    length(A_string) == 1 -> "0" ++ A_string;
    true -> A_string
  end.

Erlang Exercises: Simple sequential programs

Posted by sudothinker on February 22, 2009

My solutions to simple sequential program exercises: http://erlang.org/course/exercises.html#simple

-module(temp).
-export([convert/1]).

convert({c, Temperature}) ->
  {f, c2f(Temperature)};
convert({f, Temperature}) ->
  {c, f2c(Temperature)};
convert(Other) ->
  {invalid_object, Other}.

c2f(X) ->
  ((9/5) * X) + 32.

f2c(X) ->
  (5/9) * (X - 32).  
-module(mathStuff).
-export([perimeter/1]).

perimeter({square, Side}) ->
  4 * Side;
perimeter({circle, Radius}) ->
  2 * 3.14 * Radius;
perimeter({triangle, A, B, C}) ->
  A + B + C;
perimeter(Other) ->
  {invalid_object, Other}.

Getting up and running with a Rails deployment environment

Posted by sudothinker on February 18, 2009

These are the steps I followed to get from a fresh Ubunto Gutsy installation on Slicehost to a complete Rails deployment including: DNS records, SSH keys, Server Security (disabling root access and changing SSH port), SVN, Ruby, MySQL, rubygems, Rails, Mongrel, Mongrel cluster, nginx and Capistrano.

  1. http://articles.slicehost.com/2007/10/24/creating-dns-records (More info: http://wiki.slicehost.com/doku.php?id=detailed_information_on_dns_record_types)
  2. http://articles.slicehost.com/2007/11/23/ubuntu-gutsy-mysql-and-ror (Pages 1 and 2)
  3. http://articles.slicehost.com/2008/1/16/ubuntu-gutsy-nginx-vhosts-rails-and-mongrels
  4. http://articles.slicehost.com/subversion
  5. http://articles.slicehost.com/2008/1/9/capistrano-series-introduction
  6. http://articles.slicehost.com/2007/11/29/ubuntu-gutsy-mongrel-clusters-and-surviving-a-reboot

Setup with mephisto, github pages, and tumblr

Posted by sudothinker on February 17, 2009

I have a somewhat unique setup for sudothinker.com.

I use mephisto hosted on my slicehost slice for sudothinker.com, I use tumblr for beers.sudothinker.com and github pages for codes.sudothinker.com.

The reason for the 3 separate tools is so I can have the best tool for the job at hand.

For my blog I wanted fully functional, battle tested blog software. I also wanted the flexibilty to make layout changes without code pushes. Mephisto fits this bill really well and its theme editor in the browser is pretty handy to avoid cap deploys.

For beers.sudothinker.com, I want a way to showcase photos easily. I normally take these photos with my iPhone and so publishing new photos is easy with the Tumblr app for the iPhone, I also get free image hosting through my tumblr account so its one hosting aspect that I don’t need to worry about.

For codes.sudothinker.com, I wanted somewhere where I can host static pages with the flexibility of revisions, all the css/js for this site are hosted on that subdomain too. This makes it really easy to make incremental changes to the css/js files for all three domains with the flexibility of a git backend. Changes are also pushed live right away and are hosted for free on github.com. I could probably do the same with mephisto pages/sections, but this way I get to use textmate and git for editing the static pages rather than the browser.

Stay tuned for a tutorial on this kind of setup.

Simple backup with rsync and slicehost

Posted by sudothinker on February 12, 2009

I’ve been looking into all sorts of backup solutions lately, including BackBlaze, Dropbox, s3 and SugarSync.

My top level goals are:

  • Ridiculously easy to backup so I do it often
  • Syncing – I don’t want to have to deal with figuring out which files to back up and duplicate files.
  • Remote – I have a 1TB drive which I use to back up, but am trying to prevent against the fire/theft scenario and losing all my data
  • Low cost, I don’t want to pay an arm and a leg monthly for data which doesn’t frequently get accessed.
  • Attached network drive backup – I use a 1TB drive to house all the data which I need to backup remotely.

BackBlaze seems too cheap to be true, I used it for the 14 day trial and it seemed to work fine and at $5 a month for unlimited data it seems like a steal. I am just a little worried about the company in general, be good to hear someone recommend them.

Dropbox is handy for sharing files but doesn’t fit my bill for my backup goals. It works well for a dropbox folder but becomes a little tricky if you want to backup your entire drive.

s3 is definitely a great service, but it is a little pricey for me. SugarSync is also a bit more money than what I was hoping to pay.

After trying all these services it dawned on me that I am getting 10GB on my Slicehost account which I am not really using. So I got to work writing an rsync back up solution which would backup to my slicehost slice.

rsync -vaz --delete-excluded --delete --exclude-from=/Users/michael/.rsync_exclude Documents code mik:~/backup/'

This script when run from my home directory will rsync my Documents and code directories onto my slicehost slice (I have setup my .ssh/config to use the alias mik as my slicehost slice). I can also have a file .rsync_exclude in my home directory which can contain patterns of files which I want to exclude from these directories.

So far this has worked really well for me, with this command I can just set up a cron job on my local machine which will do the backups in the background, or just create a backup alias which can be run manually whenever I want to backup.

Found Blog!

Posted by sudothinker on February 11, 2009

SF Ruby Meetup 4.29.08

Posted by sudothinker on April 30, 2008

Went to my first SF meetup today, hosted by the good folks at Affinity Labs.

Higher-Order Procedures

The first talk was by Bala Paranj on the topic of Higher-Order Procedures in Ruby. He presented code like the following:
def make_filter(predicate)
  lambda do |list|
    results = []
    list.each do |r|
      results << r if predicate.call(r)
    end
    results
  end
end

even_filter = make_filter(lambda{|x| x % 2 == 0})

p even_filter.call([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# [2, 4, 6, 8, 10]

Im kind of conflicted with the above snippet – There are advantages of make_filter returning a proc:

  1. You can delay code execution until later in the program
  2. It allows for more reusable code as you can pass filters around rather than repeating even procs

For (1) – this can be said as a big advantage of higher-order procedures in general, you don’t have to deal with data until the last possible point. With this approach you can separate business logic and data crunching through the application. For (2), I’m not so convinced, while it does make for reusable code, there is an extra level of indirection created and I feel that the even_filter would have to be used in multiple places in the app for it to be justified.

The alternative which I would probably implement to achieve the above:

def even?
  lambda {|x| x % 2 == 0}
end

def filter_list(list, predicate)
  list.inject([]) do |result, element|
    result << element if predicate.call(element)
    result
  end
end

p filter_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], even?)
# [2, 4, 6, 8, 10]

I would argue that this is a better abstraction to have, you are still passing around predicates but I feel that the filter_list is more re-useable than the make_filter method. With this implementation we can reuse logic like determining if a number is even, and we also get the flexibility of applying any predicate to a list to filter elements. Another reason why I like this is because I don’t like calling .call on what seem to be method objects, in the above example we had to use even_filter.call, which I see as cumbersome, with the later approach we can use filter_list as a method and call with straight parameters.

The above code can be found on my github page.

Erector

Pat Maddox presented a view template engine Erector

Erector is an alternative to other templating engines like Markaby and HAML. It is becoming a crowded field with over 19 templating engines now competing for dominance in rails. Since its inception, rails has been using erb for view templates. While this does have its limitations, it has stood the test of time. (Newer frameworks like merb allow for a more flexibility in choosing a template engine and support for markaby and HAML exist via gems for merb applications.)

So why is Erector different? Well the logic for starting Erector which I understood from the presentation was that writing erb sucks, and that Markaby and HAML are either not good enough or just look ugly. While I agree that HAML looks ugly, I am not really convinced that Markaby should be shot down quite so quickly before investing time on a new template engine.

Erector feels a lot like Markaby in many respects, the main difference I see is the code organization, Markaby follows erb convention in laying out your views in that each view reads from top to bottom, but instead of erb and HTML, it uses Ruby. Erector on the other hand splits up common chuncks of markup and functionality into ‘widgets’ which can get called from controllers via render_widget. It splits up these widgets in order to get reusability and extensibility in the views – these widgets are basically ruby objects and so can be subclassed and extended to gain functionality.

While I think Erector is an interesting concept, I feel the indirection created is very cumbersome. In order to change some copy, you have to find the layout, then follow the indirection of all the widgets which are rendered and then find the text you want to change. Widgets seem a bit like partials to me, but I feel that partials are logically organized and make sense as chunks of markup, making these widget ruby objects of markup just seems like overkill to me and introduces a lot of complexity in view rendering.

IBM Sharable Code & Mashups

The last presentation came from Michael Maximilien on the topic of mashups.

He presented on an interesting system which is basically a DSL for generating mashups. The example given was generating a website which mashes up some flickr photos and digg articles or youtube videos. The process is to write a single ‘Recipe’ in the DSL which in turn generates a full rails application, complete with migrations and API service calls to generate the mashup. So whats the DSL recipe? Well its everything that defines the mashup. All API calls need to be iterated out, all possible data objects returned by the API, all the views along with the markup for the application…

Another interesting aspect is deployments, you can specify a recipe for a particular deployment destination, for example facebook or iphone – define all the api keys and then generate a new rails application for that target. The main pitfall of something like this is that, although the API data can be reused, you’d have to iterate out all the views for the different deploy targets (Facebook in FBML for example).

This seems interesting, and goes along with the goal of Sharable Code. While I can’t see programmers using a tool like this to generate mash ups as they would want more flexibility in the generated code, there may be some appeal for non-programmers who want to get quick functional mashups with minimal initial overhead.

I also found a video of Michael himself explaining Swashup.