作者归档:船长

Learning Ruby 3, Containers, Blocks, and Iterators

with<Programming Ruby>
Chapter 4
Containers, Blocks, and Iterators

Containers

Arrays
a = [ 3.14159,  "pie", 99 ]
a.class         Array
           →
a.length        3
           →
a[0]            3.14159
           →

b = Array.new
b.length   →0
b[0] = "second"
b[1] = "array"
b          → ["second", "array"]

   Positive → 0                                         Negative
                      1     2     3     4    5      6
    indices                                        −1 ← indices
              −7     −6    −5    −4    −3   −2
          a = “ant” “bat” “cat” “dog” “elk” “?y” “gnu”
      a[2] →              “cat”
     a[-3] →                          “elk”
  a[1..3] →         “bat” “cat” “dog”
a[-3..-1] →                           “elk” “?y” “gnu”
 a[4..-2] →                           “elk” “?y”

the index to [ ]= is two numbers (a start and a length) or a range
a = [ 1, 3, 5, 7, 9 ]   [1, 3, 5, 7, 9]
                      →
a[2, 2] = ’cat’         [1, 3, "cat", 9]
                      →
                        [1, 3, "dog", "cat", 9]
a[2, 0] = ’dog’       →
                        [1, 9, 8, 7, "dog", "cat", 9]
a[1, 1] = [ 9, 8, 7 ] →
a[0..3] = []            ["dog", "cat", 9]
                      →
a[5..6] = 99, 98        ["dog", "cat", 9, nil, nil, 99, 98]
                      →

Hashes (associative arrays, maps, or dictionaries)
h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }
h.length   →3
h['dog']   → "canine"
h['cow'] = 'bovine'
h[12]    = 'dodecine'
h['cat'] = 99
h          → {"cow"=>"bovine", "cat"=>99, 12=>"dodecine",
               "donkey"=>"asinine", "dog"=>"canine"}

Implementing a SongList Container

class SongList
  def append(song)
    @songs.push(song)
    self
  end
end

class SongList
  def delete_first
    @songs.shift
  end
  def delete_last
    @songs.pop
  end
end

class SongList
  def [](index)
    @songs[index]
  end
end

Blocks and Iterators

class SongList
  def with_title(title)
    @songs.find {|song| title == song.name }
  end
end
find is an iterator
iterator: a method that invokes a block of code repeatedly
    def three_times
      yield
      yield
      yield
    end
    three_times { puts "Hello" }
produces:
    Hello
    Hello
    Hello

i1, i2 = 1, 1 # parallel assignment (i1 = 1 and i2 = 1)

def fib_up_to(max)
  i1, i2 = 1, 1        # parallel assignment (i1 = 1 and i2 = 1)
  while i1 <= max
    yield i1
    i1, i2 = i2, i1+i2
  end
end
fib_up_to(1000) {|f| print f, " " }

if they appear for the ?rst time in the block, they’re local to the block. If instead they ?rst appeared outside the block, the variables will be shared between the block and the surrounding environment.
a = [1, 2]
b = 'cat'
a.each {|b| c = b * a[1] }
a                 [1, 2]
              →
b                 2
              →
defined?(c)       nil
              →

class Array
  def find
    for i in 0…size
      value = self[i]
      return value if yield(value)
    end
    return nil
  end
end
[1, 3, 5, 7, 9].find {|v| v*v > 30 }   7
                                     →
[ 1, 3, 5, 7, 9 ].each {|i| puts i }
["H", "A", "L"].collect {|x| x.succ } ["I", "B", "M"]

[1,3,5,7].inject(0) {|sum, element| sum+element}           16
                                                         →
[1,3,5,7].inject(1) {|product, element| product*element}   105
                                                         →

if inject is called with no parameter,it uses the ?rst element of the collection as the initial value and starts the iteration with the second value.
[1,3,5,7].inject {|sum, element| sum+element}           16
                                                      →
[1,3,5,7].inject {|product, element| product*element}   105
                                                      →

Blocks for Transactions
class File
  def File.open_and_process(*args)
    f = File.open(*args)
    yield f
    f.close()
  end
end

 *args, meaning “collect the actual parameters passed to the method into an array named args

Blocks Can Be Closures

songlist = SongList.new
class JukeboxButton < Button
  def initialize(label, &action)
    super(label)
    @action = action
  end
  def button_pressed
    @action.call(self)
  end
end
start_button = JukeboxButton.new("Start") { songlist.start }
pause_button = JukeboxButton.new("Pause") { songlist.pause }
                                                                         &action,Ruby looks for a code block whenever that method is called. That code block is converted to an object of class Proc and assigned to the parameter. You can then treat the parameter as any other variable. In our example, we assigned it to the instance variable @action. When the callback method button_pressed is invoked, we use the Proc#call method on that object to invoke the block.

method lambda, which converts a block to a Proc object.

def n_times(thing)
  return lambda {|n| thing * n }
end
p1 = n_times(23)
p1.call(3)   → 69
p1.call(4)   → 92
p2 = n_times("Hello ")
p2.call(3)   → "Hello Hello Hello "

发表在 Ruby on Rails | 留下评论

Rocky Balboa,2006

Rocky Balboa,2006
http://www.imdb.com/title/tt0479143/

我以为这是部动作片(显然我对Sylvester Stallone的年纪问题看得太轻了),而影片的前面一大半却比较沉闷,所以看得不很爽。
转折发生在Rocky在街头教训自己的儿子那段, 听着那段掷地有声的精彩言论,我竟然突然感动要流泪!
挫败后不要找别人出气,而是要自己回击!
看来Stallone不但勇猛,而且很有战略,随着自己年龄的增加,他巧妙地把影片的重心由动作转到内涵上。
影片也再次让我感受到美国老人的孤寂。

6

Rocky Balboa,2006
美国Las Vegas夜景, 听说重庆也以夜景出名,不过还不能比较。

发表在 电影评论 | 留下评论

Learning Ajax 3, form and form observer

with <ajax on rails>

make fake form with the combination of link_to_remote and :submit option

3.4 Ajax Forms

form_for
remote_form_for

3.5

<%= form_tag :action => 'reverse' %>
  <p>Text to reverse: <%= text_field_tag 'text_to_reverse' %></p>
  <p id="reversed2"></p>
  <p><%= submit_to_remote 'submit', 'Reverse!',
          :update => 'reversed2',
          :url => { :action => 'reverse' } %></p>
<%= end_form_tag %>
the form can be submitted both via Ajax or non-Ajax methods. Consider this variation with two submit buttons
a common application for submit_to_remote would be checking a form for validity before actually submitting it for creation.

Form Observers

If :with doesn't contain an equal sign character (=), it's interpreted as a name for the parameterso foo becomes 'foo='+value. But if :with does contain an equal sign, it remains untouchedso foo=bar remains foo=bar.

:function => "alert(value)"

Observing an Entire Form
<form id="myForm">
  <p>Text to reverse: <%= text_field_tag 'text_to_reverse' %></p>
  <p id="reversed"></p>
</form>

<%= observe_form 'myForm',
      :update => "reversed",
      :url    => { :action => 'reverse' } %>
an observer for the form with the ID myForm, so that whenever any of its fields change, an Ajax.Updater call is created accordingly, which passes the serialized form values to the server.

发表在 Ruby on Rails | 留下评论

Learning Ajax 2, url, link and button

with <Ajax on Rails>
S2.3. Bringing Rails into the Picture

complex url_for example:
url_for :only_path => false, :protocol => ‘gopher:// ‘,
  :host => ‘example.com’, :controller =&gt; ‘chapter2′,
  :action => ‘myresponse’, :trailing_slash => true, :foo => ‘bar’,
  :anchor => ‘baz’
#=> ‘gopher://example.com/chapter2/myresponse?foo=bar/#baz’

ajax on rails(aor) alert:
<p><%= link_to_remote "Alert with javascript Helper", :url =>
   "/chapter2/myresponse", :success => "alert(request.responseText)" %></p>

aor insert:
<p><%= link_to_remote "Update  with javascript Helper", :url =>
  {:action => "myresponse"}, :update => "response5" %></p>
<p id="response5"></p>

Chapter 3. Introducing Prototype

3.2 Ajax Links

:method => :delete
<%= link_to "Delete", "/people/1", :method => :delete %>

==>
<a href="/people/1"
  onclick="var f = document.createElement(‘form’);
           f.style.display = ‘none’;
           this.parentNode.appendChild(f);
           f.method = ‘POST’;
           f.action = this.href;
           var m = document.createElement(‘input’);
           m.setAttribute(‘type’, ‘hidden’);
           m.setAttribute(‘name’, ‘_method’);
           m.setAttribute(‘value‘, ‘delete’);
           f.appendChild(m);
           f.submit(  );
           return false;">Delete</a>

Return false;
<a href="#"
   onclick="new Ajax.Updater(‘current_time’, ‘/chapter3/get_time’,
               {asynchronous:true, evalScripts:true});
            return false;">Check Time</a>
<div id="current_time"></div>
The link will only be followed if the expression evaluates true (or if the user has javascript turned off). That’s why the link_to_remote helper puts return false at the end of the onclick attribute.

Callbacks:
<%= link_to_remote "Check Time",
    :update   => ‘current_time’,
    :url      => { :action => ‘get_time’ },
    :before   => "$(‘indicator’).show(  )",
    :success  => "$(‘current_time’).visualEffect(‘highlight’)",
    :failure  => "alert(‘There was an error. ‘)",
    :complete => "$(‘indicator’).hide(  )" %>
<span id="indicator" style="display: none;">Loading…</span>
<div id="current_time"></div>

hide( ) and show( )
for an element to be dynamically shown via javascript, its CSS display: none property must be defined inline

this won’t work:
<style type="text/css">
  #indicator { display: none; }
</style>
<div id="indicator">Hidden DIV</div>
<script type="text/javascript">
  $("indicator").show(  ); // won’t work
</script>

But this will work:

<div id="indicator" style="display: none">Hidden DIV</div>
<script type="text/javascript">
  $("indicator").show(  ); // will work
</script>

:condition
<li><%= check_box_tag ‘checkbox’ %> Thing #1</li>
<%= link_to_remote "Delete checked items",
    :condition => "$(‘checkbox’).checked",
    :url       => { :action => ‘delete_items’ } %>

:submit
it allows you to simulate a form submission. By providing the ID of a page element, any fields contained in it will be sent along with the request.
<div id="fakeForm">
  <input type="text" name="foo" value="bar" />
</div>
<%= link_to_remote "Submit fake form",
       :submit   => "fakeForm",
       :url      => { :action => ‘repeat’ },
       :complete => "alert(request.responseText)" %>

nested forms

<form id="myForm">
  <input type="text" name="text_to_reverse" id="text_to_reverse" />
  <%= link_to_remote "Reverse field",
       :url      => { :action => ‘reverse’ },
       :submit   => "myForm",
       :complete => "$(‘text_to_reverse’).value=request.responseText" %>
  <input type="submit" />
</form>

:with
<%= link_to_remote "Link with params",
       :url      => { :action => ‘repeat’ },
       :complete => "alert(request.responseText)",
       :with     => "’foo=bar’" %>
two sets of quote marks. javascript expression

include references to javascript variables or DOM elements:
<input id="myElement" type="text" value="bar" />
<%= link_to_remote "Link with dynamic params",
       :url      => { :action => ‘repeat’ },
       :complete => "alert(request.responseText)",
       :with     => "’foo=’+escape($F(‘myElement’))" %>
escape it (so that it can safely be included in a URL query string)

link_to_function
<%= link_to_function "Toggle DIV", "$(‘indicator’).toggle(  )" %></p>
toggle( ), which hides and shows elements on the page.

button_to_function
<%= button_to_function "Greet", "alert(‘Hello world!’)" %>

combine with remote_function
<%= button_to_function "Check Time",
      remote_function(:update => "current_time",
        :url => { :action => ‘get_time’ }) %>

DIY button_to_remote
def button_to_remote(name, options = {})
  button_to_function(name, remote_function(options))
end
==>
<%= button_to_remote "Get Time Now",
      :update => "current_time",
      :url    => { :action => ‘get_time’ } %>

发表在 Ruby on Rails, 站长文档 | 留下评论

Ruby on Rails, Layout

<%= render :partial => "person" %>

the partial is named "person," the main template will look for an instance variable @person, and pass it to the partial as a local variable, person.if the instance variable doesn't match the name of the partial, you'd explicitly pass it, like this:

<%= render :partial => "person", :locals => { :person => @scott } %>
All the key/value pairs in the :locals hash will be made into local variables for the partial.

<%= render :partial => "person", :collection => @people %>
In this example, the main template has an array @people that will be looped through, passing a local variable person to the partial.

render :layout => false
def reverse
  @reversed_text = params[:text_to_reverse].reverse
  render :layout => false
end

发表在 Ruby on Rails | 留下评论

Learning Ajax 1, Prototype

with <Ajax on Rails>
Chapter 2 .Getting Our Feet Wet

S2.1. The Old-Fashioned Way
<p><a href="#" onclick="asyncAlert(  )">Call async server-side</a></p>
<script type="text/javascript">
  function asyncAlert(  ) {
    //Call server(IE-safe)
    function getRequestObject(  ) {
      try { return new XMLHttpRequest(  ) } catch (e) {}
      try { return new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {}
      try { return new ActiveXObject("Microsoft.XMLHTTP") } catch (e) {}
      return false
    }
    var request = getRequestObject(  );
    request.open('get', '/chapter2/myresponse');
    //we define a function that checks to see if readyState is 4 (which means the request is complete)
    request.onreadystatechange = function(  ) {
      if(request.readyState==4) alert(request.responseText);
    }
    request.send(  );
  }
</script>

s2.2. javascript Libraries and Prototype
Prototype Way:
<script src="/javascripts/prototype.js" type="text/javascript">
</script>
<p><a href="#" onclick="prototypeAlert(  );">Call with Prototype</a></p>
<script type="text/javascript">
 function prototypeAlert(  ) {
  new Ajax.Request('/chapter2/myresponse', { onSuccess: function(request) {
   alert(request.responseText);
  }})
 }
</script>

Update a element's innerHTML
<p><a href="#" onclick="updateElement(  )">Update element </a></p>
<p id="response"></p>
<script type="text/javascript">
  function updateElement(  ) {
    new Ajax.Request('/chapter2/myresponse', { onSuccess: function(request) {
      $('response').update(request.responseText);
    }})
  }
</script>

================>
<p><a href="#" onclick="updater(  )">Update with Ajax.Updater</a></p>
<p id="response2"></p>
<script type="text/javascript">
  function updater(  ) {
    new Ajax.Updater('response2', '/chapter2/myresponse');
  }
</script>

insert content:
<p><a href="#" onclick="appendToElement(  )">Append to element</a></p>
<p id="response3"></p>
<script type="text/javascript">
  function appendToElement(  ) {
    new Ajax.Updater('response3', '/chapter2/myresponse',
      { insertion:Insertion.Bottom });
  }
</script>
//insertions: Before, Top, Bottom, and After.

===============>
<p><a href="#" onclick="new Ajax.Updater('response4',
'/chapter2/myresponse', { insertion:Insertion.Bottom });">
Append to element</a></p>
<p id="response4"></p>

发表在 Ruby on Rails | 留下评论

A Bloody Aria, 2006

A Bloody Aria, 2006
http://www.imdb.com/title/tt0821462/

好恶心, 没想到韩石圭会参演这样的电影。
不过刚开始那一小段很不错。
4

发表在 电影评论 | 留下评论

大电影之数百亿, 2006

大电影之数百亿, 2006

搞的电影没有想像中多,也没有想像中恶。。。

5

发表在 电影评论 | 留下评论

Google的病毒式营销

Google AdSense广告收入是Google收入的主要来源之一。
Google AdSense让站长发布其广告,与站长瓜分收益,同时又让以重金为酬,让站长向其它站长或公司推荐AdSense和与其相对的广告收集项目AdWords. 站长们一传十,十传百, 不用专门的推销人员,省下管理了人员,却带来乘方式的回报。这种新式的病毒式营销既与Google这类早去蓬勃的信息产业类型门当户对, 又低耗高效, 实在是高!

Google在其它领域使用的病毒式营销
Gmail的邀请式注册

病毒式营销(viral marketing/viral advertising)

self-replicating viral processes
analogous to the spread of pathological
to obtain a large number of interested people at a low cost.

Word of Mouth Marketing (WOMM)

发表在 信息处理 | 留下评论

Babel,2006

Babel,2006

http://www.imdb.com/title/tt0449467/
今天去书店看到一本名为

的书,可能很是暢销,被摆在了电梯口。
看来很多人都发现这个世界越来越小了。
我也很想说明万物是关联的,用电影,告诉大家,今天在街上和你擦肩而过的,今天之前你不认识,今天之后你们或许也永远没有机会再次相见的人,却可能是和你关联着的。

感觉这片的结构是这个意思,但内容却比较分散。两年前(?)类似的电影<Crash>给我的印象好一些。

7

Babel,2006
繁华的日本都市

Babel,2006
这是一套很爽的房子,下面跟着电影镜头重点参观一下,看点是它的阳台

Babel,2006
透过窗户可以看到都市夜景

Babel,2006
绕过那个窗户可以出到阳台

Babel,2006
阳台上看到的美丽夜景

Babel,2006
偶尔阳台本身也可以成为风景

Babel,2006
大厦远景(左部那橦),那套房子是顶层(31楼或以上楼层)右角

发表在 电影评论 | 一条评论