<commit_before>module.exports = function (ast, vars) {
    if (!vars) vars = {};
    var FAIL = {};

    var result = (function walk (node) {
        if (node.type === 'Literal') {
            return node.value;
        }
        else if (node.type === 'UnaryExpression'){
            var val = walk(node.argument)
            if (node.operator === '+') return +val
            if (node.operator === '-') return -val
            if (node.operator === '~') return ~val
            if (node.operator === '!') return !val
            return FAIL
        }
        else if (node.type === 'ArrayExpression') {
            var xs = [];
            for (var i = 0, l = node.elements.length; i < l; i++) {
                var x = walk(node.elements[i]);
                if (x === FAIL) return FAIL;
                xs.push(x);
            }
            return xs;
        }
        else if (node.type === 'ObjectExpression') {
            var obj = {};
            for (var i = 0; i < node.properties.length; i++) {
                var prop = node.properties[i];
                var value = prop.value === null
                    ? prop.value
                    : walk(prop.value)
                ;
                if (value === FAIL) return FAIL;
                obj[prop.key.value] = value;
            }
            return obj;
        }
        else if (node.type === 'BinaryExpression') {
            var l = walk(node.left);
            if (l === FAIL) return FAIL;
            var r = walk(node.right);
            if (r === FAIL) return FAIL;

            var op = node.operator;
            if (op === '==') return l == r;
            if (op === '===') return l === r;
            if (op === '!=') return l != r;
            if (op === '!==') return l !== r;
            if (op === '+') return l + r;
            if (op === '-') return l - r;
            if (op === '*') return l * r;
            if (op === '/') return l / r;
            if (op === '%') return l % r;
            if (op === '<') return l < r;
            if (op === '<=') return l <= r;
            if (op === '>') return l > r;
            if (op === '>=') return l >= r;
            if (op === '|') return l | r;
            if (op === '&') return l & r;
            if (op === '^') return l ^ r;
            if (op === '&&') return l && r;
            if (op === '||') return l || r;

            return FAIL;
        }
        else if (node.type === 'Identifier') {
            if ({}.hasOwnProperty.call(vars, node.name)) {
                return vars[node.name];
            }
            else return FAIL;
        }
        else if (node.type === 'CallExpression') {
            if ({}.hasOwnProperty.call(vars, node.callee.name)) {
                var args = [];
                for (var i = 0, l = node.arguments.length; i < l; i++) {
                    var x = walk(node.arguments[i]);
                    if (x === FAIL) return FAIL;
                    args.push(x);
                }
                return vars[node.callee.name].apply(null, args);
            }
            else return FAIL;
        }
        else if (node.type === 'MemberExpression') {
            var obj = walk(node.object);
            if (obj === FAIL) return FAIL;
            if (node.property.type === 'Identifier') {
                return obj[node.property.name];
            }
            var prop = walk(node.property);
            if (prop === FAIL) return FAIL;
            return obj[prop];
        }
        else if (node.type === 'ConditionalExpression') {
            var val = walk(node.test)
            if (val === FAIL) return FAIL;
            return val ? walk(node.consequent) : walk(node.alternate)
        }
        else return FAIL;
    })(ast);

    return result === FAIL ? undefined : result;
};
<commit_msg>added non-quoted object key support<commit_after>module.exports = function (ast, vars) {
    if (!vars) vars = {};
    var FAIL = {};

    var result = (function walk (node) {
        if (node.type === 'Literal') {
            return node.value;
        }
        else if (node.type === 'UnaryExpression'){
            var val = walk(node.argument)
            if (node.operator === '+') return +val
            if (node.operator === '-') return -val
            if (node.operator === '~') return ~val
            if (node.operator === '!') return !val
            return FAIL
        }
        else if (node.type === 'ArrayExpression') {
            var xs = [];
            for (var i = 0, l = node.elements.length; i < l; i++) {
                var x = walk(node.elements[i]);
                if (x === FAIL) return FAIL;
                xs.push(x);
            }
            return xs;
        }
        else if (node.type === 'ObjectExpression') {
            var obj = {};
            for (var i = 0; i < node.properties.length; i++) {
                var prop = node.properties[i];
                var value = prop.value === null
                    ? prop.value
                    : walk(prop.value)
                ;
                if (value === FAIL) return FAIL;
                obj[prop.key.value || prop.key.name] = value;
            }
            return obj;
        }
        else if (node.type === 'BinaryExpression') {
            var l = walk(node.left);
            if (l === FAIL) return FAIL;
            var r = walk(node.right);
            if (r === FAIL) return FAIL;

            var op = node.operator;
            if (op === '==') return l == r;
            if (op === '===') return l === r;
            if (op === '!=') return l != r;
            if (op === '!==') return l !== r;
            if (op === '+') return l + r;
            if (op === '-') return l - r;
            if (op === '*') return l * r;
            if (op === '/') return l / r;
            if (op === '%') return l % r;
            if (op === '<') return l < r;
            if (op === '<=') return l <= r;
            if (op === '>') return l > r;
            if (op === '>=') return l >= r;
            if (op === '|') return l | r;
            if (op === '&') return l & r;
            if (op === '^') return l ^ r;
            if (op === '&&') return l && r;
            if (op === '||') return l || r;

            return FAIL;
        }
        else if (node.type === 'Identifier') {
            if ({}.hasOwnProperty.call(vars, node.name)) {
                return vars[node.name];
            }
            else return FAIL;
        }
        else if (node.type === 'CallExpression') {
            if ({}.hasOwnProperty.call(vars, node.callee.name)) {
                var args = [];
                for (var i = 0, l = node.arguments.length; i < l; i++) {
                    var x = walk(node.arguments[i]);
                    if (x === FAIL) return FAIL;
                    args.push(x);
                }
                return vars[node.callee.name].apply(null, args);
            }
            else return FAIL;
        }
        else if (node.type === 'MemberExpression') {
            var obj = walk(node.object);
            if (obj === FAIL) return FAIL;
            if (node.property.type === 'Identifier') {
                return obj[node.property.name];
            }
            var prop = walk(node.property);
            if (prop === FAIL) return FAIL;
            return obj[prop];
        }
        else if (node.type === 'ConditionalExpression') {
            var val = walk(node.test)
            if (val === FAIL) return FAIL;
            return val ? walk(node.consequent) : walk(node.alternate)
        }
        else return FAIL;
    })(ast);

    return result === FAIL ? undefined : result;
};
<|endoftext|>


<commit_before>require('newrelic');
var express = require('express'),
bodyParser = require('body-parser'),
swig = require('swig');

var app = express();
var conf = require('./conf.js');
var database = require('./db.js')(conf);
var stalk = require('./stalk.js')(conf);

app.use(express.static(__dirname + '/public'));
app.use(bodyParser());
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');

database(function (err, db) {
    if (err) throw err;

    global.Mail = require('./mailer.js')(db, conf);

    app.post('/stalkers', function (req, res) {
        var email = req.param('email');

        if (!email) {
            res.json(500, {error: 'missing email'});
        } else {
            db.Stalkers.newStalker(email, function (err, stalker) {
                if (err) {
                    res.json(500, {error: err});
                } else {
                    res.json({stalker: stalker});
                }
            });
        }
    });

    app.get('/activities', function (req, res) {
        db.Activity.find({}, {sort: {date: -1}, wrap: false}, function (err, data) {
            if (err) {
                res.json(500, {error: err});
            } else {
                res.json({activities: data});
            }
        });
    });

    app.get('/stalk', function (req, res) {
        stalk.run(db, function (err) {
            if (err) {
                res.json(500, {error: err});
            } else {
                res.json({status: 'ok'});
            }
        });
    });

    app.get('/', function (req, res) {
        res.render('spa.html');
    });

    app.listen(conf.port, function () {
        console.log('Server run on ' + conf.port);
    });
});
<commit_msg>Fix stalk url method for work with temporize.net<commit_after>require('newrelic');
var express = require('express'),
bodyParser = require('body-parser'),
swig = require('swig');

var app = express();
var conf = require('./conf.js');
var database = require('./db.js')(conf);
var stalk = require('./stalk.js')(conf);

app.use(express.static(__dirname + '/public'));
app.use(bodyParser());
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');

database(function (err, db) {
    if (err) throw err;

    global.Mail = require('./mailer.js')(db, conf);

    app.post('/stalkers', function (req, res) {
        var email = req.param('email');

        if (!email) {
            res.json(500, {error: 'missing email'});
        } else {
            db.Stalkers.newStalker(email, function (err, stalker) {
                if (err) {
                    res.json(500, {error: err});
                } else {
                    res.json({stalker: stalker});
                }
            });
        }
    });

    app.get('/activities', function (req, res) {
        db.Activity.find({}, {sort: {date: -1}, wrap: false}, function (err, data) {
            if (err) {
                res.json(500, {error: err});
            } else {
                res.json({activities: data});
            }
        });
    });

    app.all('/stalk', function (req, res) {
        stalk.run(db, function (err) {
            if (err) {
                res.json(500, {error: err});
            } else {
                res.json({status: 'ok'});
            }
        });
    });

    app.get('/', function (req, res) {
        res.render('spa.html');
    });

    app.listen(conf.port, function () {
        console.log('Server run on ' + conf.port);
    });
});
<|endoftext|>


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

var cmds = {};
var options = {};
var positionals = {};
var aliases = {};

var toFunction = function(values) {
	if (typeof values === 'function') return values;

	if (values === '@file') return require('./helpers').file;
	if (values === '@dir')  return require('./helpers').dir;
	if (values === '@host') return require('./helpers').host;

	return function(callback) {
		callback(null, values);
	};
};

var clone = function(obj) {
	var c = {};
	Object.keys(obj || {}).forEach(function(key) {
		c[key] = obj[key];
	});
	return c;
};

var normalize = function(cmd, argv) {
	var aka = aliases[cmd] || aliases.__main__ || aliases['*'] || {};
	Object.keys(argv).forEach(function(arg) {
		if (!aka[arg]) return;
		var opt = aka[arg];
		argv[opt] = argv[opt] ? [].concat(argv[opt], argv[arg]) : argv[arg];
		delete argv[arg];
	});
	return argv;
};

var opt = function(name) {
	return '--'+name;
};

var deopt = function(opt) {
	return opt.replace(/^-+/g, '');
};

var tab = function(name) {
	var index = name ? 1 : 0;

	name = name || '__main__';
	var opts = options[name] = clone(options['*']);
	var pos = positionals[name] = clone(positionals['*']);
	var alias = aliases[name] = clone(aliases['*']);

	var onpositional = function(values) {
		if (name === '*') return pos[index++] = toFunction(values);
		if (name in cmds) pos[index++] = toFunction(cmds[name]);
		cmds[name] = values;
	};

	var onoption = function(name, shorts, values) {
		shorts.forEach(function(s) {
			alias[s] = name;
		});
		opts[name] = toFunction(values);
	};

	var parse = function(a) {
		if (typeof a !== 'string' || a[0] !== '-') {
			onpositional(a);
			return parse;
		}
		var shorts = Array.prototype.slice.call(arguments, 1);
		var values = (shorts[shorts.length - 1] || '')[0] === '-' ? undefined : shorts.pop();
		onoption(deopt(a), shorts.map(deopt), values);
		return parse;
	};

	return parse;
};

var call = function(fn, word, opts, callback) {
	if (fn.length === 3) return fn(word, opts, callback);
	if (fn.length === 2) return fn(word, callback);
	fn(callback);
};

var complete = function(index, words) {
	var ch = (words[index] || '')[0];

	words = words.map(function(word) {
		if (word[0] === '"') return word.replace(/(^")|("$)/g, '').replace(/\\"/g, '"');
		if (word[0] === "'") return word.replace(/(^')|('$)/g, '').replace(/\\'/g, "'");
		return word.replace(/\\(.)/g, '$1');
	});

	var cur = words[index] || '';
	var prev = words[index-1] || '';
	var _ = minimist(words.slice(0, index+1))._;
	var cmd = _[0];
	var argv = normalize(cmd, minimist(words));

	var callback = function(err, values, opts) {
		if (err) return process.exit(1);
		if (!opts) opts = {};

		values = [].concat(values || []).map(String);

		if (opts.filter !== false) {
			values = values.filter(function(value) {
				return value.slice(0, cur.length) === cur;
			});
		}

		values = values.map(function(word) {
			if (ch === '"') return word.replace(/"/g, '\\"')+'"';
			if (ch === "'") return word.replace(/'/g, "\\'")+"'";
			return word.replace(/([ ;!"'$()\[\]^{}&*?\\<>,`|])/g, '\\$1');
		});

		process.stdout.write(values.join('\n'), function() {
			process.exit(opts.exitCode || 0);
		});
	};

	if (cur.slice(0, 2) === '--' || cur === '-') {
		var names = Object.keys(options[cmd] || options.__main__ || options['*'] || {});
		return callback(null, names.map(opt));
	}

	var aka = aliases[cmd] || aliases.__main__ || aliases['*'] || {};

	if (cur[0] === '-') {
		var alias = aka[deopt(cur)];
		return alias ? callback(null, [opt(alias)], {filter:false}) : callback();
	}

	if (prev[0] === '-') {
		var name = deopt(prev);
		var fn = (options[cmd] || options.__main__ || options['*'] || {})[aka[name] || name];
		if (fn) return call(fn, cur, argv, callback);
		return callback();
	}

	index = _.length-1;
	var pos = (positionals[cmd] || positionals.__main__ || {})[index];
	if (pos) return call(pos, cur, argv, callback);

	if (prev[0] === '-' || cur[0] === '-') return callback();
	if (_.length > 1) return callback();

	var words = Object.keys(cmds).filter(function(cmd) {
		return cmd !== '__main__' && cmd !== '*';
	});

	return callback(null, words);
};

var parseCompletion = function(argv) {
	for (var i = 0; i < argv.length; i++) {
		if (argv[i] === 'completion' && argv[i+1] === '--' && (argv[i-1] || '')[0] !== '-') {
			return argv.slice(i+2).concat(argv.slice(0, i));
		}
	}
	return null;
};

tab.completion = require('./completion');

tab.parse = function(argv) {
	argv = argv || process.argv.slice(2);

	var completion = parseCompletion(argv);
	if (completion) {
		complete(Number(completion.shift()), completion);
		return true;
	}

	argv = minimist(argv);
	if (argv._[0] === 'completion') tab('completion')('--save', '-s')('--bin', '-b')('--dir', '-d')(tab.completion);

	var apply = function(cmd) {
		var offset = cmd ? 1 : 0;

		if (!cmd) cmd = '__main__';
		if (!cmds[cmd]) return false;

		process.nextTick(function() {
			var arity = Object.keys(positionals[cmd]).length;
			var args = [];

			for (var i = 0; i < arity; i++) {
				args[i] = argv._[i+offset];
			}

			args.push(normalize(cmd, argv));
			cmds[cmd].apply(null, args);
		});
		return true;
	};

	return apply(argv._[0]) || apply();
};

module.exports = tab;
<commit_msg>support wildcard argument completion<commit_after>var minimist = require('minimist');

var cmds = {};
var options = {};
var positionals = {};
var aliases = {};
var wildcards = {};

var toFunction = function(values) {
	if (typeof values === 'function') return values;

	if (values === '@file') return require('./helpers').file;
	if (values === '@dir')  return require('./helpers').dir;
	if (values === '@host') return require('./helpers').host;

	return function(callback) {
		callback(null, values);
	};
};

var clone = function(obj) {
	var c = {};
	Object.keys(obj || {}).forEach(function(key) {
		c[key] = obj[key];
	});
	return c;
};

var normalize = function(cmd, argv) {
	var aka = aliases[cmd] || aliases.__main__ || aliases['*'] || {};
	Object.keys(argv).forEach(function(arg) {
		if (!aka[arg]) return;
		var opt = aka[arg];
		argv[opt] = argv[opt] ? [].concat(argv[opt], argv[arg]) : argv[arg];
		delete argv[arg];
	});
	return argv;
};

var opt = function(name) {
	return '--'+name;
};

var deopt = function(opt) {
	return opt.replace(/^-+/g, '');
};

var tab = function(name) {
	var index = name ? 1 : 0;

	name = name || '__main__';
	var opts = options[name] = clone(options['*']);
	var pos = positionals[name] = clone(positionals['*']);
	var alias = aliases[name] = clone(aliases['*']);

	var onpositional = function(values) {
		if (name === '*') return pos[index++] = toFunction(values);
		if (name in cmds) pos[index++] = toFunction(cmds[name]);
		cmds[name] = values;
	};

	var onwildcard = function(values) {
		wildcards[name] = toFunction(values);
	}

	var onoption = function(name, shorts, values) {
		shorts.forEach(function(s) {
			alias[s] = name;
		});
		opts[name] = toFunction(values);
	};

	var parse = function(a, b) {
		if (a === '*') {
			onwildcard(b);
			return parse;
		}
		if (typeof a !== 'string' || a[0] !== '-') {
			onpositional(a);
			return parse;
		}
		var shorts = Array.prototype.slice.call(arguments, 1);
		var values = (shorts[shorts.length - 1] || '')[0] === '-' ? undefined : shorts.pop();
		onoption(deopt(a), shorts.map(deopt), values);
		return parse;
	};

	return parse;
};

var call = function(fn, word, opts, callback) {
	if (fn.length === 3) return fn(word, opts, callback);
	if (fn.length === 2) return fn(word, callback);
	fn(callback);
};

var complete = function(index, words) {
	var ch = (words[index] || '')[0];

	words = words.map(function(word) {
		if (word[0] === '"') return word.replace(/(^")|("$)/g, '').replace(/\\"/g, '"');
		if (word[0] === "'") return word.replace(/(^')|('$)/g, '').replace(/\\'/g, "'");
		return word.replace(/\\(.)/g, '$1');
	});

	var cur = words[index] || '';
	var prev = words[index-1] || '';
	var _ = minimist(words.slice(0, index+1))._;
	var cmd = _[0];
	var argv = normalize(cmd, minimist(words));

	var callback = function(err, values, opts) {
		if (err) return process.exit(1);
		if (!opts) opts = {};

		values = [].concat(values || []).map(String);

		if (opts.filter !== false) {
			values = values.filter(function(value) {
				return value.slice(0, cur.length) === cur;
			});
		}

		values = values.map(function(word) {
			if (ch === '"') return word.replace(/"/g, '\\"')+'"';
			if (ch === "'") return word.replace(/'/g, "\\'")+"'";
			return word.replace(/([ ;!"'$()\[\]^{}&*?\\<>,`|])/g, '\\$1');
		});

		process.stdout.write(values.join('\n'), function() {
			process.exit(opts.exitCode || 0);
		});
	};

	if (cur.slice(0, 2) === '--' || cur === '-') {
		var names = Object.keys(options[cmd] || options.__main__ || options['*'] || {});
		return callback(null, names.map(opt));
	}

	var aka = aliases[cmd] || aliases.__main__ || aliases['*'] || {};

	if (cur[0] === '-') {
		var alias = aka[deopt(cur)];
		return alias ? callback(null, [opt(alias)], {filter:false}) : callback();
	}

	if (prev[0] === '-') {
		var name = deopt(prev);
		var fn = (options[cmd] || options.__main__ || options['*'] || {})[aka[name] || name];
		if (fn) return call(fn, cur, argv, callback);
		return callback();
	}

	index = _.length-1;
	var pos = (positionals[cmd] || positionals.__main__ || {})[index] || wildcards[cmd] || wildcards.__main__;
	if (pos) return call(pos, cur, argv, callback);

	if (prev[0] === '-' || cur[0] === '-') return callback();
	if (_.length > 1) return callback();

	var words = Object.keys(cmds).filter(function(cmd) {
		return cmd !== '__main__' && cmd !== '*';
	});

	return callback(null, words);
};

var parseCompletion = function(argv) {
	for (var i = 0; i < argv.length; i++) {
		if (argv[i] === 'completion' && argv[i+1] === '--' && (argv[i-1] || '')[0] !== '-') {
			return argv.slice(i+2).concat(argv.slice(0, i));
		}
	}
	return null;
};

tab.completion = require('./completion');

tab.parse = function(argv) {
	argv = argv || process.argv.slice(2);

	var completion = parseCompletion(argv);
	if (completion) {
		complete(Number(completion.shift()), completion);
		return true;
	}

	argv = minimist(argv);
	if (argv._[0] === 'completion') tab('completion')('--save', '-s')('--bin', '-b')('--dir', '-d')(tab.completion);

	var apply = function(cmd) {
		var offset = cmd ? 1 : 0;

		if (!cmd) cmd = '__main__';
		if (!cmds[cmd]) return false;

		process.nextTick(function() {
			var arity = Object.keys(positionals[cmd]).length;
			var args = [];

			for (var i = 0; i < arity; i++) {
				args[i] = argv._[i+offset];
			}

			args.push(normalize(cmd, argv));
			cmds[cmd].apply(null, args);
		});
		return true;
	};

	return apply(argv._[0]) || apply();
};

module.exports = tab;
<|endoftext|>


<commit_before>var cssnext = require("cssnext")
var assign = require("object-assign")
var loaderUtils = require("loader-utils")

function defaultOptions(context, map){
  var options = {}
  options.from = loaderUtils.getRemainingRequest(context)
  options.to = loaderUtils.getRemainingRequest(context)
  if (context.sourceMap) {
    options.map = {
      inline: false,
      annotation: false,
      prev: map
    }
  }
  options.compress = context.minimize
  return options
}

function cssnextLoader(contents, map){
  this.cacheable()
  var options = assign({}, defaultOptions(this, map), this.options.cssnext)
  options.features = assign({}, this.options.cssnext ? this.options.cssnext.features : null)
  options.features.import = assign({}, options.features.import || null)
  options.features.import.onImport = function(files){
    files.forEach(this.addDependency)
  }.bind(this)
  try {
    var result = cssnext(contents, options)
    if (result.css) {
      this.callback(null, result.css, result.map)
    } else {
      return result
    }
  } catch(err) {
    this.emitError(err)
  }
}

module.exports = cssnextLoader
<commit_msg>fix `import`<commit_after>var cssnext = require("cssnext")
var assign = require("object-assign")
var loaderUtils = require("loader-utils")

function defaultOptions(context, map){
  var options = {}
  options.from = loaderUtils.getRemainingRequest(context)
  options.to = loaderUtils.getRemainingRequest(context)
  if (context.sourceMap) {
    options.map = {
      inline: false,
      annotation: false,
      prev: map
    }
  }
  options.compress = context.minimize
  return options
}

function cssnextLoader(contents, map){
  this.cacheable()
  var options = assign({}, defaultOptions(this, map), this.options.cssnext)
  options.features = assign({}, this.options.cssnext ? this.options.cssnext.features : null)
  options.import = assign({}, options.import || null)
  options.import.onImport = function(files){
    files.forEach(this.addDependency)
  }.bind(this)
  try {
    var result = cssnext(contents, options)
    if (result.css) {
      this.callback(null, result.css, result.map)
    } else {
      return result
    }
  } catch(err) {
    this.emitError(err)
  }
}

module.exports = cssnextLoader
<|endoftext|>


<commit_before>var url = require('url')

module.exports = parse

function parse(request, _callback) {
  var method = request.method.toLowerCase()
    , callback = _callback || Function()
    , params = ''

  if(method !== 'post' && method !== 'put') {
    return callback(null, url.parse(request.url, true).query)
  }

  request.on('data', onData)
  request.on('end', endRequest)

  request.resume()

  function onData(data) {
    params += data

    if(params.length > 1e6) {
      request.connection.destroy()
      callback(new Error('param size exceeded'))
    }
  }

  function endRequest() {
    try {
      var result = JSON.parse(params)
    } catch(e) {
      return callback(e)
    }

    callback(null, result)
  }
}
<commit_msg>remove space<commit_after>var url = require('url')

module.exports = parse

function parse(request, _callback) {
  var method = request.method.toLowerCase()
    , callback = _callback || Function()
    , params = ''

  if(method !== 'post' && method !== 'put') {
    return callback(null, url.parse(request.url, true).query)
  }

  request.on('data', onData)
  request.on('end', endRequest)

  request.resume()

  function onData(data) {
    params += data

    if(params.length > 1e6) {
      request.connection.destroy()
      callback(new Error('param size exceeded'))
    }
  }

  function endRequest() {
    try {
      var result = JSON.parse(params)
    } catch(e) {
      return callback(e)
    }

    callback(null, result)
  }
}
<|endoftext|>


<commit_before>'use strict';

var assign = require('mixin-deep');

function regulate(anyValues, anyPromotions, anyEliminations) {
	var eliminations, promotions;

	promotions = _arrayify(anyPromotions);
	eliminations = _arrayify(anyEliminations);
	return _regulate(anyValues);

	function _regulate(values) {
		if (Array.isArray(values)) {
			return values.map(_regulate);
		}
		if (isObject(values)) {
			return _eliminate(_promote(values));
		}
		return values;
	}

	function _promote(values) {
		return _each(values, __promote);

		function __promote(value, key, result) {
			if (includes(promotions, key) && isObject(value)) {
				assign(result, _regulate(value));
				return true;
			}
		}
	}

	function _eliminate(values) {
		return _each(values, __eliminate);

		function __eliminate(value, key) {
			return includes(eliminations, key);
		}
	}

	function _each(values, fn) {
		return Object.keys(values).reduce(_property, {});

		function _property(result, key) {
			var value;

			value = values[key];
			if (!fn(value, key, result)) {
				(result[key] = _regulate(value));
			}
			return result;
		}
	}
}

function _arrayify(value) {
	if (Array.isArray(value)) {
		return value;
	}
	if (isString(value)) {
		return [value];
	}
	return [];
}

function isString(value) {
	return typeof value === 'string';
}

function isObject(value) {
	return !!value && typeof value === 'object' && !Array.isArray(value);
}

function includes(array, value) {
	return array.indexOf(value) !== -1;
}

module.exports = regulate;
<commit_msg>normalize __promote() and __eliminate() call<commit_after>'use strict';

var assign = require('mixin-deep');

function regulate(anyValues, anyPromotions, anyEliminations) {
	var eliminations, promotions;

	promotions = _arrayify(anyPromotions);
	eliminations = _arrayify(anyEliminations);
	return _regulate(anyValues);

	function _regulate(values) {
		if (Array.isArray(values)) {
			return values.map(_regulate);
		}
		if (isObject(values)) {
			return _eliminate(_promote(values));
		}
		return values;
	}

	function _promote(values) {
		return _each(values, __promote);

		function __promote(value, key, result) {
			if (includes(promotions, key) && isObject(value)) {
				return assign(result, _regulate(value));
			}
		}
	}

	function _eliminate(values) {
		return _each(values, __eliminate);

		function __eliminate(value, key, result) {
			if (includes(eliminations, key)) {
				return result;
			}
		}
	}

	function _each(values, fn) {
		return Object.keys(values).reduce(_property, {});

		function _property(result, key) {
			var value;

			value = values[key];
			return fn(value, key, result) || (result[key] = _regulate(value), result);
		}
	}
}

function _arrayify(value) {
	if (Array.isArray(value)) {
		return value;
	}
	if (isString(value)) {
		return [value];
	}
	return [];
}

function isString(value) {
	return typeof value === 'string';
}

function isObject(value) {
	return !!value && typeof value === 'object' && !Array.isArray(value);
}

function includes(array, value) {
	return array.indexOf(value) !== -1;
}

module.exports = regulate;
<|endoftext|>


<commit_before>const baseConfig = require('../../core/build/webpack.base.config.js')
const webpack = require('webpack')
const VueLoaderPlugin = require('vue-loader/lib/plugin')

const webpackConfig = Object.assign({}, baseConfig, {
  devtool: 'inline-source-map',
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': '"test"'
    }),
    new VueLoaderPlugin()
  ]
})

// no need for app entry during tests
delete webpackConfig.entry

module.exports = function (config) {
  config.set({
    browsers: ['Chrome'],
    frameworks: ['mocha', 'sinon-chai'],
    reporters: ['spec'],
    files: ['./index.js'],
    preprocessors: {
      './index.js': ['webpack', 'sourcemap']
    },
    webpack: webpackConfig,
    webpackMiddleware: {
      noInfo: true
    }
  })
}
<commit_msg>Change Chrome to headless in karma.conf.js<commit_after>const baseConfig = require('../../core/build/webpack.base.config.js')
const webpack = require('webpack')
const VueLoaderPlugin = require('vue-loader/lib/plugin')

const webpackConfig = Object.assign({}, baseConfig, {
  devtool: 'inline-source-map',
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': '"test"'
    }),
    new VueLoaderPlugin()
  ]
})

// no need for app entry during tests
delete webpackConfig.entry

module.exports = function (config) {
  config.set({
    browsers: ['ChromeHeadless'],
    frameworks: ['mocha', 'sinon-chai'],
    reporters: ['spec'],
    files: ['./index.js'],
    preprocessors: {
      './index.js': ['webpack', 'sourcemap']
    },
    webpack: webpackConfig,
    webpackMiddleware: {
      noInfo: true
    }
  })
}
<|endoftext|>


<commit_before>'use strict';

var Mocha = require('../../lib/mocha');
var Test = Mocha.Test;

describe('Mocha', function () {
  var blankOpts = { reporter: function () {} }; // no output

  describe('.run(fn)', function () {
    it('should not raise errors if callback was not provided', function () {
      var mocha = new Mocha(blankOpts);
      mocha.run();
    });

    it('should execute the callback when complete', function (done) {
      var mocha = new Mocha(blankOpts);
      mocha.run(function () {
        done();
      });
    });

    it('should execute the callback with the number of failures ' +
      'as parameter', function (done) {
      var mocha = new Mocha(blankOpts);
      var failingTest = new Test('failing test', function () {
        throw new Error('such fail');
      });
      mocha.suite.addTest(failingTest);
      mocha.run(function (failures) {
        expect(failures).to.equal(1);
        done();
      });
    });
  });

  describe('.addFile()', function () {
    it('should add the given file to the files array', function () {
      var mocha = new Mocha(blankOpts);
      mocha.addFile('myFile.js');
      expect(mocha.files.length).to.equal(1);
      expect(mocha.files[0]).to.equal('myFile.js');
    });
  });

  describe('.invert()', function () {
    it('should set the invert option to true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.invert();
      expect(mocha.options.invert).to.equal(true);
    });

    it('should be chainable', function () {
      var mocha = new Mocha(blankOpts);
      expect(mocha.invert()).to.equal(mocha);
    });
  });

  describe('.ignoreLeaks()', function () {
    it('should set the ignoreLeaks option to true when param equals true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.ignoreLeaks(true);
      expect(mocha.options.ignoreLeaks).to.equal(true);
    });

    it('should set the ignoreLeaks option to false when param equals false', function () {
      var mocha = new Mocha(blankOpts);
      mocha.ignoreLeaks(false);
      expect(mocha.options.ignoreLeaks).to.equal(false);
    });

    it('should set the ignoreLeaks option to false when the param is undefined', function () {
      var mocha = new Mocha(blankOpts);
      mocha.ignoreLeaks();
      expect(mocha.options.ignoreLeaks).to.equal(false);
    });

    it('should be chainable', function () {
      var mocha = new Mocha(blankOpts);
      expect(mocha.ignoreLeaks(false)).to.equal(mocha);
    });
  });

  describe('.checkLeaks()', function () {
    it('should set the ignoreLeaks option to false', function () {
      var mocha = new Mocha(blankOpts);
      mocha.checkLeaks();
      expect(mocha.options.ignoreLeaks).to.equal(false);
    });

    it('should be chainable', function () {
      var mocha = new Mocha(blankOpts);
      expect(mocha.checkLeaks()).to.equal(mocha);
    });
  });

  describe('.fullTrace()', function () {
    it('should set the fullStackTrace option to true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.fullTrace();
      expect(mocha.options.fullStackTrace).to.equal(true);
    });

    it('should be chainable', function () {
      var mocha = new Mocha(blankOpts);
      expect(mocha.fullTrace()).to.equal(mocha);
    });
  });

  describe('.growl()', function () {
    it('should set the growl option to true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.growl();
      expect(mocha.options.growl).to.equal(true);
    });

    it('should be chainable', function () {
      var mocha = new Mocha(blankOpts);
      expect(mocha.growl()).to.equal(mocha);
    });
  });

  describe('.useInlineDiffs()', function () {
    it('should set the useInlineDiffs option to true when param equals true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.useInlineDiffs(true);
      expect(mocha.options.useInlineDiffs).to.equal(true);
    });

    it('should set the useInlineDiffs option to false when param equals false', function () {
      var mocha = new Mocha(blankOpts);
      mocha.useInlineDiffs(false);
      expect(mocha.options.useInlineDiffs).to.equal(false);
    });

    it('should set the useInlineDiffs option to false when the param is undefined', function () {
      var mocha = new Mocha(blankOpts);
      mocha.useInlineDiffs();
      expect(mocha.options.useInlineDiffs).to.equal(false);
    });

    it('should be chainable', function () {
      var mocha = new Mocha(blankOpts);
      expect(mocha.useInlineDiffs()).to.equal(mocha);
    });
  });

  describe('.noHighlighting()', function () {
    it('should set the noHighlighting option to true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.noHighlighting();
      expect(mocha.options.noHighlighting).to.equal(true);
    });
  });

  describe('.allowUncaught()', function () {
    it('should set the allowUncaught option to true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.allowUncaught();
      expect(mocha.options.allowUncaught).to.equal(true);
    });
  });

  describe('.delay()', function () {
    it('should set the delay option to true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.delay();
      expect(mocha.options.delay).to.equal(true);
    });
  });
});
<commit_msg>Add test for Mocha.bail()<commit_after>'use strict';

var Mocha = require('../../lib/mocha');
var Test = Mocha.Test;

describe('Mocha', function () {
  var blankOpts = { reporter: function () {} }; // no output

  describe('.run(fn)', function () {
    it('should not raise errors if callback was not provided', function () {
      var mocha = new Mocha(blankOpts);
      mocha.run();
    });

    it('should execute the callback when complete', function (done) {
      var mocha = new Mocha(blankOpts);
      mocha.run(function () {
        done();
      });
    });

    it('should execute the callback with the number of failures ' +
      'as parameter', function (done) {
      var mocha = new Mocha(blankOpts);
      var failingTest = new Test('failing test', function () {
        throw new Error('such fail');
      });
      mocha.suite.addTest(failingTest);
      mocha.run(function (failures) {
        expect(failures).to.equal(1);
        done();
      });
    });
  });

  describe('.addFile()', function () {
    it('should add the given file to the files array', function () {
      var mocha = new Mocha(blankOpts);
      mocha.addFile('myFile.js');
      expect(mocha.files.length).to.equal(1);
      expect(mocha.files[0]).to.equal('myFile.js');
    });
  });

  describe('.invert()', function () {
    it('should set the invert option to true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.invert();
      expect(mocha.options.invert).to.equal(true);
    });

    it('should be chainable', function () {
      var mocha = new Mocha(blankOpts);
      expect(mocha.invert()).to.equal(mocha);
    });
  });

  describe('.ignoreLeaks()', function () {
    it('should set the ignoreLeaks option to true when param equals true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.ignoreLeaks(true);
      expect(mocha.options.ignoreLeaks).to.equal(true);
    });

    it('should set the ignoreLeaks option to false when param equals false', function () {
      var mocha = new Mocha(blankOpts);
      mocha.ignoreLeaks(false);
      expect(mocha.options.ignoreLeaks).to.equal(false);
    });

    it('should set the ignoreLeaks option to false when the param is undefined', function () {
      var mocha = new Mocha(blankOpts);
      mocha.ignoreLeaks();
      expect(mocha.options.ignoreLeaks).to.equal(false);
    });

    it('should be chainable', function () {
      var mocha = new Mocha(blankOpts);
      expect(mocha.ignoreLeaks(false)).to.equal(mocha);
    });
  });

  describe('.checkLeaks()', function () {
    it('should set the ignoreLeaks option to false', function () {
      var mocha = new Mocha(blankOpts);
      mocha.checkLeaks();
      expect(mocha.options.ignoreLeaks).to.equal(false);
    });

    it('should be chainable', function () {
      var mocha = new Mocha(blankOpts);
      expect(mocha.checkLeaks()).to.equal(mocha);
    });
  });

  describe('.fullTrace()', function () {
    it('should set the fullStackTrace option to true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.fullTrace();
      expect(mocha.options.fullStackTrace).to.equal(true);
    });

    it('should be chainable', function () {
      var mocha = new Mocha(blankOpts);
      expect(mocha.fullTrace()).to.equal(mocha);
    });
  });

  describe('.growl()', function () {
    it('should set the growl option to true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.growl();
      expect(mocha.options.growl).to.equal(true);
    });

    it('should be chainable', function () {
      var mocha = new Mocha(blankOpts);
      expect(mocha.growl()).to.equal(mocha);
    });
  });

  describe('.useInlineDiffs()', function () {
    it('should set the useInlineDiffs option to true when param equals true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.useInlineDiffs(true);
      expect(mocha.options.useInlineDiffs).to.equal(true);
    });

    it('should set the useInlineDiffs option to false when param equals false', function () {
      var mocha = new Mocha(blankOpts);
      mocha.useInlineDiffs(false);
      expect(mocha.options.useInlineDiffs).to.equal(false);
    });

    it('should set the useInlineDiffs option to false when the param is undefined', function () {
      var mocha = new Mocha(blankOpts);
      mocha.useInlineDiffs();
      expect(mocha.options.useInlineDiffs).to.equal(false);
    });

    it('should be chainable', function () {
      var mocha = new Mocha(blankOpts);
      expect(mocha.useInlineDiffs()).to.equal(mocha);
    });
  });

  describe('.noHighlighting()', function () {
    it('should set the noHighlighting option to true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.noHighlighting();
      expect(mocha.options.noHighlighting).to.equal(true);
    });
  });

  describe('.allowUncaught()', function () {
    it('should set the allowUncaught option to true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.allowUncaught();
      expect(mocha.options.allowUncaught).to.equal(true);
    });
  });

  describe('.delay()', function () {
    it('should set the delay option to true', function () {
      var mocha = new Mocha(blankOpts);
      mocha.delay();
      expect(mocha.options.delay).to.equal(true);
    });
  });

  describe('.bail()', function () {
    it('should set the suite._bail to true if there is no arguments', function () {
      var mocha = new Mocha({bail: false});
      expect(mocha.suite._bail).to.equal(false);
      mocha.bail();
      expect(mocha.suite._bail).to.equal(true);
    });
  });
});
<|endoftext|>


<commit_before>var _ = require('lodash'),
    formatted = '' +
    '' +
    '' +
    '';

module.exports = {
    respond: function ( req, res, format ) {
        return _.once(function ( error, data ) {
            if (req.query.formatted !== void 0 || format) {
                res.send(formatted +
                    '
' +
                    JSON.stringify(data, null, 4) +
                    '
');
            }
            if (error) {
                data = {error: error};
                res.status(404).send(data);
            } else {
                res.json(data);
            }
        });
    },
    load: function(app, routes){
        var key;
        routes.forEach(function ( route ) {
            var API = route.API;
            for (key in API) {
                console.log('registering ' + key + ' as ' + API[key].type);
                app[API[key].type](key, API[key].responder);
                //if (API[key].type !== 'get' && API[key].type !== 'use') {
                //    console.log('registering ' + key + ' as get');
                //    app.get(key, API[key].responder);
                //}
            }
        });
    }
};

<commit_msg>Add headers to prevent browser caching<commit_after>var _ = require('lodash'),
    formatted = '' +
    '' +
    '' +
    '';

module.exports = {
    respond: function ( req, res, format ) {
        return _.once(function ( error, data ) {
            //disable browser caching
            res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
            res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
            res.setHeader("Expires", "0"); // Proxies.
            if (req.query.formatted !== void 0 || format) {
                res.send(formatted +
                    '
' +
                    JSON.stringify(data, null, 4) +
                    '
');
            }
            if (error) {
                data = {error: error};
                res.status(404).send(data);
            } else {
                res.json(data);
            }
        });
    },
    load: function(app, routes){
        var key;
        routes.forEach(function ( route ) {
            var API = route.API;
            for (key in API) {
                console.log('registering ' + key + ' as ' + API[key].type);
                app[API[key].type](key, API[key].responder);
                //if (API[key].type !== 'get' && API[key].type !== 'use') {
                //    console.log('registering ' + key + ' as get');
                //    app.get(key, API[key].responder);
                //}
            }
        });
    }
};

<|endoftext|>


<commit_before>'use strict';
/*jshint expr: true*/
const path = require('path');
const events = require('events');
const chai = require('chai');
const fs = require('fs-extra');
const expect = require('chai').expect;
const testSchemaDBPath = path.join(__dirname, '../mock/modeltestdb.json');
const removeTestDB = require('../util/removeTestDB');
let lowkie = require('../../index');
let lowkieClass = require('../../lib/lowkieClass');
let testUserModelScheme = {
  name: String,
  email: String,
  active: Boolean,
  age: Number,
  profile: {
    type: String,
    default: 'no profile',
  },
};
let testUserModel;
// let testUserModel;

describe('Model', function () {
  this.timeout(10000);
  before('intialize lowkie instance', (done) => {
    removeTestDB(testSchemaDBPath, false);
    lowkie.connect(testSchemaDBPath)
      .then((/*db*/) => {
        // console.log('connected modeltestdb');
        // testUserModel = lowkie.Schema(testUserModelScheme);
        // testUserModel = lowkie.model('testuser', testUserModel);
        // console.log({testUserModel})
        done();
      })
      .catch(done);
  });
	describe('Creation', function () {
    it('should throw an error if creating a model before databse is loaded', function () {
      let newLOWKIE = new lowkieClass({});
      expect(newLOWKIE.model.bind(newLOWKIE)).to.throw('There has to be an active lowkie connection before creating models, lowkie.connect is asynchronous');
    });
    it('should throw an error if model name is not a valid string', function (done) {
      let newLOWKIE = new lowkieClass({});
      let throwawayfilepath = path.join(__dirname, '../mock/modelthrowaway1.json');
      newLOWKIE.connect(throwawayfilepath)
        .then(() => {
          expect(newLOWKIE.model.bind(newLOWKIE)).to.throw('model name must be a valid string');
          removeTestDB(throwawayfilepath);
          done()
        })
        .catch(done);
    });
    it('should throw an error if schema isnt an instance of lowkie schema', function (done) {
      let newLOWKIE = new lowkieClass({});
      let throwawayfilepath = path.join(__dirname, '../mock/modelthrowaway2.json');
      let model = 'testmodel';
      newLOWKIE.connect(throwawayfilepath)
        .then(() => {
          expect(newLOWKIE.model.bind(newLOWKIE, model, { name:String,description:String, })).to.throw(`${model} must be an instance of a lowkieSchema`);
          removeTestDB(throwawayfilepath);
          done();
        })
        .catch(done);
    });
    it('should register models globally', () => {
      let goodModelSchema = lowkie.Schema(testUserModelScheme);
      lowkie.model('goodModel', goodModelSchema);
      // console.log(lowkie.models);
      expect(Object.keys(lowkie.models)).to.have.length.above(0);
    });
  });
  after('remove test schema db', () => {
    removeTestDB(testSchemaDBPath, true);
  });
});<commit_msg>Adding more test coverage<commit_after>'use strict';
/*jshint expr: true*/
const path = require('path');
const events = require('events');
const chai = require('chai');
const sinon = require('sinon');
const fs = require('fs-extra');
const expect = require('chai').expect;
const testSchemaDBPath = path.join(__dirname, '../mock/modeltestdb.json');
const removeTestDB = require('../util/removeTestDB');
let lowkie = require('../../index');
let lowkieClass = require('../../lib/lowkieClass');
let testUserModelScheme = {
  name: String,
  email: String,
  active: Boolean,
  age: Number,
  profile: {
    type: String,
    default: 'no profile',
  },
};
let testUserModel;
let goodModelSchema;
let goodModel;

describe('Model', function () {
  this.timeout(10000);
  before('intialize lowkie instance', (done) => {
    removeTestDB(testSchemaDBPath, false);
    lowkie.connect(testSchemaDBPath)
      .then((/*db*/) => {
        // console.log('connected modeltestdb');
        // testUserModel = lowkie.Schema(testUserModelScheme);
        // testUserModel = lowkie.model('testuser', testUserModel);
        // console.log({testUserModel})
        done();
      })
      .catch(done);
  });
	describe('Creation', function () {
    it('should throw an error if creating a model before databse is loaded', function () {
      let spy = sinon.spy();
      // let originalConsoleError = console.error;
      let newLOWKIE = new lowkieClass({});
      newLOWKIE.debug = true;
      console.error = spy;
      expect(newLOWKIE.model.bind(newLOWKIE)).to.throw('There has to be an active lowkie connection before creating models, lowkie.connect is asynchronous');
      expect(spy).to.be.been.called;
    });
    it('should throw an error if model name is not a valid string', function (done) {
      let newLOWKIE = new lowkieClass({});
      let throwawayfilepath = path.join(__dirname, '../mock/modelthrowaway1.json');
      newLOWKIE.connect(throwawayfilepath)
        .then(() => {
          expect(newLOWKIE.model.bind(newLOWKIE)).to.throw('model name must be a valid string');
          removeTestDB(throwawayfilepath);
          done()
        })
        .catch(done);
    });
    it('should throw an error if schema isnt an instance of lowkie schema', function (done) {
      let newLOWKIE = new lowkieClass({});
      let throwawayfilepath = path.join(__dirname, '../mock/modelthrowaway2.json');
      let model = 'testmodel';
      newLOWKIE.connect(throwawayfilepath)
        .then(() => {
          expect(newLOWKIE.model.bind(newLOWKIE, model, { name:String,description:String, })).to.throw(`${model} must be an instance of a lowkieSchema`);
          removeTestDB(throwawayfilepath);
          done();
        })
        .catch(done);
    });
    it('should register models globally', () => {
      goodModelSchema = lowkie.Schema(testUserModelScheme);
      goodModel = lowkie.model('goodModel', goodModelSchema);
      // console.log(lowkie.models);
      expect(Object.keys(lowkie.models)).to.have.length.above(0);
    });
    it('should use existing schema if already exists', () => {
      let newGoodModelSchema = lowkie.Schema(testUserModelScheme);
      let newGoodModel = lowkie.model('goodModel', newGoodModelSchema);
      // console.log(lowkie.models);
      expect(Object.keys(lowkie.models)).to.have.lengthOf(1);
      expect(goodModel).to.eql(newGoodModel);
    });
  });
  after('remove test schema db', () => {
    removeTestDB(testSchemaDBPath, true);
  });
});<|endoftext|>


<commit_before>import getCoordinatesFromLocation from './actions/facebookcoordsservice';
import getImagesFromCoords from './actions/instagramservice';

const express = require('express');
const http = require('http');
const path = require('path');
const socketIo = require('socket.io');
const webpack = require('webpack');
const webpackConfig = require('./webpack.config.js');

const compiler = webpack(webpackConfig);
const webpackDevMiddleware = require('webpack-dev-middleware')(compiler, { noInfo: false, publicPath: webpackConfig.output.publicPath });

const app = express();
const server = http.createServer(app);
const io = socketIo(server, { pingTimeout: 3000, pingInterval: 3000 });

app.use(webpackDevMiddleware);
app.use(require('webpack-hot-middleware')(compiler));

// no
app.use(express.static(path.join(__dirname, '/public')));

app.get('/test', async (request, response) => {
  const location = request.query.location;
 // const params = request.params;

  console.log('LOCATION', location);
  // console.log('params', params);

  // ok, works. it's much better.where you see it works?
  // no errors, and we got the data. ok
  // if we do it without await, we'll get the promise in "coords".
  // now it's typical js code. we have promise we need to resolve with .then
  // we don't want to do that shit. we want to work with data, not deal with promises here. ok
  // const coords = getCoordinatesFromLocation(location);
  // understand the difference? yes but ok i thouth its async by default. without await, code doesn't stop
  // it doesn't wait until your data is coming back. so you can't be sure whats inside the variable.

  // //aahhh so its like we didnt catch the data, yes. it will be there at some point, in the future when
  // promise resolves, but when you run the code, there will be a promise. we want to work with data.

  // it's the same but i dont get something js is async by default wey never added.
  // js is async, that's why it doesn't wait until promise resolves. but we don't want that.
  // we prefer to do this:
  const coords = await getCoordinatesFromLocation(location);
  // response.json(coords);
  try {
    const images = await getImagesFromCoords(coords);
    response.json({ images, coords });
  } catch (err) {
    throw new Error(err);
  }

  // response.json('ok');

  // this way you can use "coords" and you will be sure that there is data from the server,
  // not promise or other shit. you tell js to wait until promise resolves.
  // .then shit does it no? when promise resolves, it executes .then. here. but why would you want
  // to write .then then .then instead of this? just to see its working hhhhh
  // you right you already showed me. you see how simple it is to work with async functions?
  console.log(coords);

    /*
    .then((data) => {
      // you understand the logic?yes
      // make it happen. /test/?location=tel-aviv
      // should returns data from instagram.
      // adblocks instagram too/?
      // adblock is irrelevant if you're using your own
      // server. client won't connect to facebook and to instagram
      // anymore. react will ask /test/ for images.
      // remake instagram api, so it would work on server and on client
      // as well. find isomorphic jsonp library. ok. good. talk to me, after you rewrite instagram service. ok tnx alot this is crazy
      // it's must have. now nobody can steal you facebook api key.

      response.json(data);
      // console.log(data);
      // where are you executing instagram service exactly?
      // it's facebook apino instagram. my bad.
      // this is a fucking mess with .then.then.then.zubi.fuck.ASS.. let's see if async/await works here
      getImagesFromCoords(data)
        .then((res) => {
          response.json(res);
          console.log('response from server', res);
        }).catch(err => console.log(err));
    }).catch(err => console.log(err));

    */
});

app.get('*', (request, response) => {
  response.sendFile(path.resolve(__dirname, 'public', 'index.html'));
});
server.listen(8080);

// no need for router? what router and where?

//  setInterval(() => {
//    io.emit('message', { name: 'Server', text: 'Shalom' });
//  }, 5000);

// Socket.io Code
// const users = [];
const users = {};
const socketsim = {};
const clients = [];
const coords = [];

io.on('connection', (socket) => { // what this line doing? when someone connects
 // socket.emit('user_connected', socket.id); // understand the problem? yes, we sent message only to ourself
  console.log('someone connected.');

  socket.on('user_connected', (username) => {
    console.log('data', username);
   // users[username] = socket.id;

   // socket.join({ username: socket.id });
    socket.join(socket.id);

  //  clients.push(users[username] = socket.id);

    // const user = username;
    const connections = {
      [username]: socket.id
    };
    clients.push(connections);

    // users.push(connections);    // Store a reference to your socket
    socketsim[socket.id] = { user: username, soc: socket };  // Store a reference to your socket
    console.log('data_socket', socket.adapter.rooms);
    console.log('data_users', users);
    io.sockets.emit('connected_users', clients);
  });

      // Private message is sent from client with username of person you want to 'private message'
  socket.on('private_message', (data) => {
    const msg = data.message;
    const to = data.to;
    // const from = data.from;
   // const username = sockets[socket.id];
    console.log('soketeee', data);
    console.log('soketeee', socketsim);
    console.log('dataaa', socket);
    // console.log('soketeee2', sockets[socket.id]);
   // console.log('soketeee3', users[to]);
   // console.log('soketeee44', socket.id);

        // Lookup the socket of the user you want to private message, and send them your message
    // console.log('message arrived to', message);
   // socketsim[users[to]].soc.emit('message_to', { msg, from: socketsim[socket.id].user });
    socket.to(to).emit('message_to', { msg, from: socketsim[socket.id].user });
  });

  socket.on('typing_private_message', (data) => {
    console.log('TYPING');
    const msg = data.message;
    const to = data.to;
    // const from = data.from;
   // const username = sockets[socket.id];
   // console.log('soketeee', data);
   // console.log('soketeee', socketsim);
   // console.log('dataaa', socket);
    // console.log('soketeee2', sockets[socket.id]);
   // console.log('soketeee3', users[to]);
   // console.log('soketeee44', socket.id);

        // Lookup the socket of the user you want to private message, and send them your message
    // console.log('message arrived to', message);
   // socketsim[users[to]].soc.emit('message_to', { msg, from: socketsim[socket.id].user });
    socket.to(to).emit('typing_message_to', { msg, from: socketsim[socket.id].user });
  });

  socket.on('message', (message, callback) => { // got message from user, send it to other users
    console.log('got message. message: ', message);
    // let's say, you want to save message into database.
    // you need to do it here, on message receive.
    // but if saving message to DB fails, you can callback with an error from the db.
    // understand?
    // yes
    // JUST AN EXAMPLE CODE, FOR DEMO PURPOSES ONLY ok
    // mongo.save(message, (err) => {
      // callback({ error: err });
    // });

    setTimeout(() => {
      callback({ error: null, data: message }); // to make server send an error assign false to eeror or string
    }, 3000); // Run callback after 3 seconds

    socket.broadcast.emit('message', message);
  });

  socket.on('user_coords', (location) => {
    console.log('user_coords.');
    coords.push(location);
    io.sockets.emit('publish_coords', { coords });
  });

  socket.on('disconnect', () => {
    console.log('someone disconnected.');
    io.sockets.emit('user_disconnected', { disconnected: true, id: socket.id });
  });
});

<commit_msg>new-file-app.json<commit_after>import thunk from 'redux-thunk';
import reducers from './reducers';

// import { composeWithDevTools } from 'remote-redux-devtools';
// mport createLogger from 'redux-logger';

import routes from './src/routes';

// const logger = createLogger();

// const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export const store = createStore(reducers,
    applyMiddleware(thunk)
  );

ReactDom.render(
  <Provider store={store}>
    <Router history={browserHistory} routes={routes} />
  </Provider>, document.querySelector('.app')
);
<|endoftext|>


<commit_before>'use strict';

var test = require('tap').test;
var streamBuffers = require("stream-buffers");
var UntilStream = require('../');

test("read until pattern", function (t) {
  t.plan(2);
  var us = new UntilStream({ pattern: ' World'});
  us.on('finish', function () {
    sourceStream.destroy();
  });

  var sourceStream = new streamBuffers.ReadableStreamBuffer({
    frequency: 0,
    chunkSize: 1000
  });
  sourceStream.put("Hello World!");

  sourceStream.pipe(us);

  us.once('readable', function() {
    var data = us.read();
    t.equal(data.toString(), 'Hello');
    data = us.read();
    t.equal(data.toString(), ' World!');
    t.end();
  });
});

test("pipe until pattern", function (t) {
  t.plan(2);
  var us = new UntilStream({ pattern: ' World'});
  us.on('finish', function () {
    sourceStream.destroy();
  });

  var sourceStream = new streamBuffers.ReadableStreamBuffer({
    frequency: 0,
    chunkSize: 1000
  });
  sourceStream.put("Hello World!");

  var writableStream = new streamBuffers.WritableStreamBuffer({
    initialSize: 100
  });

  writableStream.on('close', function () {
    var str = writableStream.getContentsAsString('utf8');
    t.equal(str, 'Hello');
    var data = us.read();
    t.equal(data.toString(), ' World!');
    t.end();
  });

  sourceStream.pipe(us).pipe(writableStream);
});

test("pipe until pattern - pattern straddles two chunks", function (t) {
  t.plan(2);
  var us = new UntilStream({ pattern: ' World'});
  us.on('finish', function () {
    sourceStream.destroy();
  });

  var sourceStream = new streamBuffers.ReadableStreamBuffer({
    frequency: 0,
    chunkSize: 1000
  });
  sourceStream.put("Hello World!");

  var writableStream = new streamBuffers.WritableStreamBuffer({
    initialSize: 100
  });

  writableStream.on('close', function () {
    var str = writableStream.getContentsAsString('utf8');
    t.equal(str, 'Hello');
    var data = us.read();
    t.equal(data.toString(), ' World!');
    t.end();
  });

  sourceStream.pipe(us).pipe(writableStream, { chunkSize: 8 });
});

test("pipe until pattern - first chunk ends with potential pattern", function (t) {
  t.plan(2);
  var us = new UntilStream({ pattern: ' World'});
  us.on('finish', function () {
    sourceStream.destroy();
  });

  var sourceStream = new streamBuffers.ReadableStreamBuffer({
    frequency: 0,
    chunkSize: 1000
  });
  sourceStream.put("Hello Wordy World!");

  var writableStream = new streamBuffers.WritableStreamBuffer({
    initialSize: 100
  });

  writableStream.on('close', function () {
    var str = writableStream.getContentsAsString('utf8');
    t.equal(str, 'Hello Wordy');
    var data = us.read();
    t.equal(data.toString(), ' World!');
    t.end();
  });

  sourceStream.pipe(us).pipe(writableStream, { chunkSize: 8 });
});
<commit_msg>Better pipe until test<commit_after>'use strict';

var test = require('tap').test;
var streamBuffers = require("stream-buffers");
var UntilStream = require('../');

test("read until pattern", function (t) {
  t.plan(2);
  var us = new UntilStream({ pattern: ' World'});
  us.on('finish', function () {
    sourceStream.destroy();
  });

  var sourceStream = new streamBuffers.ReadableStreamBuffer({
    frequency: 0,
    chunkSize: 1000
  });
  sourceStream.put("Hello World!");

  sourceStream.pipe(us);

  us.once('readable', function() {
    var data = us.read();
    t.equal(data.toString(), 'Hello');
    data = us.read();
    t.equal(data.toString(), ' World!');
    t.end();
  });
});

test("pipe until pattern", function (t) {
  t.plan(2);
  var us = new UntilStream({ pattern: 'jumps'});
  us.on('finish', function () {
    sourceStream.destroy();
  });

  var sourceStream = new streamBuffers.ReadableStreamBuffer({ chunkSize: 8 });
  sourceStream.put("The quick brown fox jumps over the lazy dog");

  var writableStream = new streamBuffers.WritableStreamBuffer({
    initialSize: 100
  });

  writableStream.on('close', function () {
    var str = writableStream.getContentsAsString('utf8');
    t.equal(str, 'The quick brown fox ');
    var data = us.read();
    t.equal(data.toString().indexOf('jumps'), 0);
    t.end();
  });

  sourceStream.pipe(us).pipe(writableStream);
});

test("pipe until pattern - pattern straddles two chunks", function (t) {
  t.plan(2);
  var us = new UntilStream({ pattern: ' World'});
  us.on('finish', function () {
    sourceStream.destroy();
  });

  var sourceStream = new streamBuffers.ReadableStreamBuffer({
    frequency: 0,
    chunkSize: 1000
  });
  sourceStream.put("Hello World!");

  var writableStream = new streamBuffers.WritableStreamBuffer({
    initialSize: 100
  });

  writableStream.once('close', function () {
    var str = writableStream.getContentsAsString('utf8');
    t.equal(str, 'Hello');
    var data = us.read();
    t.equal(data.toString(), ' World!');
    t.end();
  });

  sourceStream.pipe(us).pipe(writableStream, { chunkSize: 8 });
});

test("pipe until pattern - first chunk ends with potential pattern", function (t) {
  t.plan(2);
  var us = new UntilStream({ pattern: ' World'});
  us.on('finish', function () {
    sourceStream.destroy();
  });

  var sourceStream = new streamBuffers.ReadableStreamBuffer({
    frequency: 0,
    chunkSize: 1000
  });
  sourceStream.put("Hello Wordy World!");

  var writableStream = new streamBuffers.WritableStreamBuffer({
    initialSize: 100
  });

  writableStream.on('close', function () {
    var str = writableStream.getContentsAsString('utf8');
    t.equal(str, 'Hello Wordy');
    var data = us.read();
    t.equal(data.toString(), ' World!');
    t.end();
  });

  sourceStream.pipe(us).pipe(writableStream, { chunkSize: 8 });
});
<|endoftext|>


<commit_before>/*jslint node: true */
"use strict";

var _ = require('underscore');
var Promise = require('bluebird');

var eventTree = function () {
    return {
        hash: {}
        , funcs: []
        , onces: []
        , promises: []
    };
};

var addCallback = function (once, route, tree, cb) {
    var head = _.head(route);
    if (!tree.hash.hasOwnProperty(head)) {
        tree.hash[head] = eventTree();
    }

    if (route.length > 1) {
        return addCallback(once, _.rest(route), tree.hash[head], cb);
    }
    else if (route.length === 1) {
        if (once) {
            tree.hash[head].onces.push(cb);
        }
        else {
            if (cb.length === 2) {
                tree.hash[head].promises.push(Promise.promisify(cb));
            }
            else {
                tree.hash[head].funcs.push(cb);
            }
        }
    }
};

var promisifyArray = function (arr) {
    return _.map(arr, function (f) {
        return Promise.promisify(f);
    });
};

var any = function (arr) {
    return _.any(arr);
};

var execTree = function (tree, msg) {
    if (!tree || (tree.funcs.length === 0
                  && tree.onces.length === 0
                  && tree.promises.length === 0)) {
        return Promise.resolve(false);
    }

    return Promise.all(_.map(tree.promises, function (p) {
        return p(msg);
    }))
        .then(function () {
            _.each(tree.funcs, function (cb) {
                cb(msg);
            });
            var onces = tree.onces;
            tree.onces = [];
            _.each(onces, function (cb) {
                cb(msg);
            });
            return true;
        });
};

var applySubTrees = function (tree, method) {
    return Promise.map(_.pairs(tree.hash)
                       , function (kv) {
                           if (kv[0] === '**') {
                               return false;
                           }
                           else {
                               return method(kv[1]);
                           }
                       }, {concurrency: 1});
};

var joinTwoExecutions = function (left, right) {
    return Promise.join(left, right, function (l, r) {
        return l || r;
    });
};

var joinThreeExecutions = function (left, mid, right) {
    return Promise.join(left, mid, right, function (l, m, r) {
        return l || m || r;
    });
};

var execAll = function (tree, msg) {
    var subTreeExecution = applySubTrees(tree, function (subtree) {
        return execAll(subtree, msg);
    });
    return joinTwoExecutions(execTree(tree, msg)
                            , subTreeExecution);
};

var execMatch = function (target, tree, msg) {
    if (!tree) {
        return Promise.resolve(false);
    }
    var targetTree = tree.hash.hasOwnProperty(target) && tree.hash[target];
    if (!targetTree) {
        return Promise.resolve(false);
    }
    var doubleStarTree = targetTree.hash['**'];
    return joinTwoExecutions(execTree(targetTree, msg)
                            , execTree(doubleStarTree, msg));
};

var anyExecutions = function (executions) {
    return _.any(executions);
};

var noExecution = function () {
    return Promise.resolve(false);
};

var execCallbacks = function (route, tree, msg) {
    if (!tree) {
        return noExecution();
    }
    var head = _.head(route);
    if (head === '**') {
        return execAll(tree, msg);
    }
    else if (route.length > 1) {
        var rest = _.rest(route);
        if (head === '*') {
            return applySubTrees(tree, function (subtree) {
                return execCallbacks(rest, subtree, msg);
            })
                .then(anyExecutions);
        }
        else {
            var matchTree = tree.hash.hasOwnProperty(head) && tree.hash[head];
            return Promise.join(execTree(tree.hash['*'] && tree.hash['*'].hash['**'], msg)
                               , execTree(matchTree && matchTree.hash['**'], msg)
                               , execCallbacks(rest, tree.hash['*'], msg)
                               , execCallbacks(rest, matchTree, msg), function () {
                                   return _.any(arguments);
                               });
        }
    }
    else if (route.length === 1) {
        if (head === '*') {
            return applySubTrees(tree, function (subtree) {
                return execTree(subtree, msg);
            })
                .then(anyExecutions);
        }
        else {
            return joinTwoExecutions(execMatch('*', tree, msg)
                                     , execMatch(head, tree, msg));
        }
    }
    else {
        return noExecution();
    }
};

var filterFuncs = function (funcs, f) {
    if (f) {
        return _.without(funcs, f);
    }
    else {
        return [];
    }
};

var emptyTree = function (tree) {
    return tree.funcs.length === 0
        && tree.onces.length === 0
        && _.isEmpty(tree.hash);
};

var deleteIfEmpty = function (target, hash) {
    if (emptyTree(hash[target])) {
        delete hash[target];
    }
};

var removeFunc = function (tree, f) {
    tree.funcs = filterFuncs(tree.funcs, f);
    tree.onces = filterFuncs(tree.onces, f);
};

var removeCallback = function (route, tree, f) {
    var head = _.head(route);
    if (route.length > 1) {
        var rest = _.rest(route);
        if (head === '*') {
            return _.each(tree.hash, function (subtree, subhead) {
                if (subhead !== '**') {
                    removeCallback(rest, subtree, f);
                    deleteIfEmpty(subhead, tree.hash);
                }
            });
        }
        else if (tree.hash.hasOwnProperty(head)) {
            removeCallback(_.rest(route), tree.hash[head], f);
            deleteIfEmpty(head, tree.hash);
        }
    }
    else if (route.length === 1) {
        if (head === '**')  {
            removeFunc(tree, f);
            _.each(tree.hash, function (subtree, subhead) {
                removeCallback(route, subtree, f);
                deleteIfEmpty(subhead, tree.hash);
            });
        }
        if (head === '*') {
            _.each(tree.hash, function (subtree, subhead) {
                removeFunc(subtree, f);
                deleteIfEmpty(subhead, tree.hash);
            });
        }
        else if (tree.hash.hasOwnProperty(head)) {
            removeFunc(tree.hash[head], f);
            deleteIfEmpty(head, tree.hash);
        }
    }
};

var EventEmitter = function () {
    this._eventTree = eventTree();
};

_.extend(EventEmitter.prototype, {
    on: function (route, cb) {
        return addCallback(false, route, this._eventTree, cb);
    }
    , emit: function (route, msg) {
        var _this = this;
        return execTree(_this._eventTree.hash['**'], msg)
        .then(function (l) {
            return execCallbacks(route, _this._eventTree, msg)
            .then(function (r) {
                return l || r;
            });
        });
    }
    , removeListener: function (route, f) {
        removeCallback(route, this._eventTree, f);
    }
    , once: function (route, cb) {
        return addCallback(true, route, this._eventTree, cb);
    }
    , removeAllListeners: function (route) {
        if (route[0] === '**') {
            this._eventTree = eventTree();
        }
        else {
            removeCallback(route, this._eventTree);
        }
    }
});

module.exports = {
    EventEmitter: EventEmitter
};
<commit_msg>Ensure calling next level ** when matching *<commit_after>/*jslint node: true */
"use strict";

var _ = require('underscore');
var Promise = require('bluebird');

var eventTree = function () {
    return {
        hash: {}
        , funcs: []
        , onces: []
        , promises: []
    };
};

var addCallback = function (once, route, tree, cb) {
    var head = _.head(route);
    if (!tree.hash.hasOwnProperty(head)) {
        tree.hash[head] = eventTree();
    }

    if (route.length > 1) {
        return addCallback(once, _.rest(route), tree.hash[head], cb);
    }
    else if (route.length === 1) {
        if (once) {
            tree.hash[head].onces.push(cb);
        }
        else {
            if (cb.length === 2) {
                tree.hash[head].promises.push(Promise.promisify(cb));
            }
            else {
                tree.hash[head].funcs.push(cb);
            }
        }
    }
};

var promisifyArray = function (arr) {
    return _.map(arr, function (f) {
        return Promise.promisify(f);
    });
};

var any = function (arr) {
    return _.any(arr);
};

var execTree = function (tree, msg) {
    if (!tree || (tree.funcs.length === 0
                  && tree.onces.length === 0
                  && tree.promises.length === 0)) {
        return Promise.resolve(false);
    }

    return Promise.all(_.map(tree.promises, function (p) {
        return p(msg);
    }))
        .then(function () {
            _.each(tree.funcs, function (cb) {
                cb(msg);
            });
            var onces = tree.onces;
            tree.onces = [];
            _.each(onces, function (cb) {
                cb(msg);
            });
            return true;
        });
};

var applySubTrees = function (tree, method) {
    return Promise.map(_.pairs(tree.hash)
                       , function (kv) {
                           if (kv[0] === '**') {
                               return false;
                           }
                           else {
                               return method(kv[1]);
                           }
                       }, {concurrency: 1});
};

var joinTwoExecutions = function (left, right) {
    return Promise.join(left, right, function (l, r) {
        return l || r;
    });
};

var joinThreeExecutions = function (left, mid, right) {
    return Promise.join(left, mid, right, function (l, m, r) {
        return l || m || r;
    });
};

var execAll = function (tree, msg) {
    var subTreeExecution = applySubTrees(tree, function (subtree) {
        return execAll(subtree, msg);
    });
    return joinTwoExecutions(execTree(tree, msg)
                            , subTreeExecution);
};

var execMatch = function (target, tree, msg) {
    if (!tree) {
        return Promise.resolve(false);
    }
    var targetTree = tree.hash.hasOwnProperty(target) && tree.hash[target];
    if (!targetTree) {
        return Promise.resolve(false);
    }
    var doubleStarTree = targetTree.hash['**'];
    return joinTwoExecutions(execTree(targetTree, msg)
                            , execTree(doubleStarTree, msg));
};

var anyExecutions = function (executions) {
    return _.any(executions);
};

var noExecution = function () {
    return Promise.resolve(false);
};

var execCallbacks = function (route, tree, msg) {
    if (!tree) {
        return noExecution();
    }
    var head = _.head(route);
    if (head === '**') {
        return execAll(tree, msg);
    }
    else if (route.length > 1) {
        var rest = _.rest(route);
        if (head === '*') {
            return applySubTrees(tree, function (subtree) {
                return Promise.join(execTree(subtree.hash['**'], msg)
                            , execCallbacks(rest, subtree, msg)
                                   , function (l, r) {
                                       return l || r;
                                   });
            });
        }
        else {
            var matchTree = tree.hash.hasOwnProperty(head) && tree.hash[head];
            return Promise.join(execTree(tree.hash['*'] && tree.hash['*'].hash['**'], msg)
                               , execTree(matchTree && matchTree.hash['**'], msg)
                               , execCallbacks(rest, tree.hash['*'], msg)
                               , execCallbacks(rest, matchTree, msg), function () {
                                   return _.any(arguments);
                               });
        }
    }
    else if (route.length === 1) {
        if (head === '*') {
            return applySubTrees(tree, function (subtree) {
                return execTree(subtree, msg);
            })
                .then(anyExecutions);
        }
        else {
            return joinTwoExecutions(execMatch('*', tree, msg)
                                     , execMatch(head, tree, msg));
        }
    }
    else {
        return noExecution();
    }
};

var filterFuncs = function (funcs, f) {
    if (f) {
        return _.without(funcs, f);
    }
    else {
        return [];
    }
};

var emptyTree = function (tree) {
    return tree.funcs.length === 0
        && tree.onces.length === 0
        && _.isEmpty(tree.hash);
};

var deleteIfEmpty = function (target, hash) {
    if (emptyTree(hash[target])) {
        delete hash[target];
    }
};

var removeFunc = function (tree, f) {
    tree.funcs = filterFuncs(tree.funcs, f);
    tree.onces = filterFuncs(tree.onces, f);
};

var removeCallback = function (route, tree, f) {
    var head = _.head(route);
    if (route.length > 1) {
        var rest = _.rest(route);
        if (head === '*') {
            return _.each(tree.hash, function (subtree, subhead) {
                if (subhead !== '**') {
                    removeCallback(rest, subtree, f);
                    deleteIfEmpty(subhead, tree.hash);
                }
            });
        }
        else if (tree.hash.hasOwnProperty(head)) {
            removeCallback(_.rest(route), tree.hash[head], f);
            deleteIfEmpty(head, tree.hash);
        }
    }
    else if (route.length === 1) {
        if (head === '**')  {
            removeFunc(tree, f);
            _.each(tree.hash, function (subtree, subhead) {
                removeCallback(route, subtree, f);
                deleteIfEmpty(subhead, tree.hash);
            });
        }
        if (head === '*') {
            _.each(tree.hash, function (subtree, subhead) {
                removeFunc(subtree, f);
                deleteIfEmpty(subhead, tree.hash);
            });
        }
        else if (tree.hash.hasOwnProperty(head)) {
            removeFunc(tree.hash[head], f);
            deleteIfEmpty(head, tree.hash);
        }
    }
};

var EventEmitter = function () {
    this._eventTree = eventTree();
};

_.extend(EventEmitter.prototype, {
    on: function (route, cb) {
        return addCallback(false, route, this._eventTree, cb);
    }
    , emit: function (route, msg) {
        var _this = this;
        return execTree(_this._eventTree.hash['**'], msg)
        .then(function (l) {
            return execCallbacks(route, _this._eventTree, msg)
            .then(function (r) {
                return l || r;
            });
        });
    }
    , removeListener: function (route, f) {
        removeCallback(route, this._eventTree, f);
    }
    , once: function (route, cb) {
        return addCallback(true, route, this._eventTree, cb);
    }
    , removeAllListeners: function (route) {
        if (route[0] === '**') {
            this._eventTree = eventTree();
        }
        else {
            removeCallback(route, this._eventTree);
        }
    }
});

module.exports = {
    EventEmitter: EventEmitter
};
<|endoftext|>