<commit_before>'use strict';

/** @interface */
const ITrackerAdapter = require('../interfaces/i-tracker-adapter');

const probe = require('tcp-ping').probe;

/**
 * Abstract Tracker Adapter class
 * @implements {ITrackerAdapter}
 * @extends {EventEmitter}
 */
class AbstractTrackerAdapter extends ITrackerAdapter {
	constructor() {
		super();

		if (this.constructor === AbstractTrackerAdapter) {
			throw new TypeError("Can not construct abstract class.");
		}

		/**
		 * @type {string}
		 * @protected
		 */
		this._url = '';

		/**
		 * Object that is converted to another class
		 * @type {function(*)}
		 * @protected
		 */
		this._adaptee = null;
	}

	/**
	 * @inheritDoc
	 */
	doQuery(optParams) {
		let params = /** @type {QueryParams} */ {};
		params.query = optParams.query || '.cbr';
		params.category = optParams.category || '';
		params.maxItems = optParams.maxItems || 10;
		params.order = optParams.order || '';
		params.desc = optParams.category || false;

		return new Promise((resolve, reject) => {
			this._searchQueryRequest(params)
				.then(responseData => {
					this._createQueryResponse(responseData)
						.then(queryResponse => {
							resolve(queryResponse);
						})
						.catch(err => {
							reject(err);
						});
				})
				.catch(err => {
					reject(err);
				});
		});
	}

	/**
	 * @inheritDoc
	 */
	getUrl() {
		return this._url;
	}

	/**
	 * @inheritDoc
	 */
	isAvailable() {
		return new Promise((resolve, reject) => {
			probe(this._getDomain(), 80, (err, avail) => {
				if (err) {
					reject(err);
				} else {
					if (avail) {
						resolve();
					} else {
						reject();
					}
				}
			})
		});
	}

	/**
	 * @protected
	 * @return {string}
	 */
	_getDomain() {
		const regExp = /(http|https):\/\//;
		return this._url.split(regExp)[2];
	}

	/**
	 * @param {QueryParams} params
	 * @return {Promise.<IQueryResponse|error>}
	 * @abstract
	 * @protected
	 */
	_searchQueryRequest(params) {
		throw new TypeError('Abstracted method _searchQueryRequest is not implemented');
	}

	/**
	 * @param {*} responseData
	 * @return {Promise.<IQueryResponse|error>}
	 * @abstract
	 * @protected
	 */
	_createQueryResponse(responseData) {
		throw new TypeError('Abstract method _createQueryResponse is not implemented');
	}
}

module.exports = AbstractTrackerAdapter;
<commit_msg>Refactored and reworked<commit_after>'use strict';

/** @interface */
const ITracker = require('../interfaces/i-tracker');

const probe = require('tcp-ping').probe;

/**
 * Abstract Tracker Adapter class
 * @implements {ITracker}
 * @extends {EventEmitter}
 */
class AbstractTrackerAdapter extends ITracker {
	constructor() {
		super();

		if (this.constructor === AbstractTrackerAdapter) {
			throw new TypeError("Can not construct abstract class.");
		}

		/**
		 * @type {string}
		 * @protected
		 */
		this._url = '';

		/**
		 * Object that is converted to another class
		 * @type {function(*)}
		 * @protected
		 */
		this._adaptee = null;

		/**
		 * @type {ISearchResponse}
		 * @protected
		 */
		this._searchResponse = null;
	}

	/**
	 * @inheritDoc
	 */
	search(optParams) {
		let params = /** @type {SearchParams} */ {};
		params.query = optParams.query || 'cbr';
		params.maxItems = optParams.maxItems || 10;
		params.order = optParams.order || '';
		params.desc = optParams.desc || false;

		return new Promise((resolve, reject) => {
			this.isAvailable()
				.then(() => {
					this._searchRequest(params.query)
						.then(responseData => {
							this._normalizeSearchResponse(responseData, params)
								.then(torrents => {
									resolve(torrents);
								})
								.catch(err => {
									reject(err);
								});
						})
						.catch(err => {
							reject(err);
						});
				})
				.catch(err => {
					reject(err);
				});
		});
	}

	/**
	 * @inheritDoc
	 */
	getUrl() {
		return this._url;
	}

	/**
	 * @inheritDoc
	 */
	isAvailable() {
		return new Promise((resolve, reject) => {
			probe(this._getDomain(), 80, (err, avail) => {
				if (err) {
					reject(err);
				} else {
					if (avail) {
						resolve();
					} else {
						reject(new Error('Tracker is not available now'));
					}
				}
			})
		});
	}

	/**
	 * @protected
	 * @return {string}
	 */
	_getDomain() {
		const regExp = /(http|https):\/\//;
		return this._url.split(regExp)[2];
	}

	/**
	 * @param {*} responseData
	 * @param {SearchParams} params
	 * @return {Promise.<Array.<ITorrent>|error>}
	 * @abstract
	 * @protected
	 */
	_normalizeSearchResponse(responseData, params) {
		return new Promise((resolve, reject) => {
			this._searchResponse.uninit();
			this._searchResponse.init(responseData, params)
				.then(() => {
					resolve(this._searchResponse.getTorrents());
				})
				.catch(err => {
					reject(err);
				});
		});
	}

	/**
	 * @param {string} queryString
	 * @return {Promise.<*|error>}
	 * @abstract
	 * @protected
	 */
	_searchRequest(queryString) {
		throw new TypeError('Abstracted method _searchRequest is not implemented');
	}
}

module.exports = AbstractTrackerAdapter;
<|endoftext|>


<commit_before>/*
 * This file is part of Cockpit.
 *
 * Copyright (C) 2013 Red Hat, Inc.
 *
 * Cockpit is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * Cockpit is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
 */

var $ = require("jquery");
var cockpit = require("cockpit");

/* These add themselves to jQuery so just including is enough */
require("patterns");
require("bootstrap-datepicker/dist/js/bootstrap-datepicker");

var _ = cockpit.gettext;

/* The server time object */
var server_time = null;

/* The current operation */
var operation = null;

/* The entry point, shows the dialog */
module.exports = function shutdown(op, st) {
    operation = op;
    server_time = st;
    $('#shutdown-dialog').modal('show');
};

$('#shutdown-dialog .shutdown-date').datepicker({
    autoclose: true,
    todayHighlight: true,
    format: 'yyyy-mm-dd',
    startDate: "today",
});

$("#shutdown-dialog input")
    .on('focusout', update)
    .on('change', update);

/* The delay in the dialog */
var delay = 0;
$("#shutdown-dialog .dropdown li")
    .on("click", function(ev) {
        delay = $(this).attr("value");
        update();
    });

/* Prefilling the date if it's been set */
var cached_date = null;
$('#shutdown-dialog .shutdown-date')
    .on('focusin', function() {
        cached_date = $(this).val();
    })
    .on('focusout', function() {
        if ($(this).val().length === 0)
            $(this).val(cached_date);
    });

$("#shutdown-dialog").on("show.bs.modal", function(ev) {

    /* The date picker also triggers this event, since it is modal */
    if (ev.target.id !== "shutdown-dialog")
        return;

    $("#shutdown-dialog textarea").
        val("").
        attr("placeholder", _("Message to logged in users")).
        attr("rows", 5);

    /* Track the value correctly */
    delay = $("#shutdown-dialog li:first-child").attr("value");

    server_time.wait().then(function() {
        $('#shutdown-dialog .shutdown-date').val(server_time.format());
        $('#shutdown-dialog .shutdown-hours').val(server_time.utc_fake_now.getUTCHours());
        $('#shutdown-dialog .shutdown-minutes').val(server_time.utc_fake_now.getUTCMinutes());
    });

    if (operation == 'shutdown') {
        $('#shutdown-dialog .modal-title').text(_("Shut Down"));
        $("#shutdown-dialog .btn-danger").text(_("Shut Down"));
    } else {
        $('#shutdown-dialog .modal-title').text(_("Restart"));
        $("#shutdown-dialog .btn-danger").text(_("Restart"));
    }

    update();
});

function update() {
    $("#shutdown-dialog input").parent().toggle(delay == "x");
    $("#shutdown-dialog .dropdown button span").text($("#shutdown-dialog li[value='" + delay + "']").text());

    var val = parseInt($('#shutdown-dialog .shutdown-minutes').val(), 10);
    if (val < 10)
        $('#shutdown-dialog .shutdown-minutes').val("0" + val);
}

/* Validate the input fields */
function calculate() {
    if (delay != "x")
        return cockpit.resolve("+" + delay);

    var datestr = $("#shutdown-dialog .shutdown-date").val();
    var hourstr = $("#shutdown-dialog .shutdown-hours").val();
    var minstr = $("#shutdown-dialog .shutdown-minutes").val();

    var h = parseInt(hourstr, 10);
    var m = parseInt(minstr, 10);

    var time_error = false;
    if (isNaN(h) || h < 0 || h > 23  ||
        isNaN(m) || m < 0 || m > 59) {
        time_error = true;
    }

    var date = new Date(datestr);

    var date_error = false;
    if (isNaN(date.getTime()) || date.getTime() < 0)
        date_error = true;

    var ex = null;
    if (time_error && date_error) {
        ex = new Error(_("Invalid date format and invalid time format"));
    } else if (time_error) {
        ex = new Error (_("Invalid time format"));
    } else if (date_error) {
        ex = new Error (_("Invalid date format"));
    }

    if (ex) {
        ex.target = "table td:last-child div";
        return cockpit.reject(ex);
    }

    var cmd = ["date", "--date=" + datestr + " " + hourstr + ":" + minstr, "+%s"];
    return cockpit.spawn(cmd, { err: "message" }).then(function(data) {
        var input_timestamp = parseInt(data, 10);
        var server_timestamp = parseInt(server_time.now.getTime() / 1000, 10);
        var offset = Math.ceil((input_timestamp - server_timestamp) / 60);
        if (offset < 0) {
            console.log("Shutdown offset in minutes is in the past:", offset);
            ex = new Error(_("Cannot schedule event in the past"));
            ex.target = "table td:last-child div";
            return cockpit.reject(ex);
        }

        return "+" + offset;
    });
}

/* Perform the actual action */
function perform(message) {
    return calculate().then(function(when) {
        var arg = (operation == "shutdown") ? "--poweroff" : "--reboot";
        var message = $("#shutdown-dialog textarea").val();
        if (operation == "restart")
            cockpit.hint("restart");
        return cockpit.spawn(["shutdown", arg, when, message], { superuser: true, err: "message" });
    });
}

/* Perform the action */

$("#shutdown-dialog .btn-danger").click(function() {
    $("#shutdown-dialog").dialog("promise", perform());
});
<commit_msg>systemd: Allow a shutdown one minute in the past<commit_after>/*
 * This file is part of Cockpit.
 *
 * Copyright (C) 2013 Red Hat, Inc.
 *
 * Cockpit is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * Cockpit is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
 */

var $ = require("jquery");
var cockpit = require("cockpit");

/* These add themselves to jQuery so just including is enough */
require("patterns");
require("bootstrap-datepicker/dist/js/bootstrap-datepicker");

var _ = cockpit.gettext;

/* The server time object */
var server_time = null;

/* The current operation */
var operation = null;

/* The entry point, shows the dialog */
module.exports = function shutdown(op, st) {
    operation = op;
    server_time = st;
    $('#shutdown-dialog').modal('show');
};

$('#shutdown-dialog .shutdown-date').datepicker({
    autoclose: true,
    todayHighlight: true,
    format: 'yyyy-mm-dd',
    startDate: "today",
});

$("#shutdown-dialog input")
    .on('focusout', update)
    .on('change', update);

/* The delay in the dialog */
var delay = 0;
$("#shutdown-dialog .dropdown li")
    .on("click", function(ev) {
        delay = $(this).attr("value");
        update();
    });

/* Prefilling the date if it's been set */
var cached_date = null;
$('#shutdown-dialog .shutdown-date')
    .on('focusin', function() {
        cached_date = $(this).val();
    })
    .on('focusout', function() {
        if ($(this).val().length === 0)
            $(this).val(cached_date);
    });

$("#shutdown-dialog").on("show.bs.modal", function(ev) {

    /* The date picker also triggers this event, since it is modal */
    if (ev.target.id !== "shutdown-dialog")
        return;

    $("#shutdown-dialog textarea").
        val("").
        attr("placeholder", _("Message to logged in users")).
        attr("rows", 5);

    /* Track the value correctly */
    delay = $("#shutdown-dialog li:first-child").attr("value");

    server_time.wait().then(function() {
        $('#shutdown-dialog .shutdown-date').val(server_time.format());
        $('#shutdown-dialog .shutdown-hours').val(server_time.utc_fake_now.getUTCHours());
        $('#shutdown-dialog .shutdown-minutes').val(server_time.utc_fake_now.getUTCMinutes());
    });

    if (operation == 'shutdown') {
        $('#shutdown-dialog .modal-title').text(_("Shut Down"));
        $("#shutdown-dialog .btn-danger").text(_("Shut Down"));
    } else {
        $('#shutdown-dialog .modal-title').text(_("Restart"));
        $("#shutdown-dialog .btn-danger").text(_("Restart"));
    }

    update();
});

function update() {
    $("#shutdown-dialog input").parent().toggle(delay == "x");
    $("#shutdown-dialog .dropdown button span").text($("#shutdown-dialog li[value='" + delay + "']").text());

    var val = parseInt($('#shutdown-dialog .shutdown-minutes').val(), 10);
    if (val < 10)
        $('#shutdown-dialog .shutdown-minutes').val("0" + val);
}

/* Validate the input fields */
function calculate() {
    if (delay != "x")
        return cockpit.resolve("+" + delay);

    var datestr = $("#shutdown-dialog .shutdown-date").val();
    var hourstr = $("#shutdown-dialog .shutdown-hours").val();
    var minstr = $("#shutdown-dialog .shutdown-minutes").val();

    var h = parseInt(hourstr, 10);
    var m = parseInt(minstr, 10);

    var time_error = false;
    if (isNaN(h) || h < 0 || h > 23  ||
        isNaN(m) || m < 0 || m > 59) {
        time_error = true;
    }

    var date = new Date(datestr);

    var date_error = false;
    if (isNaN(date.getTime()) || date.getTime() < 0)
        date_error = true;

    var ex = null;
    if (time_error && date_error) {
        ex = new Error(_("Invalid date format and invalid time format"));
    } else if (time_error) {
        ex = new Error (_("Invalid time format"));
    } else if (date_error) {
        ex = new Error (_("Invalid date format"));
    }

    if (ex) {
        ex.target = "table td:last-child div";
        return cockpit.reject(ex);
    }

    var cmd = ["date", "--date=" + datestr + " " + hourstr + ":" + minstr, "+%s"];
    return cockpit.spawn(cmd, { err: "message" }).then(function(data) {
        var input_timestamp = parseInt(data, 10);
        var server_timestamp = parseInt(server_time.now.getTime() / 1000, 10);
        var offset = Math.ceil((input_timestamp - server_timestamp) / 60);

        /* If the time in minutes just changed, make it happen now */
        if (offset === -1) {
            offset = 0;

        /* Otherwise this is a failure */
        } else if (offset < 0) {
            console.log("Shutdown offset in minutes is in the past:", offset);
            ex = new Error(_("Cannot schedule event in the past"));
            ex.target = "table td:last-child div";
            return cockpit.reject(ex);
        }

        return "+" + offset;
    });
}

/* Perform the actual action */
function perform(message) {
    return calculate().then(function(when) {
        var arg = (operation == "shutdown") ? "--poweroff" : "--reboot";
        var message = $("#shutdown-dialog textarea").val();
        if (operation == "restart")
            cockpit.hint("restart");
        return cockpit.spawn(["shutdown", arg, when, message], { superuser: true, err: "message" });
    });
}

/* Perform the action */

$("#shutdown-dialog .btn-danger").click(function() {
    $("#shutdown-dialog").dialog("promise", perform());
});
<|endoftext|>


<commit_before>/**
 * Google Maps Service module.
 * @module @google/maps
 */

/**
 * Initializes the Google Maps service.
 *
 * @param {Object} options
 * @param {string} options.key - API key (required, unless clientID / clientSecret provided).
 * @param {string=} options.clientId - Maps API for Work - client ID.
 * @param {string=} options.clientSecret - Maps API for Work - client secret (aka private key).
 * @param {number=} options.rate.limit - Maximum number of requests per period (default: 10).
 * @param {number=} options.rate.period - Period for rate limit (default: 1000 ms).
 * @param {Function=} options.Promise - Promise constructor (optional).
 * @return {GoogleMapsClient} The client object containing all API methods.
 */
 exports.init = function(options) {

  var makeApiCall = require('./internal/make-api-call').inject(options || {});

  var makeApiMethod = function(apiConfig) {
    return function(query, callback) {
      query = apiConfig.validator(query);
      query.supportsClientId = apiConfig.supportsClientId !== false;
      return makeApiCall(apiConfig.url, query, callback);
    };
  };

  var geocode = require('./apis/geocode');
  var timezone = require('./apis/timezone');
  var directions = require('./apis/directions');
  var distanceMatrix = require('./apis/distance-matrix');
  var elevation = require('./apis/elevation');
  var roads = require('./apis/roads');
  var places = require('./apis/places');

  return {
    directions: makeApiMethod(directions.directions),
    distanceMatrix: makeApiMethod(distanceMatrix.distanceMatrix),
    elevation: makeApiMethod(elevation.elevation),
    elevationAlongPath: makeApiMethod(elevation.elevationAlongPath),
    geocode: makeApiMethod(geocode.geocode),
    reverseGeocode: makeApiMethod(geocode.reverseGeocode),
    places: makeApiMethod(places.places),
    place: makeApiMethod(places.place),
    placesPhoto: makeApiMethod(places.placesPhoto),
    placesAutoComplete: makeApiMethod(places.placesAutoComplete),
    snapToRoads: makeApiMethod(roads.snapToRoads),
    speedLimits: makeApiMethod(roads.speedLimits),
    snappedSpeedLimits: makeApiMethod(roads.snappedSpeedLimits),
    timezone: makeApiMethod(timezone.timezone)
  };

};

<commit_msg>Send validation exceptions to callback.<commit_after>/**
 * Google Maps Service module.
 * @module @google/maps
 */

/**
 * Initializes the Google Maps service.
 *
 * @param {Object} options
 * @param {string} options.key - API key (required, unless clientID / clientSecret provided).
 * @param {string=} options.clientId - Maps API for Work - client ID.
 * @param {string=} options.clientSecret - Maps API for Work - client secret (aka private key).
 * @param {number=} options.rate.limit - Maximum number of requests per period (default: 10).
 * @param {number=} options.rate.period - Period for rate limit (default: 1000 ms).
 * @param {Function=} options.Promise - Promise constructor (optional).
 * @return {GoogleMapsClient} The client object containing all API methods.
 */
 exports.init = function(options) {

  var makeApiCall = require('./internal/make-api-call').inject(options || {});

  var makeApiMethod = function(apiConfig) {
    return function(query, callback) {
      try {
        query = apiConfig.validator(query);
      } catch (e) {
        callback(e, null);
        return;
      }
      query.supportsClientId = apiConfig.supportsClientId !== false;
      return makeApiCall(apiConfig.url, query, callback);
    };
  };

  var geocode = require('./apis/geocode');
  var timezone = require('./apis/timezone');
  var directions = require('./apis/directions');
  var distanceMatrix = require('./apis/distance-matrix');
  var elevation = require('./apis/elevation');
  var roads = require('./apis/roads');
  var places = require('./apis/places');

  return {
    directions: makeApiMethod(directions.directions),
    distanceMatrix: makeApiMethod(distanceMatrix.distanceMatrix),
    elevation: makeApiMethod(elevation.elevation),
    elevationAlongPath: makeApiMethod(elevation.elevationAlongPath),
    geocode: makeApiMethod(geocode.geocode),
    reverseGeocode: makeApiMethod(geocode.reverseGeocode),
    places: makeApiMethod(places.places),
    place: makeApiMethod(places.place),
    placesPhoto: makeApiMethod(places.placesPhoto),
    placesAutoComplete: makeApiMethod(places.placesAutoComplete),
    snapToRoads: makeApiMethod(roads.snapToRoads),
    speedLimits: makeApiMethod(roads.speedLimits),
    snappedSpeedLimits: makeApiMethod(roads.snappedSpeedLimits),
    timezone: makeApiMethod(timezone.timezone)
  };

};

<|endoftext|>


<commit_before>const React = require('react');
const h = require('react-hyperscript');
//const queryString = require('query-string');
const _ = require('lodash');
//const Loader = require('react-loader');

// const hideTooltips = require('../../common/cy/events/click').hideTooltips;
// const removeStyle= require('../../common/cy/manage-style').removeStyle;
const make_cytoscape = require('../../common/cy/');
// const interactionsStylesheet= require('../../common/cy/interactions-stylesheet');
const { ServerAPI } = require('../../services/');
const { BaseNetworkView } = require('../../common/components');
//const { getLayoutConfig } = require('../../common/cy/layout');
//const downloadTypes = require('../../common/config').downloadTypes;

const enrichmentConfig={
  //extablish toolbar and declare features to not include
  toolbarButtons: _.differenceBy(BaseNetworkView.config.toolbarButtons,[{'id': 'expandCollapse'}, {'id': 'showInfo'}],'id'),
  menus: BaseNetworkView.config.menus,
  //allow for searching of nodes
  useSearchBar: true
};

function validateInput(query, array, object)
{
  //recognized input
  if(_.isEmpty(object) && array.length == 0 )
  {
    alert("Thank you for your input. ***Service will continue to analysis");
    ServerAPI.enrichmentAPI(query, 'analysis');
    console.log(ServerAPI.enrichmentAPI(query, 'analysis'));
  }
    //unrec gene
  else if(array.length != 0 && _.isEmpty(object) == true)
  {
    let errorMes = "";
    for (let i = 0; i < array.length; i++)
    {
      errorMes += "\n" + array[i] + " is not a recognized";
    }
    errorMes += "\nPlease fix your input and submit again";
    alert(errorMes);
  }
  //duplicate
  else if(_.isEmpty(object) == false && array.length == 0)
    {
      let errorMes = "";
      for (let i = 0; i < _.keys(object).length; i++ )
      {
        let propertyName = _.keys(object)[i];
        let duplicateVal = object[propertyName];
        errorMes += "\n" + duplicateVal[0] + " and " + duplicateVal[1] + " are duplicates ";
      }
      errorMes += "\nPlease fix your input and submit again";
      alert(errorMes);
    }
  //unrec and duplicate
  else
  {
    let errorMes = "";
    for (let i = 0; i < _.keys(object).length; i++ )
      {
        let propertyName = _.keys(object)[i];
        let duplicateVal = object[propertyName];
        errorMes += "\n" + duplicateVal[0] + " and " + duplicateVal[1] + " are duplicates ";
      }
    for (let i = 0; i < array.length; i++)
    {
      errorMes += "\n" + array[i] + " is not recognized";
    }
    errorMes += "\nPlease fix your input and submit again";
    alert(errorMes);
  }
}

class Enrichment extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cy: make_cytoscape({headless: true}),
      componentConfig: enrichmentConfig,
      layoutConfig: {},
      networkJSON: {},
      networkMetadata: {
        name: '',
        datasource: '',
        comments: []
      },
      query: '',
      titleContainer: [],
    };
  }

  geneInputChange(e) {
    this.setState( {query: e.target.value});
  }

  geneInputSubmission(input){
    const geneArray = input.split(/\n/g);
    const inputObject = {genes: _.pull(geneArray,"")};
    console.log(inputObject.genes);

    ServerAPI.enrichmentAPI(inputObject, "validation").then(function(result) {
      //object
      let duplicate = result.duplicate;
      //array of objects
      let geneInfo = result.geneInfo;
      //array
      let unrecognized = result.unrecognized;
      console.log(unrecognized);
      console.log(duplicate);
      validateInput(inputObject, unrecognized, duplicate);
    });
  }

  render() {
    const state = this.state;
    const baseView = h(BaseNetworkView.component, {
      componentConfig: state.componentConfig,
      //titles at top of toolbar
      networkMetadata: {},
      titleContainer: [
        h('h4', [
          h('span', 'Pathway Enrichment   '),]),
          h('img', {
            src: '/img/humanIcon.png'
            }),
          h('div.gene-input-container', [
            h('textarea.gene-input-box', {
             placeholder: 'Enter one gene per line',
             onChange: e => this.geneInputChange(e),
             onKeyPress: e => {
               this.geneInputChange(e);
             }
            })]),
          h('submit-container', {
            onClick: () => {
              this.geneInputSubmission(this.state.query);
            }},
          [
          h('button.submit', 'Submit'),
          ])
      ]
    });
    return h('div.main', [baseView]);
  }
}
module.exports = Enrichment;

//NOTE: CURRENTLY ONLY RENDERS ON PAGE WHEN base-network-view.js function 'componentDidMount(){}'
//      IS COMMENTED OUT<commit_msg>take into account that min set size default is 5 and max is 200<commit_after>const React = require('react');
const h = require('react-hyperscript');
//const queryString = require('query-string');
const _ = require('lodash');
//const Loader = require('react-loader');

// const hideTooltips = require('../../common/cy/events/click').hideTooltips;
// const removeStyle= require('../../common/cy/manage-style').removeStyle;
// const make_cytoscape = require('../../common/cy/');
// const interactionsStylesheet= require('../../common/cy/interactions-stylesheet');
const { ServerAPI } = require('../../services/');
const { BaseNetworkView } = require('../../common/components');
//const { getLayoutConfig } = require('../../common/cy/layout');
//const downloadTypes = require('../../common/config').downloadTypes;

const enrichmentConfig={
  //extablish toolbar and declare features to not include
  toolbarButtons: _.differenceBy(BaseNetworkView.config.toolbarButtons,[{'id': 'expandCollapse'}, {'id': 'showInfo'}],'id'),
  menus: BaseNetworkView.config.menus,
  //allow for searching of nodes
  useSearchBar: true
};

function validateInput(query, array, object)
{
  //recognized input
  if(_.isEmpty(object) && array.length == 0 )
  {
    alert("Thank you for your input. ***Service will continue to analysis");
    //ServerAPI.enrichmentAPI(query, 'analysis');
    //console.log(ServerAPI.enrichmentAPI(query, 'validate'));
    //console.log(ServerAPI.enrichmentAPI(query, 'analysis'));
  }
    //unrec gene
  else if(array.length != 0 && _.isEmpty(object) == true)
  {
    let errorMes = "";
    for (let i = 0; i < array.length; i++)
    {
      errorMes += "\n" + array[i] + " is not a recognized";
    }
    errorMes += "\nPlease fix your input and submit again";
    alert(errorMes);
  }
  //duplicate
  else if(_.isEmpty(object) == false && array.length == 0)
    {
      let errorMes = "";
      for (let i = 0; i < _.keys(object).length; i++ )
      {
        let propertyName = _.keys(object)[i];
        let duplicateVal = object[propertyName];
        errorMes += "\n" + duplicateVal[0] + " and " + duplicateVal[1] + " are duplicates ";
      }
      errorMes += "\nPlease fix your input and submit again";
      alert(errorMes);
    }
  //unrec and duplicate
  else
  {
    let errorMes = "";
    for (let i = 0; i < _.keys(object).length; i++ )
      {
        let propertyName = _.keys(object)[i];
        let duplicateVal = object[propertyName];
        errorMes += "\n" + duplicateVal[0] + " and " + duplicateVal[1] + " are duplicates ";
      }
    for (let i = 0; i < array.length; i++)
    {
      errorMes += "\n" + array[i] + " is not recognized";
    }
    errorMes += "\nPlease fix your input and submit again";
    alert(errorMes);
  }
}

class Enrichment extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      componentConfig: enrichmentConfig,
      networkMetadata: {
        name: '',
        datasource: '',
        comments: []
      },
      query: '',
      titleContainer: [],
    };
  }

  geneInputChange(e) {
    this.setState( {query: e.target.value});
  }

  geneInputSubmission(input){
    const geneArray = input.split(/\n/g);
    if(geneArray.length < 5) return alert("Please input 4 or more tokens");
    if(geneArray.length > 200)return alert("Please input less than 200 tokens");
    const inputObject = {genes: _.pull(geneArray,"")};
    //console.log(inputObject.genes);

    ServerAPI.enrichmentAPI(inputObject, "validation").then(function(result) {
      //object
      let duplicate = result.duplicate;
      //array of objects
      let geneInfo = result.geneInfo;
      //array
      let unrecognized = result.unrecognized;
      //console.log(unrecognized);
      //console.log(duplicate);
      validateInput(inputObject, unrecognized, duplicate);
    });
  }

  render() {
    const state = this.state;
    const baseView = h(BaseNetworkView.component, {
      componentConfig: state.componentConfig,
      //titles at top of toolbar
      networkMetadata: {},
      titleContainer: [
        h('h4', [
          h('span', 'Pathway Enrichment   '),]),
          h('img', {
            src: '/img/humanIcon.png'
            }),
          h('div.gene-input-container', [
            h('textarea.gene-input-box', {
             placeholder: 'Enter one gene per line',
             onChange: e => this.geneInputChange(e),
             onKeyPress: e => {
               this.geneInputChange(e);
             }
            })]),
          h('submit-container', {
            onClick: () => {
              this.geneInputSubmission(this.state.query);
            }},
          [
          h('button.submit', 'Submit'),
          ])
      ]
    });
    return h('div.main', [baseView]);
  }
}
module.exports = Enrichment;

//NOTE: CURRENTLY ONLY RENDERS ON PAGE WHEN base-network-view.js function 'componentDidMount(){}'
//      IS COMMENTED OUT<|endoftext|>


<commit_before>/**
 * Randy is a country singer that sends notifications, drives a Trans Am, and is one serious bad ass.
 *
 * @package randy
 * @author Andrew Sliwinski <andrew@diy.org>
 */

/**
 * Dependencies
 */
var _       = require('underscore'),
    async   = require('async'),
    redis   = require('redis'),
    sio     = require('socket.io'),
    uuid    = require('node-uuid');

var Util    = require('./util'),
    Storage = require('./storage');

/**
 * Generic socket emitter.
 *
 * @param {Object} Socket
 * @param {Object} Notice
 *
 * @return {void}
 */
function emit (socket, notice) {
    socket.emit('notice', notice);
}

// --------------------------------

/**
 * Constructor
 */
function Randy () {
    var self = this;

    // Setup
    self.ns         = 'randy';
    self.pub        = null;
    self.sub        = null;
    self.store      = null;
    self.io         = null;
    self.sockets    = new Object(null);

    /**
     * Gets the socket (if available) for the specified target.
     *
     * @param {String} Target
     *
     * @return {Object}
     */
    function getSocket (target, callback) {
        if (target === null || target === '') {
            callback(null, self.io.sockets);
        } else {
            try {
                callback(null, self.sockets[target].socket);
            } catch (err) {
                Util.stdout(err);
            }
        }
    };

    /**
     * Subscription "message" event handler.
     *
     * @param {String} Channel
     * @param {String} Notice (JSON String)
     *
     * @return {void}
     */
    self.listener   = function (channel, data) {
        async.auto({
            decode:      function (callback) {
                Util.parse(data, callback);
            },

            socket:     ['decode', function (callback, obj) {
                getSocket(obj.decode.target, callback);
            }],

            emit:       ['socket', function (callback, obj) {
                emit(obj.socket, obj.decode);
            }]
        }, Util.stdout);
    };

    /**
     * Socket.io "connection" event handler.
     *
     * @param {Object} Socket
     *
     * @return {void}
     */
    self.connection = function (socket) {

        /**
         * Registers a socket to begin recieving notifications.
         *
         * @param {String} Unique user id
         *
         * @return {void}
         */
        socket.on('register', function (id) {
            // Check if exists
            if (typeof self.sockets[id] === 'undefined') {
                self.sockets[id] = {
                    id:         socket.id,
                    socket:     socket
                };
            } else {
                self.sockets[id].id     = socket.id;
                self.sockets[id].socket = socket;
            }

            // Emit from storage
            self.store.all(id, function (err, obj) {
                if (err) {
                    callback(err);
                } else {
                    async.forEach(obj, function (a, callback) {
                        emit(socket, a);
                        callback();
                    }, Util.stdout);
                }
            });
        });

        /**
         * Dismisses a persistent notification.
         *
         * @param {Object} Identity
         *                      - id {String, Required}
         *                      - uid {String, Required}
         *
         * @return {void}
         */
        socket.on('dismiss', function (data) {
            self.store.del(data.uid, data.id, Util.stdout);
        });

        /**
         * Submits a new event via the loopback interface.
         *
         * @param {Object} Notification object (see "register" method).
         *
         * @return {void}
         */
        socket.on('loopback', function (data) {
            self.submit(data, Util.stdout);
        });
    };
};

/**
 * Start listening for connections on the specified port.
 *
 * @param {Number} Port
 *
 * @return {Error}
 */
Randy.prototype.listen = function (port, arg, callback) {
    var self = this;

    // Detect argument list
    if (_.isUndefined(callback)) {
        callback    = arg;
        arg         = {
            port:       null,
            host:       null,
            pass:       null,
            options:    null
        };
    };

    // Normalize "null" types
    for (var item in arg) {
        arg[item] = (arg[item] === 'null') ? null : arg[item];
        arg[item] = (item === 'port') ? Number(arg[item]) : arg[item];
    }

    async.auto({
        connect:        function (callback) {
            self.store  = new Storage(redis.createClient(arg.port, arg.host, arg.options));
            self.pub    = redis.createClient(arg.port, arg.host, arg.options);
            self.sub    = redis.createClient(arg.port, arg.host, arg.options);
            callback(null);
        },

        authenticate:   ['connect', function (callback) {
            if (arg.pass !== null) {
                async.parallel([
                    function (callback) {
                        self.store.auth(arg.pass, callback);
                    },
                    function (callback) {
                        self.pub.auth(arg.pass, callback);
                    },
                    function (callback) {
                        self.sub.auth(arg.pass, callback);
                    }
                ], callback);
            } else {
                callback(null);
            }
        }],

        pubsub:         ['authenticate', function (callback) {
            self.sub.subscribe(self.ns);
            self.sub.on('message', self.listener);
            callback(null);
        }],

        sockets:        ['authenticate', function (callback) {
            self.io     = sio.listen(Number(port));
            self.io.set('log level', 1);
            self.io.sockets.on('connection', self.connection);
            callback(null);
        }]
    }, callback);
};

/**
 * Submits a new notification.
 *
 * @param {Object} Notification
 *                  - persist {Boolean, Default=false}
 *                  - target {String, Default=null}
 *                  - message {String, Required}
 *
 * @return {Error}
 */
Randy.prototype.submit = function (notice, callback) {
    var self = this;

    _.defaults(notice, {
        id:         uuid.v4(),                  // Assign uuid
        stamp:      new Date().toJSON(),        // Timestamp
        persist:    false,
        target:     null,
        message:    null
    });

    // Normalize typing
    notice.persist  = (notice.persist.toLowerCase() === 'true' || notice.persist === true) ? true : false;
    notice.target   = (notice.target === '') ? null : notice.target;

    // Persist
    if (notice.persist && notice.target !== null) {
        self.store.set(notice.target, notice.id, notice, Util.stdout);
    }

    // If no message is specified, drop the request
    if (notice.message === null || notice.message === '') {
        return callback('No message was specified.');
    }

    // Hash notice and publish to redis store
    async.auto({
        encode:     function (callback) {
            Util.stringify(notice, callback);
        },

        publish:    ['encode', function (callback, obj) {
            self.pub.publish(self.ns, obj.encode);
            callback(null);
        }]
    }, callback);
};

/**
 * Destroy the socket.io connection and redis subscription(s).
 *
 * @return {Error}
 */
Randy.prototype.destroy = function (callback) {
    var self = this;

    try {
        self.sub.unsubscribe();
        self.pub.end();
        self.sub.end();
        callback(null);
    } catch (err) {
        Util.stdout(err);
    }
};

// --------------------------------
// --------------------------------

/**
 * Export
 */
module.exports = new Randy();
<commit_msg>Got all crazy with managing multiple redis connections<commit_after>/**
 * Randy is a country singer that sends notifications, drives a Trans Am, and is one serious bad ass.
 *
 * @package randy
 * @author Andrew Sliwinski <andrew@diy.org>
 */

/**
 * Dependencies
 */
var _       = require('underscore'),
    async   = require('async'),
    redis   = require('redis'),
    sio     = require('socket.io'),
    uuid    = require('node-uuid');

var Util    = require('./util'),
    Storage = require('./storage');

/**
 * Generic socket emitter.
 *
 * @param {Object} Socket
 * @param {Object} Notice
 *
 * @return {void}
 */
function emit (socket, notice) {
    socket.emit('notice', notice);
}

// --------------------------------

/**
 * Constructor
 */
function Randy () {
    var self = this;

    // Setup
    self.ns         = 'randy';
    self.pub        = null;
    self.sub        = null;
    self.store      = null;
    self.io         = null;
    self.sockets    = new Object(null);

    /**
     * Gets the socket (if available) for the specified target.
     *
     * @param {String} Target
     *
     * @return {Object}
     */
    function getSocket (target, callback) {
        if (target === null || target === '') {
            callback(null, self.io.sockets);
        } else {
            try {
                callback(null, self.sockets[target].socket);
            } catch (err) {
                Util.stdout(err);
            }
        }
    };

    /**
     * Subscription "message" event handler.
     *
     * @param {String} Channel
     * @param {String} Notice (JSON String)
     *
     * @return {void}
     */
    self.listener   = function (channel, data) {
        async.auto({
            decode:      function (callback) {
                Util.parse(data, callback);
            },

            socket:     ['decode', function (callback, obj) {
                getSocket(obj.decode.target, callback);
            }],

            emit:       ['socket', function (callback, obj) {
                emit(obj.socket, obj.decode);
            }]
        }, Util.stdout);
    };

    /**
     * Socket.io "connection" event handler.
     *
     * @param {Object} Socket
     *
     * @return {void}
     */
    self.connection = function (socket) {

        /**
         * Registers a socket to begin recieving notifications.
         *
         * @param {String} Unique user id
         *
         * @return {void}
         */
        socket.on('register', function (id) {
            // Check if exists
            if (typeof self.sockets[id] === 'undefined') {
                self.sockets[id] = {
                    id:         socket.id,
                    socket:     socket
                };
            } else {
                self.sockets[id].id     = socket.id;
                self.sockets[id].socket = socket;
            }

            // Emit from storage
            self.store.all(id, function (err, obj) {
                if (err) {
                    callback(err);
                } else {
                    async.forEach(obj, function (a, callback) {
                        emit(socket, a);
                        callback();
                    }, Util.stdout);
                }
            });
        });

        /**
         * Dismisses a persistent notification.
         *
         * @param {Object} Identity
         *                      - id {String, Required}
         *                      - uid {String, Required}
         *
         * @return {void}
         */
        socket.on('dismiss', function (data) {
            self.store.del(data.uid, data.id, Util.stdout);
        });

        /**
         * Submits a new event via the loopback interface.
         *
         * @param {Object} Notification object (see "register" method).
         *
         * @return {void}
         */
        socket.on('loopback', function (data) {
            self.submit(data, Util.stdout);
        });
    };
};

/**
 * Start listening for connections on the specified port.
 *
 * @param {Number} Port
 *
 * @return {Error}
 */
Randy.prototype.listen = function (port, arg, callback) {
    var self = this;

    // Detect argument list
    if (_.isUndefined(callback)) {
        callback    = arg;
        arg         = {
            port:       null,
            host:       null,
            pass:       null,
            options:    null
        };
    };

    // Normalize "null" types
    for (var item in arg) {
        arg[item] = (arg[item] === 'null') ? null : arg[item];
        arg[item] = (item === 'port') ? Number(arg[item]) : arg[item];
    }

    async.auto({
        connect:        function (callback) {
            var a = [];
            for (var i = 0; i < 3; i++) {
                a[i] = redis.createClient(arg.port, arg.host, arg.options);
            }
            callback(null, a);
        },

        authenticate:   ['connect', function (callback, obj) {
            if (arg.pass !== null) {
                async.forEach(obj.connect, function (obj, callback) {
                    obj.auth(arg.pass, callback);
                }, callback);
            } else {
                callback(null);
            }
        }],

        assign:         ['authenticate', function (callback, obj) {
            self.store  = new Storage(obj.connect[0]);
            self.pub    = obj.connect[1];
            self.sub    = obj.connect[2];
            callback(null);
        }],

        pubsub:         ['assign', function (callback) {
            self.sub.subscribe(self.ns);
            self.sub.on('message', self.listener);
            callback(null);
        }],

        sockets:        ['assign', function (callback) {
            self.io     = sio.listen(Number(port));
            self.io.set('log level', 1);
            self.io.sockets.on('connection', self.connection);
            callback(null);
        }]
    }, callback);
};

/**
 * Submits a new notification.
 *
 * @param {Object} Notification
 *                  - persist {Boolean, Default=false}
 *                  - target {String, Default=null}
 *                  - message {String, Required}
 *
 * @return {Error}
 */
Randy.prototype.submit = function (notice, callback) {
    var self = this;

    _.defaults(notice, {
        id:         uuid.v4(),                  // Assign uuid
        stamp:      new Date().toJSON(),        // Timestamp
        persist:    false,
        target:     null,
        message:    null
    });

    // Normalize typing
    notice.persist  = (notice.persist.toLowerCase() === 'true' || notice.persist === true) ? true : false;
    notice.target   = (notice.target === '') ? null : notice.target;

    // Persist
    if (notice.persist && notice.target !== null) {
        self.store.set(notice.target, notice.id, notice, Util.stdout);
    }

    // If no message is specified, drop the request
    if (notice.message === null || notice.message === '') {
        return callback('No message was specified.');
    }

    // Hash notice and publish to redis store
    async.auto({
        encode:     function (callback) {
            Util.stringify(notice, callback);
        },

        publish:    ['encode', function (callback, obj) {
            self.pub.publish(self.ns, obj.encode);
            callback(null);
        }]
    }, callback);
};

/**
 * Destroy the socket.io connection and redis subscription(s).
 *
 * @return {Error}
 */
Randy.prototype.destroy = function (callback) {
    var self = this;

    try {
        self.sub.unsubscribe();
        self.pub.end();
        self.sub.end();
        callback(null);
    } catch (err) {
        Util.stdout(err);
    }
};

// --------------------------------
// --------------------------------

/**
 * Export
 */
module.exports = new Randy();
<|endoftext|>


<commit_before>module.exports = {
  'middleware': require('./middleware'),
  'routes': require('./routes'),
  'run': require('./run'),
  'utils': require('./utils'),
  'server': require('./server'),
  'init': require('./init')
};
<commit_msg>Added version to lib wrap.<commit_after>module.exports = {
  'middleware': require('./middleware'),
  'routes': require('./routes'),
  'run': require('./run'),
  'utils': require('./utils'),
  'server': require('./server'),
  'init': require('./init'),
  'version': require('./version')
};
<|endoftext|>


<commit_before>require('odata-server');

var endPoints = [];
exports.addServiceEndPoint = function(name, url) {
    console.log(name);
};

exports.createResoServer = function(config) {

    var http    = require('http');
    var https   = require('https');
    var express = require('express');
    var app     = express();

    app.use(express.compress());
    app.use(express.json());
    app.use(express.urlencoded());

    var svc = null;

    // set up the services
    for (var i = 0; i < config.services.length; i++) {
        svc = config.services[i];
        console.log(svc.path);
        app.use(svc.path, $data.ODataServer(svc));
    }

    if (config.port !== undefined){
        var httpServer = http.createServer(app);
        httpServer.listen(config.port);
        console.log('http listening on ' + config.port);
    }

    if (config.sslPort !== undefined) {
        var httpsServer = https.createServer(config.credentials, app);
        httpsServer.listen(config.sslPort);
        console.log('https listening on ' + config.sslPort);
    }

};
<commit_msg>DataSevices are going to be handled in the model definition<commit_after>require('odata-server');

exports.createResoServer = function(config) {

    var http    = require('http');
    var https   = require('https');
    var express = require('express');
    var app     = express();

    app.use(express.compress());
    app.use(express.json());
    app.use(express.urlencoded());

    var svc = null;

    // set up the services
    for (var i = 0; i < config.services.length; i++) {
        svc = config.services[i];
        console.log(svc.path);
        app.use(svc.path, $data.ODataServer(svc));
    }

    if (config.port !== undefined){
        var httpServer = http.createServer(app);
        httpServer.listen(config.port);
        console.log('http listening on ' + config.port);
    }

    if (config.sslPort !== undefined) {
        var httpsServer = https.createServer(config.credentials, app);
        httpsServer.listen(config.sslPort);
        console.log('https listening on ' + config.sslPort);
    }

};
<|endoftext|>


<commit_before>var PassThrough = require('stream').PassThrough;
var Transform = require('./transform');
var util = require('util');

var PAYLOAD_SIZE = 1024 * 16;

function getDecoder(stream, callback) {
  if (!stream || stream._hasGotDecoder || typeof stream.onDecode !== 'function') {
    return callback();
  }
  stream._hasGotDecoder = true;
  stream.onDecode(callback);
}

function getEncoder(stream, callback) {
  if (!stream || stream._hasGotEncoder || typeof stream.onEncode !== 'function') {
    return callback();
  }
  stream._hasGotEncoder = true;
  stream.onEncode(callback);
}

function pipeError(src, target) {
  src && src.on('error', function(err) {
    target.emit('error', err);
  });
}

function PipeStream(options) {
  if (!(this instanceof PipeStream)) {
    return new PipeStream(options);
  }

  init(this);
  this._pipeError = (options && options.pipeError) !== false;
  this._options = util._extend({objectMode: true}, options);
  PassThrough.call(this, this._options);
}

util.inherits(PipeStream, PassThrough);

var proto = PipeStream.prototype;
var originPipe = proto.pipe;

proto.src = function(src, pipeOpts) {
  var self = this;
  var stream = self._originalStream;
  stream && stream.emit('src', src);
  getDecoder(stream, function(decoder) {
    pipeError(decoder, src);
    getEncoder(stream, function(encoder) {
      pipeError(encoder, src);
      if (decoder) {
        src = src.pipe(decoder, decoder.pipeOpts);
      }
      var dest = self._dest;
      if (encoder) {
        encoder.pipe(dest, dest.pipeOpts);
        dest = encoder;
      }
      src.pipe(self, pipeOpts).pipe(dest, dest.pipeOpts);
    });
  });
  return this;
};

proto.pipe = function(dest, pipeOpts) {
  var self = this;
  var stream = self._originalStream;
  var emitDestError = function(err) {
    dest.emit('error', err);
  };
  stream && stream.emit('dest', dest);
  var pipes = self._heads.concat(self._pipes, self._tails);
  init(self);
  getEncoder(stream, function(encoder) {
    var passThrough = new PassThrough(this._options);
    originPipe.call(self, passThrough);
    pipes.unshift(passThrough);
    dest.pipeOpts = pipeOpts;
    if (encoder) {
      encoder.on('error', emitDestError);
      encoder._noPipeError = false;
      pipes.push(encoder);
    }
    pipes.push(dest);
    pipeErrorToDest(self, true);
  });
  function pipeErrorToDest(src, pipeError) {
    var needPipeError = self._pipeError && !src._noPipeError && src != dest
      && (pipeError || (src.pipeOpts && src.pipeOpts.pipeError)) !== false;
    return needPipeError ? src.on('error', emitDestError) : src;
  }

  self._pipeStream(pipes, 1, function(dest) {
    self.emit('_pipeEnd', dest);
  }, pipeErrorToDest);

  return dest;
};

proto._pipeStream = function pipeStream(pipes, i, callback, pipeErrorToDest) {
  var self = this;
  var pipe = pipes[i];
  var src = pipes[i - 1];
  if (typeof pipe == 'function') {
    pipe(src, function(dest) {
      pipes[i] = pipeErrorToDest(dest);
      next();
    });
  } else if (src instanceof PipeStream) {
    src.once('_pipeEnd', next);
    src.pipe(pipeErrorToDest(pipe), pipe.pipeOpts);
  } else {
    src.pipe(pipeErrorToDest(pipe), pipe.pipeOpts);
    next();
  }

  function next() {
    if (i + 1 == pipes.length) {
      callback(pipe);
    } else {
      self._pipeStream(pipes, ++i, callback, pipeErrorToDest);
    }
  }
};

proto.add = function(pipe, pipeOpts) {
  pipe.pipeOpts = pipeOpts;
  this._pipes.push(pipe);
  return this;
};

proto.insert = function(pipe, pipeOpts, index) {
  if (typeof pipeOpts == 'number') {
    var tmp = pipeOpts;
    pipeOpts = index;
    index = tmp;
  }
  pipe.pipeOpts = pipeOpts;
  typeof index == 'number' ? this._pipes.splice(index, 0, pipe) : this._pipes.push(pipe);
  return this;
};

proto.addHead = function(pipe, pipeOpts) {
  pipe.pipeOpts = pipeOpts;
  this._heads.push(pipe);
  return this;
};

proto.prepend = function(pipe, pipeOpts) {
  pipe.pipeOpts = pipeOpts;
  this._heads.unshift(pipe);
  return this;
};

proto.addTail = function(pipe, pipeOpts) {
  pipe.pipeOpts = pipeOpts;
  this._tails.unshift(pipe);
  return this;
};

proto.append = function(pipe, pipeOpts) {
  pipe.pipeOpts = pipeOpts;
  this._tails.push(pipe);
  return this;
};

proto.dest = function(dest, pipeOpts) {
  dest.pipeOpts = pipeOpts;
  this._dest = dest;
  return dest;
};

function init(pipeStream) {
  pipeStream._heads = [];
  pipeStream._pipes = [];
  pipeStream._tails = [];
}

PipeStream.Transform = Transform;
PipeStream.wrap = function(stream, dest, options) {
  return new PipeStream(options).wrapStream(stream, dest, options);
};

PipeStream.wrapSrc = function(stream, options) {

  return PipeStream.wrap(stream, false, options);
};

PipeStream.wrapDest = function(stream, options) {

  return PipeStream.wrap(stream, true, options);
};

var keys = Object.keys(proto);
var getPayloadSize = function(opts) {
  var payloadSize = opts && opts.getPayloadSize;
  return payloadSize > 0 ? payloadSize : PAYLOAD_SIZE;
};

proto.wrapStream = function(stream, dest, pipeOpts) {
  if (typeof pipeOpts == 'boolean' && typeof dest != 'boolean') {
    var tmp = pipeOpts;
    pipeOpts = dest;
    dest = tmp;
  }

  this._originalStream = stream;
  if (dest) {
    this.dest(stream, pipeOpts);
  } else {
    var self = this;
    var pipe = stream.pipe;
    var payloadSize = getPayloadSize(pipeOpts);
    var callbacks = [];
    var payload, done, err, decodeStream;
    var end = function(e) {
      done = true;
      err = e;
      stream.pause();
      decodeStream.removeListener('data', handleData);
      decodeStream.removeListener('error', end);
      decodeStream.removeListener('end', end);
      callbacks.forEach(function(cb) {
        cb(err, payload);
      });
      callbacks = [];
    };
    var handleData = function(data) {
      payload = payload ? Buffer.concat([payload, data]) : data;
      if (payload.length >= payloadSize) {
        end();
      }
    };
    var getReqDecoder = function(stream, callback) {
      if (decodeStream) {
        return callback(decodeStream);
      }
      getDecoder(stream, function(decoder) {
        decodeStream = decoder || stream;
        if (decoder) {
          pipeError(decoder, stream);
          pipe.call(stream, decoder, decoder.pipeOpts);
          pipe = decoder.pipe;
        }
        callback(decodeStream);
      });
    };
    stream.getPayload = function(cb, size) {
      if (done) {
        return cb(err, payload);
      }
      if (size > payloadSize) {
        payloadSize = size;
      }
      if (!callbacks.length) {
        getReqDecoder(stream, function() {
          decodeStream.on('data', handleData);
          decodeStream.on('error', end);
          decodeStream.on('end', end);
        });
      }
      callbacks.push(cb);
    };
    stream.on('dest', function() {
      getReqDecoder(stream, function() {
        end();
        payload && self.write(payload);
        pipe.call(decodeStream, self, pipeOpts);
        stream.resume();
      });
    });
  }

  for (var i = 0, key; key = keys[i]; i++) {
    if (dest ? i != 'pipe' : i != 'src') {
      stream[key] = this[key].bind(this);
    }
  }

  return stream;
};

module.exports = PipeStream;
<commit_msg>fix: pipe stream<commit_after>var PassThrough = require('stream').PassThrough;
var Transform = require('./transform');
var util = require('util');

var PAYLOAD_SIZE = 1024 * 16;

function getDecoder(stream, callback) {
  if (!stream || stream._hasGotDecoder || typeof stream.onDecode !== 'function') {
    return callback();
  }
  stream._hasGotDecoder = true;
  stream.onDecode(callback);
}

function getEncoder(stream, callback) {
  if (!stream || stream._hasGotEncoder || typeof stream.onEncode !== 'function') {
    return callback();
  }
  stream._hasGotEncoder = true;
  stream.onEncode(callback);
}

function pipeError(src, target) {
  src && src.on('error', function(err) {
    target.emit('error', err);
  });
}

function PipeStream(options) {
  if (!(this instanceof PipeStream)) {
    return new PipeStream(options);
  }

  init(this);
  this._pipeError = (options && options.pipeError) !== false;
  this._options = util._extend({objectMode: true}, options);
  PassThrough.call(this, this._options);
}

util.inherits(PipeStream, PassThrough);

var proto = PipeStream.prototype;
var originPipe = proto.pipe;

proto.src = function(src, pipeOpts) {
  var self = this;
  var stream = self._originalStream;
  stream && stream.emit('src', src);
  getDecoder(stream, function(decoder) {
    pipeError(decoder, src);
    getEncoder(stream, function(encoder) {
      pipeError(encoder, src);
      if (decoder) {
        src = src.pipe(decoder, decoder.pipeOpts);
      }
      var dest = self._dest;
      if (encoder) {
        encoder.pipe(dest, dest.pipeOpts);
        dest = encoder;
      }
      src.pipe(self, pipeOpts).pipe(dest, dest.pipeOpts);
    });
  });
  return this;
};

proto.pipe = function(dest, pipeOpts) {
  var self = this;
  var stream = self._originalStream;
  var emitDestError = function(err) {
    dest.emit('error', err);
  };
  stream && stream.emit('dest', dest);
  var pipes = self._heads.concat(self._pipes, self._tails);
  init(self);
  getEncoder(stream, function(encoder) {
    var passThrough = new PassThrough(this._options);
    originPipe.call(self, passThrough);
    pipes.unshift(passThrough);
    dest.pipeOpts = pipeOpts;
    if (encoder) {
      encoder.on('error', emitDestError);
      encoder._noPipeError = false;
      pipes.push(encoder);
    }
    pipes.push(dest);
    var pipeErrorToDest = function(src, pipeError) {
      var needPipeError = self._pipeError && !src._noPipeError && src != dest
        && (pipeError || (src.pipeOpts && src.pipeOpts.pipeError)) !== false;
      return needPipeError ? src.on('error', emitDestError) : src;
    };
    pipeErrorToDest(self, true);
    self._pipeStream(pipes, 1, function(dest) {
      self.emit('_pipeEnd', dest);
    }, pipeErrorToDest);
  });
  return dest;
};

proto._pipeStream = function pipeStream(pipes, i, callback, pipeErrorToDest) {
  var self = this;
  var pipe = pipes[i];
  var src = pipes[i - 1];
  if (typeof pipe == 'function') {
    pipe(src, function(dest) {
      pipes[i] = pipeErrorToDest(dest);
      next();
    });
  } else if (src instanceof PipeStream) {
    src.once('_pipeEnd', next);
    src.pipe(pipeErrorToDest(pipe), pipe.pipeOpts);
  } else {
    src.pipe(pipeErrorToDest(pipe), pipe.pipeOpts);
    next();
  }

  function next() {
    if (i + 1 == pipes.length) {
      callback(pipe);
    } else {
      self._pipeStream(pipes, ++i, callback, pipeErrorToDest);
    }
  }
};

proto.add = function(pipe, pipeOpts) {
  pipe.pipeOpts = pipeOpts;
  this._pipes.push(pipe);
  return this;
};

proto.insert = function(pipe, pipeOpts, index) {
  if (typeof pipeOpts == 'number') {
    var tmp = pipeOpts;
    pipeOpts = index;
    index = tmp;
  }
  pipe.pipeOpts = pipeOpts;
  typeof index == 'number' ? this._pipes.splice(index, 0, pipe) : this._pipes.push(pipe);
  return this;
};

proto.addHead = function(pipe, pipeOpts) {
  pipe.pipeOpts = pipeOpts;
  this._heads.push(pipe);
  return this;
};

proto.prepend = function(pipe, pipeOpts) {
  pipe.pipeOpts = pipeOpts;
  this._heads.unshift(pipe);
  return this;
};

proto.addTail = function(pipe, pipeOpts) {
  pipe.pipeOpts = pipeOpts;
  this._tails.unshift(pipe);
  return this;
};

proto.append = function(pipe, pipeOpts) {
  pipe.pipeOpts = pipeOpts;
  this._tails.push(pipe);
  return this;
};

proto.dest = function(dest, pipeOpts) {
  dest.pipeOpts = pipeOpts;
  this._dest = dest;
  return dest;
};

function init(pipeStream) {
  pipeStream._heads = [];
  pipeStream._pipes = [];
  pipeStream._tails = [];
}

PipeStream.Transform = Transform;
PipeStream.wrap = function(stream, dest, options) {
  return new PipeStream(options).wrapStream(stream, dest, options);
};

PipeStream.wrapSrc = function(stream, options) {

  return PipeStream.wrap(stream, false, options);
};

PipeStream.wrapDest = function(stream, options) {

  return PipeStream.wrap(stream, true, options);
};

var keys = Object.keys(proto);
var getPayloadSize = function(opts) {
  var payloadSize = opts && opts.getPayloadSize;
  return payloadSize > 0 ? payloadSize : PAYLOAD_SIZE;
};

proto.wrapStream = function(stream, dest, pipeOpts) {
  if (typeof pipeOpts == 'boolean' && typeof dest != 'boolean') {
    var tmp = pipeOpts;
    pipeOpts = dest;
    dest = tmp;
  }

  this._originalStream = stream;
  if (dest) {
    this.dest(stream, pipeOpts);
  } else {
    var self = this;
    var pipe = stream.pipe;
    var payloadSize = getPayloadSize(pipeOpts);
    var callbacks = [];
    var payload, done, err, decodeStream;
    var end = function(e) {
      done = true;
      err = e;
      stream.pause();
      decodeStream.removeListener('data', handleData);
      decodeStream.removeListener('error', end);
      decodeStream.removeListener('end', end);
      callbacks.forEach(function(cb) {
        cb(err, payload);
      });
      callbacks = [];
    };
    var handleData = function(data) {
      payload = payload ? Buffer.concat([payload, data]) : data;
      if (payload.length >= payloadSize) {
        end();
      }
    };
    var getReqDecoder = function(stream, callback) {
      if (decodeStream) {
        return callback(decodeStream);
      }
      getDecoder(stream, function(decoder) {
        decodeStream = decoder || stream;
        if (decoder) {
          pipeError(decoder, stream);
          pipe.call(stream, decoder, decoder.pipeOpts);
          pipe = decoder.pipe;
        }
        callback(decodeStream);
      });
    };
    stream.getPayload = function(cb, size) {
      if (done) {
        return cb(err, payload);
      }
      if (size > payloadSize) {
        payloadSize = size;
      }
      if (!callbacks.length) {
        getReqDecoder(stream, function() {
          decodeStream.on('data', handleData);
          decodeStream.on('error', end);
          decodeStream.on('end', end);
        });
      }
      callbacks.push(cb);
    };
    stream.on('dest', function() {
      getReqDecoder(stream, function() {
        end();
        payload && self.write(payload);
        pipe.call(decodeStream, self, pipeOpts);
        stream.resume();
      });
    });
  }

  for (var i = 0, key; key = keys[i]; i++) {
    if (dest ? i != 'pipe' : i != 'src') {
      stream[key] = this[key].bind(this);
    }
  }

  return stream;
};

module.exports = PipeStream;
<|endoftext|>


<commit_before>const Joi = require('joi');

const ValidationError = require('./validation-error');
const { joiSchema } = require('./joi');
const { mergeEvOptions, evSchema } = require('./ev');
const { parameters } = require('./parameters');
const { handleMutation } = require('./mutation');
const { clean, keyByField } = require('./reducers');

exports.validate = (schema = {}, options = {}, joi = {}) => {
  Joi.assert(options, evSchema);
  Joi.assert(schema, joiSchema);

  const evOptions = mergeEvOptions(options);
  // We can avoid making a new object for each incoming request when options.context is false:
  const baseJoiOptions = { ...joi, warnings: true };

  async function validate(request, parameter, joiOptions) {
    let result;
    try {
      result = await schema[parameter].validateAsync(request[parameter], joiOptions);
    } catch (error) {
      return { [parameter]: error.details };
    }
    handleMutation(request, parameter, result.value, evOptions.context);
    return undefined;
  }

  const hasErrors = (errors) => (errors ? new ValidationError(errors, evOptions) : null);

  return async (request, response, next) => {
    try {
      const joiOptions = options.context ? { ...baseJoiOptions, context: request } : baseJoiOptions;

      const promises = parameters
        .filter(parameter => request[parameter] && schema[parameter])
        .map(parameter => validate(request, parameter, joiOptions));

      let e = await Promise.all(promises);
      e = clean(e);
      const r = keyByField(e, options.keyByField);

      next(hasErrors(r));
    } catch (err) {
      // Make sure that we don't cause an unhandled rejection if there's an error in the code:
      next(err);
    }
  };
};

exports.ValidationError = ValidationError;
exports.Joi = Joi;
<commit_msg>Tidy up some more<commit_after>const Joi = require('joi');

const ValidationError = require('./validation-error');
const { joiSchema } = require('./joi');
const { mergeEvOptions, evSchema } = require('./ev');
const { parameters } = require('./parameters');
const { handleMutation } = require('./mutation');
const { clean, keyByField } = require('./reducers');

exports.validate = (schema = {}, options = {}, joi = {}) => {
  Joi.assert(options, evSchema);
  Joi.assert(schema, joiSchema);

  const evOptions = mergeEvOptions(options);
  // We can avoid making a new object for each incoming request when options.context is false:
  const baseJoiOptions = { ...joi, warnings: true };

  async function validate(request, parameter, joiOptions) {
    let result;
    try {
      result = await schema[parameter].validateAsync(request[parameter], joiOptions);
    } catch (error) {
      return { [parameter]: error.details };
    }
    handleMutation(request, parameter, result.value, evOptions.context);
    return undefined;
  }

  return async (request, response, next) => {
    try {
      const joiOptions = options.context ? { ...baseJoiOptions, context: request } : baseJoiOptions;

      const promises = parameters
        .filter(parameter => request[parameter] && schema[parameter])
        .map(parameter => validate(request, parameter, joiOptions));

      const errors = keyByField(clean(await Promise.all(promises)), options.keyByField);

      if (errors) {
        next(new ValidationError(errors, evOptions));
      } else {
        next();
      }
    } catch (err) {
      // Make sure that we don't cause an unhandled rejection if there's an error in the code:
      next(err);
    }
  };
};

exports.ValidationError = ValidationError;
exports.Joi = Joi;
<|endoftext|>


<commit_before>var mongoose = require('mongoose'),
    _ = require('underscore'),
    async = require('async');

var options = {
  depth: 2
};

var findFP = function (query, opts, cb) {
  if(opts.depth === 0) return cb(null, []);
  if(_.isUndefined(this.schema.filterFields)) return cb('Model ' + that.modelName + ' is missing a filter');

  // //  Check for passed in include/exlude fi
  // if(!_.isUndefined(opts.includeFields)) {
  //   opts.depth = _getFilterDepth(opts.includeFields);
  // }

  // //  Check for passed in include/exlude fi
  // if(!_.isUndefined(opts.excludeFields)) {
  //   opts.depth = _getFilterDepth(opts.excludeFields);
  // }

  var opts = _.clone(_.defaults(opts, options));

  opts.schemaFilter = this.schema.filterFields
  opts.schemaFields = this.schema.paths;

  var modelRefFields = _getModelReferences(this);
  // Find the fields that need to be populated
  opts.populateFields = _.filter(modelRefFields, function(item){ return item.field !== '_id'; });
  this.find(query, null, opts.paging).lean().exec(function(err, results) {
    if(results == null || results.length === 0) return cb(null, null);

    //  Our recursion check point
    if(opts.depth > 1) {
      _queryChildren(results, _.clone(opts), function(err, results){
        // If we're back up to the root call do final root filter
        if(_.isUndefined(opts.isChild) && !_.isUndefined(opts.hasFiltering)) return cb(err, _rootFilter(results, opts));

        cb(err, _filterResults(results, opts.schemaFilter));
      });
    } else {
      // If we're back up to the root call do final root filter
      if(_.isUndefined(opts.isChild) && !_.isUndefined(opts.hasFiltering)) return cb(err, _rootFilter(results, opts));

      cb(err, _filterResults(results, opts.schemaFilter));
    }
  });
};

var findOneFP = function (query, opts, cb) {
  this.findFP(query, opts, function(err, results){
    if(results == null) return cb(err, null)
    cb(err, results[0]);
  });
};

var findByIdAndUpdateFP = function (id, body, opts, cb) {

  var model = this;

  model.findByIdAndUpdate(id, body, function(err, result){
    if (err) return callback (err, null);
    if (result === null) return callback (null, null);
    //  Filter and Populate
    model.findFP({ _id: result.id }, opts, function(err, results){
      if(results == null) return cb(err, null)
      cb(err, results[0]);
    });
  });
};

var saveFP = function(opts, callback) {

  var model = this;

  model.save (function (err, instance) {
    if (err) return callback (err, null);
    mongoose.model(model.constructor.modelName).findFP({ _id : instance._id}, opts, function(err, results){
      return callback (null, results[0]);
    });
  });
};

var _queryChildren = function(results, opts, callback) {

  async.map(results, function(result, callback){

    _queryChild(result, opts, callback);

  }, function(err, results){
    callback(err, results);
  });
};

var _queryChild = function(result, opts, callback) {

  async.each(opts.populateFields, function(field, callback){
    if(_.isUndefined(mongoose.model(field.model).schema.filterFields)) return callback('Model ' + field.model + ' is missing a filter');

    var childFields = mongoose.model(field.model).schema.filterFields;

    var options = {
      depth: opts.depth - 1,
      populateFields: childFields
    };

    options.isChild = true;

    var query = { _id : result[field.field] }
    if(_.isArray(result[field.field])) {
      query = { _id : { $in : result[field.field]} }
    }

    mongoose.model(field.model).findFP(query, _.clone(options), function(err, instances){
      if(err) return callback(err);
      if(instances === null) return callback(null);

      if (_.isArray(result[field.field])) {
        instances = _.map(result[field.field], function(item) {
          return _.find(instances, function(instance) {
            if(!instance || !instance.id) return false;
            return instance.id.toString() === item.toString();
          }) || {};
        });
      }

      result[field.field] = _.map(instances, function(instance){ return _.pick(instance, childFields); });

      // If it is not an array, return single instance
      if(!_isModelRefArray(opts.schemaFields[field.field])) result[field.field] = result[field.field][0];

      callback(null);
    });
  }, function(err){

    callback(err, result)

  });
};

var _rootFilter = function(results, opts) {

  if(opts.excludeFields) {
    return _.map(results, function(result) {
      var schemaFilter = opts.schemaFilter;
      return _.pick(stepThroughFilterExclude([result], opts.excludeFields)[0], schemaFilter);
    });
  } else {
    return _.map(results, function(result) {
      return stepThroughFilter([result], opts.includeFields)[0];
    });
  }
}

var stepThroughFilter = function(results, currentFields) {

  return _.map(results, function(result){

    if(result.id == null)
      result.id = result._id;

    // Check for wildcard, if so return all
    if(_.contains(currentFields, '*')) {
      return result;
    } else {
      var filterFields = _getCurrentFields(currentFields);
    }

    _.each(filterFields, function(field){
      var childFields = _getChildFields(currentFields, field);
      if(childFields.length > 0 && !_.isUndefined(result[field])) {
        if(_.isArray(result[field]))
          result[field] = stepThroughFilter(result[field], childFields);
        else
          result[field] = stepThroughFilter([result[field]], childFields)[0];
      } else {

        //  Field filter doesn't define children, so if is a Obj Ref field, just return the ids
        if(_.isArray(result[field]) && _.isObject(result[field][0]) && field !== 'id') {
          result[field] = _.map(result[field], function(field){
            return field.id;
          });
        } else if (_.isObject(result[field]) && !_.isArray(result[field]) && !_.isDate(result[field])  && field !== 'id' && !/^[0-9a-fA-F]{24}$/.test(result[field].toString()) ) {
          result[field] = result[field].id;
        }
      }
    });
    return _.pick(result, filterFields);
  });
};

var stepThroughFilterExclude = function(results, currentFields) {

  return _.map(results, function(result){

    if(result.id == null)
      result.id = result._id;

    var filterFields = _getCurrentFields(currentFields);

    _.each(filterFields, function(field){

      var childFields = _getChildFields(currentFields, field);

      if(childFields.length > 0 && !_.isUndefined(result[field])) {
        if(_.isArray(result[field]))
          result[field] = stepThroughFilterExclude(result[field], childFields);
        else
          result[field] = stepThroughFilterExclude([result[field]], childFields)[0];
      }
    });

    //  Check if it is an unpopluated field, resulting from relationship to entity no longer existing
    if(/^[0-9a-fA-F]{24}$/.test(result.toString())) return {};
    return _.omit(result, _getCurrentFieldsExclude(currentFields));
  });
};

var _filterResults = function(results, filterFields) {

  return _.map(results, function(result){
    if(result.id == null)
      result.id = result._id;

    return _.pick(result, filterFields);
  });
};

var _filterResult = function(result, filterFields) {
  if(result.id == null)
    result.id = result._id;
  return _.pick(result, filterFields);
};

var _getCurrentFields = function(dotNotionFields) {
  return _.uniq(_.compact(_.map(dotNotionFields, function(field){
    var field = field.split('.');
    return field[0];
  })));
};

var _getCurrentFieldsExclude = function(dotNotionFields) {

  return _.uniq(_.compact(_.filter(dotNotionFields, function(field){
    return field.indexOf('.') === -1
  })));
};

var _getChildFields = function(dotNotionFields, parentField) {
  return _.compact(_.map(dotNotionFields, function(field){
    var fields = field.split('.');
    if(fields[0] === parentField) {
      fields.shift();
      return fields.join('.');
    } else {
      return null;
    }
  }));
};

//  Check if the model ref an array
var _isModelRefArray = function(schemaField) {
  return _.isObject(schemaField.caster);
};

var _getModelReferences = function (model) {

  var fields = model.schema.paths;

  return _.flatten(_.compact(_.map(_.pairs(fields), function(field) {
    //  If it's an array, get actual field attrs
    if(_isModelRefArray(field[1])) field = [field[0], field[1].caster];
    //  We don't want type mixed fields, or non Model Refs or _id
    if(_.isUndefined(field[1].instance) || field[1].instance !== 'ObjectID' || field[0] === '_id') return null;

    //  Check for special multiple model ref
    if(field[1].options.refs) {
      return _.map(field[1].options.refs, function(ref){
        return { field: field[0], model: ref }
      });
    }

    return { field: field[0], model: field[1].options.ref };
  })));
};

var _getFilterDepth = function(filterFields) {
  if(filterFields.length === 0) return 0;

  //  This is a hack, need to look at nicer way
  return 10;

  return _.max(filterFields, function(field){
    return field.split('.').length;
  }).split('.').length;
};

module.exports = exports = function mongooseExpandPlugin(schema, options) {

  schema.statics.findFP = findFP;
  schema.statics.findOneFP = findOneFP;
  schema.statics.findByIdAndUpdateFP = findByIdAndUpdateFP;
  schema.methods.saveFP = saveFP;

};
<commit_msg>Error check<commit_after>var mongoose = require('mongoose'),
    _ = require('underscore'),
    async = require('async');

var options = {
  depth: 2
};

var findFP = function (query, opts, cb) {
  if(opts.depth === 0) return cb(null, []);
  if(_.isUndefined(this.schema.filterFields)) return cb('Model ' + that.modelName + ' is missing a filter');

  // //  Check for passed in include/exlude fi
  // if(!_.isUndefined(opts.includeFields)) {
  //   opts.depth = _getFilterDepth(opts.includeFields);
  // }

  // //  Check for passed in include/exlude fi
  // if(!_.isUndefined(opts.excludeFields)) {
  //   opts.depth = _getFilterDepth(opts.excludeFields);
  // }

  var opts = _.clone(_.defaults(opts, options));

  opts.schemaFilter = this.schema.filterFields
  opts.schemaFields = this.schema.paths;

  var modelRefFields = _getModelReferences(this);
  // Find the fields that need to be populated
  opts.populateFields = _.filter(modelRefFields, function(item){ return item.field !== '_id'; });
  this.find(query, null, opts.paging).lean().exec(function(err, results) {
    if(results == null || results.length === 0) return cb(null, null);

    //  Our recursion check point
    if(opts.depth > 1) {
      _queryChildren(results, _.clone(opts), function(err, results){
        // If we're back up to the root call do final root filter
        if(_.isUndefined(opts.isChild) && !_.isUndefined(opts.hasFiltering)) return cb(err, _rootFilter(results, opts));

        cb(err, _filterResults(results, opts.schemaFilter));
      });
    } else {
      // If we're back up to the root call do final root filter
      if(_.isUndefined(opts.isChild) && !_.isUndefined(opts.hasFiltering)) return cb(err, _rootFilter(results, opts));

      cb(err, _filterResults(results, opts.schemaFilter));
    }
  });
};

var findOneFP = function (query, opts, cb) {
  this.findFP(query, opts, function(err, results){
    if(results == null) return cb(err, null)
    cb(err, results[0]);
  });
};

var findByIdAndUpdateFP = function (id, body, opts, cb) {

  var model = this;

  model.findByIdAndUpdate(id, body, function(err, result){
    if (err) return callback (err, null);
    if (result === null) return callback (null, null);
    //  Filter and Populate
    model.findFP({ _id: result.id }, opts, function(err, results){
      if(results == null) return cb(err, null)
      cb(err, results[0]);
    });
  });
};

var saveFP = function(opts, callback) {

  var model = this;

  model.save (function (err, instance) {
    if (err) return callback (err, null);
    mongoose.model(model.constructor.modelName).findFP({ _id : instance._id}, opts, function(err, results){
      if(err) return callback(err);
      return callback (null, results[0]);
    });
  });
};

var _queryChildren = function(results, opts, callback) {

  async.map(results, function(result, callback){

    _queryChild(result, opts, callback);

  }, function(err, results){
    callback(err, results);
  });
};

var _queryChild = function(result, opts, callback) {

  async.each(opts.populateFields, function(field, callback){
    if(_.isUndefined(mongoose.model(field.model).schema.filterFields)) return callback('Model ' + field.model + ' is missing a filter');

    var childFields = mongoose.model(field.model).schema.filterFields;

    var options = {
      depth: opts.depth - 1,
      populateFields: childFields
    };

    options.isChild = true;

    var query = { _id : result[field.field] }
    if(_.isArray(result[field.field])) {
      query = { _id : { $in : result[field.field]} }
    }

    mongoose.model(field.model).findFP(query, _.clone(options), function(err, instances){
      if(err) return callback(err);
      if(instances === null) return callback(null);

      if (_.isArray(result[field.field])) {
        instances = _.map(result[field.field], function(item) {
          return _.find(instances, function(instance) {
            if(!instance || !instance.id) return false;
            return instance.id.toString() === item.toString();
          }) || {};
        });
      }

      result[field.field] = _.map(instances, function(instance){ return _.pick(instance, childFields); });

      // If it is not an array, return single instance
      if(!_isModelRefArray(opts.schemaFields[field.field])) result[field.field] = result[field.field][0];

      callback(null);
    });
  }, function(err){

    callback(err, result)

  });
};

var _rootFilter = function(results, opts) {

  if(opts.excludeFields) {
    return _.map(results, function(result) {
      var schemaFilter = opts.schemaFilter;
      return _.pick(stepThroughFilterExclude([result], opts.excludeFields)[0], schemaFilter);
    });
  } else {
    return _.map(results, function(result) {
      return stepThroughFilter([result], opts.includeFields)[0];
    });
  }
}

var stepThroughFilter = function(results, currentFields) {

  return _.map(results, function(result){

    if(result.id == null)
      result.id = result._id;

    // Check for wildcard, if so return all
    if(_.contains(currentFields, '*')) {
      return result;
    } else {
      var filterFields = _getCurrentFields(currentFields);
    }

    _.each(filterFields, function(field){
      var childFields = _getChildFields(currentFields, field);
      if(childFields.length > 0 && !_.isUndefined(result[field])) {
        if(_.isArray(result[field]))
          result[field] = stepThroughFilter(result[field], childFields);
        else
          result[field] = stepThroughFilter([result[field]], childFields)[0];
      } else {

        //  Field filter doesn't define children, so if is a Obj Ref field, just return the ids
        if(_.isArray(result[field]) && _.isObject(result[field][0]) && field !== 'id') {
          result[field] = _.map(result[field], function(field){
            return field.id;
          });
        } else if (_.isObject(result[field]) && !_.isArray(result[field]) && !_.isDate(result[field])  && field !== 'id' && !/^[0-9a-fA-F]{24}$/.test(result[field].toString()) ) {
          result[field] = result[field].id;
        }
      }
    });
    return _.pick(result, filterFields);
  });
};

var stepThroughFilterExclude = function(results, currentFields) {

  return _.map(results, function(result){

    if(result.id == null)
      result.id = result._id;

    var filterFields = _getCurrentFields(currentFields);

    _.each(filterFields, function(field){

      var childFields = _getChildFields(currentFields, field);

      if(childFields.length > 0 && !_.isUndefined(result[field])) {
        if(_.isArray(result[field]))
          result[field] = stepThroughFilterExclude(result[field], childFields);
        else
          result[field] = stepThroughFilterExclude([result[field]], childFields)[0];
      }
    });

    //  Check if it is an unpopluated field, resulting from relationship to entity no longer existing
    if(/^[0-9a-fA-F]{24}$/.test(result.toString())) return {};
    return _.omit(result, _getCurrentFieldsExclude(currentFields));
  });
};

var _filterResults = function(results, filterFields) {

  return _.map(results, function(result){
    if(result.id == null)
      result.id = result._id;

    return _.pick(result, filterFields);
  });
};

var _filterResult = function(result, filterFields) {
  if(result.id == null)
    result.id = result._id;
  return _.pick(result, filterFields);
};

var _getCurrentFields = function(dotNotionFields) {
  return _.uniq(_.compact(_.map(dotNotionFields, function(field){
    var field = field.split('.');
    return field[0];
  })));
};

var _getCurrentFieldsExclude = function(dotNotionFields) {

  return _.uniq(_.compact(_.filter(dotNotionFields, function(field){
    return field.indexOf('.') === -1
  })));
};

var _getChildFields = function(dotNotionFields, parentField) {
  return _.compact(_.map(dotNotionFields, function(field){
    var fields = field.split('.');
    if(fields[0] === parentField) {
      fields.shift();
      return fields.join('.');
    } else {
      return null;
    }
  }));
};

//  Check if the model ref an array
var _isModelRefArray = function(schemaField) {
  return _.isObject(schemaField.caster);
};

var _getModelReferences = function (model) {

  var fields = model.schema.paths;

  return _.flatten(_.compact(_.map(_.pairs(fields), function(field) {
    //  If it's an array, get actual field attrs
    if(_isModelRefArray(field[1])) field = [field[0], field[1].caster];
    //  We don't want type mixed fields, or non Model Refs or _id
    if(_.isUndefined(field[1].instance) || field[1].instance !== 'ObjectID' || field[0] === '_id') return null;

    //  Check for special multiple model ref
    if(field[1].options.refs) {
      return _.map(field[1].options.refs, function(ref){
        return { field: field[0], model: ref }
      });
    }

    return { field: field[0], model: field[1].options.ref };
  })));
};

var _getFilterDepth = function(filterFields) {
  if(filterFields.length === 0) return 0;

  //  This is a hack, need to look at nicer way
  return 10;

  return _.max(filterFields, function(field){
    return field.split('.').length;
  }).split('.').length;
};

module.exports = exports = function mongooseExpandPlugin(schema, options) {

  schema.statics.findFP = findFP;
  schema.statics.findOneFP = findOneFP;
  schema.statics.findByIdAndUpdateFP = findByIdAndUpdateFP;
  schema.methods.saveFP = saveFP;

};
<|endoftext|>


<commit_before>var BloggifyLib = module.exports = {};

var _cache = {};

BloggifyLib.clearCache = function (options) {

    if (options && options.root) {
        _cache.APP_ROOT = options.root;
    } else {
        options = {
            root: _cache.APP_ROOT
        };
    }

    // Require config
    var Config = global.Config = Utils.requireNoCache(options.root + "/config");

    // Set log level
    Debug._config.logLevel = Config.logLevel;

    // start parsing paths
    Utils.parsePaths(Config.gitSite.paths, ["parsed"]);

    // Attach core pages
    Config.gitSite.parsed.roots.pages["/login"] = {
        url: "/core/html/login.html"
      , visible: false
      , slug: "login"
    };

    Config.gitSite.parsed.roots.pages["/blog"] = {
        url: "/core/html/blog.html"
      , label: "Blog"
      , order: 19
      , slug: "blog"
    };

    Config.gitSite.parsed.roots.pages["/admin"] = {
        url: "/core/html/admin.html"
      , label: "Admin"
      , order: 21
      , loggedIn: true
      , slug: "admin"
    };

    // statique config
    Statique
        .server({ root: options.root + Config.gitSite.url })
        .setRoutes(Config.gitSite.parsed.roots.pages)
      ;
};

/**
 * start
 *
 * @name start
 * @function
 * @param {Object} options The options object containing the following fields:
 *  - root: the bloggify root directory
 * @return
 */
BloggifyLib.start = function (options) {

    // Clear cache
    BloggifyLib.clearCache(options);

    // Handle uncaught exceptions
    if (Config.logLevel < 4) {
        process.on("uncaughtException", function (err) {
            Debug.log(err, "error");
        });
    }

    // Output
    Debug.log("Started Bloggify platform", "info");
};
<commit_msg>Set error pages<commit_after>var BloggifyLib = module.exports = {};

var _cache = {};

BloggifyLib.clearCache = function (options) {

    if (options && options.root) {
        _cache.APP_ROOT = options.root;
    } else {
        options = {
            root: _cache.APP_ROOT
        };
    }

    // Require config
    var Config = global.Config = Utils.requireNoCache(options.root + "/config");

    // Set log level
    Debug._config.logLevel = Config.logLevel;

    // start parsing paths
    Utils.parsePaths(Config.gitSite.paths, ["parsed"]);

    // Attach core pages
    Config.gitSite.parsed.roots.pages["/login"] = {
        url: "/core/html/login.html"
      , visible: false
      , slug: "login"
    };

    Config.gitSite.parsed.roots.pages["/blog"] = {
        url: "/core/html/blog.html"
      , label: "Blog"
      , order: 19
      , slug: "blog"
    };

    Config.gitSite.parsed.roots.pages["/admin"] = {
        url: "/core/html/admin.html"
      , label: "Admin"
      , order: 21
      , loggedIn: true
      , slug: "admin"
    };

    // Statique config
    Statique
        .server({ root: options.root + Config.gitSite.url })
        .setRoutes(Config.gitSite.parsed.roots.pages)
        .setErrors(Config.errorPages)
      ;
};

/**
 * start
 *
 * @name start
 * @function
 * @param {Object} options The options object containing the following fields:
 *  - root: the bloggify root directory
 * @return
 */
BloggifyLib.start = function (options) {

    // Clear cache
    BloggifyLib.clearCache(options);

    // Handle uncaught exceptions
    if (Config.logLevel < 4) {
        process.on("uncaughtException", function (err) {
            Debug.log(err, "error");
        });
    }

    // Output
    Debug.log("Started Bloggify platform", "info");
};
<|endoftext|>


<commit_before>// Load modules.
var Container = require('./container');

exports = module.exports = new Container();

// Exports.
exports.Container = Container;

exports.fs =
exports.node = require('./sources/dir');
exports.node_modules = require('./sources/node_modules');
<commit_msg>Add deprecation warning.<commit_after>// Load modules.
var Container = require('./container')
  , deprecate = require('depd')('electrolyte');

exports = module.exports = new Container();

// Exports.
exports.Container = Container;

exports.fs =
exports.dir = require('./sources/dir');
exports.node = deprecate.function(exports.dir, 'Container#node: Use Container#dir instead');

exports.node_modules = require('./sources/node_modules');
<|endoftext|>


<commit_before>/**
 * Describes the play state.
 */

var PlayState = function() {
	var mSelf = this;
	var mHud; 				// Game hud
	var mLevel;
	var mPlayer;
	var mMatchTime;			// Remaining time for the match
	var mHealth;			// Available health points.
	var mScore = {			// Info regarding global score (throughout the game session)
		right: 0,
		wrong: 0,
		miss: 0
	};

	this.create = function() {
		this.game.stage.backgroundColor = '#5FCDE4';

		// Init physics
		this.game.physics.startSystem(Phaser.Physics.ARCADE);
		this.game.physics.setBoundsToWorld();
 		this.game.physics.arcade.gravity.y = 300;
		this.game.time.desiredFps = 30;

		// Init entities
		mLevel = new Level(this.game);
		this.initPlayer();

		// Init misc stuff
		mMatchTime = Constants.GAME_MATCH_DURATION;
		mHealth = Constants.GAME_HEALTH_MAX;

		mHud = new Hud();
		this.game.add.existing(mHud);

		if(GlobalInfo && GlobalInfo.data) {
			GlobalInfo.data.markGameStarted();
		}
	};

	this.initPlayer = function() {
		mPlayer = this.game.add.sprite(50, this.game.width * 0.15, 'player');

		mPlayer.animations.add('run', [0, 1, 2, 3, 4, 5], 10, true);
		mPlayer.animations.add('jump', [6, 7, 8, 8, 9, 10], 5, true);
		mPlayer.animations.play('run');

		this.game.physics.enable(mPlayer, Phaser.Physics.ARCADE);
		mPlayer.body.collideWorldBounds = true;
	};

	this.updateTimeAndTracking = function() {
		if(GlobalInfo && GlobalInfo.expression) {
			var aEmotions = GlobalInfo.expression.getEmotions();
			var aPoints = GlobalInfo.expression.getPoints();

			// Emotions are available for reading?
			if(aEmotions.length > 0 && Constants.GAME_ENABLE_DATA_LOG) {
				// Yeah, they are, collect them
				GlobalInfo.data.log({e: aEmotions, p: aPoints, s: mScore});
				GlobalInfo.data.send(GlobalInfo.uuid, GlobalInfo.game);
			}
		}

		// Update match time
		mMatchTime -= this.game.time.elapsedMS;

		if(mMatchTime <= 0 || mHealth <= 0) {
			// Match is over!
			if(GlobalInfo) {
				GlobalInfo.score = mScore;
			}
			// TODO: disable face tracking here
			this.game.state.start('over');
		}

		if(GlobalInfo && GlobalInfo.data) {
			GlobalInfo.data.update();
		}
	};

	this.update = function() {
		this.updateTimeAndTracking();

		mPlayer.body.velocity.x = 0;
		mPlayer.x = this.game.width * 0.15;

	    if (this.game.input.keyboard.downDuration(Phaser.Keyboard.SPACEBAR, 10)) {
			//if(mControls.up.isDown) {
		        mPlayer.animations.play('jump');
				mPlayer.y -= 50;
				mPlayer.body.velocity.y = -350;
				console.log('sdsdsd');

		    //} else if(mControls.down.isDown) {
			//	mPlayer.animations.play('duck');
			//}
	    }

		if (!this.game.input.keyboard.downDuration(Phaser.Keyboard.SPACEBAR, 10)) {
			this.game.physics.arcade.collide(mPlayer, mLevel.getFloor());
		}

		this.game.physics.arcade.overlap(mPlayer, mLevel.getSlopes(), this.handleMovesOnSlopes);
	};

	this.handleMovesOnSlopes = function(thePlayer, theSlope) {
		var aScale;

		aScale = (thePlayer.x - theSlope.x) / theSlope.width;

		if(theSlope.key == 'slope-up') {
			if(aScale < 0.1) {
				thePlayer.y = theSlope.y - theSlope.height / 2;

			} else if(aScale >= 0.1 && aScale <= 0.6) {
				thePlayer.y = theSlope.y - (theSlope.height / 2 + aScale * theSlope.height);
			}
		} else {
			if(aScale >= 0.25 && aScale <= 0.6) {
				thePlayer.y = theSlope.y - theSlope.height / 2 - 40 + aScale * (theSlope.height / 2);

			} else if(aScale > 0.6) {
				thePlayer.y = theSlope.y - theSlope.height / 2;
			}
		}
	};

	// theType can be 'right', 'wrong' or 'miss'
	this.countMove = function(theType) {
		if(theType == 'right') {
			mScore.right++;
			mHealth += Constants.GAME_CORRECT_HEALTH;

		} else if(theType == 'wrong') {
			mScore.wrong++;
			mHealth -= Constants.GAME_MISTAKE_HEALTH;

		} else {
			mScore.miss++;
			mHealth -= Constants.GAME_MISTAKE_HEALTH;
		}

		// Prevent overfeeding health
		if(mHealth >= Constants.GAME_HEALTH_MAX) {
			mHealth = Constants.GAME_HEALTH_MAX;
		}

		mHud.refresh();
	}

	// Getters

	this.getScore = function() {
		return mScore;
	};

	this.getMatchRemainingTime = function() {
		return mMatchTime;
	};

	this.getHud = function() {
		return mHud;
	};

	this.getHealthPercentage = function() {
		return mHealth/Constants.GAME_HEALTH_MAX;
	};
};
<commit_msg>The jump is a bit better<commit_after>/**
 * Describes the play state.
 */

var PlayState = function() {
	var mSelf = this,
		mHud, 				// Game hud
		mLevel,
		mPlayer,
		mJumping,
		mDashing,
		mActionTimer,
		mMatchTime,			// Remaining time for the match
		mHealth,			// Available health points.
		mScore = {			// Info regarding global score (throughout the game session)
			right: 0,
			wrong: 0,
			miss: 0
		};

	this.create = function() {
		this.game.stage.backgroundColor = '#5FCDE4';

		// Init physics
		this.game.physics.startSystem(Phaser.Physics.ARCADE);
		this.game.physics.setBoundsToWorld();
 		this.game.physics.arcade.gravity.y = 1000;
		this.game.time.desiredFps = 30;

		// Init entities
		mLevel = new Level(this.game);
		this.initPlayer();

		// Init misc stuff
		mMatchTime = Constants.GAME_MATCH_DURATION;
		mHealth = Constants.GAME_HEALTH_MAX;
		mJumping = false;
		mDashing = false;
		mActionTimer = 0;

		mHud = new Hud();
		this.game.add.existing(mHud);

		if(GlobalInfo && GlobalInfo.data) {
			GlobalInfo.data.markGameStarted();
		}
	};

	this.initPlayer = function() {
		mPlayer = this.game.add.sprite(50, this.game.width * 0.15, 'player');

		mPlayer.animations.add('run', [0, 1, 2, 3, 4, 5], 10, true);
		mPlayer.animations.add('jump', [6, 7, 8, 8, 9, 10], 5, true);
		mPlayer.animations.play('run');

		this.game.physics.enable(mPlayer, Phaser.Physics.ARCADE);
		mPlayer.body.collideWorldBounds = true;
	};

	this.updateTimeAndTracking = function() {
		if(GlobalInfo && GlobalInfo.expression) {
			var aEmotions = GlobalInfo.expression.getEmotions();
			var aPoints = GlobalInfo.expression.getPoints();

			// Emotions are available for reading?
			if(aEmotions.length > 0 && Constants.GAME_ENABLE_DATA_LOG) {
				// Yeah, they are, collect them
				GlobalInfo.data.log({e: aEmotions, p: aPoints, s: mScore});
				GlobalInfo.data.send(GlobalInfo.uuid, GlobalInfo.game);
			}
		}

		// Update match time
		mMatchTime -= this.game.time.elapsedMS;

		if(mMatchTime <= 0 || mHealth <= 0) {
			// Match is over!
			if(GlobalInfo) {
				GlobalInfo.score = mScore;
			}
			// TODO: disable face tracking here
			this.game.state.start('over');
		}

		if(GlobalInfo && GlobalInfo.data) {
			GlobalInfo.data.update();
		}
	};

	this.update = function() {
		var aKeyboard;

		this.updateTimeAndTracking();

		mPlayer.body.velocity.x = 0;
		mPlayer.x = this.game.width * 0.15;
		aKeyboard = this.game.input.keyboard;

		if(mJumping || mDashing) {
			mActionTimer -= this.game.time.elapsedMS;

			if(mActionTimer <= 0) {
				mJumping = false;
				mDashing = false;
				mPlayer.animations.play('run');
			}
		}

	    if (aKeyboard.downDuration(Phaser.Keyboard.SPACEBAR, 10)) {
			if(!mJumping && aKeyboard.isDown(Phaser.Keyboard.UP, 10)) {
				mJumping = true;
				mActionTimer = 500;
		        mPlayer.animations.play('jump');
				mPlayer.body.velocity.y = -500;

			} else if(!mJumping && aKeyboard.isDown(Phaser.Keyboard.DOWN, 10)){
				mDashing = true;
				mActionTimer = 500;
				mPlayer.animations.play('jump');
			}
	    }

		if (!mJumping) {
			this.game.physics.arcade.collide(mPlayer, mLevel.getFloor());
		}

		this.game.physics.arcade.overlap(mPlayer, mLevel.getSlopes(), this.handleMovesOnSlopes);
	};

	this.handleMovesOnSlopes = function(thePlayer, theSlope) {
		var aScale;

		aScale = (thePlayer.x - theSlope.x) / theSlope.width;

		if(theSlope.key == 'slope-up') {
			if(aScale < 0.1) {
				thePlayer.y = theSlope.y - theSlope.height / 2;

			} else if(aScale >= 0.1 && aScale <= 0.6) {
				thePlayer.y = theSlope.y - (theSlope.height / 2 + aScale * theSlope.height);
			}
		} else {
			if(aScale >= 0.25 && aScale <= 0.6) {
				thePlayer.y = theSlope.y - theSlope.height / 2 - 40 + aScale * (theSlope.height / 2);

			} else if(aScale > 0.6) {
				thePlayer.y = theSlope.y - theSlope.height / 2;
			}
		}
	};

	// theType can be 'right', 'wrong' or 'miss'
	this.countMove = function(theType) {
		if(theType == 'right') {
			mScore.right++;
			mHealth += Constants.GAME_CORRECT_HEALTH;

		} else if(theType == 'wrong') {
			mScore.wrong++;
			mHealth -= Constants.GAME_MISTAKE_HEALTH;

		} else {
			mScore.miss++;
			mHealth -= Constants.GAME_MISTAKE_HEALTH;
		}

		// Prevent overfeeding health
		if(mHealth >= Constants.GAME_HEALTH_MAX) {
			mHealth = Constants.GAME_HEALTH_MAX;
		}

		mHud.refresh();
	}

	// Getters

	this.getScore = function() {
		return mScore;
	};

	this.getMatchRemainingTime = function() {
		return mMatchTime;
	};

	this.getHud = function() {
		return mHud;
	};

	this.getHealthPercentage = function() {
		return mHealth/Constants.GAME_HEALTH_MAX;
	};
};
<|endoftext|>