<commit_before>/*
   +----------------------------------------------------------------------+
   |                            HEP Random                                |
   |                          --- RandGauss ---                           |
   |                            Module File                               |
   +----------------------------------------------------------------------+
   Module defining methods for shooting gaussian distributed random values,
   given a mean (default=0) or specifying also a deviation (default=1).
   Gaussian random numbers are generated two at the time, so every
   other time shoot is called the number returned is the one generated the
   time before.
   +----------------------------------------------------------------------+
   | JavaScript                                                           |
   +----------------------------------------------------------------------+
   F. Quinonez - Created 2015-10-30
               - Geant4 File
   +----------------------------------------------------------------------+
   | C++                                                                  |
   +----------------------------------------------------------------------+
   Gabriele Cosmo - Created: 5th September 1995
                  - Added methods to shoot arrays: 28th July 1997
   J.Marraffino   - Added default arguments as attributes and
                    operator() with arguments. Introduced method normal()
                    for computation in fire(): 16th Feb 1998
   Gabriele Cosmo - Relocated static data from HepRandom: 5th Jan 1999
   M Fischler     - Copy constructor should supply right engine to HepRandom:
  		    1/26/00.
   M Fischler     - Workaround for problem of non-reproducing saveEngineStatus
  		    by saving cached gaussian.  March 2000.
   M Fischler     - Avoiding hang when file not found in restoreEngineStatus
                    12/3/04
   M Fischler     - put and get to/from streams 12/8/04
   M Fischler     - save and restore dist to streams 12/20/04
   M Fischler	  - put/get to/from streams uses pairs of ulongs when
  		    storing doubles avoid problems with precision.
  		    Similarly for saveEngineStatus and RestoreEngineStatus
  		    and for save/restore distState
  		    Care was taken that old-form output can still be read back.
  			4/14/05
*/

define( [ '../Random/JamesRandom' ], function( JamesRandom ){
  "use strict";

  function RandGauss( args ){
    this.fmean = args.mean || 0.0;
    this.fstdDev = args.stdDev || 1.0;
    this.fengine = args.engine || Object.create( JamesRandom({}) );
    this.fset = false;
    this.fnextGauss;
  }

  RandGauss.snextGauss = 0.0;
  RandGauss.sset = false;

  RandGauss.GetFlag = function(){
    return RandGauss.sset;
  };

  RandGauss.GetVal = function(){
    return RandGauss.snextGauss;
  };

  RandGauss.SetFlag = function( var value ){
    RandGauss.sset = value;
  };

  RandGauss.SetVal = function( var value ){
    RandGauss.snextValue = value;
  };

  RandGauss.Shoot = function( args ){
    var smean = args.mean || 0.0;
    var sstdDev = args.stdDev || 1.0;
    var sengine = args.engine || Object.create( JamesRandom({}) );

    // Gaussian random numbers are generated two at the time, so every other
    // time this is called we just return a number generated the time before.
    if ( GetFlag() ) {
      SetFlag( false );
      var x = GetVal();
      return x;
    }

    var r,v1,v2,fac,val; // double

    do {
      v1 = 2.0 * sengine.Flat() - 1.0;
      v2 = 2.0 * sengine.Flat() - 1.0;
      r = v1 * v1 + v2 * v2;
    } while( r > 1.0 );

    fac = Math.sqrt( -2.0 * Math.log( r ) / r );
    val = v1 * fac;
    RandGauss.SetVal( val );
    RandGaus.SetFlag( true );
    return v2 * fac;
  };

  RandGauss.ShootArray = function(){
    var ssize = args.size || 1;
    var smean = args.mean || 0.0;
    var sstdDev = args.stdDev || 1.0;
    var sengine = args.engine || Object.create( JamesRandom({}) );
    // var svect = args.vect;

    var argsShoot = { mean: smean, stdDev: sstdDev, engine: sengine };

    for( var i = 0; i < ssize; ++i ){
      args.vect.push( RandGauss.Shoot( argsShoot ) );
    }
  };

  RandGauss.prototype = {
    constructor: RandGauss,

    Fire: function(){
      return this.Normal * this.fstdDev + this.fmean;
    },

    FireArray: function( /* size of vect */ size, /* Array */ vect ){
      for( var i = 0; i < size; ++i ){
        vect.push( this.Fire() );
      }
    },

    Normal: function(){
      if( this.fset ){
        this.fset = false;
        return this.fnextGauss;
      }

      var r,v1,v2,fac,val; // double

      do {
        v1 = 2.0 * this.fengine.Flat() - 1.0;
        v2 = 2.0 * this.fengine.Flat() - 1.0;
        r = v1 * v1 + v2 * v2;
      } while( r > 1.0 );

      fac = Math.sqrt( -2.0 * Math.log( r ) / r );
      val = v1 * fac;
      this.fnextGauss = val;
      this.fset = true;
      return v2 * fac;
    }

  }
  return RandGauss;
});

<commit_msg>Typo Corrected<commit_after>/*
   +----------------------------------------------------------------------+
   |                            HEP Random                                |
   |                          --- RandGauss ---                           |
   |                            Module File                               |
   +----------------------------------------------------------------------+
   Module defining methods for shooting gaussian distributed random values,
   given a mean (default=0) or specifying also a deviation (default=1).
   Gaussian random numbers are generated two at the time, so every
   other time shoot is called the number returned is the one generated the
   time before.
   +----------------------------------------------------------------------+
   | JavaScript                                                           |
   +----------------------------------------------------------------------+
   F. Quinonez - Created 2015-10-30
               - Geant4 File
   +----------------------------------------------------------------------+
   | C++                                                                  |
   +----------------------------------------------------------------------+
   Gabriele Cosmo - Created: 5th September 1995
                  - Added methods to shoot arrays: 28th July 1997
   J.Marraffino   - Added default arguments as attributes and
                    operator() with arguments. Introduced method normal()
                    for computation in fire(): 16th Feb 1998
   Gabriele Cosmo - Relocated static data from HepRandom: 5th Jan 1999
   M Fischler     - Copy constructor should supply right engine to HepRandom:
  		    1/26/00.
   M Fischler     - Workaround for problem of non-reproducing saveEngineStatus
  		    by saving cached gaussian.  March 2000.
   M Fischler     - Avoiding hang when file not found in restoreEngineStatus
                    12/3/04
   M Fischler     - put and get to/from streams 12/8/04
   M Fischler     - save and restore dist to streams 12/20/04
   M Fischler	  - put/get to/from streams uses pairs of ulongs when
  		    storing doubles avoid problems with precision.
  		    Similarly for saveEngineStatus and RestoreEngineStatus
  		    and for save/restore distState
  		    Care was taken that old-form output can still be read back.
  			4/14/05
*/

define( [ '../Random/JamesRandom' ], function( JamesRandom ){
  "use strict";

  function RandGauss( args ){
    this.fmean = args.mean || 0.0;
    this.fstdDev = args.stdDev || 1.0;
    this.fengine = args.engine || Object.create( JamesRandom({}) );
    this.fset = false;
    this.fnextGauss;
  }

  RandGauss.snextGauss = 0.0;
  RandGauss.sset = false;

  RandGauss.GetFlag = function(){
    return RandGauss.sset;
  };

  RandGauss.GetVal = function(){
    return RandGauss.snextGauss;
  };

  RandGauss.SetFlag = function( value ){
    RandGauss.sset = value;
  };

  RandGauss.SetVal = function( value ){
    RandGauss.snextValue = value;
  };

  RandGauss.Shoot = function( args ){
    var smean = args.mean || 0.0;
    var sstdDev = args.stdDev || 1.0;
    var sengine = args.engine || Object.create( JamesRandom({}) );

    // Gaussian random numbers are generated two at the time, so every other
    // time this is called we just return a number generated the time before.
    if ( GetFlag() ) {
      SetFlag( false );
      var x = GetVal();
      return x;
    }

    var r,v1,v2,fac,val; // double

    do {
      v1 = 2.0 * sengine.Flat() - 1.0;
      v2 = 2.0 * sengine.Flat() - 1.0;
      r = v1 * v1 + v2 * v2;
    } while( r > 1.0 );

    fac = Math.sqrt( -2.0 * Math.log( r ) / r );
    val = v1 * fac;
    RandGauss.SetVal( val );
    RandGaus.SetFlag( true );
    return v2 * fac;
  };

  RandGauss.ShootArray = function(){
    var ssize = args.size || 1;
    var smean = args.mean || 0.0;
    var sstdDev = args.stdDev || 1.0;
    var sengine = args.engine || Object.create( JamesRandom({}) );
    // var svect = args.vect;

    var argsShoot = { mean: smean, stdDev: sstdDev, engine: sengine };

    for( var i = 0; i < ssize; ++i ){
      args.vect.push( RandGauss.Shoot( argsShoot ) );
    }
  };

  RandGauss.prototype = {
    constructor: RandGauss,

    Fire: function(){
      return this.Normal * this.fstdDev + this.fmean;
    },

    FireArray: function( /* size of vect */ size, /* Array */ vect ){
      for( var i = 0; i < size; ++i ){
        vect.push( this.Fire() );
      }
    },

    Normal: function(){
      if( this.fset ){
        this.fset = false;
        return this.fnextGauss;
      }

      var r,v1,v2,fac,val; // double

      do {
        v1 = 2.0 * this.fengine.Flat() - 1.0;
        v2 = 2.0 * this.fengine.Flat() - 1.0;
        r = v1 * v1 + v2 * v2;
      } while( r > 1.0 );

      fac = Math.sqrt( -2.0 * Math.log( r ) / r );
      val = v1 * fac;
      this.fnextGauss = val;
      this.fset = true;
      return v2 * fac;
    }

  }
  return RandGauss;
});

<|endoftext|>


<commit_before>function ObjectManager(universe) {
    this.universe = universe;
    this.objects = [];  // List of all available objects on map.
    this.staged = [];   // List of objects currently showed on screen.
    // List of objects needed to compute exact position of objects on screen.
    // If for example Earth is showed on screen, we need exact position of
    // Sun to compute the position of Earth. Sun is then "bound object".
    this.boundToStaged = [];
    // Parent object of all objects on screen (currently Sun).
    this.centralObject = null;
    this.ships = [];
}

ObjectManager.prototype.parseObjects = function(map) {
    var objects = {}; // tmp variable to map name:MapObject
    var key, object, obj;
    for (key in map) {
        object = map[key];
        if (object.type >= MapObject.SHIP) {
            obj = new IntelligentShip(this, key, object.type, object.texture, object.x, object.y, object.items, object.prices, object.orbit_speed, object.waypoints);
        }
        else {
            obj = new CelestialBody(this, key, object.type, object.texture, object.x, object.y, object.items, object.prices, object.orbit_a, object.orbit_b, object.orbit_speed);
        }
        this.objects[this.objects.length] = obj;
        objects[key] = obj;
        if (object.type >= MapObject.SHIP) {
            this.ships[this.ships.length] = obj;
        }
    }

    // Add parent->child relationship between objects to computer orbits
    for (key in map) {
        object = map[key];
        if (object.type >= MapObject.SHIP) {
            continue;
        }
        var center = object.orbit_center;
        if (center !== "") {
            objects[key].parentObject = objects[center];
            objects[center].childrenObjects[objects[center].childrenObjects.length] = objects[key];
        }
        else {
            this.centralObject = objects[key];
        }
    }

    this.updateObjects();
    if (this.onObjectsLoaded) this.onObjectsLoaded();
};

ObjectManager.prototype.loadObjects = function() {
    var that = this;
    var loader = new PIXI.JsonLoader("resources/map.json");
    loader.on('loaded', function(evt) {
        that.parseObjects(evt.content.content.json.map);
    });
    loader.load();
};

ObjectManager.prototype.doOrbitalMovement = function() {
    if (this.centralObject) {
        this.centralObject.doOrbitalMovement(0, 0, 0, 0);
    }
    for (var index = 0; index < this.ships.length; index++) {
        this.ships[index].doOrbitalMovement(0, 0, 0, 0);
    }
};

ObjectManager.prototype.moveObjects = function(diffX, diffY) {
    var index, obj;

    // Move the objects bound to staged objects.
    for (index = 0; index < this.boundToStaged.length; index++) {
        obj = this.boundToStaged[index];
        obj.position.x += diffX;
        obj.position.y += diffY;
    }

    // Move staged objects with the background
    for (index = 0; index < this.staged.length; index++) {
        obj = this.staged[index];
        obj.position.x += diffX;
        obj.position.y += diffY;
    }
};

ObjectManager.prototype.removeFromStage = function(obj) {
    this.staged.splice(this.staged.indexOf(obj), 1);
    obj.staged = false;
    this.universe.removeChild(obj);

    if (obj.type < MapObject.SHIP) {
        // We are removing object which still has some stagged children, so
        // this object is bound to them. Movate it to boundToStaged.
        if (obj.staggedChildren !== 0) {
            this.boundToStaged[this.boundToStaged.length] = obj;
        }

        // Decrease the "staggedChildren" of all parents of this object.
        while (obj.parentObject) {
            obj = obj.parentObject;
            obj.staggedChildren -= 1;
            // If this parent does not have any stagged children and is not
            // stagged, we can remove it from boundToStaged, because there's
            // no reason to keep it there.
            if (obj.staggedChildren === 0 && !obj.staged) {
                this.boundToStaged.splice(this.boundToStaged.indexOf(obj), 1);
            }
        }
    }
    else {
        obj.closeShips.splice(0, obj.closeShips.length);
        for (var i = 0; i < this.staged.length; i++) {
            var o = this.staged[i];
            if (o.type < MapObject.SHIP || o.name == obj.name) {
                continue;
            }

            if (obj.type === o.type) {
                continue;
            }

            for (var index = 0; index < o.closeShips.length; index++) {
                if (o.closeShips[index].name == obj.name) {
                    o.closeShips.splice(index, 1);
                    break;
                }
            }
        }
    }
};

ObjectManager.prototype.addToStage = function(obj) {
    if (obj.type >= MapObject.SHIP) {
        obj.staged = true;
        this.staged[this.staged.length] = obj;
        obj.position.x = -(obj.mapX - this.left) * Universe.MAP_POINT_SIZE;
        obj.position.y = -(obj.mapY - this.top) * Universe.MAP_POINT_SIZE;
        this.universe.addChildAt(obj, this.universe.children.length - 1);

        for (var i = 0; i < this.staged.length; i++) {
            var o = this.staged[i];
            if (o.type < MapObject.SHIP || o.name == obj.name) {
                continue;
            }

            if (obj.type === o.type) {
                continue;
            }

            o.closeShips[o.closeShips.length] = obj;
            obj.closeShips[obj.closeShips.length] = o;
        }
        return;
    }

    // We are adding object which has been in boundToStagged before, so we have
    // to remove it from boundToStagged.
    if (obj.staggedChildren !== 0) {
        this.boundToStaged.splice(this.boundToStaged.indexOf(obj), 1);
    }
    // If we are adding object which has not been bound to any object yet,
    // we have to update its coordinates
    else {
        obj.position.x = -(obj.mapX - this.left) * Universe.MAP_POINT_SIZE;
        obj.position.y = -(obj.mapY - this.top) * Universe.MAP_POINT_SIZE;
    }
    obj.staged = true;
    this.staged[this.staged.length] = obj;
    this.universe.addChildAt(obj, 0);

    // Increase the staggedChildren counter of all parents.
    while (obj.parentObject) {
        obj = obj.parentObject;
        obj.staggedChildren += 1;
        // If the parent is not in boundToStaged list, add it there.
        if (obj.staggedChildren == 1 && !obj.staged) {
            obj.position.x = -(obj.mapX - this.left) * Universe.MAP_POINT_SIZE;
            obj.position.y = -(obj.mapY - this.top) * Universe.MAP_POINT_SIZE;
            this.boundToStaged[this.boundToStaged.length] = obj;
        }
    }
};

ObjectManager.prototype.getObject = function(x, y) {
    for (var index = 0; index < this.staged.length; index++) {
        var obj = this.staged[index];
        if (x > (obj.position.x - (obj.width >> 1))
            && x < (obj.position.x - (obj.width >> 1)) + obj.width
            && y > (obj.position.y - (obj.height >> 1))
            && y < (obj.position.y - (obj.height >> 1)) + obj.height) {
            return obj;
        }
    }
    return null;
};

ObjectManager.prototype.updateObjects = function() {
    // Get the current screen borders
    this.left = ((this.universe.tilePositionX + Main.WIDTH) / Universe.MAP_POINT_SIZE) >> 0;
    this.right = ((this.universe.tilePositionX) / Universe.MAP_POINT_SIZE) >> 0;
    this.top = ((this.universe.tilePositionY + Main.HEIGHT) / Universe.MAP_POINT_SIZE) >> 0;
    this.bottom = ((this.universe.tilePositionY) / Universe.MAP_POINT_SIZE) >> 0;
    var visitedObject = null;

    for (var index = 0; index < this.objects.length; index++) {
        var obj = this.objects[index];
        // If this object is not staged, check if it is close to the screen
        // and add it to screen.
        if (!obj.staged && obj.mapX <= this.left + 18 && obj.mapX >= this.right - 18 && obj.mapY <= this.top + 18 && obj.mapY >= this.bottom - 18) {
            this.addToStage(obj);
        }
        // For staged object, remove it if it is no close
        // to screen anymore.
        else if (obj.staged && (obj.mapX > this.left + 18 || obj.mapX < this.right - 18 || obj.mapY > this.top + 18 || obj.mapY < this.bottom - 18)) {
            this.removeFromStage(obj);
        }
        // If the ship is above the object, mark object as visited.
        else if (obj.staged && obj.collides(Main.CENTER_X, Main.CENTER_Y)) {
            visitedObject = obj;
        }
    }

    return visitedObject;
};

ObjectManager.prototype.updateStaggedObjects = function() {
    var visitedObject = null;

    for (var index = 0; index < this.objects.length; index++) {
        var obj = this.objects[index];
        // If this object is not staged, check if it is close to the screen
        // and add it to screen.
        if (!obj.staged && obj.mapX <= this.left + 18 && obj.mapX >= this.right - 18 && obj.mapY <= this.top + 18 && obj.mapY >= this.bottom - 18) {
            this.addToStage(obj);
        }
        // For staged object, remove it if it is no close
        // to screen anymore.
        else if (obj.staged && (obj.mapX > this.left + 18 || obj.mapX < this.right - 18 || obj.mapY > this.top + 18 || obj.mapY < this.bottom - 18)) {
            this.removeFromStage(obj);
        }
        // If the ship is above the object, mark object as visited.
        else if (obj.staged && obj.collides(Main.CENTER_X, Main.CENTER_Y)) {
            visitedObject = obj;
        }
    }

    return visitedObject;
};

ObjectManager.prototype.reset = function() {
    for (var index = 0; index < this.objects.length; index++) {
        var obj = this.objects[index];
        if (obj.staged) {
            this.universe.removeChild(obj);
        }
        obj.reset();
    }

    if (this.centralObject) {
        this.centralObject.recountPosition();
    }

    this.staged.length = 0;
    this.boundToStaged.length = 0;
    console.log("reset");
};

ObjectManager.prototype.save = function() {
    for (var index = 0; index < this.objects.length; index++) {
        var obj = this.objects[index];
        obj.save();
    }
};

ObjectManager.prototype.load = function() {
    // Reset everything before loading, otherwise we would
    // have some objects already on screen, but on bad coordinates.
    this.reset();
    // Load all objects.
    for (var index = 0; index < this.objects.length; index++) {
        var obj = this.objects[index];
        obj.load();
    }
    // And now update them, so we have proper coordinates of the objects.
    this.updateObjects();
    if (this.centralObject) {
        this.centralObject.recountPosition();
    }
};

if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
        exports = module.exports = ObjectManager;
    }
}
<commit_msg>Enemy ships can attack our ship<commit_after>function ObjectManager(universe) {
    this.universe = universe;
    this.objects = [];  // List of all available objects on map.
    this.staged = [];   // List of objects currently showed on screen.
    // List of objects needed to compute exact position of objects on screen.
    // If for example Earth is showed on screen, we need exact position of
    // Sun to compute the position of Earth. Sun is then "bound object".
    this.boundToStaged = [];
    // Parent object of all objects on screen (currently Sun).
    this.centralObject = null;
    this.ships = [];
}

ObjectManager.prototype.parseObjects = function(map) {
    var objects = {}; // tmp variable to map name:MapObject
    var key, object, obj;
    for (key in map) {
        object = map[key];
        if (object.type >= MapObject.SHIP) {
            obj = new IntelligentShip(this, key, object.type, object.texture, object.x, object.y, object.items, object.prices, object.orbit_speed, object.waypoints);
        }
        else {
            obj = new CelestialBody(this, key, object.type, object.texture, object.x, object.y, object.items, object.prices, object.orbit_a, object.orbit_b, object.orbit_speed);
        }
        this.objects[this.objects.length] = obj;
        objects[key] = obj;
        if (object.type >= MapObject.SHIP) {
            this.ships[this.ships.length] = obj;
        }
    }

    // Add parent->child relationship between objects to computer orbits
    for (key in map) {
        object = map[key];
        if (object.type >= MapObject.SHIP) {
            continue;
        }
        var center = object.orbit_center;
        if (center !== "") {
            objects[key].parentObject = objects[center];
            objects[center].childrenObjects[objects[center].childrenObjects.length] = objects[key];
        }
        else {
            this.centralObject = objects[key];
        }
    }

    this.updateObjects();
    if (this.onObjectsLoaded) this.onObjectsLoaded();
};

ObjectManager.prototype.loadObjects = function() {
    var that = this;
    var loader = new PIXI.JsonLoader("resources/map.json");
    loader.on('loaded', function(evt) {
        that.parseObjects(evt.content.content.json.map);
    });
    loader.load();
};

ObjectManager.prototype.doOrbitalMovement = function() {
    if (this.centralObject) {
        this.centralObject.doOrbitalMovement(0, 0, 0, 0);
    }
    for (var index = 0; index < this.ships.length; index++) {
        this.ships[index].doOrbitalMovement(0, 0, 0, 0);
    }
};

ObjectManager.prototype.moveObjects = function(diffX, diffY) {
    var index, obj;

    // Move the objects bound to staged objects.
    for (index = 0; index < this.boundToStaged.length; index++) {
        obj = this.boundToStaged[index];
        obj.position.x += diffX;
        obj.position.y += diffY;
    }

    // Move staged objects with the background
    for (index = 0; index < this.staged.length; index++) {
        obj = this.staged[index];
        obj.position.x += diffX;
        obj.position.y += diffY;
    }
};

ObjectManager.prototype.removeFromStage = function(obj) {
    this.staged.splice(this.staged.indexOf(obj), 1);
    obj.staged = false;
    this.universe.removeChild(obj);

    if (obj.type < MapObject.SHIP) {
        // We are removing object which still has some stagged children, so
        // this object is bound to them. Movate it to boundToStaged.
        if (obj.staggedChildren !== 0) {
            this.boundToStaged[this.boundToStaged.length] = obj;
        }

        // Decrease the "staggedChildren" of all parents of this object.
        while (obj.parentObject) {
            obj = obj.parentObject;
            obj.staggedChildren -= 1;
            // If this parent does not have any stagged children and is not
            // stagged, we can remove it from boundToStaged, because there's
            // no reason to keep it there.
            if (obj.staggedChildren === 0 && !obj.staged) {
                this.boundToStaged.splice(this.boundToStaged.indexOf(obj), 1);
            }
        }
    }
    else {
        obj.closeShips.splice(0, obj.closeShips.length);
        for (var i = 0; i < this.staged.length; i++) {
            var o = this.staged[i];
            if (o.type < MapObject.SHIP || o.name == obj.name) {
                continue;
            }

            if (obj.type === o.type) {
                continue;
            }

            for (var index = 0; index < o.closeShips.length; index++) {
                if (o.closeShips[index].name == obj.name) {
                    o.closeShips.splice(index, 1);
                    break;
                }
            }
        }
    }
};

ObjectManager.prototype.addToStage = function(obj) {
    if (obj.type >= MapObject.SHIP) {
        obj.staged = true;
        this.staged[this.staged.length] = obj;
        obj.position.x = -(obj.mapX - this.left) * Universe.MAP_POINT_SIZE;
        obj.position.y = -(obj.mapY - this.top) * Universe.MAP_POINT_SIZE;
        this.universe.addChildAt(obj, this.universe.children.length - 1);
        if (obj.type == MapObject.ENEMY_SHIP) {
            obj.closeShips[obj.closeShips.length] = this.universe.ship;
        }

        for (var i = 0; i < this.staged.length; i++) {
            var o = this.staged[i];
            if (o.type < MapObject.SHIP || o.name == obj.name) {
                continue;
            }

            if (obj.type === o.type) {
                continue;
            }

            o.closeShips[o.closeShips.length] = obj;
            obj.closeShips[obj.closeShips.length] = o;
        }
        return;
    }

    // We are adding object which has been in boundToStagged before, so we have
    // to remove it from boundToStagged.
    if (obj.staggedChildren !== 0) {
        this.boundToStaged.splice(this.boundToStaged.indexOf(obj), 1);
    }
    // If we are adding object which has not been bound to any object yet,
    // we have to update its coordinates
    else {
        obj.position.x = -(obj.mapX - this.left) * Universe.MAP_POINT_SIZE;
        obj.position.y = -(obj.mapY - this.top) * Universe.MAP_POINT_SIZE;
    }
    obj.staged = true;
    this.staged[this.staged.length] = obj;
    this.universe.addChildAt(obj, 0);

    // Increase the staggedChildren counter of all parents.
    while (obj.parentObject) {
        obj = obj.parentObject;
        obj.staggedChildren += 1;
        // If the parent is not in boundToStaged list, add it there.
        if (obj.staggedChildren == 1 && !obj.staged) {
            obj.position.x = -(obj.mapX - this.left) * Universe.MAP_POINT_SIZE;
            obj.position.y = -(obj.mapY - this.top) * Universe.MAP_POINT_SIZE;
            this.boundToStaged[this.boundToStaged.length] = obj;
        }
    }
};

ObjectManager.prototype.getObject = function(x, y) {
    for (var index = 0; index < this.staged.length; index++) {
        var obj = this.staged[index];
        if (x > (obj.position.x - (obj.width >> 1))
            && x < (obj.position.x - (obj.width >> 1)) + obj.width
            && y > (obj.position.y - (obj.height >> 1))
            && y < (obj.position.y - (obj.height >> 1)) + obj.height) {
            return obj;
        }
    }
    return null;
};

ObjectManager.prototype.updateObjects = function() {
    // Get the current screen borders
    this.left = ((this.universe.tilePositionX + Main.WIDTH) / Universe.MAP_POINT_SIZE) >> 0;
    this.right = ((this.universe.tilePositionX) / Universe.MAP_POINT_SIZE) >> 0;
    this.top = ((this.universe.tilePositionY + Main.HEIGHT) / Universe.MAP_POINT_SIZE) >> 0;
    this.bottom = ((this.universe.tilePositionY) / Universe.MAP_POINT_SIZE) >> 0;
    var visitedObject = null;

    for (var index = 0; index < this.objects.length; index++) {
        var obj = this.objects[index];
        // If this object is not staged, check if it is close to the screen
        // and add it to screen.
        if (!obj.staged && obj.mapX <= this.left + 18 && obj.mapX >= this.right - 18 && obj.mapY <= this.top + 18 && obj.mapY >= this.bottom - 18) {
            this.addToStage(obj);
        }
        // For staged object, remove it if it is no close
        // to screen anymore.
        else if (obj.staged && (obj.mapX > this.left + 18 || obj.mapX < this.right - 18 || obj.mapY > this.top + 18 || obj.mapY < this.bottom - 18)) {
            this.removeFromStage(obj);
        }
        // If the ship is above the object, mark object as visited.
        else if (obj.staged && obj.collides(Main.CENTER_X, Main.CENTER_Y)) {
            visitedObject = obj;
        }
    }

    return visitedObject;
};

ObjectManager.prototype.updateStaggedObjects = function() {
    var visitedObject = null;

    for (var index = 0; index < this.objects.length; index++) {
        var obj = this.objects[index];
        // If this object is not staged, check if it is close to the screen
        // and add it to screen.
        if (!obj.staged && obj.mapX <= this.left + 18 && obj.mapX >= this.right - 18 && obj.mapY <= this.top + 18 && obj.mapY >= this.bottom - 18) {
            this.addToStage(obj);
        }
        // For staged object, remove it if it is no close
        // to screen anymore.
        else if (obj.staged && (obj.mapX > this.left + 18 || obj.mapX < this.right - 18 || obj.mapY > this.top + 18 || obj.mapY < this.bottom - 18)) {
            this.removeFromStage(obj);
        }
        // If the ship is above the object, mark object as visited.
        else if (obj.staged && obj.collides(Main.CENTER_X, Main.CENTER_Y)) {
            visitedObject = obj;
        }
    }

    return visitedObject;
};

ObjectManager.prototype.reset = function() {
    for (var index = 0; index < this.objects.length; index++) {
        var obj = this.objects[index];
        if (obj.staged) {
            this.universe.removeChild(obj);
        }
        obj.reset();
    }

    if (this.centralObject) {
        this.centralObject.recountPosition();
    }

    this.staged.length = 0;
    this.boundToStaged.length = 0;
    console.log("reset");
};

ObjectManager.prototype.save = function() {
    for (var index = 0; index < this.objects.length; index++) {
        var obj = this.objects[index];
        obj.save();
    }
};

ObjectManager.prototype.load = function() {
    // Reset everything before loading, otherwise we would
    // have some objects already on screen, but on bad coordinates.
    this.reset();
    // Load all objects.
    for (var index = 0; index < this.objects.length; index++) {
        var obj = this.objects[index];
        obj.load();
    }
    // And now update them, so we have proper coordinates of the objects.
    this.updateObjects();
    if (this.centralObject) {
        this.centralObject.recountPosition();
    }
};

if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
        exports = module.exports = ObjectManager;
    }
}
<|endoftext|>


<commit_before>// @flow
import express from 'express'
import compression from 'compression'
import path from 'path'

import bodyParser from 'body-parser'
import session from 'express-session'
import errorhandler from 'errorhandler'
import cors from 'cors'

import logger from 'morgan'
import methodOverride from 'method-override'
import mongoose from 'mongoose'
import bluebird from 'bluebird'

import routes from './routes'
import config from './config'

const startServer = (cfg: Object) => {
  const app = express()

  // Configure express middleware
  app.use(cors())
  app.use(logger('dev'))
  app.use(bodyParser.urlencoded({ extended: false }))
  app.use(bodyParser.json())
  app.use(methodOverride())
  app.use(compression())
  app.use(express.static(path.resolve(__dirname, 'public')))
  app.use(session({ secret: 'conduit', cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }))

  const options = { promiseLibrary: bluebird, safe: true }
  mongoose.connect(config.db.url, options)

  app.use(routes)

  if (cfg.production) {
    app.use(errorhandler())
  }

  // catch 404 and forward to error handler
  app.use((req, res, next) => {
    const err : Object = new Error('Not Found')
    err.status = 404
    next(err)
  })

  // error handlers

  // development error handler
  // will print stacktrace
  if (!cfg.production) {
    app.use((err, req, res) => {
      // eslint-disable-next-line no-console
      console.log(err.stack)

      res.status(err.status || 500)

      res.json({
        errors: {
          message: err.message,
          error: err,
        },
      })
    })
  }

  // production error handler
  // no stacktraces leaked to user
  app.use((err, req, res) => {
    res.status(err.status || 500)
    res.json({
      errors: {
        message: err.message,
        error: {},
      },
    })
  })

  return new Promise((resolve) => {
    const server = app.listen(cfg.server.port, () => {
      // eslint-disable-next-line no-console
      console.log(`Server is listening on port: ${cfg.server.port}`)
      resolve(server)
    })
  })
}

if (require.main === module) {
  startServer(config)
}

export default startServer
<commit_msg>Remove DB connection out of startServer.<commit_after>// @flow
import express from 'express'
import compression from 'compression'
import path from 'path'

import bodyParser from 'body-parser'
import session from 'express-session'
import errorhandler from 'errorhandler'
import cors from 'cors'

import logger from 'morgan'
import methodOverride from 'method-override'
import mongoose from 'mongoose'
import BPromise from 'bluebird'

import routes from './routes'
import config from './config'

const startServer = (cfg: Object) => {
  const app = express()

  // Configure express middleware
  app.use(cors())
  app.use(logger('dev'))
  app.use(bodyParser.urlencoded({ extended: false }))
  app.use(bodyParser.json())
  app.use(methodOverride())
  app.use(compression())
  app.use(express.static(path.resolve(__dirname, 'public')))
  app.use(session({ secret: 'conduit', cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }))

  app.use(routes)

  if (cfg.production) {
    app.use(errorhandler())
  }

  // catch 404 and forward to error handler
  app.use((req, res, next) => {
    const err : Object = new Error('Not Found')
    err.status = 404
    next(err)
  })

  // error handlers

  // development error handler
  // will print stacktrace
  if (!cfg.production) {
    app.use((err, req, res) => {
      // eslint-disable-next-line no-console
      console.log(err.stack)

      res.status(err.status || 500)

      res.json({
        errors: {
          message: err.message,
          error: err,
        },
      })
    })
  }

  // production error handler
  // no stacktraces leaked to user
  app.use((err, req, res) => {
    res.status(err.status || 500)
    res.json({
      errors: {
        message: err.message,
        error: {},
      },
    })
  })

  return new BPromise((resolve) => {
    const server = app.listen(cfg.server.port, () => {
      // eslint-disable-next-line no-console
      console.log(`Server is listening on port: ${cfg.server.port}`)
      resolve(server)
    })
  })
}

if (require.main === module) {
  const options = { promiseLibrary: BPromise, safe: true }
  mongoose.connect(config.db.url, options)
  startServer(config)
}

export default startServer
<|endoftext|>


<commit_before>'use strict';

const ccxt = require ('ccxt')
    , {
        sleep,
        isNode,
        milliseconds,
    } = ccxt
    , Client = require ('./Client')
    , WebSocket = isNode ? require ('ws') : window.WebSocket

module.exports = class WsClient extends Client {

    createWebsocket () {
        console.log (new Date (), 'connecting...')
        this.connectionStarted = milliseconds ()
        this.setConnectionTimeout ()
        this.connection = new WebSocket (this.url, this.protocols, this.options)
        this.connection
            .on ('open', this.onOpen.bind (this))
            .on ('ping', this.onPing.bind (this))
            .on ('pong', this.onPong.bind (this))
            .on ('error', this.onError.bind (this))
            .on ('close', this.onClose.bind (this))
            .on ('upgrade', this.onUpgrade.bind (this))
            .on ('message', this.onMessage.bind (this))
        // this.connection.terminate () // debugging
        // this.connection.close () // debugging
    }

    connect (backoffDelay = 0) {
        if ((this.connection.readyState !== WebSocket.OPEN) && (this.connection.readyState !== WebSocket.CONNECTING)) {
            // prevent multiple calls overwriting each other
            this.connection.readyState = WebSocket.CONNECTING
            // exponential backoff for consequent ws connections if necessary
            if (backoffDelay) {
                sleep (backoffDelay).then (this.createWebsocket.bind (this))
            } else {
                this.createWebsocket ()
            }
        }
        return this.connected
    }

    isOpen () {
        return (this.connection.readyState === WebSocket.OPEN)
    }
}
<commit_msg>WsClient createConnection<commit_after>'use strict';

const ccxt = require ('ccxt')
    , {
        sleep,
        isNode,
        milliseconds,
    } = ccxt
    , Client = require ('./Client')
    , WebSocket = isNode ? require ('ws') : window.WebSocket

module.exports = class WsClient extends Client {

    createConnection () {
        console.log (new Date (), 'connecting...')
        this.connectionStarted = milliseconds ()
        this.setConnectionTimeout ()
        this.connection = new WebSocket (this.url, this.protocols, this.options)
        this.connection
            .on ('open', this.onOpen.bind (this))
            .on ('ping', this.onPing.bind (this))
            .on ('pong', this.onPong.bind (this))
            .on ('error', this.onError.bind (this))
            .on ('close', this.onClose.bind (this))
            .on ('upgrade', this.onUpgrade.bind (this))
            .on ('message', this.onMessage.bind (this))
        // this.connection.terminate () // debugging
        // this.connection.close () // debugging
    }

    connect (backoffDelay = 0) {
        if ((this.connection.readyState !== WebSocket.OPEN) && (this.connection.readyState !== WebSocket.CONNECTING)) {
            // prevent multiple calls overwriting each other
            this.connection.readyState = WebSocket.CONNECTING
            // exponential backoff for consequent ws connections if necessary
            if (backoffDelay) {
                sleep (backoffDelay).then (this.createConnection.bind (this))
            } else {
                this.createConnection ()
            }
        }
        return this.connected
    }

    isOpen () {
        return (this.connection.readyState === WebSocket.OPEN)
    }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
var bluebee = bluebee || (function(){
	/////////////////////////////////////////////////////////////////////////////////////////////////

	var
	////=============================================================================================
	// Requirements

		sys		= require( "sys" ),
		fs		= require( "fs" ),
		socket		= require( "socket.io" ),
		EventEmitter	= require( "events" ).EventEmitter,

	////=============================================================================================
	// Propertys

		debug	= true;
		path	= process.cwd();

		system	= {},						//Some System ressources
		core	= {},						//Holds all Core-Modules
		modules	= {},						//Holds all feature-modules

	////=============================================================================================
	// Methods

		////-----------------------------------------------------------------------------------------
		// Initializer ( Constructor )
		init = function(){
			switch( process.argv[ 2 ] ){
				case "start":
					// Output
					log( "BlueBee is starting now", "prompt" );

					//Handles the process-events
					processHandler();

					//Writes the pid into a file, and gives a callback for success, and fail
					writePid(
						function(){
							loadConfig( loadCore );
						}, function(){
							log( "BlueBee is already started")
					});
					break;
				case "stop":
					log( "BlueBee is stopping now", "prompt" );
					break;
				case "restart":
					log( "BlueBee is restarting now", "prompt" );
					break;
				case "status" :
					log( "BlueBee status is: ", "prompt" );
					break;
				case "install" :
					log( "BlueBee will now be installed", "prompt" );
					loadConfig( function(){
						var couch			= new require( bb.path + "/server/core/couchdb.js" );
						couch.module.prototype		= new EventEmitter();
						bb.core[ "couchdb" ]		= new couch.module();
						bb.core[ "couchdb" ].bb		= bb;
						bb.core[ "couchdb" ].main( function(){
							bb.core[ "couchdb" ].install();
						} );

					});
					break;
				default:
					log( "Usage: bluebee {start|stop|restart|status}", "prompt" );
			}

		};

		////-----------------------------------------------------------------------------------------
		//Loads the config
		loadConfig = function( cb ){
			//First the config
			var conf			= new require( bb.path + "/server/core/config.js" );
			conf.module.prototype		= new EventEmitter();
			bb.core[ "config" ]		= new conf.module();
			bb.core[ "config" ].bb		= bb;
			bb.core[ "config" ].main( cb );
		}

		////-----------------------------------------------------------------------------------------
		//Loads all the Core-Ressources
		loadCore = function(){
			loader( bb.path + "/server/core", bb.core, loadModules );
		};

		////-----------------------------------------------------------------------------------------
		//Loads all the Modules
		loadModules = function(){
			loader( bb.path + "/server/modules", bb.modules, bb.core.http.httpServer);
		};

		////-----------------------------------------------------------------------------------------
		//The loader itself
	        loader = function( path, modulesObj, cb ){
			fs.readdir( path, function( err, files ){
				if( err ){
					log( err, "error" );
				} else {
					var i = 0;
					var v = 0;

					files.forEach( function( file ){//Counts the modules
						var moduleName			= file.split( "." )[ 0 ];
						if( file[ 0 ] != "." && !modulesObj[ moduleName ] ){
							i++;
						}
					});
					files.forEach( function( file ){
						var moduleName			= file.split( "." )[ 0 ];

						if( file[ 0 ] != "." && !modulesObj[ moduleName ]){
							try{//initializing of the module
								var mod				= new require( path + "/" + file );
								mod.module.prototype		= new EventEmitter();
								modulesObj[ moduleName ]	= new mod.module();
								modulesObj[ moduleName ].bb	= bb;
							} catch( e ) {
								log( file + ": " + e, "error" );
								log( "Module " + file + " crashed, bluebee is shutting down.", "prompt" );
								//#ToDo shutdown of bluebee
							}

							modulesObj[ moduleName ].main( function(){
								v++;
								if( i === v ){ //Modules are loaded - trigger the callback
									cb();
								}
							});
						}
					});
				}
			});
		};

		////-----------------------------------------------------------------------------------------
		// loadModule
		loadModule = function( type, name ){//currently not used
			var moduleArr;
			if( type == "core" ){
				moduleArr = bb.core;
			} else if( type == "modules" ){
				moduleArr = bb.modules;
			} else {
				throw "loadModule: undefined type";
			}
			var mod				= new require( bb.path + "/server/" + type + "/" + name + ".js" );
			mod.module.prototype		= new EventEmitter();
			moduleArr[ name ]		= new mod.module();
			moduleArr[ name ].bb		= bb;
			moduleArr[ name ].main( cb );
		]

		////-----------------------------------------------------------------------------------------
		// Process handler
		processHandler = function(){
			process.on( "uncaughtException", function ( err ) {
				log( err, "error" );
			});

			process.on( "exit", function(){
				log( "Im stopping now, right?", "prompt" );
			});

			process.on( "SIGKILL", function(){
				process.exit();
			});

			process.on( "SIGTERM", function(){
				process.exit();
			});

			process.on('SIGINT', function () {//Handles shutdown
				process.exit();
			});
		},

		////-----------------------------------------------------------------------------------------
		// Writes the Pid
		writePid = function( cbSuccess, cbFail ){
			cbSuccess(); //ToDo the real handling, and deactivation if in debug-mode
		},

		////-----------------------------------------------------------------------------------------
		// Output Messages
		log = function( content, type ){
			if( type == "error" ){
				//Safe to file #ToDo

				//Print if debug-mode
				if( bb.debug ){
					console.log( "---------------------------------------------------------------" );
					console.log( "ERROR - " + new Date() ); //#ToDo change the format
					console.log( content );
					console.trace(); //#ToDo delete last trace-entry (its this one)
					console.log( "---------------------------------------------------------------" );
				}
			} else if( type == "access" ){
				//Safe to file #ToDo

				//Print if debug-mode
				if( bb.debug ){
					console.log( "ACCESS:" );
					console.log( content );
				}
			} else if( type == "prompt" ){
				//Prints it directly to the console
				sys.puts( content );
			} else if( bb.debug ){
				//Print if debug-mode #ToDo safe to file
				console.log( content );
			}
        };

	bb	= { core: core, modules: modules, log: log, path: path, debug: debug, version: '0.0.1' };//Central object, which is assigned to all modules

	/////////////////////////////////////////////////////////////////////////////////////////////////

	////=============================================================================================
	// Call the Constructor

	init();

	////=============================================================================================
	// Public API

	return {
	};

	/////////////////////////////////////////////////////////////////////////////////////////////////
})();
<commit_msg>oups, made a syntaxerror<commit_after>#!/usr/bin/env node
var bluebee = bluebee || (function(){
	/////////////////////////////////////////////////////////////////////////////////////////////////

	var
	////=============================================================================================
	// Requirements

		sys		= require( "sys" ),
		fs		= require( "fs" ),
		socket		= require( "socket.io" ),
		EventEmitter	= require( "events" ).EventEmitter,

	////=============================================================================================
	// Propertys

		debug	= true;
		path	= process.cwd();

		system	= {},						//Some System ressources
		core	= {},						//Holds all Core-Modules
		modules	= {},						//Holds all feature-modules

	////=============================================================================================
	// Methods

		////-----------------------------------------------------------------------------------------
		// Initializer ( Constructor )
		init = function(){
			switch( process.argv[ 2 ] ){
				case "start":
					// Output
					log( "BlueBee is starting now", "prompt" );

					//Handles the process-events
					processHandler();

					//Writes the pid into a file, and gives a callback for success, and fail
					writePid(
						function(){
							loadConfig( loadCore );
						}, function(){
							log( "BlueBee is already started")
					});
					break;
				case "stop":
					log( "BlueBee is stopping now", "prompt" );
					break;
				case "restart":
					log( "BlueBee is restarting now", "prompt" );
					break;
				case "status" :
					log( "BlueBee status is: ", "prompt" );
					break;
				case "install" :
					log( "BlueBee will now be installed", "prompt" );
					loadConfig( function(){
						var couch			= new require( bb.path + "/server/core/couchdb.js" );
						couch.module.prototype		= new EventEmitter();
						bb.core[ "couchdb" ]		= new couch.module();
						bb.core[ "couchdb" ].bb		= bb;
						bb.core[ "couchdb" ].main( function(){
							bb.core[ "couchdb" ].install();
						} );

					});
					break;
				default:
					log( "Usage: bluebee {start|stop|restart|status}", "prompt" );
			}

		};

		////-----------------------------------------------------------------------------------------
		//Loads the config
		loadConfig = function( cb ){
			//First the config
			var conf			= new require( bb.path + "/server/core/config.js" );
			conf.module.prototype		= new EventEmitter();
			bb.core[ "config" ]		= new conf.module();
			bb.core[ "config" ].bb		= bb;
			bb.core[ "config" ].main( cb );
		}

		////-----------------------------------------------------------------------------------------
		//Loads all the Core-Ressources
		loadCore = function(){
			loader( bb.path + "/server/core", bb.core, loadModules );
		};

		////-----------------------------------------------------------------------------------------
		//Loads all the Modules
		loadModules = function(){
			loader( bb.path + "/server/modules", bb.modules, bb.core.http.httpServer);
		};

		////-----------------------------------------------------------------------------------------
		//The loader itself
	        loader = function( path, modulesObj, cb ){
			fs.readdir( path, function( err, files ){
				if( err ){
					log( err, "error" );
				} else {
					var i = 0;
					var v = 0;

					files.forEach( function( file ){//Counts the modules
						var moduleName			= file.split( "." )[ 0 ];
						if( file[ 0 ] != "." && !modulesObj[ moduleName ] ){
							i++;
						}
					});
					files.forEach( function( file ){
						var moduleName			= file.split( "." )[ 0 ];

						if( file[ 0 ] != "." && !modulesObj[ moduleName ]){
							try{//initializing of the module
								var mod				= new require( path + "/" + file );
								mod.module.prototype		= new EventEmitter();
								modulesObj[ moduleName ]	= new mod.module();
								modulesObj[ moduleName ].bb	= bb;
							} catch( e ) {
								log( file + ": " + e, "error" );
								log( "Module " + file + " crashed, bluebee is shutting down.", "prompt" );
								//#ToDo shutdown of bluebee
							}

							modulesObj[ moduleName ].main( function(){
								v++;
								if( i === v ){ //Modules are loaded - trigger the callback
									cb();
								}
							});
						}
					});
				}
			});
		};

		////-----------------------------------------------------------------------------------------
		// loadModule
		loadModule = function( type, name ){//currently not used
			var moduleArr;
			if( type == "core" ){
				moduleArr = bb.core;
			} else if( type == "modules" ){
				moduleArr = bb.modules;
			} else {
				throw "loadModule: undefined type";
			}
			var mod				= new require( bb.path + "/server/" + type + "/" + name + ".js" );
			mod.module.prototype		= new EventEmitter();
			moduleArr[ name ]		= new mod.module();
			moduleArr[ name ].bb		= bb;
			moduleArr[ name ].main( cb );
		}

		////-----------------------------------------------------------------------------------------
		// Process handler
		processHandler = function(){
			process.on( "uncaughtException", function ( err ) {
				log( err, "error" );
			});

			process.on( "exit", function(){
				log( "Im stopping now, right?", "prompt" );
			});

			process.on( "SIGKILL", function(){
				process.exit();
			});

			process.on( "SIGTERM", function(){
				process.exit();
			});

			process.on('SIGINT', function () {//Handles shutdown
				process.exit();
			});
		},

		////-----------------------------------------------------------------------------------------
		// Writes the Pid
		writePid = function( cbSuccess, cbFail ){
			cbSuccess(); //ToDo the real handling, and deactivation if in debug-mode
		},

		////-----------------------------------------------------------------------------------------
		// Output Messages
		log = function( content, type ){
			if( type == "error" ){
				//Safe to file #ToDo

				//Print if debug-mode
				if( bb.debug ){
					console.log( "---------------------------------------------------------------" );
					console.log( "ERROR - " + new Date() ); //#ToDo change the format
					console.log( content );
					console.trace(); //#ToDo delete last trace-entry (its this one)
					console.log( "---------------------------------------------------------------" );
				}
			} else if( type == "access" ){
				//Safe to file #ToDo

				//Print if debug-mode
				if( bb.debug ){
					console.log( "ACCESS:" );
					console.log( content );
				}
			} else if( type == "prompt" ){
				//Prints it directly to the console
				sys.puts( content );
			} else if( bb.debug ){
				//Print if debug-mode #ToDo safe to file
				console.log( content );
			}
        };

	bb	= { core: core, modules: modules, log: log, path: path, debug: debug, version: '0.0.1' };//Central object, which is assigned to all modules

	/////////////////////////////////////////////////////////////////////////////////////////////////

	////=============================================================================================
	// Call the Constructor

	init();

	////=============================================================================================
	// Public API

	return {
	};

	/////////////////////////////////////////////////////////////////////////////////////////////////
})();
<|endoftext|>


<commit_before>'use strict'

var create_plane = function(width, height, position, rotation) {
    var material = new THREE.MeshBasicMaterial({
        color: 0x000000,
        opacity: 0.0,
        side: THREE.DoubleSide
    })
    var geometry = new THREE.PlaneGeometry(width, height)
    var mesh = new THREE.Mesh(geometry, material)
    mesh.position.x = position.x
    mesh.position.y = position.y
    mesh.position.z = position.z
    mesh.rotation.x = rotation.x
    mesh.rotation.y = rotation.y
    mesh.rotation.z = rotation.z
    return mesh
}

var create_css_page = function(width, height, position, rotation, text) {
    // Create the CSS object.
    var html = '

' + text + '

'
    var div = document.createElement('div')
    div.innerHTML = html
    var css_object = new THREE.CSS3DObject(div)
    css_object.position.x = position.x
    css_object.position.y = position.y
    css_object.position.z = position.z
    css_object.rotation.x = rotation.x
    css_object.rotation.y = rotation.y
    css_object.rotation.z = rotation.z

    return css_object
}

var renderer_api  = new RendererAPI()
if (renderer_api.is_webgl_enabled() === false) {
    console.log('WebGL is not enabled!')
    throw new Error('WebGL is not enabled!')
}
var stats_api = new StatsAPI()
var scene = new THREE.Scene()
var camera   = new THREE.PerspectiveCamera(renderer_api.field_of_view, renderer_api.aspect_ratio, renderer_api.near_clipping, renderer_api.far_clipping)
renderer_api.set_camera(camera)

// Going to try to create a plane here.
var plane_geometry = new THREE.PlaneGeometry(2000, 2000, 100, 100)
plane_geometry.applyMatrix(new THREE.Matrix4().makeRotationX(- Math.PI / 2))
//var plane_material = new THREE.MeshBasicMaterial({color: 0x0000ff})
var plane_material = new THREE.MeshLambertMaterial({color: 0xccffcc, side: THREE.FrontSide, wireframe: false})
var plane_mesh     = new THREE.Mesh(plane_geometry, plane_material)
scene.add(plane_mesh)
var ground_normal = plane_mesh.normal
console.log('GROUND NORMAL IS : ' + ground_normal)

var fps_controls = new FPSControls(camera, ground_normal)

scene.add(fps_controls.get_object())

var pointer_lock_api = new PointerLockAPI(fps_controls)

var geometry = new THREE.BoxGeometry(5,5, 5)
//var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })
var material = new THREE.MeshLambertMaterial({ color: 0x00ff00 })
var cube 	 = new THREE.Mesh(geometry, material)
//scene.add(cube)

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

//var css_renderer_api = new CSSRendererAPI()

//var cssScene = new THREE.Scene()

var math_formulas = document.getElementById('math_formulas')

var element = document.createElement('div')
element.innerHTML = 'Plain text inside a div.'
element.className = 'three-div'

// Create a test plane.
var p_width = 100
var p_height = 100
var p_position = new THREE.Vector3(20, 30, -30)
var p_rotation = new THREE.Vector3(0, 0, 0)
var test_plane = create_plane(p_width, p_height, p_position, p_rotation)
//scene.add(test_plane)
//var test_css_plane = create_css_page(p_width, p_height, p_position, p_rotation, '`b^x=c^(xlog_cb)`')
//cssScene.add(test_css_plane)

// Second test plane.
var p_width2 = 200
var p_height2 = 200
var p_position2 = new THREE.Vector3(20, 30, -60)
var p_rotation2 = new THREE.Vector3(0, 0, 0)
var test_plane2 = create_plane(p_width2, p_height2, p_position2, p_rotation2)
//scene.add(test_plane2)
//var test_css_plane2 = create_css_page(p_width2, p_height2, p_position2, p_rotation2, '`log_bx=(log_cx)/(log_cb)`')
//cssScene.add(test_css_plane2)

//var light4 = new THREE.HemisphereLight(0xffbf67, 0x15c6ff, .3)
//scene.add(light4)

//scene.add(css_object)
//cssScene.add(css_object)

// @@@@
//css_renderer_api.renderer.domElement.appendChild(renderer_api.renderer.domElement)
//document.body.appendChild(css_renderer_api.renderer.domElement)
// @@@@
document.body.appendChild(renderer_api.renderer.domElement)

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

// Add lights.
//var ambiColor = '#cbe7ff'
//var ambientLight = new THREE.AmbientLight(ambiColor, .2)
//scene.add(ambientLight)
/*
var light = new THREE.DirectionalLight( 0xffffff, 1.5 )
light.position.set(1, 1, 1 )
scene.add(light)s

var light2 = new THREE.DirectionalLight( 0xffffff, 0.75 )
light2.position.set(-1, - 0.5, -1)
scene.add(light2)
*/

var data_display = new DataDisplay(fps_controls)

var light3 = new THREE.PointLight(0xccffcc, 1, 1000)
light3.position.set(5, 15, 5)
scene.add(light3)

//var shader_api = new ShaderAPI(renderer_api, scene, camera)

//

var world  = new World(scene)
var client = new Client(world)

setInterval(function() {
    var data = fps_controls.get_position().x + '|' + fps_controls.get_position().z
    client.send_data(data)
}, 100)

var loader = new THREE.FontLoader()
loader.load('/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/font/helvetiker_regular.typeface.json', function(tex){
    var  textGeo = new THREE.TextGeometry('Test', {
        size: 100,
        height: 5,
        curveSegments: 2,
        font: tex
    })
    var  color = new THREE.Color()
    color.setRGB(50, 50, 50)
    var  textMaterial = new THREE.MeshLambertMaterial({ color: color })
    var  text = new THREE.Mesh(textGeo, textMaterial)
    scene.add(text)
})
//

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

var text_position = new THREE.Vector3(40, 40, 100)
var text_rotation = new THREE.Vector3(0, 0, 0)
var text_plane = new PlaneAPI(200, 50, text_position, text_rotation)
text_plane.create_dynamic_text('Hello Worlddddddddddd', scene, renderer_api.renderer)

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

var previous_time = performance.now()

var animate = function () {
    //shader_api.render()

    requestAnimationFrame(animate)

    stats_api.pre_render()

    cube.rotation.x += 0.01
    cube.rotation.y += 0.01

    var time = performance.now()
    var delta = (time - previous_time) / 1000

    fps_controls.physics(delta)
    data_display.update()

    renderer_api.renderer.render(scene, camera)
    //css_renderer_api.renderer.render(cssScene, camera)

    stats_api.post_render()

    previous_time = time
}

animate()

<commit_msg>General updating 10<commit_after>'use strict'

var create_plane = function(width, height, position, rotation) {
    var material = new THREE.MeshBasicMaterial({
        color: 0x000000,
        opacity: 0.0,
        side: THREE.DoubleSide
    })
    var geometry = new THREE.PlaneGeometry(width, height)
    var mesh = new THREE.Mesh(geometry, material)
    mesh.position.x = position.x
    mesh.position.y = position.y
    mesh.position.z = position.z
    mesh.rotation.x = rotation.x
    mesh.rotation.y = rotation.y
    mesh.rotation.z = rotation.z
    return mesh
}

var create_css_page = function(width, height, position, rotation, text) {
    // Create the CSS object.
    var html = '

' + text + '

'
    var div = document.createElement('div')
    div.innerHTML = html
    var css_object = new THREE.CSS3DObject(div)
    css_object.position.x = position.x
    css_object.position.y = position.y
    css_object.position.z = position.z
    css_object.rotation.x = rotation.x
    css_object.rotation.y = rotation.y
    css_object.rotation.z = rotation.z

    return css_object
}

var renderer_api  = new RendererAPI()
if (renderer_api.is_webgl_enabled() === false) {
    console.log('WebGL is not enabled!')
    throw new Error('WebGL is not enabled!')
}
var stats_api = new StatsAPI()
var scene = new THREE.Scene()
var camera   = new THREE.PerspectiveCamera(renderer_api.field_of_view, renderer_api.aspect_ratio, renderer_api.near_clipping, renderer_api.far_clipping)
renderer_api.set_camera(camera)

// Going to try to create a plane here.
var plane_geometry = new THREE.PlaneGeometry(2000, 2000, 100, 100)
plane_geometry.applyMatrix(new THREE.Matrix4().makeRotationX(- Math.PI / 2))
//var plane_material = new THREE.MeshBasicMaterial({color: 0x0000ff})
var plane_material = new THREE.MeshLambertMaterial({color: 0xccffcc, side: THREE.FrontSide, wireframe: false})
var plane_mesh     = new THREE.Mesh(plane_geometry, plane_material)
scene.add(plane_mesh)
//var ground_normal = plane_mesh.normal
var ground_normal = Vector3(0, 1, 0)
console.log('GROUND NORMAL IS : ' + ground_normal)

var fps_controls = new FPSControls(camera, ground_normal)

scene.add(fps_controls.get_object())

var pointer_lock_api = new PointerLockAPI(fps_controls)

var geometry = new THREE.BoxGeometry(5,5, 5)
//var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })
var material = new THREE.MeshLambertMaterial({ color: 0x00ff00 })
var cube 	 = new THREE.Mesh(geometry, material)
//scene.add(cube)

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

//var css_renderer_api = new CSSRendererAPI()

//var cssScene = new THREE.Scene()

var math_formulas = document.getElementById('math_formulas')

var element = document.createElement('div')
element.innerHTML = 'Plain text inside a div.'
element.className = 'three-div'

// Create a test plane.
var p_width = 100
var p_height = 100
var p_position = new THREE.Vector3(20, 30, -30)
var p_rotation = new THREE.Vector3(0, 0, 0)
var test_plane = create_plane(p_width, p_height, p_position, p_rotation)
//scene.add(test_plane)
//var test_css_plane = create_css_page(p_width, p_height, p_position, p_rotation, '`b^x=c^(xlog_cb)`')
//cssScene.add(test_css_plane)

// Second test plane.
var p_width2 = 200
var p_height2 = 200
var p_position2 = new THREE.Vector3(20, 30, -60)
var p_rotation2 = new THREE.Vector3(0, 0, 0)
var test_plane2 = create_plane(p_width2, p_height2, p_position2, p_rotation2)
//scene.add(test_plane2)
//var test_css_plane2 = create_css_page(p_width2, p_height2, p_position2, p_rotation2, '`log_bx=(log_cx)/(log_cb)`')
//cssScene.add(test_css_plane2)

//var light4 = new THREE.HemisphereLight(0xffbf67, 0x15c6ff, .3)
//scene.add(light4)

//scene.add(css_object)
//cssScene.add(css_object)

// @@@@
//css_renderer_api.renderer.domElement.appendChild(renderer_api.renderer.domElement)
//document.body.appendChild(css_renderer_api.renderer.domElement)
// @@@@
document.body.appendChild(renderer_api.renderer.domElement)

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

// Add lights.
//var ambiColor = '#cbe7ff'
//var ambientLight = new THREE.AmbientLight(ambiColor, .2)
//scene.add(ambientLight)
/*
var light = new THREE.DirectionalLight( 0xffffff, 1.5 )
light.position.set(1, 1, 1 )
scene.add(light)s

var light2 = new THREE.DirectionalLight( 0xffffff, 0.75 )
light2.position.set(-1, - 0.5, -1)
scene.add(light2)
*/

var data_display = new DataDisplay(fps_controls)

var light3 = new THREE.PointLight(0xccffcc, 1, 1000)
light3.position.set(5, 15, 5)
scene.add(light3)

//var shader_api = new ShaderAPI(renderer_api, scene, camera)

//

var world  = new World(scene)
var client = new Client(world)

setInterval(function() {
    var data = fps_controls.get_position().x + '|' + fps_controls.get_position().z
    client.send_data(data)
}, 100)

var loader = new THREE.FontLoader()
loader.load('/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/font/helvetiker_regular.typeface.json', function(tex){
    var  textGeo = new THREE.TextGeometry('Test', {
        size: 100,
        height: 5,
        curveSegments: 2,
        font: tex
    })
    var  color = new THREE.Color()
    color.setRGB(50, 50, 50)
    var  textMaterial = new THREE.MeshLambertMaterial({ color: color })
    var  text = new THREE.Mesh(textGeo, textMaterial)
    scene.add(text)
})
//

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

var text_position = new THREE.Vector3(40, 40, 100)
var text_rotation = new THREE.Vector3(0, 0, 0)
var text_plane = new PlaneAPI(200, 50, text_position, text_rotation)
text_plane.create_dynamic_text('Hello Worlddddddddddd', scene, renderer_api.renderer)

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

var previous_time = performance.now()

var animate = function () {
    //shader_api.render()

    requestAnimationFrame(animate)

    stats_api.pre_render()

    cube.rotation.x += 0.01
    cube.rotation.y += 0.01

    var time = performance.now()
    var delta = (time - previous_time) / 1000

    fps_controls.physics(delta)
    data_display.update()

    renderer_api.renderer.render(scene, camera)
    //css_renderer_api.renderer.render(cssScene, camera)

    stats_api.post_render()

    previous_time = time
}

animate()

<|endoftext|>


<commit_before>'use strict';

const Joi = require('joi');
const Randomstring = require('randomstring');

exports.register = function (server, options, next) {

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply.view('index');
        }
    });

    server.route({
        method: 'POST',
        path: '/generate',
        handler: function (request, reply) {

            const models = request.server.plugins['hapi-sequelize'].db.sequelize.models;

            // Figure out what's longer, 50% of the URL's length, or our minimum length of 50 characters.
            const potentialLength = request.payload.url.length * 1.5;
            const newLength = parseInt(potentialLength > 50 ? potentialLength : 50);

            const lengthedUrl = Randomstring.generate(newLength);

            // First check and see if the URL already exists in the database.
            models.Url.findOrCreate({
                where: { original: request.payload.url },
                defaults: { lengthened: lengthedUrl }
            })
                .spread((url, created) => {

                    return reply(url);
                })
                .catch((err) => {

                    return reply(err);
                });
        },
        config: {
            validate: {
                payload: {
                    url: Joi.string().uri({ scheme: ['http', 'https'] }).max(500).required()
                }
            }
        }
    });

    next();
};

exports.register.attributes = {
    name: 'web',
    dependencies: 'visionary'
};
<commit_msg>Add path for redirecting the lengthened URLs.<commit_after>'use strict';

const Joi = require('joi');
const Randomstring = require('randomstring');
const Boom = require('boom');

exports.register = function (server, options, next) {

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply.view('index');
        }
    });

    server.route({
        method: 'GET',
        path: '/r/{longUrl}',
        handler: function (request, reply) {

            const models = request.server.plugins['hapi-sequelize'].db.sequelize.models;

            models.Url.findOne({ where: {lengthened: request.params.longUrl}})
                .then((url) => {

                    if (!url) {
                        return reply(Boom.badRequest('Invalid URL.'));
                    }

                    return reply.redirect(url.original).permanent();
                })
                .catch((err) => {

                    return reply(err);
                });

        },
    });

    server.route({
        method: 'POST',
        path: '/generate',
        handler: function (request, reply) {

            const models = request.server.plugins['hapi-sequelize'].db.sequelize.models;

            // Figure out what's longer, 50% of the URL's length, or our minimum length of 50 characters.
            const potentialLength = request.payload.url.length * 1.5;
            const newLength = parseInt(potentialLength > 50 ? potentialLength : 50);

            const lengthedUrl = Randomstring.generate(newLength);

            // First check and see if the URL already exists in the database.
            models.Url.findOrCreate({
                where: { original: request.payload.url },
                defaults: { lengthened: lengthedUrl }
            })
                .spread((url, created) => {

                    return reply(url);
                })
                .catch((err) => {

                    return reply(err);
                });
        },
        config: {
            validate: {
                payload: {
                    url: Joi.string().uri({ scheme: ['http', 'https'] }).max(500).required()
                }
            }
        }
    });

    next();
};

exports.register.attributes = {
    name: 'web',
    dependencies: 'visionary'
};
<|endoftext|>


<commit_before>// Tests for BookReaderJSLocate.php

// $$$ TODO -- make the test host configurable/automagic

module("JSLocate");

test("first test within module", function() {
  ok( true, "all pass" );
});

// Set up dummy BookReader class for JSLocate
function BookReader() {
};

BookReader.prototype.init = function() {
    return true;
};

asyncTest("JSLocate for notesonsubmarine00grea", function() {
    expect(1);
    $.getScript('http://www-testflip.archive.org/bookreader/BookReaderJSLocate.php?id=amonographonmec00buregoog',
        function(data, textStatus) {
            equals(13, window.br.titleLeaf, 'br object should exist with title leaf 13. See https://bugs.launchpad.net/bookreader/+bug/517424');
            start();
        }
    );
});

<commit_msg>Clean up JSLocate test<commit_after>// Tests for BookReaderJSLocate.php

// $$$ TODO -- make the test host configurable/automagic

module("JSLocate");

testHost = 'http://www-testflip.archive.org';

// Set up dummy BookReader class for JSLocate
function BookReader() {
};

BookReader.prototype.init = function() {
    return true;
};

asyncTest("JSLocate for notesonsubmarine00grea", function() {
    expect(1);
    $.getScript(testHost + '/bookreader/BookReaderJSLocate.php?id=amonographonmec00buregoog',
        function(data, textStatus) {
            equals(13, window.br.titleLeaf, 'br object should exist with title leaf 13. See https://bugs.launchpad.net/bookreader/+bug/517424');
            start();
        }
    );
});

<|endoftext|>


<commit_before>mass.define("scaffold","fs,path,router,here_document",function(fs,path,Router){

    function createFileByTemplate(filename, template, prepare) {
        if (!template.match(/\..+$/)) {
            var fileExtension =  '.js';
            template += fileExtension;
            filename += fileExtension;
        }
        var text = fs.readFileSync(path.join(__dirname, "templates", template));
        if (prepare) {
            text = text.toString('utf8');
            if (typeof prepare === 'function') {
                prepare = [prepare];
            }
            prepare.forEach(function (p) {
                text = p(text);
            });
        }
        return createFile(filename, text);
    }
    function createFile(filename, contents) {
        var fullPath = mass.adjustPath(filename).replace(/\\/g,"/");
        var match = fullPath.match(/(.*)\//);
        if(match){
            mass.mkdirSync(match[1]);
        }
        if (path.existsSync(fullPath)) {
            mass.log("创建文件"+filename+"失败",true);
        } else {
            fs.writeFileSync(fullPath, contents);
            mass.log("创建文件"+filename+"成功",true);
        }
        return fullPath;
    }
    function replaceViewEngine(template) {
        return template.replace(/VIEWENGINE/g,  'ejs');
    }

    function createDir(dir) {
        var fullPath = mass.adjustPath(dir);
        mass.mkdirSync(fullPath)
    }
    var actiontmpls = {
        index:function(req,res){
            res.render("tmpl",{})
        },
        show:function(req,res){
            res.render("tmpl",{})
        },
        "new":function(req,res){
            res.render("tmpl",{})
        },
        edit:function(req,res){
            res.render("tmpl",{})
        },
        create:function(req,res){/* POST */ },
        update:function(req,res){ /* PUT */},
        destroy:function(req,res){ /* DELETE */}
    }
    return function(name){
        name = name.replace(/\\/g,"/");
        //将模板文件全部复制到新网站的目录之下
        mass.cpdirSync("./templates",mass.adjustPath(""))

        var secret = require('crypto').createHash('sha1').update(Math.random().toString()).digest('hex');

        createFile('app/controllers/application_controller.js',  mass.hereDoc(function(){/*
        before('protect from forgery',function(){
            protectFromForgery("#{0}")
        }) */
            },secret));

        var routes_url = mass.adjustPath('config/routes.js'),

        mapper = new Router;

        mass.require("routes("+routes_url+")",function(fn){//读取routes.js配置文件
            fn(mapper);
        });
        var ejstmpl = fs.readFileSync("ejs/index.html")
        for(var controller in mapper.controllers){
            var object = mapper.controllers[controller];
            if(object.namespace){//如果存在命名空间,则需要创建对应的文件夹
                "controllers,views,models".replace(mass.rword,function(word){
                    createDir(path.join("app",word,object.namespace))
                });
            }

            //创建控制器
            var contents = mass.hereDoc(function(){/*
            mass.define("#{0}_controller",function(){
                return {
                   #{1}
                }
            });*/
                },controller,object.actions.map(function(action){ //创建动作
                    return "\t\t\""+action + "\":"+actiontmpls[action]
                }).join(",\n"));

            createFile(path.join("app","controllers",object.namespace, controller +"_controller.js") ,contents )
            //创建视图
            object.views.forEach(function(view){
                createFile(path.join("app","views",object.namespace, controller ,view +".html") ,ejstmpl )
            });
            //创建模型

            createFile(path.join("app","models",object.namespace, object.model_name +".js") ,"// "+ object.model_name)

        }
        //添加控制器的相关模板
        return mapper;
    }
});
////转换成一个字符串
//utils.serializeCookie = function (name, val, options) {
//    var ret = name + '=' + escape(val) + ';';
//    if (options.path)
//        ret += ' path=' + options.path + ';';
//    if (options.expires)
//        ret += ' expires=' + options.expires.toGMTString() + ';';
//    if (options.domain)
//        ret += ' domain=' + options.domain + ';';
//    if (options.secure)
//        ret += ' secure';
//    return ret;
//};
////将它转换为一个对象
//utils.unserializeCookie = function (cookies) {
//    if (!cookies)
//        return {}
//    var cookieline = cookies.toString().split(';');
//    var ret = {};
//    for (i in cookieline) {
//        var line = cookieline[i].trim().split('=');
//        if (line.length > 1) {
//            var k = line[0].trim();
//            var v = unescape(line[1].trim());
//            ret[k] = v;
//        }
//    }
//    return ret;
//};
//

//
//            exports.parse = function(cookie, name) {
//  var cookies = {};
//  if (typeof cookie == 'string') {
//    // Copied from: [cookie-sessions](http://github.com/caolan/cookie-sessions/blob/master/lib/cookie-sessions.js)
//    cookies = cookie.split(/\s*;\s*/g).map(
//        function(x) {
//          return x.split('=');
//        }).reduce(function(a, x) {
//          a[unescape(x[0])] = unescape(x[1]);
//          return a;
//        }, {});
//  }
//  return name ? cookies[name] : cookies;
//};
//
//exports.stringify = function(name, value, options) {
//  var cookie = name + "=" + escape(value);
//  if (options) {
//    options.expires && (cookie += "; expires=" + options.expires.toUTCString());
//    options.path && (cookie += "; path=" + options.path);
//    options.domain && (cookie += "; domain=" + options.domain);
//    options.secure && (cookie += "; secure=" + options.secure);
//    options.httponly && (cookie += "; httponly=" + options.httponly);
//  }
//  return cookie;
//};
//
//exports.checkLength = function(cookieStr) {
//  // recommended in [RFC2109](http://tools.ietf.org/html/rfc2109.html) Section `6.3 Implementation Limits`
//  return cookieStr.length <= 4096;
//};<commit_msg>格式化动态生成的JS代码<commit_after>mass.define("scaffold","fs,path,router,here_document",function(fs,path,Router){

    function createFileByTemplate(filename, template, prepare) {
        if (!template.match(/\..+$/)) {
            var fileExtension =  '.js';
            template += fileExtension;
            filename += fileExtension;
        }
        var text = fs.readFileSync(path.join(__dirname, "templates", template));
        if (prepare) {
            text = text.toString('utf8');
            if (typeof prepare === 'function') {
                prepare = [prepare];
            }
            prepare.forEach(function (p) {
                text = p(text);
            });
        }
        return createFile(filename, text);
    }
    function createFile(filename, contents) {
        var fullPath = mass.adjustPath(filename).replace(/\\/g,"/");
        var match = fullPath.match(/(.*)\//);
        if(match){
            mass.mkdirSync(match[1]);
        }
        if (path.existsSync(fullPath)) {
            mass.log("创建文件"+filename+"失败",true);
        } else {
            fs.writeFileSync(fullPath, contents);
            mass.log("创建文件"+filename+"成功",true);
        }
        return fullPath;
    }
    function replaceViewEngine(template) {
        return template.replace(/VIEWENGINE/g,  'ejs');
    }

    function createDir(dir) {
        var fullPath = mass.adjustPath(dir);
        mass.mkdirSync(fullPath)
    }
    var actiontmpls = {
        index:function(req,res){
            res.render("tmpl",{})
        },
        show:function(req,res){
            res.render("tmpl",{})
        },
        "new":function(req,res){
            res.render("tmpl",{})
        },
        edit:function(req,res){
            res.render("tmpl",{})
        },
        create:function(req,res){/* POST */ },
        update:function(req,res){ /* PUT */},
        destroy:function(req,res){ /* DELETE */}
    }
    return function(name){
        name = name.replace(/\\/g,"/");
        //将模板文件全部复制到新网站的目录之下
        var hasBuilt = mass.settings.hasBuilt;
        if(!hasBuilt){
            mass.cpdirSync("./templates",mass.adjustPath(""))

            var secret = require('crypto').createHash('sha1').update(Math.random().toString()).digest('hex');

            createFile('app/controllers/application_controller.js',  mass.hereDoc(function(){/*
        before('protect from forgery',function(){
            protectFromForgery("#{0}")
        }) */
                },secret));
        }

        var routes_url = mass.adjustPath('config/routes.js'),

        mapper = new Router;

        mass.require("routes("+routes_url+")",function(fn){//读取routes.js配置文件
            fn(mapper);
        });
        if(!hasBuilt){
            var ejstmpl = fs.readFileSync("ejs/index.html")
            for(var controller in mapper.controllers){
                var object = mapper.controllers[controller];
                if(object.namespace){//如果存在命名空间,则需要创建对应的文件夹
                    "controllers,views,models".replace(mass.rword,function(word){
                        createDir(path.join("app",word,object.namespace))
                    });
                }

                //创建控制器
                var contents = mass.hereDoc(function(){/*
            mass.define("#{0}_controller",function(){
                return {
                   #{1}
                }
            });*/
                    },controller,object.actions.map(function(action){ //创建动作
                        return "\t\t\""+action + "\":"+actiontmpls[action]
                    }).join(",\n"));
                contents =  require('./js_beautify.js').js_beautify(contents)

                createFile(path.join("app","controllers",object.namespace, controller +"_controller.js") ,contents )
                //创建视图
                object.views.forEach(function(view){
                    createFile(path.join("app","views",object.namespace, controller ,view +".html") ,ejstmpl )
                });
                //创建模型

                createFile(path.join("app","models",object.namespace, object.model_name +".js") ,"// "+ object.model_name)

            }
        }
        //添加控制器的相关模板
        return mapper;
    }
});
////转换成一个字符串
//utils.serializeCookie = function (name, val, options) {
//    var ret = name + '=' + escape(val) + ';';
//    if (options.path)
//        ret += ' path=' + options.path + ';';
//    if (options.expires)
//        ret += ' expires=' + options.expires.toGMTString() + ';';
//    if (options.domain)
//        ret += ' domain=' + options.domain + ';';
//    if (options.secure)
//        ret += ' secure';
//    return ret;
//};
////将它转换为一个对象
//utils.unserializeCookie = function (cookies) {
//    if (!cookies)
//        return {}
//    var cookieline = cookies.toString().split(';');
//    var ret = {};
//    for (i in cookieline) {
//        var line = cookieline[i].trim().split('=');
//        if (line.length > 1) {
//            var k = line[0].trim();
//            var v = unescape(line[1].trim());
//            ret[k] = v;
//        }
//    }
//    return ret;
//};
//

//
//            exports.parse = function(cookie, name) {
//  var cookies = {};
//  if (typeof cookie == 'string') {
//    // Copied from: [cookie-sessions](http://github.com/caolan/cookie-sessions/blob/master/lib/cookie-sessions.js)
//    cookies = cookie.split(/\s*;\s*/g).map(
//        function(x) {
//          return x.split('=');
//        }).reduce(function(a, x) {
//          a[unescape(x[0])] = unescape(x[1]);
//          return a;
//        }, {});
//  }
//  return name ? cookies[name] : cookies;
//};
//
//exports.stringify = function(name, value, options) {
//  var cookie = name + "=" + escape(value);
//  if (options) {
//    options.expires && (cookie += "; expires=" + options.expires.toUTCString());
//    options.path && (cookie += "; path=" + options.path);
//    options.domain && (cookie += "; domain=" + options.domain);
//    options.secure && (cookie += "; secure=" + options.secure);
//    options.httponly && (cookie += "; httponly=" + options.httponly);
//  }
//  return cookie;
//};
//
//exports.checkLength = function(cookieStr) {
//  // recommended in [RFC2109](http://tools.ietf.org/html/rfc2109.html) Section `6.3 Implementation Limits`
//  return cookieStr.length <= 4096;
//};<|endoftext|>


<commit_before>
// make a request to lastFM
function lastFM(data, callback){
  return reqwest({
    url:"https://ws.audioscrobbler.com/2.0/",
    data: data,
    type: 'xml',
    success: function(data){
      if(callback){callback(false, data)}
    },
    error: function(err){
      if(callback){callback(err)}
    }
  })
}

// generate data for a request
function requestData(api_key, user, page){
  return {
    method:'user.getrecenttracks',
    user:user,
    api_key:api_key,
    limit:200,
    page: page || 1
  }
}

// generate a list of request data objects
function requestList(api_key, user, page_count){
  var requests = [];
  for(var page = 1; page <= page_count; page++){
    requests.push(requestData(api_key, user, page))
  }
  return requests
}

// extract the data from the xml response
function extractTracks(doc){

  // probably nicer ways to do this
  var arr = [];
  var track, obj, child;
  var tracks = doc.evaluate('lfm/recenttracks/track', doc, null, XPathResult.ANY_TYPE, null)
  while (track = tracks.iterateNext()){
    obj = {};
    for (var i = track.childNodes.length - 1; i >= 0; i--) {
      child = track.childNodes[i];
      if(child.tagName)
        obj[child.tagName] = child.textContent;
    };
    arr.push(obj)
  }

  return arr;
}

function extractPageCount(doc){
  var recenttracks = doc.evaluate('lfm/recenttracks', doc, null, XPathResult.ANY_TYPE, null).iterateNext()
  return parseInt(recenttracks.getAttribute('totalPages'), 10)
}

// pull out a row of keys
function row(keys, obj){
  return keys.map(function(k){
    return obj[k]
  })
}

// create a csv row from an array
function csv(array){

  // this is not a world class csv generator
  return array.map(function(item){
    return  typeof(item) === 'string' ?
      item.replace(/[\",]/g,'') :
      item;
  }).join(',')
}

// delay a function by millis
function delay(fn, millis){
  return function(){
    var args = [].slice.call(arguments);
    setTimeout.apply(this, [fn,millis].concat(args));
  }
}

/*
var output = [];

// find the page count
lastFM(requestData(key, username))
.then(extractPageCount)
.then(function(page_count){

  // request all pages
  requestList(key, username, page_count)
  // .slice(0,30) // actually only 5
  .forEach(function(r,i){
    setTimeout(function(){
      lastFM(r)
      .then(extractTracks)
      .then(function(tracks){
        console.log('.')
        // output[0].map(function(d){return row(['artist', 'name', 'date'], d)}).map(csv).join('\n')
        output[i] = new Blob([tracks.map(function(d){return row(['artist', 'name', 'date'], d)}).map(csv).join('\n'),'\n'])
      })
    },  i * 1000)
  })
})

// b = new Blob(output, {type: 'text/csv'})
// saveAs(b)

*/
<commit_msg>add requestors for user and week requests<commit_after>
// make a request to lastFM
function lastFM(data, callback){
  return reqwest({
    url:"https://ws.audioscrobbler.com/2.0/",
    data: data,
    type: 'xml',
    success: function(data){
      if(callback){callback(false, data)}
    },
    error: function(err){
      if(callback){callback(err)}
    }
  })
}

function requestUser(api_key, user){
  return {
    method:'user.getInfo',
    user: user,
    api_key: api_key,
    format: 'json'
  }
}

function normaliseUser(data){
  console.log(data);
  return data.user
}

// Weeks look like they might be pretty
// useless
function requestWeeks(api_key, user){
  return {
    method:'user.getweeklychartlist',
    user: user,
    api_key: api_key,
    format: 'json'
  }
}

function normaliseWeeks(data){
  return {
    name: data.weeklychartlist['@attr'].user,
    weeks: data.weeklychartlist.chart.map(function(chart){
      return {
        from: chart.from,
        to:   chart.to
      }
    })
  };
}

// generate data for a request
function requestData(api_key, user, page){
  return {
    method:'user.getrecenttracks',
    user:user,
    api_key:api_key,
    limit:200,
    page: page || 1
  }
}

// generate a list of request data objects
function requestList(api_key, user, page_count){
  var requests = [];
  for(var page = 1; page <= page_count; page++){
    requests.push(requestData(api_key, user, page))
  }
  return requests
}

// extract the data from the xml response
function extractTracks(doc){

  // probably nicer ways to do this
  var arr = [];
  var track, obj, child;
  var tracks = doc.evaluate('lfm/recenttracks/track', doc, null, XPathResult.ANY_TYPE, null)
  while (track = tracks.iterateNext()){
    obj = {};
    for (var i = track.childNodes.length - 1; i >= 0; i--) {
      child = track.childNodes[i];
      if(child.tagName)
        obj[child.tagName] = child.textContent;
    };
    arr.push(obj)
  }

  return arr;
}

function extractPageCount(doc){
  var recenttracks = doc.evaluate('lfm/recenttracks', doc, null, XPathResult.ANY_TYPE, null).iterateNext()
  return parseInt(recenttracks.getAttribute('totalPages'), 10)
}

// pull out a row of keys
function row(keys, obj){
  return keys.map(function(k){
    return obj[k]
  })
}

// create a csv row from an array
function csv(array){

  // this is not a world class csv generator
  return array.map(function(item){
    return  typeof(item) === 'string' ?
      item.replace(/[\",]/g,'') :
      item;
  }).join(',')
}

// delay a function by millis
function delay(fn, millis){
  return function(){
    var args = [].slice.call(arguments);
    setTimeout.apply(this, [fn,millis].concat(args));
  }
}

/*
var output = [];

// find the page count
lastFM(requestData(key, username))
.then(extractPageCount)
.then(function(page_count){

  // request all pages
  requestList(key, username, page_count)
  // .slice(0,30) // actually only 5
  .forEach(function(r,i){
    setTimeout(function(){
      lastFM(r)
      .then(extractTracks)
      .then(function(tracks){
        console.log('.')
        // output[0].map(function(d){return row(['artist', 'name', 'date'], d)}).map(csv).join('\n')
        output[i] = new Blob([tracks.map(function(d){return row(['artist', 'name', 'date'], d)}).map(csv).join('\n'),'\n'])
      })
    },  i * 1000)
  })
})

// b = new Blob(output, {type: 'text/csv'})
// saveAs(b)

*/
<|endoftext|>