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

日志


2007/1/29

Top 5 Time Management Tips(zz)

http://www.usenix.org/events/lisa06/tech/slides/li...
#1 Create a Mutual Interruption Shield
#2 Turn Chaos Into Routines
#3 Record All Requests
#4 Keep 365 Todo-List Each Year
#5 Document Processes You Hate

2007/1/16

网络还没好,趁晚上能上网把有用的抄到这里先


Watir FAQ

Pettichord, last edited by Zeljko on Jan 11, 2007  (view change)

How do I use Watir?

Q. How do I use Watir to...

A. Aside from studying the Watir libraries themselves and the User Guide, a good way to understand how to use Watir and get examples is to take a look at the unit tests. There are tests for all of the features in Watir which can serve as excellent documentation and a basic tutorial.

Handling JavaScript Pop-Up Windows

Q. When IE throws up a JavaScript pop-up window, it appears to hang my Ruby script.
How can I make those windows go away?

A. http://rubyforge.org/pipermail/wtr-general/2005-April/001461.html

OR...

# Auto Popup Handler. Posted by brad@longbrothers.net
    #
    require 'win32ole'  # already included if you use 'require watir'
    #
    # Function to look for popups
    def check_for_popups
        autoit = WIN32OLE.new('<nowiki>AutoItX3</nowiki>.Control')
        #
        # Do forever - assumes popups could occur anywhere/anytime in your application.
        loop do
            # Look for window with given title. Give up after 1 second.
            ret = autoit.<nowiki>WinWait</nowiki>('Popup Window Title', '', 1)
            #
            # If window found, send appropriate keystroke (e.g. {enter}, {Y}, {N}).
            if (ret==1) then autoit.Send('{enter}') end
            #
            # Take a rest to avoid chewing up cycles and give another thread a go.
            # Then resume the loop.
            sleep(3)
        end
    end
    #
    # MAIN APPLICATION CODE
    # Setup popup handler
    $popup = Thread.new { check_for_popups }  # start popup handler
    at_exit { Thread.kill($popup) }           # kill thread on exit of main application
    #
    # Main application code follows
    # ...

OR...

# A Better Popup Handler using the latest Watir version. Posted by Mark_cain@rl.gov
    #
    require 'watir\contrib\enabled_popup' 
    #
    def startClicker( button , waitTime= 9, user_input=nil )
      # get a handle if one exists
      hwnd = $ie.enabled_popup(waitTime)  
      if (hwnd)  # yes there is a popup
        w = WinClicker.new
        if ( user_input ) 
          w.setTextValueForFileNameField( hwnd, "#{user_input}" )
        end
        # I put this in to see the text being input it is not necessary to work
        sleep 3         
        # "OK" or whatever the name on the button is
        w.clickWindowsButton_hwnd( hwnd, "#{button}" )
        #
        # this is just cleanup
        w=nil    
      end
    end
    #
    # MAIN APPLICATION CODE
    #
    $ie = Watir::IE.start( "c:\test.htm" )

    # This is whatever object that uses the click method.  
    # You MUST use the click_no_wait method.
    $ie.image( :id, '3' ).click_no_wait
    #
    # 3rd parameter is optional and is used for input and file dialog boxes.
    startClicker( "OK ", 7 , "User Input" )
    #
    # Main application code follows
    # ...

Watir and Linux / Firefox

Watir 2.0 has support planned for Linux and Firefox. See http://rubyforge.org/pipermail/wtr-general/2005-May/001907.html

Multiple concurrent Internet Explorer windows that are not based on the same 'iexplore.exe' process

Q. That is to say, we need to have 5 Internet Explorer applications running, with 5 independent 'iexplore.exe' processes. While we have been able to open multiple Internet Explorer windows concurrently (using the methods shown in the 'concurrent_search' multi-thread example), we have been unable to determine a way to have new IE instances created with their own iexplore.exe process. We have begun investigating the WIN32OLE, but wanted to see whether this issue has been addressed previously by Watir.

A. http://rubyforge.org/pipermail/wtr-general/2005-March/001276.html

Accessing a security alert window

Q. I'm writing a web application testing using watir 1.3. I encountered a problem with accessing pop up windows. Does any one know how to access a security alert window and press 'Yes' button on the window using Watir? It will be highly appreciated if you can help me to solve this problem. This issue has been blocking me to proceed my test for several days now.

A. http://rubyforge.org/pipermail/wtr-general/2005-May/001676.html

Can Watir attach to a popup window? (Yes)

Q. I am having trouble using IE.attach to attach to a popup window. How can i get this to work?

A. Watir 1.4.1 works fine with ordinary web popup windows. However, it does not support modal web popup windows. These are web pages that popup and block access to the orignal page until you've closed them.

Watir 1.5 includes support for these pages. Use IE#modal_dialog to access them. 

Triggering JavaScript events

Q. When I enter text in a text field, or interact with something on a page, there is a JavaScript event that is triggered by mouse movements. How do I get Watir to trigger these events?

A. If the tag contains a JavaScript call, you can use the "fire_event" method to trigger it. ex. onchange=doThis() or onmouseup=clearForm()

To trigger a text field named "my_field" with an onchange event we would do this with Watir:

ie.text_field(:name, "my_field").fire_event("onchange")

Interacting with a JavaScript tree view

It's important to find out which frame the tree view is in, which can be done using "show_frames". Once we know that, we can use the image "index" attribute to find the plus images to expand the menu.

Here is an example using IRB (Start > Run > IRB) (Type what is in bold):

irb(main):001:0> require 'watir'
=> true
irb(main):002:0> ie = Watir::IE.new
<nowiki>=> #<Watir::IE:0x2df00e8 @ie=#<WIN32OLE:0x2df0088>, @defaultSleepTime=0.1,
@error_ch
x02ab0568@c:/ruby/lib/ruby/site_ruby/1.8/watir.rb:1213>],
@logger=#<Watir::DefaultLogger=#<Logger::LogDevice:0x2deffc8 @dev=#<IO:0x2a6e980>, @shift_size=nil,
@level=2, @datetime_format="%d-%b-%Y %H:%M:%S", @progname=nil>,
@typingspeed
jectHighLightColor="yellow", @enable_spinner=false, @url_list=[], @form=nil>
irb(main):003:0></nowiki> ie.goto("*HTTP://www.ivanpeters.com/")*
=> 3.422
irb(main):004:0> ie.frame("menu").link(:text , /wel/i).flash
=> 10
irb(main):005:0> ie.frame("menu").image(:index, 1).flash
=> 10
irb(main):006:0> ie.frame("menu").image(:index, 2).flash
=> 10
irb(main):007:0> ie.frame("menu").image(:index, 3).flash
=> 10
irb(main):008:0> ie.frame("menu").image(:index, 3).click
=> nil
irb(main):009:0> ie.frame("menu").link(:text, "Who is using it?").flash
=> 10

We used "flash" to find the image we wanted which was the first "plus" sign. Once we found it using index (at index 3), we clicked it to expand it. Once it was expanded, we were able to interact with elements under that tree node.

Searching the mail archives

For searching archives try this in Google:

site:rubyforge.org "[Wtr-general]" javascript

(instead of "javascript" you can use anything you think can be useful)

Or you could visit one of the mailing list archives and search that way.

Using key/value pairs

Q. I'd like  to have a configuration file (eg. config.txt), which would have a number of key/value pairs, such as "UserName=user", which would be read by a test script to, for example, log into a page.

A. You can use ruby file for this. i.e

$user_name = 'atilla'
$last_name = 'ozgur'

Save this as initialValues.rb

Then in your script, add the line

    require initialValues.rb

and the classes and variables are ready for your use. Do not forget that these are global variables. Maybe a class and class variables would be more suitable for this. They will be more encapsulated in that way.

class initialValues
    @@user_name = 'atilla'
    @@last_name = 'ozgur'
  end

Note: A variable prefixed with two at signs is a class variable, accessible within both instance and class methods of the class.

Then you can use them as.

initialValues.user_name
initialValues.last_name

this way, related values will have their place.

"Unable to locate object" error when clicking an image

<td align="middle" colSpan="2"><input type="image" src="images/RBJ_LoginButtonOff.gif" border="0" tabindex="3"></td>
ie.image(:src,/RBJ_LoginButtonOff/).click

The result is an "unable to locate object" error. This is because it is a button, not an image. Try ie.button(:src,/RBJ_LoginButtonOff/).click

Closing all open IE windows

This routine can be useful as part of setup or teardown. It attaches to, and closes, all open IE windows.

def close_all_windows
      loop do
        begin
          Watir::IE.attach(:title, //).close
        rescue Watir::Exception::NoMatchingWindowFoundException
          break
        rescue
          retry
        end
      end
    end

An enhanced version of this functionality is now included in Watir 1.5. (It also closes modal web dialogs.)

require 'watir/close_all'Watir::IE.close_all

A final brute-force method (that works on Windows XP) might be to kill all iexplore.exe processes via a system command:

system("taskkill /t /f /im iexplore.exe")

Ruby and Watir version

Q. How do I get the version numbers of Ruby and Watir?

A. Go to command prompt.

For the Watir version type:

ruby -e 'require "watir"; puts Watir::IE::VERSION'

For the Ruby version type:

ruby -v

Access denied when trying to access a frame

This error message is due to Internet Explorer's attempt to prevent cross-window domain scripting (also known as cross-site scripting, or XSS).  For security reasons, IE prevents embedded code in one frame from accessing another if the frame contents come from different domains. Watir runs into the same barriers when you attempt to navigate from a page hosted from one site to a frame hosted by another.

You may try one or more of the following methods to resolve this issue:

  1. Navigate directly to the subframe (and the server that hosts it).  That is, instead of having your script click on the link, use ie.goto(http://www.thenewsite.com/framecontents.html).
  2. Add the particular host to the Internet Explorer Trusted Sites list.  From IE's menu bar, choose Tools / Internet Options; click on the Security tab; click on the Trusted Sites icon; click on the Sites... button; type the name of the site into the field labelled "Add this Web site to the zone:".  You may need to uncheck the box labelled "Require server verification ( https: ) for all sites in this zone."  Click OK to finish the process.
  3. Create an alias in the hosts file.  This text file is typically in the folder c:\windows\system32\drivers\etc.  Add a line in the form
    192.168.10.32 foosystem

    Replace 192.168.10.32 with the IP address of the host that is serving up the frame contents.  Then access the frame using https://foosystem/testsystem.

  4. Set Internet Explorer to its lowest possible security setting.  From IE's menu bar, choose Tools / Internet Options; click on the Security tab; click on the Default Level button, and slide the slider to the Low setting; then click on OK to finish the process.

If none of these work, and you are still getting annoying error messages about Access Denied when your scripts run, you can turn off these warnings. 

ie.logger.level = Logger::ERROR


Microsoft Reference
For background information about the security rules that cause this problem, see About Cross-Frame Scripting and Security

Installing a Gem from the latest development source

Note: If you've installed Watir with the One Click Installer. You should uninstall that version before attempting to upgrade to the development source gem.

Note: It is easier to simply use a recent _development gem.

Projects on OpenQA use Subversion as the Source Code Management tool. TortoiseSVN is a good Subversion client which integrates into windows explorer: http://tortoisesvn.tigris.org/

Once TortoiseSVN is installed, checkout the source:

  • Create a folder to checkout into, this will be the watir_install_dir
  • Right click on watir_install_dir, from the context menu select SVN Checkout...
  • In the dialog box enter: http://svn.openqa.org/svn/watir/trunk/watir for the url
  • Hit Ok, Watir source should now download into the watir_install_dir

Now that you have your own local copy of the source, you can create your own gem and install it into your local ruby gems directory. Open a command line, navigate to watir_install_dir and type the following:

gem build watir.gemspec

This will create a file that is named something like watir.1.5.1.1032.gem. The actual version number will be based on the latest revision number of the source in subversion.

 You can install your gem simply by typing this in the same directory:

gem install watir

Note that this command will first look for a watir gem in the current directory. If it isn't found there, then it will look to the gem server on the internet (at rubyforge.org).

This command will list the gem versions on your local system, you should now have the latest development version listed. 

gem list --local

You can also do a gem uninstall on previous versions if you'd like.

gem uninstall watir

and you'll get a list of versions to choose from.

To keep in sync with the latest code you can now right click on watir_install_dir, click on SVN Update and follow the gem install process again.

How to collect reports from tests

Q: I have several tests which run through Test Unit, now I want to pull the results as html or xml.
A: If your tests inherit from TestCase then use Test Report which collects the results of your test runs in either html or xml.

Example:

require 'stringio'
require 'test/unit/testsuite'

require 'test/unit/ui/reporter'

Test::Unit::UI::Reporter.run(My_Test_Case.suite, result_path, :html)

result_path being the directory you want to use for your reports.

Read the README file in the test reporter download for more information.

How do I hide the browser window without using the -b flag?

Q: How can I hide the IE browser window without using the -b flag?

A: $HIDE_IE = true; ie = Watir::IE.new()

adding assert_false to your tests

As you may know Test::Unit does ! include an assert_false.

Enter this in assertations.rb

public
  def assert_false(boolean, message="") 
    _wrap_assertion do 
      assert_block("assert should not be called with a block.") { !block_given? } 
      assert_block(message) { !boolean } 
    end 
  end

test example

regex = /Joe.*Bloggs/ 
 assert_false($ie.contains_text(regex), "#{regex} unexpectedly found in HTML")

aidy

How do I create an Application\Object Map?

Bret came up with a simple but clever idea

Insert the object recognition into a small method

e.g.

def login_link;$ie.link(:text, 'Log in');end
def username_field;$ie.text_field(:name, 'userid');end

then in your test class do:

login_link.click
username_field.set(username)

If you wrap those small methods into a class:

class ObjectMap
  def login_link;$ie.link(:text, 'Log in');end
  def username_field;$ie.text_field(:name, 'userid');end
end

Then in our re-usable methods that may be held in Ruby Modules, we can go:

def log_in(username='aidy', password='lewis')
  ObjectMap.new.instance_eval do
    login_link.click
    username_field.set(username)
    password_field.set(password)
    login_btn.click  
   end
end

instance_eval evaluates the block of methods to their own receiver object. It saves us writing:

map = ObjectMap.new
map.login_link.click
map.username_field.set(username)
etc ....

aidy

Watir && Regular Expressions

Watir allows the tester to use Regular Expressions for object recognition instead of using the full string literal.
This is useful for HTML objects that are dynamically created.

For example in my WebSphere application we may have a link with this URL

$ie.link(:url, "javascript:PC_7_0_G7_selectTerritory('0',%20'amend')").click

However this: 'PC_7_0_G7_' will change dependant on the environment.

With RegEx we could find that link by doing :

$ie.link(:url, /selectTerritory\('0',%20'amend'\)/).click

or this

$ie.link(:url, /javascript.*selectTerritory\('0',%20'amend'\)/).click

note: '.*' will match any character or digit any number of times.

RegEx contains special characters that need to be escaped. For example here ')' we use the backward slash to escape a closing bracket.

To find out what characters need to be escaped, go into irb, then enter

Regexp.escape "javascript:PC_7_0_G7_selectTerritory('0',%20'amend')"

the escape sequences will be returned

=> "javascript:PC_7_0_G7_selectTerritory\\('0',%20'amend'\\)"

note: use only one backslash; we are shown two, because they are escaped within a string,

aidy

I have > 1 object of the same name. How do I commit an action on anything but the first one?

Lets imagine we have two 'Employees' links.

This will click the first link that is found on the page

$ie.link(:text, 'Employees').click

Use this syntax for the second (or more)

$ie.link(:text => 'Employees', :index  => 2).click

note: the above syntax is not yet implemented for input elements ("<INPUT>"),
such as text_field, though it is supported for most other elements.

TO DO: aidy will try to fix this

你得是个有出息的孩子(zz)

怎么感觉我那时看到的不是这个版本呢,奇怪! 不过,呵呵,“按照一种说法,一个男人(其实女人也是如此)不成熟的标志就是他(或她)还愿意为某种东西(甚至包括爱情)献身。”,这句说的很像我:)

(在北大法学院2005届学生毕业典礼上的致词,2005/6/29)

朱苏力- 北大法学院院长

    20多年前,和你们一样,我在北大过着一段悠闲得令人羞愧的日子,一段努力地无所事事的日子;没有时间的概念,我愿意、好像也可以永远这样地赖在这里。也知道毕业这个词,但它没有体温;直到有一天才残酷地发现,原来大学也会毕业的。于是,“改邪归正”,从春天开始(那时还不用自己找工作),就不再上课,不再到图书馆占座,茫然地一心一意——毕业ing。

    今天,你们的这个ing也走到了尽头,黑色的学位服凝重在你身上……

    不要说你们伤感。伤感不是青年人的专利。静下来,写这段讲话的时候,其实,我,我们这些看着你们长大的老师,也一样伤感;并且年年如此。岁月并没有让我们的心长出茧子,只是我们学会了掩饰,也善于掩饰。我们不再表达;伤感的表达是青年知识人的专利,我们知道。

    “自古多情伤离别”;但离别会让你想一些来不及想的事,说一些本不会说的话,让没心没肺的你第一次品味了甚至喜欢上了惆怅,或是让滴酒不沾的你今晚变成了“酒井”先生或小姐。如果没有这样的离别,人生会多么乏味!问一问今天在座的王磊老师,还有刘燕老师、沈岿老师,还有今年毕业的凌斌博士、李清池博士,自打他们本科进来之后,就一直没有离开北大的校门,或只有短暂的离开。他们的本科或研究生毕业都不像你们今天这样百感交集,有滋有味,肆无忌惮;在他们心中,那只是又一个暑期的开始。

    这一个暑期是不一样的,你再也“赖”不下去了。

    其实外面的世界确实很精彩。走出大学校园,你会发现我们这个社会,这个国家,充满着活力。当然,活力并不都是美好、清新、温情脉脉的,吉它、摇滚和玫瑰花;社会中的活力常常很“糙”,更多野性、欲望和挣扎,还有你们要时时提防的贪婪、阴谋和背叛—— 一如桑德堡笔下的《芝加哥》。但这就是真实世界的活力,伴随着小麦颜色的农民工、水泥森林和汽车尾气中灰蒙蒙的朝阳,以及我们这个民族的身姿一同在这块土地上崛起。

    想一想,为什么最近美国和欧盟会对中国的纺织品出口设限,并一再要求人民币升值?为什么近来小泉等人总在那里惹事,搞些小动作,没什么技术含量,搞得“中国人民很生气,后果很严重”?海峡对岸,连战来了,宋楚瑜也来了;阿扁没来,但很憋气,知道迟早也得来。我们周围也还有一大堆问题,贫富不均、发展不平衡、污染、腐败和不公。有同学可能还没找好工作,没有“签约”;签了的,也未必满意,可能还想毁约。所有这些问题,都让人烦心,让人不爽。但有哪个时代,人人都爽——管它到哪一天,至少也会有人失恋吧?换一个角度看,也许这些问题都表明中国正在迅速发展和崛起,以一种任何人都无法遏止的强劲活力。中国正登上一个更大的舞台,一个更宽敞但不一定更平整的舞台;这意味着你们要面对更多的麻烦,一些前人和我们都没有经历因此有待你们来应对的
麻烦。你们任重而道远。

    说着说着就高调起来了。没有办法,在这个时代,我们这些人都有点,也应当有点,理想主义。还是渴望为了什么而献身,这是青春期的焦灼,也是生命力的反映。
    但是,按照一种说法,一个男人(其实女人也是如此)不成熟的标志就是他(或她)还愿意为某种东西(甚至包括爱情)献身。咋看起来,这好像是对我们这些理想主义者的一个讽刺。其实不然。这句话只是从另一个角度揭示了生活,暴露了那种浪漫主义的理想主义之脆弱和虚妄。献身其实是比较容易的,也许只要一丝血性,一点勇气,有时甚至只要一分冲动。但这往往不能改变什么,最多只满足了青春期那一份个人英雄主义的激情。激情过后,则往往是空虚、失落,甚至堕落。而在今天这个好像越来越斤斤计较的年代,人们连激情也洋溢不出来了——前几年傻乎乎地,也许在看中国足球队比赛时,山呼海啸,人潮起伏,好像还有那么一点感觉。但今天还有多少人看中国队比赛?!

    然而,真正的理想主义往往在激情之后。它不是夏日的骄阳,而是秋日的明亮,它要经受时光的煎熬和磨砺,要能够接受甚至融入平和、平凡、平淡甚至看似平庸的生活,从容但倔强地蜿蜒,在不经意中成就自己。它常常包含了失败甚至屈辱,还必须接受妥协、误解、嫉妒、非议。它同坚忍相伴,它同自信携手。

    想一想那选择了在辱骂声中顽强活下来最终为赵氏孤儿复仇的程婴;想一想在北海的秋风长草间十九年目送衡阳雁去的苏武;想一想走在江西新建县拖拉机厂的上班路上并保证“永不翻案”的邓小平;或者只是想一想多年来养育了也许是你们家祖祖辈辈第一位大学生、硕士生或博士生的你们的父母。

    这些理想当然是不同的,有些似乎还不够崇高,不够伟大,今天的法律人甚至会批评其过于野蛮或狭隘;但抽象看来,他们毫无例外都是理想主义者,是成熟的并因此是真正的理想主义者。因为在今天我们社会,判断是否真正理想主义者的标准不应全都是实质的,不完全是你是否认同、分享他/她的追求,是否值得你为之献身;而至少部分应是形式的,即他/她是否始终并无怨无悔地追求了,是否展现了一种坚忍,一种对目标的恪守,一种我先前说过的那种“认命”或“安分守己”。

    也因为理想并不完全是个人的选择,在相当程度上,它是社会的构建,基于一个人对自身能力、时代和社会环境的理解、判断和想象。你们也不例外。也许你们的理想会显得比我们的,比我们前辈的更宏阔,更高远,但那不过是你们的能力以及北大和今日中国为你们展示了更多选项以及更大的可能性。而我们最关心的是,许多年后,在漫长的再也谈不动理想的年月后,你能否像你所敬重的甚或不那么敬重的前辈那样,拿出一个作品,值得你向世人自豪——即使仅仅如同此刻站在你父母亲骄傲目光中的你?

    因此,我希望你们切记,真正的理想,无论大小,无论高下,最终都一定要用成果来兑现,否则最多只是一个令人遗憾的、但对这个世界多一个少一个都没有意义的愿望表达,甚至只是一通大话、一张空头支票或一个笑柄。

    我们会宽容、理解并心痛你们必定会有的失败和挫折,但我们祝福、渴望并欣喜你们成功,即使是微不足道的成功——如同当年你跌跌撞撞迈出的第一步。我们并不苛刻。

    而且,我们也有耐心。我们会在这里长久守候;即使夜深了,也会给你留着灯,留着门——只是,你得是有出息的孩子。

    而且,我们相信,你是有出息的孩子!你们会是有出息的孩子!

                                                      2005年6月于北大法学院

2007/1/6

Five Principles for Happiness in 2007(zz)

希望能在新的一年中给大家带来幸福, 因为你们的幸福就是我最大的幸福:)

The Automatic Millionaire

by David Bach

Five Principles for Happiness in 2007

by David Bach

Tuesday, January 2, 2007

The arrival of the new year marks a symbolic time for fresh starts. Many of us take it as an opportunity to set goals, contemplate decisions, and renew commitments. It's special because of the revitalized sense of hope it brings.

Before you make your New Year's resolutions for 2007, I'd like to share some thoughts about how it's never too late to start living a rich life.

The Live Rich Factor

Most people believe that if they just had more money, the things that make them unhappy would disappear and their lives would be better. The truth is that your life can be better without more money. It can be better today, but you need to make some decisions and take some actions.

You don't need me to tell you what will make you happy -- only you know that truth.

I believe each of us has the power to discover our purpose and become joyful in the process of journeying toward that purpose. It's not easy, however. Nothing important and meaningful ever is.

What you need to do is create what I call the "Live Rich Factor" in your life. I call it this because those who find the purpose that leads them to joy are truly the luckiest people in the world, because they're living richly.

There are five basic principles involved in creating your Live Rich Factor:

Principle 1: Give Yourself a Break

We all tell ourselves the story of the one that got away. You can't move forward if you spend time focusing on what you shoulda-woulda-coulda done in 2006 or before. It's over, and its time to move on. The fastest way I know to do this is to write all of your regrets down on paper.

Make a list of all your personal and financial if-onlys. For example, "If only I had saved more money. If only I hadn't quit that job. If only I hadn't taken the job I have." You get the idea.

After reading the list aloud to yourself, get rid of it. Let it all go by literally burning the list (safely). Now you're ready for a fresh start in 2007 -- a new beginning.

Principle 2: Get Connected with Your Truth

The hardest thing to do is be honest with yourself. Asking yourself some key questions will lead you to some amazing discoveries, and possibly motivate you to do what it takes to create the life you envision for yourself.

I suggest writing your (honest) answers to the following questions in a new journal for the new year:

  • What makes you happy at work?
  • What makes you happy at home?
  • What makes you happy with your friends and family?
  • What makes you happy when you're by yourself?
  • What do you love to do?
  • What would you do with your life today if you weren't afraid of failure?
  • What's not working in your life?
  • What are you currently doing that prevents you from experiencing joy?
  • What's working in your life?
  • Who's not working in your life?
  • Who in your life is subtracting value from and adding misery to it?
  • Can you fix any of these relationships, or should you let them go from your life?
  • What relationships are working in your life?
  • If we were getting together one year from today, what would have to happen for you to be able to tell me that you now have more joy in your life?
  • What's the single most important thing you've learned about yourself as a result of answering these questions?

You'll find that by putting your answers down on paper, they'll become clear more quickly and the actions you need to take more obvious and easier to initiate.

Principle 3: Stop Judging Yourself

Be nicer to yourself in 2007. Many people talk to themselves in a way they would never accept from a stranger, friend, or loved one. If this describes you, try stopping the negative conversations you have with yourself immediately.

For one week, simply commit to saying "stop it" when you think a negative thought about yourself. If you're in the habit of saying negative things to yourself, you'll find this is one of the most difficult exercises you'll ever do. Carry a notepad with you and make a mark each time you catch yourself thinking negatively. You'll find that as the days go by, your negative thinking can quickly be reduced.

Principle 4: Stop Judging Others

It's hard to be joyful when you're always judging others. In fact, it's close to impossible. Judging others creates a huge amount of stress in our lives. It affects our marriages and our relationships with our kids as well as the way we relate to friends, co-workers, and society in general.

We're not here to judge one another.

The next time you find yourself upset at someone or some situation, catch yourself and ask, "Are you judging?" Judging others is often an unconscious habit. But it's a habit that can be changed the moment you decide to stop doing it.

Principle 5 : Pursue Fun with a Vengeance

It's OK to pursue fun. It's what children do. My greatest joy these days is the simple pleasure of playing with my three-year-old son, Jack.

This holiday season with Jack taught me the simple power of pursuing fun -- again and again. What was fun for Jack this Christmas? It turns out it wasn't the Big Wheel that my wife, Michelle, and I stayed up so late building on Christmas Eve. And it wasn't the Star Wars Lego toy (although he was pretty excited about that).

Instead, what Jack found the most fun was a new game I made up to keep him entertained. The game was called Geronimo -- and it involved Jack jumping from the bed onto a stack of pillows yelling "Geronimo!" This silly little game ended up bringing us both hours of fun. The price of the game: nothing. The fun: priceless. And the laughs? Endless.

Why do we stop pursing fun as we get older? Fun shouldn't be squeezed into a few weeks of vacation each year. And it shouldn't be squeezed into the last chapter of your life when you "get to" retire. Fun deserves to be a part of your life now -- in 2007.

But fun doesn't just happen. You have to make it a priority in your life or it'll go missing. Life's too short to not have it.

So here's to a fun, happy, and healthy New Year. Cheers!

2007/1/4

intro to cron

留个记录,以后用的时候就在这里查了.
Newbie: Intro to cron
Date: 30-Dec-99
Author: cogNiTioN <cognition@attrition.org>

Cron

This file is an introduction to cron, it covers the basics of what cron does,
and how to use it.

What is cron?

Cron is the name of program that enables unix users to execute commands or
scripts (groups of commands) automatically at a specified time/date. It is
normally used for sys admin commands, like makewhatis, which builds a
search database for the man -k command, or for running a backup script, 
but can be used for anything. A common use for it today is connecting to 
the internet and downloading your email.

This file will look at Vixie Cron, a version of cron authored by Paul Vixie.

How to start Cron

Cron is a daemon, which means that it only needs to be started once, and will 
lay dormant until it is required. A Web server is a daemon, it stays dormant 
until it gets asked for a web page. The cron daemon, or crond, stays dormant 
until a time specified in one of the config files, or crontabs.

On most Linux distributions crond is automatically installed and entered into 
the start up scripts. To find out if it's running do the following:

cog@pingu $ ps aux | grep crond
root       311  0.0  0.7  1284  112 ?        S    Dec24   0:00 crond
cog       8606  4.0  2.6  1148  388 tty2     S    12:47   0:00 grep crond

The top line shows that crond is running, the bottom line is the search
we just run.

If it's not running then either you killed it since the last time you rebooted,
or it wasn't started.

To start it, just add the line crond to one of your start up scripts. The 
process automatically goes into the back ground, so you don't have to force
it with &. Cron will be started next time you reboot. To run it without 
rebooting, just type crond as root:

root@pingu # crond

With lots of daemons, (e.g. httpd and syslogd) they need to be restarted 
after the config files have been changed so that the program has a chance 
to reload them. Vixie Cron will automatically reload the files after they 
have been edited with the crontab command. Some cron versions reload the
files every minute, and some require restarting, but Vixie Cron just loads 
the files if they have changed.

Using cron

There are a few different ways to use cron (surprise, surprise). 

In the /etc directory you will probably find some sub directories called 
'cron.hourly', 'cron.daily', 'cron.weekly' and 'cron.monthly'. If you place 
a script into one of those directories it will be run either hourly, daily, 
weekly or monthly, depending on the name of the directory. 

If you want more flexibility than this, you can edit a crontab (the name 
for cron's config files). The main config file is normally /etc/crontab.
On a default RedHat install, the crontab will look something like this:

root@pingu # cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly

The first part is almost self explanatory; it sets the variables for cron.

SHELL is the 'shell' cron runs under. If unspecified, it will default to 
the entry in the /etc/passwd file.

PATH contains the directories which will be in the search path for cron 
e.g if you've got a program 'foo' in the directory /usr/cog/bin, it might 
be worth adding /usr/cog/bin to the path, as it will stop you having to use
the full path to 'foo' every time you want to call it.

MAILTO is who gets mailed the output of each command. If a command cron is 
running has output (e.g. status reports, or errors), cron will email the output 
to whoever is specified in this variable. If no one if specified, then the 
output will be mailed to the owner of the process that produced the output.

HOME is the home directory that is used for cron. If unspecified, it will 
default to the entry in the /etc/passwd file.

Now for the more complicated second part of a crontab file.
An entry in cron is made up of a series of fields, much like the /etc/passwd
file is, but in the crontab they are separated by a space. There are normally
seven fields in one entry. The fields are:

minute hour dom month dow user cmd

minute	This controls what minute of the hour the command will run on,
	 and is between '0' and '59'
hour	This controls what hour the command will run on, and is specified in
         the 24 hour clock, values must be between 0 and 23 (0 is midnight)
dom	This is the Day of Month, that you want the command run on, e.g. to
	 run a command on the 19th of each month, the dom would be 19.
month	This is the month a specified command will run on, it may be specified
	 numerically (0-12), or as the name of the month (e.g. May)
dow	This is the Day of Week that you want a command to be run on, it can
	 also be numeric (0-7) or as the name of the day (e.g. sun).
user	This is the user who runs the command.
cmd	This is the command that you want run. This field may contain 
	 multiple words or spaces.

If you don't wish to specify a value for a field, just place a * in the 
field.

e.g.
01 * * * * root echo "This command is run at one min past every hour"
17 8 * * * root echo "This command is run daily at 8:17 am"
17 20 * * * root echo "This command is run daily at 8:17 pm"
00 4 * * 0 root echo "This command is run at 4 am every Sunday"
* 4 * * Sun root echo "So is this"
42 4 1 * * root echo "This command is run 4:42 am every 1st of the month"
01 * 19 07 * root echo "This command is run hourly on the 19th of July"

Notes:

Under dow 0 and 7 are both Sunday.

If both the dom and dow are specified, the command will be executed when
either of the events happen. 
e.g.
* 12 16 * Mon root cmd
Will run cmd at midday every Monday and every 16th, and will produce the 
same result as both of these entries put together would:
* 12 16 * * root cmd
* 12 * * Mon root cmd

Vixie Cron also accepts lists in the fields. Lists can be in the form, 1,2,3 
(meaning 1 and 2 and 3) or 1-3 (also meaning 1 and 2 and 3).
e.g.
59 11 * * 1,2,3,4,5 root backup.sh
Will run backup.sh at 11:59 Monday, Tuesday, Wednesday, Thursday and Friday,
as will:
59 11 * * 1-5 root backup.sh 

Cron also supports 'step' values.
A value of */2 in the dom field would mean the command runs every two days
and likewise, */5 in the hours field would mean the command runs every 
5 hours.
e.g. 
* 12 10-16/2 * * root backup.sh
is the same as:
* 12 10,12,14,16 * * root backup.sh

*/15 9-17 * * * root connection.test
Will run connection.test every 15 mins between the hours or 9am and 5pm

Lists can also be combined with each other, or with steps:
* 12 1-15,17,20-25 * * root cmd
Will run cmd every midday between the 1st and the 15th as well as the 20th 
and 25th (inclusive) and also on the 17th of every month.
* 12 10-16/2 * * root backup.sh
is the same as:
* 12 10,12,14,16 * * root backup.sh

When using the names of weekdays or months, it isn't case sensitive, but only
the first three letters should be used, e.g. Mon, sun or Mar, jul.

Comments are allowed in crontabs, but they must be preceded with a '#', and
must be on a line by them self.  


Multiuser cron

As Unix is a multiuser OS, some of the apps have to be able to support 
multiple users, cron is one of these. Each user can have their own crontab
file, which can be created/edited/removed by the command crontab. This
command creates an individual crontab file and although this is a text file,
as the /etc/crontab is, it shouldn't be edited directly. The crontab file is
often stored in /var/spool/cron/crontabs/<user> (Unix/Slackware/*BSD), 
/var/spool/cron/<user> (RedHat) or /var/cron/tabs/<user> (SuSE), 
but might be kept elsewhere depending on what Un*x flavor you're running.

To edit (or create) your crontab file, use the command crontab -e, and this
will load up the editor specified in the environment variables EDITOR or 
VISUAL, to change the editor invoked on Bourne-compliant shells, try: 
cog@pingu $ export EDITOR=vi
On C shells:
cog@pingu $ setenv EDITOR vi
You can of course substitute vi for the text editor of your choice.

Your own personal crontab follows exactly the same format as the main
/etc/crontab file does, except that you need not specify the MAILTO 
variable, as this entry defaults to the process owner, so you would be mailed
the output anyway, but if you so wish, this variable can be specified.
You also need not have the user field in the crontab entries. e.g.

min hr dom month dow cmd

Once you have written your crontab file, and exited the editor, then it will
check the syntax of the file, and give you a chance to fix any errors.

If you want to write your crontab without using the crontab command, you can
write it in a normal text file, using your editor of choice, and then use the
crontab command to replace your current crontab with the file you just wrote.
e.g. if you wrote a crontab called cogs.cron.file, you would use the cmd

cog@pingu $ crontab cogs.cron.file

to replace your existing crontab with the one in cogs.cron.file.

You can use 

cog@pingu $ crontab -l 

to list your current crontab, and

cog@pingu $ crontab -r

will remove (i.e. delete) your current crontab.

Privileged users can also change other user's crontab with:

root@pingu # crontab -u  

and then following it with either the name of a file to replace the 
existing user's crontab, or one of the -e, -l or -r options.

According to the documentation the crontab command can be confused by the 
su command, so if you running a su'ed shell, then it is recommended you 
use the -u option anyway.

Controlling Access to cron

Cron has a built in feature of allowing you to specify who may, and who 
may not use it. It does this by the use of /etc/cron.allow and /etc/cron.deny
files. These files work the same way as the allow/deny files for other 
daemons do. To stop a user using cron, just put their name in cron.deny, to
allow a user put their name in the cron.allow. If you wanted to prevent all
users from using cron, you could add the line ALL to the cron.deny file:

root@pingu # echo ALL >>/etc/cron.deny

If you want user cog to be able to use cron, you would add the line cog 
to the cron.allow file:

root@pingu # echo cog >>/etc/cron.allow

If there is neither a cron.allow nor a cron.deny file, then the use of cron
is unrestricted (i.e. every user can use it).  If you were to put the name of
some users into the cron.allow file, without creating a cron.deny file, it
would have the same effect as creating a cron.deny file with ALL in it.
This means that any subsequent users that require cron access should be 
put in to the cron.allow file.  

Output from cron

As I've said before, the output from cron gets mailed to the owner of the
process, or the person specified in the MAILTO variable, but what if you
don't want that? If you want to mail the output to someone else, you can
just pipe the output to the command mail.
e.g.
 
cmd | mail -s "Subject of mail" user

If you wish to mail the output to someone not located on the machine, in the
above example, substitute user for the email address of the person who 
wishes to receive the output.

If you have a command that is run often, and you don't want to be emailed 
the output every time, you can redirect the output to a log file (or 
/dev/null, if you really don't want the output).
e,g

cmd >> log.file

Notice we're using two > signs so that the output appends the log file and 
doesn't clobber previous output.
The above example only redirects the standard output, not the standard error,
if you want all output stored in the log file, this should do the trick:

cmd >> logfile 2>&1

You can then set up a cron job that mails you the contents of the file at
specified time intervals, using the cmd:

mail -s "logfile for cmd" <log.file
 

Now you should be able to use cron to automate things a bit more.
A future file going into more detail, explaining the differences between 
the various different crons and with more worked examples, is planned.


Additional Reference:

Man pages: cron(8) crontab(5) crontab(1)

Book: _Running Linux_ (O'Reilly ISBN: 1-56592-469-X)


cog

© Copyright 2000 cogNiTioN <cognition@attrition.org>
2007/1/3

新年新bt:)

抓lqqm top10_mm照片的代码,

require 'watir'
require 'open-uri'

#$HIDE_IE = true
ie = Watir::IE.new

ie.goto("http://top10_mm.lqqm.net")
#ie.frame(:index, 3).show_links
#puts ie.frame(:index, 3).link(:text, "上一页").href
#$links = Array.new
has_next = true
if FileTest.exists? "lqqm_urls.msh"
  File.open("lqqm_urls.msh", 'rb') do |f|
    $image_urls = Marshal.load(f)
    p $image_urls
  end
else
  $image_urls = Hash.new
end
p $image_urls
count = 0
while has_next
  indexes = Array.new
  ie.frame(:index, 3).links.each_with_index do |l, idx|
    if l.href =~ /\/con\?B=\d+&F=M\.\d+.A&N=\d+&T=/
      #$links << l.href
      #puts l.href
      indexes << idx + 1
    end
  end
  indexes.each do |idx|
    #puts ie.frame(:index, 3).link(:index, idx).href
    ie.frame(:index, 3).link(:index, idx).click
    begin
      ie.frame(:index, 3).images.each do |img|
        s = img.src
        s["top10_mm.lqqm.net"] = "202.205.10.86"
        puts s
        
        next if s =~ /smilies\/icon_/
        next if $image_urls.has_key? s
        $image_urls[s] = 1
        begin
          open(s,"Accept"=>"image/png,*/*;q=0.5", 
"Keep-Alive"=>"300",
"Connection"=>"keep-alive") do |f| open("D:\\lqqm_top10mm_2\\#{count}.jpg", 'wb') do |fo| fo << f.read count += 1 end end rescue puts $! next end end rescue puts $! ensure ie.back end end begin ie.frame(:index, 3).link(:text, "上一页").click rescue puts $! break end end ie.close File.open("lqqm_urls.msh", 'wb') do |f| Marshal.dump($image_urls, f) puts "marshal OK!" end