Search

12/31/2008

realazy » Blog Archive » 使用 iframe 获取网页片段的一个好处

realazy » Blog Archive » 使用 iframe 获取网页片段的一个好处

1. 使用 XMLHttpRequest 直接访问 partial,获取 responseText 后赋予 index 页面上某个元素的 innerHTML 即可完成。partial 必须是一个纯粹的 HTML 片段(基于以上假设)。
2. 在页面上创建一个隐藏的 iframe, 使用 iframe 的 src 请求 partial, partial 可以作为一个完整的页面,里面包含 JavaScript,由 partial 里的 JS 完成替换 index 上页面片段替换。
但在第二种情况下,用户看到内容可能也只是 HTML 片段,但这却是一个完整的页面,一个可以执行 JS 的完整页面。我们只需检查这个页面的 parent 对象有没有我们预设的值,就可以判断它是不是在 iframe 之内了,然后我们可以让它跳转到正常的页面。

Magic Ink: Information Software and the Graphical Interface

Magic Ink: Information Software and the Graphical Interface
d.CAT- the RIA blog » 這個介面好

資訊呈現的畫面,本身也就是操作的介面

widget_sentences.png

UA Profiler

UA Profiler

Check Latency
This isn't actually a test. Many of the tests measure how long it takes for a resource to load, but the load time can vary greatly depending on the user's network latency. This page measures the average latency to the UA Profiler server, and then adjusts the timing thresholds throughout the remaining test pages accordingly. If you have high latency (slow network connection), the tests take longer to load. If you have low latency (fast network connection), the tests are run faster.
Connections per Hostname
When HTTP/1.1 was introduced with persistent connections enabled by default, the suggestion was that browsers open only two connections per hostname. Pages that had 10 or 20 resources served from a single hostname loaded slowly because the resources were downloaded two-at-a-time. Browsers have been increasing the number of connections opened per hostname, for example, IE went from 2 in IE7 to 6 in IE8. This test measures how many HTTP/1.1 connections are opened for the browser being tested.
Max Connections
The previous test measures maximum connections for a single hostname. This test measures the maximum number of connections a browser will open total - across all hostnames. The upper limit is 60, so if a browser actually supports more than that it'll still show up as 60.
Parallel Scripts
When most browsers start downloading an external script, they wait until the script is done downloading, parsed, and executed before starting any other downloads. Although parsing and executing scripts in order is important for maintaining code dependencies, it's possible to safely download scripts in parallel with other resources in the page (including other scripts). This test determines if scripts can be downloaded in parallel with other resources in the page.
Parallel Stylesheets
Similar to scripts, some browsers block all downloads once they start downloading a stylesheet. This test determines if stylesheets can be downloaded in parallel with other resources in the page.
Parallel Stylesheet and Inline Script
A lesser known performance problem is the problems caused when a stylesheet is followed by an inline script block. If a browser doesn't block when downloading stylesheets (as measured by the previous test), then a stylesheet followed by an image could both be downloaded in parallel. But suppose an inline script block was placed between the stylesheet's LINK tag and the image IMG tag. The result, for some browsers, is that the image isn't downloaded until the stylesheet finishes. The reason is that the image download must occur after the inline script block is executed (in case the script block itself inserts images or in some other way manipulates the DOM), and the inline script block doesn't execute until after the stylesheet is downloaded and parsed (in case the inline script block depends on CSS rules in the stylesheet). It's important to preserve the order of the stylesheet rules being applied to the page, followed by executing the inline script block, but there's no reason other resources shouldn't be downloaded in parallel and not applied to the page until after the inline script block is executed. A subtlety of this test is that if the test is determined to be a failure if the inline script is executed before the stylesheet is done downloading - although this is faster it could lead to unexpected behavior.
Prime the Cache
This page isn't a test - it merely loads resources that will be used in the next few pages to test caching.
Cache Expires
This test determines if a resource with a future expiration date is correctly read from the browser's cache, or issues an unnecessary HTTP request. This is really testing the browser's memory cache.
Cache Redirects
Many pages use redirects to send users from one page to another, for example http://google.com/ redirects to http://www.google.com/. Unfortunately, most browsers don't pay attention to the cache headers of these redirects, and force the user to endure the redirect over and over again. This test measures if a redirect for the page is cached when it has a future expiration date.
Cache Resource Redirects
Whereas the previous test measures redirect caching for the main page, this test measures redirect caching for resources in the page.
Link Prefetch
This test determines if the prefetch keyword for the link tag works. (See the link prefetch description in this MDC FAQ and in a working draft of the HTML 5 spec.) Prefetch is an easy way for web developers to download resources they know the user will need in the future.
Compression Supported
Compressing text responses typically reduces the number of bytes transmitted by approximately 70%. This test measures if the browser sends an Accept-Encoding header announcing support for compression.
data: URLs
A "data:" URL (aka an inline image), is a technique for embedding other resources directly into the main HTML document. Doing this avoids an extra HTTP request. This test checks if an image inserted using a "data:" URL is rendered correctly.

John Resig - Browser Page Load Performance
http://stevesouders.com/hammerhead/
http://stevesouders.com/cuzillion/

12/30/2008

H! Hover Selector

H! Hover Selector
1. use row_hover.call(this);
2. use "row_hover" in window rather than typeof window["row_hover"]
3. this.runtimeStyle.behavior="none" for one-time css expression


tr {
behavior: expression(
/*you can remove these following comments, make it clearner*/
("row_hover" in window)
/*detect wherther window.row_hover is declared*/
? window.row_hover.call(this)
/*call window.row_hover from */
: window.row_hover =
/*declare window.row_hover if it`s not declared*/
/*pretty cool, let`s put JS function here, huh!*/
function() {;
this.runtimeStyle.behavior = "none";
/*OK, remove `s behavior since it had finish his job*/
this.onmouseover = function() {
this.className = "hover";
};
/*go on~*/
this.onmouseout = function() {
this.className = "";
};
/*go on~*/
});
/*OK, that`s it~*/
}

/*Let`s make it compatible for most modern browsers*/
tr.hover, tr:hover{background:#336699;color:white;}

iPhone Human Interface Guidelines

iPhone Human Interface Guidelines
Apple JavaScript Coding Guidelines: Introduction to Apple JavaScript Coding Guidelines

12/28/2008

JavaScript timers - using functions and scope

JavaScript timers - using functions and scope - Robert’s talk - Web development and Internet trends
setElmBGColor function - using a function and scope


function setElmBGColor (bgColor) {
var currentElm = this;
setTimeout(function () {
currentElm.style.backgroundColor = bgColor;
}, 1000);
}

setElmBGColor function - using a function with scope and closure

function setElmBGColor (bgColor) {
setTimeout(function (elm) {
return function () {
elm.style.backgroundColor = bgColor;
};
}(this), 1000);
}

call - MDC

call - MDC
You can use call to chain constructors for an object, similar to Java. In the following example, the constructor for the product object is defined with two parameters, name and value. Another object, prod_dept, initializes its unique variable (dept) and calls the constructor for product in its constructor to initialize the other variables.


function product(name, value){
this.name = name;
if(value >= 1000)
this.value = 999;
else
this.value = value;
}

function prod_dept(name, value, dept){
this.dept = dept;
product.call(this, name, value);
}

prod_dept.prototype = new product();

// since 5 is less than 1000, value is set
cheese = new prod_dept("feta", 5, "food");

// since 5000 is above 1000, value will be 999
car = new prod_dept("honda", 5000, "auto");

12/22/2008

yui - custom event

yui - custom event
Step 1: Define a custom event


var onCustomEvent1 = new YAHOO.util.CustomEvent('onCustomEvent');

Step 2: Make methods subscribe to the event

onCustomEvent1.subscribe(method1);
onCustomEvent1.subscribe(method2);

etc.You can also pass arguments to the subscribe method, which can be accessed by the subscribed method, as explained below.

Step 3: Whenever that event is supposed to be triggerd, cause the event to be executed

onCustomEvent1.fire();

You can also pass arguments to the fire method, these arguments can then be accessed in the subscribe method explained below.

onCustomEvent1.fire({action:'fire'});
function method1(event, arguments, obj) {}

* event returns the name of the custom event
* arguments is the set of arguments that are passed in the fire event
* obj is the argument that is passed in the subscribe method.

var fooEvent = new YAHOO.util.CustomEvent('fooEvent');

fooEvent.subscribe(function (a, b, c) {
console.log(arguments); // ["fooEvent", [Object { hello="world"}], Object { foo="bar"}]
}, {foo: 'bar'})

fooEvent.fire({hello:'world'})

12/20/2008

YouTube - Taiwan will touch your heart

User Generated Charity 2.0 - Microfinance 與 Microcredit 的 Kiva 初體驗

User Generated Charity 2.0 - Microfinance 與 Microcredit 的 Kiva 初體驗
私募基金金主週記:Kiva 微型貸款初體驗

這幾天都在摸 Kiva ,對整個價值鍊又有更多的了解。由於 Paypal 贊助(這很重要),所以手續費全免,貸出的金額理論上 100% 會到申貸者身上,我放款 300 美金,申請微型貸款的人就會完整拿到 300 美金。但這個錢不是直接從 Kiva 撥下去,而是透過各國的微型貸款機構,也就是類似Grameen Bank(鄉村銀行)這樣的組織來進行。

各地的微型貸款組織從 Kiva 獲得金錢後,再轉給小販、小農,並且負責追蹤、輔導、寫報告、按月催討。這些 Microfinance 機構當然也都是非營利性質的社會企業,雖然不以營利為目的,但也是要吃飯、喝水、過生活的。所以申貸者還款時還要給利息,這些利息就是各地微型貸款機構的營運費用。

Kiva 本身目前不收利息,所以只能靠金主捐款。現在 Kiva 貸出去的錢大約 3 億台幣,在美國應該不算大錢,但對一天收入只有幾塊的地方而言,感覺應該很像 Blackstone 或 Carlyle 了。

Kiva作為一個網站型社會企業的策略調整
我的Kiva 怎麼生出下線了
賀!Kiva放款客戶超過20組!
很巧的是,昨天收到了最新一期的 COLORS 雜誌,主題是 Money,雜誌還附上了兩張類似海報的「Microcredit」漂亮文宣,是 Benetton 跟 Birima 這個組織聯名的,裡面很圖像式的告訴你微型貸款如何幫助那些每日生活費在1美金以下的人可以從事商業活動,改善生活,有99%的微型貸款者會還款,其中93%的貸款者可以因此獲利,平均2年內靠微型貸款增加一倍的收入。

Microfinance 在台灣-先進國家的微型貸款能成功嗎?-
Kiva大暴走,還款改成逐月回吐
《窮人的銀行家》─ 給窮人一根釣竿

尤努斯發現,窮人並不是由於好吃懶做或是天性愚笨,只是因為他們沒有財產擔保,所以不能向銀行借錢,於是只好日復一日被高利貸壓得喘不過氣,如果給窮人們一根釣竿,他們就能脫離貧困的生活,同時也能改變下一代的命運。

比起有錢人的還款率,窮人更重視信用,因為他們知道,他們唯有跟鄉間銀行進行小額借款,抱持良好信用,才能真正翻身,尤其是婦女,鄉間銀行的推行能讓婦女也加入改善家庭經濟的行列,尤努斯為了推展鄉間銀行,眼睜睜讓妻女離去,這份心意實屬難得可貴(後來他有結婚啦!)

INET6: 「Yahoo!奇摩字典」Ubiquity Script

INET6: 「Yahoo!奇摩字典」Ubiquity Script


CmdUtils.CreateCommand({
name: "fy",
homepage: "zhpy.googlecode.com",
author: {
name: "Fred Lin",
email: "gasolin+ubiquity@gmail.com"
},
license: "MIT",
description: "yahoo dict",
help: "fy [keyword]",

takes: {
"keyword": noun_arb_text
},

preview: function(pblock, directObject) {
searchText = jQuery.trim(directObject.text)
var previewTemplate = "輸入要搜尋的單字 ${query}";
var previewData = {
query: searchText
};
pblock.innerHTML = CmdUtils.renderTemplate(previewTemplate, previewData);
},

execute: function(directObject) {
var url = "http://tw.dictionary.yahoo.com/dictionary?s={QUERY}"
var urlString = url.replace("{QUERY}", directObject.text);
Utils.openUrlInBrowser(urlString);
}
})

Creating your own code swarm

Creating your own code swarm

code_swarm - Plurk from amir salihefendic on Vimeo.
http://vis.cs.ucdavis.edu/~ogawa/codeswarm/
http://code.google.com/p/codeswarm/
tag: svn, cvs

12/18/2008

Pike's Mozilla Firefox Extensions

Pike's Mozilla Firefox Extensions - Bookmark Backup

Description

Bookmark Backup is a simple extension that helps to keep your bookmarks (and optionally other Firefox settings) safe. Each time Firefox is closed, a copy of your bookmarks file will be made to a backup location. If Firefox's bookmarks become corrupted or lost, find the most recent uncorrupted backup and copy it into your profile folder. By default the backups can be found in the Backups folder inside Firefox's profile folder, though this location can be changed in Bookmark Backup's Options dialog.

Additionally, thanks to code contributed by Nickolay Ponomarev, other files may also be backed up along with the bookmarks file. You can specify which files to backup in the Options dialog. Just check the box for each type of setting you want backed up, any other files can be listed in the following text box separated by a | character. Please refer to the Firefox Support Knowledge Base for details about what data is stored in each file.

Please remember, this extension should be used in addition to a regular profile backup not as a replacement.

12/16/2008

strfriend - visualize regular expressions simply

strfriend - visualize regular expressions simply
example: /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]+\]|[^[\]]+)+\]|\\.|[^ >+~,(\[]+)+|[>+~])(\s*,\s*)?/g - from sizzle
2008-12-16_1007302 by you.
tag: regular expression regexp

12/15/2008

Conditional stylesheets vs CSS hacks? Answer: Neither!

Conditional stylesheets vs CSS hacks? Answer: Neither!

* Conditional stylesheets mean 1 or 2 additional HTTP requests to download
* As they are in the the <head>, the rendering of the page waits until they're totally loaded.
* Also - Yahoo's internal coding best practices do not recommend conditional stylesheets
* It can separate a single CSS rule into multiple files. I’ve spent a lot of time wondering “Where the eff is that rule coming from!?” when it turned out to be tucked away in a conditional stylesheet.



<!--[if lt IE 7 ]>
<body class="ie6"><![endif]-->
<!--[if IE 7 ]>
<body class="ie7"><![endif]-->
<!--[if IE 8 ]>
<body class="ie8"><![endif]-->
<!--[if !IE]>
--> <body><!--<![endif]-->

Ajaxian » More JavaScript Inheritance; Prototypes vs. Closures

Ajaxian » More JavaScript Inheritance; Prototypes vs. Closures
JavaScript Inheritance via Prototypes and Closures | ruzee.com - Steffen Rusitschka
Prototype-based


var A = function(){}; // This is the constructor of "A"
A.prototype.value = 1;
A.prototype.test = function() { alert(this.value); }
var a = new A(); // create an instance of A
alert(a.value); // => 1
alert(a.test()); // => 1

Closure-based

var C = function() {
// a private function
var print = function(msg) {
alert(msg);
};
this.value = 1;
this.test = function() {
print(this.value); // calls our private function
};
};
var c = new C();
alert(c.value); // => 1
alert(c.test()); // => 1

Ajaxian » CSS Spriting without background-image

Ajaxian » CSS Spriting without background-image
Jennifer Semtner.com :: Web Designer / Developer » Blog Archive » Extending CSS Spriting

1. You can’t attach alternate text to divs for accessibility purposes
2. CSS Spriting and the IE6 PNG fix are incompatible
3. The images will not print out on printouts unless the client option to print background images is selected (this is bad for logos and menus, etc)
4. For images in pages (that are not actually background images), it seems semantically bad to hide the image in CSS.

3 ways to do the css sprites.
1. background-image
2. image-map
3. image tab with rect.

YQL - converting the web to JSON with mock SQL

YQL - converting the web to JSON with mock SQL

Hence we need converters. You can use cURL and beautiful soup or roll your own hell of regular expressions. Alternatively you can use Yahoo Pipes to build your converter. Pipes is the bomb but a lot of people complained that there is no version control and that you need to use the very graphical interface to get to your data (which was the point of Pipes but let's not go there).

for all the open services that don't need authentication you can use these YQL statements as a REST API with JSON output and an optional callback function for JSON-P by adding it to http://query.yahooapis.com/v1/public/yql?. For example to get the latest three headlines from Ajaxian's RSS feed as JSON and wrap it in a function called leechajaxian do the following:

http://query.yahooapis.com/v1/public/yql?select title from rss where url="http://feeds.feedburner.com/ajaxian" limit 3

You can also search the web with YQL: http://query.yahooapis.com/v1/public/yql?q=select title,abstract,url from search.web where query="json" limit 3&format=json&callback=leechajaxian
What about screenscraping? You can get data from any valid HTML document using XPATH with select * from html. For example to get the first 3 tag links on my blog you can do the following:

http://query.yahooapis.com/v1/public/yql?q=select * from html where url="http://wait-till-i.com" and xpath='//a[@rel="tag"]' limit 3&format=json&callback=leechajaxian

yql test console
Creating an OAuth Application - YDN
Wait till I come! » Blog Archive » YQL is so the bomb to get web data as XML or JSON


<script type="text/javascript" charset="utf-8">
function photos(o){
var out = document.getElementById('photos');
var html = '';
for(var i=0;i<o.query.results.result.length;i++){
var cur = o.query.results.result[i];
html += ‘<img src="’+cur.thumbnail_url+’" alt="’+cur.abstract+’">’;
}
out.innerHTML = html;
}
</script>
<script type="text/javascript" src="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20search.images%20where%20query%3D%22rabbit%22%20and%20mimetype%20like%20%22%25jpeg%25%22&format=json&callback=photos"></script>

Beautiful Soup: We called him Tortoise because he taught us.
Beautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping. Three features make it powerful:

1. Beautiful Soup won't choke if you give it bad markup. It yields a parse tree that makes approximately as much sense as your original document. This is usually good enough to collect the data you need and run away.
2. Beautiful Soup provides a few simple methods and Pythonic idioms for navigating, searching, and modifying a parse tree: a toolkit for dissecting a document and extracting what you need. You don't have to create a custom parser for each application.
3. Beautiful Soup automatically converts incoming documents to Unicode and outgoing documents to UTF-8. You don't have to think about encodings, unless the document doesn't specify an encoding and Beautiful Soup can't autodetect one. Then you just have to specify the original encoding.

12/08/2008

Σ(i)總匯王

Σ(i)總匯王 (02)2929-4910
台北縣中和市中安街210號
營業時間 週一~週五 05:30~16:00
     假日    05:30~17:00
食在中永和 (35)

12/04/2008

維綸麵食館

維綸麵食館
地址:台北市汀州路三段293號
TEL:2368-2634

GNU Core Utilities - Wikipedia, the free encyclopedia

GNU Core Utilities - Wikipedia, the free encyclopedia
yes (Unix) - Wikipedia, the free encyclopedia


yes can be used to send an affirmative (or negative; e.g. yes n) response to any command that would otherwise request one, and thereby causing the command to run non-interactively.

This usage may be obsolete today, as most commands that would request response from the user have either a 'force' option (e.g., rm -f) or an 'assume-yes' option (e.g., apt-get -y in Debian).

As an example, the following:
rm -f *.txt
is equivalent to
yes | rm *.txt

» 编程珠玑番外篇-8.Smalltalk 中的珠玑 | 4G spaces

» 编程珠玑番外篇-8.Smalltalk 中的珠玑 | 4G spaces

关于反射的基本概念在脚本语言里面是屡见不鲜的了. 大家都知道, LISP 里面的 eval 后面可以加任何的字符串, 构造出一个运行时对象. 脚本语言实现反射也很简单: 本来就是解释执行的语言, 多一个 eval 等价于多调用一次解释器而已. 而编译型语言就麻烦了, 因为解释器已经在编译期用过了, 运行的时候解释器是不存在的. 这样, 就造成了编译型语言没有运行时信息这个本质困难. Smalltalk 用了一个巧妙的方法解决了这个问题, 也就是 Java 和 Python 等现代语言用的方法: 虚拟机. 能编译的代码被先编译, 需要解释的代码在运行时可以被虚拟机自带的解析器再解析. 除了加入一个小的解释器到虚拟机外, Smalltalk 更进一步, 把对象的元信息也抽象成一个对象, 这样运行时需要的一个对象的所有元信息都能在面向对象的标准框架下表达. 我们用类 Java 的语言来举例: 一个叫 a 的 Foo 对象, 包含一个 a.hello() 的方法, 这个方法既可以通过 a.hello() 来调用, 也可以通过 a.class 先得到 a 的类, 再通过 a.Class.findMethod(”hello”) 找到这个方法. 最后再通过 .invoke() 调用这个方法. 这样的流程在没有虚拟机的 C++ 里面是没法完成的.

现在做单元测试的框架, 一般都被称为 xUnit 家族. xUnit 家族最早的成员, 不是 JUnit, 而是 SUnit (Smalltalk Unit). SUnit 的历史比 Junit 悠久得多, 大约在1994年的时候, Kent Beck, 也就是 Junit 的作者之一, 写了 SUnit. 而后才有了 JUnit (1998). 所以, 在 SUnit 的网站上, 极其显摆的写着”一切单元测试框架之母” (The mother of all unit testing frameworks). 事实上这是大实话 — 所有单元测试框架里面的名词术语, 都从 Sunit 来的, 如 TestCase, Fixture 等等.

既然 SUnit 和 Junit 是同一个作者, 而早在1996年, Java 就已经成为工业界炙手可热的语言, 为什么要等到两年之后, JUnit 才横空出世呢. 这里面的原因说简单也简单: 自动单元测试需要反射支持. 1998 年前的 Java 没有反射, 直到1998年 Java 1.2 发布, 反射才完整的被支持. 所以, 只有1998年之后, Java 才有办法做自动单元测试.

我们回顾一下 Junit 的工作流程: 继承一个 TestCase, 加入很多以 test 开头的方法, 把自己的类加入 TestSuite 或者直接用 TestRunner, 让测试跑起来. Junit 能够自动覆盖所有 test 开头的方法, 输出红棒绿棒. 这地方的关键是自动覆盖. 假如每个测试都是靠程序员自己写 printf 比较, 那不叫自动. 假如每个 TestCase 里面的每个 test 开头的方法都要程序员自己写代码去调用, 那也不叫自动. 所谓的自动, 就是在机器和人之间形成一定的规约, 然后机器就去做繁琐的工作, 最小化人的工作(RoR就是很好的例子).

注意到我们的需求是 “让 Junit 自动调用以 test 开头的方法”, 而不需要自己很笨的一个一个自己去调用这些方法. 这意味着 Java 语言必须支持一个机制, 让 JUnit 知道一个测试类的所有方法名称, 然后还能挑出 test 开头的方法, 一一去调用. 这不就是反射么! 事实也证明了这一点: 目前互联网上找到的最早的 Junit 的源代码, 1.0 版的核心就只用了一个 Java 的标准库: reflect. 相反, 不支持反射的语言, 就得告诉单元测试的框架我要运行哪些. 比如说 C++ 的单元测试框架 CppUnit, 就很不方便–必须告诉框架我要测哪几个函数, 就算他们以 test 开头也不行. 还有一个好玩的例子是 J2ME 的测试框架. J2ME 是 Java 小型版, 不支持 reflect, 因此, JUnit 平移不上去. 如果细看所有的这些移植 JUnit 的尝试, 很容易发现, 移植出去的版本作用到有反射机制的语言上, 使用起来就很方便, 就比较成功, 比如NUnit; 没反射机制的就比较麻烦, 用的人也相对少, 比如 CppUnit 和 J2MEUnit. 反正任何对于 JUnit 的移植, 都绕不开”反射” 这个机制. 有反射者昌, 无反射者弱. NUnit 这个移植版本, 还曾经被 Kent Beck 夸设计好, 其原因, 与 C# 语言比 Java 更加良好的 attribute 和反射机制, 是息息相关的.


Reflection (computer science) - Wikipedia, the free encyclopedia
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behaviour. The programming paradigm driven by reflection is called reflective programming. It is a particular kind of metaprogramming.

In most modern computer architectures, program instructions are stored as data - hence the distinction between instruction and data is merely a matter of how the information is treated by the computer and programming language. Normally, 'instructions' are 'executed' and 'data' is 'processed'; however, in some languages, programs can also treat instructions as data and therefore make reflective modifications. Reflection is most commonly used in high-level virtual machine programming languages like Smalltalk and scripting languages, and less commonly used in manifestly typed and/or statically typed programming languages such as Java and C.

Metaprogramming - Wikipedia, the free encyclopedia

12/01/2008

[].slice

Array-like Objects in JavaScript - Blog - ShiftEleven
slice
this extracts a section of an array and returns a new array, and without a beginning and ending index, it simply returns a copy of the array


var $A = function(obj) {
return Array.prototype.slice.call(obj);
};
// Example usage:
$A(document.getElementsByTagName("li"));


JavaScript数组操作 - Richie - 博客园

//Supported by Firefox, IE6, IE7, Opera, Safari
var arrayLike = { 0:"ccc", 1:1, 2:"eee", 3:8, length:4 }; //an object that looks like an object
var trueArray = [].slice.call(arrayLike, 2, arrayLike.length); //make a new array with arrayLike
trueArray.push("2008-02-12");
document.write(trueArray.join(" | ")); //result: eee | 8 | 2008-02-12
document.write("
");


Array.prototype.map = function(callback){
if(!callback || typeof callback!="function") return this;
for(var i=0; i<this.length; i++) callback( this[i], i);
return this;
};

11/30/2008

document.compatMode and almost standards mode

http://chunghe.googlecode.com/svn/trunk/experiment/almost.standard.mode/
http://chunghe.googlecode.com/svn/trunk/experiment/almost.standard.mode/standard.mode.htm
document.compatMode - MDC


mode = document.compatMode


mode is a string containing "BackCompat" for Quirks mode or "CSS1Compat" for Strict mode.
There is a third mode, Gecko's "Almost_Standards" Mode, which only differs from Strict mode in the layout of images inside table cells. This third mode is reported the same way as Strict mode: "CSS1Compat".

Gecko's "Almost Standards" Mode - MDC - 在 almost standard mode 設定 img{display:block} or img{vertical-align:bottom} 看起來跟 standard mode 一模一樣
"Almost standards" rendering mode is exactly the same as "standards" mode in all details save one: the layout of images inside table cells is handled as they are in Gecko's "quirks" mode, which is fairly consistent with other browsers, such as Internet Explorer. This means that sliced-images-in-tables layouts are less likely to fall apart in Gecko-based browsers based on the rendering engine found in Mozilla 1.0.1 or later when in either "quirks" or "almost standards" mode. (See the DevEdge article "Images, Tables, and Mysterious Gaps" for a detailed explanation of how such layouts are treated in "standards" mode.)

The DOCTYPEs that will trigger "almost standards" mode are those which contain:

* The public identifier "-//W3C//DTD XHTML 1.0 Transitional//EN"
* The public identifier "-//W3C//DTD XHTML 1.0 Frameset//EN"
* The public identifier "-//W3C//DTD HTML 4.01 Transitional//EN", with a system identifier
* The public identifier "-//W3C//DTD HTML 4.01 Frameset//EN", with a system identifier
* The IBM system DOCTYPE "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd"

A complete DOCTYPE contains a public identifier and a system identifier.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

The parts are as follows:
* Public Identifier: "-//W3C//DTD HTML 4.01 Transitional//EN"
* System Identifier: "http://www.w3.org/TR/html4/loose.dtd"

Images, Tables, and Mysterious Gaps - MDC
Figure 3
The most crucial part of Figure 3 is the baseline (represented by the blue line), and its placement within the line box. The baseline's exact placement is dependent on the "default" font for the line box (represented by the red box), which is determined by the value of font-family for the element that contains the line box. It isn't possible for an author to change the baseline's position directly, so wherever it ends up is where it will be. The space below the baseline is referred to as "descender space" since that's where the descenders in lowercase letters like "j", "y", and "q" are drawn. Figure 4 shows what happens when we add an image to the mix.
Figure 4
Note where the image sits by default: its bottom edge is aligned with the baseline of the line box. This placement can be changed with vertical-align.
he other main choice is leave the image inline and alter the vertical alignment of the image with respect to the line box. For example, you could try the following:
td img {vertical-align: bottom;}

This will cause the bottom edges of the images to be aligned with the bottom of the line box, instead of the baseline.
here have been many proposals to fix the problem, but one of the most promising approaches is the property line-box-contain, which has been proposed for inclusion in CSS3. Should this property be adopted, then any browser supporting it could emulate traditional "shrinkwrap" behavior without risking other layout upset with the following rule:
td {line-box-contain: font replaced;}  /* proposed for CSS3 */

The Skinny on Doctypes

The Skinny on Doctypes
At Google, we have this obsession with byte size. And by byte size, any “lack-therof” the better. Therefore the doctype you will find on most Google webpages while still triggering the browser into “standards mode” is as simple as you see below:


<!doctype html>

[ref] All you need is <!doctype html> - David’s Web Development Blog
Website overview - Browsershots

11/28/2008

invert color


var invertColot = function(c) {
var t1 = '0123456789abcdef#'
var t2 = 'fedcba9876543210#'
return c.replace(/./gi, function(s){
return t2.charAt(t1.indexOf(s));
})
};

11/25/2008

Personas

Personas - from Wiley about face 3

To create a product that must satisfy a diverse audience of users, logic might tell you to make it as broad in its functionality as possible to accommodate the most people. This logic, however, is flawed. The best way to successfully accommodate a variety of users is to design for specific types of individuals with specific needs. When you broadly and arbitrarily extend a product’s functionality to include many constituencies, you increase the cognitive load and navigational overhead for all users. Facilities that may please some users will likely interfere with the satisfaction of others.

A simplified example of how personas are useful. If you try to design an automobile that pleases every possible driver, you end up with a car with every possible feature, but that pleases nobody. Software today is too often designed to please too many users, resulting in low user satisfaction. Figure 5-2 provides an alternative approach.

11/23/2008

Forms in HTML documents

Forms in HTML documents

The enctype attribute of the FORM element specifies the content type used to encode the form data set for submission to the server.
application/x-www-form-urlencoded
This is the default content type. Forms submitted with this content type must be encoded as follows:
1. Control names and values are escaped. Space characters are replaced by `+', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by `%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., `%0D%0A').
2. The control names/values are listed in the order they appear in the document. The name is separated from the value by `=' and name/value pairs are separated from each other by `&'.

multipart/form-data
The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
A "multipart/form-data" message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream. Part boundaries should not occur in any of the data; how this is done lies outside the scope of this specification.

11/19/2008

Code: Flickr Developer Blog » Lessons Learned while Building an iPhone Site

Code: Flickr Developer Blog » Lessons Learned while Building an iPhone Site

We did this by hijacking all links of the page: when a link is clicked, we intercept the event, fetch the page fragment using Ajax, and insert the HTML into a new div.
Using this system complicates your code a bit. You need JavaScript to handle the hijacking, the page fragment insertion, and the address bar hash changes (which allow the back and forward buttons to work normally). You also need your backend to recognize requests made with Ajax, and to only send the page content instead of the full HTML document. And lastly, if you want normal URLs to work, and each of your pages to be bookmarkable, you will need even more JavaScript.

3. Don’t Build for Just One Device
Most of the differences lie in layout. It’s important to structure your pages around a grid that can expand as a percentage of the page width. This allows your layouts to work on many different screen sizes and orientations. The iPhone, for example, allows both landscape and portrait viewing styles, which have vastly different layout requirements. By using percentages, you can have the content fill the screen regardless of orientation. Another option is to detect viewport width and height, and use JavaScript to dynamically adjust classes based on those measurements (but we found this was overkill; CSS can handle most situations on its own).

5. Tell the User What is Happening
To combat this problem, we added loading indicators to every link. These tell the user that something is happening, and reassures them that their action was detected. It also makes the pages seem to load much faster, since something is happening right away; In our testing, these indicators were the difference between a UI that seems snappy and responsive, and one that seemed slow and inconsistent.

One Easy Option

The iUI framework implements a lot of these practices for you, and might be a good place to start in developing any mobile site (though keep in mind it was developed specifically for the iPhone). We found it especially useful in the early stages of development, though eventually we pulled it out and wrote custom code to run the site.

ydn-javascript : Message: Re: [ydn-javascript] grids not valid css when validating css against w3.org

ydn-javascript : Message: Re: [ydn-javascript] grids not valid css when validating css against w3.org

First, YUI Fonts sets *font-size:small; and *font:x-small; after initially setting a pixel font size. They are both instances of what I described above for IE, however "*font:x-small;" is also flagged for a different reason. The "font:" syntax is shorthand for all of the various font- properties (family, weight, line-height, etc). It is an error to use shorthand without specifying all the values. When IE is in Quirks Mode is don't fail on this error, and instead applies the value. So, by taking advantage of this mode-specific behavior in IE I can efficiently pass one value to Quirks Mode and another value to Standards Mode. I need to do this because the default font size is different in the two modes. (YUI recommends you use Standards Mode, but we strive for the library to work well in both modes.)
A Philosophical Note
A final note: Some CSS developers advocate that non-standard or non-valid CSS used to accommodate a specific browser's peculiarities should be quarantined within a discrete .css file that is provided to that specific browser only. (For IE, it's often delivered via "conditional comments.") Another argument suggests that filters and hacks should always be isolated to facilitate long-term maintenance. I do not generally contest those points of view, however, I feel that when developing library/framework code (as opposed to authoring site-specific code), the decision has different criteria. I think keeping keeping all the CSS for all the browsers in a single file makes the library easier to use, and helps it perform optimally (because it reduces HTTP requests). And I think the maintenance issue is less critical for library code since the library has dedicated custodians tending to it permanently.

11/18/2008

YouTube - 【汚部屋☆47】Honeyを踊ってみた。

YouTube - 【汚部屋☆47】Honeyを踊ってみた。

Ajaxian » Testing Ext Applications With Selenium

Ajaxian » Testing Ext Applications With Selenium - 除了 Selenium ide 以外還有 selenium rc 可以把 browser 叫起來執行預錄下來的 script.

Selenium IDE provides a great way to create your tests and execute them in Firefox. Tests can only be run by manually opening Firefox and executing tests. What if you want to run you want to automate your tests and run them in other browsers? This is where Selenium Remote Control comes into play.

From the Selenium website: “Selenium Remote Control (RC) is a test tool that allows you to write automated web application UI tests in any programming language against any HTTP website using any mainstream JavaScript-enabled browser. Selenium RC comes in two parts. 1. A server which automatically launches and kills browsers, and acts as a HTTP proxy for web requests from them. 2. Client libraries for your favorite computer language.

Ajaxian » How Do You Prototype Your Apps?

Ajaxian » How Do You Prototype Your Apps?
Interface Driven Requirements Docs | commadot.com - 這篇的 powerpoint 用法真是神乎其技
其他在這篇提到的 prototyping tool還有
http://irise.com
http://axure.com - very popular
Wireframe Wonder To Speed Up Web Development - Social media, web development and digital life - JungleG

Popular JavaScript Framework Libraries: An Overview - Part 2 / Page 2

Popular JavaScript Framework Libraries: An Overview - Part 2 / Page 2

YAHOO.lang.extend provides a simple mechanism for setting up the prototype, constructor and superclass properties for objects that are extending other objects. It also prevents the constructor of the extended object (i.e., the superclass) from being executed twice. Let's take a look at an example. The following code assigns a namespace for our classes, creates a Person superclass and a child Investor class that inherits from it. You can see that code conciseness is being traded for clarity. Depending on your personal views, you may prefer a $ sign over YAHOO.test:


YAHOO.namespace("test");

YAHOO.test.Person = function(name) {
alert("Hi, I'm " + name);
};

YAHOO.test.Person.prototype.speak = function(words) {
alert(words);
};

YAHOO.test.Investor = function(name) {
// chain the constructors
YAHOO.test.Investor.superclass.constructor.call(this, name);
alert("Hi, my name is " + name + " and I'm an investor.");
};

// Investor extends Person. Must be done immediately after the Investor constructor
YAHOO.lang.extend(YAHOO.test.Investor, YAHOO.test.Person);

YAHOO.test.Investor.prototype.speak = function(words) {
// chain the method
YAHOO.test.Investor.superclass.speak.call(this, words);
alert("It has not been a good year for investors!");
};

var investor = new YAHOO.test.Investor("Bill");
investor.speak("I don't feel so good.");

11/17/2008

Getting your ASCII on with Flickr - Nihilogic

Getting your ASCII on with Flickr - Nihilogic

The Flickr search part is pretty straight forward. A single request is sent, calling the "flickr.photos.search" method. We then get a list of photos from Flickr, but we can't access the data in these directly due to the same-origin policy of the Canvas element. To get around this, we're using a small proxy script (written in PHP) that does nothing other than retrieve the image file and pass it straight through to the browser.

The image is then painted (and downscaled since we're not using all pixels) on a hidden Canvas element, the image data is retrieved using getImageData() and each pixel in the image is analyzed. The brightness of the pixel is calculated using a simple RGB to brightness formula and this level of brightness is then mapped to a list of characters selected for their varying apparent brightness. The list used here is [ .,:;i1tfLCG08@] for black/white output and [ CGO08@] for colored output.

jsAscii - ASCII art from images with Javascript and Canvas - Nihilogic
tag: ascii, asciified

Code: Flickr Developer Blog » On UI Quality (The Little Things): Client-side Image Resizing

Code: Flickr Developer Blog » On UI Quality (The Little Things): Client-side Image Resizing

Tweaking image resampling in IE

IE 7 supports high-quality bicubic image resampling, producing results akin to what you’d see in most image editing programs. It’s disabled by default, but you can enable it using -ms-interpolation-mode:bicubic;. It’s probably safest to apply this only to images you are explicitly showing at non-native sizes.

IE 6 is a riskier proposition, but can show improved image resizing when the AlphaImageLoader CSS filter is applied, the same filter commonly used for properly displaying PNGs with alpha transparency. For example, filter:progid:DXImageTransform.Microsoft.AlphaImageLoader (src='/path/to/image.jpg', sizingMethod='scale');. While there is no transparency to apply here, the resizing method applied gives a higher-quality result.

Clickjacking

Dealing with UI redress vulnerabilities inherent to the current web
[whatwg] Dealing with UI redress vulnerabilities inherent to the current web
hackademix.net » Clickjacking and NoScript

11/16/2008

物件導向Javascript - 封裝

物件導向Javascript - 封裝

可以把Javascript看成用 execution context 為單位組成的結構,javascript在執行的時候,會在不同的 execution context 間切換。 execution context 有三種: Global , Function 以及 Eval 。Javascript變數解析的規則叫做 scope chain ,每次進入不同的 execution context ,執行環境就會為它建立一個 scope chain ,結構類似一個堆疊,目前正在執行的 execution context 放在堆疊的最上面,然後依次是其他的 execution context 。舉例來說,當函數a裡面定義了另一個函數b,那在執行函數b裡面的程式時, scope chain 會像是:b->a->Global,Javascript會依照這個順序尋找變數、函數等的定義。(還是有點像天書)>


function test() {
global1 = 1;
var private1 = 2;
}
function check() {
alert(global1);
}
test();
check();

用 scope chain 規則來解釋:當執行test()時,碰到了global1這個東西,在test函數裡面並沒有定義,所以執行環境到 Global 找,也沒找到,然後執行環境就在 Global 定義了一個變數,名稱叫做global1,然後把1這個值assign給他。之後執行check(),碰到 global1這個東西,在check函數裡面也沒定義,所以執行環境跑到 scope chain 中的下一個 execution context ,也就是 Global 中找,然後找到了。所以alert()就會秀出1。

javascript datatype

javascript的data type可以分為(1) primitive type (2) reference type (objects)
primitive: fixed size in memory, ex: numbers, boolean values, null, undefined
reference(objects): can be of any length, ex: array, objects, functions.


var a = 3.14; // Declare and initialize a variable
var b = a; // Copy the variable's value to a new variable
a = 4; // Modify the value of the original variable
alert(b) // Displays 3.14; the copy has not changed


var a = [1,2,3]; // Initialize a variable to refer to an array
var b = a; // Copy that reference into a new variable
a[0] = 99; // Modify the array using the original reference
alert(b); // Display the changed array [99,2,3] using the new reference

11/15/2008

uesrful imagemagick command

// convert images to png8
convert foo.png png8:foo.png


# Use a simple shell loop, to process each of the images.
mkdir thumbnails
for $f in *.jpg
do convert $f -thumbnail 200x90 thumbnails/$f.gif
done

# Use find to substitute filenames into a 'convert' command
# This also provides the ability to recurse though directories by removing
# the -prune option, as well as doing other file checks (like image type,
# or the disk space used by an image).
find * -prune -name '*.jpg' \
-exec convert '{}' -thumbnail 200x90 thumbnails/'{}'.gif \;

# Use xargs -- with a shell wrapper to put the argument into a variable
# This can be combined with either "find" or "ls" to list filenames.
ls *.jpg | xargs -n1 sh -c 'convert $0 -thumbnail 200x90 thumbnails/$0.gif'

# An alternative method on linux (rather than plain unix)
# This does not need a shell to handle the argument.
ls *.jpg | xargs -I FILE convert FILE -thumbnail 200x90 th_FILE.gif

ImageMagick: One-Second Gradient Images
generate a image named temp.png with gradient from #000 to #fff
convert -size 300x200 gradient:'#000'-'#fff' temp.png
在window下必須改寫為雙引號
convert -size 300x200 gradient:"#000"-"#fff" temp.png
Canvas Creation -- IM v6 Examples
For example you can use a Sigmoidal Contrast function to create a more natural looking gradient.
convert -size 100x100 gradient: -sigmoidal-contrast 6,50% gradient_sigmoidal.jpg
Fundamentals of Image Processing
draw a 100x100 transparent canvas, then draw a red line from 10,10 to 90,90
convert -size 100x100 xc:none -fill red -draw "line 10,10 90,90" output.png
the fill color draws the line, not the stroke color. Note that setting the stroke width doesn't affect the images; however, the linewidth setting will change the width of the line
The arguments to the circle shape are slightly different from the rectangle shape. The first
argument is the center of the circle, and the second argument is how far the circle extends.
create a transparent canvas and a circle
-draw 'circle 50,50 50,80' 圓心在50,50 半徑從50到80
convert -size 200x200 xc:none -fill gray20 -draw "circle 100,100 30,30" output.png
create a transparent canvas and a rect with blue background and 20px red border
convert -size 100x100 xc:none -fill blue -stroke red -strokewidth 20 -draw "rectagnel 10,10 90,90" rect.png

Image Optimization, Part 3: Four Steps to File Size Reduction » Yahoo! User Interface Blog

Image Optimization, Part 3: Four Steps to File Size Reduction » Yahoo! User Interface Blog
< pngcrush -rem alla -brute -reduce src.png dest.png
* src.png is the source image, dest.png is the destination (result) image
* -rem alla means remove all chunks but keeps the one for transparency
* -reduce tries to reduce the number of colors in the palette if this is possible
* -brute tries over a hundred different methods for optimization in addition to the default 10. It’s slower and most of the times doesn’t improve much. But if you’re doing this process “offline”, one or two more seconds are not important since there’s a chance if a filesize win. Remove this option in performance-sensitive scenarios.
Here's a command to copy the source image, optimize it and don’t carry over any metadata in the new copy:
< jpegtran -copy none -optimize src.jpg dest.jpg
You may be able to further improve image size by using jpegtran's -progressive option. It produces JPEGs that load progressively in the browser, starting from a lower quality version of the image and improving as new image information arrives. You can see this behavior if you look at photos on Picassa, but you have to switch photos fast, because otherwise while you’re looking at one, the next one is being preloaded.
Important note on stripping meta information: do it only for images that you own, because when jpegtan strips all the meta, it also strips any copyright information contained in the image file.
In order to automatically change your GIFs, you can use ImageMagick’s convert:
< convert image.gif image.png
If you want to force PNG8 format you can use:
< convert image.gif PNG8:image.png
tools:
1. ImageMagick to identify the image type and to convert GIFs to PNG.
2. pngcrush to strip unneeded chunks from PNGs. We're currently experimenting with other PNG tools such as pngout, optipng, pngrewrite that will allow for even better png optimization.
3. jpegtran to strip all meta data from JPEGs (currently disabled) and try progressive JPEGs.
4. gifsicle to optimize GIF animations by striping repeating pixels in different frames.

11/14/2008

call() and apply()

obj.method.call(another_obj, param1, param2)
obj.method.apply(another_obj, [param1, param2])

function f() {
var args = [].slice.call(arguments, 1, 3);
return args;
}

>>> f(1, 2, 3, 4, 5, 6)
2,3

[].slice.call can also be Array.prototype.slice.call

function one() {
alert(1);
return function() {
alert(2);
}
}
>>> my = one(); // alerts 1
>>> my(); // alerts 2

Adding properties to the function objects, e.g. cache, 'coz functions are objects

function myFunc(param){
if (!myFunc.cache) {
myFunc.cache = {};
}
if (!myFunc.cache[param]) {
var result = {}; // …
myFunc.cache[param] = result;
}
return myFunc.cache[param];
}

a is private, sayAh() is privileged

function MyConstr() {
var a = 1;
this.sayAh = function() {
return a;
};
}

>>> new MyConstr().sayAh();

Protoscript - Popup Behavior Demo

Protoscript - Popup Behavior Demo

Protoscript is a simplified scripting language for creating Ajax style prototypes for the Web. With Protoscript it's easy to bring interface elements to life. Simply connect them to behaviors and events to create complex interactions.


$proto('img#avatar', {
Click: {
onClick: {
Fade: {
opacity: {to: 0},
onComplete: {Close : {} }
}
}
}
});

11/11/2008

Plank - Lang's little gems

Plank - Lang's little gems

 YAHOO.lang.substitute('Hello {world}', {'world':'earth'});  


var foo = {
count :0,
'method' : function(data) {
this.count++;
if(this.count == 10) {
timer.cancel();
}
console.log(this.count);
}
}
var timer = YAHOO.lang.later(1000, foo, 'method', [{data:'bar', data2:'zeta'}], true);


var myAwesomelWidget = function(oConfigs) {
oConfigs = oConfigs || {};
var defaults = {
'awesomeness' : '11',
'shiny' : 'high',
'sparkle' : 'high'
}
var combinedConfigs = YAHOO.lang.merge(defaults, oConfigs);
//Shiny is now set to low, everything else in combinedConfigs is set to the defaults
};
myAwesomelWidget({'shiny': 'low'});`

Ajaxian » Reminded of speaking your YAHOO.lang

Gotcha (programming) - Wikipedia, the free encyclopedia

Gotcha (programming) - Wikipedia, the free encyclopedia

In programming, a gotcha is a feature of a system, a program or a programming language that works in the way it is documented but is counter-intuitive and almost invites mistakes because it is both enticingly easy to invoke and completely unexpected and/or unreasonable in its outcome.

Yahoo! Front End Developer's Summit 2008 - Tal

Yahoo! Front End Developer's Summit 2008 - Talk

Back To The Future
View SlideShare presentation or Upload your own. (tags: f2esummit2008 f2esummit)

Resize or Scaling -- IM v6 Examples

Resize or Scaling -- IM v6 Examples

Image Optimization Part 2: Selecting the Right File Format » Yahoo! User Interface Blog

A List Apart: Articles: Cross-Browser Variable Opacity with PNG: A Real Solution

Whereas PNG supports alpha transparency, GIF only supports binary transparency

Image Optimization Part 2: Selecting the Right File Format » Yahoo! User Interface Blog - 這篇講得很詳細。
GIF
* GIF is a palette (also called “indexed”) type of image. It contains a palette of indexed colors, up to 256, and for every pixel of the image there is a corresponding color index.
* GIF is a non-lossy format, which means that when you modify the image and save it, you don’t lose quality.
* GIF also supports transparency, which is a sort of boolean type of transparency. A pixel in a GIF image is either fully transparent or it's fully opaque.

JPEG
* JPEG doesn’t have the 256 colors restriction associated with GIFs; it can contain millions of colors and it has great compression.
* It's a lossy format, meaning you lose quality with every edit, so it’s best to store the intermediate results in a different format if you plan to have many edits.
* There are, however, some operations that can be performed losslessly, such as cropping a part of the image, rotating it or modifying meta information, such as comments stored in the image file.
* JPEG doesn't support transparency.

PNG
* PNGs is a non-lossy format that comes in several kinds, but for practical purposes, we can think of PNGs as being of two kinds: 1. PNG8, and 2. truecolor PNGs.
* PNG8 is a palette image format, just like GIF, and 8 stands for 8 bits, or 28, or 256, the number of palette entries. The terms "PNG8", "palette PNG" and "indexed PNG" are used interchangeably.
* How does PNG8 compare to GIF? Pros: (1) it usually yields a smaller file size. (2) it supports alpha (variable) transparency. Cons: (1) no animation support
* The second type of PNGs, truecolor PNGs, can have millions of colors, like JPEG. You can also sometimes come across the names PNG24 or PNG32.
* And how does truecolor PNG compare to JPEG? On the pros side, it's non-lossy and supports alpha transparency, but on the cons side, the file size is bigger.
* This makes truecolor PNG an ideal format as an intermediate between several edits of a JPEG and also in cases where every pixel matters and the file size doesn't matter much, such as taking screeenshots for a help manual or some printed material.

Internet Explorer and PNG transparency
* With PNG8, whenever you have semi-transparent pixels they appear as fully transparent in IE (version 6 and lower). This is not ideal but it’s still useful and is the same behavior that you get from a GIF.
* Below is an example that illustrates this, note how in IE6 the semi-transparent light around the bulb is missing
PNG8 alpha transparency
* For truecolor PNGs, the situation is a much less attractive compromise. All the semi transparent pixels appear grey in IE prior to version 7
* IE7 introduces proper native support for alpha transparency in both PNG8 and truecolor PNGs. For earlier IE versions you need to fix the truecolor PNG transparency issue using CSS and an AlphaImageLoader filter
* Although PNG8 should be the preferred of the PNGs, because it’s smaller in filesize and degrades well in early IEs without special CSS filters, there are still some use cases for truecolor PNGs:
(1) When the 256 colors of the PNG8 are not enough, you may need a truecolor PNG: in the other hand, if the colors are around a thousand or so, you may try to convert this image to a PNG8 and see if it looks acceptable. Very often, the human eye is not sensitive enough to tell the difference between 200 and 1000 colors. That depends on the image, of course; often you can safely remove 1000 colors, but sometimes removing even 2 colors results in an unacceptable image.
(2) When most of the image is semi-transparent: If only a small part of the image is semi-transparent, like around rounded corners, the GIF-like degradation of PNG8 is often OK. But if most of the image is translucent (think a PLAY button over a video thumbnail), you might not have a choice but to use the AlphaImageLoader hack.

Conclusion
* JPEG is the format for photos.
* GIF is the format for animations.
* PNG8 is the format for everything else — icons, buttons, backgrounds, graphs…you name it.

11/10/2008

YUI: Weighing in on Pageweights » Yahoo! User Interface Blog

YUI: Weighing in on Pageweights » Yahoo! User Interface BlogA la Carte Pageweight of Individual YUI JavaScript Components, Including All Dependencies

Loading YUI: Seeds, Core, and Combo-handling » Yahoo! User Interface Blog

Loading YUI: Seeds, Core, and Combo-handling » Yahoo! User Interface Blog
Loading TabView with YUI Loader
Loading TabView with YUI Loader + YUI Core as a foundation.
K-weight for common YUI components.
2. Using YUI Loader Plus Core as a Seed File
1. Using YUI Loader as a Seed File
* You have access to Event Utility’s event listener methods and its crucial page-timing methods (like onDOMReady and onContentReady) right away;
* You have access to the Dom Collection’s swiss-army knife of DOM convenience methods right away.


<script type="text/javascript"
src="http://yui.yahooapis.com/combo?2.6.0/build/yuiloader-dom-event/yuiloader-dom-event.js"></script>
<script>
(function() {
//create Loader instance:
var loader = new YAHOO.util.YUILoader({
require: ["tabview"],
onSuccess: function() {
//when TabView is loaded, instantiate Tabs:
var tabView = new YAHOO.widget.TabView('demo');
},
combine: true
});

//When our target element is ready, bring
//in the non-blocking, combo-handled script
//download. We can use Event here because
//we've loaded YUI Core at the top of the page:
YAHOO.util.Event.onContentReady("demo", function() {
loader.insert();
});

})();


3. Combining All Requests in a Single FileBest practice according to Yahoo’s
Exceptional Performance guidelines would be to put this single file as close to the bottom of the page as possible, allowing the content and design to be processed before the browser hits your JS files. (Note: this is one reason why you might find approaches 1 and 2 useful — putting the 17.4KB YUI Loader + YUI Core file at the top of your file has minimal performance impact, and it allows you to load other JavaScript-dependent modules onDOMReady where appropriate.)

YAHOO.env.modules & YAHOO.env.ua

YAHOO.env.modules裡面紀錄著該頁所用的所有yui componets and version number.
YAHOO.env.ua裡面紀錄著user agent and version number.
每一個 yui components 通過 YAHOO.register把自己的information紀錄在YAHOO.evn.modules這個object裡面。ex: YAHOO.register("editor", YAHOO.widget.Editor, {version: "2.6.0", build: "1321"});
2008-11-10_102619

11/07/2008

Master the Linux bash command line with these 10 shortcuts

Master the Linux bash command line with these 10 shortcuts

4. Use key shortcuts to efficiently edit the command line
bash supports a number of keyboard shortcuts for command-line navigation and editing. The Ctrl-A key shortcut moves the cursor to the beginning of the command line, while the Ctrl-E shortcut moves the cursor to the end of the command line. The Ctrl-W shortcut deletes the word immediately before the cursor, while the Ctrl-K shortcut deletes everything immediately after the cursor. You can undo a deletion with Ctrl-Y.

7. Quickly jump to frequently-used directories
You probably already know that the $PATH variable lists bash's "search path" - the directories it will search when it can't find the requested file in the current directory. However, bash also supports the $CDPATH variable, which lists the directories the cd command will look in when attempting to change directories. To use this feature, assign a directory list to the $CDPATH variable, as shown in the example below:
bash> CDPATH='.:~:/usr/local/apache/htdocs:/disk1/backups'
bash> export CDPATH

Now, whenever you use the cd command, bash will check all the directories in the $CDPATH list for matches to the directory name.

Alphanum: Javascript Natural Sorting Algorithm

這篇提到的問題跟我之前遇到的一模一樣,只要把str modified過之後,存回變數本身,IE就變得怪怪的,我遇到的狀況是會死在sorting function裡面,不過也不是每一次都會發生,ex: a = 'foo.png'; a = a.slice(0, a.indexOf('.'));,解決的辦法就是用另外一個變數來接。
Alphanum: Javascript Natural Sorting Algorithm - The Roost - by Brian Huisman

  a = chunkify(a);
b = chunkify(b);

Note the variable names, where the assignment tries to place the result back into the original variable. Actually, all that's required for the bug to manifest is to assign any array to the incoming a and b variables. For some strange reason this would fail in IE6 and IE7 while sorting arrays with larger than 23 or 24 elements. In these cases, at seemingly random times during the sort, "undefined" would be passed back to a, causing the next reference to it to trigger an exception.

11/06/2008

SproutCore

SproutCore » demos
SproutCore - Wikipedia, the free encyclopedia

SproutCore is an open source JavaScript framework. Its goal is to allow developers to create web applications with advanced capabilities and the feel of desktop applications. It uses Ruby to generate static HTML and JavaScript files. SproutCore, initially created in 2007 by Sproutit as the basis for their Mailroom application, is available under the MIT License.

Apple announced MobileMe at WWDC in 2008, noting that much of it was built using SproutCore. Apple has contributed greatly to the project as part of a Web 2.0 initiative.

10/28/2008

IE vs. FireFox 系列 - showModalDialog

IE vs. FireFox 系列 - showModalDialog
window.open - MDC

modal
Note: Starting with Mozilla 1.2.1, this feature requires the UniversalBrowserWrite privilege ( bug 180048 ). Without this privilege, it is ignored.
If set to yes, the new window is said to be modal. The user cannot return to the main window until the modal window is closed. A typical modal window is created by the alert() function.
The exact behavior of modal windows depends on the platform and on the Mozilla release version.

Blog.XDite.net » 在 Linux 上架設 Screenshot Service

Blog.XDite.net » 在 Linux 上架設 Screenshot Service


killall firefox Xvfb
Xvfb :2 -screen 0 1024x768x24 -fbdir /tmp -nolisten inet6 & sleep 10
DISPLAY=:2.0 firefox -width 1024 -height 768 http://www.google.com &
sleep 10
xwd -display :2.0 -root -out shot.xwd
xwdtopnm shot.xwd> shot.pnm
pnmscale -xysize 200 150 shot.pnm> shotsmall.pnm
pnmtojpeg shotsmall.pnm> shot_thumb.jpg
pnmtojpeg shot.pnm> shot.jpg

大吉祥香豆腐(富)

大吉祥香豆腐(富) - iPeen 愛評網-最豐富的美食餐廳情報集散地
營業時間:週一至週六11點到20點(不過客人多可能提早賣完)

地址:北縣淡水鎮北新路182巷3弄28號

10/27/2008

Overflow Auto and Position Relative

ie6 overflow:auto不起作用的情况 - DotNet开发之路 - 博客园

今天遇到一个比较特殊的情况:ie6下设置overflow:auto不起作用,在火狐下正常显示。ie下滚动条是出来了,但是内容却跑到下面去了,滚动条行同虚设。网上搜索了一下都说是设置高度和宽度就ok了,开始还以为是百分比高度引起的,但设置成绝对高度200px后还是不行。最后通过经验判断出原来是overflow的那个div没有position定位,给加了个定位和top,left属性后一切都正常了!汗,实际开发中遇到的问题远远比预料的多啊,这或许是为什么软件项目开发总是延迟,尽管开发人员加班加点成了家常便饭还是不可避免的。

Overflow Auto and Position Relative 在 ie 的 standard mode下,container設定overflow:auto; 裡面的element設定position:relative的話,一樣會visible,解決的辦法是在container也加上position:relative
http://chunghe.googlecode.com/svn/trunk/experiment/overflow.auto.and.position.relative/before.htm
http://chunghe.googlecode.com/svn/trunk/experiment/overflow.auto.and.position.relative/after.htm

Website overview - Browsershots

Website overview - Browsershots - It's free!

在ie下TABLE、 TFOOT、 THEAD 和 TR 項目 innerHTML 屬性是唯讀屬性

在 Internet Explorer 設定 Table.innerHTML PRB: 錯誤

發生的原因
為 TABLE、 TFOOT、 THEAD 和 TR 項目 innerHTML 屬性是唯讀屬性。
解決方案
若要變更這些項目, 資料表的內容使用資料表物件模型或文件物件模型 (DOM)。

Ajaxian » innerHTML Gotchas
In IE you can’t use innerHTML or outerHTML on tables and instead e to use the “table model”. On MSDN refer to IHTMLTableSection and IHTMLTableRow for methods to insert rows/cells into a table.

Today’s hack is brought to us by Microsoft’s lunacy:
var innerHTML = “Hello world!”;
var div = document.createElement(”DIV”);
div.innerHTML = “” + innerHTML + “
”;
// Get the tr from the table in the div
var trElem = div.getElementsByTagName(”TR”)[0];

deleteCell Method (IHTMLTableRow)
IHTMLTableSection Interface ()

localeCompare

如何用javascript做中文排序 @ 雜七雜八的kewang部落格 :: PIXNET 痞客邦 ::

看了這兩篇「JavaScript中实现数组的排序、乱序和搜索。」和「利用JavaScript的sort()对包含汉字字符串数组进行排序」之後,才知道javascript有localeCompare()這種函式可以拿來做本地化的字串比較。

localeCompare的使用方法就是像這樣:
ret = '國立宜蘭大學'.localeCompare('國立台灣大學')

原始字串(國立宜蘭大學)跟要比較的字串(國立台灣大學)做比較,如果原始字串比較小的話,則ret就會傳回小於0的數字;如果比較大的話,則傳回大於0的數字;如果相等就傳回0。

http://chunghe.googlecode.com/svn/trunk/experiment/sort.by.filename.htm


function sortByFileName(a, b){
var x = parseInt(a);
var y = parseInt(b);
if(( isNaN(x)) || (isNaN(y)))
return a.localeCompare(b);
return x-y;
}

10/26/2008

萬華美食

食尚玩家2007-10-13 萬華夜市超猛又好呷-生活好料理食譜-新浪部落
福州元祖胡椒餅
和平西路三段109巷裏
2308-3075

西昌街青草巷:百年青草店
四知青草葯膏
台北市西昌街224巷5號
2308-1256

76年老店-好吃傳三代冰果店
龍都冰果店
廣州街168號

台南擔仔麵
華西街31號
2308-1123

漢記剝骨鵝肉
華西街28號
2308-8046

頂級甜不辣
廣州街與梧州街交叉口
2302-6022

GreyNick Life:[食尚玩家]-萬華古早味..永富冰淇淋 - yam天空部落

Mobile01 萬華區:麗珠什錦麵/排骨飯(這家的排骨無敵好吃)
Meiko's 強迫症患者的異想世界:【萬華50年老店】麗珠什錦麵 - yam天空部落
麗珠什錦麵

TEL:2308-6530
ADD:台北市興寧街48號
營業時間:11:30~23:00(星期一公休

10/25/2008

border: none

在IE下, 如果設定
在standard mode下, 還是會顯示 border
在quirk mode下, 不會顯示 border
可能的workaround可以是 border: 1px solid #fff
http://chunghe.googlecode.com/svn/trunk/experiment/input.border/input.border.none.standard.mode.htm
http://chunghe.googlecode.com/svn/trunk/experiment/input.border/input.border.quirk.mode.htm

10/24/2008

回头来看看Table:TD也玩overflow:hidden

* 在ie下, tr不能有border, td才有
* 在td下要使用white-space:nowrap, overflow:hidden
第一種方法. 用nobr;
第二種方法. td width用%表示
第三種方法. td span{display:block; overflow:hidden; white-space:nowrap}
回头来看看Table:TD也玩overflow:hidden - 飘零雾雨的庄园

10/22/2008

JavaScript's class-less objects by Stoyan Stefanov

JavaScript's class-less objects by Stoyan Stefanov
By convention, though, constructor functions are named with a capital letter to distinguish visually from normal functions and methods.

So which way is better - object literal or constructor function? Well, that depends on your specific task. For example, if you need to create many different, yet similar objects, then the class-like constructors may be the right choice. But if your object is more of a one-off singleton, then object literal is definitely simpler and shorter.

(Actually in JavaScript pretty much everything is an object, with the exception of the few primitive data types - string, boolean, number and undefined. Functions are objects, arrays are objects, even null is an object. Furthermore, the primitive data types can also be converted and used as objects, so for example "string".length is valid.)

Inheritance via the prototype
Here's a constructor function which will be the parent:

function NormalObject() {
this.name = 'normal';
this.getName = function() {
return this.name;
};
}

Now a second constructor:
function PreciousObject(){
this.shiny = true;
this.round = true;
}

PreciousObject.prototype = new NormalObject();

Notice how we needed to create an object with new and assign it to the prototype, because the prototype is just an object. It's not like one constructor function inherited from another, in essence we inherited from an object. JavaScript doesn't have classes that inherit from other classes, here objects inherit from other objects.
If you have several constructor functions that will inherit NormalObject objects, you may create new NormalObject() every time, but it's not necessary. Even the whole NormalObject constructor may not be needed. Another way to do the same would be to create one (singleton) normal object and use it as a base for the other objects.
var normal = {
name: 'normal',
getName: function() {
return this.name;
}
};

PreciousObject.prototype = normal;

Inheritance by copying properties
var shiny = {
shiny: true,
round: true
};

var normal = {
name: 'name me',
getName: function() {
return this.name;
}
};

function extend(parent, child) {
for (var i in parent) {
child[i] = parent[i];
}
}

extend(normal, shiny); // inherit
shiny.getName(); // "name me"

function begetObject(o) {
function F() {}
F.prototype = o;
return new F();
}

Parent object:

var normal = {
name: 'name me',
getName: function() {
return this.name;
}
};

A new object inheriting from the parent:
var shiny = begetObject(normal);


Augment the new object with more functionality:
shiny.round = true;
shiny.preciousness = true;

YUI's extend()
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
}


/**
* Utility to set up the prototype, constructor and superclass properties to
* support an inheritance strategy that can chain constructors and methods.
* Static members will not be inherited.
*
* @method extend
* @static
* @param {Function} subc the object to modify
* @param {Function} superc the object to inherit
* @param {Object} overrides additional properties/methods to add to the
* subclass prototype. These will override the
* matching items obtained from the superclass
* if present.
*/
extend: function(subc, superc, overrides) {
if (!superc||!subc) {
throw new Error("extend failed, please check that " +
"all dependencies are included.");
}
var F = function() {};
F.prototype=superc.prototype;
subc.prototype=new F();
subc.prototype.constructor=subc;
subc.superclass=superc.prototype;
if (superc.prototype.constructor == Object.prototype.constructor) {
superc.prototype.constructor=superc;
}

if (overrides) {
for (var i in overrides) {
if (L.hasOwnProperty(overrides, i)) {
subc.prototype[i]=overrides[i];
}
}

L._IEEnumFix(subc.prototype, overrides);
}
},

  • there are no classes
  • objects inherit from objects
  • object literal notation var o = {};
  • constructor functions provide Java-like syntax var o = new Object();
  • functions are objects
  • all function objects have a prototype property
    v And finally, there are dozens of ways to inmplement inheritance, you can pick and choose depending on your task at hand, personal preferences, team preferences, mood or the current phase of the Moon.

  • jslibs - Google Code

    jslibs - Google Code - try jshost examples/systray.js

    jslibs is a standalone JavaScript development runtime environment for using JavaScript as a general-purpose scripting language.

    jslibs uses SpiderMonkey library that is Gecko's JavaScript engine (SpiderMonkey is used in various Mozilla products, including Firefox).

    jslibs provides a set of native modules that contains various general purpose classes and functions.

    Some of these modules are simple wrappers for familiar libraries such as: zlib, SQLite, FastCGI, NSPR (Netscape Portable Runtime) , ODE (Open Dynamics Engine) , libpng, libjpeg, librsvg, SDL, libiconv, OpenGL, OpenAL, ogg vorbis, libTomCrypt, libffi (Foreign function interface) , ...

    via Ajaxian » jslibs - free JavaScript of browser limitations

    10/20/2008

    10/18 SA@Taipei 主講 Open at Yahoo!

    10/18 SA@Taipei 主講 Open at Yahoo!
    Instance-based:可例項化
    YUI 2.x: YAHOO 作為全域變數,只能有一個,容易被覆寫


    YAHOO.widget.HelloWorld = doSomething; // 開發者 1 寫的
    ...
    YAHOO.widget.HelloWorld = doNothing; // 開發者 2 寫的

    YUI 3.x: YUI() 可建立起一個全新的例項,不會被覆寫

    YUI().use('node', function(Y) { // 開發者 1 寫的
    Y.HelloWorld = doSomething;
    };);
    YUI.use('drag', function(Y) { // 開發者 2 寫的
    Y.HelloWorld = doNothing;
    };);

    YUI 3.x: 取得的物件不再是 HTMLElement

    var el = Y.get('#foo');
    alert(el.nodeName); //output: undefined
    alert(el.get('nodeName')); //output: DIVs

    YUI 2.xFunction-based 的存取方式

    var $D = YAHOO.util.Dom; // reference cache
    var el = $D.get('foo');
    YUD.addClass(el, 'highlighted');
    el.innerHTML += ' clicked';

    YUI 3.x: Object-based 的存取方式

    var el = Y.get('#foo');
    el.addClass('highlighted');
    el.set('innerHTML') = el.get('innerHTML') + ' clicked';

    YUI 3: event listener
    事件的綁法
    方法一:Y.on()

    YUI().use('node', function (Y) {
    Y.on('click', function (e) {
    // 處理事件
    }, '#foo');
    });

    方法二:Node.on()

    YUI().use('node', function (Y) {
    var el = Y.get('#foo');
    el.on( click', function (e) {
    // 處理事件
    });
    });

    YUI 2.x: 還是一般 DOM Event

    var $E = YAHOO.util.Event; // reference cache
    $E.on('foo', 'click', function (e) {
    alert(e.type); //output: click
    $E.preventDefault(e); //防止像是連結或表單送出的預設事件
    $E.stopPropogation(e); //防止Bubbleup
    });

    YUI 3.x: 封裝後更物件導向

    Y.on('click', function (e) {
    alert(e.type); //output: undefinded
    e.preventDefault();
    e.stopPropogation();
    }, '#foo');

    Textile

    Textile
    Textile - SWiK

    Textile is a web text markup-language that balances the strength of HTML with speed and ease of editing.

    Unlike many wiki or other markup languages, Textile sticks closely to the semantics of HTML, headings for example are represented by ‘h1’, ‘h2’ for <h1> and <h2>. Attaching classes and ids to elements is also easy with Textile.

    Textile is used by both blogs and a number of wikis, including the Ruby on Rails instiki powered wiki and by SWiK. Textile does not make a provision for wiki links however, so various wikis have interpreted their own wiki link standards.

    http://jrm.cc/extras/live-textile-preview.php

    test data

    一張很慢的圖
    http://sowrock.com/bin/sleep.cgi?type=gif&sleep=3&expires=-1&last=0&imagenum=13&t=1224467689
    一個很慢的script
    http://sowrock.com/bin/sleep.cgi?type=js&sleep=10&expires=-1&last=0

    tag: steve

    10/17/2008

    Best Practices for Speeding Up Your Web Site

    Best Practices for Speeding Up Your Web Site
    Add an Expires or a Cache-Control Header

    Browsers (and proxies) use a cache to reduce the number and size of HTTP requests, making web pages load faster. A web server uses the Expires header in the HTTP response to tell the client how long a component can be cached. This is a far future Expires header, telling the browser that this response won't be stale until April 15, 2010.

    Expires: Thu, 15 Apr 2010 20:00:00 GMT

    If your server is Apache, use the ExpiresDefault directive to set an expiration date relative to the current date. This example of the ExpiresDefault directive sets the Expires date 10 years out from the time of the request.

    ExpiresDefault "access plus 10 years"

    Avoid Redirects
    One of the most wasteful redirects happens frequently and web developers are generally not aware of it. It occurs when a trailing slash (/) is missing from a URL that should otherwise have one. For example, going to http://astrology.yahoo.com/astrology results in a 301 response containing a redirect to http://astrology.yahoo.com/astrology/ (notice the added trailing slash). This is fixed in Apache by using Alias or mod_rewrite, or the DirectorySlash directive if you're using Apache handlers.

    Make JavaScript and CSS External
    Home pages that have few (perhaps only one) page view per session may find that inlining JavaScript and CSS results in faster end-user response times.

    Remove Duplicate Scripts
    Unnecessary HTTP requests happen in Internet Explorer, but not in Firefox. In Internet Explorer, if an external script is included twice and is not cacheable, it generates two HTTP requests during page loading. Even if the script is cacheable, extra HTTP requests occur when the user reloads the page.

    Configure ETags
    Entity tags (ETags) are a mechanism that web servers and browsers use to determine whether the component in the browser's cache matches the one on the origin server. (An "entity" is another word a "component": images, scripts, stylesheets, etc.) ETags were added to provide a mechanism for validating entities that is more flexible than the last-modified date. An ETag is a string that uniquely identifies a specific version of a component. The only format constraints are that the string be quoted. The origin server specifies the component's ETag using the ETag response header.

    HTTP/1.1 200 OK
    Last-Modified: Tue, 12 Dec 2006 03:03:59 GMT
    ETag: "10c24bc-4ab-457e1c1f"
    Content-Length: 12195

    Later, if the browser has to validate a component, it uses the If-None-Match header to pass the ETag back to the origin server. If the ETags match, a 304 status code is returned reducing the response by 12195 bytes for this example.

    Minimize the Number of iframes
    <iframe> pros:

    * Helps with slow third-party content like badges and ads
    * Security sandbox
    * Download scripts in parallel

    Use Cookie-free Domains for Components
    When the browser makes a request for a static image and sends cookies together with the request, the server doesn't have any use for those cookies. So they only create network traffic for no good reason. You should make sure static components are requested with cookie-free requests. Create a subdomain and host all your static components there.

    Avoid Filters
    The best approach is to avoid AlphaImageLoader completely and use gracefully degrading PNG8 instead, which are fine in IE. If you absolutely need AlphaImageLoader, use the underscore hack _filter as to not penalize your IE7+ users.

    Optimize Images
    You can check the GIFs and see if they are using a palette size corresponding to the number of colors in the image. Using imagemagick it's easy to check using
    identify -verbose image.gif
    When you see an image useing 4 colors and a 256 color "slots" in the palette, there is room for improvement.

    tag: yslow