<commit_before>
//Create a function which given two minimum and maximum numbers returns a random number
function randCalc(minMaxArray){
  return Math.floor((Math.random() * (minMaxArray[1] - minMaxArray[0] + 1)) + minMaxArray[0]);
}

//Call randCalc function and return an array with pizza, deliveries and drivers information
function hourStats(pizzaArray, deliveryArray){
  var pizzas = randCalc(pizzaArray); //4
  var deliveries = randCalc(deliveryArray); //2
  if (pizzas < deliveries){
    deliveries = pizzas;
    var drivers = Math.ceil(deliveries / 3);
  }
  else {
    var drivers = Math.ceil(deliveries / 3);
  }
  var output = [pizzas, deliveries, drivers];
  return output;
}

//Store pizza minimums and maximums in object
var dPizzas = {
  t8_11am: [0,4],
  t11_2am: [0,7],
  t2_5pm: [2,15],
  t5_8pm: [15,35],
  t8_11pm: [12,31],
  t11_2pm: [5,20]
};

//Store delivery minimums and maximums in object
var dDeliveries = {
  t8_11am: [0,4],
  t11_2am: [0,4],
  t2_5pm: [1,4],
  t5_8pm: [3,8],
  t8_11pm: [5,12],
  t11_2pm: [6,11]
};

function Location(name){
  this.name = name;
  this.t8am = hourStats(dPizzas.t8_11am,dDeliveries.t8_11am);
}

console.log(hourStats(dPizzas.t8_11pm,dDeliveries.t8_11pm));
//Create each location object using literal notation
// var hillsboro = {
//   t8am: randCalc(mktAnalysis.t8_11am),
//   t9am: randCalc(mktAnalysis.t8_11am),
//   t10am: randCalc(mktAnalysis.t8_11am),
//
//   t11am: randCalc(mktAnalysis.t11_2am),
//   t12pm: randCalc(mktAnalysis.t11_2am),
//   t1pm: randCalc(mktAnalysis.t11_2am),
//
//   t2pm: randCalc(mktAnalysis.t2_5pm),
//   t3pm: randCalc(mktAnalysis.t2_5pm),
//   t4pm: randCalc(mktAnalysis.t2_5pm),
//
//   t5pm: randCalc(mktAnalysis.t5_8pm),
//   t6pm: randCalc(mktAnalysis.t5_8pm),
//   t7pm: randCalc(mktAnalysis.t5_8pm),
//
//   t8pm: randCalc(mktAnalysis.t8_11pm),
//   t9pm: randCalc(mktAnalysis.t8_11pm),
//   t10pm: randCalc(mktAnalysis.t8_11pm),
//
//   t11pm: randCalc(mktAnalysis.t11_2pm),
//   t12am: randCalc(mktAnalysis.t11_2pm),
//   t1am: randCalc(mktAnalysis.t11_2pm)
//   // t8_11: [0,4],
//   // t11_2: [0,7],
//   // t2_5: [2,15],
//   // t5_8: [15,35],
//   // t8_11: [12,31],
//   // t11_2: [5,20]
//   // genRandom: function() {
// };
<commit_msg>Added function to create objects iteratively<commit_after>
//Create a function which given two minimum and maximum numbers returns a random number
function randCalc(minMaxArray){
  return Math.floor((Math.random() * (minMaxArray[1] - minMaxArray[0] + 1)) + minMaxArray[0]);
}

//Call randCalc function and return an array with pizza, deliveries and drivers information
function hourStats(pizzaArray, deliveryArray){
  var pizzas = randCalc(pizzaArray); //4
  var deliveries = randCalc(deliveryArray); //2
  if (pizzas < deliveries){
    deliveries = pizzas;
    var drivers = Math.ceil(deliveries / 3);
  }
  else {
    var drivers = Math.ceil(deliveries / 3);
  }
  var output = [pizzas, deliveries, drivers];
  return output;
}

//Store pizza minimums and maximums in object
var dPizzas = {
  t8_11: [0,4],
  t11_14: [0,7],
  t14_17: [2,15],
  t17_20: [15,35],
  t20_23: [12,31],
  t23_2: [5,20]
};

//Store delivery minimums and maximums in object
var dDeliveries = {
  t8_11: [0,4],
  t11_14: [0,4],
  t14_17: [1,4],
  t17_20: [3,8],
  t20_23: [5,12],
  t23_2: [6,11]
};

var hours = [['t8', 't9', 't10'], ['t11', 't12', 't13'], ['t14', 't15', 't16'], ['t17', 't18', 't19'], ['t20', 't21', 't22'], ['t23', 't0', 't1']];

function Location(name){
  this.name = name;
  this.shop = {};
  for (i = 0; i < hours.length; i++){
    if (hours[i][0] === 't8'){
      for (j = 0; j < 3; j++){
        this.shop[hours[i][j]] = hourStats(dPizzas.t8_11,dDeliveries.t8_11);
      }
    }
    else if (hours[i][0] === 't11'){
      for (j = 0; j < 3; j++){
        this.shop[hours[i][j]] = hourStats(dPizzas.t11_14,dDeliveries.t11_14);
      }
    }
    else if (hours[i][0] === 't14'){
      for (j = 0; j < 3; j++){
        this.shop[hours[i][j]] = hourStats(dPizzas.t14_17,dDeliveries.t14_17);
      }
    }
    else if (hours[i][0] === 't17'){
      for (j = 0; j < 3; j++){
        this.shop[hours[i][j]] = hourStats(dPizzas.t17_20,dDeliveries.t17_20);
      }
    }
    else if (hours[i][0] === 't20'){
      for (j = 0; j < 3; j++){
        this.shop[hours[i][j]] = hourStats(dPizzas.t20_23,dDeliveries.t20_23);
      }
    }
    else if (hours[i][0] === 't23'){
      for (j = 0; j < 3; j++){
        this.shop[hours[i][j]] = hourStats(dPizzas.t23_2,dDeliveries.t23_2);
      }
    }
    else {
      console.log('ERROR');
    }
  };
};

var hillsboro = new Location('Hillsboro');

console.table(hillsboro);
//Create each location object using literal notation
// var hillsboro = {
//   t8am: randCalc(mktAnalysis.t8_11am),
//   t9am: randCalc(mktAnalysis.t8_11am),
//   t10am: randCalc(mktAnalysis.t8_11am),
//
//   t11am: randCalc(mktAnalysis.t11_2am),
//   t12pm: randCalc(mktAnalysis.t11_2am),
//   t1pm: randCalc(mktAnalysis.t11_2am),
//
//   t2pm: randCalc(mktAnalysis.t2_5pm),
//   t3pm: randCalc(mktAnalysis.t2_5pm),
//   t4pm: randCalc(mktAnalysis.t2_5pm),
//
//   t5pm: randCalc(mktAnalysis.t5_8pm),
//   t6pm: randCalc(mktAnalysis.t5_8pm),
//   t7pm: randCalc(mktAnalysis.t5_8pm),
//
//   t8pm: randCalc(mktAnalysis.t8_11pm),
//   t9pm: randCalc(mktAnalysis.t8_11pm),
//   t10pm: randCalc(mktAnalysis.t8_11pm),
//
//   t11pm: randCalc(mktAnalysis.t11_2pm),
//   t12am: randCalc(mktAnalysis.t11_2pm),
//   t1am: randCalc(mktAnalysis.t11_2pm)
//   // t8_11: [0,4],
//   // t11_2: [0,7],
//   // t2_5: [2,15],
//   // t5_8: [15,35],
//   // t8_11: [12,31],
//   // t11_2: [5,20]
//   // genRandom: function() {
// };
<|endoftext|>


<commit_before>/**
 * @module Event
 * @namespace Event
 */

var TW = TW || {};
TW.Event = TW.Event || {};

/**
   Namespace that contain all possibles values for input keyboard.
   Each property is a constant representing a keyboard key.

   @class Key
   @static
*/
TW.Event.Key = {
    /**
       @property Backspace {Number}
    */
    Backspace: 8,
    /**
       @property Tab {Number}
    */
    Tab: 9,
    /**
       @property Enter {Number}
    */
    Enter: 13,
    /**
       @property Shift {Number}
    */
    Shift: 16,
    /**
       @property Ctrl {Number}
    */
    Ctrl: 17,
    /**
       @property Alt {Number}
    */
    Alt: 18,
    /**
       @property Pause {Number}
    */
    Pause: 19,
    /**
       @property CapsLock {Number}
    */
    CapsLock: 20,
    /**
       @property Escape {Number}
    */
    Escape: 27,
    /**
       @property PageUp {Number}
    */
    PageUp: 33,
    /**
       @property PageDown {Number}
    */
    PageDown: 34,
    /**
       @property End {Number}
    */
    End: 35,
    /**
       @property Home {Number}
    */
    Home: 36,
    /**
       @property LeftArrow {Number}
    */
    LeftArrow: 37,
    /**
       @property UpArrow {Number}
    */
    UpArrow: 38,
    /**
       @property RightArrow {Number}
    */
    RightArrow: 39,
    /**
       @property DownArrow {Number}
    */
    DownArrow: 40,
    /**
       @property Insert {Number}
    */
    Insert: 45,
    /**
       @property Delete {Number}
    */
    Delete: 46,
    /**
       @property 0 {Number}
    */
    0: 48,
    /**
       @property 1 {Number}
    */
    1: 49,
    /**
       @property 2 {Number}
    */
    2: 50,
    /**
       @property 3 {Number}
    */
    3: 51,
    /**
       @property 4 {Number}
    */
    4: 52,
    /**
       @property 5 {Number}
    */
    5: 53,
    /**
       @property 6 {Number}
    */
    6: 54,
    /**
       @property 7 {Number}
    */
    7: 55,
    /**
       @property 8 {Number}
    */
    8: 56,
    /**
       @property 9 {Number}
    */
    9: 57,
    /**
       @property A {Number}
    */
    A: 65,
    /**
       @property B {Number}
    */
    B: 66,
    /**
       @property C {Number}
    */
    C: 67,
    /**
       @property D {Number}
    */
    D: 68,
    /**
       @property E {Number}
    */
    E: 69,
    /**
       @property F {Number}
    */
    F: 70,
    /**
       @property G {Number}
    */
    G: 71,
    /**
       @property H {Number}
    */
    H: 72,
    /**
       @property I {Number}
    */
    I: 73,
    /**
       @property J {Number}
    */
    J: 74,
    /**
       @property K {Number}
    */
    K: 75,
    /**
       @property L {Number}
    */
    L: 76,
    /**
       @property M {Number}
    */
    M: 77,
    /**
       @property N {Number}
    */
    N: 78,
    /**
       @property O {Number}
    */
    O: 79,
    /**
       @property P {Number}
    */
    P: 80,
    /**
       @property Q {Number}
    */
    Q: 81,
    /**
       @property R {Number}
    */
    R: 82,
    /**
       @property S {Number}
    */
    S: 83,
    /**
       @property T {Number}
    */
    T: 84,
    /**
       @property U {Number}
    */
    U: 85,
    /**
       @property V {Number}
    */
    V: 86,
    /**
       @property W {Number}
    */
    W: 87,
    /**
       @property X {Number}
    */
    X: 88,
    /**
       @property Y {Number}
    */
    Y: 89,
    /**
       @property Z {Number}
    */
    Z: 90,
    /**
       @property F1 {Number}
    */
    F1: 112,
    /**
       @property F2 {Number}
    */
    F2: 113,
    /**
       @property F3 {Number}
    */
    F3: 114,
    /**
       @property F4 {Number}
    */
    F4: 115,
    /**
       @property F5 {Number}
    */
    F5: 116,
    /**
       @property F6 {Number}
    */
    F6: 117,
    /**
       @property F7 {Number}
    */
    F7: 118,
    /**
       @property F8 {Number}
    */
    F8: 119,
    /**
       @property F9 {Number}
    */
    F9: 120,
    /**
       @property F10 {Number}
    */
    F10: 121,
    /**
       @property F11 {Number}
    */
    F11: 122,
    /**
       @property F12 {Number}
    */
    F12: 123,
    /**
       @property Space {Number}
    */
    Space: 32
};

/**
   A service to manage input keyboard

   @class KeyboardService
   @static
*/
TW.Event.KeyboardService = {
    keyDown: [],
    oldKeyDown: [],
    _callBack: [],

    initialize: function() {
        window.onkeydown = _updateDown;
        window.onkeyup = _updateUp;
        keyDown = [];
        _callBack = [];
        oldKeyDown = [];
    },

    addCallback: function(fun) {
	_callback.push(fun);
	return _callback.length;
    },

    deleteCallback: function(funId) {
	_callback.splice(funId, 1);
    },

    _updateDown: function(event) {
	_updateArray();

	for (var it = 0; it > keyDown.length; it++) {
	    if (keyDown[it] === event.keyCode) {
		return;
	    }
	}
	keyDown.push(event.keyCode);
    },

    _updateUp: function(event) {
        _updateArray();

        for(var it = 0; it < keyDown.length; it++) {
            if (keyDown[it] == event.keyCode) {
                keyDown.splice(it, 1);
	    }
        }
    },

    isKeyDown: function(keyCode) {
        for(var it = 0; it < keyDown.length; it++) {
            if (keyDown[it] == keyCode) {
                return true;
            }
	}
        return false;
    },

    isOldKeyDown: function(keyCode) {
        for(var it = 0; it < oldKeyDown.length; it++) {
            if (oldKeyDown[it] == keyCode) {
                return true;
            }
	}
        return false;
    },

    isKeyUp: function(keyCode) {
	return !isKeyDown(keyCode);
    },

    isKeyPressed: function(keyCode) {
        if (this.isOldKeyDown(keyCode) && this.isKeyUp(keyCode)) {
            for(var it = 0; it < oldKeyDown.length; it++) {
                if (oldKeyDown[it] == keyCode) {
                    oldKeyDown.splice(it, 1);
		}
            }
            return true;
        }
        return false;
    },

    update: function() {
        for(var it = 0; it < _callBack.length; it++) {
            _callBack[it]();
        }
    },

    _updateArray: function() {
        oldKeyDown.length = 0;
        for (var it = 0; it < keyDown.length; it++) {
            oldKeyDown.push(keyDown[it]);
	}
    }

};
<commit_msg>add doc on event module<commit_after>/**
 * @module Event
 * @namespace Event
 */

var TW = TW || {};
TW.Event = TW.Event || {};

/**
   Namespace that contain all possibles values for input keyboard.
   Each property is a constant representing a keyboard key.

   a variable of type Event.Key must be one of the values
   defined on this class.

   @class Key
   @static
*/
TW.Event.Key = {
    /**
       @property Backspace {Number}
    */
    Backspace: 8,
    /**
       @property Tab {Number}
    */
    Tab: 9,
    /**
       @property Enter {Number}
    */
    Enter: 13,
    /**
       @property Shift {Number}
    */
    Shift: 16,
    /**
       @property Ctrl {Number}
    */
    Ctrl: 17,
    /**
       @property Alt {Number}
    */
    Alt: 18,
    /**
       @property Pause {Number}
    */
    Pause: 19,
    /**
       @property CapsLock {Number}
    */
    CapsLock: 20,
    /**
       @property Escape {Number}
    */
    Escape: 27,
    /**
       @property PageUp {Number}
    */
    PageUp: 33,
    /**
       @property PageDown {Number}
    */
    PageDown: 34,
    /**
       @property End {Number}
    */
    End: 35,
    /**
       @property Home {Number}
    */
    Home: 36,
    /**
       @property LeftArrow {Number}
    */
    LeftArrow: 37,
    /**
       @property UpArrow {Number}
    */
    UpArrow: 38,
    /**
       @property RightArrow {Number}
    */
    RightArrow: 39,
    /**
       @property DownArrow {Number}
    */
    DownArrow: 40,
    /**
       @property Insert {Number}
    */
    Insert: 45,
    /**
       @property Delete {Number}
    */
    Delete: 46,
    /**
       @property 0 {Number}
    */
    0: 48,
    /**
       @property 1 {Number}
    */
    1: 49,
    /**
       @property 2 {Number}
    */
    2: 50,
    /**
       @property 3 {Number}
    */
    3: 51,
    /**
       @property 4 {Number}
    */
    4: 52,
    /**
       @property 5 {Number}
    */
    5: 53,
    /**
       @property 6 {Number}
    */
    6: 54,
    /**
       @property 7 {Number}
    */
    7: 55,
    /**
       @property 8 {Number}
    */
    8: 56,
    /**
       @property 9 {Number}
    */
    9: 57,
    /**
       @property A {Number}
    */
    A: 65,
    /**
       @property B {Number}
    */
    B: 66,
    /**
       @property C {Number}
    */
    C: 67,
    /**
       @property D {Number}
    */
    D: 68,
    /**
       @property E {Number}
    */
    E: 69,
    /**
       @property F {Number}
    */
    F: 70,
    /**
       @property G {Number}
    */
    G: 71,
    /**
       @property H {Number}
    */
    H: 72,
    /**
       @property I {Number}
    */
    I: 73,
    /**
       @property J {Number}
    */
    J: 74,
    /**
       @property K {Number}
    */
    K: 75,
    /**
       @property L {Number}
    */
    L: 76,
    /**
       @property M {Number}
    */
    M: 77,
    /**
       @property N {Number}
    */
    N: 78,
    /**
       @property O {Number}
    */
    O: 79,
    /**
       @property P {Number}
    */
    P: 80,
    /**
       @property Q {Number}
    */
    Q: 81,
    /**
       @property R {Number}
    */
    R: 82,
    /**
       @property S {Number}
    */
    S: 83,
    /**
       @property T {Number}
    */
    T: 84,
    /**
       @property U {Number}
    */
    U: 85,
    /**
       @property V {Number}
    */
    V: 86,
    /**
       @property W {Number}
    */
    W: 87,
    /**
       @property X {Number}
    */
    X: 88,
    /**
       @property Y {Number}
    */
    Y: 89,
    /**
       @property Z {Number}
    */
    Z: 90,
    /**
       @property F1 {Number}
    */
    F1: 112,
    /**
       @property F2 {Number}
    */
    F2: 113,
    /**
       @property F3 {Number}
    */
    F3: 114,
    /**
       @property F4 {Number}
    */
    F4: 115,
    /**
       @property F5 {Number}
    */
    F5: 116,
    /**
       @property F6 {Number}
    */
    F6: 117,
    /**
       @property F7 {Number}
    */
    F7: 118,
    /**
       @property F8 {Number}
    */
    F8: 119,
    /**
       @property F9 {Number}
    */
    F9: 120,
    /**
       @property F10 {Number}
    */
    F10: 121,
    /**
       @property F11 {Number}
    */
    F11: 122,
    /**
       @property F12 {Number}
    */
    F12: 123,
    /**
       @property Space {Number}
    */
    Space: 32
};

/**
   A service to manage input keyboard

   @class KeyboardService
   @static
*/
TW.Event.KeyboardService = {
    /**
       Array of all keyboard keys actually down.
       @property {Array} keyDown
     */
    keyDown: [],

    /**
       Array of all keyboard keys down before the last update.
       @property {Array} oldKeyDown
     */
    oldKeyDown: [],

    /**
       Array of callback function
       @property {Array} _callback
       @private
     */
    _callBack: [],

    /**
       initialize the keyboard service.
       Must be called before any use.

       @method initialize
    */
    initialize: function() {
        window.onkeydown = _updateDown;
        window.onkeyup = _updateUp;
        keyDown = [];
        _callBack = [];
        oldKeyDown = [];
    },

    /**
       Adding a callback

       @method addCallback
       @param {Function} callback
       @return {Number} number of registered callback
     */
    addCallback: function(fun) {
	_callback.push(fun);
	return _callback.length;
    },

    /**
       Remove a callback

       @method deleteCallback
       @param {Number} funId array index of the callback
     */
    deleteCallback: function(funId) {
	_callback.splice(funId, 1);
    },

    /**
       Update the state when a key is pressed

       @method _updateDown
       @param {Event.Key} event the keyboard key value
       @private
     */
    _updateDown: function(event) {
	_updateArray();

	for (var it = 0; it > keyDown.length; it++) {
	    if (keyDown[it] === event.keyCode) {
		return;
	    }
	}
	keyDown.push(event.keyCode);
    },

    /**
       Update the state when a key is released

       @method _updateUp
       @param {Event.Key} event the keyboard key value
       @private
     */
    _updateUp: function(event) {
        _updateArray();

        for(var it = 0; it < keyDown.length; it++) {
            if (keyDown[it] == event.keyCode) {
                keyDown.splice(it, 1);
	    }
        }
    },

    /**
       Check if a keyboard key is down

       @method isKeyDown
       @param {Event.Key} keyCode the value of the keyboard key
       @return {bool} `true` if keyCode is down;
         otherwise `false`
    */
    isKeyDown: function(keyCode) {
        for(var it = 0; it < keyDown.length; it++) {
            if (keyDown[it] == keyCode) {
                return true;
            }
	}
        return false;
    },

    /**
       Check if a keyboard key was down before the last update

       @method isOldKeyDown
       @param {Event.Key} keyCode the value of the keyboard key
       @return {bool} `true` if keyCode was down;
         otherwise `false`
    */
    isOldKeyDown: function(keyCode) {
        for(var it = 0; it < oldKeyDown.length; it++) {
            if (oldKeyDown[it] == keyCode) {
                return true;
            }
	}
        return false;
    },

    /**
       Check if a keyboard key is up

       @method isKeyUp
       @param {Event.Key} keyCode the value of the keyboard key
       @return {bool} `true` if keyCode is up;
         otherwise `false`
    */
    isKeyUp: function(keyCode) {
	return !isKeyDown(keyCode);
    },

    /**
       Check if a keyboard key is pressed.
       A key is pressed if its status changes from up to down.

       @method isKeyDown
       @param {Event.Key} keyCode the value of the keyboard key
       @return {bool} `true` if keyCode is pressed;
         otherwise `false`
    */
    isKeyPressed: function(keyCode) {
        if (this.isOldKeyDown(keyCode) && this.isKeyUp(keyCode)) {
            for(var it = 0; it < oldKeyDown.length; it++) {
                if (oldKeyDown[it] == keyCode) {
                    oldKeyDown.splice(it, 1);
		}
            }
            return true;
        }
        return false;
    },

    /**
       ???

       @method update
     */
    update: function() {
        for(var it = 0; it < _callBack.length; it++) {
            _callBack[it]();
        }
    },

    /**
       Move keyDown to oldKeyDown.

       @method _updateArray
       @private
     */
    _updateArray: function() {
        oldKeyDown = [];
        for (var it = 0; it < keyDown.length; it++) {
            oldKeyDown.push(keyDown[it]);
	}
    }
};
<|endoftext|>


<commit_before>var bignum = require("bignumber");
var ByteBuffer = require("bytebuffer");

var private = {}, self = null,
	library = null, modules = null;

private.types = {};

//constructor
function Block(cb, _library) {
	self = this;
	library = _library;
	cb(null, self);
}

//public methods
Block.prototype.getBytes = function (block, withSignature) {
	var size = 8 + 4 + 4 + 4 + 32 + 32 + 8 + 4 + 4;

	if (withSignature && block.signature) {
		size = size + 64;
	}

	var bb = new ByteBuffer(size, true);

	if (block.prevBlockId) {
		var pb = bignum(block.prevBlockId).toBuffer({size: "8"});
		for (var i = 0; i < 8; i++) {
			bb.writeByte(pb[i]);
		}
	} else {
		for (var i = 0; i < 8; i++) {
			bb.writeByte(0);
		}
	}

	bb.writeInt(block.height);
	bb.writeInt(block.timestamp);
	bb.writeInt(block.payloadLength);

	var ph = new Buffer(block.payloadHash, "hex");
	for (var i = 0; i < ph.length; i++) {
		bb.writeByte(ph[i]);
	}

	var pb = new Buffer(block.delegate, "hex");
	for (var i = 0; i < pb.length; i++) {
		bb.writeByte(pb[i]);
	}

	if (block.pointId) {
		pb = bignum(block.pointId).toBuffer({ size: "8" });
		for (var i = 0; i < 8; i++) {
			bb.writeByte(pb[i]);
		}
	}

	if (block.pointHeight) {
		bb.writeInt(block.pointHeight);
	}

	bb.writeInt(block.count);

	if (withSignature && block.signature) {
		var pb = new Buffer(block.signature, "hex");
		for (var i = 0; i < pb.length; i++) {
			bb.writeByte(pb[i]);
		}
	}

	bb.flip();
	var b = bb.toBuffer();

	return b;
}

Block.prototype.verifySignature = function (block) {
	var blockBytes = self.getBytes(block);
	if (block.id != modules.api.crypto.getId(blockBytes)) {
		return false;
	}
	if (!modules.api.crypto.verify(block.delegate, block.signature, blockBytes)) {
		return false;
	}

	return true;
}

Block.prototype.save = function (block, cb) {
	modules.api.sql.insert({
		table: "blocks",
		values: {
			id: block.id,
			timestamp: block.timestamp,
			height: block.height,
			payloadLength: block.payloadLength,
			payloadHash: block.payloadHash,
			prevBlockId: block.prevBlockId,
			pointId: block.pointId,
			pointHeight: block.pointHeight,
			delegate: block.delegate,
			signature: block.signature,
			count: block.count
		}
	}, cb);
}

Block.prototype.normalize = function (block, cb) {
	for (var i in block) {
		if (block[i] === null || typeof block[i] == "undefined") {
			delete block[i];
		}
	}

	library.validator.validate(block, {
		type: "object",
		properties: {
			id: {
				type: "string"
			},
			timestamp: {
				type: "integer"
			},
			payloadLength: {
				type: "integer"
			},
			payloadHash: {
				type: "string",
				format: "hex"
			},
			prevBlockId: {
				type: "string"
			},
			pointId: {
				type: "string"
			},
			pointHeight: {
				type: "integer"
			},
			delegate: {
				type: "string",
				format: "publicKey"
			},
			signature: {
				type: "string",
				format: "signature"
			},
			count: {
				type: "integer"
			}
		},
		required: ["id", "timestamp", "payloadLength", "payloadHash", "pointId", "pointHeight", "delegate", "signature", "count"]
	}, function (err) {
		if (err) {
			return cb(err[0].message);
		}
		cb();
	});
}

Block.prototype.dbRead = function (row) {
	return {
		id: row.b_id,
		height: row.b_height,
		timestamp: row.b_timestamp,
		payloadLength: row.b_payloadLength,
		payloadHash: row.b_payloadHash,
		prevBlockId: row.b_prevBlockId,
		pointId: row.b_pointId,
		pointHeight: row.b_pointHeight,
		delegate: row.b_delegate,
		signature: row.b_signature,
		count: row.b_count
	};
}

Block.prototype.onBind = function (_modules) {
	modules = _modules;
}

//export
module.exports = Block;
<commit_msg>fix pointId type issue<commit_after>var bignum = require("bignumber");
var ByteBuffer = require("bytebuffer");

var private = {}, self = null,
	library = null, modules = null;

private.types = {};

//constructor
function Block(cb, _library) {
	self = this;
	library = _library;
	cb(null, self);
}

//public methods
Block.prototype.getBytes = function (block, withSignature) {
	var size = 8 + 4 + 4 + 4 + 32 + 32 + 8 + 4 + 4;

	if (withSignature && block.signature) {
		size = size + 64;
	}

	var bb = new ByteBuffer(size, true);

	if (block.prevBlockId) {
		var pb = bignum(block.prevBlockId).toBuffer({size: "8"});
		for (var i = 0; i < 8; i++) {
			bb.writeByte(pb[i]);
		}
	} else {
		for (var i = 0; i < 8; i++) {
			bb.writeByte(0);
		}
	}

	bb.writeInt(block.height);
	bb.writeInt(block.timestamp);
	bb.writeInt(block.payloadLength);

	var ph = new Buffer(block.payloadHash, "hex");
	for (var i = 0; i < ph.length; i++) {
		bb.writeByte(ph[i]);
	}

	var pb = new Buffer(block.delegate, "hex");
	for (var i = 0; i < pb.length; i++) {
		bb.writeByte(pb[i]);
	}

	if (block.pointId) {
		bb.writeString(block.pointId)
	}

	if (block.pointHeight) {
		bb.writeInt(block.pointHeight);
	}

	bb.writeInt(block.count);

	if (withSignature && block.signature) {
		var pb = new Buffer(block.signature, "hex");
		for (var i = 0; i < pb.length; i++) {
			bb.writeByte(pb[i]);
		}
	}

	bb.flip();
	var b = bb.toBuffer();

	return b;
}

Block.prototype.verifySignature = function (block) {
	var blockBytes = self.getBytes(block);
	if (block.id != modules.api.crypto.getId(blockBytes)) {
		return false;
	}
	if (!modules.api.crypto.verify(block.delegate, block.signature, blockBytes)) {
		return false;
	}

	return true;
}

Block.prototype.save = function (block, cb) {
	modules.api.sql.insert({
		table: "blocks",
		values: {
			id: block.id,
			timestamp: block.timestamp,
			height: block.height,
			payloadLength: block.payloadLength,
			payloadHash: block.payloadHash,
			prevBlockId: block.prevBlockId,
			pointId: block.pointId,
			pointHeight: block.pointHeight,
			delegate: block.delegate,
			signature: block.signature,
			count: block.count
		}
	}, cb);
}

Block.prototype.normalize = function (block, cb) {
	for (var i in block) {
		if (block[i] === null || typeof block[i] == "undefined") {
			delete block[i];
		}
	}

	library.validator.validate(block, {
		type: "object",
		properties: {
			id: {
				type: "string"
			},
			timestamp: {
				type: "integer"
			},
			payloadLength: {
				type: "integer"
			},
			payloadHash: {
				type: "string",
				format: "hex"
			},
			prevBlockId: {
				type: "string"
			},
			pointId: {
				type: "string"
			},
			pointHeight: {
				type: "integer"
			},
			delegate: {
				type: "string",
				format: "publicKey"
			},
			signature: {
				type: "string",
				format: "signature"
			},
			count: {
				type: "integer"
			}
		},
		required: ["id", "timestamp", "payloadLength", "payloadHash", "pointId", "pointHeight", "delegate", "signature", "count"]
	}, function (err) {
		if (err) {
			return cb(err[0].message);
		}
		cb();
	});
}

Block.prototype.dbRead = function (row) {
	return {
		id: row.b_id,
		height: row.b_height,
		timestamp: row.b_timestamp,
		payloadLength: row.b_payloadLength,
		payloadHash: row.b_payloadHash,
		prevBlockId: row.b_prevBlockId,
		pointId: row.b_pointId,
		pointHeight: row.b_pointHeight,
		delegate: row.b_delegate,
		signature: row.b_signature,
		count: row.b_count
	};
}

Block.prototype.onBind = function (_modules) {
	modules = _modules;
}

//export
module.exports = Block;
<|endoftext|>


<commit_before>Object.forEach = function (object, callback) {
    for (var key in object) {
        if (object.hasOwnProperty(key))
            callback.call(object, key, object[key]);
    }
};
Object.every = function (object, callback) {
    for (var key in object) {
        if (object.hasOwnProperty(key))
            if (callback.call(object, key, object[key]) === false) return false;
    }
    return true;
};
Object.some = function (object, callback) {
    var status = false;
    for (var key in object) {
        if (object.hasOwnProperty(key))
            status = callback.call(object, key, object[key]) || status;
    }
    return status;
};
Object.clone = function (o) {
    if (o === null || typeof(o) !== 'object') return o;

    var objNew = o.constructor();

    for (var key in o)
        objNew[key] = Object.clone(o[key]);

    return objNew;
};
Object.merge = function (o1, o2) {
    var objNew = Object.clone(o1);
    for (var p in o2) {
        if (o2[p] && o2[p].constructor === Object) {
            if (!o1[p]) o1[p] = {};
            objNew[p] = Object.merge(o1[p], o2[p]);
        } else {
            objNew[p] = o2[p];
        }
    }
    return objNew;
};
document.elem = function (elemname, attributes, text) {
    if (typeof attributes === 'string') {
        text = attributes;
        attributes = null;
    }
    if (elemname === 'textElem') return document.createTextNode(text);
    return document.createElement(elemname).attrib(attributes).setText(text);
};
document.getElem = document.querySelector;
document.getElemAll = document.querySelectorAll;
document.delElem = function (element) {
    if (typeof element === 'string') {
        element = document.getElemAll(element);
    }
    if (element.forEach) {
        element.forEach(function () {
            if (this.parentNode) this.parentNode.removeChild(this);
        });
    } else if (element && element.parentNode) {
        element.parentNode.removeChild(element);
    }
};
document.ready = function (callback) {
    if (document.readyState == "complete" || document.readyState == "loaded" || document.readyState == "interactive") {
        setTimeout(callback,1);
    }else if (document.addEventListener) {
            document.addEventListener("DOMContentLoaded", callback);
    } else {
        document.onreadystatechange = function () {
            if (document.readyState == "interactive") callback();
        }
    }
};
Element.prototype.getElem = Element.prototype.querySelector;
Element.prototype.getElemAll = Element.prototype.querySelectorAll;
Element.prototype.del = function () {
    var parent = this.parentNode;
    if (parent) parent.removeChild(this);
    return parent;
};
Element.prototype.elem = function (elemname, attr, text, returnparent) {
    if (typeof elemname !== 'string') {
        var _that = this;
        [].concat(elemname).forEach(function (element) {
            _that.appendChild(element);
        });
        return this;
    }
    var elem = document.elem(elemname, attr, text);
    this.appendChild(elem);
    return (returnparent !== null && returnparent) ? this : ['br', 'hr', 'textElem'].indexOf(elemname) === -1 ? elem : returnparent === false ? elem : this;
};
Element.prototype.siblings = function () {
    return this.parentElement.children;
};
Element.prototype.up = function () {
    return this.parentElement;
}
Element.prototype.attrib = function (attribute, value) {
    if (attribute) {
        var _this = this;
        var setOrRemove = function (key, value) {
            value !== null ? _this.setAttribute(key, value) : _this.removeAttribute(key);
        };
        if (typeof attribute === "object") {
            Object.forEach(attribute, setOrRemove);
        } else if (typeof attribute === 'string') {
            setOrRemove(attribute, value);
        }
    }
    return this;
};
Element.prototype.setText = function (text) {
    if (text) {
        this.textContent = text;
    }
    return this;
};
Element.prototype.clearElem = function () {
    if (this.textContent !== null) {
        this.textContent = '';
    }
    while (this.firstChild) {
        this.removeChild(this.firstChild);
    }
    return this;
};
Element.prototype.on = function (event, listener, useCapture) {
    if (this.attachEvent) {
        this.attachEvent(event, listener);
    } else {
        this.addEventListener(event, listener, useCapture);
    }
    return this;
};
Element.prototype.off = function (event, listener, useCapture) {
    if (this.detachEvent) {
        this.detachEvent(event, listener);
    } else {
        this.removeEventListener(event, listener, useCapture);
    }
    return this;
};
Element.prototype.addClass = function (className) {
    var classes = this.className.split(' ');
    if (classes.indexOf(className) === -1) {
        classes.push(className);
        this.className = classes.join(' ');
    }
    return this;
};
Element.prototype.removeClass = function (className) {
    var classes = this.className.split(' ');
    var index = classes.indexOf(className);
    if (index !== -1) {
        classes.splice(index, 1);
        this.className = classes.join(' ');
    }
    return this;
};
Element.prototype.hasClass = function (className) {
    return this.className.split(' ').indexOf(className) !== -1;
};
NodeList.prototype.forEach = function (callback) {
    for (var i = 0; i < this.length; i++) {
        callback.call(this[i], i);
    }
};
NodeList.prototype.every = function (callback) {
    for (var i = 0; i < this.length; i++) {
        if (callback.call(this[i]) === false) return false;
    }
    return true;
};
NodeList.prototype.some = function (callback) {
    var status = false;
    for (var i = 0; i < this.length; i++) {
        status = callback.call(this[i]) || status;
    }
    return status;
};
NodeList.prototype.attrib = function (attribute, value) {
    this.each(function () {
        this.attrib(attribute, value)
    });
    return this;
};
NodeList.prototype.elem = function (elemname, attr, text, returnparent) {
    var rand = Math.random() * 10000, name = "data-elemjs-NL-elem";
    this.each(function () {
        this.elem(elemname, attr, text, returnparent).attrib(name, rand);
    });
    return document.getElemAll("[" + name + "='" + rand + "']").attrib(name, null);
};
NodeList.prototype.del = function () {
    var rand = Math.random() * 10000, name = "data-elemjs-NL-del";
    this.each(function () {
        this.del().attrib(name, rand);
    });
    return document.getElemAll("[" + name + "='" + rand + "']").attrib(name, null);
};
NodeList.prototype.getElem = function (selector) {
    var rand = Math.random() * 10000, name = "data-elemjs-NL-getElem";
    this.each(function () {
        var temp = this.getElem(selector);
        if (temp !== null)temp.attrib(name, rand);
    });
    return document.getElemAll("[" + name + "='" + rand + "']").attrib(name, null);
};
NodeList.prototype.getElemAll = function (selector) {
    var rand = Math.random() * 10000, name = "data-elemjs-NL-getElemAll";
    this.each(function () {
        this.getElemAll(selector).attrib(name, rand);
    });
    return document.getElemAll("[" + name + "='" + rand + "']").attrib(name, null);
};
NodeList.prototype.on = function (event, listener, useCapture) {
    this.each(function () {
        this.on(event, listener, useCapture);
    });
    return this;
};
NodeList.prototype.off = function (event, listener, useCapture) {
    this.each(function () {
        this.off(event, listener, useCapture);
    });
    return this;
};
NodeList.prototype.toArray = function () {
    var arr = [];
    for (var i = this.length; i--; arr.unshift(this[i]));
    return arr;
};
['section', 'nav', 'article', 'aside', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'footer', 'address', 'main', 'p', 'hr', 'pre', 'ol', 'ul', 'li', 'div', 'a', 'em', 'strong', 'code', 'span', 'br', 'img', 'svg', 'table', 'tbody', 'thead', 'tfoot', 'tr', 'td', 'th', 'form', 'label', 'input', 'button', 'select', 'option', 'textarea', 'textElem'].map(function (elemname) {
    Element.prototype[elemname] = function (attr, text, returnparent) {
        return this.elem(elemname, attr, text, returnparent);
    };
    document[elemname] = function (attr, text) {
        return this.elem(elemname, attr, text);
    };
    NodeList.prototype[elemname] = function (attr, text, returnparent) {
        return this.elem(elemname, attr, text, returnparent);
    }
});
Window.http = {
    request: function (config, onSuccess, onError) {
        var defaults = { method: 'GET', async: true, headers: {} };
        var options = Object.merge(defaults, config);
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
            if (this.status >= 200 && this.status < 300) {
                if (typeof onSuccess === 'function') onSuccess(this.responseText, this.status, this);
            } else {
                if (typeof onError === 'function') onError(this.responseText, this.status, this);
            }
        };
        xhr.onerror = function () {
            if (typeof onError === 'function') onError(this.statusText, this.status, this);
        };
        xhr.open(options.method, options.url, options.aSync);
        if (options.headers !== null && typeof options.headers === 'object')
            Object.forEach(options.headers, function (key, value) {
                xhr.setRequestHeader(key, value);
            });
        if (options.data && typeof options.data === "object" && config.headers["Content-type"] === "application/x-www-form-urlencoded") {
            options.data = Window.http.serialize(options.data);
        }
        xhr.send(options.data);
        return xhr;
    },
    GET: function (config, onSuccess, onError) {
        config = (typeof config === "string") ? {url: config} : config || {};
        config.method = "GET";
        if (config.data && typeof config.data === 'object') {
            config.url += document.a({href: config.url}).search ? '&' : '?';
            config.url += Window.http.serialize(config.data);
            delete config.data;
        }
        return Window.http.request(config, onSuccess, onError);
    },
    POST: function (config, onSuccess, onError) {
        config = (typeof config === "string") ? {url: config} : config || {};
        config.method = "POST";
        config.headers = config.headers || {};
        config.headers["Content-type"] = config.headers["Content-type"] || "application/x-www-form-urlencoded";
        return Window.http.request(config, onSuccess, onError);
    },
    PUT: function (config, onSuccess, onError) {
        config = (typeof config === "string") ? {url: config} : config || {};
        config.method = "PUT";
        config.headers = config.headers || {};
        config.headers["Content-type"] = config.headers["Content-type"] || "application/x-www-form-urlencoded";
        return Window.http.request(config, onSuccess, onError);
    },
    DELETE: function (config, onSuccess, onError) {
        config = (typeof config === "string") ? {url: config} : config || {};
        config.method = "DELETE";
        return Window.http.request(config, onSuccess, onError);
    },
    serialize: function (obj, prefix) {
        var str = [];
        Object.forEach(obj, function (key, value) {
            var k = prefix ? prefix + "[" + key + "]" : key, v = value;
            str.push(typeof v == "object" ?
                Window.http.serialize(v, k) :
                encodeURIComponent(k) + "=" + encodeURIComponent(v));
        });
        return str.join("&");
    },
    load: function (config) {
        config = (typeof config === "string") ? {url: config} : config || {};
        config.src = config.src || config.url;
        delete config.url;
        if (config.data && typeof config.data === 'object') {
            config.src += document.a({href: config.src}).search ? '&' : '?';
            config.src += Window.http.serialize(config.data);
            delete config.data;
        }
        if (config.id) {
            var toDelete = document.getElem("#" + config.id);
            if (toDelete !== null) {
                toDelete.del();
            }
        }
        return document.getElem("head").elem("script", config);
    }
};
<commit_msg>added before and after functions for http requests<commit_after>Object.forEach = function (object, callback) {
    for (var key in object) {
        if (object.hasOwnProperty(key))
            callback.call(object, key, object[key]);
    }
};
Object.every = function (object, callback) {
    for (var key in object) {
        if (object.hasOwnProperty(key))
            if (callback.call(object, key, object[key]) === false) return false;
    }
    return true;
};
Object.some = function (object, callback) {
    var status = false;
    for (var key in object) {
        if (object.hasOwnProperty(key))
            status = callback.call(object, key, object[key]) || status;
    }
    return status;
};
Object.clone = function (o) {
    if (o === null || typeof(o) !== 'object') return o;

    var objNew = o.constructor();

    for (var key in o)
        objNew[key] = Object.clone(o[key]);

    return objNew;
};
Object.merge = function (o1, o2) {
    var objNew = Object.clone(o1);
    for (var p in o2) {
        if (o2[p] && o2[p].constructor === Object) {
            if (!o1[p]) o1[p] = {};
            objNew[p] = Object.merge(o1[p], o2[p]);
        } else {
            objNew[p] = o2[p];
        }
    }
    return objNew;
};
document.elem = function (elemname, attributes, text) {
    if (typeof attributes === 'string') {
        text = attributes;
        attributes = null;
    }
    if (elemname === 'textElem') return document.createTextNode(text);
    return document.createElement(elemname).attrib(attributes).setText(text);
};
document.getElem = document.querySelector;
document.getElemAll = document.querySelectorAll;
document.delElem = function (element) {
    if (typeof element === 'string') {
        element = document.getElemAll(element);
    }
    if (element.forEach) {
        element.forEach(function () {
            if (this.parentNode) this.parentNode.removeChild(this);
        });
    } else if (element && element.parentNode) {
        element.parentNode.removeChild(element);
    }
};
document.ready = function (callback) {
    if (document.readyState == "complete" || document.readyState == "loaded" || document.readyState == "interactive") {
        setTimeout(callback,1);
    }else if (document.addEventListener) {
            document.addEventListener("DOMContentLoaded", callback);
    } else {
        document.onreadystatechange = function () {
            if (document.readyState == "interactive") callback();
        }
    }
};
Element.prototype.getElem = Element.prototype.querySelector;
Element.prototype.getElemAll = Element.prototype.querySelectorAll;
Element.prototype.del = function () {
    var parent = this.parentNode;
    if (parent) parent.removeChild(this);
    return parent;
};
Element.prototype.elem = function (elemname, attr, text, returnparent) {
    if (typeof elemname !== 'string') {
        var _that = this;
        [].concat(elemname).forEach(function (element) {
            _that.appendChild(element);
        });
        return this;
    }
    var elem = document.elem(elemname, attr, text);
    this.appendChild(elem);
    return (returnparent !== null && returnparent) ? this : ['br', 'hr', 'textElem'].indexOf(elemname) === -1 ? elem : returnparent === false ? elem : this;
};
Element.prototype.siblings = function () {
    return this.parentElement.children;
};
Element.prototype.up = function () {
    return this.parentElement;
}
Element.prototype.attrib = function (attribute, value) {
    if (attribute) {
        var _this = this;
        var setOrRemove = function (key, value) {
            value !== null ? _this.setAttribute(key, value) : _this.removeAttribute(key);
        };
        if (typeof attribute === "object") {
            Object.forEach(attribute, setOrRemove);
        } else if (typeof attribute === 'string') {
            setOrRemove(attribute, value);
        }
    }
    return this;
};
Element.prototype.setText = function (text) {
    if (text) {
        this.textContent = text;
    }
    return this;
};
Element.prototype.clearElem = function () {
    if (this.textContent !== null) {
        this.textContent = '';
    }
    while (this.firstChild) {
        this.removeChild(this.firstChild);
    }
    return this;
};
Element.prototype.on = function (event, listener, useCapture) {
    if (this.attachEvent) {
        this.attachEvent(event, listener);
    } else {
        this.addEventListener(event, listener, useCapture);
    }
    return this;
};
Element.prototype.off = function (event, listener, useCapture) {
    if (this.detachEvent) {
        this.detachEvent(event, listener);
    } else {
        this.removeEventListener(event, listener, useCapture);
    }
    return this;
};
Element.prototype.addClass = function (className) {
    var classes = this.className.split(' ');
    if (classes.indexOf(className) === -1) {
        classes.push(className);
        this.className = classes.join(' ');
    }
    return this;
};
Element.prototype.removeClass = function (className) {
    var classes = this.className.split(' ');
    var index = classes.indexOf(className);
    if (index !== -1) {
        classes.splice(index, 1);
        this.className = classes.join(' ');
    }
    return this;
};
Element.prototype.hasClass = function (className) {
    return this.className.split(' ').indexOf(className) !== -1;
};
NodeList.prototype.forEach = function (callback) {
    for (var i = 0; i < this.length; i++) {
        callback.call(this[i], i);
    }
};
NodeList.prototype.every = function (callback) {
    for (var i = 0; i < this.length; i++) {
        if (callback.call(this[i]) === false) return false;
    }
    return true;
};
NodeList.prototype.some = function (callback) {
    var status = false;
    for (var i = 0; i < this.length; i++) {
        status = callback.call(this[i]) || status;
    }
    return status;
};
NodeList.prototype.attrib = function (attribute, value) {
    this.each(function () {
        this.attrib(attribute, value)
    });
    return this;
};
NodeList.prototype.elem = function (elemname, attr, text, returnparent) {
    var rand = Math.random() * 10000, name = "data-elemjs-NL-elem";
    this.each(function () {
        this.elem(elemname, attr, text, returnparent).attrib(name, rand);
    });
    return document.getElemAll("[" + name + "='" + rand + "']").attrib(name, null);
};
NodeList.prototype.del = function () {
    var rand = Math.random() * 10000, name = "data-elemjs-NL-del";
    this.each(function () {
        this.del().attrib(name, rand);
    });
    return document.getElemAll("[" + name + "='" + rand + "']").attrib(name, null);
};
NodeList.prototype.getElem = function (selector) {
    var rand = Math.random() * 10000, name = "data-elemjs-NL-getElem";
    this.each(function () {
        var temp = this.getElem(selector);
        if (temp !== null)temp.attrib(name, rand);
    });
    return document.getElemAll("[" + name + "='" + rand + "']").attrib(name, null);
};
NodeList.prototype.getElemAll = function (selector) {
    var rand = Math.random() * 10000, name = "data-elemjs-NL-getElemAll";
    this.each(function () {
        this.getElemAll(selector).attrib(name, rand);
    });
    return document.getElemAll("[" + name + "='" + rand + "']").attrib(name, null);
};
NodeList.prototype.on = function (event, listener, useCapture) {
    this.each(function () {
        this.on(event, listener, useCapture);
    });
    return this;
};
NodeList.prototype.off = function (event, listener, useCapture) {
    this.each(function () {
        this.off(event, listener, useCapture);
    });
    return this;
};
NodeList.prototype.toArray = function () {
    var arr = [];
    for (var i = this.length; i--; arr.unshift(this[i]));
    return arr;
};
['section', 'nav', 'article', 'aside', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'footer', 'address', 'main', 'p', 'hr', 'pre', 'ol', 'ul', 'li', 'div', 'a', 'em', 'strong', 'code', 'span', 'br', 'img', 'svg', 'table', 'tbody', 'thead', 'tfoot', 'tr', 'td', 'th', 'form', 'label', 'input', 'button', 'select', 'option', 'textarea', 'textElem'].map(function (elemname) {
    Element.prototype[elemname] = function (attr, text, returnparent) {
        return this.elem(elemname, attr, text, returnparent);
    };
    document[elemname] = function (attr, text) {
        return this.elem(elemname, attr, text);
    };
    NodeList.prototype[elemname] = function (attr, text, returnparent) {
        return this.elem(elemname, attr, text, returnparent);
    }
});
Window.http = {
    request: function (config, onSuccess, onError) {
        Window.http._callback(Window.http.before);
        var defaults = { method: 'GET', async: true, headers: {} };
        var options = Object.merge(defaults, config);
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
            Window.http._callback(Window.http.after);
            if (this.status >= 200 && this.status < 300) {
                if (typeof onSuccess === 'function') onSuccess(this.responseText, this.status, this);
            } else {
                if (typeof onError === 'function') onError(this.responseText, this.status, this);
            }
        };
        xhr.onerror = function () {
            Window.http._callback(Window.http.after);
            if (typeof onError === 'function') onError(this.statusText, this.status, this);
        };
        xhr.open(options.method, options.url, options.aSync);
        if (options.headers !== null && typeof options.headers === 'object')
            Object.forEach(options.headers, function (key, value) {
                xhr.setRequestHeader(key, value);
            });
        if (options.data && typeof options.data === "object" && config.headers["Content-type"] === "application/x-www-form-urlencoded") {
            options.data = Window.http.serialize(options.data);
        }
        xhr.send(options.data);
        return xhr;
    },
    _callback: function(callbackObject){
      if(callbackObject && typeof callbackObject.callback === 'function'){
          if(callbackObject.async){
              setTimeout(callbackObject.callback,1);
          }else{
              callbackObject.callback.call();
          }
      }
    },
    GET: function (config, onSuccess, onError) {
        config = (typeof config === "string") ? {url: config} : config || {};
        config.method = "GET";
        if (config.data && typeof config.data === 'object') {
            config.url += document.a({href: config.url}).search ? '&' : '?';
            config.url += Window.http.serialize(config.data);
            delete config.data;
        }
        return Window.http.request(config, onSuccess, onError);
    },
    POST: function (config, onSuccess, onError) {
        config = (typeof config === "string") ? {url: config} : config || {};
        config.method = "POST";
        config.headers = config.headers || {};
        config.headers["Content-type"] = config.headers["Content-type"] || "application/x-www-form-urlencoded";
        return Window.http.request(config, onSuccess, onError);
    },
    PUT: function (config, onSuccess, onError) {
        config = (typeof config === "string") ? {url: config} : config || {};
        config.method = "PUT";
        config.headers = config.headers || {};
        config.headers["Content-type"] = config.headers["Content-type"] || "application/x-www-form-urlencoded";
        return Window.http.request(config, onSuccess, onError);
    },
    DELETE: function (config, onSuccess, onError) {
        config = (typeof config === "string") ? {url: config} : config || {};
        config.method = "DELETE";
        return Window.http.request(config, onSuccess, onError);
    },
    serialize: function (obj, prefix) {
        var str = [];
        Object.forEach(obj, function (key, value) {
            var k = prefix ? prefix + "[" + key + "]" : key, v = value;
            str.push(typeof v == "object" ?
                Window.http.serialize(v, k) :
                encodeURIComponent(k) + "=" + encodeURIComponent(v));
        });
        return str.join("&");
    },
    load: function (config) {
        config = (typeof config === "string") ? {url: config} : config || {};
        config.src = config.src || config.url;
        delete config.url;
        if (config.data && typeof config.data === 'object') {
            config.src += document.a({href: config.src}).search ? '&' : '?';
            config.src += Window.http.serialize(config.data);
            delete config.data;
        }
        if (config.id) {
            var toDelete = document.getElem("#" + config.id);
            if (toDelete !== null) {
                toDelete.del();
            }
        }
        return document.getElem("head").elem("script", config);
    },
    setBefore: function(callback, async){
        Window.http.before = {callback:callback,async:async};
    },
    setAfter: function(callback, async){
        Window.http.after = {callback:callback,async:async};
    }
};
<|endoftext|>


<commit_before>var cproc = require('child_process');
var util = require('util');
var _ = require('underscore')._;

var Timer = (function() {
  var Timer = require('./proto').proto();
  function time() { return (new Date()).getTime(); }
  Timer.init = function() {
    this._t = time();
  };
  Timer.elapsed = function() {
    return time() - this._t;
  };
  return Timer;
})();

exports.Timer = Timer;

function rtrim(s) {
	return s.replace(/\s+$/, '');
}

var color = require("./ansi-color").set;

var shutdownCallback;
exports.onShutdown = function(cb) { shutdownCallback = cb; };

function shutdown(signal) {
  if (signal !== 'exit') { info('Received ' + signal +'.'); }
  killLaunchedProcesses();
  if (shutdownCallback) { shutdownCallback(signal); }
  if (signal !== 'exit') { process.exit(); }
}

process.on('SIGTERM', function() { shutdown('SIGTERM'); });
process.on('SIGHUP', function() { shutdown('SIGHUP'); });
process.on('exit', function () { shutdown('exit'); });

var launchedProcesses = [];

function addLaunchedProcess(proc) {
  launchedProcesses.push(proc);
}

function removeLaunchedProcess(proc) {
  launchedProcesses = _.without(launchedProcesses, proc);
}

function killLaunchedProcesses() {
  _.each(launchedProcesses, function(child) {
    verbose('Killing host process ' + child.pid);
    child.kill();
  });
  launchedProcesses = [];
}

function exec2(cmd, args, opts, cb) {
  var simple = _.prune(cmd + ' ' + args.join(' '), 40);
  var printFn = (opts.verbose ? info : verbose);
  printFn('exec2: ' + simple + ' ' + util.inspect(opts));
  if (!opts || !opts.cwd) {
    error('cwd not specified in ' + simple);
  }
  var proc = cproc.spawn.call(this, cmd, args, opts),
      out = [],
      err = [],
      t = Timer.make();
  function log(x) {
    if (!opts.pipePlain) { console.log(color(rtrim(x + ''), 'cyan')); }
    else { process.stdout.write(x + ''); }
  }
  proc.stdout.on('data', function (data) {
    if (opts.pipe || opts.pipeStdout) { log(data); }
    _.each((data + '').split('\n'), function(line) {
      if (line !== '') {
        proc.stdout.emit('line', line);
      }
    });
    out.push(data);
  });
  proc.stderr.on('data', function (data) {
    if (!opts.quietError) {
      process.stderr.write(color('    error in ' + simple + ':\n', 'black', true) + color(data + '', 'red'));
    }
    err.push(data);
  });
  proc.on('exit', function (code) {
    printFn(t.elapsed() + '  completed2: ' + simple + (code ? ' (' + code + ')' : ''));
    if (cb) {
      cb(code, out.join(''), err.join(''));
    }
    removeLaunchedProcess(proc);
  });
  addLaunchedProcess(proc);
  return proc;
}

function exec(cmd, opts, cb) {
  if (opts && opts.length !== undefined) {
    return exec2.apply(this, arguments);
  } else {
    info('exec: ' + cmd);
    var t = Timer.make();
    var proc = cproc.exec(cmd, opts, function(error, stdout, stderr) {
      info(t.elapsed() + '  completed ' + cmd);
      if (error) { error('error: ' + error); }
      info(stderr);
      if (cb) { cb.apply(this, arguments); }
      removeLaunchedProcess(proc);
    });
    addLaunchedProcess(proc);
  }
}

exports.exec = exec;
<commit_msg>autocommit<commit_after>var cproc = require('child_process');
var util = require('util');
var _ = require('underscore')._;

var Timer = (function() {
  var Timer = require('./proto').proto();
  function time() { return (new Date()).getTime(); }
  Timer.init = function() {
    this._t = time();
  };
  Timer.elapsed = function() {
    return time() - this._t;
  };
  return Timer;
})();

exports.Timer = Timer;

function rtrim(s) {
	return s.replace(/\s+$/, '');
}

var color = require("./ansi-color").set;

var shutdownCallback;
exports.onShutdown = function(cb) { shutdownCallback = cb; };

function shutdown(signal) {
  if (signal !== 'exit') { info('Received ' + signal +'.'); }
  killLaunchedProcesses();
  if (shutdownCallback) { shutdownCallback(signal); }
  if (signal !== 'exit') { process.exit(); }
}

process.on('SIGTERM', function() { shutdown('SIGTERM'); });
process.on('SIGHUP', function() { shutdown('SIGHUP'); });
process.on('exit', function () { shutdown('exit'); });

var launchedProcesses = [];

function addLaunchedProcess(proc) {
  launchedProcesses.push(proc);
}

function removeLaunchedProcess(proc) {
  launchedProcesses = _.without(launchedProcesses, proc);
}

function killLaunchedProcesses() {
  _.each(launchedProcesses, function(child) {
    verbose('Killing host process ' + child.pid);
    child.kill();
  });
  launchedProcesses = [];
}

function exec2(cmd, args, opts, cb) {
  var simple = _.prune(cmd + ' ' + args.join(' '), 40);
  var printFn = (opts.verbose ? info : verbose);
  printFn('exec2: ' + simple + ' ' + util.inspect(opts));
  if (!opts || !opts.cwd) {
    error('cwd not specified in ' + simple);
  }
  var proc = cproc.spawn.call(this, cmd, args, opts),
      out = [],
      err = [],
      t = Timer.make();
  function log(x) {
    if (!opts.pipePlain) { console.log(color(rtrim(x + ''), 'cyan')); }
    else { process.stdout.write(x + ''); }
  }
  proc.stdout.on('data', function (data) {
    if (opts.pipe || opts.pipeStdout) { log(data); }
    _.each((data + '').split('\n'), function(line) {
      if (line !== '') {
        proc.stdout.emit('line', line);
      }
    });
    proc.emit('stdout', data);
    out.push(data);
  });
  proc.stderr.on('data', function (data) {
    if (!opts.quietError) {
      process.stderr.write(color('    error in ' + simple + ':\n', 'black', true) + color(data + '', 'red'));
    }
    proc.emit('stderr', data);
    err.push(data);
  });
  proc.on('exit', function (code) {
    printFn(t.elapsed() + '  completed2: ' + simple + (code ? ' (' + code + ')' : ''));
    if (cb) {
      cb(code, out.join(''), err.join(''));
    }
    removeLaunchedProcess(proc);
  });
  addLaunchedProcess(proc);
  return proc;
}

function exec(cmd, opts, cb) {
  if (opts && opts.length !== undefined) {
    return exec2.apply(this, arguments);
  } else {
    info('exec: ' + cmd);
    var t = Timer.make();
    var proc = cproc.exec(cmd, opts, function(error, stdout, stderr) {
      info(t.elapsed() + '  completed ' + cmd);
      if (error) { error('error: ' + error); }
      info(stderr);
      if (cb) { cb.apply(this, arguments); }
      removeLaunchedProcess(proc);
    });
    addLaunchedProcess(proc);
  }
}

exports.exec = exec;
<|endoftext|>


<commit_before>// Rollup plugins
const buble = require('rollup-plugin-buble')
const eslint = require('rollup-plugin-eslint')
const resolve = require('rollup-plugin-node-resolve')
const commonjs = require('rollup-plugin-commonjs')
const replace = require('rollup-plugin-replace')
const uglify = require('rollup-plugin-uglify')
const progress = require('rollup-plugin-progress')
const postcss = require('rollup-plugin-postcss')
const html = require('rollup-plugin-html')
const git = require('git-rev-sync')
const { version } = require('../package.json')

module.exports = {
	moduleName: 'bPlayer',
	entry: 'src/bplayer.js',
	devDest: 'test/bplayer.dev.js',
	proDest: 'dist/bplayer.min.js',
	format: 'umd',
	sourceMap: 'inline',
	plugins: [
		progress({
			clearLine: false
		}),
		resolve({
			jsnext: true,
			main: true,
			browser: true,
		}),
		commonjs(),
		html({
			include: 'src/*.html'
		}),
		postcss(),
		eslint({
			exclude: ['**/*.html', '**/*.css']
		}),
		buble({
			transforms: {
				modules: false,
				dangerousForOf: true
			},
			objedtAssign: 'Object.assign'
		}),
		replace({
			ENV: JSON.stringify(process.env.NODE_ENV || 'development'),
			VERSION: JSON.stringify(`${version}.${git.branch()}.${git.short()}`)
		}),
		(process.env.NODE_ENV === 'production' && uglify())
	]
}
<commit_msg>Remove branch logout<commit_after>// Rollup plugins
const buble = require('rollup-plugin-buble')
const eslint = require('rollup-plugin-eslint')
const resolve = require('rollup-plugin-node-resolve')
const commonjs = require('rollup-plugin-commonjs')
const replace = require('rollup-plugin-replace')
const uglify = require('rollup-plugin-uglify')
const progress = require('rollup-plugin-progress')
const postcss = require('rollup-plugin-postcss')
const html = require('rollup-plugin-html')
const git = require('git-rev-sync')
const { version } = require('../package.json')

module.exports = {
	moduleName: 'bPlayer',
	entry: 'src/bplayer.js',
	devDest: 'test/bplayer.dev.js',
	proDest: 'dist/bplayer.min.js',
	format: 'umd',
	sourceMap: 'inline',
	plugins: [
		progress({
			clearLine: false
		}),
		resolve({
			jsnext: true,
			main: true,
			browser: true,
		}),
		commonjs(),
		html({
			include: 'src/*.html'
		}),
		postcss(),
		eslint({
			exclude: ['**/*.html', '**/*.css']
		}),
		buble({
			transforms: {
				modules: false,
				dangerousForOf: true
			},
			objedtAssign: 'Object.assign'
		}),
		replace({
			ENV: JSON.stringify(process.env.NODE_ENV || 'development'),
			VERSION: JSON.stringify(`${version}.${git.short()}`)
		}),
		(process.env.NODE_ENV === 'production' && uglify())
	]
}
<|endoftext|>


<commit_before>angular
.module('jbAngularSelectable', [])
.factory('Selectables', SelectablesFactory);

function SelectablesFactory() {

  function Selectables(selectables) {
    this.selectables = selectables instanceof Array ? selectables : [];
  }

  Selectables.prototype.select = function(arr) {
    if (!(arr instanceof Array)) {
      arr = [arr];
    }

    var self = this;
    arr.forEach(function(obj) {
      if(self.selectables.indexOf(obj) < 0) {
        self.selectables.push(obj);
      }
    });
  }

  Selectables.prototype.selectOnly = function(obj) {
    // deselect anything already selected
    for(var i = 0; i < this.selectables.length; i++) {
      this.deselect(this.selectables[i])
    }

    this.select(obj);
  }

  Selectables.prototype.selectIf = function(obj, isSelectable) {
    if (isSelectable) {
      this.select(obj);
    }
  }

  Selectables.prototype.selectOnlyIf = function(obj, isSelectable) {
    if (isSelectable) {
      this.selectOnly(obj);
    }
  }

  Selectables.prototype.deselect = function(obj) {
    var pos = this.selectables.indexOf(obj);
    if(pos >= 0) {
      this.selectables.splice(pos, 1);
    }
  }

  Selectables.prototype.toggle = function(obj) {
    if (this.isSelected(obj)) {
      this.deselect(obj)
    } else {
      this.select(obj);
    }
  }

  Selectables.prototype.toggleOnly = function(obj) {
    if (this.isSelected(obj)) {
      this.deselect(obj);
    } else {
      this.selectOnly(obj);
    }
  }

  Selectables.prototype.toggleIf = function(obj, isSelectable) {
    if (!isSelectable) return;
    this.toggle(obj);
  }

  Selectables.prototype.toggleOnlyIf = function(obj, isSelectable) {
    if (!isSelectable) return;
    this.toggleOnly(obj);
  }

  // this is likely inefficient as any digest cycle will cause this to be
  // to be re-run, walking through the array each time
  Selectables.prototype.isSelected = function(obj) {
    return this.selectables.indexOf(obj) >= 0;
  }

  Selectables.prototype.hasSelected = function() {
    return this.selectables.length >= 1;
  }

  Selectables.prototype.getSelected = function() {
    return this.selectables;
  }

  return Selectables;
}

<commit_msg>deselectAll emptys all selected things<commit_after>angular
.module('jbAngularSelectable', [])
.factory('Selectables', SelectablesFactory);

function SelectablesFactory() {

  function Selectables(selectables) {
    this.selectables = selectables instanceof Array ? selectables : [];
  }

  Selectables.prototype.select = function(arr) {
    if (!(arr instanceof Array)) {
      arr = [arr];
    }

    var self = this;
    arr.forEach(function(obj) {
      if(self.selectables.indexOf(obj) < 0) {
        self.selectables.push(obj);
      }
    });
  }

  Selectables.prototype.selectOnly = function(obj) {
    // deselect anything already selected
    for(var i = 0; i < this.selectables.length; i++) {
      this.deselect(this.selectables[i])
    }

    this.select(obj);
  }

  Selectables.prototype.selectIf = function(obj, isSelectable) {
    if (isSelectable) {
      this.select(obj);
    }
  }

  Selectables.prototype.selectOnlyIf = function(obj, isSelectable) {
    if (isSelectable) {
      this.selectOnly(obj);
    }
  }

  Selectables.prototype.deselect = function(obj) {
    var pos = this.selectables.indexOf(obj);
    if(pos >= 0) {
      this.selectables.splice(pos, 1);
    }
  }

  Selectables.prototype.deselectAll = function() {
    this.selectables.length = 0;
  }

  Selectables.prototype.toggle = function(obj) {
    if (this.isSelected(obj)) {
      this.deselect(obj)
    } else {
      this.select(obj);
    }
  }

  Selectables.prototype.toggleOnly = function(obj) {
    if (this.isSelected(obj)) {
      this.deselect(obj);
    } else {
      this.selectOnly(obj);
    }
  }

  Selectables.prototype.toggleIf = function(obj, isSelectable) {
    if (!isSelectable) return;
    this.toggle(obj);
  }

  Selectables.prototype.toggleOnlyIf = function(obj, isSelectable) {
    if (!isSelectable) return;
    this.toggleOnly(obj);
  }

  // this is likely inefficient as any digest cycle will cause this to be
  // to be re-run, walking through the array each time
  Selectables.prototype.isSelected = function(obj) {
    return this.selectables.indexOf(obj) >= 0;
  }

  Selectables.prototype.hasSelected = function() {
    return this.selectables.length >= 1;
  }

  Selectables.prototype.getSelected = function() {
    return this.selectables;
  }

  return Selectables;
}

<|endoftext|>