<commit_before>var spawn = require("child_process").spawn;
var exec = require("child_process").exec;
var fs = require("fs");
var path = require("path");
var createDir = require("./utils").createDir;
var readDotEnsimeValue = require("./utils").readDotEnsimeValue;
var readDotEnsimeArray = require("./utils").readDotEnsimeArray;

function Launcher(dotEnsime, ensimeVersion, installDir, sbtCmd) {
  this.dotEnsime = dotEnsime;
  this.ensimeVersion = ensimeVersion;
  this.installDir = installDir;
  this.sbtCmd = sbtCmd;

  this.classpathFile = installDir + path.sep + "ensime.classpath";
  this.ensimeCache = path.dirname(dotEnsime) + path.sep + ".ensime_cache";
  this.sbtVersion = "0.13.9";
  this.maxWaitMs = 30000; //max 5min startup time for ensime-server
}

/** Update ensime to the specified version. Can also be used to fix installations.
 * @param output {out: Stream, err: Stream}
 * @return nothing */
Launcher.prototype.update = function(output, callback) {
  console.log("Updating ensime-server.");
  this.cleanup(function () {
    try {
      fs.unlinkSync(this.classpathFile);
    } catch (e) {
      //didn't exist
    }
    this.install(output, callback);
  });
};

Launcher.prototype.install = function(output, callback) {
  console.log("Installing ensime-server " + this.ensimeVersion + " to " + this.installDir);
  createDir(this.installDir);
  createDir(this.installDir + path.sep + "project");

  var dotEnsimeContents = fs.readFileSync(this.dotEnsime, "utf-8");
  var scalaVersion = readDotEnsimeValue(dotEnsimeContents, "scala-version");
  console.log("Using scala version " + scalaVersion);

  // Generate build.sbt
  var buildSbtContents = generateBuildSbt(scalaVersion, this.ensimeVersion, this.classpathFile);
  fs.writeFileSync(this.installDir + path.sep + "build.sbt", buildSbtContents);
  // Generate build.properties
  var buildPropertiesContents = "sbt.version=" + this.sbtVersion;
  fs.writeFileSync(this.installDir + path.sep + "project" + path.sep + "build.properies", buildPropertiesContents);

  //Execute sbt
  var sbt = spawn(this.sbtCmd, ["-Dsbt.log.noformat=true", "saveClasspath", "clean"], {
    cwd: this.installDir
  });
  sbt.stdout.pipe(output.out);
  sbt.stderr.pipe(output.err);
  sbt.on("close", function(code) {
    if (code != 0) callback("SBT exited with code " + code);
    callback(false);
  });
  sbt.stdin.end();
};

function generateBuildSbt(scalaVersion, ensimeVersion, target) {
  return "" +
    "import sbt._\n" +
    "import IO._\n" +
    "import java.io._\n" +
    "scalaVersion := \"" + scalaVersion + "\"\n" +

    "ivyScala := ivyScala.value map { _.copy(overrideScalaVersion = true) }\n" +

    "// we don't need jcenter, so this speeds up resolution\n" +
    "fullResolvers -= Resolver.jcenterRepo\n" +
    "// allows local builds of scala\n" +
    "resolvers += Resolver.mavenLocal\n" +
    "// for java support\n" +
    "resolvers += \"NetBeans\" at \"http://bits.netbeans.org/nexus/content/groups/netbeans\"\n" +
    "// this is where the ensime-server snapshots are hosted\n" +
    "resolvers += Resolver.sonatypeRepo(\"snapshots\")\n" +

    "libraryDependencies ++= Seq(\n" +
    "  \"org.ensime\" %% \"ensime\" % \"" + ensimeVersion + "\"\n" +
    ")\n" +
    "dependencyOverrides ++= Set(\n" +
    "  \"org.scala-lang\" % \"scala-compiler\" % scalaVersion.value,\n" +
    "  \"org.scala-lang\" % \"scala-library\" % scalaVersion.value,\n" +
    "  \"org.scala-lang\" % \"scala-reflect\" % scalaVersion.value,\n" +
    "  \"org.scala-lang\" % \"scalap\" % scalaVersion.value\n" +
    ")\n" +

    "val saveClasspathTask = TaskKey[Unit](\"saveClasspath\", \"Save the classpath to a file\")\n" +
    "saveClasspathTask := {\n" +
    "  val managed = (managedClasspath in Runtime).value.map(_.data.getAbsolutePath)\n" +
    "  val unmanaged = (unmanagedClasspath in Runtime).value.map(_.data.getAbsolutePath)\n" +
    "  val out = file(\"" + target + "\")\n" +
    "  IO.write(out, (unmanaged ++ managed).mkString(File.pathSeparator))\n" +
    "}";
}

/** Start ensime.
 * @param output {out: Stream, err: Stream}
 * @return {http: Int} */
Launcher.prototype.start = function(output, callback) {
  if (this.ensimeProcess) return callback("Already running.");

  this.getClasspath(output, function(err, classpath) {
    if (err) return callback(err);
    console.log("Starting ensime-server for " + this.dotEnsime);
    this.ensimeProcess = startFromClasspath(output, this.dotEnsime, this.ensimeCache, classpath, function(err) {
      if (err) return callback(err);
      console.log("Waiting for ensime-server to start.");
      waitForPort(this.ensimeCache, this.maxWaitMs, callback);
    }.bind(this));
  }.bind(this));
};

Launcher.prototype.getClasspath = function(output, callback) {
  if (fs.existsSync(this.classpathFile)) {
    //already dowloaded ensime and its dependencies
    var contents = fs.readFileSync(this.classpathFile);
    callback(false, contents);
  }
  else {
    //need to download ensime-server first
    console.log("Need to install ensime-server first. Doing that now...\n");
    output.out.write("Need to download ENSIME first.");
    this.install(output, function(err) {
      if (err) return callback(err);
      output.out.write("Downloaded ENSIME.\n");
      var contents = fs.readFileSync(this.classpathFile);
      callback(false, contents);
    }.bind(this));
  }
};

function startFromClasspath(output, dotEnsime, ensimeCache, classpath, callback) {
  var dotEnsimeContents = fs.readFileSync(dotEnsime, "utf-8");
  var javaHome = readDotEnsimeValue(dotEnsimeContents, "java-home");
  var javaCmd = javaHome + path.sep + "bin" + path.sep + "java";
  var javaFlags = readDotEnsimeArray(dotEnsimeContents, "java-flags");
  console.log("Using JVM flags " + javaFlags.join(" "));

  createDir(ensimeCache);

  var toolsJar = javaHome + path.sep + "lib" + path.sep + "tools.jar";
  var args = ["-classpath", toolsJar + path.delimiter + classpath];
  args = args.concat(javaFlags);
  args.push("-Densime.config=" + dotEnsime);
  args.push("org.ensime.server.Server");
  var p = spawn(javaCmd, args);
  p.stdout.pipe(output.out);
  p.stderr.pipe(output.err);
  p.on("close", function(code) {
    console.log("Ensime server exited with code " + code);
  });
  p.stdin.end();

  var replied = false;
  p.on("error", function(err) {
    if (!replied) callback(err);
    replied = true;
  });
  p.stdout.on("data", function() {
    if (!replied) callback(false);
    replied = true;
  });
  return p;
}

function waitForPort(ensimeCache, maxMs, callback) {
  if (maxMs < 0) callback("Timeout waiting for ensime-server to start.");
  var httpFile = ensimeCache + path.sep + "http";
  try {
    var port = fs.readFileSync(httpFile);
    callback(false, {
      http: parseInt(port, 10)
    });
  }
  catch (e) {
    var t = 300;
    setTimeout(function() {
      waitForPort(ensimeCache, maxMs - t, callback);
    }, t);
  }
}

/** Stop ensime. */
Launcher.prototype.stop = function(callback) {
  if (this.ensimeProcess) {
    console.log("Stopping ensime process (" + this.ensimeProcess.pid + ")");
    this.ensimeProcess.kill();
    callback(false);
  }
  else callback(false);
};

/** Gets rid of a running ensime process even if it was not started here. */
Launcher.prototype.cleanup = function(callback) {
  try {
    var httpFile = this.ensimeCache + path.sep + "http";
    var portString = fs.readFileSync(httpFile);

    try {
      // Kill process holding the port
      var port = parseInt(portString, 10);
      exec("lsof -i :" + port + " | grep LISTEN | awk '{print $2}' | xargs kill -9");
      console.info("Killed process holding port " + port);
    }
    catch (e) {
      //ignore
    }
    finally {
      fs.unlinkSync(httpFile);
      console.log("Deleted http-port file.");
    }
  }
  catch (e) {
    //ignore
  }

  try {
    fs.unlinkSync(this.ensimeCache + path.sep + "port");
    console.log("Deleted port file.");
  }
  catch (e) {}

  callback(false);
};

/** Looks for a running ensime and returns the port it runs on. */
Launcher.prototype.ports = function(callback) {
  var httpFile = this.ensimeCache + path.sep + "http";
  try {
    var port = fs.readFileSync(httpFile);
    callback(false, {
      http: parseInt(port, 10)
    });
  }
  catch (e) {
    callback(true);
  }
};

module.exports = Launcher;<commit_msg>Add missing bind.<commit_after>var spawn = require("child_process").spawn;
var exec = require("child_process").exec;
var fs = require("fs");
var path = require("path");
var createDir = require("./utils").createDir;
var readDotEnsimeValue = require("./utils").readDotEnsimeValue;
var readDotEnsimeArray = require("./utils").readDotEnsimeArray;

function Launcher(dotEnsime, ensimeVersion, installDir, sbtCmd) {
  this.dotEnsime = dotEnsime;
  this.ensimeVersion = ensimeVersion;
  this.installDir = installDir;
  this.sbtCmd = sbtCmd;

  this.classpathFile = installDir + path.sep + "ensime.classpath";
  this.ensimeCache = path.dirname(dotEnsime) + path.sep + ".ensime_cache";
  this.sbtVersion = "0.13.9";
  this.maxWaitMs = 30000; //max 5min startup time for ensime-server
}

/** Update ensime to the specified version. Can also be used to fix installations.
 * @param output {out: Stream, err: Stream}
 * @return nothing */
Launcher.prototype.update = function(output, callback) {
  console.log("Updating ensime-server.");
  this.cleanup(function () {
    try {
      fs.unlinkSync(this.classpathFile);
    } catch (e) {
      //didn't exist
    }
    this.install(output, callback);
  }.bind(this));
};

Launcher.prototype.install = function(output, callback) {
  console.log("Installing ensime-server " + this.ensimeVersion + " to " + this.installDir);
  createDir(this.installDir);
  createDir(this.installDir + path.sep + "project");

  var dotEnsimeContents = fs.readFileSync(this.dotEnsime, "utf-8");
  var scalaVersion = readDotEnsimeValue(dotEnsimeContents, "scala-version");
  console.log("Using scala version " + scalaVersion);

  // Generate build.sbt
  var buildSbtContents = generateBuildSbt(scalaVersion, this.ensimeVersion, this.classpathFile);
  fs.writeFileSync(this.installDir + path.sep + "build.sbt", buildSbtContents);
  // Generate build.properties
  var buildPropertiesContents = "sbt.version=" + this.sbtVersion;
  fs.writeFileSync(this.installDir + path.sep + "project" + path.sep + "build.properies", buildPropertiesContents);

  //Execute sbt
  var sbt = spawn(this.sbtCmd, ["-Dsbt.log.noformat=true", "saveClasspath", "clean"], {
    cwd: this.installDir
  });
  sbt.stdout.pipe(output.out);
  sbt.stderr.pipe(output.err);
  sbt.on("close", function(code) {
    if (code != 0) callback("SBT exited with code " + code);
    callback(false);
  });
  sbt.stdin.end();
};

function generateBuildSbt(scalaVersion, ensimeVersion, target) {
  return "" +
    "import sbt._\n" +
    "import IO._\n" +
    "import java.io._\n" +
    "scalaVersion := \"" + scalaVersion + "\"\n" +

    "ivyScala := ivyScala.value map { _.copy(overrideScalaVersion = true) }\n" +

    "// we don't need jcenter, so this speeds up resolution\n" +
    "fullResolvers -= Resolver.jcenterRepo\n" +
    "// allows local builds of scala\n" +
    "resolvers += Resolver.mavenLocal\n" +
    "// for java support\n" +
    "resolvers += \"NetBeans\" at \"http://bits.netbeans.org/nexus/content/groups/netbeans\"\n" +
    "// this is where the ensime-server snapshots are hosted\n" +
    "resolvers += Resolver.sonatypeRepo(\"snapshots\")\n" +

    "libraryDependencies ++= Seq(\n" +
    "  \"org.ensime\" %% \"ensime\" % \"" + ensimeVersion + "\"\n" +
    ")\n" +
    "dependencyOverrides ++= Set(\n" +
    "  \"org.scala-lang\" % \"scala-compiler\" % scalaVersion.value,\n" +
    "  \"org.scala-lang\" % \"scala-library\" % scalaVersion.value,\n" +
    "  \"org.scala-lang\" % \"scala-reflect\" % scalaVersion.value,\n" +
    "  \"org.scala-lang\" % \"scalap\" % scalaVersion.value\n" +
    ")\n" +

    "val saveClasspathTask = TaskKey[Unit](\"saveClasspath\", \"Save the classpath to a file\")\n" +
    "saveClasspathTask := {\n" +
    "  val managed = (managedClasspath in Runtime).value.map(_.data.getAbsolutePath)\n" +
    "  val unmanaged = (unmanagedClasspath in Runtime).value.map(_.data.getAbsolutePath)\n" +
    "  val out = file(\"" + target + "\")\n" +
    "  IO.write(out, (unmanaged ++ managed).mkString(File.pathSeparator))\n" +
    "}";
}

/** Start ensime.
 * @param output {out: Stream, err: Stream}
 * @return {http: Int} */
Launcher.prototype.start = function(output, callback) {
  if (this.ensimeProcess) return callback("Already running.");

  this.getClasspath(output, function(err, classpath) {
    if (err) return callback(err);
    console.log("Starting ensime-server for " + this.dotEnsime);
    this.ensimeProcess = startFromClasspath(output, this.dotEnsime, this.ensimeCache, classpath, function(err) {
      if (err) return callback(err);
      console.log("Waiting for ensime-server to start.");
      waitForPort(this.ensimeCache, this.maxWaitMs, callback);
    }.bind(this));
  }.bind(this));
};

Launcher.prototype.getClasspath = function(output, callback) {
  if (fs.existsSync(this.classpathFile)) {
    //already dowloaded ensime and its dependencies
    var contents = fs.readFileSync(this.classpathFile);
    callback(false, contents);
  }
  else {
    //need to download ensime-server first
    console.log("Need to install ensime-server first. Doing that now...\n");
    output.out.write("Need to download ENSIME first.");
    this.install(output, function(err) {
      if (err) return callback(err);
      output.out.write("Downloaded ENSIME.\n");
      var contents = fs.readFileSync(this.classpathFile);
      callback(false, contents);
    }.bind(this));
  }
};

function startFromClasspath(output, dotEnsime, ensimeCache, classpath, callback) {
  var dotEnsimeContents = fs.readFileSync(dotEnsime, "utf-8");
  var javaHome = readDotEnsimeValue(dotEnsimeContents, "java-home");
  var javaCmd = javaHome + path.sep + "bin" + path.sep + "java";
  var javaFlags = readDotEnsimeArray(dotEnsimeContents, "java-flags");
  console.log("Using JVM flags " + javaFlags.join(" "));

  createDir(ensimeCache);

  var toolsJar = javaHome + path.sep + "lib" + path.sep + "tools.jar";
  var args = ["-classpath", toolsJar + path.delimiter + classpath];
  args = args.concat(javaFlags);
  args.push("-Densime.config=" + dotEnsime);
  args.push("org.ensime.server.Server");
  var p = spawn(javaCmd, args);
  p.stdout.pipe(output.out);
  p.stderr.pipe(output.err);
  p.on("close", function(code) {
    console.log("Ensime server exited with code " + code);
  });
  p.stdin.end();

  var replied = false;
  p.on("error", function(err) {
    if (!replied) callback(err);
    replied = true;
  });
  p.stdout.on("data", function() {
    if (!replied) callback(false);
    replied = true;
  });
  return p;
}

function waitForPort(ensimeCache, maxMs, callback) {
  if (maxMs < 0) callback("Timeout waiting for ensime-server to start.");
  var httpFile = ensimeCache + path.sep + "http";
  try {
    var port = fs.readFileSync(httpFile);
    callback(false, {
      http: parseInt(port, 10)
    });
  }
  catch (e) {
    var t = 300;
    setTimeout(function() {
      waitForPort(ensimeCache, maxMs - t, callback);
    }, t);
  }
}

/** Stop ensime. */
Launcher.prototype.stop = function(callback) {
  if (this.ensimeProcess) {
    console.log("Stopping ensime process (" + this.ensimeProcess.pid + ")");
    this.ensimeProcess.kill();
    callback(false);
  }
  else callback(false);
};

/** Gets rid of a running ensime process even if it was not started here. */
Launcher.prototype.cleanup = function(callback) {
  try {
    var httpFile = this.ensimeCache + path.sep + "http";
    var portString = fs.readFileSync(httpFile);

    try {
      // Kill process holding the port
      var port = parseInt(portString, 10);
      exec("lsof -i :" + port + " | grep LISTEN | awk '{print $2}' | xargs kill -9");
      console.info("Killed process holding port " + port);
    }
    catch (e) {
      //ignore
    }
    finally {
      fs.unlinkSync(httpFile);
      console.log("Deleted http-port file.");
    }
  }
  catch (e) {
    //ignore
  }

  try {
    fs.unlinkSync(this.ensimeCache + path.sep + "port");
    console.log("Deleted port file.");
  }
  catch (e) {}

  callback(false);
};

/** Looks for a running ensime and returns the port it runs on. */
Launcher.prototype.ports = function(callback) {
  var httpFile = this.ensimeCache + path.sep + "http";
  try {
    var port = fs.readFileSync(httpFile);
    callback(false, {
      http: parseInt(port, 10)
    });
  }
  catch (e) {
    callback(true);
  }
};

module.exports = Launcher;<|endoftext|>


<commit_before>'use strict';

const StripClassCallCheckPlugin = require('babel6-plugin-strip-class-callcheck');
const Funnel = require('broccoli-funnel');
const Rollup = require('broccoli-rollup');
const merge = require('broccoli-merge-trees');
const VersionChecker = require('ember-cli-version-checker');

const path = require('path');

const BlockScopingTransform = (function() {
  let plugin = require('babel-plugin-transform-es2015-block-scoping');

  // adding `baseDir` ensures that broccoli-babel-transpiler does not
  // issue a warning and opt out of caching
  let pluginPath = require.resolve('babel-plugin-transform-es2015-block-scoping/package');
  let pluginBaseDir = path.dirname(pluginPath);
  plugin.baseDir = () => pluginBaseDir;

  return plugin;
})();

function isProductionEnv() {
  const isProd = /production/.test(process.env.EMBER_ENV);
  const isTest = process.env.EMBER_CLI_TEST_COMMAND;

  return isProd && !isTest;
}

module.exports = {
  name: '@html-next/vertical-collection',

  init() {
    this._super.init && this._super.init.apply(this, arguments);

    this.options = this.options || {};
  },

  treeForAddon(tree) {
    let babel = this.addons.find((addon) => addon.name === 'ember-cli-babel');
    let withPrivate = new Funnel(tree, { include: ['-private/**'] });
    let withoutPrivate = new Funnel(tree, {
      exclude: [
        '**/**.hbs',
        '-private',
        isProductionEnv() ? '-debug' : false
      ].filter(Boolean),

      destDir: '@html-next/vertical-collection'
    });

    let privateTree = babel.transpileTree(withPrivate, {
      babel: this.options.babel,
      'ember-cli-babel': {
        compileModules: false
      }
    });

    const templateTree = new Funnel(tree, {
      include: ['**/**.hbs']
    });

    // use the default options
    const addonTemplateTree = this._super.treeForAddon.call(this, templateTree);
    let publicTree = babel.transpileTree(withoutPrivate);

    privateTree = new Rollup(privateTree, {
      rollup: {
        input: '-private/index.js',
        output: [
          {
            file: '@html-next/vertical-collection/-private.js',
            format: 'amd',
            amd: {
              id: '@html-next/vertical-collection/-private'
            }
          }
        ],
        external: ['ember', 'ember-raf-scheduler']
      }
    });

    // the output of treeForAddon is required to be modules/<your files>
    publicTree = new Funnel(publicTree, { destDir: 'modules' });
    privateTree = new Funnel(privateTree, { destDir: 'modules' });

    return merge([
      addonTemplateTree,
      publicTree,
      privateTree
    ]);
  },

  _hasSetupBabelOptions: false,
  buildBabelOptions(originalOptions) {
    const plugins = originalOptions.plugins || [];

    const opts = {
      loose: true,
      plugins,
      postTransformPlugins: [StripClassCallCheckPlugin],
      exclude: [
        'transform-es2015-block-scoping',
        'transform-es2015-typeof-symbol'
      ]
    };

    opts.plugins.push(
      [BlockScopingTransform, { 'throwIfClosureRequired': true }]
    );

    return opts;
  },
  _setupBabelOptions() {
    if (this._hasSetupBabelOptions) {
      return;
    }

    this.options.babel = this.buildBabelOptions(this.options.babel);

    this._hasSetupBabelOptions = true;
  },

  included(app) {
    this._super.included.apply(this, arguments);
    this.checker = new VersionChecker(app);

    while (typeof app.import !== 'function' && app.app) {
      app = app.app;
    }

    if (typeof app.import !== 'function') {
      throw new Error('vertical-collection is being used within another addon or engine '
        + 'and is having trouble registering itself to the parent application.');
    }

    this._env = app.env;
    this._setupBabelOptions(app.env);

    if (!/production/.test(app.env) && !/test/.test(app.env)) {
      app.import('vendor/debug.css');
    }
  },

  treeForApp() {
    const tree = this._super.treeForApp.apply(this, arguments);

    const exclude = [];

    if (isProductionEnv()) {
      exclude.push('initializers/debug.js');
    }

    if (this.checker.forEmber().isAbove('1.13.0')) {
      exclude.push('initializers/vertical-collection-legacy-compat.js');
    }

    return new Funnel(tree, { exclude });
  }
};
<commit_msg>Remove "find host" loop (#181)<commit_after>'use strict';

const StripClassCallCheckPlugin = require('babel6-plugin-strip-class-callcheck');
const Funnel = require('broccoli-funnel');
const Rollup = require('broccoli-rollup');
const merge = require('broccoli-merge-trees');
const VersionChecker = require('ember-cli-version-checker');

const path = require('path');

const BlockScopingTransform = (function() {
  let plugin = require('babel-plugin-transform-es2015-block-scoping');

  // adding `baseDir` ensures that broccoli-babel-transpiler does not
  // issue a warning and opt out of caching
  let pluginPath = require.resolve('babel-plugin-transform-es2015-block-scoping/package');
  let pluginBaseDir = path.dirname(pluginPath);
  plugin.baseDir = () => pluginBaseDir;

  return plugin;
})();

function isProductionEnv() {
  const isProd = /production/.test(process.env.EMBER_ENV);
  const isTest = process.env.EMBER_CLI_TEST_COMMAND;

  return isProd && !isTest;
}

module.exports = {
  name: '@html-next/vertical-collection',

  init() {
    this._super.init && this._super.init.apply(this, arguments);

    this.options = this.options || {};
  },

  treeForAddon(tree) {
    let babel = this.addons.find((addon) => addon.name === 'ember-cli-babel');
    let withPrivate = new Funnel(tree, { include: ['-private/**'] });
    let withoutPrivate = new Funnel(tree, {
      exclude: [
        '**/**.hbs',
        '-private',
        isProductionEnv() ? '-debug' : false
      ].filter(Boolean),

      destDir: '@html-next/vertical-collection'
    });

    let privateTree = babel.transpileTree(withPrivate, {
      babel: this.options.babel,
      'ember-cli-babel': {
        compileModules: false
      }
    });

    const templateTree = new Funnel(tree, {
      include: ['**/**.hbs']
    });

    // use the default options
    const addonTemplateTree = this._super.treeForAddon.call(this, templateTree);
    let publicTree = babel.transpileTree(withoutPrivate);

    privateTree = new Rollup(privateTree, {
      rollup: {
        input: '-private/index.js',
        output: [
          {
            file: '@html-next/vertical-collection/-private.js',
            format: 'amd',
            amd: {
              id: '@html-next/vertical-collection/-private'
            }
          }
        ],
        external: ['ember', 'ember-raf-scheduler']
      }
    });

    // the output of treeForAddon is required to be modules/<your files>
    publicTree = new Funnel(publicTree, { destDir: 'modules' });
    privateTree = new Funnel(privateTree, { destDir: 'modules' });

    return merge([
      addonTemplateTree,
      publicTree,
      privateTree
    ]);
  },

  _hasSetupBabelOptions: false,
  buildBabelOptions(originalOptions) {
    const plugins = originalOptions.plugins || [];

    const opts = {
      loose: true,
      plugins,
      postTransformPlugins: [StripClassCallCheckPlugin],
      exclude: [
        'transform-es2015-block-scoping',
        'transform-es2015-typeof-symbol'
      ]
    };

    opts.plugins.push(
      [BlockScopingTransform, { 'throwIfClosureRequired': true }]
    );

    return opts;
  },
  _setupBabelOptions() {
    if (this._hasSetupBabelOptions) {
      return;
    }

    this.options.babel = this.buildBabelOptions(this.options.babel);

    this._hasSetupBabelOptions = true;
  },

  included(app) {
    this._super.included.apply(this, arguments);
    this.checker = new VersionChecker(app);

    this._env = app.env;
    this._setupBabelOptions(app.env);

    if (!/production/.test(app.env) && !/test/.test(app.env)) {
      app.import('vendor/debug.css');
    }
  },

  treeForApp() {
    const tree = this._super.treeForApp.apply(this, arguments);

    const exclude = [];

    if (isProductionEnv()) {
      exclude.push('initializers/debug.js');
    }

    if (this.checker.forEmber().isAbove('1.13.0')) {
      exclude.push('initializers/vertical-collection-legacy-compat.js');
    }

    return new Funnel(tree, { exclude });
  }
};
<|endoftext|>


<commit_before>var bitwise = require('./bitwise.js')

// Use Hilbert curve point generation to map 2D data to 1D space and vice-versa.
// Will later expand to allow `n` dimensions.

function Point(x, y, z) {
    this.rotations = {
        x: 0,
        y: 0,
        z: 0
    }

    this.init = function (x, y, z) {
        this.x = Math.round(x) || 0
        this.y = Math.round(y) || 0
        if (z != null) {
            this.z = Math.round(z) || 0
            this.d = 3
            this.n = 4 * this.z + 2 * this.y  + this.x
        } else {
            this.z = null
            this.d = 2
        }
    }
    if (x instanceof Array) {
        this.init(x[0], x[1], x[2])
    } else {
        this.init(x, y, z)
    }
}

Point.prototype.rotate = function (p, n) { // :: Point -> Int -> Point
    // record rotations
    if (p.n == 0) return new Point(this.z, this.x, this.y)
    if (p.n == 1 || p.n == 3) return new Point(this.y, this.z, this.x)
    if (p.n == 2 || p.n == 6) return new Point(n - this.x, n - this.y, this.z)
    return new Point(n - this.z, this.x, n - this.y)
}

Point.prototype.rotate2d = function (n, xbit, ybit) { // : Int -> Int -> Int -> Point
    return new Point(rotate2d(n, this.x, this.y, xbit, ybit))
}

Point.prototype.rotate3d = function (level) { // :: Int -> Point
    return new Point(rotate3d(level, this.x, this.y, this.z))
}

Point.prototype.toArray = function () { // :: -> [Int, Int]
        if (this.d == 3) { return [this.x, this.y, this.z] }
        return [this.x, this.y]
}

Point.prototype.mod = function (n) { // :: Int -> Point
    return new Point(this.x % n, this.y % n, this.z % n)
}

// Accepts the height or width of a square/graph, and the coordinates to
// convert.
function convert2dPointToDistance (p, height) { // :: Int -> Int -> Int -> Int
    var xbit, ybit, level, d = 0
    var forHeight = p.x > p.y ? p.x : p.y

    // needs some tests to make sure height is compatible
    // What keeps the user from putting 54 down as the height
    while (forHeight >= height) {
            height *=2
    }
    // For each Hilbert level, we want to add an amount to
    // `d` based on which region we are in
    for (level = height / 2; level > 0; level = Math.floor(level / 2)) {
        // Determine what region we're in
        xbit = (p.x & level) > 0
        ybit = (p.y & level) > 0
        // increase distance based on region
        d += level * level * ((3 * xbit) ^ ybit)
        // rotate so that we'll be in sync with the next
        // region.
        p = p.rotate2d(level, xbit, ybit)
        // HEAD
        // p = p.rotate2d(height, xbit, ybit)
    }

    return d
}

// height and coordinates.
function convert3dPointToDistance (p, height) { // :: Int -> Int -> Int -> Int -> Int
    var s = 1, level = 0
    var max = Math.max.apply(Math, p.toArray())
    for (; 2 * s <= max; s *= 2) {
        level = (level + 1) % 3
    }

    // shuffle axes
    // rotate based on parity
}

// Accepts height or width of a square/graph and distance
function convertDistanceTo2dPoint (distance, height) { // :: Int -> Int -> [Int, Int]
    distance = Math.floor(distance)
    var xbit, ybit, level, p = new Point(0, 0)

    if (height <= Math.sqrt(distance))  {
        height = 2
        while (height <= Math.sqrt(distance)) {
            height *=2
        }
    }

    for (level = 1; level < height; level *= 2) {
        xbit = 1 & (distance / 2)
        ybit = 1 & (distance ^ xbit)

        p = p.rotate2d(level, xbit, ybit)
        p.x += level * xbit
        p.y += level * ybit
        distance = Math.floor(distance / 4)
    }

    return p.toArray()
}

// height/width of a square/graph and distance
function convertDistanceTo3dPoint (distance, height) { // Int -> Int -> [Int, Int, Int]
    distance = Math.floor(distance)
    var xbit, ybit, zbit, level, parity
    var iter = 2, log = 0, p = new Point(0, 0, 0)

    height = height || 2

    // vvv this is interesting.
    for (parity = 1; parity < height; parity *= 2, ++log) {}
    parity = log % 3;

    // the `|| distance` was removed from 2d version
    for (level = 1; level < height || distance > 0; level *=2) {
        xbit = distance & 1;
        ybit = (distance / 2) & 1;
        zbit = (distance / 4) & 1;

        var temp = rotate3d(level - 1, xbit ^ ybit, ybit ^ zbit, zbit)
        p.x = temp[0] * level + level - 1
        p.y = temp[1] * level + level - 1
        p.z = temp[2] * level + level - 1

        distance = Math.floor(distance / 8)
        level *= 2;
        iter++;
    }

    return p.rotateLeft(iter - parity + 1).toArray();
}

// Rotate the coordinate plane and (x,y)
function rotate2d (n, x, y, xbit, ybit) { // :: Int -> Int -> Int -> Int -> Int -> [Int, Int]
    if (ybit == 0  ) {
        if (xbit == 1) {
            x = n - 1 - x
            y = n - 1 - y
        }

        var temp = x
        x = y
        y = temp
    }

    return [x, y]
}

// Rotate the coordinate plane and (x,y, z)
function rotate3d(level, x, y, z) { // :: Int -> Int -> Int -> Int -> [Int, Int, Int]
    var index = 4 * z + 2 * y + x
    if (index == 0) {
        return [z, x, y]
    } else if (index == 1 || index == 3) {
        return [y, z, x]
    } else if (index == 2 || index == 6) {
        return [level - x, level - y, z]
    } else if (index == 5 || index == 7) {
        return [y, level - z, level - x]
    } else {
        return [level - z, x, level - y]
    }
}

function grayCode (sequence) {
    return sequence ^ (sequence >> 1)
}

// returns a non-negative int 'inverse' such that graycode(inverse) = g
function grayInverse (g) { // : Int -> Int
    var m = precision(g), inverse = g, j = 1
    while (j < m) {
        inverse = inverse ^ (g >> j)
        j++
    }
    return inverse
}

// Returns the number of bits required to store an integer
function precision (n) { // :: Int > Int
    var ret = 0
    while (n > 0) {
        ret++
        n = n >> 1
    }
    return ret
}

function grayTransform (entry, direction, x, dim) { // :: Int -> Int -> Int -> Int
    return bitwise.rotateRight((x ^ entry), dim, 0, direction + 1)
}

function grayInverseTransform (entry, direction, x, dim) { // :: Int -> Int -> Int -> Int
    return grayTransform(bitwise.rotateRight(entry, dim, 0, direction + 1), dim - direction - 1, x, dim)
}

function entrySequence (i) { // :: Int -> Int
    if (i) {
        return grayCode(2 * Math.floor((i-1) / 2))
    }
    return 0
}

function directionSequence(i, dim) { // :: Int -> Int -> Int
    if (i == 0) return 0
    if (i % 2 == 0) return trailingSetBits(i - 1) % dim
    return trailingSetBits(i) % dim
}

function trailingSetBits (i) { // :: Int -> Int
    var ones = ~i & (i + 1)
    return Math.log(ones) / Math.log(2)
}

function hilbertIndex(point, options) { // :: [Int, Int, ..] -> {} -> Int
    options = options || {}
    var index = 0, code,
        entry = options.entry || 0,
        direction = options.direction || 0,
        i = options.precision || precision(Math.max.apply(null, point)) - 1,
        dim = point.length

    while (i >= 0) {

        var bits = 0
        var mask = 1 << dim - 1

        for (var k = 0; k < point.length; k++) {
            if (point[dim - (k+1)] & (1 << i)) {
                bits |= mask
            }
            mask >>>= 1
        }

        bits = grayTransform(entry, direction, bits, dim)
        code = grayInverse(bits)

        entry = entry ^ bitwise.rotateLeft(entrySequence(code), dim, 0, direction + 1)
        direction = (direction + directionSequence(code, dim) + 1) % dim
        index = (index << dim) | code

        i--
    }

    return index
}

function hilbertIndexInverse(dim, index, options) { // :: Int -> Int -> [Int, Int, ..]
    options = options || {}
    var entry = options.entry || 0,
        direction = options.direction || 0,
        m = options.precision || precision(index),
        p = Array.apply(null, new Array(dim)).map(Number.prototype.valueOf, 0)

    for (var i = m - 1; i >= 0; i--) {

        var mask = 1 << (i * dim), bits = 0, code

        for (var k = dim - 1; k >= 0; k--) {
            if (index & (mask << k)) {
                bits |= (1 << k)
            }
        }

        code = grayInverseTransform(entry, direction, grayCode(bits), dim)

        for (var k = 0; k < dim; k++) {
            if (code & (1 << k)) {
                p[k] |= (1 << i)
            }
        }

        entry = entry ^ bitwise.rotateLeft(entrySequence(bits), dim, 0, direction + 1)
        direction = (direction + directionSequence(bits, dim) + 1) % dim
    }

    return p
}

function nthRoot(num, nArg, precArg) {
  var n = nArg || 2;
  var prec = precArg || 12;

  var x = 1; // Initial guess.
  for (var i=0; i<prec; i++) {
    x = 1/n * ((n-1)*x + (num / Math.pow(x, n-1)));
  }

  return x;
}

exports.xy2d = function (x, y, height) {
    height = height || 2
    return convert2dPointToDistance(new Point(x, y), height)
}

exports.xyz2d = function(x, y, z, height) {
    height = height || 2
    return convert3dPointToDistance(new Point(x, y, z), height)
}
exports.d2xy = convertDistanceTo2dPoint
exports.d2xyz = convertDistanceTo3dPoint
exports.hilbert = hilbertIndex
exports.hilbertInverse = hilbertIndexInverse
<commit_msg>Remove dead code.<commit_after>var bitwise = require('./bitwise.js')

// Use Hilbert curve point generation to map 2D data to 1D space and vice-versa.
// Will later expand to allow `n` dimensions.

function Point(x, y, z) {
    this.rotations = {
        x: 0,
        y: 0,
        z: 0
    }

    this.init = function (x, y, z) {
        this.x = Math.round(x) || 0
        this.y = Math.round(y) || 0
        if (z != null) {
            this.z = Math.round(z) || 0
            this.d = 3
            this.n = 4 * this.z + 2 * this.y  + this.x
        } else {
            this.z = null
            this.d = 2
        }
    }
    if (x instanceof Array) {
        this.init(x[0], x[1], x[2])
    } else {
        this.init(x, y, z)
    }
}

Point.prototype.rotate2d = function (n, xbit, ybit) { // : Int -> Int -> Int -> Point
    return new Point(rotate2d(n, this.x, this.y, xbit, ybit))
}

Point.prototype.rotate3d = function (level) { // :: Int -> Point
    return new Point(rotate3d(level, this.x, this.y, this.z))
}

Point.prototype.toArray = function () { // :: -> [Int, Int]
        if (this.d == 3) { return [this.x, this.y, this.z] }
        return [this.x, this.y]
}

// Accepts the height or width of a square/graph, and the coordinates to
// convert.
function convert2dPointToDistance (p, height) { // :: Int -> Int -> Int -> Int
    var xbit, ybit, level, d = 0
    var forHeight = p.x > p.y ? p.x : p.y

    // needs some tests to make sure height is compatible
    // What keeps the user from putting 54 down as the height
    while (forHeight >= height) {
            height *=2
    }
    // For each Hilbert level, we want to add an amount to
    // `d` based on which region we are in
    for (level = height / 2; level > 0; level = Math.floor(level / 2)) {
        // Determine what region we're in
        xbit = (p.x & level) > 0
        ybit = (p.y & level) > 0
        // increase distance based on region
        d += level * level * ((3 * xbit) ^ ybit)
        // rotate so that we'll be in sync with the next
        // region.
        p = p.rotate2d(level, xbit, ybit)
        // HEAD
        // p = p.rotate2d(height, xbit, ybit)
    }

    return d
}

// height and coordinates.
function convert3dPointToDistance (p, height) { // :: Int -> Int -> Int -> Int -> Int
    var s = 1, level = 0
    var max = Math.max.apply(Math, p.toArray())
    for (; 2 * s <= max; s *= 2) {
        level = (level + 1) % 3
    }

    // shuffle axes
    // rotate based on parity
}

// Accepts height or width of a square/graph and distance
function convertDistanceTo2dPoint (distance, height) { // :: Int -> Int -> [Int, Int]
    distance = Math.floor(distance)
    var xbit, ybit, level, p = new Point(0, 0)

    if (height <= Math.sqrt(distance))  {
        height = 2
        while (height <= Math.sqrt(distance)) {
            height *=2
        }
    }

    for (level = 1; level < height; level *= 2) {
        xbit = 1 & (distance / 2)
        ybit = 1 & (distance ^ xbit)

        p = p.rotate2d(level, xbit, ybit)
        p.x += level * xbit
        p.y += level * ybit
        distance = Math.floor(distance / 4)
    }

    return p.toArray()
}

// height/width of a square/graph and distance
function convertDistanceTo3dPoint (distance, height) { // Int -> Int -> [Int, Int, Int]
    distance = Math.floor(distance)
    var xbit, ybit, zbit, level, parity
    var iter = 2, log = 0, p = new Point(0, 0, 0)

    height = height || 2

    // vvv this is interesting.
    for (parity = 1; parity < height; parity *= 2, ++log) {}
    parity = log % 3;

    // the `|| distance` was removed from 2d version
    for (level = 1; level < height || distance > 0; level *=2) {
        xbit = distance & 1;
        ybit = (distance / 2) & 1;
        zbit = (distance / 4) & 1;

        var temp = rotate3d(level - 1, xbit ^ ybit, ybit ^ zbit, zbit)
        p.x = temp[0] * level + level - 1
        p.y = temp[1] * level + level - 1
        p.z = temp[2] * level + level - 1

        distance = Math.floor(distance / 8)
        level *= 2;
        iter++;
    }

    return p.rotateLeft(iter - parity + 1).toArray();
}

// Rotate the coordinate plane and (x,y)
function rotate2d (n, x, y, xbit, ybit) { // :: Int -> Int -> Int -> Int -> Int -> [Int, Int]
    if (ybit == 0  ) {
        if (xbit == 1) {
            x = n - 1 - x
            y = n - 1 - y
        }

        var temp = x
        x = y
        y = temp
    }

    return [x, y]
}

// Rotate the coordinate plane and (x,y, z)
function rotate3d(level, x, y, z) { // :: Int -> Int -> Int -> Int -> [Int, Int, Int]
    var index = 4 * z + 2 * y + x
    if (index == 0) {
        return [z, x, y]
    } else if (index == 1 || index == 3) {
        return [y, z, x]
    } else if (index == 2 || index == 6) {
        return [level - x, level - y, z]
    } else if (index == 5 || index == 7) {
        return [y, level - z, level - x]
    } else {
        return [level - z, x, level - y]
    }
}

function grayCode (sequence) {
    return sequence ^ (sequence >> 1)
}

// returns a non-negative int 'inverse' such that graycode(inverse) = g
function grayInverse (g) { // : Int -> Int
    var m = precision(g), inverse = g, j = 1
    while (j < m) {
        inverse = inverse ^ (g >> j)
        j++
    }
    return inverse
}

// Returns the number of bits required to store an integer
function precision (n) { // :: Int > Int
    var ret = 0
    while (n > 0) {
        ret++
        n = n >> 1
    }
    return ret
}

function grayTransform (entry, direction, x, dim) { // :: Int -> Int -> Int -> Int
    return bitwise.rotateRight((x ^ entry), dim, 0, direction + 1)
}

function grayInverseTransform (entry, direction, x, dim) { // :: Int -> Int -> Int -> Int
    return grayTransform(bitwise.rotateRight(entry, dim, 0, direction + 1), dim - direction - 1, x, dim)
}

function entrySequence (i) { // :: Int -> Int
    if (i) {
        return grayCode(2 * Math.floor((i-1) / 2))
    }
    return 0
}

function directionSequence(i, dim) { // :: Int -> Int -> Int
    if (i == 0) return 0
    if (i % 2 == 0) return trailingSetBits(i - 1) % dim
    return trailingSetBits(i) % dim
}

function trailingSetBits (i) { // :: Int -> Int
    var ones = ~i & (i + 1)
    return Math.log(ones) / Math.log(2)
}

function hilbertIndex(point, options) { // :: [Int, Int, ..] -> {} -> Int
    options = options || {}
    var index = 0, code,
        entry = options.entry || 0,
        direction = options.direction || 0,
        i = options.precision || precision(Math.max.apply(null, point)) - 1,
        dim = point.length

    while (i >= 0) {

        var bits = 0
        var mask = 1 << dim - 1

        for (var k = 0; k < point.length; k++) {
            if (point[dim - (k+1)] & (1 << i)) {
                bits |= mask
            }
            mask >>>= 1
        }

        bits = grayTransform(entry, direction, bits, dim)
        code = grayInverse(bits)

        entry = entry ^ bitwise.rotateLeft(entrySequence(code), dim, 0, direction + 1)
        direction = (direction + directionSequence(code, dim) + 1) % dim
        index = (index << dim) | code

        i--
    }

    return index
}

function hilbertIndexInverse(dim, index, options) { // :: Int -> Int -> [Int, Int, ..]
    options = options || {}
    var entry = options.entry || 0,
        direction = options.direction || 0,
        m = options.precision || precision(index),
        p = Array.apply(null, new Array(dim)).map(Number.prototype.valueOf, 0)

    for (var i = m - 1; i >= 0; i--) {

        var mask = 1 << (i * dim), bits = 0, code

        for (var k = dim - 1; k >= 0; k--) {
            if (index & (mask << k)) {
                bits |= (1 << k)
            }
        }

        code = grayInverseTransform(entry, direction, grayCode(bits), dim)

        for (var k = 0; k < dim; k++) {
            if (code & (1 << k)) {
                p[k] |= (1 << i)
            }
        }

        entry = entry ^ bitwise.rotateLeft(entrySequence(bits), dim, 0, direction + 1)
        direction = (direction + directionSequence(bits, dim) + 1) % dim
    }

    return p
}

function nthRoot(num, nArg, precArg) {
  var n = nArg || 2;
  var prec = precArg || 12;

  var x = 1; // Initial guess.
  for (var i=0; i<prec; i++) {
    x = 1/n * ((n-1)*x + (num / Math.pow(x, n-1)));
  }

  return x;
}

exports.xy2d = function (x, y, height) {
    height = height || 2
    return convert2dPointToDistance(new Point(x, y), height)
}

exports.xyz2d = function(x, y, z, height) {
    height = height || 2
    return convert3dPointToDistance(new Point(x, y, z), height)
}
exports.d2xy = convertDistanceTo2dPoint
exports.d2xyz = convertDistanceTo3dPoint
exports.hilbert = hilbertIndex
exports.hilbertInverse = hilbertIndexInverse
<|endoftext|>


<commit_before>/*!
 * msgpack-response
 * Copyright(c) 2017 Mobiltron Inc
 * MIT Licensed
 */

/**
 * Module dependencies.
 */
const _ = require('lodash');
const onHeaders = require('on-headers')
const msgpackLite = require('msgpack-lite');

/**
 * Module variables.
 * @private
 */
var cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/;

/**
 * Transform response data using msgpack.
 *
 * @return {Function} middleware
 * @public
 */
function mgsPackResponse () {

  return function _mgsPackResponse(req, res, next) {
    var ended = false;
    var length;
    var listeners = [];
    var stream;
    var _end = res.end;
    var _on = res.on;
    var _write = res.write;

    // flush
    res.flush = function flush () {
      if (stream) {
        stream.flush()
      }
    };

    // proxy
    res.write = function write(chunk, encoding) {
      if (ended) {
        return false
      }

      if (!this._header) {
        this._implicitHeader()
      }

      console.log(chunk);

      return stream
        ? stream.write(new Buffer(chunk, encoding))
        : _write.call(this, chunk, encoding)
    };

    //end
    res.end = function end (chunk, encoding) {
      if (ended) {
        return false;
      }

      if (!this._header) {
        // estimate the length
        if (!this.getHeader('Content-Length')) {
          length = chunkLength(chunk, encoding)
        }

        this._implicitHeader()
      }

      if (!stream) {
        return _end.call(this, chunk, encoding)
      }

      // mark ended
      ended = true;

      return chunk
        ? stream.end(new Buffer(chunk, encoding))
        : stream.end()
    };

    res.on = function on(type, listener) {
      if (!listeners || type !== 'drain') {
        return _on.call(this, type, listener)
      }

      if (stream) {
        return stream.on(type, listener)
      }

      // buffer listeners for future stream
      listeners.push([type, listener]);

      return this;
    };

    function noMsgPacking() {
      addListeners(res, _on, listeners);
      listeners = null;
    }

    onHeaders(res, function onResponseHeaders () {
      if (!shouldMsgPack(req, res)) {
        noMsgPacking();
        return;
      }

      // already msg packed
      if (res.get('Content-Type') === 'application/json') {
        noMsgPacking();
        return;
      }

      // head
      if (req.method === 'HEAD') {
        noMsgPacking();
        return;
      }

      stream = msgpackLite.createEncodeStream();

      addListeners(stream, stream.on, listeners);

      res.setHeader('Content-Type', 'application/x-msgpack');
      res.removeHeader('Content-Length');

      stream.on('data', function onStreamData (chunk) {
        if (_write.call(res, chunk) === false) {
          stream.pause()
        }
      });

      stream.on('end', function onStreamEnd () {
         _end.call(res)
      });

      _on.call(res, 'drain', function onResponseDrain () {
        stream.resume();
      });
    });

    next();
  }
}

function chunkLength (chunk, encoding) {
  if (!chunk) {
    return 0
  }

  return !Buffer.isBuffer(chunk)
    ? Buffer.byteLength(chunk, encoding)
    : chunk.length
}

/**
 * Default filter function.
 * @private
 */
function shouldMsgPack(req, res) {
  var acceptType = req.get('accept');
  var type = res.get('Content-Type');

  return _.isNil(acceptType) === false && acceptType === 'application/x-msgpack' && _.isNil(type) === false && type.match(/application\/json/)[0] === 'application/json';
}

/**
 * Add bufferred listeners to stream
 * @private
 */
function addListeners (stream, on, listeners) {
  for (var i = 0; i < listeners.length; i++) {
    on.apply(stream, listeners[i])
  }
}

/**
 * Module exports.
 * @public
 */
module.exports = mgsPackResponse;
<commit_msg>printout body<commit_after>/*!
 * msgpack-response
 * Copyright(c) 2017 Mobiltron Inc
 * MIT Licensed
 */

/**
 * Module dependencies.
 */
const _ = require('lodash');
const onHeaders = require('on-headers')
const msgpackLite = require('msgpack-lite');

/**
 * Module variables.
 * @private
 */
var cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/;

/**
 * Transform response data using msgpack.
 *
 * @return {Function} middleware
 * @public
 */
function mgsPackResponse () {

  return function _mgsPackResponse(req, res, next) {
    var ended = false;
    var length;
    var listeners = [];
    var stream;
    var _end = res.end;
    var _on = res.on;
    var _write = res.write;

    // flush
    res.flush = function flush () {
      if (stream) {
        stream.flush()
      }
    };

    // proxy
    res.write = function write(chunk, encoding) {
      if (ended) {
        return false
      }

      if (!this._header) {
        this._implicitHeader()
      }

      console.log(chunk);

      return stream
        ? stream.write(new Buffer(chunk, encoding))
        : _write.call(this, chunk, encoding)
    };

    //end
    res.end = function end (chunk, encoding) {
      if (ended) {
        return false;
      }

      if (!this._header) {
        // estimate the length
        if (!this.getHeader('Content-Length')) {
          length = chunkLength(chunk, encoding)
        }

        this._implicitHeader()
      }

      if (!stream) {
        return _end.call(this, chunk, encoding)
      }

      // mark ended
      ended = true;

      return chunk
        ? stream.end(new Buffer(chunk, encoding))
        : stream.end()
    };

    res.on = function on(type, listener) {
      if (!listeners || type !== 'drain') {
        return _on.call(this, type, listener)
      }

      if (stream) {
        return stream.on(type, listener)
      }

      // buffer listeners for future stream
      listeners.push([type, listener]);

      return this;
    };

    function noMsgPacking() {
      addListeners(res, _on, listeners);
      listeners = null;
    }

    onHeaders(res, function onResponseHeaders () {
      if (!shouldMsgPack(req, res)) {
        noMsgPacking();
        return;
      }

      // already msg packed
      if (res.get('Content-Type') === 'application/json') {
        noMsgPacking();
        return;
      }

      // head
      if (req.method === 'HEAD') {
        noMsgPacking();
        return;
      }

      stream = msgpackLite.createEncodeStream();
      console.log(req.body);

      addListeners(stream, stream.on, listeners);

      res.setHeader('Content-Type', 'application/x-msgpack');
      res.removeHeader('Content-Length');

      stream.on('data', function onStreamData (chunk) {
        if (_write.call(res, chunk) === false) {
          stream.pause()
        }
      });

      stream.on('end', function onStreamEnd () {
         _end.call(res)
      });

      _on.call(res, 'drain', function onResponseDrain () {
        stream.resume();
      });
    });

    next();
  }
}

function chunkLength (chunk, encoding) {
  if (!chunk) {
    return 0
  }

  return !Buffer.isBuffer(chunk)
    ? Buffer.byteLength(chunk, encoding)
    : chunk.length
}

/**
 * Default filter function.
 * @private
 */
function shouldMsgPack(req, res) {
  var acceptType = req.get('accept');
  var type = res.get('Content-Type');

  return _.isNil(acceptType) === false && acceptType === 'application/x-msgpack' && _.isNil(type) === false && type.match(/application\/json/)[0] === 'application/json';
}

/**
 * Add bufferred listeners to stream
 * @private
 */
function addListeners (stream, on, listeners) {
  for (var i = 0; i < listeners.length; i++) {
    on.apply(stream, listeners[i])
  }
}

/**
 * Module exports.
 * @public
 */
module.exports = mgsPackResponse;
<|endoftext|>


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

var EventEmitter = require('events').EventEmitter;
var csv = require('ya-csv');

var firstOctet  = 256 * 256 * 256;
var secondOctet = 256 * 256;
var thirdOctet  = 256;
var fourthOctet = 1;

var DB = function (csvfile) {
    if(!csvfile) throw new(Error)('Please provide a ip database file');

    this.ready = false;
    this.queue = [];
    this.items = [];
    this.emitter = new(EventEmitter)();

    var that = this;
    var reader = csv.createCsvFileReader(csvfile, {
        'separator': ',',
        'quote': '"',
        'escapechar': '"',
        'comment': '#',
    });

    reader.on('data', function(line) {
        var current = {};
        current.start   = parseInt(line[0]);
        current.end     = parseInt(line[1]);
        current.code    = line[4];
        current.country = line[6];

        that.items.push(current);
    });

    var error = false;
    reader.on('error', function (err) {
        error = new(Error)('csv parsing error, did you specify the database correctly?');
    });

    reader.on('end', function () {
        that.ready = true;
        if (!error) {
            that.emit('ready', null, that);
        } else {
            that.emit('ready', error);
        }
        that.queue.forEach(function (req) {
            that.lookup(req.ip, req.callback);
        });
    });
}

DB.prototype.on = function (event, callback) {
    this.emitter.on(event, callback);
};

DB.prototype.emit = function () {
    this.emitter.emit.apply(this.emitter, arguments);
};

DB.prototype.ipToInt = function(ip) {
    var octets = ip.split('.').map(function (octet) { return parseInt(octet) });

    octets[0] = octets[0] * firstOctet;
    octets[1] = octets[1] * secondOctet
    octets[2] = octets[2] * thirdOctet
    octets[3] = octets[3] * fourthOctet;

    return octets.reduce(function(sum, octet) { return octet + sum });
}

DB.prototype.intToIp = function(intIp) {
    var octets = [(intIp / firstOctet)  & 255,
                  (intIp / secondOctet) & 255,
                  (intIp / thirdOctet)  & 255,
                  (intIp / fourthOctet) & 255];

    return octets.join('.');
}

var sys = require('sys');
DB.prototype.bsearch = function (needle, heystack) {
    var start = 0,
        end = heystack.length - 1,
        middle, target;

    while (start < end) {
        middle = Math.floor((end - start) / 2) + start;
        target = heystack[middle];

        if (needle >= target.start && needle <= target.end) {
            return target;
        }

        if (needle < target.start)
            end = middle - 1;
        else
            start = middle + 1;
    }
};

DB.prototype._lookup = function (ip, callback) {
    var intIp = this.ipToInt(ip);

    var result = this.bsearch(intIp, this.items);
    if (result) {
        result.start_ip = this.intToIp(result.start);
        result.end_ip   = this.intToIp(result.end);
        callback && callback(null, result);
        return result;
    } else {
        callback && callback(new(Error)('ip not found'))
    }
};

DB.prototype.lookup = function (ip, callback) {
    if (!this.ready) {
        this.queue.push({ip: ip, callback: callback});
    } else {
        return this._lookup(ip, callback);
    }
}

var loadDB = function (dbfile, callback) {
    var db = new(DB)(dbfile);
    db.on('ready', callback);
};

exports.DB = DB;
exports.loadDB = loadDB;
<commit_msg>BUGFIX: handle csv errors correctly<commit_after>#!/usr/bin/env node

var EventEmitter = require('events').EventEmitter;
var csv = require('ya-csv');

var firstOctet  = 256 * 256 * 256;
var secondOctet = 256 * 256;
var thirdOctet  = 256;
var fourthOctet = 1;

var DB = function (csvfile) {
    if(!csvfile) throw new(Error)('Please provide a ip database file');

    this.ready = false;
    this.queue = [];
    this.items = [];
    this.emitter = new(EventEmitter)();

    var that = this;
    var reader = csv.createCsvFileReader(csvfile, {
        'separator': ',',
        'quote': '"',
        'escapechar': '"',
        'comment': '#',
    });

    reader.on('data', function(line) {
        var current = {};
        current.start   = parseInt(line[0]);
        current.end     = parseInt(line[1]);
        current.code    = line[4];
        current.country = line[6];

        that.items.push(current);
    });

    reader.on('error', function (err) {
        that.emit('ready', new(Error)('csv parsing error, did you specify the database correctly?'));
    });

    reader.on('end', function () {
        that.ready = true;
        that.emit('ready', null, that);

        that.queue.forEach(function (req) {
            that.lookup(req.ip, req.callback);
        });
    });
}

DB.prototype.on = function (event, callback) {
    this.emitter.on(event, callback);
};

DB.prototype.emit = function () {
    this.emitter.emit.apply(this.emitter, arguments);
};

DB.prototype.ipToInt = function(ip) {
    var octets = ip.split('.').map(function (octet) { return parseInt(octet) });

    octets[0] = octets[0] * firstOctet;
    octets[1] = octets[1] * secondOctet
    octets[2] = octets[2] * thirdOctet
    octets[3] = octets[3] * fourthOctet;

    return octets.reduce(function(sum, octet) { return octet + sum });
}

DB.prototype.intToIp = function(intIp) {
    var octets = [(intIp / firstOctet)  & 255,
                  (intIp / secondOctet) & 255,
                  (intIp / thirdOctet)  & 255,
                  (intIp / fourthOctet) & 255];

    return octets.join('.');
}

var sys = require('sys');
DB.prototype.bsearch = function (needle, heystack) {
    var start = 0,
        end = heystack.length - 1,
        middle, target;

    while (start < end) {
        middle = Math.floor((end - start) / 2) + start;
        target = heystack[middle];

        if (needle >= target.start && needle <= target.end) {
            return target;
        }

        if (needle < target.start)
            end = middle - 1;
        else
            start = middle + 1;
    }
};

DB.prototype._lookup = function (ip, callback) {
    var intIp = this.ipToInt(ip);

    var result = this.bsearch(intIp, this.items);
    if (result) {
        result.start_ip = this.intToIp(result.start);
        result.end_ip   = this.intToIp(result.end);
        callback && callback(null, result);
        return result;
    } else {
        callback && callback(new(Error)('ip not found'))
    }
};

DB.prototype.lookup = function (ip, callback) {
    if (!this.ready) {
        this.queue.push({ip: ip, callback: callback});
    } else {
        return this._lookup(ip, callback);
    }
}

var loadDB = function (dbfile, callback) {
    var db = new(DB)(dbfile);
    db.on('ready', callback);
};

exports.DB = DB;
exports.loadDB = loadDB;
<|endoftext|>


<commit_before>/*!
 * snakeskin-loader
 * https://github.com/SnakeskinTpl/snakeskin-loader
 *
 * Released under the MIT license
 * https://github.com/SnakeskinTpl/snakeskin-loader/blob/master/LICENSE
 */

var
	$C = require('collection.js').$C,
	parent = module.parent;

var
	path = require('path'),
	loaderUtils = require('loader-utils'),
	snakeskin = require('snakeskin'),
	babel = require('babel-core'),
	beautify = require('js-beautify'),
	exists = require('exists-sync');

module.exports = function (source) {
	if (this.cacheable) {
		this.cacheable();
	}

	var
		ssrc = path.join(process.cwd(), '.snakeskinrc'),
		opts = loaderUtils.parseQuery(this.query),
		tpls = {};

	if (!this.query && exists(ssrc)) {
		opts = snakeskin.toObj(ssrc);
	}

	opts = $C(opts).reduce(function (map, val, key) {
		map[key] = parse(val);
		return map;

	}, {
		debug: {},
		module: 'cjs',
		moduleId: 'tpls',
		useStrict: true,
		eol: '\n'
	});

	var
		eol = opts.eol,
		mod = opts.module,
		useStrict = opts.useStrict ? '"useStrict";' : '',
		prettyPrint = opts.prettyPrint,
		nRgxp = /\r?\n|\r/g;

	if (opts.jsx || opts.exec) {
		opts.module = 'cjs';
	}

	if (opts.jsx) {
		opts.literalBounds = ['{', '}'];
		opts.renderMode = 'stringConcat';
		opts.context = tpls;
		opts.exec = false;

	} else if (opts.exec) {
		if (opts.prettyPrint) {
			opts.prettyPrint = false;
		}

		opts.context = tpls;
	}

	opts.cache = false;
	opts.throws = true;
	opts.pack = opts.pack !== undefined ? opts.pack : true;

	var
		file = this.resourcePath,
		res = snakeskin.compile(source, opts, {file: file}),
		that = this;

	$C(opts.debug.files).forEach(function (bool, filePath) {
		that.addDependency(filePath);
	});

	function testId(id) {
		try {
			var obj = {};
			eval('obj.' + id + '= true');
			return true;

		} catch (ignore) {
			return false;
		}
	}

	function compileJSX(tpls, prop) {
		prop = prop || 'exports';
		$C(tpls).forEach(function (el, key) {
			var
				val,
				validKey = false;

			if (testId(key)) {
				val = prop + '.' + key;
				validKey = true;

			} else {
				val = prop + '["' + key.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"]';
			}

			if (typeof el !== 'function') {
				res +=
					'if (' + val + ' instanceof Object === false) {' +
						val + ' = {};' +
						(validKey && mod === 'native' ? 'export var ' + key + '=' + val + ';' : '') +
					'}'
				;

				return compileJSX(el, val);
			}

			var decl = /function .*?\)\s*\{/.exec(el.toString());
			res += babel.transform(val + ' = ' + decl[0] + ' ' + el(opts.data) + '};', {
				babelrc: false,
				plugins: [
					require('babel-plugin-syntax-jsx'),
					require('babel-plugin-transform-react-jsx'),
					require('babel-plugin-transform-react-display-name')
				]
			}).code;
		});
	}

	if (opts.jsx) {
		res = /\/\*[\s\S]*?\*\//.exec(res)[0];

		if (mod === 'native') {
			res +=
				useStrict +
				'import React from "react";' +
				'var exports = {};' +
				'export default exports;'
			;

		} else {
			res +=
				'(function(global, factory) {' +
					(
						{cjs: true, umd: true}[mod] ?
							'if (typeof exports === "object" && typeof module !== "undefined") {' +
								'factory(exports, typeof React === "undefined" ? require("react") : React);' +
								'return;' +
							'}' :
							''
					) +

					(
						{amd: true, umd: true}[mod] ?
							'if (typeof define === "function" && define.amd) {' +
								'define("' + (opts.moduleId) + '", ["exports", "react"], factory);' +
								'return;' +
							'}' :
							''
					) +

					(
						{global: true, umd: true}[mod] ?
							'factory(global' + (opts.moduleName ? '.' + opts.moduleName + '= {}' : '') + ', React);' :
							''
					) +

				'})(this, function (exports, React) {' +
					useStrict
			;
		}

		compileJSX(tpls);
		if (mod !== 'native') {
			res += '});';
		}

		if (prettyPrint) {
			res = beautify.js(res);
		}

		res = res.replace(nRgxp, eol) + eol;

	} else if (opts.exec) {
		res = snakeskin.getMainTpl(tpls, file, opts.tpl) || '';

		if (res) {
			res = res(opts.data);

			if (prettyPrint) {
				res = beautify.html(res);
			}

			res = res.replace(nRgxp, eol) + eol;
		}
	}

	return res;
};

function toJS(str) {
	return new Function(
		'module',
		'exports',
		'require',
		'__filename',
		'__dirname',
		'return ' + str

	)(parent, parent.exports, parent.require, parent.filename, path.dirname(parent.filename));
}

function parse(val) {
	try {
		if (typeof val === 'object') {
			$C(val).forEach(function (el, key) {
				val[key] = toJS(el);
			});

			return val;
		}

		return toJS(val);

	} catch (ignore) {
		return val;
	}
}
<commit_msg>:wrench:<commit_after>/*!
 * snakeskin-loader
 * https://github.com/SnakeskinTpl/snakeskin-loader
 *
 * Released under the MIT license
 * https://github.com/SnakeskinTpl/snakeskin-loader/blob/master/LICENSE
 */

var
	$C = require('collection.js').$C,
	parent = module.parent;

var
	path = require('path'),
	loaderUtils = require('loader-utils'),
	snakeskin = require('snakeskin'),
	babel = require('babel-core'),
	beautify = require('js-beautify'),
	exists = require('exists-sync');

module.exports = function (source) {
	if (this.cacheable) {
		this.cacheable();
	}

	var
		ssrc = path.join(process.cwd(), '.snakeskinrc'),
		opts = loaderUtils.parseQuery(this.query),
		tpls = {};

	if (!this.query && exists(ssrc)) {
		opts = snakeskin.toObj(ssrc);
	}

	opts = $C(opts).reduce(function (map, val, key) {
		map[key] = parse(val);
		return map;

	}, {
		debug: {},
		module: 'cjs',
		moduleId: 'tpls',
		useStrict: true,
		eol: '\n',
		pack: true
	});

	var
		eol = opts.eol,
		mod = opts.module,
		useStrict = opts.useStrict ? '"useStrict";' : '',
		prettyPrint = opts.prettyPrint,
		nRgxp = /\r?\n|\r/g;

	if (opts.jsx || opts.exec) {
		opts.module = 'cjs';
	}

	if (opts.jsx) {
		opts.literalBounds = ['{', '}'];
		opts.renderMode = 'stringConcat';
		opts.context = tpls;
		opts.exec = false;

	} else if (opts.exec) {
		if (opts.prettyPrint) {
			opts.prettyPrint = false;
		}

		opts.context = tpls;
	}

	opts.cache = false;
	opts.throws = true;

	var
		file = this.resourcePath,
		res = snakeskin.compile(source, opts, {file: file}),
		that = this;

	$C(opts.debug.files).forEach(function (bool, filePath) {
		that.addDependency(filePath);
	});

	function testId(id) {
		try {
			var obj = {};
			eval('obj.' + id + '= true');
			return true;

		} catch (ignore) {
			return false;
		}
	}

	function compileJSX(tpls, prop) {
		prop = prop || 'exports';
		$C(tpls).forEach(function (el, key) {
			var
				val,
				validKey = false;

			if (testId(key)) {
				val = prop + '.' + key;
				validKey = true;

			} else {
				val = prop + '["' + key.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"]';
			}

			if (typeof el !== 'function') {
				res +=
					'if (' + val + ' instanceof Object === false) {' +
						val + ' = {};' +
						(validKey && mod === 'native' ? 'export var ' + key + '=' + val + ';' : '') +
					'}'
				;

				return compileJSX(el, val);
			}

			var decl = /function .*?\)\s*\{/.exec(el.toString());
			res += babel.transform(val + ' = ' + decl[0] + ' ' + el(opts.data) + '};', {
				babelrc: false,
				plugins: [
					require('babel-plugin-syntax-jsx'),
					require('babel-plugin-transform-react-jsx'),
					require('babel-plugin-transform-react-display-name')
				]
			}).code;
		});
	}

	if (opts.jsx) {
		res = /\/\*[\s\S]*?\*\//.exec(res)[0];

		if (mod === 'native') {
			res +=
				useStrict +
				'import React from "react";' +
				'var exports = {};' +
				'export default exports;'
			;

		} else {
			res +=
				'(function(global, factory) {' +
					(
						{cjs: true, umd: true}[mod] ?
							'if (typeof exports === "object" && typeof module !== "undefined") {' +
								'factory(exports, typeof React === "undefined" ? require("react") : React);' +
								'return;' +
							'}' :
							''
					) +

					(
						{amd: true, umd: true}[mod] ?
							'if (typeof define === "function" && define.amd) {' +
								'define("' + (opts.moduleId) + '", ["exports", "react"], factory);' +
								'return;' +
							'}' :
							''
					) +

					(
						{global: true, umd: true}[mod] ?
							'factory(global' + (opts.moduleName ? '.' + opts.moduleName + '= {}' : '') + ', React);' :
							''
					) +

				'})(this, function (exports, React) {' +
					useStrict
			;
		}

		compileJSX(tpls);
		if (mod !== 'native') {
			res += '});';
		}

		if (prettyPrint) {
			res = beautify.js(res);
		}

		res = res.replace(nRgxp, eol) + eol;

	} else if (opts.exec) {
		res = snakeskin.getMainTpl(tpls, file, opts.tpl) || '';

		if (res) {
			res = res(opts.data);

			if (prettyPrint) {
				res = beautify.html(res);
			}

			res = res.replace(nRgxp, eol) + eol;
		}
	}

	return res;
};

function toJS(str) {
	return new Function(
		'module',
		'exports',
		'require',
		'__filename',
		'__dirname',
		'return ' + str

	)(parent, parent.exports, parent.require, parent.filename, path.dirname(parent.filename));
}

function parse(val) {
	try {
		if (typeof val === 'object') {
			$C(val).forEach(function (el, key) {
				val[key] = toJS(el);
			});

			return val;
		}

		return toJS(val);

	} catch (ignore) {
		return val;
	}
}
<|endoftext|>


<commit_before>module.exports.settings = require('./lib/settings');
module.exports.functions = require('./lib/functions');
module.exports.tasks = require('./lib/tasks');
module.exports.featureman = require('./lib/featureman');

if (process.env.PRODUCT_DIR) {
  module.exports.context = require('./lib/context');
  module.exports.product = require('./lib/product');
}
<commit_msg>index now in lib<commit_after><|endoftext|>


<commit_before>//var ttss_base = 'http://www.ttss.krakow.pl/internetservice/services';
var ttss_base = '/proxy.php';
var ttss_refresh = 20000; // 20 seconds

var stop_id;
var stop_name = document.getElementById('stop-name');
var stop_name_form = stop_name.form;
var stop_name_autocomplete = document.getElementById('stop-name-autocomplete');
var stop_name_autocomplete_xhr;

var times_xhr;
var times_timer;
var times_stop_name = document.getElementById('times-stop-name');
var times_alerts = document.getElementById('times-alerts');
var times_table = document.getElementById('times-table');
var times_lines = document.getElementById('times-lines');

/*
var route_xhr;
var route_line = document.getElementById('route-line');
var route_table = document.getElementById('route-table');
*/

var refresh_button = document.getElementById('refresh');
var refresh_text = document.getElementById('refresh-text');
var refresh_time;
var refresh_timer;

var alert = document.getElementById('alert');
var alert_text = document.getElementById('alert-text');
var alert_close = document.getElementById('alert-close');

function parseStatus(status) {
	switch(status.status) {
		case 'STOPPING':
			return '<<<';
		case 'PREDICTED':
			if(status.actualRelativeTime <= 0)
				return '<<<';
			if(status.actualRelativeTime >= 60)
				return Math.floor(status.actualRelativeTime / 60) + ' min';
			return status.actualRelativeTime + ' s';
		case 'DEPARTED':
			return Math.floor(-status.actualRelativeTime / 60) + ' min ago';
		default:
			return status.mixedTime;
	}
}

function parseTime(date, time) {
	var result = new Date(date.getFullYear(), date.getMonth(), date.getDay());
	var time_split = time.split(':');
	result.setHours(time_split[0]);
	result.setMinutes(time_split[1]);

	if(result.getTime() - date.getTime() > 72000000) {
		result.setTime(result.getTime() - 86400000);
	}

	if(date.getTime() - result.getTime() > 72000000) {
		result.setTime(result.getTime() + 86400000);
	}

	return result;
}

function parseDelay(status) {
	if(!status.actualTime) return '?';
	if(!status.plannedTime) return '?';

	var now = new Date();
	var actual = parseTime(now, status.actualTime);
	var planned = parseTime(now, status.plannedTime);

	return ((actual.getTime() - planned.getTime()) / 1000 / 60) + ' min';
}

function deleteChildren(element) {
	while(element.lastChild) element.removeChild(element.lastChild);
}

function addElementWithText(parent, element, text) {
	var elem = document.createElement(element);
	elem.appendChild(document.createTextNode(text));
	parent.appendChild(elem);
	return elem;
}

function addCellWithText(parent, text) {
	addElementWithText(parent, 'td', text);
}

function addParaWithText(parent, text) {
	addElementWithText(parent, 'p', text);
}

function setText(element, text) {
	deleteChildren(element);
	element.appendChild(document.createTextNode(text));
}

function fail(message, more) {
	if(refresh_timer) clearInterval(refresh_timer);
	if(times_timer) clearTimeout(times_timer);

	setText(alert_text, message);
	alert.style.display = 'block';

	console.log(message + ' More details follow.');
	if(more) console.log(more);
}

function fail_ajax(data) {
	// abort() is not a failure
	if(data.readyState == 0 && data.statusText == 'abort') return;

	if(data.status == 0) {
		fail('Request failed - please check your network connectivity.', data);
	} else if (data.statusText) {
		fail('Internet request failed with error: ' + data.statusText + '.', data);
	} else {
		fail('Internet request failed.', data);
	}
}

function loadTimes(stopId = null, clearRoute = false) {
	if(!stopId) stopId = stop_id;
	if(!stopId) return;

	if(times_timer) clearTimeout(times_timer);
	if(times_xhr) times_xhr.abort();

	refresh_button.removeAttribute('disabled');

	times_xhr = $.get(
		ttss_base + '/passageInfo/stopPassages/stop'
			+ '?stop=' + encodeURIComponent(stopId)
			+ '&mode=departure'
	).done(function(data) {
		setText(times_stop_name, data.stopName);
		deleteChildren(times_alerts);
		deleteChildren(times_table);
		deleteChildren(times_lines);
		/*
		if(clearRoute) {
			deleteChildren(route_line);
			deleteChildren(route_table);
		}
		*/

		for(var i = 0, il = data.generalAlerts.length; i < il; i++) {
			addParaWithText(times_alerts, data.generalAlerts[i]);
		}

		for(var i = 0, il = data.old.length; i < il; i++) {
			var tr = document.createElement('tr');
			addCellWithText(tr, data.old[i].patternText);
			addCellWithText(tr, data.old[i].direction);
			var status = parseStatus(data.old[i]);
			addCellWithText(tr, status);
			addCellWithText(tr, '');

			tr.className = 'active';
			times_table.appendChild(tr);
		}

		for(var i = 0, il = data.actual.length; i < il; i++) {
			var tr = document.createElement('tr');
			addCellWithText(tr, data.actual[i].patternText);
			addCellWithText(tr, data.actual[i].direction);
			var status = parseStatus(data.actual[i]);
			addCellWithText(tr, status);
			var delay = parseDelay(data.actual[i]);
			addCellWithText(tr, delay);

			if(status == '<<<') tr.className = 'success';
			else if(parseInt(delay) > 9) tr.className = 'danger';
			else if(parseInt(delay) > 3) tr.className = 'warning';
			times_table.appendChild(tr);
		}

		for(var i = 0, il = data.routes.length; i < il; i++) {
			var tr = document.createElement('tr');
			addCellWithText(tr, data.routes[i].name);
			addCellWithText(tr, data.routes[i].directions.join(' - '));
			addCellWithText(tr, data.routes[i].authority);

			/*
			tr.addEventListener('click', function(routeId, routeTr){ return function(e) {
				var trs = tr.parentNode;
				for(var i = 0; i < trs.childNodes.length; i++) {
					trs.childNodes[i].removeAttribute('class');
				}
				routeTr.className = 'warning';

				if(route_xhr) route_xhr.abort();
				route_xhr = $.get(
					ttss_base + '/routeInfo/routeStops'
						+ '?routeId=' + encodeURIComponent(routeId)
				).done(function(data) {
					setText(route_line, data.route.name + ': '
						+ data.route.directions.join(' - '));
					deleteChildren(route_table);

					routeTr.className = 'success';

					for(var i = 0, il = data.stops.length; i < il; i++) {
						var tr = document.createElement('tr');
						addCellWithText(tr, data.stops[i].name);
						route_table.appendChild(tr);
					}
				}).fail(fail_ajax);
			}}(data.routes[i].id, tr));
			*/

			times_lines.appendChild(tr);

			for(var j = 0, jl = data.routes[i].alerts.length; j < jl; j++) {
				addParaWithText(
					times_alerts,
					'Line ' +  data.routes[i].name + ': '
						+ data.routes[i].alerts[j]
				);
			}
		}

		startTimer(new Date());

		times_timer = setTimeout(function(){ loadTimes(); }, ttss_refresh);
	}).fail(fail_ajax);
}

function declinate(num, singular, plural) {
	if(num == 1) return num + ' ' + singular;
	return num + ' ' + plural;
}

function startTimer(date) {
	if(date) {
		setText(refresh_text, 'Last refreshed: just now')
		refresh_time = date;
	}
	if(!refresh_time) return;
	if(refresh_timer) clearInterval(refresh_timer);

	var now = new Date();
	var ms = now.getTime() - refresh_time.getTime();

	var interval = 1000;
	if(ms >= 120000) interval = 60000;

	refresh_timer = setInterval(function() {
		var now = new Date();
		var ms = now.getTime() - refresh_time.getTime();

		if(ms >= 120000) {
			setText(refresh_text, 'Last refreshed: '
				+ declinate(Math.floor(ms / 60000), 'minute ago', 'minutes ago'));
			startTimer();
		} else {
			setText(refresh_text, 'Last refreshed: '
				+ declinate(Math.floor(ms / 1000), 'second ago', 'seconds ago'));
		}
	}, interval);
}

function init() {
	if(!window.jQuery) {
		fail('Required JavaScript jQuery library failed to load. You may try refreshing the page.');
		return;
	}

	$.ajaxSetup({
		dataType: 'json',
		timeout: 3000,
	});

	stop_name.addEventListener('input', function(e) {
		if(!stop_name.value) return;
		if(stop_name_autocomplete_xhr) stop_name_autocomplete_xhr.abort();

		stop_name_autocomplete_xhr = $.get(
			ttss_base + '/lookup/autocomplete/json'
				+ '?query=' + encodeURIComponent(stop_name.value)
		).done(function(data) {
			deleteChildren(stop_name_autocomplete);
			for(var i = 1, il = data.length; i < il; i++) {
				var opt = document.createElement('option');
				opt.value = data[i].id;
				opt.appendChild(document.createTextNode(data[i].name));
				stop_name_autocomplete.appendChild(opt);
			}

			if(!stop_id) setText(refresh_text, 'Select the stop and click "Go"');
		}).fail(fail_ajax);
	});

	setText(refresh_text, 'Enter the stop name to begin');

	stop_name_form.addEventListener('submit', function(e) {
		e.preventDefault();
		if(!stop_name_autocomplete.value) return;
		stop_id = stop_name_autocomplete.value;
		loadTimes(stop_id, true);
	});

	refresh_button.addEventListener('click', function(e) {
		loadTimes(stop_id);
	});

	alert_close.addEventListener('click', function(e) {
		alert.style.display = 'none';
	});
}

init();
<commit_msg>Decode non-latin characters in stop names autocompletion<commit_after>//var ttss_base = 'http://www.ttss.krakow.pl/internetservice/services';
var ttss_base = '/proxy.php';
var ttss_refresh = 20000; // 20 seconds

var stop_id;
var stop_name = document.getElementById('stop-name');
var stop_name_form = stop_name.form;
var stop_name_autocomplete = document.getElementById('stop-name-autocomplete');
var stop_name_autocomplete_xhr;

var times_xhr;
var times_timer;
var times_stop_name = document.getElementById('times-stop-name');
var times_alerts = document.getElementById('times-alerts');
var times_table = document.getElementById('times-table');
var times_lines = document.getElementById('times-lines');

/*
var route_xhr;
var route_line = document.getElementById('route-line');
var route_table = document.getElementById('route-table');
*/

var refresh_button = document.getElementById('refresh');
var refresh_text = document.getElementById('refresh-text');
var refresh_time;
var refresh_timer;

var alert = document.getElementById('alert');
var alert_text = document.getElementById('alert-text');
var alert_close = document.getElementById('alert-close');

function parseStatus(status) {
	switch(status.status) {
		case 'STOPPING':
			return '<<<';
		case 'PREDICTED':
			if(status.actualRelativeTime <= 0)
				return '<<<';
			if(status.actualRelativeTime >= 60)
				return Math.floor(status.actualRelativeTime / 60) + ' min';
			return status.actualRelativeTime + ' s';
		case 'DEPARTED':
			return Math.floor(-status.actualRelativeTime / 60) + ' min ago';
		default:
			return status.mixedTime;
	}
}

function parseTime(date, time) {
	var result = new Date(date.getFullYear(), date.getMonth(), date.getDay());
	var time_split = time.split(':');
	result.setHours(time_split[0]);
	result.setMinutes(time_split[1]);

	if(result.getTime() - date.getTime() > 72000000) {
		result.setTime(result.getTime() - 86400000);
	}

	if(date.getTime() - result.getTime() > 72000000) {
		result.setTime(result.getTime() + 86400000);
	}

	return result;
}

function parseDelay(status) {
	if(!status.actualTime) return '?';
	if(!status.plannedTime) return '?';

	var now = new Date();
	var actual = parseTime(now, status.actualTime);
	var planned = parseTime(now, status.plannedTime);

	return ((actual.getTime() - planned.getTime()) / 1000 / 60) + ' min';
}

function deleteChildren(element) {
	while(element.lastChild) element.removeChild(element.lastChild);
}

function addElementWithText(parent, element, text) {
	var elem = document.createElement(element);
	elem.appendChild(document.createTextNode(text));
	parent.appendChild(elem);
	return elem;
}

function addCellWithText(parent, text) {
	addElementWithText(parent, 'td', text);
}

function addParaWithText(parent, text) {
	addElementWithText(parent, 'p', text);
}

function setText(element, text) {
	deleteChildren(element);
	element.appendChild(document.createTextNode(text));
}

function fail(message, more) {
	if(refresh_timer) clearInterval(refresh_timer);
	if(times_timer) clearTimeout(times_timer);

	setText(alert_text, message);
	alert.style.display = 'block';

	console.log(message + ' More details follow.');
	if(more) console.log(more);
}

function fail_ajax(data) {
	// abort() is not a failure
	if(data.readyState == 0 && data.statusText == 'abort') return;

	if(data.status == 0) {
		fail('Request failed - please check your network connectivity.', data);
	} else if (data.statusText) {
		fail('Internet request failed with error: ' + data.statusText + '.', data);
	} else {
		fail('Internet request failed.', data);
	}
}

function loadTimes(stopId = null, clearRoute = false) {
	if(!stopId) stopId = stop_id;
	if(!stopId) return;

	if(times_timer) clearTimeout(times_timer);
	if(times_xhr) times_xhr.abort();

	refresh_button.removeAttribute('disabled');

	times_xhr = $.get(
		ttss_base + '/passageInfo/stopPassages/stop'
			+ '?stop=' + encodeURIComponent(stopId)
			+ '&mode=departure'
	).done(function(data) {
		setText(times_stop_name, data.stopName);
		deleteChildren(times_alerts);
		deleteChildren(times_table);
		deleteChildren(times_lines);
		/*
		if(clearRoute) {
			deleteChildren(route_line);
			deleteChildren(route_table);
		}
		*/

		for(var i = 0, il = data.generalAlerts.length; i < il; i++) {
			addParaWithText(times_alerts, data.generalAlerts[i]);
		}

		for(var i = 0, il = data.old.length; i < il; i++) {
			var tr = document.createElement('tr');
			addCellWithText(tr, data.old[i].patternText);
			addCellWithText(tr, data.old[i].direction);
			var status = parseStatus(data.old[i]);
			addCellWithText(tr, status);
			addCellWithText(tr, '');

			tr.className = 'active';
			times_table.appendChild(tr);
		}

		for(var i = 0, il = data.actual.length; i < il; i++) {
			var tr = document.createElement('tr');
			addCellWithText(tr, data.actual[i].patternText);
			addCellWithText(tr, data.actual[i].direction);
			var status = parseStatus(data.actual[i]);
			addCellWithText(tr, status);
			var delay = parseDelay(data.actual[i]);
			addCellWithText(tr, delay);

			if(status == '<<<') tr.className = 'success';
			else if(parseInt(delay) > 9) tr.className = 'danger';
			else if(parseInt(delay) > 3) tr.className = 'warning';
			times_table.appendChild(tr);
		}

		for(var i = 0, il = data.routes.length; i < il; i++) {
			var tr = document.createElement('tr');
			addCellWithText(tr, data.routes[i].name);
			addCellWithText(tr, data.routes[i].directions.join(' - '));
			addCellWithText(tr, data.routes[i].authority);

			/*
			tr.addEventListener('click', function(routeId, routeTr){ return function(e) {
				var trs = tr.parentNode;
				for(var i = 0; i < trs.childNodes.length; i++) {
					trs.childNodes[i].removeAttribute('class');
				}
				routeTr.className = 'warning';

				if(route_xhr) route_xhr.abort();
				route_xhr = $.get(
					ttss_base + '/routeInfo/routeStops'
						+ '?routeId=' + encodeURIComponent(routeId)
				).done(function(data) {
					setText(route_line, data.route.name + ': '
						+ data.route.directions.join(' - '));
					deleteChildren(route_table);

					routeTr.className = 'success';

					for(var i = 0, il = data.stops.length; i < il; i++) {
						var tr = document.createElement('tr');
						addCellWithText(tr, data.stops[i].name);
						route_table.appendChild(tr);
					}
				}).fail(fail_ajax);
			}}(data.routes[i].id, tr));
			*/

			times_lines.appendChild(tr);

			for(var j = 0, jl = data.routes[i].alerts.length; j < jl; j++) {
				addParaWithText(
					times_alerts,
					'Line ' +  data.routes[i].name + ': '
						+ data.routes[i].alerts[j]
				);
			}
		}

		startTimer(new Date());

		times_timer = setTimeout(function(){ loadTimes(); }, ttss_refresh);
	}).fail(fail_ajax);
}

function declinate(num, singular, plural) {
	if(num == 1) return num + ' ' + singular;
	return num + ' ' + plural;
}

function startTimer(date) {
	if(date) {
		setText(refresh_text, 'Last refreshed: just now')
		refresh_time = date;
	}
	if(!refresh_time) return;
	if(refresh_timer) clearInterval(refresh_timer);

	var now = new Date();
	var ms = now.getTime() - refresh_time.getTime();

	var interval = 1000;
	if(ms >= 120000) interval = 60000;

	refresh_timer = setInterval(function() {
		var now = new Date();
		var ms = now.getTime() - refresh_time.getTime();

		if(ms >= 120000) {
			setText(refresh_text, 'Last refreshed: '
				+ declinate(Math.floor(ms / 60000), 'minute ago', 'minutes ago'));
			startTimer();
		} else {
			setText(refresh_text, 'Last refreshed: '
				+ declinate(Math.floor(ms / 1000), 'second ago', 'seconds ago'));
		}
	}, interval);
}

var decodeEntitiesTextArea = document.createElement('textarea');
function decodeEntities(text) {
	decodeEntitiesTextArea.innerHTML = text;
	return decodeEntitiesTextArea.value;
}

function init() {
	if(!window.jQuery) {
		fail('Required JavaScript jQuery library failed to load. You may try refreshing the page.');
		return;
	}

	$.ajaxSetup({
		dataType: 'json',
		timeout: 3000,
	});

	stop_name.addEventListener('input', function(e) {
		if(!stop_name.value) return;
		if(stop_name_autocomplete_xhr) stop_name_autocomplete_xhr.abort();

		stop_name_autocomplete_xhr = $.get(
			ttss_base + '/lookup/autocomplete/json'
				+ '?query=' + encodeURIComponent(stop_name.value)
		).done(function(data) {
			deleteChildren(stop_name_autocomplete);
			for(var i = 1, il = data.length; i < il; i++) {
				var opt = document.createElement('option');
				opt.value = data[i].id;
				setText(opt, decodeEntities(data[i].name));
				stop_name_autocomplete.appendChild(opt);
			}

			if(!stop_id) setText(refresh_text, 'Select the stop and click "Go"');
		}).fail(fail_ajax);
	});

	setText(refresh_text, 'Enter the stop name to begin');

	stop_name_form.addEventListener('submit', function(e) {
		e.preventDefault();
		if(!stop_name_autocomplete.value) return;
		stop_id = stop_name_autocomplete.value;
		loadTimes(stop_id, true);
	});

	refresh_button.addEventListener('click', function(e) {
		loadTimes(stop_id);
	});

	alert_close.addEventListener('click', function(e) {
		alert.style.display = 'none';
	});
}

init();
<|endoftext|>


<commit_before>'use strict';
const fs = require('fs');

let isDocker;

function hasDockerEnv() {
	try {
		fs.statSync('/.dockerenv');
		return true;
	} catch (_) {
		return false;
	}
}

function hasDockerCGroup() {
	try {
		return fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');
	} catch (_) {
		return false;
	}
}

module.exports = () => {
	if (isDocker === undefined) {
		isDocker = hasDockerEnv() || hasDockerCGroup();
	}

	return isDocker;
};
<commit_msg>Improve detection<commit_after>'use strict';
const fs = require('fs');

let isDocker;

function hasDockerEnv() {
	try {
		fs.statSync('/.dockerenv');
		return true;
	} catch (_) {
		return false;
	}
}

function hasDockerCGroup() {
	try {
		const cGroup = fs.readFileSync('/proc/self/cgroup', 'utf8');

		return cGroup.includes('docker') ||
			cGroup.split('\n').some(line => line.length > 0 && !line.endsWith('/') && !line.endsWith('init.scope'));
	} catch (_) {
		return false;
	}
}

module.exports = () => {
	if (isDocker === undefined) {
		isDocker = hasDockerEnv() || hasDockerCGroup();
	}

	return isDocker;
};
<|endoftext|>


<commit_before>const fs = require("fs")

index = () => {
	return fs.readFileSync("./pages/index.html")
}

module.exports = index<commit_msg>index.js -> pages.js<commit_after><|endoftext|>


<commit_before>'use strict';

var getter = function (obj, keychains, defaultValue) {
  var keys = keychains.split('.'),/*split 属性链*/
    result = obj,//存储最终结果
    sFunc = 'function',
    sObj = 'object';

  for(var i = 0, size = keys.length; i < size; i++) {
    if(typeof obj === sFunc || typeof obj === sObj) {
      result = result[keys[i]];
    }else{
      break;
    }
  }
  return result;
};

module.exports = getter;<commit_msg>bug fix<commit_after>'use strict';

var getter = function (obj, keychains, defaultValue) {
  var keys = keychains.split('.'),/*split 属性链*/
    result = obj,//存储最终结果
    sFunc = 'function',
    sObj = 'object';

  for(var i = 0, size = keys.length; i < size; i++) {
    if(typeof result === sFunc || typeof result === sObj) {
      result = result[keys[i]];
    }else{
      break;
    }
  }
  return result;
};

module.exports = getter;
<|endoftext|>


<commit_before>!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("mobx"),require("mobx-react")):"function"==typeof define&&define.amd?define(["react","mobx","mobx-react"],t):"object"==typeof exports?exports.mobxReactConnect=t(require("react"),require("mobx"),require("mobx-react")):e.mobxReactConnect=t(e.React,e.mobx,e.mobxReact)}(this,function(e,t,r){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var r={};return t.m=e,t.c=r,t.i=function(e){return e},t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=5)}([function(t,r){t.exports=e},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(0),i=n(u),c=r(3),f=r(4),a=r(2),s=n(a),l=function(e,t,r){var n={};return Object.keys(e).forEach(function(t){n[t]=e[t]}),n.displayName=e.name||e.displayName,n.componentWillMount=function(){this.store="function"==typeof t?new t(this.props):(0,c.observable)(t)},n.render=function(){return(0,s.default)(e(o({},this.props,{store:this.store}),this.context),r)},(0,f.observer)(i.default.createClass(n))};t.default=l},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u=r(0),i=n(u),c=function(e){var t=void 0;if(e.constructor===Array)t=e.map(function(e){return e});else{t={};for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])}return Object.setPrototypeOf(t,Object.getPrototypeOf(e)),t},f=function(e){var t=e.styleName,r=[];return t&&"string"==typeof t&&(r=t.split(" ")),r},a=function(e){return e&&"[object Array]"===toString.call(e)},s=function(e){var t="function"==typeof Symbol&&Symbol.iterator;return!!e&&"function"==typeof(t?e[t]:e["@@iterator"])},l=function(e){var t=void 0===e?"undefined":o(e);return null!=e&&("object"===t||"function"===t)},p=function e(t,r){if(!l(t)||!r)return t;var n=t,o=!1;Object.isFrozen&&Object.isFrozen(n)&&(o=!0,n=c(n),n.props=c(n.props));var u=f(n.props);if(u.length){var p=n.props.className,d=u.map(function(e){return r[e]});n.props.className=p?[p].concat(d).join(" "):d.join(" "),delete n.props.styleName}var b=n.props.children;return i.default.isValidElement(b)?n.props.children=e(i.default.Children.only(b),r):a(b)?n.props.children=b.map(function(t){return i.default.isValidElement(t)?e(t,r):t}):s(b)&&(n.props.children=i.default.Children.map(b,function(t){return i.default.isValidElement(t)?e(t,r):t})),o&&(Object.freeze(n.props),Object.freeze(n)),n};t.default=p},function(e,r){e.exports=t},function(e,t){e.exports=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.connect=void 0;var o=r(1),u=n(o);t.connect=u.default}])});<commit_msg>build<commit_after>!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("mobx"),require("mobx-react")):"function"==typeof define&&define.amd?define(["react","mobx","mobx-react"],t):"object"==typeof exports?exports.mobxReactConnect=t(require("react"),require("mobx"),require("mobx-react")):e.mobxReactConnect=t(e.React,e.mobx,e.mobxReact)}(this,function(e,t,r){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var r={};return t.m=e,t.c=r,t.i=function(e){return e},t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=5)}([function(t,r){t.exports=e},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(0),c=n(u),i=r(3),f=r(4),a=r(2),s=n(a),l=function(e,t,r){var n={};return Object.keys(e).forEach(function(t){n[t]=e[t]}),n.displayName=e.name||e.displayName,n.componentWillMount=function(){this.store="function"==typeof t?new t(this.props):(0,i.observable)(t)},n.render=function(){return(0,s.default)(e(o({},this.props,{store:this.store}),this.context),r)},(0,f.observer)(c.default.createClass(n))};t.default=l},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u=r(0),c=n(u),i=function(e){var t=void 0;if(e.constructor===Array)t=e.map(function(e){return e});else{t={};for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])}return Object.setPrototypeOf(t,Object.getPrototypeOf(e)),t},f=function(e){var t=e.styleName,r=e.clazz,n=[];return t&&"string"==typeof t&&(n=t.split(" ")),r&&"string"==typeof r&&(n=n.concat(r.split(" "))),n},a=function(e){return e&&"[object Array]"===toString.call(e)},s=function(e){var t="function"==typeof Symbol&&Symbol.iterator;return!!e&&"function"==typeof(t?e[t]:e["@@iterator"])},l=function(e){var t=void 0===e?"undefined":o(e);return null!=e&&("object"===t||"function"===t)},p=function e(t,r){if(!l(t)||!r)return t;var n=t,o=!1;Object.isFrozen&&Object.isFrozen(n)&&(o=!0,n=i(n),n.props=i(n.props));var u=f(n.props);if(u.length){var p=n.props.className,d=u.map(function(e){return r[e]});n.props.className=p?[p].concat(d).join(" "):d.join(" "),delete n.props.styleName,delete n.props.clazz}var b=n.props.children;return c.default.isValidElement(b)?n.props.children=e(c.default.Children.only(b),r):a(b)?n.props.children=b.map(function(t){return c.default.isValidElement(t)?e(t,r):t}):s(b)&&(n.props.children=c.default.Children.map(b,function(t){return c.default.isValidElement(t)?e(t,r):t})),o&&(Object.freeze(n.props),Object.freeze(n)),n};t.default=p},function(e,r){e.exports=t},function(e,t){e.exports=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.connect=void 0;var o=r(1),u=n(o);t.connect=u.default}])});<|endoftext|>


<commit_before>module.exports = function (arr, arg) {
  if (arr.length === 0) {
    return 0;
  }

  var indices = [];

  for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < arr.length; j++) {
      if (i !== j) {
        if (indices.indexOf(i) === -1 && indices.indexOf(j) === -1) {
          if (arr[i] + arr[j] === arg) {
            indices.push(i, j);
          }
        }
      }
    }
  }

  return indices.reduce(function(a, b) {
    return a + b;
  });
}
<commit_msg>fix(pairwise): fixed return no match<commit_after>module.exports = function pairwise(arr, arg) {
  if (arr.length === 0) {
    return 0
  }

  const indices = []

  for (let i = 0; i < arr.length; i += 1) {
    for (let j = 0; j < arr.length; j += 1) {
      if (i !== j) {
        if (indices.indexOf(i) === -1 && indices.indexOf(j) === -1) {
          if (arr[i] + arr[j] === arg) {
            indices.push(i, j)
          }
        }
      }
    }
  }

  return indices.reduce((a, b) => a + b, 0)
}
<|endoftext|>