Friday, December 30, 2016

Object.assign()

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

var obj = { a: 1 };
var copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }

@reference_1_mozilla
@reference_2_stackoverflow

Wednesday, December 21, 2016

javascript inheritance: Two - (2) test 5

@reference_-1_overall
@reference_-2_inheritance-Two (1)

//test start - 5
//using default: 'Employee.prototype = Object.create(Person.prototype)'

try {
    //Person.prototype.sayHello(); // output: Hello, my name is undefined.
    //Person.prototype.run(); // output: undefined is running.
    //Person.prototype.walk(); //throw an error: Object doesn't support property or method 'walk'
    //
    //Employee.prototype.sayHello(); // output: Hello, my name is undefined, I'm the undefined
    //Employee.prototype.run(); // output: undefined is running.
    //Employee.prototype.walk(); //throw an error: Object doesn't support property or method 'walk'

    let jack = Object.create(Employee.prototype, {
        name: {
            value: "Jack",
            writable: true,
            enumerable: true,
            configurable: true
        },
        title: {
            value: "Manager",
            writable: true,
            enumerable: true,
            configurable: true
        }
    }
);
    //jack.sayHello(); // output: Hello, my name is Jack, I'm the Manager
    //alert(Employee.prototype.isPrototypeOf(jack)); // output: true
    //jack.run(); // output: Jack is running.
    //jack.walk(); // throw an error: Object doesn't support property or method 'walk'
    //Employee.prototype.sayHello.call(jane); // output: Hello, my name is Jane, I'm the Accountant.
    //Person.prototype.sayHello.call(jane); // output: Hello, my name is Jane.


    //var jane = new Employee("Jane", "Accountant");
    let y = {};
    y.prototype = jane;
    //y.sayHello(); // throw an error: Object doesn't support property or method 'sayHello'
    //y.run(); // throw an error: Object doesn't support property or method 'run'
    //y.walk(); // throw an error: Object doesn't support property or method 'walk'

    let z = function() {};
    z.prototype = Object.create(jane);
    let zi = new z();
    zi.sayHello(); // output: Hello, my name is Jane, I'm the Accountant.
    zi.run(); // output: Jane is running.
    zi.walk(); // output: Jane is walking.
    //alert(jane.isPrototypeOf(zi)); // output: true             

    let a = function() {};
    a.prototype = Object.create(null);

    //alert(z.prototype === a.prototype); // output: false
    //alert(compareObj(z.prototype, a.prototype)); // output: true  
    //alert(compareContent(z.prototype, a.prototype)); // throw an error: Object doesn't support property or method 'isPrototypeOf'

    //alert(z.prototype.isPrototypeOf(a.prototype)); // output: false
    //alert(a.prototype.isPrototypeOf(z.prototype)); // throw an error: Object doesn't support property or method 'isPrototypeOf'

    //Note that compareObj & compareContent function may change

    //alert(deepCompare(z.prototype, a.prototype));  // throw an error: Number Expected
    //alert(z.prototype.constructor); // the output is the Employee's constructor
    //alert(a.prototype.constructor); // output: undefined
    //alert(z === a); // output: false
    //alert(compareObj(z, a)); // output: true
    //alert(compareContent(z, a)); // output: true
    //alert(deepCompare(z, a)); // output: true     
           
    //test end - 5

 
//test start - 6
let b = Object.create(jane);
//alert(compareObj(b, jane)); // output: false
//alert(Object.keys(b).length + " -- " + Object.keys(jane).length); // output: 0 -- 3

//txt = outputObj(b);
//txt += "===========================<br>";
//txt += outputObj(jane); // output: the object output are the same

c = function(name) {
    this.name = name;
    this.constructor.prototype.sayHello = function() {
        alert("Hello, " + this.name);
    };
    alert("hello");
};
function d(name) {
    this.name = name;
    d.prototype.sayHello = function() {
        alert("Hello, " + this.name);
    };
    alert("hello");
};
c.prototype = {a: 1};
d.prototype = {b: 1};
let g = new c("Jason"); // output: hello
let h = new d("Jason"); // output: hello
//g.sayHello(); // output: Hello, Jason
//c.prototype.sayHello(); // output: Hello, undefined
//h.sayHello(); // output: Hello, Jason
//d.prototype.sayHello(); // output: Hello, undefined

function i(name) {
    this.name = name;
    this.sayHello = function() {
        alert("Hello, " + this.name);
    };
    alert("hello");
};
//i.prototype.sayHello();//throw an error: Object doesn't support property or method 'sayHello'
j = function(name) {
    this.name = name;
    this.constructor.prototype.sayHello = function() {
        alert("Hello, " + this.name);
    };
    alert("hello");
};
//let k = new j("Jason"); // output: hello
//alert(g.constructor === k.constructor); // output: false
//let l = new j("Jason"); // output: hello
//alert(k.constructor === l.constructor); // output: true
//alert(compareObj({}.constructor, [].constructor)); // output: false
//alert(compareContent({}.constructor, [].constructor)); // output: false
//alert(deepCompare({}.constructor, [].constructor)); // output: false            


let e = {a: 1, b: 2, c: 3},
     f = {a: 1, b: 2, c: 3};
//alert(compareContent(e, f));// output: true
//alert(compareObj(e, f)); // output: true
//alert(deepCompare(e, f)); // output: true

e.prototype = {d: 4};
f.prototype = {d: 4};
//alert(compareContent(e, f));// output: false
//alert(compareObj(e, f)); // output: true
//alert(deepCompare(e, f)); // output: false

}catch (err) {
    alert(err.message);
}
//test end - 6

javascript inheritance: Two - Employee.prototype = Object.create(Person.prototype)

 @reference_-1_overall
 
//test start- 2
//what if using 'Employee.prototype = Person.prototype' instead?

//jane.sayHello(); //output: Hello, my name is Jane, I'm the Accountant.
//jane.walk(); // output: Jane is walking.
//jane.run();  // output: Jane is running.
//alert(Employee.prototype.isPrototypeOf(jane)); // output: true

//txt = jane.constructor.toString();
//output: function Employee(name, title) { Person.call(this, name); this.title = title; }
//p.sayHello();  //output: Hello, my name is Jane, I'm the undefined.

//Because 'Employee.prototype.sayHello = function () {...}' statement also changed the 'Person.prototype'.
//test end - 2

//test start- 3
//what if using 'Employee.prototype = new Person()' instead?
//jane.sayHello(); //output: Hello, my name is Jane, I'm the Accountant.
//jane.walk(); // output: Jane is walking.
//jane.run();  // output: Jane is running.
//alert(Employee.prototype.isPrototypeOf(jane)); // output: true

try {
    let e = Object.create(Employee.prototype);
    //e.sayHello();  // output: Hello, my name is undefined, I'm the undefined
    //e.walk(); // output: undefined is walking.
    //e.run(); // output: undefined is running.
    let x = Object.create(Person.prototype);
    //x.sayHello(); // output: Hello, my name is undefined.
    //x.walk(); //throw an error: Object doesn't support property or method 'walk'
    //x.run(); // output: undefined is running.
} catch (err) {
    alert(err.message);
}

//test end - 3

Very simply said, new X is Object.create(X.prototype) with additionally running the constructor function. (And giving the constructor the chance to return the actual object that should be the result of the expression instead of this.)
@reference_1_stackoverflow

//test start - 4
//using default: 'Employee.prototype = Object.create(Person.prototype)'
try {
    let e = Object.create(Employee.prototype);
    //alert(typeof e.prototype); // output: undefined
    //e.sayHello();  // output: Hello, my name is undefined, I'm the undefined
    //e.walk(); // throw an error: Object doesn't support property or method 'walk'
    //e.run(); // output: undefined is running.
    let x = Object.create(Person.prototype);
    //x.sayHello(); // output: Hello, my name is undefined.
    //x.walk(); //throw an error: Object doesn't support property or method 'walk'
    //x.run(); // output: undefined is running.
} catch (err) {
    alert(err.message);
}

//test end - 4

javascript inheritance: One - overall

function Person(name) {
    this.name = name;
    this.walk = function() {
        alert(this.name + " is walking.");
    };
}
Person.prototype.sayHello = function() {
    alert("Hello, my name is " + this.name);
};
Person.prototype.run = function() {
    alert(this.name + " is running.");
};

function Employee(name, title) {
    Person.call(this, name);
    this.title = title;
}

//Employee.prototype = Person.prototype;   // what if using this instead?
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.sayHello = function() {
    alert("Hello, my name is " + this.name + ", I'm the " + this.title);
};

// test code - overall
var txt = "Hello, World!";
var p = new Person("Jane");

//alert(Person.prototype.isPrototypeOf(p)); // output: true
//p.sayHello(); // output: Hello, my name is Jane.
//alert(typeof Person.prototype); // output: object


//txt = outputObj(Person.prototype);
//  output: 

//     [n: sayHello - d: 0 - v: function () { alert("Hello, my name is " + this.name + "."); }]
//     [n: run - d: 0 - v: function () { alert(this.name + " is running."); }]


//alert(typeof Employee.prototype); // output: object
//alert(typeof Employee.constructor); // output: function


//txt = outputObj(Employee.prototype);
//output: 

//[n: constructor - d: 0 - v: function Employee(name, title) { Person.call(this, name); this.title = title; }]
//[n: sayHello - d: 0 - v: function () { alert("Hello, my name is " + this.name + ", I'm the " + this.title + "."); }]
//[n: run - d: 0 - v: function () { alert(this.name + " is running."); }]


//txt = Employee.prototype.constructor.toString();
//  output: function Employee(name, title) { Person.call(this, name); this.title = title; }
var jane = new Employee("Jane", "Accountant");

//jane.sayHello(); //output: Hello, my name is Jane, I'm the Accountant.
//jane.walk(); // output: Jane is walking.
//jane.run();  // output: Jane is running.
//alert(Employee.prototype.isPrototypeOf(jane)); // output: true

//txt = jane.constructor.toString();
//output: function Employee(name, title) { Person.call(this, name); this.title = title; }

//txt = typeof jane.prototype; //output:undefined


@reference_1_Inheritance and the prototype chain_mozilla
@reference_2_Introduction to Object-Oriented JavaScript_mozilla

Tuesday, December 20, 2016

Difference between for...of and for...in

The for...in loop will iterate over all enumerable properties of an object.
The for...of syntax is specific to collections, rather than all objects. It will iterate in this manner over the elements of any collection that has a [Symbol.iterator] property.
The following example shows the difference between a for...of loop and a for...in loop.

Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};

let iterable = [3, 5, 7];
iterable.foo = "hello";

for (let i in iterable) {
     console.log(i);  // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
for (let i of iterable) {
     console.log(i);  // logs 3, 5, 7 
}

@reference_0_mozilla

Variables: let, const, or var

New variables in JavaScript are declared using one of three keywords: let, const, or var.

let allows you to declare block-level variables. The declared variable is available from the function block it is enclosed in.

//myLetVariable is *not* visible out here
for( let myLetVariable = 0; myLetVariable < 5; myLetVariable++ ) {
       //myLetVariable is only visible in here
}
//myLetVariable is *not* visible out here

const allows you to declare variables whose values are never intended to change. The variable is available from the function block it is declared in.
  
const Pi = 3.14; // variable Pi is set

const Pi = 3.14; // variable Pi is set
Pi = 1; // will throw an error because you cannot change a constant variable.

var is the most common declarative keyword. It does not have the restrictions that the other two keywords have. This is because it was traditionally the only way to declare a variable in JavaScript. A variable declared with the var keyword is available from the function block it is declared in.

//myVarVariable *is* visible out here
for( var myVarVariable = 0; myVarVariable < 5; myVarVariable++ ) {
         //myVarVariable is visible to the whole function
}
//myVarVariable *is* visible out here

If you declare a variable without assigning any value to it, its type is undefined.

An important difference between JavaScript and other languages like Java is that in JavaScript, blocks do not have scope; only functions have scope. So if a variable is defined using var in a compound statement (for example inside an if control structure), it will be visible to the entire function.
However, starting with ECMAScript Edition 6, let and const declarations allow you to create block-scoped variables.

@reference_0_mozilla

values converted to a boolean

JavaScript has a boolean type, with possible values true and false (both of which are keywords.) Any value can be converted to a boolean according to the following rules:
false, 0, empty strings (""), NaN, null, and undefined all become false.
All other values become true.

 
You can perform this conversion explicitly using the Boolean() function:

Boolean(""); // false
Boolean(234); // true

@reference_0_mozilla


parseInt() and parseFloat() function

The parseInt() and parseFloat() functions parse a string until they reach a character that isn't valid for the specified number format, then return the number parsed up to that point. However the "+" operator simply converts the string to NaN if there is an invalid character contained within it. Just try parsing the string "10.2abc" with each method by yourself in the console and you'll understand the differences better.

+ "42"; // 42
+ "010"; // 10
+ "0x10"; // 16

isNaN(NaN); // true
isFinite(1/0); // false
isFinite(-Infinity); // false
isFinite(NaN); // false

@reference_0_mozilla


Monday, December 19, 2016

javascript function comparison

@reference_1_stackoverflow

Compile and Install Shadowsocks-libev on Ubuntu 16.04 Server

1. git version control tool

 apt-get update
 apt install git

2. Clone the source repository from Github.

git clone https://github.com/shadowsocks/shadowsocks-libev.git 
cd shadowsocks-libev

3. Install build dependencies.

apt install build-essential autoconf libtool libssl-dev asciidoc
apt-get install libpcre3 libpcre3-dev

4. Configure build environment and compile it.

./configure && make

5. Install shadowsocks-libev

make install
---------------------------------------------
nano /etc/shadowsocks/config.json
......
{
"server":"your_server_ip",
"server_port":9999,
"local_address": "127.0.0.1",
"local_port":1080,
"password":"your_passwd",
"timeout":600,
"method":"aes-256-cfb"
}
---------------------------------------------
Run:
nohup ss-server -c /etc/shadowsocks/config2.json &

Then:
nano /etc/rc.local
Add the ss-server command above exit 0

@reference_1_linuxbabe
@reference_2_cyberciti

-------------------------------------------------
no plan to support multi port configuration. Actually you can use multiple instances instead. For example:
ss-server -c config1.json -f pid1
ss-server -c config2.json -f pid2
ss-server -c config3.json -f pid3
As the best practice we recommend for shadowsocks-libev, it helps to isolate each user in different processes and reconfigure each user's port/password/encyption/timeout without reload/restart the whole service. Furthermore, this approach enables us to manage users with legacy control panels, for example old SSH / VHOST panels with each user's ss-server running in its own space.
Compared to other implementations, shadowsocks-libev uses much fewer resources (about 1MB memory and hundreds of file descriptors in a typical usage) . As a result, this kind of multi processes should only introduce slight overhead and even works well for low end boxes. @reference_3_github
 -------------------------------------------
不用多实例,用iptables的端口转发功能,随意设定在多少端口上监听 。
 iptables -t nat -A PREROUTING -d <监听地址>/32 -p tcp -m tcp --dport <起始端口>:<结束端口>  -j REDIRECT --to-ports <SS 端口>
@reference_4_plus.google
@reference_5_teddysun

Thursday, December 15, 2016

isPrototypeOf & constructor & prototype

if (o1.isPrototypeOf(o2) || o2.isPrototypeOf(o1))
    return false;
if (o1.constructor !== o2.constructor)
    return false;
if (o1.prototype !== o2.prototype)
    return false;

@reference_1_mozilla
@reference_2_mozilla
@reference_3_mozilla

JSON.stringify()

JSON.stringify() converts a value to JSON notation representing it:
  • Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.
  • Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.
  • If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). JSON.stringify can also just return undefined when passing in "pure" values like JSON.stringify(function(){}) or JSON.stringify(undefined).
  • All symbol-keyed properties will be completely ignored, even when using the replacer function.
  • Non-enumerable properties will be ignored

JSON.stringify({});                  // '{}'
JSON.stringify(true);                // 'true'
JSON.stringify('foo');               // '"foo"'
JSON.stringify([1, 'false', false]); // '[1,"false",false]'
JSON.stringify({ x: 5 });            // '{"x":5}'

JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)) 
// '"2006-01-02T15:04:05.000Z"'

JSON.stringify({ x: 5, y: 6 });
// '{"x":5,"y":6}' or '{"y":6,"x":5}'
JSON.stringify([new Number(1), new String('false'), new Boolean(false)]);
// '[1,"false",false]'

JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }); 
// '{"x":[10,null,null,null]}' 
 
// Symbols:
JSON.stringify({ x: undefined, y: Object, z: Symbol('') });
// '{}'
JSON.stringify({ [Symbol('foo')]: 'foo' });
// '{}'
JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]);
// '{}'
JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) {
  if (typeof k === 'symbol') {
    return 'a symbol';
  }
});
// '{}'

// Non-enumerable properties:
JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, 
                                      y: { value: 'y', enumerable: true } }) );
// '{"y":"y"}'
----------------------------
alert(JSON.stringify(/[a-z]/g));  // {}

@reference_0_mozilla

Difference between toString() and JSON.stringify()

["1,",2,3].toString();
//"1,,2,3" ... so you can't just split by comma and get original array
//it is in fact impossible to restore the original array from this result
JSON.stringify(["1,",2,3])
//'["1,",2,3]' //original array can be restored exactly

for an object say
obj = { a: 'a', '1': 1 } 
obj.toString() gives:  "[object Object]"
JSON.stringify(obj) gives: "{"1":1,"a":"a"}" 

For .toString(), a default value is returned when the argument type is an object. JSON.stringify on the other hand returns JSON text, which can be converted back into a JSON object by using JSON.parse


@reference_1_stackoverflow
@reference_2_mozilla

Wednesday, December 14, 2016

Object content comparison in JavaScript

@reference_1_stackoverflow
@reference_2_stackoverflow
@reference_3_mozilla

How to count a JavaScript object's attributes?

var attr, len = 0;
for (attr in obj)len++;

var count = 0;
for (k in myobj) if (myobj.hasOwnProperty(k)) count++;

Object.keys(obj).length
Object.getOwnPropertyNames(obj).length

@reference_1_stackoverflow
@reference_2_stackoverflow
@reference_3_blueidea
@reference_4_oschina
@reference_5_mozilla
@reference_6_taocms

Fiddler下Firefox提示“您的连接并不安全”的解决办法

通过安装Fiddler的https认证文件的方法解决问题。

@reference_1_cnblogs
@reference_2_cnblogs

8 Regular Expressions

@reference_1_tutsplus
@reference_2_regexr

AJAX cross domain call

@reference_1_stackoverflow
@reference_2_stackoverflow
@reference_3_google

Monday, December 12, 2016

AJAX - Server Response

The readyState property holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

The onreadystatechange property defines a function to be executed when the readyState changes.

The status property and the statusText property holds the status of the XMLHttpRequest object.
status 200: "OK"
403: "Forbidden"
404: "Page not found"
502: "Bad Gateway"

statusText Returns the status-text (e.g. "OK" or "Not Found")



@reference_1
@reference_2


JSON Datatype

Javascript 在很多时候会把 JSON 对象里面没有双引号包围的值,当做数值处理。
比如: {"a":987654321} 这个 JSON 里头的变量 a,会被当做一个整数 987654321 看待,
而:{"a":"987654321"} 这个 JSON 里头的变量 a,会被当做一个字串,字串的内容是“987654321”。
@reference_1_sanwen8

Worker.onmessage & Window.postMessage()

@reference_1_onmessage-mozilla
@reference_2_postMessage-mozilla
@reference_3_Web Workers API-mozilla

Sunday, December 11, 2016

'登录' !== '登陆'


@reference_0_zhihu

html5 web worker: Bringing Multi-threading to JavaScript

@reference_0_htmlgoodies
@reference_1_w3schools
@reference_2_w3school.cn
@reference_3_sporto.github.io
@reference_4_blog.sina
@reference_5_zhihu

Qualcomm Atheros AR956x

在XP下更改MAC地址那是很简单的事。但是到了Win7下却怎么都没法修改了,驱动中没有相关选项,用专门修改MAC地址的软件也不行,经过不断尝试,发现在Win7下修改Inter无线网卡地址时,从左往右第二个字符必须为2、6、A、E其中之一,如:
00:00:00:00:00:00 —— 无效
02:00:00:00:00:00 —— 有效
0A:00:00:00:00:00 —— 有效
至于用来修改的软件很多,比如Mac MakeUp(Mac makeup可以改外置usb网卡)、网卡地址修改器等。也可以打开网络与共享中心,点击更改适配器配置,右击无线网络链接-属性-配置-高级-Network Address,在“值”里面直接更改(无需重启,立即生效)。

经尝试,在Atheros的无线网卡下也是可行的

@reference_0

Friday, December 9, 2016

In JavaScript, object references are values.

Arguments are Passed by Value

The parameters, in a function call, are the function's arguments.
JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations.
If a function changes an argument's value, it does not change the parameter's original value.
Changes to arguments are not visible (reflected) outside the function.
 

Objects are Passed by Reference

In JavaScript, object references are values.
Because of this, objects will behave like they are passed by reference:
If a function changes an object property, it changes the original value.
Changes to object properties are visible (reflected) outside the function.

@reference_0 

Thursday, December 8, 2016

Comma operator

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
 expr1, expr2, expr3...

Description
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.


Examples
for (var i = 0, j = 9; i <= 9; i++, j--)
  console.log("a[" + i + "][" + j + "] = " + a[i][j]);
........................
// Note that the following creates globals and is disallowed in strict mode.
a = b = 3, c = 4; // Returns 4 in console
console.log(a); // 3 (left-most)

x = (y = 5, z = 6); // Returns 6 in console
console.log(x); // 6 (right-most)
........................
function myFunc () {
  var x = 0;
  return (x += 1, x); // the same as return ++x;
} 
@reference_1

Wednesday, December 7, 2016

jQuery的isEmptyObject()方法

function isEmptyObject(e) {
var t;
for (t in e)
return !1;
return !0
}
......................
return !1 means return false and return !0 - return true.
when you place ! in front the result is evaluated as Boolean and it the opposite is returned.mostly see this in a code passed through google's optimizer. it is mostly done to achieve shortness of the code.
It is often used when boolean result is needed - you may see something like !!(expression). Search in jQuery, for example.

@reference_1
@reference_2

在一个js文件中包含另一个js文件

document.write("<script src='xxx.js'></script>");

Negative Array Index in Javascript

If you are from python or ruby school, you shall be familar with negative array index, like a[-1] will return the last element, a[-2] will return the second-to-last element and so on.
@reference_1

Tuesday, December 6, 2016

Javascript获取对象的属性名及对应的属性值

for(attribute in obj){
     alert(attribute);
     //alert(obj[attribute]);
}

@reference_0
---------------------------------
The following function traverse an Object and output its content:
function outputObj(o) {
    var txt = "",
        depth = 0;
    var sp = function(n) {
        var s = "";
        for (var i = 0; i < n; i++) {
            s += "&nbsp&nbsp&nbsp&nbsp&nbsp.";
        }
        return s;
    };
    var sub = function(obj) {
        var attr;
        for (attr in obj) {
            if ((typeof obj[attr]) !== "object") {
                txt += sp(depth) + "[attr:" + attr + " - depth:" + depth + " - value:<b>" +
                           obj[attr] + "</b>]<br>";
            } else {
                txt += sp(depth) + "[attr:" + attr + " - depth:" + depth + "]...<br>";
                depth++;
                arguments.callee(obj[attr]);
            }
        }
        depth--;
        return txt;
    };
    return sub(o);
}
..........................................
$("#demo").html(outputObj(obj));

Monday, December 5, 2016

Baidu Fanyi

var url = "http://fanyi.baidu.com/v2transapi";
var form = {
                    from: "en",
                    to: "zh",
                    query: "hot",
                    transtype: "realtime",
                    simple_means_flag: 3 };
$.post(url, form, showMsg);
------------------------------------------------------------
"liju_result" decoding codes are in the  "index_60f64ad.js" file
.....................................................................
var u = ["《柯林斯高阶英汉双解学习词典》", "《汉英大词典》", "百度翻译例句库"];

function buildSample(t) {
    var e = t;
    var a = "en", n = "zh";
    var r = {};
    if (r.tplData = {}, r.tplData.to_lang = n, e["double"] = e["double"].replace(/\\'/g, "'"), e.single = e.single.replace(/\\'/g, "'"), e["double"] = e["double"].replace(/[‘|’]/g, "'"), e.single = e.single.replace(/[‘|’]/g, "'"), e["double"]) {
        var u = this.getDoubleSample(e["double"]);
        r.tplData["double"] = u["double"], r.tplData.senData = u.senData, s = r;
    }
    if (e.single) {
        e.single = $.parseJSON(e.single), e.senData2 = [];
        for (var g = 0, p = e.single.length; p > g; g++) {
            var d, m = "";
            "zh" === n ? d = e.single[g][0] : "en" === n && (d = e.single[g][1]);
            for (var c = 0, h = d.length; h > c; c++)
                m += d[c][0], d[c][3] && (m += d[c][3]);
            m = encodeURIComponent(m), e.senData2[g] = m;
            var v = e.single[g][1];
            if (/^http\:\/\//.test(v)) {
                v = v.replace(/^http\:\/\//, "");
                var f = v.indexOf("/");
                e.single[g][2] = f > 0 ? v.substr(0, f) : v;
            } else
                e.single[g][2] = e.single[g][1], e.single[g][1] = "#";
        }
        r.tplData.single = e.single, r.tplData.senData2 = e.senData2;
    }
    return r.tplData;
}

function getDoubleSample(t) {
    var n = "zh";
    var e = {};

    e["double"] = $.parseJSON(t), e.senData = [];
    for (var a = !0, s = 0, l = e["double"].length; l > s; s++) {
        var i, o = "";
        "zh" === n ? i = e["double"][s][0] : "en" === n && (i = e["double"][s][1]);
        for (var r = 0, g = i.length; g > r; r++)
            o += i[r][0], i[r][4] && (o += i[r][4]);
        o = encodeURIComponent(o), e.senData[s] = o, a && $.inArray(e["double"][s][2], u) < 0 && (e["double"][s].isFirstNetSt = !0, a = !1);
        var p = e["double"][s][2];
        if (/^https?\:\/\//.test(p)) {
            p = p.replace(/^https?\:\/\//, "");
            var d = p.indexOf("/");
            e["double"][s][3] = d > 0 ? p.substr(0, d) : p;
        } else
            e["double"][s][3] = e["double"][s][2], e["double"][s][2] = "#";
    }
    return e;
}
------------------------------------------------------
var liju = {
      "double": "[[[[\"Some\",\"w_0\"............................."
      "tag": [
                 "截至"
      ],
     "single": "[[[[\"\\\"\",\"w_0\",0],[................................."
}

/*
 var txt = getDoubleSample(liju.double);
 var t = "", x, y;
for(x in txt["senData"]){
y = Number(x) + 1;
t += y + ". "+ txt["senData"][x] + "<(转义)br(转义)>"; }
t = decodeURIComponent(t);
$("#demo").html(t);
 */
var txt = buildSample(liju);
var t = "", x, y;

for (x in txt["senData2"]) {
y = Number(x) + 1;
 t += y + ". " + txt["senData2"][x] + "<(转义)br(转义)>"; }
t = decodeURIComponent(t);
$("#demo").html(t);

decodeURIComponent() and decodeURI()

What is the difference between decodeURIComponent() and decodeURI()?
 
To explain the difference between these two let me explain the difference between encodeURI and encodeURIComponent.
The main difference is that:
  • encodeURI is intended for use on the full URI.
  • encodeURIComponent is intended to be used on .. well .. URI components that is any part that lies between separators (; / ? : @ & = + $ , #).
So, in encodeURIComponent these separators are encoded also because they are regarded as text and not special characters.
Now back to the difference between the decode functions, each function decodes strings generated by its corresponding encode counterpart taking care of the semantics of the special characters and their handling.

@reference_1
@reference_2
@reference_3

Thursday, December 1, 2016

iciba - word

http://dict-mobile.iciba.com/interface/index.php?callback=jQuery19008480490877831784_1480641521922&c=word&m=getsuggest&nums=10&ck=709a0db45332167b0e2ce1868b84773e&timestamp=1480641526056&client=6&uid=0&is_need_mean=1&word=good&_=1480641521936

http://dict-mobile.iciba.com/interface/index.php?callback=jQuery19008480490877831785_1480641521923&c=word&m=getsuggest&nums=10&ck=709a0db45332167b0e2ce1868b84773e&timestamp=1480641526056&client=6&uid=0&is_need_mean=1&word=kid&_=1480641521944

http://dict-mobile.iciba.com/interface/index.php?callback=jQuery&c=word&m=getsuggest&nums=10&ck=709a0db45332167b0e2ce1868b84773e&timestamp=1480641526056&client=6&uid=0&is_need_mean=1&word=kick&_=1480641521944

-----------------------------------------------
search.js
define("m-search", ["api", "history"], function(e, t) {
    e.regist("getsuggest", "http://dict-mobile.iciba.com/interface/index.php", {
        c: "word",
        m: "getsuggest",
        nums: 10,
        ck: "709a0db45332167b0e2ce1868b84773e",
        timestamp: (new Date).getTime(),
        client: 6,
        uid: 0,
        is_need_mean: 1
    }), e.regist("hotword", "http://dict-mobile.iciba.com/interface/index.php", {
        c: "hotword",
        m: "getword",
        client: 4,
        type: 1,
        timestamp: 1449818906,
        uuid: "45E0C158-F794-4F5C-90BB-69FA54F9CD53",
        v: "8.2.4",
        sv: "iPhoneOS7.1.1",
        sign: "7094eb96b203669e",
        uid: "",
        wtype: 1,
        size: 10,
        lang: 1
    });

.............................................................
----------------------------------------------
http://dict-pc.iciba.com/interface/index.php?callback=jQuery&c=word&m=getsuggest&nums=10&ck=709a0db45332167b0e2ce1868b84773e&timestamp=1480641526056&client=6&uid=0&is_need_mean=1&word=kick&_=1480641521944

http://dict-pc.iciba.com/interface/index.php?c=word&m=getsuggest&nums=10&ck=709a0db45332167b0e2ce1868b84773e&timestamp=1480641526056&client=6&uid=0&is_need_mean=1&word=bus&_=1480641521944

http://dict-pc.iciba.com/interface/index.php?c=word&m=getsuggest&nums=30&client=6&is_need_mean=1&word=rodent

??????????????????????????
http://dict-pc.iciba.com/interface/index.php?c=word&m=getsuggest&nums=10&client=6&is_need_mean=1&word=as%20of

@reference_1

Wednesday, November 30, 2016

Poe's law

Poe's law is an Internet adage that states that, without a clear indicator of the author's intent, it is impossible to create a parody of extreme views so obviously exaggerated that it cannot be mistaken by some readers or viewers as a sincere expression of the parodied views.

The original statement of the adage, by Nathan Poe, was:
Without a winking smiley or other blatant display of humor, it is uttrerly impossible to parody a Creationist in such a way that someone won't mistake for the genuine article.

@reference_0

Monday, November 28, 2016

SQL injection

SQL injection is a technique where malicious users can inject SQL commands into an SQL statement, via web page input.
Injected SQL commands can alter SQL statement and compromise the security of a web application.

txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
The original purpose of the code was to create an SQL statement to select a user with a given user id.
If there is nothing to prevent a user from entering "wrong" input, the user can enter some "smart" input like this: UserId:

Server Result: SELECT * FROM Users WHERE UserId = 105 or 1=1
The SQL above is valid. It will return all rows from the table Users, since WHERE 1=1 is always true.

A smart hacker might get access to user names and passwords in a database by simply inserting " or ""=" into the user name or password text box:
User Name:

Password:

The code at the server will create a valid SQL statement like this:
 SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
The result SQL is valid. It will return all rows from the table Users, since  
WHERE ""="" is always true.

 SQL Injection Based on Batched SQL Statements 
The following input:
User id:

The code at the server would create a valid SQL statement like this:
 SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers

Parameters for Protection

How to build parameterized queries in some common web languages?INSERT INTO STATEMENT IN PHP:
$stmt = $dbh->prepare("INSERT INTO Customers (CustomerName,Address,City)
VALUES (:nam, :add, :cit)");
$stmt->bindParam(':nam', $txtNam);
$stmt->bindParam(':add', $txtAdd);
$stmt->bindParam(':cit', $txtCit);
$stmt->execute();
-------------------------------------------------
@reference_0

外键约束 Foreign Key Constraints

@reference_1   @reference_2

Sunday, November 27, 2016

insert values (` !== ", ` !== ')

INSERT INTO t_users (`t_username`, `t_password`, `t_name`, `t_email`) VALUES (`qqqqq`, `3bad6af0fa4b8b330d162e19938ee981`, `qqqq`, `qqqq`)
报错:  #1054 - Unknown column 'qqqqq' in 'field list'


 INSERT INTO t_users (`t_username`, `t_password`, `t_name`, `t_email`) VALUES ("qqqqq", "3bad6af0fa4b8b330d162e19938ee981", "qqqq", "qqqq")
或者
INSERT INTO t_users (`t_username`, `t_password`, `t_name`, `t_email`) VALUES ('qqqqq', '3bad6af0fa4b8b330d162e19938ee981', 'qqqq', 'qqqq')
执行成功

总结:插入值引号用"或',不能用` 。(` !== ", ` !== ')

Saturday, November 26, 2016

Tips - CSS Layout

*{margin: 0px;} // 去缝隙
header_t_l{... float:left;} // 对齐方式
header_t_r{... float:left;} // 用display:inline?
header_b{... float:left;}  // (?)<div>是block级别的
@reference_1

The Old Way - using {float: left;}{clear: left;}
The New Way - using {display: inline-block;}
@reference_2

...CSS box model中,width/height不算入padding和border...
@reference_3

img{vertical-align:middle;} //图片和input输入框水平对齐

Thursday, November 24, 2016

:nth-child & :nth-of-type

.first span:nth-child(2n+1),
.second span:nth-child(2n+1), 
.third span:nth-of-type(2n+1) { 
background-color: lime; 
}
--------------------
Responsive Table
A responsive table will display a horizontal scroll bar if the screen is too small to display the full content.
Add a container element (like <div>) with overflow-x:auto around the <table> element to make it responsive:
<div style="overflow-x:auto;">
<table>
... table content ...
</table>
</div>
------------------------
display: block;
display: inline;
display: none;
visibility: hidden;
@reference_2

position: static;
position: relative;
position: fixed;
position: absolute;
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).
However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
Note: A "positioned" element is one whose position is anything except static.
@reference_3

Wednesday, November 23, 2016

javascript Currying

function accumulator() {
    if (arguments.length > 0) {
        var arr = Array.prototype.slice.call(arguments, 0);
        var sum = Array.prototype.reduce.call(arr, function (a, b) { return a + b; });
        return sum;
        }
        else return 0;
}

function curryIt(fn) {
    if (arguments.length === 0 || typeof fn !== 'function') return 0;
    var args = Array.prototype.slice.call(arguments, 1);
    var newa = [];
    return function () {
         newa = Array.prototype.slice.call(arguments, 0);
         if (!newa.length) {
             return fn.apply(this, args);
         }
         else {
               args = args.concat(newa);
               return arguments.callee;
         }
   };
}
----------------------------------------
keywords: Closure, partially applied function / 闭包, 偏(应用)函数
@reference_1 @reference_2  @reference_3  @reference_4
@reference_5

Tuesday, November 22, 2016

Counting instances of values in an object

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

var countedNames = names.reduce(function(allNames, name) { 
  if (name in allNames) {
    allNames[name]++;
  }
  else {
    allNames[name] = 1;
  }
  return allNames;
}, {});
// countedNames is { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
@source_0 

Javascript 'in' operator

The in operator returns true if the specified property is in the specified object.
 // Arrays
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
0 in trees        // returns true
3 in trees        // returns true
6 in trees        // returns false
"bay" in trees    // returns false (you must specify the 
                  // index number, not the value at that index)
"length" in trees // returns true (length is an Array property)
Symbol.iterator in trees // returns true (arrays are iterable, works only in ES6+)

// Predefined objects
"PI" in Math          // returns true

// Custom objects
var mycar = {make: "Honda", model: "Accord", year: 1998};
"make" in mycar  // returns true
"model" in mycar // returns true
 @source_1
-------------------------
var point = {x:1,y:1};
"x" in point //true
"z" in point //false
"toString" in point //true
var ary = [1,2,3];
"0" in ary; //true,ary含有索引0("0"回转换为0);
1 in ary;  //true,ary含有索引1
3 in ary;  //false
@source_2
 


javascript '||'、'&&'

由于javascript是弱类型语言,所以在javascript中这两个表达式可能跟其他语言(比如java)中不太一样。
在javascript中,“&&”运算符运算法则如下:
如果&&左侧表达式的值为真值,则返回右侧表达式的值;否则返回左侧表达式的值。
||”运算符的运算法则如下:
如果||左侧表达式的值为真值,则返回左侧表达式的值;否则返回右侧表达式的值。

Source@0

The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objects before accessing their attributes:

var name = o && o.getName();
Or for setting default values:
var name = otherName || "default";
JavaScript has a ternary operator for conditional expressions:
var allowed = (age > 18) ? "yes" : "no";

@reference_1_mozilla

Tricky use case of map

It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors.
// Consider:
['1', '2', '3'].map(parseInt);
// While one could expect [1, 2, 3]
// The actual result is [1, NaN, NaN]

// parseInt is often used with one argument, but takes two.
// The first is an expression and the second is the radix.
// To the callback function, Array.prototype.map passes 3 arguments: 
// the element, the index, the array
// The third argument is ignored by parseInt, but not the second one,
// hence the possible confusion. See the blog post for more details

function returnInt(element) {
  return parseInt(element, 10);
}

['1', '2', '3'].map(returnInt); // [1, 2, 3]
// Actual result is an array of numbers (as expected)

// A simpler way to achieve the above, while avoiding the "gotcha":
['1', '2', '3'].map(Number); // [1, 2, 3] 
@Soure

why Array.prototype.map.call instead of Array.map.call

Array is a constructor function to create arrays.

If you type Array in browser console you will get a function definition, something like

function Array() { [native code] }

While if you type Array.prototype in browser console you will get an empty array i.e [ ] i.e. an Array object.

Consider this excerpt
function a(){
console.log('hi');
function b(){console.log('b');}
function c(){console.log('c');}
return {b:b,c:c,d:this}
}

When you type d = new a();
Then d is an object having two properties which are functions i.e. b and c and you can call

>> d.b() //logs b
>> d.c() //logs c

But you cannot call

a.b() or a.c() // since function b and c is not property of a.

So just as function b and c are defined in function a. Similarly function map is defined in function Array.

So you cannot call Array.map() but you have to get an object of Array and call map function on it.
Array.prototype gives us an Array object
Therefore they are using Array.prototype.map.call(a,func)

http://stackoverflow.com/questions/20153455/why-array-prototype-map-call-instead-of-array-map-call 

Using map to reverse a string

var str = '12345';
Array.prototype.map.call(str, function(x) {
  return x;
}).reverse().join(''); 

// Output: '54321'
// Bonus: use '===' to test if original string was a palindrome
 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map 

Monday, November 21, 2016

Array.prototype.slice.call()

Array.prototype.slice.call()能将具有length属性的对象转成数组
Array.prototype.slice.call(arguments)能够将arguments转成数组,那么就是 arguments.toArray().slice();
是不是就可以说Array.prototype.slice.call(arguments)的过程就是先将传入进来的第一个参数转为数组,再调用slice?

1 var a={length:2,0:'first',1:'second'};
2 Array.prototype.slice.call(a);//  ["first", "second"]
3  
4 var a={length:2};
5 Array.prototype.slice.call(a);//  [undefined, undefined]

http://www.cnblogs.com/littledu/archive/2012/05/19/2508672.html 
Array.prototype.slice.call(arguments,0);
Array.prototype.slice.call("abcd",0);
http://blog.chinaunix.net/uid-26672038-id-3336525.html 

(slice有两个用法,一个是String.slice,一个是Array.slice,
第一个返回的是字符串,第二个返回的是数组,这里我们看第2个。) 

Array toString() & String split()

<p>The toString() method returns an array as a comma separated string.</p>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
</script>
// result: Banana,Orange,Apple,Mango
-------------------------------
<script>
function myFunction() {
    var str = "a,b,c,d,e,f";
    var arr = str.split(",");
    document.getElementById("demo").innerHTML = arr[0];
}
</script>
// result: a
If the separator is omitted, the returned array will contain the whole string in index [0].
If the separator is "", the returned array will be an array of single characters.

Invoking a Function with call() and apply()

call() and apply() are predefined JavaScript function methods. Both methods can be used to invoke a function, and both methods must have the owner object as first parameter.

function myFunction(a, b) {
    return a * b;
}
myObject = myFunction.call(myObject, 10, 2);     // Will return 20 
 
function myFunction(a, b) {
    return a * b;
}
myArray = [10, 2];
myObject = myFunction.apply(myObject, myArray);  // Will also return 20 
 
The only difference is that call() takes the function arguments separately, and apply() takes the function arguments in an array. In JavaScript strict mode, the first argument becomes the value of this in the invoked function, even if the argument is not an object.
In "non-strict" mode, if the value of the first argument is null or undefined, it is replaced with the global object.
With call() or apply() you can set the value of this, and invoke a function as a new method of an existing object.
 http://www.w3schools.com/js/js_function_invocation.asp