Liu 的个人资料唯有仰望是真实的照片日志列表更多 工具 帮助

日志


2007/5/30

换音乐了

每次上kola同学的博,大晚上的就想说一个字,真xxx的2,
于是,我决定也换成它

之前一个文章的续(zz)

marketing.jpg

 

You’re a man and you see a gorgeous woman at a party.You go up to her and say, “I’m fantastic in bed,” That’s —Direct Marketing.

You’re at a party with a bunch of friends and see a gorgeous woman. One of your friends goes up to her and pointing at you says,”He’s fantastic in bed,” That’s—Advertising.

You see a gorgeous woman at a party. You go up to her and get her telephone number. The next day you call and say, “Hi, I’m fantastic in bed,” That’s — Telemarketing.

You’re at a party and see a gorgeous woman. You get up and straighten your tie. You walk up to her and pour her a drink and then say, “By the way, I’m fantastic in bed,” That’s —Public Relations.


You’re at a party and see a gorgeous woman. She walks up to you and says, “I hear you’re fantastic in bed,” That’s — Brand Recognition.


You’re at a party and see a gorgeous woman. You talk her into going home with your friend - That’s a —-Sales Rep.


Your friend can’t satisfy her so he calls you - That’s — Tech Support.


You’re on your way to a party when you realize that there could be gorgeous women in all these houses you’re passing. So you climb onto the roof of one situated toward the center and shout at the top of your lungs, “I’m fantastic in bed!” That’s–Junk Mail。

2007/5/29

19 Rails Tricks Most Rails Coders Don't Know(zz)

Post by Peter Cooper

Permanent Link  |   book mark 19 Rails Tricks Most Rails Coders Don't Know in del.icio.usDel.icio.us  |   See this page in technoratiCosmos

When looking at my own Rails code and that of the community as a whole, I often see places where certain Rails techniques could have been used, but weren't. As much for my own memory as yours, I thought I'd list down some Rails tricks and tips that can make your application or code more efficient:

Benchmark logic in your controller actions - It's really easy. Use the benchmark class method available on all your models like this:

User.benchmark("adding and deleting 1000 users") do
	1000.times do
		User.create(:name => 'something')
		x = User.find_by_name('something')
		x.destroy
	end
end

Of course, your code would be a lot better ;-) The regular SQL logs are not shown when within the benchmark sections. Only the benchmark results are shown.

Nested-Set

acts_as_nested_set
- Almost everyone is familiar with acts_as_tree, but acts_as_nested_set snuck into Rails quietly. It's much like acts_as_tree, but with the added benefit that you can select all of the children (and their own descendants) of a node with a single query. A list of the instance methods is available.

Easier collections with to_proc - Sick of writing things like post.collect { |p| p.title } or post.select { |p| p.activated? }.collect{ |p| p.title} ? A little Ruby hackery that allows you to convert symbols into proc references makes it easy. You can write post.collect(&:title) or post.select(&:activated?).collect(&:title) instead! Learn a lot more about this.

Convert arrays to sentences in views - If you were collecting a bunch of names to be shown in a view, you might end up with an array like ['Peter', 'Fred', 'Chris'], and joining these with commas and inserting 'and' before the final one is a common pain. Not so, if you use the array method to_sentence as provided in Rails. names.to_sentence would return Peter, Fred, and Chris.

Send files back to the user - Usually, static files can be retrieved by using the direct URL and circumventing your Rails application. In some situations, however, it can be useful to hide the true location of files, particularly if you're sending something of value (e-books, for example). It may be essential to only send files to logged in users too. send_file makes it possible. It sends files in 4096 byte chunks, so even large files can be sent without slowing the system down.

Iterating through page elements with RJS - Changing page elements with RJS is easy, but what if you don't know exactly which elements you want to change, and would instead prefer to address them with CSS queries? You can with RJS's select method. For example: page.select('#items li').each { |item| item.hide } . Powerful stuff!

Check for existence - When doing a Model.find(id), an exception can be returned if the item with an id of 'id' doesn't exist. If you want to avoid this, use Model.exists?(id) first to get a true or false for whether that item exists or not.

Number helpers for common number tasks - All of these number helpers aren't commonly used but provide great shortcuts: number_to_currency(1234567.948) # => $1,234,567.95 or human_size(1234567890) # => 1.1GB or number_with_delimiter(999999999) # => 999,999,999. There are others.

Testing different route configurations easily - with_routing is a test helper that allows you to temporarily override the default 'routes' in routes.rb for test purposes. Demonstration:

with_routing do |set|
  set.draw { set.connect ':controller/:id/:action' }
  assert_equal(
     ['/content/10/show', {}],
     set.generate(:controller => 'content', :id => 10, :action => 'show')
  )
end

You can learn a little more here.

Get lots of info about requests - Checking request.post? and request.xhr? are popular ways to look for POST and AJAX requests, but some of the other request methods are lesser used. For example: request.subdomains can return an array of subdomains that you could use as part of your authentication scheme, request.request_uri returns the full local request URL, request.host returns the full hostname, request.method returns the HTTP method as a lowercase symbol, and request.ssl? returns true if it's an HTTPS / SSL request.

Improving session performance even more than with ActiveRecord - By default, Rails stores sessions on the local file system. Many users change this to using ActiveRecordStore to store sessions in the database. An even faster alternative is to use Memcached to store sessions, but that takes a lot to set up (and isn't available unless you run your own servers, etc). But you can get faster than ActiveRecordStore by using Stefan Kaes' SQLSessionStore. It circumvents the inefficiencies of ActiveRecordStore using his own direct SQL technique to store sessions.

Caching unchanging data at application startup - If you have data that doesn't change between application restarts, cache it in a constant somewhere. For example, you might have a YAML or XML file in /config that stores application configuration data, and you could load it into a constant in environment.rb, making lookups quick and easy application-wide.

Check your views are rendering valid HTML / XHTML - It's not for everyone, but if your output validates as correct HTML / XHTML, it's a sign your views are going to render properly. Scott Raymond has developed a assert_valid_markup test helper that you can use from your functional tests.

Cleaner HTML output testing - Combine why's Hpricot HTML parser and a special test extension, and you can have powerful tests like so: assert_equal "My title", tag('title') or assert element('body').should_contain('something'). This might be ideal for developing tests to test user built templates. In any case, it's nicer than assert_tag!

Run long-running tasks separately in the background - BackgrounDRb is a small framework, by Ezra Zygmuntowicz, that runs as a daemon in the background that can accept tasks your Rails application sends to it, and whose execution is totally separate to your Rails app. It's extremely powerful, and useful for many tasks such as sending hundreds of e-mails, fetching URLs, and other things you don't want to slow down the request times for your main app. One great demo is to develop a task that increments a variable by 1 and sleeps for 1 second. You can then make a Rails method that queries the variable, and see the distinct separation. Learn more.

Make ids in URLs more user friendly - Override the to_param method on your model and return something like "#{id}-#{title.gsub(/[^a-z0-9]+/i, '-')}" to get URLs like so: http://yoursite.com/posts/show/123-post-title-goes-here .. Much nicer for users, and you don't need to change anything with Post.find(params[:id]) as the non numeric characters will be stripped automagically! Get a full explanation here.

Separate out slices of functionality into Engines - Everyone's heard of Rails' plugins, but pitifully few are using Rails Engines! Rails Engines are like plugins on steroids. They can contain their own models, controllers, and views, and integrate with any applications you run them under. This allows you to split out common fragments of functionality (login, user management, content management, etc.) into separate 'engines' to use in your different projects within minutes. No more writing dull login code! Rails Engines is a big deal, but it should be a far bigger deal.

Calculations - Do you want to get maximums, minimums, averages, or sums for data in your tables? ActiveRecord's Calculations make these all possible. Person.average('age'), Person.maximum(:age, :group => 'last_name'), and Order.sum('total') all become a reality. Most can be customized pretty deeply with extra options, so go read about them if they're not already part of your code.

XML or YAML output of your data - It's not necessarily to create a Builder .rxml template for all XML output. ActiveRecord has a to_xml method that will output the object or result set in XML format. It works with simple objects, to complete tables (like User.find(:all).to_xml). Using includes works too, as with Post.find(:all, :include => [:comments]).to_xml. YAML is also supported, by using to_yaml instead.

2007/5/28

太土鳖了

ft啊,原来是这样写

os.path.join("home", "ayuer", "test", "whatever")

而不是

os.path.join(os.path.join(os.path.join("home", "ayuer"), "test"), "whatever")

不注重细节的毛病,我反省啊反省...

Introduction to BackgrounDRb(zz)

http://www.infoq.com/articles/BackgrounDRb

Posted by Ezra Zygmuntowicz on Jun 27, 2006 03:09 AM

Ruby on Rails is a great framework for developing many diverse types of web applications. As the problem domain of these web applications expands, you may need to run computationally intensive or long running background tasks. This poses a problem in that you are constrained to work within the request/response cycle of HTTP. So how can you run these long background tasks without your web server timing out? And how do you display the progress to your users?

Enter BackgrounDRb. This is a Rails plugin I wrote recently as one way to solve this problem. Ruby includes DRb (Distributed Ruby) as part of the standard library. DRb provides a simple API for publishing and consuming Ruby objects over TCP/IP networks or unix domain sockets. BackgrounDRb is a small framework that facilitates running background tasks in a separate process from Rails, thereby decoupling them from the request/response cycle. With DRb you can manage your tasks from Rails using hooks for progress bars or status updates to your users.

The BackgrounDRb server works by publishing a MiddleMan object. This object is the manager for your worker classes. It holds a @jobs hash composed of { job_key => running_worker_object } pairs and a @timestamps hash composed of { job_key => timestamp } pairs. The MiddleMan object straddles the interface between the DRb server and your Rails application. Here is a simple diagram to show the architecture.

This is a generic worker class as created by the worker generator provided by the plugin.

$ script/generate worker Foo
class FooWorker < BackgrounDRb::Rails
def do_work(args)
# This method is called in its own new thread when you
# call new worker. args is set to :args
end

end

When your FooWorker object is instantiated from rails via MiddleMan, the do_work method is automatically run in its own thread. We use a thread here so rails does not wait for the do_work method to finish before it continues on.

With BackgrounDRb, you usually create a new worker object with an AJAX request. Your view can then use periodically_call_remote to fetch the progress of your job and display it however you like. Let's flesh out the FooWorker class and show how you would create a new FooWorker object and retrieve its progress from within a rails controller.

class FooWorker < BackgrounDRb::Rails
attr_reader :progress
def do_work(args)
@progress = 0
calculate_the_meaning_of_life(args)
end
def calculate_the_meaning_of_life(args)
while @progress < 100
# calculations here
@progress += 1
end
end
end

Now in the controller:

class MyController < ApplicationController
def start_background_task
session[:job_key] =
MiddleMan.new_worker(:class => :foo_worker,
:args => "Arguments used to instantiate a new FooWorker object")
end
def get_progress
if request.xhr?
progress_percent = MiddleMan.get_worker(session[:job_key]).progress
render :update do |page|
page.call('progressPercent', 'progressbar', progress_percent)
page.redirect_to( :action => 'done') if progress_percent >= 100
end
else
redirect_to :action => 'index'
end
end
def done
render :text => "

Your FooWorker task has completed

"
MiddleMan.delete_worker(session[:job_key])
end
end

And in your start_background_task.rhtml view file you could use something like this:

    <html>
	      <head>
	       <style type="text/css">
	         .progress{
	           width: 1px;
	           height: 16px;
	           color: white;
	           font-size: 12px;
	           overflow: hidden;
	           background-color: #287B7E;
	           padding-left: 5px;
	         }
	       </style>
	       <script type="text/javascript">
	         function progressPercent(bar, percentage) {
	           document.getElementById(bar).style.width =  parseInt(percentage*2)+"px";
	           document.getElementById(bar).innerHTML= "<div align='center'>"+percentage+"%</div>"
	         }
	       </script>
	      </head>
	       <body>
	        <div id='progressbar' class="progress"></div>
	        <%= periodically_call_remote(:url => {:action => 'get_progress'}, :frequency => 1) %>
	       </body>
    </html>

MiddleMan.new_worker returns a randomly generated job_key that you can store in the session for later retrieval. If you want to specify a named key instead of using the generated key you can do so like this:

 # This will throw a BackgrounDRbDuplicateKeyError if the :job_key already exists.
 MiddleMan.new_worker(:class => :foo_worker,
                           :job_key => :my_worker,
                           :args => "Arguments used to instantiate a new FooWorker object")

      MiddleMan.get_worker :my_worker

Upon instalation, the plugin writes a config file into RAILS_ROOT/config/backgroundrb.yml. In this file there is a load_rails config option. If this is set to true then you will be able to use your ActiveRecord objects in your worker classes. When you start the server it will use your already existing database.yml file for database connection details.

This plugin can also be used for caching large or compute-intensive objects including ActiveRecord objects. You can store rendered views or large queries in the cache. In fact you can store any text or object that can be marshalled. Here is how you would use the cache:

# Fill the cache
@posts = Post.find(:all, :include => :comments)
MiddleMan.cache_as(:post_cache, @posts)
# OR
@posts = MiddleMan.cache_as :post_cache do
Post.find(:all, :include => :comments)
end

# Retrieve the cache
@posts = MiddleMan.cache_get(:post_cache)
# OR
@posts = MiddleMan.cache_get(:post_cache) { Post.find(:all, :include => :comments) }

MiddleMan.cache_get takes an optional block argument. If the cache located at the :post_cache key is empty, the results of evaluating the block are placed in the cache and assigned to @posts. If you don't supply a block and the cache is empty it will return nil.

In the current implementation, you are responsible for expiring your own caches and deleting your own workers from the main pool. This works two ways. You can either explicitly call MiddleMan.delete_worker(:job_key) or MiddleMan.delete_cache(:cache_key). There is also a MiddleMan.gc! method that takes a Time object and deletes all jobs with a time-stamp older than the one specified. Here is a script that can be run from cron to expire jobs older than 30 minutes:

#!/usr/bin/env ruby
require "drb"
DRb.start_service
MiddleMan = DRbObject.new(nil, "druby://localhost:22222")
MiddleMan.gc!(Time.now - 60*30)

In the near future there will be a timing mechanism built into BackgrounDRb. This will allow for jobs and garbage collection to be run at scheduled times and for specifying a time-to-live parameter when you create new jobs or caches.

There are Rake tasks as well as plain Ruby command line scripts to start and stop the daemon. On OS X, linux or BSD you can use the Rake tasks to start and stop the server:

$ rake backgroundrb:start
$ rake backgroundrb:stop

On Windows you currently have to keep a console window open while you run the backgroundrb server (Hopefully this will change in the near future). So on Windows, to start the daemon you would open a console and run the command like this:

> ruby script\backgroundrb\start
# ctrl-break to stop

So what are a few real world use cases, you ask? Here is a small list of things I am currently using BackgrounDRb for:

  • Downloading and caching RSS feeds for a feed aggregator.
  • Screen scraping automation using watir to drive a web browser that navigates to other websites in the background to collect information.
  • Automating Xen VPS creation and sysadmin tasks.
  • Creating indexes in the background for Hyper Estraier and ferret search technologies.
  • Bridging Rails and IRC bots.

Plans for the future include the ability to fork new processes to handle larger jobs that require their own Ruby interpreter instance. Also work needs to be done to let BackgrounDRb run as a Windows service. Anyone who is familiar with Windows services that can offer some help here would be greatly appreciated. Suggestions and patches are also welcome.

  • rubyforge project
  • Blog
  • install as plugin: script/plugin install svn://rubyforge.org//var/svn/backgroundrb

Date and Time Representation in Python(zz)

http://seehuhn.de/pages/pdate

Jochen Voss (last update: 2007-05-27)

There are many different ways to represent date and time in Python programs. This page gives an overview over the different methods and explains how to convert between different representations. The main focus of this page is on how to represent points in time often assuming some fixed, local time zone. This is used for example when analysing log files. I will not explain here how to convert between different time zones or between different calendars.

Date and Time representations

ISO 8601 Time Representation

The international standard ISO 8601 describes a string representation for dates and times. Two simple examples of this format are

2007-03-04 20:32:17
20070304T203217

(which both stand for the 4th of March 2007, a bit after half past eight) but the format also allows for sub-second resolution times and to specify time zones. This format is of course not Python specific, but it is good for storing dates and times in a portable format. Details about this format can be found on Markus Kuhn's ISO 8601 page and on Gary Houston's ISO 8601:1988 Date/Time Representations page.

I recommend use of this format to store times in files.

One way to get the current time in this representation is to use strftime from the time module in the Python standard library:

>>> from time import strftime
>>> strftime("%Y-%m-%d %H:%M:%S")
'2007-03-03 22:14:39'
Python datetime Objects

The datetime module of the Python standard library provides the datetime class.

I recommend use of this format, when possible, to represent times in Python programs.

One way to get the current time in this representation is to use the now method of the datetime class in the Python standard library:

>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2007, 3, 3, 22, 20, 11, 443849)
Unix Time

The traditional way to describe times on a Unix system is to give the number of seconds elapsed since the beginning of the year 1970. Sometimes this count includes leap seconds and sometimes it does not. Traditionally this number is an integer, but of course one can get sub-second resolution by using floating point numbers here.

One way to get the current time in this representation is to use time from the time module in the Python standard library. This function returns the number of seconds elapsed since the beginning of the year 1970 in UTC as a float:

>>> from time import time
>>> time()
1172960204.226908
Broken Down Time

This is what is represented by struct_time objects in Python (and similarly by struct tm in the C standard library). Time is represented as a tuple consisting of the following fields:

  1. the year as a four-digit number, e.g. 2007
  2. the month (1, 2, …, 12)
  3. the day of the month (1, 2, …, 31)
  4. hour (0, 1, …, 23)
  5. minutes (0, 1, …, 59)
  6. seconds (0, 1, …, 61 where 60 and 61 are used for leap seconds)
  7. week day (0=Monday, 1=Tuesday, …, 6=Sunday)
  8. day of the year (1, 2, …, 366)
  9. daylight saving time information (0, 1, or -1)

It is not possible to get sub-second resolution in this representation. For details see the time module description of the Python standard library.

One way to get the current time in this representation is to use localtime from the time module in the Python standard library:

>>> from time import localtime
>>> localtime()
(2007, 3, 3, 22, 13, 27, 5, 62, 0)
The Egenix mxDateTime Class

Egenix provides the mxDateTime class as part of their mx extensions for Python. This class seems to be relatively similar to the standard datetime class, but it provides a parser for ISO 8601 date strings.

One way to get the current time in this representation is to use the now constructor from the mx.DateTime module:

>>> from mx.DateTime import now
>>> now()
<DateTime object for '2007-03-03 22:51:13.37' at 52a2c0>
The Matplotlib Date Representation

The very nice matplotlib graphing library has support for using dates to locate data in plots. The library represents dates/times as single floating point numbers and provides functions num2date and date2num to convert between Python datetime objects and the matplotlib representation. The numbers represent days but I am not sure which day in time is matplotlib day 0.

One way to get the current time in this representation is as follows:

>>> from matplotlib.dates import date2num
>>> from datetime import datetime
>>> date2num(datetime.now())
732738.96073077701

Date Conversions

Since I recommend to normally use the standard Python datetime class to store times in Python programs, I only provide recipes here to convert between datetime and any of the other representations here. A summary of the described methods can be found in table 1 below.

Conversion between ISO Time Representation and datetime

Unfortunately there is no easy way to parse full ISO 8601 dates using the Python standard library. If you know the exact format of the date string in advance, you can use the strptime constructor of the datetime class (new in Python version 2.5):

>>> from datetime import datetime
>>> datetime.strptime("2007-03-04 21:08:12", "%Y-%m-%d %H:%M:%S")
datetime.datetime(2007, 3, 4, 21, 8, 12)

There are several parsers available in external modules. The most robust one I found is contained in the Egenix mxDateTime module:

>>> from mx.DateTime.ISO import ParseDateTimeUTC
>>> from datetime import datetime
>>> x = ParseDateTimeUTC("2007-03-04 21:08:12")
>>> datetime.fromtimestamp(x)
datetime.datetime(2007, 3, 4, 21, 8, 12)

Another one is contained in the PyXML package:

>>> from xml.utils.iso8601 import parse
>>> parse("2001-11-12T12:13:00+01:00")
1005563580.0

Conversion from datetime objects is easy using the strftime method:

>>> from datetime import datetime
>>> t = datetime.now()
>>> t.strftime("%Y-%m-%d %H:%M:%S")
'2007-03-04 00:15:12'
Conversion between Unix times and datetime

To convert a Unix time stamp to datetime use the fromtimestamp constructor:

>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)

To convert a datetime object into a Unix time stamp, one has to first convert it into a struct_time:

>>> from datetime import datetime
>>> from time import mktime
>>> t=datetime.now()
>>> mktime(t.timetuple())+1e-6*t.microsecond
1172970859.472672
Conversion between struct_time and datetime

struct_time objects can be converted to datetime objects using the normal datetime constructor:

>>> from time import localtime
>>> from datetime import datetime
>>> x = localtime()
>>> datetime(*x[:6])
datetime.datetime(2007, 3, 4, 1, 0, 39)

datetime objects can be converted back to struct_time using the timetuple class method:

>>> from datetime import datetime
>>> t = datetime.now()
>>> t.timetuple()
(2007, 3, 4, 1, 3, 18, 6, 63, -1)
Conversion between the Egenix mxDateTime class and datetime

mxDateTime objects can be converted to datetime via the Unix time stamp format:

>>> from mx.DateTime import now
>>> from datetime import datetime
>>> x = now()
>>> datetime.fromtimestamp(x)
datetime.datetime(2007, 3, 4, 1, 14, 19, 472672)

The reverse conversion is a bit awkward:

>>> from mx.DateTime import DateTime
>>> from datetime import datetime
>>> t = datetime.now()
>>> DateTime(t.year,t.month,t.day,t.hour,t.minute,t.second+1e-6*t.microsecond)
<DateTime object for '2007-03-04 01:14:19.47' at 104a368>
Conversion between the matplotlib time representation and datetime

This conversion is straight-forward using the converter functions provided by matplotlib:

>>> from matplotlib.dates import num2date
>>> num2date(732738.96073077701)
datetime.datetime(2007, 3, 3, 23, 3, 27, 139133, tzinfo=<UTC>)

and

>>> from matplotlib.dates import date2num
>>> from datetime import datetime
>>> t = datetime.now()
>>> date2num(t)
732738.96073077701
Conversion Summary

Table 1 summarises the conversion methods discussed in this chapter.

Time Representation
conversion to datetime
conversion from datetime

ISO strings
Difficult with the standard library. Use either strptime, the Egenix ISO module or PyXML's xml.utils.iso8601 module.
t.strftime("%Y-%m-%dT%H:%M:%S")

Unix time
datetime.fromtimestamp(x)
mktime(t.timetuple())+1e-6*t.microsecond

struct_time
datetime(*x[:6])
t.timetuple()

mxDateTime
datetime.fromtimestamp(x)
see text

matplotlib
num2date(x)
date2num(t)

Table 1. Summary of the different conversions to and from the Python standard library's datetime class. The value t always stands for a value in the representation given in the first column, x denotes datetime objects.

References

2007/5/24

类天使(zz)

象音乐             都为你痴狂
象棋子             静静在一旁
象地球             到处是磁场
象蝙蝠             不能见太阳
象祈祷             神解开迷茫
象文字             记录的翅膀
象死神             把握着死亡
象湿润             在眼角流淌
象寂寞             侵蚀了力量
象他们             粘着象蜜糖

象你们             为爱不投降
象我们             一世不心伤

那么。。。。。。。。
象情人             好好爱一场
象爱人             那里是天堂
alors........         类天使

2007/5/22

XPath and WATiR(zz)

nice, but i'm still looking for ways to do other things than click, we are good at point&click, don't we:)

XPath and WATiR

by Angrez on http://angrez.blogspot.com/2006/06/xpath-and-watir...

WATiR provides very simple API's for functional testing an Web Application. With even limited scripting experience with Ruby you'll be able to create scripts to test your application. It provides API's for accessing almost all common elements on an HTML page. It allows you to access elements on the basis of some pre-defined attributes.

Now, there were few things that were lacking:
1. What if you have a element which you can't access using those pre-defined attributes?
2. What if there is no API for a particular HTML element?
3. What if you want to access some element depeding upon some other element? For e.g.: Accessing which has a image with some pre-defined "src" attribute.

The solution to all above problems is using XPATH to access these elements. XPATH query is a well defined and very powerful way for addressing elements in an XML document. If the HTML markup of the page is well-formed we can treat it as XML document and use XPATH query to select an element. So we introduced a new attribute to address such elements called ":xpath".

Will explain the usage of XPATH with examples for each of the above problem.

Problem1: Accessing elements using attributes that are not pre-defined:

Suppose you have an HTML "select" element like:

<select foo="bar"> <option value="1">1< /option> < /select>

Now "foo" is not standard attribute but browser will simply ignore it. Now if you want to access this element you need to use XPATH query. So to access element the statement will look like:

element = browser.select(:xpath, "//select[@foo='bar']")

The above statement will return you the desired element.

Problem2: Accessing elements for which there is no class in WATiR:

Suppose you have an HTML "map" element on your page. Now for "map" element there is no class in WATiR which you can use to access the elements. For such elements you can use the function "element_by_xpath" which takes in "XPATH query" and return you the desired element.

Example:

Suppose you have a "map" like this:

< map name="top_menu_map" id="top_menu_map">
< area shape="rect" coords="18,2,62,17" ref="http://engin.com.au/public/index.htm" target="_self" alt="engin home"> < /area >
< /map>

Now you want to access "area" element. You can do it using the function described above. So to access element the statement will look like:

browser.element_by_xpath("//area[contains(@href , 'signup.htm')]").click()

Problem3: Accessing elements with respect to other elements:

Suppose you need to access an element(which doesn't have any fix attribute) based on position of some other element(which has a fix attribute). WATiR doesn't provide any direct way to access element based on position of other element. So what you can do is:
1. Go to the element which is fixed using WATiR classes. Then, traverse the DOM tree using the underlying "ole_object" for that element.
OR
2. Supply an XPATH query that selects the element based on the position of other element.

Example:

Suppose you have an HTML like this:

<table>
<tr>
<td> <img src="1.jpg"> <input type="button"> < /td>
<td> <img src="2.jpg"> <input type="button"> < /td>
<td> <img src="3.jpg"> <input type="button"> < /td>
<td> <img src="4.jpg"> <input type="button"> < /td>
< /tr>
<tr>
<td> <img src="5.jpg"> <input type="button"> < /td>
<td> <img src="6.jpg"> <input type="button"> < /td>
<td> <img src="7.jpg"> <input type="button"> < /td>
<td> <img src="8.jpg"> <input type="button"> < /td>
< /tr>
< /table>
Now suppose you want to click on button that has image with src="7.jpg" in front of it. So you have two ways to do it:
1. First find out the table using :index attribute which is always dangerous because page structure may change. Then iterate over rows and then cells to find which cell contains that image. Then in that cell find the button and then click it.
OR
2. You can give an "XPATH " query to select the element. So your statement will look like this:

browser.button(:xpath, "//img[@src='7.jpg']/input").click()

Problems with XPATH:
The only problem with XPATH is that its a bit slower while selecting the elements on the page. We are working on improving the time it takes to select the element.
So to summarize, using XPATH query you get extreme powerful selection mechanism which will allow you select those elements also that are other wise difficult to select using WATiR native selection mechanism.

2007/5/21

RAILSCONF 05.17-20.07 Portland, Oregon

2007 Presentations

Presentation files will be made available after the session has concluded and the speaker has given us the files. Check back if you don't see the file you're looking for—it might be available later! (However, please note some speakers choose not to share their presentations.)

Adding Tests to Legacy Rails Apps
Speaker(s): Evan (Rabble) Henshaw-Plath
Presentation Date: 05/18/2007
View full description
Download presentation files

Building and Working with Static Sites in Ruby on Rails
Speaker(s): Ben Scofield
Presentation Date: 05/18/2007
View full description
Download presentation files

Building Community-focused Apps with Rails
Speaker(s): Dan Benjamin
Presentation Date: 05/18/2007
View full description
Download presentation files

Business Intelligence with Rails: "Done in 45 Minutes!"
Speaker(s): Soren Burkhart
Presentation Date: 05/19/2007
View full description
Download presentation files

Clean Code
Speaker(s): Robert Martin
Presentation Date: 05/18/2007
View full description
Download presentation files

Custom Rails Helpers: Keeping Your Views DRY
Speaker(s): Glenn Vanderburg
Presentation Date: 05/19/2007
View full description
Download presentation files

Doing REST Right
Speaker(s): Scott Raymond
Presentation Date: 05/18/2007
View full description
Download presentation files

Full-stack Web App Testing with Selenium and Rails
Speaker(s): Brian Takita Alex Chaffee
Presentation Date: 05/18/2007
View full description
Download presentation files

Mapping Rails to Legacy Systems
Speaker(s): Stephen Becker Devon Jones
Presentation Date: 05/18/2007
View full description
Download presentation files

Rails Routing Roundup
Speaker(s): David A. Black
Presentation Date: 05/17/2007
View full description
Download presentation files

Scale Rails Without Bounds on Amazon EC2
Speaker(s): Thorsten von Eicken Gary Burke
Presentation Date: 05/18/2007
View full description
Download presentation files

Scaling a Rails Application from the Bottom Up
Speaker(s): Jason Hoffman
Presentation Date: 05/17/2007
View full description
Download presentation files

Standing on the Shoulders of Giants
Speaker(s): Adam Keys
Presentation Date: 05/18/2007
View full description
Download presentation files

When V is for Vexing: Patterns to DRY Up Your Views
Speaker(s): Bruce Williams
Presentation Date: 05/17/2007
View full description
Download presentation files

这么近,那么远...(是我故意反过来的)

独白(张):离开书店既时候,我留低左把遮,希望拎左佢返屋企个个系你啦……….
这么远那么近
曲:张国荣词:黄伟文编:李端娴@人山人海
独白:张国荣
专辑:ep:cross over
独白(张):2000年零时零分,电视直播纽约时代广场既庆祝人潮,我有无见过你?
黄:愈夜愈看愈美丽但谁会来电
当我凝视我的脸几亿人在爱恋
画面在脑内乍现波斯湾最南面
灯塔中谁人在约会我不必真正遇见
是谁在对岸露台上对望互传着渴望
你熄灯我点烟
隔住块玻璃隔住个都市自言自语地共你在热恋
在池袋碰面在南极碰面或其实根本在这大楼里面
但是每一天当我在左转你便行向右终不会遇见
独白(张):如果你识我既话,我今年会收到乜野圣诞礼物?
独白(张):呢间餐厅呢只水杯你会唔会用过?
黄:命运就放在桌上地球仪正旋动
找个点凭直觉按下去可不可按住你?
是谁在对岸露台上对望互传着渴望
你熄灯我点烟
隔住块玻璃隔住个都市自言自语地共你在热恋
在池袋碰面在南极碰面或其实根本在这大楼里面
但是每一天当我在左转你便行向右终不会遇见
独白(张):我由布鲁塞尔坐火车去阿姆斯特丹,望住是窗外面飞过既几十个小镇
独白(张):几千里土地几千万个人
独白(张):我怀疑我地人生里面唯一相遇既机会已经错过左
黄:喜欢的歌差不多吧(李泰祥既新唱片你买左未?)
对你会否曾打错号码(我怀疑果次把声好沙个个就系你)
我坐这里你坐过吗?(我认得你d字迹)
偶尔看著同一片落霞(佢由亚洲一直飘到南美洲)
是谁在对岸露台上对望互传着渴望你熄灯我点烟
隔住块玻璃隔住个都市自言自语地共你在热恋
月台上碰面月球上碰面或其实根本在这道墙背面
或是有一天当你在左转我便行向右都不会遇见
******(音乐伴奏)******
独白(张):我买左两本「几米」既漫画,另一本将来送俾你

2007/5/19

Because you are ugly

You always want something more,
you never treasure anything you got,
you always want to be both in and out of this fortress besieged,
you always always make the pity look hopping someone would care,
why should anyone gives a shit,
why you live at all...
2007/5/16

14 rules for fast web pages(zz)

 web2.0 Expo挺有趣的,推荐去翻翻那些presentations。

Steve Souders of Yahoo's "Exceptional Performance Team" gave an insanely great presentation at Web 2.0 about optimizing website performance by focusing on front end issues. Unfortunately I didn't get to see it in person but the Web 2.0 talks have just been put up and the ppt is fascinating and absolutely a must-read for anyone involved in web products.

His work has been serialized on the Yahoo user interface blog, and will also be published in an upcoming O'Reilly title (est publish date: Sep 07).

We have so much of this wrong at topix now that it makes me want to cry but you can bet I've already emailed this ppt to my eng team. :) Even if you're pure mgmt or product marketing you need to be aware of these issues and how they directly affect user experience. We've seen a direct correlation between site speed and traffic.

This is a big presentation, with a lot of data in it (a whole book's worth apparently), but half way through he boils it down into 14 rules for faster front end performance:

  1. Make fewer HTTP requests
  2. Use a CDN
  3. Add an Expires header
  4. Gzip components
  5. Put CSS at the top
  6. Move JS to the bottom
  7. Avoid CSS expressions
  8. Make JS and CSS external
  9. Reduce DNS lookups
  10. Minify JS
  11. Avoid redirects
  12. Remove duplicate scripts
  13. Turn off ETags
  14. Make AJAX cacheable and small

The full talk has details on what all of these mean in practice. The final slide of the deck is a set of references and resources, which I've pulled out here for clickability:

book: http://www.oreilly.com/catalog/9780596514211/
examples: http://stevesouders.com/examples/
image maps: http://www.w3.org/TR/html401/struct/objects.html#h-13.6
CSS sprites: http://alistapart.com/articles/sprites
inline images: http://tools.ietf.org/html/rfc2397
jsmin: http://crockford.com/javascript/jsmin
dojo compressor: http://dojotoolkit.org/docs/shrinksafe
HTTP status codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
IBM Page Detailer: http://alphaworks.ibm.com/tech/pagedetailer
Fasterfox: http://fasterfox.mozdev.org/
LiveHTTPHeaders: http://livehttpheaders.mozdev.org/
Firebug: http://getfirebug.com/
YUIBlog: http://yuiblog.com/blog/2006/11/28/performance-research-part-1/
http://yuiblog.com/blog/2007/01/04/performance-research-part-2/
http://yuiblog.com/blog/2007/03/01/performance-research-part-3/
http://yuiblog.com/blog/2007/04/11/performance-research-part-4/
YDN: http://developer.yahoo.net/blog/archives/2007/03/high_performanc.html
http://developer.yahoo.net/blog/archives/2007/04/rule_1_make_few.html

2007/5/15

Why we buy stuff

有时候,买东西是bt的为了满足自己的拥有欲和支配感。
突然想到有次问多年的好友为什么要抽烟呢, 他说拿着烟的时候还有一点点对手里的东西的完全控制的感觉, 当时没怎么明白。

2007/5/13

A force de solitude(因为孤独)

Tu attends que l’amour ou la haine
Arrive et te surprenne
Mais tes jours et tes nuits
Sont pareils
Tous les mêmes, idem
Qu’est-ce qui pourrait t’arriver ?
A force de solitude
T’as perdu l’habitude
De trouver les mots qu’il faudrait
A force de solitude
T’as perdu l’habitude
D’entendre les mots qui pourraient
Déchirer ton envie
Captiver ton regard
Te faire apercevoir
Toute la magie de la vie
Te donner un espoir
Mais ta vie qui passe
Te dépasse
Tu ne trouves toujours pas ta place
Et ici ou ailleurs
T’as l’impression
De connaitre par coeur
Qu’est-ce qui pourrait t’arriver ?
A force de solitude
T’as perdu l’habitude
De trouver les mots qu’il faudrait
A force de solitude
T’as perdu l’habitude
D’entendre les mots qui pourraient
Ensoleiller ta vie
Effacer de ta mémoire
Effacer t?t ou tard
Tous les chagrins d’aujourd’hui
Te donner envie d’y croire
Qu’est-ce qui pourrait t’arriver ?
A force de solitude
T’as perdu l’habitude
De trouver les mots qu’il faudrait
A force de solitude
T’as perdu l’habitude
D’entendre les mots qui pourraient
Délivrer tes envies
Captiver ton regard
Te faire apercevoir
Toute la lumières de la vie
Te ;donner un espoir
Ensoleiller ta vie
Effacer de ta mémoire
Effacer t?t ou tard
Tous les chagrins d’aujourd’hui
Te donner un espoir
Toute la magie de la vie
C’est simplement d’y croire.


你期待着爱与恨的来临
期待他们带给你奇遇
可你所有的白天和夜晚
都一样的平淡无奇
明天在你身上会发生什么?
因为孤独
你已不再习惯去找寻这句你需要的话
因为孤独
你已不再习惯去理解这句话的含义
而它却能够
燃起你的热情
吸引你的视线
让你感到生活中的奇迹/带给你希望
生活压倒了你
你总是找不到自己的位置
在这里或在别处
你总感到需要用心去明白
明天在你身上会发生什么?
因为孤独
你已不再习惯去找寻这句你需要的话
因为孤独
你已不再习惯去理解这句话的含义
而它却能够
照亮你的生活
迟早从你的记忆里抹去今日的忧伤
给你热情去相信
因为孤独
你已不再习惯去找寻这句你需要的话
因为孤独
你已不再习惯去理解这句话的含义
而它却能够
燃起你的热情
吸引你的视线
让你感到生命的光芒
带给你以希望
它能够
照亮你的生活
迟早从你的记忆里抹去今日的忧伤
带给你希望
只要你坚信
所有生命的奇迹都会降临。
 下载:
http://www.zj1015.com/song/333/05082_1.mp3

2007/5/10

将闷骚进行到底...

孤雁儿
藤床纸帐朝眠起,说不尽、无佳思。
沈香烟断玉炉寒,伴我情怀如水。
笛声三弄,梅心惊破,多少春情意。
小风疏雨萧萧地,又催下、千行泪。
吹箫人去玉楼空,肠断与谁同倚?
一枝折得,人间天上,没个人堪寄。

 

一剪梅
红藕香残玉簟秋。轻解罗裳,独上兰舟。云中谁寄锦书来?雁字回时,月满西楼。
花自飘零水自流。一种相思,两处闲愁。此情无计可消除,才下眉头,却上心头。

 

蝶恋花
暖日晴风初破冻,柳眼梅腮,已觉春心动。酒意诗情谁与共,泪融残粉花钿重。
乍试夹衫金缕缝,山枕斜欹,枕损钗头凤。独抱浓愁无好梦,夜阑犹翦灯花弄。

 

浣溪沙
莫许杯深琥珀浓,未成沈醉意先融,疏钟己应晚来风。
瑞脑香消魂梦断,辟寒金小髻鬟松,醒时空对烛花红。

 

点绛唇
寂寞深闺,柔肠一寸愁千缕。惜春春去,几点催花雨。
倚遍栏干,只是无情绪!人何处?连天衰草,望断归来路。

2007/5/7

The most distant way in the world


The most distant way in the world
is not the way from birth to the end.
it is when i sit near you
that you don't understand i love u.

The most distant way in the world
is not that you're not sure i love u.
It is when my love is bewildering the soul
but i can't speak it out.

The most distant way in the world
is not that i can't say i love u.
it is after looking into my heart
i can't change my love.

The most distant way in the world
is not that i'm loving u.
it is in our love
we are keeping between the distance.

The most distant way in the world
is not the distance across us.
it is when we're breaking through the way
we deny the existance of love.

So the most distant way in the world
is not in two distant trees.
it is the same rooted branches
can't enjoy the co-existance.

So the most distant way in the world
is not in the being sepearated branches.
it is in the blinking stars
they can't burn the light.

So the most distant way in the world
is not the burning stars.
it is after the light
they can't be seen from afar.

So the most distant way in the world
is not the light that is fading away.
it is the coincidence of us
is not supposed for the love.

So the most distant way in the world
is the love between the fish and bird.
one is flying at the sky,
the other is looking upon into the sea.

2007/5/5

......

古希腊有个神话,勒安得尔是阿比多斯的少年,他爱上了爱神在塞斯托斯的女祭司赫萝,每天晚上从阿比多斯游过赫勒斯谤海峡,到塞斯托斯去和她幽会,第二天早晨再游回阿比多斯。赫萝每晚在岛上塔楼挂灯为情人引路,有一次灯被暴风雨吹灭,勒安得尔在海上迷路,溺水而亡。赫萝发觉后亦跳海自尽。

 

有一对恋人去爬山,在快接近山顶的时候,小伙子不小心触到了老鹰的窝,脚下一滑坠入了山崖,姑娘看到伤心极了,她对着小伙子大喊“我爱你”,然后跳下了山崖。

我们为何在此?我们为何而来?

霍金2006年6月19日北京

 

根据中非Boshongo人的传说,世界太初只有黑暗、水和伟大的Bumba上帝。一天,Bumba胃痛发作,呕吐出太阳。太阳灼干了一些水,留下土地。他仍然胃痛不止,又吐出了月亮和星辰,然后吐出一些动物,豹、鳄鱼、乌龟、最后是人。

  这个创世纪的神话,和其它许多神话一样,试图回答我们大家都想诘问的问题:为何我们在此?我们从何而来?一般的答案是,人类的起源是发生在比较近期的事。人类正在知识上和技术上不断地取得进步。这样,它不可能存在那么久,否则的话,它应该取得更大的进步。这一点甚至在更早的时候就应该很清楚了。

  例如,按照Usher主教《创世纪》把世界的创生定于公元前4004年10月23日上午9时。另一方面,诸如山岳和河流的自然环境,在人的生命周期里改变甚微。所以人们通常把它们当作不变的背景。要么作为空洞的风景已经存在了无限久,要么是和人类在相同的时刻被创生出来。

  但是并非所有人都喜欢宇宙有个开端的思想。例如,希腊最著名的哲学家亚里士多德,相信宇宙已经存在了无限久的时间。某种永恒的东西比某种创生的东西更完美。他提出我们之所以看到发展处于这个情形,那是因为洪水或者其它自然灾害,不断重复地让文明回复到萌芽阶段。信仰永恒宇宙的动机是想避免求助于神意的干涉,以创生宇宙并启始运行。相反地,那些相信宇宙具有开端的人,将开端当作上帝存在的论据,把上帝当作宇宙的第一原因或者原动力。

  如果人们相信宇宙有一个开端,那么很明显的问题是,在开端之前发生了甚么?上帝在创造宇宙之前,他在做甚么?他是在为那些诘问这类问题的人准备地狱吗?德国哲学家伊曼努尔.康德十分关心宇宙有无开端的问题。他觉得,不管宇宙有无开端,都会引起逻辑矛盾或者二律背反。如果宇宙有一个开端,为何在它起始之前要等待无限久。他将此称为正题。另一方面,如果宇宙已经存在无限久,为甚么它要花费无限长的时间才达到现在这个阶段。他把此称为反题。无论正题还是反题,都是基于康德的假设,几乎所有人也是这么办的,那就是,时间是绝对的,也就是说,时间从无限的过去向无限的将来流逝。时间独立于宇宙,在这个背景中,宇宙可以存在,也可以不存在。

  直至今天,在许多科学家的心中,仍然保持这样的图景。然而,1915年爱因斯坦提出他的革命性的广义相对论。在该理论中,空间和时间不再是绝对的,不再是事件的固定背景。相反地,它们是动力量,宇宙中的物质和能量确定其形状。它们只有在宇宙之中才能够定义。这样谈论宇宙开端之前的时间是毫无意义的。这有点儿像去寻找比南极还南的一点没有意义一样。它是没有定义的。

  如果宇宙随时间本质上不变,正如20世纪20年代之前一般认为的那样,就没有理由阻止在过去任意早的时刻定义时间。人们总可以将历史往更早的时刻延展,在这个意义上,任何所谓的宇宙开端都是人为的。于是,情形可以是这样,这个宇宙是去年创生的,但是所有记忆和物理证据都显得它要古老得多。这就产生了有关存在意义的高深哲学问题。我将采用所谓的实证主义方法来对付这些问题。在这个方法中,其思想是,我们按照我们构造世界的模型来解释自己感官的输入。人们不能询问这个模型是否代表实在,只能问它能否行得通。首先,如果按照一个简单而优雅的模型可以解释大量的观测;其次,如果这个模型作出可能被观察检验,也可能被证伪的明确预言,这个模型即是一个好模型。

  根据实证主义方法,人们可以比较宇宙的两个模型。第一个模型,宇宙是去年创生的,而另一个是宇宙已经存在了远为长久的时间。一对孪生子在比一年前更早的时刻诞生,已经存在了久于一年的宇宙的模型能够解释像孪生子这样的事物。

  另一方面,宇宙去年创生的模型不能解释这类事件,因此第二个模型更好。人们不能诘问宇宙是否在一年前确实存在过,或者仅仅显得是那样。在实证主义的方法中,它们没有区别。

  在一个不变的宇宙中,不存在一个自然的起始之点。然而,20世纪20年代当埃德温.哈勃在威尔逊山上开始利用100英寸的望远镜进行观测时,情形发生了根本的改变。哈勃发现,恒星并非均匀地分布于整个空间,而是大量地聚集在称为星系的集团之中。

  哈勃测量来自星系的光,进而能够确定它们的速度。他预料向我们飞来的星系和离我们飞去的星系一样多。这是在一个随时间不变的宇宙中应有的。但是令哈勃惊讶的是,他发现几乎所有的星系都飞离我们而去。此外,星系离开我们越远,则飞离得越快。宇宙不随时间不变,不像原先所有人以为的那样。它正在膨胀。星系之间的距离随时间而增大。

  宇宙膨胀是20世纪或者任何世纪最重要的智力发现之一。它转变了宇宙是否有一个开端的争论。如果星系现在正分开运动,那么,它们在过去一定更加靠近。如果它们过去的速度一直不变,则大约150亿年之前,所有星系应该一个落在另一个上。这个时刻是宇宙的开端吗?

  许多科学家仍然不喜欢宇宙具有开端。因为这似乎意味着物理学崩溃了。人们就不得不去求助于外界的作用,为方便起见,可以把它称作上帝,去确定宇宙如何起始。因此他们提出一些理论。在这些理论中,宇宙此刻正在膨胀,但是没有开端。其中之一便是邦迪、高尔德和霍伊尔于1948年提出的稳恒态理论。

  在稳恒态理论中,其思想是,随着星系离开,由假设中的在整个空间连续创生的物质形成新的星系。宇宙会永远存在,而且在所有时间中都显得一样。这最后的性质从实证主义的观点来看,作为一个可以用观测来检验的明确预言,具有巨大的优点。在马丁.莱尔领导下的剑桥射电观测天文小组,在20世纪60年代早期对弱射电源进行了调查。这些源在天空分布得相当均匀,表明大部分源位于银河系之外。平均而言,较弱的源离得较远。

  稳恒态理论预言了源的数目对应于源强度的图的形状。但是观测表明,微弱的源比预言的更多,这表明在过去源的密度较高。这就和稳恒态理论的任何东西在时间中都是不变的基本假设相冲突。由于这个,也由于其它原因,稳恒态理论被抛弃了。

  还有另一种避免宇宙有一开端的企图是,建议存在一个早先的收缩相,但是由于旋转和局部的无规性,物质不会落到同一点。相反,物质的不同部分会相互错开,宇宙会重新膨胀,这时密度保持有限。两位俄国人利弗席兹和哈拉尼科夫实际上声称,他们证明了,没有严格对称的一般收缩总会引起反弹,而密度保持有限。这个结果对于马克思主义列宁主义的唯物辩证法十分便利,因为它避免了有关宇宙创生的难以应付的问题。因此,这对于苏联科学家而言成为一篇信仰的文章。

  当利弗席兹和哈拉尼科夫发表其断言时,我是一名21岁的研究生,为了完成博士论文,我正在寻找一个问题。我不相信他们所谓的证明,于是就着手和罗杰.彭罗斯一起发展新的数学方法去研究这个问题。我们证明了宇宙不能反弹。如果爱因斯坦的广义相对论是正确的,就存在一个奇点,这是具有无限密度和无限时空曲率的点,时间在那里有一个开端。

  在我得到第一个奇点结果数月之后,即1965年10月,人们得到了确认宇宙有一个非常密集开端的思想的观察证据,那是发现了贯穿整个空间的微弱的微波背景。这些微波和你使用的微波炉的微波是一样的,但是比它微弱多了。它们只能将匹萨加热到摄氏负270.4度,甚至无法将匹萨化冻,更不用说烤熟它。实际上你自己就可以观察到这些微波。把你的电视调到一个空的频道去,在荧幕上看到的雪花的百分之几就归因于这个微波背景。早期非常热和密集状态遗留下的辐射是对这个背景的仅有的合理解释。随着宇宙膨胀,辐射一直冷却下来,直至我们今天观察到它的微弱的残余。

  虽然彭罗斯和我自己的奇性定理预言,宇宙有一个开端,这些定理并没有告诉宇宙如何起始。广义相对论方程在奇点处崩溃了。这样,爱因斯坦理论不能预言宇宙如何起始,它只能预言一旦起始后如何演化。人们对彭罗斯和我的结果可有两种态度。一种是上帝由于我们不能理解的原因,选择宇宙的启始方式。这是约翰.保罗教的观点。在梵蒂冈的一次宇宙论会议上,这位教皇告诉代表们,在宇宙起始之后,研究它是可以的。但是他们不应该探究起始的本身,因为这是创生的时刻,这是上帝的事体。我暗自庆幸,他没有意识到,我在会议上发表了一篇论文,刚好提出宇宙如何起始。我可不想象伽利略那样被递交给宗教裁判厅。

  对我们结果的另外解释,这也是得到大多数科学家赞同的解释。这个结果显示,在早期宇宙中的非常强大的引力场中,广义相对论崩溃了,必须用一个更完备的理论来取代它。因为广义相对论没有注意到物质小尺度结构,而后者是由量子理论制约的,所以人们预料总要进行这种取代。在通常情况下,因为宇宙的尺度和量子理论的微观尺度相比较极为巨大,所以是否取代无所谓。但是当宇宙处于普朗克尺度,也就是1千亿亿亿亿分之一米时,这两个尺度变成相同,必须考虑量子理论。

  为了理解宇宙的起源,我们必须把广义相对论和量子理论相结合。里查德.费恩曼对历史求和的思想似乎是实现这个目标的最佳方法。里查德.费恩曼是一位多姿多彩的人物。他在帕沙迪那的脱衣舞酒吧里敲小鼓,又是加州理工学院卓越的物理学家。他提议一个系统从状态A到状态B经过所有可能的路径或历史。

  每个路径或者历史都有一定的振幅和强度。而系统从A到B的概率是将每个路径的振幅加起来。存在一个由兰干酪制成月亮的历史。但是其振幅很低。这对于老鼠来说不是一个好消息。

  宇宙现在状态的概率可将结局为这个状态的所有历史迭加得到。但是这些历史如何起始的呢?这是一个改头换面的起源问题。是否需要一个造物主下达命令,宇宙如此这般起始呢?还是由科学定律来确定宇宙的初始条件呢?

  事实上,即便宇宙的历史回到无限的过去,这个问题仍然存在。但是如果宇宙只在150亿年前起始,这个问题就更加急切。询问在时间的开端会发生甚么,有点像当人们认为世界是平坦的,询问在世界的边缘会发生甚么一样。世界是一块平板吗?海洋从它边缘上倾泻下去吗?我已经用实验对此验证过。我环球旅行过,我并没有掉下去。

  正如大家知道的,当人们意识到世界不是一块平板,而是一个弯曲的面时,在宇宙的边缘发生甚么的问题就被解决了。然而,时间似乎不同。它显得和空间相分离。像是一个铁轨模型。如果它有一个开端,就必须有人去启动火车运行。

  爱因斯坦的广义相对论将时间和空间统一成时空。但是时间仍然和空间不同,它正像一个通道,要么有开端和终结,要么无限地伸展出去。然而,詹姆.哈特尔和我意识到,当广义相对论和量子论相结合时,在极端情形下,时间可以像空间中另一方向那样行为。这意味着,和我们摆脱世界边缘的方法类似,可以摆脱时间具有开端的问题。

  假定宇宙的开端正如地球的南极,其纬度取时间的角色。宇宙就在南极作为一个起始点。随着往北运动,代表宇宙尺度的常纬度的圆就膨胀。诘问在宇宙开端之前发生了甚么是没有意义的问题。因为在南极的南边没有任何东西。

  时间,用纬度来测量,在南极处有一个开端。但是南极和其它的点非常相像。至少我听别人这么讲的。我去过南极洲,没有去过南极。

  同样的自然定律正如在其它地方一样,在南极成立。长期以来,人们说宇宙的开端是正常定律失效之处,所以宇宙不应该有开端。而现在,宇宙的开端由科学定律来制约,所以反对宇宙有开端的论证不再成立。

  詹姆.哈特尔和我发展宇宙自发创生的图景有一点像泡泡在沸腾的水中形成。

  其思想是,宇宙最可能的历史像是泡泡的表面。许多小泡泡出现,然后再消失。这些对应于微小的宇宙,它们膨胀,但在仍然处于微观尺度时再次坍缩。它们是另外可能的宇宙,由于不能维持足够长的时间,来不及发展星系和恒星,更不用说智慧生命了,所以我们对它们没有多大兴趣。然而,这些小泡泡中的一些会膨胀到一定的尺度,到那时可以安全地逃避坍缩。它们会继续以不断增大的速率膨胀,形成我们看到的泡泡。它们对应于开始以不断增加的速率膨胀的宇宙。这就是所谓的暴胀,正如每年的价格上涨一样。

  通货膨胀的世界纪录应归一战以后的德国。在18月期间价格增大了一千万倍。但是,它和早期宇宙中的暴胀相比实在微不足道。宇宙在比一秒还微小得多的时间里膨胀了十的30次方倍。和通货膨胀不同,早期宇宙的暴胀是非常好的事情。它产生了一个非常巨大的均匀的宇宙,正如我们观察到的。然而,它不是完全均匀的。在对历史求和中,稍微具有无规性的历史和完全均匀和规则历史的概率几乎相同。因此,理论预言早期宇宙很可能是稍微不均匀的。这些无规性在从不同方向来的微波背景强度上引起小的变化。利用MAP(微波各向异性)卫星已经观察到微波背景,发现了和预言完全一致的变化。这样,我们知道自己正在正确的道路上前进。

  早期宇宙中的无规性,意味着在有些区域的密度,比其它地方的稍高。这些额外密度的引力吸引使这个区域的膨胀减缓,而且最终能够使这些区域坍缩形成星系和恒星。请仔细看这张微波天图。它是宇宙中一切结构的蓝图。我们是极早期宇宙的量子起伏的产物。上帝的确在掷骰子。

  在过去的百年间,我们在宇宙学中取得了惊人的进步。广义相对论和宇宙膨胀的发现,粉碎了永远存在并将永远继续存在的宇宙的古老图像。取而代之,广义相对论预言,宇宙和时间本身都在大爆炸处起始。它还预言时间在黑洞里终结。宇宙微波背景的发现,以及黑洞的观测,支持这些结论。这是我们的宇宙图像和实在本身的一个深刻的改变。

  虽然广义相对论预言了,宇宙来自于过去一个高曲率的时期,但它不能预言宇宙如何从大爆炸形成。这样,广义相对论自身不能回答宇宙学的核心问题,为何宇宙如此这般。然而,如果广义相对论和量子论相合并,就可能预言宇宙是如何起始的。它开始以不断增大的速率膨胀。这两个理论的结合预言,在这个称作暴胀的时期,微小的起伏会发展,导致星系、恒星以及宇宙中所有其它结构的形成。对宇宙微波背景中的小的非均匀性的观测,完全证实了预言的性质。这样,我们似乎正朝着理解宇宙起源的正确方向前进,尽管还有许多工作要做。当我们通过精密测量空间航空器之间距离,进而能够检测到引力波,就会打开极早期宇宙的新窗口。引力波从最早的时刻自由地向我们传播,所有介入的物质都无法阻碍它。与此相比较,自由电子多次地散射光。这种散射一直进行到30万年后电子被凝结之前。

  尽管我们已经取得了一些伟大成功,并非一切都已解决。我们观察到,宇宙的膨胀在长期的变缓之后,再次加速。对此理论还不能理解清楚。缺乏这种理解,对宇宙的未来还无法确定。它会继续地无限地膨胀下去吗?暴胀是一个自然定律吗?或者宇宙最终会再次坍缩吗?新的观测结果,理论的进步正迅速涌来。宇宙学是一个非常激动人心和活跃的学科。我们正接近回答这古老的问题:我们为何在此?我们从何而来?   

  谢谢各位。

Donne Moi Le Temps

Donne-moi le temps

Jenifer

Tell'ment de gens veulent 
Tell'ment être aimés 
Pour se donner peuvent 
Tout abandonner 
Tellement d'erreurs qu'on 
pourrait s'éviter 
Si l'on savait juste un peu patienter 

Donne-moi le temps 
D'apprendre ce qu'il faut apprende 
Donne-moi le temps 
D'avancer comme je le ressens 
Y'a pas d'amour au hasard 
Ou qui arrive trop tard 
J'appendrai le temps d'attendre 

Tellement de rêve qui 
se trouvent gachés 
A vivre tout, juste pour s'évader 
Est ce que nos peurs valent 
A ce point la peine 
Pour exiger aussi peu de nous même ? 

Tu auras le temps 
De prendre ce que tu veux prendre 
Tu auras le temps de nous faire avancer ensemble 
Tant de gens se cherchent 
Se désirent, se suivent et se perdent 
Donnons nous la peine 
De se découvrir, se conna?tre 
Je ne laisserai pas l'amour au hasard 
Ni qu'il soit trop tard 
Si la patiente s'apprend 
J'apprendrai ce qu'est attendre 
Je prends le temps 
Pour que tu m'attendes 
Le temps 
Pour toi 

=============================================== 

给我时间

简妮芙

如此多的人希冀, 
能够被人爱惜, 
互相给予, 
甚至完全抛弃, 
所有我们可以避免的骗局, 
如果我们懂得多一点的耐心。 

给我一点时间, 
去学会该学的东西。 
给我一点时间, 
去继续我所感受的情绪。 
没有偶然的爱情, 
或是迟来的爱情, 
我需要学会, 
等待的心情。 

如此多的幻想, 
被隐藏心底, 
生命的契机, 
期待激情。 
是否我们的恐惧, 
值得,令我们要求上帝, 
减少一点惩罚的程序。 

你会有时间, 
取走你该取的东西。 
你会有时间, 
去令我们一起继续。 

如此多的人, 
互相找寻, 
互相期冀, 
互相追随, 
却又最终互相丢弃。 

让我们多惩罚一下自己, 
彼此发掘,更多了解。 
我不要一见钟情, 
不要迟来的爱情, 
让我们学会耐心。 

我会学会该学会的东西, 
我拿走时间, 
你等我的光阴。 
给我一点时间, 
一段为你的生命。

http://www.math.buffalo.edu/~phuvu/music/Jennifer - Donne Moi Le Temps.mp3

我只有两天

from 两天 by 许巍

 

我只有两天
我从没有把握
一天用来出生
一天用来死亡
我只有两天
我从没有把握
一天用来希望
一天用来绝望
我只有两天
每天都在幻想
一天用来想你
一天用来想我
我只有两天
我从没有把握
一天用来路过
另一天还是路过