<commit_before>"use strict";

var routing = require('./server/routing.js')
  , loggerjs = require('./server/logger.js')
  , logger = loggerjs.get('appium')
  , UUID = require('uuid-js')
  , _ = require('underscore')
  , Capabilities = require('./server/capabilities')
  , IOS = require('./devices/ios/ios.js')
  , Safari = require('./devices/ios/safari.js')
  , Android = require('./devices/android/android.js')
  , Selendroid = require('./devices/android/selendroid.js')
  , Chrome = require('./devices/android/chrome.js')
  , FirefoxOs = require('./devices/firefoxos/firefoxos.js')
  , jwpResponse = require('./devices/common.js').jwpResponse
  , status = require("./server/status.js");

var DT_IOS = "ios"
  , DT_SAFARI = "safari"
  , DT_ANDROID = "android"
  , DT_CHROME = "chrome"
  , DT_SELENDROID = "selendroid"
  , DT_FIREFOX_OS = "firefoxos";

var Appium = function (args) {
  this.args = args;
  this.serverArgs = _.clone(args);
  this.rest = null;
  this.webSocket = null;
  this.deviceType = null;
  this.device = null;
  this.sessionId = null;
  this.desiredCapabilities = {};
  this.oldDesiredCapabilities = {};
  this.session = null;
  this.preLaunched = false;
  this.sessionOverride = this.args.sessionOverride;
  this.resetting = false;
  this.defCommandTimeoutMs = this.args.defaultCommandTimeout * 1000;
  this.commandTimeoutMs = this.defCommandTimeoutMs;
  this.commandTimeout = null;
};

Appium.prototype.attachTo = function (rest) {
  this.rest = rest;
  routing(this);
};

Appium.prototype.attachSocket = function (webSocket) {
  this.webSocket = webSocket;
};

Appium.prototype.registerConfig = function (configObj) {
  this.serverConfig = configObj;
};

Appium.prototype.deviceIsRegistered = function (deviceType) {
  if (deviceType === DT_SAFARI) deviceType = DT_IOS;
  if (deviceType === DT_CHROME) deviceType = DT_ANDROID;
  return _.has(this.serverConfig, deviceType);
};

Appium.prototype.preLaunch = function (cb) {
  logger.info("Pre-launching app");
  var caps = {};
  this.start(caps, function (err) {
    if (err) {
      cb(err, null);
    } else {
      this.preLaunched = true;
      cb(null, this);
    }
  }.bind(this));
};

Appium.prototype.setArgFromCap = function (arg, cap) {
  if (typeof this.desiredCapabilities[cap] !== "undefined") {
    this.args[arg] = this.desiredCapabilities[cap];
  }
};

Appium.prototype.updateResetArgsFromCaps = function () {
  this.setArgFromCap("noReset", "noReset");
  this.setArgFromCap("fullReset", "fullReset");

  // user can set noReset or fullReset
  var caps = this.desiredCapabilities;
  if (caps.noReset === true) this.args.fullReset = false;
  if (caps.fullReset === true) this.args.noReset = false;

  // not user visible via caps
  this.args.fastReset = !this.args.fullReset && !this.args.noReset;
  this.args.skipUninstall = this.args.fastReset || this.args.noReset;
};

Appium.prototype.start = function (desiredCaps, cb) {
  this.desiredCapabilities = new Capabilities(desiredCaps);
  this.updateResetArgsFromCaps();

  this.args.webSocket = this.webSocket; // allow to persist over many sessions
  if (this.sessionId === null || this.sessionOverride) {
    this.configure(this.args, this.desiredCapabilities, function (err) {
      if (err) {
        logger.info("Got configuration error, not starting session");
        this.cleanupSession();
        cb(err, null);
      } else {
        this.invoke(cb);
      }
    }.bind(this));
  } else {
    return cb(new Error("Requested a new session but one was in progress"));
  }
};

Appium.prototype.getDeviceType = function (args, caps) {
  var type =  this.getDeviceFromMJSONWP(args, caps) ||
              this.getDeviceTypeFromArgsOrNamedApp(args, caps) ||
              this.getDeviceTypeFromAppOrPackage(args, caps);
  if (type) {
    return type;
  }
  throw new Error("Could not determine your device from Appium arguments " +
                "or desired capabilities. Please make sure to specify the " +
                "'deviceName' capability");
};

Appium.prototype.getDeviceFromMJSONWP = function (args, caps) {
  var platform = caps.platformName || args.platformName;
  platform = platform ? platform.toString().toLowerCase() : '';
  var browser = caps.browserName || args.browserName;
  browser = browser ? browser.toString().toLowerCase() : '';
  var automation = caps.automationName || args.automationName;
  automation = automation ? automation.toString().toLowerCase() : '';

  var validPlatforms = ['ios', 'android', 'firefoxos'];
  if (platform && !_.contains(validPlatforms, platform)) {
    throw new Error("Could not determine your device. You sent in a " +
                    "platformName capability of '" + platform + "' but that " +
                    "is not a supported platform. Supported platforms are: " +
                    "iOS, Android, Selendroid, and FirefoxOS");
  }
  var type =  this.getDeviceTypeFromAutomationName(automation) ||
              this.getDeviceTypeFromBrowserName(browser) ||
              this.getDeviceTypeFromPlatformCap(platform);
  if (type) return type;
};

Appium.prototype.getDeviceTypeFromArgsOrNamedApp = function (args, caps) {
  var app = args.app || caps.app;
  app = app ? app.toString().toLowerCase() : '';
  var type = this.getDeviceTypeFromNamedApp(app) ||
             this.getDeviceTypeFromArgs(args);
  if (type) return type;
};

Appium.prototype.getDeviceTypeFromAppOrPackage = function (args, caps) {
  var app = args.app || caps.app;
  app = app ? app.toString().toLowerCase() : '';
  var pkg = args.androidPackage || caps.appPackage;
  pkg = pkg ? pkg.toString().toLowerCase() : '';
  var type =  this.getDeviceTypeFromApp(app) ||
              this.getDeviceTypeFromPackage(pkg);
  if (type) return type;
};

Appium.prototype.getDeviceTypeFromAutomationName = function (automation) {
  if (automation.indexOf('selendroid') !== -1) return DT_SELENDROID;
};

Appium.prototype.getDeviceTypeFromBrowserName = function (browser) {
  if (browser === "safari") {
    return DT_SAFARI;
  } else if (_.contains(["chrome", "chromium", "browser"], browser)) {
    return DT_CHROME;
  }
};

Appium.prototype.getDeviceTypeFromPlatformCap = function (caps) {
  var device = null;
  switch (caps) {
  case 'ios':
    device = DT_IOS;
    break;
  case 'android':
    device = DT_ANDROID;
    break;
  case 'firefoxos':
    device = DT_FIREFOX_OS;
    break;
  }
  return device;
};

Appium.prototype.getDeviceTypeFromDeviceCap = function (device) {

  if (device.indexOf('iphone') !== -1) {
    return DT_IOS;
  } else if (device.indexOf('ipad') !== -1) {
    return DT_IOS;
  } else if (device.indexOf('selendroid') !== -1) {
    return DT_SELENDROID;
  } else if (device.indexOf('firefox') !== -1) {
    return DT_FIREFOX_OS;
  } else if (device.indexOf('android') !== -1) {
    return DT_ANDROID;
  }
};

Appium.prototype.getDeviceTypeFromNamedApp = function (app) {
  if (app  === "safari") {
    return DT_SAFARI;
  } else if (app === "settings") {
    return DT_IOS;
  } else if (_.contains(["chrome", "chromium", "browser"], app)) {
    return DT_CHROME;
  }
};

Appium.prototype.getDeviceTypeFromApp = function (app) {
  if (/\.app$/.test(app) || /\.app\.zip$/.test(app)) {
    return DT_IOS;
  } else if (/\.apk$/.test(app) || /\.apk\.zip$/.test(app)) {
    return DT_ANDROID;
  }
};

Appium.prototype.getDeviceTypeFromPackage = function (pkg) {
  var chromePkgs = [
    "com.android.chrome"
  , "org.chromium.chrome.testshell"
  , "com.android.browser"
  ];
  if (_.contains(chromePkgs, pkg)) {
    return DT_CHROME;
  } else if (pkg) {
    return DT_ANDROID;
  }
};

Appium.prototype.getDeviceTypeFromArgs = function (args) {
  if (args.ipa && /\.ipa$/.test(args.ipa.toString().toLowerCase())) {
    return DT_IOS;
  } else if (args.safari) {
    return DT_SAFARI;
  } else if (args.forceIphone || args.forceIpad) {
    return  DT_IOS;
  }
};

Appium.prototype.configure = function (args, desiredCaps, cb) {
  var deviceType;

  try {
    deviceType = this.getDeviceType(args, desiredCaps);
  } catch (e) {
    logger.error(e.message);
    return cb(e);
  }

  if (!this.deviceIsRegistered(deviceType)) {
    logger.error("Trying to run a session for device '" + deviceType + "' " +
                 "but that device hasn't been configured. Run config");
    return cb(new Error("Device " + deviceType + " not configured yet"));
  }
  this.device = this.getNewDevice(deviceType);
  this.device.configure(args, desiredCaps, cb);
};

Appium.prototype.invoke = function (cb) {
  this.sessionId = UUID.create().hex;
  logger.info('Creating new appium session ' + this.sessionId);

  if (this.device.args.autoLaunch === false) {
    // if user has passed in desiredCaps.autoLaunch = false
    // meaning they will manage app install / launching
    cb(null, this.device);
  } else {
    // the normal case, where we launch the device for folks

    var onStart = function (err, sessionIdOverride) {
      if (sessionIdOverride) {
        this.sessionId = sessionIdOverride;
        logger.info("Overriding session id with " +
                    JSON.stringify(sessionIdOverride));
      }
      if (err) return this.cleanupSession(err, cb);
      logger.info("Device launched! Ready for commands");
      this.setCommandTimeout(this.desiredCapabilities.newCommandTimeout);
      cb(null, this.device);
    }.bind(this);

    this.device.start(onStart, this.cleanupSession.bind(this));
  }
};

Appium.prototype.getNewDevice = function (deviceType) {
  var DeviceClass = (function () {
    switch (deviceType) {
      case DT_IOS:
        return IOS;
      case DT_SAFARI:
        return Safari;
      case DT_ANDROID:
        return Android;
      case DT_CHROME:
        return Chrome;
      case DT_SELENDROID:
        return Selendroid;
      case DT_FIREFOX_OS:
        return FirefoxOs;
      default:
        throw new Error("Tried to start a device that doesn't exist: " +
                        deviceType);
    }
  })();
  return new DeviceClass();
};

Appium.prototype.timeoutWaitingForCommand = function () {
  logger.info("Didn't get a new command in " + (this.commandTimeoutMs / 1000) +
              " secs, shutting down...");
  this.stop(function () {
    logger.info("We shut down because no new commands came in");
  }.bind(this));
};

Appium.prototype.cleanupSession = function (err, cb) {
  logger.info("Cleaning up appium session");
  if (this.commandTimeout) {
    clearTimeout(this.commandTimeout);
    this.commandTimeout = null;
  }
  this.commandTimeoutMs = this.defCommandTimeoutMs;
  var dyingSession = this.sessionId;
  this.sessionId = null;
  this.sessionOverride = false;
  this.device = null;
  this.args = _.clone(this.serverArgs);
  this.oldDesiredCapabilities = _.clone(this.desiredCapabilities);
  this.desiredCapabilities = {};
  if (cb) {
    if (err) return cb(err);
    cb(null, {status: status.codes.Success.code, value: null,
      sessionId: dyingSession});
  }
};

Appium.prototype.resetTimeout = function () {
  if (this.commandTimeout) {
    clearTimeout(this.commandTimeout);
  }
  if (this.commandTimeoutMs && this.commandTimeoutMs > 0) {
    this.commandTimeout = setTimeout(this.timeoutWaitingForCommand.bind(this),
      this.commandTimeoutMs);
  }
};

Appium.prototype.setCommandTimeout = function (secs, cb) {
  if (typeof secs === "undefined") {
    secs = this.defCommandTimeoutMs / 1000;
    logger.info("Setting command timeout to the default of " + secs + " secs");
  } else {
    logger.info("Setting command timeout to " + secs + " secs");
  }
  this.commandTimeoutMs = secs * 1000;
  this.resetTimeout();
  if (typeof cb === "function") {
    jwpResponse(null, secs, cb);
  }
};

Appium.prototype.stop = function (cb) {
  if (this.sessionId === null || this.device === null) {
    logger.info("Trying to stop appium but there's no session, doing nothing");
    return cb();
  }

  logger.info('Shutting down appium session...');
  this.device.stop(function (code) {
    var err;
    if (code && code > 0) {
      err = new Error("Device exited with code: " + code);
    }
    this.cleanupSession(err, cb);
  }.bind(this));
};

Appium.prototype.reset = function (cb) {
  logger.info("Resetting app mid-session");
  if (typeof this.device.resetAndStartApp === "function") {
    logger.info("Running device specific reset");
    this.device.resetAndStartApp(function (err) {
      jwpResponse(err, cb);
    });
  } else {
    logger.info("Running generic full reset");
    var oldImpWait = this.device.implicitWaitMs
      , oldCommandTimeoutMs = this.commandTimeoutMs
      , oldId = this.sessionId;

    this.resetting = true;
    this.stop(function () {
      logger.info("Restarting app");
      this.start(this.oldDesiredCapabilities, function (err) {
        if (err) return cb(err);
        this.resetting = false;
        this.device.implicitWaitMs = oldImpWait;
        this.sessionId = oldId;
        this.setCommandTimeout(oldCommandTimeoutMs / 1000, cb);
      }.bind(this));
    }.bind(this));
  }
};

module.exports = function (args) {
  return new Appium(args);
};
<commit_msg>Misleading error message for a Valid Platform<commit_after>"use strict";

var routing = require('./server/routing.js')
  , loggerjs = require('./server/logger.js')
  , logger = loggerjs.get('appium')
  , UUID = require('uuid-js')
  , _ = require('underscore')
  , Capabilities = require('./server/capabilities')
  , IOS = require('./devices/ios/ios.js')
  , Safari = require('./devices/ios/safari.js')
  , Android = require('./devices/android/android.js')
  , Selendroid = require('./devices/android/selendroid.js')
  , Chrome = require('./devices/android/chrome.js')
  , FirefoxOs = require('./devices/firefoxos/firefoxos.js')
  , jwpResponse = require('./devices/common.js').jwpResponse
  , status = require("./server/status.js");

var DT_IOS = "ios"
  , DT_SAFARI = "safari"
  , DT_ANDROID = "android"
  , DT_CHROME = "chrome"
  , DT_SELENDROID = "selendroid"
  , DT_FIREFOX_OS = "firefoxos";

var Appium = function (args) {
  this.args = args;
  this.serverArgs = _.clone(args);
  this.rest = null;
  this.webSocket = null;
  this.deviceType = null;
  this.device = null;
  this.sessionId = null;
  this.desiredCapabilities = {};
  this.oldDesiredCapabilities = {};
  this.session = null;
  this.preLaunched = false;
  this.sessionOverride = this.args.sessionOverride;
  this.resetting = false;
  this.defCommandTimeoutMs = this.args.defaultCommandTimeout * 1000;
  this.commandTimeoutMs = this.defCommandTimeoutMs;
  this.commandTimeout = null;
};

Appium.prototype.attachTo = function (rest) {
  this.rest = rest;
  routing(this);
};

Appium.prototype.attachSocket = function (webSocket) {
  this.webSocket = webSocket;
};

Appium.prototype.registerConfig = function (configObj) {
  this.serverConfig = configObj;
};

Appium.prototype.deviceIsRegistered = function (deviceType) {
  if (deviceType === DT_SAFARI) deviceType = DT_IOS;
  if (deviceType === DT_CHROME) deviceType = DT_ANDROID;
  return _.has(this.serverConfig, deviceType);
};

Appium.prototype.preLaunch = function (cb) {
  logger.info("Pre-launching app");
  var caps = {};
  this.start(caps, function (err) {
    if (err) {
      cb(err, null);
    } else {
      this.preLaunched = true;
      cb(null, this);
    }
  }.bind(this));
};

Appium.prototype.setArgFromCap = function (arg, cap) {
  if (typeof this.desiredCapabilities[cap] !== "undefined") {
    this.args[arg] = this.desiredCapabilities[cap];
  }
};

Appium.prototype.updateResetArgsFromCaps = function () {
  this.setArgFromCap("noReset", "noReset");
  this.setArgFromCap("fullReset", "fullReset");

  // user can set noReset or fullReset
  var caps = this.desiredCapabilities;
  if (caps.noReset === true) this.args.fullReset = false;
  if (caps.fullReset === true) this.args.noReset = false;

  // not user visible via caps
  this.args.fastReset = !this.args.fullReset && !this.args.noReset;
  this.args.skipUninstall = this.args.fastReset || this.args.noReset;
};

Appium.prototype.start = function (desiredCaps, cb) {
  this.desiredCapabilities = new Capabilities(desiredCaps);
  this.updateResetArgsFromCaps();

  this.args.webSocket = this.webSocket; // allow to persist over many sessions
  if (this.sessionId === null || this.sessionOverride) {
    this.configure(this.args, this.desiredCapabilities, function (err) {
      if (err) {
        logger.info("Got configuration error, not starting session");
        this.cleanupSession();
        cb(err, null);
      } else {
        this.invoke(cb);
      }
    }.bind(this));
  } else {
    return cb(new Error("Requested a new session but one was in progress"));
  }
};

Appium.prototype.getDeviceType = function (args, caps) {
  var type =  this.getDeviceFromMJSONWP(args, caps) ||
              this.getDeviceTypeFromArgsOrNamedApp(args, caps) ||
              this.getDeviceTypeFromAppOrPackage(args, caps);
  if (type) {
    return type;
  }
  throw new Error("Could not determine your device from Appium arguments " +
                "or desired capabilities. Please make sure to specify the " +
                "'deviceName' capability");
};

Appium.prototype.getDeviceFromMJSONWP = function (args, caps) {
  var platform = caps.platformName || args.platformName;
  platform = platform ? platform.toString().toLowerCase() : '';
  var browser = caps.browserName || args.browserName;
  browser = browser ? browser.toString().toLowerCase() : '';
  var automation = caps.automationName || args.automationName;
  automation = automation ? automation.toString().toLowerCase() : '';

  var validPlatforms = ['ios', 'android', 'firefoxos'];
  if (platform && !_.contains(validPlatforms, platform)) {
    throw new Error("Could not determine your device. You sent in a " +
                    "platformName capability of '" + platform + "' but that " +
                    "is not a supported platform. Supported platforms are: " +
                    "iOS, Android and FirefoxOS");
  }
  var type =  this.getDeviceTypeFromAutomationName(automation) ||
              this.getDeviceTypeFromBrowserName(browser) ||
              this.getDeviceTypeFromPlatformCap(platform);
  if (type) return type;
};

Appium.prototype.getDeviceTypeFromArgsOrNamedApp = function (args, caps) {
  var app = args.app || caps.app;
  app = app ? app.toString().toLowerCase() : '';
  var type = this.getDeviceTypeFromNamedApp(app) ||
             this.getDeviceTypeFromArgs(args);
  if (type) return type;
};

Appium.prototype.getDeviceTypeFromAppOrPackage = function (args, caps) {
  var app = args.app || caps.app;
  app = app ? app.toString().toLowerCase() : '';
  var pkg = args.androidPackage || caps.appPackage;
  pkg = pkg ? pkg.toString().toLowerCase() : '';
  var type =  this.getDeviceTypeFromApp(app) ||
              this.getDeviceTypeFromPackage(pkg);
  if (type) return type;
};

Appium.prototype.getDeviceTypeFromAutomationName = function (automation) {
  if (automation.indexOf('selendroid') !== -1) return DT_SELENDROID;
};

Appium.prototype.getDeviceTypeFromBrowserName = function (browser) {
  if (browser === "safari") {
    return DT_SAFARI;
  } else if (_.contains(["chrome", "chromium", "browser"], browser)) {
    return DT_CHROME;
  }
};

Appium.prototype.getDeviceTypeFromPlatformCap = function (caps) {
  var device = null;
  switch (caps) {
  case 'ios':
    device = DT_IOS;
    break;
  case 'android':
    device = DT_ANDROID;
    break;
  case 'firefoxos':
    device = DT_FIREFOX_OS;
    break;
  }
  return device;
};

Appium.prototype.getDeviceTypeFromDeviceCap = function (device) {

  if (device.indexOf('iphone') !== -1) {
    return DT_IOS;
  } else if (device.indexOf('ipad') !== -1) {
    return DT_IOS;
  } else if (device.indexOf('selendroid') !== -1) {
    return DT_SELENDROID;
  } else if (device.indexOf('firefox') !== -1) {
    return DT_FIREFOX_OS;
  } else if (device.indexOf('android') !== -1) {
    return DT_ANDROID;
  }
};

Appium.prototype.getDeviceTypeFromNamedApp = function (app) {
  if (app  === "safari") {
    return DT_SAFARI;
  } else if (app === "settings") {
    return DT_IOS;
  } else if (_.contains(["chrome", "chromium", "browser"], app)) {
    return DT_CHROME;
  }
};

Appium.prototype.getDeviceTypeFromApp = function (app) {
  if (/\.app$/.test(app) || /\.app\.zip$/.test(app)) {
    return DT_IOS;
  } else if (/\.apk$/.test(app) || /\.apk\.zip$/.test(app)) {
    return DT_ANDROID;
  }
};

Appium.prototype.getDeviceTypeFromPackage = function (pkg) {
  var chromePkgs = [
    "com.android.chrome"
  , "org.chromium.chrome.testshell"
  , "com.android.browser"
  ];
  if (_.contains(chromePkgs, pkg)) {
    return DT_CHROME;
  } else if (pkg) {
    return DT_ANDROID;
  }
};

Appium.prototype.getDeviceTypeFromArgs = function (args) {
  if (args.ipa && /\.ipa$/.test(args.ipa.toString().toLowerCase())) {
    return DT_IOS;
  } else if (args.safari) {
    return DT_SAFARI;
  } else if (args.forceIphone || args.forceIpad) {
    return  DT_IOS;
  }
};

Appium.prototype.configure = function (args, desiredCaps, cb) {
  var deviceType;

  try {
    deviceType = this.getDeviceType(args, desiredCaps);
  } catch (e) {
    logger.error(e.message);
    return cb(e);
  }

  if (!this.deviceIsRegistered(deviceType)) {
    logger.error("Trying to run a session for device '" + deviceType + "' " +
                 "but that device hasn't been configured. Run config");
    return cb(new Error("Device " + deviceType + " not configured yet"));
  }
  this.device = this.getNewDevice(deviceType);
  this.device.configure(args, desiredCaps, cb);
};

Appium.prototype.invoke = function (cb) {
  this.sessionId = UUID.create().hex;
  logger.info('Creating new appium session ' + this.sessionId);

  if (this.device.args.autoLaunch === false) {
    // if user has passed in desiredCaps.autoLaunch = false
    // meaning they will manage app install / launching
    cb(null, this.device);
  } else {
    // the normal case, where we launch the device for folks

    var onStart = function (err, sessionIdOverride) {
      if (sessionIdOverride) {
        this.sessionId = sessionIdOverride;
        logger.info("Overriding session id with " +
                    JSON.stringify(sessionIdOverride));
      }
      if (err) return this.cleanupSession(err, cb);
      logger.info("Device launched! Ready for commands");
      this.setCommandTimeout(this.desiredCapabilities.newCommandTimeout);
      cb(null, this.device);
    }.bind(this);

    this.device.start(onStart, this.cleanupSession.bind(this));
  }
};

Appium.prototype.getNewDevice = function (deviceType) {
  var DeviceClass = (function () {
    switch (deviceType) {
      case DT_IOS:
        return IOS;
      case DT_SAFARI:
        return Safari;
      case DT_ANDROID:
        return Android;
      case DT_CHROME:
        return Chrome;
      case DT_SELENDROID:
        return Selendroid;
      case DT_FIREFOX_OS:
        return FirefoxOs;
      default:
        throw new Error("Tried to start a device that doesn't exist: " +
                        deviceType);
    }
  })();
  return new DeviceClass();
};

Appium.prototype.timeoutWaitingForCommand = function () {
  logger.info("Didn't get a new command in " + (this.commandTimeoutMs / 1000) +
              " secs, shutting down...");
  this.stop(function () {
    logger.info("We shut down because no new commands came in");
  }.bind(this));
};

Appium.prototype.cleanupSession = function (err, cb) {
  logger.info("Cleaning up appium session");
  if (this.commandTimeout) {
    clearTimeout(this.commandTimeout);
    this.commandTimeout = null;
  }
  this.commandTimeoutMs = this.defCommandTimeoutMs;
  var dyingSession = this.sessionId;
  this.sessionId = null;
  this.sessionOverride = false;
  this.device = null;
  this.args = _.clone(this.serverArgs);
  this.oldDesiredCapabilities = _.clone(this.desiredCapabilities);
  this.desiredCapabilities = {};
  if (cb) {
    if (err) return cb(err);
    cb(null, {status: status.codes.Success.code, value: null,
      sessionId: dyingSession});
  }
};

Appium.prototype.resetTimeout = function () {
  if (this.commandTimeout) {
    clearTimeout(this.commandTimeout);
  }
  if (this.commandTimeoutMs && this.commandTimeoutMs > 0) {
    this.commandTimeout = setTimeout(this.timeoutWaitingForCommand.bind(this),
      this.commandTimeoutMs);
  }
};

Appium.prototype.setCommandTimeout = function (secs, cb) {
  if (typeof secs === "undefined") {
    secs = this.defCommandTimeoutMs / 1000;
    logger.info("Setting command timeout to the default of " + secs + " secs");
  } else {
    logger.info("Setting command timeout to " + secs + " secs");
  }
  this.commandTimeoutMs = secs * 1000;
  this.resetTimeout();
  if (typeof cb === "function") {
    jwpResponse(null, secs, cb);
  }
};

Appium.prototype.stop = function (cb) {
  if (this.sessionId === null || this.device === null) {
    logger.info("Trying to stop appium but there's no session, doing nothing");
    return cb();
  }

  logger.info('Shutting down appium session...');
  this.device.stop(function (code) {
    var err;
    if (code && code > 0) {
      err = new Error("Device exited with code: " + code);
    }
    this.cleanupSession(err, cb);
  }.bind(this));
};

Appium.prototype.reset = function (cb) {
  logger.info("Resetting app mid-session");
  if (typeof this.device.resetAndStartApp === "function") {
    logger.info("Running device specific reset");
    this.device.resetAndStartApp(function (err) {
      jwpResponse(err, cb);
    });
  } else {
    logger.info("Running generic full reset");
    var oldImpWait = this.device.implicitWaitMs
      , oldCommandTimeoutMs = this.commandTimeoutMs
      , oldId = this.sessionId;

    this.resetting = true;
    this.stop(function () {
      logger.info("Restarting app");
      this.start(this.oldDesiredCapabilities, function (err) {
        if (err) return cb(err);
        this.resetting = false;
        this.device.implicitWaitMs = oldImpWait;
        this.sessionId = oldId;
        this.setCommandTimeout(oldCommandTimeoutMs / 1000, cb);
      }.bind(this));
    }.bind(this));
  }
};

module.exports = function (args) {
  return new Appium(args);
};
<|endoftext|>


<commit_before>var VariableModifyForm = {};

// validate the form if the user stopped typing for 250 ms
VariableModifyForm.validate = _.debounce(function(form) {
	"use strict";
	var data = "";
	var validateUrl = $(form).data('validate-url');

	data = $(form).serialize();

	$.post(validateUrl, data, function(response) {
		//first remove all previous validation results
		$(form).find('.has-feedback').removeClass('has-error');
		$(form).find('.has-feedback').removeClass('has-success');
		$(form).find('.help-block').empty();
		$(form).find('.form-control-feedback').removeClass('glyphicon-remove');
		$(form).find('.form-control-feedback').removeClass('glyphicon-ok');
		$(form).find('.globalError').removeClass('alert alert-danger');
		$(form).find('.globalError').empty();

		var $inputs = $(form).find('.form-control');
		var $globalErrorDivs = $(form).find('.globalError');

		for (var j = 0; j < $globalErrorDivs.length; j++){
			var globalError = response.errorMessageMap[$globalErrorDivs[j].id];
			if(globalError){
				  $($globalErrorDivs[j]).first().addClass('alert alert-danger');
				$($globalErrorDivs[j]).html(
						'
' + globalError + '
');
			}
		}

		for (var i = 0; i < $inputs.length; i++) {
			var error = response.errorMessageMap[$inputs[i].name];
			var $formGroup = $($inputs[i].closest('.form-group'));
			if (error) {
				//field has error thus add messages and styles
				$formGroup.addClass('has-error');
				$formGroup.find('.form-control-feedback').addClass(
						'glyphicon-remove');
				$formGroup.find('.help-block').html(
						'
' + error.sort().join('
') + '
');
			} else {
				//field is valid
				$formGroup.addClass('has-success');
				$formGroup.find('.form-control-feedback').addClass(
						'glyphicon-ok');
			}
		}
	}, 'json');
},250);

$(document).ready(function() {
	"use strict";
	// scroll to the button which has just created dynamic form fields
	var focusElementId = $('body').data('focus-element-id');
	if (focusElementId) {
		$('html, body').animate({
			scrollTop: $('#' + focusElementId).offset().top
		}, 1000);
		$('#' + focusElementId).focus();
	}
});
<commit_msg>Fixed error<commit_after>var VariableModifyForm = {};

// validate the form if the user stopped typing for 250 ms
VariableModifyForm.validate = _.debounce(function(form) {
	"use strict";
	var data = "";
	var validateUrl = $(form).data('validate-url');

	data = $(form).serialize();

	$.post(validateUrl, data, function(response) {
		//first remove all previous validation results
		$(form).find('.has-feedback').removeClass('has-error');
		$(form).find('.has-feedback').removeClass('has-success');
		$(form).find('.help-block').empty();
		$(form).find('.form-control-feedback').removeClass('glyphicon-remove');
		$(form).find('.form-control-feedback').removeClass('glyphicon-ok');
		$(form).find('.global-error').removeClass('alert alert-danger');
		$(form).find('.global-error').empty();

		var $inputs = $(form).find('.form-control');
		var $globalErrorDivs = $(form).find('.global-error');

		for (var j = 0; j < $globalErrorDivs.length; j++){
			var globalError = response.errorMessageMap[$globalErrorDivs[j].id];
			if(globalError){
				  $($globalErrorDivs[j]).first().addClass('alert alert-danger');
				$($globalErrorDivs[j]).html(
						'
' + globalError + '
');
			}
		}

		for (var i = 0; i < $inputs.length; i++) {
			var error = response.errorMessageMap[$inputs[i].name];
			var $formGroup = $($inputs[i].closest('.form-group'));
			if (error) {
				//field has error thus add messages and styles
				$formGroup.addClass('has-error');
				$formGroup.find('.form-control-feedback').addClass(
						'glyphicon-remove');
				$formGroup.find('.help-block').html(
						'
' + error.sort().join('
') + '
');
			} else {
				//field is valid
				$formGroup.addClass('has-success');
				$formGroup.find('.form-control-feedback').addClass(
						'glyphicon-ok');
			}
		}
	}, 'json');
},250);

$(document).ready(function() {
	"use strict";
	// scroll to the button which has just created dynamic form fields
	var focusElementId = $('body').data('focus-element-id');
	if (focusElementId) {
		$('html, body').animate({
			scrollTop: $('#' + focusElementId).offset().top
		}, 1000);
		$('#' + focusElementId).focus();
	}
});
<|endoftext|>


<commit_before>'use strict'

const chai = require('chai')
const expect = chai.expect
const sinon = require('sinon')
const proxyquire = require('proxyquire').noCallThru()
const request = require('request')

chai.use(require('sinon-chai'))

describe('mocker: incoming webhooks', function () {
  let loggerMock
  let incomingWebhooks

  before(function () {
    loggerMock = {
      error: sinon.stub(),
      info: sinon.stub(),
      debug: sinon.stub()
    }

    // I ran into some weird scoping issues by redefining this in a beforeEach
    // moving to a before() fixed them
    incomingWebhooks = proxyquire('../../mocker/incoming-webhooks', {
      '../lib/logger': loggerMock
    })
  })

  beforeEach(function () {
    loggerMock.error.reset()
    loggerMock.info.reset()
    loggerMock.debug.reset()

    incomingWebhooks.reset()
  })

  function sendToUrl (url, body, cb) {
    request({
      method: 'POST',
      uri: url,
      json: true,
      body: body
    }, cb)
  }

  describe('register', function () {
    let url

    beforeEach(function () {
      url = 'http://register.not.real'
    })

    it('should register a url with default response', function (done) {
      sendToUrl(url, {}, beforeRegister)

      function beforeRegister (err) {
        expect(err).to.exist

        incomingWebhooks.register(url)
        sendToUrl(url, {}, afterRegister)
      }

      function afterRegister (err, res, body) {
        expect(err).not.to.exist

        // default response
        expect(res.statusCode).to.equal(200)
        expect(body.ok).to.be.true
        done()
      }
    })
  })

  describe('addResponse', function () {
    let url

    beforeEach(function () {
      url = 'http://addResponse.not.real'
      incomingWebhooks.register(url)
    })

    it('should add a custom response', function (done) {
      incomingWebhooks.addResponse({
        url: url,
        statusCode: 500,
        body: {not: 'ok'},
        headers: {walter: 'white'}
      })

      sendToUrl(url, {}, (err, res, body) => {
        if (err) return done(err)

        expect(res.statusCode).to.equal(500)
        expect(body).to.deep.equal({not: 'ok'})
        expect(res.headers.walter).to.equal('white')
        done()
      })
    })

    it('should set default status', function (done) {
      incomingWebhooks.addResponse({
        url: url,
        body: {maybe: 'ok'},
        headers: {walter: 'white'}
      })

      sendToUrl(url, {}, (err, res, body) => {
        if (err) return done(err)
        expect(res.statusCode).to.equal(200)
        expect(body).to.deep.equal({maybe: 'ok'})
        done()
      })
    })

    it('should set default body', function (done) {
      incomingWebhooks.addResponse({
        url: url,
        statusCode: 500,
        headers: {walter: 'white'}
      })

      sendToUrl(url, {}, (err, res, body) => {
        if (err) return done(err)
        expect(res.statusCode).to.equal(500)
        expect(body).to.deep.equal({ok: true})
        done()
      })
    })

    it('should set default headers', function (done) {
      incomingWebhooks.addResponse({
        url: url,
        statusCode: 500,
        body: {maybe: 'ok'}
      })

      sendToUrl(url, {}, (err, res, body) => {
        if (err) return done(err)
        expect(res.statusCode).to.equal(500)
        expect(body).to.deep.equal({maybe: 'ok'})
        expect(res.headers).to.be.defined

        done()
      })
    })

    it('should queue requests', function (done) {
      incomingWebhooks.addResponse({
        url: url,
        statusCode: 201
      })

      incomingWebhooks.addResponse({
        url: url,
        statusCode: 202
      })

      sendToUrl(url, {}, (err, res) => {
        if (err) return done(err)
        expect(res.statusCode).to.equal(201)

        sendToUrl(url, {}, queuedCall)
      })

      function queuedCall (err, res) {
        if (err) return done(err)
        expect(res.statusCode).to.equal(202)

        sendToUrl(url, {}, defaultCall)
      }

      function defaultCall (err, res) {
        if (err) return done(err)
        expect(res.statusCode).to.equal(200)
        done()
      }
    })

    it('should add a request after a reset', function (done) {
      incomingWebhooks.addResponse({
        url: url,
        statusCode: 201
      })

      incomingWebhooks.reset()

      incomingWebhooks.addResponse({
        url: url,
        statusCode: 202
      })

      sendToUrl(url, {}, (err, res) => {
        if (err) return done(err)
        expect(res.statusCode).to.equal(202)
        done()
      })
    })

    it('should add a request after flushing request queue', function (done) {
      incomingWebhooks.addResponse({
        url: url,
        statusCode: 201
      })

      sendToUrl(url, {}, (err, res) => {
        if (err) return done(err)
        expect(res.statusCode).to.equal(201)

        sendToUrl(url, {}, emptyQueue)
      })

      function emptyQueue (err, res) {
        if (err) return done(err)
        expect(res.statusCode).to.equal(200)

        incomingWebhooks.addResponse({
          url: url,
          statusCode: 202
        })

        sendToUrl(url, {}, queuedResponse)
      }

      function queuedResponse (err, res) {
        if (err) return done(err)
        expect(res.statusCode).to.equal(202)
        done()
      }
    })
  })

  describe('calls', function () {
    let url

    beforeEach(function () {
      url = 'http://calls.not.real'
      incomingWebhooks.register(url)
    })

    it('should record calls', function (done) {
      const body = {
        walter: 'white'
      }

      sendToUrl(url, body, () => {
        expect(incomingWebhooks.calls).to.have.length(1)

        const firstCall = incomingWebhooks.calls[0]
        expect(firstCall).to.have.keys(['url', 'body', 'headers'])
        expect(firstCall.url).to.equal(url)
        expect(firstCall.body).to.deep.equal({walter: 'white'})
        expect(firstCall.headers).to.exist

        done()
      })
    })

    it('should record application/x-www-form-urlencoded body as an object', function (done) {
      const formBody = {
        walter: 'white'
      }

      request({
        method: 'POST',
        uri: url,
        form: formBody
      }, () => {
        expect(incomingWebhooks.calls).to.have.length(1)
        const firstCall = incomingWebhooks.calls[0]
        expect(firstCall.body).to.deep.equal({walter: 'white'})

        done()
      })
    })
  })

  describe('reset', function () {
    let url

    beforeEach(function () {
      url = 'http://reset.not.real'
      incomingWebhooks.register(url)
    })

    it('should reset call count', function (done) {
      sendToUrl(url, {}, () => {
        expect(incomingWebhooks.calls).to.have.length(1)
        incomingWebhooks.reset()
        expect(incomingWebhooks.calls).to.have.length(0)

        done()
      })
    })

    it('should reset queued responses', function (done) {
      incomingWebhooks.addResponse({
        url: url,
        statusCode: 500,
        body: {not: 'ok'}
      })

      incomingWebhooks.reset()
      sendToUrl(url, {}, (err, res, body) => {
        if (err) return done(err)

        expect(res.statusCode).to.equal(200)
        expect(body).to.deep.equal({ok: true})

        done()
      })
    })
  })
})
<commit_msg>updates incoming webhooks tests to use custom responses<commit_after>'use strict'

const chai = require('chai')
const expect = chai.expect
const sinon = require('sinon')
const proxyquire = require('proxyquire').noCallThru()
const request = require('request')

chai.use(require('sinon-chai'))

describe('mocker: incoming webhooks', function () {
  let loggerMock
  let incomingWebhooks
  let customResponsesMock

  before(function () {
    loggerMock = {
      error: sinon.stub(),
      info: sinon.stub(),
      debug: sinon.stub()
    }

    customResponsesMock = {
      get: sinon.stub(),
      reset: sinon.stub(),
      set: sinon.stub()
    }

    // I ran into some weird scoping issues by redefining this in a beforeEach
    // moving to a before() fixed them
    incomingWebhooks = proxyquire('../../mocker/incoming-webhooks', {
      '../lib/logger': loggerMock,
      '../lib/custom-responses': customResponsesMock
    })
  })

  beforeEach(function () {
    loggerMock.error.reset()
    loggerMock.info.reset()
    loggerMock.debug.reset()

    customResponsesMock.get.reset()
    customResponsesMock.set.reset()
    customResponsesMock.reset.reset()
    customResponsesMock.get.returns(200, 'OK', {})

    incomingWebhooks.reset()
  })

  function sendToUrl (url, body, cb) {
    request({
      method: 'POST',
      uri: url,
      json: true,
      body: body
    }, cb)
  }

  describe('register', function () {
    let url

    beforeEach(function () {
      url = 'http://register.not.real'
    })

    it('should register a url', function (done) {
      sendToUrl(url, {}, beforeRegister)

      function beforeRegister (err) {
        expect(err).to.exist

        incomingWebhooks.register(url)
        sendToUrl(url, {}, afterRegister)
      }

      function afterRegister (err, res, body) {
        expect(err).not.to.exist

        expect(customResponsesMock.get).to.have.been.calledWith('incoming-webhooks', url)
        done()
      }
    })
  })

  describe('addResponse', function () {
    let url

    beforeEach(function () {
      url = 'http://addResponse.not.real'
      incomingWebhooks.register(url)
    })

    it('should add a custom response', function () {
      const opts = {
        url: url,
        statusCode: 500,
        body: {not: 'ok'},
        headers: {walter: 'white'}
      }

      incomingWebhooks.addResponse(opts)

      expect(customResponsesMock.set).to.have.been.calledWith('incoming-webhooks', opts)
    })
  })

  describe('calls', function () {
    let url

    beforeEach(function () {
      url = 'http://calls.not.real'
      incomingWebhooks.register(url)
    })

    it('should record calls', function (done) {
      const body = {
        walter: 'white'
      }

      sendToUrl(url, body, () => {
        expect(incomingWebhooks.calls).to.have.length(1)

        const firstCall = incomingWebhooks.calls[0]
        expect(firstCall).to.have.keys(['url', 'body', 'headers'])
        expect(firstCall.url).to.equal(url)
        expect(firstCall.body).to.deep.equal({walter: 'white'})
        expect(firstCall.headers).to.exist

        done()
      })
    })

    it('should record application/x-www-form-urlencoded body as an object', function (done) {
      const formBody = {
        walter: 'white'
      }

      request({
        method: 'POST',
        uri: url,
        form: formBody
      }, () => {
        expect(incomingWebhooks.calls).to.have.length(1)
        const firstCall = incomingWebhooks.calls[0]
        expect(firstCall.body).to.deep.equal({walter: 'white'})

        done()
      })
    })
  })

  describe('reset', function () {
    let url

    beforeEach(function () {
      url = 'http://reset.not.real'
      incomingWebhooks.register(url)
    })

    it('should reset call count', function (done) {
      sendToUrl(url, {}, () => {
        expect(incomingWebhooks.calls).to.have.length(1)
        incomingWebhooks.reset()
        expect(incomingWebhooks.calls).to.have.length(0)

        done()
      })
    })

    it('should reset queued responses', function () {
      incomingWebhooks.reset()
      expect(customResponsesMock.reset).to.have.been.calledWith('incoming-webhooks')
    })
  })
})
<|endoftext|>


<commit_before>$(function(){
  mapApp.init();

  $('#add-place-to-form').on('click', mapApp.captureLatLng);
  $('#form-new-startup').on('submit', mapApp.postStartup);
})

var mapApp = mapApp || {};

mapApp.captureLatLng = function(){
  event.preventDefault();
  // When we click
  // console.log(mapApp.newStartup);
  mapApp.startupLat = mapApp.newStartup.geometry.location.lat();
  mapApp.startupLng = mapApp.newStartup.geometry.location.lng();

  $("#new-startup-latitude").val(mapApp.startupLat);
  $("#new-startup-longitude").val(mapApp.startupLng);
  $("#new-startup-website").val(mapApp.newStartup.website);
  $("#new-startup-name").val(mapApp.newStartup.name);
}

mapApp.addMarker = function(){

}

mapApp.removeAllMarkers = function(){

}

mapApp.postStartup = function(){
  event.preventDefault();

  var data = {
    name:         $("#new-startup-name").val(),
    headquarters: $("#new-startup-headquarters").val(),
    latitude:     mapApp.startupLat,
    longitude:    mapApp.startupLng,
    founders:     $("#new-startup-founders").val(),
    sector:       $("#new-startup-sector").val(),
    email:        $("#new-startup-email").val(),
    phone:        $("#new-startup-phone").val(),
    website:      mapApp.newStartup.website,
    twitter:      $("#new-startup-twitter").val(),
    facebook:     $("#new-startup-facebook").val(),
    photo:        $("#new-startup-photo").val(),
    logo:         $("#new-startup-logo").val(),
  };

  $.ajax({
    method:     'post', //method,
    url:        'https://localhost:3000/api/startups', //url,
    data:       data,
    beforeSend: setRequestHeader
  })
  .done(function(data){
    return showStartup(data);
  })
  .fail(function(data){
    displayErrors(data.responseJSON.message);
  });
}

mapApp.init = function(){

  var markers = [];

  var canvas = document.getElementById('googleMap');
  var center = new google.maps.LatLng(51.5072, 0.1275)
  var mapOptions = {
    zoom: 14,
    center: center,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };
  this.map = new google.maps.Map(canvas, mapOptions);
  mapApp.startupIcon   = 'http://i.imgur.com/zSIbR3c.jpg';
  mapApp.workspaceIcon = 'http://i.imgur.com/J6p1ops.png';

  // Main Search Box
  mapApp.mainSearchBox = new google.maps.places.Autocomplete(document.getElementById('main-search-box'));
  google.maps.event.addListener(mapApp.mainSearchBox, 'place_changed', function(){
    mapApp.place = mapApp.mainSearchBox.getPlace();
  });
  google.maps.event.addDomListener(window, 'resize', function(){
    mapApp.map.setCenter(center);
  });

  // Add Google Autocomplete box to startup-search-box input
  mapApp.startupSearchBox = new google.maps.places.Autocomplete(document.getElementById('startup-search-box'));
  google.maps.event.addListener(mapApp.startupSearchBox, 'place_changed', function(){

    mapApp.newStartup = mapApp.startupSearchBox.getPlace();
    var icon = mapApp.startupIcon;
    var marker = new google.maps.Marker({
      map:      mapApp.map,
      icon:     icon,
      title:    mapApp.newStartup.name,
      position: mapApp.newStartup.geometry.location
    });
    // Recenter the map onto the newStartup position
    mapApp.map.setCenter(mapApp.newStartup.geometry.location);
  });

  // Add Google Autocomplete box to workspace-search-box input
  mapApp.workspaceSearchBox = new google.maps.places.Autocomplete(document.getElementById('workspace-search-box'));
  google.maps.event.addListener(mapApp.workspaceSearchBox, 'place_changed', function(){

    mapApp.newWorkspace = mapApp.workspaceSearchBox.getPlace();
    var icon = mapApp.startupIcon;
    var marker = new google.maps.Marker({
      map:      mapApp.map,
      icon:     icon,
      title:    mapApp.newWorkspace.name,
      position: mapApp.newWorkspace.geometry.location
    });
    // Recenter the map onto the newWorkspace position
    mapApp.map.setCenter(mapApp.newWorkspace.geometry.location);
  });

  // All search boxes have the class .search-box
  // When you click or focus back into the box, empty it
  $('.search-box').on('click', function(){
    $(this).val('');
  })
  $('.search-box').on('focus', function(){
    $(this).val('');
  })

}<commit_msg>Object-orienting the code<commit_after>$(function(){
  mapApp.init();

  $('#add-place-to-form').on('click', mapApp.captureLatLng);
  $('#form-new-startup').on('submit', mapApp.postStartup);
})

var mapApp = mapApp || {};

mapApp.captureLatLng = function(){
  event.preventDefault();
  // When we click
  // console.log(mapApp.newStartup);
  mapApp.startupLat = mapApp.newStartup.geometry.location.lat();
  mapApp.startupLng = mapApp.newStartup.geometry.location.lng();

  $("#new-startup-latitude").val(mapApp.startupLat);
  $("#new-startup-longitude").val(mapApp.startupLng);
  $("#new-startup-website").val(mapApp.newStartup.website);
  $("#new-startup-name").val(mapApp.newStartup.name);
}

mapApp.addMarker = function(){

}

mapApp.removeAllMarkers = function(){

}

mapApp.postStartup = function(){
  event.preventDefault();

  var data = {
    name:         $("#new-startup-name").val(),
    headquarters: $("#new-startup-headquarters").val(),
    latitude:     mapApp.startupLat,
    longitude:    mapApp.startupLng,
    founders:     $("#new-startup-founders").val(),
    sector:       $("#new-startup-sector").val(),
    email:        $("#new-startup-email").val(),
    phone:        $("#new-startup-phone").val(),
    website:      mapApp.newStartup.website,
    twitter:      $("#new-startup-twitter").val(),
    facebook:     $("#new-startup-facebook").val(),
    photo:        $("#new-startup-photo").val(),
    logo:         $("#new-startup-logo").val(),
  };

  $.ajax({
    method:     'post', //method,
    url:        'https://localhost:3000/api/startups', //url,
    data:       data,
    beforeSend: setRequestHeader
  })
  .done(function(data){
    return showStartup(data);
  })
  .fail(function(data){
    displayErrors(data.responseJSON.message);
  });
}

mapApp.init = function(){

  mapApp.canvas = document.getElementById('googleMap');
  mapApp.center = new google.maps.LatLng(51.5072, 0.1275)
  mapApp.mapOptions = {
    zoom: 14,
    center: mapApp.center,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };

  this.map = new google.maps.Map(mapApp.canvas, mapApp.mapOptions);

  mapApp.markers = [];

  // Icons for markers
  mapApp.startupIcon   = 'http://i.imgur.com/zSIbR3c.jpg';
  mapApp.workspaceIcon = 'http://i.imgur.com/J6p1ops.png';

  // Get data with AJAX
  // allStartups = data.startups;

  // mapApp.dropMarkers = function() {
  //   mapApp.clearMarkers();
  //   for (var i = 0; i < allStartups.length; i++) {
  //     mapApp.addMarkerWithTimeout(allStartups[i], i * 200);
  //   }
  // }

  mapApp.clearMarkers = function() {
    for (var i = 0; i < mapApp.markers.length; i++) {
      mapApp.markers[i].setMap(null);
    }
    mapApp.markers = [];
  }

  mapApp.addMarkerWithTimeout = function(position, timeout) {
    window.setTimeout(function() {
      mapApp.markers.push(new google.maps.Marker({
        position: position,
        map: map,
        animation: google.maps.Animation.DROP
      }));
    }, timeout);
  }

  // Main Search Box
  mapApp.mainSearchBox = new google.maps.places.Autocomplete(document.getElementById('main-search-box'));
  google.maps.event.addListener(mapApp.mainSearchBox, 'place_changed', function(){
    mapApp.place = mapApp.mainSearchBox.getPlace();
  });
  google.maps.event.addDomListener(window, 'resize', function(){
    mapApp.map.setCenter(mapApp.center);
  });

  // Add Google Autocomplete box to startup-search-box input
  mapApp.startupSearchBox = new google.maps.places.Autocomplete(document.getElementById('startup-search-box'));
  google.maps.event.addListener(mapApp.startupSearchBox, 'place_changed', function(){

    mapApp.newStartup = mapApp.startupSearchBox.getPlace();
    var icon = mapApp.startupIcon;
    var marker = new google.maps.Marker({
      map:       mapApp.map,
      icon:      icon,
      animation: google.maps.Animation.DROP,
      title:     mapApp.newStartup.name,
      position:  mapApp.newStartup.geometry.location
    });
    // Recenter the map onto the newStartup position
    mapApp.map.setCenter(mapApp.newStartup.geometry.location);
  });

  // Add Google Autocomplete box to workspace-search-box input
  mapApp.workspaceSearchBox = new google.maps.places.Autocomplete(document.getElementById('workspace-search-box'));
  google.maps.event.addListener(mapApp.workspaceSearchBox, 'place_changed', function(){

    mapApp.newWorkspace = mapApp.workspaceSearchBox.getPlace();
    var icon = mapApp.startupIcon;
    var marker = new google.maps.Marker({
      map:      mapApp.map,
      icon:     icon,
      animation: google.maps.Animation.DROP,
      title:    mapApp.newWorkspace.name,
      position: mapApp.newWorkspace.geometry.location
    });
    // Recenter the map onto the newWorkspace position
    mapApp.map.setCenter(mapApp.newWorkspace.geometry.location);
  });

  // All search boxes have the class .search-box
  // When you click or focus back into the box, empty it
  $('.search-box').on('click', function(){
    $(this).val('');
  })
  $('.search-box').on('focus', function(){
    $(this).val('');
  })

}<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/*eslint no-console: 0*/
var childProcess = require('child_process');
var parseArgs = require('minimist');
var path = require('path');
var ldj = require('ldjson-stream');
var fs = require('fs');
var util = require('util');
var process = require('process');
var console = require('console');
var setTimeout = require('timers').setTimeout;
var assert = require('assert');
var dgram = require('dgram');

var server = path.join(__dirname, 'bench_server.js');
var relay = path.join(__dirname, 'relay_server.js');
var trace = path.join(__dirname, 'trace_server.js');
var bench = path.join(__dirname, 'multi_bench.js');

process.stderr.setMaxListeners(Infinity);

var SERVER_PORT = 7100;
var TRACE_SERVER_PORT = 7039;
var RELAY_SERVER_PORT = 7038;
var RELAY_TRACE_PORT = 7037;
var STATSD_PORT = 7036;
var INSTANCE_COUNT = 72;
var CLIENT_PORT = 7041;

function BenchmarkRunner(opts) {
    if (!(this instanceof BenchmarkRunner)) {
        return new BenchmarkRunner(opts);
    }

    var self = this;

    self.opts = opts;

    self.relayProcs = [];
    self.statsdServer = null;
    self.serverProcs = [];
    self.traceProc = null;
    self.benchProcs = [];
    self.benchCounter = 0;
    self.fileStream = null;
}

BenchmarkRunner.prototype.start = function start() {
    var self = this;

    self.startStatsd();

    if (self.opts.multiProc) {
        self.startServer(SERVER_PORT, 24);
        self.startServer(SERVER_PORT + 24, 24);
        self.startServer(SERVER_PORT + 48, 24);
    } else {
        self.startServer(SERVER_PORT, INSTANCE_COUNT);
    }

    if (self.opts.trace) {
        self.startTraceServer();
    }

    if (self.opts.relay || self.opts.trace) {
        setTimeout(startRelayServers, 500);
    } else {
        setTimeout(startClient, 500);
    }

    function startRelayServers() {
        self.startRelay('bench-relay');
        if (self.opts.trace) {
            self.startRelay('trace-relay');
        }

        setTimeout(startClient, 500);
    }

    function startClient() {
        self.openFileStream();

        if (self.opts.multiProc) {
            self.startClient(CLIENT_PORT);
            self.startClient(CLIENT_PORT + 200);
            self.startClient(CLIENT_PORT + 300);
        } else {
            self.startClient(CLIENT_PORT);
        }

        if (self.opts.torch) {
            self.startTorch();
        }
    }
};

BenchmarkRunner.prototype.startStatsd = function startStatsd() {
    var self = this;

    self.statsdServer = dgram.createSocket('udp4');
    self.statsdServer.bind(STATSD_PORT);
};

BenchmarkRunner.prototype.startServer =
function startServer(serverPort, instances) {
    var self = this;

    if (self.opts.goServer) {
      return self.startGoServer(serverPort, instances);
    }

    var serverProc = run(server, [
        self.opts.trace ? '--trace' : '--no-trace',
        '--traceRelayHostPort', '127.0.0.1:' + RELAY_TRACE_PORT,
        '--port', String(serverPort),
        '--instances', String(instances),
        '--pingOverhead', 'norm:10,5',
        '--setOverhead', 'norm:200,20',
        '--getOverhead', 'norm:100,10'
    ]);
    self.serverProcs.push(serverProc);
    serverProc.stdout.pipe(process.stderr);
    serverProc.stderr.pipe(process.stderr);
};

BenchmarkRunner.prototype.startGoServer =
function startGoServer(serverPort, instances) {
    var self = this;

    var serverProc = runExternal("../../golang/build/examples/bench/server", [
      "--host", "localhost",
      "--port", String(serverPort),
      "--instances", String(instances),
    ]);
    self.serverProcs.push(serverProc);
    serverProc.stdout.pipe(process.stderr);
    serverProc.stderr.pipe(process.stderr);
};

BenchmarkRunner.prototype.startTraceServer =
function startTraceServer() {
    var self = this;

    self.traceProc = run(trace);
    self.traceProc.stdout.pipe(process.stderr);
    self.traceProc.stderr.pipe(process.stdout);
};

BenchmarkRunner.prototype.startRelay =
function startRelay(type) {
    var self = this;

    // type = 'bench-relay'
    var relayProc = run(relay, [
        '--benchPort', String(SERVER_PORT),
        '--tracePort', String(TRACE_SERVER_PORT),
        '--benchRelayPort', String(RELAY_SERVER_PORT),
        '--traceRelayPort', String(RELAY_TRACE_PORT),
        '--type', type,
        '--instances', String(INSTANCE_COUNT),
        self.opts.trace ? '--trace' : '--no-trace',
        self.opts.debug ? '--debug' : '--no-debug'
    ]);
    self.relayProcs.push(relayProc);
    relayProc.stdout.pipe(process.stderr);
    relayProc.stderr.pipe(process.stderr);
};

BenchmarkRunner.prototype.openFileStream =
function openFileStream() {
    var self = this;

    if (self.opts.output) {
        self.fileStream = fs.createWriteStream(self.opts.output, {
            encoding: 'utf8'
        });
    }
};

BenchmarkRunner.prototype.startClient =
function startClient(clientPort) {
    var self = this;

    self.benchCounter++;

    var args = self.opts['--'];
    args = args.concat([
        '--benchPort', String(SERVER_PORT),
        '--clientPort', String(clientPort),
        '--instanceNumber', String(self.benchCounter)
    ]);
    var benchProc = run(bench, args);
    self.benchProcs.push(benchProc);

    benchProc.stderr.pipe(process.stderr);

    benchProc.stdout
        .pipe(ldj.parse())
        .on('data', function onChunk(result) {
            console.log(util.format(
                '%s: %s, %s/%s min/max/avg/p95: %s/%s/%s/%s %sms total, %s ops/sec',
                String(result.instanceNumber),
                lpad(result.descr, 13),
                lpad(result.pipeline, 5),
                result.numClients,
                lpad(result.min, 4),
                lpad(result.max, 4),
                lpad(result.mean.toFixed(2), 7),
                lpad(result.p95.toFixed(2), 7),
                lpad(result.elapsed, 6),
                lpad(typeof result.rate === 'number' ?
                    result.rate.toFixed(2) : 'NaN', 8
                )
            ));

            if (self.fileStream) {
                self.fileStream.write(JSON.stringify(result) + '\n');
            }
        });

    benchProc.once('close', function onClose() {
        if (--self.benchCounter === 0) {
            self.close();
        }
    });
};

BenchmarkRunner.prototype.close = function close() {
    var self = this;

    console.error('benchmark finished');
    for (var i = 0; i < self.serverProcs.length; i++) {
        self.serverProcs[i].kill();
    }
    if (self.traceProc) {
        self.traceProc.kill();
    }

    if (self.fileStream) {
        self.fileStream.end();
    }

    for (i = 0; i < self.relayProcs.length; i++) {
        self.relayProcs[i].kill();
    }

    self.statsdServer.close();
};

BenchmarkRunner.prototype.startTorch = function startTorch() {
    var self = this;

    assert(self.opts.torch === 'client' ||
           self.opts.torch === 'relay' ||
           self.opts.torch === 'server',
           'Torch flag must be client or relay'
    );
    assert(self.opts.torchFile, 'torchFile needed');

    var torchPid;
    var torchFile = self.opts.torchFile;
    var torchTime = self.opts.torchTime || '30';
    var torchDelay = self.opts.torchDelay || 10 * 1000;
    var torchType = self.opts.torchType || 'raw';

    if (self.opts.torch === 'relay') {
        torchPid = self.relayProcs[0].pid;
    } else if (self.opts.torch === 'client') {
        torchPid = self.benchProcs[0].pid;
    } else if (self.opts.torch === 'server') {
        torchPid = self.serverProcs[0].pid;
    }

    setTimeout(function delayTorching() {
        var torchProc = childProcess.spawn('sudo', [
            'torch', torchPid, torchType, torchTime
        ]);
        torchProc.stdout.pipe(
            fs.createWriteStream(torchFile)
        );
        torchProc.stderr.pipe(process.stderr);
        console.error('starting flaming');

        torchProc.once('close', function onTorchClose() {
            console.error('finished flaming');
        });
    }, torchDelay);
};

if (require.main === module) {
    var argv = parseArgs(process.argv.slice(2), {
        '--': true,
        alias: {
            o: 'output'
        },
        boolean: ['relay', 'trace', 'debug']
    });
    var runner = BenchmarkRunner(argv);
    runner.start();
}

function lpad(input, len, chr) {
    var str = input.toString();
    chr = chr || ' ';

    while (str.length < len) {
        str = chr + str;
    }
    return str;
}

function runExternal(runner, args) {
  var child = childProcess.spawn(runner, args);
  console.error('running', runner, child.pid);
  return child;
}

function run(script, args) {
    var name = script.replace(/\.js$/, '');
    args = args ? args.slice(0) : [];
    args.unshift(script);
    var child = childProcess.spawn(process.execPath, args);
    console.error('running', name, child.pid);
    return child;
}
<commit_msg>benchmarks: support disabling endpoint overhead<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/*eslint no-console: 0*/
var childProcess = require('child_process');
var parseArgs = require('minimist');
var path = require('path');
var ldj = require('ldjson-stream');
var fs = require('fs');
var util = require('util');
var process = require('process');
var console = require('console');
var setTimeout = require('timers').setTimeout;
var assert = require('assert');
var dgram = require('dgram');

var server = path.join(__dirname, 'bench_server.js');
var relay = path.join(__dirname, 'relay_server.js');
var trace = path.join(__dirname, 'trace_server.js');
var bench = path.join(__dirname, 'multi_bench.js');

process.stderr.setMaxListeners(Infinity);

var SERVER_PORT = 7100;
var TRACE_SERVER_PORT = 7039;
var RELAY_SERVER_PORT = 7038;
var RELAY_TRACE_PORT = 7037;
var STATSD_PORT = 7036;
var INSTANCE_COUNT = 72;
var CLIENT_PORT = 7041;

function BenchmarkRunner(opts) {
    if (!(this instanceof BenchmarkRunner)) {
        return new BenchmarkRunner(opts);
    }

    var self = this;

    self.opts = opts;

    self.relayProcs = [];
    self.statsdServer = null;
    self.serverProcs = [];
    self.traceProc = null;
    self.benchProcs = [];
    self.benchCounter = 0;
    self.fileStream = null;
}

BenchmarkRunner.prototype.start = function start() {
    var self = this;

    self.startStatsd();

    if (self.opts.multiProc) {
        self.startServer(SERVER_PORT, 24);
        self.startServer(SERVER_PORT + 24, 24);
        self.startServer(SERVER_PORT + 48, 24);
    } else {
        self.startServer(SERVER_PORT, INSTANCE_COUNT);
    }

    if (self.opts.trace) {
        self.startTraceServer();
    }

    if (self.opts.relay || self.opts.trace) {
        setTimeout(startRelayServers, 500);
    } else {
        setTimeout(startClient, 500);
    }

    function startRelayServers() {
        self.startRelay('bench-relay');
        if (self.opts.trace) {
            self.startRelay('trace-relay');
        }

        setTimeout(startClient, 500);
    }

    function startClient() {
        self.openFileStream();

        if (self.opts.multiProc) {
            self.startClient(CLIENT_PORT);
            self.startClient(CLIENT_PORT + 200);
            self.startClient(CLIENT_PORT + 300);
        } else {
            self.startClient(CLIENT_PORT);
        }

        if (self.opts.torch) {
            self.startTorch();
        }
    }
};

BenchmarkRunner.prototype.startStatsd = function startStatsd() {
    var self = this;

    self.statsdServer = dgram.createSocket('udp4');
    self.statsdServer.bind(STATSD_PORT);
};

BenchmarkRunner.prototype.startServer =
function startServer(serverPort, instances) {
    var self = this;

    if (self.opts.goServer) {
      return self.startGoServer(serverPort, instances);
    }

    var noOverhead = self.opts.noEndpointOverhead;

    var serverProc = run(server, [
        self.opts.trace ? '--trace' : '--no-trace',
        '--traceRelayHostPort', '127.0.0.1:' + RELAY_TRACE_PORT,
        '--port', String(serverPort),
        '--instances', String(instances),
        '--pingOverhead', noOverhead ? 'none' : 'norm:10,5',
        '--setOverhead', noOverhead ? 'none' : 'norm:200,20',
        '--getOverhead', noOverhead ? 'none' : 'norm:100,10'
    ]);
    self.serverProcs.push(serverProc);
    serverProc.stdout.pipe(process.stderr);
    serverProc.stderr.pipe(process.stderr);
};

BenchmarkRunner.prototype.startGoServer =
function startGoServer(serverPort, instances) {
    var self = this;

    var serverProc = runExternal("../../golang/build/examples/bench/server", [
      "--host", "localhost",
      "--port", String(serverPort),
      "--instances", String(instances),
    ]);
    self.serverProcs.push(serverProc);
    serverProc.stdout.pipe(process.stderr);
    serverProc.stderr.pipe(process.stderr);
};

BenchmarkRunner.prototype.startTraceServer =
function startTraceServer() {
    var self = this;

    self.traceProc = run(trace);
    self.traceProc.stdout.pipe(process.stderr);
    self.traceProc.stderr.pipe(process.stdout);
};

BenchmarkRunner.prototype.startRelay =
function startRelay(type) {
    var self = this;

    // type = 'bench-relay'
    var relayProc = run(relay, [
        '--benchPort', String(SERVER_PORT),
        '--tracePort', String(TRACE_SERVER_PORT),
        '--benchRelayPort', String(RELAY_SERVER_PORT),
        '--traceRelayPort', String(RELAY_TRACE_PORT),
        '--type', type,
        '--instances', String(INSTANCE_COUNT),
        self.opts.trace ? '--trace' : '--no-trace',
        self.opts.debug ? '--debug' : '--no-debug'
    ]);
    self.relayProcs.push(relayProc);
    relayProc.stdout.pipe(process.stderr);
    relayProc.stderr.pipe(process.stderr);
};

BenchmarkRunner.prototype.openFileStream =
function openFileStream() {
    var self = this;

    if (self.opts.output) {
        self.fileStream = fs.createWriteStream(self.opts.output, {
            encoding: 'utf8'
        });
    }
};

BenchmarkRunner.prototype.startClient =
function startClient(clientPort) {
    var self = this;

    self.benchCounter++;

    var args = self.opts['--'];
    args = args.concat([
        '--benchPort', String(SERVER_PORT),
        '--clientPort', String(clientPort),
        '--instanceNumber', String(self.benchCounter)
    ]);
    var benchProc = run(bench, args);
    self.benchProcs.push(benchProc);

    benchProc.stderr.pipe(process.stderr);

    benchProc.stdout
        .pipe(ldj.parse())
        .on('data', function onChunk(result) {
            console.log(util.format(
                '%s: %s, %s/%s min/max/avg/p95: %s/%s/%s/%s %sms total, %s ops/sec',
                String(result.instanceNumber),
                lpad(result.descr, 13),
                lpad(result.pipeline, 5),
                result.numClients,
                lpad(result.min, 4),
                lpad(result.max, 4),
                lpad(result.mean.toFixed(2), 7),
                lpad(result.p95.toFixed(2), 7),
                lpad(result.elapsed, 6),
                lpad(typeof result.rate === 'number' ?
                    result.rate.toFixed(2) : 'NaN', 8
                )
            ));

            if (self.fileStream) {
                self.fileStream.write(JSON.stringify(result) + '\n');
            }
        });

    benchProc.once('close', function onClose() {
        if (--self.benchCounter === 0) {
            self.close();
        }
    });
};

BenchmarkRunner.prototype.close = function close() {
    var self = this;

    console.error('benchmark finished');
    for (var i = 0; i < self.serverProcs.length; i++) {
        self.serverProcs[i].kill();
    }
    if (self.traceProc) {
        self.traceProc.kill();
    }

    if (self.fileStream) {
        self.fileStream.end();
    }

    for (i = 0; i < self.relayProcs.length; i++) {
        self.relayProcs[i].kill();
    }

    self.statsdServer.close();
};

BenchmarkRunner.prototype.startTorch = function startTorch() {
    var self = this;

    assert(self.opts.torch === 'client' ||
           self.opts.torch === 'relay' ||
           self.opts.torch === 'server',
           'Torch flag must be client or relay'
    );
    assert(self.opts.torchFile, 'torchFile needed');

    var torchPid;
    var torchFile = self.opts.torchFile;
    var torchTime = self.opts.torchTime || '30';
    var torchDelay = self.opts.torchDelay || 10 * 1000;
    var torchType = self.opts.torchType || 'raw';

    if (self.opts.torch === 'relay') {
        torchPid = self.relayProcs[0].pid;
    } else if (self.opts.torch === 'client') {
        torchPid = self.benchProcs[0].pid;
    } else if (self.opts.torch === 'server') {
        torchPid = self.serverProcs[0].pid;
    }

    setTimeout(function delayTorching() {
        var torchProc = childProcess.spawn('sudo', [
            'torch', torchPid, torchType, torchTime
        ]);
        torchProc.stdout.pipe(
            fs.createWriteStream(torchFile)
        );
        torchProc.stderr.pipe(process.stderr);
        console.error('starting flaming');

        torchProc.once('close', function onTorchClose() {
            console.error('finished flaming');
        });
    }, torchDelay);
};

if (require.main === module) {
    var argv = parseArgs(process.argv.slice(2), {
        '--': true,
        alias: {
            o: 'output'
        },
        boolean: ['relay', 'trace', 'debug', 'noEndpointOverhead']
    });
    var runner = BenchmarkRunner(argv);
    runner.start();
}

function lpad(input, len, chr) {
    var str = input.toString();
    chr = chr || ' ';

    while (str.length < len) {
        str = chr + str;
    }
    return str;
}

function runExternal(runner, args) {
  var child = childProcess.spawn(runner, args);
  console.error('running', runner, child.pid);
  return child;
}

function run(script, args) {
    var name = script.replace(/\.js$/, '');
    args = args ? args.slice(0) : [];
    args.unshift(script);
    var child = childProcess.spawn(process.execPath, args);
    console.error('running', name, child.pid);
    return child;
}
<|endoftext|>


<commit_before>// person-get-inbox-test-as-root.js
//
// Test getting the inbox of a remote person
//
// Copyright 2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require("assert"),
    vows = require("vows"),
    Step = require("step"),
    http = require("http"),
    querystring = require("querystring"),
    _ = require("underscore"),
    fs = require("fs"),
    path = require("path"),
    Person = require("../lib/model/person").Person,
    databank = require("databank"),
    httputil = require("./lib/http"),
    oauthutil = require("./lib/oauth"),
    newCredentials = oauthutil.newCredentials,
    newClient = oauthutil.newClient,
    pj = httputil.postJSON,
    gj = httputil.getJSON,
    dialbackApp = require("./lib/dialback").dialbackApp,
    setupApp = oauthutil.setupApp,
    Databank = databank.Databank,
    DatabankObject = databank.DatabankObject;

var suite = vows.describe("test discovery of endpoint for a user");

var tc = JSON.parse(fs.readFileSync(path.join(__dirname, "config.json")));

suite.addBatch({
    "When we set up the app": {
        topic: function() {
            var db = Databank.get(tc.driver, tc.params);
            Step(
                function() {
                    db.connect({}, this);
                },
                function(err) {
                    if (err) throw err;
                    DatabankObject.bank = db;
                    setupApp(80, "social.localhost", this);
                },
                this.callback
            );
        },
        "it works": function(err, app) {
            assert.ifError(err);
        },
        teardown: function(app) {
            app.close();
        },
        "and we create an in-process Person with an Webfinger ID on an invalid domain": {
            topic: function() {
                var props = {id: "acct:derrick@social.invalid"},
                    callback = this.callback;
                Person.create(props, callback);
            },
            "it works": function(err, person) {
                assert.ifError(err);
                assert.isObject(person);
                assert.instanceOf(person, Person);
            },
            "and we try to get their inbox URL": {
                topic: function(person) {
                    var callback = this.callback;
                    person.getInbox(function(err, endpoint) {
                        if (err) {
                            callback(null);
                        } else {
                            callback(new Error("Unexpected success"));
                        }
                    });
                },
                "it fails correctly": function(err) {
                    assert.ifError(err);
                }
            }
        },
        "and we create an in-process Person with an Webfinger ID on a valid domain but nonexistent account": {
            topic: function() {
                var props = {id: "acct:mark@social.localhost"},
                    callback = this.callback;
                Person.create(props, callback);
            },
            "it works": function(err, person) {
                assert.ifError(err);
                assert.isObject(person);
                assert.instanceOf(person, Person);
            },
            "and we try to get their inbox URL": {
                topic: function(person) {
                    var callback = this.callback;
                    person.getInbox(function(err, endpoint) {
                        if (err) {
                            callback(null);
                        } else {
                            callback(new Error("Unexpected success"));
                        }
                    });
                },
                "it fails correctly": function(err) {
                    assert.ifError(err);
                }
            }
        },
        "and we get new OAuth credentials": {
            topic: function() {
                oauthutil.newClient("social.localhost", 80, this.callback);
            },
            "it works": function(err, cl) {
                assert.ifError(err);
                assert.isObject(cl);
            },
            "and we register a new user": {
                topic: function(cl) {
                    oauthutil.register(cl, "jeffmills", "to|the|m00n", "social.localhost", 80, this.callback);
                },
                "it works": function(err, user) {
                    assert.ifError(err);
                    assert.isObject(user);
                },
                "and we create an in-process Person with that ID": {
                    topic: function() {
                        var props = {id: "acct:jeffmills@social.localhost"},
                            callback = this.callback;

                        Person.create(props, function(err, person) {
                            if (err) {
                                callback(err, null);
                            } else {
                                callback(null, person);
                            }
                        });
                    },
                    "it works": function(err, person) {
                        assert.ifError(err);
                        assert.isObject(person);
                    },
                    "and we get that person's inbox": {
                        topic: function(person) {
                            person.getInbox(this.callback);
                        },
                        "it works": function(err, inbox) {
                            assert.ifError(err);
                            assert.isString(inbox);
                        },
                        "it is correct": function(err, inbox) {
                            assert.ifError(err);
                            assert.isString(inbox);
                            assert.equal(inbox, "http://social.localhost/api/user/jeffmills/inbox");
                        }
                    }
                }
            }
        }
    }
});

suite["export"](module);
<commit_msg>Don't use the same store for local and remote in person-get-inbox-test-as-root.js<commit_after>// person-get-inbox-test-as-root.js
//
// Test getting the inbox of a remote person
//
// Copyright 2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require("assert"),
    vows = require("vows"),
    Step = require("step"),
    http = require("http"),
    querystring = require("querystring"),
    _ = require("underscore"),
    fs = require("fs"),
    path = require("path"),
    Person = require("../lib/model/person").Person,
    databank = require("databank"),
    httputil = require("./lib/http"),
    oauthutil = require("./lib/oauth"),
    newCredentials = oauthutil.newCredentials,
    newClient = oauthutil.newClient,
    pj = httputil.postJSON,
    gj = httputil.getJSON,
    dialbackApp = require("./lib/dialback").dialbackApp,
    setupAppConfig = oauthutil.setupAppConfig,
    Databank = databank.Databank,
    DatabankObject = databank.DatabankObject;

var suite = vows.describe("test discovery of endpoint for a user");

var tc = JSON.parse(fs.readFileSync(path.join(__dirname, "config.json")));

suite.addBatch({
    "When we set up the app": {
        topic: function() {
            var db = Databank.get(tc.driver, tc.params);
            Step(
                function() {
                    db.connect({}, this);
                },
                function(err) {
                    if (err) throw err;
                    DatabankObject.bank = db;
                    setupAppConfig({port: 80, hostname: "social.localhost", driver: "memory", params: {}}, this);
                },
                this.callback
            );
        },
        "it works": function(err, app) {
            assert.ifError(err);
        },
        teardown: function(app) {
            app.close();
        },
        "and we create an in-process Person with an Webfinger ID on an invalid domain": {
            topic: function() {
                var props = {id: "acct:derrick@social.invalid"},
                    callback = this.callback;
                Person.create(props, callback);
            },
            "it works": function(err, person) {
                assert.ifError(err);
                assert.isObject(person);
                assert.instanceOf(person, Person);
            },
            "and we try to get their inbox URL": {
                topic: function(person) {
                    var callback = this.callback;
                    person.getInbox(function(err, endpoint) {
                        if (err) {
                            callback(null);
                        } else {
                            callback(new Error("Unexpected success"));
                        }
                    });
                },
                "it fails correctly": function(err) {
                    assert.ifError(err);
                }
            }
        },
        "and we create an in-process Person with an Webfinger ID on a valid domain but nonexistent account": {
            topic: function() {
                var props = {id: "acct:mark@social.localhost"},
                    callback = this.callback;
                Person.create(props, callback);
            },
            "it works": function(err, person) {
                assert.ifError(err);
                assert.isObject(person);
                assert.instanceOf(person, Person);
            },
            "and we try to get their inbox URL": {
                topic: function(person) {
                    var callback = this.callback;
                    person.getInbox(function(err, endpoint) {
                        if (err) {
                            callback(null);
                        } else {
                            callback(new Error("Unexpected success"));
                        }
                    });
                },
                "it fails correctly": function(err) {
                    assert.ifError(err);
                }
            }
        },
        "and we get new OAuth credentials": {
            topic: function() {
                oauthutil.newClient("social.localhost", 80, this.callback);
            },
            "it works": function(err, cl) {
                assert.ifError(err);
                assert.isObject(cl);
            },
            "and we register a new user": {
                topic: function(cl) {
                    oauthutil.register(cl, "jeffmills", "to|the|m00n", "social.localhost", 80, this.callback);
                },
                "it works": function(err, user) {
                    assert.ifError(err);
                    assert.isObject(user);
                },
                "and we create an in-process Person with that ID": {
                    topic: function() {
                        var props = {id: "acct:jeffmills@social.localhost"},
                            callback = this.callback;

                        Person.create(props, function(err, person) {
                            if (err) {
                                callback(err, null);
                            } else {
                                callback(null, person);
                            }
                        });
                    },
                    "it works": function(err, person) {
                        assert.ifError(err);
                        assert.isObject(person);
                    },
                    "and we get that person's inbox": {
                        topic: function(person) {
                            person.getInbox(this.callback);
                        },
                        "it works": function(err, inbox) {
                            assert.ifError(err);
                            assert.isString(inbox);
                        },
                        "it is correct": function(err, inbox) {
                            assert.ifError(err);
                            assert.isString(inbox);
                            assert.equal(inbox, "http://social.localhost/api/user/jeffmills/inbox");
                        }
                    }
                }
            }
        }
    }
});

suite["export"](module);
<|endoftext|>


<commit_before> /*
  * jsHelper 0.1
  * Copyright (c) 2014 FrankFan http://fy98.com/
  * Date: 2014-11-20
  * jsHelper插件封装了一些jQuery中没有的方法
  */
 (function($) {
     $.fn.jsHelper = function(options) {
         var defaults = {
             evenRowClass: "evenRow",
             oddRowClass: "oddRow",
             activeRowClass: "activeRow"
         }

         var options = $.extend(defaults, options);

         this.each(function() {
             var thisTable = $(this);
             //添加奇偶行颜色
             $(thisTable).find("tr:even").addClass(options.evenRowClass);
             $(thisTable).find("tr:odd").addClass(options.oddRowClass);
             //添加活动行颜色
             $(thisTable).find("tr").bind("mouseover", function() {
                 $(this).addClass(options.activeRowClass);
             });
             $(thisTable).find("tr").bind("mouseout", function() {
                 $(this).removeClass(options.activeRowClass);
             });
         });
     };
 })(jQuery);<commit_msg>update<commit_after> /*
  * jsHelper 0.1
  * Copyright (c) 2014 FrankFan http://fy98.com/
  * Date: 2014-11-20
  * jsHelper插件封装了一些jQuery中没有的方法
  */
 (function($) {
     $.fn.jsHelper = function(options) {
         var defaults = {
             evenRowClass: "evenRow",
             oddRowClass: "oddRow",
             activeRowClass: "activeRow"
         }

         var options = $.extend(defaults, options);

         this.each(function() {
             var thisTable = $(this);
             //添加奇偶行颜色
             $(thisTable).find("tr:even").addClass(options.evenRowClass);
             $(thisTable).find("tr:odd").addClass(options.oddRowClass);
             //添加活动行颜色
             $(thisTable).find("tr").bind("mouseover", function() {
                 $(this).addClass(options.activeRowClass);
             });
             $(thisTable).find("tr").bind("mouseout", function() {
                 $(this).removeClass(options.activeRowClass);
             });
         });

     };
 })(jQuery);<|endoftext|>


<commit_before><commit_msg>[RM8002|RS8010] Detector clear float BUG=https://code.google.com/p/compatibility-detector/issues/detail?id=155 TEST=None<commit_after><|endoftext|>