<commit_before>var React = require('react');

module.exports = React.createClass({
  getDefaultProps: function () {
    return {
      buffer: null,
      width: 500,
      height: 100,
      zoom: 1,
      color: 'black',
      onDone: null
    };
  },

  propTypes: {
    buffer: React.PropTypes.object.isRequired,
    width: React.PropTypes.number,
    height: React.PropTypes.number,
    zoom: React.PropTypes.number,
    color: React.PropTypes.string,
    onDone: React.PropTypes.func
  },

  componentDidMount: function () {
    var width = this.props.width * this.props.zoom;
    var middle = this.props.height / 2;

    var channelData = this.props.buffer.getChannelData(0);
    var step = Math.ceil(channelData.length / width);

    var ctx = this.refs.canvas.getDOMNode().getContext('2d');
    ctx.fillStyle = this.props.color;
    this.draw(width, step, middle, channelData, ctx);

    if (this.props.onDone) { this.props.onDone(); }
  },

  draw: function (width, step, middle, data, ctx) {
    for (var i = 0; i < width; i += 1) {
      var min = 1.0;
      var max = -1.0;

      for (var j = 0; j < step; j += 1) {
        var datum = data[(i * step) + j];

        if (datum < min) {
          min = datum;
        } else if (datum > max) {
          max = datum;
        }

        ctx.fillRect(i, (1 + min) * middle, 1, Math.max(1, (max - min) * middle));
      }
    }
  },

  render: function () {
    return (
        <canvas
          ref="canvas"
          width={this.props.width * this.props.zoom}
          height={this.props.height}></canvas>
        );
  }
});
<commit_msg>Set display name<commit_after>var React = require('react');

module.exports = React.createClass({
  displayName: 'Waveform',

  getDefaultProps: function () {
    return {
      buffer: null,
      width: 500,
      height: 100,
      zoom: 1,
      color: 'black',
      onDone: null
    };
  },

  propTypes: {
    buffer: React.PropTypes.object.isRequired,
    width: React.PropTypes.number,
    height: React.PropTypes.number,
    zoom: React.PropTypes.number,
    color: React.PropTypes.string,
    onDone: React.PropTypes.func
  },

  componentDidMount: function () {
    var width = this.props.width * this.props.zoom;
    var middle = this.props.height / 2;

    var channelData = this.props.buffer.getChannelData(0);
    var step = Math.ceil(channelData.length / width);

    var ctx = this.refs.canvas.getDOMNode().getContext('2d');
    ctx.fillStyle = this.props.color;
    this.draw(width, step, middle, channelData, ctx);

    if (this.props.onDone) { this.props.onDone(); }
  },

  draw: function (width, step, middle, data, ctx) {
    for (var i = 0; i < width; i += 1) {
      var min = 1.0;
      var max = -1.0;

      for (var j = 0; j < step; j += 1) {
        var datum = data[(i * step) + j];

        if (datum < min) {
          min = datum;
        } else if (datum > max) {
          max = datum;
        }

        ctx.fillRect(i, (1 + min) * middle, 1, Math.max(1, (max - min) * middle));
      }
    }
  },

  render: function () {
    return (
        <canvas
          ref="canvas"
          width={this.props.width * this.props.zoom}
          height={this.props.height}></canvas>
        );
  }
});
<|endoftext|>


<commit_before>/**
 * This file contains definitions for all the blocks that are generated using blockgen.js
 * they access sensor values, as seen at http://www.robotc.net/wiki/NXT_Sensors_Overview
 *
 * @author eric@legoaces.org (Eric Miller)
 */
if (typeof(NXT) == 'undefined'){
NXT = {};}

Blockly.Blocks['sensor_constant'] = {
		init: function() {
			this.setHelpUrl('http://www.example.com/');
			this.setColour(MOTOR_COLOR);
			this.appendDummyInput()
			//TODO: let this list be dynamically configurable somehow.
				.appendField(new Blockly.FieldDropdown([["touch multiplexer", "touch"], ["gyroscope", "gyro"], ["IR seeker", "seeker"]]), "SENSOR");
			this.setOutput(true, "Sensor");
			this.setTooltip('');
		}
};

Blockly.RobotC['sensor_constant'] = function(block) {
	var dropdown_motor = block.getFieldValue('SENSOR');
	var code = dropdown_motor;
	return [code, Blockly.RobotC.ORDER_ATOMIC];
};

NXT.Sensors = {};
NXT.Sensors.color = 100;
NXT.Sensors.Simplecode = [
{
	name:"sensor_value",
	display_name:"get value", //defaults to name
	args:[["sensor", "Sensor"]],
	tooltip: 'Gets value for a given sensor (see RobotC wiki)',
	hue: NXT.Sensors.color,
	returns: 'Number',
	template: 'SensorValue[~0]'
},
{
	name:"sensor_value",
	display_name:"get raw value", //defaults to name
	args:[["sensor", "Sensor"]],
	tooltip: 'Gets raw value for a given sensor (see RobotC wiki)',
	hue: NXT.Sensors.color,
	returns: 'Number',
	template: 'SensorRaw[~0]'
}
                      ];

Blockly.RobotC.generateBlocks(NXT.Sensors.color, NXT.Sensors.Simplecode);<commit_msg>Incomplete - task : Add RobotC Blocks  Changed sensor block color<commit_after>/**
 * This file contains definitions for all the blocks that are generated using blockgen.js
 * they access sensor values, as seen at http://www.robotc.net/wiki/NXT_Sensors_Overview
 *
 * @author eric@legoaces.org (Eric Miller)
 */
if (typeof(NXT) == 'undefined'){
NXT = {};}

Blockly.Blocks['sensor_constant'] = {
		init: function() {
			this.setHelpUrl('http://www.example.com/');
			this.setColour(MOTOR_COLOR);
			this.appendDummyInput()
			//TODO: let this list be dynamically configurable somehow.
				.appendField(new Blockly.FieldDropdown([["touch multiplexer", "touch"], ["gyroscope", "gyro"], ["IR seeker", "seeker"]]), "SENSOR");
			this.setOutput(true, "Sensor");
			this.setTooltip('');
		}
};

Blockly.RobotC['sensor_constant'] = function(block) {
	var dropdown_motor = block.getFieldValue('SENSOR');
	var code = dropdown_motor;
	return [code, Blockly.RobotC.ORDER_ATOMIC];
};

NXT.Sensors = {};
NXT.Sensors.color = 160;
NXT.Sensors.Simplecode = [
{
	name:"sensor_value",
	display_name:"get value", //defaults to name
	args:[["sensor", "Sensor"]],
	tooltip: 'Gets value for a given sensor (see RobotC wiki)',
	hue: NXT.Sensors.color,
	returns: 'Number',
	template: 'SensorValue[~0]'
},
{
	name:"sensor_value",
	display_name:"get raw value", //defaults to name
	args:[["sensor", "Sensor"]],
	tooltip: 'Gets raw value for a given sensor (see RobotC wiki)',
	hue: NXT.Sensors.color,
	returns: 'Number',
	template: 'SensorRaw[~0]'
}
                      ];

Blockly.RobotC.generateBlocks(NXT.Sensors.color, NXT.Sensors.Simplecode);<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const lwip = require('lwip-promise');
const async = require('async-q');

class Resizer {
    constructor(options) {
        this.options = _.assign({}, Resizer.defaultOptions, options || {});
    }

    getPathWithoutExtension(filePath) {
        return filePath.substr(0, filePath.lastIndexOf('.'));
    }

    getExtension(filePath) {
        return filePath.substr(filePath.lastIndexOf('.') + 1);
    }

    createThumbnail(filePath, options) {
        const suffix = options.suffix || 'thumbnail';
        const interpolation = options.interpolation || 'linear';
        const format = options.format || 'png';
        const dstPath = this.getPathWithoutExtension(filePath) + `_${suffix}.png`;

        return lwip
            .openAsync(filePath)
            .then(image => image.coverAsync(options.width, options.height, interpolation))
            .then(resizedImage => resizedImage.writeFileAsync(dstPath, format))
            .then(() => dstPath);
    }

    createCover(filePath, options) {
        const suffix = options.suffix || 'cover';
        const interpolation = options.interpolation || 'linear';
        const format = options.format || 'png';
        const dstPath = this.getPathWithoutExtension(filePath) + `_${suffix}.png`;

        return lwip
            .openAsync(filePath)
            .then(image => {
                const width = image.width();
                const height = image.height();
                const aspectRatio = width / height;

                let resizeWidth = width;
                let resizeHeight = height;

                if (resizeWidth > options.width) {
                    resizeWidth = options.width;
                    resizeHeight = resizeWidth / aspectRatio;
                } else if (resizeHeight > options.height) {
                    resizeHeight = options.height;
                    resizeWidth = resizeHeight * aspectRatio;
                }

                return image.resizeAsync(resizeWidth, resizeHeight, interpolation);
            })
            .then(resizedImage => resizedImage.writeFileAsync(dstPath, format))
            .then(() => dstPath);
    };

    processImage(filePath, attachBase) {
        const jobs = _.map(this.options.tasks, task => {
            if (_.isObject(task.cover)) {
                return _ => this.createCover(filePath, task.cover).then(path => attachBase.coverPath = path);
            } else if (_.isObject(task.thumbnail)) {
                return _ => this.createThumbnail(filePath, task.thumbnail).then(path => attachBase.thumbnailPath = path);
            }
        });

        return async.series(jobs)
    }

    single(multerInstance, filename) {
        const that = this;
        return function(req, res, next) {
            multerInstance.single(filename)(req, res, err => {
                that
                    .processImage(req.file.path, req.file)
                    .then(_ => next())
                    .catch(next);
            });
        };
    }

    array(multerInstance, filename, maxCount) {
        const that = this;
        return function(req, res, next) {
            multerInstance.array(filename, maxCount)(req, res, err => {
                async
                    .eachSeries(req.files,
                        file => that.processImage(file.path, file))
                    .then(_ => next())
                    .catch(next);
            });
        };
    }
}

Resizer.defaultOptions = {
    tasks: []
};

module.exports = Resizer;
<commit_msg>fix(index): Use proper names for tasks<commit_after>'use strict';

const _ = require('lodash');
const lwip = require('lwip-promise');
const async = require('async-q');

class Resizer {
    constructor(options) {
        this.options = _.assign({}, Resizer.defaultOptions, options || {});
    }

    getPathWithoutExtension(filePath) {
        return filePath.substr(0, filePath.lastIndexOf('.'));
    }

    getExtension(filePath) {
        return filePath.substr(filePath.lastIndexOf('.') + 1);
    }

    createCover(filePath, options) {
        const suffix = options.suffix || 'cover';
        const interpolation = options.interpolation || 'linear';
        const format = options.format || 'png';
        const dstPath = this.getPathWithoutExtension(filePath) + `_${suffix}.png`;

        return lwip
            .openAsync(filePath)
            .then(image => image.coverAsync(options.width, options.height, interpolation))
            .then(resizedImage => resizedImage.writeFileAsync(dstPath, format))
            .then(() => dstPath);
    }

    createResized(filePath, options) {
        const suffix = options.suffix || 'resized';
        const interpolation = options.interpolation || 'linear';
        const format = options.format || 'png';
        const dstPath = this.getPathWithoutExtension(filePath) + `_${suffix}.png`;

        return lwip
            .openAsync(filePath)
            .then(image => {
                const width = image.width();
                const height = image.height();
                const aspectRatio = width / height;

                let resizeWidth = width;
                let resizeHeight = height;

                if (resizeWidth > options.width) {
                    resizeWidth = options.width;
                    resizeHeight = resizeWidth / aspectRatio;
                } else if (resizeHeight > options.height) {
                    resizeHeight = options.height;
                    resizeWidth = resizeHeight * aspectRatio;
                }

                return image.resizeAsync(resizeWidth, resizeHeight, interpolation);
            })
            .then(resizedImage => resizedImage.writeFileAsync(dstPath, format))
            .then(() => dstPath);
    };

    processImage(filePath, attachBase) {
        const jobs = _.map(this.options.tasks, task => {
            if (_.isObject(task.resize)) {
                return _ => this.createResized(filePath, task.resize).then(path => attachBase.resizedPath = path);
            } else if (_.isObject(task.cover)) {
                return _ => this.createCover(filePath, task.cover).then(path => attachBase.coverPath = path);
            }
        });

        return async.series(jobs)
    }

    single(multerInstance, filename) {
        const that = this;
        return function(req, res, next) {
            multerInstance.single(filename)(req, res, err => {
                that
                    .processImage(req.file.path, req.file)
                    .then(_ => next())
                    .catch(next);
            });
        };
    }

    array(multerInstance, filename, maxCount) {
        const that = this;
        return function(req, res, next) {
            multerInstance.array(filename, maxCount)(req, res, err => {
                async
                    .eachSeries(req.files,
                        file => that.processImage(file.path, file))
                    .then(_ => next())
                    .catch(next);
            });
        };
    }
}

Resizer.defaultOptions = {
    tasks: []
};

module.exports = Resizer;
<|endoftext|>


<commit_before>/**

 * Module dependencies.
 */

var Me = require('./lib/me');
var Site = require('./lib/site');
var debug = require('debug')('wpcom');

/**
 * WordPress.com REST API class.
 *
 * @api public
 */

function WPCOM(request){
  if (!(this instanceof WPCOM)) return new WPCOM(request);
  if ('function' !== typeof request) {
    throw new TypeError('a `request` WP.com function must be passed in');
  }
  this.request = request;
  this.params = {};
}

/**
 * Get me object instance
 *
 * @api public
 */

WPCOM.prototype.me = function(){
  return new Me(this);
};

/**
 * Get site object instance
 *
 * @param {String} id
 * @api public
 */

WPCOM.prototype.site = function(id){
  return new Site(id, this);
};

/**
 * List Freshly Pressed Posts
 *
 * @param {Object} params (optional)
 * @param {Function} fn callback function
 * @api public
 */

WPCOM.prototype.freshlyPressed = function(params, fn){
  this.sendRequest('freshly-pressed.get', null, params, fn);
};

/**
 * Request to WordPress REST API
 *
 * @param {String||Object} options
 * @param {Object} [query]
 * @param {Object} [body]
 * @param {Function} fn
 * @api private
 */

WPCOM.prototype.sendRequest = function (options, query, body, fn){
  debug('sendRequest("%s")', options.path);

  if ('string' == typeof options) {
    options = { path: options };
  }

  this.params.method = (options.method || 'GET').toUpperCase();
  this.params.path = options.path;

  if ('function' == typeof query) {
    fn = query;
    query = {};
  }

  if ('function' == typeof body) {
    fn = body;
    query = {};
  }

  if (query) this.params.query = query;
  if (body) this.params.body = body;
  if (!fn) fn = function(err){ if (err) throw err; };

  // request method
  this.request(this.params, fn);
};

/**
 * Expose `WPCOM` module
 */

module.exports = WPCOM;
<commit_msg>core: psss<commit_after>
/**
 * Module dependencies.
 */

var Me = require('./lib/me');
var Site = require('./lib/site');
var debug = require('debug')('wpcom');

/**
 * WordPress.com REST API class.
 *
 * @api public
 */

function WPCOM(request){
  if (!(this instanceof WPCOM)) return new WPCOM(request);
  if ('function' !== typeof request) {
    throw new TypeError('a `request` WP.com function must be passed in');
  }
  this.request = request;
  this.params = {};
}

/**
 * Get me object instance
 *
 * @api public
 */

WPCOM.prototype.me = function(){
  return new Me(this);
};

/**
 * Get site object instance
 *
 * @param {String} id
 * @api public
 */

WPCOM.prototype.site = function(id){
  return new Site(id, this);
};

/**
 * List Freshly Pressed Posts
 *
 * @param {Object} params (optional)
 * @param {Function} fn callback function
 * @api public
 */

WPCOM.prototype.freshlyPressed = function(params, fn){
  this.sendRequest('freshly-pressed.get', null, params, fn);
};

/**
 * Request to WordPress REST API
 *
 * @param {String||Object} options
 * @param {Object} [query]
 * @param {Object} [body]
 * @param {Function} fn
 * @api private
 */

WPCOM.prototype.sendRequest = function (options, query, body, fn){
  debug('sendRequest("%s")', options.path);

  if ('string' == typeof options) {
    options = { path: options };
  }

  this.params.method = (options.method || 'GET').toUpperCase();
  this.params.path = options.path;

  if ('function' == typeof query) {
    fn = query;
    query = {};
  }

  if ('function' == typeof body) {
    fn = body;
    query = {};
  }

  if (query) this.params.query = query;
  if (body) this.params.body = body;
  if (!fn) fn = function(err){ if (err) throw err; };

  // request method
  this.request(this.params, fn);
};

/**
 * Expose `WPCOM` module
 */

module.exports = WPCOM;
<|endoftext|>


<commit_before>'use strict'

const solc = require('solc')
const bluebird = require('bluebird')
const chalk = require('chalk')
const TestRPC = require('ethereumjs-testrpc')
const waterfall = require('promise.waterfall')
const Web3 = require('web3')
const provider = new Web3.providers.HttpProvider('http://localhost:8545')
const web3 = new Web3(TestRPC.provider())
const newContract = require('eth-new-contract').default(provider)
const pkg = require('./package.json')

const contractName = 'ReplContainer'
const main = 'Main'

// contract template where the user commands are injected before compilation
const template = args => `pragma solidity ${pkg.dependencies.solc};
contract ${contractName} {
  function ${main}() constant returns (${args.returnType}) {
    ${args.content}
    return ${args.returnExpression}
  }
}`

/** Parse the error message thrown with a naive compile in order to determine the actual return type. This is the hacky alternative to parsing an AST. */
const regexpReturnError = /Return argument type (.*) is not implicitly convertible to expected type \(type of first return variable\) bool./
const matchReturnTypeFromError = message => message.match(regexpReturnError)

const getAccounts = bluebird.promisify(web3.eth.getAccounts.bind(web3.eth))

/** Takes a list of commands and evaluates them inside a contract. Returns a promised result of the last command. Returns null if the command is not an expression. */
const evalSol = commands => {
  /** Returns true if the given command is an expression that can return a value. */
  const isExpression = command => !/[^=]=[^=]/.test(command)
  const lastCommand = commands[commands.length - 1]

  let returnType = 'bool'
  const content = commands.slice(0, commands.length - 1).join('\n')
  const contentWithReturnExpression = commands.join('\n')
  const sourceFirstPass = template({ content: contentWithReturnExpression, returnType, returnExpression: isExpression(lastCommand) ? lastCommand : 'false;' })
  let source = sourceFirstPass

  // Attempt to compile the first pass knowing that any return value (other than bool) will fail. Parse the error message to determine the correct return value and generate the correct source.
  const compilationFirstPass = solc.compile(sourceFirstPass)

  // get errors and warnings
  // remove "Unused local variable" warning which will always trigger in REPL mode
  if (compilationFirstPass.errors) {

    const errorsFirstPass = compilationFirstPass.errors
      .filter(err => !err.match(/\: Warning\: /))
    const warnings = compilationFirstPass.errors
      .filter(err => err.match(/\: Warning\: /) && !err.match('Unused local variable'))

    if (warnings.length) {
      console.log(chalk.yellow(warnings.join('\n')))
    }

    // handle errors
    if (errorsFirstPass.length > 0) {
      const match = matchReturnTypeFromError(errorsFirstPass[0])
      if (match) {
        returnType = match[1]
      } else {
        return Promise.reject(errorsFirstPass.join('\n'))
      }
      source = template({ content, returnType, returnExpression: lastCommand })
    }
  }

  const compilation = solc.compile(source)
  if (compilation.errors) {

    const errors = compilation.errors
      .filter(err => !err.match(/\: Warning\: /))

    if (errors.length) {
      console.error(chalk.red(`Error compiling Solidity:

${source.split('\n').map((line, n) => (n + 1) + '  ' + line).join('\n')}

  ${errors.join('\n  ')}`, errors))
      return Promise.reject('Error compiling Solidity')
    }
  }

  // if the last command is not an expression with a return value (e.g. an assignment), just return null
  // this still must be done after compilation in case there is an error
  if (!isExpression(lastCommand)) {
    return Promise.resolve(null)
  }

  // if we made it this far, deploy the bytecode
  const contract = compilation.contracts[`:${contractName}`]
  const bytecode = contract.bytecode
  const abi = JSON.parse(contract.interface)
  const ReplContainer = web3.eth.contract(abi)

  // execute the compiled contract and execute its Main function to get a result
  return waterfall([
    getAccounts,
    accounts => newContract(ReplContainer, { from: accounts[0], data: bytecode, gas: 3e6 }),
    contract => bluebird.promisify(contract[main])()
  ])
}

/** Creates a new repl environment that can evaluate solidity commands. Returns a single function that takes a new command. */
module.exports = () => {
  const commands = []

  /** Takes a new command and returns the result of evaluating it in the current context. */
  return rawCommand => {
    const command = rawCommand.trim()

    // ignore blank lines
    if (command === '') {
      return Promise.resolve(null)
    }

    const commandWithSemi = command + (command.endsWith(';') ? '' : ';')
    return evalSol(commands.concat(commandWithSemi))
      .then(result => {
        commands.push(commandWithSemi)
        return result
      })
  }
}
<commit_msg>Remove TestRPC provider. Fix promisified getAccounts bug.<commit_after>'use strict'

const solc = require('solc')
const bluebird = require('bluebird')
const chalk = require('chalk')
const TestRPC = require('ethereumjs-testrpc')
const waterfall = require('promise.waterfall')
const Web3 = require('web3')
const provider = new Web3.providers.HttpProvider('http://localhost:8545')
// TestRPC.provider() gives error "Synchronous requests are not supported."
// during newContract in latest version.
const web3 = new Web3(provider)
const newContract = require('eth-new-contract').default(provider)
const pkg = require('./package.json')

const contractName = 'ReplContainer'
const main = 'Main'

// contract template where the user commands are injected before compilation
const template = args => `pragma solidity ${pkg.dependencies.solc};
contract ${contractName} {
  function ${main}() constant returns (${args.returnType}) {
    ${args.content}
    return ${args.returnExpression}
  }
}`

/** Parse the error message thrown with a naive compile in order to determine the actual return type. This is the hacky alternative to parsing an AST. */
const regexpReturnError = /Return argument type (.*) is not implicitly convertible to expected type \(type of first return variable\) bool./
const matchReturnTypeFromError = message => message.match(regexpReturnError)

// promisified getAccounts because Bluebird.promisify gives "callback is not a function"
const getAccounts = () => {
  return new bluebird((resolve, reject) => {
    web3.eth.getAccounts((err, result) => {
      if (err) return reject(err)
      resolve(result)
    })
  })
}

/** Takes a list of commands and evaluates them inside a contract. Returns a promised result of the last command. Returns null if the command is not an expression. */
const evalSol = commands => {
  /** Returns true if the given command is an expression that can return a value. */
  const isExpression = command => !/[^=]=[^=]/.test(command)
  const lastCommand = commands[commands.length - 1]

  let returnType = 'bool'
  const content = commands.slice(0, commands.length - 1).join('\n')
  const contentWithReturnExpression = commands.join('\n')
  const sourceFirstPass = template({ content: contentWithReturnExpression, returnType, returnExpression: isExpression(lastCommand) ? lastCommand : 'false;' })
  let source = sourceFirstPass

  // Attempt to compile the first pass knowing that any return value (other than bool) will fail. Parse the error message to determine the correct return value and generate the correct source.
  const compilationFirstPass = solc.compile(sourceFirstPass)

  // get errors and warnings
  // remove "Unused local variable" warning which will always trigger in REPL mode
  if (compilationFirstPass.errors) {

    const errorsFirstPass = compilationFirstPass.errors
      .filter(err => !err.match(/\: Warning\: /))
    const warnings = compilationFirstPass.errors
      .filter(err => err.match(/\: Warning\: /) && !err.match('Unused local variable'))

    if (warnings.length) {
      console.log(chalk.yellow(warnings.join('\n')))
    }

    // handle errors
    if (errorsFirstPass.length > 0) {
      const match = matchReturnTypeFromError(errorsFirstPass[0])
      if (match) {
        returnType = match[1]
      } else {
        return Promise.reject(errorsFirstPass.join('\n'))
      }
      source = template({ content, returnType, returnExpression: lastCommand })
    }
  }

  const compilation = solc.compile(source)
  if (compilation.errors) {

    const errors = compilation.errors
      .filter(err => !err.match(/\: Warning\: /))

    if (errors.length) {
      console.error(chalk.red(`Error compiling Solidity:

${source.split('\n').map((line, n) => (n + 1) + '  ' + line).join('\n')}

  ${errors.join('\n  ')}`, errors))
      return Promise.reject('Error compiling Solidity')
    }
  }

  // if the last command is not an expression with a return value (e.g. an assignment), just return null
  // this still must be done after compilation in case there is an error
  if (!isExpression(lastCommand)) {
    return Promise.resolve(null)
  }

  // if we made it this far, deploy the bytecode
  const contract = compilation.contracts[`:${contractName}`]
  const bytecode = contract.bytecode
  const abi = JSON.parse(contract.interface)
  const ReplContainer = web3.eth.contract(abi)

  // execute the compiled contract and execute its Main function to get a result
  return waterfall([
    getAccounts,
    accounts => newContract(ReplContainer, { from: accounts[0], data: bytecode, gas: 3e6 }),
    contract => bluebird.promisify(contract[main])()
  ])
}

/** Creates a new repl environment that can evaluate solidity commands. Returns a single function that takes a new command. */
module.exports = () => {
  const commands = []

  /** Takes a new command and returns the result of evaluating it in the current context. */
  return rawCommand => {
    const command = rawCommand.trim()

    // ignore blank lines
    if (command === '') {
      return Promise.resolve(null)
    }

    const commandWithSemi = command + (command.endsWith(';') ? '' : ';')
    return evalSol(commands.concat(commandWithSemi))
      .then(result => {
        commands.push(commandWithSemi)
        return result
      })
  }
}
<|endoftext|>


<commit_before>function LinalgModule(stdlib, foreign, heap) {
  "use asm";

  var abs = stdlib.Math.abs,
      imul = stdlib.Math.imul,
      uiarray = new stdlib.Uint32Array(heap),
      darray = new stdlib.Float64Array(heap);

  function daxpy(n, alpha, x, incX, y, incY) {
    n = n | 0;
    alpha = +alpha;
    x = x | 0;
    incX = incX | 0;
    y = y | 0;
    incY = incY | 0;

    var i = 0,
        j = 0;

    n = n << 3;
    x = x << 3;
    incX = incX << 3;
    y = y << 3;
    incY = incY << 3;

    for (i = x, j = y; (i | 0) < (n | 0); i = i + incX | 0, j = j + incY | 0) {
      darray[j >> 3] = alpha * darray[i >> 3] + (+darray[j >> 3]);
    }
  }

  function dasum(n, x, incX) {
    n = n | 0;
    x = x | 0;
    incX = incX | 0;

    var i = 0,
        value = 0.0;

    n = n << 3;
    x = x << 3;
    incX = incX << 3;

    for (i = x; (i | 0) < (n | 0); i = i + incX | 0) {
      value = value + (+abs(darray[i >> 3]));
    }

    return value;
  }

  function dcopy(n, x, incx, y, incy) {
    n = n | 0;
    x = x | 0;
    incx = incx | 0;
    y = y | 0;
    incy = incy | 0;

    var i = 0,
        pxi = 0,
        pyi = 0;

    incx = incx << 3;
    incy = incy << 3;

    for (i = 0, pxi = x, pyi = y; (i | 0) < (n | 0); i = i + 1 | 0, pxi = pxi + incx | 0, pyi = pyi + incy | 0) {
      darray[pyi >> 3] = darray[pxi >> 3];
    }
  }

  function ddot(n, x, incX, y, incY) {
    n = n | 0;
    x = x | 0;
    incX = incX | 0;
    y = y | 0;
    incY = incY | 0;

    var i = 0,
        j = 0,
        value = 0.0;

    n = n << 3;
    x = x << 3;
    incX = incX << 3;
    y = y << 3;
    incY = incY << 3;

    for (i = x, j = y; (i | 0) < (n | 0); i = i + incX | 0, j = j + incY | 0) {
      value = value + darray[i >> 3] * darray[j >> 3];
    }

    return value;
  }

  function dswap(n, x, incx, y, incy) {
    n = n | 0;
    x = x | 0;
    incx = incx | 0;
    y = y | 0;
    incy = incy | 0;

    var i = 0,
        pxi = 0,
        pyi = 0,
        tmp = 0.0;

    incx = incx << 3;
    incy = incy << 3;

    for (i = 0, pxi = x, pyi = y; (i | 0) < (n | 0); i = i + 1 | 0, pxi = pxi + incx | 0, pyi = pyi + incy | 0) {
      tmp = +darray[pxi >> 3];
      darray[pxi >> 3] = darray[pyi >> 3];
      darray[pyi >> 3] = tmp;
    }
  }

  function idamax(n, x, incx) {
    n = n | 0;
    x = x | 0;
    incx = incx | 0;

    var i = 0,
        pxi = 0,
        index = 0,
        tmp = 0.0,
        value = 0.0;

    incx = incx << 3;

    for (i = 0, pxi = x; (i | 0) < (n | 0); i = i + 1 | 0, pxi = pxi + incx | 0) {
      tmp = +abs(darray[pxi >> 3]);
      if (tmp > value) {
        index = i;
        value = tmp;
      }
    }

    return index | 0;
  }

  function dgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy) {
    // TODO support lda
    trans = trans | 0;
    m = m | 0;
    n = n | 0;
    alpha = +alpha;
    a = a | 0;
    lda = lda | 0;
    x = x | 0;
    incx = incx | 0;
    beta = +beta;
    y = y | 0;
    incy = incy | 0;

    var i = 0,
        j = 0,
        paij = 0,
        pxj = 0,
        pyi = 0,
        val = 0.0;

    for (i = 0; (i | 0) < (m | 0); i = i + 1 | 0) {
      pyi = y + ((imul(i, incx) | 0) << 3) | 0;
      val = beta * darray[pyi >> 3];
      for (j = 0; (j | 0) < (n | 0); j = j + 1 | 0) {
        paij = a + ((imul(i, n) | 0) + j << 3) | 0;
        pxj = x + ((imul(j, incy) | 0) << 3) | 0;
        val = val + alpha * darray[paij >> 3] * darray[pxj >> 3];
      }
      darray[pyi >> 3] = val;
    }
  }

  function dtrsv(uplo, trans, diag, n, a, lda, x, incx) {
    // TODO support trans, lda
    uplo = uplo | 0;
    trans = trans | 0;
    diag = diag | 0;
    n = n | 0;
    a = a | 0;
    lda = lda | 0;
    x = x | 0;
    incx = incx | 0;

    var i = 0,
        j = 0,
        paii = 0,
        paji = 0,
        pxi = 0,
        pxj = 0;

    if (uplo) {
      // lower triangular matrix
      for (i = 0; (i | 0) < (n | 0); i = i + 1 | 0) {
        pxi = x + ((imul(i, incx) | 0) << 3) | 0;
        if (!diag) {
          paii = a + ((imul(i, n) | 0) + i << 3) | 0;
          darray[pxi >> 3] = darray[pxi >> 3] / darray[paii >> 3];
        }
        for (j = i + 1 | 0; (j | 0) < (n | 0); j = j + 1 | 0) {
          paji = a + ((imul(j, n) | 0) + i << 3) | 0;
          pxj = x + ((imul(j, incx) | 0) << 3) | 0;
          darray[pxj >> 3] = darray[pxj >> 3] - darray[pxi >> 3] * darray[paji >> 3];
        }
      }
    } else {
      // upper triangular matrix
      for (i = n - 1 | 0; (i | 0) >= 0; i = i - 1 | 0) {
        pxi = x + ((imul(i, incx) | 0) << 3) | 0;
        if (!diag) {
          paii = a + ((imul(i, n) | 0) + i << 3) | 0;
          darray[pxi >> 3] = darray[pxi >> 3] / darray[paii >> 3];
        }
        for (j = 0; (j | 0) < (i | 0); j = j + 1 | 0) {
          paji = a + ((imul(j, n) | 0) + i << 3) | 0;
          pxj = x + ((imul(j, incx) | 0) << 3) | 0;
          darray[pxj >> 3] = darray[pxj >> 3] - darray[pxi >> 3] * darray[paji >> 3];
        }
      }
    }
  }

  function dgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc) {
    // TODO support transa, transb, lda, ldb, ldc
    transa = transa | 0;
    transb = transb | 0;
    m = m | 0;
    n = n | 0;
    k = k | 0;
    alpha = +alpha;
    a = a | 0;
    lda = lda | 0;
    b = b | 0;
    ldb = ldb | 0;
    beta = +beta;
    c = c | 0;
    ldc = ldc | 0;

    var i = 0,
        j = 0,
        l = 0,
        aIndex = 0,
        bIndex = 0,
        cIndex = 0;

    for (i = 0; (i | 0) < (m | 0); i = i + 1 | 0) {
      for (j = 0; (j | 0) < (n | 0); j = j + 1 | 0) {
        cIndex = c + (imul(i, n) | 0) + j << 3;
        darray[cIndex >> 3] = beta * darray[cIndex >> 3];
        for (l = 0; (l | 0) < (k | 0); l = l + 1 | 0) {
          aIndex = a + (imul(i, k) | 0) + l << 3;
          bIndex = b + (imul(l, k) | 0) + j << 3;
          darray[cIndex >> 3] = +darray[cIndex >> 3] + alpha * darray[aIndex >> 3] * darray[bIndex >> 3];
        }
      }
    }
  }

  function dgesv(n, nrhs, a, lda, ipiv, b, ldb) {
    n = n | 0;
    nrhs = nrhs | 0;
    a = a | 0;
    lda = lda | 0;
    ipiv = ipiv | 0;
    b = b | 0;
    ldb = ldb | 0;

    var i = 0,
        j = 0,
        tmp = 0.0,
        pipivi = 0,
        pbi = 0,
        pbj = 0;

    dgetrf(n, n, a, lda, ipiv);

    for (i = 0; (i | 0) < (n | 0); i = i + 1 | 0) {
      pipivi = ipiv + (i << 2) | 0;
      j = uiarray[pipivi >> 2] | 0;
      pbi = b + (i << 3) | 0;
      pbj = b + (j << 3) | 0;
      tmp = +darray[pbi >> 3];
      darray[pbi >> 3] = darray[pbj >> 3];
      darray[pbj >> 3] = tmp;
    }

    dtrsv(1, 0, 1, n, a, lda, b, 1);
    dtrsv(0, 0, 0, n, a, lda, b, 1);
  }

  function dgetrf(m, n, a, lda, ipiv) {
    // TODO support lda
    m = m | 0;
    n = n | 0;
    a = a | 0;
    lda = lda | 0;
    ipiv = ipiv | 0;

    var i = 0,
        j = 0,
        k = 0,
        l = 0,
        pipivk = 0,
        paik = 0,
        pajk = 0,
        pakk = 0,
        pajl = 0,
        pakl = 0;

    for (k = 0; (k | 0) < (n - 1 | 0); k = k + 1 | 0) {
      i = k + (idamax(n - k | 0, a + ((imul(i, n) | 0) << 3) + k | 0, m) | 0) | 0;
      pipivk = ipiv + (k << 2) | 0;
      uiarray[pipivk >> 2] = i;
      dswap(n, a + ((imul(i, n) | 0) << 3) | 0, 1, a + ((imul(k, n) | 0) << 3) | 0, 1);
      for (j = k + 1 | 0; (j | 0) < (n | 0); j = j + 1 | 0) {
        pajk = a + ((imul(j, n) | 0) + k << 3) | 0;
        pakk = a + ((imul(k, n) | 0) + k << 3) | 0;
        darray[pajk >> 3] = darray[pajk >> 3] / darray[pakk >> 3];
        for (l = k + 1 | 0; (l | 0) < (n | 0); l = l + 1 | 0) {
          pajl = a + ((imul(j, n) | 0) + l << 3) | 0;
          pakl = a + ((imul(k, n) | 0) + l << 3) | 0;
          darray[pajl >> 3] = darray[pajl >> 3] - darray[pajk >> 3] * darray[pakl >> 3];
        }
      }
    }
    uiarray[ipiv + (n - 1 << 2) >> 2] = n - 1;
  }

  return {
    daxpy: daxpy,
    dasum: dasum,
    dcopy: dcopy,
    ddot: ddot,
    dswap: dswap,
    idamax: idamax,
    dgemv: dgemv,
    dtrsv: dtrsv,
    dgemm: dgemm,
    dgesv: dgesv,
    dgetrf: dgetrf
  };
}

module.exports = LinalgModule;
<commit_msg>Fix pivoting for dgetrf<commit_after>function LinalgModule(stdlib, foreign, heap) {
  "use asm";

  var abs = stdlib.Math.abs,
      imul = stdlib.Math.imul,
      uiarray = new stdlib.Uint32Array(heap),
      darray = new stdlib.Float64Array(heap);

  function daxpy(n, alpha, x, incX, y, incY) {
    n = n | 0;
    alpha = +alpha;
    x = x | 0;
    incX = incX | 0;
    y = y | 0;
    incY = incY | 0;

    var i = 0,
        j = 0;

    n = n << 3;
    x = x << 3;
    incX = incX << 3;
    y = y << 3;
    incY = incY << 3;

    for (i = x, j = y; (i | 0) < (n | 0); i = i + incX | 0, j = j + incY | 0) {
      darray[j >> 3] = alpha * darray[i >> 3] + (+darray[j >> 3]);
    }
  }

  function dasum(n, x, incX) {
    n = n | 0;
    x = x | 0;
    incX = incX | 0;

    var i = 0,
        value = 0.0;

    n = n << 3;
    x = x << 3;
    incX = incX << 3;

    for (i = x; (i | 0) < (n | 0); i = i + incX | 0) {
      value = value + (+abs(darray[i >> 3]));
    }

    return value;
  }

  function dcopy(n, x, incx, y, incy) {
    n = n | 0;
    x = x | 0;
    incx = incx | 0;
    y = y | 0;
    incy = incy | 0;

    var i = 0,
        pxi = 0,
        pyi = 0;

    incx = incx << 3;
    incy = incy << 3;

    for (i = 0, pxi = x, pyi = y; (i | 0) < (n | 0); i = i + 1 | 0, pxi = pxi + incx | 0, pyi = pyi + incy | 0) {
      darray[pyi >> 3] = darray[pxi >> 3];
    }
  }

  function ddot(n, x, incX, y, incY) {
    n = n | 0;
    x = x | 0;
    incX = incX | 0;
    y = y | 0;
    incY = incY | 0;

    var i = 0,
        j = 0,
        value = 0.0;

    n = n << 3;
    x = x << 3;
    incX = incX << 3;
    y = y << 3;
    incY = incY << 3;

    for (i = x, j = y; (i | 0) < (n | 0); i = i + incX | 0, j = j + incY | 0) {
      value = value + darray[i >> 3] * darray[j >> 3];
    }

    return value;
  }

  function dswap(n, x, incx, y, incy) {
    n = n | 0;
    x = x | 0;
    incx = incx | 0;
    y = y | 0;
    incy = incy | 0;

    var i = 0,
        pxi = 0,
        pyi = 0,
        tmp = 0.0;

    incx = incx << 3;
    incy = incy << 3;

    for (i = 0, pxi = x, pyi = y; (i | 0) < (n | 0); i = i + 1 | 0, pxi = pxi + incx | 0, pyi = pyi + incy | 0) {
      tmp = +darray[pxi >> 3];
      darray[pxi >> 3] = darray[pyi >> 3];
      darray[pyi >> 3] = tmp;
    }
  }

  function idamax(n, x, incx) {
    n = n | 0;
    x = x | 0;
    incx = incx | 0;

    var i = 0,
        pxi = 0,
        index = 0,
        tmp = 0.0,
        value = 0.0;

    incx = incx << 3;

    for (i = 0, pxi = x; (i | 0) < (n | 0); i = i + 1 | 0, pxi = pxi + incx | 0) {
      tmp = +abs(darray[pxi >> 3]);
      if (tmp > value) {
        index = i;
        value = tmp;
      }
    }

    return index | 0;
  }

  function dgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy) {
    // TODO support lda
    trans = trans | 0;
    m = m | 0;
    n = n | 0;
    alpha = +alpha;
    a = a | 0;
    lda = lda | 0;
    x = x | 0;
    incx = incx | 0;
    beta = +beta;
    y = y | 0;
    incy = incy | 0;

    var i = 0,
        j = 0,
        paij = 0,
        pxj = 0,
        pyi = 0,
        val = 0.0;

    for (i = 0; (i | 0) < (m | 0); i = i + 1 | 0) {
      pyi = y + ((imul(i, incx) | 0) << 3) | 0;
      val = beta * darray[pyi >> 3];
      for (j = 0; (j | 0) < (n | 0); j = j + 1 | 0) {
        paij = a + ((imul(i, n) | 0) + j << 3) | 0;
        pxj = x + ((imul(j, incy) | 0) << 3) | 0;
        val = val + alpha * darray[paij >> 3] * darray[pxj >> 3];
      }
      darray[pyi >> 3] = val;
    }
  }

  function dtrsv(uplo, trans, diag, n, a, lda, x, incx) {
    // TODO support trans, lda
    uplo = uplo | 0;
    trans = trans | 0;
    diag = diag | 0;
    n = n | 0;
    a = a | 0;
    lda = lda | 0;
    x = x | 0;
    incx = incx | 0;

    var i = 0,
        j = 0,
        paii = 0,
        paji = 0,
        pxi = 0,
        pxj = 0;

    if (uplo) {
      // lower triangular matrix
      for (i = 0; (i | 0) < (n | 0); i = i + 1 | 0) {
        pxi = x + ((imul(i, incx) | 0) << 3) | 0;
        if (!diag) {
          paii = a + ((imul(i, n) | 0) + i << 3) | 0;
          darray[pxi >> 3] = darray[pxi >> 3] / darray[paii >> 3];
        }
        for (j = i + 1 | 0; (j | 0) < (n | 0); j = j + 1 | 0) {
          paji = a + ((imul(j, n) | 0) + i << 3) | 0;
          pxj = x + ((imul(j, incx) | 0) << 3) | 0;
          darray[pxj >> 3] = darray[pxj >> 3] - darray[pxi >> 3] * darray[paji >> 3];
        }
      }
    } else {
      // upper triangular matrix
      for (i = n - 1 | 0; (i | 0) >= 0; i = i - 1 | 0) {
        pxi = x + ((imul(i, incx) | 0) << 3) | 0;
        if (!diag) {
          paii = a + ((imul(i, n) | 0) + i << 3) | 0;
          darray[pxi >> 3] = darray[pxi >> 3] / darray[paii >> 3];
        }
        for (j = 0; (j | 0) < (i | 0); j = j + 1 | 0) {
          paji = a + ((imul(j, n) | 0) + i << 3) | 0;
          pxj = x + ((imul(j, incx) | 0) << 3) | 0;
          darray[pxj >> 3] = darray[pxj >> 3] - darray[pxi >> 3] * darray[paji >> 3];
        }
      }
    }
  }

  function dgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc) {
    // TODO support transa, transb, lda, ldb, ldc
    transa = transa | 0;
    transb = transb | 0;
    m = m | 0;
    n = n | 0;
    k = k | 0;
    alpha = +alpha;
    a = a | 0;
    lda = lda | 0;
    b = b | 0;
    ldb = ldb | 0;
    beta = +beta;
    c = c | 0;
    ldc = ldc | 0;

    var i = 0,
        j = 0,
        l = 0,
        aIndex = 0,
        bIndex = 0,
        cIndex = 0;

    for (i = 0; (i | 0) < (m | 0); i = i + 1 | 0) {
      for (j = 0; (j | 0) < (n | 0); j = j + 1 | 0) {
        cIndex = c + (imul(i, n) | 0) + j << 3;
        darray[cIndex >> 3] = beta * darray[cIndex >> 3];
        for (l = 0; (l | 0) < (k | 0); l = l + 1 | 0) {
          aIndex = a + (imul(i, k) | 0) + l << 3;
          bIndex = b + (imul(l, k) | 0) + j << 3;
          darray[cIndex >> 3] = +darray[cIndex >> 3] + alpha * darray[aIndex >> 3] * darray[bIndex >> 3];
        }
      }
    }
  }

  function dgesv(n, nrhs, a, lda, ipiv, b, ldb) {
    n = n | 0;
    nrhs = nrhs | 0;
    a = a | 0;
    lda = lda | 0;
    ipiv = ipiv | 0;
    b = b | 0;
    ldb = ldb | 0;

    var i = 0,
        j = 0,
        tmp = 0.0,
        pipivi = 0,
        pbi = 0,
        pbj = 0;

    dgetrf(n, n, a, lda, ipiv);

    for (i = 0; (i | 0) < (n | 0); i = i + 1 | 0) {
      pipivi = ipiv + (i << 2) | 0;
      j = uiarray[pipivi >> 2] | 0;
      pbi = b + (i << 3) | 0;
      pbj = b + (j << 3) | 0;
      tmp = +darray[pbi >> 3];
      darray[pbi >> 3] = darray[pbj >> 3];
      darray[pbj >> 3] = tmp;
    }

    dtrsv(1, 0, 1, n, a, lda, b, 1);
    dtrsv(0, 0, 0, n, a, lda, b, 1);
  }

  function dgetrf(m, n, a, lda, ipiv) {
    // TODO support lda
    m = m | 0;
    n = n | 0;
    a = a | 0;
    lda = lda | 0;
    ipiv = ipiv | 0;

    var i = 0,
        j = 0,
        k = 0,
        l = 0,
        pipivk = 0,
        paik = 0,
        pajk = 0,
        pakk = 0,
        pajl = 0,
        pakl = 0;

    for (k = 0; (k | 0) < (n - 1 | 0); k = k + 1 | 0) {
      i = k + (idamax(n - k | 0, a + ((imul(k, n) | 0) + k << 3) | 0, m) | 0) | 0;
      pipivk = ipiv + (k << 2) | 0;
      uiarray[pipivk >> 2] = i;
      dswap(n, a + ((imul(i, n) | 0) << 3) | 0, 1, a + ((imul(k, n) | 0) << 3) | 0, 1);
      for (j = k + 1 | 0; (j | 0) < (n | 0); j = j + 1 | 0) {
        pajk = a + ((imul(j, n) | 0) + k << 3) | 0;
        pakk = a + ((imul(k, n) | 0) + k << 3) | 0;
        darray[pajk >> 3] = darray[pajk >> 3] / darray[pakk >> 3];
        for (l = k + 1 | 0; (l | 0) < (n | 0); l = l + 1 | 0) {
          pajl = a + ((imul(j, n) | 0) + l << 3) | 0;
          pakl = a + ((imul(k, n) | 0) + l << 3) | 0;
          darray[pajl >> 3] = darray[pajl >> 3] - darray[pajk >> 3] * darray[pakl >> 3];
        }
      }
    }
    uiarray[ipiv + (n - 1 << 2) >> 2] = n - 1;
  }

  return {
    daxpy: daxpy,
    dasum: dasum,
    dcopy: dcopy,
    ddot: ddot,
    dswap: dswap,
    idamax: idamax,
    dgemv: dgemv,
    dtrsv: dtrsv,
    dgemm: dgemm,
    dgesv: dgesv,
    dgetrf: dgetrf
  };
}

module.exports = LinalgModule;
<|endoftext|>


<commit_before>var elementResizeEvent = require('element-resize-event');
var throttle = require('lodash.throttle');

var throttledSetState = throttle(function() {
  this.setState({componentWidth: this.getDOMNode().offsetWidth});
}, 16.666); // Throttle updates to 60 FPS.

module.exports = {
  componentDidMount: function() {
    this.setState({componentWidth: this.getDOMNode().offsetWidth});
    elementResizeEvent(this.getDOMNode(), this.onResize);
  },
  onResize: throttledSetState
};
<commit_msg>Let implementing components set an initial componentWidth<commit_after>var elementResizeEvent = require('element-resize-event');
var throttle = require('lodash.throttle');

var throttledSetState = throttle(function() {
  this.setState({componentWidth: this.getDOMNode().offsetWidth});
}, 16.666); // Throttle updates to 60 FPS.

module.exports = {
  getInitialState: function() {
    return {
      componentWidth: this.props.initialComponentWidth
    };
  },
  componentDidMount: function() {
    this.setState({componentWidth: this.getDOMNode().offsetWidth});
    elementResizeEvent(this.getDOMNode(), this.onResize);
  },
  onResize: throttledSetState
};
<|endoftext|>


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

var app = {
  root: __dirname,
  config: {
    accessToken: null,
    clientId: null,
    clientSecret: null,
    endpoint: 'https://api.toonapi.com',
    redirectUrl: null,
    timeout: 5000
  }
};

/**
 * Process HTTP response for callback
 *
 * @callback callback
 * @param err {Error, null} - httpreq error
 * @param res {object} - httpreq response details
 * @param callback {function} - `function (err, data) {}`
 * @returns {void}
 */

function httpResponse (err, res, callback) {
  var data = res && res.body || '';
  var error = null;

  if (err) {
    return callback (err);
  }

  try {
    data = JSON.parse (data);
  } catch (e) {
    e.statusCode = res.statusCode;
    e.body = data;
    return callback (e);
  }

  if (res.statusCode >= 300) {
    error = new Error ('API error');
    error.statusCode = res.statusCode;
    error.error = data;
    return callback (error);
  }

  return callback (null, data);
}

/**
  * Send HTTP request to the remote API
  *
  * @callback callback
  * @param props {object} - Request details
  * @param props.path {string} - Request path after `endpoint`
  * @param [props.method = GET] {string} - GET, POST, etc
  * @param [props.params] {object} - GET or POST fields to send
  * @param callback {function} - `function (err, data) {}`
  * @returns {void}
  */

app.httpRequest = function httpRequest (props, callback) {
  var options = {
    method: props.method || 'GET',
    url: app.config.endpoint + props.path,
    parameters: props.params || null,
    json: props.json || null,
    timeout: props.timeout || app.config.timeout,
    headers: {
      'Accept': 'application/json',
      'User-Agent': 'node/toonapi (https://github.com/fvdm/nodejs-toonapi)'
    }
  };

  if (app.config.accessToken) {
    options.headers.Authorization = 'Bearer ' + app.config.accessToken;
  }

  function doResponse (err, res) {
    httpResponse (err, res, callback);
  }

  httpreq.doRequest (options, doResponse);
};

/**
 * Module config and interface
 *
 * @param set {object} - Configuration settings
 * @param set.clientId {string} - API client_id
 * @param set.clientSecret {string} - API client_secret
 * @param set.redirectUrl {string} - API redirect URL
 * @returns {object} - Interface methods
 */

function setup (set) {
  app.config.accessToken = set.accessToken || null;
  app.config.clientId = set.clientId || null;
  app.config.clientSecret = set.clientSecret || null;
  app.config.endpoint = set.endpoint || app.config.endpoint;
  app.config.redirectUri = set.redirectUri || null;
  app.config.timeout = set.timeout || app.config.timeout;

  return {
    oauth: require (app.root + '/lib/oauth.js') (app),
    agreements: require (app.root + '/lib/agreements.js') (app),
    consumption: require (app.root + '/lib/consumption.js') (app),
    devices: require (app.root + '/lib/devices.js') (app),
    display: require (app.root + '/lib/display.js') (app),
    pushEvent: require (app.root + '/lib/pushEvent.js') (app),
    temperature: require (app.root + '/lib/temperature.js') (app)
  };
}

module.exports = setup;
<commit_msg>Refactor(errors): Moved errors to dedicated function<commit_after>var httpreq = require ('httpreq');

var app = {
  root: __dirname,
  config: {
    accessToken: null,
    clientId: null,
    clientSecret: null,
    endpoint: 'https://api.toonapi.com',
    redirectUrl: null,
    timeout: 5000
  }
};

/**
 * Callback an error
 *
 * @callback callback
 * @param message {string} - Error.message
 * @param err {Error, mixed} - Error.error
 * @param code {number} - Error.statusCode
 * @param callback {function} - `function (err) {}`
 * @returns {void}
 */

app.doError = function doError (message, err, code, callback) {
  var error = new Error (message);

  error.error = err;
  error.statusCode = code;
  callback (error);
};

/**
 * Process HTTP response for callback
 *
 * @callback callback
 * @param err {Error, null} - httpreq error
 * @param res {object} - httpreq response details
 * @param callback {function} - `function (err, data) {}`
 * @returns {void}
 */

function httpResponse (err, res, callback) {
  var data = res && res.body || '';

  if (err) {
    return callback (err);
  }

  // Parse response
  try {
    data = JSON.parse (data);
  } catch (e) {
    e.body = data;
    return app.doError ('invalid response', e, res.statusCode, callback);
  }

  // Catch JSON API error
  if (res.statusCode >= 300) {
    return app.doError ('API error', data, res.statusCode, callback);
  }

  return callback (null, data);
}

/**
  * Send HTTP request to the remote API
  *
  * @callback callback
  * @param props {object} - Request details
  * @param props.path {string} - Request path after `endpoint`
  * @param [props.method = GET] {string} - GET, POST, etc
  * @param [props.params] {object} - GET or POST fields to send
  * @param callback {function} - `function (err, data) {}`
  * @returns {void}
  */

app.httpRequest = function httpRequest (props, callback) {
  var options = {
    method: props.method || 'GET',
    url: app.config.endpoint + props.path,
    parameters: props.params || null,
    json: props.json || null,
    timeout: props.timeout || app.config.timeout,
    headers: {
      'Accept': 'application/json',
      'User-Agent': 'node/toonapi (https://github.com/fvdm/nodejs-toonapi)'
    }
  };

  if (app.config.accessToken) {
    options.headers.Authorization = 'Bearer ' + app.config.accessToken;
  }

  function doResponse (err, res) {
    httpResponse (err, res, callback);
  }

  httpreq.doRequest (options, doResponse);
};

/**
 * Module config and interface
 *
 * @param set {object} - Configuration settings
 * @param set.clientId {string} - API client_id
 * @param set.clientSecret {string} - API client_secret
 * @param set.redirectUrl {string} - API redirect URL
 * @returns {object} - Interface methods
 */

function setup (set) {
  app.config.accessToken = set.accessToken || null;
  app.config.clientId = set.clientId || null;
  app.config.clientSecret = set.clientSecret || null;
  app.config.endpoint = set.endpoint || app.config.endpoint;
  app.config.redirectUri = set.redirectUri || null;
  app.config.timeout = set.timeout || app.config.timeout;

  return {
    oauth: require (app.root + '/lib/oauth.js') (app),
    agreements: require (app.root + '/lib/agreements.js') (app),
    consumption: require (app.root + '/lib/consumption.js') (app),
    devices: require (app.root + '/lib/devices.js') (app),
    display: require (app.root + '/lib/display.js') (app),
    pushEvent: require (app.root + '/lib/pushEvent.js') (app),
    temperature: require (app.root + '/lib/temperature.js') (app)
  };
}

module.exports = setup;
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { ScrollView, Animated, Platform, Easing } from 'react-native';
import shallowCompare from 'react-addons-shallow-compare';

export default class Carousel extends Component {

    static propTypes = {
        ...ScrollView.propTypes,
        /**
         * Supply items to loop on
         */
        items: PropTypes.array.isRequired,
        /**
         * Width in pixels of your slider according
         * to your styles
         */
        sliderWidth: PropTypes.number.isRequired,
        /**
         * Width in pixels of your elements
         */
        itemWidth: PropTypes.number.isRequired,
        /**
         * Function returning a react element. The entry
         * data is the 1st parameter, its index is the 2nd
         */
        renderItem: PropTypes.func.isRequired,
        /**
         * Style of each item's container
         */
        slideStyle: PropTypes.number.isRequired,
        /**
         * whether to implement a `shouldComponentUpdate`
         * strategy to minimize updates
         */
        shouldOptimizeUpdates: PropTypes.bool,
        /**
        * Global wrapper's style
        */
        containerCustomStyle: PropTypes.number,
        /**
        * Content container's style
        */
        contentContainerCustomStyle: PropTypes.number,
        /**
         * Delta x when swiping to trigger the snap
         */
        swipeThreshold: PropTypes.number,
        /**
         * Animated animation to use. Provide the name
         * of the method, defaults to timing
         */
        animationFunc: PropTypes.string,
        /**
         * Animation options to be merged with the
         * default ones. Can be used w/ animationFunc
         */
        animationOptions: PropTypes.object,
        /**
         * Scale factor of the inactive slides
         */
        inactiveSlideScale: PropTypes.number,
        /**
         * Opacity value of the inactive slides
         */
        inactiveSlideOpacity: PropTypes.number,
        /**
         * Index of the first item to display
         */
        firstItem: PropTypes.number,
        /**
         * Trigger autoplay
         */
        autoplay: PropTypes.bool,
        /**
         * Delay until navigating to the next item
         */
        autoplayInterval: PropTypes.number,
        /**
         * Delay before enabling autoplay on startup and
         * after releasing the touch
         */
        autoplayDelay: PropTypes.number,
        /**
         * If enabled, releasing the touch will scroll
         * to the center of the nearest/active item
         */
        enableSnap: PropTypes.bool,
        /**
         * Snapping on android is kinda choppy, especially
         * when swiping quickly so you can disable it
         */
        snapOnAndroid: PropTypes.bool,
        /**
         * Fired when snapping to an item
         */
        onSnapToItem: PropTypes.func
    };

    static defaultProps = {
        shouldOptimizeUpdates: true,
        autoplay: false,
        autoplayInterval: 3000,
        autoplayDelay: 5000,
        firstItem: 0,
        enableSnap: true,
        snapOnAndroid: false,
        swipeThreshold: 20,
        animationFunc: 'timing',
        animationOptions: {
            easing: Easing.elastic(1)
        },
        slideStyle: {},
        containerCustomStyle: null,
        contentContainerCustomStyle: null,
        inactiveSlideScale: 0.9,
        inactiveSlideOpacity: 1
    }

    constructor (props) {
        super(props);
        this.state = {
            activeItem: props.firstItem
        };
        this._positions = [];
        this._calcCardPositions(props);
        this._onScroll = this._onScroll.bind(this);
        this._onScrollEndDrag = this._snapEnabled ? this._onScrollEndDrag.bind(this) : false;
        this._onScrollBegin = this._snapEnabled ? this._onScrollBegin.bind(this) : false;
        this._initInterpolators = this._initInterpolators.bind(this);
        this._onTouchRelease = props.autoplay ? this._onTouchRelease.bind(this) : undefined;
        this._onTouchMove = props.autoplay ? this._onTouchMove.bind(this) : undefined;
    }

    componentDidMount () {
        const { firstItem, autoplay } = this.props;

        this._initInterpolators(this.props);
        setTimeout(() => {
            this.snapToItem(firstItem, false, false);
        }, 0);
        if (autoplay) {
            this.startAutoplay();
        }
    }

    shouldComponentUpdate (nextProps, nextState) {
        if (this.props.shouldOptimizeUpdates === false) {
            return true;
        } else {
            const { items, firstItem, autoplay } = nextProps;
            if(items.length !== this.props.items.length) {
                nextState.interpolators = this._initInterpolators(nextProps);
                setTimeout(() => {
                    this.snapToItem(firstItem, false, false);
                }, 0);
                if (autoplay) {
                    this.startAutoplay();
                }
            }
            return shallowCompare(this, nextProps, nextState);
        }
    }

    componentWillUnmount () {
        this.stopAutoplay();
    }

    get _snapEnabled () {
        const { enableSnap, snapOnAndroid } = this.props;

        return enableSnap && (Platform.OS === 'ios' || snapOnAndroid);
    }

    get _nextItem () {
        const { activeItem } = this.state;

        return this._positions[activeItem + 1] ? activeItem + 1 : 0;
    }

    _calcCardPositions (props = this.props) {
        const { items, itemWidth } = props;

        items.forEach((item, index) => {
            this._positions[index] = {
                start: index * itemWidth
            };
            this._positions[index].end = this._positions[index].start + itemWidth;
        });
    }

    _initInterpolators (props = this.props) {
        const { items, firstItem } = props;
        let interpolators = [];

        items.forEach((item, index) => {
            interpolators.push(new Animated.Value(index === firstItem ? 1 : 0));
        });
        this.setState({ interpolators });

        return interpolators;
    }

    _getActiveItem (centerX, offset = 25) {
        for (let i = 0; i < this._positions.length; i++) {
            const { start, end } = this._positions[i];
            if (centerX + offset >= start && centerX - offset <= end) {
                return i;
            }
        }
        return 0;
    }

    _getCenterX (event) {
        const { sliderWidth, itemWidth } = this.props;
        const containerSideMargin = (sliderWidth - itemWidth) / 2;

        return event.nativeEvent.contentOffset.x + sliderWidth / 2 - containerSideMargin;
    }

    _onScroll (event) {
        const { animationFunc, animationOptions } = this.props;
        const { activeItem } = this.state;
        const newActiveItem = this._getActiveItem(this._getCenterX(event));

        if (activeItem !== newActiveItem) {
            Animated[animationFunc](
                this.state.interpolators[activeItem],
                { ...animationOptions, toValue: 0 }
            ).start();
            this.setState({ activeItem: newActiveItem });
            Animated[animationFunc](
                this.state.interpolators[newActiveItem],
                { ...animationOptions, toValue: 1 }
            ).start();
        }
    }

    _onScrollBegin (event) {
        this._scrollStartX = event.nativeEvent.contentOffset.x;
        this._scrollStartActive = this.state.activeItem;
    }

    _onScrollEndDrag (event) {
        this._scrollEndX = event.nativeEvent.contentOffset.x;
        this._scrollEndActive = this.state.activeItem;

        const deltaX = this._scrollEndX - this._scrollStartX;

        if (this._snapEnabled) {
            this._snapScroll(deltaX);
        }
    }

    _onTouchMove () {
        if (this._autoplaying) {
            this.stopAutoplay();
        }
        clearTimeout(this._enableAutoplayTimeout);
    }

    _onTouchRelease () {
        const { autoplayDelay } = this.props;

        setTimeout(() => {
            this._enableAutoplayTimeout =
                setTimeout(() => {
                    this.startAutoplay(true);
                }, autoplayDelay);
        }, 1000);
    }

    _snapScroll (deltaX) {
        const { swipeThreshold } = this.props;

        if (this._scrollStartActive !== this._scrollEndActive) {
            // Snap to the new active item
            this.snapToItem(this._scrollEndActive);
        } else {
            // Snap depending on delta
            if (deltaX > 0) {
                if (deltaX > swipeThreshold) {
                    this.snapToItem(this._scrollStartActive + 1);
                } else {
                    this.snapToItem(this._scrollEndActive);
                }
            } else if (deltaX < 0) {
                if (deltaX < -swipeThreshold) {
                    this.snapToItem(this._scrollStartActive - 1);
                } else {
                    this.snapToItem(this._scrollEndActive);
                }
            } else {
                // Snap to current
                this.snapToItem(this._scrollEndActive);
            }
        }
    }

    get items () {
        const { items, renderItem, slideStyle, inactiveSlideScale, inactiveSlideOpacity } = this.props;
        if (!this.state.interpolators || !this.state.interpolators.length) {
            return false;
        }

        return items.map((entry, index) => {
            const animatedValue = this.state.interpolators[index];
            return (
                <Animated.View
                  key={`carousel-item-${index}`}
                  style={[
                      slideStyle,
                      {transform: [{
                          scale: animatedValue.interpolate({
                              inputRange: [0, 1],
                              outputRange: [inactiveSlideScale, 1]
                          })
                      }],
                          opacity: animatedValue.interpolate({
                              inputRange: [0, 1],
                              outputRange: [inactiveSlideOpacity, 1]
                          })
                      }
                  ]}>
                    { renderItem(entry, index) }
                </Animated.View>
            );
        });
    }

    get currentIndex () {
        return this.state.activeItem;
    }

    startAutoplay (instantly = false) {
        const { autoplayInterval, autoplayDelay } = this.props;

        if (this._autoplaying) {
            return;
        }

        setTimeout(() => {
            this._autoplaying = true;
            this._autoplayInterval =
                setInterval(() => {
                    this.snapToItem(this._nextItem);
                }, autoplayInterval);
        }, instantly ? 0 : autoplayDelay);
    }

    stopAutoplay () {
        this._autoplaying = false;
        clearInterval(this._autoplayInterval);
    }

    snapToItem (index, animated = true, fireCallback = true) {
        const itemsLength = this._positions.length;

        if (index >= itemsLength) {
            index = itemsLength - 1;
            fireCallback = false;
        } else if (index < 0) {
            index = 0;
            fireCallback = false;
        }

        const snapX = this._positions[index].start;

        // Make sure the component hasn't been unmounted
        if (this.refs.scrollview) {
            this.refs.scrollview.scrollTo({x: snapX, y: 0, animated});
            this.props.onSnapToItem && fireCallback && this.props.onSnapToItem(index, this.props.items[index]);
        }
    }

    snapToNext (animated = true) {
        const itemsLength = this._positions.length;

        let newIndex = this.currentIndex + 1;
        if (newIndex > itemsLength - 1) {
            newIndex = 0;
        }
        this.snapToItem(newIndex, animated);
    }

    snapToPrev (animated = true) {
        const itemsLength = this._positions.length;

        let newIndex = this.currentIndex - 1;
        if (newIndex < 0) {
            newIndex = itemsLength - 1;
        }
        this.snapToItem(newIndex, animated);
    }

    render () {
        const { sliderWidth, itemWidth, containerCustomStyle, contentContainerCustomStyle } = this.props;

        const containerSideMargin = (sliderWidth - itemWidth) / 2;
        const style = [
            { paddingHorizontal: Platform.OS === 'ios' ? containerSideMargin : 0 },
            containerCustomStyle || {}
        ];
        const contentContainerStyle = [
            { paddingHorizontal: Platform.OS === 'android' ? containerSideMargin : 0 },
            contentContainerCustomStyle || {}
        ];

        return (
            <ScrollView
              {...this.props}
              style={style}
              contentContainerStyle={contentContainerStyle}
              ref={'scrollview'}
              horizontal={true}
              onScrollBeginDrag={this._onScrollBegin}
              onScrollEndDrag={this._onScrollEndDrag}
              onResponderRelease={this._onTouchRelease}
              onResponderMove={this._onTouchMove}
              onScroll={this._onScroll}
              scrollEventThrottle={50}
              >
                { this.items }
            </ScrollView>
        );
    }
}
<commit_msg>Update fix issue with interpolators and items prop length<commit_after>import React, { Component, PropTypes } from 'react';
import { ScrollView, Animated, Platform, Easing } from 'react-native';
import shallowCompare from 'react-addons-shallow-compare';

export default class Carousel extends Component {

    static propTypes = {
        ...ScrollView.propTypes,
        /**
         * Supply items to loop on
         */
        items: PropTypes.array.isRequired,
        /**
         * Width in pixels of your slider according
         * to your styles
         */
        sliderWidth: PropTypes.number.isRequired,
        /**
         * Width in pixels of your elements
         */
        itemWidth: PropTypes.number.isRequired,
        /**
         * Function returning a react element. The entry
         * data is the 1st parameter, its index is the 2nd
         */
        renderItem: PropTypes.func.isRequired,
        /**
         * Style of each item's container
         */
        slideStyle: PropTypes.number.isRequired,
        /**
         * whether to implement a `shouldComponentUpdate`
         * strategy to minimize updates
         */
        shouldOptimizeUpdates: PropTypes.bool,
        /**
        * Global wrapper's style
        */
        containerCustomStyle: PropTypes.number,
        /**
        * Content container's style
        */
        contentContainerCustomStyle: PropTypes.number,
        /**
         * Delta x when swiping to trigger the snap
         */
        swipeThreshold: PropTypes.number,
        /**
         * Animated animation to use. Provide the name
         * of the method, defaults to timing
         */
        animationFunc: PropTypes.string,
        /**
         * Animation options to be merged with the
         * default ones. Can be used w/ animationFunc
         */
        animationOptions: PropTypes.object,
        /**
         * Scale factor of the inactive slides
         */
        inactiveSlideScale: PropTypes.number,
        /**
         * Opacity value of the inactive slides
         */
        inactiveSlideOpacity: PropTypes.number,
        /**
         * Index of the first item to display
         */
        firstItem: PropTypes.number,
        /**
         * Trigger autoplay
         */
        autoplay: PropTypes.bool,
        /**
         * Delay until navigating to the next item
         */
        autoplayInterval: PropTypes.number,
        /**
         * Delay before enabling autoplay on startup and
         * after releasing the touch
         */
        autoplayDelay: PropTypes.number,
        /**
         * If enabled, releasing the touch will scroll
         * to the center of the nearest/active item
         */
        enableSnap: PropTypes.bool,
        /**
         * Snapping on android is kinda choppy, especially
         * when swiping quickly so you can disable it
         */
        snapOnAndroid: PropTypes.bool,
        /**
         * Fired when snapping to an item
         */
        onSnapToItem: PropTypes.func
    };

    static defaultProps = {
        shouldOptimizeUpdates: true,
        autoplay: false,
        autoplayInterval: 3000,
        autoplayDelay: 5000,
        firstItem: 0,
        enableSnap: true,
        snapOnAndroid: false,
        swipeThreshold: 20,
        animationFunc: 'timing',
        animationOptions: {
            easing: Easing.elastic(1)
        },
        slideStyle: {},
        containerCustomStyle: null,
        contentContainerCustomStyle: null,
        inactiveSlideScale: 0.9,
        inactiveSlideOpacity: 1
    }

    constructor (props) {
        super(props);
        this.state = {
            activeItem: props.firstItem
        };
        this._positions = [];
        this._calcCardPositions(props);
        this._onScroll = this._onScroll.bind(this);
        this._onScrollEndDrag = this._snapEnabled ? this._onScrollEndDrag.bind(this) : false;
        this._onScrollBegin = this._snapEnabled ? this._onScrollBegin.bind(this) : false;
        this._initInterpolators = this._initInterpolators.bind(this);
        this._onTouchRelease = props.autoplay ? this._onTouchRelease.bind(this) : undefined;
        this._onTouchMove = props.autoplay ? this._onTouchMove.bind(this) : undefined;
    }

    componentDidMount () {
        const { firstItem, autoplay } = this.props;

        this._initInterpolators(this.props);
        setTimeout(() => {
            this.snapToItem(firstItem, false, false);
        }, 0);
        if (autoplay) {
            this.startAutoplay();
        }
    }

    shouldComponentUpdate (nextProps, nextState) {
        if (this.props.shouldOptimizeUpdates === false) {
            return true;
        } else {
            return shallowCompare(this, nextProps, nextState);
        }
    }

    componentWillReceiveProps(nextProps) {
        const { items, firstItem } = nextProps;
        if(items.length !== this.props.items.length) {
            this._positions = [];
            this._calcCardPositions(nextProps);
            this._initInterpolators(nextProps);
            this.setState({activeItem: firstItem});
        }
    }

    componentWillUnmount () {
        this.stopAutoplay();
    }

    get _snapEnabled () {
        const { enableSnap, snapOnAndroid } = this.props;

        return enableSnap && (Platform.OS === 'ios' || snapOnAndroid);
    }

    get _nextItem () {
        const { activeItem } = this.state;

        return this._positions[activeItem + 1] ? activeItem + 1 : 0;
    }

    _calcCardPositions (props = this.props) {
        const { items, itemWidth } = props;

        items.forEach((item, index) => {
            this._positions[index] = {
                start: index * itemWidth
            };
            this._positions[index].end = this._positions[index].start + itemWidth;
        });
    }

    _initInterpolators (props = this.props) {
        const { items, firstItem } = props;
        let interpolators = [];

        items.forEach((item, index) => {
            interpolators.push(new Animated.Value(index === firstItem ? 1 : 0));
        });
        this.setState({ interpolators });
    }

    _getActiveItem (centerX, offset = 25) {
        for (let i = 0; i < this._positions.length; i++) {
            const { start, end } = this._positions[i];
            if (centerX + offset >= start && centerX - offset <= end) {
                return i;
            }
        }
        return 0;
    }

    _getCenterX (event) {
        const { sliderWidth, itemWidth } = this.props;
        const containerSideMargin = (sliderWidth - itemWidth) / 2;

        return event.nativeEvent.contentOffset.x + sliderWidth / 2 - containerSideMargin;
    }

    _onScroll (event) {
        const { animationFunc, animationOptions } = this.props;
        const { activeItem } = this.state;
        const newActiveItem = this._getActiveItem(this._getCenterX(event));

        if (activeItem !== newActiveItem) {
            Animated[animationFunc](
                this.state.interpolators[activeItem],
                { ...animationOptions, toValue: 0 }
            ).start();
            this.setState({ activeItem: newActiveItem });
            Animated[animationFunc](
                this.state.interpolators[newActiveItem],
                { ...animationOptions, toValue: 1 }
            ).start();
        }
    }

    _onScrollBegin (event) {
        this._scrollStartX = event.nativeEvent.contentOffset.x;
        this._scrollStartActive = this.state.activeItem;
    }

    _onScrollEndDrag (event) {
        this._scrollEndX = event.nativeEvent.contentOffset.x;
        this._scrollEndActive = this.state.activeItem;

        const deltaX = this._scrollEndX - this._scrollStartX;

        if (this._snapEnabled) {
            this._snapScroll(deltaX);
        }
    }

    _onTouchMove () {
        if (this._autoplaying) {
            this.stopAutoplay();
        }
        clearTimeout(this._enableAutoplayTimeout);
    }

    _onTouchRelease () {
        const { autoplayDelay } = this.props;

        setTimeout(() => {
            this._enableAutoplayTimeout =
                setTimeout(() => {
                    this.startAutoplay(true);
                }, autoplayDelay);
        }, 1000);
    }

    _snapScroll (deltaX) {
        const { swipeThreshold } = this.props;

        if (this._scrollStartActive !== this._scrollEndActive) {
            // Snap to the new active item
            this.snapToItem(this._scrollEndActive);
        } else {
            // Snap depending on delta
            if (deltaX > 0) {
                if (deltaX > swipeThreshold) {
                    this.snapToItem(this._scrollStartActive + 1);
                } else {
                    this.snapToItem(this._scrollEndActive);
                }
            } else if (deltaX < 0) {
                if (deltaX < -swipeThreshold) {
                    this.snapToItem(this._scrollStartActive - 1);
                } else {
                    this.snapToItem(this._scrollEndActive);
                }
            } else {
                // Snap to current
                this.snapToItem(this._scrollEndActive);
            }
        }
    }

    get items () {
        const { items, renderItem, slideStyle, inactiveSlideScale, inactiveSlideOpacity } = this.props;
        if (!this.state.interpolators || !this.state.interpolators.length) {
            return false;
        }

        return items.map((entry, index) => {
            const animatedValue = this.state.interpolators[index];
            return (
                <Animated.View
                  key={`carousel-item-${index}`}
                  style={[
                      slideStyle,
                      {transform: [{
                          scale: animatedValue.interpolate({
                              inputRange: [0, 1],
                              outputRange: [inactiveSlideScale, 1]
                          })
                      }],
                          opacity: animatedValue.interpolate({
                              inputRange: [0, 1],
                              outputRange: [inactiveSlideOpacity, 1]
                          })
                      }
                  ]}>
                    { renderItem(entry, index) }
                </Animated.View>
            );
        });
    }

    get currentIndex () {
        return this.state.activeItem;
    }

    startAutoplay (instantly = false) {
        const { autoplayInterval, autoplayDelay } = this.props;

        if (this._autoplaying) {
            return;
        }

        setTimeout(() => {
            this._autoplaying = true;
            this._autoplayInterval =
                setInterval(() => {
                    this.snapToItem(this._nextItem);
                }, autoplayInterval);
        }, instantly ? 0 : autoplayDelay);
    }

    stopAutoplay () {
        this._autoplaying = false;
        clearInterval(this._autoplayInterval);
    }

    snapToItem (index, animated = true, fireCallback = true) {
        const itemsLength = this._positions.length;

        if (index >= itemsLength) {
            index = itemsLength - 1;
            fireCallback = false;
        } else if (index < 0) {
            index = 0;
            fireCallback = false;
        }

        const snapX = this._positions[index].start;

        // Make sure the component hasn't been unmounted
        if (this.refs.scrollview) {
            this.refs.scrollview.scrollTo({x: snapX, y: 0, animated});
            this.props.onSnapToItem && fireCallback && this.props.onSnapToItem(index, this.props.items[index]);
        }
    }

    snapToNext (animated = true) {
        const itemsLength = this._positions.length;

        let newIndex = this.currentIndex + 1;
        if (newIndex > itemsLength - 1) {
            newIndex = 0;
        }
        this.snapToItem(newIndex, animated);
    }

    snapToPrev (animated = true) {
        const itemsLength = this._positions.length;

        let newIndex = this.currentIndex - 1;
        if (newIndex < 0) {
            newIndex = itemsLength - 1;
        }
        this.snapToItem(newIndex, animated);
    }

    render () {
        const { sliderWidth, itemWidth, containerCustomStyle, contentContainerCustomStyle } = this.props;

        const containerSideMargin = (sliderWidth - itemWidth) / 2;
        const style = [
            { paddingHorizontal: Platform.OS === 'ios' ? containerSideMargin : 0 },
            containerCustomStyle || {}
        ];
        const contentContainerStyle = [
            { paddingHorizontal: Platform.OS === 'android' ? containerSideMargin : 0 },
            contentContainerCustomStyle || {}
        ];

        return (
            <ScrollView
              {...this.props}
              style={style}
              contentContainerStyle={contentContainerStyle}
              ref={'scrollview'}
              horizontal={true}
              onScrollBeginDrag={this._onScrollBegin}
              onScrollEndDrag={this._onScrollEndDrag}
              onResponderRelease={this._onTouchRelease}
              onResponderMove={this._onTouchMove}
              onScroll={this._onScroll}
              scrollEventThrottle={50}
              >
                { this.items }
            </ScrollView>
        );
    }
}
<|endoftext|>


<commit_before>var _ = require('lodash')
  , volume = require('./lib/volume')
  , rooms = require('./lib/rooms')
  , responses = require('./lib/responses')
  , helptext = require('./lib/helptext');

module.exports = function(robot) {
  robot.brain.on('loaded', function() {
    init(robot.brain.snoozer);
  });

  robot.respond(/cinco help/, function(msg) {
    msg.send(helptext);
  });

  robot.respond(/cinco (facetime )?(party )?snoozer/i, function(msg) {
    var room = msg.message.room;

    if (rooms.has(room)) {
      rooms.remove(room);
      msg.send('Cinco Facetime Party Snoozer is powered off! You\'ll have to make your own conversation now.');
    } else {
      rooms.add(room);
      volume.setToDefault(room);
      msg.send('Cinco Facetime Party Snoozer is on! Now get to talking about whatever boring thing you want!');
    }
  });

  robot.respond(/cinco status/i, function(msg) {
    var room = msg.message.room;
    if (rooms.has(room)) {
      msg.send('Cinco Facetime Party Snoozer is on and ready to talk!');
    } else {
      msg.send('Cinco Facetime Party Snoozer is off, maybe you should turn it on so this place feels lively!');
    }
  });

  robot.respond(/cinco louder/i, function(msg) {
    var room = msg.message.room;
    volume.louder(room);
    msg.send('Volume set to ' + volume.value(room));
  });

  robot.respond(/cinco loudest/i, function(msg) {
    var room = msg.message.room;
    volume.loudest(room);
    msg.send('Volume set to ' + volume.value(room));
  });

  robot.respond(/cinco quieter/i, function(msg) {
    var room = msg.message.room;
    volume.quieter(room);
    msg.send('Volume set to ' + volume.value(room));
  });

  robot.respond(/cinco quietest/i, function(msg) {
    var room = msg.message.room;
    volume.quietest(room);
    msg.send('Volume set to ' + volume.value(room));
  });

  robot.respond(/cinco reset/i, function(msg) {
    init();
    msg.send('Cinco Facetime Party Snoozer has been reset for all channels.');
  });

  // the magic
  robot.hear(/.*/i, function(msg) {
    var room = msg.message.room
      , loudEnough = _.random(volume.min, volume.max) <= volume.value(room);

    if (rooms.has(room) && loudEnough) {
      msg.send(responses.random());
    }
  });

  robot.respond(/cinco debug/i, function(msg) {
    msg.send(JSON.stringify(robot.brain.snoozer, null, 2));
  });

  function init(initialVal) {
    robot.brain.snoozer = initialVal || {};
    volume.init(robot.brain.snoozer);
    rooms.init(robot.brain.snoozer);

  }
};
<commit_msg>shaping up the wording<commit_after>var _ = require('lodash')
  , volume = require('./lib/volume')
  , rooms = require('./lib/rooms')
  , responses = require('./lib/responses')
  , helptext = require('./lib/helptext');

module.exports = function(robot) {
  robot.brain.on('loaded', function() {
    init(robot.brain.snoozer);
  });

  robot.respond(/cinco help/, function(msg) {
    msg.send(helptext);
  });

  robot.respond(/cinco (facetime )?(party )?snoozer/i, function(msg) {
    var room = msg.message.room;

    if (rooms.has(room)) {
      rooms.remove(room);
      msg.send('Cinco Facetime Party Snoozer is powered off! You\'ll have to make your own conversation now.');
    } else {
      rooms.add(room);
      volume.setToDefault(room);
      msg.send('Cinco Facetime Party Snoozer is on! Now you can talk about whatever boring thing you want!');
    }
  });

  robot.respond(/cinco status/i, function(msg) {
    var room = msg.message.room;
    if (rooms.has(room)) {
      msg.send('Cinco Facetime Party Snoozer is on and ready to talk!');
    } else {
      msg.send('Cinco Facetime Party Snoozer is off, maybe you should turn it on so this place feels lively!');
    }
  });

  robot.respond(/cinco louder/i, function(msg) {
    var room = msg.message.room;
    volume.louder(room);
    msg.send('Volume set to ' + volume.value(room));
  });

  robot.respond(/cinco loudest/i, function(msg) {
    var room = msg.message.room;
    volume.loudest(room);
    msg.send('Volume set to ' + volume.value(room));
  });

  robot.respond(/cinco quieter/i, function(msg) {
    var room = msg.message.room;
    volume.quieter(room);
    msg.send('Volume set to ' + volume.value(room));
  });

  robot.respond(/cinco quietest/i, function(msg) {
    var room = msg.message.room;
    volume.quietest(room);
    msg.send('Volume set to ' + volume.value(room));
  });

  robot.respond(/cinco reset/i, function(msg) {
    init();
    msg.send('Cinco Facetime Party Snoozer has been reset for all channels.');
  });

  // the magic
  robot.hear(/.*/i, function(msg) {
    var room = msg.message.room
      , loudEnough = _.random(volume.min, volume.max) <= volume.value(room);

    if (rooms.has(room) && loudEnough) {
      msg.send(responses.random());
    }
  });

  robot.respond(/cinco debug/i, function(msg) {
    msg.send(JSON.stringify(robot.brain.snoozer, null, 2));
  });

  function init(initialVal) {
    robot.brain.snoozer = initialVal || {};
    volume.init(robot.brain.snoozer);
    rooms.init(robot.brain.snoozer);
  }
};
<|endoftext|>


<commit_before>'use strict';

var decompress = require('decompress');
var eachAsync = require('each-async');
var fs = require('fs');
var mkdir = require('mkdirp');
var path = require('path');
var request = require('request');
var through = require('through2');

/**
 * Download a file to a given destination
 *
 * Options:
 *
 *   - `extract` Try extracting the file
 *   - `mode` Set mode on the downloaded files
 *   - `strip` Equivalent to --strip-components for tar
 *
 * @param {String|Array|Object} url
 * @param {String} dest
 * @param {Object} opts
 * @api public
 */

module.exports = function (url, dest, opts) {
    url = Array.isArray(url) ? url : [url];
    opts = opts || {};

    var stream = through();
    var strip = +opts.strip || '0';

    eachAsync(url, function (url, index, done) {
        var req;
        var target = path.join(dest, path.basename(url));

        opts.url = url;

        if (url.url && url.name) {
            target = path.join(dest, url.name);
            opts.url = url.url;
        }

        req = request.get(opts);

        req.on('data', function (data) {
            stream.emit('data', data);
        });

        req.on('error', function (err) {
            stream.emit('error', err);
        });

        req.on('response', function (res) {
            var mime = res.headers['content-type'];
            var status = res.statusCode;
            var end;

            if (status < 200 || status >= 300) {
                stream.emit('error', status);
                return;
            }

            stream.emit('response', res);

            if (opts.extract && decompress.canExtract(url, mime)) {
                var ext = decompress.canExtract(url) ? url : mime;

                end = decompress.extract({
                    ext: ext,
                    path: dest,
                    strip: strip
                });
            } else {
                if (!fs.existsSync(dest)) {
                    mkdir.sync(dest);
                }

                end = fs.createWriteStream(target);
            }

            req.pipe(end);

            end.on('close', function () {
                if (!opts.extract && opts.mode) {
                    fs.chmodSync(target, opts.mode);
                }

                done();
            });
        });
    }, function () {
        stream.emit('close');
    });

    return stream;
};
<commit_msg>allow complex url description when extracting<commit_after>'use strict';

var decompress = require('decompress');
var eachAsync = require('each-async');
var fs = require('fs');
var mkdir = require('mkdirp');
var path = require('path');
var request = require('request');
var through = require('through2');

/**
 * Download a file to a given destination
 *
 * Options:
 *
 *   - `extract` Try extracting the file
 *   - `mode` Set mode on the downloaded files
 *   - `strip` Equivalent to --strip-components for tar
 *
 * @param {String|Array|Object} url
 * @param {String} dest
 * @param {Object} opts
 * @api public
 */

module.exports = function (url, dest, opts) {
    url = Array.isArray(url) ? url : [url];
    opts = opts || {};

    var stream = through();
    var strip = +opts.strip || '0';

    eachAsync(url, function (url, index, done) {
        var req;
        var target = path.join(dest, path.basename(url));

        opts.url = url;

        if (url.url && url.name) {
            target = path.join(dest, url.name);
            opts.url = url.url;
        }

        req = request.get(opts);

        req.on('data', function (data) {
            stream.emit('data', data);
        });

        req.on('error', function (err) {
            stream.emit('error', err);
        });

        req.on('response', function (res) {
            var mime = res.headers['content-type'];
            var status = res.statusCode;
            var end;

            if (status < 200 || status >= 300) {
                stream.emit('error', status);
                return;
            }

            stream.emit('response', res);

            if (opts.extract && decompress.canExtract(opts.url, mime)) {
                var ext = decompress.canExtract(opts.url) ? opts.url : mime;

                end = decompress.extract({
                    ext: ext,
                    path: dest,
                    strip: strip
                });
            } else {
                if (!fs.existsSync(dest)) {
                    mkdir.sync(dest);
                }

                end = fs.createWriteStream(target);
            }

            req.pipe(end);

            end.on('close', function () {
                if (!opts.extract && opts.mode) {
                    fs.chmodSync(target, opts.mode);
                }

                done();
            });
        });
    }, function () {
        stream.emit('close');
    });

    return stream;
};
<|endoftext|>