<commit_before>module.exports = createConsole;
module.exports.load = load;
module.exports.combine = combine;
module.exports.getCellContent = getCellContent;
module.exports.insert = insert;
module.exports.insert.Array = insertArray;
module.exports.insert.Object = insertObject;

var Table = require('cli-table');
var requireAll = require('require-all');

function createConsole(objects) {
  var oldLog = console.log;

  var konsole = function printObject(input, fields) {
    var str = toString(objects, input, fields);
    if (str) {
      oldLog(str);
    }
    else {
      oldLog(input);
    }
  };

  // populate methods from console
  for (var key in console) {
    konsole[key] = console[key];
  }

  // replace .log()
  konsole.log = function log() {
    var args = [];
    var str;
    for (var i = 0; i < arguments.length; i++) {
      str = toString(objects, arguments[i]);
      if (str) {
        oldLog(str);
      }
      else {
        args.push(arguments[i]);
      }
    }
    oldLog.apply(this, args);
  };

  // add .toString()
  konsole.toString = function objectToString(input, fields) {
    return toString(objects, input, fields);
  };

  // save config
  konsole._tconsoleConfig = objects;

  return konsole;
}

function toString(objects, input, fields) {
  for (var type in objects) {
    if (objects[type].test && objects[type].test.call(input)) {
      fields = fields || objects[type].defaultFields || Object.keys(objects[type].fields);
      if (fields === '*')
        fields = Object.keys(objects[type].fields);

      return fromObject(objects, input, type, fields);
    }
  }

  if (input instanceof Array) {
    var satisfiesAll = false;
    var tester;

    for (var type in objects) {
      tester = objects[type].test;
      if (!tester && /^array:/.test(type) && objects[type.replace(/^array:/, '')]) {
        tester = objects[type.replace(/^array:/, '')].test;
      }

      satisfiesAll = input.every(function(row) {
        return tester.call(row);
      });

      if (satisfiesAll) {
        if (!fields && objects['array:'+type])
          fields = objects['array:'+type].defaultFields || Object.keys(objects['array:'+type].fields);
        if (!fields)
          fields = objects[type].defaultFields || Object.keys(objects[type].fields);

        return fromObject(objects, input, type, fields, true);
      }
    }
  }

  if (typeof input === 'object') {
    var satisfiesAll = false;
    var tester;

    var keys = Object.keys(input).filter(function(key) {
      return key[0] !== '_';
    });

    for (var type in objects) {
      tester = objects[type].test;
      if (!tester && /^array:/.test(type) && objects[type.replace(/^array:/, '')]) {
        tester = objects[type.replace(/^array:/, '')].test;
      }

      satisfiesAll = keys.every(function(key) {
        return tester.call(input[key]);
      });

      if (satisfiesAll) {
        if (!fields && objects['array:'+type])
          fields = objects['array:'+type].defaultFields || Object.keys(objects['array:'+type].fields);
        if (!fields)
          fields = objects[type].defaultFields || Object.keys(objects[type].fields);

        var arr = keys.map(function(key) {
          return input[key];
        });

        return fromObject(objects, arr, type, fields);
      }
    }
  }

  return false;
}

function fromObject(objects, input, type, fields) {
  var fieldNames = fields.map(function(field) {
    if (typeof field === 'string')
      return field;
    if (typeof field === 'object' && field.hasOwnProperty('name'))
      return field.name;
    return '';
  });

  if (input instanceof Array || objects[type].headers) {
    var colAligns = [];
    fields.forEach(function(field, ix) {
      if (typeof field === 'object' && field.align)
        colAligns[ix] = field.align;
    });

    var headers = objects[type].header ? objects[type].header(fieldNames, input) : fieldNames;

    var table = new Table({
      head: headers,
      colAligns: colAligns
    });
  }
  else {
    // Vertical table
    var table = new Table();
  }

  if (objects[type].insert) {
    objects[type].insert.call(input, table, objects[type], fieldNames);
  }
  else {
    if (!objects[type].fields && /^array:/.test(type)) {
      insert.call(input, table, objects[type.replace(/^array:/, '')], fieldNames);
    }
    else {
      insert.call(input, table, objects[type], fieldNames);
    }
  }

  return table.toString();
}

/**
 * Default renderer.insert function, `this` bound to the input.
 * @param  {Table} table       cli-table
 * @param  {Object} object     renderer object
 * @param  {Array} fields      fields to show
 */
function insert(table, object, fields) {
  var input = this;

  if (input instanceof Array) {
    insertArray.call(input, table, object, fields);
  }
  else {
    insertObject.call(input, table, object, fields);
  }
}

/**
 * renderer.insert function for rendering arrays,
 *   `this` bound to the input.
 * @param  {Table} table       cli-table
 * @param  {Object} object     renderer object
 * @param  {Array} fields      fields to show
 */
function insertArray(table, object, fields) {
  var input = this;

  input.forEach(function addRow(entry, rowNo) {
    var tableRow = fields.map(function cell(fieldName) {
      return getCellContent.call(entry, object.fields[fieldName], rowNo);
    });
    table.push(tableRow);
  });
}

/**
 * renderer.insert function for rendering objects,
 *   `this` bound to the input.
 * @param  {Table} table       cli-table
 * @param  {Object} object     renderer object
 * @param  {Array} fields      fields to show
 */
function insertObject(table, object, fields) {
  var input = this;

  fields.forEach(function addField(field) {
    var cells = {};
    cells[field] = getCellContent.call(input, object.fields[field]);
    table.push(cells);
  });
}

/**
 * Get the content of a cell. `field` is the function or string
 *   to use. `this` should be bound to the actual entry.
 * Additional parameters are forwarded to the function `field`.
 * @param  {Function|String} field
 * @return {String}
 */
function getCellContent(field) {
  var entry = this;
  var args = Array.prototype.slice.call(arguments, 1);

  if (typeof field === 'string')
    return field;
  if (typeof field === 'function') {
    var value;
    try {
      value = field.apply(entry, args);
    } catch (e) {
      value = '(err)';
    }
    if (value === undefined || value === null)
      return '';

    return value.toString();
  }
  return '';
}

/**
 * Create a console by requiring all renderers in a given
 *   location.
 * @param  {String} location Filesystem path to use with require-all
 * @return {tconsole}
 */
function load(location) {
  var required = requireAll(location);
  var config = {};
  for (var key in required) {
    config[key.replace(/^array\./, 'array:')] = required[key];
  }
  var konsole = createConsole(config);
  return konsole;
}

/**
 * Combine multiple tconsole instances.
 * @return {tconsole}
 */
function combine() {
  var config = {};
  Array.prototype.forEach.call(arguments, function(tconsoleInstance) {
    mergeObject(config, tconsoleInstance._tconsoleConfig);
  });
  return createConsole(config);
}

/**
 * Merge properties of obj2 into obj1.
 * @param  {Object} obj1
 * @param  {Object} obj2
 * @return {Object}
 */
function mergeObject(obj1, obj2){
  for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
}
<commit_msg>Throw Error for undefined tester<commit_after>module.exports = createConsole;
module.exports.load = load;
module.exports.combine = combine;
module.exports.getCellContent = getCellContent;
module.exports.insert = insert;
module.exports.insert.Array = insertArray;
module.exports.insert.Object = insertObject;

var Table = require('cli-table');
var requireAll = require('require-all');

function createConsole(objects) {
  var oldLog = console.log;

  var konsole = function printObject(input, fields) {
    var str = toString(objects, input, fields);
    if (str) {
      oldLog(str);
    }
    else {
      oldLog(input);
    }
  };

  // populate methods from console
  for (var key in console) {
    konsole[key] = console[key];
  }

  // replace .log()
  konsole.log = function log() {
    var args = [];
    var str;
    for (var i = 0; i < arguments.length; i++) {
      str = toString(objects, arguments[i]);
      if (str) {
        oldLog(str);
      }
      else {
        args.push(arguments[i]);
      }
    }
    oldLog.apply(this, args);
  };

  // add .toString()
  konsole.toString = function objectToString(input, fields) {
    return toString(objects, input, fields);
  };

  // save config
  konsole._tconsoleConfig = objects;

  return konsole;
}

function toString(objects, input, fields) {
  for (var type in objects) {
    if (objects[type].test && objects[type].test.call(input)) {
      fields = fields || objects[type].defaultFields || Object.keys(objects[type].fields);
      if (fields === '*')
        fields = Object.keys(objects[type].fields);

      return fromObject(objects, input, type, fields);
    }
  }

  if (input instanceof Array) {
    var satisfiesAll = false;
    var tester;

    for (var type in objects) {
      tester = objects[type].test;
      if (!tester && /^array:/.test(type) && objects[type.replace(/^array:/, '')]) {
        tester = objects[type.replace(/^array:/, '')].test;
      }

      satisfiesAll = input.every(function(row) {
        return tester.call(row);
      });

      if (satisfiesAll) {
        if (!fields && objects['array:'+type])
          fields = objects['array:'+type].defaultFields || Object.keys(objects['array:'+type].fields);
        if (!fields)
          fields = objects[type].defaultFields || Object.keys(objects[type].fields);

        return fromObject(objects, input, type, fields, true);
      }
    }
  }

  if (typeof input === 'object') {
    var satisfiesAll = false;
    var tester;

    var keys = Object.keys(input).filter(function(key) {
      return key[0] !== '_';
    });

    for (var type in objects) {
      tester = objects[type].test;
      if (!tester) {
        if (/^array:/.test(type) && objects[type.replace(/^array:/, '')]) {
          tester = objects[type.replace(/^array:/, '')].test;
        }
        else {
          throw new Error('No tester for type '+type);
        }
      }

      satisfiesAll = keys.every(function(key) {
        return tester.call(input[key]);
      });

      if (satisfiesAll) {
        if (!fields && objects['array:'+type])
          fields = objects['array:'+type].defaultFields || Object.keys(objects['array:'+type].fields);
        if (!fields)
          fields = objects[type].defaultFields || Object.keys(objects[type].fields);

        var arr = keys.map(function(key) {
          return input[key];
        });

        return fromObject(objects, arr, type, fields);
      }
    }
  }

  return false;
}

function fromObject(objects, input, type, fields) {
  var fieldNames = fields.map(function(field) {
    if (typeof field === 'string')
      return field;
    if (typeof field === 'object' && field.hasOwnProperty('name'))
      return field.name;
    return '';
  });

  if (input instanceof Array || objects[type].headers) {
    var colAligns = [];
    fields.forEach(function(field, ix) {
      if (typeof field === 'object' && field.align)
        colAligns[ix] = field.align;
    });

    var headers = objects[type].header ? objects[type].header(fieldNames, input) : fieldNames;

    var table = new Table({
      head: headers,
      colAligns: colAligns
    });
  }
  else {
    // Vertical table
    var table = new Table();
  }

  if (objects[type].insert) {
    objects[type].insert.call(input, table, objects[type], fieldNames);
  }
  else {
    if (!objects[type].fields && /^array:/.test(type)) {
      insert.call(input, table, objects[type.replace(/^array:/, '')], fieldNames);
    }
    else {
      insert.call(input, table, objects[type], fieldNames);
    }
  }

  return table.toString();
}

/**
 * Default renderer.insert function, `this` bound to the input.
 * @param  {Table} table       cli-table
 * @param  {Object} object     renderer object
 * @param  {Array} fields      fields to show
 */
function insert(table, object, fields) {
  var input = this;

  if (input instanceof Array) {
    insertArray.call(input, table, object, fields);
  }
  else {
    insertObject.call(input, table, object, fields);
  }
}

/**
 * renderer.insert function for rendering arrays,
 *   `this` bound to the input.
 * @param  {Table} table       cli-table
 * @param  {Object} object     renderer object
 * @param  {Array} fields      fields to show
 */
function insertArray(table, object, fields) {
  var input = this;

  input.forEach(function addRow(entry, rowNo) {
    var tableRow = fields.map(function cell(fieldName) {
      return getCellContent.call(entry, object.fields[fieldName], rowNo);
    });
    table.push(tableRow);
  });
}

/**
 * renderer.insert function for rendering objects,
 *   `this` bound to the input.
 * @param  {Table} table       cli-table
 * @param  {Object} object     renderer object
 * @param  {Array} fields      fields to show
 */
function insertObject(table, object, fields) {
  var input = this;

  fields.forEach(function addField(field) {
    var cells = {};
    cells[field] = getCellContent.call(input, object.fields[field]);
    table.push(cells);
  });
}

/**
 * Get the content of a cell. `field` is the function or string
 *   to use. `this` should be bound to the actual entry.
 * Additional parameters are forwarded to the function `field`.
 * @param  {Function|String} field
 * @return {String}
 */
function getCellContent(field) {
  var entry = this;
  var args = Array.prototype.slice.call(arguments, 1);

  if (typeof field === 'string')
    return field;
  if (typeof field === 'function') {
    var value;
    try {
      value = field.apply(entry, args);
    } catch (e) {
      value = '(err)';
    }
    if (value === undefined || value === null)
      return '';

    return value.toString();
  }
  return '';
}

/**
 * Create a console by requiring all renderers in a given
 *   location.
 * @param  {String} location Filesystem path to use with require-all
 * @return {tconsole}
 */
function load(location) {
  var required = requireAll(location);
  var config = {};
  for (var key in required) {
    config[key.replace(/^array\./, 'array:')] = required[key];
  }
  var konsole = createConsole(config);
  return konsole;
}

/**
 * Combine multiple tconsole instances.
 * @return {tconsole}
 */
function combine() {
  var config = {};
  Array.prototype.forEach.call(arguments, function(tconsoleInstance) {
    mergeObject(config, tconsoleInstance._tconsoleConfig);
  });
  return createConsole(config);
}

/**
 * Merge properties of obj2 into obj1.
 * @param  {Object} obj1
 * @param  {Object} obj2
 * @return {Object}
 */
function mergeObject(obj1, obj2){
  for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
}
<|endoftext|>


<commit_before>var Minimatch = require('minimatch').Minimatch;

module.exports = function(options){
    var registratorName = options.registratorName;
    var blackbox = false;

    if ('blackbox' in options === false) {
        blackbox = [
            '/bower_compontents/**',
            '/node_modules/**'
        ];
    } else {
        if (Array.isArray(options.blackbox)) {
            blackbox = options.blackbox;
        } else {
            console.warn('[' + require('./package.json').name + '] Wrong value for blackbox option');
        }
    }

    if (Array.isArray(blackbox)) {
        blackbox = blackbox.map(function(str){
            return new Minimatch(str);
        });
    }

    function isBlackbox(filename){
        return blackbox && blackbox.some(function(mm){
            return mm.match(filename);
        });
    }

    function calcLocation(file, node){
        return [
            file.opts.filename || 'unknown',
            node.loc.start.line,
            node.loc.start.column + 1,
            node.loc.end.line,
            node.loc.end.column + 1
        ].join(':');
    }

    return function (_ref) {
        var Plugin = _ref.Plugin;
        var t = _ref.types;

        function getLocation(file, node){
            if (node.loc) {
                return calcLocation(file, node);
            }

            if (t.isCallExpression(node) && node.callee.name === registratorName) {
                return calcLocation(file, node.arguments[0]); // or get loc from node.arguments[1]... ?s
            }

            return null;
        }

        function extend(dest, source){
            for (var key in source)
                if (Object.prototype.hasOwnProperty.call(source, key))
                    dest[key] = source[key];

            return dest;
        }

        function createInfoObject(loc, isBlackbox, extra){
            var properties = [];

            if (loc) {
                properties.push(t.property(
                    'init',
                    t.identifier('loc'),
                    t.literal(loc)
                ));
            }

            if (isBlackbox) {
                properties.push(t.property(
                    'init',
                    t.identifier('blackbox'),
                    t.literal(true)
                ));
            }

            if (extra) {
                properties = properties.concat(extra);
            }

            return t.objectExpression(properties);
        }

        function wrapNodeReference(loc, name, isBlackbox){
            return t.expressionStatement(
                t.callExpression(t.identifier(registratorName), [
                    t.identifier(name),
                    createInfoObject(loc, isBlackbox)
                ])
            );
        }

        function wrapNode(loc, node, isBlackbox){
            return t.callExpression(t.identifier(registratorName), [
                node,
                createInfoObject(loc, isBlackbox)
            ]);
        }

        function wrapObjectNode(loc, node, isBlackbox, map){
            return t.callExpression(t.identifier(registratorName), [
                node,
                createInfoObject(loc, isBlackbox, [
                    t.property(
                        'init',
                        t.identifier('map'),
                        t.objectExpression(map)
                    )
                ])
            ]);
        }

        function buildMap(node, getLocation){
            return node.properties.reduce(function(result, property){
                if (!property.computed && property.kind == 'init') {
                    var value = property.value;
                    var location = getLocation(value);

                    result.push(
                        t.property(
                            'init',
                            extend({}, property.key),
                            t.literal(location)
                        )
                    );
                }

                return result;
            }, []);
        }

        return new Plugin('babel-plugin-source-wrapper', {
            metadata: { secondPass: false },
            visitor: {
                shouldSkip: function(path){
                    return path.node.skip_;
                },

                FunctionDeclaration: function(node, parent, scope, file){
                    var loc = getLocation(file, node);
                    var node = wrapNodeReference(loc, node.id.name, isBlackbox(file.opts.filename));
                    node.skip_ = true;
                    this.insertAfter(node);
                },

                'FunctionExpression|ArrowFunctionExpression|ClassExpression|NewExpression|ArrayExpression|JSXElement': {
                    exit: function(node, parent, scope, file){
                        this.skip();
                        var loc = getLocation(file, node);
                        return wrapNode(loc, node, isBlackbox(file.opts.filename));
                    }
                },

                ObjectExpression: {
                    enter: function(node, parent, scope, file){
                        this.setData('map', buildMap(node, getLocation.bind(null, file)));
                    },
                    exit: function(node, parent, scope, file){
                        this.skip();
                        var loc = getLocation(file, node);
                        var map = this.getData('map');
                        return wrapObjectNode(loc, node, isBlackbox(file.opts.filename), map);
                    }
                },
                CallExpression: {
                    exit: function(node, parent, scope, file){
                        //this.skip();

                        if (t.isMemberExpression(node.callee) && !node.callee.computed){
                            var loc = getLocation(file, node);
                            return wrapNode(loc, node, isBlackbox(file.opts.filename));
                        }
                    }
                }
            }
        });
    };
};
<commit_msg>force set info for NewExpression<commit_after>var Minimatch = require('minimatch').Minimatch;

module.exports = function(options){
    var registratorName = options.registratorName;
    var blackbox = false;

    if ('blackbox' in options === false) {
        blackbox = [
            '/bower_compontents/**',
            '/node_modules/**'
        ];
    } else {
        if (Array.isArray(options.blackbox)) {
            blackbox = options.blackbox;
        } else {
            console.warn('[' + require('./package.json').name + '] Wrong value for blackbox option');
        }
    }

    if (Array.isArray(blackbox)) {
        blackbox = blackbox.map(function(str){
            return new Minimatch(str);
        });
    }

    function isBlackbox(filename){
        return blackbox && blackbox.some(function(mm){
            return mm.match(filename);
        });
    }

    function calcLocation(file, node){
        return [
            file.opts.filename || 'unknown',
            node.loc.start.line,
            node.loc.start.column + 1,
            node.loc.end.line,
            node.loc.end.column + 1
        ].join(':');
    }

    return function (_ref) {
        var Plugin = _ref.Plugin;
        var t = _ref.types;

        function getLocation(file, node){
            if (node.loc) {
                return calcLocation(file, node);
            }

            if (t.isCallExpression(node) && node.callee.name === registratorName) {
                return calcLocation(file, node.arguments[0]); // or get loc from node.arguments[1]... ?s
            }

            return null;
        }

        function extend(dest, source){
            for (var key in source)
                if (Object.prototype.hasOwnProperty.call(source, key))
                    dest[key] = source[key];

            return dest;
        }

        function createInfoObject(loc, isBlackbox, extra){
            var properties = [];

            if (loc) {
                properties.push(t.property(
                    'init',
                    t.identifier('loc'),
                    t.literal(loc)
                ));
            }

            if (isBlackbox) {
                properties.push(t.property(
                    'init',
                    t.identifier('blackbox'),
                    t.literal(true)
                ));
            }

            if (extra) {
                properties = properties.concat(extra);
            }

            return t.objectExpression(properties);
        }

        function wrapNodeReference(loc, name, isBlackbox){
            return t.expressionStatement(
                t.callExpression(t.identifier(registratorName), [
                    t.identifier(name),
                    createInfoObject(loc, isBlackbox)
                ])
            );
        }

        function wrapNode(loc, node, isBlackbox, force){
            var args = [
                node,
                createInfoObject(loc, isBlackbox)
            ];

            if (force) {
                args.push(t.literal(true));
            }

            return t.callExpression(t.identifier(registratorName), args);
        }

        function wrapObjectNode(loc, node, isBlackbox, map){
            return t.callExpression(t.identifier(registratorName), [
                node,
                createInfoObject(loc, isBlackbox, [
                    t.property(
                        'init',
                        t.identifier('map'),
                        t.objectExpression(map)
                    )
                ])
            ]);
        }

        function buildMap(node, getLocation){
            return node.properties.reduce(function(result, property){
                if (!property.computed && property.kind == 'init') {
                    var value = property.value;
                    var location = getLocation(value);

                    result.push(
                        t.property(
                            'init',
                            extend({}, property.key),
                            t.literal(location)
                        )
                    );
                }

                return result;
            }, []);
        }

        return new Plugin('babel-plugin-source-wrapper', {
            metadata: { secondPass: false },
            visitor: {
                shouldSkip: function(path){
                    return path.node.skip_;
                },

                FunctionDeclaration: function(node, parent, scope, file){
                    var loc = getLocation(file, node);
                    var node = wrapNodeReference(loc, node.id.name, isBlackbox(file.opts.filename));
                    node.skip_ = true;
                    this.insertAfter(node);
                },

                'FunctionExpression|ArrowFunctionExpression|ClassExpression|ArrayExpression|JSXElement': {
                    exit: function(node, parent, scope, file){
                        this.skip();
                        var loc = getLocation(file, node);
                        return wrapNode(loc, node, isBlackbox(file.opts.filename));
                    }
                },

                NewExpression:  {
                    exit: function(node, parent, scope, file){
                        this.skip();
                        var loc = getLocation(file, node);
                        return wrapNode(loc, node, isBlackbox(file.opts.filename), true);
                    }
                },

                ObjectExpression: {
                    enter: function(node, parent, scope, file){
                        this.setData('map', buildMap(node, getLocation.bind(null, file)));
                    },
                    exit: function(node, parent, scope, file){
                        this.skip();
                        var loc = getLocation(file, node);
                        var map = this.getData('map');
                        return wrapObjectNode(loc, node, isBlackbox(file.opts.filename), map);
                    }
                },
                CallExpression: {
                    exit: function(node, parent, scope, file){
                        //this.skip();

                        if (t.isMemberExpression(node.callee) && !node.callee.computed){
                            var loc = getLocation(file, node);
                            return wrapNode(loc, node, isBlackbox(file.opts.filename));
                        }
                    }
                }
            }
        });
    };
};
<|endoftext|>


<commit_before>'use strict';

var fillMissingKeys = require('fill-keys');

function ProxyquireifyError(msg) {
  this.name = 'ProxyquireifyError';
  Error.captureStackTrace(this, ProxyquireifyError);
  this.message = msg || 'An error occurred inside proxyquireify.';
}

function validateArguments(request, stubs) {
  var msg = (function getMessage() {
    if (!request)
      return 'Missing argument: "request". Need it to resolve desired module.';

    if (!stubs)
      return 'Missing argument: "stubs". If no stubbing is needed, use regular require instead.';

    if (typeof request != 'string')
      return 'Invalid argument: "request". Needs to be a requirable string that is the module to load.';

    if (typeof stubs != 'object')
      return 'Invalid argument: "stubs". Needs to be an object containing overrides e.g., {"path": { extname: function () { ... } } }.';
  })();

  if (msg) throw new ProxyquireifyError(msg);
}

var stubs;
var noCallThruGlobal = false;

function stub(stubs_) {
  stubs = stubs_;
  // This cache is used by the prelude as an alternative to the regular cache.
  // It is not read or written here, except to set it to an empty object when
  // adding stubs and to reset it to null when clearing stubs.
  module.exports._cache = {};
}

function reset() {
  stubs = undefined;
  noCallThruGlobal = false;
  module.exports._cache = null;
}

var proxyquire = module.exports = function (require_) {
  if (typeof require_ != 'function')
    throw new ProxyquireifyError(
        'It seems like you didn\'t initialize proxyquireify with the require in your test.\n'
      + 'Make sure to correct this, i.e.: "var proxyquire = require(\'proxyquireify\')(require);"'
    );

  reset();

  var prxCall = function(request, stubs) {

    validateArguments(request, stubs);

    // set the stubs and require dependency
    // when stub require is invoked by the module under test it will find the stubs here
    stub(stubs);
    var dep = require_(request);
    //reset();

    return dep;
  };

  prxCall.noCallThru = function () {
    noCallThruGlobal = true;
  };

  prxCall.reset = reset;
  return prxCall;
};

var clsc = function () {
  var args = arguments;

  args = [].slice.call( args );
  for (var i = 0, len = args.length; i < len; i++) {
    var current = args[ i ];
    if ( typeof current !== 'undefined' && current !== null  ) {
      return current;
    }
  }
  return null;
};
// Start with the default cache
proxyquire._cache = null;

proxyquire._proxy = function (require_, request) {
  function original() {
    return require_(request);
  }

  if (!stubs) return original();

  var stub = stubs[request];

  if (!stub) return original();

  var noCallThru = false;

  if (!noCallThruGlobal) {
    var stubWideNoCallThru = !!stubs['@noCallThru'] && stub['@noCallThru'] !== false;
    noCallThru = stubWideNoCallThru || !!stub['@noCallThru'];
  }
  else {
    noCallThru = clsc(stub['@noCallThru'], stubs['@noCallThru'], noCallThruGlobal)
  }

  return noCallThru ? stub : fillMissingKeys(stub, original());
};

if (require.cache) {
  // only used during build, so prevent browserify from including it
  var replacePreludePath = './lib/replace-prelude';
  var replacePrelude = require(replacePreludePath);
  proxyquire.browserify = replacePrelude.browserify;
  proxyquire.plugin = replacePrelude.plugin;
}
<commit_msg>FIX: return the require function from the call to `noCallThru`<commit_after>'use strict';

var fillMissingKeys = require('fill-keys');

function ProxyquireifyError(msg) {
  this.name = 'ProxyquireifyError';
  Error.captureStackTrace(this, ProxyquireifyError);
  this.message = msg || 'An error occurred inside proxyquireify.';
}

function validateArguments(request, stubs) {
  var msg = (function getMessage() {
    if (!request)
      return 'Missing argument: "request". Need it to resolve desired module.';

    if (!stubs)
      return 'Missing argument: "stubs". If no stubbing is needed, use regular require instead.';

    if (typeof request != 'string')
      return 'Invalid argument: "request". Needs to be a requirable string that is the module to load.';

    if (typeof stubs != 'object')
      return 'Invalid argument: "stubs". Needs to be an object containing overrides e.g., {"path": { extname: function () { ... } } }.';
  })();

  if (msg) throw new ProxyquireifyError(msg);
}

var stubs;
var noCallThruGlobal = false;

function stub(stubs_) {
  stubs = stubs_;
  // This cache is used by the prelude as an alternative to the regular cache.
  // It is not read or written here, except to set it to an empty object when
  // adding stubs and to reset it to null when clearing stubs.
  module.exports._cache = {};
}

function reset() {
  stubs = undefined;
  noCallThruGlobal = false;
  module.exports._cache = null;
}

var proxyquire = module.exports = function (require_) {
  if (typeof require_ != 'function')
    throw new ProxyquireifyError(
        'It seems like you didn\'t initialize proxyquireify with the require in your test.\n'
      + 'Make sure to correct this, i.e.: "var proxyquire = require(\'proxyquireify\')(require);"'
    );

  reset();

  var prxCall = function(request, stubs) {

    validateArguments(request, stubs);

    // set the stubs and require dependency
    // when stub require is invoked by the module under test it will find the stubs here
    stub(stubs);
    var dep = require_(request);
    //reset();

    return dep;
  };

  prxCall.noCallThru = function () {
    noCallThruGlobal = true;
    return prxCall;
  };

  prxCall.reset = reset;
  return prxCall;
};

var clsc = function () {
  var args = arguments;

  args = [].slice.call( args );
  for (var i = 0, len = args.length; i < len; i++) {
    var current = args[ i ];
    if ( typeof current !== 'undefined' && current !== null  ) {
      return current;
    }
  }
  return null;
};
// Start with the default cache
proxyquire._cache = null;

proxyquire._proxy = function (require_, request) {
  function original() {
    return require_(request);
  }

  if (!stubs) return original();

  var stub = stubs[request];

  if (!stub) return original();

  var noCallThru = false;

  if (!noCallThruGlobal) {
    var stubWideNoCallThru = !!stubs['@noCallThru'] && stub['@noCallThru'] !== false;
    noCallThru = stubWideNoCallThru || !!stub['@noCallThru'];
  }
  else {
    noCallThru = clsc(stub['@noCallThru'], stubs['@noCallThru'], noCallThruGlobal)
  }

  return noCallThru ? stub : fillMissingKeys(stub, original());
};

if (require.cache) {
  // only used during build, so prevent browserify from including it
  var replacePreludePath = './lib/replace-prelude';
  var replacePrelude = require(replacePreludePath);
  proxyquire.browserify = replacePrelude.browserify;
  proxyquire.plugin = replacePrelude.plugin;
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var errorFactory = require('error-factory');
var querystring = require('querystring');
var request = require('superagent');
var Promise = require('bluebird');

var endpoints = require(__dirname + '/api-endpoints.json');

// Custom Errors
// indicates errors such as a network failure or timeout
var CommunicationError = errorFactory('CommunicationError');

// indicates errors returned by Slack e.g. for incorrect parameters supplied for an endpoint
var SlackError = errorFactory('SlackError');

// signifies that a non-200 status code was returned by Slack. This is different from
// SlackError because Slack returns a 200 status code for the kinds of errors
// identified by SlackError
var SlackServiceError = errorFactory('SlackServiceError', ['message', 'errorDetails']);

var api = _.mapValues(endpoints, function(section, sectionName) {
  return _.mapValues(section, function(method, methodName) {
    return apiMethod(sectionName, methodName);
  });
});

api.errors = {
  SlackError: SlackError,
  SlackServiceError: SlackServiceError,
  CommunicationError: CommunicationError
};

api.oauth.getUrl = function getUrl(options, done) {
  if (typeof options === 'string') {
    options = {
      client_id: options
    };
  }

  if (!options || !options.client_id) {
    throw new ReferenceError('A client_id is required for this method.');
  }

  options.state = options.state || Math.random();

  if (!done || !_.isFunction(done)) {
    done = function noop() {};
  }

  return done(null, 'https://slack.com/oauth/authorize?' + querystring.stringify(options));
};

api.oauth.access = function authorize(options, state, done) {
  // Polymorphism
  if (_.isFunction(state) && _.isUndefined(done)) {
    done = state;
    state = null;
  }

  // Error Handling
  if (!done || !_.isFunction(done)) {
    done = function noop() {};
  }

  if (!options) {
    throw new ReferenceError('oauth.access requires an options Object as a first argument.');
  }

  if (_.isArray(options) || _.isString(options) || _.isFunction(options)) {
    throw new TypeError('oauth.access requires an options Object as a first argument.');
  }

  if (state && options.state && state !== options.state) {
    return done(new SlackError('States do not match. WARNING! This could mean that the authentication was a forgery.'), null);
  }

  // Access authentication
  return apiMethod('oauth', 'access')(options, done);
};

function promisify() {
  //make sure to bubble up errors instead of console.error'ing them via Bluebird
  //so that client code can add their own catch and error handling
  Promise.onPossiblyUnhandledRejection(function(error) {
    throw error;
  });

  return _.mapValues(api, function(section, sectionName) {
    if (sectionName === 'errors') return section;
    return _.mapValues(section, function(method, name) {
      return Promise.promisify(method);
    });
  });
}

function apiMethod(sectionName, methodName) {
  return function callApi(args, done) {
    var config;
    var requiredArgsList;
    var url;

    // Polymorphism
    if (_.isUndefined(done) && _.isFunction(args)) {
      done = args;
      args = {};
    } else if (_.isUndefined(done) && _.isUndefined(args)) {
      args = {};
      done = function() {};
    }

    if (!api.hasOwnProperty(sectionName)) {
      throw new ReferenceError('API object, ' + sectionName + ', does not exist.');
    }

    if (!api[sectionName].hasOwnProperty(methodName)) {
      throw new ReferenceError('API Method, ' + sectionName + '#' + methodName + ', does not exist.');
    }

    config = endpoints[sectionName][methodName];

    var requiredArgsList = collectRequiredArgs(config.arguments);
    _.each(requiredArgsList, function(requiredArg) {
      if (_.isUndefined(args[requiredArg])) {
        throw new TypeError('API Method, ' + sectionName + '#' + methodName + ', requires the following args: ' + requiredArgsList.join(', '));
      }
    });

    url = config.url + '?' + querystring.stringify(args);

    request
      .post(config.url + '?token=' + config.token)
      .send(args)
      .end(function(error, response) {
        if (error) {
          return done(new CommunicationError('Communication error while posting message to Slack. ' + error), null);
        } else {
          if (response.ok) {
            if (!response.body.ok) {
              return done(new SlackError(config.errors[response.body.error] || response.body.error), response.body);
            }
            done(null, response.body);
          } else {
            return done(new SlackServiceError('Did not receive a successful response from Slack.', {
              errorDetails: {
                errorCode: response.statusCode,
                errorResponse: response.body
              }
            }), null);
          }
        }
      });
  }
}

function collectRequiredArgs(configuredArgs) {
  return _.filter(_.keys(configuredArgs), function(key) {
    return configuredArgs[key].required;
  });
}

api.promisify = promisify;
module.exports = api;
<commit_msg>trying out json.stringify<commit_after>'use strict';

var _ = require('lodash');
var errorFactory = require('error-factory');
var querystring = require('querystring');
var request = require('superagent');
var Promise = require('bluebird');

var endpoints = require(__dirname + '/api-endpoints.json');

// Custom Errors
// indicates errors such as a network failure or timeout
var CommunicationError = errorFactory('CommunicationError');

// indicates errors returned by Slack e.g. for incorrect parameters supplied for an endpoint
var SlackError = errorFactory('SlackError');

// signifies that a non-200 status code was returned by Slack. This is different from
// SlackError because Slack returns a 200 status code for the kinds of errors
// identified by SlackError
var SlackServiceError = errorFactory('SlackServiceError', ['message', 'errorDetails']);

var api = _.mapValues(endpoints, function(section, sectionName) {
  return _.mapValues(section, function(method, methodName) {
    return apiMethod(sectionName, methodName);
  });
});

api.errors = {
  SlackError: SlackError,
  SlackServiceError: SlackServiceError,
  CommunicationError: CommunicationError
};

api.oauth.getUrl = function getUrl(options, done) {
  if (typeof options === 'string') {
    options = {
      client_id: options
    };
  }

  if (!options || !options.client_id) {
    throw new ReferenceError('A client_id is required for this method.');
  }

  options.state = options.state || Math.random();

  if (!done || !_.isFunction(done)) {
    done = function noop() {};
  }

  return done(null, 'https://slack.com/oauth/authorize?' + querystring.stringify(options));
};

api.oauth.access = function authorize(options, state, done) {
  // Polymorphism
  if (_.isFunction(state) && _.isUndefined(done)) {
    done = state;
    state = null;
  }

  // Error Handling
  if (!done || !_.isFunction(done)) {
    done = function noop() {};
  }

  if (!options) {
    throw new ReferenceError('oauth.access requires an options Object as a first argument.');
  }

  if (_.isArray(options) || _.isString(options) || _.isFunction(options)) {
    throw new TypeError('oauth.access requires an options Object as a first argument.');
  }

  if (state && options.state && state !== options.state) {
    return done(new SlackError('States do not match. WARNING! This could mean that the authentication was a forgery.'), null);
  }

  // Access authentication
  return apiMethod('oauth', 'access')(options, done);
};

function promisify() {
  //make sure to bubble up errors instead of console.error'ing them via Bluebird
  //so that client code can add their own catch and error handling
  Promise.onPossiblyUnhandledRejection(function(error) {
    throw error;
  });

  return _.mapValues(api, function(section, sectionName) {
    if (sectionName === 'errors') return section;
    return _.mapValues(section, function(method, name) {
      return Promise.promisify(method);
    });
  });
}

function apiMethod(sectionName, methodName) {
  return function callApi(args, done) {
    var config;
    var requiredArgsList;
    var url;

    // Polymorphism
    if (_.isUndefined(done) && _.isFunction(args)) {
      done = args;
      args = {};
    } else if (_.isUndefined(done) && _.isUndefined(args)) {
      args = {};
      done = function() {};
    }

    if (!api.hasOwnProperty(sectionName)) {
      throw new ReferenceError('API object, ' + sectionName + ', does not exist.');
    }

    if (!api[sectionName].hasOwnProperty(methodName)) {
      throw new ReferenceError('API Method, ' + sectionName + '#' + methodName + ', does not exist.');
    }

    config = endpoints[sectionName][methodName];

    var requiredArgsList = collectRequiredArgs(config.arguments);
    _.each(requiredArgsList, function(requiredArg) {
      if (_.isUndefined(args[requiredArg])) {
        throw new TypeError('API Method, ' + sectionName + '#' + methodName + ', requires the following args: ' + requiredArgsList.join(', '));
      }
    });

    if (args.attachments) {
        args.attachments = JSON.stringfiy(args.attachments);
    }

    url = config.url + '?' + querystring.stringify(args);

    request
      .get(url)
      .end(function(error, response) {
        if (error) {
          return done(new CommunicationError('Communication error while posting message to Slack. ' + error), null);
        } else {
          if (response.ok) {
            if (!response.body.ok) {
              return done(new SlackError(config.errors[response.body.error] || response.body.error), response.body);
            }
            done(null, response.body);
          } else {
            return done(new SlackServiceError('Did not receive a successful response from Slack.', {
              errorDetails: {
                errorCode: response.statusCode,
                errorResponse: response.body
              }
            }), null);
          }
        }
      });
  }
}

function collectRequiredArgs(configuredArgs) {
  return _.filter(_.keys(configuredArgs), function(key) {
    return configuredArgs[key].required;
  });
}

api.promisify = promisify;
module.exports = api;
<|endoftext|>


<commit_before>// BASE SETUP
// =============================================================================

// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var config = require('./config.json');
var bodyParser = require('body-parser');
var http = require('http');
var querystring = require('querystring');
var socket = require("socket.io-client")('http://fika-api-dev.eu-central-1.elasticbeanstalk.com/');
socket.on('connect', function() {
    console.log("Connected to FIKA-API");
});

// this is me
var me = config.id;

socket.on('message', function(message) {
    console.log(message);
if(message.message){
    var cleanMessage = message.message.replace(/"/g, '"');
    var parsedJson = JSON.parse(cleanMessage);
   if(parsedJson.sender== me){
       console.log(parsedJson);
       lightOn(parsedJson.state);
}}
});

function lightOn(state){
    console.log(state);
     const postData = JSON.stringify({ "on": (state=='START')? true:false, "hue":46920});
    console.log(postData);
    var options = {
        host: '192.168.6.140',
        port: 80,
        path: '/api/tyObM0Dd4TlMYGoqua7rFBcPNPQBVkJ5eZt8lfrM/lights/1/state',
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(postData)
        }
    };

    var req = http.request(options, function(res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function(chunk) {
            console.log('LAMP REQUEST BODY: ' + chunk);
        });
    });

    req.write(postData);
    req.end();
}

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080; // set our port

// SOCKET LISTENER FOR OUR API
/*
var socket = socketio("http://fika-api-dev.eu-central-1.elasticbeanstalk.com/fika-relay");
socket.on('message', function(data) {
    //$('#messages').append($('<li>').text(JSON.stringify(data.message)));
    console.log(data);
});*/

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/on/:state', function(extreq, res) {
    res.json({ message: 'hooray! welcome to our api!' });

    console.log("EXT REQUEST BODY STATE PARAM: " + extreq.params.state);

    let stateParam = (extreq.params.state == "true");

    const postData = JSON.stringify({ "on": stateParam });
    console.log(postData);
    var options = {
        host: '192.168.6.140',
        port: 80,
        path: '/api/tyObM0Dd4TlMYGoqua7rFBcPNPQBVkJ5eZt8lfrM/lights/1/state',
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(postData)
        }
    };

    var req = http.request(options, function(res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function(chunk) {
            console.log('LAMP REQUEST BODY: ' + chunk);
        });
    });

    req.write(postData);
    req.end();

});

// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);<commit_msg>Colors<commit_after>// BASE SETUP
// =============================================================================

// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var config = require('./config.json');
var bodyParser = require('body-parser');
var http = require('http');
var querystring = require('querystring');
var socket = require("socket.io-client")('http://fika-api-dev.eu-central-1.elasticbeanstalk.com/');
socket.on('connect', function() {
    console.log("Connected to FIKA-API");
});

// this is me
var me = config.id;

socket.on('message', function(message) {
    console.log("------->",message);

   // var cleanMessage = message.replace(/"/g, '"');
    //var parsedJson = JSON.parse(cleanMessage);
   if(message.sender== me){
      // console.log(parsedJson);
       lightOn(message.state);
}
});

function lightOn(state){

    var lightSettings = {
        "on": null,
        "hue": null
    }
    if(state=='START') {
        lightSettings.on = true;
        lightSettings.hue = 46920;
    }
    else if(state == 'CONFIRM') {
        lightSettings.on = true;
        lightSettings.hue = 25500;
    }
    else {
        lightSettings.on = false;
    }
    const postData = JSON.stringify(lightSettings);
    console.log(postData);
    var options = {
        host: '192.168.6.140',
        port: 80,
        path: '/api/tyObM0Dd4TlMYGoqua7rFBcPNPQBVkJ5eZt8lfrM/lights/1/state',
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(postData)
        }
    };

    var req = http.request(options, function(res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function(chunk) {
            console.log('LAMP REQUEST BODY: ' + chunk);
        });
    });

    req.write(postData);
    req.end();
}

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080; // set our port

// SOCKET LISTENER FOR OUR API
/*
var socket = socketio("http://fika-api-dev.eu-central-1.elasticbeanstalk.com/fika-relay");
socket.on('message', function(data) {
    //$('#messages').append($('<li>').text(JSON.stringify(data.message)));
    console.log(data);
});*/

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/on/:state', function(extreq, res) {
    res.json({ message: 'hooray! welcome to our api!' });

    console.log("EXT REQUEST BODY STATE PARAM: " + extreq.params.state);

    let stateParam = (extreq.params.state == "true");

    const postData = JSON.stringify({ "on": stateParam });
    console.log(postData);
    var options = {
        host: '192.168.6.140',
        port: 80,
        path: '/api/tyObM0Dd4TlMYGoqua7rFBcPNPQBVkJ5eZt8lfrM/lights/1/state',
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(postData)
        }
    };

    var req = http.request(options, function(res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function(chunk) {
            console.log('LAMP REQUEST BODY: ' + chunk);
        });
    });

    req.write(postData);
    req.end();

});

// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);<|endoftext|>


<commit_before>require('dotenv').config();

var express = require('express');
var app = express();
var fs = require( 'fs' );
var auth = require('basic-auth');
var bodyParser = require('body-parser');

app.use(bodyParser.json({
    type: '*/*'
}));

//authorization
app.use(function(req, res, next) {
    var credentials = auth(req);
    if (!credentials || credentials.name !== process.env.API_USER || credentials.pass !== process.env.API_PASS) {
        res.set({
            'WWW-Authenticate': 'Basic realm="simple-admin"'
        });
        res.sendStatus(401);
    } else {
        next();
    }
});

routes = fs.readdirSync('./routes');
routes.forEach( function( routeFile ) {
    app.use('/api/' + routeFile, require('./routes/' + routeFile));
});

function error(err, req, res, next) {
    console.error(err.stack);
    res.send(500);
}
app.use(error);

var server = app.listen(process.env.RASPAPI_PORT, function() {

    var host = server.address().address;
    var port = server.address().port;

    console.log('raspapi listening at http://%s:%s', host, port);

});
<commit_msg>feat(server): improve error and "status code only" responses to return json<commit_after>require('dotenv').config();

var express = require('express');
var app = express();
var fs = require( 'fs' );
var auth = require('basic-auth');
var bodyParser = require('body-parser');

//parsing
app.use(bodyParser.json({
    type: '*/*'
}));

//authorization
app.use(function(req, res, next) {
    var credentials = auth(req);
    if (!credentials || credentials.name !== process.env.API_USER || credentials.pass !== process.env.API_PASS) {
        res.set({
            'WWW-Authenticate': 'Basic realm="simple-admin"'
        });
        res.sendStatus(401);
    } else {
        next();
    }
});

//pretty jsonresponses
app.use(function(req, res, next) {
    res.sendStatusJson = function (status) {
        res.status(status).send({status: status});
    };
    next();
});

//routes
routes = fs.readdirSync('./routes');
routes.forEach( function( routeFile ) {
    app.use('/api/' + routeFile, require('./routes/' + routeFile));
});

//errorhandling
app.use(function(err, req, res, next) {
    console.error(err.stack);
    res.status(500).send({
        error: "500"
    });
    next(err);
});

var server = app.listen(process.env.RASPAPI_PORT, function() {

    var host = server.address().address;
    var port = server.address().port;

    console.log('raspapi listening at http://%s:%s', host, port);

});
<|endoftext|>


<commit_before>var fc = require('fc');
var btnode = require('./binarytreenode');
var nick = require('./clip').nick;

var root = new btnode({
  plane: [],
  geometry: [[-100, 200], [-100, -100], [200, -100], [200, 200]]
});

root
  .cut([0,0, 0,100], 'L')
  .cut([0,100, 100,100], 'L')
  .cut([100,100, 100,0], 'L')
  .cut([100,0, 0,0], 'L')
  .cut([50,75, 25,50], 'R')
  .cut([25,50, 50,25], 'R')
  .cut([50,25, 75,50], 'R')
  .cut([75,50, 50,75], 'R');

render('R'); // try 'L', 'R', or '-'

function drawPoly (ctx, polygon) {
  ctx.moveTo(polygon[0][0], polygon[0][1]);
  for (var i = 0; i < polygon.length; i++) {
    ctx.beginPath();
    ctx.arc(polygon[i][0], polygon[i][1], 4, 0, 2 * Math.PI, false);
    ctx.fillStyle = 'rgba(' + 1 + ', 0, 0, ' + (i+1) *.15 + ')';
    ctx.closePath()
    ctx.fill();
  }

  ctx.beginPath();
  ctx.moveTo(polygon[0][0], polygon[0][1]);

  for (var i = 0; i < polygon.length; i++) {
    if (i < polygon.length - 1) {
      ctx.lineTo(polygon[i + 1][0], polygon[i + 1][1]);
    }
    else {
      ctx.lineTo(polygon[0][0], polygon[0][1]);
    }
  }
  ctx.closePath();

  ctx.fillStyle = 'rgba(0, 0, 0, .1)';
  ctx.strokeStyle = 'black';
  ctx.stroke();
  ctx.fill();
}

function render (side) {
  var polygons = [];

  function renderIterator (context) {
    if (context && context.isLeaf()) {
      switch (side) {
        case 'L':
          if (context.side === 'L') {
            var relative = context.parent.rightChild.rightChild;
            var cuttingPlane = relative ? relative.data.plane : [];
            polygons.push(nick(context.data.geometry, cuttingPlane));
          }
        break;

        case 'R':
          if (context.side === 'R') {
            var relative = context.parent.leftChild.leftChild;
            var cuttingPlane = relative ? relative.data.plane : [];
            polygons.push(nick(context.data.geometry, cuttingPlane));
          }
        break;

        default:
          polygons.push(context.data.geometry);
        break;
      }
    }
  }

  function renderCompleted () {
    var ctx = fc(function () {
      ctx.translate(200, 200);
      for (var j = 0; j < polygons.length; j++) {
        drawPoly(ctx, polygons[j]);
        // if (j === 2) return;
      }
    });

    ctx.dirty();
  }

  root.traverse(renderIterator, 0, '-', renderCompleted);
}
<commit_msg>removed stray debugging line from bsp.js<commit_after>var fc = require('fc');
var btnode = require('./binarytreenode');
var nick = require('./clip').nick;

var root = new btnode({
  plane: [],
  geometry: [[-100, 200], [-100, -100], [200, -100], [200, 200]]
});

root
  .cut([0,0, 0,100], 'L')
  .cut([0,100, 100,100], 'L')
  .cut([100,100, 100,0], 'L')
  .cut([100,0, 0,0], 'L')
  .cut([50,75, 25,50], 'R')
  .cut([25,50, 50,25], 'R')
  .cut([50,25, 75,50], 'R')
  .cut([75,50, 50,75], 'R');

render('R'); // try 'L', 'R', or '-'

function drawPoly (ctx, polygon) {
  ctx.moveTo(polygon[0][0], polygon[0][1]);
  for (var i = 0; i < polygon.length; i++) {
    ctx.beginPath();
    ctx.arc(polygon[i][0], polygon[i][1], 4, 0, 2 * Math.PI, false);
    ctx.fillStyle = 'rgba(' + 1 + ', 0, 0, ' + (i+1) *.15 + ')';
    ctx.closePath()
    ctx.fill();
  }

  ctx.beginPath();
  ctx.moveTo(polygon[0][0], polygon[0][1]);

  for (var i = 0; i < polygon.length; i++) {
    if (i < polygon.length - 1) {
      ctx.lineTo(polygon[i + 1][0], polygon[i + 1][1]);
    }
    else {
      ctx.lineTo(polygon[0][0], polygon[0][1]);
    }
  }
  ctx.closePath();

  ctx.fillStyle = 'rgba(0, 0, 0, .1)';
  ctx.strokeStyle = 'black';
  ctx.stroke();
  ctx.fill();
}

function render (side) {
  var polygons = [];

  function renderIterator (context) {
    if (context && context.isLeaf()) {
      switch (side) {
        case 'L':
          if (context.side === 'L') {
            var relative = context.parent.rightChild.rightChild;
            var cuttingPlane = relative ? relative.data.plane : [];
            polygons.push(nick(context.data.geometry, cuttingPlane));
          }
        break;

        case 'R':
          if (context.side === 'R') {
            var relative = context.parent.leftChild.leftChild;
            var cuttingPlane = relative ? relative.data.plane : [];
            polygons.push(nick(context.data.geometry, cuttingPlane));
          }
        break;

        default:
          polygons.push(context.data.geometry);
        break;
      }
    }
  }

  function renderCompleted () {
    var ctx = fc(function () {
      ctx.translate(200, 200);
      for (var j = 0; j < polygons.length; j++) {
        drawPoly(ctx, polygons[j]);
      }
    });

    ctx.dirty();
  }

  root.traverse(renderIterator, 0, '-', renderCompleted);
}
<|endoftext|>


<commit_before>'use strict';

var winston = require.main.require('winston');
var async = require.main.require('async');
var nconf = require.main.require('nconf');
var url = require.main.require('url');
var Meta = require.main.require('./src/meta');
var Posts = require.main.require('./src/posts');
var Topics = require.main.require('./src.topics');
var Privileges = require.main.require('./src/privileges');
var Plugins = require.main.require('./src/plugins');
var SocketHelpers = require.main.require('./src/socket.io/helpers');
var User = require.main.require('./src/user');
var hostEmailer = require.main.require('./src/emailer');
var SendGrid;
var Emailer = {};

Emailer.hostname = url.parse(nconf.get('url')).hostname;
Emailer.receiptRegex = new RegExp('^reply-([\\d]+)@' + Emailer.hostname + '$');

Emailer.init = function (data, callback) {
	var render = function (req, res) {
		var destinationURL = nconf.get('url') + '/plugins/emailer-sendgrid/webhook';
		res.render('admin/plugins/emailer-sendgrid', { destinationURL: destinationURL });
	};

	Meta.settings.get('sendgrid', function (err, settings) {
		if (!err && settings && settings.apiKey) {
			SendGrid = require('@sendgrid/mail');
			SendGrid.setApiKey(settings.apiKey);
		} else {
			winston.error('[plugins/emailer-sendgrid] API key not set!');
		}

		var multipart = module.parent.require('connect-multiparty');
		var multipartMiddleware = multipart();

		data.router.get('/admin/plugins/emailer-sendgrid', data.middleware.admin.buildHeader, render);
		data.router.get('/api/admin/plugins/emailer-sendgrid', render);
		data.router.post('/plugins/emailer-sendgrid/webhook', multipartMiddleware, Emailer.receive);

		if (typeof callback === 'function') {
			callback();
		}
	});
};

Emailer.receive = function (req, res) {
	Plugins.fireHook('filter:plugins.emailer.receive', {
		req: req,
		res: res,
		service: 'sendgrid',
	}, function (err, data) {
		if (err) {
			Emailer.handleError(err, data.req.body);
			return res.sendStatus(200);
		}

		async.waterfall([
			async.apply(Emailer.verifyEvent, data.req.body),
			Emailer.resolveUserOrGuest,
			Emailer.processEvent,
			Emailer.notifyUsers,
		], function (err, eventObj) {
			if (err) {
				Emailer.handleError(err, eventObj);
			}

			res.sendStatus(200);
		});
	});
};

Emailer.verifyEvent = function (eventObj, next) {
	var pid = eventObj.to.match(Emailer.receiptRegex);

	if (pid && pid.length && pid[1]) {
		pid = pid[1];
		eventObj.pid = pid;
		Posts.getPostField(pid, 'tid', function (err, tid) {
			if (!err && tid) {
				eventObj.tid = tid;
				next(null, eventObj);
			} else {
				if (!tid) { winston.warn('[emailer.sendgrid.verifyEvent] Could not retrieve tid'); }
				next(new Error('invalid-data'));
			}
		});
	} else {
		winston.warn('[emailer.sendgrid.verifyEvent] Could not locate post id');
		next(new Error('invalid-data'), eventObj);
	}
};

Emailer.resolveUserOrGuest = function (eventObj, callback) {
// This method takes the event object, reads the sender email and resolves it to a uid
// if the email is set in the system. If not, and guest posting is enabled, the email
// is treated as a guest instead.
	var envelope = JSON.parse(eventObj.envelope);
	User.getUidByEmail(envelope.from, function (err, uid) {
		if (err) {
			return callback(err);
		}

		if (uid) {
			eventObj.uid = uid;
			callback(null, eventObj);
		} else {
			// See if guests can post to the category in question
			async.waterfall([
				async.apply(Topics.getTopicField, eventObj.tid, 'cid'),
				function (cid, next) {
					Privileges.categories.groupPrivileges(cid, 'guests', next);
				},
			], function (err, privileges) {
				if (err) {
					return callback(privileges);
				}

				if (privileges['groups:topics:reply']) {
					eventObj.uid = 0;

					if (parseInt(Meta.config.allowGuestHandles, 10) === 1) {
						if (eventObj.msg.from_name && eventObj.msg.from_name.length) {
							eventObj.handle = eventObj.msg.from_name;
						} else {
							eventObj.handle = eventObj.msg.from_email;
						}
					}

					callback(null, eventObj);
				} else {
					// Guests can't post here
					winston.verbose('[emailer.sendgrid] Received reply by guest to pid ' + eventObj.pid + ', but guests are not allowed to post here.');
					callback(new Error('[[error:no-privileges]]'));
				}
			});
		}
	});
};

Emailer.processEvent = function (eventObj, callback) {
	winston.verbose('[emailer.sendgrid] Processing incoming email reply by uid ' + eventObj.uid + ' to pid ' + eventObj.pid);
	Topics.reply({
		uid: eventObj.uid,
		toPid: eventObj.pid,
		tid: eventObj.tid,
		content: require('node-email-reply-parser')(eventObj.text, true),
		handle: (eventObj.uid === 0 && eventObj.hasOwnProperty('handle') ? eventObj.handle : undefined),
	}, callback);
};

Emailer.notifyUsers = function (postData, next) {
	var result = {
		posts: [postData],
		privileges: {
			'topics:reply': true,
		},
		'reputation:disabled': parseInt(Meta.config['reputation:disabled'], 10) === 1,
		'downvote:disabled': parseInt(Meta.config['downvote:disabled'], 10) === 1,
	};

	SocketHelpers.notifyOnlineUsers(parseInt(postData.uid, 10), result);
	next();
};

Emailer.send = function (data, callback) {
	if (SendGrid) {
		Meta.settings.get('sendgrid', function (err, settings) {
			if (err) {
				return callback(err);
			}

			data.headers = data.headers || {};	// pre core v1.10.2

			async.waterfall([
				function (next) {
					if (data.fromUid) {
						next(null, data.fromUid);
					} else if (data._raw.notification && data._raw.notification.pid) {
						Posts.getPostField(data._raw.notification.pid, 'uid', next);
					} else {
						next(null, false);
					}
				},
				function (uid, next) {
					if (uid === false) { return next(null, {}); }

					User.getSettings(uid, function (err, settings) {
						if (err) {
							return next(err);
						}

						if (settings.showemail) {
							User.getUserFields(parseInt(uid, 10), ['email', 'username'], function (err, userData) {
								if (err) {
									return next(err);
								}

								next(null, userData);
							});
						} else {
							User.getUserFields(parseInt(uid, 10), ['username'], function (err, userData) {
								if (err) {
									return next(err);
								}

								next(null, userData);
							});
						}
					});
				},
				function (userData, next) {
					let replyTo;
					if (data._raw.notification && data._raw.notification.pid && settings.inbound_enabled === 'on') {
						replyTo = 'reply-' + data._raw.notification.pid + '@' + Emailer.hostname;
					}

					SendGrid.send({
						to: data.to,
						toname: data.toName,
						subject: data.subject,
						from: data.from,
						fromname: data.from_name || userData.username || undefined,
						text: data.text,
						html: data.html,
						headers: data.headers,
						reply_to: replyTo,
					}, next);
				},
			], function (err) {
				if (!err) {
					winston.verbose('[emailer.sendgrid] Sent `' + data.template + '` email to uid ' + data.uid);
					callback(null, data);
				} else {
					winston.warn('[emailer.sendgrid] Unable to send `' + data.template + '` email to uid ' + data.uid + '!!');
					winston.warn('[emailer.sendgrid] Error Stringified:' + JSON.stringify(err));
					callback(err);
				}
			});
		});
	} else {
		winston.warn('[plugins/emailer-sendgrid] API user and key not set, not sending email as SendGrid object is not instantiated.');
		callback(null, data);
	}
};

Emailer.handleError = function (err, eventObj) {
	var envelope = JSON.parse(eventObj.envelope);

	if (err) {
		switch (err.message) {
		case '[[error:no-privileges]]':
		case 'invalid-data':
			// Bounce a return back to sender
			hostEmailer.sendToEmail('bounce', envelope.from, Meta.config.defaultLang || 'en-GB', {
				site_title: Meta.config.title || 'NodeBB',
				subject: 'Re: ' + eventObj.subject,
				messageBody: eventObj.html,
			}, function (err) {
				if (err) {
					winston.error('[emailer.sendgrid] Unable to bounce email back to sender! ' + err.message);
				} else {
					winston.verbose('[emailer.sendgrid] Bounced email back to sender (' + envelope.from + ')');
				}
			});
			break;
		}
	}
};

Emailer.admin = {
	menu: function (custom_header, callback) {
		custom_header.plugins.push({
			route: '/plugins/emailer-sendgrid',
			icon: 'fa-envelope-o',
			name: 'Emailer (SendGrid)',
		});

		callback(null, custom_header);
	},
};

module.exports = Emailer;
<commit_msg>fix typo<commit_after>'use strict';

var winston = require.main.require('winston');
var async = require.main.require('async');
var nconf = require.main.require('nconf');
var url = require.main.require('url');
var Meta = require.main.require('./src/meta');
var Posts = require.main.require('./src/posts');
var Topics = require.main.require('./src/topics');
var Privileges = require.main.require('./src/privileges');
var Plugins = require.main.require('./src/plugins');
var SocketHelpers = require.main.require('./src/socket.io/helpers');
var User = require.main.require('./src/user');
var hostEmailer = require.main.require('./src/emailer');
var SendGrid;
var Emailer = {};

Emailer.hostname = url.parse(nconf.get('url')).hostname;
Emailer.receiptRegex = new RegExp('^reply-([\\d]+)@' + Emailer.hostname + '$');

Emailer.init = function (data, callback) {
	var render = function (req, res) {
		var destinationURL = nconf.get('url') + '/plugins/emailer-sendgrid/webhook';
		res.render('admin/plugins/emailer-sendgrid', { destinationURL: destinationURL });
	};

	Meta.settings.get('sendgrid', function (err, settings) {
		if (!err && settings && settings.apiKey) {
			SendGrid = require('@sendgrid/mail');
			SendGrid.setApiKey(settings.apiKey);
		} else {
			winston.error('[plugins/emailer-sendgrid] API key not set!');
		}

		var multipart = module.parent.require('connect-multiparty');
		var multipartMiddleware = multipart();

		data.router.get('/admin/plugins/emailer-sendgrid', data.middleware.admin.buildHeader, render);
		data.router.get('/api/admin/plugins/emailer-sendgrid', render);
		data.router.post('/plugins/emailer-sendgrid/webhook', multipartMiddleware, Emailer.receive);

		if (typeof callback === 'function') {
			callback();
		}
	});
};

Emailer.receive = function (req, res) {
	Plugins.fireHook('filter:plugins.emailer.receive', {
		req: req,
		res: res,
		service: 'sendgrid',
	}, function (err, data) {
		if (err) {
			Emailer.handleError(err, data.req.body);
			return res.sendStatus(200);
		}

		async.waterfall([
			async.apply(Emailer.verifyEvent, data.req.body),
			Emailer.resolveUserOrGuest,
			Emailer.processEvent,
			Emailer.notifyUsers,
		], function (err, eventObj) {
			if (err) {
				Emailer.handleError(err, eventObj);
			}

			res.sendStatus(200);
		});
	});
};

Emailer.verifyEvent = function (eventObj, next) {
	var pid = eventObj.to.match(Emailer.receiptRegex);

	if (pid && pid.length && pid[1]) {
		pid = pid[1];
		eventObj.pid = pid;
		Posts.getPostField(pid, 'tid', function (err, tid) {
			if (!err && tid) {
				eventObj.tid = tid;
				next(null, eventObj);
			} else {
				if (!tid) { winston.warn('[emailer.sendgrid.verifyEvent] Could not retrieve tid'); }
				next(new Error('invalid-data'));
			}
		});
	} else {
		winston.warn('[emailer.sendgrid.verifyEvent] Could not locate post id');
		next(new Error('invalid-data'), eventObj);
	}
};

Emailer.resolveUserOrGuest = function (eventObj, callback) {
// This method takes the event object, reads the sender email and resolves it to a uid
// if the email is set in the system. If not, and guest posting is enabled, the email
// is treated as a guest instead.
	var envelope = JSON.parse(eventObj.envelope);
	User.getUidByEmail(envelope.from, function (err, uid) {
		if (err) {
			return callback(err);
		}

		if (uid) {
			eventObj.uid = uid;
			callback(null, eventObj);
		} else {
			// See if guests can post to the category in question
			async.waterfall([
				async.apply(Topics.getTopicField, eventObj.tid, 'cid'),
				function (cid, next) {
					Privileges.categories.groupPrivileges(cid, 'guests', next);
				},
			], function (err, privileges) {
				if (err) {
					return callback(privileges);
				}

				if (privileges['groups:topics:reply']) {
					eventObj.uid = 0;

					if (parseInt(Meta.config.allowGuestHandles, 10) === 1) {
						if (eventObj.msg.from_name && eventObj.msg.from_name.length) {
							eventObj.handle = eventObj.msg.from_name;
						} else {
							eventObj.handle = eventObj.msg.from_email;
						}
					}

					callback(null, eventObj);
				} else {
					// Guests can't post here
					winston.verbose('[emailer.sendgrid] Received reply by guest to pid ' + eventObj.pid + ', but guests are not allowed to post here.');
					callback(new Error('[[error:no-privileges]]'));
				}
			});
		}
	});
};

Emailer.processEvent = function (eventObj, callback) {
	winston.verbose('[emailer.sendgrid] Processing incoming email reply by uid ' + eventObj.uid + ' to pid ' + eventObj.pid);
	Topics.reply({
		uid: eventObj.uid,
		toPid: eventObj.pid,
		tid: eventObj.tid,
		content: require('node-email-reply-parser')(eventObj.text, true),
		handle: (eventObj.uid === 0 && eventObj.hasOwnProperty('handle') ? eventObj.handle : undefined),
	}, callback);
};

Emailer.notifyUsers = function (postData, next) {
	var result = {
		posts: [postData],
		privileges: {
			'topics:reply': true,
		},
		'reputation:disabled': parseInt(Meta.config['reputation:disabled'], 10) === 1,
		'downvote:disabled': parseInt(Meta.config['downvote:disabled'], 10) === 1,
	};

	SocketHelpers.notifyOnlineUsers(parseInt(postData.uid, 10), result);
	next();
};

Emailer.send = function (data, callback) {
	if (SendGrid) {
		Meta.settings.get('sendgrid', function (err, settings) {
			if (err) {
				return callback(err);
			}

			data.headers = data.headers || {};	// pre core v1.10.2

			async.waterfall([
				function (next) {
					if (data.fromUid) {
						next(null, data.fromUid);
					} else if (data._raw.notification && data._raw.notification.pid) {
						Posts.getPostField(data._raw.notification.pid, 'uid', next);
					} else {
						next(null, false);
					}
				},
				function (uid, next) {
					if (uid === false) { return next(null, {}); }

					User.getSettings(uid, function (err, settings) {
						if (err) {
							return next(err);
						}

						if (settings.showemail) {
							User.getUserFields(parseInt(uid, 10), ['email', 'username'], function (err, userData) {
								if (err) {
									return next(err);
								}

								next(null, userData);
							});
						} else {
							User.getUserFields(parseInt(uid, 10), ['username'], function (err, userData) {
								if (err) {
									return next(err);
								}

								next(null, userData);
							});
						}
					});
				},
				function (userData, next) {
					let replyTo;
					if (data._raw.notification && data._raw.notification.pid && settings.inbound_enabled === 'on') {
						replyTo = 'reply-' + data._raw.notification.pid + '@' + Emailer.hostname;
					}

					SendGrid.send({
						to: data.to,
						toname: data.toName,
						subject: data.subject,
						from: data.from,
						fromname: data.from_name || userData.username || undefined,
						text: data.text,
						html: data.html,
						headers: data.headers,
						reply_to: replyTo,
					}, next);
				},
			], function (err) {
				if (!err) {
					winston.verbose('[emailer.sendgrid] Sent `' + data.template + '` email to uid ' + data.uid);
					callback(null, data);
				} else {
					winston.warn('[emailer.sendgrid] Unable to send `' + data.template + '` email to uid ' + data.uid + '!!');
					winston.warn('[emailer.sendgrid] Error Stringified:' + JSON.stringify(err));
					callback(err);
				}
			});
		});
	} else {
		winston.warn('[plugins/emailer-sendgrid] API user and key not set, not sending email as SendGrid object is not instantiated.');
		callback(null, data);
	}
};

Emailer.handleError = function (err, eventObj) {
	var envelope = JSON.parse(eventObj.envelope);

	if (err) {
		switch (err.message) {
		case '[[error:no-privileges]]':
		case 'invalid-data':
			// Bounce a return back to sender
			hostEmailer.sendToEmail('bounce', envelope.from, Meta.config.defaultLang || 'en-GB', {
				site_title: Meta.config.title || 'NodeBB',
				subject: 'Re: ' + eventObj.subject,
				messageBody: eventObj.html,
			}, function (err) {
				if (err) {
					winston.error('[emailer.sendgrid] Unable to bounce email back to sender! ' + err.message);
				} else {
					winston.verbose('[emailer.sendgrid] Bounced email back to sender (' + envelope.from + ')');
				}
			});
			break;
		}
	}
};

Emailer.admin = {
	menu: function (custom_header, callback) {
		custom_header.plugins.push({
			route: '/plugins/emailer-sendgrid',
			icon: 'fa-envelope-o',
			name: 'Emailer (SendGrid)',
		});

		callback(null, custom_header);
	},
};

module.exports = Emailer;
<|endoftext|>


<commit_before>var exec = require('child_process').exec;
var parseWrk = require('./lib/parseWrk');
var util = require("util");

function wrk(opts, callback) {
  var cmd = opts.path || 'wrk';

  if (opts.threads)
    cmd += ' -t' + opts.threads;
  if (opts.connections)
    cmd += ' -c' + opts.connections;
  if (opts.duration)
    cmd += ' -d' + opts.duration;
  if (opts.script)
    cmd += ' -s' + opts.script;
  if (opts.timeout)
    cmd += ' --timeout ' + opts.timeout;
  if (opts.rate)
    cmd += ' -R' + opts.rate;
  if (opts.printLatency)
    cmd += ' --latency ';
  if (opts.headers) {
    Object.keys(opts.headers).forEach(function(key) {
      cmd += util.format(' -H  \'%s: %s\'', key,  opts.headers[key]);
    })
  }

  cmd += ' ' + opts.url;
  opts.debug && console.log(cmd);
  var child = exec(cmd, function(error, stdout, stderr) {
    if (opts.debug) {
      stdout && console.log(stdout);
      stderr && console.error(stderr);
    }
    if (error) {
      return callback(error);
    }

    callback(null, parseWrk(stdout));
  });
}

module.exports = wrk;
module.exports.co = function(opts) {
  return function(callback) {
    wrk(opts, callback);
  }
};
<commit_msg>add support for execOptions, passing through options to child_process.exec<commit_after>var exec = require('child_process').exec;
var parseWrk = require('./lib/parseWrk');
var util = require("util");

function wrk(opts, callback) {
  var cmd = opts.path || 'wrk';

  if (opts.threads)
    cmd += ' -t' + opts.threads;
  if (opts.connections)
    cmd += ' -c' + opts.connections;
  if (opts.duration)
    cmd += ' -d' + opts.duration;
  if (opts.script)
    cmd += ' -s' + opts.script;
  if (opts.timeout)
    cmd += ' --timeout ' + opts.timeout;
  if (opts.rate)
    cmd += ' -R' + opts.rate;
  if (opts.printLatency)
    cmd += ' --latency ';
  if (opts.headers) {
    Object.keys(opts.headers).forEach(function(key) {
      cmd += util.format(' -H  \'%s: %s\'', key,  opts.headers[key]);
    })
  }

  // the caller may have requested that we pass options to the exec
  const { execOptions={} } = opts

  cmd += ' ' + opts.url;
  opts.debug && console.log(cmd);
  var child = exec(cmd, execOptions, function(error, stdout, stderr) {
    if (opts.debug) {
      stdout && console.log(stdout);
      stderr && console.error(stderr);
    }
    if (error) {
      return callback(error);
    }

    callback(null, parseWrk(stdout));
  });
}

module.exports = wrk;
module.exports.co = function(opts) {
  return function(callback) {
    wrk(opts, callback);
  }
};
<|endoftext|>


<commit_before>var express = require('express');
var app = express();

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, response) {
  response.render('pages/index')
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

<commit_msg>Add missing semicolon to express route handler<commit_after>var express = require('express');
var app = express();

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, response) {
  response.render('pages/index');
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

<|endoftext|>


<commit_before>'use strict';

/**
 * Created by mwarapitiya on 10/23/16.
 */

var path = require('path');
var childProcess = require('child_process');
var through = require('through2');
var gutil = require('gulp-util');
var which = require('which');
var mapSeries = require('async/mapSeries');
var yarnArgs = require('./utils/commands');
var PluginError = gutil.PluginError;

// Consts
var PLUGIN_NAME = 'gulpYarn';

var commandList = {
    'package.json': {
        cmd: 'yarn',
        args: []
    }
};

// Plugin level function(dealing with files)
function gulpYarn(gulpYarnOptions) {
    var toRun = [];
    var count = 0;

    // Creating a stream through which each file will pass
    return through.obj(function (file, enc, callback) {
        if (file === undefined || file.isNull()) {
            // return empty file
            return callback(null, file);
        }

        // flush function
        var flush = function flush(err, file) {
            if (err) {
                return callback(err);
            }
            return callback(null, file);
        };

        var command = clone(commandList[path.basename(file.path)]);

        if (command) {
            if (gulpYarnOptions) {
                var error = undefined;
                command.args = Object.keys(gulpYarnOptions).map(function (key) {
                    if (yarnArgs.hasOwnProperty(key) && gulpYarnOptions[key] === true) {
                        return yarnArgs[key];
                    } else {
                        if (key !== 'args') {
                            error = new PluginError(PLUGIN_NAME, `Command '${key}' not supported.`);
                        }
                    }
                }).filter(function (item) {
                    return item !== undefined || item === null;
                });

                if (error) {
                    return flush(error);
                }
            }
            if (gulpYarnOptions && gulpYarnOptions.args) {
                command.args = flatten(command.args.concat(formatArguments(gulpYarnOptions.args)));
            }
            command.cwd = path.dirname(file.path);
            toRun.push(command);
        }

        if (!toRun.length) {
            callback(new PluginError(PLUGIN_NAME, `No commands found to run.`));
        }

        return mapSeries(toRun, function (singleCommand, next) {
            which(singleCommand.cmd, function (err, cmdpath) {
                if (err) {
                    next(new PluginError(PLUGIN_NAME, `Error while determining the folder path.`));
                }
                var cmd = childProcess.spawn(cmdpath, singleCommand.args, {
                    stdio: 'inherit',
                    cwd: singleCommand.cwd || process.cwd()
                });
                cmd.once('close', function (code) {
                    if (code !== 0) {
                        next(new PluginError(PLUGIN_NAME, `${command.cmd} exited with non-zero code ${code}.`));
                    } else {
                        // If all commands are finished
                        if (toRun.length === ++count) {
                            next(false, file);
                        }
                    }
                });
            });
        }, function (err, file) {
            if (err) {
                flush(err);
            }
            flush(null, file[0]);
        });
    });
}

/**
 * Clone object
 * @param obj
 * @returns {*}
 */
function clone(obj) {
    if (Array.isArray(obj)) {
        return obj.map(clone);
    } else if (typeof obj === 'object') {
        var copy = {};
        Object.keys(obj).forEach(function (key) {
            copy[key] = clone(obj[key]);
        });
        return copy;
    }
    return obj;
}

/**
 * Flatten deep arrays
 * @param arr
 * @returns {*}
 */
function flatten(arr) {
    return arr.reduce(function (flat, toFlatten) {
        return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
    }, []);
}

/**
 * Formant Arguments
 * @param args
 * @returns {*}
 */
function formatArguments(args) {
    if (Array.isArray(args)) {
        return args.map(function (item) {
            return formatArgument(item);
        });
    } else if (typeof args === 'string' || args instanceof String) {
        return [formatArgument(args)];
    }
    console.error(`${PLUGIN_NAME} : Arguments are not passed in a valid format: ${args}`);
    return [];
}

/**
 * Format argument
 * @param arg
 * @returns {*}
 */
function formatArgument(arg) {
    var result = arg;
    while (!result.match(/--.*/)) {
        result = `-${result}`;
    }
    return result;
}

// Exporting the plugin main function
module.exports = gulpYarn;
<commit_msg>fix(core): add shell option to spawn function<commit_after>'use strict';

/**
 * Created by mwarapitiya on 10/23/16.
 */

var path = require('path');
var childProcess = require('child_process');
var through = require('through2');
var gutil = require('gulp-util');
var which = require('which');
var mapSeries = require('async/mapSeries');
var yarnArgs = require('./utils/commands');
var PluginError = gutil.PluginError;

// Consts
var PLUGIN_NAME = 'gulpYarn';

var commandList = {
    'package.json': {
        cmd: 'yarn',
        args: []
    }
};

// Plugin level function(dealing with files)
function gulpYarn(gulpYarnOptions) {
    var toRun = [];
    var count = 0;

    // Creating a stream through which each file will pass
    return through.obj(function (file, enc, callback) {
        if (file === undefined || file.isNull()) {
            // return empty file
            return callback(null, file);
        }

        // flush function
        var flush = function flush(err, file) {
            if (err) {
                return callback(err);
            }
            return callback(null, file);
        };

        var command = clone(commandList[path.basename(file.path)]);

        if (command) {
            if (gulpYarnOptions) {
                var error = undefined;
                command.args = Object.keys(gulpYarnOptions).map(function (key) {
                    if (yarnArgs.hasOwnProperty(key) && gulpYarnOptions[key] === true) {
                        return yarnArgs[key];
                    } else {
                        if (key !== 'args') {
                            error = new PluginError(PLUGIN_NAME, `Command '${key}' not supported.`);
                        }
                    }
                }).filter(function (item) {
                    return item !== undefined || item === null;
                });

                if (error) {
                    return flush(error);
                }
            }
            if (gulpYarnOptions && gulpYarnOptions.args) {
                command.args = flatten(command.args.concat(formatArguments(gulpYarnOptions.args)));
            }
            command.cwd = path.dirname(file.path);
            toRun.push(command);
        }

        if (!toRun.length) {
            callback(new PluginError(PLUGIN_NAME, `No commands found to run.`));
        }

        return mapSeries(toRun, function (singleCommand, next) {
            which(singleCommand.cmd, function (err, cmdpath) {
                if (err) {
                    next(new PluginError(PLUGIN_NAME, `Error while determining the folder path.`));
                }
                var installOptions = {
                    stdio: 'inherit',
                    shell: true,
                    cwd: singleCommand.cwd || process.cwd()
                };
                var cmd = childProcess.spawn(cmdpath, singleCommand.args, installOptions);
                cmd.once('close', function (code) {
                    if (code !== 0) {
                        next(new PluginError(PLUGIN_NAME, `${command.cmd} exited with non-zero code ${code}.`));
                    } else {
                        // If all commands are finished
                        if (toRun.length === ++count) {
                            next(false, file);
                        }
                    }
                });
            });
        }, function (err, file) {
            if (err) {
                flush(err);
            }
            flush(null, file[0]);
        });
    });
}

/**
 * Clone object
 * @param obj
 * @returns {*}
 */
function clone(obj) {
    if (Array.isArray(obj)) {
        return obj.map(clone);
    } else if (typeof obj === 'object') {
        var copy = {};
        Object.keys(obj).forEach(function (key) {
            copy[key] = clone(obj[key]);
        });
        return copy;
    }
    return obj;
}

/**
 * Flatten deep arrays
 * @param arr
 * @returns {*}
 */
function flatten(arr) {
    return arr.reduce(function (flat, toFlatten) {
        return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
    }, []);
}

/**
 * Formant Arguments
 * @param args
 * @returns {*}
 */
function formatArguments(args) {
    if (Array.isArray(args)) {
        return args.map(function (item) {
            return formatArgument(item);
        });
    } else if (typeof args === 'string' || args instanceof String) {
        return [formatArgument(args)];
    }
    console.error(`${PLUGIN_NAME} : Arguments are not passed in a valid format: ${args}`);
    return [];
}

/**
 * Format argument
 * @param arg
 * @returns {*}
 */
function formatArgument(arg) {
    var result = arg;
    while (!result.match(/--.*/)) {
        result = `-${result}`;
    }
    return result;
}

// Exporting the plugin main function
module.exports = gulpYarn;
<|endoftext|>