<commit_before>'use strict';
var uniqueRandomArray = require('unique-random-array');
var femaleHumanNamesEn = require('./female-human-names-en.json');
var maleHumanNamesEn = require('./male-human-names-en.json');
var allHumanNamesEn = [];

var femaleHumanNamesIt = require('./female-human-names-it.json');
var maleHumanNamesIt = require('./male-human-names-it.json');
var allHumanNamesIt = [];

var femaleHumanNamesFr = require('./female-human-names-fr.json');
var maleHumanNamesFr = require('./male-human-names-fr.json');
var allHumanNamesFr = [];

var femaleHumanNamesDe = require('./female-human-names-de.json');
var maleHumanNamesDe = require('./male-human-names-de.json');
var allHumanNamesDe = [];

var femaleHumanNamesEs = require('./female-human-names-es.json');
var maleHumanNamesEs = require('./male-human-names-es.json');
var allHumanNamesEs = [];

femaleHumanNamesEn.forEach(function (el, i) {
    if((maleHumanNamesEn[i] != undefined) && (maleHumanNamesEn[i] != 'undefined')){
        allHumanNamesEn.push(el, maleHumanNamesEn[i]);
    }
});

femaleHumanNamesIt.forEach(function (el, i) {
    if((maleHumanNamesIt[i] != undefined) && (maleHumanNamesIt[i] != 'undefined')){
        allHumanNamesIt.push(el, maleHumanNamesIt[i]);
    }
});

femaleHumanNamesFr.forEach(function (el, i) {
    if((maleHumanNamesFr[i] != undefined) && (maleHumanNamesFr[i] != 'undefined')){
        allHumanNamesFr.push(el, maleHumanNamesFr[i]);
    }
});

femaleHumanNamesDe.forEach(function (el, i) {
    if((maleHumanNamesDe[i] != undefined) && (maleHumanNamesDe[i] != 'undefined')){
        allHumanNamesDe.push(el, maleHumanNamesDe[i]);
    }
});

femaleHumanNamesEs.forEach(function (el, i) {
    if((maleHumanNamesEs[i] != undefined) && (maleHumanNamesEs[i] != 'undefined')){
        allHumanNamesEs.push(el, maleHumanNamesEs[i]);
    }
});

exports.femaleEn = femaleHumanNamesEn;
exports.maleEn = maleHumanNamesEn;
exports.allEn = allHumanNamesEn;

exports.femaleIt = femaleHumanNamesIt;
exports.maleIt = maleHumanNamesIt;
exports.allIt = allHumanNamesIt;

exports.femaleFr = femaleHumanNamesFr;
exports.maleFr = maleHumanNamesFr;
exports.allFr = allHumanNamesFr;

exports.femaleDe = femaleHumanNamesDe;
exports.maleDe = maleHumanNamesDe;
exports.allDe = allHumanNamesDe;

exports.femaleEs = femaleHumanNamesEs;
exports.maleEs = maleHumanNamesEs;
exports.allEs = allHumanNamesEs;

exports.femaleRandomEn = uniqueRandomArray(femaleHumanNamesEn);
exports.maleRandomEn = uniqueRandomArray(maleHumanNamesEn);
exports.allRandomEn = uniqueRandomArray(allHumanNamesEn);

exports.femaleRandomIt = uniqueRandomArray(femaleHumanNamesIt);
exports.maleRandomIt = uniqueRandomArray(maleHumanNamesIt);
exports.allRandomIt = uniqueRandomArray(allHumanNamesIt);

exports.femaleRandomFr = uniqueRandomArray(femaleHumanNamesFr);
exports.maleRandomFr = uniqueRandomArray(maleHumanNamesFr);
exports.allRandomFr = uniqueRandomArray(allHumanNamesFr);

exports.femaleRandomDe = uniqueRandomArray(femaleHumanNamesDe);
exports.maleRandomDe = uniqueRandomArray(maleHumanNamesDe);
exports.allRandomDe = uniqueRandomArray(allHumanNamesDe);

exports.femaleRandomEs = uniqueRandomArray(femaleHumanNamesEs);
exports.maleRandomEs = uniqueRandomArray(maleHumanNamesEs);
exports.allRandomEs = uniqueRandomArray(allHumanNamesEs);
<commit_msg>Update index.js<commit_after>'use strict';
var uniqueRandomArray = require('unique-random-array');
var femaleHumanNamesEn = require('./female-human-names-en.json');
var maleHumanNamesEn = require('./male-human-names-en.json');
var allHumanNamesEn = [];

var femaleHumanNamesIt = require('./female-human-names-it.json');
var maleHumanNamesIt = require('./male-human-names-it.json');
var allHumanNamesIt = [];

var femaleHumanNamesFr = require('./female-human-names-fr.json');
var maleHumanNamesFr = require('./male-human-names-fr.json');
var allHumanNamesFr = [];

var femaleHumanNamesDe = require('./female-human-names-de.json');
var maleHumanNamesDe = require('./male-human-names-de.json');
var allHumanNamesDe = [];

var femaleHumanNamesEs = require('./female-human-names-es.json');
var maleHumanNamesEs = require('./male-human-names-es.json');
var allHumanNamesEs = [];

femaleHumanNamesEn.forEach(function (el, i) {
    if((maleHumanNamesEn[i] != undefined) && (maleHumanNamesEn[i] != 'undefined')){
        allHumanNamesEn.push(el, maleHumanNamesEn[i]);
    }
});

femaleHumanNamesIt.forEach(function (el, i) {
    if((maleHumanNamesIt[i] != undefined) && (maleHumanNamesIt[i] != 'undefined')){
        allHumanNamesIt.push(el, maleHumanNamesIt[i]);
    }
});

femaleHumanNamesFr.forEach(function (el, i) {
    if((maleHumanNamesFr[i] != undefined) && (maleHumanNamesFr[i] != 'undefined')){
        allHumanNamesFr.push(el, maleHumanNamesFr[i]);
    }
});

femaleHumanNamesDe.forEach(function (el, i) {
    if((maleHumanNamesDe[i] != undefined) && (maleHumanNamesDe[i] != 'undefined')){
        allHumanNamesDe.push(el, maleHumanNamesDe[i]);
    }
});

femaleHumanNamesEs.forEach(function (el, i) {
    if((maleHumanNamesEs[i] != undefined) && (maleHumanNamesEs[i] != 'undefined')){
        allHumanNamesEs.push(el, maleHumanNamesEs[i]);
    }
});

exports.femaleEn = femaleHumanNamesEn;
exports.maleEn = maleHumanNamesEn;
exports.allEn = allHumanNamesEn;

exports.femaleIt = femaleHumanNamesIt;
exports.maleIt = maleHumanNamesIt;
exports.allIt = allHumanNamesIt;

exports.femaleFr = femaleHumanNamesFr;
exports.maleFr = maleHumanNamesFr;
exports.allFr = allHumanNamesFr;

exports.femaleDe = femaleHumanNamesDe;
exports.maleDe = maleHumanNamesDe;
exports.allDe = allHumanNamesDe;

exports.femaleEs = femaleHumanNamesEs;
exports.maleEs = maleHumanNamesEs;
exports.allEs = allHumanNamesEs;

exports.femaleRandom = uniqueRandomArray(femaleHumanNamesEn);
exports.maleRandom = uniqueRandomArray(maleHumanNamesEn);
exports.allRandom = uniqueRandomArray(allHumanNamesEn);

exports.femaleRandomEn = uniqueRandomArray(femaleHumanNamesEn);
exports.maleRandomEn = uniqueRandomArray(maleHumanNamesEn);
exports.allRandomEn = uniqueRandomArray(allHumanNamesEn);

exports.femaleRandomIt = uniqueRandomArray(femaleHumanNamesIt);
exports.maleRandomIt = uniqueRandomArray(maleHumanNamesIt);
exports.allRandomIt = uniqueRandomArray(allHumanNamesIt);

exports.femaleRandomFr = uniqueRandomArray(femaleHumanNamesFr);
exports.maleRandomFr = uniqueRandomArray(maleHumanNamesFr);
exports.allRandomFr = uniqueRandomArray(allHumanNamesFr);

exports.femaleRandomDe = uniqueRandomArray(femaleHumanNamesDe);
exports.maleRandomDe = uniqueRandomArray(maleHumanNamesDe);
exports.allRandomDe = uniqueRandomArray(allHumanNamesDe);

exports.femaleRandomEs = uniqueRandomArray(femaleHumanNamesEs);
exports.maleRandomEs = uniqueRandomArray(maleHumanNamesEs);
exports.allRandomEs = uniqueRandomArray(allHumanNamesEs);
<|endoftext|>


<commit_before>/**
 * This module maps the Lambda proxy requests to the Hapijs router
 */
'use strict';

const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection(); // no connection details for lambda

// flag so plugsin dont get reconfigured
let loaded = false;

/**
 * Configures the lambda proxy to host hapi.js plugins
 * @param plugins An array of plugins to register
 */
exports.configure = function(plugins){
    if(!plugins) throw 'Plugins must be configured as an array';

    server.makeReady = function(onServerReady){
        if(!loaded){
            server.register(plugins, onServerReady);
            loaded = true;
        }
        else{
            onServerReady(null);
        }
    };
}

exports.handler = (event, context, callback) => {

    server.makeReady((err) => {

        if(err) throw err;

        // lambda removes query string params from the url and places them into
        // and object in event. Hapi expects them on the url path
        let path = event.path;
        const qs = Object.keys(event.queryStringParameters).map(key => { return key + '=' + event.queryStringParameters[key]; });
        if(qs.length > 0){
            path += '?' + qs.join('&');
        }

        // map lambda event to hapi request
        const options = {
            method: event.httpMethod,
            url: path,
            payload: event.body,
            headers: event.headers,
            validate: false
        };

        server.inject(options, function(res){

            // some headers are rejected by lambda
            // ref: http://stackoverflow.com/questions/37942119/rust-aws-api-gateway-service-proxy-to-s3-file-upload-using-raw-https-request/37950875#37950875
            // ref: https://github.com/awslabs/aws-serverless-express/issues/10
            delete res.headers['content-encoding'];
            delete res.headers['transfer-encoding'];

            // handle cors here b/c api gateway does half of it for us
            // these options must match the serverless.yaml options
            res.headers['Access-Control-Allow-Origin'] = '*';
            res.headers['Access-Control-Allow-Credentials'] = true;

            const response = {
                statusCode: res.statusCode,
                headers: res.headers,
                body: JSON.stringify(res.result)
            };

            console.log('response', response);

            callback(null, response);
        });

    });

};<commit_msg>Fix a bug in query parm parsing<commit_after>/**
 * This module maps the Lambda proxy requests to the Hapijs router
 */
'use strict';

const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection(); // no connection details for lambda

// flag so plugsin dont get reconfigured
let loaded = false;

/**
 * Configures the lambda proxy to host hapi.js plugins
 * @param plugins An array of plugins to register
 */
exports.configure = function(plugins){
    if(!plugins) throw 'Plugins must be configured as an array';

    server.makeReady = function(onServerReady){
        if(!loaded){
            server.register(plugins, onServerReady);
            loaded = true;
        }
        else{
            onServerReady(null);
        }
    };
}

exports.handler = (event, context, callback) => {

    server.makeReady((err) => {

        if(err) throw err;

        // lambda removes query string params from the url and places them into
        // and object in event. Hapi expects them on the url path
        let path = event.path;
        if(event.queryStringParameters){
            const qs = Object.keys(event.queryStringParameters).map(key => { return key + '=' + event.queryStringParameters[key]; });
            if(qs.length > 0){
                path += '?' + qs.join('&');
            }
        }

        // map lambda event to hapi request
        const options = {
            method: event.httpMethod,
            url: path,
            payload: event.body,
            headers: event.headers,
            validate: false
        };

        server.inject(options, function(res){

            // some headers are rejected by lambda
            // ref: http://stackoverflow.com/questions/37942119/rust-aws-api-gateway-service-proxy-to-s3-file-upload-using-raw-https-request/37950875#37950875
            // ref: https://github.com/awslabs/aws-serverless-express/issues/10
            delete res.headers['content-encoding'];
            delete res.headers['transfer-encoding'];

            // handle cors here b/c api gateway does half of it for us
            // these options must match the serverless.yaml options
            res.headers['Access-Control-Allow-Origin'] = '*';
            res.headers['Access-Control-Allow-Credentials'] = true;

            const response = {
                statusCode: res.statusCode,
                headers: res.headers,
                body: JSON.stringify(res.result)
            };

            console.log('response', response);

            callback(null, response);
        });

    });

};<|endoftext|>


<commit_before>(function () {

	var destinations = [
	  ['Dusseldorf', 51.227098,6.774337],
	  ['Cologne', 50.936796,6.960998],
	  ['Bacharach', 50.056478,7.769684],
		['Braubach', 50.277054,7.644371],
	  ['Rothenburg (ob der Tauber)', 49.379411,10.185911],
	  ['Erfurt', 50.98437,11.030563],
	  ['Wittenberg', 51.873735,12.628071],
	  ['Berlin', 52.517892,13.408599],
	  ['Munich', 48.136308,11.578109],
	  ['Füssen', 47.572009,10.691572],
	  ['Munich', 48.136308,11.578109],
	  ['Venice', 45.437671,12.326818],
	  ['Cinque Terre (Monterosso al Mare)', 44.145369,9.653183],
		['Cinque Terre (Vernazza)', 44.134913,9.685003],
		['Cinque Terre (Monterosso al Mare)', 44.145369,9.653183],
	  ['Pisa', 43.722234,10.401939],
	  ['Siena', 43.318184,11.330971],
	  ['Florence', 43.770908,11.248184],
	  ['Rome', 41.892055,12.483162]
	];

	var map;

	function initialize() {
	  var mapOptions = {
	    center: new google.maps.LatLng(46.027482,10.389633),
	    zoom: 5,
	    mapTypeId: google.maps.MapTypeId.ROADMAP
	  };

	  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
		dropDestinations();
  }

	function addMarker(destination) {
		var marker = new google.maps.Marker({
		      position: new google.maps.LatLng(destination[1],destination[2]),
		      map: map,
		      title:destination[0]
		  })
	}

	function dropDestinations() {
		for (var i=0; i < destinations.length; i++) {
	    setTimeout(function() {
		    addMarker(destinations[i]);
		  }, i * 200);
		}
	}

	google.maps.event.addDomListener(window, 'load', initialize);
}());

<commit_msg>took out delay attempt for now to just get the pins on the maps<commit_after>(function () {

	var destinations = [
	  ['Dusseldorf', 51.227098,6.774337],
	  ['Cologne', 50.936796,6.960998],
	  ['Bacharach', 50.056478,7.769684],
		['Braubach', 50.277054,7.644371],
	  ['Rothenburg (ob der Tauber)', 49.379411,10.185911],
	  ['Erfurt', 50.98437,11.030563],
	  ['Wittenberg', 51.873735,12.628071],
	  ['Berlin', 52.517892,13.408599],
	  ['Munich', 48.136308,11.578109],
	  ['Füssen', 47.572009,10.691572],
	  ['Munich', 48.136308,11.578109],
	  ['Venice', 45.437671,12.326818],
	  ['Cinque Terre (Monterosso al Mare)', 44.145369,9.653183],
		['Cinque Terre (Vernazza)', 44.134913,9.685003],
		['Cinque Terre (Monterosso al Mare)', 44.145369,9.653183],
	  ['Pisa', 43.722234,10.401939],
	  ['Siena', 43.318184,11.330971],
	  ['Florence', 43.770908,11.248184],
	  ['Rome', 41.892055,12.483162]
	];

	var map;

	function initialize() {
	  var mapOptions = {
	    center: new google.maps.LatLng(46.027482,10.389633),
	    zoom: 5,
	    mapTypeId: google.maps.MapTypeId.ROADMAP
	  };

	  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
		dropDestinations();
  }

	function addMarker(destination) {
		var marker = new google.maps.Marker({
		      position: new google.maps.LatLng(destination[1],destination[2]),
		      map: map,
		      title:destination[0]
		  })
	}

	function dropDestinations() {
		for (var i=0; i < destinations.length; i++) {
	    // setTimeout(function() {
		    addMarker(destinations[i]);
		  // }, i * 200);
		}
	}

	google.maps.event.addDomListener(window, 'load', initialize);
}());

<|endoftext|>


<commit_before>/**
 * Image url
 * @typedef {String} Url
 */

/**
 * Diff mode
 * @typedef {String} Mode - difference | fade | swipe
 */

/**
 * Float number
 * @typedef {Number} Float
 */

// jquery4
var $ = function querySelector(domElem, selector) {
  if (arguments.length < 2) {
    selector = domElem;
    domElem = document;
  }
  return domElem.querySelector(selector);
};

/**
 * @class ImageDiff
 */
var ImageDiff = function () {
  /**
   * Init ImageDiff, load new images, set diff mode
   * @param {HTMLElement} domElem - ImageDiff instance (.image-diff)
   * @param {Url} before
   * @param {Url} after
   * @param {Mode} mode
   * @public
   * @constructor
   */
  function ImageDiff(domElem, before, after, mode) {
    this.domElems = {
      before: $(domElem, '.image-diff__before img'),
      after: $(domElem, '.image-diff__after img'),
      beforeWrapper: $(domElem, '.image-diff__before'),
      afterWrapper: $(domElem, '.image-diff__after'),
      wrapper: $(domElem, '.image-diff__wrapper'),
      inner: $(domElem, '.image-diff__inner')
    }

    this.domElems.before.onload=this._handleImgLoad();
    this.domElems.after.onload=this._handleImgLoad();

    this.update(before, after, mode);
  }

  ImageDiff.modes = ['difference', 'fade', 'swipe'];

  ImageDiff.getDefaultProps = function getDefaultProps() {
    return {
      value: 1,
      width: 0, height: 0,
      after: {width:0,height:0,url:''},
      before: {width:0,height:0, url:''},
      mode: 'difference' // ImageDiff.modes
    };
  };

  // default props
  ImageDiff.prototype.props = ImageDiff.getDefaultProps();

  /**
   * load new images or change diff mode
   * @param {Url} before
   * @param {Url} after
   * @param {Mode} mode
   * @public
   */
  ImageDiff.prototype.update = function update(before, after, mode) {
    this.props = ImageDiff.getDefaultProps();

    this.props.before.url = before;
    this.props.after.url = after;

    this.domElems.before.src = before;
    this.domElems.after.src = after;

    this._initMode(mode);
  };

  /**
   * @param {Float} value - 0..1
   * @public
   */
  ImageDiff.prototype.swipe = function swipe(value) {
    this._updateValue('swipe', value);
    this.domElems.wrapper.style.width = (this.props.width * (1. - value)) + 'px';
  };

  /**
   * @param {Float} value - 0..1
   * @public
   */
  ImageDiff.prototype.fade = function fade(value) {
    this._updateValue('fade', value);
    this.domElems.wrapper.style.opacity = value;
  };

  ImageDiff.prototype._updateValue = function _updateValue(mode, value) {
    if (value < 0-1e-6 || value > 1.+1e-6) {
      throw mode + ' value must be within 0..1, but given:' + value;
    }
    if (this.props.mode !== mode) {
      throw 'current diff mode is ' + this.props.mode + ', not ' + mode;
    }
    this.props.value = value;
  };

  ImageDiff.prototype._initSize = function _initSize(width, height) {
    // Размеры могут прийти раньше от первой или от второй картинки.
    // Повторное обновление не требется.
    // При загрузке новых картинок делается сброс размеров.
    if (this.props.width && this.props.height) {
      return;
    }

    this.props.width = width;
    this.props.height = height;

    (function initDomElems(argument) {
      var _this = this;
      var sizes = {width:width, height:height};

      Object.keys(sizes).forEach(function(key) {
        var val = sizes[key];
        ['afterWrapper', 'beforeWrapper', 'wrapper', 'inner'].forEach(function (elem) {
          _this.domElems[elem].style[key] = val + 'px';
        });
      });
    }).call(this);
  };

  ImageDiff.prototype._initMode = function _initMode(mode) {
    if (!ImageDiff.modes.includes(mode)) {
      throw 'Given mode «' + mode + '» not contained in collection ' + ImageDiff.modes;
    }
    this.props.mode = mode;
    this.domElems.inner.className = 'image-diff__inner image-diff__inner--' + mode;
  };

  ImageDiff.prototype._handleImgLoad = function _handleImgLoad() {
    var _this = this;

    return function () {
      var img = this;
      _this._initSize(img.width, img.height);
    };
  };

  return ImageDiff;
}();

if (module.exports) {
  module.exports = ImageDiff;
} else if (window) {
  window.ImageDiff = ImageDiff;
}
<commit_msg>fix export<commit_after>/**
 * Image url
 * @typedef {String} Url
 */

/**
 * Diff mode
 * @typedef {String} Mode - difference | fade | swipe
 */

/**
 * Float number
 * @typedef {Number} Float
 */

// jquery4
var $ = function querySelector(domElem, selector) {
  if (arguments.length < 2) {
    selector = domElem;
    domElem = document;
  }
  return domElem.querySelector(selector);
};

/**
 * @class ImageDiff
 */
var ImageDiff = function () {
  /**
   * Init ImageDiff, load new images, set diff mode
   * @param {HTMLElement} domElem - ImageDiff instance (.image-diff)
   * @param {Url} before
   * @param {Url} after
   * @param {Mode} mode
   * @public
   * @constructor
   */
  function ImageDiff(domElem, before, after, mode) {
    this.domElems = {
      before: $(domElem, '.image-diff__before img'),
      after: $(domElem, '.image-diff__after img'),
      beforeWrapper: $(domElem, '.image-diff__before'),
      afterWrapper: $(domElem, '.image-diff__after'),
      wrapper: $(domElem, '.image-diff__wrapper'),
      inner: $(domElem, '.image-diff__inner')
    }

    this.domElems.before.onload=this._handleImgLoad();
    this.domElems.after.onload=this._handleImgLoad();

    this.update(before, after, mode);
  }

  ImageDiff.modes = ['difference', 'fade', 'swipe'];

  ImageDiff.getDefaultProps = function getDefaultProps() {
    return {
      value: 1,
      width: 0, height: 0,
      after: {width:0,height:0,url:''},
      before: {width:0,height:0, url:''},
      mode: 'difference' // ImageDiff.modes
    };
  };

  // default props
  ImageDiff.prototype.props = ImageDiff.getDefaultProps();

  /**
   * load new images or change diff mode
   * @param {Url} before
   * @param {Url} after
   * @param {Mode} mode
   * @public
   */
  ImageDiff.prototype.update = function update(before, after, mode) {
    this.props = ImageDiff.getDefaultProps();

    this.props.before.url = before;
    this.props.after.url = after;

    this.domElems.before.src = before;
    this.domElems.after.src = after;

    this._initMode(mode);
  };

  /**
   * @param {Float} value - 0..1
   * @public
   */
  ImageDiff.prototype.swipe = function swipe(value) {
    this._updateValue('swipe', value);
    this.domElems.wrapper.style.width = (this.props.width * (1. - value)) + 'px';
  };

  /**
   * @param {Float} value - 0..1
   * @public
   */
  ImageDiff.prototype.fade = function fade(value) {
    this._updateValue('fade', value);
    this.domElems.wrapper.style.opacity = value;
  };

  ImageDiff.prototype._updateValue = function _updateValue(mode, value) {
    if (value < 0-1e-6 || value > 1.+1e-6) {
      throw mode + ' value must be within 0..1, but given:' + value;
    }
    if (this.props.mode !== mode) {
      throw 'current diff mode is ' + this.props.mode + ', not ' + mode;
    }
    this.props.value = value;
  };

  ImageDiff.prototype._initSize = function _initSize(width, height) {
    // Размеры могут прийти раньше от первой или от второй картинки.
    // Повторное обновление не требется.
    // При загрузке новых картинок делается сброс размеров.
    if (this.props.width && this.props.height) {
      return;
    }

    this.props.width = width;
    this.props.height = height;

    (function initDomElems(argument) {
      var _this = this;
      var sizes = {width:width, height:height};

      Object.keys(sizes).forEach(function(key) {
        var val = sizes[key];
        ['afterWrapper', 'beforeWrapper', 'wrapper', 'inner'].forEach(function (elem) {
          _this.domElems[elem].style[key] = val + 'px';
        });
      });
    }).call(this);
  };

  ImageDiff.prototype._initMode = function _initMode(mode) {
    if (!ImageDiff.modes.includes(mode)) {
      throw 'Given mode «' + mode + '» not contained in collection ' + ImageDiff.modes;
    }
    this.props.mode = mode;
    this.domElems.inner.className = 'image-diff__inner image-diff__inner--' + mode;
  };

  ImageDiff.prototype._handleImgLoad = function _handleImgLoad() {
    var _this = this;

    return function () {
      var img = this;
      _this._initSize(img.width, img.height);
    };
  };

  return ImageDiff;
}();

if (module && module.exports) {
  module.exports = ImageDiff;
} else if (window) {
  window.ImageDiff = ImageDiff;
}
<|endoftext|>


<commit_before>const preset = require('babel-preset-es2020')
const through = require('through2')
const babel = require('babel-core')

module.exports = es2020

// In hindsight we can do without most of ES6
// (str, obj) -> transformStream
function es2020 (filename, options) {
  if (/\.json$/i.test(filename)) return through()
  const bufs = []
  const transformStream = through(write, end)
  return transformStream

  function write (buf, enc, next) {
    bufs.push(buf)
    next()
  }

  function end () {
    const src = Buffer.concat(bufs).toString('utf8')
    try {
      var res = babel.transform(src, {
        plugins: preset.plugins,
        sourceMaps: options._flags.debug ? 'inline' : false,
        filename: filename
      })
    } catch (err) {
      this.emit('error', err)
      return
    }
    this.push(res.code)
    this.push(null)
  }
}
<commit_msg>babel: compact-false (#19)<commit_after>const preset = require('babel-preset-es2020')
const through = require('through2')
const babel = require('babel-core')

module.exports = es2020

// In hindsight we can do without most of ES6
// (str, obj) -> transformStream
function es2020 (filename, options) {
  if (/\.json$/i.test(filename)) return through()
  const bufs = []
  const transformStream = through(write, end)
  return transformStream

  function write (buf, enc, next) {
    bufs.push(buf)
    next()
  }

  function end () {
    const src = Buffer.concat(bufs).toString('utf8')
    try {
      var res = babel.transform(src, {
        plugins: preset.plugins,
        sourceMaps: options._flags.debug ? 'inline' : false,
        filename: filename,
        compact: false
      })
    } catch (err) {
      this.emit('error', err)
      return
    }
    this.push(res.code)
    this.push(null)
  }
}
<|endoftext|>


<commit_before>// timeout fix for Node.js
jasmine.getGlobal().setTimeout = function(funcToCall, millis) {
  if (jasmine.Clock.installed.setTimeout.apply) {
    return jasmine.Clock.installed.setTimeout.apply(this, arguments);
  } else {
    return jasmine.Clock.installed.setTimeout(funcToCall, millis);
  }
};

// TODO add other time-related Clock mocks: setInterval etc

module.exports = {

  /**
   * call this in beforeEach method to add more available matchers
   * @param spec "this" within spec
   */
  addJasmineMatchers: function (spec) {
    spec.addMatchers({
      /**
       * Array contains all elements of another array
       * @param needles another array
       * @returns {Boolean} true/false
       */
      toContainAll: function(needles) {
        var haystack = this.actual;
        return needles.every(function (elem) {
          return haystack.some(function (sackElem) {
            return spec.env.equals_(elem, sackElem);
          });
        });
      }
    });
  },

  /**
   * filter jasmine spied function calls by first argument
   * @param calls calls array
   * @param firstArg value of first arg
   */
  getCallsFilteredByFirstArg: function (calls, firstArg){
    return _.filter(calls, function (elem) {
      return elem.args[0] === firstArg;
    });
  }

};

<commit_msg>lodash dependency<commit_after>var _ = require('lodash');

// timeout fix for Node.js
jasmine.getGlobal().setTimeout = function(funcToCall, millis) {
  if (jasmine.Clock.installed.setTimeout.apply) {
    return jasmine.Clock.installed.setTimeout.apply(this, arguments);
  } else {
    return jasmine.Clock.installed.setTimeout(funcToCall, millis);
  }
};

// TODO add other time-related Clock mocks: setInterval etc

module.exports = {

  /**
   * call this in beforeEach method to add more available matchers
   * @param spec "this" within spec
   */
  addJasmineMatchers: function (spec) {
    spec.addMatchers({
      /**
       * Array contains all elements of another array
       * @param needles another array
       * @returns {Boolean} true/false
       */
      toContainAll: function(needles) {
        var haystack = this.actual;
        return needles.every(function (elem) {
          return haystack.some(function (sackElem) {
            return spec.env.equals_(elem, sackElem);
          });
        });
      }
    });
  },

  /**
   * filter jasmine spied function calls by first argument
   * @param calls calls array
   * @param firstArg value of first arg
   */
  getCallsFilteredByFirstArg: function (calls, firstArg){
    return _.filter(calls, function (elem) {
      return elem.args[0] === firstArg;
    });
  }

};

<|endoftext|>


<commit_before>
require("./parts/pointset/linear");
require("./parts/pointset/random");
require("./parts/pointset/spiral");
require("./parts/pointset/static");

require("./parts/lines")

module.exports = function (opts){
  if ( ! opts ) opts = {};
  var parts = require('./parts');
  var core = require('./core');

  // block layouts
  parts.loadPart("blockFill");
  parts.loadPart("blockShapes");
  //parts.loadPart("blockSplit");
  //parts.loadPart("splitMask");
  parts.loadPart("blockLayout");

  // shape patterns
  parts.loadPart("scatterShapes");
//  parts.loadPart("orderedShapes");
//  parts.loadPart("gridShapes");
  parts.loadPart("overlayLines");

  // shapes
  parts.loadPart("polygon");
  parts.loadPart("stars");
  parts.loadPart("circle");
  parts.loadPart("lines");

  // Pallete scheems
  parts.loadPart("midToneHilight");
  parts.loadPart("monochrome");
  parts.loadPart("bichrome");

  return new Unique(parts,core,opts);
}

function Unique(parts,core,opts){
  this.parts = parts;
  this.core = core;
  this.opts = opts;
}
Unique.prototype.start = function(key){
  return new Builder(this,key);
}

function Builder(unique,key){
  this.unique = unique;
  this.width = unique.opts.width||800;
  this.height = unique.opts.height||600;
  this.key = key;
}
Builder.prototype.size = function(width,height){
  this.width = width;
  this.height = height;
  return this;
};
Builder.prototype.describe = function(){
  var struct = this.unique.core.process(this.key,this.width,this.height,this.unique.parts);
  console.log(struct.describe);
  return struct.describe();
};
Builder.prototype.writeXML = function( pretty ){
  var struct = this.unique.core.process(this.key,this.width,this.height,this.unique.parts);
  return struct.build( pretty )
}
<commit_msg>stuff<commit_after>
require("./parts/pointset/linear");
require("./parts/pointset/random");
require("./parts/pointset/spiral");
require("./parts/pointset/static");

require("./parts/lines")

module.exports = function (opts){
  if ( ! opts ) opts = {};
  var parts = require('./parts');
  var core = require('./core');

  // block layouts
  parts.loadPart("blockFill");
  parts.loadPart("blockShapes");
  //parts.loadPart("blockSplit");
  //parts.loadPart("splitMask");
  parts.loadPart("blockLayout");

  // shape patterns
  parts.loadPart("scatterShapes");
  parts.loadPart("gridShapes");
  parts.loadPart("overlayLines");

  // shapes
  parts.loadPart("polygon");
  parts.loadPart("stars");
  parts.loadPart("circle");

  // Pallete scheems
  parts.loadPart("midToneHilight");
  parts.loadPart("monochrome");
  parts.loadPart("bichrome");

  return new Unique(parts,core,opts);
}

function Unique(parts,core,opts){
  this.parts = parts;
  this.core = core;
  this.opts = opts;
}
Unique.prototype.start = function(key){
  return new Builder(this,key);
}

function Builder(unique,key){
  this.unique = unique;
  this.width = unique.opts.width||800;
  this.height = unique.opts.height||600;
  this.key = key;
}
Builder.prototype.size = function(width,height){
  this.width = width;
  this.height = height;
  return this;
};
Builder.prototype.describe = function(){
  var struct = this.unique.core.process(this.key,this.width,this.height,this.unique.parts);
  console.log(struct.describe);
  return struct.describe();
};
Builder.prototype.writeXML = function( pretty ){
  var struct = this.unique.core.process(this.key,this.width,this.height,this.unique.parts);
  return struct.build( pretty )
}
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');

function HtmlWebpackHarddiskPlugin (options) {
  assert.equal(options, undefined, 'The HtmlWebpackPugPlugin does not accept any options');
}

HtmlWebpackPugPlugin.prototype.apply = function (compiler) {
  var self = this;
  // Hook into the html-webpack-plugin processing
  compiler.plugin('compilation', function (compilation) {
    compilation.plugin('html-webpack-plugin-after-html-processing', function (htmlPluginData, callback) {
      self.postProcessHtml(htmlPluginData, callback);
    });
  });
};

/**
 * Writes an asset to disk
 */
HtmlWebpackPugPlugin.prototype.postProcessHtml = function (htmlPluginData, callback) {
  var self = this;
  var options = htmlPluginData.plugin.options;
  // Skip if the plugin configuration didn't set `inject` to true or didn't set `filetype`
  if (!options.inject || !options.filetype) {
    return callback(null);
  }
  htmlPluginData.html = self.injectAssetsIntoFile(htmlPluginData);
  callback(null, htmlPluginData);
};

/**
 * Injects the assets into the given file string
 */
HtmlWebpackPugPlugin.prototype.injectAssetsIntoFile = function (htmlPluginData) {
  var self = this;
  var html = htmlPluginData.html;
  var assets = htmlPluginData.assets

  var styles = self.headExtraction(html);
  var scripts = self.bodyExtraction(html);
  var file = self.removeUnnecessaryTags(html);

  switch (htmlPluginData.plugin.options.filetype) {
    case 'haml':
      return self.injectAssetsIntoHaml(file, styles, scripts, assets);
    case 'jade':
    case 'pug':
      return self.injectAssetsIntoPug(file, styles, scripts, assets);
    case 'slim':
      return self.injectAssetsIntoSlim(file, styles, scripts, assets);
    default:
      return html;
  }
};

/**
 * Extract the style tags from head
 */
HtmlWebpackPugPlugin.prototype.headExtraction = function (html) {
  var regExp = /<head><(.*)><\/head>/i;
  var match = regExp.exec(html);
  if (!match || match.length < 2) {
    return [];
  }
  return match[1].split('><');
};

/**
 * Extract the script tags from body
 */
HtmlWebpackPugPlugin.prototype.bodyExtraction = function (html) {
  var regExp = /<(script.*)><\/script>/i;
  var match = regExp.exec(html);
  if (!match || match.length < 2) {
    return [];
  }
  return match[1].split('></script><');
};

/**
 * Remove html format tags
 */
HtmlWebpackPugPlugin.prototype.removeUnnecessaryTags = function (html) {
  var headRegExp = /<head><(.*)><\/head>/i;
  var bodyRegExp = /<(script.*)><\/script>/i;
  return html.replace(headRegExp, '').replace(bodyRegExp, '');
};

/**
 * Create a tag of haml format
 */
HtmlWebpackPugPlugin.prototype.createHamlTag = function (tag) {
  return '%' + tag.split(' ').join(', :').replace(',', '{').replace(/=/g, ' => ') + ' }';
};

/**
 * Injects the assets into the given haml string
 */
HtmlWebpackPugPlugin.prototype.injectAssetsIntoHaml = function (file, styles, scripts, assets) {
  var self = this;
  var head = styles.map(self.createHamlTag);
  var body = scripts.map(self.createHamlTag);
  return self.injectAssets(file, head, body, assets);
};

/**
 * Create a tag of pug format
 */
HtmlWebpackPugPlugin.prototype.createPugTag = function (tag) {
  return tag.replace(' ', '(') + ')';
};

/**
 * Injects the assets into the given pug string
 */
HtmlWebpackPugPlugin.prototype.injectAssetsIntoPug = function (file, styles, scripts, assets) {
  var self = this;
  var head = styles.map(self.createPugTag);
  var body = scripts.map(self.createPugTag);
  return self.injectAssets(file, head, body, assets);
};

/**
 * Injects the assets into the given slim string
 */
HtmlWebpackPugPlugin.prototype.injectAssetsIntoSlim = function (file, styles, scripts, assets) {
  var self = this;
  return self.injectAssets(file, styles, scripts, assets);
};

/**
 * Injects the assets into the given string
 */
HtmlWebpackPugPlugin.prototype.injectAssets = function (file, head, body, assets) {
  var self = this;
  var bodyRegExp = /( *)(%?body)/i;

  var match = bodyRegExp.exec(file);
  if (match.length) {
    var hlSpace = match[1].repeat(2);
    if (head.length) {
      head = head.map(function(v) {
        return hlSpace + v;
      });
      // Append assets to head element
      file = file.replace(bodyRegExp, head.join('\n') + '\n' + match[0]);
    }

    if (body.length) {
      body = body.map(function(v) {
        return hlSpace + v;
      });
      // Append scripts to the end of the file:
      file += body.join('\n');
    }
  }

  // Inject manifest into the opening html tag
  // if (assets.manifest) {
  //   html = html.replace(/(%?html)/i, function (match, start) {
  //     // Append the manifest only if no manifest was specified
  //     if (/\smanifest\s*=/.test(match)) {
  //       return match;
  //     }
  //     return start + ' manifest="' + assets.manifest + '"' + end;
  //   });
  // }
  return file;
};

module.exports = HtmlWebpackPugPlugin;
<commit_msg>Correct the name mistake<commit_after>'use strict';

var assert = require('assert');

function HtmlWebpackPugPlugin (options) {
  assert.equal(options, undefined, 'The HtmlWebpackPugPlugin does not accept any options');
}

HtmlWebpackPugPlugin.prototype.apply = function (compiler) {
  var self = this;
  // Hook into the html-webpack-plugin processing
  compiler.plugin('compilation', function (compilation) {
    compilation.plugin('html-webpack-plugin-after-html-processing', function (htmlPluginData, callback) {
      self.postProcessHtml(htmlPluginData, callback);
    });
  });
};

/**
 * Writes an asset to disk
 */
HtmlWebpackPugPlugin.prototype.postProcessHtml = function (htmlPluginData, callback) {
  var self = this;
  var options = htmlPluginData.plugin.options;
  // Skip if the plugin configuration didn't set `inject` to true or didn't set `filetype`
  if (!options.inject || !options.filetype) {
    return callback(null);
  }
  htmlPluginData.html = self.injectAssetsIntoFile(htmlPluginData);
  callback(null, htmlPluginData);
};

/**
 * Injects the assets into the given file string
 */
HtmlWebpackPugPlugin.prototype.injectAssetsIntoFile = function (htmlPluginData) {
  var self = this;
  var html = htmlPluginData.html;
  var assets = htmlPluginData.assets

  var styles = self.headExtraction(html);
  var scripts = self.bodyExtraction(html);
  var file = self.removeUnnecessaryTags(html);

  switch (htmlPluginData.plugin.options.filetype) {
    case 'haml':
      return self.injectAssetsIntoHaml(file, styles, scripts, assets);
    case 'jade':
    case 'pug':
      return self.injectAssetsIntoPug(file, styles, scripts, assets);
    case 'slim':
      return self.injectAssetsIntoSlim(file, styles, scripts, assets);
    default:
      return html;
  }
};

/**
 * Extract the style tags from head
 */
HtmlWebpackPugPlugin.prototype.headExtraction = function (html) {
  var regExp = /<head><(.*)><\/head>/i;
  var match = regExp.exec(html);
  if (!match || match.length < 2) {
    return [];
  }
  return match[1].split('><');
};

/**
 * Extract the script tags from body
 */
HtmlWebpackPugPlugin.prototype.bodyExtraction = function (html) {
  var regExp = /<(script.*)><\/script>/i;
  var match = regExp.exec(html);
  if (!match || match.length < 2) {
    return [];
  }
  return match[1].split('></script><');
};

/**
 * Remove html format tags
 */
HtmlWebpackPugPlugin.prototype.removeUnnecessaryTags = function (html) {
  var headRegExp = /<head><(.*)><\/head>/i;
  var bodyRegExp = /<(script.*)><\/script>/i;
  return html.replace(headRegExp, '').replace(bodyRegExp, '');
};

/**
 * Create a tag of haml format
 */
HtmlWebpackPugPlugin.prototype.createHamlTag = function (tag) {
  return '%' + tag.split(' ').join(', :').replace(',', '{').replace(/=/g, ' => ') + ' }';
};

/**
 * Injects the assets into the given haml string
 */
HtmlWebpackPugPlugin.prototype.injectAssetsIntoHaml = function (file, styles, scripts, assets) {
  var self = this;
  var head = styles.map(self.createHamlTag);
  var body = scripts.map(self.createHamlTag);
  return self.injectAssets(file, head, body, assets);
};

/**
 * Create a tag of pug format
 */
HtmlWebpackPugPlugin.prototype.createPugTag = function (tag) {
  return tag.replace(' ', '(') + ')';
};

/**
 * Injects the assets into the given pug string
 */
HtmlWebpackPugPlugin.prototype.injectAssetsIntoPug = function (file, styles, scripts, assets) {
  var self = this;
  var head = styles.map(self.createPugTag);
  var body = scripts.map(self.createPugTag);
  return self.injectAssets(file, head, body, assets);
};

/**
 * Injects the assets into the given slim string
 */
HtmlWebpackPugPlugin.prototype.injectAssetsIntoSlim = function (file, styles, scripts, assets) {
  var self = this;
  return self.injectAssets(file, styles, scripts, assets);
};

/**
 * Injects the assets into the given string
 */
HtmlWebpackPugPlugin.prototype.injectAssets = function (file, head, body, assets) {
  var self = this;
  var bodyRegExp = /( *)(%?body)/i;

  var match = bodyRegExp.exec(file);
  if (match.length) {
    var hlSpace = match[1].repeat(2);
    if (head.length) {
      head = head.map(function(v) {
        return hlSpace + v;
      });
      // Append assets to head element
      file = file.replace(bodyRegExp, head.join('\n') + '\n' + match[0]);
    }

    if (body.length) {
      body = body.map(function(v) {
        return hlSpace + v;
      });
      // Append scripts to the end of the file:
      file += body.join('\n');
    }
  }

  // Inject manifest into the opening html tag
  // if (assets.manifest) {
  //   html = html.replace(/(%?html)/i, function (match, start) {
  //     // Append the manifest only if no manifest was specified
  //     if (/\smanifest\s*=/.test(match)) {
  //       return match;
  //     }
  //     return start + ' manifest="' + assets.manifest + '"' + end;
  //   });
  // }
  return file;
};

module.exports = HtmlWebpackPugPlugin;
<|endoftext|>


<commit_before>// Mise en place des en tetes
const discord = require('discord.js')
const client = new discord.Client()
const ch = client.guilds.size

// On start le bot
client.on('ready', () => {
// client.user.setPresence({ streaming: { name: ch + ' serveurs actifs', url: 'https://www.twitch.tv/the_commentary', type: 1 } })
  var opts = {
    name: 'Call of Duty: Black Ops 10',
    url: 'https://www.twitch.tv/lirik',
    type: 1
  }

  client.setStatus(null, opts)

  console.log('-------------------------------------')
  console.log('    [!] ComaBot connecté [!]')
  console.log('-------------------------------------')
})
// Create an event listener for new guild members

/* Partie Ping */
const ping = require('./module/ping.js')
ping(client)

/* Partie Avatar */
const avatar = require('./module/avatar.js')
avatar(client)

/* Partie Musique */
const music = require('./discord.js-music-v11')
music(client)

/* Partie Message Aux Gens */
const message1 = require('./module/message_personne.js')
message1(client)

/* Partie Say */
const say = require('./module/say.js')
say(client)

/* Partie cpasmoi
const cpasmoi = require('./module/cpasmoi.js')
cpasmoi(client) */

/* Partie Verif Role
const verifrole = require('./module/verifrole.js')
verifrole(client) */

/* Partie Help */
const help = require('./module/help.js')
help(client)

/* Partie Kick  */
const kick = require('./module/kick.js')
kick(client)

/* Partie Ban */
const ban = require('./module/ban.js')
ban(client)

/* Partie Teste1
const test1 = require('./module/test1.js')
test1(client) */

var dt = process.env.TOKEN || process.argv[2]

if (!dt) {
  console.log('')
}

client.login(dt)
<commit_msg>Added Files<commit_after>// Mise en place des en tetes
const discord = require('discord.js')
const client = new discord.Client()
const ch = client.guilds.size

// On start le bot
client.on('ready', () => {
  client.user.setPresence({ streaming: { name: ch + ' serveurs actifs', url: 'https://www.twitch.tv/the_commentary', type: 0 } })
  console.log('-------------------------------------')
  console.log('    [!] ComaBot connecté [!]')
  console.log('-------------------------------------')
})
// Create an event listener for new guild members

/* Partie Ping */
const ping = require('./module/ping.js')
ping(client)

/* Partie Avatar */
const avatar = require('./module/avatar.js')
avatar(client)

/* Partie Musique */
const music = require('./discord.js-music-v11')
music(client)

/* Partie Message Aux Gens */
const message1 = require('./module/message_personne.js')
message1(client)

/* Partie Say */
const say = require('./module/say.js')
say(client)

/* Partie cpasmoi
const cpasmoi = require('./module/cpasmoi.js')
cpasmoi(client) */

/* Partie Verif Role
const verifrole = require('./module/verifrole.js')
verifrole(client) */

/* Partie Help */
const help = require('./module/help.js')
help(client)

/* Partie Kick  */
const kick = require('./module/kick.js')
kick(client)

/* Partie Ban */
const ban = require('./module/ban.js')
ban(client)

/* Partie Teste1
const test1 = require('./module/test1.js')
test1(client) */

var dt = process.env.TOKEN || process.argv[2]

if (!dt) {
  console.log('')
}

client.login(dt)
<|endoftext|>


<commit_before>'use strict';

var hashValue = require('./build/Release/hashvalue')
  , SimpleCache = require("simple-lru-cache")
  , parse = require('connection-parse')
  , crypto = require('crypto');

function HashRing(servers, algorithm, options) {
  options = options || {};

  this.algorithm = algorithm || 'md5';

  // Private propperties
  this.ring = [];
  this.size = 0;
  this.servers = parse(servers).servers;
  this.cache = new SimpleCache({
    maxSize: options.maxCacheSize || 5000
  });

  // Override our hasher, which defaults to hashing using the `crypto` module by
  // default.
  if ('crc32' === this.algorithm) {
    this.hash = this.crc32;
  } else if ('function' === typeof this.algorithm) {
    this.hash = this.algorithm;
  }

  // Initialize the hash ring
  this.generate();
}

HashRing.prototype.generate = function generate() {
  var servers = this.servers
    , self = this;

  // Generate the total weight of all the servers
  var total = servers.reduce(function reduce(total, server) {
    return total += server.weight;
  }, 0);

  var index = 0;

  servers.forEach(function each(server) {
    var percentage = server.weight / total
      , length = Math.floor(percentage * 40 * servers.length)
      , key
      , x;

    for (var i = 0; i < length; i++) {
      x = self.digest(server.string +'-'+ i);

      for (var j = 0; j < 3; j++) {
        key = hashValue.hash(x[3 + j * 4], x[2 + j * 4], x[1 + j * 4], x[j * 4]);
        self.ring[index] = new Node(key, server.string);
        index++;
      }
    }
  });

  // Sort the keys
  this.ring = this.ring.sort(function sorted(a, b) {
    return (a.point < b.point)
      ? -1
      : (a.point > b.point)
        ? 1
        : 0;
  });

  this.size = this.ring.length;
};

HashRing.prototype.get = function get(key) {
  var hashValue = this.hashValue(key)
    , ring = this.ring
    , high = this.size
    , low = 0
    , mid;

  // Preform bisection on the array
  while (true) {
    mid = (low + high) >> 1;

    if (mid === this.size) return ring[0].server;

    var middle = ring[mid].point;
    var prev = mid === 0 ? 0 : ring[mid - 1].point;

    if (hashValue <= middle && hashValue > prev) return ring[mid].server;

    if (middle < hashValue) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }

    if (low > high) return ring[0].server;
  }
};

HashRing.prototype.hash = function hash(key) {
  return crypto.createHash(this.algorithm).update().digest();
};

HashRing.prototype.digest = function digest(key) {
  return this.hash(key +'').toString().split('').map(function charCode(char) {
    return char.charCodeAt(0);
  });
};

HashRing.prototype.hashValue = function hasher(key) {
  var x = this.digest(key);

  return hashValue.hash(x[3], x[2], x[1], x[0]);
};

function Node(point, server) {
  this.point = point;
  this.server = server;
}

module.exports = HashRing;
<commit_msg>[minor] Work on restoring the old API<commit_after>'use strict';

var hashValue = require('./build/Release/hashvalue')
  , SimpleCache = require("simple-lru-cache")
  , parse = require('connection-parse')
  , crypto = require('crypto');

/**
 * Add a virtual node parser to the connection string parser.
 *
 * @param {Object} data server data
 * @param {Mixed} value optional value
 * @api private
 */
parse.extension('vnodes', function vnode(data, value) {
  if (value && 'vnodes' in value) {
    data.vnodes = +value.vnodes || 0;
  } else {
    data.vnodes = 0;
  }
});

/**
 * HashRing implements consistent hashing so adding or removing servers of one
 * slot does not significantly change the mapping of the key to slots. The
 * consistent hashing algorithm is based on ketama or libketama.
 *
 * @constructor
 * @param {Mixed} server Servers that need to be added to the ring
 * @param {Mixed} algorithm Either a Crypto compatible algorithm or custom hasher
 * @param {Object} options Optional configuration and options for the ring
 */
function HashRing(servers, algorithm, options) {
  options = options || {};

  // These properties can be configured
  this.algorithm = algorithm || 'md5';
  this.vnode = options.vnode_count || 40;

  // Private properties
  var connections = parse(servers);

  this.ring = [];
  this.size = 0;
  this.vnodes = connections.vnodes;
  this.servers = connections.servers;

  // Set up a ache as we don't want to preform a hashing operation every single
  // time we lookup a key.
  this.cache = new SimpleCache({
    maxSize: options.maxCacheSize || 5000
  });

  // Override the hashing function if people want to use a hashing algorithm
  // that is not supported by Node, for example if you want to MurMur hashing or
  // something else exotic.
  if ('function' === typeof this.algorithm) {
    this.hash = this.algorithm;
  }

  // Generate the continuum of the HashRing.
  this.continuum();
}

/**
 * Generates the continuum of server a.k.a the Hash Ring based on their weights
 * and virtual nodes assigned.
 *
 * @api private
 */
HashRing.prototype.continuum = function generate() {
  var servers = this.servers
    , self = this
    , index = 0
    , total;

  // Generate the total weight of all the servers
  total = servers.reduce(function reduce(total, server) {
    return total += server.weight;
  }, 0);

  servers.forEach(function each(server) {
    var percentage = server.weight / total
      , vnodes = self.vnodes[server] || self.vnodes
      , length = Math.floor(percentage * vnodes * servers.length)
      , key
      , x;

    for (var i = 0; i < length; i++) {
      x = self.digest(server.string +'-'+ i);

      for (var j = 0; j < 3; j++) {
        key = hashValue.hash(x[3 + j * 4], x[2 + j * 4], x[1 + j * 4], x[j * 4]);
        self.ring[index] = new Node(key, server.string);
        index++;
      }
    }
  });

  // Sort the keys
  this.ring = this.ring.sort(function sorted(a, b) {
    return (a.value < b.value) ? -1 : (a.value > b.value) ? 1 : 0;
  });

  this.size = this.ring.length;
};

/**
 * Find the correct node for the key which is closest to the point after what
 * the given key hashes to.
 *
 * @param {String} key
 * @returns {String} server
 * @api public
 */
HashRing.prototype.get = function get(key) {
  var hashValue = this.hashValue(key)
    , ring = this.ring
    , high = this.size
    , low = 0
    , middle
    , prev
    , mid;

  // Preform a search on the array to find the server with the next biggest
  // point after what the given key hashes to
  while (true) {
    mid = (low + high) / 2;

    if (mid === this.size) return ring[0].server;

    middle = ring[mid].value;
    prev = mid === 0 ? 0 : ring[mid - 1].value;

    if (hashValue <= middle && hashValue > prev) return ring[mid].server;

    if (middle < hashValue) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }

    if (low > high) return ring[0].server;
  }
};

/**
 * Generates a hash of the string.
 *
 * @param {String} key
 * @returns {String} hash
 * @api private
 */
HashRing.prototype.hash = function hash(key) {
  return crypto.createHash(this.algorithm).update(key).digest();
};

/**
 * Digest hash so we can make a numeric representation from the hash.
 *
 * @param {String} key The key that needs to be hashed
 * @returns {Array}
 * @api private
 */
HashRing.prototype.digest = function digest(key) {
  return this.hash(key +'').toString().split('').map(function charCode(char) {
    return char.charCodeAt(0);
  });
};

/**
 * None ketama:
 * The following changes are not ported from the ketama algorithm and are hash
 * ring specific. Add, remove or replace servers with as less disruption as
 * possible.
 */

HashRing.prototype.replace = function replace(from, to) {

};

HashRing.prototype.add = function add(servers) {

};

HashRing.prototype.remove = function remove(server) {

};

/**
 * Get the hashed value for the given key
 *
 * @param {String} key
 * @returns {Number}
 * @api private
 */
HashRing.prototype.hashValue = function hasher(key) {
  var x = this.digest(key);

  return hashValue.hash(x[3], x[2], x[1], x[0]);
};

/**
 * A single Node in our hash ring.
 *
 * @constructor
 * @param {Number} hashvalue
 * @param {String} server
 * @api private
 */
function Node(hashvalue, server) {
  this.value = hashvalue;
  this.server = server;
}

/**
 * Set up the legacy API aliases.
 *
 * @api public
 */
HashRing.prototype.replaceServer = HashRing.prototype.replace;
HashRing.prototype.removeServer = HashRing.prototype.remove;
HashRing.prototype.addServer = HashRing.prototype.add;
HashRing.prototype.getNode = HashRing.prototype.get;

/**
 * Expose the module.
 *
 * @api public
 */
module.exports = HashRing;
<|endoftext|>


<commit_before>import tweenState from 'react-tween-state';
import NativeButton from './NativeButton';
import styles from './styles';

import React, {
  Component,
} from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';

import {
  PanResponder,
  TouchableHighlight,
  StyleSheet,
  Text,
  View,
  ViewPropTypes,
} from 'react-native';

const SwipeoutBtn = createReactClass({

  propTypes: {
    backgroundColor: PropTypes.string,
    color: PropTypes.string,
    component: PropTypes.node,
    onPress: PropTypes.func,
    text: PropTypes.string,
    type: PropTypes.string,
    underlayColor: PropTypes.string,
  },

  getDefaultProps: function() {
    return {
      backgroundColor: null,
      color: null,
      component: null,
      underlayColor: null,
      height: 0,
      onPress: null,
      disabled: false,
      text: 'Click me',
      type: '',
      width: 0,
    };
  },

  render: function() {
    var btn = this.props;

    var styleSwipeoutBtn = [styles.swipeoutBtn];

    //  apply "type" styles (delete || primary || secondary)
    if (btn.type === 'delete') styleSwipeoutBtn.push(styles.colorDelete);
    else if (btn.type === 'primary') styleSwipeoutBtn.push(styles.colorPrimary);
    else if (btn.type === 'secondary') styleSwipeoutBtn.push(styles.colorSecondary);

    //  apply background color
    if (btn.backgroundColor) styleSwipeoutBtn.push([{ backgroundColor: btn.backgroundColor }]);

    styleSwipeoutBtn.push([{
      height: btn.height,
      width: btn.width,
    }]);

    var styleSwipeoutBtnComponent = [];

    //  set button dimensions
    styleSwipeoutBtnComponent.push([{
      height: btn.height,
      width: btn.width,
    }]);

    var styleSwipeoutBtnText = [styles.swipeoutBtnText];

    //  apply text color
    if (btn.color) styleSwipeoutBtnText.push([{ color: btn.color }]);

    return  (
      <NativeButton
        onPress={this.props.onPress}
        underlayColor={this.props.underlayColor}
        disabled={this.props.disabled}
        style={[styles.swipeoutBtnTouchable, styleSwipeoutBtn]}
        textStyle={styleSwipeoutBtnText}>
        {
          (btn.component ?
            <View style={styleSwipeoutBtnComponent}>{btn.component}</View>
            :
            btn.text
          )
        }
      </NativeButton>
    );
  }
});

const Swipeout = createReactClass({
  mixins: [tweenState.Mixin],

  propTypes: {
    autoClose: PropTypes.bool,
    backgroundColor: PropTypes.string,
    close: PropTypes.bool,
    left: PropTypes.array,
    onOpen: PropTypes.func,
    onClose: PropTypes.func,
    right: PropTypes.array,
    scroll: PropTypes.func,
    style: ViewPropTypes.style,
    sensitivity: PropTypes.number,
    buttonWidth: PropTypes.number,
    disabled: PropTypes.bool,
  },

  getDefaultProps: function() {
    return {
      disabled: false,
      rowID: -1,
      sectionID: -1,
      sensitivity: 50,
    };
  },

  getInitialState: function() {
    return {
      autoClose: this.props.autoClose || false,
      btnWidth: 0,
      btnsLeftWidth: 0,
      btnsRightWidth: 0,
      contentHeight: 0,
      contentPos: 0,
      contentWidth: 0,
      openedRight: false,
      swiping: false,
      tweenDuration: 160,
      timeStart: null,
    };
  },

  componentWillMount: function() {
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (event, gestureState) => true,
      onStartShouldSetPanResponderCapture: (event, gestureState) =>
        this.state.openedLeft || this.state.openedRight,
      onMoveShouldSetPanResponder: (event, gestureState) =>
        Math.abs(gestureState.dx) > this.props.sensitivity &&
        Math.abs(gestureState.dy) <= this.props.sensitivity,
      onPanResponderGrant: this._handlePanResponderGrant,
      onPanResponderMove: this._handlePanResponderMove,
      onPanResponderRelease: this._handlePanResponderEnd,
      onPanResponderTerminate: this._handlePanResponderEnd,
      onShouldBlockNativeResponder: (event, gestureState) => false,
      onPanResponderTerminationRequest: () => false,
    });
  },

  componentWillReceiveProps: function(nextProps) {
    if (nextProps.close) this._close();
  },

  _handlePanResponderGrant: function(e: Object, gestureState: Object) {
    if (this.props.disabled) return;
    this.refs.swipeoutContent.measure((ox, oy, width, height) => {
      let buttonWidth = this.props.buttonWidth || (width/5);
      this.setState({
        btnWidth: buttonWidth,
        btnsLeftWidth: this.props.left ? buttonWidth*this.props.left.length : 0,
        btnsRightWidth: this.props.right ? buttonWidth*this.props.right.length : 0,
        swiping: true,
        timeStart: (new Date()).getTime(),
      });
    });
  },

  _handlePanResponderMove: function(e: Object, gestureState: Object) {
    if (this.props.disabled) return;
    var posX = gestureState.dx;
    var posY = gestureState.dy;
    var leftWidth = this.state.btnsLeftWidth;
    var rightWidth = this.state.btnsRightWidth;
    if (this.state.openedRight) var posX = gestureState.dx - rightWidth;
    else if (this.state.openedLeft) var posX = gestureState.dx + leftWidth;

    //  prevent scroll if moveX is true
    var moveX = Math.abs(posX) > Math.abs(posY);
    if (this.props.scroll) {
      if (moveX) this.props.scroll(false);
      else this.props.scroll(true);
    }
    if (this.state.swiping) {
      //  move content to reveal swipeout
      if (posX < 0 && this.props.right) {
        this.setState({ contentPos: Math.min(posX, 0) })
      } else if (posX > 0 && this.props.left) {
        this.setState({ contentPos: Math.max(posX, 0) })
      };
    }
  },

  _handlePanResponderEnd: function(e: Object, gestureState: Object) {
    if (this.props.disabled) return;
    var posX = gestureState.dx;
    var contentPos = this.state.contentPos;
    var contentWidth = this.state.contentWidth;
    var btnsLeftWidth = this.state.btnsLeftWidth;
    var btnsRightWidth = this.state.btnsRightWidth;

    //  minimum threshold to open swipeout
    var openX = contentWidth*0.33;

    //  should open swipeout
    var openLeft = posX > openX || posX > btnsLeftWidth/2;
    var openRight = posX < -openX || posX < -btnsRightWidth/2;

    //  account for open swipeouts
    if (this.state.openedRight) var openRight = posX-openX < -openX;
    if (this.state.openedLeft) var openLeft = posX+openX > openX;

    //  reveal swipeout on quick swipe
    var timeDiff = (new Date()).getTime() - this.state.timeStart < 200;
    if (timeDiff) {
      var openRight = posX < -openX/10 && !this.state.openedLeft;
      var openLeft = posX > openX/10 && !this.state.openedRight;
    }

    if (this.state.swiping) {
      if (openRight && contentPos < 0 && posX < 0) {
        this._open(-btnsRightWidth, 'right');
      } else if (openLeft && contentPos > 0 && posX > 0) {
        this._open(btnsLeftWidth, 'left');
      } else {
        this._close();
      }
    }

    //  Allow scroll
    if (this.props.scroll) this.props.scroll(true);
  },

  _tweenContent: function(state, endValue) {
    this.tweenState(state, {
      easing: tweenState.easingTypes.easeInOutQuad,
      duration: endValue === 0 ? this.state.tweenDuration*1.5 : this.state.tweenDuration,
      endValue: endValue,
    });
  },

  _rubberBandEasing: function(value, limit) {
    if (value < 0 && value < limit) return limit - Math.pow(limit - value, 0.85);
    else if (value > 0 && value > limit) return limit + Math.pow(value - limit, 0.85);
    return value;
  },

  //  close swipeout on button press
  _autoClose: function(btn) {
    if (this.state.autoClose) this._close();
    var onPress = btn.onPress;
    if (onPress) onPress();
  },

  _open: function(contentPos, direction) {
    const left = direction === 'left';
    const { sectionID, rowID, onOpen } = this.props;
    onOpen && onOpen(sectionID, rowID, direction);
    this._tweenContent('contentPos', contentPos);
    this.setState({
      contentPos,
      openedLeft: left,
      openedRight: !left,
      swiping: false,
    });
  },

  _close: function() {
    const { sectionID, rowID, onClose } = this.props;
    if (onClose && (this.state.openedLeft || this.state.openedRight)) {
      const direction = this.state.openedRight ? 'right' : 'left';
      onClose(sectionID, rowID, direction);
    }
    this._tweenContent('contentPos', 0);
    this.setState({
      openedRight: false,
      openedLeft: false,
      swiping: false,
    });
  },

  render: function() {
    var contentWidth = this.state.contentWidth;
    var posX = this.getTweeningValue('contentPos');

    var styleSwipeout = [styles.swipeout, this.props.style];
    if (this.props.backgroundColor) {
      styleSwipeout.push([{ backgroundColor: this.props.backgroundColor }]);
    }

    var limit = -this.state.btnsRightWidth;
    if (posX > 0) var limit = this.state.btnsLeftWidth;

    var styleLeftPos = {
      left: {
        left: 0,
        overflow: 'hidden',
        width: Math.min(limit*(posX/limit), limit),
      },
    };
    var styleRightPos = {
      right: {
        left: Math.abs(contentWidth + Math.max(limit, posX)),
        right: 0,
      },
    };
    var styleContentPos = {
      content: {
        left: this._rubberBandEasing(posX, limit),
      },
    };

    var styleContent = [styles.swipeoutContent];
    styleContent.push(styleContentPos.content);

    var styleRight = [styles.swipeoutBtns];
    styleRight.push(styleRightPos.right);

    var styleLeft = [styles.swipeoutBtns];
    styleLeft.push(styleLeftPos.left);

    var isRightVisible = posX < 0;
    var isLeftVisible = posX > 0;

    return (
      <View style={styleSwipeout}>
        <View
          ref="swipeoutContent"
          style={styleContent}
          onLayout={this._onLayout}
          {...this._panResponder.panHandlers}
        >
          {this.props.children}
        </View>
        { this._renderButtons(this.props.right, isRightVisible, styleRight) }
        { this._renderButtons(this.props.left, isLeftVisible, styleLeft) }
      </View>
    );
  },

  _onLayout: function(event) {
    var { width, height } = event.nativeEvent.layout;
    this.setState({
      contentWidth: width,
      contentHeight: height,
    });
  },

  _renderButtons: function(buttons, isVisible, style) {
    if (buttons && isVisible) {
      return( <View style={style}>
        { buttons.map(this._renderButton) }
      </View>);
    } else {
      return (
        <View/>
      );
    }
  },

  _renderButton: function(btn, i) {
    return (
      <SwipeoutBtn
        backgroundColor={btn.backgroundColor}
        color={btn.color}
        component={btn.component}
        disabled={btn.disabled}
        height={this.state.contentHeight}
        key={i}
        onPress={() => this._autoClose(btn)}
        text={btn.text}
        type={btn.type}
        underlayColor={btn.underlayColor}
        width={this.state.btnWidth}
      />
    );
  }
})

Swipeout.NativeButton = NativeButton;
Swipeout.SwipeoutButton = SwipeoutBtn;

export default Swipeout;
<commit_msg>Swipe menu manual open (#161)<commit_after>import tweenState from 'react-tween-state';
import NativeButton from './NativeButton';
import styles from './styles';

import React, {
  Component,
} from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';

import {
  PanResponder,
  TouchableHighlight,
  StyleSheet,
  Text,
  View,
  ViewPropTypes,
} from 'react-native';

const SwipeoutBtn = createReactClass({

  propTypes: {
    backgroundColor: PropTypes.string,
    color: PropTypes.string,
    component: PropTypes.node,
    onPress: PropTypes.func,
    text: PropTypes.string,
    type: PropTypes.string,
    underlayColor: PropTypes.string,
  },

  getDefaultProps: function() {
    return {
      backgroundColor: null,
      color: null,
      component: null,
      underlayColor: null,
      height: 0,
      onPress: null,
      disabled: false,
      text: 'Click me',
      type: '',
      width: 0,
    };
  },

  render: function() {
    var btn = this.props;

    var styleSwipeoutBtn = [styles.swipeoutBtn];

    //  apply "type" styles (delete || primary || secondary)
    if (btn.type === 'delete') styleSwipeoutBtn.push(styles.colorDelete);
    else if (btn.type === 'primary') styleSwipeoutBtn.push(styles.colorPrimary);
    else if (btn.type === 'secondary') styleSwipeoutBtn.push(styles.colorSecondary);

    //  apply background color
    if (btn.backgroundColor) styleSwipeoutBtn.push([{ backgroundColor: btn.backgroundColor }]);

    styleSwipeoutBtn.push([{
      height: btn.height,
      width: btn.width,
    }]);

    var styleSwipeoutBtnComponent = [];

    //  set button dimensions
    styleSwipeoutBtnComponent.push([{
      height: btn.height,
      width: btn.width,
    }]);

    var styleSwipeoutBtnText = [styles.swipeoutBtnText];

    //  apply text color
    if (btn.color) styleSwipeoutBtnText.push([{ color: btn.color }]);

    return  (
      <NativeButton
        onPress={this.props.onPress}
        underlayColor={this.props.underlayColor}
        disabled={this.props.disabled}
        style={[styles.swipeoutBtnTouchable, styleSwipeoutBtn]}
        textStyle={styleSwipeoutBtnText}>
        {
          (btn.component ?
            <View style={styleSwipeoutBtnComponent}>{btn.component}</View>
            :
            btn.text
          )
        }
      </NativeButton>
    );
  }
});

const Swipeout = createReactClass({
  mixins: [tweenState.Mixin],

  propTypes: {
    autoClose: PropTypes.bool,
    backgroundColor: PropTypes.string,
    close: PropTypes.bool,
    left: PropTypes.array,
    onOpen: PropTypes.func,
    onClose: PropTypes.func,
    right: PropTypes.array,
    scroll: PropTypes.func,
    style: ViewPropTypes.style,
    sensitivity: PropTypes.number,
    buttonWidth: PropTypes.number,
    disabled: PropTypes.bool,
  },

  getDefaultProps: function() {
    return {
      disabled: false,
      rowID: -1,
      sectionID: -1,
      sensitivity: 50,
    };
  },

  getInitialState: function() {
    return {
      autoClose: this.props.autoClose || false,
      btnWidth: 0,
      btnsLeftWidth: 0,
      btnsRightWidth: 0,
      contentHeight: 0,
      contentPos: 0,
      contentWidth: 0,
      openedRight: false,
      swiping: false,
      tweenDuration: 160,
      timeStart: null,
    };
  },

  componentWillMount: function() {
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (event, gestureState) => true,
      onStartShouldSetPanResponderCapture: (event, gestureState) =>
        this.state.openedLeft || this.state.openedRight,
      onMoveShouldSetPanResponderCapture: (event, gestureState) =>
        Math.abs(gestureState.dx) > this.props.sensitivity &&
        Math.abs(gestureState.dy) <= this.props.sensitivity,
      onPanResponderGrant: this._handlePanResponderGrant,
      onPanResponderMove: this._handlePanResponderMove,
      onPanResponderRelease: this._handlePanResponderEnd,
      onPanResponderTerminate: this._handlePanResponderEnd,
      onShouldBlockNativeResponder: (event, gestureState) => false,
      onPanResponderTerminationRequest: () => false,
    });
  },

  componentWillReceiveProps: function(nextProps) {
    if (nextProps.close) this._close();
    if (nextProps.openRight) this._openRight();
    if (nextProps.openLeft) this._openLeft();
  },

  _handlePanResponderGrant: function(e: Object, gestureState: Object) {
    if (this.props.disabled) return;
    if (!this.state.openedLeft && !this.state.openedRight) {
      this._callOnOpen();
    } else {
      this._callOnClose();
    }
    this.refs.swipeoutContent.measure((ox, oy, width, height) => {
      let buttonWidth = this.props.buttonWidth || (width/5);
      this.setState({
        btnWidth: buttonWidth,
        btnsLeftWidth: this.props.left ? buttonWidth*this.props.left.length : 0,
        btnsRightWidth: this.props.right ? buttonWidth*this.props.right.length : 0,
        swiping: true,
        timeStart: (new Date()).getTime(),
      });
    });
  },

  _handlePanResponderMove: function(e: Object, gestureState: Object) {
    if (this.props.disabled) return;
    var posX = gestureState.dx;
    var posY = gestureState.dy;
    var leftWidth = this.state.btnsLeftWidth;
    var rightWidth = this.state.btnsRightWidth;
    if (this.state.openedRight) var posX = gestureState.dx - rightWidth;
    else if (this.state.openedLeft) var posX = gestureState.dx + leftWidth;

    //  prevent scroll if moveX is true
    var moveX = Math.abs(posX) > Math.abs(posY);
    if (this.props.scroll) {
      if (moveX) this.props.scroll(false);
      else this.props.scroll(true);
    }
    if (this.state.swiping) {
      //  move content to reveal swipeout
      if (posX < 0 && this.props.right) {
        this.setState({ contentPos: Math.min(posX, 0) })
      } else if (posX > 0 && this.props.left) {
        this.setState({ contentPos: Math.max(posX, 0) })
      };
    }
  },

  _handlePanResponderEnd: function(e: Object, gestureState: Object) {
    if (this.props.disabled) return;
    var posX = gestureState.dx;
    var contentPos = this.state.contentPos;
    var contentWidth = this.state.contentWidth;
    var btnsLeftWidth = this.state.btnsLeftWidth;
    var btnsRightWidth = this.state.btnsRightWidth;

    //  minimum threshold to open swipeout
    var openX = contentWidth*0.33;

    //  should open swipeout
    var openLeft = posX > openX || posX > btnsLeftWidth/2;
    var openRight = posX < -openX || posX < -btnsRightWidth/2;

    //  account for open swipeouts
    if (this.state.openedRight) var openRight = posX-openX < -openX;
    if (this.state.openedLeft) var openLeft = posX+openX > openX;

    //  reveal swipeout on quick swipe
    var timeDiff = (new Date()).getTime() - this.state.timeStart < 200;
    if (timeDiff) {
      var openRight = posX < -openX/10 && !this.state.openedLeft;
      var openLeft = posX > openX/10 && !this.state.openedRight;
    }

    if (this.state.swiping) {
      if (openRight && contentPos < 0 && posX < 0) {
        this._open(-btnsRightWidth, 'right');
      } else if (openLeft && contentPos > 0 && posX > 0) {
        this._open(btnsLeftWidth, 'left');
      } else {
        this._close();
      }
    }

    //  Allow scroll
    if (this.props.scroll) this.props.scroll(true);
  },

  _tweenContent: function(state, endValue) {
    this.tweenState(state, {
      easing: tweenState.easingTypes.easeInOutQuad,
      duration: endValue === 0 ? this.state.tweenDuration*1.5 : this.state.tweenDuration,
      endValue: endValue,
    });
  },

  _rubberBandEasing: function(value, limit) {
    if (value < 0 && value < limit) return limit - Math.pow(limit - value, 0.85);
    else if (value > 0 && value > limit) return limit + Math.pow(value - limit, 0.85);
    return value;
  },

  //  close swipeout on button press
  _autoClose: function(btn) {
    if (this.state.autoClose) this._close();
    var onPress = btn.onPress;
    if (onPress) onPress();
  },

  _open: function(contentPos, direction) {
    const left = direction === 'left';
    const { sectionID, rowID, onOpen } = this.props;
    onOpen && onOpen(sectionID, rowID, direction);
    this._tweenContent('contentPos', contentPos);
    this.setState({
      contentPos,
      openedLeft: left,
      openedRight: !left,
      swiping: false,
    });
  },

  _close: function() {
    const { sectionID, rowID, onClose } = this.props;
    if (onClose && (this.state.openedLeft || this.state.openedRight)) {
      const direction = this.state.openedRight ? 'right' : 'left';
      onClose(sectionID, rowID, direction);
    }
    this._tweenContent('contentPos', 0);
    this._callOnClose();
    this.setState({
      openedRight: false,
      openedLeft: false,
      swiping: false,
    });
  },

  _callOnClose: function() {
    if (this.props.onClose) this.props.onClose(this.props.sectionID, this.props.rowID);
  },

  _callOnOpen: function() {
    if (this.props.onOpen) this.props.onOpen(this.props.sectionID, this.props.rowID);
  },

  _openRight: function() {
    this.refs.swipeoutContent.measure((ox, oy, width, height) => {
      this.setState({
        btnWidth: (width/5),
        btnsRightWidth: this.props.right ? (width/5)*this.props.right.length : 0,
      }, () => {
        this._tweenContent('contentPos', -this.state.btnsRightWidth);
        this._callOnOpen();
        this.setState({
          contentPos: -this.state.btnsRightWidth,
          openedLeft: false,
          openedRight: true,
          swiping: false
        });
      });
    });
  },

  _openLeft: function() {
    this.refs.swipeoutContent.measure((ox, oy, width, height) => {
      this.setState({
        btnWidth: (width/5),
        btnsLeftWidth: this.props.left ? (width/5)*this.props.left.length : 0,
      }, () => {
        this._tweenContent('contentPos', this.state.btnsLeftWidth);
        this._callOnOpen();
        this.setState({
          contentPos: this.state.btnsLeftWidth,
          openedLeft: true,
          openedRight: false,
          swiping: false
        });
      });
    });
  },

  render: function() {
    var contentWidth = this.state.contentWidth;
    var posX = this.getTweeningValue('contentPos');

    var styleSwipeout = [styles.swipeout, this.props.style];
    if (this.props.backgroundColor) {
      styleSwipeout.push([{ backgroundColor: this.props.backgroundColor }]);
    }

    var limit = -this.state.btnsRightWidth;
    if (posX > 0) var limit = this.state.btnsLeftWidth;

    var styleLeftPos = {
      left: {
        left: 0,
        overflow: 'hidden',
        width: Math.min(limit*(posX/limit), limit),
      },
    };
    var styleRightPos = {
      right: {
        left: Math.abs(contentWidth + Math.max(limit, posX)),
        right: 0,
      },
    };
    var styleContentPos = {
      content: {
        left: this._rubberBandEasing(posX, limit),
      },
    };

    var styleContent = [styles.swipeoutContent];
    styleContent.push(styleContentPos.content);

    var styleRight = [styles.swipeoutBtns];
    styleRight.push(styleRightPos.right);

    var styleLeft = [styles.swipeoutBtns];
    styleLeft.push(styleLeftPos.left);

    var isRightVisible = posX < 0;
    var isLeftVisible = posX > 0;

    return (
      <View style={styleSwipeout}>
        <View
          ref="swipeoutContent"
          style={styleContent}
          onLayout={this._onLayout}
          {...this._panResponder.panHandlers}
        >
          {this.props.children}
        </View>
        { this._renderButtons(this.props.right, isRightVisible, styleRight) }
        { this._renderButtons(this.props.left, isLeftVisible, styleLeft) }
      </View>
    );
  },

  _onLayout: function(event) {
    var { width, height } = event.nativeEvent.layout;
    this.setState({
      contentWidth: width,
      contentHeight: height,
    });
  },

  _renderButtons: function(buttons, isVisible, style) {
    if (buttons && isVisible) {
      return( <View style={style}>
        { buttons.map(this._renderButton) }
      </View>);
    } else {
      return (
        <View/>
      );
    }
  },

  _renderButton: function(btn, i) {
    return (
      <SwipeoutBtn
        backgroundColor={btn.backgroundColor}
        color={btn.color}
        component={btn.component}
        disabled={btn.disabled}
        height={this.state.contentHeight}
        key={i}
        onPress={() => this._autoClose(btn)}
        text={btn.text}
        type={btn.type}
        underlayColor={btn.underlayColor}
        width={this.state.btnWidth}
      />
    );
  }
})

Swipeout.NativeButton = NativeButton;
Swipeout.SwipeoutButton = SwipeoutBtn;

export default Swipeout;
<|endoftext|>


<commit_before>/*
	Copyright 2013-2014, Marten de Vries

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/

"use strict";

//TODO: call http equivalent if http adapter

var Promise = require("bluebird");

var coucheval = require("../utils/coucheval.js");
var addCallback = require("../utils/promisewrapper.js");
var couchdb_objects = require("../couchdb-objects");

function addOldDoc(db, id, args) {
  return db.get(id).then(function (err) {
    args.push(null);
    return args;
  }, function (doc) {
    args.push(doc);
    return args;
  });
}

function doValidation(db, newDoc, options, callback) {
  //a new promise because sometimes it's possible to declare a
  //document valid early on in the process.
  return new Promise(function (resolve, reject) {
    function doActualValidation(args) {
      var validationFuncs = args[0];
      var newOptions = args[1];
      var oldDoc = args[2];

      try {
        validationFuncs.forEach(function (validationFunc) {
          validationFunc(newDoc, oldDoc, newOptions.userCtx, newOptions.secObj);
        });
      } catch (e) {
        if (typeof e.unauthorized !== "undefined") {
          reject({
            error: "unauthorized",
            reason: e.unauthorized,
            status: 401
          });
        } else if (typeof e.forbidden !== "undefined") {
          reject({
            error: "forbidden",
            reason: e.forbidden,
            status: 403
          });
        } else {
          reject(coucheval.wrapExecutionError(e));
        }
        throw "done";
      }
      //passed all validation functions -> success
      resolve();
    }

    if ((newDoc._id || "").indexOf("_design/") === 0) {
      //a design document -> always validates succesful.
      resolve();
      //done
      return;
    }
    //gather required data
    var validationFuncsPromise = getValidationFunctions(db).then(function (validationFuncs) {
      if (!validationFuncs.length) {
        resolve();
        throw "done";
      }
      return validationFuncs;
    });
    var completeOptionsPromise = completeValidationOptions(db, options);

    Promise.all([validationFuncsPromise, completeOptionsPromise]).then(function (args) {
      //gather last piece of data & start the actual validation
      addOldDoc(db, newDoc._id, args).then(doActualValidation);
    }).catch(reject);
  });
}

function completeValidationOptions(db, options) {
  if (!options) {
    options = {};
  }
  if (!options.secObj) {
    options.secObj = couchdb_objects.buildSecurityObject();
  }
  if (!options.userCtx) {
    var buildUserContext = couchdb_objects.buildUserContextObject;
    return db.info().then(buildUserContext).then(function (userCtx) {
      options.userCtx = userCtx;
      return options;
    });
  }
  return Promise.resolve(options);
}

function getValidationFunctions(db, callback) {
  return db.allDocs({
    startkey: "_design/",
    endkey: "_design0",
    include_docs: true
  }).then(parseValidationFunctions);
}

function parseValidationFunctions(resp) {
  var validationFuncs = resp.rows.map(function (row) {
    return {
      doc: row.doc,
      func: row.doc.validate_doc_update
    };
  });
  validationFuncs = validationFuncs.filter(function (info) {
    return typeof info.func !== "undefined";
  });
  validationFuncs = validationFuncs.map(function (info) {
    //convert str -> function
    return coucheval.evaluate(info.doc, {}, info.func);
  });
  return validationFuncs;
}

function processArgs(db, callback, options) {
  if (!callback) {
    callback = options;
    options = {};
  }
  return {
    db: db,
    callback: callback,
    options: options
  };
}

exports.validatingPut = function (doc, options, callback) {
  var args = processArgs(this, callback, options);
  var promise = doValidation(args.db, doc, args.options).then(function () {
    return args.db.put(doc, args.options);
  });
  addCallback(promise, callback);
  return promise;
};

exports.validatingPost = function (doc, options, callback) {
  //fixme: see bulkDocs: set id if not one already early.
  var args = processArgs(this, callback, options);
  var promise = doValidation(args.db, doc, args.options).then(function () {
    return args.db.post(doc, args.options);
  });
  addCallback(promise, callback);
  return promise;
};

exports.validatingRemove = function (doc, options, callback) {
  var args = processArgs(this, callback, options);

  doc._deleted = true;
  var promise = doValidation(args.db, doc, args.options).then(function () {
    return args.db.remove(doc, args.options);
  });
  addCallback(promise, callback);
  return promise;
};

exports.validatingBulkDocs = function (bulkDocs, options, callback) {
  //the ``all_or_nothing`` attribute on ``bulkDocs`` is unsupported.
  //Also, the result array might not be in the same order as
  //``bulkDocs.docs``
  var args = processArgs(this, callback, options);

  var done = [];
  var todo = [];

  var validations = bulkDocs.docs.map(function (doc) {
    return doValidation(args.db, doc, args.options).then(function (resp) {
      todo.push(doc);
    }, function (err) {
      //FIXME: _id should be set by this moment. As should it in
      //post. Fix that (using db.id(), which is private but I guess
      //acceptable in this case.)
      err.id = doc._id;
      done.push(err);
    });
  });
  var promise = Promise.all(validations).then(function () {
    return args.db.bulkDocs({docs: todo}, args.options);
  }).then(function (insertedDocs) {
    return done.concat(insertedDocs);
  });
  addCallback(promise, callback);
  return promise;
};

var vpa = function (docId, attachmentId, rev, attachment, type, options, callback) {
  var args = processArgs(this, callback, options);

  //get the doc
  var promise = args.db.get(docId, {rev: rev}).catch(function (err) {
    //TODO: check if the thingy should have a _rev already here.
    //and is that even possible?
    return {_id: docId};
  }).then(function (doc) {
    //validate the doc + attachment
    doc._attachments = doc._attachments || {};
    doc._attachments[attachmentId] = {
      content_type: type,
      data: attachment,
    };
    return doValidation(args.db, doc, args.options);
  }).then(function () {
    //save the attachment
    return args.db.putAttachment(docId, attachmentId, rev, attachment, type);
  });
  addCallback(promise, callback);
  return promise;
};
exports.validatingPutAttachment = vpa;

var vra = function (docId, attachmentId, rev, options, callback) {
  var args = processArgs(this, callback, options);
  //get the doc
  var promise = args.db.get(docId, {rev: rev}).then(function (doc) {
    //validate the doc without attachment
    delete doc._attachments[attachmentId];

    return doValidation(args.db, doc, args.options);
  }).then(function () {
    //remove the attachment
    return args.db.removeAttachment(docId, attachmentId, rev);
  });
  addCallback(promise, callback);
  return promise;
};
exports.validatingRemoveAttachment = vra;
<commit_msg>All JS are now Node modules of their own, that could even be published to the registry if necessary. For now just there's a script that links them locally (and installs all their dependencies).<commit_after>/*
	Copyright 2013-2014, Marten de Vries

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/

"use strict";

//TODO: call http equivalent if http adapter

var Promise = require("bluebird");

var coucheval = require("couchdb-eval");
var couchdb_objects = require("couchdb-objects");
var nodify = require("promise-nodify");

function addOldDoc(db, id, args) {
  return db.get(id).then(function (err) {
    args.push(null);
    return args;
  }, function (doc) {
    args.push(doc);
    return args;
  });
}

function doValidation(db, newDoc, options, callback) {
  //a new promise because sometimes it's possible to declare a
  //document valid early on in the process.
  return new Promise(function (resolve, reject) {
    function doActualValidation(args) {
      var validationFuncs = args[0];
      var newOptions = args[1];
      var oldDoc = args[2];

      try {
        validationFuncs.forEach(function (validationFunc) {
          validationFunc(newDoc, oldDoc, newOptions.userCtx, newOptions.secObj);
        });
      } catch (e) {
        if (typeof e.unauthorized !== "undefined") {
          reject({
            error: "unauthorized",
            reason: e.unauthorized,
            status: 401
          });
        } else if (typeof e.forbidden !== "undefined") {
          reject({
            error: "forbidden",
            reason: e.forbidden,
            status: 403
          });
        } else {
          reject(coucheval.wrapExecutionError(e));
        }
        throw "done";
      }
      //passed all validation functions -> success
      resolve();
    }

    if ((newDoc._id || "").indexOf("_design/") === 0) {
      //a design document -> always validates succesful.
      resolve();
      //done
      return;
    }
    //gather required data
    var validationFuncsPromise = getValidationFunctions(db).then(function (validationFuncs) {
      if (!validationFuncs.length) {
        resolve();
        throw "done";
      }
      return validationFuncs;
    });
    var completeOptionsPromise = completeValidationOptions(db, options);

    Promise.all([validationFuncsPromise, completeOptionsPromise]).then(function (args) {
      //gather last piece of data & start the actual validation
      addOldDoc(db, newDoc._id, args).then(doActualValidation);
    }).catch(reject);
  });
}

function completeValidationOptions(db, options) {
  if (!options) {
    options = {};
  }
  if (!options.secObj) {
    options.secObj = couchdb_objects.buildSecurityObject();
  }
  if (!options.userCtx) {
    var buildUserContext = couchdb_objects.buildUserContextObject;
    return db.info().then(buildUserContext).then(function (userCtx) {
      options.userCtx = userCtx;
      return options;
    });
  }
  return Promise.resolve(options);
}

function getValidationFunctions(db, callback) {
  return db.allDocs({
    startkey: "_design/",
    endkey: "_design0",
    include_docs: true
  }).then(parseValidationFunctions);
}

function parseValidationFunctions(resp) {
  var validationFuncs = resp.rows.map(function (row) {
    return {
      doc: row.doc,
      func: row.doc.validate_doc_update
    };
  });
  validationFuncs = validationFuncs.filter(function (info) {
    return typeof info.func !== "undefined";
  });
  validationFuncs = validationFuncs.map(function (info) {
    //convert str -> function
    return coucheval.evaluate(info.doc, {}, info.func);
  });
  return validationFuncs;
}

function processArgs(db, callback, options) {
  if (!callback) {
    callback = options;
    options = {};
  }
  return {
    db: db,
    callback: callback,
    options: options
  };
}

exports.validatingPut = function (doc, options, callback) {
  var args = processArgs(this, callback, options);
  var promise = doValidation(args.db, doc, args.options).then(function () {
    return args.db.put(doc, args.options);
  });
  nodify(promise, callback);
  return promise;
};

exports.validatingPost = function (doc, options, callback) {
  //fixme: see bulkDocs: set id if not one already early.
  var args = processArgs(this, callback, options);
  var promise = doValidation(args.db, doc, args.options).then(function () {
    return args.db.post(doc, args.options);
  });
  nodify(promise, callback);
  return promise;
};

exports.validatingRemove = function (doc, options, callback) {
  var args = processArgs(this, callback, options);

  doc._deleted = true;
  var promise = doValidation(args.db, doc, args.options).then(function () {
    return args.db.remove(doc, args.options);
  });
  nodify(promise, callback);
  return promise;
};

exports.validatingBulkDocs = function (bulkDocs, options, callback) {
  //the ``all_or_nothing`` attribute on ``bulkDocs`` is unsupported.
  //Also, the result array might not be in the same order as
  //``bulkDocs.docs``
  var args = processArgs(this, callback, options);

  var done = [];
  var todo = [];

  var validations = bulkDocs.docs.map(function (doc) {
    return doValidation(args.db, doc, args.options).then(function (resp) {
      todo.push(doc);
    }, function (err) {
      //FIXME: _id should be set by this moment. As should it in
      //post. Fix that (using db.id(), which is private but I guess
      //acceptable in this case.)
      err.id = doc._id;
      done.push(err);
    });
  });
  var promise = Promise.all(validations).then(function () {
    return args.db.bulkDocs({docs: todo}, args.options);
  }).then(function (insertedDocs) {
    return done.concat(insertedDocs);
  });
  nodify(promise, callback);
  return promise;
};

var vpa = function (docId, attachmentId, rev, attachment, type, options, callback) {
  var args = processArgs(this, callback, options);

  //get the doc
  var promise = args.db.get(docId, {rev: rev}).catch(function (err) {
    //TODO: check if the thingy should have a _rev already here.
    //and is that even possible?
    return {_id: docId};
  }).then(function (doc) {
    //validate the doc + attachment
    doc._attachments = doc._attachments || {};
    doc._attachments[attachmentId] = {
      content_type: type,
      data: attachment,
    };
    return doValidation(args.db, doc, args.options);
  }).then(function () {
    //save the attachment
    return args.db.putAttachment(docId, attachmentId, rev, attachment, type);
  });
  nodify(promise, callback);
  return promise;
};
exports.validatingPutAttachment = vpa;

var vra = function (docId, attachmentId, rev, options, callback) {
  var args = processArgs(this, callback, options);
  //get the doc
  var promise = args.db.get(docId, {rev: rev}).then(function (doc) {
    //validate the doc without attachment
    delete doc._attachments[attachmentId];

    return doValidation(args.db, doc, args.options);
  }).then(function () {
    //remove the attachment
    return args.db.removeAttachment(docId, attachmentId, rev);
  });
  nodify(promise, callback);
  return promise;
};
exports.validatingRemoveAttachment = vra;
<|endoftext|>


<commit_before>var path = require('path');
var os = require('os');
var notifier = require('node-notifier');

var DEFAULT_LOGO = path.join(__dirname, 'logo.png');

var WebpackNotifierPlugin = module.exports = function(options) {
    this.options = options || {};
    this.lastBuildSucceeded = false;
};

WebpackNotifierPlugin.prototype.compileMessage = function(stats) {
    var error;
    if (stats.hasErrors()) {
        error = stats.compilation.errors[0];

    } else if (stats.hasWarnings() && !this.options.excludeWarnings) {
        error = stats.compilation.warnings[0];

    } else if (!this.lastBuildSucceeded || this.options.alwaysNotify) {
        this.lastBuildSucceeded = true;
        return 'Build successful';

    } else {
        return;
    }

    this.lastBuildSucceeded = false;

    var message;
    if (error.module && error.module.rawRequest)
        message = error.module.rawRequest + '\n';

    if (error.error)
        message = 'Error: ' + message + error.error.toString();
    else if (error.warning)
        message = 'Warning: ' + message + error.warning.toString();

    return message;
};

WebpackNotifierPlugin.prototype.compilationDone = function(stats) {
    var msg = this.compileMessage(stats);
    if (msg) {
        var contentImage = ('contentImage' in this.options) ?
            this.options.contentImage : DEFAULT_LOGO;

        notifier.notify({
            title: this.options.title || 'Webpack',
            message: msg,
            contentImage: contentImage,
            icon: (os.platform() === 'win32') ? contentImage : undefined
        });
    }
};

WebpackNotifierPlugin.prototype.apply = function(compiler) {
    compiler.plugin('done', this.compilationDone.bind(this));
};
<commit_msg>Use contentImage as icon on linux<commit_after>var path = require('path');
var os = require('os');
var notifier = require('node-notifier');

var DEFAULT_LOGO = path.join(__dirname, 'logo.png');

var WebpackNotifierPlugin = module.exports = function(options) {
    this.options = options || {};
    this.lastBuildSucceeded = false;
};

WebpackNotifierPlugin.prototype.compileMessage = function(stats) {
    var error;
    if (stats.hasErrors()) {
        error = stats.compilation.errors[0];

    } else if (stats.hasWarnings() && !this.options.excludeWarnings) {
        error = stats.compilation.warnings[0];

    } else if (!this.lastBuildSucceeded || this.options.alwaysNotify) {
        this.lastBuildSucceeded = true;
        return 'Build successful';

    } else {
        return;
    }

    this.lastBuildSucceeded = false;

    var message;
    if (error.module && error.module.rawRequest)
        message = error.module.rawRequest + '\n';

    if (error.error)
        message = 'Error: ' + message + error.error.toString();
    else if (error.warning)
        message = 'Warning: ' + message + error.warning.toString();

    return message;
};

WebpackNotifierPlugin.prototype.compilationDone = function(stats) {
    var msg = this.compileMessage(stats);
    if (msg) {
        var contentImage = ('contentImage' in this.options) ?
            this.options.contentImage : DEFAULT_LOGO;

        notifier.notify({
            title: this.options.title || 'Webpack',
            message: msg,
            contentImage: contentImage,
            icon: (os.platform() === 'win32' || os.platform() === 'linux') ? contentImage : undefined
        });
    }
};

WebpackNotifierPlugin.prototype.apply = function(compiler) {
    compiler.plugin('done', this.compilationDone.bind(this));
};
<|endoftext|>