<commit_before>'use strict';

var minilog = require('minilog')
  , standardRequest = require('request')
  , util = require('util');

var FinalAction = require('./final_action')
  , mediaTypeRegistry = require('./media_type_registry')
  , Walker = require('./walker')
  , mediaTypes = require('./media_types');

var log = minilog('traverson');

function Builder(mediaType, startUri) {
  var adapter = this.createAdapter(mediaType);
  this.walker = new Walker(adapter);
  this.walker.startUri = startUri;
  this.walker.request = this.request = standardRequest;
  this.walker.parseJson = JSON.parse;
  this.finalAction = new FinalAction(this.walker);
}

Builder.prototype.createAdapter = function(mediaType) {
  var AdapterType = mediaTypeRegistry.get(mediaType);
  if (!AdapterType) {
    throw new Error('Unknown or unsupported media type: ' + mediaType);
  }
  log.debug('creating new ' + AdapterType.name);
  return new AdapterType(false);
};

Builder.prototype.follow = function() {
  if (arguments.length === 1 && util.isArray(arguments[0])) {
    this.walker.links = arguments[0];
  } else {
    this.walker.links = Array.prototype.slice.apply(arguments);
  }
  return this;
};

Builder.prototype.walk = Builder.prototype.follow;

Builder.prototype.withTemplateParameters = function(parameters) {
  this.walker.templateParameters = parameters;
  return this;
};

Builder.prototype.withRequestOptions = function(options) {
  this.walker.request = this.request = standardRequest.defaults(options);
  return this;
};

Builder.prototype.withRequestLibrary = function(request) {
  this.walker.request = this.request = request;
  return this;
};

Builder.prototype.parseResponseBodiesWith = function(parser) {
  this.walker.parseJson = parser;
  return this;
};

Builder.prototype.resolveRelative = function() {
  this.walker.resolveRelative = true;
  return this;
};

Builder.prototype.get = function(callback) {
  var self = this;
  this.walker.walk(function(err, nextStep, lastStep) {
    log.debug('walker.walk returned');
    if (err) {
      return callback(err, lastStep.response, lastStep.uri);
    }
    self.finalAction.get(nextStep, callback);
  });
};

/*
 * Special variant of get() that does not yield the full http response to the
 * callback but instead the already parsed JSON as an object.
 */
Builder.prototype.getResource = function(callback) {
  var self = this;
  this.walker.walk(function(err, nextStep, lastStep) {
    log.debug('walker.walk returned');
    if (err) {
      return callback(err, lastStep.response, lastStep.uri);
    }
    self.finalAction.getResource(nextStep, callback);
  });
};

/*
 * Special variant of get() that does not execute the last request but instead
 * yields the last URI to the callback.
 */

Builder.prototype.getUri = function(callback) {
  var self = this;
  this.walker.walk(function(err, nextStep, lastStep) {
    log.debug('walker.walk returned');
    if (err) {
      return callback(err, lastStep.response, lastStep.uri);
    }
    self.finalAction.getUri(nextStep, callback);
  });
};

Builder.prototype.post = function(body, callback) {
  this.finalAction.walkAndExecute(body, this.request, this.request.post,
      callback);
};

Builder.prototype.put = function(body, callback) {
  this.finalAction.walkAndExecute(body, this.request, this.request.put,
      callback);
};

Builder.prototype.patch = function(body, callback) {
  this.finalAction.walkAndExecute(body, this.request, this.request.patch,
      callback);
};

Builder.prototype.del = function(callback) {
  this.finalAction.walkAndExecute(null, this.request, this.request.del,
      callback);
};

module.exports = Builder;
<commit_msg>This gracefully handles requests with now 'follows' in them<commit_after>'use strict';

var minilog = require('minilog')
  , standardRequest = require('request')
  , util = require('util');

var FinalAction = require('./final_action')
  , mediaTypeRegistry = require('./media_type_registry')
  , Walker = require('./walker')
  , mediaTypes = require('./media_types');

var log = minilog('traverson');

function Builder(mediaType, startUri) {
  var adapter = this.createAdapter(mediaType);
  this.walker = new Walker(adapter);
  this.walker.links = [];
  this.walker.startUri = startUri;
  this.walker.request = this.request = standardRequest;
  this.walker.parseJson = JSON.parse;
  this.finalAction = new FinalAction(this.walker);
}

Builder.prototype.createAdapter = function(mediaType) {
  var AdapterType = mediaTypeRegistry.get(mediaType);
  if (!AdapterType) {
    throw new Error('Unknown or unsupported media type: ' + mediaType);
  }
  log.debug('creating new ' + AdapterType.name);
  return new AdapterType(false);
};

Builder.prototype.follow = function() {
  if (arguments.length === 1 && util.isArray(arguments[0])) {
    this.walker.links = arguments[0];
  } else {
    this.walker.links = Array.prototype.slice.apply(arguments);
  }
  return this;
};

Builder.prototype.walk = Builder.prototype.follow;

Builder.prototype.withTemplateParameters = function(parameters) {
  this.walker.templateParameters = parameters;
  return this;
};

Builder.prototype.withRequestOptions = function(options) {
  this.walker.request = this.request = standardRequest.defaults(options);
  return this;
};

Builder.prototype.withRequestLibrary = function(request) {
  this.walker.request = this.request = request;
  return this;
};

Builder.prototype.parseResponseBodiesWith = function(parser) {
  this.walker.parseJson = parser;
  return this;
};

Builder.prototype.resolveRelative = function() {
  this.walker.resolveRelative = true;
  return this;
};

Builder.prototype.get = function(callback) {
  var self = this;
  this.walker.walk(function(err, nextStep, lastStep) {
    log.debug('walker.walk returned');
    if (err) {
      return callback(err, lastStep.response, lastStep.uri);
    }
    self.finalAction.get(nextStep, callback);
  });
};

/*
 * Special variant of get() that does not yield the full http response to the
 * callback but instead the already parsed JSON as an object.
 */
Builder.prototype.getResource = function(callback) {
  var self = this;
  this.walker.walk(function(err, nextStep, lastStep) {
    log.debug('walker.walk returned');
    if (err) {
      return callback(err, lastStep.response, lastStep.uri);
    }
    self.finalAction.getResource(nextStep, callback);
  });
};

/*
 * Special variant of get() that does not execute the last request but instead
 * yields the last URI to the callback.
 */

Builder.prototype.getUri = function(callback) {
  var self = this;
  this.walker.walk(function(err, nextStep, lastStep) {
    log.debug('walker.walk returned');
    if (err) {
      return callback(err, lastStep.response, lastStep.uri);
    }
    self.finalAction.getUri(nextStep, callback);
  });
};

Builder.prototype.post = function(body, callback) {
  this.finalAction.walkAndExecute(body, this.request, this.request.post,
      callback);
};

Builder.prototype.put = function(body, callback) {
  this.finalAction.walkAndExecute(body, this.request, this.request.put,
      callback);
};

Builder.prototype.patch = function(body, callback) {
  this.finalAction.walkAndExecute(body, this.request, this.request.patch,
      callback);
};

Builder.prototype.del = function(callback) {
  this.finalAction.walkAndExecute(null, this.request, this.request.del,
      callback);
};

module.exports = Builder;
<|endoftext|>


<commit_before>/**
 * Main AngularJS Web Application
 */
var app = angular.module('CVMS', [
  'ngRoute'
]);

/**
 * Configure the Routes
 */
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    // Home
    .when("/", {templateUrl: "partials/home.html", controller: "PageCtrl"})
    // Pages
    .when("/about", {templateUrl: "partials/about.html", controller: "PageCtrl"})
    .when("/services", {templateUrl: "partials/services.html", controller: "PageCtrl"})
    .when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
    // Blog
    .when("/blog", {templateUrl: "partials/blog.html", controller: "BlogCtrl"})
    // else 404
    .otherwise("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"});
}]);

/**
 * Controls the Blog
 */
app.controller('BlogCtrl', function (/* $scope, $location, $http */) {
  console.log("Blog Controller reporting for duty.");
});

/**
 * Controls all other Pages
 */
app.controller('PageCtrl', function (/* $scope, $location, $http */) {
  console.log("Page Controller reporting for duty.");

  // Activates the Carousel
  $('.carousel').carousel({
    interval: 5000
  });

  // Activates Tooltips for Social Links
  $('.tooltip-social').tooltip({
    selector: "a[data-toggle=tooltip]"
  })
});
<commit_msg>Update main.js<commit_after>/**
 * Main AngularJS Web Application
 */
var app = angular.module('CVMS', [
  'ngRoute'
]);

/**
 * Configure the Routes
 */
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    // Home
    .when("/", {templateUrl: "partials/home.html", controller: "PageCtrl"})
    // Pages
    .when("/about", {templateUrl: "partials/about.html", controller: "PageCtrl"})
    .when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
    // Blog
    .when("/blog", {templateUrl: "partials/blog.html", controller: "BlogCtrl"})
    // else 404
    .otherwise("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"});
}]);

/**
 * Controls the Blog
 */
app.controller('BlogCtrl', function (/* $scope, $location, $http */) {
  console.log("Blog Controller reporting for duty.");
});

/**
 * Controls all other Pages
 */
app.controller('PageCtrl', function (/* $scope, $location, $http */) {
  console.log("Page Controller reporting for duty.");

  // Activates the Carousel
  $('.carousel').carousel({
    interval: 5000
  });

  // Activates Tooltips for Social Links
  $('.tooltip-social').tooltip({
    selector: "a[data-toggle=tooltip]"
  })
});
<|endoftext|>


<commit_before>
// builtin
var fs = require('fs');
var path = require('path');
var natives = process.binding('natives');

// 3rd party
var required = require('required');
var merge = require('merge');

// local
var client = require('../client');

// shims we provide by default for core modules
// any user specified shims will add to this (or override it)
var k_default_shims = {
    'events': require.resolve('events-browserify'),
    'http': require.resolve('http-browserify'),
    'child_process': require.resolve('../shims/child_process'),
    'stream': require.resolve('../shims/stream'),
};

/// @return {Boolean} true if [id] is a native module
var is_native = function(id) {
    return !!natives[id];
};

var Bundle = function(filename, opt) {
    var self = this;

    opt = opt || {};

    self._entry = filename;

    // safe to prefix using 'script/entry.base_filename.js'
    // this will prevent conflict as it is namespaced under script
    self.name = opt.name || ('script/main.' + path.basename(filename));

    self._main = opt.main || false;
    self._client = opt.client || false;

    self._externals = opt.external || [];

    // a shim is 'name' -> '/path/to/file.js'
    // merge user shims over default shims
    self._shims = merge(k_default_shims, opt.shims || {});
}

// generate the bundled string
Bundle.prototype.generate = function(cb) {
    var self = this;

    var out = '(function(require) {\n';

    self.normalize(function(err, result) {
        if (err) {
            return cb(err);
        }

        var deps = result.deps;
        var aliases = result.aliases;

        Object.keys(aliases).forEach(function(from) {
            var to = aliases[from];
            // map the new short name to an already loaded name
            out += 'require.alias(\'' + from + '\', \'' + to + '\');\n';
        });

        // fullpath -> source
        var sources = {};

        // load sources
        function load_sources(cb) {
            var paths = Object.keys(deps);
            (function next(err) {
                var path = paths.shift();
                if (!path) {
                    return cb();
                }

                fs.readFile(path, 'utf8', function(err, src) {
                    if (err) {
                        return cb(err);
                    }

                    sources[path] = src;
                    next();
                });
            })();
        }

        load_sources(function(err) {
            if (err) {
                return cb(err);
            }

            var paths = Object.keys(deps);

            paths.forEach(function(path) {
                var info = deps[path];

                var name = info.name;
                var offset = info.offset;
                var src = sources[path];

                out += 'require.define(\'' + name + '\', \'' + offset + '\', ';
                out += 'function(global, module, exports, require, process, __filename, __dirname) {\n';
                out += src;
                out += '\n});\n\n';
            });

            var entry = deps[self._entry];
            if (self._main) {
                out += 'require(\'' + entry.name + '\');\n';
            }

            // close the whole closure
            out += '})(require);\n';

            cb(null, out);
        })
    });
};

/// TODO should be recursive since having our externals contain a file
/// is the same to us as having their externals contain the file
/// need to make sure external is resolved
Bundle.prototype.external = function(filename) {
    var self = this;

    // if our externals are our filename directly, then use the external
    // TODO any externals in the chain should be allowed to stand in for an external

    var externals = self._externals;
    for (var i=0 ; i<externals.length ; ++i) {
        var external = externals[i];
        if (external._entry === filename) {
            return external;
        }
    }

    return null;
};

// flatten deps
// deps is a tree
// flatten into an object of
// {
//  filename: {
//      requires: {
//          'a': '/full/path/to/a',
//          'b': '/full/path/to/b'
//      }
// }
Bundle.prototype.flatten = function(deps) {
    var self = this;

    var flat = {};

    deps.forEach(function(dep) {
        var reqs = {};

        if (self.external(dep.filename)) {
            return
        };

        dep.deps.forEach(function(dep) {
            reqs[dep.id] = dep.filename;
        });

        // bring in all the child dependencies
        merge(flat, self.flatten(dep.deps));
        flat[dep.filename] = reqs;
    });

    return flat;
};

Bundle.prototype.resolve = function(cb) {
    var self = this;

    var filename = self._entry;

    // basepath is used to create the aliases for path lookup
    var basepath = path.dirname(filename);

    var shims = self._shims;

    required(filename, { ignoreMissing: true }, function(err, deps) {
        if (err) {
            return cb(err);
        }

        shim(deps, shims, function(err) {
            if (err) {
                return cb(err);
            }

            // should be done after shim since native modules
            // will have filename populated
            var ids = {};
            deps.reduce(function(prev, curr, idx, arr) {
                prev[curr.id] = curr.filename;
                return prev;
            }, ids);

            var flat = self.flatten(deps);

            // deps for the entry file
            flat[filename] = ids;

            cb(null, flat);
        });
    });
};

Bundle.prototype.normalize = function(cb) {
    var self = this;

    var filename = self._entry;

    // basepath is used to create the aliases for path lookup
    var basepath = path.dirname(filename);

    var shims = self._shims;

    self.resolve(function(err, flat) {
        if (err) {
            return cb(err);
        }

        var paths = Object.keys(flat);

        var registry = {};

        // exported aliases
        var aliases = {};

        // register all of the dependencies
        paths.forEach(function(file) {
            var basename = path.basename(file, '.js');
            var dirname = path.dirname(file);
            var relative = path.relative(basepath, dirname);

            var name = '/' + path.join(relative, basename);

            if (relative) {
                relative += '/';
            }

            // we will see the full path later
            // for now, we just need to do what?
            // register the entry for this pathname
            registry[file] = {
                name: name,
                offset: '/' + relative
            };
        });

        // setup aliases
        // shortname is what the file is registered as
        // in our file we have require(<id>)
        // we lookup the fullpath for that id from the registry
        // and make an alias from ./relative/id to the registered path
        paths.forEach(function(file) {
            var dirname = path.dirname(file);
            var relative = path.relative(basepath, dirname);

            // we now have a registry of all the full file paths
            // -> the registered name
            // now just make aliases for the reqs -> registered name
            var reqs = flat[file];
            Object.keys(reqs).forEach(function(id) {
                var filename = reqs[id];

                // ./ requires are trimmed aray
                if (id[0] === '.' && id[1] === '/') {
                    id = id.slice(2);
                }

                // rel is the absolute path to the require with offset applied
                var rel = '/' + id;
                if (relative) {
                    rel = '/' + relative + rel;
                }

                // TODO(shtylman) this means it was in an external
                // since we never registered the file
                // should register external files
                if (!registry[filename]) {
                    aliases[rel] = '/' + id;
                    return;
                }

                var reg_name = registry[filename].name;

                // ignore noop aliases
                if (rel === reg_name) {
                    return;
                }

                // paths with .. are always aliased
                // client does not do path operations
                if (id[0] === '.' && id[1] === '.') {
                    aliases[rel] = reg_name;
                    return;
                }

                aliases[rel] = reg_name;
            });
        });

        cb(null, {
            deps: registry,
            aliases: aliases
        });
    });
};

// return a path for package.json from given basepath
function pkg_find(basepath) {
    if (!basepath) {
        return;
    }

    var pkg_path = basepath + '/package.json';
    if (fs.existsSync(pkg_path)) {
        return pkg_path;
    }

    // up up up!
    return pkg_find(path.dirname(basepath));
}

// take a set of deps and replace with any shims
function shim(deps, shims, cb) {
    if (!deps || deps.length === 0) {
        return cb(null);
    }

    var count = 0;

    // filenames which we have already loaded package.json
    var loaded_pkgs = {};

    // loop deps
    // see if we need to keep each one
    (function next() {
        if (count >= deps.length) {
            return cb(null);
        }

        var dep = deps[count++];
        if (dep.seen) {
            return next();
        }

        // find a suitable package.json file
        // this is where we find the shims
        // once we have seen a filename, there is no need to check
        // it again
        if (dep.filename && !loaded_pkgs[dep.filename]) {
            loaded_pkgs[dep.filename] = true;
            var basepath = path.dirname(dep.filename);

            // TODO async
            var pkg_path = pkg_find(basepath);
            if (pkg_path) {
                var pkg_info = JSON.parse(fs.readFileSync(pkg_path, 'utf8'));
                var base = path.dirname(pkg_path);
                for (var key in pkg_info.shims) {
                    var shim_path = path.join(base, pkg_info.shims[key]);
                    if (key[0] === '.') {
                        key = path.normalize(path.join(base, key));
                    }
                    shims[key] = shim_path;
                }
            }
        }

        dep.seen = true;

        // this will be called at the final dep
        var shim_filename = shims[dep.id];

        // if shim was loaded by id, then don't override
        if (!shim_filename && dep.filename) {
            shim_filename = shims[dep.filename];
        }

        if (shim_filename) {
            required(shim_filename, function(err, shim_deps) {
                if (err) {
                    return cb(err);
                }

                dep.filename = shim_filename;
                dep.native = is_native(dep.id);

                // need to shim any deps in the loaded shim
                // a shim could require modules which need to be shimmed
                shim(shim_deps, shims, function(err) {
                    dep.deps = shim_deps;
                    next();
                });
            });

            return;
        }

        shim(dep.deps, shims, function(err) {
            if (err) {
                return cb(err);
            }

            delete dep.seen;
            next();
        });
    })();
};

module.exports.Bundle = Bundle;

// .file(/path/to/local/file, opt);
module.exports.file = function(filename, opt) {
    return new Bundle(filename, opt);
};

// .module('some-module', opt);
module.exports.module = function(name, opt) {

    var filename = require.resolve(name);

    // the entry registered name will be the module name
    opt = merge({ name: name }, opt || {});

    return new Bundle(filename, opt);
};

<commit_msg>use request name if provided<commit_after>
// builtin
var fs = require('fs');
var path = require('path');
var natives = process.binding('natives');

// 3rd party
var required = require('required');
var merge = require('merge');

// local
var client = require('../client');

// shims we provide by default for core modules
// any user specified shims will add to this (or override it)
var k_default_shims = {
    'events': require.resolve('events-browserify'),
    'http': require.resolve('http-browserify'),
    'child_process': require.resolve('../shims/child_process'),
    'stream': require.resolve('../shims/stream'),
};

/// @return {Boolean} true if [id] is a native module
var is_native = function(id) {
    return !!natives[id];
};

var Bundle = function(filename, opt) {
    var self = this;

    opt = opt || {};

    self._entry = filename;

    // safe to prefix using 'script/entry.base_filename.js'
    // this will prevent conflict as it is namespaced under script
    self.name = opt.name || ('script/main.' + path.basename(filename));

    self._main = opt.main || false;
    self._client = opt.client || false;
    self._name = opt.name;

    self._externals = opt.external || [];

    // a shim is 'name' -> '/path/to/file.js'
    // merge user shims over default shims
    self._shims = merge(k_default_shims, opt.shims || {});
}

// generate the bundled string
Bundle.prototype.generate = function(cb) {
    var self = this;

    var out = '(function(require) {\n';

    self.normalize(function(err, result) {
        if (err) {
            return cb(err);
        }

        var deps = result.deps;
        var aliases = result.aliases;

        Object.keys(aliases).forEach(function(from) {
            var to = aliases[from];
            // map the new short name to an already loaded name
            out += 'require.alias(\'' + from + '\', \'' + to + '\');\n';
        });

        // fullpath -> source
        var sources = {};

        // load sources
        function load_sources(cb) {
            var paths = Object.keys(deps);
            (function next(err) {
                var path = paths.shift();
                if (!path) {
                    return cb();
                }

                fs.readFile(path, 'utf8', function(err, src) {
                    if (err) {
                        return cb(err);
                    }

                    sources[path] = src;
                    next();
                });
            })();
        }

        load_sources(function(err) {
            if (err) {
                return cb(err);
            }

            var paths = Object.keys(deps);

            paths.forEach(function(path) {
                var info = deps[path];

                var name = info.name;
                var offset = info.offset;
                var src = sources[path];

                out += 'require.define(\'' + name + '\', \'' + offset + '\', ';
                out += 'function(global, module, exports, require, process, __filename, __dirname) {\n';
                out += src;
                out += '\n});\n\n';
            });

            var entry = deps[self._entry];
            if (self._main) {
                out += 'require(\'' + entry.name + '\');\n';
            }

            // close the whole closure
            out += '})(require);\n';

            cb(null, out);
        })
    });
};

/// TODO should be recursive since having our externals contain a file
/// is the same to us as having their externals contain the file
/// need to make sure external is resolved
Bundle.prototype.external = function(filename) {
    var self = this;

    // if our externals are our filename directly, then use the external
    // TODO any externals in the chain should be allowed to stand in for an external

    var externals = self._externals;
    for (var i=0 ; i<externals.length ; ++i) {
        var external = externals[i];
        if (external._entry === filename) {
            return external;
        }
    }

    return null;
};

// flatten deps
// deps is a tree
// flatten into an object of
// {
//  filename: {
//      requires: {
//          'a': '/full/path/to/a',
//          'b': '/full/path/to/b'
//      }
// }
Bundle.prototype.flatten = function(deps) {
    var self = this;

    var flat = {};

    deps.forEach(function(dep) {
        var reqs = {};

        if (self.external(dep.filename)) {
            return
        };

        dep.deps.forEach(function(dep) {
            reqs[dep.id] = dep.filename;
        });

        // bring in all the child dependencies
        merge(flat, self.flatten(dep.deps));
        flat[dep.filename] = reqs;
    });

    return flat;
};

Bundle.prototype.resolve = function(cb) {
    var self = this;

    var filename = self._entry;

    // basepath is used to create the aliases for path lookup
    var basepath = path.dirname(filename);

    var shims = self._shims;

    required(filename, { ignoreMissing: true }, function(err, deps) {
        if (err) {
            return cb(err);
        }

        shim(deps, shims, function(err) {
            if (err) {
                return cb(err);
            }

            // should be done after shim since native modules
            // will have filename populated
            var ids = {};
            deps.reduce(function(prev, curr, idx, arr) {
                prev[curr.id] = curr.filename;
                return prev;
            }, ids);

            var flat = self.flatten(deps);

            // deps for the entry file
            flat[filename] = ids;

            cb(null, flat);
        });
    });
};

Bundle.prototype.normalize = function(cb) {
    var self = this;

    var filename = self._entry;

    // basepath is used to create the aliases for path lookup
    var basepath = path.dirname(filename);

    var shims = self._shims;

    self.resolve(function(err, flat) {
        if (err) {
            return cb(err);
        }

        var paths = Object.keys(flat);

        var registry = {};

        // exported aliases
        var aliases = {};

        // register all of the dependencies
        paths.forEach(function(file) {
            var basename = path.basename(file, '.js');
            var dirname = path.dirname(file);
            var relative = path.relative(basepath, dirname);

            var name = '/' + path.join(relative, basename);

            if (relative) {
                relative += '/';
            }

            if (file === filename && self._name) {
                name = self._name;
            }

            // we will see the full path later
            // for now, we just need to do what?
            // register the entry for this pathname
            registry[file] = {
                name: name,
                offset: '/' + relative
            };
        });

        // setup aliases
        // shortname is what the file is registered as
        // in our file we have require(<id>)
        // we lookup the fullpath for that id from the registry
        // and make an alias from ./relative/id to the registered path
        paths.forEach(function(file) {
            var dirname = path.dirname(file);
            var relative = path.relative(basepath, dirname);

            // we now have a registry of all the full file paths
            // -> the registered name
            // now just make aliases for the reqs -> registered name
            var reqs = flat[file];
            Object.keys(reqs).forEach(function(id) {
                var filename = reqs[id];

                // ./ requires are trimmed aray
                if (id[0] === '.' && id[1] === '/') {
                    id = id.slice(2);
                }

                // rel is the absolute path to the require with offset applied
                var rel = '/' + id;
                if (relative) {
                    rel = '/' + relative + rel;
                }

                // TODO(shtylman) this means it was in an external
                // since we never registered the file
                // should register external files
                if (!registry[filename]) {
                    aliases[rel] = '/' + id;
                    return;
                }

                var reg_name = registry[filename].name;

                // ignore noop aliases
                if (rel === reg_name) {
                    return;
                }

                // paths with .. are always aliased
                // client does not do path operations
                if (id[0] === '.' && id[1] === '.') {
                    aliases[rel] = reg_name;
                    return;
                }

                aliases[rel] = reg_name;
            });
        });

        cb(null, {
            deps: registry,
            aliases: aliases
        });
    });
};

// return a path for package.json from given basepath
function pkg_find(basepath) {
    if (!basepath) {
        return;
    }

    var pkg_path = basepath + '/package.json';
    if (fs.existsSync(pkg_path)) {
        return pkg_path;
    }

    // up up up!
    return pkg_find(path.dirname(basepath));
}

// take a set of deps and replace with any shims
function shim(deps, shims, cb) {
    if (!deps || deps.length === 0) {
        return cb(null);
    }

    var count = 0;

    // filenames which we have already loaded package.json
    var loaded_pkgs = {};

    // loop deps
    // see if we need to keep each one
    (function next() {
        if (count >= deps.length) {
            return cb(null);
        }

        var dep = deps[count++];
        if (dep.seen) {
            return next();
        }

        // find a suitable package.json file
        // this is where we find the shims
        // once we have seen a filename, there is no need to check
        // it again
        if (dep.filename && !loaded_pkgs[dep.filename]) {
            loaded_pkgs[dep.filename] = true;
            var basepath = path.dirname(dep.filename);

            // TODO async
            var pkg_path = pkg_find(basepath);
            if (pkg_path) {
                var pkg_info = JSON.parse(fs.readFileSync(pkg_path, 'utf8'));
                var base = path.dirname(pkg_path);
                for (var key in pkg_info.shims) {
                    var shim_path = path.join(base, pkg_info.shims[key]);
                    if (key[0] === '.') {
                        key = path.normalize(path.join(base, key));
                    }
                    shims[key] = shim_path;
                }
            }
        }

        dep.seen = true;

        // this will be called at the final dep
        var shim_filename = shims[dep.id];

        // if shim was loaded by id, then don't override
        if (!shim_filename && dep.filename) {
            shim_filename = shims[dep.filename];
        }

        if (shim_filename) {
            required(shim_filename, function(err, shim_deps) {
                if (err) {
                    return cb(err);
                }

                dep.filename = shim_filename;
                dep.native = is_native(dep.id);

                // need to shim any deps in the loaded shim
                // a shim could require modules which need to be shimmed
                shim(shim_deps, shims, function(err) {
                    dep.deps = shim_deps;
                    next();
                });
            });

            return;
        }

        shim(dep.deps, shims, function(err) {
            if (err) {
                return cb(err);
            }

            delete dep.seen;
            next();
        });
    })();
};

module.exports.Bundle = Bundle;

// .file(/path/to/local/file, opt);
module.exports.file = function(filename, opt) {
    return new Bundle(filename, opt);
};

// .module('some-module', opt);
module.exports.module = function(name, opt) {

    var filename = require.resolve(name);

    // the entry registered name will be the module name
    opt = merge({ name: name }, opt || {});

    return new Bundle(filename, opt);
};

<|endoftext|>


<commit_before>/** MAKE SURE THIS FILE IS INCLUDED AFTER JQUERY.
 * This file contains some jQuery in its functions and runs stable on JQuery 1.11.1
 * To contributors:
 *     The following arrays contain the names AND links to the buzzwords, nouns, and technologies used.
 *     Feel free to refine the existing list and/or add new items to the lists. Make sure to keep the same
 *     format throughout the arrays. Also, make sure that the word you are adding actually makes sense grammatically
 *     if it were to be used in the idea sentence
 */

// The array that contains the list of buzzwords and their respective links
// Make sure to add "a" or "an" before the word
var buzzwords = [
    ['a 3D','http://en.wikipedia.org/wiki/3D'],
    ['a back-end','http://www.techopedia.com/definition/1405/back-end-system'],
    ['a big data', 'http://www.techopedia.com/definition/27745/big-data'],
    ['a blockchain-based','http://www.techopedia.com/definition/30246/blockchain'],
    ['a collaborative','http://www.techopedia.com/definition/4927/web-collaboration'],
    ['a cross-platform','http://www.techopedia.com/definition/17056/cross-platform'],
    ['a crowdsourced','http://www.techopedia.com/definition/27816/crowdsourcing'],
    ['a modular','http://www.techopedia.com/definition/24771/modular'],
    ['a peer-to-peer','http://en.wikipedia.org/wiki/Peer-to-peer'],
    ['a scalable','http://www.techopedia.com/definition/9269/scalability'],
    ['a secure','http://www.techopedia.com/definition/23548/internet-security'],
    ['a social','http://www.techopedia.com/definition/23759/social-platform'],
    ['a software as a service','http://www.techopedia.com/definition/155/software-as-a-service-saas'],
    ['a wearable','http://www.techopedia.com/definition/16339/wearable-computer'],
    ['an immersive', 'http://dictionary.reference.com/browse/immersive']
];

// The array that contains the list of nouns and their respective links
var nouns = [

    //Fix these links - should lead to something better than Wikipedia

    //Platforms
    ['Android app', 'http://developer.android.com/index.html'],
    ['Chrome app', 'https://developer.chrome.com/apps/first_app'],
    ['Chrome extension', 'https://developer.chrome.com/extensions/getstarted'],
    ['Firefox extension', 'https://developer.mozilla.org/en-US/Add-ons'],
    ['Firefox OS app', 'https://developer.mozilla.org/en-US/Apps/Build/installable_apps_for_Firefox_OS'],
    ['Google Cardboard app', 'https://developers.google.com/cardboard/overview'],
    ['Google Glass app', 'https://developers.google.com/glass/'],
    ['iPhone app', 'http://en.wikipedia.org/wiki/App_Store_(iOS)'],
    ['Leap Motion app', 'https://developer.leapmotion.com/'],
    ['Myo app', 'https://developer.thalmic.com/'],
    ['Occulus Rift app', 'https://developer.oculus.com/'],
    ['Pebble app', 'https://developer.getpebble.com/'],
    ['web app', 'https://developer.apple.com/programs/ios/'],
    ['Windows Phone app', 'https://dev.windows.com/en-us'],

    //Types
    ['application', 'http://en.wikipedia.org/wiki/Application_software'],
    ['game', 'http://en.wikipedia.org/wiki/Game'],
    ['operating system', 'http://en.wikipedia.org/wiki/Operating_system']
];

// The array that contains the list of technologies and their respective links
var techs = [
    //APIs
    ['Bitpay API', 'https://bitpay.com/api'],
    ['Coinbase API', 'https://www.coinbase.com/docs/api/overview'],
    ['Facebook API', 'https://www.bento.io/facebook'],
    ['Foursquare API', 'https://www.bento.io/foursquare'],
    ['GitHub API', 'https://developer.github.com/v3/'],
    ['lob API', 'https://www.bento.io/lob'],
    ['Mandrill API', 'https://www.bento.io/mandrill'],
    ['SalesForce API', 'http://www.salesforce.com/us/developer/docs/api/index.htm'],
    ['Sendgrid API', 'https://www.bento.io/sendgrid'],
    ['Shirts.io API', 'https://www.bento.io/shirts.io'],
    ['Stripe API', 'https://www.bento.io/stripe'],
    ['Twilio API', 'https://www.bento.io/twilio'],
    ['Twitter API', 'https://dev.twitter.com/overview/documentation'],
    //tools
    ['Twitter Fabric', 'https://dev.twitter.com/products/fabric'],
    //languages
    ['.NET', 'https://www.bento.io/.net'],
    ['C#', 'https://www.bento.io/c-sharp'],
    ['Clojure', 'https://www.bento.io/clojure'],
    ['Dart', 'https://www.bento.io/dart'],
    ['Go', 'https://www.bento.io/go'],
    ['Groovy', 'https://www.bento.io/groovy'],
    ['Haskell', 'http://learnyouahaskell.com/'],
    ['Java', 'https://www.bento.io/java'],
    ['JavaScript', 'https://www.bento.io/javascript'],
    ['JQuery', 'https://www.bento.io/jquery'],
    ['Objective-C', 'https://www.bento.io/objective-c'],
    ['Perl', 'https://www.bento.io/perl'],
    ['PHP', 'https://www.bento.io/php'],
    ['Python', 'https://www.bento.io/python'],
    ['Ruby', 'https://www.bento.io/ruby'],
    ['Scala', 'https://www.bento.io/scala'],
    ['Swift', 'https://www.bento.io/swift'],
    //stack pieces
    ['CouchDB', 'https://www.bento.io/couchdb'],
    ['MongoDB', 'https://www.bento.io/mongo'],
    //Frameworks, etc
    ['AngularJS', 'https://www.bento.io/angular'],
    ['Backbone.js', 'https://www.bento.io/backbone'],
    ['Bootstrap', 'https://www.bento.io/bootstrap'],
    ['Bottle', 'https://www.bento.io/bottle'],
    ['CakePHP', 'https://www.bento.io/cakephp'],
    ['CodeIgniter', 'https://www.bento.io/codeigniter'],
    ['Django', 'https://www.bento.io/django'],
    ['Elixir', 'https://www.bento.io/elixir'],
    ['Ember', 'https://www.bento.io/ember'],
    ['Express', 'https://www.bento.io/express'],
    ['Flask', 'https://www.bento.io/flask'],
    ['Flight', 'https://www.bento.io/flight'],
    ['Jade', 'https://www.bento.io/jade'],
    ['Laravel', 'https://www.bento.io/laravel'],
    ['LESS', 'https://www.bento.io/less'],
    ['Meteor', 'https://www.bento.io/meteor'],
    ['Phalcon', 'https://www.bento.io/phalcon'],
    ['PHPixie', 'https://www.bento.io/phpixie'],
    ['Play', 'https://www.bento.io/play'],
    ['react.js', 'http://facebook.github.io/react/'],
    ['Ruby on Rails', 'https://www.bento.io/rails'],
    ['Sass', 'https://www.bento.io/sass'],
    ['Symfony', 'https://www.bento.io/symfony'],
    ['Tornado', 'https://www.bento.io/tornado'],
    ['Twig', 'https://www.bento.io/twig'],
    ['uilang', 'https://www.bento.io/uilang'],
    ['Underscore.js', 'https://www.bento.io/underscore'],
    ['Yii', 'https://www.bento.io/yii']

];

// The function that returns a random index of an array.
function randomize (arrayToRandomize) {
    return Math.floor(Math.random() * arrayToRandomize.length);
}

// Function for generating a buzzword that returns the name and the link.
// Access the name by generatedBuzzword.name and the link by generatedBuzzword.link
function generateBuzzWord() {
    var rand = randomize(buzzwords);
    // Return multiple values as JSON to access easily
    return {
        name: buzzwords[rand][0],
        link: buzzwords[rand][1]
    };
}

// This function generates a name for the project using the Foswig function. Make sure to include foswig.js before this file in index.html
function generateName() {
    chain = new Foswig(3);
    chain.addWordsToChain(dictionary);
    return chain.generateWord(5,10,true);
}

// This function will generate the nouns based on the array above. Much simpler than the others
function generateNoun() {
    var rand = randomize(nouns);
    // Return multiple values as JSON to access easily
    return {
        name: nouns[rand][0],
        link: nouns[rand][1]
    };
}

// Function for generating technology names, This will return four values: Tech 1 name and link and tech 2 name and link
// Access name and link of tech 1 by generatedTech.tech1.name and generatedTech.tech1.link. Same notation for tech 2.
function generateTechs() {
    var rand1 = randomize(techs);
    var rand2 = randomize(techs);

    // If rand2 happens to equal rand1, calculate it until it doesn't
    while (rand1 == rand2) {
        rand2 = randomize(techs);
    }
    // Return multiple values as JSON to access easily
    return {
        tech1 : {
            name: techs[rand1][0],
            link: techs[rand1][1]
        },
        tech2 : {
            name: techs[rand2][0],
            link: techs[rand2][1]
        }
    }
}

// Button click event when the chevron is clicked
function clickGenerateButton() {

    // Replace the go button with a replay button
    if ($(".fa-rocket:visible")) {
        $('.fa-rocket').hide();
        $('.fa-refresh').show();
    }
    else if ($(".fa-refresh:visible")) {
        $('.fa-refresh').hide();
        $('.fa-rocket').show();
    }

    // Generate name and insert text
    var generatedName = generateName();
    $("#ideaName").text(generatedName);

    // Generate buzz word and insert text
    var generatedBuzzWord = generateBuzzWord();
    $("#ideaBuzzWord").html("" + generatedBuzzWord.name + "");

    // Generate noun and insert text
    var generatedNoun = generateNoun();
    $("#ideaNoun").html("" + generatedNoun.name + "");

    // Generate tech words then insert both into text
    var generatedTechs = generateTechs();
    $("#ideaTech1").html("" + generatedTechs.tech1.name + "");
    $("#ideaTech2").html("" + generatedTechs.tech2.name + "");

    //Make the Twitter button have your idea in the text
    $("#twitter-share-button").attr("href", "https://twitter.com/intent/tweet?original_referer=&text=This%20%23hackathon%20I%27m%20going%20to%20make%20"+generatedName+"%2C%20"+generatedBuzzWord.name+"%20"+generatedNoun.name+"%20using%20"+generatedTechs.tech1.name+"%20and%20"+generatedTechs.tech2.name+"%2C%20thanks%20%40impatientbanana!");
}

// This is the function that animates the scrolling down when the chevron is clicked
function animateScrolling() {
    $('html, body').animate({
        scrollTop: $("#generatorContainer").offset().top
    }, 1000);
}

// This function will change each divs heights according to the viewport size when the window is resized
function resizeListener() {
    // This will execute whenever the window is resized
    var w = $(window).height();
    $("#jumbotron").height(w);
    $("#generatorContainer").height(w);
}

// The values for counterBuzzwords, counterNouns, counterTechs1, counterTechs2, counterNames NEED to be defined in index.html because of the nature of the setInterval function using this function
function loopThroughArrays() {

    // Show
    $("#ideaName").text(dictionary[counterNames]);
    $("#ideaBuzzWord").text(buzzwords[counterBuzzwords][0]);
    $("#ideaNoun").text(nouns[counterNouns][0]);
    $("#ideaTech1").text(techs[counterTechs1][0]);
    $("#ideaTech2").text(techs[counterTechs2][0]);

    // Loop through buzzwords
    counterBuzzwords = ++counterBuzzwords;
    if (counterBuzzwords == nouns.length) {
        counterBuzzwords = 0;
    }

    // Loop through nouns
    counterNouns = ++counterNouns;
    if (counterNouns == nouns.length) {
        counterNouns = 0;
    }

    // Loop through techs (k is tech 1, l is tech 2)
    counterTechs1 = ++counterTechs1;
    if (counterTechs1 == techs.length) {
        counterTechs1 = 0;
    }

    counterTechs2 = ++counterTechs2;
    if (counterTechs2 == techs.length) {
        counterTechs2 = 0;
    }

    // Loop through dictionary of names
    counterNames = ++counterNames;
    if (counterNames == dictionary.length) {
        counterNames = 0;
    }
}<commit_msg>counter++ instead of ++ counter. It may fix the freezes<commit_after>/** MAKE SURE THIS FILE IS INCLUDED AFTER JQUERY.
 * This file contains some jQuery in its functions and runs stable on JQuery 1.11.1
 * To contributors:
 *     The following arrays contain the names AND links to the buzzwords, nouns, and technologies used.
 *     Feel free to refine the existing list and/or add new items to the lists. Make sure to keep the same
 *     format throughout the arrays. Also, make sure that the word you are adding actually makes sense grammatically
 *     if it were to be used in the idea sentence
 */

// The array that contains the list of buzzwords and their respective links
// Make sure to add "a" or "an" before the word
var buzzwords = [
    ['a 3D','http://en.wikipedia.org/wiki/3D'],
    ['a back-end','http://www.techopedia.com/definition/1405/back-end-system'],
    ['a big data', 'http://www.techopedia.com/definition/27745/big-data'],
    ['a blockchain-based','http://www.techopedia.com/definition/30246/blockchain'],
    ['a collaborative','http://www.techopedia.com/definition/4927/web-collaboration'],
    ['a cross-platform','http://www.techopedia.com/definition/17056/cross-platform'],
    ['a crowdsourced','http://www.techopedia.com/definition/27816/crowdsourcing'],
    ['a modular','http://www.techopedia.com/definition/24771/modular'],
    ['a peer-to-peer','http://en.wikipedia.org/wiki/Peer-to-peer'],
    ['a scalable','http://www.techopedia.com/definition/9269/scalability'],
    ['a secure','http://www.techopedia.com/definition/23548/internet-security'],
    ['a social','http://www.techopedia.com/definition/23759/social-platform'],
    ['a software as a service','http://www.techopedia.com/definition/155/software-as-a-service-saas'],
    ['a wearable','http://www.techopedia.com/definition/16339/wearable-computer'],
    ['an immersive', 'http://dictionary.reference.com/browse/immersive']
];

// The array that contains the list of nouns and their respective links
var nouns = [

    //Fix these links - should lead to something better than Wikipedia

    //Platforms
    ['Android app', 'http://developer.android.com/index.html'],
    ['Chrome app', 'https://developer.chrome.com/apps/first_app'],
    ['Chrome extension', 'https://developer.chrome.com/extensions/getstarted'],
    ['Firefox extension', 'https://developer.mozilla.org/en-US/Add-ons'],
    ['Firefox OS app', 'https://developer.mozilla.org/en-US/Apps/Build/installable_apps_for_Firefox_OS'],
    ['Google Cardboard app', 'https://developers.google.com/cardboard/overview'],
    ['Google Glass app', 'https://developers.google.com/glass/'],
    ['iPhone app', 'http://en.wikipedia.org/wiki/App_Store_(iOS)'],
    ['Leap Motion app', 'https://developer.leapmotion.com/'],
    ['Myo app', 'https://developer.thalmic.com/'],
    ['Occulus Rift app', 'https://developer.oculus.com/'],
    ['Pebble app', 'https://developer.getpebble.com/'],
    ['web app', 'https://developer.apple.com/programs/ios/'],
    ['Windows Phone app', 'https://dev.windows.com/en-us'],

    //Types
    ['application', 'http://en.wikipedia.org/wiki/Application_software'],
    ['game', 'http://en.wikipedia.org/wiki/Game'],
    ['operating system', 'http://en.wikipedia.org/wiki/Operating_system']
];

// The array that contains the list of technologies and their respective links
var techs = [
    //APIs
    ['Bitpay API', 'https://bitpay.com/api'],
    ['Coinbase API', 'https://www.coinbase.com/docs/api/overview'],
    ['Facebook API', 'https://www.bento.io/facebook'],
    ['Foursquare API', 'https://www.bento.io/foursquare'],
    ['GitHub API', 'https://developer.github.com/v3/'],
    ['lob API', 'https://www.bento.io/lob'],
    ['Mandrill API', 'https://www.bento.io/mandrill'],
    ['SalesForce API', 'http://www.salesforce.com/us/developer/docs/api/index.htm'],
    ['Sendgrid API', 'https://www.bento.io/sendgrid'],
    ['Shirts.io API', 'https://www.bento.io/shirts.io'],
    ['Stripe API', 'https://www.bento.io/stripe'],
    ['Twilio API', 'https://www.bento.io/twilio'],
    ['Twitter API', 'https://dev.twitter.com/overview/documentation'],
    //tools
    ['Twitter Fabric', 'https://dev.twitter.com/products/fabric'],
    //languages
    ['.NET', 'https://www.bento.io/.net'],
    ['C#', 'https://www.bento.io/c-sharp'],
    ['Clojure', 'https://www.bento.io/clojure'],
    ['Dart', 'https://www.bento.io/dart'],
    ['Go', 'https://www.bento.io/go'],
    ['Groovy', 'https://www.bento.io/groovy'],
    ['Haskell', 'http://learnyouahaskell.com/'],
    ['Java', 'https://www.bento.io/java'],
    ['JavaScript', 'https://www.bento.io/javascript'],
    ['JQuery', 'https://www.bento.io/jquery'],
    ['Objective-C', 'https://www.bento.io/objective-c'],
    ['Perl', 'https://www.bento.io/perl'],
    ['PHP', 'https://www.bento.io/php'],
    ['Python', 'https://www.bento.io/python'],
    ['Ruby', 'https://www.bento.io/ruby'],
    ['Scala', 'https://www.bento.io/scala'],
    ['Swift', 'https://www.bento.io/swift'],
    //stack pieces
    ['CouchDB', 'https://www.bento.io/couchdb'],
    ['MongoDB', 'https://www.bento.io/mongo'],
    //Frameworks, etc
    ['AngularJS', 'https://www.bento.io/angular'],
    ['Backbone.js', 'https://www.bento.io/backbone'],
    ['Bootstrap', 'https://www.bento.io/bootstrap'],
    ['Bottle', 'https://www.bento.io/bottle'],
    ['CakePHP', 'https://www.bento.io/cakephp'],
    ['CodeIgniter', 'https://www.bento.io/codeigniter'],
    ['Django', 'https://www.bento.io/django'],
    ['Elixir', 'https://www.bento.io/elixir'],
    ['Ember', 'https://www.bento.io/ember'],
    ['Express', 'https://www.bento.io/express'],
    ['Flask', 'https://www.bento.io/flask'],
    ['Flight', 'https://www.bento.io/flight'],
    ['Jade', 'https://www.bento.io/jade'],
    ['Laravel', 'https://www.bento.io/laravel'],
    ['LESS', 'https://www.bento.io/less'],
    ['Meteor', 'https://www.bento.io/meteor'],
    ['Phalcon', 'https://www.bento.io/phalcon'],
    ['PHPixie', 'https://www.bento.io/phpixie'],
    ['Play', 'https://www.bento.io/play'],
    ['react.js', 'http://facebook.github.io/react/'],
    ['Ruby on Rails', 'https://www.bento.io/rails'],
    ['Sass', 'https://www.bento.io/sass'],
    ['Symfony', 'https://www.bento.io/symfony'],
    ['Tornado', 'https://www.bento.io/tornado'],
    ['Twig', 'https://www.bento.io/twig'],
    ['uilang', 'https://www.bento.io/uilang'],
    ['Underscore.js', 'https://www.bento.io/underscore'],
    ['Yii', 'https://www.bento.io/yii']

];

// The function that returns a random index of an array.
function randomize (arrayToRandomize) {
    return Math.floor(Math.random() * arrayToRandomize.length);
}

// Function for generating a buzzword that returns the name and the link.
// Access the name by generatedBuzzword.name and the link by generatedBuzzword.link
function generateBuzzWord() {
    var rand = randomize(buzzwords);
    // Return multiple values as JSON to access easily
    return {
        name: buzzwords[rand][0],
        link: buzzwords[rand][1]
    };
}

// This function generates a name for the project using the Foswig function. Make sure to include foswig.js before this file in index.html
function generateName() {
    chain = new Foswig(3);
    chain.addWordsToChain(dictionary);
    return chain.generateWord(5,10,true);
}

// This function will generate the nouns based on the array above. Much simpler than the others
function generateNoun() {
    var rand = randomize(nouns);
    // Return multiple values as JSON to access easily
    return {
        name: nouns[rand][0],
        link: nouns[rand][1]
    };
}

// Function for generating technology names, This will return four values: Tech 1 name and link and tech 2 name and link
// Access name and link of tech 1 by generatedTech.tech1.name and generatedTech.tech1.link. Same notation for tech 2.
function generateTechs() {
    var rand1 = randomize(techs);
    var rand2 = randomize(techs);

    // If rand2 happens to equal rand1, calculate it until it doesn't
    while (rand1 == rand2) {
        rand2 = randomize(techs);
    }
    // Return multiple values as JSON to access easily
    return {
        tech1 : {
            name: techs[rand1][0],
            link: techs[rand1][1]
        },
        tech2 : {
            name: techs[rand2][0],
            link: techs[rand2][1]
        }
    }
}

// Button click event when the chevron is clicked
function clickGenerateButton() {

    // Replace the go button with a replay button
    if ($(".fa-rocket:visible")) {
        $('.fa-rocket').hide();
        $('.fa-refresh').show();
    }
    else if ($(".fa-refresh:visible")) {
        $('.fa-refresh').hide();
        $('.fa-rocket').show();
    }

    // Generate name and insert text
    var generatedName = generateName();
    $("#ideaName").text(generatedName);

    // Generate buzz word and insert text
    var generatedBuzzWord = generateBuzzWord();
    $("#ideaBuzzWord").html("" + generatedBuzzWord.name + "");

    // Generate noun and insert text
    var generatedNoun = generateNoun();
    $("#ideaNoun").html("" + generatedNoun.name + "");

    // Generate tech words then insert both into text
    var generatedTechs = generateTechs();
    $("#ideaTech1").html("" + generatedTechs.tech1.name + "");
    $("#ideaTech2").html("" + generatedTechs.tech2.name + "");

    //Make the Twitter button have your idea in the text
    $("#twitter-share-button").attr("href", "https://twitter.com/intent/tweet?original_referer=&text=This%20%23hackathon%20I%27m%20going%20to%20make%20"+generatedName+"%2C%20"+generatedBuzzWord.name+"%20"+generatedNoun.name+"%20using%20"+generatedTechs.tech1.name+"%20and%20"+generatedTechs.tech2.name+"%2C%20thanks%20%40impatientbanana!");
}

// This is the function that animates the scrolling down when the chevron is clicked
function animateScrolling() {
    $('html, body').animate({
        scrollTop: $("#generatorContainer").offset().top
    }, 1000);
}

// This function will change each divs heights according to the viewport size when the window is resized
function resizeListener() {
    // This will execute whenever the window is resized
    var wind = $(window).height();
    $("#jumbotron").height(wind);
    $("#generatorContainer").height(wind);
}

// The values for counterBuzzwords, counterNouns, counterTechs1, counterTechs2, counterNames NEED to be defined in index.html because of the nature of the setInterval function using this function
function loopThroughArrays() {

    // Show
    $("#ideaName").text(dictionary[counterNames]);
    $("#ideaBuzzWord").text(buzzwords[counterBuzzwords][0]);
    $("#ideaNoun").text(nouns[counterNouns][0]);
    $("#ideaTech1").text(techs[counterTechs1][0]);
    $("#ideaTech2").text(techs[counterTechs2][0]);

    // Loop through buzzwords
    counterBuzzwords = counterBuzzwords++;
    if (counterBuzzwords == nouns.length) {
        counterBuzzwords = 0;
    }

    // Loop through nouns
    counterNouns = ++counterNouns;
    if (counterNouns == nouns.length) {
        counterNouns = 0;
    }

    // Loop through techs (k is tech 1, l is tech 2)
    counterTechs1 = ++counterTechs1;
    if (counterTechs1 == techs.length) {
        counterTechs1 = 0;
    }

    counterTechs2 = ++counterTechs2;
    if (counterTechs2 == techs.length) {
        counterTechs2 = 0;
    }

    // Loop through dictionary of names
    counterNames = ++counterNames;
    if (counterNames == dictionary.length) {
        counterNames = 0;
    }
}<|endoftext|>


<commit_before>'use strict';

function iterTree(fn, tree) {
    if (tree.left === null) { // Leaf, call the function
        fn(tree.value)
    } else {
        iterTree(fn, tree.left) // Left, then right
        iterTree(fn, tree.right)
    }
}

function mapTree(fn, tree) {
    if (tree.size === 1) {
        return {size: 1, value: fn(tree.value), left: null, right: null}
    } else {
        var newLeft = mapTree(fn, tree.left)
        var newRight = mapTree(fn, tree.right)
        return {size: tree.size, left: newLeft, right: newRight}
    }
}

function updateTree(tree, index, value) {
    if (tree.size === 1) {
        return {size: 1, left: null, right: null, value: value}
    }

    var newTree = {size: tree.size, left: tree.left, right: tree.right}
    if (index < tree.left.size) {
        newTree.left = updateTree(tree.left, index, value)
    } else {
        newTree.right = updateTree(tree.right, index - tree.right.size, value)
    }
    return newTree
}

class BForest {
    constructor(array) {
        this.trees = []
        if (array !== undefined) {
            this.trees = this.prepend(array).trees
        }
    }

    prepend(array) {
        if (array === undefined) {
            return this
        }

        var bf = this
        for (var i = array.length - 1; i >= 0; i--) {
            bf = bf.cons(array[i])
        }

        return bf
    }

    isEmpty() {
        return (this.trees.length === 0)
    }

    head() {
        if (this.isEmpty()) {
            return null
        }

        var ptr = this.trees[0]
        while (ptr.left !== null) {
            ptr = ptr.left // Go all the way left
        }

        return ptr.value
    }

    cons(element) {
        var bf = new BForest()
        var newTree = { size: 1, value: element, left: null, right: null}

        for (var i = 0; i < this.trees.length; i++) {
            if (this.trees[i].size > newTree.size) {
                bf.trees = [newTree].concat(this.trees.slice(i))
                return bf;
            }
            newTree = {size: 2 * newTree.size, left: newTree, right: this.trees[i]}
        }

        bf.trees = [newTree]
        return bf
    }

    iter(fn) {
        for (var i = 0; i < this.trees.length; i++) {
            iterTree(fn, this.trees[i])
        }
    }

    map(fn) {
        var bf = new BForest()

        for (var i = 0; i < this.trees.length; i++) {
            bf.trees.push(mapTree(fn, this.trees[i]))
        }

        return bf
    }

    tail() {
        if (this.isEmpty()) {
            return this
        }

        var bf = new BForest()
        if (this.trees[0].size > 1) { // Need to break apart first tree
            var ptr = this.trees[0]

            while (ptr !== null && ptr.right !== null) {
                bf.trees.push(ptr.right) // Collect the trees on the right
                ptr = ptr.left // Recurse down the left side of the tree
            }

            bf.trees.reverse() // Last tree pushed on is the smallest/'first'
        }

        bf.trees = bf.trees.concat(this.trees.slice(1)) // Keep old trees
        return bf
    }

    index(index) {
        if (this.isEmpty() || !Number.isInteger(index) || index < 0) {
            return null
        }

        for (var i = 0; i < this.trees.length; i++) {
            if (index < this.trees[i].size) { // It's in this tree
                var ptr = this.trees[i]
                while (ptr.left !== null) {
                    if (index < ptr.left.size) { // 0 <= index < 2^n
                        ptr = ptr.left // [0..2^n] -> [0..2^(n-1)]
                    } else {
                        index -= ptr.left.size // [0..2^n] -> [2^(n-1)..2^n] - 2^(n-1)
                        ptr = ptr.right
                    }
                }
                return ptr.value // We must be at the leaf [i] if ptr.left is null
            } else { // It's in a later tree, subtract from index # skipped
                index -= this.trees[i].size
            }
        }
        return null // We looked at all the trees and didn't find [i]
    }

    update(index, value) {
        if (this.isEmpty()) { return null }

        for (var i = 0; i < this.trees.length; i++) {
            if (index >= this.trees[i].size) { // It's in a later tree
                index -= this.trees[i].size // Subtract from index # skipped
                continue
            }

            var bf = new BForest()
            bf.trees = this.trees.slice(0, i) // Collect all trees before
            bf.trees.push(updateTree(this.trees[i], index, value))
            bf.trees = bf.trees.concat(this.trees.slice(i + 1)) // And after
            return bf
        }
        return this // Updated nothing! Return the original tree
    }

    toString() {
        var strings = []
        this.iter(function(elt) { strings.push(elt.toString()) })
        return '[' + strings.join(', ') + ']'
    }
}

module.exports = BForest
<commit_msg>Replace all var-bindings w/ let-bindings.<commit_after>'use strict';

function iterTree(fn, tree) {
    if (tree.left === null) { // Leaf, call the function
        fn(tree.value)
    } else {
        iterTree(fn, tree.left) // Left, then right
        iterTree(fn, tree.right)
    }
}

function mapTree(fn, tree) {
    if (tree.size === 1) {
        return {size: 1, value: fn(tree.value), left: null, right: null}
    } else {
        let newLeft = mapTree(fn, tree.left)
        let newRight = mapTree(fn, tree.right)

        return {size: tree.size, left: newLeft, right: newRight}
    }
}

function updateTree(tree, index, value) {
    if (tree.size === 1) {
        return {size: 1, left: null, right: null, value: value}
    }

    let newTree = {size: tree.size, left: tree.left, right: tree.right}
    if (index < tree.left.size) {
        newTree.left = updateTree(tree.left, index, value)
    } else {
        newTree.right = updateTree(tree.right, index - tree.right.size, value)
    }

    return newTree
}

class BForest {
    constructor(array) {
        this.trees = []
        if (array !== undefined) {
            this.trees = this.prepend(array).trees
        }
    }

    prepend(array) {
        if (array === undefined) {
            return this
        }

        let bf = this
        for (let i = array.length - 1; i >= 0; i--) {
            bf = bf.cons(array[i])
        }

        return bf
    }

    isEmpty() {
        return (this.trees.length === 0)
    }

    head() {
        if (this.isEmpty()) {
            return null
        }

        let ptr = this.trees[0]
        while (ptr.left !== null) {
            ptr = ptr.left // Go all the way left
        }

        return ptr.value
    }

    cons(element) {
        let bf = new BForest()
        let newTree = { size: 1, value: element, left: null, right: null}

        for (let i = 0; i < this.trees.length; i++) {
            if (this.trees[i].size > newTree.size) {
                bf.trees = [newTree].concat(this.trees.slice(i))
                return bf;
            }
            newTree = {size: 2 * newTree.size, left: newTree, right: this.trees[i]}
        }

        bf.trees = [newTree]
        return bf
    }

    iter(fn) {
        for (let i = 0; i < this.trees.length; i++) {
            iterTree(fn, this.trees[i])
        }
    }

    map(fn) {
        let bf = new BForest()

        for (let i = 0; i < this.trees.length; i++) {
            bf.trees.push(mapTree(fn, this.trees[i]))
        }

        return bf
    }

    tail() {
        if (this.isEmpty()) {
            return this
        }

        let bf = new BForest()
        if (this.trees[0].size > 1) { // Need to break apart first tree
            let ptr = this.trees[0]

            while (ptr !== null && ptr.right !== null) {
                bf.trees.push(ptr.right) // Collect the trees on the right
                ptr = ptr.left // Recurse down the left side of the tree
            }

            bf.trees.reverse() // Last tree pushed on is the smallest/'first'
        }

        bf.trees = bf.trees.concat(this.trees.slice(1)) // Keep old trees
        return bf
    }

    index(index) {
        if (this.isEmpty() || !Number.isInteger(index) || index < 0) {
            return null
        }

        for (let i = 0; i < this.trees.length; i++) {
            if (index < this.trees[i].size) { // It's in this tree
                let ptr = this.trees[i]
                while (ptr.left !== null) {
                    if (index < ptr.left.size) { // 0 <= index < 2^n
                        ptr = ptr.left // [0..2^n] -> [0..2^(n-1)]
                    } else {
                        index -= ptr.left.size // [0..2^n] -> [2^(n-1)..2^n] - 2^(n-1)
                        ptr = ptr.right
                    }
                }
                return ptr.value // We must be at the leaf [i] if ptr.left is null
            } else { // It's in a later tree, subtract from index # skipped
                index -= this.trees[i].size
            }
        }
        return null // We looked at all the trees and didn't find [i]
    }

    update(index, value) {
        if (this.isEmpty()) { return null }

        for (let i = 0; i < this.trees.length; i++) {
            if (index >= this.trees[i].size) { // It's in a later tree
                index -= this.trees[i].size // Subtract from index # skipped
                continue
            }

            let bf = new BForest()
            bf.trees = this.trees.slice(0, i) // Collect all trees before
            bf.trees.push(updateTree(this.trees[i], index, value))
            bf.trees = bf.trees.concat(this.trees.slice(i + 1)) // And after
            return bf
        }
        return this // Updated nothing! Return the original tree
    }

    toString() {
        let strings = []
        this.iter(function(elt) { strings.push(elt.toString()) })
        return '[' + strings.join(', ') + ']'
    }
}

module.exports = BForest
<|endoftext|>


<commit_before>import _ from "lodash";

import Posts from "./posts.js";

export default class ModeMenu {
  static initialize() {
    ModeMenu.uninitializeDanbooruModeMenu();
    ModeMenu.initializeModeMenu();
    ModeMenu.initializeTagScriptControls();
    ModeMenu.initializeThumbnails();
    ModeMenu.initializeHotkeys();
  }

  static uninitializeDanbooruModeMenu() {
    Danbooru.PostModeMenu.initialize = _.noop;
    Danbooru.PostModeMenu.show_notice = _.noop;
    $(".post-preview a").unbind("click", Danbooru.PostModeMenu.click);
    $(document).unbind("keydown", "1 2 3 4 5 6 7 8 9 0", Danbooru.PostModeMenu.change_tag_script);
    $("#sidebar #mode-box").hide();
  }

  static initializeModeMenu() {
    $('.ex-mode-menu select[name="mode"]').change(ModeMenu.switchMode);
    ModeMenu.setMode(EX.config.modeMenuState);
  }

  static initializeTagScriptControls() {
    $('.ex-mode-menu input[name="tag-script"]').on(
      "input", _.debounce(ModeMenu.saveTagScript, 250)
    );

    $('.ex-mode-menu select[name="tag-script-number"]').change(ModeMenu.switchTagScript);
    ModeMenu.setTagScriptNumber(EX.config.tagScriptNumber);

    $('.ex-mode-menu button[name="apply"]').click(ModeMenu.applyTagScript);
    $('.ex-mode-menu button[name="select-all"]').click(ModeMenu.selectAll);
    $('.ex-mode-menu button[name="select-invert"]').click(ModeMenu.invertSelection);
  }

  static initializeThumbnails() {
    $(`
      .mod-queue-preview aside a,
      div.post-preview .preview a,
      article.post-preview a
    `).click(ModeMenu.onThumbnailClick);
  }

  static initializeHotkeys() {
    $(document).keydown("1 2 3 4 5 6 7 8 9", ModeMenu.switchToTagScript);

    $(document).keydown("shift+a", ModeMenu.applyTagScript);
    $(document).keydown("ctrl+a",  ModeMenu.selectAll);
    $(document).keydown("ctrl+i",  ModeMenu.invertSelection);

    $(document).keydown("esc", e => ModeMenu.setMode("view"));
    $(document).keydown("`", e => ModeMenu.toggleMode("preview"));
    $(document).keydown("shift+`", e => ModeMenu.toggleMode("preview"));
  }

  static switchToTagScript(event) {
    const newN = Number(String.fromCharCode(event.which));
    const oldN = ModeMenu.getTagScriptNumber();

    if (ModeMenu.getMode() === "tag-script" && newN === oldN) {
      $('.ex-mode-menu input[name="tag-script"]').focus();
    } else {
      ModeMenu.setMode("tag-script");
      ModeMenu.setTagScriptNumber(newN);
    }

    event.preventDefault();
  }

  static switchMode() {
    const mode = ModeMenu.getMode();
    EX.config.modeMenuState = mode;

    $("body").removeClass((i, klass) => (klass.match(/mode-.*/) || []).join(' '));
    // $("body").removeClass("mode-view mode-preview mode-tag-script");
    $("body").addClass(`mode-${mode}`);

    if (mode === "tag-script") {
      $(".ex-mode-menu .ex-tag-script-controls").show();

      $("#page").selectable({
        filter: "article.post-preview, div.post-preview .preview, .mod-queue-preview aside",
        delay: 200,
      });
    } else {
      $(".ex-mode-menu .ex-tag-script-controls").hide();

      if ($("#page").selectable("instance")) {
        $("#page").selectable("destroy");
      }
    }
  }

  static switchTagScript(event) {
    const n = ModeMenu.getTagScriptNumber();
    EX.config.tagScriptNumber = n;

    const script = EX.config.tagScripts[n];
    $('.ex-mode-menu input[name="tag-script"]').val(script).change();
  }

  static onThumbnailClick(event) {
    // Only apply on left click, not middle click and not ctrl+left click.
    if (event.ctrlKey || event.which !== 1) {
      return;
    }

    switch (ModeMenu.getMode()) {
      case "view":
        return;

      case "tag-script":
        $(event.target).closest(".ui-selectee").toggleClass("ui-selected");
        /* fallthrough */

      case "preview":
        let post = Posts.normalize($(event.target).closest(".post-preview").data());

        const html = Posts.preview(post, post.large_file_url);
        $("#ex-preview-panel article").replaceWith(html);

        event.preventDefault();
        break;
    }
  }

  static applyTagScript(event) {
    const mode = ModeMenu.getMode();

    if (mode === "tag-script") {
      const tag_script = ModeMenu.getTagScript();
      $(".ui-selected").each((i, e) => {
        const post_id = $(e).closest(".post-preview").data("id");
        Danbooru.TagScript.run(post_id, tag_script);
      });
    }
  }

  static selectAll(event) {
    if ($(".ui-selected").length) {
      $(".ui-selected").removeClass("ui-selected");
    } else {
      $(".ui-selectee").addClass("ui-selected");
    }

    event.preventDefault();
  }

  static invertSelection(event) {
    let $unselected = $(".ui-selectee:not(.ui-selected)");
    let $selected = $(".ui-selectee.ui-selected");

    $unselected.addClass("ui-selected");
    $selected.removeClass("ui-selected");
  }

  static getMode() {
    return $(".ex-mode-menu select").val();
  }

  static setMode(mode) {
    $('.ex-mode-menu select[name="mode"]').val(mode).change();
  }

  static toggleMode(mode) {
    ModeMenu.setMode(ModeMenu.getMode() === mode ? "view" : mode);
  }

  static getTagScript() {
    return $('.ex-mode-menu input[name="tag-script"]').val().trim();
  }

  static saveTagScript() {
    const scripts = EX.config.tagScripts;
    scripts[ModeMenu.getTagScriptNumber()] = ModeMenu.getTagScript();
    EX.config.tagScripts = scripts;
  }

  static getTagScriptNumber() {
    return Number($('.ex-mode-menu select[name="tag-script-number"]').val());
  }

  static setTagScriptNumber(n) {
    $('.ex-mode-menu select[name="tag-script-number"]').val(n).change();
  }
}
<commit_msg>[feat] Make switch modes show/hide the preview panel.<commit_after>import _ from "lodash";

import Posts from "./posts.js";

export default class ModeMenu {
  static initialize() {
    ModeMenu.uninitializeDanbooruModeMenu();
    ModeMenu.initializeModeMenu();
    ModeMenu.initializeTagScriptControls();
    ModeMenu.initializeThumbnails();
    ModeMenu.initializeHotkeys();
  }

  static uninitializeDanbooruModeMenu() {
    Danbooru.PostModeMenu.initialize = _.noop;
    Danbooru.PostModeMenu.show_notice = _.noop;
    $(".post-preview a").unbind("click", Danbooru.PostModeMenu.click);
    $(document).unbind("keydown", "1 2 3 4 5 6 7 8 9 0", Danbooru.PostModeMenu.change_tag_script);
    $("#sidebar #mode-box").hide();
  }

  static initializeModeMenu() {
    $('.ex-mode-menu select[name="mode"]').change(ModeMenu.switchMode);
    ModeMenu.setMode(EX.config.modeMenuState);
  }

  static initializeTagScriptControls() {
    $('.ex-mode-menu input[name="tag-script"]').on(
      "input", _.debounce(ModeMenu.saveTagScript, 250)
    );

    $('.ex-mode-menu select[name="tag-script-number"]').change(ModeMenu.switchTagScript);
    ModeMenu.setTagScriptNumber(EX.config.tagScriptNumber);

    $('.ex-mode-menu button[name="apply"]').click(ModeMenu.applyTagScript);
    $('.ex-mode-menu button[name="select-all"]').click(ModeMenu.selectAll);
    $('.ex-mode-menu button[name="select-invert"]').click(ModeMenu.invertSelection);
  }

  static initializeThumbnails() {
    $(`
      .mod-queue-preview aside a,
      div.post-preview .preview a,
      article.post-preview a
    `).click(ModeMenu.onThumbnailClick);
  }

  static initializeHotkeys() {
    $(document).keydown("1 2 3 4 5 6 7 8 9", ModeMenu.switchToTagScript);

    $(document).keydown("shift+a", ModeMenu.applyTagScript);
    $(document).keydown("ctrl+a",  ModeMenu.selectAll);
    $(document).keydown("ctrl+i",  ModeMenu.invertSelection);

    $(document).keydown("esc", e => ModeMenu.setMode("view"));
    $(document).keydown("`", e => ModeMenu.toggleMode("preview"));
    $(document).keydown("shift+`", e => ModeMenu.toggleMode("preview"));
  }

  static switchToTagScript(event) {
    const newN = Number(String.fromCharCode(event.which));
    const oldN = ModeMenu.getTagScriptNumber();

    if (ModeMenu.getMode() === "tag-script" && newN === oldN) {
      $('.ex-mode-menu input[name="tag-script"]').focus();
    } else {
      ModeMenu.setMode("tag-script");
      ModeMenu.setTagScriptNumber(newN);
    }

    event.preventDefault();
  }

  static switchMode() {
    const mode = ModeMenu.getMode();
    EX.config.modeMenuState = mode;

    $("body").removeClass((i, klass) => (klass.match(/mode-.*/) || []).join(' '));
    $("body").addClass(`mode-${mode}`);

    if (mode === "tag-script") {
      $(".ex-mode-menu .ex-tag-script-controls").show();

      $("#page").selectable({
        filter: "article.post-preview, div.post-preview .preview, .mod-queue-preview aside",
        delay: 200,
      });
    } else {
      $(".ex-mode-menu .ex-tag-script-controls").hide();

      if ($("#page").selectable("instance")) {
        $("#page").selectable("destroy");
      }
    }

    if (mode === "view") {
      $("#ex-preview-panel").hide({ effect: "slide", direction: "right" }, 1000);
    } else {
      $("#ex-preview-panel").show({ effect: "slide", direction: "left" }, 1000);
    }
  }

  static switchTagScript(event) {
    const n = ModeMenu.getTagScriptNumber();
    EX.config.tagScriptNumber = n;

    const script = EX.config.tagScripts[n];
    $('.ex-mode-menu input[name="tag-script"]').val(script).change();
  }

  static onThumbnailClick(event) {
    // Only apply on left click, not middle click and not ctrl+left click.
    if (event.ctrlKey || event.which !== 1) {
      return;
    }

    switch (ModeMenu.getMode()) {
      case "view":
        return;

      case "tag-script":
        $(event.target).closest(".ui-selectee").toggleClass("ui-selected");
        /* fallthrough */

      case "preview":
        let post = Posts.normalize($(event.target).closest(".post-preview").data());

        const html = Posts.preview(post, post.large_file_url);
        $("#ex-preview-panel article").replaceWith(html);

        event.preventDefault();
        break;
    }
  }

  static applyTagScript(event) {
    const mode = ModeMenu.getMode();

    if (mode === "tag-script") {
      const tag_script = ModeMenu.getTagScript();
      $(".ui-selected").each((i, e) => {
        const post_id = $(e).closest(".post-preview").data("id");
        Danbooru.TagScript.run(post_id, tag_script);
      });
    }
  }

  static selectAll(event) {
    if ($(".ui-selected").length) {
      $(".ui-selected").removeClass("ui-selected");
    } else {
      $(".ui-selectee").addClass("ui-selected");
    }

    event.preventDefault();
  }

  static invertSelection(event) {
    let $unselected = $(".ui-selectee:not(.ui-selected)");
    let $selected = $(".ui-selectee.ui-selected");

    $unselected.addClass("ui-selected");
    $selected.removeClass("ui-selected");
  }

  static getMode() {
    return $(".ex-mode-menu select").val();
  }

  static setMode(mode) {
    $('.ex-mode-menu select[name="mode"]').val(mode).change();
  }

  static toggleMode(mode) {
    ModeMenu.setMode(ModeMenu.getMode() === mode ? "view" : mode);
  }

  static getTagScript() {
    return $('.ex-mode-menu input[name="tag-script"]').val().trim();
  }

  static saveTagScript() {
    const scripts = EX.config.tagScripts;
    scripts[ModeMenu.getTagScriptNumber()] = ModeMenu.getTagScript();
    EX.config.tagScripts = scripts;
  }

  static getTagScriptNumber() {
    return Number($('.ex-mode-menu select[name="tag-script-number"]').val());
  }

  static setTagScriptNumber(n) {
    $('.ex-mode-menu select[name="tag-script-number"]').val(n).change();
  }
}
<|endoftext|>


<commit_before>/* jslint node: true, esnext: true */

"use strict";

const fifo = require('fifo');

/**
 *  Template for the Channel object
 */
const RootChannel = {
	toString: function () {
		return this.name;
	}
};

/*
 * create two endpoints glued together to form a channel
 * @return array with the two channles
 */
function create(ep1, ep2) {
	let requests = fifo();

	const name = `${ep1.name}-${ep2.name}`;
	const description1 = `Channel from ${ep1.name} to ${ep2.name}`;
	const description2 = `Channel from ${ep2.name} to ${ep1.name}`;

	return Object.create(RootChannel, {
		name: {
			value: name
		},
		endpointA: {
			value: Object.create(ep1, {
				description: {
					value: description1
				},
				implementation: {
					value: function* () {
						while (true) {
							let request =
								yield;

							requests.push(request);
						}
					}
				}
			})
		},
		endpointB: {
			value: Object.create(ep2, {
				description: {
					value: description2
				},
				implementation: {
					value: function* () {
						while (true) {
							let request = requests.shift();

							if (!request) {
								break;
							}

							yield request;
						}
					}
				}
			})
		}
	});
}

exports.create = create;
<commit_msg>logging<commit_after>/* jslint node: true, esnext: true */

"use strict";

const fifo = require('fifo');

/**
 *  Template for the Channel object
 */
const RootChannel = {
  toString: function () {
    return this.name;
  }
};

/*
 * create two endpoints glued together to form a channel
 * @return array with the two channles
 */
function create(ep1, ep2) {
  let requests = fifo();

  const name = `${ep1.name}-${ep2.name}`;
  const description1 = `Channel from ${ep1.name} to ${ep2.name}`;
  const description2 = `Channel from ${ep2.name} to ${ep1.name}`;

  return Object.create(RootChannel, {
    name: {
      value: name
    },
    endpointA: {
      value: Object.create(ep1, {
        description: {
          value: description1
        },
        implementation: {
          value: function* () {
            while (true) {
              let request =
                yield;

              console.log(`got request: ${name}: ${JSON.stringify(request.info)}`);
              requests.push(request);
            }
          }
        }
      })
    },
    endpointB: {
      value: Object.create(ep2, {
        description: {
          value: description2
        },
        implementation: {
          value: function* () {
            while (true) {
              let request = requests.shift();

              if (!request) {
                console.log(`provide request ${name}: *** nothing more to provide ***`);
                break;
              }

              console.log(`provide request ${name}: ${JSON.stringify(request.info)}`);

              yield request;
            }
          }
        }
      })
    }
  });
}

exports.create = create;
<|endoftext|>


<commit_before>function submitForm() {
  // Firebase ref
  var ref = new Firebase("https://dr-iqbal.firebaseio.com/"),
      nomor = new Firebase("https://dr-iqbal.firebaseio.com/no_antrian");

  // Today date's
  var date = new Date(),
      year = date.getFullYear(),
      month = date.getMonth() + 1,
      day = date.getDate(),
      right_now = year + '-' + month + '-' + day,
      today = ref.child(right_now);

  // Get input value
  var input = $('.input').val(),
      nama = $('#nama').val(),
      no_bpjs = $('#no_bpjs').val(),
      nik = $('#nik').val(),
      no_rujuk = $('#no_rujuk').val(),
      keluhan = $('#keluhan').val();

  // Validate user input
  if (input === '' || keluhan.length < 10 || nik.length != 16 || no_bpjs.length != 13 || no_rujuk.length != 20) {
    swal({
      title: "Input tidak valid",
      text: "Salah satu input anda tidak valid",
      type: "error"
    })
  } else {
      nomor.once('value', function(snapshot){
        if (snapshot.val() >= 40) {
          swal({
            title: "Kuota pasien sudah penuh",
            text: "Kuota pasien untuk hari ini sudah penuh" + "
" + "Cobalah mendaftar besok",
            type: "warning",
            html: true
          })
        } else {
            nomor.transaction(function(currentRank){
              update = currentRank + 1;

              return update;
            }, function(error, commited, snapshot){
              if (error) {
                swal({
                  title: "Gagal mengambil data",
                  text: "Gagal mengambil data, coba cek kembali koneksi anda",
                  type: "error"
                })
              } else {
                  swal({
                    title: "Terdaftar",
                    text: "Anda terdaftar pada: " + right_now,
                    type: "success",
                  }, function() {
                    location.reload();
                  })

                  today.push().set({
                    nama: nama,
                    no_bpjs: no_bpjs,
                    nik: nik,
                    no_rujuk: no_rujuk,
                    keluhan: keluhan,
                    date: date,
                    no_antri: snapshot.val()
                  })
                }
            })
        }
      })
    } // ./else
  }<commit_msg>Pushed data first<commit_after>function submitForm() {
  // Firebase ref
  var ref = new Firebase("https://dr-iqbal.firebaseio.com/"),
      nomor = new Firebase("https://dr-iqbal.firebaseio.com/no_antrian");

  // Today date's
  var date = new Date(),
      year = date.getFullYear(),
      month = date.getMonth() + 1,
      day = date.getDate(),
      right_now = year + '-' + month + '-' + day,
      today = ref.child(right_now);

  // Get input value
  var input = $('.input').val(),
      nama = $('#nama').val(),
      no_bpjs = $('#no_bpjs').val(),
      nik = $('#nik').val(),
      no_rujuk = $('#no_rujuk').val(),
      keluhan = $('#keluhan').val();

  // Validate user input
  if (input === '' || keluhan.length < 10 || nik.length != 16 || no_bpjs.length != 13 || no_rujuk.length != 20) {
    swal({
      title: "Input tidak valid",
      text: "Salah satu input anda tidak valid",
      type: "error"
    })
  } else {
      nomor.once('value', function(snapshot){
        if (snapshot.val() >= 40) {
          swal({
            title: "Kuota pasien sudah penuh",
            text: "Kuota pasien untuk hari ini sudah penuh" + "
" + "Cobalah mendaftar besok",
            type: "warning",
            html: true
          })
        } else {
            nomor.transaction(function(currentRank){
              update = currentRank + 1;

              return update;
            }, function(error, commited, snapshot){
              if (error) {
                swal({
                  title: "Gagal mengambil data",
                  text: "Gagal mengambil data, coba cek kembali koneksi anda",
                  type: "error"
                })
              } else {
                  today.push().set({
                    nama: nama,
                    no_bpjs: no_bpjs,
                    nik: nik,
                    no_rujuk: no_rujuk,
                    keluhan: keluhan,
                    date: date,
                    no_antri: snapshot.val()
                  })

                  swal({
                    title: "Terdaftar",
                    text: "Anda terdaftar pada: " + right_now,
                    type: "success",
                  }, function() {
                    location.reload();
                  })

                }
            })
        }
      })
    } // ./else
  }<|endoftext|>