<commit_before>'use strict';

var method = require('./../method');
var assign = require('lodash.assign');

/**
 * @memberof scripts
 * @method create
 * @description Creates a new startup script.  Optionally specify a machine to use this startup script.
 * Note: currently only Linux based machines support startup scripts.  Also, note: script data is limited to 16KB per script.
 * @param {string} scriptName - A unique name for the script
 * @param {string} [scriptFile] - File path to a file containing the script data; either scriptFile or scriptText must be provide.
 * @param {string} [scriptText] - A string containing the script text; either scriptFile or scriptText must be provide.
 * @param {string} [scriptDescription] - Description of the script
 * @param {boolean} [isEnabled] - Determines if the script is enabled or not.  Defaults to true.
 * @param {boolean} [runOnce] - Determines if the script is run on first boot or evey boot.  Defaults to false.
 * @param {string} [machineId] - Machine id of a machine that should execute this script at startup
 * @param {function} cb - Node-style error-first callback function
 * @returns {object} script - The created script JSON object
 * @example
 * paperspace.scripts.create({
 *   scriptName: 'My Script',
 *   scriptFile: './my_script_file.sh', // must specify either scriptFile or scriptText
 *   scriptDescription: 'A startup script', // optional
 *   isEnabled: true, // optional
 *   runOnce: false, // optional
 *   machineId: 'ps123abc', // optional
 * }, function(err, resp) {
 *   // handle error or http response
 * });
 * @example
 * $ paperspace accounts create \
 *     --scriptName "My Script" \
 *     --scriptDescription "A startup script" \
 *     --scriptText "services start nginx" \
 *     --isEnabled true \
 *     --runOnce false \
 *     --machineId "ps123abc"
 * @example
 * # HTTP request:
 * https://api.paperspace.io
 * POST /account/setStartupScript {"scriptName": "My Script", "scriptDescription": "A startup script", "isEnabled": true, "runOnce": false, "machineId": "ps123abc"}
 * x-api-key: 1ba4f98e7c0...
 * (file contents as multipart form data)
 * # Returns 200 on success
 */

function create(params, cb) {
	if (!params.scriptFile && !params.scriptText) return cb(new Error('Missing required parameter: either scriptFile or scriptText'));
	if (params.scriptFile && params.scriptText) return cb(new Error('Only one of scriptFile or scriptText allowed'));
	return method(create, params, cb);
}

assign(create, {
	auth: true,
	group: 'scripts',
	name: 'create',
	method: 'post',
	route: '/scripts/createScript',
	requires: {
		scriptName: 'string',
	},
	file: 'scriptFile',
	returns: {},
});

module.exports = create;
<commit_msg>add sample result for scripts create method<commit_after>'use strict';

var method = require('./../method');
var assign = require('lodash.assign');

/**
 * @memberof scripts
 * @method create
 * @description Creates a new startup script.  Optionally specify a machine to use this startup script.
 * Note: currently only Linux based machines support startup scripts.  Also, note: script data is limited to 16KB per script.
 * @param {string} scriptName - A unique name for the script
 * @param {string} [scriptFile] - File path to a file containing the script data; either scriptFile or scriptText must be provide.
 * @param {string} [scriptText] - A string containing the script text; either scriptFile or scriptText must be provide.
 * @param {string} [scriptDescription] - Description of the script
 * @param {boolean} [isEnabled] - Determines if the script is enabled or not.  Defaults to true.
 * @param {boolean} [runOnce] - Determines if the script is run on first boot or evey boot.  Defaults to false.
 * @param {string} [machineId] - Machine id of a machine that should execute this script at startup
 * @param {function} cb - Node-style error-first callback function
 * @returns {object} script - The created script JSON object
 * @example
 * paperspace.scripts.create({
 *   scriptName: 'My Script',
 *   scriptFile: './my_script_file.sh', // must specify either scriptFile or scriptText
 *   scriptDescription: 'A startup script', // optional
 *   isEnabled: true, // optional
 *   runOnce: false, // optional
 *   machineId: 'ps123abc', // optional
 * }, function(err, resp) {
 *   // handle error or http response
 * });
 * @example
 * $ paperspace accounts create \
 *     --scriptName "My Script" \
 *     --scriptDescription "A startup script" \
 *     --scriptText "services start nginx" \
 *     --isEnabled true \
 *     --runOnce false \
 *     --machineId "ps123abc"
 * @example
 * # HTTP request:
 * https://api.paperspace.io
 * POST /account/setStartupScript {"scriptName": "My Script", "scriptDescription": "A startup script", "isEnabled": true, "runOnce": false, "machineId": "ps123abc"}
 * x-api-key: 1ba4f98e7c0...
 * (file contents as multipart form data)
 * # Returns 200 on success
 * @example
 * // Example return value:
 * {
 *   "id": "sc123abc",
 *   "ownerType": "user",
 *   "ownerId": "u456def",
 *   "name": "My Script",
 *   "description": "my_script_file.sh",
 *   "dtCreated": "2017-06-15T19:22:13.507Z",
 *   "isEnabled": true,
 *   "runOnce": false
 * }
 */

function create(params, cb) {
	if (!params.scriptFile && !params.scriptText) return cb(new Error('Missing required parameter: either scriptFile or scriptText'));
	if (params.scriptFile && params.scriptText) return cb(new Error('Only one of scriptFile or scriptText allowed'));
	return method(create, params, cb);
}

assign(create, {
	auth: true,
	group: 'scripts',
	name: 'create',
	method: 'post',
	route: '/scripts/createScript',
	requires: {
		scriptName: 'string',
	},
	file: 'scriptFile',
	returns: {},
});

module.exports = create;
<|endoftext|>


<commit_before>"use strict";

var Park = require("../park");
var Moment = require("moment-timezone");

var s_parkID = Symbol();
var s_authToken = Symbol();
var s_apiBase = Symbol();

/**
 * Implements the Seaworld API framework.
 * @class
 * @extends Park
 */
class SeaworldPark extends Park {
    /**
     * Create new SeaworldPark Object.
     * This object should not be called directly, but rather extended for each of the individual SeaWorld parks
     * @param {Object} options
     * @param {String} options.park_id ID of the park to access the API for
     * @param {String} [options.auth_token] Auth token to use to connect to the API
     * @param {String} [options.api_base] Base URL to access the API
     */
    constructor(options = {}) {
        options.name = options.name || "SeaWorld Park";

        // inherit from base class
        super(options);

        // assign park configurations
        if (!options.park_id) throw new Error("Missing park's API ID");
        this[s_parkID] = options.park_id;

        // accept API options to override defaults if needed
        this[s_authToken] = options.auth_token || "***REMOVED***";
        this[s_apiBase] = options.api_base || "https://seas.te2.biz/v1/rest/venue/";
    }

    FetchWaitTimes() {
        return new Promise(function(resolve, reject) {
            // first make sure we have our ride names
            this.GetRideNames().then(function(rideNames) {
                this.GetAPIUrl({
                    url: `${this[s_apiBase]}${this[s_parkID]}/poi/all/status`
                }).then(function(waitTimeData) {
                    for (var i = 0, ride; ride = waitTimeData[i++];) {
                        // find/create this ride object (only if we have a name for it)
                        if (rideNames[ride.id]) {
                            var rideObject = this.GetRideObject({
                                id: ride.id,
                                name: rideNames[ride.id]
                            });

                            if (rideObject) {
                                // update ride wait time
                                rideObject.WaitTime = ride.status && ride.status.waitTime ? ride.status.waitTime : -1;
                            }
                        }
                    }

                    resolve();
                }.bind(this), reject);
            }.bind(this), reject);
        }.bind(this));
    }

    FetchOpeningTimes() {
        return new Promise(function(resolve, reject) {
            this.GetAPIUrl({
                url: `${this[s_apiBase]}${this[s_parkID]}/hours/${Moment().tz(this.Timezone).format("YYYY-MM-DD")}`,
                data: {
                    days: 30
                }
            }).then(function(scheduleData) {
                for (var i = 0, day; day = scheduleData[i++];) {
                    var thisDay = Moment(day.date, "YYYY-MM-DD");
                    this.Schedule.SetDate({
                        date: thisDay,
                        openingTime: day.open ? Moment(day.open, "YYYY-MM-DDTHH:mm:ss.SSSZZ").tz(this.Timezone) : thisDay,
                        closingTime: day.close ? Moment(day.close, "YYYY-MM-DDTHH:mm:ss.SSSZZ").tz(this.Timezone) : thisDay,
                        type: day.isOpen ? "Operating" : "Closed",
                    });
                }

                resolve();
            }.bind(this), reject);
        }.bind(this));
    }

    /**
     * Get cached (or fresh fetch) of ride names
     * @returns {Promise<Object>} Object of RideID => Ride name in English
     */
    GetRideNames() {
        return new Promise(function(resolve, reject) {
            // wrap cache request (cache ride names for 24 hours)
            this.Cache.Wrap("ridenames", this.FetchRideNames.bind(this), 60 * 60 * 24).then(resolve, reject);
        }.bind(this));
    }

    /**
     * Fetch all the rides and ride names for this park from the API (skip the cache)
     * @returns {Promise<Object>} Object of RideID => Ride name in English
     */
    FetchRideNames() {
        return new Promise(function(resolve, reject) {
            this.Log(`Fetching ride names for ${this.Name}`);

            // fetch POI (points-of-interest) data from API
            this.GetAPIUrl({
                url: `${this[s_apiBase]}${this[s_parkID]}/poi/all`
            }).then(function(rideData) {
                if (!rideData) return reject("No POI data returned from Seaworld API");

                var rideNames = {};
                for (var i = 0, poi; poi = rideData[i++];) {
                    // only include POI data for rides
                    if (poi.type == "Ride") {
                        // grab "label", which is the English title for each POI
                        rideNames[poi.id] = poi.label;
                    }
                }

                resolve(rideNames);
            }.bind(this), reject);
        }.bind(this));
    }

    GetAPIUrl(requestObject) {
        return new Promise(function(resolve, reject) {
            // make sure headers exist if they weren't set already
            if (!requestObject.headers) requestObject.headers = [];
            requestObject.headers.Authorization = "Basic " + new Buffer(this[s_authToken]).toString("base64");

            // make sure we get JSON back
            requestObject.forceJSON = true;

            // send network request
            this.HTTP(requestObject).then(resolve, reject);
        }.bind(this));
    }
}

module.exports = SeaworldPark;<commit_msg>Expose ride_types option for SeaWorld-based APIs. This is in prep for Cedar Fair park (Knott's Berry Farm, Cedar Point etc.) support which is based on the same API (!)<commit_after>"use strict";

var Park = require("../park");
var Moment = require("moment-timezone");

var s_parkID = Symbol();
var s_authToken = Symbol();
var s_apiBase = Symbol();
var s_rideTypes = Symbol();

/**
 * Implements the Seaworld API framework.
 * @class
 * @extends Park
 */
class SeaworldPark extends Park {
    /**
     * Create new SeaworldPark Object.
     * This object should not be called directly, but rather extended for each of the individual SeaWorld parks
     * @param {Object} options
     * @param {String} options.park_id ID of the park to access the API for
     * @param {String} [options.auth_token] Auth token to use to connect to the API
     * @param {String} [options.api_base] Base URL to access the API
     * @param {String[]} [options.ride_types] Array of types that denote rides at the park (to avoid listing restaurants/toilets etc. as rides)
     */
    constructor(options = {}) {
        options.name = options.name || "SeaWorld Park";

        // inherit from base class
        super(options);

        // assign park configurations
        if (!options.park_id) throw new Error("Missing park's API ID");
        this[s_parkID] = options.park_id;

        // accept API options to override defaults if needed
        this[s_authToken] = options.auth_token || "***REMOVED***";
        this[s_apiBase] = options.api_base || "https://seas.te2.biz/v1/rest/venue/";

        // array of valid ride types. Some implementations of the API use various types to declare rides (eg. Family/Kid/Thrill etc.)
        this[s_rideTypes] = options.ride_types || ["Ride"];
    }

    FetchWaitTimes() {
        return new Promise(function(resolve, reject) {
            // first make sure we have our ride names
            this.GetRideNames().then(function(rideNames) {
                this.GetAPIUrl({
                    url: `${this[s_apiBase]}${this[s_parkID]}/poi/all/status`
                }).then(function(waitTimeData) {
                    for (var i = 0, ride; ride = waitTimeData[i++];) {
                        // find/create this ride object (only if we have a name for it)
                        if (rideNames[ride.id]) {
                            var rideObject = this.GetRideObject({
                                id: ride.id,
                                name: rideNames[ride.id]
                            });

                            if (rideObject) {
                                // update ride wait time
                                rideObject.WaitTime = ride.status && ride.status.waitTime ? ride.status.waitTime : -1;
                            }
                        }
                    }

                    resolve();
                }.bind(this), reject);
            }.bind(this), reject);
        }.bind(this));
    }

    FetchOpeningTimes() {
        return new Promise(function(resolve, reject) {
            this.GetAPIUrl({
                url: `${this[s_apiBase]}${this[s_parkID]}/hours/${Moment().tz(this.Timezone).format("YYYY-MM-DD")}`,
                data: {
                    days: 30
                }
            }).then(function(scheduleData) {
                for (var i = 0, day; day = scheduleData[i++];) {
                    var thisDay = Moment(day.date, "YYYY-MM-DD");
                    this.Schedule.SetDate({
                        date: thisDay,
                        openingTime: day.open ? Moment(day.open, "YYYY-MM-DDTHH:mm:ss.SSSZZ").tz(this.Timezone) : thisDay,
                        closingTime: day.close ? Moment(day.close, "YYYY-MM-DDTHH:mm:ss.SSSZZ").tz(this.Timezone) : thisDay,
                        type: day.isOpen ? "Operating" : "Closed",
                    });
                }

                resolve();
            }.bind(this), reject);
        }.bind(this));
    }

    /**
     * Get cached (or fresh fetch) of ride names
     * @returns {Promise<Object>} Object of RideID => Ride name in English
     */
    GetRideNames() {
        return new Promise(function(resolve, reject) {
            // wrap cache request (cache ride names for 24 hours)
            this.Cache.Wrap("ridenames", this.FetchRideNames.bind(this), 60 * 60 * 24).then(resolve, reject);
        }.bind(this));
    }

    /**
     * Fetch all the rides and ride names for this park from the API (skip the cache)
     * @returns {Promise<Object>} Object of RideID => Ride name in English
     */
    FetchRideNames() {
        return new Promise(function(resolve, reject) {
            this.Log(`Fetching ride names for ${this.Name}`);

            // fetch POI (points-of-interest) data from API
            this.GetAPIUrl({
                url: `${this[s_apiBase]}${this[s_parkID]}/poi/all`
            }).then(function(rideData) {
                if (!rideData) return reject("No POI data returned from Seaworld API");

                var rideNames = {};
                for (var i = 0, poi; poi = rideData[i++];) {
                    // only include POI data for rides
                    if (this[s_rideTypes].indexOf(poi.type) >= 0) {
                        // grab "label", which is the English title for each POI
                        rideNames[poi.id] = poi.label;
                    }
                }

                resolve(rideNames);
            }.bind(this), reject);
        }.bind(this));
    }

    GetAPIUrl(requestObject) {
        return new Promise(function(resolve, reject) {
            // make sure headers exist if they weren't set already
            if (!requestObject.headers) requestObject.headers = [];
            requestObject.headers.Authorization = "Basic " + new Buffer(this[s_authToken]).toString("base64");

            // make sure we get JSON back
            requestObject.forceJSON = true;

            // send network request
            this.HTTP(requestObject).then(resolve, reject);
        }.bind(this));
    }
}

module.exports = SeaworldPark;<|endoftext|>


<commit_before>var options = require('commander');

var version = require('../package.json').version;
var defaultConfigs = require('./default-configs');

options.port             = defaultConfigs.port;
options.accessLogFile    = defaultConfigs.access_log_file;
options.systemLogFile    = defaultConfigs.system_log_file;
options.systemLogLevel   = defaultConfigs.system_log_level;
options.daemon           = defaultConfigs.daemon;
options.pidFile          = defaultConfigs.pid_file
options.cacheSize        = defaultConfigs.cache_size;
options.enableTrustProxy = defaultConfigs.enable_trust_proxy;
options.plugins          = defaultConfigs.plugins;
options.environment      = defaultConfigs.environment;

options.droongaEngineHostName = defaultConfigs.engine.host;
options.droongaEnginePort     = defaultConfigs.engine.port;
options.tag                   = defaultConfigs.engine.tag;
options.defaultDataset        = defaultConfigs.engine.default_dataset;
options.receiveHostName       = defaultConfigs.engine.receive_host;

function intOption(newValue, oldValue) {
  return parseInt(newValue);
}

function pluginsOption(newValue, oldValue) {
  return newValue.split(/\s*,\s*/).map(function (plugin) {
    return require(plugin);
  });
}

function generateOptionHandler(onHandle, converter) {
  return function(newValue, oldValue) {
    onHandle(newValue);
    if (converter)
      return converter(newValue);
    else
      return newValue;
  };
}

options = options
  .version(version);

function add() {
  options = options.option.apply(options, arguments);
  return exports;
}
exports.add = add;

function define() {
  add('--port <port>',
      'Port number (' + options.port + ')',
      generateOptionHandler(function() {
        options.portGiven = true;
      }, intOption));
  add('--receive-host-name <name>',
      'Host name of the protocol adapter. ' +
        'It must be resolvable by Droonga engine. ' +
        '(' + options.receiveHostName + ')',
      generateOptionHandler(function() {
        options.receiveHostNameGiven = true;
      }));
  add('--droonga-engine-host-name <name>',
      'Host name of Droonga engine (' + options.droongaEngineHostName + ')',
      generateOptionHandler(function() {
        options.droongaEngineHostNameGiven = true;
      }));
  add('--droonga-engine-port <port>',
      'Port number of Droonga engine (' + options.droongaEnginePort + ')',
      generateOptionHandler(function() {
        options.droongaEnginePortGiven = true;
      }, intOption));
  add('--default-dataset <dataset>',
      'The default dataset (' + options.defaultDataset + ')',
      generateOptionHandler(function() {
        options.defaultDatasetGiven = true;
      }));
  add('--tag <tag>',
      'The tag (' + options.tag + ')',
      generateOptionHandler(function() {
        options.tagGiven = true;
      }));
  add('--access-log-file <file>',
      'Output access logs to <file>. ' +
        'You can use "-" as <file> to output to the standard output. ' +
        '(' + options.accessLogFile + ')',
      generateOptionHandler(function() {
        options.accessLogFileGiven = true;
      }));
  add('--system-log-file <file>',
      'Output system logs to <file>. ' +
        'You can use "-" as <file> to output to the standard output. ' +
        '(' + options.systemLogFile + ')',
      generateOptionHandler(function() {
        options.systemLogFileGiven = true;
      }));
  add('--system-log-level <level>',
      'Log level for the system log. Possible values: ' +
      'silly|debug|verbose|info|warn|error',
        '(' + options.systemLogLevel + ')',
      generateOptionHandler(function() {
        options.systemLogLevelGiven = true;
      }));
  add('--cache-size <size>',
      'The max number of cached requests ' +
        '(' + options.cacheSize + ')',
      generateOptionHandler(function() {
        options.cacheSizeGiven = true;
      }, intOption));
  add('--enable-trust-proxy',
      'Enable "trust proxy" configuration. It is required when you run droonga-http-server behind a reverse proxy. ' +
        '(' + options.enableTrustProxy + ')',
      generateOptionHandler(function() {
        options.enableTrustProxyGiven = true;
      }));
  add('--plugins <plugin1,plugin2,...>',
      'Use specified plugins. ' +
        '(' + options.plugins.join(',') + ')',
      generateOptionHandler(function() {
        options.pluginsGiven = true;
      }, pluginsOption));
  add('--daemon',
      'Run as a daemon. (' + options.daemon + ')',
      generateOptionHandler(function() {
        options.daemonGiven = true;
      }));
  add('--pid-file <pid-file>',
      'Output PID to <pid-file>.',
      generateOptionHandler(function() {
        options.pidFileGiven = true;
      }));
  add('--environment <environment>',
      'Use specified environment. (' + options.environment + ')',
      generateOptionHandler(function() {
        options.environmentGiven = true;
      }));
  return exports;
}
exports.define = define;

function parse(argv) {
  return options.parse(argv);
}
exports.parse = parse;
<commit_msg>Fix wrong default value for system-log-level option.<commit_after>var options = require('commander');

var version = require('../package.json').version;
var defaultConfigs = require('./default-configs');

options.port             = defaultConfigs.port;
options.accessLogFile    = defaultConfigs.access_log_file;
options.systemLogFile    = defaultConfigs.system_log_file;
options.systemLogLevel   = defaultConfigs.system_log_level;
options.daemon           = defaultConfigs.daemon;
options.pidFile          = defaultConfigs.pid_file
options.cacheSize        = defaultConfigs.cache_size;
options.enableTrustProxy = defaultConfigs.enable_trust_proxy;
options.plugins          = defaultConfigs.plugins;
options.environment      = defaultConfigs.environment;

options.droongaEngineHostName = defaultConfigs.engine.host;
options.droongaEnginePort     = defaultConfigs.engine.port;
options.tag                   = defaultConfigs.engine.tag;
options.defaultDataset        = defaultConfigs.engine.default_dataset;
options.receiveHostName       = defaultConfigs.engine.receive_host;

function intOption(newValue, oldValue) {
  return parseInt(newValue);
}

function pluginsOption(newValue, oldValue) {
  return newValue.split(/\s*,\s*/).map(function (plugin) {
    return require(plugin);
  });
}

function generateOptionHandler(onHandle, converter) {
  return function(newValue, oldValue) {
    onHandle(newValue);
    if (converter)
      return converter(newValue);
    else
      return newValue;
  };
}

options = options
  .version(version);

function add() {
  options = options.option.apply(options, arguments);
  return exports;
}
exports.add = add;

function define() {
  add('--port <port>',
      'Port number (' + options.port + ')',
      generateOptionHandler(function() {
        options.portGiven = true;
      }, intOption));
  add('--receive-host-name <name>',
      'Host name of the protocol adapter. ' +
        'It must be resolvable by Droonga engine. ' +
        '(' + options.receiveHostName + ')',
      generateOptionHandler(function() {
        options.receiveHostNameGiven = true;
      }));
  add('--droonga-engine-host-name <name>',
      'Host name of Droonga engine (' + options.droongaEngineHostName + ')',
      generateOptionHandler(function() {
        options.droongaEngineHostNameGiven = true;
      }));
  add('--droonga-engine-port <port>',
      'Port number of Droonga engine (' + options.droongaEnginePort + ')',
      generateOptionHandler(function() {
        options.droongaEnginePortGiven = true;
      }, intOption));
  add('--default-dataset <dataset>',
      'The default dataset (' + options.defaultDataset + ')',
      generateOptionHandler(function() {
        options.defaultDatasetGiven = true;
      }));
  add('--tag <tag>',
      'The tag (' + options.tag + ')',
      generateOptionHandler(function() {
        options.tagGiven = true;
      }));
  add('--access-log-file <file>',
      'Output access logs to <file>. ' +
        'You can use "-" as <file> to output to the standard output. ' +
        '(' + options.accessLogFile + ')',
      generateOptionHandler(function() {
        options.accessLogFileGiven = true;
      }));
  add('--system-log-file <file>',
      'Output system logs to <file>. ' +
        'You can use "-" as <file> to output to the standard output. ' +
        '(' + options.systemLogFile + ')',
      generateOptionHandler(function() {
        options.systemLogFileGiven = true;
      }));
  add('--system-log-level <level>',
      'Log level for the system log. Possible values: ' +
      'silly|debug|verbose|info|warn|error' +
        '(' + options.systemLogLevel + ')',
      generateOptionHandler(function() {
        options.systemLogLevelGiven = true;
      }));
  add('--cache-size <size>',
      'The max number of cached requests ' +
        '(' + options.cacheSize + ')',
      generateOptionHandler(function() {
        options.cacheSizeGiven = true;
      }, intOption));
  add('--enable-trust-proxy',
      'Enable "trust proxy" configuration. It is required when you run droonga-http-server behind a reverse proxy. ' +
        '(' + options.enableTrustProxy + ')',
      generateOptionHandler(function() {
        options.enableTrustProxyGiven = true;
      }));
  add('--plugins <plugin1,plugin2,...>',
      'Use specified plugins. ' +
        '(' + options.plugins.join(',') + ')',
      generateOptionHandler(function() {
        options.pluginsGiven = true;
      }, pluginsOption));
  add('--daemon',
      'Run as a daemon. (' + options.daemon + ')',
      generateOptionHandler(function() {
        options.daemonGiven = true;
      }));
  add('--pid-file <pid-file>',
      'Output PID to <pid-file>.',
      generateOptionHandler(function() {
        options.pidFileGiven = true;
      }));
  add('--environment <environment>',
      'Use specified environment. (' + options.environment + ')',
      generateOptionHandler(function() {
        options.environmentGiven = true;
      }));
  return exports;
}
exports.define = define;

function parse(argv) {
  return options.parse(argv);
}
exports.parse = parse;
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const React = require('react')
const ImmutableComponent = require('../../../js/components/immutableComponent')
const {StyleSheet, css} = require('aphrodite/no-important')
const globalStyles = require('./styles/global')
const {isWindows, isLinux} = require('../../common/lib/platformUtil')

/**
 * Boilerplate component for all tab icons
 */
class TabIcon extends ImmutableComponent {
  render () {
    const tabIconStyle = {
      // Currently it's not possible to concatenate Aphrodite generated classes
      // and pre-built classes using default Aphrodite API, so we keep with inline-style
      fontSize: 'inherit',
      display: 'flex',
      alignSelf: 'center',
      width: globalStyles.spacing.iconSize,
      height: globalStyles.spacing.iconSize,
      alignItems: 'center',
      justifyContent: 'center'
    }
    return

      {
      this.props.symbol
        ?
        : null
      }

  }
}

class Favicon extends ImmutableComponent {
  get favicon () {
    return !this.props.isLoading && this.props.tabProps.get('icon')
  }

  get loadingIcon () {
    return this.props.isLoading
      ? globalStyles.appIcons.loading
      : null
  }

  get defaultIcon () {
    return (!this.props.isLoading && !this.favicon)
      ? globalStyles.appIcons.defaultIcon
      : null
  }

  render () {
    const iconStyles = StyleSheet.create({
      favicon: {backgroundImage: `url(${this.favicon})`}
    })
    return this.props.tabProps.get('location') !== 'about:newtab'
      ? <TabIcon
        data-test-favicon={this.favicon}
        data-test-id={this.loadingIcon ? 'loading' : 'defaultIcon'}
        className={css(styles.icon, this.favicon && iconStyles.favicon)}
        symbol={this.loadingIcon || this.defaultIcon} />
      : null
  }
}

class AudioTabIcon extends ImmutableComponent {
  get pageCanPlayAudio () {
    return this.props.tabProps.get('audioPlaybackActive') || this.props.tabProps.get('audioMuted')
  }

  get narrowView () {
    const sizes = ['medium', 'mediumSmall', 'small', 'extraSmall', 'smallest']
    return sizes.includes(this.props.tabProps.get('breakpoint'))
  }

  get locationHasSecondaryIcon () {
    return !!this.props.tabProps.get('isPrivate') || !!this.props.tabProps.get('partitionNumber')
  }

  get mutedState () {
    return this.pageCanPlayAudio && this.props.tabProps.get('audioMuted')
  }

  get unmutedState () {
    this.props.tabProps.get('audioPlaybackActive') && !this.props.tabProps.get('audioMuted')
  }

  get audioIcon () {
    return !this.mutedState
      ? globalStyles.appIcons.volumeOn
      : globalStyles.appIcons.volumeOff
  }

  render () {
    return this.pageCanPlayAudio && !this.narrowView
      ? <TabIcon className={css(styles.icon, styles.audioIcon)} symbol={this.audioIcon} onClick={this.props.onClick} />
      : null
  }
}

class PrivateIcon extends ImmutableComponent {
  get narrowView () {
    const sizes = ['small', 'extraSmall', 'smallest']
    return sizes.includes(this.props.tabProps.get('breakpoint'))
  }

  render () {
    return this.props.tabProps.get('isPrivate') && !this.props.tabProps.get('hoverState') && !this.narrowView
      ? <TabIcon className={css(styles.icon)} symbol={globalStyles.appIcons.private} />
      : null
  }
}

class NewSessionIcon extends ImmutableComponent {
  get narrowView () {
    const sizes = ['small', 'extraSmall', 'smallest']
    return sizes.includes(this.props.tabProps.get('breakpoint'))
  }

  render () {
    return this.props.tabProps.get('partitionNumber') && !this.props.tabProps.get('hoverState') && !this.narrowView
    ? <TabIcon className={css(styles.icon)} symbol={globalStyles.appIcons.newSession} {...this.props} />
    : null
  }
}

class TabTitle extends ImmutableComponent {
  get locationHasSecondaryIcon () {
    return !!this.props.tabProps.get('isPrivate') || !!this.props.tabProps.get('partitionNumber')
  }

  get isPinned () {
    return !!this.props.tabProps.get('pinnedLocation')
  }

  get pageCanPlayAudio () {
    return this.props.tabProps.get('audioPlaybackActive') || this.props.tabProps.get('audioMuted')
  }

  get hoveredOnNarrowView () {
    const sizes = ['mediumSmall', 'small', 'extraSmall', 'smallest']
    return this.props.tabProps.get('hoverState') && sizes.includes(this.props.tabProps.get('breakpoint'))
  }

  get shouldHideTitle () {
    return (this.props.tabProps.get('breakpoint') === 'largeMedium' && this.pageCanPlayAudio && this.locationHasSecondaryIcon) ||
      (this.props.tabProps.get('breakpoint') === 'mediumSmall' && this.locationHasSecondaryIcon) ||
      this.props.tabProps.get('breakpoint') === 'extraSmall' || this.props.tabProps.get('breakpoint') === 'smallest' ||
      this.hoveredOnNarrowView
  }

  render () {
    const titleStyles = StyleSheet.create({
      reduceTitleSize: {
        // include a margin gutter with same size
        // as closeTabIcon to avoid title overflow
        // when hovering over a tab
        marginRight: `calc(${globalStyles.spacing.iconSize} + ${globalStyles.spacing.defaultIconPadding})`
      }
    })
    return !this.isPinned && !this.shouldHideTitle
    ?

      {this.props.pageTitle}

    : null
  }
}

class CloseTabIcon extends ImmutableComponent {
  get isPinned () {
    return !!this.props.tabProps.get('pinnedLocation')
  }

  get narrowView () {
    const sizes = ['extraSmall', 'smallest']
    return sizes.includes(this.props.tabProps.get('breakpoint'))
  }

  render () {
    return this.props.tabProps.get('hoverState') && !this.narrowView && !this.isPinned
      ? <TabIcon
        data-test-id='closeTabIcon'
        className={css(styles.closeTab)}
        symbol={globalStyles.appIcons.closeTab}
        {...this.props} />
      : null
  }
}

const styles = StyleSheet.create({
  icon: {
    width: globalStyles.spacing.iconSize,
    minWidth: globalStyles.spacing.iconSize,
    height: globalStyles.spacing.iconSize,
    backgroundSize: globalStyles.spacing.iconSize,
    fontSize: globalStyles.fontSize.tabIcon,
    backgroundPosition: 'center',
    backgroundRepeat: 'no-repeat',
    display: 'flex',
    alignSelf: 'center',
    position: 'relative',
    textAlign: 'center',
    justifyContent: 'center',
    paddingLeft: globalStyles.spacing.defaultIconPadding,
    paddingRight: globalStyles.spacing.defaultIconPadding
  },

  iconNarrowView: {
    padding: 0
  },

  audioIcon: {
    color: globalStyles.color.highlightBlue
  },

  closeTab: {
    opacity: '0.7',
    position: 'absolute',
    top: '0',
    right: '0',
    padding: '0 4px',
    borderTopRightRadius: globalStyles.radius.borderRadius,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    fontSize: globalStyles.spacing.iconSize,
    width: globalStyles.spacing.iconSize,
    height: '100%',
    border: '0',
    zIndex: globalStyles.zindex.zindexTabs,

    ':hover': {
      opacity: '1'
    }
  },

  tabTitle: {
    WebkitUserSelect: 'none',
    boxSizing: 'border-box',
    fontSize: globalStyles.fontSize.tabTitle,
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
    height: '15px',
    padding: globalStyles.spacing.defaultTabPadding
  },

  tabTitleForWindows: {
    fontWeight: '500',
    fontSize: globalStyles.fontSize.tabTitle,
    height: '18px'
  },

  tabTitleForLinux: {
    height: globalStyles.fontSize.tabTitle
  }
})

module.exports = {
  Favicon,
  AudioTabIcon,
  NewSessionIcon,
  PrivateIcon,
  TabTitle,
  CloseTabIcon
}
<commit_msg>Make alignment for tabTitle consistent across OSes<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const React = require('react')
const ImmutableComponent = require('../../../js/components/immutableComponent')
const {StyleSheet, css} = require('aphrodite/no-important')
const globalStyles = require('./styles/global')
const {isWindows} = require('../../common/lib/platformUtil')

/**
 * Boilerplate component for all tab icons
 */
class TabIcon extends ImmutableComponent {
  render () {
    const tabIconStyle = {
      // Currently it's not possible to concatenate Aphrodite generated classes
      // and pre-built classes using default Aphrodite API, so we keep with inline-style
      fontSize: 'inherit',
      display: 'flex',
      alignSelf: 'center',
      width: globalStyles.spacing.iconSize,
      height: globalStyles.spacing.iconSize,
      alignItems: 'center',
      justifyContent: 'center'
    }
    return

      {
      this.props.symbol
        ?
        : null
      }

  }
}

class Favicon extends ImmutableComponent {
  get favicon () {
    return !this.props.isLoading && this.props.tabProps.get('icon')
  }

  get loadingIcon () {
    return this.props.isLoading
      ? globalStyles.appIcons.loading
      : null
  }

  get defaultIcon () {
    return (!this.props.isLoading && !this.favicon)
      ? globalStyles.appIcons.defaultIcon
      : null
  }

  render () {
    const iconStyles = StyleSheet.create({
      favicon: {backgroundImage: `url(${this.favicon})`}
    })
    return this.props.tabProps.get('location') !== 'about:newtab'
      ? <TabIcon
        data-test-favicon={this.favicon}
        data-test-id={this.loadingIcon ? 'loading' : 'defaultIcon'}
        className={css(styles.icon, this.favicon && iconStyles.favicon)}
        symbol={this.loadingIcon || this.defaultIcon} />
      : null
  }
}

class AudioTabIcon extends ImmutableComponent {
  get pageCanPlayAudio () {
    return this.props.tabProps.get('audioPlaybackActive') || this.props.tabProps.get('audioMuted')
  }

  get narrowView () {
    const sizes = ['medium', 'mediumSmall', 'small', 'extraSmall', 'smallest']
    return sizes.includes(this.props.tabProps.get('breakpoint'))
  }

  get locationHasSecondaryIcon () {
    return !!this.props.tabProps.get('isPrivate') || !!this.props.tabProps.get('partitionNumber')
  }

  get mutedState () {
    return this.pageCanPlayAudio && this.props.tabProps.get('audioMuted')
  }

  get unmutedState () {
    this.props.tabProps.get('audioPlaybackActive') && !this.props.tabProps.get('audioMuted')
  }

  get audioIcon () {
    return !this.mutedState
      ? globalStyles.appIcons.volumeOn
      : globalStyles.appIcons.volumeOff
  }

  render () {
    return this.pageCanPlayAudio && !this.narrowView
      ? <TabIcon className={css(styles.icon, styles.audioIcon)} symbol={this.audioIcon} onClick={this.props.onClick} />
      : null
  }
}

class PrivateIcon extends ImmutableComponent {
  get narrowView () {
    const sizes = ['small', 'extraSmall', 'smallest']
    return sizes.includes(this.props.tabProps.get('breakpoint'))
  }

  render () {
    return this.props.tabProps.get('isPrivate') && !this.props.tabProps.get('hoverState') && !this.narrowView
      ? <TabIcon className={css(styles.icon)} symbol={globalStyles.appIcons.private} />
      : null
  }
}

class NewSessionIcon extends ImmutableComponent {
  get narrowView () {
    const sizes = ['small', 'extraSmall', 'smallest']
    return sizes.includes(this.props.tabProps.get('breakpoint'))
  }

  render () {
    return this.props.tabProps.get('partitionNumber') && !this.props.tabProps.get('hoverState') && !this.narrowView
    ? <TabIcon className={css(styles.icon)} symbol={globalStyles.appIcons.newSession} {...this.props} />
    : null
  }
}

class TabTitle extends ImmutableComponent {
  get locationHasSecondaryIcon () {
    return !!this.props.tabProps.get('isPrivate') || !!this.props.tabProps.get('partitionNumber')
  }

  get isPinned () {
    return !!this.props.tabProps.get('pinnedLocation')
  }

  get pageCanPlayAudio () {
    return this.props.tabProps.get('audioPlaybackActive') || this.props.tabProps.get('audioMuted')
  }

  get hoveredOnNarrowView () {
    const sizes = ['mediumSmall', 'small', 'extraSmall', 'smallest']
    return this.props.tabProps.get('hoverState') && sizes.includes(this.props.tabProps.get('breakpoint'))
  }

  get shouldHideTitle () {
    return (this.props.tabProps.get('breakpoint') === 'largeMedium' && this.pageCanPlayAudio && this.locationHasSecondaryIcon) ||
      (this.props.tabProps.get('breakpoint') === 'mediumSmall' && this.locationHasSecondaryIcon) ||
      this.props.tabProps.get('breakpoint') === 'extraSmall' || this.props.tabProps.get('breakpoint') === 'smallest' ||
      this.hoveredOnNarrowView
  }

  render () {
    const titleStyles = StyleSheet.create({
      reduceTitleSize: {
        // include a margin gutter with same size
        // as closeTabIcon to avoid title overflow
        // when hovering over a tab
        marginRight: `calc(${globalStyles.spacing.iconSize} + ${globalStyles.spacing.defaultIconPadding})`
      }
    })
    return !this.isPinned && !this.shouldHideTitle
    ?

      {this.props.pageTitle}

    : null
  }
}

class CloseTabIcon extends ImmutableComponent {
  get isPinned () {
    return !!this.props.tabProps.get('pinnedLocation')
  }

  get narrowView () {
    const sizes = ['extraSmall', 'smallest']
    return sizes.includes(this.props.tabProps.get('breakpoint'))
  }

  render () {
    return this.props.tabProps.get('hoverState') && !this.narrowView && !this.isPinned
      ? <TabIcon
        data-test-id='closeTabIcon'
        className={css(styles.closeTab)}
        symbol={globalStyles.appIcons.closeTab}
        {...this.props} />
      : null
  }
}

const styles = StyleSheet.create({
  icon: {
    width: globalStyles.spacing.iconSize,
    minWidth: globalStyles.spacing.iconSize,
    height: globalStyles.spacing.iconSize,
    backgroundSize: globalStyles.spacing.iconSize,
    fontSize: globalStyles.fontSize.tabIcon,
    backgroundPosition: 'center',
    backgroundRepeat: 'no-repeat',
    display: 'flex',
    alignSelf: 'center',
    position: 'relative',
    textAlign: 'center',
    justifyContent: 'center',
    paddingLeft: globalStyles.spacing.defaultIconPadding,
    paddingRight: globalStyles.spacing.defaultIconPadding
  },

  iconNarrowView: {
    padding: 0
  },

  audioIcon: {
    color: globalStyles.color.highlightBlue
  },

  closeTab: {
    opacity: '0.7',
    position: 'absolute',
    top: '0',
    right: '0',
    padding: '0 4px',
    borderTopRightRadius: globalStyles.radius.borderRadius,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    fontSize: globalStyles.spacing.iconSize,
    width: globalStyles.spacing.iconSize,
    height: '100%',
    border: '0',
    zIndex: globalStyles.zindex.zindexTabs,

    ':hover': {
      opacity: '1'
    }
  },

  tabTitle: {
    WebkitUserSelect: 'none',
    boxSizing: 'border-box',
    fontSize: globalStyles.fontSize.tabTitle,
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
    lineHeight: '1.6',
    padding: globalStyles.spacing.defaultTabPadding
  },

  tabTitleForWindows: {
    fontWeight: '500',
    fontSize: globalStyles.fontSize.tabTitle
  }
})

module.exports = {
  Favicon,
  AudioTabIcon,
  NewSessionIcon,
  PrivateIcon,
  TabTitle,
  CloseTabIcon
}
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc directive
 * @name lineupApp.directive:myNamePanel
 * @description
 * # myNamePanel
 */
angular.module('lineupApp')
  .directive('myNamePanel', function () {
    return {
      restrict: 'E',
      link: function postLink(scope, element, attrs) {
          console.log(attrs);
          var outerDiv = $('
');

          outerDiv.css({
              opacity: 0.6,
              position: 'absolute',
              left: -300,
              bottom: 500,
              color: '#b6a0b4',
              'text-transform': 'uppercase',
              'height': '300px',
              'font-family': '"Roboto", sans-serif',
              'padding-left': '80px'
          });

          var nameHeader = $('
name
');
          nameHeader.css({
              color: '#12b7a7',
             'line-height': '1em',
             'font-weight': 'bold'
          });

          var nameBox = $('
Scanlon
');
          nameBox.css({
             color: '#b6a0b4',
             'font-size': '2.6em',
             'line-height': '1em',
             'margin-bottom': '15px',
          });

          var subjectBox = $('
Subject: Robert Scanlon
');
          subjectBox.css({
             // 'font-weight': 'bold',
             'font-size': '1.6em',
             'display': 'none'
          });

          var info = [[
              'alias: "arscan"',
              'species: terran',
              'origin: terra',
              'legs: 2',
              'arms: 2',
              'height: 6\' 2"',
              'weight: 215lbs'
          ], [
              'education',
              'Cornell: BS Computer Science',
              'MIT: MS Engineering & Management',
              ' ',
              'occupation',
              'Software Engineer',
              'Web, Data viz'
          ]];

          var infoBox = $('
');

          infoBox.css({
              'list-style': 'none',
              'padding': 0
          });

          for(var i = 0; i< info.length; i++){
              for(var j = 0; j< info[i].length; j++){
                  var liBox = $('
' + info[i][j] + '
');
                  infoBox.append(liBox);
              }
          }

          $('li', infoBox).css({
              display: 'none'
          });

          var svgContainer = $('
');

          svgContainer.css({
                  position: 'absolute',
                  left: 0,
                  //top: 78,
                  top: 178,
                  //height: 200,
                  height: 0,
                  overflow: 'hidden',
                  width: 100
              });

          var svgSubContainer = $('
');
          svgSubContainer.css({
                  position: 'relative',
                  width: 100,
                  height: 200,
                  left: 0,
                  //height: '200px'
                   top: -100,
              });

          svgContainer.append(svgSubContainer);

          var paper = new Raphael(svgSubContainer[0], 100, 200);

          /* draw the new bullet points */
          function drawSvgLine(yStart, dir){

              paper
                .path( ['M', 26, yStart, 'L', 42, yStart + dir*16, 'L', 70, yStart + dir*16 ] )
                .attr({stroke: '#b6a0b4', 'stroke-width':1, 'opacity': 0.5})
                .glow({color: '#b6a0b4', opacity: 0.2, width: 5});
          }

          /* blue vertical line */
          paper
            .path( ['M', 70, 0, 'L', 70, 200] )
            .attr({stroke: '#12b7a7', 'stroke-width':1, 'opacity': 0.5})
            .glow({color: '#12b7a7', opacity: 0.2, width: 5});

          /* stem of bullets */
          paper
            .path( ['M', 0, 100, 'L', 34, 100] )
            .attr({stroke: '#b6a0b4', 'stroke-width':1, 'opacity': 0.5})
            .glow({color: '#b6a0b4', opacity: 0.2, width: 5});

          /* two short middle bullets */

          paper
            .path( ['M', 34, 100, 'L', 42, 92, 'L', 70, 92] )
            .attr({stroke: '#b6a0b4', 'stroke-width':1, 'opacity': 0.5})
            .glow({color: '#b6a0b4', opacity: 0.2, width: 5});

          paper
            .path( ['M', 34, 100, 'L', 42, 108, 'L', 70, 108] )
            .attr({stroke: '#b6a0b4', 'stroke-width':1, 'opacity': 0.5})
            .glow({color: '#b6a0b4', opacity: 0.2, width: 5});

          for(var i = 1; i<13; i++){
              var dir = -1;
              if(i > 6){
                  dir = 1;
              }
              drawSvgLine(10 + i * 14, dir);
          }

          outerDiv.append(nameHeader)
                  .append(nameBox)
                  .append(subjectBox)
                  .append(infoBox)
                  .append(svgContainer);

          element.append(outerDiv);

          outerDiv
             .velocity({bottom: 190, left: 300})
             .delay(5000)
             .velocity({left: 30})
             .velocity({left: 0}, {duration: 3000, loop: false});

          svgContainer.velocity({top: '-=100px', height: 200}, {duration:  700, delay: 2800, easing: 'linear', progress: function(el,percent){ }});
          svgSubContainer.velocity({top: 0}, {duration: 700, delay: 2800, easing: 'linear'});

          subjectBox.delay(1000).velocity('transition.slideRightIn', {stagger: 250});
          $('li.infoBox0', infoBox)
             .delay(1500)
             .velocity('transition.slideRightIn', {stagger: 100})
             .delay(3000)
             .velocity('transition.slideRightOut', {duration: 100});

          $('li.infoBox1', infoBox)
             .delay(6500)
             .velocity('transition.slideRightIn', {stagger:  200});

      }
    };
  });
<commit_msg>add some glow to the text<commit_after>'use strict';

/**
 * @ngdoc directive
 * @name lineupApp.directive:myNamePanel
 * @description
 * # myNamePanel
 */
angular.module('lineupApp')
  .directive('myNamePanel', function () {
    return {
      restrict: 'E',
      link: function postLink(scope, element, attrs) {
          console.log(attrs);
          var outerDiv = $('
');

          outerDiv.css({
              opacity: 0.6,
              position: 'absolute',
              left: -300,
              bottom: 500,
              color: '#b6a0b4',
              'text-transform': 'uppercase',
              'height': '300px',
              'font-family': '"Roboto", sans-serif',
              'padding-left': '80px',
              'text-shadow': '0 0 30px #fff'
          });

          var nameHeader = $('
name
');
          nameHeader.css({
              color: '#12b7a7',
             'line-height': '1em',
             'font-weight': 'bold'
          });

          var nameBox = $('
Scanlon
');
          nameBox.css({
             color: '#b6a0b4',
             'font-size': '2.6em',
             'line-height': '1em',
             'margin-bottom': '15px',
          });

          var subjectBox = $('
Subject: Robert Scanlon
');
          subjectBox.css({
             // 'font-weight': 'bold',
             'font-size': '1.6em',
             'display': 'none'
          });

          var info = [[
              'alias: "arscan"',
              'species: terran',
              'origin: terra',
              'legs: 2',
              'arms: 2',
              'height: 6\' 2"',
              'weight: 215lbs'
          ], [
              'education',
              'Cornell: BS Computer Science',
              'MIT: MS Engineering & Management',
              ' ',
              'occupation',
              'Software Engineer',
              'Web, Data viz'
          ]];

          var infoBox = $('
');

          infoBox.css({
              'list-style': 'none',
              'padding': 0
          });

          for(var i = 0; i< info.length; i++){
              for(var j = 0; j< info[i].length; j++){
                  var liBox = $('
' + info[i][j] + '
');
                  infoBox.append(liBox);
              }
          }

          $('li', infoBox).css({
              display: 'none'
          });

          var svgContainer = $('
');

          svgContainer.css({
                  position: 'absolute',
                  left: 0,
                  //top: 78,
                  top: 178,
                  //height: 200,
                  height: 0,
                  overflow: 'hidden',
                  width: 100
              });

          var svgSubContainer = $('
');
          svgSubContainer.css({
                  position: 'relative',
                  width: 100,
                  height: 200,
                  left: 0,
                  //height: '200px'
                   top: -100,
              });

          svgContainer.append(svgSubContainer);

          var paper = new Raphael(svgSubContainer[0], 100, 200);

          /* draw the new bullet points */
          function drawSvgLine(yStart, dir){

              paper
                .path( ['M', 26, yStart, 'L', 42, yStart + dir*16, 'L', 70, yStart + dir*16 ] )
                .attr({stroke: '#b6a0b4', 'stroke-width':1, 'opacity': 0.5})
                .glow({color: '#b6a0b4', opacity: 0.2, width: 5});
          }

          /* blue vertical line */
          paper
            .path( ['M', 70, 0, 'L', 70, 200] )
            .attr({stroke: '#12b7a7', 'stroke-width':1, 'opacity': 0.5})
            .glow({color: '#12b7a7', opacity: 0.2, width: 5});

          /* stem of bullets */
          paper
            .path( ['M', 0, 100, 'L', 34, 100] )
            .attr({stroke: '#b6a0b4', 'stroke-width':1, 'opacity': 0.5})
            .glow({color: '#b6a0b4', opacity: 0.2, width: 5});

          /* two short middle bullets */

          paper
            .path( ['M', 34, 100, 'L', 42, 92, 'L', 70, 92] )
            .attr({stroke: '#b6a0b4', 'stroke-width':1, 'opacity': 0.5})
            .glow({color: '#b6a0b4', opacity: 0.2, width: 5});

          paper
            .path( ['M', 34, 100, 'L', 42, 108, 'L', 70, 108] )
            .attr({stroke: '#b6a0b4', 'stroke-width':1, 'opacity': 0.5})
            .glow({color: '#b6a0b4', opacity: 0.2, width: 5});

          for(var i = 1; i<13; i++){
              var dir = -1;
              if(i > 6){
                  dir = 1;
              }
              drawSvgLine(10 + i * 14, dir);
          }

          outerDiv.append(nameHeader)
                  .append(nameBox)
                  .append(subjectBox)
                  .append(infoBox)
                  .append(svgContainer);

          element.append(outerDiv);

          outerDiv
             .velocity({bottom: 190, left: 300})
             .delay(5000)
             .velocity({left: 30})
             .velocity({left: 0}, {duration: 3000, loop: false});

          svgContainer.velocity({top: '-=100px', height: 200}, {duration:  700, delay: 2800, easing: 'linear', progress: function(el,percent){ }});
          svgSubContainer.velocity({top: 0}, {duration: 700, delay: 2800, easing: 'linear'});

          subjectBox.delay(1000).velocity('transition.slideRightIn', {stagger: 250});
          $('li.infoBox0', infoBox)
             .delay(1500)
             .velocity('transition.slideRightIn', {stagger: 100})
             .delay(3000)
             .velocity('transition.slideRightOut', {duration: 100});

          $('li.infoBox1', infoBox)
             .delay(6500)
             .velocity('transition.slideRightIn', {stagger:  200});

      }
    };
  });
<|endoftext|>


<commit_before>'use babel';

import { CompositeDisposable } from 'atom';
import Docker from 'dockerode';

export default {

  subscriptions: null,

  activate() {
    require('atom-package-deps').install('sphinx-preview')
      .then(() => {
        this.subscriptions = new CompositeDisposable();
        this.subscriptions.add(atom.commands.add('atom-workspace', {
          'sphinx-preview:toggle': () => this.toggle(),
        }));
      });
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  toggle() {
    if (this.isActiveFileRst()) {
      this.startSphinxServer((err) => {
        if (err) {
          atom.notifications.addError(err.message);
          return;
        }
        this.openBrowser();
      });
    } else {
      atom.notifications.addWarning('Active file must have reStructuredText extension (.rst)');
    }
  },

  getBindingPath() {
    return `/${atom.project.getPaths()[0].replace(/[/\\*]/g, '/').replace(':', '')}`; // WINDOWS
  },

  startSphinxServer(onStart) {
    let docker;
    if (process.platform === 'linux') {
      docker = new Docker({ socketPath: '/var/run/docker.sock' });
    } else {
      docker = new Docker({ host: 'http://localhost', port: 2375 });
    }

    const containerName = 'sphinx-preview';

    docker.listContainers({ all: true }, (err, containers) => {
      if (err) {
        onStart(err);
        return;
      }
      for (const container of containers) {
        if (container.Names.includes(`/${containerName}`)) {
          if (container.State !== 'running') {
            // Restart Container
            atom.notifications.addInfo('Starting exited container');
            const containerObj = docker.getContainer(container.Id);
            containerObj.start((errStart) => {
              if (errStart) {
                onStart(errStart);
                return;
              }
              atom.notifications.addSuccess('Container started');
              onStart();
            });
          } else {
            atom.notifications.addWarning('Container is already running');
            onStart();
          }
          return;
        }
      }

      const opts = {
        Image: 'dldl/sphinx-server',
        name: containerName,
        HostConfig: {
          Binds: [`${this.getBindingPath()}:/web`],
          PortBindings: {
            '8000/tcp': [{
              HostPort: '8000',
            }],
            '35729/tcp': [{
              HostPort: '35729',
            }],
          },
        },
      };

      atom.notifications.addInfo('Container is starting');
      docker.pull('dldl/sphinx-server:latest', (errPull) => {
        if (errPull) {
          onStart(errPull);
          return;
        }
        docker.createContainer(opts, (errCreate, container) => {
          if (errCreate) {
            onStart(errCreate);
            return;
          }
          container.start((errStart) => {
            if (errStart) {
              onStart(errStart);
              return;
            }
            atom.notifications.addSuccess('Container started');
            onStart();
          });
        });
      });
    });
  },

  isActiveFileRst() {
    const editor = atom.workspace.getActivePaneItem();
    if (!editor || !editor.buffer) return false;
    const activeFilePath = editor.buffer.file.path;
    if (!activeFilePath.includes('.')) return false;

    const ext = activeFilePath.slice(activeFilePath.lastIndexOf('.') + 1);
    return ext === 'rst';
  },

  openBrowser() {
    const editor = atom.workspace.getActivePaneItem();
    const activeFilePath = editor != null ? editor.buffer.file.path : null;

    if (!activeFilePath) return;

    const projectPath = atom.project.getPaths()[0];
    const relativePath = activeFilePath.replace(projectPath, '');
    const urlSuffix = relativePath.replace('rst', 'html').replace(/[/\\*]/g, '/');
    const fullUrl = `http://127.0.0.1:8000${urlSuffix}`;

    const viewer = atom.workspace.paneForURI(fullUrl);
    if (!viewer) {
      const prevActivePane = atom.workspace.getActivePane();
      atom.workspace.open(fullUrl, { searchAllPanes: true, split: 'right' }).then(() => {
        prevActivePane.activate();
      });
    } else {
      viewer.destroyItem(viewer.itemForURI(fullUrl));
    }
  },

};
<commit_msg>Fix macos docker daemon<commit_after>'use babel';

import { CompositeDisposable } from 'atom';
import Docker from 'dockerode';

export default {

  subscriptions: null,

  activate() {
    require('atom-package-deps').install('sphinx-preview')
      .then(() => {
        this.subscriptions = new CompositeDisposable();
        this.subscriptions.add(atom.commands.add('atom-workspace', {
          'sphinx-preview:toggle': () => this.toggle(),
        }));
      });
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  toggle() {
    if (this.isActiveFileRst()) {
      this.startSphinxServer((err) => {
        if (err) {
          atom.notifications.addError(err.message);
          return;
        }
        this.openBrowser();
      });
    } else {
      atom.notifications.addWarning('Active file must have reStructuredText extension (.rst)');
    }
  },

  getBindingPath() {
    return `/${atom.project.getPaths()[0].replace(/[/\\*]/g, '/').replace(':', '')}`; // WINDOWS
  },

  startSphinxServer(onStart) {
    let docker;
    if (process.platform === 'win32') {
      docker = new Docker({ host: 'http://localhost', port: 2375 });
    } else {
      docker = new Docker({ socketPath: '/var/run/docker.sock' });
    }

    const containerName = 'sphinx-preview';

    docker.listContainers({ all: true }, (err, containers) => {
      if (err) {
        onStart(err);
        return;
      }
      for (const container of containers) {
        if (container.Names.includes(`/${containerName}`)) {
          if (container.State !== 'running') {
            // Restart Container
            atom.notifications.addInfo('Starting exited container');
            const containerObj = docker.getContainer(container.Id);
            containerObj.start((errStart) => {
              if (errStart) {
                onStart(errStart);
                return;
              }
              atom.notifications.addSuccess('Container started');
              onStart();
            });
          } else {
            atom.notifications.addWarning('Container is already running');
            onStart();
          }
          return;
        }
      }

      const opts = {
        Image: 'dldl/sphinx-server',
        name: containerName,
        HostConfig: {
          Binds: [`${this.getBindingPath()}:/web`],
          PortBindings: {
            '8000/tcp': [{
              HostPort: '8000',
            }],
            '35729/tcp': [{
              HostPort: '35729',
            }],
          },
        },
      };

      atom.notifications.addInfo('Container is starting');
      docker.pull('dldl/sphinx-server:latest', (errPull) => {
        if (errPull) {
          onStart(errPull);
          return;
        }
        docker.createContainer(opts, (errCreate, container) => {
          if (errCreate) {
            onStart(errCreate);
            return;
          }
          container.start((errStart) => {
            if (errStart) {
              onStart(errStart);
              return;
            }
            atom.notifications.addSuccess('Container started');
            onStart();
          });
        });
      });
    });
  },

  isActiveFileRst() {
    const editor = atom.workspace.getActivePaneItem();
    if (!editor || !editor.buffer) return false;
    const activeFilePath = editor.buffer.file.path;
    if (!activeFilePath.includes('.')) return false;

    const ext = activeFilePath.slice(activeFilePath.lastIndexOf('.') + 1);
    return ext === 'rst';
  },

  openBrowser() {
    const editor = atom.workspace.getActivePaneItem();
    const activeFilePath = editor != null ? editor.buffer.file.path : null;

    if (!activeFilePath) return;

    const projectPath = atom.project.getPaths()[0];
    const relativePath = activeFilePath.replace(projectPath, '');
    const urlSuffix = relativePath.replace('rst', 'html').replace(/[/\\*]/g, '/');
    const fullUrl = `http://127.0.0.1:8000${urlSuffix}`;

    const viewer = atom.workspace.paneForURI(fullUrl);
    if (!viewer) {
      const prevActivePane = atom.workspace.getActivePane();
      atom.workspace.open(fullUrl, { searchAllPanes: true, split: 'right' }).then(() => {
        prevActivePane.activate();
      });
    } else {
      viewer.destroyItem(viewer.itemForURI(fullUrl));
    }
  },

};
<|endoftext|>


<commit_before>import fs from 'fs-extra'
import path from 'path'
import ora from 'ora'
import chalk from 'chalk'
import { exec } from 'child_process'
import { log } from '../utils'
import Mongonaut from 'mongonaut'
import Insert from './insert'
import dotenv from 'dotenv'

class Generator {
  constructor (answers, targetDir) {
    this.blueprints = []

    this.answers = answers
    this.targetDir = targetDir
    this.template = path.normalize(__dirname + '/../../../template')

    if (!answers.skipData) {
      this.insertSampleData()
      return
    }

    this.findBlueprints()
  }

  insertSampleData () {
    const walker = fs.walk(__dirname + '/../../../data/')
    let files = []

    walker.on('data', item => files.push(item.path))

    walker.on('end', function () {
      files.shift()

      const relatedDB = [
        'host',
        'name',
        'user',
        'password'
      ]

      for (let kind of relatedDB) {
        let key = 'db_' + kind,
            fromAnswers = this.answers[key]

        if (!fromAnswers) {
          continue
        }

        let inUppercase = key.toUpperCase()
        process.env[inUppercase] = fromAnswers
      }

      new Insert(files, this.findBlueprints.bind(this))
    }.bind(this))

    walker.on('error', (err, item) => {
      throw err
    })
  }

  findBlueprints () {
    const walker = fs.walk(this.template)

    walker.on('data', this.foundFile.bind(this))
    walker.on('end', this.insertBlueprints.bind(this))
  }

  foundFile (file) {
    const ignore = [
      'dist',
      'node_modules',
      'tmp'
    ]

    for (var dir of ignore) {
      if (file.path.indexOf(dir) == -1) {
        continue
      }

      return
    }

    this.blueprints.push(file.path)
  }

  done () {
    if (this.spinner) {
      this.spinner.stop()
    }

    log('Generated new site in ' + chalk.gray(this.targetDir))
  }

  insertBlueprints () {
    // Strip away the "/template" folder itself
    // We only need its contents
    var files = this.blueprints
    files.shift()

    // The properties of a parsed file path whose first
    // letter shall be replaced with a dot
    const replaceDots = [
      'name',
      'base'
    ]

    for (var file of files) {
      var filePath = path.parse(file)

      // Take care of the dotfiles
      for (var property of replaceDots) {
        filePath[property] = filePath[property].replace('_', '.')
      }

      // Generate the destination path
      var dest = path.join(this.targetDir, path.relative(this.template, path.format(filePath)))

      // Make sure the destination exists
      try {
        fs.ensureDirSync(path.dirname(dest))
      } catch (err) {
        return log(err)
      }

      if (filePath.name == '.env') {
        var contents = false

        try {
          contents = fs.readFileSync(file, 'utf8')
        } catch (err) {
          return log(err)
        }

        // Generate random session secret
        process.env.SESSION_SECRET = Math.random().toString(36).substr(2, 20)

        var parsed = dotenv.parse(new Buffer(contents)),
            newVariables = {}

        for (var property in parsed) {
          var fromProcess = process.env[property]

          if (fromProcess) {
            var prefix = property + '='
            contents = contents.replace(prefix + parsed[property], prefix + fromProcess)
          }
        }

        try {
          fs.writeFileSync(dest, contents)
        } catch (err) {
          return log(err)
        }

        continue
      }

      // If so, copy the blueprints
      try {
        fs.copySync(file, dest)
      } catch (err) {
        return log(err)
      }
    }

    if (this.answers.skipNpm) {
      this.done()
      return
    }

    this.spinner = ora(chalk.grey('Installing missing packages via npm'))
    this.spinner.color = 'grey'
    this.spinner.start()

    process.chdir(this.targetDir)

    exec('npm install', function (err, stdout, stderr) {
      if (err) throw err

      if (stdout && stdout.indexOf('example@1.0.0') > -1) {
        this.spinner.stop()
        this.done()

        return
      }

      if (stderr) {
        log(stderr)
      }

      log(chalk.red('Not able to install dependencies!'))
    }.bind(this))
  }
}

module.exports = Generator
<commit_msg>Some more comments<commit_after>import fs from 'fs-extra'
import path from 'path'
import ora from 'ora'
import chalk from 'chalk'
import { exec } from 'child_process'
import { log } from '../utils'
import Mongonaut from 'mongonaut'
import Insert from './insert'
import dotenv from 'dotenv'

class Generator {
  constructor (answers, targetDir) {
    this.blueprints = []

    this.answers = answers
    this.targetDir = targetDir
    this.template = path.normalize(__dirname + '/../../../template')

    if (!answers.skipData) {
      this.insertSampleData()
      return
    }

    this.findBlueprints()
  }

  insertSampleData () {
    const walker = fs.walk(__dirname + '/../../../data/')
    let files = []

    walker.on('data', item => files.push(item.path))

    walker.on('end', function () {
      files.shift()

      const relatedDB = [
        'host',
        'name',
        'user',
        'password'
      ]

      for (let kind of relatedDB) {
        let key = 'db_' + kind,
            fromAnswers = this.answers[key]

        if (!fromAnswers) {
          continue
        }

        let inUppercase = key.toUpperCase()
        process.env[inUppercase] = fromAnswers
      }

      new Insert(files, this.findBlueprints.bind(this))
    }.bind(this))

    walker.on('error', (err, item) => {
      throw err
    })
  }

  findBlueprints () {
    const walker = fs.walk(this.template)

    walker.on('data', this.foundFile.bind(this))
    walker.on('end', this.insertBlueprints.bind(this))
  }

  foundFile (file) {
    const ignore = [
      'dist',
      'node_modules',
      'tmp'
    ]

    for (var dir of ignore) {
      if (file.path.indexOf(dir) == -1) {
        continue
      }

      return
    }

    this.blueprints.push(file.path)
  }

  done () {
    if (this.spinner) {
      this.spinner.stop()
    }

    log('Generated new site in ' + chalk.gray(this.targetDir))
  }

  insertBlueprints () {
    // Strip away the "/template" folder itself
    // We only need its contents
    var files = this.blueprints
    files.shift()

    // The properties of a parsed file path whose first
    // letter shall be replaced with a dot
    const replaceDots = [
      'name',
      'base'
    ]

    for (var file of files) {
      var filePath = path.parse(file)

      // Take care of the dotfiles
      for (var property of replaceDots) {
        filePath[property] = filePath[property].replace('_', '.')
      }

      // Generate the destination path
      var dest = path.join(this.targetDir, path.relative(this.template, path.format(filePath)))

      // Make sure the destination exists
      try {
        fs.ensureDirSync(path.dirname(dest))
      } catch (err) {
        return log(err)
      }

      if (filePath.name == '.env') {
        var contents = false

        try {
          contents = fs.readFileSync(file, 'utf8')
        } catch (err) {
          return log(err)
        }

        // Generate random session secret
        process.env.SESSION_SECRET = Math.random().toString(36).substr(2, 20)

        // Parse content of default .env file
        var parsed = dotenv.parse(new Buffer(contents)),
            newVariables = {}

        for (var property in parsed) {
          var fromProcess = process.env[property]

          // If a new value for var exists, overwrite it in .env
          if (fromProcess) {
            var prefix = property + '='
            contents = contents.replace(prefix + parsed[property], prefix + fromProcess)
          }
        }

        // And finally, write the modified file
        try {
          fs.writeFileSync(dest, contents)
        } catch (err) {
          return log(err)
        }

        continue
      }

      // If so, copy the blueprints
      try {
        fs.copySync(file, dest)
      } catch (err) {
        return log(err)
      }
    }

    if (this.answers.skipNpm) {
      this.done()
      return
    }

    this.spinner = ora(chalk.grey('Installing missing packages via npm'))
    this.spinner.color = 'grey'
    this.spinner.start()

    process.chdir(this.targetDir)

    exec('npm install', function (err, stdout, stderr) {
      if (err) throw err

      if (stdout && stdout.indexOf('example@1.0.0') > -1) {
        this.spinner.stop()
        this.done()

        return
      }

      if (stderr) {
        log(stderr)
      }

      log(chalk.red('Not able to install dependencies!'))
    }.bind(this))
  }
}

module.exports = Generator
<|endoftext|>


<commit_before>'use strict';

const RSVP = require('rsvp');
const Task = require('../models/task');
const path = require('path');
const pkg = require('../../package.json');
const fs = require('fs');
const execa = require('../utilities/execa');

const Promise = RSVP.Promise;

class GitInitTask extends Task {
  run(_commandOptions) {
    let commandOptions = _commandOptions || {};
    const chalk = require('chalk');
    let ui = this.ui;

    if (commandOptions.skipGit) {
      return Promise.resolve();
    }

    let gitVersionWorked = false;
    return this._gitVersion().then(() => {
      gitVersionWorked = true;

      return this._gitInit()
        .then(() => this._gitAdd())
        .then(() => this._gitCommit())
        .then(() => ui.writeLine(chalk.green('Successfully initialized git.')));
    })
      .catch(error => {
        if (gitVersionWorked) {
          throw error;
        }
        // otherwise git version failed, so we skip git stuff.
      });
  }

  _gitVersion() {
    return execa('git', ['--version']);
  }

  _gitInit() {
    return execa('git', ['init']);
  }

  _gitAdd() {
    return execa('git', ['add', '.']);
  }

  _gitCommit() {
    const template = require('lodash.template');
    let commitTemplate = fs.readFileSync(path.join(__dirname, '../utilities/COMMIT_MESSAGE.txt'));
    let commitMessage = template(commitTemplate)(pkg);
    let env = this.buildGitEnvironment();
    return execa('git', ['commit', '-m', commitMessage], { env })
      .catch(error => {
        if (error && error.message && error.message.indexOf('git config --global user') > -1) {
          env.GIT_COMMITTER_NAME = 'Tomster';
          env.GIT_COMMITTER_EMAIL = 'tomster@emberjs.com';
          return execa('git', ['commit', '-m', commitMessage], { env });
        }
      });
  }

  buildGitEnvironment() {
    // Make sure we merge in the current environment so that git has access to
    // important environment variables like $HOME.
    return Object.assign({}, process.env, {
      GIT_AUTHOR_NAME: 'Tomster',
      GIT_AUTHOR_EMAIL: 'tomster@emberjs.com',
    });
  }
}

module.exports = GitInitTask;
<commit_msg>Auto merge of #7014 - ember-cli:fixup-6941, r=Turbo87<commit_after>'use strict';

const RSVP = require('rsvp');
const Task = require('../models/task');
const path = require('path');
const pkg = require('../../package.json');
const fs = require('fs');
const execa = require('../utilities/execa');

const Promise = RSVP.Promise;

module.exports = class GitInitTask extends Task {
  run(_commandOptions) {
    let commandOptions = _commandOptions || {};
    const chalk = require('chalk');
    let ui = this.ui;

    if (commandOptions.skipGit) {
      return Promise.resolve();
    }

    let gitVersionWorked = false;
    return this._gitVersion().then(() => {
      gitVersionWorked = true;

      return this._gitInit()
        .then(() => this._gitAdd())
        .then(() => this._gitCommit())
        .then(() => ui.writeLine(chalk.green('Successfully initialized git.')));
    })
      .catch(error => {
        if (gitVersionWorked) {
          throw error;
        }
        // otherwise git version failed, so we skip git stuff.
      });
  }

  _gitVersion() {
    return execa('git', ['--version']);
  }

  _gitInit() {
    return execa('git', ['init']);
  }

  _gitAdd() {
    return execa('git', ['add', '.']);
  }

  _gitCommit() {
    const template = require('lodash.template');
    let commitTemplate = fs.readFileSync(path.join(__dirname, '../utilities/COMMIT_MESSAGE.txt'));
    let commitMessage = template(commitTemplate)(pkg);
    let env = this.buildGitEnvironment();
    return execa('git', ['commit', '-m', commitMessage], { env })
      .catch(error => {
        if (isError(error) && error.message.indexOf('git config --global user') > -1) {
          env.GIT_COMMITTER_NAME = 'Tomster';
          env.GIT_COMMITTER_EMAIL = 'tomster@emberjs.com';
          return execa('git', ['commit', '-m', commitMessage], { env });
        }

        throw error;
      });
  }

  buildGitEnvironment() {
    // Make sure we merge in the current environment so that git has access to
    // important environment variables like $HOME.
    return Object.assign({}, process.env, {
      GIT_AUTHOR_NAME: 'Tomster',
      GIT_AUTHOR_EMAIL: 'tomster@emberjs.com',
    });
  }
};

function isError(error) {
  return typeof error === 'object' && error !== null && typeof error.message === 'string';
}
<|endoftext|>


<commit_before>/*jslint node: true */
/*global require */

module.exports = function (util, events, http) {
    "use strict";

    var setFilters = function (query, filter, filterList) {
        var filterLength = filterList.length;

        for (var pos = 0; pos < filterLength; pos++) {
            var field = filterList[pos].field;
            var fieldName = filterList[pos].name;

            if (query[fieldName] !== undefined) {
                var fieldValue = getFilterString(query[fieldName]);

                if (fieldValue !== undefined) {
                    var thisFilter = {};
                    thisFilter.term = {};
                    thisFilter.term[field] = fieldValue;
                    filter.and.push(thisFilter);
                }
            }
        }
    };

    var getFilterString = function (input) {
        var value;

        if (typeof input === "string") {
            value = input.toLowerCase();
        }

        return value;
    };

    var getFilterTypes = function (input) {
        var type = [];

        if (input !== undefined) {
            if (typeof input === "string") {
                type.push(input);
            } else if (Array.isArray(input)) {
                var isArrayOfStrings = input.every(function (element) {
                    return (typeof element === "string");
                });

                if (isArrayOfStrings) {
                    type = input;
                }
            }
        }

        return type;
    };

    var search = function () {
        events.EventEmitter.call(this);
    };

    util.inherits(search, events.EventEmitter);

    search.prototype.query = function (query) {
        var that = this;

        var filter = {
            "and" : [
            ]
        };

        var highlight = {
            "fields" : {
                "title" : {}
            },
            "encoder" : "html"
        };

        var requestData = {
            "query" : {
                "filtered" : {
                    query : {}
                }
            },
            "highlight" : highlight
        };

        var q = "";
        var qSuggestion = "";

        if (query.q !== undefined && typeof query.q === "string" && query.q !== "") {
            if (query.suggestion !== undefined) {
                q = "*";
                qSuggestion = query.q;
            } else {
                q = query.q;
                qSuggestion = q;
            }
        } else {
            q = "*";
            qSuggestion = "*";
        }

        requestData.query.filtered.query.query_string = {
            "query" : q,
            "default_operator" : "AND"
        };

        var priceMin;
        var priceMax;

        if (query["price-min"] !== undefined && typeof query["price-min"] === "string") {
            priceMin = query["price-min"].replace(/[^\d]/g, "");
            priceMin = parseInt(priceMin, 10);
        }

        if (query["price-max"] !== undefined && typeof query["price-max"] === "string") {
            priceMax = parseInt(query["price-max"].replace(/[^\d]/g, ""), 10);
            priceMax = parseInt(priceMax, 10);
        }

        if (! isNaN(priceMin) || ! isNaN(priceMax)) {
            var filterPrice = {};
            filterPrice.numeric_range = {};
            filterPrice.numeric_range.price = {};
            if (! isNaN(priceMin)) {
                filterPrice.numeric_range.price.from = priceMin;
            }

            if (! isNaN(priceMax)) {
                filterPrice.numeric_range.price.to = priceMax;
            }

            filter.and.push(filterPrice);
        }

        var filterTypesList = getFilterTypes(query.type);

        if (filterTypesList.length !== 0) {
            var filterTypes = {
                "terms" : {
                    "type" : filterTypesList
                }
            };

            filter.and.push(filterTypes);
        }

        setFilters(
            query,
            filter,
            [
                {
                    name : "make",
                    field : "make.lowercase"
                },
                {
                    name : "model",
                    field : "model.lowercase"
                },
                {
                    name : "year",
                    field : "year"
                },
                {
                    name : "where",
                    field : "user.where.lowercase"
                },
                {
                    name : "u",
                    field : "user.username.lowercase"
                }
            ]
        );

        if (filter.and.length !== 0) {
            requestData.query.filtered.filter = filter;
        }

        if (query.sort !== undefined) {
            if (query.sort === "price-min" || query.sort === "price-max") {
                var priceSort;

                if (query.sort === "price-min") {
                    priceSort = "asc";
                } else {
                    priceSort = "desc";
                }

                requestData.sort = [
                    {
                        "price" : {
                            "order" : priceSort,
                            "missing" : "_last",
                            "ignore_unmapped" : true
                        }
                    }
                ];
            }
        }

        if (query.suggestion !== undefined) {
            // see http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
            var qSuggestionEscaped = qSuggestion.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
            requestData.facets = {
                "title_suggestions":{
                    "terms" : {
                        "field" : "title.suggestions",
                        "regex" : "^" + qSuggestionEscaped.toLowerCase() + ".*",
                        "size" : 10,
                        "order" : "term"
                    }
                }
            };
        } else {
            requestData.facets = {
                "type" : {
                    "terms" : {
                        "field" : "type"
                    }
                },
                "make": {
                    "terms" : {
                        "field" : "make.lowercase",
                        "size" : 10
                    }
                },
                "model" : {
                    "terms" : {
                        "field" : "model.lowercase",
                        "size" : 10
                    }
                },
                "year": {
                    "terms" : {
                        "field" : "year",
                            "size" : 10
                    }
                },
                "where" : {
                    "terms" : {
                        "field" : "user.where.lowercase",
                        "size" : 10
                    }
                },
                "u" : {
                    "terms" : {
                        "field" : "user.username.lowercase",
                        "size" : 10
                    }
                }
            };
        }

        var sendBuffer = JSON.stringify(requestData);

        var from = 0;
        var size = 10;

        if (query.facets !== undefined || query.suggestion !== undefined) {
            size = 0;
        } else if (query.size !== undefined && ! isNaN(query.size)) {
            size = parseInt(query.size, 10);
        }

        if (query.from !== undefined && ! isNaN(query.from)) {
            from = parseInt(query.from, 10) - 1;
        }

        var postRequest = {
            hostname: "localhost",
            path: "/posts/post/_search?size=" + encodeURIComponent(size) + "&from=" + encodeURIComponent(from),
            port: 9200,
            method: "GET",
            headers: {
                "Content-Length": sendBuffer.length
            }
        };

        var buffer = "";

        var req = http.request(postRequest, function (res) {
            res.on("data", function (data) {
                buffer += data;
            });
            res.on("end", function() {
                if (res.statusCode === 200) {
                    var searchResponse;

                    try {
                        searchResponse = JSON.parse(buffer);
                    } catch (e) {
                        console.error("Error parsing the expected JSON response");

                        that.emit("failure", {
                            errorCode: "parsing-response"
                        });

                        return;
                    }

                    that.emit("success", searchResponse);
                } else {
                    console.warn("Request status code is %s", res.statusCode);
                    that.emit("failure", {
                        errorCode: res.statusCode
                    });
                }
            });
        });
        req.on("error", function (error) {
            that.emit("failure", {
                error: true,
                errorCode: "requestError"
            });
            console.log("elasticsearch request error");
        });
        req.write(sendBuffer);
        req.end();
    };

    exports.search = search;

    return exports;
};
<commit_msg>add transmission, traction, armor, and handicapped as search terms and facets<commit_after>/*jslint node: true */
/*global require */

module.exports = function (util, events, http) {
    "use strict";

    var setFilters = function (query, filter, filterList) {
        var filterLength = filterList.length;

        for (var pos = 0; pos < filterLength; pos++) {
            var field = filterList[pos].field;
            var fieldName = filterList[pos].name;

            if (query[fieldName] !== undefined) {
                var fieldValue = getFilterString(query[fieldName]);

                if (fieldValue !== undefined) {
                    var thisFilter = {};
                    thisFilter.term = {};
                    thisFilter.term[field] = fieldValue;
                    filter.and.push(thisFilter);
                }
            }
        }
    };

    var getFilterString = function (input) {
        var value;

        if (typeof input === "string") {
            value = input.toLowerCase();
        }

        return value;
    };

    var getFilterTypes = function (input) {
        var type = [];

        if (input !== undefined) {
            if (typeof input === "string") {
                type.push(input);
            } else if (Array.isArray(input)) {
                var isArrayOfStrings = input.every(function (element) {
                    return (typeof element === "string");
                });

                if (isArrayOfStrings) {
                    type = input;
                }
            }
        }

        return type;
    };

    var search = function () {
        events.EventEmitter.call(this);
    };

    util.inherits(search, events.EventEmitter);

    search.prototype.query = function (query) {
        var that = this;

        var filter = {
            "and" : [
            ]
        };

        var highlight = {
            "fields" : {
                "title" : {}
            },
            "encoder" : "html"
        };

        var requestData = {
            "query" : {
                "filtered" : {
                    query : {}
                }
            },
            "highlight" : highlight
        };

        var q = "";
        var qSuggestion = "";

        if (query.q !== undefined && typeof query.q === "string" && query.q !== "") {
            if (query.suggestion !== undefined) {
                q = "*";
                qSuggestion = query.q;
            } else {
                q = query.q;
                qSuggestion = q;
            }
        } else {
            q = "*";
            qSuggestion = "*";
        }

        requestData.query.filtered.query.query_string = {
            "query" : q,
            "default_operator" : "AND"
        };

        var priceMin;
        var priceMax;

        if (query["price-min"] !== undefined && typeof query["price-min"] === "string") {
            priceMin = query["price-min"].replace(/[^\d]/g, "");
            priceMin = parseInt(priceMin, 10);
        }

        if (query["price-max"] !== undefined && typeof query["price-max"] === "string") {
            priceMax = parseInt(query["price-max"].replace(/[^\d]/g, ""), 10);
            priceMax = parseInt(priceMax, 10);
        }

        if (! isNaN(priceMin) || ! isNaN(priceMax)) {
            var filterPrice = {};
            filterPrice.numeric_range = {};
            filterPrice.numeric_range.price = {};
            if (! isNaN(priceMin)) {
                filterPrice.numeric_range.price.from = priceMin;
            }

            if (! isNaN(priceMax)) {
                filterPrice.numeric_range.price.to = priceMax;
            }

            filter.and.push(filterPrice);
        }

        var filterTypesList = getFilterTypes(query.type);

        if (filterTypesList.length !== 0) {
            var filterTypes = {
                "terms" : {
                    "type" : filterTypesList
                }
            };

            filter.and.push(filterTypes);
        }

        setFilters(
            query,
            filter,
            [
                {
                    name : "make",
                    field : "make.lowercase"
                },
                {
                    name : "model",
                    field : "model.lowercase"
                },
                {
                    name : "year",
                    field : "year"
                },
                {
                    name : "where",
                    field : "user.where.lowercase"
                },
                {
                    name : "u",
                    field : "user.username.lowercase"
                },
                {
                    name : "transmission",
                    field : "transmission"
                },
                {
                    name : "traction",
                    field : "traction"
                },
                {
                    name : "armor",
                    field : "armor"
                },
                {
                    name : "handicapped",
                    field : "handicapped"
                }
            ]
        );

        if (filter.and.length !== 0) {
            requestData.query.filtered.filter = filter;
        }

        if (query.sort !== undefined) {
            if (query.sort === "price-min" || query.sort === "price-max") {
                var priceSort;

                if (query.sort === "price-min") {
                    priceSort = "asc";
                } else {
                    priceSort = "desc";
                }

                requestData.sort = [
                    {
                        "price" : {
                            "order" : priceSort,
                            "missing" : "_last",
                            "ignore_unmapped" : true
                        }
                    }
                ];
            }
        }

        if (query.suggestion !== undefined) {
            // see http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
            var qSuggestionEscaped = qSuggestion.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
            requestData.facets = {
                "title_suggestions":{
                    "terms" : {
                        "field" : "title.suggestions",
                        "regex" : "^" + qSuggestionEscaped.toLowerCase() + ".*",
                        "size" : 10,
                        "order" : "term"
                    }
                }
            };
        } else {
            requestData.facets = {
                "type" : {
                    "terms" : {
                        "field" : "type"
                    }
                },
                "make": {
                    "terms" : {
                        "field" : "make.lowercase",
                        "size" : 10
                    }
                },
                "model" : {
                    "terms" : {
                        "field" : "model.lowercase",
                        "size" : 10
                    }
                },
                "year": {
                    "terms" : {
                        "field" : "year",
                            "size" : 10
                    }
                },
                "where" : {
                    "terms" : {
                        "field" : "user.where.lowercase",
                        "size" : 10
                    }
                },
                "u" : {
                    "terms" : {
                        "field" : "user.username.lowercase",
                        "size" : 10
                    }
                },
                "transmission" : {
                    "terms" : {
                        "field" : "transmission"
                    }
                },
                "traction" : {
                    "terms" : {
                        "field" : "traction"
                    }
                },
                "armor" : {
                    "terms" : {
                        "field" : "armor"
                    }
                },
                "handicapped" : {
                    "terms" : {
                        "field" : "handicapped"
                    }
                }
            };
        }

        var sendBuffer = JSON.stringify(requestData);

        var from = 0;
        var size = 10;

        if (query.facets !== undefined || query.suggestion !== undefined) {
            size = 0;
        } else if (query.size !== undefined && ! isNaN(query.size)) {
            size = parseInt(query.size, 10);
        }

        if (query.from !== undefined && ! isNaN(query.from)) {
            from = parseInt(query.from, 10) - 1;
        }

        var postRequest = {
            hostname: "localhost",
            path: "/posts/post/_search?size=" + encodeURIComponent(size) + "&from=" + encodeURIComponent(from),
            port: 9200,
            method: "GET",
            headers: {
                "Content-Length": sendBuffer.length
            }
        };

        var buffer = "";

        var req = http.request(postRequest, function (res) {
            res.on("data", function (data) {
                buffer += data;
            });
            res.on("end", function() {
                if (res.statusCode === 200) {
                    var searchResponse;

                    try {
                        searchResponse = JSON.parse(buffer);
                    } catch (e) {
                        console.error("Error parsing the expected JSON response");

                        that.emit("failure", {
                            errorCode: "parsing-response"
                        });

                        return;
                    }

                    that.emit("success", searchResponse);
                } else {
                    console.warn("Request status code is %s", res.statusCode);
                    that.emit("failure", {
                        errorCode: res.statusCode
                    });
                }
            });
        });
        req.on("error", function (error) {
            that.emit("failure", {
                error: true,
                errorCode: "requestError"
            });
            console.log("elasticsearch request error");
        });
        req.write(sendBuffer);
        req.end();
    };

    exports.search = search;

    return exports;
};
<|endoftext|>