Search

6/27/2010

The ``Clockwise/Spiral Rule''

The ``Clockwise/Spiral Rule''

There is a technique known as the ``Clockwise/Spiral Rule'' which enables any C programmer to parse in their head any C declaration!

There are three simple steps to follow:

1. Starting with the unknown element, move in a spiral/clockwise direction; when ecountering the following elements replace them with the corresponding english statements:

[X] or []
=> Array X size of... or Array undefined size of...
(type1, type2)
=> function passing type1 and type2 returning...
*
=> pointer(s) to...

2. Keep doing this in a spiral/clockwise direction until all tokens have been covered.

3. Always resolve anything in parenthesis first!

Example #1: Simple declaration

+-------+
| +-+ |
| ^ | |
char *str[10];
^ ^ | |
| +---+ |
+-----------+

Question we ask ourselves: What is str?

``str is an...

* We move in a spiral clockwise direction starting with `str' and the first character we see is a `[' so, that means we have an array, so...

``str is an array 10 of...

* Continue in a spiral clockwise direction, and the next thing we encounter is the `*' so, that means we have pointers, so...

``str is an array 10 of pointers to...

* Continue in a spiral direction and we see the end of the line (the `;'), so keep going and we get to the type `char', so...

``str is an array 10 of pointers to char''

* We have now ``visited'' every token; therefore we are done!

http://cdecl.org/

6/24/2010

Getting started with node.js on Windows | Lazycoder

Getting started with node.js on Windows | Lazycoder
1. download vmware player. (網路設定改為NAT)
2. download TurnKey Core (102MB VM)
3. apt-get update; apt-get install build-essential; apt-get install git; apt-get install git-core; apt-get install curl; apt-get install vim;
4. ssh root@xxx.xxx.xxx.xxx:22

for ubuntu:
apt-get install libssl-dev
apt-get install pkg-config

6/23/2010

When you overwrite the prototype, it is a good idea to reset the constructor property.

When you overwrite the prototype, it is a good idea to reset the constructor property.
* constructor.prototype.constructor will point to the constructor itself.


function Dog() {
this.tail = true;
}
Dog.prototype.say = function () {
return 'Woof!'
}

var benji = new Dog();
console.log(benji.constructor.prototype.constructor); // Dog {}

// completely replace the prototype object,
// new objects create from now on will use the updated prototype.
Dog.prototype = {paws:4, hair:true};

var lucy = new Dog();

console.log(benji.__proto__); // Object {}
console.log(lucy.__proto__); // Object {paws=4, hair=true}

console.log(typeof benji.paws); // undefined
console.log(typeof benji.say); //function
console.log(typeof benji.paws); // undefined

// the constructor property of the new objects no longer reports correctly.
console.log(lucy.constructor); // Object()
console.log(benji.constructor); // Dog()

// to fix it.
Dog.prototype.constructor = Dog;


var F = function() {}, i;
F.prototype=superc.prototype;
subc.prototype=new F(); // rewrite the prototype.
subc.prototype.constructor=subc; // <--
subc.superclass=superc.prototype;


The prototype chain is live with the exception of when you completely replace the prototype object

function Dog(){this.tail = true;}
var benji = new Dog();
var rusty = new Dog();
Dog.prototype.say = function(){return 'Woof!';}

// completely overwrite the prototype
Dog.prototype = {paws: 4, hair: true};

// It turns out that our old objects do not get access to the new prototype's properties; they still keep the secret link pointing to the old prototype object:
console.log(typeof benji.paws); // undefined
console.log(benji.say()); // Woof!
console.log(typeof benji.__proto__.say); // function
console.log(typeof benji.__proto__.paws); // undefined

var lucy = new Dog();
lucy.say(); // TypeError: lucy.say is not a function
console.log(lucy.paws); // 4
console.log(typeof lucy.__proto__.say); // undefined
console.log(typeof lucy.__proto__.paws); // number


// Now the constructor property of the new objects no longer reports correctly. It should point to Dog(), but instead it points to Object()
lucy.constructor // Object()
benji.constructor // Dog()

// The most confusing part is when you look up the prototype of the constructor
console.log(typeof lucy.constructor.prototype.paws) // undefined
console.log(typeof benji.constructor.prototype.paws) // number

6/18/2010

opensearch

https://developer.mozilla.org/en/Creating_OpenSearch_plugins_for_Firefox
OpenSearch description file


<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
xmlns:moz="http://www.mozilla.org/2006/browser/search/">
<ShortName>engineName</ShortName>
<Description>engineDescription</Description>
<InputEncoding>inputEncoding</InputEncoding>
<Image width="16" height="16" type="image/x-icon">data:image/x-icon;base64,imageData</Image>
<Url type="text/html" method="method" template="searchURL">
<Param name="paramName1" value="paramValue1"/>
...
<Param name="paramNameN" value="paramValueN"/>
</Url>
<Url type="application/x-suggestions+json" template="suggestionURL"/>
<moz:SearchForm>searchFormURL</moz:SearchForm>
</OpenSearchDescription>


Autodiscovery of search plugins

<link rel="search" type="application/opensearchdescription+xml" title="MySite: By Author" href="http://www.mysite.com/mysiteauthor.xml">
<link rel="search" type="application/opensearchdescription+xml" title="MySite: By Title" href="http://www.mysite.com/mysitetitle.xml">

6/17/2010

YUI 3 学习笔记:oop - 岁月如歌

YUI 3 学习笔记:oop - 岁月如歌

简析 Extjs 类继承 - { focus : web } - JavaEye技术网站


function A() {
alert('a');
}
function B() {
B.superclass.constructor.call(this);
}
function temp() {
}
temp.prototype = A.prototype;

//防止A 的实例属性也搞到 B 里去 ,没有意思,我们只需要 A 的 prototype 里的公共属性
//不能使用 B.prototype=A.prototype 这样的话修改 B.prototype 则 A.prototype 也变了,以及影响instanceof
//不建议 B.prototype =new A() ;这样的话 A 的实例方法也到 B.prototype 里去了
B.prototype = new temp();

//上一步后 B 的实例的构造函数属性为 A 了,
// B.prototype.constructor == A
//为了以后方便B的子类调用B的构造函数
//如 C.superclass.constructor.call(this);
//要纠正
//B 的实例 的 构造函数属性要设为 B
B.prototype.constructor = B;

//要记录 B 的父亲,便于以后调用父亲方法
B.superclass = A.prototype;

if (A.prototype.constructor == Object.prototype.constructor) {
A.prototype.constructor = A;
}

6/04/2010

John Resig - How JavaScript Timers Work

John Resig - How JavaScript Timers Work


(Click to view full size diagram)

Since JavaScript can only ever execute one piece of code at a time (due to its single-threaded nature) each of these blocks of code are "blocking" the progress of other asynchronous events. This means that when an asynchronous event occurs (like a mouse click, a timer firing, or an XMLHttpRequest completing) it gets queued up to be executed later (how this queueing actually occurs surely varies from browser-to-browser, so consider this to be a simplification).
To start with, within the first block of JavaScript, two timers are initiated: a 10ms setTimeout and a 10ms setInterval. Due to where and when the timer was started it actually fires before we actually complete the first block of code. Note, however, that it does not execute immediately (it is incapable of doing that, because of the threading). Instead that delayed function is queued in order to be executed at the next available moment.

Additionally, within this first JavaScript block we see a mouse click occur. The JavaScript callbacks associated with this asynchronous event (we never know when a user may perform an action, thus it's consider to be asynchronous) are unable to be executed immediately thus, like the initial timer, it is queued to be executed later.

After the initial block of JavaScript finishes executing the browser immediately asks the question: What is waiting to be executed? In this case both a mouse click handler and a timer callback are waiting. The browser then picks one (the mouse click callback) and executes it immediately. The timer will wait until the next possible time, in order to execute.

Note that while mouse click handler is executing the first interval callback executes. As with the timer its handler is queued for later execution. However, note that when the interval is fired again (when the timer handler is executing) this time that handler execution is dropped. If you were to queue up all interval callbacks when a large block of code is executing the result would be a bunch of intervals executing with no delay between them, upon completion. Instead browsers tend to simply wait until no more interval handlers are queued (for the interval in question) before queuing more.

We can, in fact, see that this is the case when a third interval callback fires while the interval, itself, is executing. This shows us an important fact: Intervals don't care about what is currently executing, they will queue indiscriminately, even if it means that the time between callbacks will be sacrificed.

Finally, after the second interval callback is finished executing, we can see that there's nothing left for the JavaScript engine to execute. This means that the browser now waits for a new asynchronous event to occur. We get this at the 50ms mark when the interval fires again. This time, however, there is nothing blocking its execution, so it fires immediately.

setTimeout(function(){
/* Some long block of code... */
setTimeout(arguments.callee, 10);
}, 10);

setInterval(function(){
/* Some long block of code... */
}, 10);

These two pieces of code may appear to be functionally equivalent, at first glance, but they are not. Notably the setTimeout code will always have at least a 10ms delay after the previous callback execution (it may end up being more, but never less) whereas the setInterval will attempt to execute a callback every 10ms regardless of when the last callback was executed.

regexp.exec, string.match

via javascript: the definitive guide


string.match

  • if g flag was used: returns an array with the matches

  • if g was not used: an array with the match and the parenthesized subexpressions



'123-456-7890'.match(/\d{3}/g); // Returns ['123', '456’, ‘789’]
'123-456-7890'.match(/(\d{3})-(\d{3})/); // Returns ['123-456', '123', '456']

regexp.exec
Note that exec( ) always includes full details of every match in the array it returns, whether or not regexp is a global pattern. This is where exec( ) differs from String.match( ), which returns much less information when used with global patterns. Calling the exec( ) method repeatedly in a loop is the only way to obtain complete pattern-matching information for a global pattern.

6/03/2010

javascritp regular expression


var re = /\d?/; // 0 or 1
re = /\d+/; // 1 or more
re = /\d*/; // 0 or more
re = /\d{3}/; // Exactly 3 times
re = /\d{3,}/; // 3 or more times
re = /\d{3,5}/; // At least 3, but not more than 5 times



‘aaa’.match(/a+/) // [‘aaa’]
‘aaa’.match(/a+?/) // [‘a’]

11.1.3.1. Nongreedy repetition
The repetition characters listed in Table 11-3 match as many times as possible while still allowing any following parts of the regular expression to match. We say that this repetition is "greedy." It is also possible (in JavaScript 1.5 and later; this is one of the Perl 5 features not implemented in JavaScript 1.2) to specify that repetition should be done in a nongreedy way. Simply follow the repetition character or characters with a question mark: ??, +?, *?, or even {1,5}?. For example, the regular expression /a+/ matches one or more occurrences of the letter a. When applied to the string "aaa", it matches all three letters. But /a+?/ matches one or more occurrences of the letter a, matching as few characters as necessary. When applied to the same string, this pattern matches only the first letter a.

Using nongreedy repetition may not always produce the results you expect. Consider the pattern /a*b/, which matches zero or more letter a's, followed by the letter b. When applied to the string "aaab", it matches the entire string. Now let's use the nongreedy version: /a*?b/. This should match the letter b preceded by the fewest number of a's possible. When applied to the same string "aaab", you might expect it to match only the last letter b. In fact, however, this pattern matches the entire string as well, just like the greedy version of the pattern. This is because regular-expression pattern matching is done by finding the first position in the string at which a match is possible. The nongreedy version of our pattern does match at the first character of the string, so this match is returned; matches at subsequent characters are never even considered.

6/02/2010

The onerror event of the window object

The onerror event of the window object

Defining the onerror event with a function that returns a value of true at the very top of your page suppresses all scripting errors on the page .

window.onerror=function(){
alert('An error has occurred!')
return true
}



window.onerror=function(msg, url, linenumber){
alert('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber)
return true
}



var errordialog=function(msg, url, linenumber){
var dialog=document.createElement("div")
dialog.className='errordialog'
dialog.innerHTML=' JavaScript Error: ' + msg +' at line number ' + linenumber +'. Please inform webmaster.'
document.body.appendChild(dialog)
return true
}

window.onerror=function(msg, url, linenumber){
return errordialog(msg, url, linenumber)
}

MSDev - AJAX and Client-Side - Javascript: Pass by reference or value?

MSDev - AJAX and Client-Side - Javascript: Pass by reference or value?


function reftest2(a) { a.x = 10; }
c = {x:1, y:2};
reftest2(c);
alert(c.x); // 10

The confusion here results in what exactly the value of a variable is. When an object is passed into a function, its internal address is what gets passed in. That's the "value" of the object. Thus when the function modifies the x member of the object it received, it ends up modifying the same x member as that in the original object. While this might seem like pass-by-reference, it's still pass-by-value.

(If you're a C programmer, this should be totally familiar to you. C uses only pass-by-value as well, and you run into similar behavior when you pass an array into a function.)

All types are passed by value
For reference types (objects, arrays, functions, etc.), the value passed is a pointer
This can have unexpected consequences if you aren't prepared for it; modifying an array passed as an argument will modify the array value outside of the function
This is not the same as passing by reference; you can not perform in place sorting on an array using memory locations, for instance


javascript: the definitive guide
The basic rule in JavaScript is this: primitive types are manipulated by value, and reference types, as the name suggests, are manipulated by reference. Numbers and booleans are primitive types in JavaScriptprimitive because they consist of nothing more than a small, fixed number of bytes that are easily manipulated at the low levels of the JavaScript interpreter. Objects, on the other hand, are reference types. Arrays and functions, which are specialized types of objects, are therefore also reference types. These datatypes can contain arbitrary numbers of properties or elements, so they cannot be manipulated as easily as fixed-size primitive values can. Since object and array values can become quite large, it doesn't make sense to manipulate these types by value, because this could involve the inefficient copying and comparing of large amounts of memory.

Example 3-1. Copying, passing, and comparing by value

// First we illustrate copying by value
var n = 1; // Variable n holds the value 1
var m = n; // Copy by value: variable m holds a distinct value 1

// Here's a function we'll use to illustrate passing by value
// As we'll see, the function doesn't work the way we'd like it to
function add_to_total(total, x)
{
total = total + x; // This line changes only the internal copy of total
}

// Now call the function, passing the numbers contained in n and m by value.
// The value of n is copied, and that copied value is named total within the
// function. The function adds a copy of m to that copy of n. But adding
// something to a copy of n doesn't affect the original value of n outside
// of the function. So calling this function doesn't accomplish anything.
add_to_total(n, m);

// Now, we'll look at comparison by value.
// In the following line of code, the literal 1 is clearly a distinct numeric
// value encoded in the program. We compare it to the value held in variable
// n. In comparison by value, the bytes of the two numbers are checked to
// see if they are the same.
if (n == 1) m = 2; // n contains the same value as the literal 1; m is now 2


Example 3-2. Copying, passing, and comparing by reference

// Here we create an object representing the date of Christmas, 2007
// The variable xmas contains a reference to the object, not the object itself
var xmas = new Date(2007, 11, 25);
// When we copy by reference, we get a new reference to the original object
var solstice = xmas; // Both variables now refer to the same object value

// Here we change the object through our new reference to it
solstice.setDate(21);

// The change is visible through the original reference, as well
xmas.getDate( ); // Returns 21, not the original value of 25

// The same is true when objects and arrays are passed to functions.
// The following function adds a value to each element of an array.
// A reference to the array is passed to the function, not a copy of the array.
// Therefore, the function can change the contents of the array through
// the reference, and those changes will be visible when the function returns.
function add_to_totals(totals, x)
{
totals[0] = totals[0] + x;
totals[1] = totals[1] + x;
totals[2] = totals[2] + x;
}

// Finally, we'll examine comparison by reference.
// When we compare the two variables defined above, we find they are
// equal, because they refer to the same object, even though we were trying
// to make them refer to different dates:
(xmas == solstice) // Evaluates to true

// The two variables defined next refer to two distinct objects, both
// of which represent exactly the same date.
var xmas = new Date(2007, 11, 25);
var solstice_plus_4 = new Date(2007, 11, 25);

// But, by the rules of "compare by reference," distinct objects are not equal!
(xmas != solstice_plus_4) // Evaluates to true


Before we leave the topic of manipulating objects and arrays by reference, let's clear up a point of nomenclature. The phrase "pass by reference" can have several meanings. To some readers, the phrase refers to a function-invocation technique that allows a function to assign new values to its arguments and to have those modified values visible outside the function. This is not the way the term is used in this book. Here, I mean simply that a reference to an object or arraynot the object itselfis passed to a function. A function can use the reference to modify properties of the object or elements of the array. But if the function overwrites the reference with a reference to a new object or array, that modification is not visible outside the function. Readers familiar with the other meaning of this term may prefer to say that objects and arrays are passed by value, but the value that is passed is actually a reference rather than the object itself. Example 3-3 illustrates this issue.

Example 3-3. References themselves are passed by value

// This is another version of the add_to_totals( ) function. It doesn't
// work, though, because instead of changing the array itself, it tries to
// change the reference to the array.
function add_to_totals2(totals, x)
{
newtotals = new Array(3);
newtotals[0] = totals[0] + x;
newtotals[1] = totals[1] + x;
newtotals[2] = totals[2] + x;
totals = newtotals; // This line has no effect outside of the function
}

Billy Hoffman - JSConf 2010

Billy Hoffman - JSConf 2010

Dehydrating Code
* Converts any string into whitespace
* 7 bit per character: 1 = space, 0 = tab
* \n means we are done
* 'a' = 1100001
* dehydrate('a') = space, space, tab, tab, tab, ...


function dehydrate(s) {
var r = new Array();
for(var i=0; i if (s.charCodeAt(i) & (Math.pow(2, j))) {
r.push(' ');
} else {
r.push('\t');
}
}
r.push('\n');
return r.join('');
}

function hydrate (s) {
var r = []; var curr = 0;
while(s.charAt(curr) != '\n') {
var tmp = 0;
for (var i=6; i>=0; i--) {
if (s.charAt(curr) == '') tmp = tmp | (Math.pow(2, i));
curr++;
}
r.push(String.fromCharCode(tmp));
}
return r.join('');
}


//startevil

//endevil

var html = document.body.innerHTML;
var start = html.indexOf("//start" + "tevil");
var end = html.indexOf("//end" + "evil");
eval(dydrate(html.substring(start+12, end)));

some trucs and machins about google go

http://www.scribd.com/vacuum?url=http://dept-info.labri.fr/~narbel/Lect/go-lecture.pdf

6/01/2010

javascript prototype

__proto__ is not the same as prototype. __proto__ is a property of the instances(object), whereas prototype is a property of the constructor functions(function).


var o = {};
console.log(o.__proto__); // Object { }
console.log(o.prototype); // undefined
console.log(o.__proto__ == Object.prototype); // true, means pointing to the same object
console.log(o.constructor.prototype == o.__proto); // true



function Gadget(name, color) {
this.name = name;
this.color = color;
this.whatAreYou = function(){
return 'I am a ' + this.color + ' ' + this.name;
}
}

Gadget.prototype.price = 100;
Gadget.prototype.rating = 3;
Gadget.prototype.getInfo = function() {
return 'Rating: ' + this.rating + ', price: ' + this.price;
};

var newtoy = new Gadget('webcam', 'black');

console.log(newtoy) // Object {name="webcam", more...}
console.log(newtoy.constructor); // Gadget(name, color)
console.log(newtoy.constructor.prototype); // Object {price=100, more...}
console.log(newtoy.constructor.prototype.constructor); // Gadget (name, color)


Every object also gets the isPrototypeOf() method. This method tells you whether that specific object is used as a prototype of another object.

var monkey = {
feeds: 'benana',
breathes: 'air'
};

function Human() {};
Human.prototype = monkey;

var developer = new Human();
developer.feeds = 'pizza';
developer.hacks = 'JavaScript';

console.log(developer.__proto__); // Object { feeds="benana", more...}
console.log(typeof developer.__proto__); // object
console.log(typeof developer.prototype); // undefined
console.log(monkey.isPrototypeOf(developer)); // true, relationship between obejects
console.log(monkey.isPrototypeOf(Human)); // false


Prototype Chaining
As you already know, every function has a prototype property, which contains an object. When this function is invoked using the new operator, an object is created and this object has a secret link to the prototype object. The secret link (called __proto__ in some environments) allows methods and properties of the prototype object to be used as if they belong to the newly-created object.

function Shape(){
this.name = 'shape';
this.toString = function() {return this.name;};
}

function TwoDShape(){
this.name = '2D shape';
}

function Triangle(side, height) {
this.name = 'Triangle';
this.side = side;
this.height = height;
this.getArea = function(){return this.side * this.height / 2;};
}
TwoDShape.prototype = new Shape();
Triangle.prototype = new TwoDShape();