Saturday, October 6, 2012

Square Photography

Look interesting right? :)
It change my perspective. Why don't you try it!


 

Friday, October 5, 2012

Rails Namespace, Nested Resource and form_for

Couple days ago, I ran into a problem when I try to use namespace, nested resources and form_for in Rails 3 and ruby 1.9.3. I try to setup some thing similar to this, a namespace :admin, with nested resources :menus, and :menu_items. Here is the routes.rb:
namespace :admin do
  resources :menus do
    resources :menu_items
  end
end
I think it's probably common used case. Unfortunately, I got this error when I try to create a new MenuItem in menu_items/_form.html.erb
undefind method 'admin_menu_items_path' for #<#<Class ...
...
 1: <%= form_for(@admin_menu_item)do |f| %>
      ...
17: end
I realize that the standard scaffolding won't work for me, so I start googling. Right away, I get a lot of hits. It's seem to be a common issue. However, the solutions create quite a confusion for me. I try different solutions, some looking good but don't work! .. Here is what I find working.

 First, in admin/menu_items_controller.rb, method 'new':
def new 
  @menu = Admin::Menu.find(params[:menu_id])
  @menu_item = @menu.menu_items.build
  ...
end
It load up the @menu, and build @menu_item, nothing surprise me. I also get rid of than "admin" prefix. It's simpler that way.

Thursday, October 4, 2012

Permutation and Mathematical Induction

Last post, I show how basic mathematical induction works. Now, I am going to use it to prove that an algorithm is work correct. In this case, we are going to prove a permutation algorithm, which take an array of unique numbers L, and return an an array of all permutations of L. Let call it perms(L). For example:

  1. If L = [ ], then perms(L) would be [ [ ] ].
  2. If L = [1, 2, 3], the result of perms(L) will be an array [ [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]. Note: the arrary could be any order.
The algorithm that I am going to prove is shown here:
 1: def perms(L)
 2:   return [[]] if L.size == 0
 3:   result = []
 4:   L.each do |elm|
 5:     L1 = L - [elm]
 6:     perms(L1).each |p|
 7:       p1 = [elm] + p
 8:       result << p1
 9:     end
10:   end
11:   return result
12: end

The exact statement that I want to prove to you is: for any given array L of size n, the perms(L) is an array of all size-n permutation of L.

First, basis step: Let L = [ ]. The L.size will be 0. Then the perms(L) will return immediately with value [ [ ] ], which is the array of all size-0 permutation of L.

Inductive step: Let assume statement is true for any array with size n. We have to show that for any array L of size n+1, perms(L) will return an array of all size-(n+1) permutation of L.

Wednesday, October 3, 2012

Chinese Abacus and Mathematical Induction

When I was a kid, I used to practice Chinese Abacus every day. Me and my brother turn this boring practice into a competition, and the winner is the person who can do 1 + 2 + ... + 100 faster! Of course, it's has to be correct. At that time, we were told that the correct value is 5050, and we did not question about it.

Now, I kinda wonder, if I am going to proof to some one that 1 + 2 + ... + 100 = 5050, how can I do that?  Here one way to do it.

First line up two line of sum this way, one from 1 to 100, another from 100 to 1.

  1 +   2 +   3 + ... + 100
100 +  99 +  98 + ... +   1
---------------------------------------
101 + 101 + 101 + ... + 101 = 101 * 100

Then, sum each column. As you can see, sum value in each column is equal 101. Since we know that there is going to be 100 column. So the sum of the last line, which is sum of those two line, is 101 * 100. Because we start with 2 lines,  the sum of  \(1 + 2 + 3 + ... + 100\) = \(101 \cdot 100 / 2 = 5050 \).

This way, we can also show that, for any given interger \(n \ge 1\)
$$ \displaystyle\sum_{i=1}^{n} i = 1 + 2 +  ... + n = \frac{n\dot(n+1)}{2}$$
Nice!, It's probably require a genius to come up with the proof like this, don't you think?

Another way, we can use mathematical induction to proof this statement too. It's more systematic, and can be generalize to prove more complex statements. The proof by mathematical induction has two parts, basis step and induction step. Basically, we have to show the basis is true, then show if any given number is true, then the next one also true.

Tuesday, October 2, 2012

Writing Math Equation in Dynamic Page Blogs


Mathjax is an open source Javascript display engine for mathematics. It's allow you to rendered math equation on all modern browsers without have to download reader, plugins or fonts.

Mathjax support Tex, LaTax and MathML equations. Better than word, here is an example.

When \(a \ne 0\), there are two solutions to \(ax^2 + bx + c = 0\) 
and they are $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$

Which produce:
When \(a \ne 0\), there are two solutions to \(ax^2 + bx + c = 0\) and they are $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$

What not so trivial to me is how to set it up.  Basically, to endable MathJax in web platform, you have to add the line to header section.
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?
config=TeX-AMS-MML_HTMLorMML" type="text/javascript"></script>

Unfortunately, it's won't work with Dynamic Page, which I am using. Because the content of the post is showed in a popup page, the in the main page itself. The solution, the script have to be added into the post itself.

Here what I did:
  1. open the post
  2. edit in html mode
  3. copy the script on top of the post
Then start writing the math equation! That all it's take.

Mathjax has an excellent documentation how to use it here. It's really cool! :)

Monday, October 1, 2012

Favor Composition over Inheritance - Conclusion

It all come down to the word "change". Change is the key to decided which one should be inherited and which one should be composite.

The base class Duck has-a name, and swim. So does the MallardDuck which inherited from Duck. It is-a Duck after all. MallardDuck also has-a behavior fly and quack.  But these two behavior are not inherited from Duck thou. Both are composite part of MallardDuck.

What make swim, different from fly? Can we consider swim as a behavior, and implement it in the same way as fly?
The answer is in the word "change". The swim does not change. All subclass has the same swim method. While, fly and quack are not the same in all subclass. Of course, nothing prevent us from implementing swim in the same way as we did with fly. But why do we need to do more complicate code if we don't need too. Inherited would work great for swim.

Can we just override and make change in the subclass as needed? 
Yes, we can. However, if the change are the same in two different subclass, then we code duplication! Consider, both MallardDuck and RedheadDuck can fly with wing. That means we would have to make the same change to MallardDuck and RedheadDuck. By implement the part of the duck that can be changed into module, we can pick and choose what behavior we want. You can see in the part 3, it is make much more sense, easily to understand and maintain.

Object vs Module, which one should I use?
Obviously, if you want ability to change the behavior at run time, you would have to use object approach. But that is not the only advantage object approach has over module. The object give you much control over namespace and help you avoid name collision.

Consider the module implementation, when we include the module, all the methods are defined in the same name space. Which means it's possible we can get name collision.  Specially, if the module are large, and very complicated, say 10 or may be 20 methods defined. It's possible two modules have the same method name but doing different thing. For example, if we happen to include both Behavior::FlyWithWing and Behavior::NotFly, one of the fly method will get overridden.

On the other hand, if we implement using objects, it's name collision won't happen, because all the methods would be contained in the object itself.

For the problem that is not so complex, the module would be a good choice, because it's easier to understand, and manage. Beside, with good naming convention, the name collision can be avoid easily.

Knowing when to use inheritance or composition is one of the most important skill to learn. What every way you choose to implement, separated part of the object that can be change, and use them to compost the new object is the key to handling change. If it's not change, just inherited it!

Always, start with the simple solution, but also know where are you heading help you make the right choice.

Thanks for reading this far. :)

Sunday, September 30, 2012

Favor Composition over Inheritance - Part 4

Previously in the programming series posts, I show how to use module to implement composition. One limitation of using module is, duck can not change behavior at run time. Such as MallardDuck can only fly with wing. How can we allow an instance of duck to change their behavior at run time? An answer is using object instead of module.

 To support this feature, the base class, now, hold all the behaviors  implemented for subclass. That quite different from using module, which the base class know nothing about subclass behaviors at all.
class Duck
  attr_reader :name
  attr_accessor :fly_behavior, :quack_behavior
  def initialize
    @name = "mallard duck"
    @fly_behavior = nil
    @quack_behavior = nil
  end

  def fly
    fly_behavior.fly
  end

  def quack
    quack_behavior.quack
  end
end

In this case, the base class by default has no behaviors. It's the subclass job to create, and assign default behaviors of the subclass when initiate an instance. For example, MallardDuck default behavior for flying is fly with wing, etc.
require './duck'
require './behavior/fly_with_wing'
require './behavior/quack_loud'

class MallardDuck &lt; Duck
  def initialize
    @name = "mallard duck"
    @fly_behavior = Behavior::FlyWithWing.new
    @quack_behavior = Behavior::QuackLoud.new
  end
end

Cherry Blossom 2012

Pictures from Cherry Blossom this year. I like to see how it's show up in the blogs. Not so bad :)