<commit_before>var request = require('request');

module.exports = {
  _getBaseUrl: function (req) {
    return req.protocol + '://' + req.get('host');
  },

  /**
   * Exchange a LinkedIn authentication code for a OAuth access token.
   *
   * @method
   * @private
   *
   * @param {Object} req - The http request.
   * @param {string} config - The Stormpath express config object.
   * @param {string} callback - The callback to call once a response has been resolved.
   */
  exchangeAuthCodeForAccessToken: function (req, config, callback) {
    var linkedInAuthUrl = 'https://www.linkedin.com/uas/oauth2/accessToken';
    var linkedInProvider = config.socialProviders.linkedin;

    var options = {
      form: {
        grant_type: 'authorization_code',
        code: req.query.code,
        redirect_uri: this._getBaseUrl(req) + linkedInProvider.callbackUri,
        client_id: linkedInProvider.clientId,
        client_secret: linkedInProvider.clientSecret
      }
    };

    request.post(linkedInAuthUrl, options, function (err, result, body) {
      var parsedBody;

      try {
        parsedBody = JSON.parse(body);
      } catch (err) {
        return callback(err);
      }

      callback(err, parsedBody.access_token);
    });
  }
};<commit_msg>Enabling strict mode.<commit_after>'use strict';

var request = require('request');

module.exports = {
  _getBaseUrl: function (req) {
    return req.protocol + '://' + req.get('host');
  },

  /**
   * Exchange a LinkedIn authentication code for a OAuth access token.
   *
   * @method
   * @private
   *
   * @param {Object} req - The http request.
   * @param {string} config - The Stormpath express config object.
   * @param {string} callback - The callback to call once a response has been resolved.
   */
  exchangeAuthCodeForAccessToken: function (req, config, callback) {
    var linkedInAuthUrl = 'https://www.linkedin.com/uas/oauth2/accessToken';
    var linkedInProvider = config.socialProviders.linkedin;

    var options = {
      form: {
        grant_type: 'authorization_code',
        code: req.query.code,
        redirect_uri: this._getBaseUrl(req) + linkedInProvider.callbackUri,
        client_id: linkedInProvider.clientId,
        client_secret: linkedInProvider.clientSecret
      }
    };

    request.post(linkedInAuthUrl, options, function (err, result, body) {
      var parsedBody;

      try {
        parsedBody = JSON.parse(body);
      } catch (err) {
        return callback(err);
      }

      callback(err, parsedBody.access_token);
    });
  }
};
<|endoftext|>


<commit_before>module.exports = {
    root: __dirname + '/../',
    pathIgnore: ['*node_modules*']
};

var options = {
    adsafe: false,
    bitwise: true,
    browser: false,
    cap: false,
    confusion: false,
    continue: true,
    css: false,
    debug: false,
    devel: true,
    eqeq: false,
    es5: true,
    evil: true,
    forin: false,
    fragment: false,
    indent: 4,
    maxerr: 300,
    maxlen: 600,
    newcap: true,
    node: true, // jslint.com has an option for node, but the node module is not up to date yet
    nomen: true,
    on: false,
    passfail: false,
    plusplus: false,
    predef: [],
    regexp: true,
    rhino: false,
    safe: false,
    sloppy: true,
    sub: false,
    undef: false,
    unparam: false,
    vars: false,
    white: false,
    widget: false,
    windows: false
};

<commit_msg>remove comment<commit_after>module.exports = {
    root: __dirname + '/../',
    pathIgnore: ['*node_modules*']
};

var options = {
    adsafe: false,
    bitwise: true,
    browser: false,
    cap: false,
    confusion: false,
    continue: true,
    css: false,
    debug: false,
    devel: true,
    eqeq: false,
    es5: true,
    evil: true,
    forin: false,
    fragment: false,
    indent: 4,
    maxerr: 300,
    maxlen: 600,
    newcap: true,
    node: true,
    nomen: true,
    on: false,
    passfail: false,
    plusplus: false,
    predef: [],
    regexp: true,
    rhino: false,
    safe: false,
    sloppy: true,
    sub: false,
    undef: false,
    unparam: false,
    vars: false,
    white: false,
    widget: false,
    windows: false
};

<|endoftext|>


<commit_before>
/*******************************************************************************
 * Copyright (c) 2016 Nicola Del Gobbo
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the license at http://www.apache.org/licenses/LICENSE-2.0
 *
 * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
 * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
 * IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
 * MERCHANTABLITY OR NON-INFRINGEMENT.
 *
 * See the Apache Version 2.0 License for specific language governing
 * permissions and limitations under the License.
 *
 * Contributors - initial API implementation:
 * Nicola Del Gobbo <nicoladelgobbo@gmail.com>
 ******************************************************************************/

'use strict';

/*!
 * Module dependencies
 */
const bodyParser = require('body-parser');
const express = require('express');
const formidable = require('formidable');
const fs = require('fs-extra');
const http = require('http');
const HttpClient = require('../');

const port = 9999;
const host = "127.0.0.1";

describe("Test yahc", function () {

  // Set express app to test the rest client
  const app = express();
  app
  .use(
    bodyParser
    .json(
      {
        strict: true,
        inflate: true,
        limit: "5mb"
      }
    )
  );
  app
  .use(
    bodyParser
    .urlencoded(
      {
        extended: false,
        inflate: true,
        limit: "5mb",
        parameterLimit: 1000
      }
    )
  );
  app.get("/get", function (req, res) {
    res.send("Come up to meet you, tell you I'm sorry");
  });
  app.get("/get-json", function (req, res) {
    res.status(200).json({message: "Come up to meet you, tell you I'm sorry"});
  });
  app.post("/post", function (req, res) {

  });
  app.post("/post-json", function (req, res) {

  });
  app.post("/post-form-data", function (req, res) {

  });
  app.put("/put", function (req, res) {

  });
  app.put("/put-json", function (req, res) {

  });
  app.put("/put-form-data", function (req, res) {

  });
  app.delete("/delete", function (req, res) {

  });
  app.delete("/delete-json", function (req, res) {

  });
  http.createServer(app).listen(9999, '127.0.0.1');

  it(
    "GET - application/x-www-form-urlencoded",
    function (done) {
      HttpClient.get({
        url: "http://" + host + ":" + port + "/get",
        headers: {},
        qs: {},
        encType: HttpClient.ENC_TYPES.X_WWW_FORM_URLENCODED,
        isJson: false,
        timeout: 3000
      })
      .then((response) => {
        console.log(response);
        done();
      })
      .catch((err) => {
        console.log(err);
        done();
      });
    }
  );

  it(
    "GET - application/x-www-form-urlencoded - json",
    function (done) {
       HttpClient.get({
        url: "http://" + host + ":" + port + "/get-json",
        headers: {},
        qs: {},
        encType: HttpClient.ENC_TYPES.X_WWW_FORM_URLENCODED,
        isJson: true,
        timeout: 3000
      })
      .then((response) => {
        console.log(response);
        done();
      })
      .catch((err) => {
        console.log(err);
        done();
      });
    }
  );

  it(
    "POST - application/x-www-form-urlencoded",
    function (done) {
      done();
    }
  );

  it(
    "POST - application/x-www-form-urlencoded - json",
    function (done) {
      done();
    }
  );

  it(
    "POST - multipart/form-data",
    function (done) {
      done();
    }
  );

  it(
    "PUT - application/x-www-form-urlencoded",
    function (done) {
      done();
    }
  );

  it(
    "PUT -  application/x-www-form-urlencoded - json",
    function (done) {
      done();
    }
  );

  it(
    "PUT - multipart/form-data",
    function (done) {
      done();
    }
  );

  it(
    "DELETE - application/x-www-form-urlencoded",
    function (done) {
      done();
    }
  );

  it(
    "DELETE - application/x-www-form-urlencoded - json",
    function (done) {
      done();
    }
  );

});
<commit_msg>Added some tests for method get<commit_after>
/*******************************************************************************
 * Copyright (c) 2016 Nicola Del Gobbo
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the license at http://www.apache.org/licenses/LICENSE-2.0
 *
 * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
 * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
 * IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
 * MERCHANTABLITY OR NON-INFRINGEMENT.
 *
 * See the Apache Version 2.0 License for specific language governing
 * permissions and limitations under the License.
 *
 * Contributors - initial API implementation:
 * Nicola Del Gobbo <nicoladelgobbo@gmail.com>
 ******************************************************************************/

'use strict';

/*!
 * Module dependencies
 */
const bodyParser = require('body-parser');
const express = require('express');
const formidable = require('formidable');
const fs = require('fs-extra');
const http = require('http');
const HttpClient = require('../');

const port = 9999;
const host = "127.0.0.1";

describe("Test yahc", function () {

  // Set express app to test the rest client
  const app = express();
  app
  .use(
    bodyParser
    .json(
      {
        strict: true,
        inflate: true,
        limit: "5mb"
      }
    )
  );
  app
  .use(
    bodyParser
    .urlencoded(
      {
        extended: false,
        inflate: true,
        limit: "5mb",
        parameterLimit: 1000
      }
    )
  );
  app.get("/get", function (req, res) {
    res.send("Come up to meet you, tell you I'm sorry");
  });
  app.get("/get-json", function (req, res) {
    res.status(200).json({message: "Come up to meet you, tell you I'm sorry"});
  });
  app.post("/post", function (req, res) {

  });
  app.post("/post-json", function (req, res) {

  });
  app.post("/post-form-data", function (req, res) {

  });
  app.put("/put", function (req, res) {

  });
  app.put("/put-json", function (req, res) {

  });
  app.put("/put-form-data", function (req, res) {

  });
  app.delete("/delete", function (req, res) {

  });
  app.delete("/delete-json", function (req, res) {

  });
  http.createServer(app).listen(9999, '127.0.0.1');

  it(
    "GET - application/x-www-form-urlencoded",
    function (done) {
      HttpClient.get({
        url: "http://" + host + ":" + port + "/get",
        headers: {},
        qs: {},
        encType: HttpClient.ENC_TYPES.X_WWW_FORM_URLENCODED,
        isJson: false,
        timeout: HttpClient.DEFAULT_TIMEOUT
      })
      .then((response) => {
        expect(response.body).toBe("Come up to meet you, tell you I'm sorry");
        expect(response.statusCode).toEqual(200);
        expect(response.headers).not.toBeUndefined();
        done();
      })
      .catch((err) => {
        expect(err).toBeUndefined();
        done();
      });
    }
  );

  it(
    "GET - application/x-www-form-urlencoded - json",
    function (done) {
       HttpClient.get({
        url: "http://" + host + ":" + port + "/get-json",
        headers: {},
        qs: {},
        encType: HttpClient.ENC_TYPES.X_WWW_FORM_URLENCODED,
        isJson: true,
        timeout: 3000
      })
      .then((response) => {
        expect(response.body)
        .toEqual({message: "Come up to meet you, tell you I'm sorry"});
        expect(response.statusCode).toEqual(200);
        expect(response.headers).not.toBeUndefined();
        done();
      })
      .catch((err) => {
        expect(err).toBeUndefined();
        done();
      });
    }
  );

  it(
    "POST - application/x-www-form-urlencoded",
    function (done) {
      done();
    }
  );

  it(
    "POST - application/x-www-form-urlencoded - json",
    function (done) {
      done();
    }
  );

  it(
    "POST - multipart/form-data",
    function (done) {
      done();
    }
  );

  it(
    "PUT - application/x-www-form-urlencoded",
    function (done) {
      done();
    }
  );

  it(
    "PUT -  application/x-www-form-urlencoded - json",
    function (done) {
      done();
    }
  );

  it(
    "PUT - multipart/form-data",
    function (done) {
      done();
    }
  );

  it(
    "DELETE - application/x-www-form-urlencoded",
    function (done) {
      done();
    }
  );

  it(
    "DELETE - application/x-www-form-urlencoded - json",
    function (done) {
      done();
    }
  );

});
<|endoftext|>


<commit_before>function findESNamedExports(node) {
  if (node.type !== 'ExportNamedDeclaration') {
    return [];
  }

  if (node.specifiers.length) {
    return node.specifiers.map(({ exported: { name } }) => name);
  }
  if (node.declaration) {
    return node.declaration.declarations.map(({ id: { name } }) => name);
  }
  return [];
}

function findCommonJSExports(node, definedObjectExpressions) {
  if (node.type !== 'ExpressionStatement') {
    return [];
  }
  // Potential CommonJS export
  const { left, right } = node.expression;
  if (!left || !right) {
    return [];
  }
  if (left.object.name === 'module' &&
    left.property.name === 'exports') {
    let objectExpression;
    if (right.type === 'ObjectExpression') {
      objectExpression = right;
    }
    if (right.type === 'Identifier') {
      objectExpression = definedObjectExpressions[right.name];
    }
    if (objectExpression) {
      return objectExpression.properties.map(({ key }) => key.name).filter(Boolean);
    }
  }
  return [];
}

function findDefinedObjectExpressions(node) {
  if (node.type !== 'VariableDeclaration') {
    return {};
  }
  const result = {};
  node.declarations.forEach(({ id, init }) => {
    if (init.type !== 'ObjectExpression') {
      return;
    }
    result[id.name] = init;
  });
  return result;
}

function findNamedExports(nodes) {
  const result = [];
  const definedObjectExpressions = {};
  nodes.forEach((node) => {
    Object.assign(definedObjectExpressions, findDefinedObjectExpressions(node));
    result.push(...findESNamedExports(node));
    result.push(...findCommonJSExports(node, definedObjectExpressions));
  });
  return result;
}

function hasDefaultExport(nodes) {
  return nodes.some((node) => {
    if (node.type === 'ExportDefaultDeclaration') {
      return true;
    }
    if (node.type !== 'ExpressionStatement') {
      return false;
    }
    // Potential CommonJS export
    const { left, right } = node.expression;
    if (!left || !right) {
      return false;
    }
    return left.object.name === 'module' && left.property.name === 'exports';
  });
}

export default function findExports(ast) {
  return {
    named: findNamedExports(ast.program.body),
    hasDefault: hasDefaultExport(ast.program.body),
  };
}
<commit_msg>Make some arrow functions more consistent<commit_after>function findESNamedExports(node) {
  if (node.type !== 'ExportNamedDeclaration') {
    return [];
  }

  if (node.specifiers.length) {
    return node.specifiers.map(({ exported }) => exported.name);
  }
  if (node.declaration) {
    return node.declaration.declarations.map(({ id }) => id.name);
  }
  return [];
}

function findCommonJSExports(node, definedObjectExpressions) {
  if (node.type !== 'ExpressionStatement') {
    return [];
  }
  // Potential CommonJS export
  const { left, right } = node.expression;
  if (!left || !right) {
    return [];
  }
  if (left.object.name === 'module' &&
    left.property.name === 'exports') {
    let objectExpression;
    if (right.type === 'ObjectExpression') {
      objectExpression = right;
    }
    if (right.type === 'Identifier') {
      objectExpression = definedObjectExpressions[right.name];
    }
    if (objectExpression) {
      return objectExpression.properties.map(({ key }) => key.name).filter(Boolean);
    }
  }
  return [];
}

function findDefinedObjectExpressions(node) {
  if (node.type !== 'VariableDeclaration') {
    return {};
  }
  const result = {};
  node.declarations.forEach(({ id, init }) => {
    if (init.type !== 'ObjectExpression') {
      return;
    }
    result[id.name] = init;
  });
  return result;
}

function findNamedExports(nodes) {
  const result = [];
  const definedObjectExpressions = {};
  nodes.forEach((node) => {
    Object.assign(definedObjectExpressions, findDefinedObjectExpressions(node));
    result.push(...findESNamedExports(node));
    result.push(...findCommonJSExports(node, definedObjectExpressions));
  });
  return result;
}

function hasDefaultExport(nodes) {
  return nodes.some((node) => {
    if (node.type === 'ExportDefaultDeclaration') {
      return true;
    }
    if (node.type !== 'ExpressionStatement') {
      return false;
    }
    // Potential CommonJS export
    const { left, right } = node.expression;
    if (!left || !right) {
      return false;
    }
    return left.object.name === 'module' && left.property.name === 'exports';
  });
}

export default function findExports(ast) {
  return {
    named: findNamedExports(ast.program.body),
    hasDefault: hasDefaultExport(ast.program.body),
  };
}
<|endoftext|>


<commit_before>var package = require( '../package' )
var request = require( './request' )
var debug = require( 'debug' )( 'flightstats' )

/**
 * FlightStats
 * @constructor
 * @param {Object} options
 * @return {FlightStats}
 */
function FlightStats( options ) {

  if( !(this instanceof FlightStats) )
    return new FlightStats( options )

  this.options = Object.assign( {}, FlightStats.defaults, options || {} )

  this.headers = {
    'AppId': this.options.appId,
    'AppKey': this.options.apiKey,
    'User-Agent': this.options.userAgent,
  }

}

/**
 * Default options
 * @type {Object}
 */
FlightStats.defaults = {
  appId: '',
  apiKey: '',
  userAgent: process.release.name + ' ' +
    package.name + '/' + package.version,
}

FlightStats.userAgent = process.release.name + ' ' + package.name + '/' + package.version
FlightStats.baseUrl = 'https://api.flightstats.com/flex'

FlightStats.AirlineCategory = require( './airline-category' )
FlightStats.FlightStatus = require( './flight-status' )
FlightStats.ServiceType = require( './service-type' )
FlightStats.StatusUpdate = require( './status-update' )
FlightStats.IrregularOperation = require( './irregular-operation' )
FlightStats.CodeshareType = require( './codeshare-type' )

FlightStats.formatStatus = require( './format/status' )
FlightStats.formatSchedule = require( './format/schedule' )

/**
 * FlightStats prototype
 * @type {Object}
 */
FlightStats.prototype = {

  constructor: FlightStats,

  /**
   * Retrieve a list of airlines
   * @param  {Object} options
   *   @property {Boolean} all
   *   @property {Date}    date
   *   @property {String}  iata
   *   @property {String}  icao
   *   @property {String}  fs
   * @param  {Function} callback
   */
  getAirlines: function( options, callback ) {

    if( typeof options === 'function' ) {
      callback = options
      options = null
    }

    options = options != null ? options : {}

    var self = this
    var baseUrl = `${FlightStats.baseUrl}/airlines/rest/v1/json`
    var isCode = options.fs || options.iata || options.icao
    var supportsDate = !options.all || isCode

    if( !options.all && !isCode ) {
      baseUrl += '/active'
    } else if( !isCode ) {
      baseUrl += '/all'
    }

    if( options.fs ) {
      baseUrl += '/fs/' + options.fs
    } else if( options.iata ) {
      baseUrl += '/iata/' + options.iata
    } else if( options.icao ) {
      baseUrl += '/icao/' + options.icao
    }

    if( options.date && supportsDate ) {

      var year = options.date.getFullYear()
      var month = options.date.getMonth() + 1
      var day = options.date.getDate()

      baseUrl += `/${year}/${month}/${day}`

    }

    return request({
      headers: Object.assign( {}, this.headers, options.headers || void 0 ),
      url: baseUrl,
      qs: {
        extendedOptions: [
          'useHttpErrors',
          'includeNewFields'
        ].join( '+' )
      }
    }, function( error, data ) {

      // Patch inconsistent behavior of the API,
      // which returns a single object under an `airline` key
      // when looking up by ICAO airline code
      if( data && data.airline ) {
        data.airlines = [].concat( data.airline )
        data.airline = void 0
        delete data.airline
      }

      if( options.expandCategory && data && data.airlines ) {
        data.airlines = data.airlines.map( function( airline ) {
          airline.category = FlightStats.AirlineCategory[ airline.category ] ?
            Object.assign( {}, FlightStats.AirlineCategory[ airline.category ] ) :
            { code: airline.category }
          return airline
        })
      }

      callback.call( self, error, data )

    })

  },

  /**
   * Look up a flight
   * @param {Object} options
   *   @property {Date} date
   *   @property {String} airlineCode
   *   @property {String} flightNumber
   *   @property {String} airport
   *   @property {String} direction
   * @param {Function} callback
   */
  lookup: function( options, callback ) {

    debug( 'lookup' )

    var now = Date.now()
    var target = options.date.getTime()

    // TODO: Fast-error without hitting FlightStats,
    // when outside of time boundaries (?)
    var time = {
      // NOTE: `.status()` is only available within a window of -7 to +3 days
      min: now - ( 8 * 24 ) * 60 * 60 * 1000,
      max: now + ( 3 * 24 ) * 60 * 60 * 1000,
      // NOTE: `.schedule()` can go up to 30 days into the future
      // (apparently more, as experimentally proven)
      schedMax: now + ( 30 * 24 ) * 60 * 60 * 1000,
    }

    var method = target < time.min || target > time.max ?
      'schedule' : 'status'

    debug( 'lookup:time:target ', target )
    debug( 'lookup:time:window', time )
    debug( 'lookup:type', method )

    return this[ method ]( options, callback )

  },

  /**
   * Get the live status of a flight
   * @param  {Object} options
   *   @see FlightStats#lookup()
   * @param  {Function} callback
   * @return {Request}
   */
  status: function( options, callback ) {

    debug( 'status', options )

    var self = this

    var protocol = options.protocol || 'rest'
    var format = options.format || 'json'
    var baseUrl = `${FlightStats.baseUrl}/flightstatus/${protocol}/v2/${format}/flight/status`

    var carrier = options.airlineCode
    var flightNumber = options.flightNumber
    var year = options.date.getFullYear()
    var month = options.date.getMonth() + 1
    var day = options.date.getDate()
    var direction = /^dep/i.test( options.direction ) ?
      'dep' : 'arr'

    return request({
      headers: Object.assign( {}, this.headers, options.headers || void 0 ),
      url: `${baseUrl}/${carrier}/${flightNumber}/${direction}/${year}/${month}/${day}`,
      qs: {
        airport: options.airport || void 0,
        extendedOptions: [
          'includeNewFields',
          'useHttpErrors',
          'useInlinedReferences'
        ].join( '+' )
      }
    }, function( error, data ) {
      data = data ? FlightStats.formatStatus( data ) : data
      callback.call( self, error, data )
    })

  },

  /**
   * Get a flight's schedule status information
   * @param  {Object} options
   *   @see FlightStats#lookup()
   * @param  {Function} callback
   * @return {Request}
   */
  schedule: function( options, callback ) {

    debug( 'schedule', options )

    var self = this

    var protocol = options.protocol || 'rest'
    var format = options.format || 'json'
    var baseUrl = `${FlightStats.baseUrl}/schedules/${protocol}/v1/${format}/flight`

    var carrier = options.airlineCode
    var flightNumber = options.flightNumber
    var year = options.date.getFullYear()
    var month = options.date.getMonth() + 1
    var day = options.date.getDate()
    var direction = /^dep/i.test( options.direction ) ?
      'departing' : 'arriving'

    return request({
      headers: Object.assign( {}, this.headers, options.headers || void 0 ),
      url: `${baseUrl}/${carrier}/${flightNumber}/${direction}/${year}/${month}/${day}`,
      qs: {
        extendedOptions: [
          'includeDirects',
          'includeCargo',
          'useInlinedReferences'
        ].join( '+' )
      }
    }, function( error, data ) {
      data = data ? FlightStats.formatSchedule( data ) : data
      callback.call( self, error, data )
    })

  },

}

// Exports
module.exports = FlightStats
<commit_msg>Update lib/flightstats: Simplify time window check in .lookup()<commit_after>var package = require( '../package' )
var request = require( './request' )
var debug = require( 'debug' )( 'flightstats' )

/**
 * FlightStats
 * @constructor
 * @param {Object} options
 * @return {FlightStats}
 */
function FlightStats( options ) {

  if( !(this instanceof FlightStats) )
    return new FlightStats( options )

  this.options = Object.assign( {}, FlightStats.defaults, options || {} )

  this.headers = {
    'AppId': this.options.appId,
    'AppKey': this.options.apiKey,
    'User-Agent': this.options.userAgent,
  }

}

/**
 * Default options
 * @type {Object}
 */
FlightStats.defaults = {
  appId: '',
  apiKey: '',
  userAgent: process.release.name + ' ' +
    package.name + '/' + package.version,
}

FlightStats.userAgent = process.release.name + ' ' + package.name + '/' + package.version
FlightStats.baseUrl = 'https://api.flightstats.com/flex'

FlightStats.AirlineCategory = require( './airline-category' )
FlightStats.FlightStatus = require( './flight-status' )
FlightStats.ServiceType = require( './service-type' )
FlightStats.StatusUpdate = require( './status-update' )
FlightStats.IrregularOperation = require( './irregular-operation' )
FlightStats.CodeshareType = require( './codeshare-type' )

FlightStats.formatStatus = require( './format/status' )
FlightStats.formatSchedule = require( './format/schedule' )

/**
 * FlightStats prototype
 * @type {Object}
 */
FlightStats.prototype = {

  constructor: FlightStats,

  /**
   * Retrieve a list of airlines
   * @param  {Object} options
   *   @property {Boolean} all
   *   @property {Date}    date
   *   @property {String}  iata
   *   @property {String}  icao
   *   @property {String}  fs
   * @param  {Function} callback
   */
  getAirlines: function( options, callback ) {

    if( typeof options === 'function' ) {
      callback = options
      options = null
    }

    options = options != null ? options : {}

    var self = this
    var baseUrl = `${FlightStats.baseUrl}/airlines/rest/v1/json`
    var isCode = options.fs || options.iata || options.icao
    var supportsDate = !options.all || isCode

    if( !options.all && !isCode ) {
      baseUrl += '/active'
    } else if( !isCode ) {
      baseUrl += '/all'
    }

    if( options.fs ) {
      baseUrl += '/fs/' + options.fs
    } else if( options.iata ) {
      baseUrl += '/iata/' + options.iata
    } else if( options.icao ) {
      baseUrl += '/icao/' + options.icao
    }

    if( options.date && supportsDate ) {

      var year = options.date.getFullYear()
      var month = options.date.getMonth() + 1
      var day = options.date.getDate()

      baseUrl += `/${year}/${month}/${day}`

    }

    return request({
      headers: Object.assign( {}, this.headers, options.headers || void 0 ),
      url: baseUrl,
      qs: {
        extendedOptions: [
          'useHttpErrors',
          'includeNewFields'
        ].join( '+' )
      }
    }, function( error, data ) {

      // Patch inconsistent behavior of the API,
      // which returns a single object under an `airline` key
      // when looking up by ICAO airline code
      if( data && data.airline ) {
        data.airlines = [].concat( data.airline )
        data.airline = void 0
        delete data.airline
      }

      if( options.expandCategory && data && data.airlines ) {
        data.airlines = data.airlines.map( function( airline ) {
          airline.category = FlightStats.AirlineCategory[ airline.category ] ?
            Object.assign( {}, FlightStats.AirlineCategory[ airline.category ] ) :
            { code: airline.category }
          return airline
        })
      }

      callback.call( self, error, data )

    })

  },

  /**
   * Look up a flight
   * @param {Object} options
   *   @property {Date} date
   *   @property {String} airlineCode
   *   @property {String} flightNumber
   *   @property {String} airport
   *   @property {String} direction
   * @param {Function} callback
   */
  lookup: function( options, callback ) {

    debug( 'lookup' )

    var now = Date.now()
    var target = options.date.getTime()

    // NOTE: `.status()` is only available within a window of -7 to +3 days
    var timeMin = now - ( 8 * 24 ) * 60 * 60 * 1000
    var timeMax = now + ( 3 * 24 ) * 60 * 60 * 1000

    var method = target < timeMin || target > timeMax ?
      'schedule' : 'status'

    debug( 'lookup:time:target ', target )
    debug( 'lookup:time:window', timeMin, timeMax )
    debug( 'lookup:type', method )

    return this[ method ]( options, callback )

  },

  /**
   * Get the live status of a flight
   * @param  {Object} options
   *   @see FlightStats#lookup()
   * @param  {Function} callback
   * @return {Request}
   */
  status: function( options, callback ) {

    debug( 'status', options )

    var self = this

    var protocol = options.protocol || 'rest'
    var format = options.format || 'json'
    var baseUrl = `${FlightStats.baseUrl}/flightstatus/${protocol}/v2/${format}/flight/status`

    var carrier = options.airlineCode
    var flightNumber = options.flightNumber
    var year = options.date.getFullYear()
    var month = options.date.getMonth() + 1
    var day = options.date.getDate()
    var direction = /^dep/i.test( options.direction ) ?
      'dep' : 'arr'

    return request({
      headers: Object.assign( {}, this.headers, options.headers || void 0 ),
      url: `${baseUrl}/${carrier}/${flightNumber}/${direction}/${year}/${month}/${day}`,
      qs: {
        airport: options.airport || void 0,
        extendedOptions: [
          'includeNewFields',
          'useHttpErrors',
          'useInlinedReferences'
        ].join( '+' )
      }
    }, function( error, data ) {
      data = data ? FlightStats.formatStatus( data ) : data
      callback.call( self, error, data )
    })

  },

  /**
   * Get a flight's schedule status information
   * @param  {Object} options
   *   @see FlightStats#lookup()
   * @param  {Function} callback
   * @return {Request}
   */
  schedule: function( options, callback ) {

    debug( 'schedule', options )

    var self = this

    var protocol = options.protocol || 'rest'
    var format = options.format || 'json'
    var baseUrl = `${FlightStats.baseUrl}/schedules/${protocol}/v1/${format}/flight`

    var carrier = options.airlineCode
    var flightNumber = options.flightNumber
    var year = options.date.getFullYear()
    var month = options.date.getMonth() + 1
    var day = options.date.getDate()
    var direction = /^dep/i.test( options.direction ) ?
      'departing' : 'arriving'

    return request({
      headers: Object.assign( {}, this.headers, options.headers || void 0 ),
      url: `${baseUrl}/${carrier}/${flightNumber}/${direction}/${year}/${month}/${day}`,
      qs: {
        extendedOptions: [
          'includeDirects',
          'includeCargo',
          'useInlinedReferences'
        ].join( '+' )
      }
    }, function( error, data ) {
      data = data ? FlightStats.formatSchedule( data ) : data
      callback.call( self, error, data )
    })

  },

}

// Exports
module.exports = FlightStats
<|endoftext|>


<commit_before>var Stream = require('stream');

// writable
exports.Event = function (options) {

    options = options || {};
    if (typeof options.objectMode === 'undefined') {
        options.objectMode = true;
    }

    var sequence = Stream.Transform({
        objectMode: options.objectMode ? true : false,
        transform: function (chunk, enc, next) {

            var push;
            var pos = -1;
            var handler;
            var runSeq = function (err, data) {

                if (err && data) {
                    data = err;
                    err = null;
                    push = true;
                } else {
                    push = false;
                }

                // emit error
                if (err) {
                    return next(err);
                };

                // auto convert to non-object streams
                if (!sequence.wOM &&
                    typeof data !== 'string' &&
                    !(data instanceof Buffer)
                ) {
                    try {
                        data = JSON.stringify(data) + '\n';
                    } catch (err)  {
                        return next(err);
                    }
                }

                // just push data to readable if data and error is true
                if (push) {
                    return sequence.push(data);
                }

                // get handler
                if (!(handler = sequence.seq[++pos])) {
                    return next(null, data);
                }

                // call next data handler
                handler[0].call(handler[2], runSeq, handler[1], data);
            };

            if (!sequence.seq) {
                sequence.once('sequence', runSeq.bind(this, null, chunk));
                return;
            }

            runSeq(null, chunk);
        }
    });

    return sequence;
};
<commit_msg>move "next" to the end<commit_after>var Stream = require('stream');

// writable
exports.Event = function (options) {

    options = options || {};
    if (typeof options.objectMode === 'undefined') {
        options.objectMode = true;
    }

    var sequence = Stream.Transform({
        objectMode: options.objectMode ? true : false,
        transform: function (chunk, enc, next) {

            var push;
            var pos = -1;
            var handler;
            var runSeq = function (err, data) {

                if (err && data) {
                    data = err;
                    err = null;
                    push = true;
                } else {
                    push = false;
                }

                // emit error
                if (err) {
                    return next(err);
                };

                // auto convert to non-object streams
                if (!sequence.wOM &&
                    typeof data !== 'string' &&
                    !(data instanceof Buffer)
                ) {
                    try {
                        data = JSON.stringify(data) + '\n';
                    } catch (err)  {
                        return next(err);
                    }
                }

                // just push data to readable if data and error is true
                if (push) {
                    return sequence.push(data);
                }

                // get handler
                if (!(handler = sequence.seq[++pos])) {
                    return next(null, data);
                }

                // call next data handler
                handler[0].call(handler[2], handler[1], data, runSeq);
            };

            if (!sequence.seq) {
                sequence.once('sequence', runSeq.bind(this, null, chunk));
                return;
            }

            runSeq(null, chunk);
        }
    });

    return sequence;
};
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { View, StyleSheet, TouchableHighlight, Platform } from 'react-native'
import colors from '../config/colors'
import Text from '../text/Text'
import normalize from '../helpers/normalizeText'

let styles = {}

const ButtonGroup = ({
  component,
  onPress,
  buttons,
  containerStyle,
  selectedBackgroundColor,
  textStyle,
  selectedTextStyle,
  underlayColor,
  selectedIndex,
  activeOpacity,
  onHideUnderlay,
  onShowUnderlay,
  setOpacityTo,
  borderStyle
}) => {
  const Component = component || TouchableHighlight
  return (
    <View style={[styles.container, containerStyle && containerStyle]}>
      {
        buttons.map((button, i) => {
          return (
            <Component
              activeOpacity={activeOpacity}
              onHideUnderlay={onHideUnderlay}
              onShowUnderlay={onShowUnderlay}
              underlayColor={underlayColor || '#ffffff'}
              onPress={() => onPress(i)}
              setOpacityTo={setOpacityTo}
              key={i}
              style={[
                styles.button,
                i < buttons.length - 1 && styles.borderRight,
                i < buttons.length - 1 && borderStyle && borderStyle,
                selectedIndex === i && {backgroundColor: selectedBackgroundColor || 'white'}
              ]}>
              <View style={{flex: 1}}>
              {
                button.element ? <button.element /> : (
                  <Text
                  style={[
                    styles.buttonText,
                    textStyle && textStyle,
                    selectedIndex === i && {color: colors.grey1},
                    selectedIndex === i && selectedTextStyle && selectedTextStyle
                  ]}>{button}</Text>
                )
              }
              </View>
            </Component>
          )
        })
      }
    </View>
  )
}

styles = StyleSheet.create({
  button: {
    flex: 1
  },
  borderRight: {
    borderRightColor: colors.grey4,
    borderRightWidth: 1
  },
  container: {
    marginLeft: 10,
    marginRight: 10,
    marginBottom: 5,
    marginTop: 5,
    borderColor: '#e3e3e3',
    borderWidth: 1,
    flexDirection: 'row',
    borderRadius: 3,
    overflow: 'hidden',
    backgroundColor: '#f5f5f5'
  },
  buttonText: {
    flex: 1,
    paddingTop: 5,
    paddingBottom: 5,
    textAlign: 'center',
    fontSize: normalize(13),
    color: colors.grey2,
    ...Platform.select({
      ios: {
        fontWeight: '500'
      }
    })
  }
})

ButtonGroup.propTypes = {
  button: PropTypes.object
}

export default ButtonGroup
<commit_msg>Fix typo (remove duplicated condition)<commit_after>import React, { PropTypes } from 'react'
import { View, StyleSheet, TouchableHighlight, Platform } from 'react-native'
import colors from '../config/colors'
import Text from '../text/Text'
import normalize from '../helpers/normalizeText'

let styles = {}

const ButtonGroup = ({
  component,
  onPress,
  buttons,
  containerStyle,
  selectedBackgroundColor,
  textStyle,
  selectedTextStyle,
  underlayColor,
  selectedIndex,
  activeOpacity,
  onHideUnderlay,
  onShowUnderlay,
  setOpacityTo,
  borderStyle
}) => {
  const Component = component || TouchableHighlight
  return (
    <View style={[styles.container, containerStyle && containerStyle]}>
      {
        buttons.map((button, i) => {
          return (
            <Component
              activeOpacity={activeOpacity}
              onHideUnderlay={onHideUnderlay}
              onShowUnderlay={onShowUnderlay}
              underlayColor={underlayColor || '#ffffff'}
              onPress={() => onPress(i)}
              setOpacityTo={setOpacityTo}
              key={i}
              style={[
                styles.button,
                i < buttons.length - 1 && styles.borderRight,
                i < buttons.length - 1 && borderStyle,
                selectedIndex === i && {backgroundColor: selectedBackgroundColor || 'white'}
              ]}>
              <View style={{flex: 1}}>
              {
                button.element ? <button.element /> : (
                  <Text
                  style={[
                    styles.buttonText,
                    textStyle && textStyle,
                    selectedIndex === i && {color: colors.grey1},
                    selectedIndex === i && selectedTextStyle && selectedTextStyle
                  ]}>{button}</Text>
                )
              }
              </View>
            </Component>
          )
        })
      }
    </View>
  )
}

styles = StyleSheet.create({
  button: {
    flex: 1
  },
  borderRight: {
    borderRightColor: colors.grey4,
    borderRightWidth: 1
  },
  container: {
    marginLeft: 10,
    marginRight: 10,
    marginBottom: 5,
    marginTop: 5,
    borderColor: '#e3e3e3',
    borderWidth: 1,
    flexDirection: 'row',
    borderRadius: 3,
    overflow: 'hidden',
    backgroundColor: '#f5f5f5'
  },
  buttonText: {
    flex: 1,
    paddingTop: 5,
    paddingBottom: 5,
    textAlign: 'center',
    fontSize: normalize(13),
    color: colors.grey2,
    ...Platform.select({
      ios: {
        fontWeight: '500'
      }
    })
  }
})

ButtonGroup.propTypes = {
  button: PropTypes.object
}

export default ButtonGroup
<|endoftext|>


<commit_before>/*=============================================================================
 * Orange - Time System
 * By Hudell - www.hudell.com
 * OrangeTimeSystem.js
 * Version: 1.1.1
 * Free for commercial and non commercial use.
 *=============================================================================*/
 /*:
 * @plugindesc Adds a time system to your game
 * @author Hudell
 *
 * @param useRealTime
 * @desc If true, the time "Length" variables will be ignored and the plugin will use the real time
 * @default false
 *
 * @param secondLength
 * @desc How many real time milliseconds should an ingame second last
 * @default 1000
 *
 * @param minuteLength
 * @desc How many ingame seconds should an ingame minute last
 * @default 6
 *
 * @param hourLength
 * @desc How many ingame minutes should an ingame hour last
 * @default 6
 *
 * @param dayLength
 * @desc How many ingame hours should an ingame day last
 * @default 24
 *
 * @param weekLength
 * @desc How many ingame days should an ingame week last
 * @default 7
 *
 * @param monthLength
 * @desc How many ingame days should an ingame month last
 * @default 31
 *
 * @param yearLength
 * @desc How many ingame months should an ingame year last
 * @default 4
 *
 * @param dayPeriod1Hour
 * @desc At what hour does night turn into early morning
 * @default 6
 *
 * @param dayPeriod2Hour
 * @desc At what hour does early morning turn into day
 * @default 9
 *
 * @param dayPeriod3Hour
 * @desc At what hour does day turn into evening
 * @default 18
 *
 * @param dayPeriod4Hour
 * @desc At what hour does evening turn into night
 * @default 20
 *
 * @param mainSwitchId
 * @desc The Number of the Switch used to activate the flow of time
 * @default 0
 *
 * @help
 * ============================================================================
 * Introduction and Instructions
 * ============================================================================
 *
 * This plugin creates a time system for your game. Nothing will change on the
 * game itself, unless you use another plugin that uses this one.
 *
 * ============================================================================
 * Latest Version
 * ============================================================================
 *
 * Get the latest version of this script on http://link.hudell.com/time-system
 *
 */

var Imported = Imported || {};

if (Imported['MVCommons'] === undefined) {
  console.log('Download MVCommons: http://link.hudell.com/mvcommons');
  throw new Error("This library needs MVCommons to work properly!");
}
if (Imported['OrangeEventManager'] === undefined) {
  console.log('Download MVCommons: http://link.hudell.com/event-manager');
  throw new Error("This library needs OrangeEventManager to work properly!");
}

var OrangeTimeSystem = OrangeTimeSystem || MVC.shallowClone(OrangeEventManager);

var DayPeriods = {
  EARLY_MORNING: 1,
  DAY: 2,
  EVENING: 3,
  NIGHT: 4
};

(function($) {
  "use strict";

  $.Parameters = PluginManager.parameters('OrangeTimeSystem');
  $.Param = $.Param || {};

  $.Param.useRealTime = $.Parameters["useRealTime"] == "true";
  if ($.Param.useRealTime) {
    $.Param.secondLength = 1000;
  } else {
    $.Param.secondLength = Number($.Parameters['secondLength'] || 1000);
  }

  $.Param.minuteLength = Number($.Parameters['minuteLength'] || 6);
  $.Param.hourLength = Number($.Parameters['hourLength'] || 6);
  $.Param.dayLength = Number($.Parameters['dayLength'] || 24);
  $.Param.weekLength = Number($.Parameters['weekLength'] || 7);
  $.Param.monthLength = Number($.Parameters['monthLength'] || 31);
  $.Param.yearLength = Number($.Parameters['yearLength'] || 4);

  $.Param.dayPeriod1Hour = Number($.Parameters['dayPeriod1Hour'] || 6);
  $.Param.dayPeriod2Hour = Number($.Parameters['dayPeriod2Hour'] || 9);
  $.Param.dayPeriod3Hour = Number($.Parameters['dayPeriod3Hour'] || 18);
  $.Param.dayPeriod4Hour = Number($.Parameters['dayPeriod4Hour'] || 20);

  var switchId = parseInt($.Parameters['mainSwitchId'], 10);

  if (switchId !== NaN && switchId > 0) {
    $.Param.mainSwitchId = switchId;
  } else {
    $.Param.mainSwitchId = undefined;
  }

  MVC.accessor($, 'seconds');
  MVC.accessor($, 'minute');
  MVC.accessor($, 'hour');
  MVC.accessor($, 'day');
  MVC.accessor($, 'month');
  MVC.accessor($, 'year');
  MVC.accessor($, 'dayPeriod');
  MVC.accessor($, 'weekDay');

  MVC.accessor($, 'paused', function(value) {
    if ($.Param.mainSwitchId !== undefined) {
      $gameSwitches.setValue($.Param.mainSwitchId, !value);
      return;
    }

    this._paused = value;
  }, function() {
    if ($.Param.mainSwitchId !== undefined) {
      if ($gameSwitches === undefined || $gameSwitches === null) return true;
      return !$gameSwitches.value($.Param.mainSwitchId);
    }

    if (this._paused !== undefined) {
      return this._paused;
    }

    return false;
  });

  $._timeEvents = [];
  $.seconds = 0;
  $.minute = 0;
  $.hour = 0;
  $.day = 1;
  $.month = 1;
  $.year = 1;
  $.dayPeriod = 0;
  $.weekDay = 0;

  $.updateTime = function() {
    if (this.seconds >= $.Param.minuteLength) {
      this.minute += 1;
      this.seconds = 0;

      this._onChangeMinute();
    }

    if (this.minute >= $.Param.hourLength) {
      this.hour += 1;
      this.minute = 0;

      this._onChangeHour();
    }

    if (this.hour >= $.Param.dayLength) {
      this.day += 1;
      this.hour = 0;

      this._onChangeDay();
    }

    if (this.day > $.Param.monthLength) {
      this.month += 1;
      this.day = 1;

      this._onChangeMonth();
    }

    if (this.month > $.Param.yearLength) {
      this.year += 1;
      this.month = 1;

      this._onChangeYear();
    }

    var oldDayPeriod = this.dayPeriod;
    this.updateDayPeriod();

    if (oldDayPeriod != this.dayPeriod) {
      this._onChangeDayPeriod();
    }

    // Calculate week day
    var previousYears = this.year - 1;
    var previousMonths = previousYears * $.Param.yearLength;
    var numMonths = previousMonths + this.month - 1;
    var numDays = numMonths * $.Param.monthLength + this.day;
    this.weekDay = numDays % $.Param.weekLength;

    this._onUpdateTime();
  };

  $.updateDayPeriod = function() {
    // Calculate day period
    if (this.hour < $.Param.dayPeriod1Hour) {
      this.dayPeriod = 4;
    } else if (this.hour < $.Param.dayPeriod2Hour) {
      this.dayPeriod = 1;
    } else if (this.hour < $.Param.dayPeriod3Hour) {
      this.dayPeriod = 2;
    } else if (this.hour < $.Param.dayPeriod4Hour) {
      this.dayPeriod = 3;
    } else {
      this.dayPeriod = 4;
    }
  };

  $.isEarlyMorning = function() {
    return this.dayPeriod == DayPeriods.EARLY_MORNING;
  };

  $.isMidday = function() {
    return this.dayPeriod == DayPeriods.DAY;
  };

  $.isEvening = function() {
    return this.dayPeriod == DayPeriods.EVENING;
  };

  $.isNight = function() {
    return this.dayPeriod == DayPeriods.NIGHT;
  };

  $.isEnabled = function() {
    return (this._intervalHandler !== undefined);
  };

  $.enableTime = function() {
    if (this._intervalHandler !== undefined) return;

    this._intervalHandler = setInterval(function() {
      $.progressTime();
    }, $.Param.secondLength);
  };

  $.disableTime = function() {
    if (this._intervalHandler === undefined) return;

    clearInterval(this._intervalHandler);
    this._intervalHandler = undefined;
  };

  $.loadRealTime = function() {
    var date = new Date();
    var oldData = this.getDateTime();
    var anyChanged = false;

    $.seconds = date.getSeconds();
    $.minute = date.getMinutes();
    $.hour = date.getHours();
    $.day = date.getDate();
    $.month = date.getMonth() + 1;
    $.year = date.getFullYear();
    $.weekDay = date.getDay();
    $.updateDayPeriod();

    if ($.seconds != oldData.seconds) {
      $._onChangeSecond();
    }

    if ($.minute != oldData.minute) {
      $._onChangeMinute();
    }

    if ($.hour != oldData.hour) {
      $._onChangeHour();
    }

    if ($.day != oldData.day) {
      $._onChangeDay();
    }

    if ($.month != oldData.month) {
      $._onChangeMonth();
    }

    if ($.year != oldData.year) {
      $._onChangeYear();
    }
  };

  $.progressTime = function() {
    if (this.paused) return;

    if ($.Param.useRealTime) {
      $.loadRealTime();
      $._onUpdateTime();
    } else if (SceneManager._scene instanceof Scene_Map) {
      $.seconds += 1;
      $.updateTime();
      $._onChangeSecond();
    }
  };

  $._onChangeSecond = function() {
    this.runEvent('changeSecond');
  };

  $._onChangeMinute = function() {
    this.runEvent('changeMinute');
  };

  $._onChangeHour = function() {
    this.runEvent('changeHour');
  };

  $._onChangeDayPeriod = function() {
    this.runEvent('changeDayPeriod');
  };

  $._onChangeDay = function() {
    this.runEvent('changeDay');
  };

  $._onChangeMonth = function() {
    this.runEvent('changeMonth');
  };

  $._onChangeYear = function() {
    this.runEvent('changeYear');
  };

  $.onTime = function(callback, hour, minute, second) {
    return this.registerTimeEvent({
      hour: hour,
      minute: minute,
      second: second,
      callback: callback
    });
  };

  $.onDate = function(callback, day, month, year) {
    return this.registerTimeEvent({
      day: day,
      month: month,
      year: year,
      callback: callback
    });
  };

  $.onDateTime = function(callback, day, month, year, hour, minute, second) {
    return this.registerTimeEvent({
      day: day,
      month: month,
      year: year,
      hour: hour,
      minute: minute,
      second: second,
      callback: callback
    });
  };

  $.onWeekDay = function(callback, weekDay) {
    return this.registerTimeEvent({
      weekDay: weekDay,
      callback: callback
    });
  };

  $.atDate = $.onDate;
  $.atTime = $.onTime;
  $.atDateTime = $.onDateTime;
  $.atWeekDay = $.onWeekDay;

  $.registerTimeEvent = function(config) {
    this._timeEvents.push(config);
    return this._timeEvents.indexOf(config);
  };

  $._onUpdateTime = function() {
    for (var i = 0; i < this._timeEvents.length; i++) {
      var config = this._timeEvents[i];

      if (config.day !== undefined && config.day != this.day) continue;
      if (config.month !== undefined && config.month != this.month) continue;
      if (config.year !== undefined && config.year != this.year) continue;
      if (config.hour !== undefined && config.hour != this.hour) continue;
      if (config.minute !== undefined && config.minute != this.minute) continue;
      if (config.second !== undefined && config.second != this.seconds) continue;
      if (config.weekDay !== undefined && config.weekDay != this.weekDay) continue;

      this.executeCallback(config.callback);
    }
  };

  $.getDateTime = function() {
    return {
      hour: $.hour,
      minute: $.minute,
      seconds: $.seconds,
      day: $.day,
      month: $.month,
      year: $.year,
      dayPeriod: $.dayPeriod,
      weekDay: $.weekDay,
      paused: $.paused
    };
  };

  $.setDateTime = function(dateTime) {
    this.hour = dateTime.hour || 0;
    this.minute = dateTime.minute || 0;
    this.seconds = dateTime.seconds || 0;
    this.day = dateTime.day || 1;
    this.month = dateTime.month || 1;
    this.year = dateTime.year || 1;
    this.dayPeriod = dateTime.dayPeriod || DayPeriods.EARLY_MORNING;
    this.weekDay = dateTime.weekDay || 0;

    if (dateTime.paused !== undefined) {
      this.paused = dateTime.paused;
    } else {
      this.paused = false;
    }
  };

  var oldDataManager_makeSaveContents = DataManager.makeSaveContents;
  DataManager.makeSaveContents = function() {
    var contents = oldDataManager_makeSaveContents.call(this);

    contents.orangeDateTime = $.getDateTime();
    return contents;
  };

  var oldDataManager_extractSaveContents = DataManager.extractSaveContents;
  DataManager.extractSaveContents = function(contents) {
    oldDataManager_extractSaveContents.call(this, contents);

    if (contents.orangeDateTime !== undefined) {
      $.setDateTime(contents.orangeDateTime);
    }
  };

  $.enableTime();
})(OrangeTimeSystem);

PluginManager.register("OrangeTimeSystem", "1.1.1", "Adds a time system to your game", {
  email: "plugins@hudell.com",
  name: "Hudell",
  website: "http://www.hudell.com"
}, "2015-10-21");
<commit_msg>Added Time manipulation features<commit_after>/*=============================================================================
 * Orange - Time System
 * By Hudell - www.hudell.com
 * OrangeTimeSystem.js
 * Version: 1.2
 * Free for commercial and non commercial use.
 *=============================================================================*/
 /*:
 * @plugindesc Adds a time system to your game
 * @author Hudell
 *
 * @param useRealTime
 * @desc If true, the time "Length" variables will be ignored and the plugin will use the real time
 * @default false
 *
 * @param secondLength
 * @desc How many real time milliseconds should an ingame second last
 * @default 1000
 *
 * @param minuteLength
 * @desc How many ingame seconds should an ingame minute last
 * @default 6
 *
 * @param hourLength
 * @desc How many ingame minutes should an ingame hour last
 * @default 6
 *
 * @param dayLength
 * @desc How many ingame hours should an ingame day last
 * @default 24
 *
 * @param weekLength
 * @desc How many ingame days should an ingame week last
 * @default 7
 *
 * @param monthLength
 * @desc How many ingame days should an ingame month last
 * @default 31
 *
 * @param yearLength
 * @desc How many ingame months should an ingame year last
 * @default 4
 *
 * @param dayPeriod1Hour
 * @desc At what hour does night turn into early morning
 * @default 6
 *
 * @param dayPeriod2Hour
 * @desc At what hour does early morning turn into day
 * @default 9
 *
 * @param dayPeriod3Hour
 * @desc At what hour does day turn into evening
 * @default 18
 *
 * @param dayPeriod4Hour
 * @desc At what hour does evening turn into night
 * @default 20
 *
 * @param mainSwitchId
 * @desc The Number of the Switch used to activate the flow of time
 * @default 0
 *
 * @help
 * ============================================================================
 * Introduction and Instructions
 * ============================================================================
 *
 * This plugin creates a time system for your game. Nothing will change on the
 * game itself, unless you use another plugin that uses this one.
 *
 * ============================================================================
 * Latest Version
 * ============================================================================
 *
 * Get the latest version of this script on http://link.hudell.com/time-system
 *
 */

var Imported = Imported || {};

if (Imported['MVCommons'] === undefined) {
  console.log('Download MVCommons: http://link.hudell.com/mvcommons');
  throw new Error("This library needs MVCommons to work properly!");
}
if (Imported['OrangeEventManager'] === undefined) {
  console.log('Download MVCommons: http://link.hudell.com/event-manager');
  throw new Error("This library needs OrangeEventManager to work properly!");
}

var OrangeTimeSystem = OrangeTimeSystem || MVC.shallowClone(OrangeEventManager);

var DayPeriods = {
  EARLY_MORNING: 1,
  DAY: 2,
  EVENING: 3,
  NIGHT: 4
};

(function($) {
  "use strict";

  $.Parameters = PluginManager.parameters('OrangeTimeSystem');
  $.Param = $.Param || {};

  $.Param.useRealTime = $.Parameters["useRealTime"] == "true";
  if ($.Param.useRealTime) {
    $.Param.secondLength = 1000;
  } else {
    $.Param.secondLength = Number($.Parameters['secondLength'] || 1000);
  }

  $.Param.minuteLength = Number($.Parameters['minuteLength'] || 6);
  $.Param.hourLength = Number($.Parameters['hourLength'] || 6);
  $.Param.dayLength = Number($.Parameters['dayLength'] || 24);
  $.Param.weekLength = Number($.Parameters['weekLength'] || 7);
  $.Param.monthLength = Number($.Parameters['monthLength'] || 31);
  $.Param.yearLength = Number($.Parameters['yearLength'] || 4);

  $.Param.dayPeriod1Hour = Number($.Parameters['dayPeriod1Hour'] || 6);
  $.Param.dayPeriod2Hour = Number($.Parameters['dayPeriod2Hour'] || 9);
  $.Param.dayPeriod3Hour = Number($.Parameters['dayPeriod3Hour'] || 18);
  $.Param.dayPeriod4Hour = Number($.Parameters['dayPeriod4Hour'] || 20);

  var switchId = parseInt($.Parameters['mainSwitchId'], 10);

  if (switchId !== NaN && switchId > 0) {
    $.Param.mainSwitchId = switchId;
  } else {
    $.Param.mainSwitchId = undefined;
  }

  MVC.accessor($, 'seconds');
  MVC.accessor($, 'minute');
  MVC.accessor($, 'hour');
  MVC.accessor($, 'day');
  MVC.accessor($, 'month');
  MVC.accessor($, 'year');
  MVC.accessor($, 'dayPeriod');
  MVC.accessor($, 'weekDay');

  MVC.accessor($, 'paused', function(value) {
    if ($.Param.mainSwitchId !== undefined) {
      $gameSwitches.setValue($.Param.mainSwitchId, !value);
      return;
    }

    this._paused = value;
  }, function() {
    if ($.Param.mainSwitchId !== undefined) {
      if ($gameSwitches === undefined || $gameSwitches === null) return true;
      return !$gameSwitches.value($.Param.mainSwitchId);
    }

    if (this._paused !== undefined) {
      return this._paused;
    }

    return false;
  });

  $._timeEvents = [];
  $.seconds = 0;
  $.minute = 0;
  $.hour = 0;
  $.day = 1;
  $.month = 1;
  $.year = 1;
  $.dayPeriod = 0;
  $.weekDay = 0;

  $.runTimeChangeEvents = function(oldData) {
    if (oldData.seconds != this.seconds) {
      this._onChangeSecond();
    }

    if (oldData.minute !== this.minute) {
      this._onChangeMinute();
    }

    if (oldData.hour !== this.hour) {
      this._onChangeHour();
    }

    if (oldData.day !== this.day) {
      this._onChangeDay();
    }

    if (oldData.month !== this.month) {
      this._onChangeMonth();
    }

    if (oldData.year !== this.year) {
      this._onChangeYear();
    }

    if (oldData.dayPeriod !== this.dayPeriod) {
      this._onChangeDayPeriod();
    }
  };

  $.updateTime = function(runEvents) {
    if (runEvents === undefined) runEvents = true;

    var oldData = $.getDateTime();

    while (this.seconds >= $.Param.minuteLength) {
      this.minute += 1;
      this.seconds -= $.Param.minuteLength;
    }

    while (this.minute >= $.Param.hourLength) {
      this.hour += 1;
      this.minute -= $.Param.hourLength;
    }

    while (this.hour >= $.Param.dayLength) {
      this.day += 1;
      this.hour -= $.Param.dayLength;
    }

    while (this.day > $.Param.monthLength) {
      this.month += 1;
      this.day -= $.Param.monthLength;
    }

    while (this.month > $.Param.yearLength) {
      this.year += 1;
      this.month -= $.Param.yearLength;
    }

    this.updateDayPeriod();

    if (runEvents) {
      this.runTimeChangeEvents(oldData);
    }

    // Calculate week day
    var previousYears = this.year - 1;
    var previousMonths = previousYears * $.Param.yearLength;
    var numMonths = previousMonths + this.month - 1;
    var numDays = numMonths * $.Param.monthLength + this.day;
    this.weekDay = numDays % $.Param.weekLength;

    this._onUpdateTime();
  };

  $.updateDayPeriod = function() {
    // Calculate day period
    if (this.hour < $.Param.dayPeriod1Hour) {
      this.dayPeriod = 4;
    } else if (this.hour < $.Param.dayPeriod2Hour) {
      this.dayPeriod = 1;
    } else if (this.hour < $.Param.dayPeriod3Hour) {
      this.dayPeriod = 2;
    } else if (this.hour < $.Param.dayPeriod4Hour) {
      this.dayPeriod = 3;
    } else {
      this.dayPeriod = 4;
    }
  };

  $.isEarlyMorning = function() {
    return this.dayPeriod == DayPeriods.EARLY_MORNING;
  };

  $.isMidday = function() {
    return this.dayPeriod == DayPeriods.DAY;
  };

  $.isEvening = function() {
    return this.dayPeriod == DayPeriods.EVENING;
  };

  $.isNight = function() {
    return this.dayPeriod == DayPeriods.NIGHT;
  };

  $.isEnabled = function() {
    return (this._intervalHandler !== undefined);
  };

  $.enableTime = function() {
    if (this._intervalHandler !== undefined) return;

    this._intervalHandler = setInterval(function() {
      $.progressTime();
    }, $.Param.secondLength);
  };

  $.disableTime = function() {
    if (this._intervalHandler === undefined) return;

    clearInterval(this._intervalHandler);
    this._intervalHandler = undefined;
  };

  $.loadRealTime = function() {
    var date = new Date();
    var oldData = this.getDateTime();
    var anyChanged = false;

    $.seconds = date.getSeconds();
    $.minute = date.getMinutes();
    $.hour = date.getHours();
    $.day = date.getDate();
    $.month = date.getMonth() + 1;
    $.year = date.getFullYear();
    $.weekDay = date.getDay();
    $.updateDayPeriod();

    if ($.seconds != oldData.seconds) {
      $._onChangeSecond();
    }

    if ($.minute != oldData.minute) {
      $._onChangeMinute();
    }

    if ($.hour != oldData.hour) {
      $._onChangeHour();
    }

    if ($.day != oldData.day) {
      $._onChangeDay();
    }

    if ($.month != oldData.month) {
      $._onChangeMonth();
    }

    if ($.year != oldData.year) {
      $._onChangeYear();
    }
  };

  $.setTime = function(seconds, minute, hour, day, month, year) {
    var oldData = this.getDateTime();

    if (seconds !== undefined) {
      this.seconds = seconds;
    }

    if (minute !== undefined) {
      this.minute = minute;
    }

    if (hour !== undefined) {
      this.hour = hour;
    }

    if (day !== undefined) {
      this.day = day;
    }

    if (month !== undefined) {
      this.month = month;
    }

    if (year !== undefined) {
      this.year = year;
    }

    $.updateTime(false);
    $.runTimeChangeEvents(oldData);
  };

  $.passTime = function(seconds, minutes, hours, days, months, years) {
    var oldData = this.getDateTime();

    this.seconds += Number(seconds || 0);
    this.minute += Number(minutes || 0);
    this.hour += Number(hours || 0);
    this.day += Number(days || 0);
    this.month += Number(months || 0);
    this.year += Number(years || 0);

    $.updateTime(false);
    $.runTimeChangeEvents(oldData);
  };

  $.progressTime = function() {
    if (this.paused) return;

    if ($.Param.useRealTime) {
      $.loadRealTime();
      $._onUpdateTime();
    } else if (SceneManager._scene instanceof Scene_Map) {
      $.seconds += 1;
      $.updateTime();
      $._onChangeSecond();
    }
  };

  $._onChangeSecond = function() {
    this.runEvent('changeSecond');
  };

  $._onChangeMinute = function() {
    this.runEvent('changeMinute');
  };

  $._onChangeHour = function() {
    this.runEvent('changeHour');
  };

  $._onChangeDayPeriod = function() {
    this.runEvent('changeDayPeriod');
  };

  $._onChangeDay = function() {
    this.runEvent('changeDay');
  };

  $._onChangeMonth = function() {
    this.runEvent('changeMonth');
  };

  $._onChangeYear = function() {
    this.runEvent('changeYear');
  };

  $.onTime = function(callback, hour, minute, second) {
    return this.registerTimeEvent({
      hour: hour,
      minute: minute,
      second: second,
      callback: callback
    });
  };

  $.onDate = function(callback, day, month, year) {
    return this.registerTimeEvent({
      day: day,
      month: month,
      year: year,
      callback: callback
    });
  };

  $.onDateTime = function(callback, day, month, year, hour, minute, second) {
    return this.registerTimeEvent({
      day: day,
      month: month,
      year: year,
      hour: hour,
      minute: minute,
      second: second,
      callback: callback
    });
  };

  $.onWeekDay = function(callback, weekDay) {
    return this.registerTimeEvent({
      weekDay: weekDay,
      callback: callback
    });
  };

  $.atDate = $.onDate;
  $.atTime = $.onTime;
  $.atDateTime = $.onDateTime;
  $.atWeekDay = $.onWeekDay;

  $.registerTimeEvent = function(config) {
    this._timeEvents.push(config);
    return this._timeEvents.indexOf(config);
  };

  $._onUpdateTime = function() {
    for (var i = 0; i < this._timeEvents.length; i++) {
      var config = this._timeEvents[i];

      if (config.day !== undefined && config.day != this.day) continue;
      if (config.month !== undefined && config.month != this.month) continue;
      if (config.year !== undefined && config.year != this.year) continue;
      if (config.hour !== undefined && config.hour != this.hour) continue;
      if (config.minute !== undefined && config.minute != this.minute) continue;
      if (config.second !== undefined && config.second != this.seconds) continue;
      if (config.weekDay !== undefined && config.weekDay != this.weekDay) continue;

      this.executeCallback(config.callback);
    }
  };

  $.getDateTime = function() {
    return {
      hour: $.hour,
      minute: $.minute,
      seconds: $.seconds,
      day: $.day,
      month: $.month,
      year: $.year,
      dayPeriod: $.dayPeriod,
      weekDay: $.weekDay,
      paused: $.paused
    };
  };

  $.setDateTime = function(dateTime) {
    this.hour = dateTime.hour || 0;
    this.minute = dateTime.minute || 0;
    this.seconds = dateTime.seconds || 0;
    this.day = dateTime.day || 1;
    this.month = dateTime.month || 1;
    this.year = dateTime.year || 1;
    this.dayPeriod = dateTime.dayPeriod || DayPeriods.EARLY_MORNING;
    this.weekDay = dateTime.weekDay || 0;

    if (dateTime.paused !== undefined) {
      this.paused = dateTime.paused;
    } else {
      this.paused = false;
    }
  };

  var oldDataManager_makeSaveContents = DataManager.makeSaveContents;
  DataManager.makeSaveContents = function() {
    var contents = oldDataManager_makeSaveContents.call(this);

    contents.orangeDateTime = $.getDateTime();
    return contents;
  };

  var oldDataManager_extractSaveContents = DataManager.extractSaveContents;
  DataManager.extractSaveContents = function(contents) {
    oldDataManager_extractSaveContents.call(this, contents);

    if (contents.orangeDateTime !== undefined) {
      $.setDateTime(contents.orangeDateTime);
    }
  };

  $.enableTime();
})(OrangeTimeSystem);

PluginManager.register("OrangeTimeSystem", "1.2", "Adds a time system to your game", {
  email: "plugins@hudell.com",
  name: "Hudell",
  website: "http://www.hudell.com"
}, "2015-10-21");
<|endoftext|>


<commit_before>// Return require function for given path

'use strict';

var isArray        = Array.isArray
  , defineProperty = Object.defineProperty
  , Module         = require('module')
  , fs             = require('fs')
  , path           = require('path')

  , stat = fs.statSync
  , getDirname = path.dirname, resolve = path.resolve, nodeCache = Module._cache

  , cache = {}, getFromNodeCache;

getFromNodeCache = function (module) {
	var require;
	if (module.require) {
		// >= v0.5
		require = function (path) {
			return module.require(path);
		};
		defineProperty(require, 'paths', { get: function () {
			throw new Error('require.paths is removed. Use ' +
				'node_modules folders, or the NODE_PATH ' +
				'environment variable instead.');
		}});
	} else {
		// <= v0.4
		require = function (path) {
			return Module._load(path, module);
		};
		require.paths = Module._paths;
	}
	require.extensions = Module._extensions;
	require.registerExtension = function () {
		throw new Error('require.registerExtension() removed. Use ' +
			'require.extensions instead.');
	};
	require.main = process.mainModule;
	require.cache = nodeCache;
	require.resolve = function (request) {
		var res = Module._resolveFilename(request, module);
		return isArray(res) ? res[1] : res;
	};

	return require;
};

module.exports = function (filename) {
	var dirname, stats, path, id, fmodule;
	filename = resolve(filename);
	if (cache[filename]) {
		return cache[filename];
	}
	if ((fmodule = nodeCache[filename])) {
		return (cache[filename] = getFromNodeCache(fmodule));
	}

	stats = stat(filename);
	dirname = stats.isDirectory() ? filename : getDirname(filename);
	id = dirname + '/__get-require.next.js';
	fmodule = new Module(id, module);
	fmodule.filename = id;
	fmodule.paths = Module._nodeModulePaths(dirname);
	fmodule.loaded = true;
	return (cache[filename] = getFromNodeCache(fmodule));
};
<commit_msg>-- lint<commit_after>// Return require function for given path

'use strict';

var isArray        = Array.isArray
  , defineProperty = Object.defineProperty
  , Module         = require('module')
  , fs             = require('fs')
  , path           = require('path')

  , stat = fs.statSync
  , getDirname = path.dirname, resolve = path.resolve, nodeCache = Module._cache

  , cache = {}, getFromNodeCache;

getFromNodeCache = function (module) {
	var require;
	if (module.require) {
		// >= v0.5
		require = function (path) {
			return module.require(path);
		};
		defineProperty(require, 'paths', { get: function () {
			throw new Error('require.paths is removed. Use ' +
				'node_modules folders, or the NODE_PATH ' +
				'environment variable instead.');
		} });
	} else {
		// <= v0.4
		require = function (path) {
			return Module._load(path, module);
		};
		require.paths = Module._paths;
	}
	require.extensions = Module._extensions;
	require.registerExtension = function () {
		throw new Error('require.registerExtension() removed. Use ' +
			'require.extensions instead.');
	};
	require.main = process.mainModule;
	require.cache = nodeCache;
	require.resolve = function (request) {
		var res = Module._resolveFilename(request, module);
		return isArray(res) ? res[1] : res;
	};

	return require;
};

module.exports = function (filename) {
	var dirname, stats, path, id, fmodule;
	filename = resolve(filename);
	if (cache[filename]) {
		return cache[filename];
	}
	if ((fmodule = nodeCache[filename])) {
		return (cache[filename] = getFromNodeCache(fmodule));
	}

	stats = stat(filename);
	dirname = stats.isDirectory() ? filename : getDirname(filename);
	id = dirname + '/__get-require.next.js';
	fmodule = new Module(id, module);
	fmodule.filename = id;
	fmodule.paths = Module._nodeModulePaths(dirname);
	fmodule.loaded = true;
	return (cache[filename] = getFromNodeCache(fmodule));
};
<|endoftext|>


<commit_before>/**
 * Get a travel time surface and accessibility results for a particular origin.
 * Pass in references to the query (the JS object stored in query.json), the stopTreeCache, the origin file, the
 * x and y coordinates of the origin relative to the query, what parameter you want (BEST_CASE, WORST_CASE or AVERAGE),
 * and a grid. Returns a travel time/accessibility surface which can be used by isochoroneTile and accessibilityForCutoff
 */
export default function getSurface ({grid, origin, query, stopTreeCache, which}) {
  let surface = new Uint8Array(query.width * query.height)

  let transitOffset = getTransitOffset(origin.data[0])

  // how many departure minutes are there. skip number of stops
  let nMinutes = origin.data[transitOffset + 1]

  let travelTimes = new Uint8Array(nMinutes)

  // store the accessibility at each departure minute for every possible cutoff 1 - 120
  let access = new Float64Array(nMinutes * 120)

  // x and y refer to pixel coordinates not origins here
  // loop over rows first
  for (let y = 0, pixelIdx = 0, stcOffset = 0; y < query.height; y++) {
    for (let x = 0; x < query.width; x++, pixelIdx++) {
      let nStops = stopTreeCache.data[stcOffset++]

      // can we reach this pixel without riding transit?
      let nonTransitTime = origin.getNonTransitTime({x, y})

      // fill with unreachable, or the walk distance
      travelTimes.fill(nonTransitTime)

      for (let stopIdx = 0; stopIdx < nStops; stopIdx++) {
        // read the stop ID
        let stopId = stopTreeCache.data[stcOffset++]

        // read the time (minutes)
        let time = stopTreeCache.data[stcOffset++]

        // de-delta-code times
        for (let minute = 0, previous = 0; minute < nMinutes; minute++) {
          let offset = origin.index[stopId] + minute * 2 // * 2 because path info is included as well
          let travelTimeToStop = origin.data[offset] + previous
          previous = travelTimeToStop

          if (travelTimeToStop === -1) continue

          let travelTimeToPixel = (travelTimeToStop / 60 + time) | 0

          if (travelTimeToPixel > 254) continue

          if (travelTimes[minute] > travelTimeToPixel) travelTimes[minute] = travelTimeToPixel
        }
      }

      // compute and set value for pixel
      surface[pixelIdx] = computePixelValue(which, travelTimes)

      // compute access values
      computeAccessValues(x, y, query, grid, travelTimes, access)
    }
  }

  return {
    surface,
    access,
    nMinutes
  }
}

/**
 * Where is the transit portion of the origin data there are a certain number of pixels in each direction aroudn the origin with times in them. read the radius, multiply by two to get diameter, add one because there is a pixel in the center, square to get number of pixels, add one to skip the first value which gives radius, and or with to convert to 32-bit int.
 *
 * @param {Number} radius
 * @return {Number}
 */

export function getTransitOffset (radius) {
  return (Math.pow(radius * 2 + 1, 2) + 1) | 0
}

/**
 * Get the pixel value
 *
 * @param {String} which
 * @param {Uint8Array} travelTimes
 * @return {Number} pixelValue
 */

export function computePixelValue (which, travelTimes) {
  switch (which) {
    case 'BEST_CASE':
      return computeBestPixelValue(travelTimes)
    case 'AVERAGE':
      return computeAveragePixelValue(travelTimes)
    case 'WORST_CASE':
      return computeWorstPixelValue(travelTimes)
  }
}

/**
 * Compute best pixel value
 *
 * @param {Uint8Array} travelTimes
 * @return {Number} pixel
 */

export function computeBestPixelValue (travelTimes) {
  let pixel = 255
  for (let i = 0; i < travelTimes.length; i++) {
    pixel = Math.min(pixel, travelTimes[i])
  }
  return pixel
}

/**
 * Compute average pixel value
 *
 * @param {Uint8Array} travelTimes
 * @return {Number} pixel
 */

export function computeAveragePixelValue (travelTimes) {
  let sum = 0
  let count = 0

  for (let i = 0; i < travelTimes.length; i++) {
    if (travelTimes[i] !== 255) {
      sum += travelTimes[i]
      count++
    }
  }

  // coerce to int
  if (count > travelTimes.length / 2) return (sum / count) | 0
  else return 255
}

/**
 * Compute worst pixel value
 *
 * @param {Uint8Array} travelTimes
 * @return {Number} pixel
 */

export function computeWorstPixelValue (travelTimes) {
  let pixel = 0
  for (let i = 0; i < travelTimes.length; i++) {
    pixel = Math.max(pixel, travelTimes[i])
  }
  return pixel
}

/**
 * Compute access values for x, y
 *
 * @param {Number} x
 * @param {Number} y
 * @param {Object} query
 * @param {Object} grid
 * @param {Uint8Array} travelTimes
 * @param {Float64Array} accessPerMinute
 */

export function computeAccessValues (x, y, query, grid, travelTimes, access) {
  // get value of this pixel from grid
  // or everything with 0 so that v8 can do type inference
  let gridx = x + query.west - grid.west | 0
  let gridy = y + query.north - grid.north | 0

  // if condition below fails we're off the grid, value is zero, don't bother with calculations
  if (gridx >= 0 && gridx < grid.width && gridy >= 0 && gridy < grid.height) {
    let val = grid.data[gridy * grid.width + gridx]

    for (let minute = 0; minute < travelTimes.length; minute++) {
      let travelTime = travelTimes[minute]

      if (travelTime !== 255) {
        // put this in all of the correct cutoff categories for this minute
        for (let cutoff = 119; cutoff >= Math.max(travelTime - 1, 0); cutoff--) {
          access[cutoff * travelTimes.length + minute] += val
        }
      }
    }
  }
}
<commit_msg>generateSurface now takes 2s again. fixes #3.<commit_after>/**
 * Get a travel time surface and accessibility results for a particular origin.
 * Pass in references to the query (the JS object stored in query.json), the stopTreeCache, the origin file, the
 * x and y coordinates of the origin relative to the query, what parameter you want (BEST_CASE, WORST_CASE or AVERAGE),
 * and a grid. Returns a travel time/accessibility surface which can be used by isochoroneTile and accessibilityForCutoff
 */
export default function getSurface ({grid, origin, query, stopTreeCache, which}) {
  let surface = new Uint8Array(query.width * query.height)

  let transitOffset = getTransitOffset(origin.data[0])

  // how many departure minutes are there. skip number of stops
  let nMinutes = origin.data[transitOffset + 1]

  let travelTimes = new Uint8Array(nMinutes)

  // store the accessibility at each departure minute for every possible cutoff 1 - 120
  let access = new Float64Array(nMinutes * 120)

  // x and y refer to pixel coordinates not origins here
  // loop over rows first
  for (let y = 0, pixelIdx = 0, stcOffset = 0; y < query.height; y++) {
    for (let x = 0; x < query.width; x++, pixelIdx++) {
      let nStops = stopTreeCache.data[stcOffset++]

      // can we reach this pixel without riding transit?
      let nonTransitTime = origin.getNonTransitTime({x, y})

      // fill with unreachable, or the walk distance
      travelTimes.fill(nonTransitTime)

      for (let stopIdx = 0; stopIdx < nStops; stopIdx++) {
        // read the stop ID
        let stopId = stopTreeCache.data[stcOffset++]

        // read the time (minutes)
        let time = stopTreeCache.data[stcOffset++]

        // de-delta-code times
        for (let minute = 0, previous = 0; minute < nMinutes; minute++) {
          let offset = origin.index[stopId] + minute * 2 // * 2 because path info is included as well
          let travelTimeToStop = origin.data[offset] + previous
          previous = travelTimeToStop

          if (travelTimeToStop === -1) continue

          let travelTimeToPixel = (travelTimeToStop / 60 + time) | 0

          if (travelTimeToPixel > 254) continue

          if (travelTimes[minute] > travelTimeToPixel) travelTimes[minute] = travelTimeToPixel
        }
      }

      // compute and set value for pixel
      surface[pixelIdx] = computePixelValue(which, travelTimes)

      // compute access values
      computeAccessValues(x, y, query, grid, travelTimes, access)
    }
  }

  return {
    surface,
    access,
    nMinutes
  }
}

/**
 * Where is the transit portion of the origin data there are a certain number of pixels in each direction aroudn the origin with times in them. read the radius, multiply by two to get diameter, add one because there is a pixel in the center, square to get number of pixels, add one to skip the first value which gives radius, and or with to convert to 32-bit int.
 *
 * @param {Number} radius
 * @return {Number}
 */

export function getTransitOffset (radius) {
  return (Math.pow(radius * 2 + 1, 2) + 1) | 0
}

/**
 * Get the pixel value
 *
 * @param {String} which
 * @param {Uint8Array} travelTimes
 * @return {Number} pixelValue
 */

export function computePixelValue (which, travelTimes) {
  switch (which) {
    case 'BEST_CASE':
      return computeBestPixelValue(travelTimes)
    case 'AVERAGE':
      return computeAveragePixelValue(travelTimes)
    case 'WORST_CASE':
      return computeWorstPixelValue(travelTimes)
  }
}

/**
 * Compute best pixel value
 *
 * @param {Uint8Array} travelTimes
 * @return {Number} pixel
 */

export function computeBestPixelValue (travelTimes) {
  let pixel = 255
  for (let i = 0; i < travelTimes.length; i++) {
    pixel = Math.min(pixel, travelTimes[i])
  }
  return pixel
}

/**
 * Compute average pixel value
 *
 * @param {Uint8Array} travelTimes
 * @return {Number} pixel
 */

export function computeAveragePixelValue (travelTimes) {
  let sum = 0
  let count = 0

  for (let i = 0; i < travelTimes.length; i++) {
    if (travelTimes[i] !== 255) {
      sum += travelTimes[i]
      count++
    }
  }

  // coerce to int
  if (count > travelTimes.length / 2) return (sum / count) | 0
  else return 255
}

/**
 * Compute worst pixel value
 *
 * @param {Uint8Array} travelTimes
 * @return {Number} pixel
 */

export function computeWorstPixelValue (travelTimes) {
  let pixel = 0
  for (let i = 0; i < travelTimes.length; i++) {
    pixel = Math.max(pixel, travelTimes[i])
  }
  return pixel
}

/**
 * Compute access values for x, y
 *
 * @param {Number} x
 * @param {Number} y
 * @param {Object} query
 * @param {Object} grid
 * @param {Uint8Array} travelTimes
 * @param {Float64Array} accessPerMinute
 */

export function computeAccessValues (x, y, query, grid, travelTimes, access) {
  // get value of this pixel from grid
  // or everything with 0 so that v8 can do type inference
  let gridx = x + query.west - grid.west | 0
  let gridy = y + query.north - grid.north | 0

  // if condition below fails we're off the grid, value is zero, don't bother with calculations
  if (gridx >= 0 && gridx < grid.width && gridy >= 0 && gridy < grid.height) {
    let val = grid.data[gridy * grid.width + gridx]

    for (let minute = 0; minute < travelTimes.length; minute++) {
      let travelTime = travelTimes[minute]

      if (travelTime !== 255) {
        // put this in all of the correct cutoff categories for this minute
        for (let cutoff = 119; cutoff >= travelTime; cutoff--) {
          access[cutoff * travelTimes.length + minute] += val
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>'use strict';
var fs = require('fs-extra');
var path = require('path-extra');
var globby = require('globby');
var yaml = require('js-yaml');
// Only load a subset of lodash:
var _ = {
  spread: require('lodash/spread'),
  defaultsDeep: require('lodash/defaultsDeep'),
};
// Config vars:
var src;
module.exports = function getDefaults(data, filePath) {
  // Must have src/ in the path so we know when to stop:
  var dirPath=path.join(src, path.dirname(filePath));
  var arr=[load(dirPath)];
  recurse(dirPath);
  return Promise.all(arr)
  .then(function (arr) {
    // Combine defaults:
    var defaults = _.spread(_.defaultsDeep)(arr);
    // Apply data, set cache: true, and return the new data:
    return _.defaultsDeep(data, defaults, {cache: true});
  });

  function recurse(dirPath) {
    // If we have reached src/, stop:
    if (path.normalizeTrim(dirPath) === path.normalizeTrim(src)) return;
    else {
      let newPath=path.dirname(dirPath);
      arr.push(load(newPath));
      return recurse(newPath);
    }
  }
};
module.exports.setConf = function (conf) {
  src = conf.src;
};

// Accepts a directory path
// Returns the contents of the directory/_defaults.* file as an object
// Returns {} if the file does not exist
function load(dirPath) {
  return globby(path.join(dirPath, '_defaults.*')).then(function (res) {
    var defaults={};
    if (!res[0]) return defaults;
    switch (path.extname(res[0])) {
    case '.yaml':
    case '.yml':
      defaults=yaml.safeLoad(fs.readFileSync(res[0], 'utf8'));
      break;
    case '.json':
      defaults=fs.readJsonSync(res[0]);
    }
    return defaults;
  });
}
<commit_msg>Performance improvements to lib/getDefaults.js<commit_after>'use strict';
var p = require('thenify');
var fs = require('fs-extra');
var path = require('path-extra');
var globby = require('globby');
var yaml = require('js-yaml');
var cache = {};
// Only load a subset of lodash:
var _ = {
  spread: require('lodash/spread'),
  defaultsDeep: require('lodash/defaultsDeep'),
};
// Config vars:
var src;
module.exports = function getDefaults(data, filePath) {
  // Must have src/ in the path so we know when to stop:
  var dirPath=path.join(src, path.dirname(filePath));
  var arr=[load(dirPath)];
  recurse(dirPath);
  return Promise.all(arr)
  .then(function (arr) {
    // Combine defaults:
    var defaults = _.spread(_.defaultsDeep)(arr);
    // Apply data, set cache: true, and return the new data:
    return _.defaultsDeep(data, defaults, {cache: true});
  });

  function recurse(dirPath) {
    // If we have reached src/, stop:
    if (path.normalizeTrim(dirPath) === path.normalizeTrim(src)) return;
    else {
      let newPath=path.dirname(dirPath);
      arr.push(load(newPath));
      return recurse(newPath);
    }
  }
};
module.exports.setConf = function (conf) {
  src = conf.src;
};

function load(dirPath) {
  if (cache[dirPath]) return cache[dirPath];
  else {
    var val = loadFromFile(dirPath);
    cache[dirPath] = val;
    return val;
  }
}
function loadFromFile(dirPath) {
  return globby(path.join(dirPath, '_defaults.*'))
  .then(function (res) {
    var defaults={};
    if (!res[0]) return defaults;
    switch (path.extname(res[0])) {
    case '.yaml':
    case '.yml':
      defaults=p(fs.readFile)(res[0], 'utf8').then(d => yaml.safeLoad(d));
      break;
    case '.json':
      defaults=p(fs.readJson)(res[0]);
    }
    return defaults;
  });
}
<|endoftext|>