<commit_before>/**
 * Patterns registry - Central registry and scan logic for patterns
 *
 * Copyright 2012-2013 Simplon B.V.
 * Copyright 2012-2013 Florian Friesdorf
 * Copyright 2013 Marko Durkovic
 * Copyright 2013 Rok Garbas
 */

/*
 * changes to previous patterns.register/scan mechanism
 * - if you want initialised class, do it in init
 * - init returns set of elements actually initialised
 * - handle once within init
 * - no turnstile anymore
 * - set pattern.jquery_plugin if you want it
 */
define([
    "jquery",
    "pat-logger",
    "pat-utils",
    // below here modules that are only loaded
    "pat-compat",
    "pat-jquery-ext"
], function($, logger, utils) {
    var log = logger.getLogger("registry"),
        jquery_plugin = utils.jquery_plugin;

    var disable_re = /patterns-disable=([^&]+)/g,
        dont_catch_re = /patterns-dont-catch/g,
        dont_catch = false,
        disabled = {}, match;

    while ((match=disable_re.exec(window.location.search)) !== null) {
        disabled[match[1]] = true;
        log.info('Pattern disabled via url config:', match[1]);
    }

    while ((match=dont_catch_re.exec(window.location.search)) !== null) {
        dont_catch = true;
        log.info('I will not catch init exceptions');
    }

    var registry = {
        patterns: {},
        // as long as the registry is not initialized, pattern
        // registration just registers a pattern. Once init is called,
        // the DOM is scanned. After that registering a new pattern
        // results in rescanning the DOM only for this pattern.
        initialized: false,
        init: function registry_init() {
            $(document).ready(function() {
                log.info('loaded: ' + Object.keys(registry.patterns).sort().join(', '));
                registry.scan(document.body);
                registry.initialized = true;
                log.info('finished initial scan.');
            });
        },

        // FIXME: from mockup
        getOptions: function($el, patternName, options) {
            options = options || {};
            // get options from parent element first, stop if element tag name is 'body'
            if ($el.length !== 0 && !$.nodeName($el[0], 'body')) {
                options = registry.getOptions($el.parent(), patternName, options);
            }
            // collect all options from element
            var elOptions = {};
            if ($el.length !== 0) {
                elOptions = $el.data('pat-' + patternName);
                if (elOptions) {
                    // parse options if string
                    if (typeof(elOptions) === 'string') {
                        var tmpOptions = {};
                        $.each(elOptions.split(';'), function(i, item) {
                            item = item.split(':');
                            item.reverse();
                            var key = item.pop();
                            key = key.replace(/^\s+|\s+$/g, '');  // trim
                            item.reverse();
                            var value = item.join(':');
                            value = value.replace(/^\s+|\s+$/g, '');  // trim
                            tmpOptions[key] = value;
                        });
                        elOptions = tmpOptions;
                    }
                }
            }
            return $.extend(true, {}, options, elOptions);
        },

        isMockupPattern: function(pattern) {
            if (typeof pattern.prototype !== "undefined") {
                return pattern.prototype.is_mockup_pattern;
            } else {
                return false;
            }
        },

        initPattern: function registry_initPattern($el, pattern, name, trigger) {
            var plog = logger.getLogger("pat." + name);
            plog.debug("Initialising:", $el);
            if (pattern.init) {
                try {
                    pattern.init($el, null, trigger);
                } catch (e) {
                    if (dont_catch) { throw(e); }
                    plog.error("Caught error:", e);
                }
                plog.debug("done.");
            }
        },

        scan: function registry_scan(content, patterns, trigger) {
            var $content = $(content), all = [], allsel, $match;

            // If no list of patterns was specified, we scan for all patterns
            patterns = patterns || Object.keys(registry.patterns);

            // selector for all patterns
            patterns.forEach(function registry_scan_loop(name) {
                if (disabled[name]) {
                    log.debug('Skipping disabled pattern:', name);
                    return;
                }
                var pattern = registry.patterns[name];
                if (pattern.transform) {
                    try {
                        pattern.transform($content);
                    } catch (e) {
                        if (dont_catch) { throw(e); }
                        log.error("Transform error for pattern" + name, e);
                    }
                }
                if (registry.isMockupPattern(pattern)) {
                    all.push(pattern.prototype.trigger);
                } else if (pattern.trigger) {
                    all.push(pattern.trigger);
                }
            });
            // Find all elements that belong to any pattern.
            allsel = all.join(",");
            $match = $content.findInclusive(allsel);
            $match = $match.filter(function() { return $(this).parents('pre').length === 0; });
            $match = $match.filter(":not(.cant-touch-this)");

            // walk list backwards and initialize patterns inside-out.
            $match.toArray().reduceRight(function registry_pattern_init(acc, el) {
                var trigger;
                var pattern, $el = $(el);
                for (var name in registry.patterns) {
                    pattern = registry.patterns[name];
                    if (registry.isMockupPattern(pattern)) {
                        trigger = pattern.prototype.trigger;
                    } else {
                        trigger = pattern.trigger;
                    }
                    if ($el.is(trigger)) {
                        registry.initPattern($el, pattern, name, trigger);
                    }
                }
            }, null);
        },

        register: function registry_register(pattern) {
            var mockup = registry.isMockupPattern(pattern);
            var name = mockup ? pattern.prototype.name : pattern.name;
            if (!name) {
                log.warn("Pattern lacks a name:", pattern);
                return false;
            }
            if (registry.patterns[name]) {
                log.error("Already have a pattern called: " + name);
                return false;
            }
            // register pattern to be used for scanning new content
            registry.patterns[name] = pattern;

            if (mockup) {
                // automatically create jquery plugin from pattern
                if (pattern.prototype.jqueryPlugin === undefined) {
                    // FIXME: make jquery name similar to Patternslib
                    pattern.prototype.jqueryPlugin = 'pattern' + name.charAt(0).toUpperCase() + name.slice(1);
                }
                $.fn[pattern.prototype.jqueryPlugin] = function mockupJQueryPlugin(method, options) {
                    var pattern = registry.patterns[name];
                    var log = logger.getLogger("pat." + name);
                    $(this).each(function() {
                        var pat, $el = $(this);
                        if (typeof method === 'object') {
                            options = method;
                            method = undefined;
                        }
                        pat = pattern.init($el, options);
                        if (method) {
                            if (pat[method] === undefined) {
                                log.error('Method "' + method + '" does not exists.');
                                return false;
                            }
                            if (method.charAt(0) === '_') {
                                log.warn('Method "' + method + '" is private.');
                                return false;
                            }
                            pat[method].apply(pat, [options]);
                        }
                    });
                    return this;
                };
            } else {
                // register pattern as jquery plugin
                if (pattern.jquery_plugin) {
                    var pluginName = ("pat-" + name)
                            .replace(/-([a-zA-Z])/g, function(match, p1) {
                                return p1.toUpperCase();
                            });
                    $.fn[pluginName] = jquery_plugin(pattern);
                    // BBB 2012-12-10
                    $.fn[pluginName.replace(/^pat/, "pattern")] = jquery_plugin(pattern);
                }
            }
            log.debug("Registered pattern:", name, pattern);
            if (registry.initialized) {
                registry.scan(document.body, [name]);
            }
            return true;
        }
    };

    $(document).on("patterns-injected.patterns",
        function registry_onInject(ev, inject_config, inject_trigger) {
            registry.scan(ev.target, null, {type: "injection", element: inject_trigger});
            $(ev.target).trigger("patterns-injected-scanned");
        });

    return registry;
});
// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<commit_msg>The getOptions method has been moved to the mockup-core parser.<commit_after>/**
 * Patterns registry - Central registry and scan logic for patterns
 *
 * Copyright 2012-2013 Simplon B.V.
 * Copyright 2012-2013 Florian Friesdorf
 * Copyright 2013 Marko Durkovic
 * Copyright 2013 Rok Garbas
 */

/*
 * changes to previous patterns.register/scan mechanism
 * - if you want initialised class, do it in init
 * - init returns set of elements actually initialised
 * - handle once within init
 * - no turnstile anymore
 * - set pattern.jquery_plugin if you want it
 */
define([
    "jquery",
    "pat-logger",
    "pat-utils",
    // below here modules that are only loaded
    "pat-compat",
    "pat-jquery-ext"
], function($, logger, utils) {
    var log = logger.getLogger("registry"),
        jquery_plugin = utils.jquery_plugin;

    var disable_re = /patterns-disable=([^&]+)/g,
        dont_catch_re = /patterns-dont-catch/g,
        dont_catch = false,
        disabled = {}, match;

    while ((match=disable_re.exec(window.location.search)) !== null) {
        disabled[match[1]] = true;
        log.info('Pattern disabled via url config:', match[1]);
    }

    while ((match=dont_catch_re.exec(window.location.search)) !== null) {
        dont_catch = true;
        log.info('I will not catch init exceptions');
    }

    var registry = {
        patterns: {},
        // as long as the registry is not initialized, pattern
        // registration just registers a pattern. Once init is called,
        // the DOM is scanned. After that registering a new pattern
        // results in rescanning the DOM only for this pattern.
        initialized: false,
        init: function registry_init() {
            $(document).ready(function() {
                log.info('loaded: ' + Object.keys(registry.patterns).sort().join(', '));
                registry.scan(document.body);
                registry.initialized = true;
                log.info('finished initial scan.');
            });
        },

        isMockupPattern: function(pattern) {
            if (typeof pattern.prototype !== "undefined") {
                return pattern.prototype.is_mockup_pattern;
            } else {
                return false;
            }
        },

        initPattern: function registry_initPattern($el, pattern, name, trigger) {
            var plog = logger.getLogger("pat." + name);
            plog.debug("Initialising:", $el);
            if (pattern.init) {
                try {
                    pattern.init($el, null, trigger);
                } catch (e) {
                    if (dont_catch) { throw(e); }
                    plog.error("Caught error:", e);
                }
                plog.debug("done.");
            }
        },

        scan: function registry_scan(content, patterns, trigger) {
            var $content = $(content), all = [], allsel, $match;

            // If no list of patterns was specified, we scan for all patterns
            patterns = patterns || Object.keys(registry.patterns);

            // selector for all patterns
            patterns.forEach(function registry_scan_loop(name) {
                if (disabled[name]) {
                    log.debug('Skipping disabled pattern:', name);
                    return;
                }
                var pattern = registry.patterns[name];
                if (pattern.transform) {
                    try {
                        pattern.transform($content);
                    } catch (e) {
                        if (dont_catch) { throw(e); }
                        log.error("Transform error for pattern" + name, e);
                    }
                }
                if (registry.isMockupPattern(pattern)) {
                    all.push(pattern.prototype.trigger);
                } else if (pattern.trigger) {
                    all.push(pattern.trigger);
                }
            });
            // Find all elements that belong to any pattern.
            allsel = all.join(",");
            $match = $content.findInclusive(allsel);
            $match = $match.filter(function() { return $(this).parents('pre').length === 0; });
            $match = $match.filter(":not(.cant-touch-this)");

            // walk list backwards and initialize patterns inside-out.
            $match.toArray().reduceRight(function registry_pattern_init(acc, el) {
                var trigger;
                var pattern, $el = $(el);
                for (var name in registry.patterns) {
                    pattern = registry.patterns[name];
                    if (registry.isMockupPattern(pattern)) {
                        trigger = pattern.prototype.trigger;
                    } else {
                        trigger = pattern.trigger;
                    }
                    if ($el.is(trigger)) {
                        registry.initPattern($el, pattern, name, trigger);
                    }
                }
            }, null);
        },

        register: function registry_register(pattern) {
            var mockup = registry.isMockupPattern(pattern);
            var name = mockup ? pattern.prototype.name : pattern.name;
            if (!name) {
                log.warn("Pattern lacks a name:", pattern);
                return false;
            }
            if (registry.patterns[name]) {
                log.error("Already have a pattern called: " + name);
                return false;
            }
            // register pattern to be used for scanning new content
            registry.patterns[name] = pattern;

            if (mockup) {
                // automatically create jquery plugin from pattern
                if (pattern.prototype.jqueryPlugin === undefined) {
                    // FIXME: make jquery name similar to Patternslib
                    pattern.prototype.jqueryPlugin = 'pattern' + name.charAt(0).toUpperCase() + name.slice(1);
                }
                $.fn[pattern.prototype.jqueryPlugin] = function mockupJQueryPlugin(method, options) {
                    var pattern = registry.patterns[name];
                    var log = logger.getLogger("pat." + name);
                    $(this).each(function() {
                        var pat, $el = $(this);
                        if (typeof method === 'object') {
                            options = method;
                            method = undefined;
                        }
                        pat = pattern.init($el, options);
                        if (method) {
                            if (pat[method] === undefined) {
                                log.error('Method "' + method + '" does not exists.');
                                return false;
                            }
                            if (method.charAt(0) === '_') {
                                log.warn('Method "' + method + '" is private.');
                                return false;
                            }
                            pat[method].apply(pat, [options]);
                        }
                    });
                    return this;
                };
            } else {
                // register pattern as jquery plugin
                if (pattern.jquery_plugin) {
                    var pluginName = ("pat-" + name)
                            .replace(/-([a-zA-Z])/g, function(match, p1) {
                                return p1.toUpperCase();
                            });
                    $.fn[pluginName] = jquery_plugin(pattern);
                    // BBB 2012-12-10
                    $.fn[pluginName.replace(/^pat/, "pattern")] = jquery_plugin(pattern);
                }
            }
            log.debug("Registered pattern:", name, pattern);
            if (registry.initialized) {
                registry.scan(document.body, [name]);
            }
            return true;
        }
    };

    $(document).on("patterns-injected.patterns",
        function registry_onInject(ev, inject_config, inject_trigger) {
            registry.scan(ev.target, null, {type: "injection", element: inject_trigger});
            $(ev.target).trigger("patterns-injected-scanned");
        });

    return registry;
});
// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<|endoftext|>


<commit_before>var Adapter = require("socket.io-adapter");

module.exports = adapter;

function adapter(option) {
	var opt = option || {};
	var peremption = opt.peremption || 24*3600*1000;
	var length = opt.length || 100;

	function Backlog(nsp) {
		Adapter.call(this, nsp);
		this.previousMessages = {};
		var self = this;
		function cleanOldMessages() {
			var previousMessages = self.previousMessages;
			var timeLimit = (new Date()).getTime() - peremption;
			for(var room in previousMessages) {
				var messages = previousMessages[room];
				var recentMessages = [];
				var nMessages = messages.length;
				var iMin = Math.max(0, nMessages - length);
				for (var i = iMin; i < nMessages; i++) {
					var message = messages[i];
					if (message.data[1].mtime > timeLimit) recentMessages.push(message);
				};
				previousMessages[room] = recentMessages;
			}
		}
		setInterval(cleanOldMessages, peremption / 2);
	}
	require('util').inherits(Backlog, Adapter);

	Backlog.prototype.broadcast = function(packet, opts, forget) {
		var rooms = opts.rooms;
		if (rooms && !forget) {
			for (var i = 0 ; i < rooms.length; i++) {
				var room = rooms[i];
				var previousRoomMessages = this.previousMessages[room];
				if (previousRoomMessages) previousRoomMessages.push(packet);
				else this.previousMessages[room] = [packet];
			}
		}
		Adapter.prototype.broadcast.call(this, packet, opts);
	};

	Backlog.prototype.add = function(id, room, fn) {
		var previousRoomMessages = this.previousMessages[room];
		if (previousRoomMessages) {
			var joinArgs = this.nsp.connected[id].joinArgs;
			if (joinArgs) {
				delete this.nsp.connected[id].joinArgs;
				var messagesAgregate = {
					type: 2,
					data: ['message', []],
					nsp: this.nsp
				};

				for (var i = 0 ; i < previousRoomMessages.length; i++) {
					var message = previousRoomMessages[i];
					var content = message.data[1];
					if (content.mtime && content.mtime > joinArgs) {
						messagesAgregate.data[1].push(message.data[1]);
					}
				}
				this.broadcast(messagesAgregate, {rooms: [id]}, true);
			} else {
				for (var i = 0 ; i < previousRoomMessages.length; i++) {
					this.broadcast(previousRoomMessages[i], {rooms: [id]}, true);
				}
			}
		}
		Adapter.prototype.add.call(this, id, room, fn);
	};
	return Backlog;
}

<commit_msg>Do not send anything if there is no message.<commit_after>var Adapter = require("socket.io-adapter");

module.exports = adapter;

function adapter(option) {
	var opt = option || {};
	var peremption = opt.peremption || 24*3600*1000;
	var length = opt.length || 100;

	function Backlog(nsp) {
		Adapter.call(this, nsp);
		this.previousMessages = {};
		var self = this;
		function cleanOldMessages() {
			var previousMessages = self.previousMessages;
			var timeLimit = (new Date()).getTime() - peremption;
			for(var room in previousMessages) {
				var messages = previousMessages[room];
				var recentMessages = [];
				var nMessages = messages.length;
				var iMin = Math.max(0, nMessages - length);
				for (var i = iMin; i < nMessages; i++) {
					var message = messages[i];
					if (message.data[1].mtime > timeLimit) recentMessages.push(message);
				};
				previousMessages[room] = recentMessages;
			}
		}
		setInterval(cleanOldMessages, peremption / 2);
	}
	require('util').inherits(Backlog, Adapter);

	Backlog.prototype.broadcast = function(packet, opts, forget) {
		var rooms = opts.rooms;
		if (rooms && !forget) {
			for (var i = 0 ; i < rooms.length; i++) {
				var room = rooms[i];
				var previousRoomMessages = this.previousMessages[room];
				if (previousRoomMessages) previousRoomMessages.push(packet);
				else this.previousMessages[room] = [packet];
			}
		}
		Adapter.prototype.broadcast.call(this, packet, opts);
	};

	Backlog.prototype.add = function(id, room, fn) {
		var previousRoomMessages = this.previousMessages[room];
		if (previousRoomMessages) {
			var joinArgs = this.nsp.connected[id].joinArgs;
			if (joinArgs) {
				delete this.nsp.connected[id].joinArgs;
				var messagesAgregate = {
					type: 2,
					data: ['message', []],
					nsp: this.nsp
				};

				for (var i = 0 ; i < previousRoomMessages.length; i++) {
					var message = previousRoomMessages[i];
					var content = message.data[1];
					if (content.mtime && content.mtime > joinArgs) {
						messagesAgregate.data[1].push(message.data[1]);
					}
				}
				if (messagesAgregate.data[1].length) this.broadcast(messagesAgregate, {rooms: [id]}, true);
			} else {
				for (var i = 0 ; i < previousRoomMessages.length; i++) {
					this.broadcast(previousRoomMessages[i], {rooms: [id]}, true);
				}
			}
		}
		Adapter.prototype.add.call(this, id, room, fn);
	};
	return Backlog;
}

<|endoftext|>


<commit_before>var Client = require('castv2-client').Client
var DefaultMediaReceiver = require('castv2-client').DefaultMediaReceiver
var mdns = require('mdns')
var peerflix = require('peerflix')
var network = require('network-address')
var events = require('events')

module.exports = function(torrent, opts) {
  if (!opts) opts = {}

  if (!opts.type) {
    opts.type = function() {
      return 'video/mp4'
    }
  }

  var engine = peerflix(torrent, opts)
  var browser = mdns.createBrowser(mdns.tcp('googlecast'))

  browser.on('serviceUp', function(service) {
    var host = service.addresses[0]
    var client = new Client()

    engine.server.on('listening', function() {
      var addr = 'http://'+network()+':'+engine.server.address().port

      client.connect(host, function(err) {
        if (err) return engine.emit('error', err)

        engine.emit('chromecast-connected')

        client.launch(DefaultMediaReceiver, function(err, player) {
          if (err) return engine.emit('error', err)

          var media = {
            contentId: addr,
            contentType: 'video/mp4',
            streamType: 'BUFFERED', // or LIVE
            metadata: {
              type: 0,
              metadataType: 0,
              title: engine.server.index.name,
              images: []
            }
          }

          player.on('status', function(status) {
            engine.emit('chromecast-status', status)
          })

          engine.emit('chromecast-player', player)

          player.load(media, { autoplay: true }, function(err) {
            if (err) return engine.emit('error', err)
            engine.emit('chromecast-playing', engine.server.index)
          })
        })
      })
    })

    client.on('error', function(err) {
      client.close()
    })

    browser.stop()
  })

  browser.start()

  return engine
}
<commit_msg>Add exit message<commit_after>var Client = require('castv2-client').Client
var DefaultMediaReceiver = require('castv2-client').DefaultMediaReceiver
var mdns = require('mdns')
var peerflix = require('peerflix')
var network = require('network-address')
var events = require('events')

process.on('SIGINT', function() {
  // we're doing some heavy lifting so it can take some time to exit... let's
  // better output a status message so the user knows we're working on it :)
  console.log('\nPeercast is exiting...')
  process.exit()
})

module.exports = function(torrent, opts) {
  if (!opts) opts = {}

  if (!opts.type) {
    opts.type = function() {
      return 'video/mp4'
    }
  }

  var engine = peerflix(torrent, opts)
  var browser = mdns.createBrowser(mdns.tcp('googlecast'))

  browser.on('serviceUp', function(service) {
    var host = service.addresses[0]
    var client = new Client()

    engine.server.on('listening', function() {
      var addr = 'http://'+network()+':'+engine.server.address().port

      client.connect(host, function(err) {
        if (err) return engine.emit('error', err)

        engine.emit('chromecast-connected')

        client.launch(DefaultMediaReceiver, function(err, player) {
          if (err) return engine.emit('error', err)

          var media = {
            contentId: addr,
            contentType: 'video/mp4',
            streamType: 'BUFFERED', // or LIVE
            metadata: {
              type: 0,
              metadataType: 0,
              title: engine.server.index.name,
              images: []
            }
          }

          player.on('status', function(status) {
            engine.emit('chromecast-status', status)
          })

          engine.emit('chromecast-player', player)

          player.load(media, { autoplay: true }, function(err) {
            if (err) return engine.emit('error', err)
            engine.emit('chromecast-playing', engine.server.index)
          })
        })
      })
    })

    client.on('error', function(err) {
      client.close()
    })

    browser.stop()
  })

  browser.start()

  return engine
}
<|endoftext|>


<commit_before>'use strict';

var EXPRESSION_DUPLICATE_ADJACENT_LETTERS = /([^c])\1/g,
    EXPRESSION_INITIALS = /^(kn|gn|pn|ae|wr)/g,
    EXPRESSION_FINAL_MB = /(m)b$/g,
    EXPRESSION_C = /c/g,
    EXPRESSION_C_TO_X = /^ch|[^s]ch|cia/g,
    EXPRESSION_C_TO_S = /c([iey])/g,
    EXPRESSION_D_TO_J = /d(g[eiy])/g,
    EXPRESSION_D = /d/g,
    EXPRESSION_NOT_FINAL_G = /g(h[^aeiou])/g,
    /* All D's were transformed to T's, weird bug in the algorithm. */
    EXPRESSION_FINAL_GN_OR_GNED = /g(n(ed)?)$/g,
    /* Now, the spec says not to transform G to J when double G's occur. As
     * GG is already removed by duplicate adjacent letters, I'm ignoring
     * this here. */
    EXPRESSION_G_TO_J = /g([iey])/g,
    EXPRESSION_G = /g/g,
    EXPRESSION_H = /([aeiou])h([^aeiou]|$)/g,
    EXPRESSION_CK = /ck/g,
    EXPRESSION_PH = /ph/g,
    EXPRESSION_Q = /q/g,
    EXPRESSION_S = /s(h|ia|io)/g,
    EXPRESSION_T = /t(ia|io)/g,
    EXPRESSION_TH = /th/g,
    EXPRESSION_TCH = /tch/g,
    EXPRESSION_V = /v/g,
    EXPRESSION_WH = /^wh/g,
    EXPRESSION_W = /w([^aeiou]|$)/g,
    EXPRESSION_INITIAL_X = /^x/g,
    EXPRESSION_X = /x/g,
    EXPRESSION_Y = /y([^aeiou]|$)/g,
    EXPRESSION_Z = /z/,
    EXPRESSION_VOWELS = /[aeiou]/g;

function initials($0) {
    return $0.charAt(1);
}

function cToX($0) {
    return $0.replace(EXPRESSION_C, 'x');
}

function metaphone(value) {
    value = String(value)
        .toLowerCase()
        .replace(EXPRESSION_DUPLICATE_ADJACENT_LETTERS, '$1')
        .replace(EXPRESSION_INITIALS, initials)
        .replace(EXPRESSION_FINAL_MB, '$1')
        .replace(EXPRESSION_CK, 'k')
        .replace(EXPRESSION_C_TO_X, cToX)
        .replace(EXPRESSION_C_TO_S, 's$1')
        .replace(EXPRESSION_C, 'k')
        .replace(EXPRESSION_D_TO_J, 'j$1')
        .replace(EXPRESSION_D, 't')
        .replace(EXPRESSION_NOT_FINAL_G, '$1')
        .replace(EXPRESSION_FINAL_GN_OR_GNED, '$1')
        .replace(EXPRESSION_G_TO_J, 'j$1')
        .replace(EXPRESSION_G, 'k')
        .replace(EXPRESSION_H, '$1$2')
        .replace(EXPRESSION_PH, 'f')
        .replace(EXPRESSION_Q, 'k')
        .replace(EXPRESSION_S, 'x$1')
        .replace(EXPRESSION_INITIAL_X, 's')
        .replace(EXPRESSION_X, 'ks')
        .replace(EXPRESSION_T, 'x$1')
        .replace(EXPRESSION_TH, '0')
        .replace(EXPRESSION_TCH, 'ch')
        .replace(EXPRESSION_V, 'f')
        .replace(EXPRESSION_WH, 'w')
        .replace(EXPRESSION_W, '$1')
        .replace(EXPRESSION_Y, '$1')
        .replace(EXPRESSION_Z, 's');

    value = value.charAt(0) + value.slice(1).replace(EXPRESSION_VOWELS, '');

    return value.toUpperCase();
}

module.exports = metaphone;
<commit_msg>Refactor API<commit_after>'use strict';

var EXPRESSION_DUPLICATE_ADJACENT_LETTERS,
    EXPRESSION_INITIALS,
    EXPRESSION_MB_FINAL,
    EXPRESSION_C,
    EXPRESSION_TO_X,
    EXPRESSION_TO_S,
    EXPRESSION_D_TO_J,
    EXPRESSION_D,
    EXPRESSION_G_NOT_FINAL,
    EXPRESSION_GN_OR_GNED_FINAL,
    EXPRESSION_G_TO_J,
    EXPRESSION_G,
    EXPRESSION_H,
    EXPRESSION_CK,
    EXPRESSION_PH,
    EXPRESSION_Q,
    EXPRESSION_S,
    EXPRESSION_T,
    EXPRESSION_TH,
    EXPRESSION_TCH,
    EXPRESSION_V,
    EXPRESSION_WH,
    EXPRESSION_W,
    EXPRESSION_INITIAL_X,
    EXPRESSION_X,
    EXPRESSION_Y,
    EXPRESSION_Z,
    EXPRESSION_VOWELS;

/**
 * Matches duplicate characters (excluding `c`), of which
 * one should be dropped.
 */

EXPRESSION_DUPLICATE_ADJACENT_LETTERS = /([^c])\1/g;

/**
 * Matches two characters at the start of a string, of
 * which the first is silent.
 */

EXPRESSION_INITIALS = /^(kn|gn|pn|ae|wr)/g;

/**
 * Matches `mb` at the end of string, of which the `b`
 * should be dropped.
 */

EXPRESSION_MB_FINAL = /(m)b$/g;

/**
 * Matches `c`.
 */

EXPRESSION_C = /c/g;

/**
 * Matches values which should be transformed to `x`.
 */

EXPRESSION_TO_X = /^ch|[^s]ch|cia/g;

/**
 * Matches values which should be transformed to `s`.
 */

EXPRESSION_TO_S = /c([iey])/g;

/**
 * Matches values containing `d` which should be
 * transformed to `j`.
 */

EXPRESSION_D_TO_J = /d(g[eiy])/g;

/**
 * Matches `d`.
 */

EXPRESSION_D = /d/g;

/**
 * Matches values containing `gh` of which the `g` should
 * be dropped.
 */

EXPRESSION_G_NOT_FINAL = /g(h[^aeiou])/g;

/**
 * Matches final values of which the `g` should be dropped.
 *
 * Bug: All D's were transformed to T's, weird.
 */

EXPRESSION_GN_OR_GNED_FINAL = /g(n(ed)?)$/g;

/**
 * Matches values of which the `g` should be dropped.
 *
 * Bug: Now, the spec says not to transform G to J when
 * double G's occur. As GG is already removed by
 * duplicate adjacent letters, it's ignored here.
 */

EXPRESSION_G_TO_J = /g([iey])/g;

/**
 * Matches `g`.
 */

EXPRESSION_G = /g/g;

/**
 * Matches values of which the `h` should be dropped.
 */

EXPRESSION_H = /([aeiou])h([^aeiou]|$)/g;

/**
 * Matches `ck`.
 */

EXPRESSION_CK = /ck/g;

/**
 * Matches `ph`.
 */

EXPRESSION_PH = /ph/g;

/**
 * Matches `q`.
 */

EXPRESSION_Q = /q/g;

/**
 * Matches values containing `s` which should be replaced
 * with `x`.
 */

EXPRESSION_S = /s(h|ia|io)/g;

/**
 * Matches values containing `t` which should be replaced
 * with `x`.
 */

EXPRESSION_T = /t(ia|io)/g;

/**
 * Matches `th`.
 */

EXPRESSION_TH = /th/g;

/**
 * Matches `tch`.
 */

EXPRESSION_TCH = /tch/g;

/**
 * Matches `v`.
 */

EXPRESSION_V = /v/g;

/**
 * Matches initial `wh`.
 */

EXPRESSION_WH = /^wh/g;

/**
 * Matches `w`, not followed by a vowel.
 */

EXPRESSION_W = /w([^aeiou]|$)/g;

/**
 * Matches initial `x`.
 */

EXPRESSION_INITIAL_X = /^x/g;

/**
 * Matches `x`.
 */

EXPRESSION_X = /x/g;

/**
 * Matches `y`, not followed by a vowel.
 */

EXPRESSION_Y = /y([^aeiou]|$)/g;

/**
 * Matches `z`.
 */

EXPRESSION_Z = /z/;

/**
 * Matches vowels (no `y`).
 */

EXPRESSION_VOWELS = /[aeiou]/g;

/**
 * Return the character at `1`.
 */

function initials($0) {
    return $0.charAt(1);
}

/**
 * Return the value, `c`s replaced with `x`s.
 */

function cToX($0) {
    return $0.replace(EXPRESSION_C, 'x');
}

/**
 * Get the phonetics according to the original Metaphone
 * algorithm from a value.
 *
 * @param {string} value - value to detect phonetics for.
 * @return {string} phonetics.
 */

function metaphone(value) {
    value = String(value)
        .toLowerCase()
        .replace(EXPRESSION_DUPLICATE_ADJACENT_LETTERS, '$1')
        .replace(EXPRESSION_INITIALS, initials)
        .replace(EXPRESSION_MB_FINAL, '$1')
        .replace(EXPRESSION_CK, 'k')
        .replace(EXPRESSION_TO_X, cToX)
        .replace(EXPRESSION_TO_S, 's$1')
        .replace(EXPRESSION_C, 'k')
        .replace(EXPRESSION_D_TO_J, 'j$1')
        .replace(EXPRESSION_D, 't')
        .replace(EXPRESSION_G_NOT_FINAL, '$1')
        .replace(EXPRESSION_GN_OR_GNED_FINAL, '$1')
        .replace(EXPRESSION_G_TO_J, 'j$1')
        .replace(EXPRESSION_G, 'k')
        .replace(EXPRESSION_H, '$1$2')
        .replace(EXPRESSION_PH, 'f')
        .replace(EXPRESSION_Q, 'k')
        .replace(EXPRESSION_S, 'x$1')
        .replace(EXPRESSION_INITIAL_X, 's')
        .replace(EXPRESSION_X, 'ks')
        .replace(EXPRESSION_T, 'x$1')
        .replace(EXPRESSION_TH, '0')
        .replace(EXPRESSION_TCH, 'ch')
        .replace(EXPRESSION_V, 'f')
        .replace(EXPRESSION_WH, 'w')
        .replace(EXPRESSION_W, '$1')
        .replace(EXPRESSION_Y, '$1')
        .replace(EXPRESSION_Z, 's');

    value = value.charAt(0) + value.slice(1).replace(EXPRESSION_VOWELS, '');

    return value.toUpperCase();
}

/**
 * Expose `metaphone`.
 */

module.exports = metaphone;
<|endoftext|>


<commit_before>module.exports = require("./lib/pirate-speak");

var tests = [
	"Females FEMALES",
	"Semi-circle",
	"I said: \"HAHA\"",
	"Hey!!!!!I!!!!HAVE!!!!NO!!!!SPACES",
	"Hey there buddy, it's been a long time. How have you been?",
	"He, couldn't, be, stopped.",
	"I\nam\nnot\ngoing\nhome",
	"Party girls don't get hurt\nCan't feel anything, when will I learn\nI push it down, push it down.",
	"I'm the one \"for a good time call\"",
	"Swag, swag, swag, on you\nChillin' by the fire while we eatin' fondue\nI don't know about me but I know about you\nSo say hello to falsetto in three, two, swag"
];

for (var i = 0; i < tests.length; i++) {
	console.log(module.exports.translate(tests[i]));
};

fs = require("fs");

var s = fs.readFileSync("test/lyrics-tests/smooth-criminal-english.txt", "utf-8")
var t = module.exports.translate(s)
fs.writeFileSync("test/lyrics-tests/smooth-criminal-pirate.txt", t, "utf8");<commit_msg>Removing unnecessary things from index.js<commit_after>module.exports = require("./lib/pirate-speak");<|endoftext|>


<commit_before>'use strict';

import React from 'react-native';

let RCTWeChat = React.NativeModules.WeChat;

function isFunction(fn) {
	return typeof fn === 'function';
}

function safeCallback(callback) {
	return isFunction(callback) ? callback : function() {};
}

export default {
	registerApp(appid, appdesc, callback) {
		if (isFunction(appdesc)) {
			callback = appdesc;
			appdesc = null;
		}

		if (!isFunction(callback)) {
			callback = function() {};
		}

		if (!appdesc) {
			RCTWeChat.registerApp(appid, callback);
		} else {
			RCTWeChat.registerAppWithDesc(appid, appdesc, callback);
		}
	},

	isWXAppInstalled(callback) {
		RCTWeChat.isWXAppInstalled(safeCallback(callback));
	},

    getWXAppInstallUrl(callback) {
        RCTWeChat.getWXAppInstallUrl(safeCallback(callback));
    },

    isWXAppSupportApi(callback) {
        RCTWeChat.isWXAppSupportApi(safeCallback(callback));
    },

    getApiVersion(callback) {
        RCTWeChat.getApiVersion(safeCallback(callback));
    },

    openWXApp(callback) {
        RCTWeChat.openWXApp(safeCallback(callback));
    },

    sendAuthReq(scope, state, callback) {
        RCTWeChat.sendAuthReq(scope, state, safeCallback(callback));
    },

    /**
     * [sendLinkURL 向微信发送链接内容]
     * @param scene 0:聊天界面 1:朋友圈 2:收藏
     */
    sendLinkURL(options, callback) {
    	RCTWeChat.sendLinkURL(
			options.link,
		    options.tagName,
		    options.title,
		    options.desc,
		    options.thumbImage,
		    options.scene,
		    safeCallback(callback)
		);
    }

		/**
		 * [sendImage 本地图片分享]
		 * @param scene 0:聊天界面 1:朋友圈 2:收藏
		 */
		sendImage(options, callback){
				RCTWeChat.sendImage(
					options.path,
					options.tagName,
					options.title,
					options.desc,
					options.scene,
					safeCallback(callback)
				);
			}
};
<commit_msg>fix syntax bug<commit_after>'use strict';

import React from 'react-native';

let RCTWeChat = React.NativeModules.WeChat;

function isFunction(fn) {
	return typeof fn === 'function';
}

function safeCallback(callback) {
	return isFunction(callback) ? callback : function() {};
}

export default {
	registerApp(appid, appdesc, callback) {
		if (isFunction(appdesc)) {
			callback = appdesc;
			appdesc = null;
		}

		if (!isFunction(callback)) {
			callback = function() {};
		}

		if (!appdesc) {
			RCTWeChat.registerApp(appid, callback);
		} else {
			RCTWeChat.registerAppWithDesc(appid, appdesc, callback);
		}
	},

	isWXAppInstalled(callback) {
		RCTWeChat.isWXAppInstalled(safeCallback(callback));
	},

    getWXAppInstallUrl(callback) {
        RCTWeChat.getWXAppInstallUrl(safeCallback(callback));
    },

    isWXAppSupportApi(callback) {
        RCTWeChat.isWXAppSupportApi(safeCallback(callback));
    },

    getApiVersion(callback) {
        RCTWeChat.getApiVersion(safeCallback(callback));
    },

    openWXApp(callback) {
        RCTWeChat.openWXApp(safeCallback(callback));
    },

    sendAuthReq(scope, state, callback) {
        RCTWeChat.sendAuthReq(scope, state, safeCallback(callback));
    },

    /**
     * [sendLinkURL 向微信发送链接内容]
     * @param scene 0:聊天界面 1:朋友圈 2:收藏
     */
    sendLinkURL(options, callback) {
    	RCTWeChat.sendLinkURL(
			options.link,
		    options.tagName,
		    options.title,
		    options.desc,
		    options.thumbImage,
		    options.scene,
		    safeCallback(callback)
		);
	},

		/**
		 * [sendImage 本地图片分享]
		 * @param scene 0:聊天界面 1:朋友圈 2:收藏
		 */
		sendImage(options, callback){
				RCTWeChat.sendImage(
					options.path,
					options.tagName,
					options.title,
					options.desc,
					options.scene,
					safeCallback(callback)
				);
			}
};
<|endoftext|>


<commit_before>'use strict';

var scope = require('jsdom').jsdom('').parentWindow
  , primus = require.resolve('primus')
  , read = require('fs').readFileSync
  , path = require('path');

//
// The library in Primus contains additional stability fixes which makes it
// a lot more stable to run on node, which why we use that instead.
//
var library = path.join(primus, '..', 'transformers/sockjs/library.js');

scope.WebSocket = require('ws');

//
// On Node 0.12 there are some issues with eval. It somehow doesn't correctly
// introduce the SockJS global. Using script tags fully resolves this issue.
//
var script = scope.document.createElement('script');
script.text = read(library, 'utf-8');
scope.document.body.appendChild(script);
script = null;

//
// The href is `about:blank` by default. This doesn't work SockJS's same origin
// check as it cannot parse it and it start throwing errors when it attempts to
// find the host. So in order to fix this we need to force a HREF.
//
scope.location.href = 'http://localhost:8080/';
module.exports = scope.SockJS;
<commit_msg>Change jsdom.parentView to jsdom.defaultView<commit_after>'use strict';

var scope = require('jsdom').jsdom('').defaultView
  , primus = require.resolve('primus')
  , read = require('fs').readFileSync
  , path = require('path');

//
// The library in Primus contains additional stability fixes which makes it
// a lot more stable to run on node, which why we use that instead.
//
var library = path.join(primus, '..', 'transformers/sockjs/library.js');

scope.WebSocket = require('ws');

//
// On Node 0.12 there are some issues with eval. It somehow doesn't correctly
// introduce the SockJS global. Using script tags fully resolves this issue.
//
var script = scope.document.createElement('script');
script.text = read(library, 'utf-8');
scope.document.body.appendChild(script);
script = null;

//
// The href is `about:blank` by default. This doesn't work SockJS's same origin
// check as it cannot parse it and it start throwing errors when it attempts to
// find the host. So in order to fix this we need to force a HREF.
//
scope.location.href = 'http://localhost:8080/';
module.exports = scope.SockJS;
<|endoftext|>


<commit_before>#!/usr/bin/env node

var doc = [
'Analyze and debug space usage through source maps.',
'',
'Usage:',
'  source-map-explorer <script.js> [<script.js.map>]',
'  source-map-explorer [--json | --html | --tsv] <script.js> [<script.js.map>] [--replace=BEFORE --with=AFTER]... [--noroot]',
'  source-map-explorer -h | --help | --version',
'',
'If the script file has an inline source map, you may omit the map parameter.',
'',
'Options:',
'  -h --help  Show this screen.',
'  --version  Show version.',
'',
'     --json  Output JSON (on stdout) instead of generating HTML',
'             and opening the browser.',
'     --tsv   Output TSV (on stdout) instead of generating HTML',
'             and opening the browser.',
'     --html  Output HTML (on stdout) rather than opening a browser.',
'',
'   --noroot  To simplify the visualization, source-map-explorer',
'             will remove any prefix shared by all sources. If you',
'             wish to disable this behavior, set --noroot.',
'',
'  --replace=BEFORE  Apply a simple find/replace on source file',
'                    names. This can be used to fix some oddities',
'                    with paths which appear in the source map',
'                    generation process.',
'      --with=AFTER  See --replace.',
].join('\n');

var fs = require('fs'),
    path = require('path'),
    sourcemap = require('source-map'),
    convert = require('convert-source-map'),
    temp = require('temp'),
    open = require('open'),
    _ = require('underscore'),
    docopt = require('docopt').docopt;

function computeGeneratedFileSizes(mapConsumer, generatedJs) {
  var lines = generatedJs.split('\n');
  var sourceExtrema = {};  // source -> {min: num, max: num}
  var numChars = 0;
  var lastSource = null;
  for (var line = 1; line <= lines.length; line++) {
    var lineText = lines[line - 1];
    var numCols = lineText.length;
    for (var column = 0; column < numCols; column++, numChars++) {
      var pos = mapConsumer.originalPositionFor({line:line, column:column});
      var source = pos.source;
      if (source == null) {
        // Often this is from the '// #sourceMap' comment itself.
        continue;
      }

      if (source != lastSource) {
        if (!(source in sourceExtrema)) {
          sourceExtrema[source] = {min: numChars};
          lastSource = source;
        } else {
          // source-map reports odd positions for bits between files.
        }
      } else {
        sourceExtrema[source].max = numChars;
      }
    }
  }
  return _.mapObject(sourceExtrema, function(v) {
    return v.max - v.min + 1
  });
}

var SOURCE_MAP_INFO_URL = 'https://github.com/danvk/source-map-explorer/blob/master/README.md#generating-source-maps';

function loadSourceMap(jsFile, mapFile) {
  var jsData = fs.readFileSync(jsFile).toString();

  var mapConsumer;
  if (mapFile) {
    var sourcemapData = fs.readFileSync(mapFile).toString();
    mapConsumer = new sourcemap.SourceMapConsumer(sourcemapData);
  } else {
    // Try to read a source map from a 'sourceMappingURL' comment.
    var converter = convert.fromSource(jsData);
    if (!converter) {
      converter = convert.fromMapFileSource(jsData, '.');
    }
    if (!converter) {
      console.error('Unable to find a source map.');
      console.error('See ', SOURCE_MAP_INFO_URL);
      return null;
    }
    mapConsumer = new sourcemap.SourceMapConsumer(converter.toJSON());
  }

  if (!mapConsumer) {
    console.error('Unable to find a source map.');
    console.error('See ', SOURCE_MAP_INFO_URL);
    return null;
  }

  return {
    mapConsumer: mapConsumer,
    jsData: jsData
  };
}

// See http://stackoverflow.com/a/1917041/388951
function commonPathPrefix(array){
  if (array.length == 0) return '';
  var A= array.concat().sort(),
  a1= A[0].split(/(\/)/), a2= A[A.length-1].split(/(\/)/), L= a1.length, i= 0;
  while(i<L && a1[i] === a2[i]) i++;
  return a1.slice(0, i).join('');
}

// Apply a transform to the keys of an object, leaving the values unaffected.
function mapKeys(obj, fn) {
  return _.object(_.map(obj, function(v, k) { return [fn(k), v]; }));
}

function adjustSourcePaths(sizes, findRoot, finds, replaces) {
  if (findRoot) {
    var prefix = commonPathPrefix(_.keys(sizes));
    var len = prefix.length;
    if (len) {
      sizes = mapKeys(sizes, function(source) { return source.slice(len); })
    }
  }

  for (var i = 0; i < finds.length; i++) {
    var before = finds[i],
        after = replaces[i];
    sizes = mapKeys(sizes, function(source) {
      return source.replace(before, after);
    });
  }

  return sizes;
}

function validateArgs(args) {
  if (args['--replace'].length != args['--with'].length) {
    console.error('--replace flags must be paired with --with flags.');
    process.exit(1);
  }
}

// Exports are here mostly for testing.
module.exports = {
  adjustSourcePaths: adjustSourcePaths,
  mapKeys: mapKeys,
  commonPathPrefix: commonPathPrefix
};

if (require.main === module) {
var args = docopt(doc, {version: '1.1.1'});
validateArgs(args);
var data = loadSourceMap(args['<script.js>'], args['<script.js.map>']);
if (!data) {
  process.exit(1);
}
var mapConsumer = data.mapConsumer,
    jsData = data.jsData;

var sizes = computeGeneratedFileSizes(mapConsumer, jsData);

if (_.size(sizes) == 1) {
  console.error('Your source map only contains one source (',
                _.keys(sizes)[0], ')');
  console.error("This typically means that your source map doesn't map all the way back to the original sources.");
  console.error("This can happen if you use browserify+uglifyjs, for example, and don't set the --in-source-map flag to uglify.");
  console.error('See ', SOURCE_MAP_INFO_URL);
  process.exit(1);
}

sizes = adjustSourcePaths(sizes, !args['--noroot'], args['--replace'], args['--with']);

if (args['--json']) {
  console.log(JSON.stringify(sizes, null, '  '));
  process.exit(0);
}

if (args['--tsv']) {
  console.log('Source\tSize');
  _.map(sizes, function(v, k) { console.log(k+'\t'+v); })
  process.exit(0);
}

var html = fs.readFileSync(path.join(__dirname, 'tree-viz.html')).toString();

html = html.replace('INSERT TREE HERE', JSON.stringify(sizes, null, '  '))
           .replace('INSERT TITLE HERE', args['<script.js>'])

if (args['--html']) {
  console.log(html);
  process.exit(0);
}

var tempName = temp.path({suffix: '.html'});
fs.writeFileSync(tempName, html);
open(tempName);
}
<commit_msg>minor cleanup<commit_after>#!/usr/bin/env node

var doc = [
'Analyze and debug space usage through source maps.',
'',
'Usage:',
'  source-map-explorer <script.js> [<script.js.map>]',
'  source-map-explorer [--json | --html | --tsv] <script.js> [<script.js.map>] [--replace=BEFORE --with=AFTER]... [--noroot]',
'  source-map-explorer -h | --help | --version',
'',
'If the script file has an inline source map, you may omit the map parameter.',
'',
'Options:',
'  -h --help  Show this screen.',
'  --version  Show version.',
'',
'     --json  Output JSON (on stdout) instead of generating HTML',
'             and opening the browser.',
'     --tsv   Output TSV (on stdout) instead of generating HTML',
'             and opening the browser.',
'     --html  Output HTML (on stdout) rather than opening a browser.',
'',
'   --noroot  To simplify the visualization, source-map-explorer',
'             will remove any prefix shared by all sources. If you',
'             wish to disable this behavior, set --noroot.',
'',
'  --replace=BEFORE  Apply a simple find/replace on source file',
'                    names. This can be used to fix some oddities',
'                    with paths which appear in the source map',
'                    generation process.',
'      --with=AFTER  See --replace.',
].join('\n');

var fs = require('fs'),
    path = require('path'),
    sourcemap = require('source-map'),
    convert = require('convert-source-map'),
    temp = require('temp'),
    open = require('open'),
    _ = require('underscore'),
    docopt = require('docopt').docopt;

function computeGeneratedFileSizes(mapConsumer, generatedJs) {
  var lines = generatedJs.split('\n');
  var sourceExtrema = {};  // source -> {min: num, max: num}
  var numChars = 0;
  var lastSource = null;
  for (var line = 1; line <= lines.length; line++) {
    var lineText = lines[line - 1];
    var numCols = lineText.length;
    for (var column = 0; column < numCols; column++, numChars++) {
      var pos = mapConsumer.originalPositionFor({line:line, column:column});
      var source = pos.source;
      if (source == null) {
        // Often this is from the '// #sourceMap' comment itself.
        continue;
      }

      if (source != lastSource) {
        if (!(source in sourceExtrema)) {
          sourceExtrema[source] = {min: numChars};
          lastSource = source;
        } else {
          // source-map reports odd positions for bits between files.
        }
      } else {
        sourceExtrema[source].max = numChars;
      }
    }
  }
  return _.mapObject(sourceExtrema, function(v) {
    return v.max - v.min + 1
  });
}

var SOURCE_MAP_INFO_URL = 'https://github.com/danvk/source-map-explorer/blob/master/README.md#generating-source-maps';

function loadSourceMap(jsFile, mapFile) {
  var jsData = fs.readFileSync(jsFile).toString();

  var mapConsumer;
  if (mapFile) {
    var sourcemapData = fs.readFileSync(mapFile).toString();
    mapConsumer = new sourcemap.SourceMapConsumer(sourcemapData);
  } else {
    // Try to read a source map from a 'sourceMappingURL' comment.
    var converter = convert.fromSource(jsData);
    if (!converter) {
      converter = convert.fromMapFileSource(jsData, '.');
    }
    if (!converter) {
      console.error('Unable to find a source map.');
      console.error('See ', SOURCE_MAP_INFO_URL);
      return null;
    }
    mapConsumer = new sourcemap.SourceMapConsumer(converter.toJSON());
  }

  if (!mapConsumer) {
    console.error('Unable to find a source map.');
    console.error('See ', SOURCE_MAP_INFO_URL);
    return null;
  }

  return {
    mapConsumer: mapConsumer,
    jsData: jsData
  };
}

// See http://stackoverflow.com/a/1917041/388951
function commonPathPrefix(array){
  if (array.length == 0) return '';
  var A= array.concat().sort(),
  a1= A[0].split(/(\/)/), a2= A[A.length-1].split(/(\/)/), L= a1.length, i= 0;
  while(i<L && a1[i] === a2[i]) i++;
  return a1.slice(0, i).join('');
}

// Apply a transform to the keys of an object, leaving the values unaffected.
function mapKeys(obj, fn) {
  return _.object(_.map(obj, function(v, k) { return [fn(k), v]; }));
}

function adjustSourcePaths(sizes, findRoot, finds, replaces) {
  if (findRoot) {
    var prefix = commonPathPrefix(_.keys(sizes));
    var len = prefix.length;
    if (len) {
      sizes = mapKeys(sizes, function(source) { return source.slice(len); })
    }
  }

  for (var i = 0; i < finds.length; i++) {
    var before = finds[i],
        after = replaces[i];
    sizes = mapKeys(sizes, function(source) {
      return source.replace(before, after);
    });
  }

  return sizes;
}

function validateArgs(args) {
  if (args['--replace'].length != args['--with'].length) {
    console.error('--replace flags must be paired with --with flags.');
    process.exit(1);
  }
}

// Exports are here mostly for testing.
module.exports = {
  adjustSourcePaths: adjustSourcePaths,
  mapKeys: mapKeys,
  commonPathPrefix: commonPathPrefix
};

if (require.main === module) {
var args = docopt(doc, {version: '1.1.1'});
validateArgs(args);
var data = loadSourceMap(args['<script.js>'], args['<script.js.map>']);
if (!data) {
  process.exit(1);
}
var mapConsumer = data.mapConsumer,
    jsData = data.jsData;

var sizes = computeGeneratedFileSizes(mapConsumer, jsData);

if (_.size(sizes) == 1) {
  console.error('Your source map only contains one source (',
                _.keys(sizes)[0], ')');
  console.error("This typically means that your source map doesn't map all the way back to the original sources.");
  console.error("This can happen if you use browserify+uglifyjs, for example, and don't set the --in-source-map flag to uglify.");
  console.error('See ', SOURCE_MAP_INFO_URL);
  process.exit(1);
}

sizes = adjustSourcePaths(sizes, !args['--noroot'], args['--replace'], args['--with']);

if (args['--json']) {
  console.log(JSON.stringify(sizes, null, '  '));
  process.exit(0);
}

if (args['--tsv']) {
  console.log('Source\tSize');
  _.each(sizes, function(source, size) { console.log(size + '\t' + source); })
  process.exit(0);
}

var html = fs.readFileSync(path.join(__dirname, 'tree-viz.html')).toString();

html = html.replace('INSERT TREE HERE', JSON.stringify(sizes, null, '  '))
           .replace('INSERT TITLE HERE', args['<script.js>'])

if (args['--html']) {
  console.log(html);
  process.exit(0);
}

var tempName = temp.path({suffix: '.html'});
fs.writeFileSync(tempName, html);
open(tempName);
}
<|endoftext|>


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

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

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

app.get('/', function(req, res) {
  res.send('It works!');
});

app.post('/post', function(req, res) {
      var body = {
        response_type: "in_channel",
        text: req.body.text + " http://vignette4.wikia.nocookie.net/imperial-assault/images/d/d7/Imperial_Assault_Die_Face.png/revision/latest?cb=20150825022932",
        attachments: [{
          text: "You rolled a http://vignette4.wikia.nocookie.net/imperial-assault/images/d/d7/Imperial_Assault_Die_Face.png/revision/latest?cb=20150825022932"
        }]
      };

      res.send(body);
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});
<commit_msg>Multiple images<commit_after>var express = require('express');
var app = express();
var url = require('url');
var request = require('request');

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

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

app.get('/', function(req, res) {
  res.send('It works!');
});

app.post('/post', function(req, res) {
      var body = {
        response_type: "in_channel",
        text: req.body.text + " http://vignette4.wikia.nocookie.net/imperial-assault/images/d/d7/Imperial_Assault_Die_Face.png/revision/latest?cb=20150825022932  http://epilepsyu.com/epilepsyassociation/files/2016/01/FUN.gif"
      };

      res.send(body);
});

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


<commit_before>'use strict';

var path = require('path');
var util = require('util');
var gauges = require('./gauges');
var configDir = path.resolve(process.env.RSRPT_CONFIG_DIR || './');

var redis = require('redis');
var StatsD = require('statsd-client');

util.log('starting...');
util.log(`using config from ${configDir}`);

var statsConfig = require(path.join(configDir, 'statsd'));
var statsdClient = new StatsD({ host: statsConfig.host, port: statsConfig.port });

var buildTags = function(tags){
  return Object.keys(tags || {})
    .map(function(k, v){
      return `${k}=${tags[k]}`;
    }).join(',');
};

var parseStats = function(info, prefix, tags){
  return info.split('\r\n').map(function(f){
    if(!f || f.indexOf('#') > -1){
      return;
    }
    var bits = f.split(':');

    if(bits.length !== 2 || gauges[bits[0]] === undefined){
      return;
    }

    var suffix = '';
    if(tags.length > 0){
      suffix = `,${tags}`;
    }

    var pre = '';
    if(prefix && prefix.length > 0){
      pre = `${prefix}.`;
    }

    return [`${pre}${bits[0]}${suffix}`, parseInt(bits[1], 10)];
  }).filter(function(f){
    return f !== undefined && !isNaN(f[1]);
  });
};

var redisClients = require(path.join(configDir, 'redis')).map(function(c){
  var cl = redis.createClient({
    host: c.host,
    port: c.port,
    'enable_offline_queue': false
  });

  cl.on('error', function(err){
    util.log(`[${c.host}] ${err}`);
  });

  cl.on('reconnecting', function(data){
    util.log(`[${c.host}] reconnecting (delay: ${data.delay}, attempt: ${data.attempt})`);
  });

  cl.host = c.host;
  cl.tags = buildTags(c.tags);
  cl.prefix = c.prefix;

  if(c.password){
    cl.auth(c.password);
  }
  return cl;
});

redisClients.forEach(function(c){
  setInterval(function(){
    c.info(function(err, res){
      if(err){
        util.log(`[${c.host}] ${err}`);
        return;
      }

      parseStats(res, c.prefix, c.tags).forEach(function(k){
        statsdClient.gauge(k[0], k[1]);
      });
    });
  }, (statsConfig.interval || 10) * 1000);
});
<commit_msg>read config directory from command line args rather than env vars<commit_after>'use strict';

var path = require('path');
var util = require('util');
var gauges = require('./gauges');
var configDir = path.resolve(process.argv[2] || './');

var redis = require('redis');
var StatsD = require('statsd-client');

util.log('starting...');
util.log(`using config from ${configDir}`);

var statsConfig = require(path.join(configDir, 'statsd'));
var statsdClient = new StatsD({ host: statsConfig.host, port: statsConfig.port });

var buildTags = function(tags){
  return Object.keys(tags || {})
    .map(function(k, v){
      return `${k}=${tags[k]}`;
    }).join(',');
};

var parseStats = function(info, prefix, tags){
  return info.split('\r\n').map(function(f){
    if(!f || f.indexOf('#') > -1){
      return;
    }
    var bits = f.split(':');

    if(bits.length !== 2 || gauges[bits[0]] === undefined){
      return;
    }

    var suffix = '';
    if(tags.length > 0){
      suffix = `,${tags}`;
    }

    var pre = '';
    if(prefix && prefix.length > 0){
      pre = `${prefix}.`;
    }

    return [`${pre}${bits[0]}${suffix}`, parseInt(bits[1], 10)];
  }).filter(function(f){
    return f !== undefined && !isNaN(f[1]);
  });
};

var redisClients = require(path.join(configDir, 'redis')).map(function(c){
  var cl = redis.createClient({
    host: c.host,
    port: c.port,
    'enable_offline_queue': false
  });

  cl.on('error', function(err){
    util.log(`[${c.host}] ${err}`);
  });

  cl.on('reconnecting', function(data){
    util.log(`[${c.host}] reconnecting (delay: ${data.delay}, attempt: ${data.attempt})`);
  });

  cl.host = c.host;
  cl.tags = buildTags(c.tags);
  cl.prefix = c.prefix;

  if(c.password){
    cl.auth(c.password);
  }
  return cl;
});

redisClients.forEach(function(c){
  setInterval(function(){
    c.info(function(err, res){
      if(err){
        util.log(`[${c.host}] ${err}`);
        return;
      }

      parseStats(res, c.prefix, c.tags).forEach(function(k){
        statsdClient.gauge(k[0], k[1]);
      });
    });
  }, (statsConfig.interval || 10) * 1000);
});
<|endoftext|>


<commit_before>var mocha = require('mocha')
var _ = require('underscore')
var superagent = require('superagent')
var fs = require('fs')
var leftPad = require('left-pad')
var path = require('path')

module.exports = GithubReporter

function GithubReporter (runner, options) {
  var getTemplateContent = function (formatterPath, opts) {
    try {
      var content = fs.readFileSync(formatterPath).toString()
      var template = _.template(content, {variable: 'data'})
      return template(opts)
    } catch (err) {
      console.error(err)
      process.exit(1)
    }
  }

  var formatters = {
    'all-suite': function (suite, level) {
      try {
        var suiteContent = ''
        if (level === 0) {
          suiteContent += '### Report\n'
          suiteContent += '```\n'
        }

        suiteContent += leftPad(suite.title, (suite.title.length + (level * 2))) + '\n'

        _.each(suite.tests, function (test) {
          var testString = '[' + test.state + '] ' + test.title
          suiteContent += leftPad(testString, (testString.length + (level * 4))) + '\n'
        })

        _.each(suite.suites, function (innerSuite) {
          suiteContent += formatters['all-suite'](innerSuite, level + 1)
        })

        if (level === 0) {
          suiteContent += '```\n'
          suiteContent += getTemplateContent(path.join(__dirname, './templates/failed-ordered-list-with-error.template'), {
            failedTests: self.failedTests
          })
        }
        return suiteContent
      } catch (err) {
        console.error(err)
        process.exit(1)
      }
    }
  }

  var self = this
  self.passedTests = []
  self.failedTests = []
  self.config = {
    reportAlways: (process.env['REPORT_ALWAYS'] === 'true') || false,
    githubAccessToken: process.env['GITHUB_ACCESS_TOKEN'],
    githubRepoSlug: process.env['GITHUB_REPO_SLUG'],
    githubIssueAssignees: process.env['GITHUB_ISSUE_ASSIGNEES'] || '',
    reportTitle: process.env['REPORT_TITLE'],
    formatter: formatters[process.env['REPORT_FORMATTER']] || formatters['all-suite']
  }
  mocha.reporters.Base.call(this, runner)

  runner.on('start', function () {
    console.log(':: Mocha Github Reporter ::')
  })

  self.rootSuite = null
  self.suiteLevel = 0

  runner.on('suite', function (suite) {
    if (self.suiteLevel === 0) {
      self.rootSuite = suite
    }
    self.suiteLevel++
  })

  runner.on('suite end', function () {
    self.suiteLevel--
  })

  runner.on('pass', function (test) {
    self.passedTests.push({test: test})
  })

  runner.on('fail', function (test, err) {
    self.failedTests.push({test: test, error: err})
  })

  runner.on('end', function () {
    var config = self.config

    if (!_.isEmpty(options)) {
      config.githubAccessToken = config.githubAccessToken || options.token
      config.githubRepoSlug = config.githubRepoSlug || options.slug
      config.githubIssueAssignees = config.githubIssueAssignees || options.assignees

      if (!_.isEmpty(config.githubIssueAssignees)) {
        config.githubIssueAssignees = config.githubIssueAssignees.split(',')
      }

      if (!_.isEmpty(options.formatter)) {
        var formatter = formatters[options.formatter]
        if (!_.isEmpty(formatter)) {
          config.formatter = formatter
        }
      }
    }

    var missingConfigs = []

    if (_.isEmpty(config.githubAccessToken)) {
      missingConfigs.push('GITHUB_ACCESS_TOKEN env or --reporter-options token=XXXX')
    }

    if (_.isEmpty(config.githubRepoSlug)) {
      missingConfigs.push('GITHUB_REPO_SLUG env or --reporter-options slug=owner/repo')
    }

    var splittedSlug = config.githubRepoSlug.split('/')
    config.githubRepoOwner = splittedSlug[0]
    config.githubRepoName = splittedSlug[1]

    if (_.isEmpty(config.githubRepoOwner) || _.isEmpty(config.githubRepoName)) {
      missingConfigs.push('GITHUB_REPO_SLUG="owner/repo" or --reporter-options slug=owner/repo')
    }

    if (!_.isEmpty(missingConfigs)) {
      console.error('Missing Configurations. Please provide ')
      _.each(missingConfigs, function (c) {
        console.error(' ->> ' + c)
      })
      console.error()
      process.exit(1)
    }
    var opts = {
      passedTests: self.passedTests,
      failedTests: self.failedTests
    }
    var overallContent = getTemplateContent(path.join(__dirname, './templates/overall.template'), opts)
    config.reportContent = overallContent + config.formatter(self.rootSuite, 0)
  })
}

GithubReporter.prototype.done = function () {
  var self = this
  if (_.isEmpty(self.failedTests) && (self.config.reportAlways === false)) {
    console.log('Pass - ' + self.passedTests.length)
    console.log('Failure - ' + self.failedTests.length)
    console.log('Total - ' + (self.passedTests.length + self.failedTests.length))
    console.log('Skipping report, due to 0 failures. To report always, set REPORT_ALWAYS=true env.')
    console.log()
    process.exit(0)
  }
  superagent
    .post('https://api.github.com/repos/' + this.config.githubRepoOwner + '/' + this.config.githubRepoName + '/issues')
    .set('Content-Type', 'application/json')
    .set('Authorization', 'token ' + this.config.githubAccessToken)
    .set('User-Agent', 'mocha github reporter')
    .set('Accept', 'application/vnd.github.v3+json')
    .send({
      title: this.config.reportTitle,
      body: this.config.reportContent
    })
    .end(function (err, res) {
      if (err || !res || (res && !res.body)) {
        console.error('Error creating issue in the repository')
        console.error(err)
        process.exit(1)
      }

      console.log('Pass - ' + self.passedTests.length)
      console.log('Failure - ' + self.failedTests.length)
      console.log('Total - ' + (self.passedTests.length + self.failedTests.length))
      console.log()

      console.log('Report created => ' + res.body.html_url)
      console.log()

      process.exit(_.isEmpty(self.failedTests) ? 0 : 1)
    })
}
<commit_msg>Fixes spliting of repo slug<commit_after>var mocha = require('mocha')
var _ = require('underscore')
var superagent = require('superagent')
var fs = require('fs')
var leftPad = require('left-pad')
var path = require('path')

module.exports = GithubReporter

function GithubReporter (runner, options) {
  var getTemplateContent = function (formatterPath, opts) {
    try {
      var content = fs.readFileSync(formatterPath).toString()
      var template = _.template(content, {variable: 'data'})
      return template(opts)
    } catch (err) {
      console.error(err)
      process.exit(1)
    }
  }

  var formatters = {
    'all-suite': function (suite, level) {
      try {
        var suiteContent = ''
        if (level === 0) {
          suiteContent += '### Report\n'
          suiteContent += '```\n'
        }

        suiteContent += leftPad(suite.title, (suite.title.length + (level * 2))) + '\n'

        _.each(suite.tests, function (test) {
          var testString = '[' + test.state + '] ' + test.title
          suiteContent += leftPad(testString, (testString.length + (level * 4))) + '\n'
        })

        _.each(suite.suites, function (innerSuite) {
          suiteContent += formatters['all-suite'](innerSuite, level + 1)
        })

        if (level === 0) {
          suiteContent += '```\n'
          suiteContent += getTemplateContent(path.join(__dirname, './templates/failed-ordered-list-with-error.template'), {
            failedTests: self.failedTests
          })
        }
        return suiteContent
      } catch (err) {
        console.error(err)
        process.exit(1)
      }
    }
  }

  var self = this
  self.passedTests = []
  self.failedTests = []
  self.config = {
    reportAlways: (process.env['REPORT_ALWAYS'] === 'true') || false,
    githubAccessToken: process.env['GITHUB_ACCESS_TOKEN'],
    githubRepoSlug: process.env['GITHUB_REPO_SLUG'],
    githubIssueAssignees: process.env['GITHUB_ISSUE_ASSIGNEES'] || '',
    reportTitle: process.env['REPORT_TITLE'],
    formatter: formatters[process.env['REPORT_FORMATTER']] || formatters['all-suite']
  }
  mocha.reporters.Base.call(this, runner)

  runner.on('start', function () {
    console.log(':: Mocha Github Reporter ::')
  })

  self.rootSuite = null
  self.suiteLevel = 0

  runner.on('suite', function (suite) {
    if (self.suiteLevel === 0) {
      self.rootSuite = suite
    }
    self.suiteLevel++
  })

  runner.on('suite end', function () {
    self.suiteLevel--
  })

  runner.on('pass', function (test) {
    self.passedTests.push({test: test})
  })

  runner.on('fail', function (test, err) {
    self.failedTests.push({test: test, error: err})
  })

  runner.on('end', function () {
    var config = self.config

    if (!_.isEmpty(options)) {
      config.githubAccessToken = config.githubAccessToken || options.token
      config.githubRepoSlug = config.githubRepoSlug || options.slug
      config.githubIssueAssignees = config.githubIssueAssignees || options.assignees

      if (!_.isEmpty(config.githubIssueAssignees)) {
        config.githubIssueAssignees = config.githubIssueAssignees.split(',')
      }

      if (!_.isEmpty(options.formatter)) {
        var formatter = formatters[options.formatter]
        if (!_.isEmpty(formatter)) {
          config.formatter = formatter
        }
      }
    }

    var missingConfigs = []

    if (_.isEmpty(config.githubAccessToken)) {
      missingConfigs.push('GITHUB_ACCESS_TOKEN env or --reporter-options token=XXXX')
    }

    if (_.isEmpty(config.githubRepoSlug)) {
      missingConfigs.push('GITHUB_REPO_SLUG env or --reporter-options slug=owner/repo')
    } else {
      var splittedSlug = config.githubRepoSlug.split('/')
      config.githubRepoOwner = splittedSlug[0]
      config.githubRepoName = splittedSlug[1]

      if (_.isEmpty(config.githubRepoOwner) || _.isEmpty(config.githubRepoName)) {
        missingConfigs.push('GITHUB_REPO_SLUG="owner/repo" or --reporter-options slug=owner/repo')
      }
    }

    if (!_.isEmpty(missingConfigs)) {
      console.error('Missing Configurations. Please provide ')
      _.each(missingConfigs, function (c) {
        console.error(' ->> ' + c)
      })
      console.error()
      process.exit(1)
    }
    var opts = {
      passedTests: self.passedTests,
      failedTests: self.failedTests
    }
    var overallContent = getTemplateContent(path.join(__dirname, './templates/overall.template'), opts)
    config.reportContent = overallContent + config.formatter(self.rootSuite, 0)
  })
}

GithubReporter.prototype.done = function () {
  var self = this
  if (_.isEmpty(self.failedTests) && (self.config.reportAlways === false)) {
    console.log('Pass - ' + self.passedTests.length)
    console.log('Failure - ' + self.failedTests.length)
    console.log('Total - ' + (self.passedTests.length + self.failedTests.length))
    console.log('Skipping report, due to 0 failures. To report always, set REPORT_ALWAYS=true env.')
    console.log()
    process.exit(0)
  }
  superagent
    .post('https://api.github.com/repos/' + this.config.githubRepoOwner + '/' + this.config.githubRepoName + '/issues')
    .set('Content-Type', 'application/json')
    .set('Authorization', 'token ' + this.config.githubAccessToken)
    .set('User-Agent', 'mocha github reporter')
    .set('Accept', 'application/vnd.github.v3+json')
    .send({
      title: this.config.reportTitle,
      body: this.config.reportContent
    })
    .end(function (err, res) {
      if (err || !res || (res && !res.body)) {
        console.error('Error creating issue in the repository')
        console.error(err)
        process.exit(1)
      }

      console.log('Pass - ' + self.passedTests.length)
      console.log('Failure - ' + self.failedTests.length)
      console.log('Total - ' + (self.passedTests.length + self.failedTests.length))
      console.log()

      console.log('Report created => ' + res.body.html_url)
      console.log()

      process.exit(_.isEmpty(self.failedTests) ? 0 : 1)
    })
}
<|endoftext|>


<commit_before>require('module-alias/register')
const Hapi = require('hapi')
let routes = require('@route/route.js')
let preResponse = require('@middleware/pre_response.js')
const Path = require('path')
const Hoek = require('hoek')

const server = new Hapi.Server({
    connections: {
        routes: {
            files: {
                relativeTo: Path.join(__dirname, 'dist')
            }
        }
    }
})

server.connection({ port: process.env.PORT || 4000 })

server.register(require('vision'), (err) => {
    Hoek.assert(!err, err)
    server.views({
        engines: {
            njk: require('nunjucks-hapi')
        },
        relativeTo: __dirname,
        path: __dirname + '/resources/views'
        , helpersPath: __dirname + '/resources/assets'
    })
})

server.register(require("hapi-plugin-co"))

server.route(routes)

server.register( require('inert'), err => {
    if (err) console.log('Failed to load inert plugin.')
    server.route(require('@route/file.js'))
})

let bind = {
    var: 'content'
}

server.bind( bind )

server.ext('onPreResponse', preResponse)

server.state('session', {
    ttl: null,
    isSecure: false,
    isHttpOnly: true,
    encoding: 'base64json',
    clearInvalid: false,
    strictHeader: true
});

server.start(err => {
    if (err) {
        console.log(err)
    }
    console.log(`Server running at: ${server.info.uri}`);
})
<commit_msg>fix cookies<commit_after>require('module-alias/register')
const Hapi = require('hapi')
let routes = require('@route/route.js')
let preResponse = require('@middleware/pre_response.js')
const Path = require('path')
const Hoek = require('hoek')

const server = new Hapi.Server({
    connections: {
        routes: {
            files: {
                relativeTo: Path.join(__dirname, 'dist')
            }
        },
        state: {
            strictHeader: false
        }
    }
})

server.connection({ port: process.env.PORT || 4005 })

server.register(require('vision'), (err) => {
    Hoek.assert(!err, err)
    server.views({
        engines: {
            njk: require('nunjucks-hapi')
        },
        relativeTo: __dirname,
        path: __dirname + '/resources/views'
        , helpersPath: __dirname + '/resources/assets'
    })
})

server.register(require("hapi-plugin-co"))

server.route(routes)

server.register( require('inert'), err => {
    if (err) console.log('Failed to load inert plugin.')
    server.route(require('@route/file.js'))
})

let bind = {
    var: 'content'
}

server.bind( bind )

server.ext('onPreResponse', preResponse)

server.state('session', {
    ttl: null,
    isSecure: false,
    isHttpOnly: true,
    encoding: 'base64json',
    clearInvalid: false,
    strictHeader: true
});

server.start(err => {
    if (err) {
        console.log(err)
    }
    console.log(`Server running at: ${server.info.uri}`);
})
<|endoftext|>


<commit_before>'use strict';
module.exports = function (val) {
	return (Symbol && Symbol.iterator
		&& val != null && 'function' === typeof val[Symbol.iterator]);
};
<commit_msg>better check for `Symbol.iterator` support<commit_after>'use strict';
module.exports = function (val) {
	return (Symbol && 'iterator' in Symbol
		&& val != null && 'function' === typeof val[Symbol.iterator]);
};
<|endoftext|>


<commit_before>'use strict';

const https = require('https');
const pg = require('pg-promise')();

const db = pg(process.env.DATABASE_URL);

function getGistJson({gist}) {
  return new Promise(resolve => {
    https.get(`https://api.github.com/gists/${gist}`, res => {
      const body = '';

      res.on('data', chunk => body += chunk);
      res.on('end', () => resolve(JSON.parse(body)));
    }).on('error', err => {
      console.error(`Error downloading gist: ${gist}`);
      resolve(null);
    });
  });
}

db.any('SELECT * FROM pipes')
  .then(data => {
    return Promise.All(data.map(getGistJson))
      .then(x => {
        console.log(x.files);
      });
  })
  .then()
  .then(() => process.exit(0))
  .catch(err => {
    console.error('Error:', err);
    process.exit(1);
  });
<commit_msg>promises<commit_after>'use strict';

const https = require('https');
const pg = require('pg-promise')();

const db = pg(process.env.DATABASE_URL);

function getGistJson({gist}) {
  return new Promise(resolve => {
    https.get(`https://api.github.com/gists/${gist}`, res => {
      const body = '';

      res.on('data', chunk => body += chunk);
      res.on('end', () => resolve(JSON.parse(body)));
    }).on('error', err => {
      console.error(`Error downloading gist: ${gist}`);
      resolve(null);
    });
  });
}

db.any('SELECT * FROM pipes')
  .then(data => {
    return Promise.all(data.map(getGistJson))
      .then(x => {
        console.log(x.files);
      });
  })
  .then(console.log)
  .then(() => process.exit(0))
  .catch(err => {
    console.error('Error:', err);
    process.exit(1);
  });
<|endoftext|>


<commit_before>var Readable = require('stream').Readable,
  geohash = require('ngeohash'),
  pip = require('point-in-polygon'),
  turf = require('turf'),
  through2 = require('through2'),
  async = require('async');

/**
 * utilizing point-in-poly but providing support for geojson polys and holes.
 */
var inside = function (point, geopoly) {
  var inside = 0;

  if(geopoly.type !== "Polygon" && geopoly.type !== "MultiPolygon") return false;

  var shape = geopoly.type === 'Polygon' ? [geopoly.coordinates] : geopoly.coordinates;
  shape.forEach(function (polygon, ind) {
    polygon.forEach(function (ring, ind) {
      if(pip([point.longitude, point.latitude], ring)) inside++;
    });
  });
  return inside % 2;
};

/*
 * Hasher, extends Readable
 * a stream that will provide a readable list of hashes, row by row.
 *
 * Calculate geohashes of specified precision that cover the (Multi)Polygon provided
 * Note, duplicates may occur.
 */
var Hasher = function (options) {
  var defaults = {
    precision: 6,
    rowMode: false,
    geojson: [],
    splitAt: 2000
  };
  options = options || {};
  for (var attrname in defaults) {
    this[attrname] = options.hasOwnProperty(attrname) && (options[attrname] !== null && typeof options[attrname] !== 'undefined') ? options[attrname] : defaults[attrname];
  }

  this.isMulti = Array.isArray(this.geojson[0][0][0]);
  this.geojson = !this.isMulti ? [this.geojson] : this.geojson;
  this.geojson = this.geojson.map(function (el) {
    return turf.polygon(el);
  });

  Readable.call(this, {
    objectMode: this.rowMode
  });
};
require('util').inherits(Hasher, Readable);

/**
 * _read(), for Readable
 * gets your next row of hashes.
 * If not in rowMode, will push each hash to buffer
 * if there are no polygons remaining in the geojson, push null to end stream
 */
Hasher.prototype._read = function (size) {
  var self = this;
  var hashes = [];
  async.whilst(function () {
    return !hashes.length && self.geojson.length;
  }, function (callback) {
    self.getNextRow(function (err, results) {
      hashes = results || [];
      callback(err);
    });
  }, function () {
    if(!self.geojson.length && !hashes.length) return self.push(null);
    if(self.rowMode) return self.push(hashes);
    hashes.forEach(function (h) {
      self.push(h);
    });
  });
};

/**
 * getNextRow()
 * will get the next row of geohashes for the current index-0 polygon in the list.
 * only uses the current row bounds for checking pointinpoly
 * rowHash persists so that it is available on the next iteration while the poly is still the same
 */
Hasher.prototype.getNextRow = function (done) {
  var self = this;

  var makeRow = function () {

    if(!self.rowHash) {
      self.rowHash = geohash.encode(self.bounding[2], self.bounding[1], self.precision);
    }

    var rowBox = geohash.decode_bbox(self.rowHash),
      columnHash = self.rowHash,
      columnCenter = geohash.decode(columnHash),
      rowBuffer = 0.0002,
      rowHashes = [];

    var preparePoly = function (next) {
      // Detect poly length

      if(self.geojson[0].geometry.coordinates[0].length >= self.splitAt) {

        clipper = turf.polygon([[
          [ self.bounding[1] - rowBuffer, rowBox[2] + rowBuffer], // nw
          [ self.bounding[3] + rowBuffer, rowBox[2] + rowBuffer], // ne
          [ self.bounding[3] + rowBuffer, rowBox[0] - rowBuffer], // se
          [ self.bounding[1] - rowBuffer, rowBox[0] - rowBuffer], //sw
          [ self.bounding[1] - rowBuffer, rowBox[2] + rowBuffer] //nw
        ]]);

        turf.intersect(turf.featurecollection([clipper]), turf.featurecollection([self.geojson[0]]), function (err, intersection) {
          var prepare = null;
          if(intersection && intersection.features.length) {
            next(null, intersection.features[0]);
          } else {
            next(null, self.geojson[0].geometry);
          }
        });

      } else {
          next(null, self.geojson[0].geometry);
      }
    };

    preparePoly(function (err, prepared) {
      var westerly = geohash.neighbor(geohash.encode(columnCenter.latitude, self.bounding[3], self.precision), [0, 1]);
      while (columnHash != westerly) {

        if(inside(columnCenter, prepared)) rowHashes.push(columnHash);
        columnHash = geohash.neighbor(columnHash, [0, 1]);
        columnCenter = geohash.decode(columnHash);
      }

      var southNeighbour = geohash.neighbor(self.rowHash, [-1, 0]);

      // Check if the current rowHash was already the most southerly hash on the map.
      // Also check if we are at or past the bottom of the bounding box.
      if(southNeighbour === self.rowHash || rowBox[0] <= self.bounding[0]) {
        self.geojson.shift();
        self.rowHash = null;
        self.bounding = null;
      } else {
        self.rowHash = southNeighbour;
      }
      done(null, rowHashes);

    });
  };

  if(!this.bounding) {
    turf.extent(turf.featurecollection([this.geojson[0]]), function (err, extent) {
      // extent = [minX, minY, maxX, maxY], remap to match geohash lib
      self.bounding = [extent[1], extent[0], extent[3], extent[2]];
      makeRow();
    });
  } else {
    makeRow();
  }

};

/**
 * intializes the Hasher, but processes the results before returning an array.
 */
var polygonHash = module.exports = function (coords, precision, next) {
  var hasher = streamer(coords, precision, true);
  var results = [];
  hasher
    .on('end', function () {
      next(null, results);
    })
    .pipe(through2.obj(function (arr, enc, callback) {
      results = results.concat(arr);
      callback();
    }));
};

/**
 * initializes the Hasher, as a stream
 */
var streamer = module.exports.stream = function (coords, precision, rowMode) {
  return new Hasher({
    geojson: coords,
    precision: precision,
    rowMode: rowMode ? true : false
  });
};
<commit_msg>Processing last geohash in array and using pop() instead of first and shift().<commit_after>var Readable = require('stream').Readable,
  geohash = require('ngeohash'),
  pip = require('point-in-polygon'),
  turf = require('turf'),
  through2 = require('through2'),
  async = require('async');

/**
 * utilizing point-in-poly but providing support for geojson polys and holes.
 */
var inside = function (point, geopoly) {
  var inside = 0;

  if(geopoly.type !== "Polygon" && geopoly.type !== "MultiPolygon") return false;

  var shape = geopoly.type === 'Polygon' ? [geopoly.coordinates] : geopoly.coordinates;
  shape.forEach(function (polygon, ind) {
    polygon.forEach(function (ring, ind) {
      if(pip([point.longitude, point.latitude], ring)) inside++;
    });
  });
  return inside % 2;
};

/*
 * Hasher, extends Readable
 * a stream that will provide a readable list of hashes, row by row.
 *
 * Calculate geohashes of specified precision that cover the (Multi)Polygon provided
 * Note, duplicates may occur.
 */
var Hasher = function (options) {
  var defaults = {
    precision: 6,
    rowMode: false,
    geojson: [],
    splitAt: 2000
  };
  options = options || {};
  for (var attrname in defaults) {
    this[attrname] = options.hasOwnProperty(attrname) && (options[attrname] !== null && typeof options[attrname] !== 'undefined') ? options[attrname] : defaults[attrname];
  }

  this.isMulti = Array.isArray(this.geojson[0][0][0]);
  this.geojson = !this.isMulti ? [this.geojson] : this.geojson;
  this.geojson = this.geojson.map(function (el) {
    return turf.polygon(el);
  });

  Readable.call(this, {
    objectMode: this.rowMode
  });
};
require('util').inherits(Hasher, Readable);

/**
 * _read(), for Readable
 * gets your next row of hashes.
 * If not in rowMode, will push each hash to buffer
 * if there are no polygons remaining in the geojson, push null to end stream
 */
Hasher.prototype._read = function (size) {
  var self = this;
  var hashes = [];
  async.whilst(function () {
    return !hashes.length && self.geojson.length;
  }, function (callback) {
    self.getNextRow(function (err, results) {
      hashes = results || [];
      callback(err);
    });
  }, function () {
    if(!self.geojson.length && !hashes.length) return self.push(null);
    if(self.rowMode) return self.push(hashes);
    hashes.forEach(function (h) {
      self.push(h);
    });
  });
};

/**
 * getNextRow()
 * will get the next row of geohashes for the current length-1 polygon in the list.
 * only uses the current row bounds for checking pointinpoly
 * rowHash persists so that it is available on the next iteration while the poly is still the same
 */
Hasher.prototype.getNextRow = function (done) {
  var self = this,
    currentGeojson = self.geojson[self.geojson.length-1];

  var makeRow = function () {

    if(!self.rowHash) {
      self.rowHash = geohash.encode(self.bounding[2], self.bounding[1], self.precision);
    }

    var rowBox = geohash.decode_bbox(self.rowHash),
      columnHash = self.rowHash,
      columnCenter = geohash.decode(columnHash),
      rowBuffer = 0.0002,
      rowHashes = [];

    var preparePoly = function (next) {
      // Detect poly length

      if(currentGeojson.geometry.coordinates[0].length >= self.splitAt) {

        clipper = turf.polygon([[
          [ self.bounding[1] - rowBuffer, rowBox[2] + rowBuffer], // nw
          [ self.bounding[3] + rowBuffer, rowBox[2] + rowBuffer], // ne
          [ self.bounding[3] + rowBuffer, rowBox[0] - rowBuffer], // se
          [ self.bounding[1] - rowBuffer, rowBox[0] - rowBuffer], //sw
          [ self.bounding[1] - rowBuffer, rowBox[2] + rowBuffer] //nw
        ]]);

        turf.intersect(turf.featurecollection([clipper]), turf.featurecollection([currentGeojson]), function (err, intersection) {
          var prepare = null;
          if(intersection && intersection.features.length) {
            next(null, intersection.features[0]);
          } else {
            next(null, currentGeojson.geometry);
          }
        });

      } else {
          next(null, currentGeojson.geometry);
      }
    };

    preparePoly(function (err, prepared) {
      var westerly = geohash.neighbor(geohash.encode(columnCenter.latitude, self.bounding[3], self.precision), [0, 1]);
      while (columnHash != westerly) {

        if(inside(columnCenter, prepared)) rowHashes.push(columnHash);
        columnHash = geohash.neighbor(columnHash, [0, 1]);
        columnCenter = geohash.decode(columnHash);
      }

      var southNeighbour = geohash.neighbor(self.rowHash, [-1, 0]);

      // Check if the current rowHash was already the most southerly hash on the map.
      // Also check if we are at or past the bottom of the bounding box.
      if(southNeighbour === self.rowHash || rowBox[0] <= self.bounding[0]) {
        self.geojson.pop();
        self.rowHash = null;
        self.bounding = null;
      } else {
        self.rowHash = southNeighbour;
      }
      done(null, rowHashes);

    });
  };

  if(!this.bounding) {
    turf.extent(turf.featurecollection([currentGeojson]), function (err, extent) {
      // extent = [minX, minY, maxX, maxY], remap to match geohash lib
      self.bounding = [extent[1], extent[0], extent[3], extent[2]];
      makeRow();
    });
  } else {
    makeRow();
  }

};

/**
 * intializes the Hasher, but processes the results before returning an array.
 */
var polygonHash = module.exports = function (coords, precision, next) {
  var hasher = streamer(coords, precision, true);
  var results = [];
  hasher
    .on('end', function () {
      next(null, results);
    })
    .pipe(through2.obj(function (arr, enc, callback) {
      results = results.concat(arr);
      callback();
    }));
};

/**
 * initializes the Hasher, as a stream
 */
var streamer = module.exports.stream = function (coords, precision, rowMode) {
  return new Hasher({
    geojson: coords,
    precision: precision,
    rowMode: rowMode ? true : false
  });
};
<|endoftext|>


<commit_before>module.exports = {
  env: {
    browser: true,
    es6: true,
  },

  extends: 'eslint:recommended',

  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'module',
  },

  rules: {
    'no-console':  ['warn', {allow: ['info', 'warn', 'error']}],
    'no-debugger': ['warn'],

    'arrow-parens':          ['error', 'as-needed'],
    'camelcase':             ['error', {'properties': 'always'}],
    'comma-dangle':          ['error', 'always-multiline'],
    'comma-spacing':         ['error', {'before': false, 'after': true}],
    'eol-last':              ['error'],
    'eqeqeq':                ['error'],
    'indent':                ['error', 2, {SwitchCase: 1}],
    'linebreak-style':       ['error', 'unix'],
    'multiline-ternary':     ['error', 'never'],
    'no-unused-expressions': ['error'],
    'no-use-before-define':  ['error', {classes: false}],
    'quotes':                ['error', 'backtick'],
    'semi':                  ['error', 'always'],
    'space-before-blocks':   ['error', 'always'],
  },
};
<commit_msg>no space between function and paren ()<commit_after>module.exports = {
  env: {
    browser: true,
    es6: true,
  },

  extends: 'eslint:recommended',

  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'module',
  },

  rules: {
    'no-console':  ['warn', {allow: ['info', 'warn', 'error']}],
    'no-debugger': ['warn'],

    'arrow-parens':                ['error', 'as-needed'],
    'camelcase':                   ['error', {'properties': 'always'}],
    'comma-dangle':                ['error', 'always-multiline'],
    'comma-spacing':               ['error', {'before': false, 'after': true}],
    'eol-last':                    ['error'],
    'eqeqeq':                      ['error'],
    'indent':                      ['error', 2, {SwitchCase: 1}],
    'linebreak-style':             ['error', 'unix'],
    'multiline-ternary':           ['error', 'never'],
    'no-unused-expressions':       ['error'],
    'no-use-before-define':        ['error', {classes: false}],
    'quotes':                      ['error', 'backtick'],
    'semi':                        ['error', 'always'],
    'space-before-blocks':         ['error', 'always'],
    'space-before-function-paren': ['error', 'never'],
  },
};
<|endoftext|>