<commit_before>/*
 *  To run the script,
 *     - assert , a node.js native module
 *     - sprintf-js,  npm install sprintf-js -g
 *
 */
var assert = require("assert");
var format = require("sprintf-js").sprintf;

echo ("===============================================")
echo ("------------------Testing for var x, y --------")
echo ("===============================================")
assert.strictEqual(x, undefined, "before var x");
assert.strictEqual(y, undefined, "before var y");
assert.equal(x, undefined, "before var x");
assert.equal(y, undefined, "before var y");

assert.notStrictEqual(x, null, "before var x");
assert.notStrictEqual(y, null, "before var y");
assert.equal(x, null, "before var x");
assert.equal(y, null, "before var y");

inspect("x",x);
inspect("y",y);

var x, y;
inspect("x",x);
inspect("y",y);
assert.strictEqual(x, undefined, "after var x");
assert.strictEqual(y, undefined, "after var y");
assert.equal(x, undefined, "after var x");
assert.equal(y, undefined, "after var y");

assert.notStrictEqual(x, null, "after var x");
assert.notStrictEqual(y, null, "after var y");
assert.equal(x, null, "after var x");
assert.equal(y, null, "after var y");

assign("x",x,1);
assert.notEqual(x, 1, "x is 0 now, becuase the function args is passed by value not reference.");
inspect("x",x);
x = assign("x",x,1);
assert.equal(x, 1, "x is 1 now");
inspect("x",x);

x = assign("x",x,0.01)
assert.equal(x, 0.01, "x is 0.01 now");
inspect("x",x);
x = assign("x",x,null);
inspect("x",x);
assert.strictEqual(x, null, "after x = null");
assert.equal(x, null, "after x = null");
assert.equal(x, undefined, "after x = null");
assert.notStrictEqual(x, undefined,  "after x = null");

y = assign("y",y,undefined);
inspect("y",y);

assert.equal(x==y,true,"== equal");
echo(format("x == y is true , since %s == %s",x,y));

assert.equal(x===y,false, "=== equal");
echo(format("x === y is false, since %s !=== %s", x, y));
echo(format("x is a %s, but y is a %s",typeof x, typeof y));

echo ("===============================================")
echo ('----------- Tests for "",\'\',null, undefined -')
echo ("===============================================")
echo(format('The "" == null is %s',""==null));
echo(format("The '' == null is %s",''==null));
echo(format("The '' ==   \"\" is %s",''==""));
echo(format("The '' ===  \"\" is %s",''===""));
echo(format("The '' ==  undefined is %s",''==undefined));
echo(format("The '' === undefined is %s",''===undefined));

echo ("===============================================")
echo ("-------------- Tests for object book ----------")
echo ("===============================================")
var book = {
	name:""
};
inspect("book",book);
inspect('book.name',book.name);
book.name="javascript";
inspect("book",book)
var book2 = assign("book2",book2,book);
inspect("book2",book2);
echo(format("The book == book2 is %s",book==book2));
echo(format("The book === book2 is %s",book===book2));
book2.name = assign("book2.name",book2.name,"nodejs");
inspect("book",book);
inspect("book2",book2);

var book3 = {
	name:"book3"
}
inspect("book3",book3);
echo(format("The book == book3 is %s",book==book3));
book3.name=assign("book3.name",book3.name,book.name);
inspect("book3",book3);
echo(format("The book == book3 is %s",book==book3));

echo ("===============================================")
echo ("-------------- Tests for String assignment ----")
echo ("-- String assign is always copy by value !      ")
echo ("===============================================")
var str1 = "hello", str2 = "hello";
inspect("str1",str1);
inspect("str2",str2);
echo(format("The str1 == str2 is %s",str1==str2));
echo(format("The str1 === str2 is %s",str1===str2));
str2 = assign("str2",str2,"world");
inspect("str1",str1);
inspect("str2",str2);
echo(format("The str1 == str2 is %s",str1===str2));
var str3 = assign("str3",str3,str1);
inspect("str3",str3)
str3 = assign("str3",str3,"hellonew");
inspect("str1",str1);
inspect("str2",str2);
inspect("str3",str3);

echo ("===============================================")
echo ("-------------- Tests for object assignment ----")
echo ("-- Object assign is always copy by reference   ")
echo ("===============================================")
var obj1 = {} , obj2 = {};
var obj3 = obj1 ;
inspect("object1",obj1);
inspect("object2",obj2);
inspect("object3",obj3);
echo(format("The obj1 == obj2 is %s",obj1==obj2));
echo(format("The obj1 == obj3 is %s",obj1==obj3));
echo(format("The obj1 === obj3 is %s",obj1===obj3));
obj1.name=assign("obj1.name",obj1.name,"hello");
inspect("object1",obj1);
inspect("object2",obj2);
inspect("object3",obj3);
echo(format("The obj1 == obj2 is %s",obj1==obj2));
echo(format("The obj1 == obj3 is %s",obj1==obj3));
echo(format("The obj1 === obj3 is %s",obj1===obj3));
obj2.name=obj1.name;
inspect("object1",obj1);
inspect("object2",obj2);
inspect("object3",obj3);
echo(format("The obj1 == obj2 is %s",obj1==obj2));
echo(format("The obj1 == obj3 is %s",obj1==obj3));
echo(format("The obj1 === obj3 is %s",obj1===obj3));

echo ("===============================================")
echo ("-------------- Tests for Build-in -------------")
echo ("===============================================")
echo (" typeof only have 5 kinds of return : ")
echo ("     undefined, boolean, number, string, funtion, object")
test_buildin("undefined",undefined);
test_buildin("0", 0);
test_buildin("a",'a');
test_buildin("A","A");
test_buildin("hello",'hello');
test_buildin("true",true);
test_buildin("false",false);
test_buildin("null",null); //object
test_buildin("{}",{});
test_buildin("function foo() {}",function foo() {});
var a = [1,2,3];
test_buildin("[1,2,3]",a);
inspect("a",a);
inspect("a.length",a.length);
var point = [
   { x : 0, y : 1},
   { x : 1, y : 0}
]
inspect("point",point);
inspect("point[0]",point[0]);
inspect("point[0].length",point[0].length);
inspect("[point[1]].length",[point[1]].length); // the length properties is only for array object!

echo(typeof Object) // Object is a function
echo(typeof Object.prototype); //Object.prototype is a object
echo(Object.prototype.toString.call(a)); // a is a array
echo(Array.isArray(a)) //true

// null is a object is a bug for history issue, see
// http://www.2ality.com/2013/10/typeof-null.html
// http://www.2ality.com/2013/01/categorizing-values.html
// They are two types in javascript, primative and object

function test_buildin(name,variable) {
	echo(format("%s is %s",name, typeof variable));
}

function inspect(name,variable) {
	if (typeof name != 'string') {
		assert.fail(name,undefined,format("call inspect(name,variable) error, 'name' is '%s' and 'variable' is '%s'",name,variable))
	}
	console.log(format("The variable '%s' is a '%s' :",name,typeof variable),variable);

}
function echo(msg) {
	console.log(msg);
}
function assign(name, variable, value) {
	if (name === undefined) {
		assert.fail(name,undefined,format("Calling assign(name, variable, value) error, The variable '%s' has been assign from '%s' to '%s'",name,variable,value));
	}
	var _var = variable;
	var _v = value;
    //petty print out for string
	if (typeof variable == 'string') { _var = "'"+variable+"'"};
	if (typeof value == 'string') { _v = "'"+value+"'"}
    console.log(format("The variable '%s' has been assign from %s to",name,_var),_v);
    variable = value;
	return variable;
}<commit_msg>fix toBase2String()<commit_after>/*
 *  To run the script,
 *     - assert , a node.js native module
 *     - sprintf-js,  npm install sprintf-js -g
 *
 */
var assert = require("assert");
var format = require("sprintf-js").sprintf;

/**
 * Add customize method to assert
 */
assert.true = function (msg,actual) {
	assert.equal(actual, true, "'" + msg + "' : test failed!");
	echo("'" + msg + "' : tested Ok!")
};

echo ("===============================================")
echo ("------------------Testing for var x, y --------")
echo ("===============================================")
assert.strictEqual(x, undefined, "before var x");
assert.strictEqual(y, undefined, "before var y");
assert.equal(x, undefined, "before var x");
assert.equal(y, undefined, "before var y");

assert.notStrictEqual(x, null, "before var x");
assert.notStrictEqual(y, null, "before var y");
assert.equal(x, null, "before var x");
assert.equal(y, null, "before var y");

inspect("x",x);
inspect("y",y);

var x, y;
inspect("x",x);
inspect("y",y);
assert.strictEqual(x, undefined, "after var x");
assert.strictEqual(y, undefined, "after var y");
assert.equal(x, undefined, "after var x");
assert.equal(y, undefined, "after var y");

assert.notStrictEqual(x, null, "after var x");
assert.notStrictEqual(y, null, "after var y");
assert.equal(x, null, "after var x");
assert.equal(y, null, "after var y");

assign("x",x,1);
assert.notEqual(x, 1, "x is 0 now, becuase the function args is passed by value not reference.");
inspect("x",x);
x = assign("x",x,1);
assert.equal(x, 1, "x is 1 now");
inspect("x",x);

x = assign("x",x,0.01)
assert.equal(x, 0.01, "x is 0.01 now");
inspect("x",x);
x = assign("x",x,null);
inspect("x",x);
assert.strictEqual(x, null, "after x = null");
assert.equal(x, null, "after x = null");
assert.equal(x, undefined, "after x = null");
assert.notStrictEqual(x, undefined,  "after x = null");

y = assign("y",y,undefined);
inspect("y",y);

assert.equal(x==y,true,"== equal");
echo(format("x == y is true , since %s == %s",x,y));

assert.equal(x===y,false, "=== equal");
echo(format("x === y is false, since %s !=== %s", x, y));
echo(format("x is a %s, but y is a %s",typeof x, typeof y));

echo ("===============================================")
echo ('----------- Tests for "",\'\',null, undefined -')
echo ("===============================================")
echo(format('The "" == null is %s',""==null));
echo(format("The '' == null is %s",''==null));
echo(format("The '' ==   \"\" is %s",''==""));
echo(format("The '' ===  \"\" is %s",''===""));
echo(format("The '' ==  undefined is %s",''==undefined));
echo(format("The '' === undefined is %s",''===undefined));

echo ("===============================================")
echo ("-------------- Tests for object book ----------")
echo ("===============================================")
var book = {
	name:""
};
inspect("book",book);
inspect('book.name',book.name);
book.name="javascript";
inspect("book",book)
var book2 = assign("book2",book2,book);
inspect("book2",book2);
echo(format("The book == book2 is %s",book==book2));
echo(format("The book === book2 is %s",book===book2));
book2.name = assign("book2.name",book2.name,"nodejs");
inspect("book",book);
inspect("book2",book2);

var book3 = {
	name:"book3"
}
inspect("book3",book3);
echo(format("The book == book3 is %s",book==book3));
book3.name=assign("book3.name",book3.name,book.name);
inspect("book3",book3);
echo(format("The book == book3 is %s",book==book3));

echo ("===============================================")
echo ("-------------- Tests for String assignment ----")
echo ("-- String assign is always copy by value !      ")
echo ("===============================================")
var str1 = "hello", str2 = "hello";
inspect("str1",str1);
inspect("str2",str2);
echo(format("The str1 == str2 is %s",str1==str2));
echo(format("The str1 === str2 is %s",str1===str2));
str2 = assign("str2",str2,"world");
inspect("str1",str1);
inspect("str2",str2);
echo(format("The str1 == str2 is %s",str1===str2));
var str3 = assign("str3",str3,str1);
inspect("str3",str3)
str3 = assign("str3",str3,"hellonew");
inspect("str1",str1);
inspect("str2",str2);
inspect("str3",str3);

echo ("===============================================")
echo ("-------------- Tests for object assignment ----")
echo ("-- Object assign is always copy by reference   ")
echo ("===============================================")
var obj1 = {} , obj2 = {};
var obj3 = obj1 ;
inspect("object1",obj1);
inspect("object2",obj2);
inspect("object3",obj3);
echo(format("The obj1 == obj2 is %s",obj1==obj2));
echo(format("The obj1 == obj3 is %s",obj1==obj3));
echo(format("The obj1 === obj3 is %s",obj1===obj3));
obj1.name=assign("obj1.name",obj1.name,"hello");
inspect("object1",obj1);
inspect("object2",obj2);
inspect("object3",obj3);
echo(format("The obj1 == obj2 is %s",obj1==obj2));
echo(format("The obj1 == obj3 is %s",obj1==obj3));
echo(format("The obj1 === obj3 is %s",obj1===obj3));
obj2.name=obj1.name;
inspect("object1",obj1);
inspect("object2",obj2);
inspect("object3",obj3);
echo(format("The obj1 == obj2 is %s",obj1==obj2));
echo(format("The obj1 == obj3 is %s",obj1==obj3));
echo(format("The obj1 === obj3 is %s",obj1===obj3));

echo ("===============================================")
echo ("-------------- Tests for Build-in -------------")
echo ("===============================================")
echo (" typeof only have 5 kinds of return : ")
echo ("     undefined, boolean, number, string, funtion, object")
echo ("     undefined, boolean, number, string, null(although claim object) they are primitives, immutable")
echo ("     ")
test_buildin("undefined",undefined);
test_buildin("0", 0);
test_buildin("a",'a');
test_buildin("A","A");
test_buildin("hello",'hello');
test_buildin("true",true);
test_buildin("false",false);
test_buildin("null",null); //object
test_buildin("{}",{});
test_buildin("function foo() {}",function foo() {});
var a = [1,2,3];
test_buildin("[1,2,3]",a);
inspect("a",a);
inspect("a.length",a.length);
var point = [
   { x : 0, y : 1},
   { x : 1, y : 0}
]
inspect("point",point);
inspect("point[0]",point[0]);
inspect("point[0].length",point[0].length);
inspect("[point[1]].length",[point[1]].length); // the length properties is only for array object!

echo(typeof Object) // Object is a function
echo(typeof Object.prototype); //Object.prototype is a object
echo(Object.prototype.toString.call(a)); // a is a array
echo(Array.isArray(a)) //true

// null is a object is a bug for history issue, see
// http://www.2ality.com/2013/10/typeof-null.html
// http://www.2ality.com/2013/01/categorizing-values.html
// They are two types in javascript, primative and object

var f1 = function foo () {};
var f2 = function foo () {};

echo(f1 === f2)  // false
echo(f1.prototype)
echo(typeof f1.prototype) ///object, not undefined
echo(f1.prototype === f2.prototype) //false
echo(Object.prototype === f1.prototype) //false
echo(String.prototype === Object.prototype) //false
echo(String.prototype == Object.prototype) //false
echo(typeof String.prototype.indexOf === "function") //true
echo(typeof Object.prototype.indexOf === "undefined") //true
echo(typeof f1.prototype.indexOf === "undefined") //true
f1.prototype = String.prototype ;
echo(typeof f1.prototype.indexOf === "function") //true
echo(f1)
echo(String)
echo(typeof new f1())
var f3 = new f1();
echo(typeof f1 === "function");
echo(typeof f3 === "object"); //f3 is a object,
echo(typeof f3.prototype === "undefined") //true, the f3 has no prototype now
echo(typeof f3.indexOf === "function") //true, the f3 has all functions copy from it's f1's prototype

echo ("===============================================")
echo ("-------------- Tests for Arrays   -------------")
echo ("===============================================")

assert.true("Array is a function",
	typeof Array === "function");
assert.true("Array.prototype has a push method.",
	typeof Array.prototype.push === "function");
assert.true("[] is a array object",
	typeof [] === "object");
assert.true("[].prototype is undefined, remember [] is a object",
	typeof [].prototype === 'undefined');
assert.true("[] also has a pash() method",
	typeof [].push === "function") ;
assert.true("They are just same !",
	Array.prototype.push === [].push);
a = [];
inspect("a",a);
assert.true("Method push() will return the new length of array, so lenght is 1",
	a.push("alex") === 1);
assert.true("now is alex",
	a[0] === 'alex');
inspect("a",a);
echo (Array.prototype.push("alex","wu")); // so push to where?

echo ("===============================================")
echo (" Tests Kinds of Object                         ")
echo ("     - Plain Object : type Object              ")
echo ("     - Array : type Array                      ")
echo ("     - Regular Express: type RegExp            ")
echo ("===============================================")

echo ("===============================================")
echo ("---- Tests for 'new' and prototype          ---")
echo ("===============================================")
function Point(x,y){
	this.x = x
	this.y = y
}
var p = new Point(1,1);
inspect('p',p);
assert.true("the p is a new Point object ",typeof p === 'object');
assert.true("p.x === 1", p.x === 1);
var p2 = Point(1,1); // p2 is just the return of calling of Point() funtion, there is no return , so undefined.
assert.true("var p2 = Point(1,1) -> p2 is just undefined!", typeof p2 === 'undefined');

var p3 = {};
echo (typeof p3);
echo (typeof p3.prototype);
echo (typeof p.prototype);
echo (typeof Point.prototype);
p3.prototype = Point.prototype;
inspect('p3',p3);

var p4 = new Point(); //new is just a create of this and assign
assert.true("p4.x and p4.y are all undefined", p4.x === undefined);

function Point2(x,y){
	this.x = x
	this.y = y
	return x+y
}
var p5 = new Point2();
var p6 = Point2();
echo(typeof p5);
echo(p5);
echo(p6);
assert.true("p6 is just a number", typeof p6 === "number");
p5.x = 1
echo(p5)
p6.x = 1 //no effect
echo (p6);
Point2.prototype.s = function() {
	if (this.x === undefined || this.y === undefined) return 0;
	return this.x + this.y ;
}
echo (p5.s())
p5.y = 2
echo (p5.s())
echo (p5)

echo ("===============================================")
echo ("---- Tests for Function                     ---")
echo ("===============================================")

var f = function() {};
assert.true("fuction is not object, it's supertype of object", typeof f === "function" );

echo ("===============================================")
echo ("---- Tests for instanceof                   ---")
echo ("===============================================")

assert.true(" {} instanceof Object ", {} instanceof Object);
assert.true(" [] instanceof Array",   [] instanceof Array);
assert.true(" [] instanceof Object",  [] instanceof Object); //Object is supper type of Array
assert.true(" 1 NOT instanceof Number, number isn't object, it's primitive", 1 instanceof Number === false);
assert.true(" true NOT instanceof Boolean, boolean isn't object, it's primitive", true instanceof Boolean === false);
assert.true(" p instanceof Point", p instanceof Point);

echo ("===============================================")
echo ("---- Tests for Wrapper type : String        ---")
echo ("===============================================")
assert.true("  \"\"===''  ", ""==='');
assert.true('  String() === ""', String() === '');
assert.true("  String(true) === 'true' (string!)", String(true) === 'true');

echo ("===============================================")
echo ("---- Tests for Wrapper type : Boolean       ---")
echo ("===============================================")
echo ("Boolean() used as funtion to test how a value is interperted.")
assert.true("Boolean() === false",Boolean() === false);
assert.true("Boolean(0) === false",Boolean(0) === false);
assert.true("Boolean(NaN) === false",Boolean(NaN) === false);
assert.true("Boolean(\"\") === false",Boolean("") === false);
assert.true("Boolean('') === false",Boolean('') === false);
assert.true("Boolean(null) === false",Boolean(null) === false);
assert.true("Boolean(undefined) === false",Boolean(undefined) === false);
assert.true("Boolean(false) === false",Boolean(false) === false);
echo ("All other input will consider a true!!!")

echo ("===============================================")
echo ("---- Tests for Binary logical               ---")
echo ("===============================================")
function foo() {
	assert.fail("the function foo should never called!")
}
echo ("false && foo() : the function foo() is never called. ")
false && foo()
echo ("true || foo()  : the function foo() is never called. ")
true || foo()

echo( "First && Second , first is falsy, return it, otherwise return second");
assert.true( " false && 'abc' -> false", (false && 'abc') === false);
assert.true( " '' && 'abc' -> '' ", ('' && 'abc') === ''); //NaN is falsy
assert.true( " true && 'abc' -> 'abc' ", (true && 'abc') === 'abc');
assert.true( " 123 && 'abc' -> 'abc' ",(123 && 'abc') === 'abc'); //123 is truthy
echo( "First || Second , first is truthy, return frist, otherwise return second");
assert.true( " 'abc'||123 -> 'abc'", ('abc'||123) === 'abc' );
assert.true( " ''||123 -> 123 ", (''||123)===123);

echo ("===============================================")
echo ("---- Tests for Wrapper type : Number       ----")
echo ("===============================================")
var n1 = 123
var n2 = Number(123);
var n3 = new Number(123); //never use it!
assert.true("123 is a number", typeof n1 === 'number');
assert.true("123.prototype is undefined", typeof n1.prototype === 'undefined');
assert.true("Number(123) is a number", typeof n2 === 'number');
assert.true("123 === Number(123)", n1 === n2);
assert.true("new Number(123) is object (never do is !!!)", typeof n3 === 'object');
assert.true("123 !== new Number(123)", n2 !== n3);
assert.true("Number.prototype is object", typeof Number.prototype === 'object');
assert.true("Number.prototype.valueOf() return 0, the initial value of Number object ", Number.prototype.valueOf() === 0);
assert.true("123 === new Number(123).valueOf()", n3.valueOf() === 123);
var n4 = Number('123');
assert.true("123 === Number('123'), string -> number", 123 === n4);
var n5 = Number();
var n6 = Number();
echo (n5 === n6);
echo (typeof n5 === 'number');
echo (n5.valueOf() === 0);
echo (Number() === 0);

assert.true("1 === 1.0 (All numbers are floating point!) ", 1 === 1.0);
assert.true("NaN !== NaN  (NaN, “not a number”, http://en.wikipedia.org/wiki/NaN", NaN !== NaN);
assert.true("Infinity === 1/0 ", Infinity === 1/0);
assert.true("-Infinity === -1/0", -Infinity === -1/0);
assert.true(" -0 === 0 ", -0 === 0);

echo ("===============================================")
echo ("---- Tests for bitwise flag       ----")
echo ("===============================================")
var FLAG_A = 1; // 0001
var FLAG_B = 2; // 0010
var FLAG_C = 4; // 0100
var FLAG_D = 8; // 1000
echo(FLAG_A|FLAG_B);
echo(FLAG_A|FLAG_B|FLAG_C);
echo(FLAG_A|FLAG_B|FLAG_C|FLAG_D);

var str = "foobar"
echo(str.indexOf('foo'));
echo(~str.indexOf('foo'));
echo(str.indexOf('b'));
echo(~str.indexOf('b'));
echo(~str.indexOf('alex'));
echo(~str.indexOf('wu'));
echo(Boolean(-1));
echo(Boolean(0));
echo(1>-1);
echo(0>-1);
echo(-0>-1);
echo(format("%b",FLAG_D))

assert.true("314" , toBase2String(314) === '00000000000000000000000100111010');
assert.true("~314",toBase2String(~314) === '11111111111111111111111011000101');
assert.true("0"   ,   toBase2String(0) === '00000000000000000000000000000000');
assert.true("-1",    toBase2String(-1) === '11111111111111111111111111111111');
assert.true("-2147483648", toBase2String(-2147483648) === '10000000000000000000000000000000');
assert.true( "2147483647",  toBase2String(2147483647) === '01111111111111111111111111111111');

function toBase2String(number,length){
	var _size = 32 ;
	var _number = number;
	if (length && typeof length === 'number'){
		_size = length;
	}
	if (typeof _number === 'number') {
		var head ='';
        var bit = '0';
		if (number < 0) {
			_number  = (-_number) -1 ;
			bit = '1';
		}
		var result = Number(_number).toString(2);
		if (number < 0 ) {
			var _result = '';
			for (index=0; index < result.length ; index ++){
				if (result.substr(index,1) === '1') {
                    _result += '0';
				}else{
					_result += '1';
				}
			}
			result = _result;
		}
		for (index= 0 ; index < (_size-result.length) ; index ++){
			head+=bit;
		}
		return head+result;
	}
}

function test_buildin(name,variable) {
	echo(format("%s is %s",name, typeof variable));
}

function inspect(name,variable) {
	if (typeof name != 'string') {
		assert.fail(name,undefined,format("call inspect(name,variable) error, 'name' is '%s' and 'variable' is '%s'",name,variable))
	}
	console.log(format("The variable '%s' is a '%s' :",name,typeof variable),variable);

}
function echo(msg) {
	console.log(msg);
}
function assign(name, variable, value) {
	if (name === undefined) {
		assert.fail(name,undefined,format("Calling assign(name, variable, value) error, The variable '%s' has been assign from '%s' to '%s'",name,variable,value));
	}
	var _var = variable;
	var _v = value;
    //petty print out for string
	if (typeof variable == 'string') { _var = "'"+variable+"'"};
	if (typeof value == 'string') { _v = "'"+value+"'"}
    console.log(format("The variable '%s' has been assign from %s to",name,_var),_v);
    variable = value;
	return variable;
}<|endoftext|>


<commit_before>var Net = require('net');

var Host = '127.0.0.1';
var Port = 1234;

var Header = [];
var FlightData = {};
var map;
var planeMarker;
var planeIcon;
var popup = L.popup();

$(document).ready(function () {
    DrawArtificalHorizon(0, 0);
    SetAltimeter(0);

    map = L.map('map').setView([43.53086, -80.5772], 17);

    planeIcon = L.icon({
        iconUrl: 'plane.png',
        iconSize: [30, 30], // size of the icon
    });

    L.tileLayer('sat_tiles/{z}/{x}/{y}.png', {
        maxZoom: 19
    }).addTo(map);

    planeMarker = L.marker([43.53086, -80.5772], {
        icon: planeIcon
    }).addTo(map);

    map.on('click', MapClick);
});

function WriteToLog(text) {
    var logDiv = $('#log')
    logDiv.empty()
    var newItem = $('
' + text + '
');
    logDiv.append(newItem);
}

function ConnectHandler(err) {
    if (!err) {
        console.log('Connected: ' + Host + ':' + Port);
    }
}

function ErrorHandler(err) {
    console.log(err.code)
}

function DataHander(data) {
    if (Header.length === 0) {
        Header = data.toString().split(",");
        return
    }

    var dataSplit = data.toString().split(",");

    for (var i = 0; i < dataSplit.length; i++) {
        FlightData[Header[i]] = dataSplit[i];
    }

    WriteToLog('
' +
        'Pitch: ' + FlightData["pitch"] +
        ' Roll: ' + FlightData["roll"] +
        ' Yaw: ' + FlightData["yaw"] +
        ' Latitude: ' + FlightData["lat"] +
        ' Longitude: ' + FlightData["lon"] +
        ' Altitude: ' + FlightData["altitude"] +
        ' Heading: ' + FlightData["heading"] +
        '
');

    UpdateUI()
}

function DrawArtificalHorizon(roll, pitch) {
    //Initialize canvas
    var canvas = document.getElementById("horizon");
    canvas.height = 200;
    canvas.width = 200;
    var context = canvas.getContext("2d");
    context.clearRect(0, 0, canvas.width, canvas.height);

    //Sky
    context.fillStyle = "#03a9f4";
    context.beginPath();
    context.arc(100, 100, 100, Math.PI + roll - pitch, 2 * Math.PI + roll + pitch);
    context.fill();

    //Ground
    context.fillStyle = "#795548";
    context.beginPath();
    context.arc(100, 100, 100, 0 + roll + pitch, Math.PI + roll - pitch);
    context.fill();

    //Border
    context.strokeStyle = "black";
    context.lineWidth = 2;
    context.beginPath();
    context.arc(100, 100, 99, 0, 2 * Math.PI);
    context.stroke();

    //Center
    context.fillStyle = "black";
    context.beginPath();
    context.lineWidth = 2;
    context.arc(100, 100, 2, 0, 2 * Math.PI);
    context.fill();
    context.beginPath();
    context.moveTo(120, 100);
    context.lineTo(110, 100);
    context.stroke();
    context.arc(100, 100, 10, 0, Math.PI);
    context.stroke();
    context.lineTo(80, 100);
    context.stroke();
}

function SetAltimeter(altitude) {
    var altimeter = $('#altimeter')
    altimeter.empty()
    var newItem = $('
' + altitude + '
');
    altimeter.append(newItem);
}

function UpdateMap(lat, lon, heading) {
    map.removeLayer(planeMarker);
    planeMarker = L.marker([lat, lon], {
        icon: planeIcon
    }).addTo(map);
    var transform = $('.leaflet-marker-icon').css('transform')
    $('.leaflet-marker-icon').css('transform', transform + 'rotate(' + heading + 'deg)')
}

function MapClick(e) {
    popup
        .setLatLng(e.latlng)
        .setContent('
Add Waypoint
')
        .openOn(map);

    $('.addWaypoint').on('click', function () {
        map.closePopup();
        marker = L.marker(e.latlng).addTo(map);
    });
}

function UpdateUI() {
    roll = FlightData["roll"] * (Math.PI / 180);
    pitch = FlightData["pitch"] * (Math.PI / 180);
    yaw = FlightData["yaw"] * (Math.PI / 180);
    lat = FlightData["lat"];
    lon = FlightData["lon"];
    altitude = FlightData["altitude"];
    heading = FlightData["heading"];

    DrawArtificalHorizon(roll, pitch);
    SetAltimeter(altitude);

    if (!isNaN(lat) || !isNaN(lon)) {
        UpdateMap(lat, lon, heading);
    }
}

var client = new Net.Socket();

client.connect(Port, Host, ConnectHandler);
client.on('error', ErrorHandler);
client.on('data', DataHander);
client.on('close', CloseHandler);

function CloseHandler() {
    WriteToLog('Connection closed - Retrying connection');
    Header = [];
    client = new Net.Socket();
    client.connect(Port, Host, ConnectHandler);
    client.on('error', ErrorHandler);
    client.on('data', DataHander);
    client.on('close', CloseHandler);
}<commit_msg>Rotate only the plane marker<commit_after>L.RotatedMarker = L.Marker.extend({
    options: {
        angle: 0
    },
    _setPos: function (pos) {
        L.Marker.prototype._setPos.call(this, pos);
        this._icon.style[L.DomUtil.TRANSFORM] += ' rotate(' + this.options.angle + 'deg)';
    }
});

L.rotatedMarker = function (pos, options) {
    return new L.RotatedMarker(pos, options);
};

var Net = require('net');

var Host = '127.0.0.1';
var Port = 1234;

var Header = [];
var FlightData = {};
var map;
var planeMarker;
var planeIcon;
var popup = L.popup();

$(document).ready(function () {
    DrawArtificalHorizon(0, 0);
    SetAltimeter(0);

    map = L.map('map').setView([43.53086, -80.5772], 17);

    planeIcon = L.icon({
        iconUrl: 'plane.png',
        iconSize: [30, 30], // size of the icon
    });

    L.tileLayer('sat_tiles/{z}/{x}/{y}.png', {
        maxZoom: 19
    }).addTo(map);

    planeMarker = L.rotatedMarker([43.53086, -80.5772], {
        icon: planeIcon
    }).addTo(map);

    map.on('click', MapClick);
});

function WriteToLog(text) {
    var logDiv = $('#log')
    logDiv.empty()
    var newItem = $('
' + text + '
');
    logDiv.append(newItem);
}

function ConnectHandler(err) {
    if (!err) {
        console.log('Connected: ' + Host + ':' + Port);
    }
}

function ErrorHandler(err) {
    console.log(err.code)
}

function DataHander(data) {
    if (Header.length === 0) {
        Header = data.toString().split(",");
        return
    }

    var dataSplit = data.toString().split(",");

    for (var i = 0; i < dataSplit.length; i++) {
        FlightData[Header[i]] = dataSplit[i];
    }

    WriteToLog('
' +
        'Pitch: ' + FlightData["pitch"] +
        ' Roll: ' + FlightData["roll"] +
        ' Yaw: ' + FlightData["yaw"] +
        ' Latitude: ' + FlightData["lat"] +
        ' Longitude: ' + FlightData["lon"] +
        ' Altitude: ' + FlightData["altitude"] +
        ' Heading: ' + FlightData["heading"] +
        '
');

    UpdateUI()
}

function DrawArtificalHorizon(roll, pitch) {
    //Initialize canvas
    var canvas = document.getElementById("horizon");
    canvas.height = 200;
    canvas.width = 200;
    var context = canvas.getContext("2d");
    context.clearRect(0, 0, canvas.width, canvas.height);

    //Sky
    context.fillStyle = "#03a9f4";
    context.beginPath();
    context.arc(100, 100, 100, Math.PI + roll - pitch, 2 * Math.PI + roll + pitch);
    context.fill();

    //Ground
    context.fillStyle = "#795548";
    context.beginPath();
    context.arc(100, 100, 100, 0 + roll + pitch, Math.PI + roll - pitch);
    context.fill();

    //Border
    context.strokeStyle = "black";
    context.lineWidth = 2;
    context.beginPath();
    context.arc(100, 100, 99, 0, 2 * Math.PI);
    context.stroke();

    //Center
    context.fillStyle = "black";
    context.beginPath();
    context.lineWidth = 2;
    context.arc(100, 100, 2, 0, 2 * Math.PI);
    context.fill();
    context.beginPath();
    context.moveTo(120, 100);
    context.lineTo(110, 100);
    context.stroke();
    context.arc(100, 100, 10, 0, Math.PI);
    context.stroke();
    context.lineTo(80, 100);
    context.stroke();
}

function SetAltimeter(altitude) {
    var altimeter = $('#altimeter')
    altimeter.empty()
    var newItem = $('
' + altitude + '
');
    altimeter.append(newItem);
}

function UpdateMap(lat, lon, heading) {
    map.removeLayer(planeMarker);
    planeMarker = L.rotatedMarker([lat, lon], {
        icon: planeIcon,
        angle: heading
    }).addTo(map);
}

function MapClick(e) {
    popup
        .setLatLng(e.latlng)
        .setContent('
Add Waypoint
')
        .openOn(map);

    $('.addWaypoint').on('click', function () {
        map.closePopup();
        marker = L.marker(e.latlng).addTo(map);
    });
}

function UpdateUI() {
    roll = FlightData["roll"] * (Math.PI / 180);
    pitch = FlightData["pitch"] * (Math.PI / 180);
    yaw = FlightData["yaw"] * (Math.PI / 180);
    lat = FlightData["lat"];
    lon = FlightData["lon"];
    altitude = FlightData["altitude"];
    heading = FlightData["heading"];

    DrawArtificalHorizon(roll, pitch);
    SetAltimeter(altitude);

    if (!isNaN(lat) || !isNaN(lon)) {
        UpdateMap(lat, lon, heading);
    }
}

var client = new Net.Socket();

client.connect(Port, Host, ConnectHandler);
client.on('error', ErrorHandler);
client.on('data', DataHander);
client.on('close', CloseHandler);

function CloseHandler() {
    WriteToLog('Connection closed - Retrying connection');
    Header = [];
    client = new Net.Socket();
    client.connect(Port, Host, ConnectHandler);
    client.on('error', ErrorHandler);
    client.on('data', DataHander);
    client.on('close', CloseHandler);
}<|endoftext|>


<commit_before>//DEMO
var player = new Player(400,400);
var enemy = new Enemy(640,480);
var bonfire = new bonfire(640,480);
var warmth = new Warmth()
var fur = new fur(700,275)
//var mouse = new Mouse();
var Grass = document.createElement("img");
var gameover = new GameOverState ();

Grass.src = "snow.png";

function collision(x1, y1, w1, h1, x2, y2, w2, h2)
{
	if ( 	y2 + h2 < y1 ||
			x2 + w2 < x1 ||
			x2 > x1 + w1 ||
			y2 > y1 + h1)
		return false;
	return true;
}

var Background = [];

for (var y = 0; y < 15; y++)
{
	Background[y] = [];
	for (var x = 0; x < 20; x++)
	{
		Background[y][x] = Grass;
	}
}

function DEMONSTRATION(deltatime)
{

var CollideEnemy = collision(player.PositionX, player.PositionY, player.playerWidth,player.playerHeight,enemy.POS.x,enemy.POS.y,enemy.bodyW,enemy.bodyH)

if (CollideEnemy == true)
{
	player.alive = false
}

for (var y = 0; y < 15; y++)
	{
		for (var x = 0; x < 20; x++)
		{
			context.drawImage( Background[y][x],
							   x * 128, y * 128);
		}
	}
	warmth.update(deltatime);
	drawMap(context);
	enemy.draw(context);
	enemy.update(deltatime);
	SceneManager.update(deltatime);
	SceneManager.draw();
	player.draw(context);
	player.update(deltatime);
	fur.update(deltatime);
	fur.draw(context);
	context.fillStyle = "#000";
	context.font = "30px Arial";
	context.fillText( "warmth" + warmth.DEFAULT,600 ,50 );
	gameover.update(deltatime);
	gameover.draw(context);

}<commit_msg>+Added Warmth counter<commit_after>//DEMO
var player = new Player(400,400);
var enemy = new Enemy(640,480);
var bonfire = new bonfire(640,480);
var warmth = new Warmth()
var fur = new fur(700,275)
//var mouse = new Mouse();
var Grass = document.createElement("img");
var gameover = new GameOverState ();

Grass.src = "snow.png";

function collision(x1, y1, w1, h1, x2, y2, w2, h2)
{
	if ( 	y2 + h2 < y1 ||
			x2 + w2 < x1 ||
			x2 > x1 + w1 ||
			y2 > y1 + h1)
		return false;
	return true;
}

var Background = [];

for (var y = 0; y < 15; y++)
{
	Background[y] = [];
	for (var x = 0; x < 20; x++)
	{
		Background[y][x] = Grass;
	}
}

function DEMONSTRATION(deltatime)
{

var CollideEnemy = collision(player.PositionX, player.PositionY, player.playerWidth,player.playerHeight,enemy.POS.x,enemy.POS.y,enemy.bodyW,enemy.bodyH)

if (CollideEnemy == true)
{
	player.alive = false
}

for (var y = 0; y < 15; y++)
	{
		for (var x = 0; x < 20; x++)
		{
			context.drawImage( Background[y][x],
							   x * 128, y * 128);
		}
	}
	warmth.update(deltatime);
	drawMap(context);
	enemy.draw(context);
	enemy.update(deltatime);
	SceneManager.update(deltatime);
	SceneManager.draw();
	player.draw(context);
	player.update(deltatime);
	fur.update(deltatime);
	fur.draw(context);
	context.fillStyle = "#000";
	context.font = "30px Arial";
	context.fillText( "Warmth:"+ "  " + Math.floor(warmth.DEFAULT),200 ,50 );
	gameover.update(deltatime);
	gameover.draw(context);

}<|endoftext|>


<commit_before>/*
 * The complete set of Elix elements.
 *
 * This is primarily used during testing, as it causes all Elix's elements and
 * mixins to be loaded/built. Generally, you can ignore this file, and import
 * the source file(s) you want from the src folder.
 */

 // Import mixins
import * as content from './mixins/content.js';
import AttributeMarshallingMixin from './mixins/AttributeMarshallingMixin.js';
import ClickSelectionMixin from './mixins/ClickSelectionMixin.js';
import constants from './mixins/constants.js';
import ContentItemsMixin from './mixins/ContentItemsMixin.js';
import defaultScrollTarget from './mixins/defaultScrollTarget.js';
import DirectionSelectionMixin from './mixins/DirectionSelectionMixin.js';
import KeyboardDirectionMixin from './mixins/KeyboardDirectionMixin.js';
import KeyboardMixin from './mixins/KeyboardMixin.js';
import KeyboardPagedSelectionMixin from './mixins/KeyboardPagedSelectionMixin.js';
import KeyboardPrefixSelectionMixin from './mixins/KeyboardPrefixSelectionMixin.js';
import OpenCloseTransitionMixin from './mixins/OpenCloseTransitionMixin.js';
import OverlayMixin from './mixins/OverlayMixin.js';
import SelectionAriaMixin from './mixins/SelectionAriaMixin.js';
import SelectionInViewMixin from './mixins/SelectionInViewMixin.js';
import ShadowReferencesMixin from './mixins/ShadowReferencesMixin.js';
import ShadowTemplateMixin from './mixins/ShadowTemplateMixin.js';
import SingleSelectionMixin from './mixins/SingleSelectionMixin.js';
import SlotContentMixin from './mixins/SlotContentMixin.js';
import Symbol from './mixins/Symbol.js';
import symbols from './mixins/symbols.js';

// Import elements
import AlertDialog from './elements/AlertDialog.js';
import Dialog from './elements/Dialog.js';
import Drawer from './elements/Drawer.js';
import ListBox from './elements/ListBox.js';
import Modes from './elements/Modes.js';
import Popup from './elements/Popup.js';
import Spread from './elements/Spread.js';
import TabButton from './elements/TabButton.js';
import Tabs from './elements/Tabs.js';
import TabStrip from './elements/TabStrip.js';
import Toast from './elements/Toast.js';

// The complete list of all mixins and elements.
export default {
  AlertDialog,
  AttributeMarshallingMixin,
  ClickSelectionMixin,
  constants,
  content,
  ContentItemsMixin,
  defaultScrollTarget,
  Dialog,
  DirectionSelectionMixin,
  Drawer,
  KeyboardDirectionMixin,
  KeyboardMixin,
  KeyboardPagedSelectionMixin,
  KeyboardPrefixSelectionMixin,
  ListBox,
  Modes,
  OpenCloseTransitionMixin,
  OverlayMixin,
  Popup,
  SelectionAriaMixin,
  SelectionInViewMixin,
  ShadowReferencesMixin,
  ShadowTemplateMixin,
  SingleSelectionMixin,
  SlotContentMixin,
  Spread,
  Symbol,
  symbols,
  TabButton,
  Tabs,
  TabStrip,
  Toast
};
<commit_msg>Add missing export for AutosizeTextarea so that it gets transpiled.<commit_after>/*
 * The complete set of Elix elements.
 *
 * This is primarily used during testing, as it causes all Elix's elements and
 * mixins to be loaded/built. Generally, you can ignore this file, and import
 * the source file(s) you want from the src folder.
 */

 // Import mixins
import * as content from './mixins/content.js';
import AttributeMarshallingMixin from './mixins/AttributeMarshallingMixin.js';
import ClickSelectionMixin from './mixins/ClickSelectionMixin.js';
import constants from './mixins/constants.js';
import ContentItemsMixin from './mixins/ContentItemsMixin.js';
import defaultScrollTarget from './mixins/defaultScrollTarget.js';
import DirectionSelectionMixin from './mixins/DirectionSelectionMixin.js';
import KeyboardDirectionMixin from './mixins/KeyboardDirectionMixin.js';
import KeyboardMixin from './mixins/KeyboardMixin.js';
import KeyboardPagedSelectionMixin from './mixins/KeyboardPagedSelectionMixin.js';
import KeyboardPrefixSelectionMixin from './mixins/KeyboardPrefixSelectionMixin.js';
import OpenCloseTransitionMixin from './mixins/OpenCloseTransitionMixin.js';
import OverlayMixin from './mixins/OverlayMixin.js';
import SelectionAriaMixin from './mixins/SelectionAriaMixin.js';
import SelectionInViewMixin from './mixins/SelectionInViewMixin.js';
import ShadowReferencesMixin from './mixins/ShadowReferencesMixin.js';
import ShadowTemplateMixin from './mixins/ShadowTemplateMixin.js';
import SingleSelectionMixin from './mixins/SingleSelectionMixin.js';
import SlotContentMixin from './mixins/SlotContentMixin.js';
import Symbol from './mixins/Symbol.js';
import symbols from './mixins/symbols.js';

// Import elements
import AlertDialog from './elements/AlertDialog.js';
import AutosizeTextarea from './elements/AutosizeTextarea.js';
import Dialog from './elements/Dialog.js';
import Drawer from './elements/Drawer.js';
import ListBox from './elements/ListBox.js';
import Modes from './elements/Modes.js';
import Popup from './elements/Popup.js';
import Spread from './elements/Spread.js';
import TabButton from './elements/TabButton.js';
import Tabs from './elements/Tabs.js';
import TabStrip from './elements/TabStrip.js';
import Toast from './elements/Toast.js';

// The complete list of all mixins and elements.
export default {
  AlertDialog,
  AttributeMarshallingMixin,
  AutosizeTextarea,
  ClickSelectionMixin,
  constants,
  content,
  ContentItemsMixin,
  defaultScrollTarget,
  Dialog,
  DirectionSelectionMixin,
  Drawer,
  KeyboardDirectionMixin,
  KeyboardMixin,
  KeyboardPagedSelectionMixin,
  KeyboardPrefixSelectionMixin,
  ListBox,
  Modes,
  OpenCloseTransitionMixin,
  OverlayMixin,
  Popup,
  SelectionAriaMixin,
  SelectionInViewMixin,
  ShadowReferencesMixin,
  ShadowTemplateMixin,
  SingleSelectionMixin,
  SlotContentMixin,
  Spread,
  Symbol,
  symbols,
  TabButton,
  Tabs,
  TabStrip,
  Toast
};
<|endoftext|>


<commit_before>'use strict';
var coding = '5px'; //need to get rid of
var drink = '0.12';
//CREATE IMG
function Images(name) {
  this.name = name;
  this.source = 'img/' + this.name + '.jpg';
  Images.all.push(this);
}

Images.all = [];
Images.allNames = ['compare1','compare2', 'kittens', 'lilcat', 'lion', 'llamas', 'loveprairedog', 'meerkats', 'otter', 'penguins', 'prairedog', 'puppies', 'sparkles', 'SpearsAgi', 'wardog', 'wolves', 'zombies'];

for(var i = 0; i < Images.allNames.length; i++){
  new Images(Images.allNames[i]);
}

//ASSIGN ANSWERS TO each img object
Images.all[0].answer = [{y:'1 bag'},{n1: '2bags'},{n2: '3bags'}];
Images.all[1].answer = [{n1:'1 bag'},{y: '2bags'},{n2: '3bags'}];

Images.previousImg = [];

function loadImg(){
  var randomIndex = Math.floor(Math.random() * Images.allNames.length);
  if(!Images.previousImg.includes(randomIndex)) {
    Images.all[randomIndex];
    var imgEl = document.createElement('img');
    imgEl.setAttribute('src', Images.all[randomIndex].source);
    imgEl.setAttribute('alt', Images.all[randomIndex].name);
    document.getElementById('img_box').appendChild(imgEl);
    Images.previousImg.push(randomIndex);

//!!!!!!!!!!!!!the following line needs a for loop for ALL imgs
    for(var i = 0; i < Images.all[1].answer.length; i++){
      var btnEl = document.createElement('button');
      btnEl.textContent = Object.values(Images.all[1].answer[i]);
      btnEl.setAttribute('id', Object.keys(Images.all[1].answer[i]));
      document.getElementById('answers').appendChild(btnEl);
    }

  } else {
    loadImg();
  }
  imageRender('0.12', '5px');//test, need to delete
}
//PAGE LOAD IMG
loadImg();

function answersHandler(e) {
  console.log(e.target.id);
  if(e.target.id === 'y'){
    alert('Right!');
    document.getElementById('img_box').innerHTML = '';
    document.getElementById('answers').innerHTML = '';
    loadImg();
  } else {
    alert('Wrong!');
  }
}

//EVENT listener
document.getElementById('answers').addEventListener('click', answersHandler);

//IMG ALTERING FUNCTION
//test:

function imageRender(drink, coding){
  var shakeLevel = drink + 's';
  var blurLevel = 'blur(' + coding + ')';
  document.getElementById('img_box').children[0].style.animationName = 'shake ';
  document.getElementById('img_box').children[0].style.animationDuration = shakeLevel ;
  document.getElementById('img_box').children[0].style.filter = blurLevel;
}
<commit_msg>delete names that don't match the img path<commit_after>'use strict';
var coding = '5px'; //need to get rid of
var drink = '0.12';
//CREATE IMG
function Images(name) {
  this.name = name;
  this.source = 'img/' + this.name + '.jpg';
  Images.all.push(this);
}

Images.all = [];
Images.allNames = ['compare1','compare2', 'kittens', 'llamas', 'loveprairedog', 'meerkats', 'penguins', 'puppies', 'sparkles', 'SpearsAgi', 'wardog', 'wolves', 'zombies'];

for(var i = 0; i < Images.allNames.length; i++){
  new Images(Images.allNames[i]);
}

//ASSIGN ANSWERS TO each img object
Images.all[0].answer = [{y:'1 bag'},{n1: '2bags'},{n2: '3bags'}];
Images.all[1].answer = [{n1:'1 bag'},{y: '2bags'},{n2: '3bags'}];

Images.previousImg = [];

function loadImg(){
  var randomIndex = Math.floor(Math.random() * Images.allNames.length);
  if(!Images.previousImg.includes(randomIndex)) {
    Images.all[randomIndex];
    var imgEl = document.createElement('img');
    imgEl.setAttribute('src', Images.all[randomIndex].source);
    imgEl.setAttribute('alt', Images.all[randomIndex].name);
    document.getElementById('img_box').appendChild(imgEl);
    Images.previousImg.push(randomIndex);

//!!!!!!!!!!!!!the following line needs a for loop for ALL imgs
    for(var i = 0; i < Images.all[1].answer.length; i++){
      var btnEl = document.createElement('button');
      btnEl.textContent = Object.values(Images.all[1].answer[i]);
      btnEl.setAttribute('id', Object.keys(Images.all[1].answer[i]));
      document.getElementById('answers').appendChild(btnEl);
    }

  } else {
    loadImg();
  }
  imageRender('0.12', '5px');//test, need to delete
}
//PAGE LOAD IMG
loadImg();

function answersHandler(e) {
  console.log(e.target.id);
  if(e.target.id === 'y'){
    alert('Right!');
    document.getElementById('img_box').innerHTML = '';
    document.getElementById('answers').innerHTML = '';
    loadImg();
  } else {
    alert('Wrong!');
  }
}

//EVENT listener
document.getElementById('answers').addEventListener('click', answersHandler);

//IMG ALTERING FUNCTION
//test:

function imageRender(drink, coding){
  var shakeLevel = drink + 's';
  var blurLevel = 'blur(' + coding + ')';
  document.getElementById('img_box').children[0].style.animationName = 'shake ';
  document.getElementById('img_box').children[0].style.animationDuration = shakeLevel ;
  document.getElementById('img_box').children[0].style.filter = blurLevel;
}
<|endoftext|>


<commit_before>
// Based on https://github.com/gigamonkey/gg

(function () {

  // ===================
  // NODE/BROWSER CONFIG
  // ===================

  var isNode = false;

  // If Node, create a fake DOM with jsdom and require dependencies.
  if (typeof module !== 'undefined' && module.exports) {

    isNode = true;

    document = require('jsdom').jsdom();
    window = document.parentWindow;

    this.d3 = require('d3');
    this._  = require('underscore');

  }

  if (!d3 || !_) { throw 'ggd3 requires D3 and Underscore.'; }

  // =======
  // GRAPHIC
  // =======

  // The Graphic constructor is the entry point to ggd3.
  // All arguments are optional.

  function Graphic(opts, data, el, width, height, renderNow) {
    if(opts)      { this.setup(opts); }
    if(data)      { this.data(data); }
    if(el)        { this.build(el, width, height); }
    if(renderNow) { this.render(); }
  }

  Graphic.prototype.setup = function(opts) {
    _.defaults(opts || {}, { facets: {}, layers: [] });
    this.facetsController = new FacetsController(opts);
  };

  Graphic.prototype.data = function(data) {
    if (!_.isArray(data)) { return this.data || []; }
    this.data = data;
    this.facetsController.applyData(data);
  };

  Graphic.prototype.build = function(el, width, height) {

    if (!_.isString(el)) { return this.el; }

    this.target = d3.select(el);

    this.width  = width  || parseInt(this.target.style('width'));
    this.height = height || parseInt(this.target.style('height'));

    this.el = d3.select(document.createElement('div'));
    this.el.append('svg').attr('width', this.width).attr('height', this.height).attr('class', 'graphic');

    this.facetsController.applyElement(this.el, this.width, this.height);

  };

  Graphic.prototype.render = function() { this.target.html(this.el.html()); };

  // ======
  // FACETS
  // ======

  var facetsDefaults = {
    flow: undefined,
    gridX: undefined,
    gridY: undefined
  };

  function Facet(data) {
    _.extend(this, data);
  }

  function FacetsController(opts) {
    _.extend(this, facetsDefaults, opts.facets);
    if (this.gridX || this.gridY) { _.extend(this, new GridFacetController()); }
    else { _.extend(this, new FlowFacetController()); }
    this.layersController = new LayersController(opts);
    this.facets = [];
    this.scale = { x: d3.scale.ordinal(), y: d3.scale.ordinal(), domain: [] };
  }

  function FlowFacetController() {

    this.applyData = function(data) {

      var that = this;

      var facets = d3.nest()
        .key(function(row) { return row[that.flow]; })
        .entries(data);

      facets.forEach(function(facet, index) {
        var facet = new Facet(facet);
        that.layersController.applyData(facet);
        that.scale.domain.push(index);
        that.facets.push(facet);
      });

    };

    this.setRangeX = function(width, height, ratio, numFacets, numCols) {
      var that = this;
      var xRange = this.scale.domain.map(function(index) {
        if (numFacets < ratio) { return index * (width/numFacets); }
        var colNum = index % ratio;
        return (colNum/numCols) * that.width;
      });
      this.scale.x.range(xRange);
    };

    this.setRangeY = function(width, height, ratio, numFacets, numRows) {
      var yRange = this.scale.domain.map(function(index) {
        var rowNum = Math.floor(index/ratio);
        return (rowNum/numRows) * height;
      });
      this.scale.y.range(yRange);
    };

  }

  FacetsController.prototype.applyElement = function(el, width, height) {

    var that = this;

    var numFacets = this.facets.length;
    var ratio     = width/height >= 1 ? Math.floor(width/height) : 1/Math.floor(height/width);
    var numRows   = ratio >= 1 ? Math.ceil(numFacets/ratio) : Math.ceil(ratio/numFacets);
    var numCols   = Math.ceil(numFacets/numRows);

    this.width  = width/numCols;
    this.height = height/numRows;

    this.setRangeX(width, height, ratio, numFacets, numCols);
    this.setRangeY(width, height, ratio, numFacets, numRows);

    this.el = el.select('svg');
    this.el.selectAll('g.facet')
      .data(this.facets)
      .enter()
      .append('g')
      .attr('class', 'facet')
      .attr('data-key', function(facet) { return facet.key; })
      .attr('transform', function(facet) {
        return 'translate(' + that.scale.x(facet.key) + ',' + that.scale.y(facet.key) + ')';
      })
      .each(function(facet, index) {
        that.layersController.applyElement(facet, this);
      });

  };

  // ======
  // LAYERS
  // ======

  var layerDefaults = {
    geometry: 'point',
    mapping: {}
  };

  function Layer(facet, opts) {
    _.extend(this, opts, facet);
  }

  function LayersController(opts) {
    opts.layers.forEach(function(layerOpts) { _.defaults(layerOpts, layerDefaults); });
    this.layersOptions = opts.layers;
    this.layers = [];
    this.GeometriesController = new GeometriesController(opts);
  }

  LayersController.prototype.applyData = function(facet) {
    var that = this;
    this.layersOptions.forEach(function(layerOpts) {
      var layer = new Layer(facet, layerOpts);
      that.GeometriesController.applyData(layer);
      that.layers.push(layer);
    });
  };

  LayersController.prototype.applyElement = function(facet, el) {
    var that = this;
    this.el = d3.select(el);
    this.el.selectAll('g.layer')
      .data(this.layers)
      .enter()
      .append('g')
      .attr('class', 'layer')
      .attr('data-geometry', function(layer) { return layer.geometry; })
      .each(function(layer) {
        that.GeometriesController.applyElement(layer, this);
      });
  };

  // ==========
  // GEOMETRIES
  // ==========

  var geometriesDefaults = {
    group: undefined
  };

  function Group(data) {
    _.extend(this, data);
  }

  function GeometriesController(opts) {
    _.extend(this, geometriesDefaults);
    this.groups = [];
  };

  GeometriesController.prototype.applyData = function(layer) {

    var that = this;
    var groups = d3.nest().key(function(row) { return row[that.group]; }).entries(layer.values);

    groups.forEach(function(data, index) {
      var group = new Group(data);
      that.groups.push(group);
    });

  };

  GeometriesController.prototype.applyElement = function(layer, el) {
    this.el = d3.select(el);
    this.el.selectAll('g.group')
      .data(this.groups)
      .enter()
      .append('g')
      .attr('class', 'group')
      .attr('data-group', function(group) { return group.key; });
  };

  // =============
  // EXPORT GLOBAL
  // =============

  // Export as Node module.
  if (isNode) {
    module.exports = Graphic;
  }

  // Export to global context.
  this.Graphic = Graphic;

})();<commit_msg>all components need access to the full dataset. correcting.<commit_after>
// Based on https://github.com/gigamonkey/gg

(function () {

  // ===================
  // NODE/BROWSER CONFIG
  // ===================

  var isNode = false;

  // If Node, create a fake DOM with jsdom and require dependencies.
  if (typeof module !== 'undefined' && module.exports) {

    isNode = true;

    document = require('jsdom').jsdom();
    window = document.parentWindow;

    this.d3 = require('d3');
    this._  = require('underscore');

  }

  if (!d3 || !_) { throw 'ggd3 requires D3 and Underscore.'; }

  // =======
  // GRAPHIC
  // =======

  // The Graphic constructor is the entry point to ggd3.
  // All arguments are optional.

  function Graphic(opts, data, el, width, height, renderNow) {
    if(opts)      { this.setup(opts); }
    if(data)      { this.data(data); }
    if(el)        { this.build(el, width, height); }
    if(renderNow) { this.render(); }
  }

  Graphic.prototype.setup = function(opts) {
    _.defaults(opts || {}, { facets: {}, layers: [] });
    this.geometriesController = new GeometriesController(opts);
    this.layersController = new LayersController(opts, this.geometriesController);
    this.facetsController = new FacetsController(opts, this.layersController);
  };

  Graphic.prototype.data = function(dataset) {
    if (!_.isArray(dataset)) { return this.dataset || []; }
    this.dataset = dataset;
    this.facetsController.train(dataset);
    this.layersController.train(dataset);
    this.geometriesController.train(dataset);
    this.facetsController.nest(dataset);
  };

  Graphic.prototype.build = function(el, width, height) {

    if (!_.isString(el)) { return this.el; }

    this.target = d3.select(el);

    this.width  = width  || parseInt(this.target.style('width'));
    this.height = height || parseInt(this.target.style('height'));

    this.el = d3.select(document.createElement('div'));
    this.el.append('svg').attr('width', this.width).attr('height', this.height).attr('class', 'graphic');

    this.facetsController.applyElement(this.el, this.width, this.height);

  };

  Graphic.prototype.render = function() { this.target.html(this.el.html()); };

  // ======
  // FACETS
  // ======

  var facetsDefaults = {
    flow: undefined,
    gridX: undefined,
    gridY: undefined
  };

  function Facet(data) {
    _.extend(this, data);
  }

  function FacetsController(opts, layersController) {
    _.extend(this, facetsDefaults, opts.facets);
    if (this.gridX || this.gridY) { _.extend(this, new GridFacetController()); }
    else { _.extend(this, new FlowFacetController()); }
    this.layersController = layersController;
    this.scale = { x: d3.scale.ordinal(), y: d3.scale.ordinal(), domain: [] };
    this.facets = [];
  }

  function FlowFacetController() {

    this.train = function(dataset) {
      var that = this;
      this.scale.domain = d3.set(dataset.map(function(row) { return row[that.flow]; })).values();
    };

    this.nest = function(dataset) {

      var that = this;

      var facets = d3.nest()
        .key(function(row) { return row[that.flow]; })
        .entries(dataset);

      facets.forEach(function(facet, index) {
        var facet = new Facet(facet);
        that.layersController.applyData(facet);
        that.facets.push(facet);
      });

    };

    this.setRangeX = function(width, height, ratio, numFacets, numCols) {
      var that = this;
      var xRange = this.scale.domain.map(function(key, index) {
        if (numFacets < ratio) { return index * (width/numFacets); }
        var colNum = index % ratio;
        return (colNum/numCols) * that.width;
      });
      this.scale.x.range(xRange);
    };

    this.setRangeY = function(width, height, ratio, numFacets, numRows) {
      var yRange = this.scale.domain.map(function(key, index) {
        var rowNum = Math.floor(index/ratio);
        return (rowNum/numRows) * height;
      });
      this.scale.y.range(yRange);
    };

  }

  FacetsController.prototype.applyElement = function(el, width, height) {

    var that = this;

    var numFacets = this.facets.length;
    var ratio     = width/height >= 1 ? Math.floor(width/height) : 1/Math.floor(height/width);
    var numRows   = ratio >= 1 ? Math.ceil(numFacets/ratio) : Math.ceil(ratio/numFacets);
    var numCols   = Math.ceil(numFacets/numRows);

    this.width  = width/numCols;
    this.height = height/numRows;

    this.setRangeX(width, height, ratio, numFacets, numCols);
    this.setRangeY(width, height, ratio, numFacets, numRows);

    this.el = el.select('svg');
    this.el.selectAll('g.facet')
      .data(this.facets)
      .enter()
      .append('g')
      .attr('class', 'facet')
      .attr('data-key', function(facet) { return facet.key; })
      .attr('transform', function(facet) {
        return 'translate(' + that.scale.x(facet.key) + ',' + that.scale.y(facet.key) + ')';
      })
      .each(function(facet, index) {
        that.layersController.applyElement(facet, this);
      });

  };

  // ======
  // LAYERS
  // ======

  var layerDefaults = {
    geometry: 'point',
    mapping: {}
  };

  function Layer(facet, opts) {
    _.extend(this, opts, facet);
  }

  function LayersController(opts, geometriesController) {
    opts.layers.forEach(function(layerOpts) { _.defaults(layerOpts, layerDefaults); });
    this.layersOptions = opts.layers;
    this.layers = [];
    this.geometriesController = geometriesController;
  }

  LayersController.prototype.train = function(dataset) {};

  LayersController.prototype.applyData = function(facet) {
    var that = this;
    this.layersOptions.forEach(function(layerOpts) {
      var layer = new Layer(facet, layerOpts);
      that.geometriesController.applyData(layer);
      that.layers.push(layer);
    });
  };

  LayersController.prototype.applyElement = function(facet, el) {
    var that = this;
    this.el = d3.select(el);
    this.el.selectAll('g.layer')
      .data(this.layers)
      .enter()
      .append('g')
      .attr('class', 'layer')
      .attr('data-geometry', function(layer) { return layer.geometry; })
      .each(function(layer) {
        that.geometriesController.applyElement(layer, this);
      });
  };

  // ==========
  // GEOMETRIES
  // ==========

  var geometriesDefaults = {
    group: undefined
  };

  function Group(data) {
    _.extend(this, data);
  }

  function GeometriesController(opts) {
    _.extend(this, geometriesDefaults);
    this.groups = [];
  };

  GeometriesController.prototype.train = function(dataset) {};

  GeometriesController.prototype.applyData = function(layer) {

    var that = this;
    var groups = d3.nest().key(function(row) { return row[that.group]; }).entries(layer.values);

    groups.forEach(function(data, index) {
      var group = new Group(data);
      that.groups.push(group);
    });

  };

  GeometriesController.prototype.applyElement = function(layer, el) {
    this.el = d3.select(el);
    this.el.selectAll('g.group')
      .data(this.groups)
      .enter()
      .append('g')
      .attr('class', 'group')
      .attr('data-group', function(group) { return group.key; });
  };

  // =============
  // EXPORT GLOBAL
  // =============

  // Export as Node module.
  if (isNode) {
    module.exports = Graphic;
  }

  // Export to global context.
  this.Graphic = Graphic;

})();<|endoftext|>


<commit_before>var pkg = require('./package');
require('./')();

module.exports = (function(){
	// shortcut
	var col = console.col;

	// title
	console
		.spacer()
		._(pkg.name, col('─ v'+pkg.version, 'grey'))
		._('---')
		._(col(pkg.repository.url, 'grey'))
		.spacer();

	// desc
	console
		._('Description', 'bold')
		._('---')
		._(pkg.description)
		.spacer();

	// install
	console
		._('Installation', 'white')
		.title('npm install --save console2')
		.spacer();

	// reference
	var ref = console
		._('Reference', 'white')
		._('Open README.md for complete reference')
		._()
		.box();

	ref.over();

	// reference
	var lineArgs = '['+col('line', 'white')+'], ['+console.col('option', 'white')+']';
	var docs = {
		beep: ['Beep noise, outputs "BEEP"', '['+console.col('title', 'white')+']'],
		box: ['Create a sub box', lineArgs],
		build: 'Returns current stack as Promise(string)',
		col: ['Colorize a string', col('input', 'white')+', {…'+col('color', 'white')+'}'],
		dir: '~log',
		error: ['Displays text in '+col('red','red'), lineArgs],
		flush: '~out',
		getParent: ['Return a specific parent box', '['+col('generations', 'white')+'=1]'],
		help: 'Display these information',
		info: ['Displays text in '+col('green','green'), lineArgs],
		line: ['Add a new line', lineArgs],
		log: ['Alias for .line AND .out', lineArgs],
		options: ['Set option/s', col('object', 'white')],
		out: ['Print current stack', lineArgs],
		over: ['Mark box printable for out()', lineArgs],
		pad: ['Pad a string', col('string', 'white')+', '+col('length', 'white')+', ['+col('string', 'white')+']'],
		spacer: 'Add empty line',
		strip: ['Remove colors from a string', col('string', 'white')],
		time: ['Display timer', '['+col('timerName', 'white')+'], ['+col('reset', 'white')+']'],
		timeEnd: '~time',
		title: ['Display text inside a box', lineArgs],
		trace: ['Beautified console.trace', '['+col('message')+']'],
		warn: ['Displays text in '+col('yellow','yellow'), lineArgs]
	};

	// insert docs
	Object.keys(console).sort().forEach(function(key){
		if(key.substr(0,1) === '_'
			|| ['Console','assert','overrideConsole'].indexOf(key) > -1
			|| typeof console[key] !== 'function') return;
		var doc = docs[key];
		var line = col(key, 'cyan')
			+ '('+(Array.isArray(doc) ? doc[1] : '')+')';

		if(!doc) return;

		// alias
		if(typeof doc === 'string' && doc.substr(0,1) === '~')
			doc = 'Alias for '+doc.substr(1);

		// add desc
		line += console.pad(' ', 35 - console.strip(line).length)
		+ ' - '
		+ (Array.isArray(doc) ? doc[0] : doc||'');

		ref._(line);
	});

	/**
	 * Example 1
	 */
	var example1 = function(){
		console.line('New Line');

		var red = console.box('Red Box Title', 'red');
		red.line('Red Box Line').over();

		var yellow = red
			.box('Yellow Box Title', {over:true,color:'yellow',colorText:'yellow',border:2})
			.line('Yellow Box Line');
		var green = yellow.box({color:'green'}).over().line('Hello World');

		red.line('Red Box Bottom');
	};

	// example
	console.spacer().title('Example 1: Box tree', 'bold');
	console.line(example1).line();

	example1();

	/**
	 * Example 2
	 */
	var example2 = function(){
		console.line({user:'RienNeVaPlus',id:123,attr:{items:2432,top:[1,2],note:null},online:true});
	};

	// example
	console.spacer().title('Example 2: Object inspection', 'bold');
	console.line(example2).line();

	example2();

	/**
	 * Example 3
	 */
	var example3 = function(){
		console.time('CustomTimer');    // create new timer
		console.time();                 // global timer
		console.time('CustomTimer');    // output created timer
	};

	// example
	console.spacer().title('Example 3: Stopwatch', 'bold');
	console.line(example3).line();

	example3();

	/**
	 * Example 4
	 */
	var example4 = function(){
		console.trace();
	};

	// example
	console.spacer().title('Example 4: Stack trace', 'bold');
	console.line(example4).line();

	example4();

	console.spacer().title(console.col('Have fun!', 'rainbow'));
	console.out();
})();<commit_msg>Fixed help<commit_after>var pkg = require('./package');
require('./')();

module.exports = (function(){
	// shortcut
	var col = console.col;

	// title
	console
		.spacer()
		._(pkg.name, col('─ v'+pkg.version, 'grey'))
		._('---')
		._(col(pkg.repository.url, 'grey'))
		.spacer();

	// desc
	console
		._('Description', 'bold')
		._('---')
		._(pkg.description)
		.spacer();

	// install
	console
		._('Installation', 'white')
		.line('npm install --save console2')
		.spacer();

	// reference
	var ref = console
		._('Reference', 'white')
		._('Open README.md for complete reference')
		._()
		.box();

	ref.over();

	// reference
	var lineArgs = '['+col('line', 'white')+'], ['+console.col('option', 'white')+']';
	var docs = {
		beep: ['Beep noise, outputs "BEEP"', '['+console.col('title', 'white')+']'],
		box: ['Create a sub box', lineArgs],
		build: 'Returns current stack as Promise(string)',
		col: ['Colorize a string', col('input', 'white')+', {…'+col('color', 'white')+'}'],
		dir: '~log',
		error: ['Displays text in '+col('red','red'), lineArgs],
		flush: '~out',
		getParent: ['Return a specific parent box', '['+col('generations', 'white')+'=1]'],
		help: 'Display these information',
		info: ['Displays text in '+col('green','green'), lineArgs],
		line: ['Add a new line', lineArgs],
		log: ['Alias for .line AND .out', lineArgs],
		options: ['Set option/s', col('object', 'white')],
		out: ['Print current stack', lineArgs],
		over: ['Mark box printable for out()', lineArgs],
		pad: ['Pad a string', col('string', 'white')+', '+col('length', 'white')+', ['+col('string', 'white')+']'],
		spacer: 'Add empty line',
		strip: ['Remove colors from a string', col('string', 'white')],
		time: ['Display timer', '['+col('timerName', 'white')+'], ['+col('reset', 'white')+']'],
		timeEnd: '~time',
		title: ['Display text inside a box', lineArgs],
		trace: ['Beautified console.trace', '['+col('message')+']'],
		warn: ['Displays text in '+col('yellow','yellow'), lineArgs]
	};

	// insert docs
	Object.keys(console).sort().forEach(function(key){
		if(key.substr(0,1) === '_'
			|| ['Console','assert','overrideConsole'].indexOf(key) > -1
			|| typeof console[key] !== 'function') return;
		var doc = docs[key];
		var line = col(key, 'cyan')
			+ '('+(Array.isArray(doc) ? doc[1] : '')+')';

		if(!doc) return;

		// alias
		if(typeof doc === 'string' && doc.substr(0,1) === '~')
			doc = 'Alias for '+doc.substr(1);

		// add desc
		line += console.pad(' ', 35 - console.strip(line).length)
		+ ' - '
		+ (Array.isArray(doc) ? doc[0] : doc||'');

		ref._(line);
	});

	/**
	 * Example 1
	 */
	var example1 = function(){
		console.line('New Line');

		var red = console.box('Red Box Title', 'red');
		red.line('Red Box Line').over();

		var yellow = red
			.box('Yellow Box Title', {over:true,color:'yellow',colorText:'yellow',border:2})
			.line('Yellow Box Line');
		var green = yellow.box({color:'green'}).over().line('Hello World');

		red.line('Red Box Bottom');
	};

	// example
	console.spacer().title('\nExample 1: Box tree', 'bold');
	console.line(example1).line();

	example1();

	/**
	 * Example 2
	 */
	var example2 = function(){
		console.line({user:'RienNeVaPlus',id:123,attr:{items:2432,top:[1,2],note:null},online:true});
	};

	// example
	console.spacer().title('\nExample 2: Object inspection', 'bold');
	console.line(example2).line();

	example2();

	/**
	 * Example 3
	 */
	var example3 = function(){
		console.time('CustomTimer');    // create new timer
		console.time();                 // global timer
		console.time('CustomTimer');    // output created timer
	};

	// example
	console.spacer().title('\nExample 3: Stopwatch', 'bold');
	console.line(example3).line();

	example3();

	/**
	 * Example 4
	 */
	var example4 = function(){
		console.trace();
	};

	// example
	console.spacer().title('\nExample 4: Stack trace', 'bold');
	console.line(example4).line();

	example4();

	console.spacer().title(console.col('Have fun!', 'rainbow'));
	console.out();
})();<|endoftext|>


<commit_before>/**
 * @author  John Resig <jeresig@gmail.com>
 * @author  Originally by Marcus Spiegel <marcus.spiegel@gmail.com>
 * @link    https://github.com/jeresig/i18n-node
 * @license http://opensource.org/licenses/MIT
 *
 * @version 0.4.6
 */

// dependencies
var vsprintf = require("sprintf").vsprintf,
		fs = require("fs"),
		path = require("path");

function dotNotation (obj, str) {
    return str.split(".").reduce(function(o, x) { return o[x]; }, obj);
}

var i18n = module.exports = function (opt) {
	var self = this;

	// Put into dev or production mode
	this.devMode = process.env.NODE_ENV !== "production";

	// Copy over options
	for (var prop in opt) {
		this[prop] = opt[prop];
	}

	// you may register helpers in global scope, up to you
	if (typeof this.register === "object") {
		i18n.resMethods.forEach(function (method) {
			self.register[method] = self[method].bind(self);
		});
	}

	// implicitly read all locales
	// if it's an array of locale names, read in the data
	if (opt.locales && opt.locales.forEach) {
		this.locales = {};

		opt.locales.forEach(function (locale) {
			self.readFile(locale);
		});

		this.defaultLocale = opt.locales[0];
	}

	// Set the locale to the default locale
	this.setLocale(this.defaultLocale);

	// Check the defaultLocale
	if (!this.locales[this.defaultLocale]) {
		console.error("Not a valid default locale.");
	}

	if (this.request) {
		if (this.subdomain) {
			this.setLocaleFromSubdomain(this.request);
		}

		if (this.query !== false) {
			this.setLocaleFromQuery(this.request);
		}

		this.prefLocale = this.preferredLocale();

+		if (this.prefLocale !== false && this.prefLocale !== this.locale) {
+			this.setLocale(this.prefLocale);
+		}
	}
};

i18n.version = "0.4.6";

i18n.localeCache = {};
i18n.resMethods = ["__", "__n", "getLocale", "isPreferredLocale"];

i18n.expressBind = function (app, opt) {
	if (!app) {
		return;
	}

	app.use(function (req, res, next) {
		opt.request = req;
		req.i18n = new i18n(opt);

		// Express 3
		if (res.locals) {
			i18n.registerMethods(res.locals, req)
		}

		next();
	});

	// Express 2
	if (app.dynamicHelpers) {
		app.dynamicHelpers(i18n.registerMethods({}));
	}
};

i18n.registerMethods = function (helpers, req) {
	i18n.resMethods.forEach(function (method) {
		if (req) {
			helpers[method] = req.i18n[method].bind(req.i18n);
		} else {
			helpers[method] = function (req) {
				return req.i18n[method].bind(req.i18n);
			};
		}

	});

	return helpers;
};

i18n.prototype = {
	defaultLocale: "en",
	extension: ".js",
	directory: "./locales",
	cookieName: "lang",

	__: function () {
		var msg = this.translate(this.locale, arguments[0]);

		if (arguments.length > 1) {
			msg = vsprintf(msg, Array.prototype.slice.call(arguments, 1));
		}

		return msg;
	},

	__n: function (singular, plural, count) {
		var msg = this.translate(this.locale, singular, plural);

		msg = vsprintf(parseInt(count, 10) > 1 ? msg.other : msg.one, [count]);

		if (arguments.length > 3) {
			msg = vsprintf(msg, Array.prototype.slice.call(arguments, 3));
		}

		return msg;
	},

	setLocale: function (locale) {

		if (!locale) return;

		if (!this.locales[locale]) {
			if (this.devMode) {
				console.warn("Locale (" + locale + ") not found.");
			}

			locale = this.defaultLocale;
		}

		return (this.locale = locale);
	},

	getLocale: function () {
		return this.locale;
	},

	isPreferredLocale: function () {
		return !this.prefLocale ||
				this.prefLocale === this.getLocale();
	},

	setLocaleFromSessionVar: function (req) {
		req = req || this.request;

		var locale = req.session.locale;

		if (this.locales[locale]) {
			if (this.devMode) {
				console.log("Overriding locale from query: " + locale);
			}
			this.setLocale(locale);
		}

	},

	setLocaleFromQuery: function (req) {
		req = req || this.request;

		if (!req || !req.query || !req.query.lang) {
			return;
		}

		var locale = req.query.lang.toLowerCase();

		if (this.locales[locale]) {
			if (this.devMode) {
				console.log("Overriding locale from query: " + locale);
			}

			this.setLocale(locale);
		}
	},

	setLocaleFromSubdomain: function (req) {
		req = req || this.request;

		if (!req || !req.headers || !req.headers.host) {
			return;
		}

		if (/^([^.]+)/.test(req.headers.host) && this.locales[RegExp.$1]) {
			if (this.devMode) {
				console.log("Overriding locale from host: " + RegExp.$1);
			}

			this.setLocale(RegExp.$1);
		}
	},

	setLocaleFromCookie: function (req) {
		req = req || this.request;

		if (!req || !req.cookies || !this.cookieName || !req.cookies[this.cookieName]) {
			return;
		}

		var locale = req.cookies[this.cookieName].toLowerCase();

		if (this.locales[locale]) {
			if (this.devMode) {
				console.log("Overriding locale from cookie: " + locale);
			}

			this.setLocale(locale);
		}
	},

	preferredLocale: function (req) {
		req = req || this.request;

		if (!req || !req.headers) {
			return;
		}

		var accept = req.headers["accept-language"] || "",
				regExp = /(^|,\s*)([a-z0-9-]+)/gi,
				self = this,
				prefLocale;

		while (!prefLocale && (match = regExp.exec(accept))) {
			var locale = match[2].toLowerCase();
			var parts = locale.split("-");

			if (self.locales[locale]) {
				prefLocale = locale;
			} else if (parts.length > 1 && self.locales[parts[0]]) {
              	prefLocale = parts[0];
            }
		}

		return prefLocale || this.defaultLocale;
	},

	// read locale file, translate a msg and write to fs if new
	translate: function (locale, singular, plural) {
		if (!locale || !this.locales[locale]) {
			if (this.devMode) {
				console.warn("WARN: No locale found. Using the default (" +
						this.defaultLocale + ") as current locale");
			}

			locale = this.defaultLocale;

			this.initLocale(locale, {});
		}

		if (!this.locales[locale][singular]) {
			this.locales[locale][singular] = plural ?
			{ one: singular, other: plural } :
					singular;

			if (this.devMode) {
				this.writeFile(locale);
			}
		}

		return dotNotation(singular, this.locales[locale]);
	},

	// try reading a file
	readFile: function (locale) {
		var file = this.locateFile(locale);

		if (!this.devMode && i18n.localeCache[file]) {
			this.initLocale(locale, i18n.localeCache[file]);
			return;
		}

		try {
			var localeFile = fs.readFileSync(file);

			try {
				// parsing filecontents to locales[locale]
				this.initLocale(locale, JSON.parse(localeFile));

			} catch (e) {
				console.error('unable to parse locales from file (maybe ' + file +
						' is empty or invalid json?): ', e);
			}

		} catch (e) {
			// unable to read, so intialize that file
			// locales[locale] are already set in memory, so no extra read required
			// or locales[locale] are empty, which initializes an empty locale.json file
			this.writeFile(locale);
		}
	},

	// try writing a file in a created directory
	writeFile: function (locale) {
		// don't write new locale information to disk if we're not in dev mode
		if (!this.devMode) {
			// Initialize the locale if didn't exist already
			this.initLocale(locale, {});
		}

		// creating directory if necessary
		try {
			fs.lstatSync(this.directory);

		} catch (e) {
			if (this.devMode) {
				console.log('creating locales dir in: ' + this.directory);
			}

			fs.mkdirSync(this.directory, 0755);
		}

		// Initialize the locale if didn't exist already
		this.initLocale(locale, {});

		// writing to tmp and rename on success
		try {
			var target = this.locateFile(locale),
					tmp = target + ".tmp";

			fs.writeFileSync(tmp, JSON.stringify(
					this.locales[locale], null, "\t"), "utf8");

			if (fs.statSync(tmp).isFile()) {
				fs.renameSync(tmp, target);

			} else {
				console.error('unable to write locales to file (either ' + tmp +
						' or ' + target + ' are not writeable?): ');
			}

		} catch (e) {
			console.error('unexpected error writing files (either ' + tmp +
					' or ' + target + ' are not writeable?): ', e);
		}
	},

	// basic normalization of filepath
	locateFile: function (locale) {
		return path.normalize(this.directory + '/' + locale + this.extension);
	},

	initLocale: function (locale, data) {
		if (!this.locales[locale]) {
			this.locales[locale] = data;

			// Only cache the files when we're not in dev mode
			if (!this.devMode) {
				var file = this.locateFile(locale);
				if (!i18n.localeCache[file]) {
					i18n.localeCache[file] = data;
				}
			}
		}
	}
};
<commit_msg>Updated i18n.js<commit_after>/**
 * @author  John Resig <jeresig@gmail.com>
 * @author  Originally by Marcus Spiegel <marcus.spiegel@gmail.com>
 * @link    https://github.com/jeresig/i18n-node
 * @license http://opensource.org/licenses/MIT
 *
 * @version 0.4.6
 */

// dependencies
var vsprintf = require("sprintf").vsprintf,
		fs = require("fs"),
		path = require("path");

function dotNotation (obj, str) {
    return str.split(".").reduce(function(o, x) { return o[x]; }, obj);
}

var i18n = module.exports = function (opt) {
	var self = this;

	// Put into dev or production mode
	this.devMode = process.env.NODE_ENV !== "production";

	// Copy over options
	for (var prop in opt) {
		this[prop] = opt[prop];
	}

	// you may register helpers in global scope, up to you
	if (typeof this.register === "object") {
		i18n.resMethods.forEach(function (method) {
			self.register[method] = self[method].bind(self);
		});
	}

	// implicitly read all locales
	// if it's an array of locale names, read in the data
	if (opt.locales && opt.locales.forEach) {
		this.locales = {};

		opt.locales.forEach(function (locale) {
			self.readFile(locale);
		});

		this.defaultLocale = opt.locales[0];
	}

	// Set the locale to the default locale
	this.setLocale(this.defaultLocale);

	// Check the defaultLocale
	if (!this.locales[this.defaultLocale]) {
		console.error("Not a valid default locale.");
	}

	if (this.request) {
		if (this.subdomain) {
			this.setLocaleFromSubdomain(this.request);
		}

		if (this.query !== false) {
			this.setLocaleFromQuery(this.request);
		}

		this.prefLocale = this.preferredLocale();

		if (this.prefLocale !== false && this.prefLocale !== this.locale) {
			this.setLocale(this.prefLocale);
		}
	}
};

i18n.version = "0.4.6";

i18n.localeCache = {};
i18n.resMethods = ["__", "__n", "getLocale", "isPreferredLocale"];

i18n.expressBind = function (app, opt) {
	if (!app) {
		return;
	}

	app.use(function (req, res, next) {
		opt.request = req;
		req.i18n = new i18n(opt);

		// Express 3
		if (res.locals) {
			i18n.registerMethods(res.locals, req)
		}

		next();
	});

	// Express 2
	if (app.dynamicHelpers) {
		app.dynamicHelpers(i18n.registerMethods({}));
	}
};

i18n.registerMethods = function (helpers, req) {
	i18n.resMethods.forEach(function (method) {
		if (req) {
			helpers[method] = req.i18n[method].bind(req.i18n);
		} else {
			helpers[method] = function (req) {
				return req.i18n[method].bind(req.i18n);
			};
		}

	});

	return helpers;
};

i18n.prototype = {
	defaultLocale: "en",
	extension: ".js",
	directory: "./locales",
	cookieName: "lang",

	__: function () {
		var msg = this.translate(this.locale, arguments[0]);

		if (arguments.length > 1) {
			msg = vsprintf(msg, Array.prototype.slice.call(arguments, 1));
		}

		return msg;
	},

	__n: function (singular, plural, count) {
		var msg = this.translate(this.locale, singular, plural);

		msg = vsprintf(parseInt(count, 10) > 1 ? msg.other : msg.one, [count]);

		if (arguments.length > 3) {
			msg = vsprintf(msg, Array.prototype.slice.call(arguments, 3));
		}

		return msg;
	},

	setLocale: function (locale) {

		if (!locale) return;

		if (!this.locales[locale]) {
			if (this.devMode) {
				console.warn("Locale (" + locale + ") not found.");
			}

			locale = this.defaultLocale;
		}

		return (this.locale = locale);
	},

	getLocale: function () {
		return this.locale;
	},

	isPreferredLocale: function () {
		return !this.prefLocale ||
				this.prefLocale === this.getLocale();
	},

	setLocaleFromSessionVar: function (req) {
		req = req || this.request;

		var locale = req.session.locale;

		if (this.locales[locale]) {
			if (this.devMode) {
				console.log("Overriding locale from query: " + locale);
			}
			this.setLocale(locale);
		}

	},

	setLocaleFromQuery: function (req) {
		req = req || this.request;

		if (!req || !req.query || !req.query.lang) {
			return;
		}

		var locale = req.query.lang.toLowerCase();

		if (this.locales[locale]) {
			if (this.devMode) {
				console.log("Overriding locale from query: " + locale);
			}

			this.setLocale(locale);
		}
	},

	setLocaleFromSubdomain: function (req) {
		req = req || this.request;

		if (!req || !req.headers || !req.headers.host) {
			return;
		}

		if (/^([^.]+)/.test(req.headers.host) && this.locales[RegExp.$1]) {
			if (this.devMode) {
				console.log("Overriding locale from host: " + RegExp.$1);
			}

			this.setLocale(RegExp.$1);
		}
	},

	setLocaleFromCookie: function (req) {
		req = req || this.request;

		if (!req || !req.cookies || !this.cookieName || !req.cookies[this.cookieName]) {
			return;
		}

		var locale = req.cookies[this.cookieName].toLowerCase();

		if (this.locales[locale]) {
			if (this.devMode) {
				console.log("Overriding locale from cookie: " + locale);
			}

			this.setLocale(locale);
		}
	},

	preferredLocale: function (req) {
		req = req || this.request;

		if (!req || !req.headers) {
			return;
		}

		var accept = req.headers["accept-language"] || "",
				regExp = /(^|,\s*)([a-z0-9-]+)/gi,
				self = this,
				prefLocale;

		while (!prefLocale && (match = regExp.exec(accept))) {
			var locale = match[2].toLowerCase();
			var parts = locale.split("-");

			if (self.locales[locale]) {
				prefLocale = locale;
			} else if (parts.length > 1 && self.locales[parts[0]]) {
              	prefLocale = parts[0];
            }
		}

		return prefLocale || this.defaultLocale;
	},

	// read locale file, translate a msg and write to fs if new
	translate: function (locale, singular, plural) {
		if (!locale || !this.locales[locale]) {
			if (this.devMode) {
				console.warn("WARN: No locale found. Using the default (" +
						this.defaultLocale + ") as current locale");
			}

			locale = this.defaultLocale;

			this.initLocale(locale, {});
		}

		if (!this.locales[locale][singular]) {
			this.locales[locale][singular] = plural ?
			{ one: singular, other: plural } :
					singular;

			if (this.devMode) {
				this.writeFile(locale);
			}
		}

		return dotNotation(singular, this.locales[locale]);
	},

	// try reading a file
	readFile: function (locale) {
		var file = this.locateFile(locale);

		if (!this.devMode && i18n.localeCache[file]) {
			this.initLocale(locale, i18n.localeCache[file]);
			return;
		}

		try {
			var localeFile = fs.readFileSync(file);

			try {
				// parsing filecontents to locales[locale]
				this.initLocale(locale, JSON.parse(localeFile));

			} catch (e) {
				console.error('unable to parse locales from file (maybe ' + file +
						' is empty or invalid json?): ', e);
			}

		} catch (e) {
			// unable to read, so intialize that file
			// locales[locale] are already set in memory, so no extra read required
			// or locales[locale] are empty, which initializes an empty locale.json file
			this.writeFile(locale);
		}
	},

	// try writing a file in a created directory
	writeFile: function (locale) {
		// don't write new locale information to disk if we're not in dev mode
		if (!this.devMode) {
			// Initialize the locale if didn't exist already
			this.initLocale(locale, {});
		}

		// creating directory if necessary
		try {
			fs.lstatSync(this.directory);

		} catch (e) {
			if (this.devMode) {
				console.log('creating locales dir in: ' + this.directory);
			}

			fs.mkdirSync(this.directory, 0755);
		}

		// Initialize the locale if didn't exist already
		this.initLocale(locale, {});

		// writing to tmp and rename on success
		try {
			var target = this.locateFile(locale),
					tmp = target + ".tmp";

			fs.writeFileSync(tmp, JSON.stringify(
					this.locales[locale], null, "\t"), "utf8");

			if (fs.statSync(tmp).isFile()) {
				fs.renameSync(tmp, target);

			} else {
				console.error('unable to write locales to file (either ' + tmp +
						' or ' + target + ' are not writeable?): ');
			}

		} catch (e) {
			console.error('unexpected error writing files (either ' + tmp +
					' or ' + target + ' are not writeable?): ', e);
		}
	},

	// basic normalization of filepath
	locateFile: function (locale) {
		return path.normalize(this.directory + '/' + locale + this.extension);
	},

	initLocale: function (locale, data) {
		if (!this.locales[locale]) {
			this.locales[locale] = data;

			// Only cache the files when we're not in dev mode
			if (!this.devMode) {
				var file = this.locateFile(locale);
				if (!i18n.localeCache[file]) {
					i18n.localeCache[file] = data;
				}
			}
		}
	}
};
<|endoftext|>