<commit_before>var childProcess = require('child_process'),
    fs = require('fs'),
    path = require('path'),
      dirname = path.dirname;

module.exports = {
  currentBranch: function(path, callback) {
    childProcess.exec('git symbolic-ref -q HEAD', {cwd: path}, function(err, stdout) {
      var currentBranch = stdout.split('\n')
          .filter(function(branch) { return branch; })
          .map(function(branch) { return branch.replace(/^refs\/heads\//, ''); })[0];
      callback(err, currentBranch);
    });
  },

  generate: function(configSource, output, callback) {
    fs.readFile(configSource, function(err, data) {
      if (err) {
        return callback(err);
      }

      data = JSON.parse(data);
      data.release = true;

      module.exports.currentBranch(dirname(configSource), function(err, branch) {
        if (err) {
          return callback(err);
        }

        // Copy over the index source file.
        try {
          var index = fs.readFileSync(dirname(configSource) + '/index.js');
          fs.writeFileSync(dirname(output) + '/index.js', index);
        } catch (err) {
          return callback(err);
        }

        data.name += '-' + branch.replace(/^release\//, '');
        fs.writeFile(output, JSON.stringify(data, undefined, 2), callback);
      });
    });
  }
};
<commit_msg>Add additional logging to package generator<commit_after>var childProcess = require('child_process'),
    fs = require('fs'),
    path = require('path'),
      dirname = path.dirname,
    util = require('./util');

module.exports = {
  currentBranch: function(path, callback) {
    childProcess.exec('git symbolic-ref -q HEAD', {cwd: path}, function(err, stdout, stderr) {
      util.streamData('git: ', stdout);
      if (stderr) {
        util.streamData('git err: ', stderr);
      }

      var currentBranch = stdout.split('\n')
          .filter(function(branch) { return branch; })
          .map(function(branch) { return branch.replace(/^refs\/heads\//, ''); })[0];
      callback(err, currentBranch);
    });
  },

  generate: function(configSource, output, callback) {
    fs.readFile(configSource, function(err, data) {
      if (err) {
        return callback(err);
      }

      data = JSON.parse(data);
      data.release = true;

      module.exports.currentBranch(dirname(configSource), function(err, branch) {
        if (err) {
          return callback(err);
        }

        // Copy over the index source file.
        try {
          var src = dirname(configSource) + '/index.js',
              dest = dirname(output) + '/index.js';
          console.log('package: ', 'Copying package index "' + src + '" to "' + dest + '"');
          var index = fs.readFileSync(src);
          fs.writeFileSync(dest, index);
        } catch (err) {
          return callback(err);
        }

        data.name += '-' + branch.replace(/^release\//, '');
        console.log('package: ', 'Output package config for branch "' + data.name + '"');
        fs.writeFile(output, JSON.stringify(data, undefined, 2), callback);
      });
    });
  }
};
<|endoftext|>


<commit_before>module.exports=inject;

function inject(serv,player)
{

  player.on("connected",function(){
    var addr = player._client.socket.remoteAddress + ':' + player._client.socket.remotePort;
    console.log("[INFO]: " + player.username + ' connected', '(' + addr + ')');
    serv.log("[INFO]: " + player.username + ' connected', '(' + addr + ')');
  });

  player.on("spawned",function(){
    console.log("[INFO]: position written, player spawning...");
    serv.log("[INFO]: position written, player spawning...");
  });

  player.on("disconnected",function(){
    console.log("[INFO]: " + player.username + ' disconnected'+ '(' + addr + ')');
    serv.log("[INFO]: " + player.username + ' disconnected'+ '(' + addr + ')');
  });

  player.on("error",function(error){
    console.log('[ERR] ' + error.stack);
    serv.log('[ERR]: Client: ' + error.stack);
  });

  player.on("chat",function(message){
    message = '<' + player.username + '>' + ' ' + message;
    console.log("[INFO] " + message);
    serv.log("[INFO] " + message);
  });

}<commit_msg>fix disconnecting error<commit_after>module.exports=inject;

function inject(serv,player)
{

  player.on("connected",function(){
    console.log("[INFO]: " + player.username + ' connected');
    serv.log("[INFO]: " + player.username + ' connected');
  });

  player.on("spawned",function(){
    console.log("[INFO]: position written, player spawning...");
    serv.log("[INFO]: position written, player spawning...");
  });

  player.on("disconnected",function(){
    console.log("[INFO]: " + player.username + ' disconnected');
    serv.log("[INFO]: " + player.username + ' disconnected');
  });

  player.on("error",function(error){
    console.log('[ERR] ' + error.stack);
    serv.log('[ERR]: Client: ' + error.stack);
  });

  player.on("chat",function(message){
    message = '<' + player.username + '>' + ' ' + message;
    console.log("[INFO] " + message);
    serv.log("[INFO] " + message);
  });

}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Oculus Info Inc.
 * http://www.oculusinfo.com/
 *
 * Released under the MIT License.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

( function() {

    "use strict";

    var Layer = require('./Layer'),
        LayerUtil = require('./LayerUtil'),
        Util = require('../util/Util'),
        HtmlTileLayer = require('./HtmlTileLayer'),
        PubSub = require('../util/PubSub');

    /**
     * Private: Returns the zoom callback function to update level min and maxes.
     *
     * @param layer {ServerLayer} The layer object.
     */
    function zoomCallback( layer ) {
        return function() {
            if ( layer.olLayer ) {
                layer.setLevelMinMax();
            }
        };
    }

    /**
     * Instantiate a ClientLayer object.
     * @class ClientLayer
     * @augments Layer
     * @classdesc A client rendered layer object. Uses JSON data retrieved from the
     *            server in conjunction with a Renderer object or html function to
     *            create interactable DOM elements.
     *
     * @param {Object} spec - The specification object.
     *

     * {
     *     opacity  {float}    - The opacity of the layer. Default = 1.0
     *     enabled  {boolean}  - Whether the layer is visible or not. Default = true
     *     zIndex   {integer}  - The z index of the layer. Default = 1000
     *     renderer {Renderer} - The tile renderer object.
     * }
     *

     */
    function ClientLayer( spec ) {
        var that = this,
            getURL = spec.getURL || LayerUtil.getURL;
        // call base constructor
        Layer.call( this, spec );
        // set reasonable defaults
        this.zIndex = ( spec.zIndex !== undefined ) ? parseInt( spec.zIndex, 10 ) : 1000;
        this.tileTransform = spec.tileTransform || {};
        this.domain = "client";
        this.source = spec.source;
        this.getURL = function( bounds ) {
            return getURL.call( this, bounds ) + that.getQueryParamString();
        };
        if ( spec.tileClass ) {
            this.tileClass = spec.tileClass;
        }
        if ( spec.renderer ) {
            this.setRenderer( spec.renderer );
        }
        if ( spec.aggregators ) {
            _.forIn( spec.aggregators, function( agg, key ) {
                this.addAggregator( key, agg );
            });
        }
    }

    ClientLayer.prototype = Object.create( Layer.prototype );

    /**
     * Activates the layer object. This should never be called manually.
     * @memberof ClientLayer
     * @private
     */
    ClientLayer.prototype.activate = function() {
        // set callback here so it can be removed later
        this.zoomCallback = zoomCallback( this );
        // set callback to update ramp min/max on zoom
        this.map.on( "zoomend", this.zoomCallback );
        // add the new layer
        this.olLayer = new HtmlTileLayer(
            'Client Rendered Tile Layer',
            this.source.tms,
            {
                layername: this.source.id,
                type: 'json',
                maxExtent: new OpenLayers.Bounds(-20037500, -20037500,
                    20037500,  20037500),
                isBaseLayer: false,
                getURL: this.getURL,
                tileClass: this.tileClass,
                renderer: this.renderer
            });
        // set whether it is enabled or not before attaching, to prevent
        // needless tile reqeests
        this.setEnabled( this.isEnabled() );
        this.setTheme( this.map.getTheme() );
        this.setOpacity( this.getOpacity() );
        this.setBrightness( this.getBrightness() );
        this.setContrast( this.getContrast() );
        // publish activate event before appending to map
        PubSub.publish( this.getChannel(), { field: 'activate', value: true } );
        // attach to map
        this.map.olMap.addLayer( this.olLayer );
        // set z-index after
        this.setZIndex( this.zIndex );
        this.setLevelMinMax(); // set level min / max
        // publish add event
        PubSub.publish( this.getChannel(), { field: 'add', value: true } );
    };

    /**
     * Dectivates the layer object. This should never be called manually.
     * @memberof ClientLayer
     * @private
     */
    ClientLayer.prototype.deactivate = function() {
        if ( this.olLayer ) {
            this.map.olMap.removeLayer( this.olLayer );
            PubSub.publish( this.getChannel(), { field: 'remove', value: true } );
            this.olLayer.destroy();
            this.olLayer = null;
        }
        this.map.off( "zoomend", this.zoomCallback );
        this.zoomCallback = null;
        PubSub.publish( this.getChannel(), { field: 'deactivate', value: true } );
    };

    /**
     * Sets the current renderer of the layer.
     * @memberof ClientLayer
     *
     * @param {Renderer} renderer - The renderer to attach to the layer.
     */
    ClientLayer.prototype.setRenderer = function( renderer ) {
        this.renderer = renderer;
        this.renderer.attach( this );
    };

    /**
     * Adds an aggregator to the layer.
     * @memberof ClientLayer
     *
     * @param {String} id - The aggregator id.
     * @param {Renderer} renderer - The renderer to attach to the layer.
     */
    ClientLayer.prototype.addAggregator = function( id, aggregator ) {
        this.aggregators = this.aggregators || {};
        this.aggregators[ id ] = aggregator;
        this.aggregators[ id ].attach( this );
    };

    /**
     * Gets an aggregator by id.
     * @memberof ClientLayer
     *
     * @param {String} id - The aggregator id.
     */
    ClientLayer.prototype.getAggregator = function( id ) {
        return this.aggregators[ id ];
    };

    /**
     * Updates the theme associated with the layer.
     * @memberof ClientLayer
     *
     * @param {String} theme - The theme identifier string.
     */
    ClientLayer.prototype.setTheme = function( theme ) {
        this.theme = theme;
    };

    /**
     * Get the current theme for the layer.
     * @memberof ClientLayer
     *
     * @returns {String} The theme identifier string.
     */
    ClientLayer.prototype.getTheme = function() {
        return this.theme;
    };

    /**
     * Set the z index of the layer.
     * @memberof ClientLayer
     *
     * @param {integer} zIndex - The new z-order value of the layer, where 0 is front.
     */
    ClientLayer.prototype.setZIndex = function ( zIndex ) {
        // we by-pass the OpenLayers.Map.setLayerIndex() method and manually
        // set the z-index of the layer dev. setLayerIndex sets a relative
        // index based on current map layers, which then sets a z-index. This
        // caused issues with async layer loading.
        this.zIndex = zIndex;
        if ( this.olLayer ) {
            $( this.olLayer.div ).css( 'z-index', zIndex );
        }
        PubSub.publish( this.getChannel(), { field: 'zIndex', value: zIndex });
    };

    /**
     * Get the layers zIndex.
     * @memberof ClientLayer
     *
     * @returns {integer} The zIndex for the layer.
     */
    ClientLayer.prototype.getZIndex = function () {
        return this.zIndex;
    };

    /**
     * Set the layers tile transform function type.
     * @memberof ClientLayer
     *
     * @param {String} transformType - The tile transformer type.
     */
    ClientLayer.prototype.setTileTransformType = function ( transformType ) {
        if ( this.tileTransform.type !== transformType ) {
            this.tileTransform.type = transformType;
            this.redraw();
            PubSub.publish( this.getChannel(), {field: 'tileTransformType', value: transformType} );
        }
    };

    /**
     * Get the layers transformer type.
     * @memberof ClientLayer
     *
     * @return {String} The tile transform type.
     */
    ClientLayer.prototype.getTileTransformType = function () {
        return this.tileTransform.type;
    };

    /**
     * Set the tile transform data based on the time range passed in
     * @memberof ClientLayer
     *
     * @param {number} start - A unix timestamp representing the start of the time range
     * @param {number} end - A unix timestamp representing the end of the time range
     */
    ClientLayer.prototype.setTileTransformRange = function ( start, end ) {
		var meta = this.source.meta.meta,
			rangeMin = meta.rangeMin,
			rangeMax = meta.rangeMax,
			numBuckets = meta.bucketCount,
            bucketSize = ( rangeMax - rangeMin ) / numBuckets;
        if ( start > rangeMax && end < rangeMin ) {
            // outside range completely, send empty request
			this.setTileTransformData({
    			startBucket: -1,
    			endBucket: -1
            });
		}
		this.setTileTransformData({
			startBucket: Math.max( 0, Math.floor( ( start - rangeMin ) / bucketSize ) ),
			endBucket: Math.min( numBuckets - 1, Math.floor( ( end - rangeMin ) / bucketSize ) )
        });
	};

    /**
     * Set the tile transform data attribute internally
     * @memberof ClientLayer
     *
     * @param {Object} transformData - The tile transform data attribute.
     */
	ClientLayer.prototype.setTileTransformData = function( transformData ) {
        if ( !_.isEqual( this.tileTransform.data, transformData ) ) {
            this.tileTransform.data = transformData;
            this.redraw();
            PubSub.publish( this.getChannel(), {field: 'tileTransformData', value: transformData} );
        }
    };

    /**
     * Get the transformer data attribute.
     * @memberof ClientLayer
     *
     * @returns {Object} The tile transform data attribute.
     */
    ClientLayer.prototype.getTileTransformData = function () {
        return this.tileTransform.data || {};
    };

    /**
     * Get the current minimum and maximum values for the current zoom level.
     * @memberof ClientLayer
     *
     * @param {Object} The min and max of the level.
     */
    ClientLayer.prototype.getLevelMinMax = function() {
        return this.levelMinMax;
    };

    /**
     * Generate query parameters based on state of layer
     * @memberof ClientLayer
     *
     * @returns {String} The query parameter string based on the attributes of this layer.
     */
     ClientLayer.prototype.getQueryParamString = function() {
        var query = {
            tileTransform: this.tileTransform
        };
        return Util.encodeQueryParams( query );
    };

    /**
     * Redraws the entire layer.
     * @memberof ClientLayer
     */
    ClientLayer.prototype.redraw = function () {
        if ( this.olLayer ) {
            this.setLevelMinMax();
            this.olLayer.redraw();
            // If we're using the TileManager we need to force it into a refresh. There is no nice way to
            // do this as of 2.13.1, so we fake the expiry of the move/zoom timeout.
            if ( this.olLayer.map && this.olLayer.map.tileManager ) {
                this.olLayer.map.tileManager.updateTimeout(
                    this.olLayer.map,
                    this.olLayer.map.tileManager.zoomDelay,
                    true );
            }
        }
    };

    /**
     * Sets the layers min and max values for the given zoom level.
     * @memberof ClientLayer
     * @private
     * @param layer {Object} the layer object.
     */
    ClientLayer.prototype.setLevelMinMax = function() {
        var zoomLevel = this.map.getZoom(),
            source = this.source,
            meta = source.meta && source.meta.meta ? source.meta.meta[ zoomLevel ] : null,
            transformData = this.tileTransform.data || {},
            levelMinMax = meta,
            renderer = this.renderer,
            aggregated;
        if ( meta ) {
            // aggregate the data if there is an aggregator attached
            if ( renderer && renderer.aggregator ) {
                // aggregate the meta data buckets
                aggregated = renderer.aggregator.aggregate(
                    meta.bins || [],
                    transformData.startBucket,
                    transformData.endBucket );
                if ( aggregated instanceof Array ) {
                    // take the first and last index, which correspond to max / min
                    levelMinMax = {
                        minimum: aggregated[aggregated.length - 1] || null,
                        maximum: aggregated[0] || null
                    };
                } else {
                    //
                    levelMinMax = {
                        minimum: aggregated,
                        maximum: aggregated
                    };
                }
            }
        } else {
            levelMinMax = {
                minimum: null,
                maximum: null
            };
        }
        this.levelMinMax = levelMinMax;
        PubSub.publish( this.getChannel(), { field: 'levelMinMax', value: levelMinMax });
    };

    module.exports = ClientLayer;
}());
<commit_msg>Client layers resets zindex when it redraws itself<commit_after>/*
 * Copyright (c) 2014 Oculus Info Inc.
 * http://www.oculusinfo.com/
 *
 * Released under the MIT License.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

( function() {

    "use strict";

    var Layer = require('./Layer'),
        LayerUtil = require('./LayerUtil'),
        Util = require('../util/Util'),
        HtmlTileLayer = require('./HtmlTileLayer'),
        PubSub = require('../util/PubSub');

    /**
     * Private: Returns the zoom callback function to update level min and maxes.
     *
     * @param layer {ServerLayer} The layer object.
     */
    function zoomCallback( layer ) {
        return function() {
            if ( layer.olLayer ) {
                layer.setLevelMinMax();
            }
        };
    }

    /**
     * Instantiate a ClientLayer object.
     * @class ClientLayer
     * @augments Layer
     * @classdesc A client rendered layer object. Uses JSON data retrieved from the
     *            server in conjunction with a Renderer object or html function to
     *            create interactable DOM elements.
     *
     * @param {Object} spec - The specification object.
     *

     * {
     *     opacity  {float}    - The opacity of the layer. Default = 1.0
     *     enabled  {boolean}  - Whether the layer is visible or not. Default = true
     *     zIndex   {integer}  - The z index of the layer. Default = 1000
     *     renderer {Renderer} - The tile renderer object.
     * }
     *

     */
    function ClientLayer( spec ) {
        var that = this,
            getURL = spec.getURL || LayerUtil.getURL;
        // call base constructor
        Layer.call( this, spec );
        // set reasonable defaults
        this.zIndex = ( spec.zIndex !== undefined ) ? parseInt( spec.zIndex, 10 ) : 1000;
        this.tileTransform = spec.tileTransform || {};
        this.domain = "client";
        this.source = spec.source;
        this.getURL = function( bounds ) {
            return getURL.call( this, bounds ) + that.getQueryParamString();
        };
        if ( spec.tileClass ) {
            this.tileClass = spec.tileClass;
        }
        if ( spec.renderer ) {
            this.setRenderer( spec.renderer );
        }
        if ( spec.aggregators ) {
            _.forIn( spec.aggregators, function( agg, key ) {
                this.addAggregator( key, agg );
            });
        }
    }

    ClientLayer.prototype = Object.create( Layer.prototype );

    /**
     * Activates the layer object. This should never be called manually.
     * @memberof ClientLayer
     * @private
     */
    ClientLayer.prototype.activate = function() {
        // set callback here so it can be removed later
        this.zoomCallback = zoomCallback( this );
        // set callback to update ramp min/max on zoom
        this.map.on( "zoomend", this.zoomCallback );
        // add the new layer
        this.olLayer = new HtmlTileLayer(
            'Client Rendered Tile Layer',
            this.source.tms,
            {
                layername: this.source.id,
                type: 'json',
                maxExtent: new OpenLayers.Bounds(-20037500, -20037500,
                    20037500,  20037500),
                isBaseLayer: false,
                getURL: this.getURL,
                tileClass: this.tileClass,
                renderer: this.renderer
            });
        // set whether it is enabled or not before attaching, to prevent
        // needless tile reqeests
        this.setEnabled( this.isEnabled() );
        this.setTheme( this.map.getTheme() );
        this.setOpacity( this.getOpacity() );
        this.setBrightness( this.getBrightness() );
        this.setContrast( this.getContrast() );
        // publish activate event before appending to map
        PubSub.publish( this.getChannel(), { field: 'activate', value: true } );
        // attach to map
        this.map.olMap.addLayer( this.olLayer );
        // set z-index after
        this.setZIndex( this.zIndex );
        this.setLevelMinMax(); // set level min / max
        // publish add event
        PubSub.publish( this.getChannel(), { field: 'add', value: true } );
    };

    /**
     * Dectivates the layer object. This should never be called manually.
     * @memberof ClientLayer
     * @private
     */
    ClientLayer.prototype.deactivate = function() {
        if ( this.olLayer ) {
            this.map.olMap.removeLayer( this.olLayer );
            PubSub.publish( this.getChannel(), { field: 'remove', value: true } );
            this.olLayer.destroy();
            this.olLayer = null;
        }
        this.map.off( "zoomend", this.zoomCallback );
        this.zoomCallback = null;
        PubSub.publish( this.getChannel(), { field: 'deactivate', value: true } );
    };

    /**
     * Sets the current renderer of the layer.
     * @memberof ClientLayer
     *
     * @param {Renderer} renderer - The renderer to attach to the layer.
     */
    ClientLayer.prototype.setRenderer = function( renderer ) {
        this.renderer = renderer;
        this.renderer.attach( this );
    };

    /**
     * Adds an aggregator to the layer.
     * @memberof ClientLayer
     *
     * @param {String} id - The aggregator id.
     * @param {Renderer} renderer - The renderer to attach to the layer.
     */
    ClientLayer.prototype.addAggregator = function( id, aggregator ) {
        this.aggregators = this.aggregators || {};
        this.aggregators[ id ] = aggregator;
        this.aggregators[ id ].attach( this );
    };

    /**
     * Gets an aggregator by id.
     * @memberof ClientLayer
     *
     * @param {String} id - The aggregator id.
     */
    ClientLayer.prototype.getAggregator = function( id ) {
        return this.aggregators[ id ];
    };

    /**
     * Updates the theme associated with the layer.
     * @memberof ClientLayer
     *
     * @param {String} theme - The theme identifier string.
     */
    ClientLayer.prototype.setTheme = function( theme ) {
        this.theme = theme;
    };

    /**
     * Get the current theme for the layer.
     * @memberof ClientLayer
     *
     * @returns {String} The theme identifier string.
     */
    ClientLayer.prototype.getTheme = function() {
        return this.theme;
    };

    /**
     * Set the z index of the layer.
     * @memberof ClientLayer
     *
     * @param {integer} zIndex - The new z-order value of the layer, where 0 is front.
     */
    ClientLayer.prototype.setZIndex = function ( zIndex ) {
        // we by-pass the OpenLayers.Map.setLayerIndex() method and manually
        // set the z-index of the layer dev. setLayerIndex sets a relative
        // index based on current map layers, which then sets a z-index. This
        // caused issues with async layer loading.
        this.zIndex = zIndex;
        if ( this.olLayer ) {
            $( this.olLayer.div ).css( 'z-index', zIndex );
        }
        PubSub.publish( this.getChannel(), { field: 'zIndex', value: zIndex });
    };

    /**
     * Get the layers zIndex.
     * @memberof ClientLayer
     *
     * @returns {integer} The zIndex for the layer.
     */
    ClientLayer.prototype.getZIndex = function () {
        return this.zIndex;
    };

    /**
     * Set the layers tile transform function type.
     * @memberof ClientLayer
     *
     * @param {String} transformType - The tile transformer type.
     */
    ClientLayer.prototype.setTileTransformType = function ( transformType ) {
        if ( this.tileTransform.type !== transformType ) {
            this.tileTransform.type = transformType;
            this.redraw();
            PubSub.publish( this.getChannel(), {field: 'tileTransformType', value: transformType} );
        }
    };

    /**
     * Get the layers transformer type.
     * @memberof ClientLayer
     *
     * @return {String} The tile transform type.
     */
    ClientLayer.prototype.getTileTransformType = function () {
        return this.tileTransform.type;
    };

    /**
     * Set the tile transform data based on the time range passed in
     * @memberof ClientLayer
     *
     * @param {number} start - A unix timestamp representing the start of the time range
     * @param {number} end - A unix timestamp representing the end of the time range
     */
    ClientLayer.prototype.setTileTransformRange = function ( start, end ) {
		var meta = this.source.meta.meta,
			rangeMin = meta.rangeMin,
			rangeMax = meta.rangeMax,
			numBuckets = meta.bucketCount,
            bucketSize = ( rangeMax - rangeMin ) / numBuckets;
        if ( start > rangeMax && end < rangeMin ) {
            // outside range completely, send empty request
			this.setTileTransformData({
    			startBucket: -1,
    			endBucket: -1
            });
		}
		this.setTileTransformData({
			startBucket: Math.max( 0, Math.floor( ( start - rangeMin ) / bucketSize ) ),
			endBucket: Math.min( numBuckets - 1, Math.floor( ( end - rangeMin ) / bucketSize ) )
        });
	};

    /**
     * Set the tile transform data attribute internally
     * @memberof ClientLayer
     *
     * @param {Object} transformData - The tile transform data attribute.
     */
	ClientLayer.prototype.setTileTransformData = function( transformData ) {
        if ( !_.isEqual( this.tileTransform.data, transformData ) ) {
            this.tileTransform.data = transformData;
            this.redraw();
            PubSub.publish( this.getChannel(), {field: 'tileTransformData', value: transformData} );
        }
    };

    /**
     * Get the transformer data attribute.
     * @memberof ClientLayer
     *
     * @returns {Object} The tile transform data attribute.
     */
    ClientLayer.prototype.getTileTransformData = function () {
        return this.tileTransform.data || {};
    };

    /**
     * Get the current minimum and maximum values for the current zoom level.
     * @memberof ClientLayer
     *
     * @param {Object} The min and max of the level.
     */
    ClientLayer.prototype.getLevelMinMax = function() {
        return this.levelMinMax;
    };

    /**
     * Generate query parameters based on state of layer
     * @memberof ClientLayer
     *
     * @returns {String} The query parameter string based on the attributes of this layer.
     */
     ClientLayer.prototype.getQueryParamString = function() {
        var query = {
            tileTransform: this.tileTransform
        };
        return Util.encodeQueryParams( query );
    };

    /**
     * Redraws the entire layer.
     * @memberof ClientLayer
     */
    ClientLayer.prototype.redraw = function () {
        if ( this.olLayer ) {
            this.setLevelMinMax();
            this.olLayer.redraw();
            this.setZIndex(this.zIndex);
            // If we're using the TileManager we need to force it into a refresh. There is no nice way to
            // do this as of 2.13.1, so we fake the expiry of the move/zoom timeout.
            if ( this.olLayer.map && this.olLayer.map.tileManager ) {
                this.olLayer.map.tileManager.updateTimeout(
                    this.olLayer.map,
                    this.olLayer.map.tileManager.zoomDelay,
                    true );
            }
        }
    };

    /**
     * Sets the layers min and max values for the given zoom level.
     * @memberof ClientLayer
     * @private
     * @param layer {Object} the layer object.
     */
    ClientLayer.prototype.setLevelMinMax = function() {
        var zoomLevel = this.map.getZoom(),
            source = this.source,
            meta = source.meta && source.meta.meta ? source.meta.meta[ zoomLevel ] : null,
            transformData = this.tileTransform.data || {},
            levelMinMax = meta,
            renderer = this.renderer,
            aggregated;
        if ( meta ) {
            // aggregate the data if there is an aggregator attached
            if ( renderer && renderer.aggregator ) {
                // aggregate the meta data buckets
                aggregated = renderer.aggregator.aggregate(
                    meta.bins || [],
                    transformData.startBucket,
                    transformData.endBucket );
                if ( aggregated instanceof Array ) {
                    // take the first and last index, which correspond to max / min
                    levelMinMax = {
                        minimum: aggregated[aggregated.length - 1] || null,
                        maximum: aggregated[0] || null
                    };
                } else {
                    //
                    levelMinMax = {
                        minimum: aggregated,
                        maximum: aggregated
                    };
                }
            }
        } else {
            levelMinMax = {
                minimum: null,
                maximum: null
            };
        }
        this.levelMinMax = levelMinMax;
        PubSub.publish( this.getChannel(), { field: 'levelMinMax', value: levelMinMax });
    };

    module.exports = ClientLayer;
}());
<|endoftext|>


<commit_before>var O = { O: true, B: true, '': true };
var E = { E: true, B: true, '': true };

module.exports = function(feature, address) {
    // features without address data at all, on either side of the street
    if (feature._rangetype !== 'tiger' ||
        !feature._geometry ||
        (feature._geometry.type !== 'LineString' &&
        feature._geometry.type !== 'MultiLineString')) return;

    var lines = feature._geometry.type === 'MultiLineString' ?
        feature._geometry.coordinates :
        [feature._geometry.coordinates];

    var lf = Array.isArray(feature._lfromhn) ? feature._lfromhn : feature._lfromhn ? [feature._lfromhn] : [];
    var lt = Array.isArray(feature._ltohn)   ? feature._ltohn : feature._ltohn ? [feature._ltohn] : [];
    var rf = Array.isArray(feature._rfromhn) ? feature._rfromhn : feature._rfromhn ? [feature._rfromhn] : [];
    var rt = Array.isArray(feature._rtohn)   ? feature._rtohn : feature._rtohn ? [feature._rtohn] : [];
    var lp = Array.isArray(feature._parityl) ? feature._parityl : feature._parityl ? [feature._parityl] : [];
    var rp = Array.isArray(feature._parityr) ? feature._parityr : feature._parityr ? [feature._parityr] : [];

    for (var i = 0; i < lines.length; i++) {
        var lfromhn = parseSemiNumber(lf[i]),
            rfromhn = parseSemiNumber(rf[i]),
            ltohn = parseSemiNumber(lt[i]),
            rtohn = parseSemiNumber(rt[i]),
            parityl = lp[i] || '',
            parityr = rp[i] || '';

        // no usable data at all
        if ([lfromhn, rfromhn, ltohn, rtohn].every(falsy)) continue;

        var start, end, side, paritymask;

        paritymask = (address % 2) === 0 ? E : O;

        // check left side
        if (typeof lfromhn === 'number' &&
            address >= Math.min(lfromhn,ltohn) &&
            address <= Math.max(lfromhn,ltohn) &&
            paritymask[parityl]) {
            start = lfromhn;
            end = ltohn;
            side ='left';
        } else if (typeof rfromhn === 'number' &&
            address >= Math.min(rfromhn,rtohn) &&
            address <= Math.max(rfromhn,rtohn) &&
            paritymask[parityr]) {
            start = rfromhn;
            end = rtohn;
            side ='right';
        } else {
            continue;
        }

        var reverse = false;
        if (start > end) {
            reverse = true;
            // swap start and end
            var _;
            _ = end;
            end = start;
            start = _;
        }

        // a normalized number between 0 and 1
        var part = (address - start) / (end - start);
        var coords = lines[i].slice(0);

        if (reverse) coords.reverse();

        var distance = calculateDistance(coords);
        var unnorm = part * distance;

        for (var stop = 1; stop < coords.length - 1; stop++) {
            if (coords[stop][2] > unnorm) break;
        }

        var interp = (unnorm - coords[stop - 1][2]) /
            (coords[stop][2] - coords[stop - 1][2]);

        return {
            type:'Point',
            coordinates: [
                coords[stop][0] * interp + coords[stop - 1][0] * (1 - interp),
                coords[stop][1] * interp + coords[stop - 1][1] * (1 - interp)
            ].map(function(v) {
                return Math.round(v*1e6) / 1e6;
            })
        };
    }
};

module.exports.parseSemiNumber = parseSemiNumber;
module.exports.calculateDistance = calculateDistance;

function calculateDistance(coords) {
    var a, b, distance = 0;
    coords[0].push(distance);
    for (var j = 1; j < coords.length; j++) {
        a = coords[j - 1];
        b = coords[j];
        distance += Math.sqrt(
            ((a[0] - b[0]) * (a[0] - b[0])) +
            ((a[1] - b[1]) * (a[1] - b[1])));
        coords[j].push(distance);
    }
    return distance;
}

function parseSemiNumber(_) {
    _ = parseInt((_ || '').replace(/[^\d]/g,''),10);
    return isNaN(_) ? null : _;
}

function falsy(_) { return !_; }
<commit_msg>Add tilecopy command<commit_after>var O = { O: true, B: true, '': true };
var E = { E: true, B: true, '': true };

module.exports = function(feature, address) {
    // features without address data at all, on either side of the street
    if (feature._rangetype !== 'tiger' ||
        !feature._geometry ||
        (feature._geometry.type !== 'LineString' &&
        feature._geometry.type !== 'MultiLineString')) return;

    var lines = feature._geometry.type === 'MultiLineString' ?
        feature._geometry.coordinates :
        [feature._geometry.coordinates];

    var lf = Array.isArray(feature._lfromhn) ? feature._lfromhn : feature._lfromhn ? [feature._lfromhn] : [];
    var lt = Array.isArray(feature._ltohn)   ? feature._ltohn : feature._ltohn ? [feature._ltohn] : [];
    var rf = Array.isArray(feature._rfromhn) ? feature._rfromhn : feature._rfromhn ? [feature._rfromhn] : [];
    var rt = Array.isArray(feature._rtohn)   ? feature._rtohn : feature._rtohn ? [feature._rtohn] : [];
    var lp = Array.isArray(feature._parityl) ? feature._parityl : feature._parityl ? [feature._parityl] : [];
    var rp = Array.isArray(feature._parityr) ? feature._parityr : feature._parityr ? [feature._parityr] : [];

    for (var i = 0; i < lines.length; i++) {
        var lfromhn = parseSemiNumber(lf[i]),
            rfromhn = parseSemiNumber(rf[i]),
            ltohn = parseSemiNumber(lt[i]),
            rtohn = parseSemiNumber(rt[i]),
            parityl = lp[i] || '',
            parityr = rp[i] || '';

        // no usable data at all
        if ([lfromhn, rfromhn, ltohn, rtohn].every(falsy)) continue;

        var start, end, side, paritymask;

        paritymask = (address % 2) === 0 ? E : O;

        console.log(address + "|L:" + lfromhn + "-" + ltohn + "   |R:" + rfromhn + "-" + rtohn);

        // check left side
        if (typeof lfromhn === 'number' &&
            address >= Math.min(lfromhn,ltohn) &&
            address <= Math.max(lfromhn,ltohn) &&
            paritymask[parityl]) {
            start = lfromhn;
            end = ltohn;
            side ='left';
        } else if (typeof rfromhn === 'number' &&
            address >= Math.min(rfromhn,rtohn) &&
            address <= Math.max(rfromhn,rtohn) &&
            paritymask[parityr]) {
            start = rfromhn;
            end = rtohn;
            side ='right';
        } else {
            continue;
        }

        var reverse = false;
        if (start > end) {
            reverse = true;
            // swap start and end
            var _;
            _ = end;
            end = start;
            start = _;
        }

        // a normalized number between 0 and 1
        var part = (address - start) / (end - start);
        var coords = lines[i].slice(0);

        if (reverse) coords.reverse();

        var distance = calculateDistance(coords);
        var unnorm = part * distance;

        for (var stop = 1; stop < coords.length - 1; stop++) {
            if (coords[stop][2] > unnorm) break;
        }

        var interp = (unnorm - coords[stop - 1][2]) /
            (coords[stop][2] - coords[stop - 1][2]);

        return {
            type:'Point',
            coordinates: [
                coords[stop][0] * interp + coords[stop - 1][0] * (1 - interp),
                coords[stop][1] * interp + coords[stop - 1][1] * (1 - interp)
            ].map(function(v) {
                return Math.round(v*1e6) / 1e6;
            })
        };
    }
};

module.exports.parseSemiNumber = parseSemiNumber;
module.exports.calculateDistance = calculateDistance;

function calculateDistance(coords) {
    var a, b, distance = 0;
    coords[0].push(distance);
    for (var j = 1; j < coords.length; j++) {
        a = coords[j - 1];
        b = coords[j];
        distance += Math.sqrt(
            ((a[0] - b[0]) * (a[0] - b[0])) +
            ((a[1] - b[1]) * (a[1] - b[1])));
        coords[j].push(distance);
    }
    return distance;
}

function parseSemiNumber(_) {
    _ = parseInt((_ || '').replace(/[^\d]/g,''),10);
    return isNaN(_) ? null : _;
}

function falsy(_) { return !_; }
<|endoftext|>


<commit_before><commit_msg>Fix  Unterminated quoted string<commit_after><|endoftext|>


<commit_before>import Navigation from '../index.es6';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import links from '../links';

const registered = [ links.subscribe, links.myeconomist, links.logout ];
describe(`A navigation`, () => {
  describe(`it's a React component`, () => {
    it('is compatible with React.Component', () => {
      Navigation.should.be.a('function').and.respondTo('render');
    });
    it(`it's renders a React element`, () => {
      React.isValidElement(
        <Navigation
          className="navigation navigation--registered navigation--sticked"
          links={registered}
        />).should.equal(true);
    });
  });
  describe('login/logout button', () => {
    it('is a link to /user/login?destination={this.props.currentUrl}', () => {
      const instance = new Navigation({
        currentUrl: '/foo/bar'
      });
      const loginLogoutButton = TestUtils.renderIntoDocument(
        instance.renderLoginLogout()
      );
      const linkButton = TestUtils.findRenderedDOMComponentWithClass(
        loginLogoutButton,
        'navigation__user-menu-link'
      );
      linkButton.props.href.should.equal('https://www.economist.com/user/login?destination=%2Ffoo%2Fbar')
    });
    it('When the user is logged in it\'s a link to /logout?destination={this.props.currentUrl}', () => {
      const instance = new Navigation({
        currentUrl: '/foo/bar',
        userLoggedIn: true,
      });
      instance.renderLoginLogout()
        .props.href.should.equal('https://www.economist.com/logout?destination=%2Ffoo%2Fbar')
    });
  });
});
<commit_msg>update tests<commit_after>import Navigation from '../index.es6';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import links from '../links';

const registered = [ links.subscribe, links.myeconomist, links.logout ];
describe(`A navigation`, () => {
  describe(`it's a React component`, () => {
    it('is compatible with React.Component', () => {
      Navigation.should.be.a('function').and.respondTo('render');
    });
    it(`it's renders a React element`, () => {
      React.isValidElement(
        <Navigation
          className="navigation navigation--registered navigation--sticked"
          links={registered}
        />).should.equal(true);
    });
  });
  describe('login/logout button', () => {
    it('is a link to /user/login?destination={this.props.currentUrl}', () => {
      const instance = new Navigation({
        currentUrl: '/foo/bar'
      });
      const loginLogoutButton = TestUtils.renderIntoDocument(
        instance.renderLoginLogout()
      );
      const linkButton = TestUtils.findRenderedDOMComponentWithClass(
        loginLogoutButton,
        'navigation__user-menu-link'
      );
      linkButton.props.href.should.equal('/user/login?destination=%2Ffoo%2Fbar')
    });
    it('When the user is logged in it\'s a link to /logout?destination={this.props.currentUrl}', () => {
      const instance = new Navigation({
        currentUrl: '/foo/bar',
        userLoggedIn: true,
      });
      instance.renderLoginLogout()
        .props.href.should.equal('/logout?destination=%2Ffoo%2Fbar')
    });
  });
});
<|endoftext|>


<commit_before><commit_msg>rename paddles<commit_after><|endoftext|>


<commit_before>'use strict';

var helpers = require('../helpers');

/**
 * Get the current block within a node
 *
 * @param {Object} node - The node containing our desired block
 * @returns {Object} The current block of the node
 */
var getCurrentNode = function (node) {
  return node.contains('block') ? node.first('block') : false;
};

/**
 * Get the previous node
 *
 * @param {Object} node - Our current node
 * @returns {Object|bool} The previous node or false if not found
 */
var getPreviousNode = function (node) {
  // Rulesets
  if (node.is('ruleset')) {
    return node.contains('selector') ? node.last('selector') : false;
  }

  // Conditonal statements
  if (node.is('conditionalStatement')) {
    var previousParent = node.contains('condition') ? node.last('condition') : false;
    return previousParent && previousParent.contains('atkeyword') ? previousParent.last('atkeyword') : false;
  }

  // Functions, Mixins, Loops
  if (node.is('atrule') || node.is('mixin') || node.is('loop')) {
    return node.contains('atkeyword') ? node.last('atkeyword') : false;
  }
};

/**
 * Determine if current node is an exception and end checks if it is
 *
 * @param {Object} node - The original node
 * @param {object} currentNode - The current node block
 * @param {Object} previousNode - The node previous to our current node
 * @returns {bool} Wether or not the it is an exception
 */
var isException = function (node, currentNode, previousNode) {
  // If we've picked up a return @rule ignore it
  if (node.is('atrule')) {
    if (previousNode.contains('ident') && previousNode.first('ident').content === 'return') {
      return true;
    }
  }
  return false;
};

/**
 * Determine if statement is a single line statement
 *
 * @param {Object} node - The statement to check
 * @returns {bool} True or false
 */
var isSingleLineStatement = function (node) {
  return node.start.line === node.end.line;
};

/**
 * Determine if opening brace of statement is on a new line
 *
 * @param {Object} nodeA - The previous block
 * @param {Object} nodeB - The current block
 * @returns {bool} True or false
 */
var isOpeningBraceOnNewLine = function (nodeA, nodeB) {
  return nodeA.end.line === nodeB.start.line;
};

/**
 * Determine if closing brace of statement is on new line
 *
 * @param {Object} node - The current block
 * @returns {bool|null} True or false if relevant else null
 */
var isClosingBraceOnNewLine = function (node) {
  if (node.contains('block')) {
    var content = node.first('block'),
        contentLength = content.length - 1,
        lastNode = content.get(contentLength);

    if (lastNode.is('space') && helpers.hasEOL(lastNode.content)) {
      return true;
    }
    return false;
  }
  return null;
};

/**
 * Determine if condition starts on a new line by checking the leading node for
 * an end-of-line
 *
 * @param {Object} node - The node that is our condition
 * @param {Object} parentNode - The condition node's parent
 * @param {Number} j - The index of our node in the context of the parent's children
 * @returns {bool|null} True or false if relevant else null
 */
var isConditionOnNewLine = function (node, parentNode, j) {
  // Only check if it's an @else condition
  if (node.contains('ident') && node.first('ident').content === 'else') {
    // Reverse back up tree
    var previousChild = parentNode.get(--j);

    // Determine if we have a leading new line
    if (previousChild.is('space') && helpers.hasEOL(previousChild.content)) {
      return true;
    }
    return false;
  }
  return null;
};

/**
 * Run the rule checks and store return their results
 *
 * @param {Object} node - The original node
 * @param {Object} currentNode - The current node block
 * @param {Object} previousNode - The node previous to our current node
 * @param {Object} parentNode - The parent of the original node
 * @param {int} i - The index of the original node
 * @returns {Object} The results of the rule checks
 */
var runRuleChecks = function (node, currentNode, previousNode, parentNode, i) {
  var checks = {};

  // Determine if single line statement
  checks.singleLineStatement = isSingleLineStatement(node);

  // Determine if condition is on a new line
  if (node.is('atrule') || node.is('conditionalStatement')) {
    checks.conditionOnNewLine = isConditionOnNewLine(previousNode, parentNode, i);
  }

  // Determine if opening brace is on new line
  if (previousNode && currentNode) {
    checks.openingBraceOnNewLine = isOpeningBraceOnNewLine(previousNode, currentNode);
  }

  // Determine if closing brace is on new line
  checks.closingBraceOnNewLine = isClosingBraceOnNewLine(node);

  return checks;
};

/**
 * Create an issue using the supplied information
 *
 * @param {Object} parser - The parser
 * @param {Object} node - The node with the issue
 * @param {string} message - The message to display
 * @returns {Object} An object containing an issue
 */
var createIssue = function (parser, node, message) {
  return {
    'ruleId': parser.rule.name,
    'line': node.end.line,
    'column': node.end.column,
    'message': message,
    'severity': parser.severity
  };
};

module.exports = {
  'name': 'brace-style',
  'defaults': {
    'style': '1tbs',
    'allow-single-line': true
  },
  'detect': function (ast, parser) {
    var result = [];

    ast.traverseByTypes(['conditionalStatement', 'atrule', 'ruleset', 'mixin', 'loop'], function (node, i, parent) {
      var currentNode = false,
          previousNode = false,
          checks = {
            singleLineStatement: null,
            openingBraceOnNewLine: null,
            closingBraceOnNewLine: null,
            conditionOnNewLine: null
          },
          messages = [
            'Single line statements are not allowed',
            'Opening brace must be on same line as condition',
            'Brace must be on a new line',
            'Statement must start on same line as closing brace of previous statement',
            'Statement must begin on a new line',
            'Closing brace must be on a new line'
          ];

      // SCSS syntax only rule
      if (ast.syntax === 'sass') {
        return false;
      }

      // Assign current & previous nodes based on node type
      currentNode = getCurrentNode(node);
      previousNode = getPreviousNode(node);

      // If not an exception carry on
      if (!isException(node, currentNode, previousNode)) {

        // Run and store rule check results
        checks = runRuleChecks(node, currentNode, previousNode, parent, i);

        // Build single-line statement results
        if (checks.singleLineStatement === false && checks.closingBraceOnNewLine === false) {
          result = helpers.addUnique(result, createIssue(parser, currentNode, messages[5]));
        }

        if (checks.singleLineStatement === true) {
          if (parser.options['allow-single-line'] === false) {
            result = helpers.addUnique(result, createIssue(parser, node, messages[0]));
          }
          return false;
        }

        // Build brace-style results
        if (previousNode && currentNode) {
          if (parser.options.style === '1tbs') {
            if (checks.openingBraceOnNewLine === false) {
              result = helpers.addUnique(result, createIssue(parser, currentNode, messages[1]));
            }
            if (checks.conditionOnNewLine === true) {
              result = helpers.addUnique(result, createIssue(parser, previousNode, messages[3]));
            }
          }

          if (parser.options.style === 'stroustrup') {
            if (checks.openingBraceOnNewLine === false) {
              result = helpers.addUnique(result, createIssue(parser, currentNode, messages[1]));
            }
            if (checks.conditionOnNewLine === false) {
              result = helpers.addUnique(result, createIssue(parser, previousNode, messages[4]));
            }
          }

          if (parser.options.style === 'allman') {
            if (checks.openingBraceOnNewLine === true) {
              result = helpers.addUnique(result, createIssue(parser, currentNode, messages[2]));
            }
            if (checks.conditionOnNewLine === false) {
              result = helpers.addUnique(result, createIssue(parser, previousNode, messages[4]));
            }
          }
        }
      }
    });

    return result;
  }
};
<commit_msg>:bug: Fix PR feedback - tweak comments and add fallbacks<commit_after>'use strict';

var helpers = require('../helpers');

/**
 * Get the current block within a node
 *
 * @param {Object} node - The node containing our desired block
 * @returns {Object} The current block of the node
 */
var getCurrentNode = function (node) {
  return node.contains('block') ? node.first('block') : false;
};

/**
 * Get the previous node
 *
 * @param {Object} node - Our current node
 * @returns {Object|bool} The previous node or false if not found
 */
var getPreviousNode = function (node) {
  // Rulesets
  if (node.is('ruleset')) {
    return node.contains('selector') ? node.last('selector') : false;
  }

  // Conditonal statements
  if (node.is('conditionalStatement')) {
    var previousParent = node.contains('condition') ? node.last('condition') : false;
    return previousParent && previousParent.contains('atkeyword') ? previousParent.last('atkeyword') : false;
  }

  // Functions, Mixins, Loops
  if (node.is('atrule') || node.is('mixin') || node.is('loop')) {
    return node.contains('atkeyword') ? node.last('atkeyword') : false;
  }
};

/**
 * Determine if current node is an exception and end checks if it is
 * If we've picked up a return @rule ignore it
 *
 * @param {Object} node - The original node
 * @param {object} currentNode - The current node block
 * @param {Object} previousNode - The node previous to our current node
 * @returns {bool} Wtether or not the it is an exception
 */
var isException = function (node, currentNode, previousNode) {
  if (node.is('atrule')) {
    if (previousNode.contains('ident') && previousNode.first('ident').content === 'return') {
      return true;
    }
  }
  return false;
};

/**
 * Determine if statement is a single line statement
 *
 * @param {Object} node - The statement to check
 * @returns {bool} True or false
 */
var isSingleLineStatement = function (node) {
  return node.start.line === node.end.line;
};

/**
 * Determine if opening brace of statement is on a new line
 *
 * @param {Object} nodeA - The previous block
 * @param {Object} nodeB - The current block
 * @returns {bool} True or false
 */
var isOpeningBraceOnNewLine = function (nodeA, nodeB) {
  return nodeA.end.line === nodeB.start.line;
};

/**
 * Determine if closing brace of statement is on new line
 *
 * @param {Object} node - The current block
 * @returns {bool|null} True or false if relevant else null
 */
var isClosingBraceOnNewLine = function (node) {
  if (node.contains('block')) {
    var content = node.first('block'),
        contentLength = content.length - 1,
        lastNode = content.get(contentLength);

    if (lastNode.is('space') && helpers.hasEOL(lastNode.content)) {
      return true;
    }
    return false;
  }
  return null;
};

/**
 * Determine if condition starts on a new line by checking the leading node for
 * an end-of-line
 *
 * @param {Object} node - The node that is our condition
 * @param {Object} parentNode - The condition node's parent
 * @param {Number} j - The index of our node in the context of the parent's children
 * @returns {bool|null} True or false if relevant else null
 */
var isConditionOnNewLine = function (node, parentNode, j) {
  // Only check if it's an @else condition
  if (node.contains('ident') && node.first('ident').content === 'else') {
    // Reverse back up tree
    var previousChild = parentNode.get(--j) || false;

    if (previousChild) {
      // Determine if we have a leading new line
      if (previousChild.is('space') && helpers.hasEOL(previousChild.content)) {
        return true;
      }
      return false;
    }
    return false;
  }
  return null;
};

/**
 * Run the rule checks and return their results
 *
 * @param {Object} node - The original node
 * @param {Object} currentNode - The current node block
 * @param {Object} previousNode - The node previous to our current node
 * @param {Object} parentNode - The parent of the original node
 * @param {int} index - The index of the original node
 * @returns {Object} The results of the rule checks
 */
var runRuleChecks = function (node, currentNode, previousNode, parentNode, index) {
  var checks = {};

  // Determine if single line statement
  checks.singleLineStatement = isSingleLineStatement(node);

  // Determine if condition is on a new line
  if (node.is('atrule') || node.is('conditionalStatement')) {
    checks.conditionOnNewLine = isConditionOnNewLine(previousNode, parentNode, index);
  }

  // Determine if opening brace is on new line
  if (previousNode && currentNode) {
    checks.openingBraceOnNewLine = isOpeningBraceOnNewLine(previousNode, currentNode);
  }

  // Determine if closing brace is on new line
  checks.closingBraceOnNewLine = isClosingBraceOnNewLine(node);

  return checks;
};

/**
 * Create an issue using the supplied information
 *
 * @param {Object} parser - The parser
 * @param {Object} node - The node with the issue
 * @param {string} message - The message to display
 * @returns {Object} An object containing an issue
 */
var createIssue = function (parser, node, message) {
  return {
    'ruleId': parser.rule.name,
    'line': node.end.line,
    'column': node.end.column,
    'message': message,
    'severity': parser.severity
  };
};

module.exports = {
  'name': 'brace-style',
  'defaults': {
    'style': '1tbs',
    'allow-single-line': true
  },
  'detect': function (ast, parser) {
    var result = [];

    ast.traverseByTypes(['conditionalStatement', 'atrule', 'ruleset', 'mixin', 'loop'], function (node, i, parent) {
      var currentNode = false,
          previousNode = false,
          checks = {
            singleLineStatement: null,
            openingBraceOnNewLine: null,
            closingBraceOnNewLine: null,
            conditionOnNewLine: null
          },
          messages = [
            'Single line statements are not allowed',
            'Opening brace must be on the same line as condition',
            'Brace must be on a new line',
            'Statement must start on the same line as the closing brace of the previous statement',
            'Statement must begin on a new line',
            'Closing brace must be on a new line'
          ];

      // SCSS syntax only rule
      if (ast.syntax === 'sass') {
        return false;
      }

      // Assign current & previous nodes based on node type
      currentNode = getCurrentNode(node);
      previousNode = getPreviousNode(node);

      // If not an exception carry on
      if (!isException(node, currentNode, previousNode)) {

        // Run and store rule check results
        checks = runRuleChecks(node, currentNode, previousNode, parent, i);

        // Build single-line statement results
        if (checks.singleLineStatement === false && checks.closingBraceOnNewLine === false) {
          result = helpers.addUnique(result, createIssue(parser, currentNode, messages[5]));
        }

        if (checks.singleLineStatement === true) {
          if (parser.options['allow-single-line'] === false) {
            result = helpers.addUnique(result, createIssue(parser, node, messages[0]));
          }
          return false;
        }

        // Build brace-style results
        if (previousNode && currentNode) {
          if (parser.options.style === '1tbs') {
            if (checks.openingBraceOnNewLine === false) {
              result = helpers.addUnique(result, createIssue(parser, currentNode, messages[1]));
            }
            if (checks.conditionOnNewLine === true) {
              result = helpers.addUnique(result, createIssue(parser, previousNode, messages[3]));
            }
          }

          if (parser.options.style === 'stroustrup') {
            if (checks.openingBraceOnNewLine === false) {
              result = helpers.addUnique(result, createIssue(parser, currentNode, messages[1]));
            }
            if (checks.conditionOnNewLine === false) {
              result = helpers.addUnique(result, createIssue(parser, previousNode, messages[4]));
            }
          }

          if (parser.options.style === 'allman') {
            if (checks.openingBraceOnNewLine === true) {
              result = helpers.addUnique(result, createIssue(parser, currentNode, messages[2]));
            }
            if (checks.conditionOnNewLine === false) {
              result = helpers.addUnique(result, createIssue(parser, previousNode, messages[4]));
            }
          }
        }
      }
    });

    return result;
  }
};
<|endoftext|>


<commit_before>/**
 * Pseudo-rule for metadata extraction: rectrack.
 */

exports.name = 'metadata.rectrack';

exports.check = function(sr, done) {

    var dts = sr.extractHeaders()
    ,   result = {};

    var $linkThis = (dts.This) ? dts.This.dd.find("a").first() : null;
    if ($linkThis && $linkThis.length)
      result['thisVersion'] = $linkThis.attr('href').trim();

    var $linkLate = (dts.Latest) ? dts.Latest.dd.find("a").first() : null;
    if ($linkLate && $linkLate.length)
        result['latestVersion'] = $linkLate.attr('href').trim();

    var $linkPrev = (dts.Previous) ? dts.Previous.dd.find("a").first() : null;
    if ($linkPrev && $linkPrev.length)
        result['previousVersion'] = $linkPrev.attr('href').trim();

    var $linkEd = (dts.Editor) ? dts.Editor.dd.find("a").first() : null;
    if ($linkEd && $linkEd.length)
        result['editorsDraft'] = $linkEd.attr('href').trim();

    return done(result);
};
<commit_msg>metadata.dl: fix wrong name<commit_after>/**
 * Pseudo-rule for metadata extraction: dl.
 */

exports.name = 'metadata.dl';

exports.check = function(sr, done) {

    var dts = sr.extractHeaders()
    ,   result = {};

    var $linkThis = (dts.This) ? dts.This.dd.find("a").first() : null;
    if ($linkThis && $linkThis.length)
      result['thisVersion'] = $linkThis.attr('href').trim();

    var $linkLate = (dts.Latest) ? dts.Latest.dd.find("a").first() : null;
    if ($linkLate && $linkLate.length)
        result['latestVersion'] = $linkLate.attr('href').trim();

    var $linkPrev = (dts.Previous) ? dts.Previous.dd.find("a").first() : null;
    if ($linkPrev && $linkPrev.length)
        result['previousVersion'] = $linkPrev.attr('href').trim();

    var $linkEd = (dts.Editor) ? dts.Editor.dd.find("a").first() : null;
    if ($linkEd && $linkEd.length)
        result['editorsDraft'] = $linkEd.attr('href').trim();

    return done(result);
};
<|endoftext|>


<commit_before>var tap = require('tap')
  , test = tap.test
  , util = require('util')
  , request = require('request')
  , traceback = require('traceback')

var lib = require('../lib')
  , follow = require('../api')
  , DB = process.env.db || 'http://localhost:5984/follow_test'

test('Issue #8', function(t) {
  var timeouts = timeout_tracker()

  // Detect inappropriate timeouts after the run.
  var runs = {'set':false, 'clear':false}
  function badSetT() {
    runs.set = true
    return setTimeout.apply(this, arguments)
  }

  function badClearT() {
    runs.clear = true
    return clearTimeout.apply(this, arguments)
  }

  follow(DB, function(er, change) {
    t.false(er, 'Got a feed')
    t.equal(change.seq, 1, 'Handler only runs for one change')

    this.on('stop', check_timeouts)
    this.stop()

    function check_timeouts() {
      t.equal(timeouts().length, 0, 'No timeouts by the time stop fires')

      lib.timeouts(badSetT, badClearT)

      // And give it a moment to try something bad.
      setTimeout(final_timeout_check, 250)
      function final_timeout_check() {
        t.equal(timeouts().length, 0, 'No lingering timeouts after teardown: ' + tims(timeouts()))
        t.false(runs.set, 'No more setTimeouts ran')
        t.false(runs.clear, 'No more clearTimeouts ran')

        t.end()
      }
    }
  })
})

test('Issue #9', function(t) {
  var timeouts = timeout_tracker()

  follow({db:DB, inactivity_ms:30000}, function(er, change) {
    if(change.seq == 1)
      return // Let it run through once, just for fun.

    t.equal(change.seq, 2, 'The second change will be the last')
    this.stop()

    setTimeout(check_inactivity_timer, 250)
    function check_inactivity_timer() {
      t.equal(timeouts().length, 0, 'No lingering timeouts after teardown: ' + tims(timeouts()))
      timeouts().forEach(function(id) { clearTimeout(id) })
      t.end()
    }
  })
})

//
// Utilities
//

function timeout_tracker() {
  // Return an array tracking in-flight timeouts.
  var timeouts = []
  var set_num = 0

  lib.timeouts(set, clear)
  return function() { return timeouts }

  function set() {
    var result = setTimeout.apply(this, arguments)

    var caller = traceback()[2]
    set_num += 1
    result.caller = '('+set_num+') ' + (caller.method || caller.name || '<a>') + ' in ' + caller.file + ':' + caller.line
    //console.error('setTimeout: ' + result.caller)

    timeouts.push(result)
    //console.error('inflight ('+timeouts.length+'): ' + tims(timeouts))
    return result
  }

  function clear(id) {
    //var caller = traceback()[2]
    //caller = (caller.method || caller.name || '<a>') + ' in ' + caller.file + ':' + caller.line
    //console.error('clearTimeout: ' + (id && id.caller) + ' <- ' + caller)

    timeouts = timeouts.filter(function(element) { return element !== id })
    //console.error('inflight ('+timeouts.length+'): ' + tims(timeouts))
    return clearTimeout.apply(this, arguments)
  }
}

function tims(arr) {
  return JSON.stringify(arr.map(function(timer) { return timer.caller }))
}
<commit_msg>Use the couch helper library<commit_after>var tap = require('tap')
  , test = tap.test
  , util = require('util')
  , request = require('request')
  , traceback = require('traceback')

var lib = require('../lib')
  , couch = require('./couch')
  , follow = require('../api')

couch.setup(test)

test('Issue #8', function(t) {
  var timeouts = timeout_tracker()

  // Detect inappropriate timeouts after the run.
  var runs = {'set':false, 'clear':false}
  function badSetT() {
    runs.set = true
    return setTimeout.apply(this, arguments)
  }

  function badClearT() {
    runs.clear = true
    return clearTimeout.apply(this, arguments)
  }

  follow(couch.DB, function(er, change) {
    t.false(er, 'Got a feed')
    t.equal(change.seq, 1, 'Handler only runs for one change')

    this.on('stop', check_timeouts)
    this.stop()

    function check_timeouts() {
      t.equal(timeouts().length, 0, 'No timeouts by the time stop fires')

      lib.timeouts(badSetT, badClearT)

      // And give it a moment to try something bad.
      setTimeout(final_timeout_check, 250)
      function final_timeout_check() {
        t.equal(timeouts().length, 0, 'No lingering timeouts after teardown: ' + tims(timeouts()))
        t.false(runs.set, 'No more setTimeouts ran')
        t.false(runs.clear, 'No more clearTimeouts ran')

        t.end()
      }
    }
  })
})

test('Issue #9', function(t) {
  var timeouts = timeout_tracker()

  follow({db:couch.DB, inactivity_ms:30000}, function(er, change) {
    if(change.seq == 1)
      return // Let it run through once, just for fun.

    t.equal(change.seq, 2, 'The second change will be the last')
    this.stop()

    setTimeout(check_inactivity_timer, 250)
    function check_inactivity_timer() {
      t.equal(timeouts().length, 0, 'No lingering timeouts after teardown: ' + tims(timeouts()))
      timeouts().forEach(function(id) { clearTimeout(id) })
      t.end()
    }
  })
})

//
// Utilities
//

function timeout_tracker() {
  // Return an array tracking in-flight timeouts.
  var timeouts = []
  var set_num = 0

  lib.timeouts(set, clear)
  return function() { return timeouts }

  function set() {
    var result = setTimeout.apply(this, arguments)

    var caller = traceback()[2]
    set_num += 1
    result.caller = '('+set_num+') ' + (caller.method || caller.name || '<a>') + ' in ' + caller.file + ':' + caller.line
    //console.error('setTimeout: ' + result.caller)

    timeouts.push(result)
    //console.error('inflight ('+timeouts.length+'): ' + tims(timeouts))
    return result
  }

  function clear(id) {
    //var caller = traceback()[2]
    //caller = (caller.method || caller.name || '<a>') + ' in ' + caller.file + ':' + caller.line
    //console.error('clearTimeout: ' + (id && id.caller) + ' <- ' + caller)

    timeouts = timeouts.filter(function(element) { return element !== id })
    //console.error('inflight ('+timeouts.length+'): ' + tims(timeouts))
    return clearTimeout.apply(this, arguments)
  }
}

function tims(arr) {
  return JSON.stringify(arr.map(function(timer) { return timer.caller }))
}
<|endoftext|>


<commit_before>var assert = require('assert');
describe('test mapper api', function() {
  it('should declare', function(done) {
    done();
  });
});<commit_msg>add tests over mapper<commit_after>var assert = require('assert');
describe('test mapper api', function() {
  var couchbase;
  it('should declare', function(done) {
    require('../main')().then(function(api) {
      couchbase = api;
      var test = couchbase.declare('test', {
        fields: {
          foo: {
            type: 'string',
            required: true,
            index: true
          },
          bar: {
            type: 'number'
          }
        }
      });
      // check the api
      assert(test.create instanceof Function);
      assert(test.find instanceof Function);
      assert(test.setup instanceof Function);
      assert(test.options.fields.foo.validate.type instanceof Function);
      assert(test.options.fields.foo.validate.contents instanceof Function);
      assert(test.options.type === 'test');
      // setup the couchbase server
      test.setup().then(function() {
        done();
      }).done();
    }).done();
  });
  it('should create some data', function(done) {
    var entry = couchbase.get('test').create({
      foo: 'oof', bar: 123
    });
    assert(entry.foo === 'oof');
    assert(entry.bar === 123);
    assert(entry._id === false);
    entry.save().then(function() {
      assert(entry._id !== false, 'should have an ID');
      done();
    }).done();
  });
  it('should find some data', function(done) {
    couchbase.get('test').find('foo', 'oof').then(function(results) {
      assert(results.length > 0);
      done();
    }).done();
  });
});<|endoftext|>


<commit_before>'use strict';
const expect = require('unexpected'),
	dayjs = require('dayjs');

const processVoid = require('process-void');
const spawnpoint = require.resolve('..');

const timeFormat = {
	format: '{date} {type}: {line}',
	time: "HH:mm",
	date: "dddd, MMMM DD YYYY"
};

const datePattern = /\[(Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day, (January ([012]\d|3[01])|February [012]\d|Ma(rch|y) ([012]\d|3[01])|April ([012]\d|30)|June ([012]\d|30)|July ([012]\d|3[01])|August ([012]\d|3[01])|(Sept|Nov)ember ([012]\d|30)|(Octo|Decem)ber ([012]\d|3[01])) \d{4}\]/;

// resources for creating tests:
// https://sinonjs.org/
// https://github.com/elliotf/mocha-sinon
// https://github.com/mochajs/mocha/issues/1582

/**
 * Checks time from test to currentTime generated by test
 * @param  {Buffer} data recieved from 'app.stdout.data'
 * @param  {String} time recieved from 'time = currentTime.format(timeFormat.time)'
 */
const reformTimeData = (data, time) => {
	time = '[' + time + ']';
	let dataTime = [...data].slice(0, 7);
	let remains = [...data].slice(7, [...data].length);

	if(Buffer.from(dataTime).toString() !== time){
		let newTime = subtractOneMinute(dataTime);
		let newTimeString = Buffer.from(newTime).toString();
		if(newTimeString !== time){
			return Buffer.from('Check reformTimeData(), result was: ' + Buffer.from(newTime.concat(remains)).toString());
		}else{
			return Buffer.from(newTime.concat(remains));
		}
	}else{
		return data;
	}
};

/**
 * Adds 1 minute to a buffered string (e.g. [13:37]) converted to Array
 * @param  {Array} time buffered string (e.g. '[13:37]') converted to Array
 */
const subtractOneMinute = (time) => {
	let t = time;
	console.log('t: ' + t);
	t[5]--;
	if(t[5] === 47){
		t[5] = 57;
		t[4]--;
		if(t[4] === 47){
			t[4] = 53;
			t[2]--;
			if(t[2] === 47){
				t[2] = 57;
				t[1]--;
				if(t[1] === 47){
					t[1] = 50;
					t[2] = 51;
				}
			}
		}
	}

	return t;
};

describe('spawnpoint.debug', () => {
	it('should output Test', (done) => {
		const app = new processVoid(done, spawnpoint, { 'construct': true });
		void app.stdout.once('data', (data) => {
			expect(data, 'when decoded as', 'utf-8', 'to equal', 'Test\n');
			void app.done();
		});
		app.config.debug = true;
		void app.debug("Test");
	});
});

describe('spawnpoint.log', () => {
	it('should output Test', (done) => {
		const app = new processVoid(done, spawnpoint, { 'construct': true });
		app.stdout.once('data', (data) => {
			let currentTime = dayjs();
			if(datePattern.test(data)){
				let date = currentTime.format(timeFormat.date);
				expect(data, 'when decoded as', 'utf-8', 'to equal', `[${date}]\n`);
				app.stdout.once('data', (data) => {
					let time = currentTime.format(timeFormat.time);
					data = reformTimeData(data, time);
					expect(data, 'when decoded as', 'utf-8', 'to equal', `[${time}] [LOG]: Test\n`);
					void app.done();
				});
			}else{
				let time = currentTime.format(timeFormat.time);
				data = reformTimeData(data, time);
				expect(data, 'when decoded as', 'utf-8', 'to equal', `[${time}] [LOG]: Test\n`);
				void app.done();
			}
		});
		//app.send({"set": {'key': 'config.log', 'value': timeFormat}});
		app.config.log = timeFormat;
		//app.send({'command': 'log', args: ["Test"]});
		app.log("Test");
	});
});

describe('spawnpoint.info', () => {
	it('should output Test', (done) => {
		//const app = fork('./autoload-void', [''], { 'silent': true });
		const app = new processVoid(done, spawnpoint, { 'construct': true });
		app.stdout.once('data', (data) => {
			let currentTime = dayjs();
			if(datePattern.test(data)){
				let date = currentTime.format(timeFormat.date);
				expect(data, 'when decoded as', 'utf-8', 'to equal', `[${date}]\n`);
				app.stdout.once('data', (data) => {
					let time = currentTime.format(timeFormat.time);
					data = reformTimeData(data, time);
					expect(data, 'when decoded as', 'utf-8', 'to equal', `[${time}] [INFO]: Test\n`);
					void app.done();
				});
			}else{
				let time = currentTime.format(timeFormat.time);
				data = reformTimeData(data, time);
				expect(data, 'when decoded as', 'utf-8', 'to equal', `[${time}] [INFO]: Test\n`);
				void app.done();
			}
		});
		//app.send({"set": {'key': 'config.log', 'value': timeFormat}});
		app.config.log = timeFormat;
		app.info("Test");
		//app.send({'command': 'info', args: ["Test"]});
	});
});

describe('spawnpoint.warn', () => {
	it('should output Test', (done) => {
		const app = new processVoid(done, spawnpoint, { 'construct': true });
		let currentTime = dayjs();
		app.stdout.once('data', (data) => {
			let date = currentTime.format(timeFormat.date);
			expect(data, 'when decoded as', 'utf-8', 'to equal', `[${date}]\n`);
		});
		app.stderr.once('data', (data) => {
			let time = currentTime.format(timeFormat.time);
			data = reformTimeData(data, time);
			expect(data, 'when decoded as', 'utf-8', 'to equal', `[${time}] [WARN]: Test\n`);
			void app.done();
		});
		app.config.log = timeFormat;
		app.warn("Test");
	});
});

describe('spawnpoint.error', () => {
	it('should output Test', (done) => {
		const app = new processVoid(done, spawnpoint, { 'construct': true });
		let currentTime = dayjs();
		app.stdout.once('data', (data) => {
			let date = currentTime.format(timeFormat.date);
			expect(data, 'when decoded as', 'utf-8', 'to equal', `[${date}]\n`);
		});
		app.stderr.once('data', (data) => {
			let time = currentTime.format(timeFormat.time);
			data = reformTimeData(data, time);
			expect(data, 'when decoded as', 'utf-8', 'to equal', `[${time}] [ERROR]: Test\n`);
			void app.done();
		});
		app.config.log = timeFormat;
		app.error("Test");
	});
});<commit_msg>commented subtractOneMinute<commit_after>'use strict';
const expect = require('unexpected'),
	dayjs = require('dayjs');

const processVoid = require('process-void');
const spawnpoint = require.resolve('..');

const timeFormat = {
	format: '{date} {type}: {line}',
	time: "HH:mm",
	date: "dddd, MMMM DD YYYY"
};

const datePattern = /\[(Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day, (January ([012]\d|3[01])|February [012]\d|Ma(rch|y) ([012]\d|3[01])|April ([012]\d|30)|June ([012]\d|30)|July ([012]\d|3[01])|August ([012]\d|3[01])|(Sept|Nov)ember ([012]\d|30)|(Octo|Decem)ber ([012]\d|3[01])) \d{4}\]/;

// resources for creating tests:
// https://sinonjs.org/
// https://github.com/elliotf/mocha-sinon
// https://github.com/mochajs/mocha/issues/1582

/**
 * Checks time from test to currentTime generated by test
 * @param  {Buffer} data recieved from 'app.stdout.data'
 * @param  {String} time recieved from 'time = currentTime.format(timeFormat.time)'
 */
const reformTimeData = (data, time) => {
	time = '[' + time + ']';
	let dataTime = [...data].slice(0, 7);
	let remains = [...data].slice(7, [...data].length);

	if(Buffer.from(dataTime).toString() !== time){
		let newTime = subtractOneMinute(dataTime);
		let newTimeString = Buffer.from(newTime).toString();
		if(newTimeString !== time){
			return Buffer.from('Check reformTimeData(), result was: ' + Buffer.from(newTime.concat(remains)).toString());
		}else{
			return Buffer.from(newTime.concat(remains));
		}
	}else{
		return data;
	}
};

/**
 * Adds 1 minute to a buffered string (e.g. [13:37]) converted to Array
 * @param  {Array} time buffered string (e.g. [13:37]) converted to Array
 */
const subtractOneMinute = (time) => {
	let t = time;
	console.log('t: ' + t);
	t[5]--;
	/**
	 * The two digit numbers here are hex number references to a Buffer
	 * hexes 48-57 correspond to 0-9 (as string characters)
	 * The first if loop should be read as:
	 * if(time[seconds] < 0){
	 *   time[seconds] = 9;
	 *   time[minutes]--;
	 *   ...
	*/
	if(t[5] < 48){
		t[5] = 57;
		t[4]--;
		if(t[4] < 48){
			t[4] = 53;
			t[2]--;
			if(t[2] < 48){
				t[2] = 57;
				t[1]--;
				if(t[1] === 47){
					t[1] = 50;
					t[2] = 51;
				}
			}
		}
	}

	return t;
};

describe('spawnpoint.debug', () => {
	it('should output Test', (done) => {
		const app = new processVoid(done, spawnpoint, { 'construct': true });
		void app.stdout.once('data', (data) => {
			expect(data, 'when decoded as', 'utf-8', 'to equal', 'Test\n');
			void app.done();
		});
		app.config.debug = true;
		void app.debug("Test");
	});
});

describe('spawnpoint.log', () => {
	it('should output Test', (done) => {
		const app = new processVoid(done, spawnpoint, { 'construct': true });
		app.stdout.once('data', (data) => {
			let currentTime = dayjs();
			if(datePattern.test(data)){
				let date = currentTime.format(timeFormat.date);
				expect(data, 'when decoded as', 'utf-8', 'to equal', `[${date}]\n`);
				app.stdout.once('data', (data) => {
					let time = currentTime.format(timeFormat.time);
					data = reformTimeData(data, time);
					expect(data, 'when decoded as', 'utf-8', 'to equal', `[${time}] [LOG]: Test\n`);
					void app.done();
				});
			}else{
				let time = currentTime.format(timeFormat.time);
				data = reformTimeData(data, time);
				expect(data, 'when decoded as', 'utf-8', 'to equal', `[${time}] [LOG]: Test\n`);
				void app.done();
			}
		});
		//app.send({"set": {'key': 'config.log', 'value': timeFormat}});
		app.config.log = timeFormat;
		//app.send({'command': 'log', args: ["Test"]});
		app.log("Test");
	});
});

describe('spawnpoint.info', () => {
	it('should output Test', (done) => {
		//const app = fork('./autoload-void', [''], { 'silent': true });
		const app = new processVoid(done, spawnpoint, { 'construct': true });
		app.stdout.once('data', (data) => {
			let currentTime = dayjs();
			if(datePattern.test(data)){
				let date = currentTime.format(timeFormat.date);
				expect(data, 'when decoded as', 'utf-8', 'to equal', `[${date}]\n`);
				app.stdout.once('data', (data) => {
					let time = currentTime.format(timeFormat.time);
					data = reformTimeData(data, time);
					expect(data, 'when decoded as', 'utf-8', 'to equal', `[${time}] [INFO]: Test\n`);
					void app.done();
				});
			}else{
				let time = currentTime.format(timeFormat.time);
				data = reformTimeData(data, time);
				expect(data, 'when decoded as', 'utf-8', 'to equal', `[${time}] [INFO]: Test\n`);
				void app.done();
			}
		});
		//app.send({"set": {'key': 'config.log', 'value': timeFormat}});
		app.config.log = timeFormat;
		app.info("Test");
		//app.send({'command': 'info', args: ["Test"]});
	});
});

describe('spawnpoint.warn', () => {
	it('should output Test', (done) => {
		const app = new processVoid(done, spawnpoint, { 'construct': true });
		let currentTime = dayjs();
		app.stdout.once('data', (data) => {
			let date = currentTime.format(timeFormat.date);
			expect(data, 'when decoded as', 'utf-8', 'to equal', `[${date}]\n`);
		});
		app.stderr.once('data', (data) => {
			let time = currentTime.format(timeFormat.time);
			data = reformTimeData(data, time);
			expect(data, 'when decoded as', 'utf-8', 'to equal', `[${time}] [WARN]: Test\n`);
			void app.done();
		});
		app.config.log = timeFormat;
		app.warn("Test");
	});
});

describe('spawnpoint.error', () => {
	it('should output Test', (done) => {
		const app = new processVoid(done, spawnpoint, { 'construct': true });
		let currentTime = dayjs();
		app.stdout.once('data', (data) => {
			let date = currentTime.format(timeFormat.date);
			expect(data, 'when decoded as', 'utf-8', 'to equal', `[${date}]\n`);
		});
		app.stderr.once('data', (data) => {
			let time = currentTime.format(timeFormat.time);
			data = reformTimeData(data, time);
			expect(data, 'when decoded as', 'utf-8', 'to equal', `[${time}] [ERROR]: Test\n`);
			void app.done();
		});
		app.config.log = timeFormat;
		app.error("Test");
	});
});<|endoftext|>


<commit_before>'use strict';

var stems, path, o, regex;

module.exports = function(Parth){
  var parth = new Parth();

  it('can be given as a string regex', function(){
    stems = 'post /:number(\\d+)';
    path = 'post /1/?query';
    parth.set(stems);
    regex = parth.get(path, (o = { }));

    o.path.should.be.eql(path.replace(/\/\?[^ ]+/, ''));
    regex.path.should.be.eql(stems);
  });

  it('will contain all parameter keys at _', function(){
    stems = 'post /:word(\\w+)/:number(\\d+)';
    path = 'post /page/1/?query';
    parth.set(stems);
    parth.get(path, (o = { }));
    o.params._.should.be.eql(['word', 'number']);
  });

  it('parameter values should be at params', function(){
    stems = ':method(get|post) /hello/:there/:you';
    path = 'post /hello/awesome/10/?query#hash';
    parth.set(stems);
    regex = parth.get(path, (o = { }));

    o.path.should.be.eql(path.replace(/\/\?[^ ]+/, ''));
    regex.path.should.be.eql(stems);

    o.params.should.be.eql({
      _ : ['method', 'there', 'you'],
      method: 'post',
      there: 'awesome',
      you: '10'
    });
  });
};
<commit_msg>update tests<commit_after>'use strict';

var stems, path, o, regex;

module.exports = function(Parth){
  var parth = new Parth();

  it('can be given as a string regex', function(){
    stems = 'post /:number(\\d+)';
    path = 'post /1/?query';
    parth.set(stems);
    regex = parth.get(path, (o = { }));

    o.path.should.be.eql(path.replace(/\/\?[^ ]+/, ''));
    regex.path.should.be.eql(stems);
  });

  it('will contain all parameter keys at _', function(){
    stems = 'post /:word(\\w+)/:number(\\d+)';
    path = 'post /page/1/?query';
    parth.set(stems);
    parth.get(path, (o = { }));
    o.params._.should.be.eql(['word', 'number']);
  });

  it('parameter values should be at params', function(){
    stems = ':method(get|post) /hello/:there/:you';
    path = 'post /hello/awesome/10/?query#hash';
    parth.set(stems);
    regex = parth.get(path, (o = { }));

    o.path.should.be.eql(path.replace(/\/\?[^ ]+/, ''));
    regex.path.should.be.eql(stems);

    o.params.should.be.eql({
      _ : ['method', 'there', 'you'],
      method: 'post',
      there: 'awesome',
      you: 10
    });
  });
};
<|endoftext|>