text:
/*
 * SystemJS v0.8.1
 */

(function($__global) {

$__global.upgradeSystemLoader = function() {
  $__global.upgradeSystemLoader = undefined;

  // indexOf polyfill for IE
  var indexOf = Array.prototype.indexOf || function(item) {
    for (var i = 0, l = this.length; i < l; i++)
      if (this[i] === item)
        return i;
    return -1;
  }

  // Absolute URL parsing, from https://gist.github.com/Yaffle/1088850
  function parseURI(url) {
    var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
    // authority = '//' + user + ':' + pass '@' + hostname + ':' port
    return (m ? {
      href     : m[0] || '',
      protocol : m[1] || '',
      authority: m[2] || '',
      host     : m[3] || '',
      hostname : m[4] || '',
      port     : m[5] || '',
      pathname : m[6] || '',
      search   : m[7] || '',
      hash     : m[8] || ''
    } : null);
  }
  function toAbsoluteURL(base, href) {
    function removeDotSegments(input) {
      var output = [];
      input.replace(/^(\.\.?(\/|$))+/, '')
        .replace(/\/(\.(\/|$))+/g, '/')
        .replace(/\/\.\.$/, '/../')
        .replace(/\/?[^\/]*/g, function (p) {
          if (p === '/..')
            output.pop();
          else
            output.push(p);
      });
      return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
    }

    href = parseURI(href || '');
    base = parseURI(base || '');

    return !href || !base ? null : (href.protocol || base.protocol) +
      (href.protocol || href.authority ? href.authority : base.authority) +
      removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
      (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
      href.hash;
  }

  // clone the original System loader
  var System;
  (function() {
    var originalSystem = $__global.System;
    System = $__global.System = new LoaderPolyfill(originalSystem);
    System.baseURL = originalSystem.baseURL;
    System.paths = { '*': '*.js' };
    System.originalSystem = originalSystem;
  })();

  System.noConflict = function() {
    $__global.SystemJS = System;
    $__global.System = System.originalSystem;
  }

/*
 * Meta Extension
 *
 * Sets default metadata on a load record (load.metadata) from
 * loader.meta[moduleName].
 * Also provides an inline meta syntax for module meta in source.
 *
 * Eg:
 *
 * loader.meta['my/module'] = { some: 'meta' };
 *
 * load.metadata.some = 'meta' will now be set on the load record.
 *
 * The same meta could be set with a my/module.js file containing:
 *
 * my/module.js
 *   "some meta";
 *   "another meta";
 *   console.log('this is my/module');
 *
 * The benefit of inline meta is that coniguration doesn't need
 * to be known in advanced, which is useful for modularising
 * configuration and avoiding the need for configuration injection.
 *
 *
 * Example
 * -------
 *
 * The simplest meta example is setting the module format:
 *
 * System.meta['my/module'] = { format: 'amd' };
 *
 * or inside 'my/module.js':
 *
 * "format amd";
 * define(...);
 *
 */

function meta(loader) {
  var metaRegEx = /^(\s*\/\*.*\*\/|\s*\/\/[^\n]*|\s*"[^"]+"\s*;?|\s*'[^']+'\s*;?)+/;
  var metaPartRegEx = /\/\*.*\*\/|\/\/[^\n]*|"[^"]+"\s*;?|'[^']+'\s*;?/g;

  loader.meta = {};

  function setConfigMeta(loader, load) {
    var meta = loader.meta && loader.meta[load.name];
    if (meta) {
      for (var p in meta)
        load.metadata[p] = load.metadata[p] || meta[p];
    }
  }

  var loaderLocate = loader.locate;
  loader.locate = function(load) {
    setConfigMeta(this, load);
    return loaderLocate.call(this, load);
  }

  var loaderTranslate = loader.translate;
  loader.translate = function(load) {
    // detect any meta header syntax
    var meta = load.source.match(metaRegEx);
    if (meta) {
      var metaParts = meta[0].match(metaPartRegEx);
      for (var i = 0; i < metaParts.length; i++) {
        var len = metaParts[i].length;

        var firstChar = metaParts[i].substr(0, 1);
        if (metaParts[i].substr(len - 1, 1) == ';')
          len--;

        if (firstChar != '"' && firstChar != "'")
          continue;

        var metaString = metaParts[i].substr(1, metaParts[i].length - 3);

        var metaName = metaString.substr(0, metaString.indexOf(' '));
        if (metaName) {
          var metaValue = metaString.substr(metaName.length + 1, metaString.length - metaName.length - 1);

          if (load.metadata[metaName] instanceof Array)
            load.metadata[metaName].push(metaValue);
          else if (!load.metadata[metaName])
            load.metadata[metaName] = metaValue;
        }
      }
    }
    // config meta overrides
    setConfigMeta(this, load);

    return loaderTranslate.call(this, load);
  }
}/*
 * Instantiate registry extension
 *
 * Supports Traceur System.register 'instantiate' output for loading ES6 as ES5.
 *
 * - Creates the loader.register function
 * - Also supports metadata.format = 'register' in instantiate for anonymous register modules
 * - Also supports metadata.deps, metadata.execute and metadata.executingRequire
 *     for handling dynamic modules alongside register-transformed ES6 modules
 *
 * Works as a standalone extension, but benefits from having a more
 * advanced __eval defined like in SystemJS polyfill-wrapper-end.js
 *
 * The code here replicates the ES6 linking groups algorithm to ensure that
 * circular ES6 compiled into System.register can work alongside circular AMD
 * and CommonJS, identically to the actual ES6 loader.
 *
 */
function register(loader) {
  if (typeof indexOf == 'undefined')
    indexOf = Array.prototype.indexOf;
  if (typeof __eval == 'undefined')
    __eval = 0 || eval; // uglify breaks without the 0 ||

  // define exec for easy evaluation of a load record (load.name, load.source, load.address)
  // main feature is source maps support handling
  var curSystem;
  function exec(load) {
    var loader = this;
    if (load.name == '@traceur') {
      curSystem = System;
    }
    // support sourceMappingURL (efficiently)
    var sourceMappingURL;
    var lastLineIndex = load.source.lastIndexOf('\n');
    if (lastLineIndex != -1) {
      if (load.source.substr(lastLineIndex + 1, 21) == '//# sourceMappingURL=') {
        sourceMappingURL = load.source.substr(lastLineIndex + 22, load.source.length - lastLineIndex - 22);
        if (typeof toAbsoluteURL != 'undefined')
          sourceMappingURL = toAbsoluteURL(load.address, sourceMappingURL);
      }
    }

    __eval(load.source, load.address, sourceMappingURL);

    // traceur overwrites System and Module - write them back
    if (load.name == '@traceur') {
      loader.global.traceurSystem = loader.global.System;
      loader.global.System = curSystem;
    }
  }
  loader.__exec = exec;

  function dedupe(deps) {
    var newDeps = [];
    for (var i = 0, l = deps.length; i < l; i++)
      if (indexOf.call(newDeps, deps[i]) == -1)
        newDeps.push(deps[i])
    return newDeps;
  }

  /*
   * There are two variations of System.register:
   * 1. System.register for ES6 conversion (2-3 params) - System.register([name, ]deps, declare)
   *    see https://github.com/ModuleLoader/es6-module-loader/wiki/System.register-Explained
   *
   * 2. System.register for dynamic modules (3-4 params) - System.register([name, ]deps, executingRequire, execute)
   * the true or false statement
   *
   * this extension implements the linking algorithm for the two variations identical to the spec
   * allowing compiled ES6 circular references to work alongside AMD and CJS circular references.
   *
   */
  // loader.register sets loader.defined for declarative modules
  var anonRegister;
  var calledRegister;
  function register(name, deps, declare, execute) {
    if (typeof name != 'string') {
      execute = declare;
      declare = deps;
      deps = name;
      name = null;
    }

    calledRegister = true;

    var register;

    // dynamic
    if (typeof declare == 'boolean') {
      register = {
        declarative: false,
        deps: deps,
        execute: execute,
        executingRequire: declare
      };
    }
    else {
      // ES6 declarative
      if (deps.length > 0 && declare.length != 1)
        throw 'Invalid System.register form for ' + name + '. Declare function must take one argument.';
      register = {
        declarative: true,
        deps: deps,
        declare: declare
      };
    }

    // named register
    if (name) {
      register.name = name;
      // we never overwrite an existing define
      if (!loader.defined[name])
        loader.defined[name] = register;
    }
    // anonymous register
    else if (register.declarative) {
      if (anonRegister)
        throw 'Multiple anonymous System.register calls in the same module file.';
      anonRegister = register;
    }
  }
  /*
   * Registry side table - loader.defined
   * Registry Entry Contains:
   *    - name
   *    - deps
   *    - declare for declarative modules
   *    - execute for dynamic modules, different to declarative execute on module
   *    - executingRequire indicates require drives execution for circularity of dynamic modules
   *    - declarative optional boolean indicating which of the above
   *
   * Can preload modules directly on System.defined['my/module'] = { deps, execute, executingRequire }
   *
   * Then the entry gets populated with derived information during processing:
   *    - normalizedDeps derived from deps, created in instantiate
   *    - groupIndex used by group linking algorithm
   *    - evaluated indicating whether evaluation has happend
   *    - module the module record object, containing:
   *      - exports actual module exports
   *
   *    Then for declarative only we track dynamic bindings with the records:
   *      - name
   *      - setters declarative setter functions
   *      - exports actual module values
   *      - dependencies, module records of dependencies
   *      - importers, module records of dependents
   *
   * After linked and evaluated, entries are removed, declarative module records remain in separate
   * module binding table
   *
   */

  function defineRegister(loader) {
    if (loader.register)
      return;

    loader.register = register;

    if (!loader.defined)
      loader.defined = {};

    // script injection mode calls this function synchronously on load
    var onScriptLoad = loader.onScriptLoad;
    loader.onScriptLoad = function(load) {
      onScriptLoad(load);
      // anonymous define
      if (anonRegister)
        load.metadata.entry = anonRegister;

      if (anonRegister || calledRegister)
        load.metadata.format = load.metadata.format || 'register';
      if (calledRegister)
        load.metadata.registered = true;
    }
  }

  defineRegister(loader);

  function buildGroups(entry, loader, groups) {
    groups[entry.groupIndex] = groups[entry.groupIndex] || [];

    if (indexOf.call(groups[entry.groupIndex], entry) != -1)
      return;

    groups[entry.groupIndex].push(entry);

    for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) {
      var depName = entry.normalizedDeps[i];
      var depEntry = loader.defined[depName];

      // not in the registry means already linked / ES6
      if (!depEntry || depEntry.evaluated)
        continue;

      // now we know the entry is in our unlinked linkage group
      var depGroupIndex = entry.groupIndex + (depEntry.declarative != entry.declarative);

      // the group index of an entry is always the maximum
      if (depEntry.groupIndex === undefined || depEntry.groupIndex < depGroupIndex) {

        // if already in a group, remove from the old group
        if (depEntry.groupIndex) {
          groups[depEntry.groupIndex].splice(indexOf.call(groups[depEntry.groupIndex], depEntry), 1);

          // if the old group is empty, then we have a mixed depndency cycle
          if (groups[depEntry.groupIndex].length == 0)
            throw new TypeError("Mixed dependency cycle detected");
        }

        depEntry.groupIndex = depGroupIndex;
      }

      buildGroups(depEntry, loader, groups);
    }
  }

  function link(name, loader) {
    var startEntry = loader.defined[name];

    startEntry.groupIndex = 0;

    var groups = [];

    buildGroups(startEntry, loader, groups);

    var curGroupDeclarative = !!startEntry.declarative == groups.length % 2;
    for (var i = groups.length - 1; i >= 0; i--) {
      var group = groups[i];
      for (var j = 0; j < group.length; j++) {
        var entry = group[j];

        // link each group
        if (curGroupDeclarative)
          linkDeclarativeModule(entry, loader);
        else
          linkDynamicModule(entry, loader);
      }
      curGroupDeclarative = !curGroupDeclarative;
    }
  }

  // module binding records
  var moduleRecords = {};
  function getOrCreateModuleRecord(name) {
    return moduleRecords[name] || (moduleRecords[name] = {
      name: name,
      dependencies: [],
      exports: {}, // start from an empty module and extend
      importers: []
    })
  }

  function linkDeclarativeModule(entry, loader) {
    // only link if already not already started linking (stops at circular)
    if (entry.module)
      return;

    var module = entry.module = getOrCreateModuleRecord(entry.name);
    var exports = entry.module.exports;

    var declaration = entry.declare.call(loader.global, function(name, value) {
      module.locked = true;
      exports[name] = value;

      for (var i = 0, l = module.importers.length; i < l; i++) {
        var importerModule = module.importers[i];
        if (!importerModule.locked) {
          var importerIndex = indexOf.call(importerModule.dependencies, module);
          importerModule.setters[importerIndex](exports);
        }
      }

      module.locked = false;
      return value;
    });

    module.setters = declaration.setters;
    module.execute = declaration.execute;

    if (!module.setters || !module.execute) {
      throw "Invalid System.register form for " + entry.name;
    }

    // now link all the module dependencies
    for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) {
      var depName = entry.normalizedDeps[i];
      var depEntry = loader.defined[depName];
      var depModule = moduleRecords[depName];

      // work out how to set depExports based on scenarios...
      var depExports;

      if (depModule) {
        depExports = depModule.exports;
      }
      // dynamic, already linked in our registry
      else if (depEntry && !depEntry.declarative) {
        depExports = { 'default': depEntry.module.exports, '__useDefault': true };
      }
      // in the loader registry
      else if (!depEntry) {
        depExports = loader.get(depName);
      }
      // we have an entry -> link
      else {
        linkDeclarativeModule(depEntry, loader);
        depModule = depEntry.module;
        depExports = depModule.exports;
      }

      // only declarative modules have dynamic bindings
      if (depModule && depModule.importers) {
        depModule.importers.push(module);
        module.dependencies.push(depModule);
      }
      else {
        module.dependencies.push(null);
      }

      // run the setter for this dependency
      if (module.setters[i])
        module.setters[i](depExports);
    }
  }

  // An analog to loader.get covering execution of all three layers (real declarative, simulated declarative, simulated dynamic)
  function getModule(name, loader) {
    var exports;
    var entry = loader.defined[name];

    if (!entry) {
      exports = loader.get(name);
      if (!exports)
        throw "System Register: The module requested " + name + " but this was not declared as a dependency";
      if (exports.__useDefault)
        exports = exports['default'];
    }

    else {
      if (entry.declarative)
        ensureEvaluated(name, [], loader);

      else if (!entry.evaluated)
        linkDynamicModule(entry, loader);

      exports = entry.module.exports;
    }

    return exports;
  }

  function linkDynamicModule(entry, loader) {
    if (entry.module)
      return;

    var exports = {};

    var module = entry.module = { exports: exports, id: entry.name };

    // AMD requires execute the tree first
    if (!entry.executingRequire) {
      for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) {
        var depName = entry.normalizedDeps[i];
        var depEntry = loader.defined[depName];
        if (depEntry)
          linkDynamicModule(depEntry, loader);
      }
    }

    // now execute
    entry.evaluated = true;
    var output = entry.execute.call(loader.global, function(name) {
      for (var i = 0, l = entry.deps.length; i < l; i++) {
        if (entry.deps[i] != name)
          continue;
        return getModule(entry.normalizedDeps[i], loader);
      }
    }, exports, module);

    if (output)
      module.exports = output;
  }

  /*
   * Given a module, and the list of modules for this current branch,
   *  ensure that each of the dependencies of this module is evaluated
   *  (unless one is a circular dependency already in the list of seen
   *  modules, in which case we execute it)
   *
   * Then we evaluate the module itself depth-first left to right
   * execution to match ES6 modules
   */
  function ensureEvaluated(moduleName, seen, loader) {
    var entry = loader.defined[moduleName];

    // if already seen, that means it's an already-evaluated non circular dependency
    if (entry.evaluated || !entry.declarative)
      return;

    // this only applies to declarative modules which late-execute

    seen.push(moduleName);

    for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) {
      var depName = entry.normalizedDeps[i];
      if (indexOf.call(seen, depName) == -1) {
        if (!loader.defined[depName])
          loader.get(depName);
        else
          ensureEvaluated(depName, seen, loader);
      }
    }

    if (entry.evaluated)
      return;

    entry.evaluated = true;
    entry.module.execute.call(loader.global);
  }

  var registerRegEx = /System\.register/;

  var loaderFetch = loader.fetch;
  loader.fetch = function(load) {
    var loader = this;
    defineRegister(loader);
    if (loader.defined[load.name]) {
      load.metadata.format = 'defined';
      return '';
    }
    anonRegister = null;
    calledRegister = false;
    // the above get picked up by onScriptLoad
    return loaderFetch.call(loader, load);
  }

  var loaderTranslate = loader.translate;
  loader.translate = function(load) {
    this.register = register;

    this.__exec = exec;

    load.metadata.deps = load.metadata.deps || [];

    // we run the meta detection here (register is after meta)
    return Promise.resolve(loaderTranslate.call(this, load)).then(function(source) {

      // dont run format detection for globals shimmed
      // ideally this should be in the global extension, but there is
      // currently no neat way to separate it
      if (load.metadata.init || load.metadata.exports)
        load.metadata.format = load.metadata.format || 'global';

      // run detection for register format
      if (load.metadata.format == 'register' || !load.metadata.format && load.source.match(registerRegEx))
        load.metadata.format = 'register';
      return source;
    });
  }

  var loaderInstantiate = loader.instantiate;
  loader.instantiate = function(load) {
    var loader = this;

    var entry;

    // first we check if this module has already been defined in the registry
    if (loader.defined[load.name])
      entry = loader.defined[load.name];

    // picked up already by a script injection
    else if (load.metadata.entry)
      entry = load.metadata.entry;

    // otherwise check if it is dynamic
    else if (load.metadata.execute) {
      entry = {
        declarative: false,
        deps: load.metadata.deps || [],
        execute: load.metadata.execute,
        executingRequire: load.metadata.executingRequire // NodeJS-style requires or not
      };
    }

    // Contains System.register calls
    else if (load.metadata.format == 'register') {
      anonRegister = null;
      calledRegister = false;

      var System = loader.global.System = loader.global.System || loader;

      var curRegister = System.register;
      System.register = register;

      loader.__exec(load);

      System.register = curRegister;

      if (anonRegister)
        entry = anonRegister;

      if (!calledRegister && !load.metadata.registered)
        throw load.name + " detected as System.register but didn't execute.";
    }

    // named bundles are just an empty module
    if (!entry && load.metadata.format != 'es6')
      return {
        deps: [],
        execute: function() {
          return loader.newModule({});
        }
      };

    // place this module onto defined for circular references
    if (entry)
      loader.defined[load.name] = entry;

    // no entry -> treat as ES6
    else
      return loaderInstantiate.call(this, load);

    entry.deps = dedupe(entry.deps);
    entry.name = load.name;

    // first, normalize all dependencies
    var normalizePromises = [];
    for (var i = 0, l = entry.deps.length; i < l; i++)
      normalizePromises.push(Promise.resolve(loader.normalize(entry.deps[i], load.name)));

    return Promise.all(normalizePromises).then(function(normalizedDeps) {

      entry.normalizedDeps = normalizedDeps;

      return {
        deps: entry.deps,
        execute: function() {
          // recursively ensure that the module and all its
          // dependencies are linked (with dependency group handling)
          link(load.name, loader);

          // now handle dependency execution in correct order
          ensureEvaluated(load.name, [], loader);

          // remove from the registry
          loader.defined[load.name] = undefined;

          var module = loader.newModule(entry.declarative ? entry.module.exports : { 'default': entry.module.exports, '__useDefault': true });
          entry.module.module = module;

          // return the defined module object
          return module;
        }
      };
    });
  }
}
/*
 * SystemJS Core
 * Code should be vaguely readable
 *
 */
function core(loader) {

  /*
    __useDefault

    When a module object looks like:
    newModule({
      __useDefault: true,
      default: 'some-module'
    })

    Then importing that module provides the 'some-module'
    result directly instead of the full module.

    Useful for eg module.exports = function() {}
  */
  var loaderImport = loader['import'];
  loader['import'] = function(name, options) {
    return loaderImport.call(this, name, options).then(function(module) {
      return module.__useDefault ? module['default'] : module;
    });
  }

  // support the empty module, as a concept
  loader.set('@empty', loader.newModule({}));

  /*
    Config
    Extends config merging one deep only

    loader.config({
      some: 'random',
      config: 'here',
      deep: {
        config: { too: 'too' }
      }
    });

    <=>

    loader.some = 'random';
    loader.config = 'here'
    loader.deep = loader.deep || {};
    loader.deep.config = { too: 'too' };
  */
  loader.config = function(cfg) {
    for (var c in cfg) {
      var v = cfg[c];
      if (typeof v == 'object' && !(v instanceof Array)) {
        this[c] = this[c] || {};
        for (var p in v)
          this[c][p] = v[p];
      }
      else
        this[c] = v;
    }
  }

  // override locate to allow baseURL to be document-relative
  var baseURI;
  if (typeof window == 'undefined' &&
      typeof WorkerGlobalScope == 'undefined') {
    baseURI = process.cwd() + '/';
  }
  // Inside of a Web Worker
  else if(typeof window == 'undefined') {
    baseURI = loader.global.location.href;
  }
  else {
    baseURI = document.baseURI;
    if (!baseURI) {
      var bases = document.getElementsByTagName('base');
      baseURI = bases[0] && bases[0].href || window.location.href;
    }
  }

  var loaderLocate = loader.locate;
  var normalizedBaseURL;
  loader.locate = function(load) {
    if (this.baseURL != normalizedBaseURL) {
      normalizedBaseURL = toAbsoluteURL(baseURI, this.baseURL);

      if (normalizedBaseURL.substr(normalizedBaseURL.length - 1, 1) != '/')
        normalizedBaseURL += '/';
      this.baseURL = normalizedBaseURL;
    }

    return Promise.resolve(loaderLocate.call(this, load));
  }

  // Traceur conveniences
  var aliasRegEx = /^\s*export\s*\*\s*from\s*(?:'([^']+)'|"([^"]+)")/;
  var es6RegEx = /(?:^\s*|[}{\(\);,\n]\s*)(import\s+['"]|(import|module)\s+[^"'\(\)\n;]+\s+from\s+['"]|export\s+(\*|\{|default|function|var|const|let|[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*))/;

  var loaderTranslate = loader.translate;
  loader.translate = function(load) {
    var loader = this;

    if (load.name == '@traceur')
      return loaderTranslate.call(loader, load);

    // support ES6 alias modules ("export * from 'module';") without needing Traceur
    var match;
    if ((load.metadata.format == 'es6' || !load.metadata.format) && (match = load.source.match(aliasRegEx))) {
      load.metadata.format = 'cjs';
      load.source = 'module.exports = require("' + (match[1] || match[2]) + '");\n';
    }

    // detect ES6
    else if (load.metadata.format == 'es6' || !load.metadata.format && load.source.match(es6RegEx)) {
      load.metadata.format = 'es6';

      // dynamically load Traceur for ES6 if necessary
      if (!loader.global.traceur) {
        return loader['import']('@traceur').then(function() {
          return loaderTranslate.call(loader, load);
        });
      }
    }

    return loaderTranslate.call(loader, load);
  }

  // always load Traceur as a global
  var loaderInstantiate = loader.instantiate;
  loader.instantiate = function(load) {
    var loader = this;
    if (load.name == '@traceur') {
      loader.__exec(load);
      return {
        deps: [],
        execute: function() {
          return loader.newModule({});
        }
      };
    }
    return loaderInstantiate.call(loader, load);
  }
}
/*
  SystemJS Global Format

  Supports
    metadata.deps
    metadata.init
    metadata.exports

  Also detects writes to the global object avoiding global collisions.
  See the SystemJS readme global support section for further information.
*/
function global(loader) {
  function createHelpers(loader) {
    if (loader.has('@@global-helpers'))
      return;

    var hasOwnProperty = loader.global.hasOwnProperty;
    var moduleGlobals = {};

    var curGlobalObj;
    var ignoredGlobalProps;

    loader.set('@@global-helpers', loader.newModule({
      prepareGlobal: function(moduleName, deps) {
        // first, we add all the dependency modules to the global
        for (var i = 0; i < deps.length; i++) {
          var moduleGlobal = moduleGlobals[deps[i]];
          if (moduleGlobal)
            for (var m in moduleGlobal)
              loader.global[m] = moduleGlobal[m];
        }

        // now store a complete copy of the global object
        // in order to detect changes
        curGlobalObj = {};
        ignoredGlobalProps = ['indexedDB', 'sessionStorage', 'localStorage', 'clipboardData', 'frames', 'webkitStorageInfo'];
        for (var g in loader.global) {
          if (indexOf.call(ignoredGlobalProps, g) != -1) { continue; }
          if (!hasOwnProperty || loader.global.hasOwnProperty(g)) {
            try {
              curGlobalObj[g] = loader.global[g];
            } catch (e) {
              ignoredGlobalProps.push(g);
            }
          }
        }
      },
      retrieveGlobal: function(moduleName, exportName, init) {
        var singleGlobal;
        var multipleExports;
        var exports = {};

        // run init
        if (init) {
          var depModules = [];
          for (var i = 0; i < deps.length; i++)
            depModules.push(require(deps[i]));
          singleGlobal = init.apply(loader.global, depModules);
        }

        // check for global changes, creating the globalObject for the module
        // if many globals, then a module object for those is created
        // if one global, then that is the module directly
        else if (exportName) {
          var firstPart = exportName.split('.')[0];
          singleGlobal = eval.call(loader.global, exportName);
          exports[firstPart] = loader.global[firstPart];
        }

        else {
          for (var g in loader.global) {
            if (indexOf.call(ignoredGlobalProps, g) != -1)
              continue;
            if ((!hasOwnProperty || loader.global.hasOwnProperty(g)) && g != loader.global && curGlobalObj[g] != loader.global[g]) {
              exports[g] = loader.global[g];
              if (singleGlobal) {
                if (singleGlobal !== loader.global[g])
                  multipleExports = true;
              }
              else if (singleGlobal !== false) {
                singleGlobal = loader.global[g];
              }
            }
          }
        }

        moduleGlobals[moduleName] = exports;

        return multipleExports ? exports : singleGlobal;
      }
    }));
  }

  createHelpers(loader);

  var loaderInstantiate = loader.instantiate;
  loader.instantiate = function(load) {
    var loader = this;

    createHelpers(loader);

    var exportName = load.metadata.exports;

    if (!load.metadata.format)
      load.metadata.format = 'global';

    // global is a fallback module format
    if (load.metadata.format == 'global') {
      load.metadata.execute = function(require, exports, module) {

        loader.get('@@global-helpers').prepareGlobal(module.id, load.metadata.deps);

        if (exportName)
          load.source += '\nthis["' + exportName + '"] = ' + exportName + ';';

        // disable AMD detection
        var define = loader.global.define;
        loader.global.define = undefined;

        // ensure no NodeJS environment detection
        loader.global.module = undefined;
        loader.global.exports = undefined;

        loader.__exec(load);

        loader.global.define = define;

        return loader.get('@@global-helpers').retrieveGlobal(module.id, exportName, load.metadata.init);
      }
    }
    return loaderInstantiate.call(loader, load);
  }
}
/*
  SystemJS CommonJS Format
*/
function cjs(loader) {

  // CJS Module Format
  // require('...') || exports[''] = ... || exports.asd = ... || module.exports = ...
  var cjsExportsRegEx = /(?:^\s*|[}{\(\);,\n=:\?\&]\s*|module\.)(exports\s*\[\s*('[^']+'|"[^"]+")\s*\]|\exports\s*\.\s*[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*|exports\s*\=)/;
  var cjsRequireRegEx = /(?:^\s*|[}{\(\);,\n=:\?\&]\s*)require\s*\(\s*("([^"]+)"|'([^']+)')\s*\)/g;
  var commentRegEx = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg;

  function getCJSDeps(source) {
    cjsExportsRegEx.lastIndex = 0;
    cjsRequireRegEx.lastIndex = 0;

    var deps = [];

    // remove comments from the source first
    var source = source.replace(commentRegEx, '');

    var match;

    while (match = cjsRequireRegEx.exec(source))
      deps.push(match[2] || match[3]);

    return deps;
  }

  var loaderInstantiate = loader.instantiate;
  loader.instantiate = function(load) {

    if (!load.metadata.format) {
      cjsExportsRegEx.lastIndex = 0;
      cjsRequireRegEx.lastIndex = 0;
      if (cjsRequireRegEx.exec(load.source) || cjsExportsRegEx.exec(load.source))
        load.metadata.format = 'cjs';
    }

    if (load.metadata.format == 'cjs') {
      load.metadata.deps = load.metadata.deps ? load.metadata.deps.concat(getCJSDeps(load.source)) : load.metadata.deps;

      load.metadata.executingRequire = true;

      load.metadata.execute = function(require, exports, module) {
        var dirname = (load.address || '').split('/');
        dirname.pop();
        dirname = dirname.join('/');

        var globals = loader.global._g = {
          global: loader.global,
          exports: exports,
          module: module,
          require: require,
          __filename: load.address,
          __dirname: dirname
        };

        var source = '(function(global, exports, module, require, __filename, __dirname) { ' + load.source
          + '\n}).call(_g.exports, _g.global, _g.exports, _g.module, _g.require, _g.__filename, _g.__dirname);';

        // disable AMD detection
        var define = loader.global.define;
        loader.global.define = undefined;

        loader.__exec({
          name: load.name,
          address: load.address,
          source: source
        });

        loader.global.define = define;

        loader.global._g = undefined;
      }
    }

    return loaderInstantiate.call(this, load);
  };
}/*
  SystemJS AMD Format
  Provides the AMD module format definition at System.format.amd
  as well as a RequireJS-style require on System.require
*/
function amd(loader) {
  // by default we only enforce AMD noConflict mode in Node
  var isNode = typeof module != 'undefined' && module.exports;

  // AMD Module Format Detection RegEx
  // define([.., .., ..], ...)
  // define(varName); || define(function(require, exports) {}); || define({})
  var amdRegEx = /(?:^\s*|[}{\(\);,\n\?\&]\s*)define\s*\(\s*("[^"]+"\s*,\s*|'[^']+'\s*,\s*)?\s*(\[(\s*(("[^"]+"|'[^']+')\s*,|\/\/.*\r?\n|\/\*(.|\s)*?\*\/))*(\s*("[^"]+"|'[^']+')\s*,?)?(\s*(\/\/.*\r?\n|\/\*(.|\s)*?\*\/))*\s*\]|function\s*|{|[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*\))/;
  var commentRegEx = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg;

  var cjsRequirePre = "(?:^\\s*|[}{\\(\\);,\\n=:\\?\\&]\\s*)";
  var cjsRequirePost = "\\s*\\(\\s*(\"([^\"]+)\"|'([^']+)')\\s*\\)";

  var fnBracketRegEx = /\(([^\)]*)\)/;

  var wsRegEx = /^\s+|\s+$/g;

  var requireRegExs = {};

  function getCJSDeps(source, requireIndex) {

    // remove comments
    source = source.replace(commentRegEx, '');

    // determine the require alias
    var params = source.match(fnBracketRegEx);
    var requireAlias = (params[1].split(',')[requireIndex] || 'require').replace(wsRegEx, '');

    // find or generate the regex for this requireAlias
    var requireRegEx = requireRegExs[requireAlias] || (requireRegExs[requireAlias] = new RegExp(cjsRequirePre + requireAlias + cjsRequirePost, 'g'));

    requireRegEx.lastIndex = 0;

    var deps = [];

    var match;
    while (match = requireRegEx.exec(source))
      deps.push(match[2] || match[3]);

    return deps;
  }

  /*
    AMD-compatible require
    To copy RequireJS, set window.require = window.requirejs = loader.amdRequire
  */
  function require(names, callback, errback, referer) {
    // 'this' is bound to the loader
    var loader = this;

    // in amd, first arg can be a config object... we just ignore
    if (typeof names == 'object' && !(names instanceof Array))
      return require.apply(null, Array.prototype.splice.call(arguments, 1, arguments.length - 1));

    // amd require
    if (names instanceof Array)
      Promise.all(names.map(function(name) {
        return loader['import'](name, referer);
      })).then(function(modules) {
        callback.apply(null, modules);
      }, errback);

    // commonjs require
    else if (typeof names == 'string') {
      var module = loader.get(names);
      return module.__useDefault ? module['default'] : module;
    }

    else
      throw 'Invalid require';
  };
  loader.amdRequire = require;

  function makeRequire(parentName, staticRequire, loader) {
    return function(names, callback, errback) {
      if (typeof names == 'string')
        return staticRequire(names);
      return require.call(loader, names, callback, errback, { name: parentName });
    }
  }

  // run once per loader
  function generateDefine(loader) {
    // script injection mode calls this function synchronously on load
    var onScriptLoad = loader.onScriptLoad;
    loader.onScriptLoad = function(load) {
      onScriptLoad(load);
      if (anonDefine || defineBundle)
        load.metadata.format = 'defined';

      if (anonDefine) {
        load.metadata.deps = load.metadata.deps ? load.metadata.deps.concat(anonDefine.deps) : anonDefine.deps;
        load.metadata.execute = anonDefine.execute;
      }
    }

    function define(name, deps, factory) {
      if (typeof name != 'string') {
        factory = deps;
        deps = name;
        name = null;
      }
      if (!(deps instanceof Array)) {
        factory = deps;
        deps = ['require', 'exports', 'module'];
      }

      if (typeof factory != 'function')
        factory = (function(factory) {
          return function() { return factory; }
        })(factory);

      // in IE8, a trailing comma becomes a trailing undefined entry
      if (deps[deps.length - 1] === undefined)
        deps.pop();

      // remove system dependencies
      var requireIndex, exportsIndex, moduleIndex;

      if ((requireIndex = indexOf.call(deps, 'require')) != -1) {

        deps.splice(requireIndex, 1);

        var factoryText = factory.toString();

        deps = deps.concat(getCJSDeps(factoryText, requireIndex));
      }

      if ((exportsIndex = indexOf.call(deps, 'exports')) != -1)
        deps.splice(exportsIndex, 1);

      if ((moduleIndex = indexOf.call(deps, 'module')) != -1)
        deps.splice(moduleIndex, 1);

      var define = {
        deps: deps,
        execute: function(require, exports, module) {

          var depValues = [];
          for (var i = 0; i < deps.length; i++)
            depValues.push(require(deps[i]));

          module.uri = loader.baseURL + module.id;

          module.config = function() {};

          // add back in system dependencies
          if (moduleIndex != -1)
            depValues.splice(moduleIndex, 0, module);

          if (exportsIndex != -1)
            depValues.splice(exportsIndex, 0, exports);

          if (requireIndex != -1)
            depValues.splice(requireIndex, 0, makeRequire(module.id, require, loader));

          var output = factory.apply(global, depValues);

          if (typeof output == 'undefined' && module)
            output = module.exports;

          if (typeof output != 'undefined')
            return output;
        }
      };

      // anonymous define
      if (!name) {
        // already defined anonymously -> throw
        if (anonDefine)
          throw "Multiple defines for anonymous module";
        anonDefine = define;
      }
      // named define
      else {
        // if it has no dependencies and we don't have any other
        // defines, then let this be an anonymous define
        if (deps.length == 0 && !anonDefine && !defineBundle)
          anonDefine = define;

        // otherwise its a bundle only
        else
          anonDefine = null;

        // the above is just to support single modules of the form:
        // define('jquery')
        // still loading anonymously
        // because it is done widely enough to be useful

        // note this is now a bundle
        defineBundle = true;

        // define the module through the register registry
        loader.register(name, define.deps, false, define.execute);
      }
    };
    define.amd = {};
    loader.amdDefine = define;
  }

  var anonDefine;
  // set to true if the current module turns out to be a named define bundle
  var defineBundle;

  var oldModule, oldExports, oldDefine;

  // adds define as a global (potentially just temporarily)
  function createDefine(loader) {
    if (!loader.amdDefine)
      generateDefine(loader);

    anonDefine = null;
    defineBundle = null;

    // ensure no NodeJS environment detection
    var global = loader.global;

    oldModule = global.module;
    oldExports = global.exports;
    oldDefine = global.define;

    global.module = undefined;
    global.exports = undefined;

    if (global.define && global.define === loader.amdDefine)
      return;

    global.define = loader.amdDefine;
  }

  function removeDefine(loader) {
    var global = loader.global;
    global.define = oldDefine;
    global.module = oldModule;
    global.exports = oldExports;
  }

  generateDefine(loader);

  if (loader.scriptLoader) {
    var loaderFetch = loader.fetch;
    loader.fetch = function(load) {
      createDefine(this);
      return loaderFetch.call(this, load);
    }
  }

  var loaderInstantiate = loader.instantiate;
  loader.instantiate = function(load) {
    var loader = this;

    if (load.metadata.format == 'amd' || !load.metadata.format && load.source.match(amdRegEx)) {
      load.metadata.format = 'amd';

      createDefine(loader);

      try {
        loader.__exec(load);
      }
      catch(e) {
        if (loader.execute === false && isNode) {
          // use a regular expression to pull out deps
          var match = load.source.match(amdRegEx);
          if (match) {
            // named or anonymous
            if (match[1] && match[1][0] == '[')
              define(match[1].substr(match[1].length - 2), eval(match[2]), function() {});
            else if (match[2] && match[2][0] == '[')
              define(eval(match[2]), function() {});
            else
              define(function() {});
          }
        }
        else
          throw e;
      }

      removeDefine(loader);

      if (!anonDefine && !defineBundle && !isNode)
        throw "AMD module " + load.name + " did not define";

      if (anonDefine) {
        load.metadata.deps = load.metadata.deps ? load.metadata.deps.concat(anonDefine.deps) : anonDefine.deps;
        load.metadata.execute = anonDefine.execute;
      }
    }

    return loaderInstantiate.call(loader, load);
  }
}
/*
  SystemJS map support

  Provides map configuration through
    System.map['jquery'] = 'some/module/map'

  As well as contextual map config through
    System.map['bootstrap'] = {
      jquery: 'some/module/map2'
    }

  Note that this applies for subpaths, just like RequireJS

  jquery      -> 'some/module/map'
  jquery/path -> 'some/module/map/path'
  bootstrap   -> 'bootstrap'

  Inside any module name of the form 'bootstrap' or 'bootstrap/*'
    jquery    -> 'some/module/map2'
    jquery/p  -> 'some/module/map2/p'

  Maps are carefully applied from most specific contextual map, to least specific global map
*/
function map(loader) {
  loader.map = loader.map || {};

  // return if prefix parts (separated by '/') match the name
  // eg prefixMatch('jquery/some/thing', 'jquery') -> true
  //    prefixMatch('jqueryhere/', 'jquery') -> false
  function prefixMatch(name, prefix) {
    if (name.length < prefix.length)
      return false;
    if (name.substr(0, prefix.length) != prefix)
      return false;
    if (name[prefix.length] && name[prefix.length] != '/')
      return false;
    return true;
  }

  // get the depth of a given path
  // eg pathLen('some/name') -> 2
  function pathLen(name) {
    var len = 1;
    for (var i = 0, l = name.length; i < l; i++)
      if (name[i] === '/')
        len++;
    return len;
  }

  function doMap(name, matchLen, map) {
    return map + name.substr(matchLen);
  }

  // given a relative-resolved module name and normalized parent name,
  // apply the map configuration
  function applyMap(name, parentName, loader) {
    var curMatch, curMatchLength = 0;
    var curParent, curParentMatchLength = 0;
    var tmpParentLength, tmpPrefixLength;
    var subPath;
    var nameParts;

    // first find most specific contextual match
    if (parentName) {
      for (var p in loader.map) {
        var curMap = loader.map[p];
        if (typeof curMap != 'object')
          continue;

        // most specific parent match wins first
        if (!prefixMatch(parentName, p))
          continue;

        tmpParentLength = pathLen(p);
        if (tmpParentLength <= curParentMatchLength)
          continue;

        for (var q in curMap) {
          // most specific name match wins
          if (!prefixMatch(name, q))
            continue;
          tmpPrefixLength = pathLen(q);
          if (tmpPrefixLength <= curMatchLength)
            continue;

          curMatch = q;
          curMatchLength = tmpPrefixLength;
          curParent = p;
          curParentMatchLength = tmpParentLength;
        }
      }
    }

    // if we found a contextual match, apply it now
    if (curMatch)
      return doMap(name, curMatch.length, loader.map[curParent][curMatch]);

    // now do the global map
    for (var p in loader.map) {
      var curMap = loader.map[p];
      if (typeof curMap != 'string')
        continue;

      if (!prefixMatch(name, p))
        continue;

      var tmpPrefixLength = pathLen(p);

      if (tmpPrefixLength <= curMatchLength)
        continue;

      curMatch = p;
      curMatchLength = tmpPrefixLength;
    }

    if (curMatch)
      return doMap(name, curMatch.length, loader.map[curMatch]);

    return name;
  }

  var loaderNormalize = loader.normalize;
  loader.normalize = function(name, parentName, parentAddress) {
    var loader = this;
    if (!loader.map)
      loader.map = {};

    var isPackage = false;
    if (name.substr(name.length - 1, 1) == '/') {
      isPackage = true;
      name += '#';
    }

    return Promise.resolve(loaderNormalize.call(loader, name, parentName, parentAddress))
    .then(function(name) {
      name = applyMap(name, parentName, loader);

      // Normalize "module/" into "module/module"
      // Convenient for packages
      if (isPackage) {
        var nameParts = name.split('/');
        nameParts.pop();
        var pkgName = nameParts.pop();
        nameParts.push(pkgName);
        nameParts.push(pkgName);
        name = nameParts.join('/');
      }

      return name;
    });
  }
}
/*
  SystemJS Plugin Support

  Supports plugin syntax with "!"

  The plugin name is loaded as a module itself, and can override standard loader hooks
  for the plugin resource. See the plugin section of the systemjs readme.
*/
function plugins(loader) {
  if (typeof indexOf == 'undefined')
    indexOf = Array.prototype.indexOf;

  var loaderNormalize = loader.normalize;
  loader.normalize = function(name, parentName, parentAddress) {
    var loader = this;
    // if parent is a plugin, normalize against the parent plugin argument only
    var parentPluginIndex;
    if (parentName && (parentPluginIndex = parentName.indexOf('!')) != -1)
      parentName = parentName.substr(0, parentPluginIndex);

    return Promise.resolve(loaderNormalize.call(loader, name, parentName, parentAddress))
    .then(function(name) {
      // if this is a plugin, normalize the plugin name and the argument
      var pluginIndex = name.lastIndexOf('!');
      if (pluginIndex != -1) {
        var argumentName = name.substr(0, pluginIndex);

        // plugin name is part after "!" or the extension itself
        var pluginName = name.substr(pluginIndex + 1) || argumentName.substr(argumentName.lastIndexOf('.') + 1);

        // normalize the plugin name relative to the same parent
        return new Promise(function(resolve) {
          resolve(loader.normalize(pluginName, parentName, parentAddress));
        })
        // normalize the plugin argument
        .then(function(_pluginName) {
          pluginName = _pluginName;
          return loader.normalize(argumentName, parentName, parentAddress);
        })
        .then(function(argumentName) {
          return argumentName + '!' + pluginName;
        });
      }

      // standard normalization
      return name;
    });
  }

  var loaderLocate = loader.locate;
  loader.locate = function(load) {
    var loader = this;

    var name = load.name;

    // plugin
    var pluginIndex = name.lastIndexOf('!');
    if (pluginIndex != -1) {
      var pluginName = name.substr(pluginIndex + 1);

      // the name to locate is the plugin argument only
      load.name = name.substr(0, pluginIndex);

      var pluginLoader = loader.pluginLoader || loader;

      // load the plugin module
      // NB ideally should use pluginLoader.load for normalized,
      //    but not currently working for some reason
      return pluginLoader['import'](pluginName)
      .then(function() {
        var plugin = pluginLoader.get(pluginName);
        plugin = plugin['default'] || plugin;

        // allow plugins to opt-out of build
        if (plugin.build === false && loader.pluginLoader)
          load.metadata.build = false;

        // store the plugin module itself on the metadata
        load.metadata.plugin = plugin;
        load.metadata.pluginName = pluginName;
        load.metadata.pluginArgument = load.name;

        // run plugin locate if given
        if (plugin.locate)
          return plugin.locate.call(loader, load);

        // otherwise use standard locate without '.js' extension adding
        else
          return Promise.resolve(loader.locate(load))
          .then(function(address) {
            return address.substr(0, address.length - 3);
          });
      });
    }

    return loaderLocate.call(this, load);
  }

  var loaderFetch = loader.fetch;
  loader.fetch = function(load) {
    var loader = this;
    if (load.metadata.build === false)
      return '';
    else if (load.metadata.plugin && load.metadata.plugin.fetch && !load.metadata.pluginFetchCalled) {
      load.metadata.pluginFetchCalled = true;
      return load.metadata.plugin.fetch.call(loader, load, loaderFetch);
    }
    else
      return loaderFetch.call(loader, load);
  }

  var loaderTranslate = loader.translate;
  loader.translate = function(load) {
    var loader = this;
    if (load.metadata.plugin && load.metadata.plugin.translate)
      return Promise.resolve(load.metadata.plugin.translate.call(loader, load)).then(function(result) {
        if (result)
          load.source = result;
        return loaderTranslate.call(loader, load);
      });
    else
      return loaderTranslate.call(loader, load);
  }

  var loaderInstantiate = loader.instantiate;
  loader.instantiate = function(load) {
    var loader = this;
    if (load.metadata.plugin && load.metadata.plugin.instantiate)
      return Promise.resolve(load.metadata.plugin.instantiate.call(loader, load)).then(function(result) {
        load.metadata.format = 'defined';
        load.metadata.execute = function() {
          return result;
        };
        return loaderInstantiate.call(loader, load);
      });
    else if (load.metadata.plugin && load.metadata.plugin.build === false) {
      load.metadata.format = 'defined';
      load.metadata.deps.push(load.metadata.pluginName);
      load.metadata.execute = function() {
        return loader.newModule({});
      };
      return loaderInstantiate.call(loader, load);
    }
    else
      return loaderInstantiate.call(loader, load);
  }

}/*
  System bundles

  Allows a bundle module to be specified which will be dynamically
  loaded before trying to load a given module.

  For example:
  System.bundles['mybundle'] = ['jquery', 'bootstrap/js/bootstrap']

  Will result in a load to "mybundle" whenever a load to "jquery"
  or "bootstrap/js/bootstrap" is made.

  In this way, the bundle becomes the request that provides the module
*/

function bundles(loader) {
  if (typeof indexOf == 'undefined')
    indexOf = Array.prototype.indexOf;

  // bundles support (just like RequireJS)
  // bundle name is module name of bundle itself
  // bundle is array of modules defined by the bundle
  // when a module in the bundle is requested, the bundle is loaded instead
  // of the form System.bundles['mybundle'] = ['jquery', 'bootstrap/js/bootstrap']
  loader.bundles = loader.bundles || {};

  var loaderFetch = loader.fetch;
  loader.fetch = function(load) {
    var loader = this;
    if (loader.trace)
      return loaderFetch.call(this, load);
    if (!loader.bundles)
      loader.bundles = {};

    // if this module is in a bundle, load the bundle first then
    for (var b in loader.bundles) {
      if (indexOf.call(loader.bundles[b], load.name) == -1)
        continue;
      // we do manual normalization in case the bundle is mapped
      // this is so we can still know the normalized name is a bundle
      return Promise.resolve(loader.normalize(b))
      .then(function(normalized) {
        loader.bundles[normalized] = loader.bundles[normalized] || loader.bundles[b];

        // note this module is a bundle in the meta
        loader.meta = loader.meta || {};
        loader.meta[normalized] = loader.meta[normalized] || {};
        loader.meta[normalized].bundle = true;

        return loader.load(normalized);
      })
      .then(function() {
        return '';
      });
    }
    return loaderFetch.call(this, load);
  }
}/*
  SystemJS Semver Version Addon

  1. Uses Semver convention for major and minor forms

  Supports requesting a module from a package that contains a version suffix
  with the following semver ranges:
    module       - any version
    module@1     - major version 1, any minor (not prerelease)
    module@1.2   - minor version 1.2, any patch (not prerelease)
    module@1.2.3 - exact version

  It is assumed that these modules are provided by the server / file system.

  First checks the already-requested packages to see if there are any packages
  that would match the same package and version range.

  This provides a greedy algorithm as a simple fix for sharing version-managed
  dependencies as much as possible, which can later be optimized through version
  hint configuration created out of deeper version tree analysis.

  2. Semver-compatibility syntax (caret operator - ^)

  Compatible version request support is then also provided for:

    module@^1.2.3        - module@1, >=1.2.3
    module@^1.2          - module@1, >=1.2.0
    module@^1            - module@1
    module@^0.5.3        - module@0.5, >= 0.5.3
    module@^0.0.1        - module@0.0.1

  The ^ symbol is always normalized out to a normal version request.

  This provides comprehensive semver compatibility.

  3. System.versions version hints and version report

  Note this addon should be provided after all other normalize overrides.

  The full list of versions can be found at System.versions providing an insight
  into any possible version forks.

  It is also possible to create version solution hints on the System global:

  System.versions = {
    jquery: ['1.9.2', '2.0.3'],
    bootstrap: '3.0.1'
  };

  Versions can be an array or string for a single version.

  When a matching semver request is made (jquery@1.9, jquery@1, bootstrap@3)
  they will be converted to the latest version match contained here, if present.

  Prereleases in this versions list are also allowed to satisfy ranges when present.
*/

function versions(loader) {
  if (typeof indexOf == 'undefined')
    indexOf = Array.prototype.indexOf;

  // match x, x.y, x.y.z, x.y.z-prerelease.1
  var semverRegEx = /^(\d+)(?:\.(\d+)(?:\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?)?)?$/;

  var semverCompare = function(v1, v2) {
    var v1Parts = v1.split('.');
    var v2Parts = v2.split('.');
    var prereleaseIndex;
    if (v1Parts[2] && (prereleaseIndex = indexOf.call(v1Parts[2], '-')) != -1)
      v1Parts.splice(2, 1, v1Parts[2].substr(0, prereleaseIndex), v1Parts[2].substr(prereleaseIndex + 1));
    if (v2Parts[2] && (prereleaseIndex = indexOf.call(v2Parts[2], '-')) != -1)
      v2Parts.splice(2, 1, v2Parts[2].substr(0, prereleaseIndex), v2Parts[2].substr(prereleaseIndex + 1));
    for (var i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
      if (!v1Parts[i])
        return 1;
      else if (!v2Parts[i])
        return -1;
      if (v1Parts[i] != v2Parts[i])
        return parseInt(v1Parts[i]) > parseInt(v2Parts[i]) ? 1 : -1;
    }
    return 0;
  }

  loader.versions = loader.versions || {};

  var loaderNormalize = loader.normalize;
  loader.normalize = function(name, parentName, parentAddress) {
    if (!loader.versions)
      loader.versions = {};
    var packageVersions = this.versions;

    // strip the version before applying map config
    var stripVersion, stripSubPathLength;
    if (name.indexOf('@') > 0) {
      var versionIndex = name.lastIndexOf('@');
      var parts = name.substr(versionIndex + 1, name.length - versionIndex - 1).split('/');
      stripVersion = parts[0];
      stripSubPathLength = parts.length;
      name = name.substr(0, versionIndex) + name.substr(versionIndex + stripVersion.length + 1, name.length - versionIndex - stripVersion.length - 1);
    }

    // run all other normalizers first
    return Promise.resolve(loaderNormalize.call(this, name, parentName, parentAddress)).then(function(normalized) {

      var version, semverMatch, nextChar, versions;
      var index = normalized.indexOf('@');

      // if we stripped a version, and it still has no version, add it back
      if (stripVersion && (index == -1 || index == 0)) {
        var parts = normalized.split('/');
        parts[parts.length - stripSubPathLength] += '@' + stripVersion;
        normalized = parts.join('/');
        index = normalized.indexOf('@');
      }

      // see if this module corresponds to a package already in our versioned packages list

      // no version specified - check against the list (given we don't know the package name)
      if (index == -1 || index == 0) {
        for (var p in packageVersions) {
          versions = packageVersions[p];
          if (normalized.substr(0, p.length) != p)
            continue;

          nextChar = normalized.substr(p.length, 1);

          if (nextChar && nextChar != '/')
            continue;

          // match -> take latest version
          return p + '@' + (typeof versions == 'string' ? versions : versions[versions.length - 1]) + normalized.substr(p.length);
        }
        return normalized;
      }

      // get the version info
      version = normalized.substr(index + 1).split('/')[0];
      var versionLength = version.length;

      var minVersion;
      if (version.substr(0, 1) == '^') {
        version = version.substr(1);
        minVersion = true;
      }

      semverMatch = version.match(semverRegEx);

      // if not a semver, we cant help
      if (!semverMatch)
        return normalized;

      // translate '^' in range to simpler range form
      if (minVersion) {
        // ^0 -> 0
        // ^1 -> 1
        if (!semverMatch[2])
          minVersion = false;

        if (!semverMatch[3]) {

          // ^1.1 -> ^1.1.0
          if (semverMatch[2] > 0)
            semverMatch[3] = '0';

          // ^0.1 -> 0.1
          // ^0.0 -> 0.0
          else
            minVersion = false;
        }
      }

      if (minVersion) {
        // >= 1.0.0
        if (semverMatch[1] > 0) {
          if (!semverMatch[2])
            version = semverMatch[1] + '.0.0';
          if (!semverMatch[3])
            version = semverMatch[1] + '.0';
          minVersion = version;
          semverMatch = [semverMatch[1]];
        }
        // >= 0.1.0
        else if (semverMatch[2] > 0) {
          minVersion = version;
          semverMatch = [0, semverMatch[2]];
        }
        // >= 0.0.0
        else {
          // NB compatible with prerelease is just prelease itself?
          minVersion = false;
          semverMatch = [0, 0, semverMatch[3]];
        }
        version = semverMatch.join('.');
      }

      var packageName = normalized.substr(0, index);

      versions = packageVersions[packageName] || [];

      if (typeof versions == 'string')
        versions = [versions];

      // look for a version match
      // if an exact semver, theres nothing to match, just record it
      if (!semverMatch[3] || minVersion)
        for (var i = versions.length - 1; i >= 0; i--) {
          var curVersion = versions[i];
          // if I have requested x.y, find an x.y.z-b
          // if I have requested x, find any x.y / x.y.z-b
          if (curVersion.substr(0, version.length) == version && curVersion.substr(version.length, 1).match(/^[\.\-]?$/)) {
            // if a minimum version, then check too
            if (!minVersion || minVersion && semverCompare(curVersion, minVersion) != -1)
              return packageName + '@' + curVersion + normalized.substr(packageName.length + versionLength + 1);
          }
        }

      // no match
      // record the package and semver for reuse since we're now asking the server
      // x.y and x versions will now be latest by default, so they are useful in the version list
      if (indexOf.call(versions, version) == -1) {
        versions.push(version);
        versions.sort(semverCompare);

        normalized = packageName + '@' + version + normalized.substr(packageName.length + versionLength + 1);

        // if this is an x.y.z, remove any x.y, x
        // if this is an x.y, remove any x
        if (semverMatch[3] && (index = indexOf.call(versions, semverMatch[1] + '.' + semverMatch[2])) != -1)
          versions.splice(index, 1);
        if (semverMatch[2] && (index = indexOf.call(versions, semverMatch[1])) != -1)
          versions.splice(index, 1);

        packageVersions[packageName] = versions.length == 1 ? versions[0] : versions;
      }

      return normalized;
    });
  }
}
/*
 * Dependency Tree Cache
 *
 * Allows a build to pre-populate a dependency trace tree on the loader of
 * the expected dependency tree, to be loaded upfront when requesting the
 * module, avoinding the n round trips latency of module loading, where
 * n is the dependency tree depth.
 *
 * eg:
 * System.depCache = {
 *  'app': ['normalized', 'deps'],
 *  'normalized': ['another'],
 *  'deps': ['tree']
 * };
 *
 * System.import('app')
 * // simultaneously starts loading all of:
 * // 'normalized', 'deps', 'another', 'tree'
 * // before "app" source is even loaded
 */

function depCache(loader) {
  loader.depCache = loader.depCache || {};

  loaderLocate = loader.locate;
  loader.locate = function(load) {
    var loader = this;

    if (!loader.depCache)
      loader.depCache = {};

    // load direct deps, in turn will pick up their trace trees
    var deps = loader.depCache[load.name];
    if (deps)
      for (var i = 0; i < deps.length; i++)
        loader.load(deps[i]);

    return loaderLocate.call(loader, load);
  }
}

meta(System);
register(System);
core(System);
global(System);
cjs(System);
amd(System);
map(System);
plugins(System);
bundles(System);
versions(System);
depCache(System);
  if (!System.paths['@traceur'])
    System.paths['@traceur'] = $__curScript && $__curScript.getAttribute('data-traceur-src')
      || ($__curScript && $__curScript.src
        ? $__curScript.src.substr(0, $__curScript.src.lastIndexOf('/') + 1)
        : System.baseURL + (System.baseURL.lastIndexOf('/') == System.baseURL.length - 1 ? '' : '/')
        ) + 'traceur.js';
};

var $__curScript, __eval;

(function() {

  var doEval;

  __eval = function(source, address, sourceMap) {
    source += '\n//# sourceURL=' + address + (sourceMap ? '\n//# sourceMappingURL=' + sourceMap : '');

    try {
      doEval(source);
    }
    catch(e) {
      throw 'Error evaluating ' + address;
    }
  };

  var isWorker = typeof WorkerGlobalScope !== 'undefined' &&
    self instanceof WorkerGlobalScope;
  var isBrowser = typeof window != 'undefined';

  if (isBrowser) {
    var head;

    var scripts = document.getElementsByTagName('script');
    $__curScript = scripts[scripts.length - 1];

    // globally scoped eval for the browser
    doEval = function(source) {
      if (!head)
        head = document.head || document.body || document.documentElement;

      var script = document.createElement('script');
      script.text = source;
      var onerror = window.onerror;
      var e;
      window.onerror = function(_e) {
        e = _e;
      }
      head.appendChild(script);
      head.removeChild(script);
      window.onerror = onerror;
      if (e)
        throw e;
    }

    if (!$__global.System || !$__global.LoaderPolyfill) {
      // determine the current script path as the base path
      var curPath = $__curScript.src;
      var basePath = curPath.substr(0, curPath.lastIndexOf('/') + 1);
      document.write(
        '<' + 'script type="text/javascript" src="' + basePath + 'es6-module-loader.js" data-init="upgradeSystemLoader">' + '<' + '/script>'
      );
    }
    else {
      $__global.upgradeSystemLoader();
    }
  }
  else if(isWorker) {
    doEval = function(source) {
      try {
        eval(source);
      } catch(e) {
        throw e;
      }
    };

    if (!$__global.System || !$__global.LoaderPolyfill) {
      var basePath = '';
      try {
        throw new Error('Getting the path');
      } catch(err) {
        var idx = err.stack.indexOf('at ') + 3;
        var withSystem = err.stack.substr(idx, err.stack.substr(idx).indexOf('\n'));
        basePath = withSystem.substr(0, withSystem.lastIndexOf('/') + 1);
      }
      importScripts(basePath + 'es6-module-loader.js');
    } else {
      $__global.upgradeSystemLoader();
    }
  }
  else {
    var es6ModuleLoader = require('es6-module-loader');
    $__global.System = es6ModuleLoader.System;
    $__global.Loader = es6ModuleLoader.Loader;
    $__global.upgradeSystemLoader();
    module.exports = $__global.System;

    // global scoped eval for node
    var vm = require('vm');
    doEval = function(source, address, sourceMap) {
      vm.runInThisContext(source);
    }
  }
})();

})(typeof window != 'undefined' ? window : (typeof WorkerGlobalScope != 'undefined' ?
                                           self : global));


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Please enter language data in the fields below.  All data should be entered in English -->
<ldml xmlns:sil="urn://www.sil.org/ldml/0.1">
	<identity>
		<version number="0.0.1"/>
		<!-- name.en(jgk)="Gwak" -->
		<language type="jgk"/>
		<special>
			<sil:identity defaultRegion="NG" script="Latn"/>
		</special>
	</identity>
	<localeDisplayNames>
		<languages>
			<language type="jgk">Gwak</language>
		</languages>
		<special>
			<sil:names>
				<sil:name xml:lang="en">Gwak</sil:name>
			</sil:names>
		</special>
	</localeDisplayNames>
	<characters>
		<exemplarCharacters>[a b ɓ c d ɗ e ǝ g i j k l m n {ng} {ny} o p r s {sh} t u w y z {zh} ']</exemplarCharacters>
		<exemplarCharacters type="auxiliary">[f h q v x]</exemplarCharacters>
	</characters>
	<special>
		<sil:external-resources>
			<sil:font name="Charis SIL" types="default">
				<sil:url>https://wirl.api.sil.org/CharisSILReg&type=ttf</sil:url>
			</sil:font>
			<sil:font name="Noto Sans"><!--types="ui"-->
				<sil:url>https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSans/NotoSans-Regular.ttf</sil:url>
			</sil:font>
			<sil:font name="Noto Serif">
				<sil:url>https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Regular.ttf</sil:url>
			</sil:font>
		</sil:external-resources>
	</special>
</ldml>

redpajama_set_name: RedPajamaGithub


text:
package org.elasticsearch.painless.node;

import org.elasticsearch.painless.Location;
import org.elasticsearch.painless.Scope;
import org.elasticsearch.painless.ir.ClassNode;
import org.elasticsearch.painless.ir.ConstantNode;
import org.elasticsearch.painless.symbol.ScriptRoot;

import java.util.Objects;

/**
 * Represents a non-decimal numeric constant.
 */
public class ENumeric extends AExpression {

    protected final String value;
    protected final int radix;

    public ENumeric(Location location, String value, int radix) {
        super(location);

        this.value = Objects.requireNonNull(value);
        this.radix = radix;
    }

    @Override
    Output analyze(ClassNode classNode, ScriptRoot scriptRoot, Scope scope, Input input) {
        if (input.write) {
            throw createError(new IllegalArgumentException(
                    "invalid assignment: cannot assign a value to numeric constant [" + value + "]"));
        }

        if (input.read == false) {
            throw createError(new IllegalArgumentException("not a statement: numeric constant [" + value + "] not used"));
        }

        Output output = new Output();
        Object constant;

        if (value.endsWith("d") || value.endsWith("D")) {
            if (radix != 10) {
                throw createError(new IllegalStateException("Illegal tree structure."));
            }

            try {
                constant = Double.parseDouble(value.substring(0, value.length() - 1));
                output.actual = double.class;
            } catch (NumberFormatException exception) {
                throw createError(new IllegalArgumentException("Invalid double constant [" + value + "]."));
            }
        } else if (value.endsWith("f") || value.endsWith("F")) {
            if (radix != 10) {
                throw createError(new IllegalStateException("Illegal tree structure."));
            }

            try {
                constant = Float.parseFloat(value.substring(0, value.length() - 1));
                output.actual = float.class;
            } catch (NumberFormatException exception) {
                throw createError(new IllegalArgumentException("Invalid float constant [" + value + "]."));
            }
        } else if (value.endsWith("l") || value.endsWith("L")) {
            try {
                constant = Long.parseLong(value.substring(0, value.length() - 1), radix);
                output.actual = long.class;
            } catch (NumberFormatException exception) {
                throw createError(new IllegalArgumentException("Invalid long constant [" + value + "]."));
            }
        } else {
            try {
                Class<?> sort = input.expected == null ? int.class : input.expected;
                int integer = Integer.parseInt(value, radix);

                if (sort == byte.class && integer >= Byte.MIN_VALUE && integer <= Byte.MAX_VALUE) {
                    constant = (byte)integer;
                    output.actual = byte.class;
                } else if (sort == char.class && integer >= Character.MIN_VALUE && integer <= Character.MAX_VALUE) {
                    constant = (char)integer;
                    output.actual = char.class;
                } else if (sort == short.class && integer >= Short.MIN_VALUE && integer <= Short.MAX_VALUE) {
                    constant = (short)integer;
                    output.actual = short.class;
                } else {
                    constant = integer;
                    output.actual = int.class;
                }
            } catch (NumberFormatException exception) {
                try {
                    // Check if we can parse as a long. If so then hint that the user might prefer that.
                    Long.parseLong(value, radix);
                    throw createError(new IllegalArgumentException("Invalid int constant [" + value + "]. If you want a long constant "
                            + "then change it to [" + value + "L]."));
                } catch (NumberFormatException longNoGood) {
                    // Ignored
                }
                throw createError(new IllegalArgumentException("Invalid int constant [" + value + "]."));
            }
        }

        ConstantNode constantNode = new ConstantNode();
        constantNode.setLocation(location);
        constantNode.setExpressionType(output.actual);
        constantNode.setConstant(constant);

        output.expressionNode = constantNode;

        return output;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

// Includes classes and methods used to figure out near-matches of schematic and SPICE pin names,
// to help connect them.  Based on a modified Levenstein algorithm and the Hungarian algorithm.
namespace PinMatcher
{
    static public partial class PinMatcher
    {
        static readonly int index1 = 0;
        static readonly int index2 = 1;

        /// <summary>
        /// Produces an N x 2 array of strings showing the best match-up of two lists of strings.
        /// Used to match schematic pins with SPICE pins, for example.
        /// </summary>
        /// <param name="firstPinNames">The first list of strings, typically schematic pin names.</param>
        /// <param name="secondPinNames">The second list of strings, typically SPICE pin names.</param>
        /// <returns>N x 2 array of strings, showing the best match-up between two lists of strings.
        /// The first column of the array has strings from the first list in a sorted order.
        /// The second column of the array has a permutation of strings from the second list, so that
        /// strings on the same row will tend to be close matches.
        /// If one list is longer than the other, the shorter one will be extended with "" strings.</returns>
        /// <remarks>This method uses a modified Levenshtein algorithm to tell how close two strings
        /// are to matching, and the Hungarian algorithm to optimize the overall matchup.</remarks>
        /// <seealso cref="http://en.wikipedia.org/wiki/Levenshtein_distance"/>
        /// <seealso cref="http://en.wikipedia.org/wiki/Hungarian_algorithm"/>
        static public string[,] GetPinMatches(List<string> firstPinNames, List<string> secondPinNames)
        {
            int len1 = firstPinNames.Count;
            int len2 = secondPinNames.Count;

            int pinListSize = Math.Max(len1, len2);

            // Copy the pin lists so the new lists can be extended, if needed, to the same size with empty strings.
            List<string> newS1 = new List<string>(firstPinNames);
            newS1.Sort();
            while (newS1.Count < pinListSize)
            {
                newS1.Add("");
            }

            List<string> newS2 = new List<string>(secondPinNames);
            newS2.Sort();
            while (newS2.Count < pinListSize)
            {
                newS2.Add("");
            }

            // Now, both new lists of pins have the same length.
            // Compute a square cost matrix for the pins based on their distances.

            int[,] costMatrix = new int[pinListSize, pinListSize];

            for (int rows = 0; rows < pinListSize; rows++)
            {
                for (int cols = 0; cols < pinListSize; cols++)
                {
                    costMatrix[rows, cols] = Costs.CostBetweenTwoPins(newS1[rows], newS2[cols]);
                }
            }

            // Find the least cost assignment of pins to pins
            int[] pinMap = HungarianAlgorithm.FindAssignments(costMatrix);

            Debug.Assert(pinMap.Count() == pinListSize);

            // Create the output list of matched pin strings

            string[,] rVal = new string[pinListSize, 2];

            for (int i = 0; i < pinListSize; i++)
            {
                rVal[i, index1] = newS1[i];
                rVal[i, index2] = newS2[pinMap[i]];
            }
            return rVal;
        }
    }
}


text:
id: version-3.5.0-javascript-project
title: JavaScript project
original_id: javascript-project
---

In order to start with JavaScript you need to use either
[BabelPlugin](/docs/plugins/babel-plugin) or simply install `TypeScript` which
is the recommended way. We will go with `TypeScript` compiler approach, as it's
the most effecient and stable approach.

You can find an example [here](https://github.com/fuse-box/react-example)

## Install TypeScript

Don't be put off by us asking you to install TypeScript, you won't even know its
presence. FuseBox uses `TypeScript` to transpile your javascript modules.

```bash
npm install typescript --save-dev
```

## Getting started with JavaScript

Create `fuse.js` with the following javascript code.

```js
const { FuseBox, WebIndexPlugin } = require("fuse-box");
const fuse = FuseBox.init({
  homeDir: "src",
  target: "browser@es6",
  output: "dist/$name.js",
  useTypescriptCompiler: true,
  plugins: [WebIndexPlugin()],
});
fuse.dev(); // launch http server
fuse
  .bundle("app")
  .instructions(" > index.jsx")
  .hmr()
  .watch();
fuse.run();
```

## Changing JavaScript target

You can override the target by changing the `FuseBox.init` configuration

```ts
const fuse = FuseBox.init({
  homeDir: "src",
  target: "browser@es6",
  output: "dist/$name.js",
});
```

Read more about targets in [this section](/docs/guides/working-with-targets)

## Synthetic Default Imports

FuseBox doesn't polyfill default imports by default.

Correct:

```js
import * as React from "react";
```

NOT correct:

```js
import React from "react"; // <-- not correct
```

If you really want to make it work you can enable
[allowSyntheticDefaultImports](/docs/development/configuration#allowsyntheticdefaultimports).

However, it's not recommended adding this option as it adds additional overhead
to your runtime.


text:
<?php
class userAddressModel extends Model
{

}

 ?>


text:
"""Test the urilib module."""

from __future__ import print_function

import os

from chromite.lib import cros_test_lib
from chromite.lib import osutils

from chromite.lib.paygen import filelib
from chromite.lib.paygen import gslib
from chromite.lib.paygen import urilib

# We access private members to test them.
# pylint: disable=protected-access

class FakeHttpResponse(object):
  """For simulating http response objects."""

  class FakeHeaders(object):
    """Helper class for faking HTTP headers in a response."""

    def __init__(self, headers_dict):
      self.headers_dict = headers_dict

    def getheader(self, name):
      return self.headers_dict.get(name)

  def __init__(self, code, headers_dict=None):
    self.code = code
    self.headers = FakeHttpResponse.FakeHeaders(headers_dict)

  def getcode(self):
    return self.code

class TestFileManipulation(cros_test_lib.TempDirTestCase):
  """Test general urilib file methods together."""

  # pylint: disable=attribute-defined-outside-init

  FILE1 = 'file1'
  FILE2 = 'file2'
  SUBDIR = 'subdir'
  SUBFILE = '%s/file3' % SUBDIR

  FILE1_CONTENTS = 'Howdy doody there dandy'
  FILE2_CONTENTS = 'Once upon a time in a galaxy far far away.'
  SUBFILE_CONTENTS = 'Five little monkeys jumped on the bed.'

  GS_DIR = 'gs://chromeos-releases-public/unittest'

  def setUp(self):
    # Use a subdir specifically for the cache so we can use the tempdir for
    # other things (including tempfiles by gsutil/etc...).
    self.filesdir = os.path.join(self.tempdir, 'unittest-cache')
    osutils.SafeMakedirs(self.filesdir)

  def _SetUpDirs(self):
    self.file1_local = os.path.join(self.filesdir, self.FILE1)
    self.file2_local = os.path.join(self.filesdir, self.FILE2)
    self.subdir_local = os.path.join(self.filesdir, self.SUBDIR)
    self.subfile_local = os.path.join(self.filesdir, self.SUBFILE)

    self.file1_gs = os.path.join(self.GS_DIR, self.FILE1)
    self.file2_gs = os.path.join(self.GS_DIR, self.FILE2)
    self.subdir_gs = os.path.join(self.GS_DIR, self.SUBDIR)
    self.subfile_gs = os.path.join(self.GS_DIR, self.SUBFILE)

    # Pre-populate local dir with contents.
    with open(self.file1_local, 'w') as out1:
      out1.write(self.FILE1_CONTENTS)

    with open(self.file2_local, 'w') as out2:
      out2.write(self.FILE2_CONTENTS)

    os.makedirs(self.subdir_local)

    with open(self.subfile_local, 'w') as out3:
      out3.write(self.SUBFILE_CONTENTS)

    # Make sure gs:// directory is ready (empty).
    gslib.Remove(os.path.join(self.GS_DIR, '*'), recurse=True,
                 ignore_no_match=True)

  @cros_test_lib.NetworkTest()
  def testIntegration(self):
    self._SetUpDirs()

    self.assertTrue(urilib.Exists(self.filesdir, as_dir=True))
    self.assertTrue(urilib.Exists(self.file1_local))
    self.assertTrue(urilib.Exists(self.file2_local))
    self.assertTrue(urilib.Exists(self.subfile_local))
    self.assertTrue(urilib.Exists(self.subdir_local, as_dir=True))

    self.assertFalse(urilib.Exists(self.file1_gs))
    self.assertFalse(urilib.Exists(self.file2_gs))
    self.assertFalse(urilib.Exists(self.subfile_gs))

    shallow_local_files = [self.file1_local, self.file2_local]
    deep_local_files = shallow_local_files + [self.subfile_local]
    shallow_gs_files = [self.file1_gs, self.file2_gs]
    deep_gs_files = shallow_gs_files + [self.subfile_gs]

    # Test ListFiles, local version.
    self.assertEquals(set(shallow_local_files),
                      set(urilib.ListFiles(self.filesdir)))
    self.assertEquals(set(deep_local_files),
                      set(urilib.ListFiles(self.filesdir, recurse=True)))

    # Test CopyFiles, from local to GS.
    self.assertEquals(set(deep_gs_files),
                      set(urilib.CopyFiles(self.filesdir, self.GS_DIR)))

    # Test ListFiles, GS version.
    self.assertEquals(set(shallow_gs_files),
                      set(urilib.ListFiles(self.GS_DIR)))
    self.assertEquals(set(deep_gs_files),
                      set(urilib.ListFiles(self.GS_DIR, recurse=True)))

    # Test Cmp between some files.
    self.assertTrue(urilib.Cmp(self.file1_local, self.file1_gs))
    self.assertFalse(urilib.Cmp(self.file2_local, self.file1_gs))

    # Test RemoveDirContents, local version.
    urilib.RemoveDirContents(self.filesdir)
    self.assertFalse(urilib.ListFiles(self.filesdir))

    # Test CopyFiles, from GS to local.
    self.assertEquals(set(deep_local_files),
                      set(urilib.CopyFiles(self.GS_DIR, self.filesdir)))

    # Test RemoveDirContents, GS version.
    urilib.RemoveDirContents(self.GS_DIR)
    self.assertFalse(urilib.ListFiles(self.GS_DIR))

class TestUrilib(cros_test_lib.MoxTempDirTestCase):
  """Test urilib module."""

  def testExtractProtocol(self):
    tests = {'gs': ['gs://',
                    'gs://foo',
                    'gs://foo/bar'],
             'abc': ['abc://',
                     'abc://foo',
                     'abc://foo/bar'],
             None: ['foo/bar',
                    '/foo/bar',
                    '://garbage/path']}

    for protocol in tests:
      for uri in tests[protocol]:
        self.assertEquals(protocol, urilib.ExtractProtocol(uri))

  def testGetUriType(self):
    tests = {'gs': ['gs://',
                    'gs://foo',
                    'gs://foo/bar'],
             'abc': ['abc://',
                     'abc://foo',
                     'abc://foo/bar'],
             'file': ['foo/bar',
                      '/foo/bar',
                      '://garbage/path',
                      '/cnsfoo/bar']}

    for uri_type in tests:
      for uri in tests[uri_type]:
        self.assertEquals(uri_type, urilib.GetUriType(uri))

  def testSplitURI(self):
    tests = [
        ['gs', 'foo', 'gs://foo'],
        ['gs', 'foo/bar', 'gs://foo/bar'],
        ['file', '/foo/bar', 'file:///foo/bar'],
        [None, '/foo/bar', '/foo/bar'],
    ]

    for test in tests:
      uri = test[2]
      protocol, path = urilib.SplitURI(uri)
      self.assertEquals(test[0], protocol)
      self.assertEquals(test[1], path)

  def testIsGsURI(self):
    tests_true = ('gs://',
                  'gs://foo',
                  'gs://foo/bar')
    for test in tests_true:
      self.assertTrue(urilib.IsGsURI(test))

    tests_false = ('gsfoo/bar',
                   'gs/foo/bar',
                   'gs',
                   '/foo/bar',
                   '/gs',
                   '/gs/foo/bar'
                   'file://foo/bar',
                   'http://foo/bar')
    for test in tests_false:
      self.assertFalse(urilib.IsGsURI(test))

  def testIsFileURI(self):
    tests_true = ('file://',
                  'file://foo/bar',
                  'file:///foo/bar',
                  '/foo/bar',
                  'foo/bar',
                  'foo',
                  '')
    for test in tests_true:
      self.assertTrue(urilib.IsFileURI(test))

    tests_false = ('gs://',
                   'foo://',
                   'gs://foo/bar')
    for test in tests_false:
      self.assertFalse(urilib.IsFileURI(test))

  def testIsHttpURI(self):
    tests_true = ('http://',
                  'http://foo',
                  'http://foo/bar')
    for test in tests_true:
      self.assertTrue(urilib.IsHttpURI(test))

    tests_https_true = ('https://',
                        'https://foo',
                        'https://foo/bar')
    for test in tests_https_true:
      self.assertTrue(urilib.IsHttpURI(test, https_ok=True))
    for test in tests_https_true:
      self.assertFalse(urilib.IsHttpURI(test))

    tests_false = ('httpfoo/bar',
                   'http/foo/bar',
                   'http',
                   '/foo/bar',
                   '/http',
                   '/http/foo/bar'
                   'file:///foo/bar',
                   'gs://foo/bar')
    for test in tests_false:
      self.assertFalse(urilib.IsHttpURI(test))

  def testIsHttpsURI(self):
    tests_true = ('https://',
                  'https://foo',
                  'https://foo/bar')
    for test in tests_true:
      self.assertTrue(urilib.IsHttpsURI(test))

    tests_false = ('http://',
                   'http://foo',
                   'http://foo/bar',
                   'httpfoo/bar',
                   'http/foo/bar',
                   'http',
                   '/foo/bar',
                   '/http',
                   '/http/foo/bar'
                   'file:///foo/bar',
                   'gs://foo/bar')
    for test in tests_false:
      self.assertFalse(urilib.IsHttpsURI(test))

  def testMD5Sum(self):
    gs_path = 'gs://bucket/some/path'
    local_path = '/some/local/path'
    http_path = 'http://host.domain/some/path'

    self.mox.StubOutWithMock(gslib, 'MD5Sum')
    self.mox.StubOutWithMock(filelib, 'MD5Sum')

    # Set up the test replay script.
    # Run 1, GS.
    gslib.MD5Sum(gs_path).AndReturn('TheResult')
    # Run 3, local file.
    filelib.MD5Sum(local_path).AndReturn('TheResult')
    self.mox.ReplayAll()

    # Run the test verification.
    self.assertEquals('TheResult', urilib.MD5Sum(gs_path))
    self.assertEquals('TheResult', urilib.MD5Sum(local_path))
    self.assertRaises(urilib.NotSupportedForType, urilib.MD5Sum, http_path)
    self.mox.VerifyAll()

  def testCmp(self):
    gs_path = 'gs://bucket/some/path'
    local_path = '/some/local/path'
    http_path = 'http://host.domain/some/path'

    result = 'TheResult'

    self.mox.StubOutWithMock(gslib, 'Cmp')
    self.mox.StubOutWithMock(filelib, 'Cmp')

    # Set up the test replay script.
    # Run 1, two local files.
    filelib.Cmp(local_path, local_path + '.1').AndReturn(result)
    # Run 2, local and GS.
    gslib.Cmp(local_path, gs_path).AndReturn(result)
    # Run 4, GS and GS
    gslib.Cmp(gs_path, gs_path + '.1').AndReturn(result)
    # Run 7, local and HTTP
    self.mox.ReplayAll()

    # Run the test verification.
    self.assertEquals(result, urilib.Cmp(local_path, local_path + '.1'))
    self.assertEquals(result, urilib.Cmp(local_path, gs_path))
    self.assertEquals(result, urilib.Cmp(gs_path, gs_path + '.1'))
    self.assertRaises(urilib.NotSupportedBetweenTypes, urilib.Cmp,
                      local_path, http_path)
    self.mox.VerifyAll()

  @cros_test_lib.NetworkTest()
  def testURLRetrieve(self):
    good_url = 'https://codereview.chromium.org/download/issue11731004_1_2.diff'
    bad_domain_url = 'http://notarealdomainireallyhope.com/some/path'
    bad_path_url = 'https://dl.google.com/dl/edgedl/x/y/z/a/b/c/foobar'
    local_path = os.path.join(self.tempdir, 'downloaded_file')
    bad_local_path = '/tmp/a/b/c/d/x/y/z/foobar'

    git_index1 = 'e6c0d72a5122171deb4c458991d1c7547f31a2f0'
    git_index2 = '3d0f7d3edfd8146031e66dc3f45926920d3ded78'
    expected_contents = """Index: LICENSE
diff --git a/LICENSE b/LICENSE
index %s..%s 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,4 +1,4 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Copyright (c) 2013 The Chromium Authors. All rights reserved.
 //
 // Redistribution and use in source and binary forms, with or without
 // modification, are permitted provided that the following conditions are
""" % (git_index1, git_index2)

    self.assertRaises(urilib.MissingURLError, urilib.URLRetrieve,
                      bad_path_url, local_path)
    self.assertRaises(urilib.MissingURLError, urilib.URLRetrieve,
                      bad_domain_url, local_path)

    urilib.URLRetrieve(good_url, local_path)
    with open(local_path, 'r') as f:
      actual_contents = f.read()
    self.assertEqual(expected_contents, actual_contents)

    self.assertRaises(IOError, urilib.URLRetrieve, good_url, bad_local_path)

  def testCopy(self):
    gs_path = 'gs://bucket/some/path'
    local_path = '/some/local/path'
    http_path = 'http://host.domain/some/path'

    result = 'TheResult'

    self.mox.StubOutWithMock(gslib, 'Copy')
    self.mox.StubOutWithMock(filelib, 'Copy')
    self.mox.StubOutWithMock(urilib, 'URLRetrieve')

    # Set up the test replay script.
    # Run 1, two local files.
    filelib.Copy(local_path, local_path + '.1').AndReturn(result)
    # Run 2, local and GS.
    gslib.Copy(local_path, gs_path).AndReturn(result)
    # Run 4, GS and GS
    gslib.Copy(gs_path, gs_path + '.1').AndReturn(result)
    # Run 7, HTTP and local
    urilib.URLRetrieve(http_path, local_path).AndReturn(result)
    # Run 8, local and HTTP
    self.mox.ReplayAll()

    # Run the test verification.
    self.assertEquals(result, urilib.Copy(local_path, local_path + '.1'))
    self.assertEquals(result, urilib.Copy(local_path, gs_path))
    self.assertEquals(result, urilib.Copy(gs_path, gs_path + '.1'))
    self.assertEquals(result, urilib.Copy(http_path, local_path))
    self.assertRaises(urilib.NotSupportedBetweenTypes, urilib.Copy,
                      local_path, http_path)
    self.mox.VerifyAll()

  def testRemove(self):
    gs_path = 'gs://bucket/some/path'
    local_path = '/some/local/path'
    http_path = 'http://host.domain/some/path'

    self.mox.StubOutWithMock(gslib, 'Remove')
    self.mox.StubOutWithMock(filelib, 'Remove')

    # Set up the test replay script.
    # Run 1, two local files.
    filelib.Remove(local_path, local_path + '.1')
    # Run 2, local and GS.
    gslib.Remove(local_path, gs_path, ignore_no_match=True)
    # Run 4, GS and GS
    gslib.Remove(gs_path, gs_path + '.1',
                 ignore_no_match=True, recurse=True)
    # Run 7, local and HTTP
    self.mox.ReplayAll()

    # Run the test verification.
    urilib.Remove(local_path, local_path + '.1')
    urilib.Remove(local_path, gs_path, ignore_no_match=True)
    urilib.Remove(gs_path, gs_path + '.1', ignore_no_match=True, recurse=True)
    self.assertRaises(urilib.NotSupportedForTypes, urilib.Remove,
                      local_path, http_path)
    self.mox.VerifyAll()

  def testSize(self):
    gs_path = 'gs://bucket/some/path'
    local_path = '/some/local/path'
    http_path = 'http://host.domain/some/path'
    ftp_path = 'ftp://host.domain/some/path'

    result = 100
    http_response = FakeHttpResponse(200, {'Content-Length': str(result)})

    self.mox.StubOutWithMock(gslib, 'FileSize')
    self.mox.StubOutWithMock(filelib, 'Size')
    self.mox.StubOutWithMock(urilib.urllib2, 'urlopen')

    # Set up the test replay script.
    # Run 1, local.
    filelib.Size(local_path).AndReturn(result)
    # Run 2, GS.
    gslib.FileSize(gs_path).AndReturn(result)
    # Run 4, HTTP.
    urilib.urllib2.urlopen(http_path).AndReturn(http_response)
    # Run 5, FTP.
    self.mox.ReplayAll()

    # Run the test verification.
    self.assertEquals(result, urilib.Size(local_path))
    self.assertEquals(result, urilib.Size(gs_path))
    self.assertEquals(result, urilib.Size(http_path))
    self.assertRaises(urilib.NotSupportedForType, urilib.Size, ftp_path)
    self.mox.VerifyAll()

  def testExists(self):
    gs_path = 'gs://bucket/some/path'
    local_path = '/some/local/path'
    http_path = 'http://host.domain/some/path'
    ftp_path = 'ftp://host.domain/some/path'

    result = 'TheResult'

    self.mox.StubOutWithMock(gslib, 'Exists')
    self.mox.StubOutWithMock(filelib, 'Exists')
    self.mox.StubOutWithMock(urilib.urllib2, 'urlopen')

    # Set up the test replay script.
    # Run 1, local, as_dir=False
    filelib.Exists(local_path, as_dir=False).AndReturn(result)
    # Run 2, GS, as_dir=False.
    gslib.Exists(gs_path).AndReturn(result)
    # Run 3, GS, as_dir=True.
    # Run 6, HTTP, as_dir=False, code=200.
    urilib.urllib2.urlopen(http_path).AndReturn(FakeHttpResponse(200))
    # Run 7, HTTP, as_dir=False, code=404.
    urilib.urllib2.urlopen(http_path).AndReturn(FakeHttpResponse(404))
    # Run 8, HTTP, as_dir=False, HTTPError.
    urilib.urllib2.urlopen(http_path).AndRaise(
        urilib.urllib2.HTTPError('url', 404, 'msg', None, None))
    # Run 9, HTTP, as_dir=True.
    # Run 10, FTP, as_dir=False.
    self.mox.ReplayAll()

    # Run the test verification.
    self.assertEquals(result, urilib.Exists(local_path))
    self.assertEquals(result, urilib.Exists(gs_path))
    self.assertEquals(False, urilib.Exists(gs_path, as_dir=True))
    self.assertTrue(urilib.Exists(http_path))
    self.assertFalse(urilib.Exists(http_path))
    self.assertFalse(urilib.Exists(http_path))
    self.assertRaises(urilib.NotSupportedForType,
                      urilib.Exists, http_path, as_dir=True)
    self.assertRaises(urilib.NotSupportedForType, urilib.Exists, ftp_path)
    self.mox.VerifyAll()

  def testListFiles(self):
    gs_path = 'gs://bucket/some/path'
    local_path = '/some/local/path'
    http_path = 'http://host.domain/some/path'

    result = 'TheResult'
    patt = 'TheFilePattern'

    self.mox.StubOutWithMock(gslib, 'ListFiles')
    self.mox.StubOutWithMock(filelib, 'ListFiles')

    # Set up the test replay script.
    # Run 1, local.
    filelib.ListFiles(
        local_path, recurse=True, filepattern=None,
        sort=False).AndReturn(result)
    # Run 2, GS.
    gslib.ListFiles(
        gs_path, recurse=False, filepattern=patt, sort=True).AndReturn(result)
    # Run 4, HTTP.
    self.mox.ReplayAll()

    # Run the test verification.
    self.assertEquals(result, urilib.ListFiles(local_path, recurse=True))
    self.assertEquals(result, urilib.ListFiles(gs_path, filepattern=patt,
                                               sort=True))
    self.assertRaises(urilib.NotSupportedForType, urilib.ListFiles, http_path)
    self.mox.VerifyAll()


text:
class TSPacket
{
public:
	static const unsigned int size = 188;
	TSPacket();
	TSPacket(uint8_t *data, int n);

	bool transportError() { return header.transportError; }
	void print() { header.print(); }
	bool isNull() { return header.pid == 0x1FFF; }
	uint16_t getPid() { return header.pid; }
	bool getPayloadStart() { return header.payloadStart == 1; }
	uint8_t getContinuity() { return header.continuityCounter; }
	bool read(ifstream &in);
	bool parse();

	vector<uint8_t> payload;
private:
	struct Header
	{
		uint8_t syncByte : 8;
		uint8_t transportError;
		uint8_t payloadStart: 1;
		uint8_t transportPriority: 1;
		uint16_t pid: 13;
		uint8_t transportScrambling : 2;
		uint8_t adaptionField : 2;
		uint8_t continuityCounter : 4;

		void print()
		{
			cout << "Header:\n"
			<< "\t syncByte = 0x" << std::hex << +syncByte
			<< "\n\t transportError = 0x" << std::hex << +transportError
			<< "\n\t payloadStart = 0x" << std::hex << +payloadStart
			<< "\n\t transportPriority = 0x" << std::hex << +transportPriority
			<< "\n\t pid = 0x" << std::hex << pid
			<< "\n\t transportScrambling = 0x" << std::hex << +transportScrambling
			<< "\n\t adaptionField = 0x" << std::hex << +adaptionField
			<< "\n\t continuityCounter = 0x" << std::hex << +continuityCounter << endl;
		}
	};

	vector<uint8_t> raw;
	Header header;
	vector<uint8_t> adaptionField;

	string networkName;

};

#endif


text:
//
//  Copyright (c) 2015 Orbotix Inc. All rights reserved.
//

#import <CoreBluetooth/CoreBluetooth.h>

/*! abstracted radio link state
 @note this is the state that the robot is trying to enter
 */
typedef NS_ENUM (uint8_t, RKLEConnectionState) {
    /*! The communication link with a robot is not valid. */
    RKLEConnectionState_Offline,
    /*! Services and Characteristics are being discovered and configured */
    RKLEConnectionState_Connecting,
    /*! The robot is responding to communications and ready for commands to be sent. */
    RKLEConnectionState_Connected
};

@protocol RKLeNode;
@class RKRadioDescriptor;

@protocol RKLeInternalConnectDelegate <NSObject>

-(void)nodeDidConnect:(id<RKLeNode>) node;
-(void)nodeDidWake:(id<RKLeNode>) node;

@end

/*! data to enable a connect strategy to pick the best device to connect to */
@protocol RKLeNode <NSObject>

@property (nonatomic, readonly) NSNumber *RSSI;
@property (strong, nonatomic) NSDate* lastSeen;

/*! Current robot TX Power - advertised & updated when WriteRobotTxPower is requested
 @note range: -18 to +8 */
@property (nonatomic, readonly) NSNumber *advertisePower;
@property (strong, nonatomic, readonly) CBPeripheral* peripheral;
@property (strong, nonatomic, readonly) CBCentralManager* centralManager;
@property (nonatomic, weak, readonly) id<RKLeInternalConnectDelegate> connectDelegate;

/*! state Link is attempting to obtain */
@property (nonatomic, readonly) RKLEConnectionState connectionState;

-(id) initWithPeripheral:(CBPeripheral*) p andCentral:(CBCentralManager*) mgr;

-(NSString*) name;
-(NSNumber*) signalQuality;
-(BOOL)isConnecting;
-(BOOL)isConnected;

@optional
-(void) startServiceDiscoveryWith:(RKRadioDescriptor*) radioDescriptor;

@end


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <base href="/">
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>SounderRadio</title>
  <meta name="description" content="Sounder Radio - Online radio powered by SoundCloud">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/css/bootstrap.min.css" type="text/css" media="screen" title="no title" charset="utf-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">
</head>
<body>

  <sr-app><i class="fa fa-spinner fa-pulse center-view"></i></sr-app>

</body>
</html>