<commit_before>/*
 * Conditions Extension
 *
 *   Allows a condition module to alter the resolution of an import via syntax:
 *
 *     import $ from 'jquery/#{browser}';
 *
 *   Will first load the module 'browser' via `SystemJS.import('browser')` and
 *   take the default export of that module.
 *   If the default export is not a string, an error is thrown.
 *
 *   We then substitute the string into the require to get the conditional resolution
 *   enabling environment-specific variations like:
 *
 *     import $ from 'jquery/ie'
 *     import $ from 'jquery/firefox'
 *     import $ from 'jquery/chrome'
 *     import $ from 'jquery/safari'
 *
 *   It can be useful for a condition module to define multiple conditions.
 *   This can be done via the `|` modifier to specify an export member expression:
 *
 *     import 'jquery/#{./browser.js|grade.version}'
 *
 *   Where the `grade` export `version` member in the `browser.js` module  is substituted.
 *
 *
 * Boolean Conditionals
 *
 *   For polyfill modules, that are used as imports but have no module value,
 *   a binary conditional allows a module not to be loaded at all if not needed:
 *
 *     import 'es5-shim#?./conditions.js|needs-es5shim'
 *
 *   These conditions can also be negated via:
 *
 *     import 'es5-shim#?./conditions.js|~es6'
 *
 */

  var sysConditions = ['browser', 'node', 'dev', 'production', 'default'];

  function parseCondition(condition) {
    var conditionExport, conditionModule, negation;

    var negation = condition[0] == '~';
    var conditionExportIndex = condition.lastIndexOf('|');
    if (conditionExportIndex != -1) {
      conditionExport = condition.substr(conditionExportIndex + 1);
      conditionModule = condition.substr(negation, conditionExportIndex - negation);

      if (negation)
        warn.call(this, 'Condition negation form "' + condition + '" is deprecated for "' + conditionModule + '|~' + conditionExport + '"');

      if (conditionExport[0] == '~') {
        negation = true;
        conditionExport = conditionExport.substr(1);
      }
    }
    else {
      conditionExport = 'default';
      conditionModule = condition.substr(negation);
      if (sysConditions.indexOf(conditionModule) != -1) {
        conditionExport = conditionModule;
        conditionModule = null;
      }
    }

    return {
      module: conditionModule || '@system-env',
      prop: conditionExport,
      negate: negation
    };
  }

  function serializeCondition(conditionObj) {
    return conditionObj.module + '|' + (conditionObj.negate ? '~' : '') + conditionObj.prop;
  }

  function resolveCondition(conditionObj, parentName, bool) {
    var self = this;
    return this.normalize(conditionObj.module, parentName)
    .then(function(normalizedCondition) {
      return self.load(normalizedCondition)
      .then(function(q) {
        var m = readMemberExpression(conditionObj.prop, self.get(normalizedCondition));

        if (bool && typeof m != 'boolean')
          throw new TypeError('Condition ' + serializeCondition(conditionObj) + ' did not resolve to a boolean.');

        return conditionObj.negate ? !m : m;
      });
    });
  }

  var interpolationRegEx = /#\{[^\}]+\}/;
  function interpolateConditional(name, parentName) {
    // first we normalize the conditional
    var conditionalMatch = name.match(interpolationRegEx);

    if (!conditionalMatch)
      return Promise.resolve(name);

    var conditionObj = parseCondition.call(this, conditionalMatch[0].substr(2, conditionalMatch[0].length - 3));

    // in builds, return normalized conditional
    if (this.builder)
      return this['normalize'](conditionObj.module, parentName)
      .then(function(conditionModule) {
        conditionObj.module = conditionModule;
        return name.replace(interpolationRegEx, '#{' + serializeCondition(conditionObj) + '}');
      });

    return resolveCondition.call(this, conditionObj, parentName, false)
    .then(function(conditionValue) {
      if (typeof conditionValue !== 'string')
        throw new TypeError('The condition value for ' + name + ' doesn\'t resolve to a string.');

      if (conditionValue.indexOf('/') != -1)
        throw new TypeError('Unabled to interpolate conditional ' + name + (parentName ? ' in ' + parentName : '') + '\n\tThe condition value ' + conditionValue + ' cannot contain a "/" separator.');

      return name.replace(interpolationRegEx, conditionValue);
    });
  }

  function booleanConditional(name, parentName) {
    // first we normalize the conditional
    var booleanIndex = name.lastIndexOf('#?');

    if (booleanIndex == -1)
      return Promise.resolve(name);

    var conditionObj = parseCondition.call(this, name.substr(booleanIndex + 2));

    // in builds, return normalized conditional
    if (this.builder)
      return this['normalize'](conditionObj.module, parentName)
      .then(function(conditionModule) {
        conditionObj.module = conditionModule;
        return name.substr(0, booleanIndex) + '#?' + serializeCondition(conditionObj);
      });

    return resolveCondition.call(this, conditionObj, parentName, true)
    .then(function(conditionValue) {
      return conditionValue ? name.substr(0, booleanIndex) : '@empty';
    });
  }

  // normalizeSync does not parse conditionals at all although it could
  hook('normalize', function(normalize) {
    return function(name, parentName, parentAddress) {
      var loader = this;
      return booleanConditional.call(loader, name, parentName)
      .then(function(name) {
        return normalize.call(loader, name, parentName, parentAddress);
      })
      .then(function(normalized) {
        return interpolateConditional.call(loader, normalized, parentName);
      });
    };
  });
<commit_msg>Fixed wrongly named parameter... seems to be copy paste error from "import".<commit_after>/*
 * Conditions Extension
 *
 *   Allows a condition module to alter the resolution of an import via syntax:
 *
 *     import $ from 'jquery/#{browser}';
 *
 *   Will first load the module 'browser' via `SystemJS.import('browser')` and
 *   take the default export of that module.
 *   If the default export is not a string, an error is thrown.
 *
 *   We then substitute the string into the require to get the conditional resolution
 *   enabling environment-specific variations like:
 *
 *     import $ from 'jquery/ie'
 *     import $ from 'jquery/firefox'
 *     import $ from 'jquery/chrome'
 *     import $ from 'jquery/safari'
 *
 *   It can be useful for a condition module to define multiple conditions.
 *   This can be done via the `|` modifier to specify an export member expression:
 *
 *     import 'jquery/#{./browser.js|grade.version}'
 *
 *   Where the `grade` export `version` member in the `browser.js` module  is substituted.
 *
 *
 * Boolean Conditionals
 *
 *   For polyfill modules, that are used as imports but have no module value,
 *   a binary conditional allows a module not to be loaded at all if not needed:
 *
 *     import 'es5-shim#?./conditions.js|needs-es5shim'
 *
 *   These conditions can also be negated via:
 *
 *     import 'es5-shim#?./conditions.js|~es6'
 *
 */

  var sysConditions = ['browser', 'node', 'dev', 'production', 'default'];

  function parseCondition(condition) {
    var conditionExport, conditionModule, negation;

    var negation = condition[0] == '~';
    var conditionExportIndex = condition.lastIndexOf('|');
    if (conditionExportIndex != -1) {
      conditionExport = condition.substr(conditionExportIndex + 1);
      conditionModule = condition.substr(negation, conditionExportIndex - negation);

      if (negation)
        warn.call(this, 'Condition negation form "' + condition + '" is deprecated for "' + conditionModule + '|~' + conditionExport + '"');

      if (conditionExport[0] == '~') {
        negation = true;
        conditionExport = conditionExport.substr(1);
      }
    }
    else {
      conditionExport = 'default';
      conditionModule = condition.substr(negation);
      if (sysConditions.indexOf(conditionModule) != -1) {
        conditionExport = conditionModule;
        conditionModule = null;
      }
    }

    return {
      module: conditionModule || '@system-env',
      prop: conditionExport,
      negate: negation
    };
  }

  function serializeCondition(conditionObj) {
    return conditionObj.module + '|' + (conditionObj.negate ? '~' : '') + conditionObj.prop;
  }

  function resolveCondition(conditionObj, parentName, bool) {
    var self = this;
    return this.normalize(conditionObj.module, parentName)
    .then(function(normalizedCondition) {
      return self.load(normalizedCondition)
      .then(function(q) {
        var m = readMemberExpression(conditionObj.prop, self.get(normalizedCondition));

        if (bool && typeof m != 'boolean')
          throw new TypeError('Condition ' + serializeCondition(conditionObj) + ' did not resolve to a boolean.');

        return conditionObj.negate ? !m : m;
      });
    });
  }

  var interpolationRegEx = /#\{[^\}]+\}/;
  function interpolateConditional(name, parentName) {
    // first we normalize the conditional
    var conditionalMatch = name.match(interpolationRegEx);

    if (!conditionalMatch)
      return Promise.resolve(name);

    var conditionObj = parseCondition.call(this, conditionalMatch[0].substr(2, conditionalMatch[0].length - 3));

    // in builds, return normalized conditional
    if (this.builder)
      return this['normalize'](conditionObj.module, parentName)
      .then(function(conditionModule) {
        conditionObj.module = conditionModule;
        return name.replace(interpolationRegEx, '#{' + serializeCondition(conditionObj) + '}');
      });

    return resolveCondition.call(this, conditionObj, parentName, false)
    .then(function(conditionValue) {
      if (typeof conditionValue !== 'string')
        throw new TypeError('The condition value for ' + name + ' doesn\'t resolve to a string.');

      if (conditionValue.indexOf('/') != -1)
        throw new TypeError('Unabled to interpolate conditional ' + name + (parentName ? ' in ' + parentName : '') + '\n\tThe condition value ' + conditionValue + ' cannot contain a "/" separator.');

      return name.replace(interpolationRegEx, conditionValue);
    });
  }

  function booleanConditional(name, parentName) {
    // first we normalize the conditional
    var booleanIndex = name.lastIndexOf('#?');

    if (booleanIndex == -1)
      return Promise.resolve(name);

    var conditionObj = parseCondition.call(this, name.substr(booleanIndex + 2));

    // in builds, return normalized conditional
    if (this.builder)
      return this['normalize'](conditionObj.module, parentName)
      .then(function(conditionModule) {
        conditionObj.module = conditionModule;
        return name.substr(0, booleanIndex) + '#?' + serializeCondition(conditionObj);
      });

    return resolveCondition.call(this, conditionObj, parentName, true)
    .then(function(conditionValue) {
      return conditionValue ? name.substr(0, booleanIndex) : '@empty';
    });
  }

  // normalizeSync does not parse conditionals at all although it could
  hook('normalize', function(normalize) {
    return function(name, parentName, skipExt) {
      var loader = this;
      return booleanConditional.call(loader, name, parentName)
      .then(function(name) {
        return normalize.call(loader, name, parentName, skipExt);
      })
      .then(function(normalized) {
        return interpolateConditional.call(loader, normalized, parentName);
      });
    };
  });
<|endoftext|>


<commit_before>module.exports = [
  {
    // emit when a request is received by server http (/lib/api/core/servers.js)
    'data:create': [
        'log:log',
        'write:add'
    ],
    'data:update': ['write:add'],
    'data:delete': ['write:add'],
    'data:deleteByQuery': ['write:add'],
    'data:bulkImport': ['write:add'],
    'data:deleteCollection': ['write:add'],
    'data:putMapping': ['write:add']
  }

];<commit_msg>avoid logstash logging<commit_after>module.exports = [
  {
    // emit when a request is received by server http (/lib/api/core/servers.js)
    'data:create': [
        'write:add'
    ],
    'data:update': ['write:add'],
    'data:delete': ['write:add'],
    'data:deleteByQuery': ['write:add'],
    'data:bulkImport': ['write:add'],
    'data:deleteCollection': ['write:add'],
    'data:putMapping': ['write:add']
  }

];<|endoftext|>


<commit_before>const Path = require('path');
const Fs = require('fs');
const WebpackConfig = require(Path.join(process.cwd(), 'webpack.config')).options;

// debug mode
exports.debug = process.env.DEBUG || false;

// development, staging or production
exports.environment = process.env.NODE_ENV || 'development';

exports.connections = {
    web: {
        host: process.env.WEB_HOST || 'localhost',
        port: process.env.WEB_PORT || 8080,
        enabled: false
    },
    api: {
        host: process.env.API_HOST || 'localhost',
        port: process.env.API_PORT || 8081,
        tls: true,
        enabled: true
    },
    webTls: {
        host: process.env.WEB_TLS_HOST || 'localhost',
        port: process.env.WEB_TLS_HOST || 8443,
        enabled: false
    }
};

exports.auth = {
    expiresIn: '8h',
};

exports.build = {
    src: WebpackConfig.paths.src.path,
    dist: WebpackConfig.paths.output.path
};

exports.prefixes = {
    login: '/login',
    logout: '/logout',
    admin: '/admin',
    api: '/api',
    home: '/home',
    scripts: '/js',
    images: '/img',
    styles: '/css',
    fonts: '/fonts',
    profile: '/profile',
    user: '/user/{id}',
    role: '/role/{id}'
};

exports.monitor = {
    debug: exports.debug,
    interval: 5000,
    format: 'DD-MM-YYYY HH:mm:SS X', // MomentJS format string
    path: 'log'
};

exports.cache = {
    views: false, // for dev only
    images: {
        expiresIn: 30 * 1000,
        privacy: 'private'
    },
    scripts: {
        expiresIn: 30 * 1000,
        privacy: 'private'
    },
    styles: {
        expiresIn: 30 * 1000,
        privacy: 'private'
    },
    fonts: {
        expiresIn: 30 * 1000,
        privacy: 'private'
    }
};

exports.logs = {
    size: '10M',
    interval: '5d',
    rotate: 5
};

// node tls options object, check
// https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
exports.tls = {
    key: Fs.readFileSync('./certs/key.pem'),
    cert: Fs.readFileSync('./certs/cert.pem'),
};

exports.redirect = {
    // Routes that should not be requested via HTTP, redirect them to our TLS connection
    tlsOnly: [exports.prefixes.admin, exports.prefixes.profile, exports.prefixes.user, exports.prefixes.role]
};
<commit_msg>added missing config profile prefix<commit_after>const Path = require('path');
const Fs = require('fs');
const WebpackConfig = require(Path.join(process.cwd(), 'webpack.config')).options;

// debug mode
exports.debug = process.env.DEBUG || false;

// development, staging or production
exports.environment = process.env.NODE_ENV || 'development';

exports.connections = {
    web: {
        host: process.env.WEB_HOST || 'localhost',
        port: process.env.WEB_PORT || 8080,
        enabled: false
    },
    api: {
        host: process.env.API_HOST || 'localhost',
        port: process.env.API_PORT || 8081,
        tls: true,
        enabled: true
    },
    webTls: {
        host: process.env.WEB_TLS_HOST || 'localhost',
        port: process.env.WEB_TLS_HOST || 8443,
        enabled: false
    }
};

exports.auth = {
    expiresIn: '8h',
};

exports.build = {
    src: WebpackConfig.paths.src.path,
    dist: WebpackConfig.paths.output.path
};

exports.prefixes = {
    api: '/api',
    login: '/login',
    logout: '/logout',
    admin: '/admin',
    home: '/home',
    profile: '/profile',
    scripts: '/js',
    images: '/img',
    styles: '/css',
    fonts: '/fonts'
};

exports.monitor = {
    debug: exports.debug,
    interval: 5000,
    format: 'DD-MM-YYYY HH:mm:SS X', // MomentJS format string
    path: 'log'
};

exports.cache = {
    views: false, // for dev only
    images: {
        expiresIn: 30 * 1000,
        privacy: 'private'
    },
    scripts: {
        expiresIn: 30 * 1000,
        privacy: 'private'
    },
    styles: {
        expiresIn: 30 * 1000,
        privacy: 'private'
    },
    fonts: {
        expiresIn: 30 * 1000,
        privacy: 'private'
    }
};

exports.logs = {
    size: '10M',
    interval: '5d',
    rotate: 5
};

// node tls options object, check
// https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
exports.tls = {
    key: Fs.readFileSync('./certs/key.pem'),
    cert: Fs.readFileSync('./certs/cert.pem'),
};

exports.redirect = {
    // Routes that should not be requested via HTTP, redirect them to our TLS connection
    tlsOnly: [exports.prefixes.admin, exports.prefixes.profile, exports.prefixes.user, exports.prefixes.role]
};
<|endoftext|>


<commit_before>/**
 * Copyright 2015 Netsend.
 *
 * This file is part of Mastersync.
 *
 * Mastersync is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Affero General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * Mastersync is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with Mastersync. If not, see <https://www.gnu.org/licenses/>.
 */

'use strict';

var programName = 'cm';

var async = require('async');

// return a string identifier of the connection if connected over ip
function createId(conn) {
  if (typeof conn !== 'object') { throw new TypeError('conn must be an object'); }

  var connId;
  if (conn.remoteAddress) {
    connId = conn.remoteAddress + '-' + conn.remotePort + '-' + conn.localAddress + '-' + conn.localPort;
  } else {
    connId = 'UNIX domain socket';
  }
  return connId;
}

// return a connection manager with the methods register and close.
function connManager(opts) {
  opts = opts || {};
  if (typeof opts !== 'object') { throw new TypeError('opts must be an object'); }

  if (typeof opts.debug !== 'undefined' && typeof opts.debug !== 'boolean') { throw new TypeError('opts.debug must be a boolean'); }
  if (typeof opts.hide !== 'undefined' && typeof opts.hide !== 'boolean') { throw new TypeError('opts.hide must be a boolean'); }

  var conns = [];

  function register(conn) {
    if (typeof conn !== 'object') { throw new TypeError('conn must be an object'); }

    var connId = createId(conn);

    if (opts.debug) { console.log('%s: conn registering %s', programName, conns.length, connId); }

    conns.push(conn);

    // update connection id after connected
    conn.once('connect', function() {
      var oConnId = connId;
      connId = createId(conn);
      if (opts.debug) { console.log('%s: updated connId from %s to %s', programName, oConnId, connId); }
    });

    conn.on('error', function(err) {
      if (!opts.hide) { console.error('%s: conn error: %s %s', programName, err, connId); }
    });

    conn.once('end', function() {
      if (opts.debug) { console.log('%s: conn end: %s', programName, connId); }
    });

    conn.once('close', function() {
      _remove(conn);
    });
  }

  function close(cb) {
    if (typeof cb !== 'function') { throw new TypeError('cb must be a function'); }

    async.each(conns, function(conn, cb2) {
      var connId = createId(conn);

      if (opts.debug) { console.log('%s: closing connection %s...', programName, connId); }

      var closed = false;
      conn.once('close', function() {
        if (opts.debug) { console.log('%s: conn closed %s', programName, connId); }
        closed = true;
        cb2();
      });

      // give the peer some time to end
      setTimeout(function() {
        if (closed) { return; }

        if (!opts.hide) { console.log('%s: conn destroyed %s', programName, connId); }
        conn.destroy();
        _remove(conn);
        cb2();
      }, 100);

      conn.end();
    }, cb);
  }

  /**
   * Remove given collection.
   *
   * @param {Object} conn  connection to remove
   * @return {Boolean} true if removed, false if not found
   */
  function _remove(conn) {
    if (typeof conn !== 'object') { throw new TypeError('conn must be an object'); }

    var connId = createId(conn);

    if (opts.debug) { console.log('%s: conn close: %s', programName, connId); }
    var i = conns.indexOf(conn);
    if (~i) {
      if (opts.debug) { console.log('%s: removing conn %s', programName, i); }
      conns.splice(i, 1);
      return true;
    }

    if (!opts.hide) { console.error('%s: conn not found %s', programName); }
    return false;
  }

  return {
    register: register,
    close: close,
    _conns: conns,
    _remove: _remove
  };
}

module.exports.create = connManager;
module.exports.createId = createId;
<commit_msg>conn_manager: add and clarify debug info<commit_after>/**
 * Copyright 2015 Netsend.
 *
 * This file is part of Mastersync.
 *
 * Mastersync is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Affero General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * Mastersync is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with Mastersync. If not, see <https://www.gnu.org/licenses/>.
 */

'use strict';

var programName = 'cm';

var async = require('async');

// return a string identifier of the connection if connected over ip
function createId(conn) {
  if (typeof conn !== 'object') { throw new TypeError('conn must be an object'); }

  var connId;
  if (conn.remoteAddress) {
    connId = conn.remoteAddress + '-' + conn.remotePort + '-' + conn.localAddress + '-' + conn.localPort;
  } else {
    connId = 'UNIX domain socket';
  }
  return connId;
}

// return a connection manager with the methods register and close.
function connManager(opts) {
  opts = opts || {};
  if (typeof opts !== 'object') { throw new TypeError('opts must be an object'); }

  if (typeof opts.debug !== 'undefined' && typeof opts.debug !== 'boolean') { throw new TypeError('opts.debug must be a boolean'); }
  if (typeof opts.hide !== 'undefined' && typeof opts.hide !== 'boolean') { throw new TypeError('opts.hide must be a boolean'); }

  var conns = [];

  function register(conn) {
    if (typeof conn !== 'object') { throw new TypeError('conn must be an object'); }

    var connId = createId(conn);

    var remoteAddr, remotePort;

    if (opts.debug) { console.log('%s: register: conn registering %s', programName, conns.length, connId); }

    conns.push(conn);

    // update connection id after connected
    conn.once('connect', function() {
      var oConnId = connId;
      connId = createId(conn);
      if (opts.debug) { console.log('%s: register: updated connId from %s to %s', programName, oConnId, connId); }

      remoteAddr = conn.remoteAddress;
      remotePort = conn.remotePort;
    });

    conn.on('error', function(err) {
      if (!opts.hide) { console.error('%s: register: conn error: %s %s', programName, err, connId); }
    });

    conn.once('end', function() {
      if (opts.debug) { console.log('%s: register: conn end: %s', programName, connId); }
    });

    conn.once('close', function(errOccurred) {
      if (opts.debug) { console.log('%s: register: conn close: %s', programName, connId); }
      _remove(conn);
    });
  }

  function close(cb) {
    if (typeof cb !== 'function') { throw new TypeError('cb must be a function'); }

    async.each(conns, function(conn, cb2) {
      var connId = createId(conn);

      if (opts.debug) { console.log('%s: close: closing connection %s...', programName, connId); }

      var closed = false;
      conn.once('close', function() {
        if (opts.debug) { console.log('%s: close: conn closed %s', programName, connId); }
        closed = true;
        cb2();
      });

      // give the peer some time to end
      setTimeout(function() {
        if (closed) { return; }

        if (!opts.hide) { console.log('%s: close: conn destroyed %s', programName, connId); }
        conn.destroy();
        _remove(conn);
        cb2();
      }, 100);

      conn.end();
    }, cb);
  }

  /**
   * Remove given collection.
   *
   * @param {Object} conn  connection to remove
   * @return {Boolean} true if removed, false if not found
   */
  function _remove(conn) {
    if (typeof conn !== 'object') { throw new TypeError('conn must be an object'); }

    var connId = createId(conn);

    if (opts.debug) { console.log('%s: _remove: conn close: %s', programName, connId); }
    var i = conns.indexOf(conn);
    if (~i) {
      if (opts.debug) { console.log('%s: _remove: removing conn %s', programName, i); }
      conns.splice(i, 1);
      return true;
    }

    if (!opts.hide) { console.error('%s: _remove: conn not found %s', programName); }
    return false;
  }

  return {
    register: register,
    close: close,
    _conns: conns,
    _remove: _remove
  };
}

module.exports.create = connManager;
module.exports.createId = createId;
<|endoftext|>


<commit_before>// Copyright (c) 2016 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';

var test = require('tape');
var DebugLogtron = require('debug-logtron');

var TChannel = require('../../');
var HyperbahnClient = require('../../hyperbahn/index.js');

test('creating HyperbahnClient with new', function t(assert) {
    var logger = DebugLogtron('hyperbahnclient');

    var c = new HyperbahnClient({
        tchannel: TChannel({
            logger: logger
        }),
        serviceName: 'foo',
        callerName: 'foo-test',
        hostPortList: [],
        logger: logger
    });

    assert.ok(c, 'can create a client');

    c.tchannel.close();
    assert.end();
});

test('create HyperbahnClient without options', function t(assert) {
    assert.throws(function throwIt() {
        HyperbahnClient();
    }, /Must pass in a tchannel/);

    assert.end();
});

test('create HyperbahnClient without options.tchannel', function t(assert) {
    assert.throws(function throwIt() {
        HyperbahnClient({});
    }, /Must pass in a tchannel/);

    assert.end();
});

test('create HyperbahnClient with a subchannel', function t(assert) {
    var tchannel = TChannel();
    assert.throws(function throwIt() {
        HyperbahnClient({
            tchannel: tchannel.makeSubChannel({
                serviceName: 'foo'
            })
        });
    }, /Must pass in top level tchannel/);

    tchannel.close();
    assert.end();
});

test('create HyperbahnClient without serviceName', function t(assert) {
    var tchannel = TChannel();
    assert.throws(function throwIt() {
        HyperbahnClient({
            tchannel: tchannel
        });
    }, /must pass in serviceName/);

    tchannel.close();
    assert.end();
});

test('create HyperbahnClient without hostPortList', function t(assert) {
    var tchannel = TChannel();
    assert.throws(function throwIt() {
        HyperbahnClient({
            tchannel: tchannel,
            serviceName: 'foo'
        });
    }, /Must pass in hostPortList as array or hostPortFile as string/);

    tchannel.close();
    assert.end();
});

test('create HyperbahnClient with bad hostPortFile', function t(assert) {
    var tchannel = TChannel();
    assert.throws(function throwIt() {
        HyperbahnClient({
            tchannel: tchannel,
            serviceName: 'foo',
            hostPortFile: '~~~~~'
        });
    }, /Read host port list failed with Error: ENOENT, no such file or directory \'~~~~~\'/);

    tchannel.close();
    assert.end();
});
<commit_msg>fixup hyperbahn-client test<commit_after>// Copyright (c) 2016 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';

var test = require('tape');
var DebugLogtron = require('debug-logtron');

var TChannel = require('../../');
var HyperbahnClient = require('../../hyperbahn/index.js');

test('creating HyperbahnClient with new', function t(assert) {
    var logger = DebugLogtron('hyperbahnclient');

    var c = new HyperbahnClient({
        tchannel: TChannel({
            logger: logger
        }),
        serviceName: 'foo',
        callerName: 'foo-test',
        hostPortList: [],
        logger: logger
    });

    assert.ok(c, 'can create a client');

    c.tchannel.close();
    assert.end();
});

test('create HyperbahnClient without options', function t(assert) {
    assert.throws(function throwIt() {
        HyperbahnClient();
    }, /Must pass in a tchannel/);

    assert.end();
});

test('create HyperbahnClient without options.tchannel', function t(assert) {
    assert.throws(function throwIt() {
        HyperbahnClient({});
    }, /Must pass in a tchannel/);

    assert.end();
});

test('create HyperbahnClient with a subchannel', function t(assert) {
    var tchannel = TChannel();
    assert.throws(function throwIt() {
        HyperbahnClient({
            tchannel: tchannel.makeSubChannel({
                serviceName: 'foo'
            })
        });
    }, /Must pass in top level tchannel/);

    tchannel.close();
    assert.end();
});

test('create HyperbahnClient without serviceName', function t(assert) {
    var tchannel = TChannel();
    assert.throws(function throwIt() {
        HyperbahnClient({
            tchannel: tchannel
        });
    }, /must pass in serviceName/);

    tchannel.close();
    assert.end();
});

test('create HyperbahnClient without hostPortList', function t(assert) {
    var tchannel = TChannel();
    assert.throws(function throwIt() {
        HyperbahnClient({
            tchannel: tchannel,
            serviceName: 'foo'
        });
    }, /Must pass in hostPortList as array or hostPortFile as string/);

    tchannel.close();
    assert.end();
});

test('create HyperbahnClient with bad hostPortFile', function t(assert) {
    var tchannel = TChannel();
    assert.throws(function throwIt() {
        HyperbahnClient({
            tchannel: tchannel,
            serviceName: 'foo',
            hostPortFile: '~~~~~'
        });
    }, /Read host port list failed with Error: ENOENT[,:] no such file or directory/);

    tchannel.close();
    assert.end();
});
<|endoftext|>


<commit_before>var KA_LAT  = 49.00921;
var KA_LNG  = 8.45003951;
var elemSvg = null;

var GEOJSON = null;
var Party = ["CDU","SPD","FDP","GRÜNE","DIE LINKE","PIRATEN","NPD","REP","Tierschutzpartei","ÖDP","PBC","Volksabstimmung","MLPD ","BüSo","AfD","BIG","pro Deutschland","FREIE WÄHLER","PARTEI DER VERNUNFT","RENTNER"];

const PartyColors = ["000","f40502","feed01","42a62a","8b1b62","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","009de0","ffffff","ffffff","ffffff","ffffff","ffffff"];

var TILES_URL = 'http://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';

var MAP_ATTRIBUTION = 'Map data © ' +
                      'OpenStreetMap contributors | Tiles © ' +
                      'Carto';

var map = new L.Map("map", {center: [KA_LAT, KA_LNG], zoom: 12})
    .addLayer(new L.TileLayer(TILES_URL, {attribution: MAP_ATTRIBUTION}));

var svg = d3.select(map.getPanes().overlayPane).append("svg"),
    g = svg.append("g").attr("class", "leaflet-zoom-hide");

// SVG ID
svg.attr("id", "karte")

var stadtteile = g.append('g')
    .classed('stadtteile', true);

var wahlbezirke = g.append('g')
    .classed('wahlbezirke', true);

/**
 * Adapter to use Leaflet's projection in D3.
 */
function projectPoint(x, y) {
    var point = map.latLngToLayerPoint(new L.LatLng(y, x));
    this.stream.point(point.x, point.y);
}
var transform = d3.geo.transform({ point: projectPoint }),
    path = d3.geo.path().projection(transform);

/**
 * Create SVG paths from a GeoJSON file.
 */
function pathsFromGeoJSON(filename, group, setGeoJson, callback) {

    d3.json(filename, function (error, collection) {
        if (error) return callback(error, null);

        if (GEOJSON === null && setGeoJson){
            GEOJSON = collection
        }
        var feature = group.selectAll("path")
            .data(collection.features)
            .enter().append("path");

        map.on("viewreset", reset);
        reset();

        return callback(null, feature);

        // Reposition the SVG to cover the features.
        function reset() {
            var bounds = path.bounds(collection);
            var topLeft = bounds[0];
            var bottomRight = bounds[1];

            svg.attr("width", bottomRight[0] - topLeft[0])
                .attr("height", bottomRight[1] - topLeft[1])
                .style("left", topLeft[0] + "px")
                .style("top", topLeft[1] + "px");

            group.attr("transform", "translate(" + -topLeft[0] + "," + -topLeft[1] + ")");

            feature.attr("d", path);
        }
    });
}

pathsFromGeoJSON("ka_stadtteile.geojson", stadtteile,false, function (error, paths) {
    paths
        .attr("id", function (d) { return d.properties.Stadtteilnummer })
        .attr('class', 'district')
        .style('fill', 'rgba(255, 255, 255, 0.7)')
        .style('stroke', '#000')
        .style('stroke-width', 2);
});

pathsFromGeoJSON("bundestagswahl_2013_wahlbezirke.geojson", wahlbezirke, true, function (error, paths) {
    paths
        .attr("id", function (d) { return d.properties.Wahlbezirksnummer })
        .attr('class', 'wahlbezirk')
        .on('mousemove', onMouseOverWahlbezirk)
        .on('mouseleave', onMouseLeaveWahlbezirk)
        .style('fill', '#fff')
        .style('stroke', '#000')
        .style('stroke-width', 1)
        .on('click', selectDistrict);
});

$('#szenarien-carousel').bind('slide.bs.carousel', function (e) {
    colorMap();
});

function colorMapNeutrally() {

    // Karte Reference setzten wenn nicht vorhanden
    if(elemSvg === null){
        getSVGMap();
    } // end if

    if (GEOJSON !== null) {
        elemSvg.getElementById(item.properties.Wahlbezirksnummer).style.fill = '#fff';
    } else {
        console.error("GEOJSON null!")
    }
}

function colorMap() {

    // Karte Reference setzten wenn nicht vorhanden
    if(elemSvg === null){
        getSVGMap();
    } // end if

    if (GEOJSON !== null){
        for(var item of GEOJSON.features){
            var win = maxPartie(item)
            var color = winnerColor(win[0])
            if (typeof color !== 'undefined'){
                color = "#" + color;
                elemSvg.getElementById(item.properties.Wahlbezirksnummer).style.fill = color
            }
        }
    } else {
        console.error("GEOJSON null!")
    }
}

function winnerColor(partyName){
    var index = Party.indexOf(partyName)
    if (index >= 0 && PartyColors.length >= index){
        return PartyColors[index]
    } else {
        console.error("Party not found! ", partyName)
    }
}

function maxPartie(data){
    if (data !== 'undefined'){
        var max = 0;
        var partyName = null;
        Object.keys(data.properties).forEach(function(k, v){
            var value = data.properties[k]
           if (max < value && Party.indexOf(k) >= 0) {
               max = value;
               partyName = k;
           }
        })
        return [partyName, max]
    } else {
        console.error("No data")
    }
}

function getSVGMap() {
    return elemSvg = document.getElementById("karte");
}
<commit_msg>Retina basemap for prettier display on mobile/hd screens<commit_after>var KA_LAT  = 49.00921;
var KA_LNG  = 8.45003951;
var elemSvg = null;

var GEOJSON = null;
var Party = ["CDU","SPD","FDP","GRÜNE","DIE LINKE","PIRATEN","NPD","REP","Tierschutzpartei","ÖDP","PBC","Volksabstimmung","MLPD ","BüSo","AfD","BIG","pro Deutschland","FREIE WÄHLER","PARTEI DER VERNUNFT","RENTNER"];

const PartyColors = ["000","f40502","feed01","42a62a","8b1b62","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","ffffff","009de0","ffffff","ffffff","ffffff","ffffff","ffffff"];

var TILES_URL = 'http://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}@2x.png';

var MAP_ATTRIBUTION = 'Map data © ' +
                      'OpenStreetMap contributors | Tiles © ' +
                      'Carto';

var map = new L.Map("map", {center: [KA_LAT, KA_LNG], zoom: 12})
    .addLayer(new L.TileLayer(TILES_URL, {attribution: MAP_ATTRIBUTION}));

var svg = d3.select(map.getPanes().overlayPane).append("svg"),
    g = svg.append("g").attr("class", "leaflet-zoom-hide");

// SVG ID
svg.attr("id", "karte")

var stadtteile = g.append('g')
    .classed('stadtteile', true);

var wahlbezirke = g.append('g')
    .classed('wahlbezirke', true);

/**
 * Adapter to use Leaflet's projection in D3.
 */
function projectPoint(x, y) {
    var point = map.latLngToLayerPoint(new L.LatLng(y, x));
    this.stream.point(point.x, point.y);
}
var transform = d3.geo.transform({ point: projectPoint }),
    path = d3.geo.path().projection(transform);

/**
 * Create SVG paths from a GeoJSON file.
 */
function pathsFromGeoJSON(filename, group, setGeoJson, callback) {

    d3.json(filename, function (error, collection) {
        if (error) return callback(error, null);

        if (GEOJSON === null && setGeoJson){
            GEOJSON = collection
        }
        var feature = group.selectAll("path")
            .data(collection.features)
            .enter().append("path");

        map.on("viewreset", reset);
        reset();

        return callback(null, feature);

        // Reposition the SVG to cover the features.
        function reset() {
            var bounds = path.bounds(collection);
            var topLeft = bounds[0];
            var bottomRight = bounds[1];

            svg.attr("width", bottomRight[0] - topLeft[0])
                .attr("height", bottomRight[1] - topLeft[1])
                .style("left", topLeft[0] + "px")
                .style("top", topLeft[1] + "px");

            group.attr("transform", "translate(" + -topLeft[0] + "," + -topLeft[1] + ")");

            feature.attr("d", path);
        }
    });
}

pathsFromGeoJSON("ka_stadtteile.geojson", stadtteile,false, function (error, paths) {
    paths
        .attr("id", function (d) { return d.properties.Stadtteilnummer })
        .attr('class', 'district')
        .style('fill', 'rgba(255, 255, 255, 0.7)')
        .style('stroke', '#000')
        .style('stroke-width', 2);
});

pathsFromGeoJSON("bundestagswahl_2013_wahlbezirke.geojson", wahlbezirke, true, function (error, paths) {
    paths
        .attr("id", function (d) { return d.properties.Wahlbezirksnummer })
        .attr('class', 'wahlbezirk')
        .on('mousemove', onMouseOverWahlbezirk)
        .on('mouseleave', onMouseLeaveWahlbezirk)
        .style('fill', '#fff')
        .style('stroke', '#000')
        .style('stroke-width', 1)
        .on('click', selectDistrict);
});

$('#szenarien-carousel').bind('slide.bs.carousel', function (e) {
    colorMap();
});

function colorMapNeutrally() {

    // Karte Reference setzten wenn nicht vorhanden
    if(elemSvg === null){
        getSVGMap();
    } // end if

    if (GEOJSON !== null) {
        elemSvg.getElementById(item.properties.Wahlbezirksnummer).style.fill = '#fff';
    } else {
        console.error("GEOJSON null!")
    }
}

function colorMap() {

    // Karte Reference setzten wenn nicht vorhanden
    if(elemSvg === null){
        getSVGMap();
    } // end if

    if (GEOJSON !== null){
        for(var item of GEOJSON.features){
            var win = maxPartie(item)
            var color = winnerColor(win[0])
            if (typeof color !== 'undefined'){
                color = "#" + color;
                elemSvg.getElementById(item.properties.Wahlbezirksnummer).style.fill = color
            }
        }
    } else {
        console.error("GEOJSON null!")
    }
}

function winnerColor(partyName){
    var index = Party.indexOf(partyName)
    if (index >= 0 && PartyColors.length >= index){
        return PartyColors[index]
    } else {
        console.error("Party not found! ", partyName)
    }
}

function maxPartie(data){
    if (data !== 'undefined'){
        var max = 0;
        var partyName = null;
        Object.keys(data.properties).forEach(function(k, v){
            var value = data.properties[k]
           if (max < value && Party.indexOf(k) >= 0) {
               max = value;
               partyName = k;
           }
        })
        return [partyName, max]
    } else {
        console.error("No data")
    }
}

function getSVGMap() {
    return elemSvg = document.getElementById("karte");
}
<|endoftext|>


<commit_before>// angularjs service
// http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/
// http://blog.revolunet.com/blog/2014/02/14/angularjs-services-inheritance/
appModule.factory('UserService', ['$http', '$q', function($http, $q) {

  // apiURL
  var apiURL = "/api/user";

  // the service and its properties
  var UserService = function() {
    this.appUser = null;
    this.screenNameUnique = false;
    this.deleted = false;
  }

  /**
   * getUser function
   *
   * @return promise that appUser will be updated
   */
  UserService.prototype.getUser = function() {

    var self = this;

    var promise = $http.get(apiURL).then(function(success) {
      self.appUser = success.data;
      return success;
    }, function(error) {
      self.appUser = null;
      return $q.reject(error);
    });

    return promise;
  };

  /**
   * isScreenNameUnique function
   *
   * @param screenName
   *          the screen name to check
   * @return promise that screenNameUnique will be updated
   */
  UserService.prototype.isScreenNameUnique = function(screenName) {

    var apiUserScreenNameUniqueURL = apiURL + "/screenNameUnique/" + screenName;

    var self = this;

    var promise = $http.get(apiUserScreenNameUniqueURL).then(function(success) {
      self.screenNameUnique = true;
      return success;
    }, function(error) {
      self.screenNameUnique = false;
      return error;
    });

    return promise;
  };

  /**
   * registerUser function
   *
   * @param screenName
   *          the screen name to register for the user
   * @return promise that screen name will be registered and appUser will be
   *         updated
   */
  UserService.prototype.registerUser = function(screenName) {

    var self = this;

    var postData = {
      screenName: screenName
    };
    var promise = $http.post(apiURL, postData).then(function(success) {
      self.appUser = success.data;
      return success;
    }, function(error) {
      self.appUser = null;
      return $q.reject(error);
    });

    return promise;
  };

  /**
   * updateUser function
   *
   * @param screenName
   *          the screen name to register for the user
   * @param active
   *          the active flag
   * @return promise that the appUser will be updated
   */
  UserService.prototype.updateUser = function(screenName, active) {

    var self = this;

    var postData = {
      screenName: screenName,
      active: active
    };
    var promise = $http.put(apiURL, postData).then(function(success) {
      self.appUser = success.data;
      return success;
    }, function(error) {
      return $q.reject(error);
    });

    return promise;
  };

  /**
   * deleteUser function
   *
   * @param screenName
   *          the screen name to register for the user
   * @param active
   *          the active flag
   * @return promise that screen name will be deleted
   */
  UserService.prototype.deleteUser = function() {

    var self = this;

    var promise = $http.delete(apiURL).then(function(success) {
      self.deleted = true;
      self.appUser = null;
      return success;
    }, function(error) {
      self.deleted = false;
      return $q.reject(error);
    });

    return promise;
  };

  return UserService;
}]);<commit_msg>commenting changes<commit_after>// angularjs service
// http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/
// http://blog.revolunet.com/blog/2014/02/14/angularjs-services-inheritance/
appModule.factory('UserService', ['$http', '$q', function($http, $q) {

  // apiURL
  var apiURL = "/api/user";

  // the service and its properties
  var UserService = function() {
    this.appUser = null;
    this.screenNameUnique = false;
    this.deleted = false;
  }

  /**
   * getUser function
   *
   * @return promise that appUser will be updated
   */
  UserService.prototype.getUser = function() {

    var self = this;

    var promise = $http.get(apiURL).then(function(success) {
      self.appUser = success.data;
      return success;
    }, function(error) {
      self.appUser = null;
      return $q.reject(error);
    });

    return promise;
  };

  /**
   * isScreenNameUnique function
   *
   * @param screenName
   *          the screen name to check
   * @return promise that screenNameUnique will be updated
   */
  UserService.prototype.isScreenNameUnique = function(screenName) {

    var apiUserScreenNameUniqueURL = apiURL + "/screenNameUnique/" + screenName;

    var self = this;

    var promise = $http.get(apiUserScreenNameUniqueURL).then(function(success) {
      self.screenNameUnique = true;
      return success;
    }, function(error) {
      self.screenNameUnique = false;
      return error;
    });

    return promise;
  };

  /**
   * registerUser function
   *
   * @param screenName
   *          the screen name to register for the user
   * @return promise that screen name will be registered and appUser will be
   *         updated
   */
  UserService.prototype.registerUser = function(screenName) {

    var self = this;

    var postData = {
      screenName: screenName
    };
    var promise = $http.post(apiURL, postData).then(function(success) {
      self.appUser = success.data;
      return success;
    }, function(error) {
      self.appUser = null;
      return $q.reject(error);
    });

    return promise;
  };

  /**
   * updateUser function
   *
   * @param screenName
   *          the screen name to register for the user
   * @param active
   *          the active flag
   * @return promise that the appUser will be updated
   */
  UserService.prototype.updateUser = function(screenName, active) {

    var self = this;

    var postData = {
      screenName: screenName,
      active: active
    };
    var promise = $http.put(apiURL, postData).then(function(success) {
      self.appUser = success.data;
      return success;
    }, function(error) {
      return $q.reject(error);
    });

    return promise;
  };

  /**
   * deleteUser function
   *
   * @return promise that user will be deleted
   */
  UserService.prototype.deleteUser = function() {

    var self = this;

    var promise = $http.delete(apiURL).then(function(success) {
      self.deleted = true;
      self.appUser = null;
      return success;
    }, function(error) {
      self.deleted = false;
      return $q.reject(error);
    });

    return promise;
  };

  return UserService;
}]);
<|endoftext|>


<commit_before>describe("DC/OS UI [00j]", function() {
  beforeEach(function() {
    cy.configureCluster({
      mesos: "1-task-healthy"
    }).visitUrl({ url: "/", identify: true, fakeAnalytics: true });
  });

  context("Dashboard [00k]", function() {
    beforeEach(function() {
      cy.get(".sidebar-menu-item")
        .contains("Dashboard")
        .click({ force: true });
    });

    it("can change hash to dashboard page [00l]", function() {
      cy.hash().should("match", /dashboard/);
    });

    it("has eight panels [00m]", function() {
      cy.get("#application")
        .find(".panel")
        .should("to.have.length", 8);
    });
  });

  xcontext("Services [00n]", function() {
    beforeEach(function() {
      cy.get(".sidebar-menu-item")
        .contains("Services")
        .click();
      cy.get("table tbody tr").as("tableRows");
    });

    it("can change hash to services page [00o]", function() {
      cy.hash().should("match", /services/);
    });

    it("displays one row on the table [00p]", function() {
      cy.get("@tableRows").should("to.have.length", 3);
    });

    it("doesn't list marathon in the table [00q]", function() {
      cy.get("table tbody tr").should("not.contain", "marathon");
    });
  });

  context("Nodes [00r]", function() {
    beforeEach(function() {
      cy.get(".sidebar-menu-item")
        .contains("Nodes")
        .click({ force: true });
    });

    it("can change hash to nodes page [00s]", function() {
      cy.hash().should("match", /nodes/);
    });

    it("displays one row on the table [00t]", function() {
      cy.get(
        ".BottomLeftGrid_ScrollWrapper .ReactVirtualized__Grid__innerScrollContainer a"
      )
        .should("to.have.length", 4)
        .contains("dcos-01");
    });
  });
});
<commit_msg>test: fix nodes 'smoke' test<commit_after>describe("DC/OS UI [00j]", function() {
  beforeEach(function() {
    cy.configureCluster({
      mesos: "1-task-healthy",
      nodeHealth: true
    }).visitUrl({ url: "/", identify: true, fakeAnalytics: true });
  });

  context("Dashboard [00k]", function() {
    beforeEach(function() {
      cy.get(".sidebar-menu-item")
        .contains("Dashboard")
        .click({ force: true });
    });

    it("can change hash to dashboard page [00l]", function() {
      cy.hash().should("match", /dashboard/);
    });

    it("has eight panels [00m]", function() {
      cy.get("#application")
        .find(".panel")
        .should("to.have.length", 8);
    });
  });

  xcontext("Services [00n]", function() {
    beforeEach(function() {
      cy.get(".sidebar-menu-item")
        .contains("Services")
        .click();
      cy.get("table tbody tr").as("tableRows");
    });

    it("can change hash to services page [00o]", function() {
      cy.hash().should("match", /services/);
    });

    it("displays one row on the table [00p]", function() {
      cy.get("@tableRows").should("to.have.length", 3);
    });

    it("doesn't list marathon in the table [00q]", function() {
      cy.get("table tbody tr").should("not.contain", "marathon");
    });
  });

  context("Nodes [00r]", function() {
    beforeEach(function() {
      cy.get(".sidebar-menu-item")
        .contains("Nodes")
        .click({ force: true });
    });

    it("can change hash to nodes page [00s]", function() {
      cy.hash().should("match", /nodes/);
    });

    it("displays one row on the table [00t]", function() {
      cy.get(
        ".BottomLeftGrid_ScrollWrapper .ReactVirtualized__Grid__innerScrollContainer a"
      )
        .should("to.have.length", 4)
        .contains("dcos-01");
    });
  });
});
<|endoftext|>


<commit_before>import {expect} from 'chai'
import {spawn} from 'child_process'
import exec from '../../util/exec'
import kill from '../../util/kill'
import stdouted from '../../util/stdouted'
import spawnAsync from '../../util/spawnAsync'
import execAsync from '../../util/execAsync'
import path from 'path'
import fs from 'fs'
import promisify from 'es6-promisify'
import webpackConfig from '../../webpack/webpack.config.dev'

async function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

function sharedTests() {
  it('serves page with correct title', async function () {
    expect(await browser.getTitle()).to.equal('Crater')
  })
  it('serves page with correct header', async function () {
    expect(await browser.getText('h1')).to.equal('Welcome to Crater!')
  })
  it('serves up client css', async function () {
    const color = await browser.getCssProperty('h1', 'color')
    expect(color.parsed.hex).to.equal('#333333')
  })
  it('updates the counter', async function () {
    const getCounter = async () => {
      const text = await browser.getText('.counter')
      const match = /(\d+)/.exec(text)
      return match && parseInt(match[1])
    }

    const initCounter = await getCounter()
    await delay(2000)
    expect(await getCounter()).to.be.above(initCounter)
  })
  it('sends Meteor.settings.public to the client', async function () {
    expect(await browser.getText('.settings-test')).to.equal('success')
  })
}

describe('prod mode', function () {
  let server

  before(async function () {
    this.timeout(240000)
    await spawnAsync('npm', ['run', 'build'])
    await spawnAsync('npm', ['install', ...(process.env.CI ? ['--progress=false'] : [])], {
      cwd: path.join(__dirname, '../../build/meteor/bundle/programs/server'),
    })
    server = exec('npm run prod')
    await stdouted(server, /App is listening on http/i)
    await browser.reload()
    await browser.url(process.env.ROOT_URL)
  })

  after(async function () {
    this.timeout(30000)
    if (server) await kill(server)
  })

  sharedTests()
})

describe('docker build', function () {
  let server
  let env

  before(async function () {
    this.timeout(480000)
    let host
    env = {
      ...process.env,
      TAG: (await execAsync('git rev-parse HEAD')).stdout.trim(),
    }
    await spawnAsync('which', ['docker-machine'], {silent: true})
      .then(() => host = `192.168.99.100:${process.env.PORT}`)
      .catch(async () => host = (await spawnAsync('docker-compose', ['port', 'crater', '80'], {env})).stdout.trim())
    await spawnAsync('npm', ['run', 'build'])
    await spawnAsync('npm', ['run', 'build:docker'])
    server = exec('npm run docker', {
      env: {
        ...process.env,
        METEOR_SETTINGS: JSON.stringify({
          public: {
            test: 'success'
          }
        })
      }
    })
    await stdouted(server, /App is listening on http/i)
    await browser.reload()
    await browser.url(`http://${host}`)
  })

  after(async function () {
    this.timeout(20000)
    await spawnAsync('docker-compose', ['down'], {env})
  })

  sharedTests()
})

describe('dev mode', function () {
  let server

  const appFile = path.resolve(__dirname, '../../src/universal/components/App.js')
  let appCode

  before(async function () {
    this.timeout(60000)
    appCode = await promisify(fs.readFile)(appFile, 'utf8')
    server = exec('npm start')
    await stdouted(server, /webpack built [a-z0-9]+ in \d+ms/i)
    await browser.url(`http://localhost:${webpackConfig.devServer.port}`)
  })

  after(async function () {
    this.timeout(30000)
    // restore code in App.js, which (may) have been changed by hot reloading test
    if (appCode) await promisify(fs.writeFile)(appFile, appCode, 'utf8')
    if (server) await kill(server)
  })

  sharedTests()

  it('supports hot reloading', async function () {
    this.timeout(40000)
    const newHeader = 'Welcome to Crater! with hot reloading'
    const modified = appCode.replace(/Welcome to Crater!/, newHeader)
    await promisify(fs.writeFile)(appFile, modified, 'utf8')
    await browser.waitUntil(
      () => browser.getText('h1') === newHeader,
      20000,
      'expected header text to hot update within 10s'
    )
  })
})<commit_msg>move docker-compose port call to after services are running<commit_after>import {expect} from 'chai'
import {spawn} from 'child_process'
import exec from '../../util/exec'
import kill from '../../util/kill'
import stdouted from '../../util/stdouted'
import spawnAsync from '../../util/spawnAsync'
import execAsync from '../../util/execAsync'
import path from 'path'
import fs from 'fs'
import promisify from 'es6-promisify'
import webpackConfig from '../../webpack/webpack.config.dev'

async function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

function sharedTests() {
  it('serves page with correct title', async function () {
    expect(await browser.getTitle()).to.equal('Crater')
  })
  it('serves page with correct header', async function () {
    expect(await browser.getText('h1')).to.equal('Welcome to Crater!')
  })
  it('serves up client css', async function () {
    const color = await browser.getCssProperty('h1', 'color')
    expect(color.parsed.hex).to.equal('#333333')
  })
  it('updates the counter', async function () {
    const getCounter = async () => {
      const text = await browser.getText('.counter')
      const match = /(\d+)/.exec(text)
      return match && parseInt(match[1])
    }

    const initCounter = await getCounter()
    await delay(2000)
    expect(await getCounter()).to.be.above(initCounter)
  })
  it('sends Meteor.settings.public to the client', async function () {
    expect(await browser.getText('.settings-test')).to.equal('success')
  })
}

describe('prod mode', function () {
  let server

  before(async function () {
    this.timeout(240000)
    await spawnAsync('npm', ['run', 'build'])
    await spawnAsync('npm', ['install', ...(process.env.CI ? ['--progress=false'] : [])], {
      cwd: path.join(__dirname, '../../build/meteor/bundle/programs/server'),
    })
    server = exec('npm run prod')
    await stdouted(server, /App is listening on http/i)
    await browser.reload()
    await browser.url(process.env.ROOT_URL)
  })

  after(async function () {
    this.timeout(30000)
    if (server) await kill(server)
  })

  sharedTests()
})

describe('docker build', function () {
  let server
  let env

  before(async function () {
    this.timeout(480000)
    env = {
      ...process.env,
      TAG: (await execAsync('git rev-parse HEAD')).stdout.trim(),
    }
    await spawnAsync('npm', ['run', 'build'])
    await spawnAsync('npm', ['run', 'build:docker'])
    server = exec('npm run docker', {
      env: {
        ...process.env,
        METEOR_SETTINGS: JSON.stringify({
          public: {
            test: 'success'
          }
        })
      }
    })
    await stdouted(server, /App is listening on http/i)
    let host
    await spawnAsync('which', ['docker-machine'], {silent: true})
      .then(() => host = `192.168.99.100:${process.env.PORT}`)
      .catch(async () => host = (await spawnAsync('docker-compose', ['port', 'crater', '80'], {env})).stdout.trim())
    await browser.reload()
    await browser.url(`http://${host}`)
  })

  after(async function () {
    this.timeout(20000)
    await spawnAsync('docker-compose', ['down'], {env})
  })

  sharedTests()
})

describe('dev mode', function () {
  let server

  const appFile = path.resolve(__dirname, '../../src/universal/components/App.js')
  let appCode

  before(async function () {
    this.timeout(60000)
    appCode = await promisify(fs.readFile)(appFile, 'utf8')
    server = exec('npm start')
    await stdouted(server, /webpack built [a-z0-9]+ in \d+ms/i)
    await browser.url(`http://localhost:${webpackConfig.devServer.port}`)
  })

  after(async function () {
    this.timeout(30000)
    // restore code in App.js, which (may) have been changed by hot reloading test
    if (appCode) await promisify(fs.writeFile)(appFile, appCode, 'utf8')
    if (server) await kill(server)
  })

  sharedTests()

  it('supports hot reloading', async function () {
    this.timeout(40000)
    const newHeader = 'Welcome to Crater! with hot reloading'
    const modified = appCode.replace(/Welcome to Crater!/, newHeader)
    await promisify(fs.writeFile)(appFile, modified, 'utf8')
    await browser.waitUntil(
      () => browser.getText('h1') === newHeader,
      20000,
      'expected header text to hot update within 10s'
    )
  })
})<|endoftext|>


<commit_before>var request = require('request'),
    JsonDB = require('node-json-db'),
    config = require('../config.json');

var db = new JsonDB('database', true, true);

var WarcraftLogs = function () {};

var raids = {
    1000: 'Molten Core',
    1001: 'Onyxia\'s Lair',
    1002: 'Blackwing Lair',
    1003: 'Zul\'Gurub'
}

WarcraftLogs.prototype.Message = function(message)
{
    const convertMilliseconds = (miliseconds) =>
    {
        let days, hours, minutes, seconds, total_hours, total_minutes, total_seconds;

        total_seconds = parseInt(Math.floor(miliseconds / 1000));
        total_minutes = parseInt(Math.floor(total_seconds / 60));
        total_hours = parseInt(Math.floor(total_minutes / 60));
        days = parseInt(Math.floor(total_hours / 24));

        seconds = parseInt(total_seconds % 60);
        minutes = parseInt(total_minutes % 60);
        hours = parseInt(total_hours % 24);

        var ret = '';

        if (days) ret += (days > 9 ? days : '0'+days)+':';
        ret += (hours > 9 ? hours : '0'+hours)+':';
        ret += (minutes > 9 ? minutes : '0'+minutes)+':';
        ret += (seconds > 9 ? seconds : '0'+seconds);

        return ret;
    };

    const getLatestLog = (cb, guildId) =>
    {
        var zone = guildId.split('|')[1];
        var guild = guildId.split('|')[0];

        var headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'User-Agent': 'https://github.com/HxxxxxS/DiscordBot'
        }

        var options = {
            url: 'https://' + (zone == 'classic' ? 'classic.' : '') + 'warcraftlogs.com/v1/reports/guild/' + guild + '?api_key=' + config.warcraft_logs.apikey,
            port: 443,
            method: 'GET',
            headers: headers
        }

        request(options, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var data = JSON.parse(body);
                var latest = data[0];
                getLog(cb, latest.id, zone);
            }else{
                console.log((error?error:response));
                message.channel.send(`WarcraftLogs returned an error: ${response.statusCode}`);
            }
        });
    }

    const getLog = (cb, code, zone) =>
    {
        if(code.indexOf("http") > -1){
            if(code.indexOf("#") > -1) code = code.split("#")[0];
            code = code.split("/")[code.split("/").length - 1];
        }
        var headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'User-Agent': 'https://github.com/HxxxxxS/DiscordBot'
        }

        var options = {
            url: 'https://' + (zone == 'classic' ? 'classic.' : '') + 'warcraftlogs.com/v1/report/fights/' + code + '?api_key=' + config.warcraft_logs.apikey,
            port: 443,
            method: 'GET',
            headers: headers
        }

        request(options, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var data = JSON.parse(body);
                sendTheThing(cb, code, zone, data);
            }else{
                console.log((error?error:response));
                message.channel.send(`WarcraftLogs returned an error: ${response.statusCode}`);
            }
        });
    }

    const sendTheThing = (cb, code, zone, data) =>
    {
        var link = 'https://' + (zone == 'classic' ? 'classic.' : '') + 'warcraftlogs.com/reports/' + code;

        var fields = [{
            name: '\u200b',
            value:  'Title: **__'+data.title+"__**\n" +
                    //'Zone: **' + raids[data.zone] + "**\n" +
                    'Date: **' + new Date(data.start).toDateString() + "**\n" +
                    'Duration: **' + convertMilliseconds(data.end - data.start) + "**\n"
        },{name:'\u200b',value:'Bosses:'}];

        var bosses = [];

        var timer = 0;

        for (var i = 0; i<data.fights.length; i++)
        {
            var fight = data.fights[i];
            if (fight.end_time < timer) break;
            if (fight.boss)
            {
                if (bosses.indexOf(fight.name)>-1) continue;
                bosses.push(fight.name);
                var enemy;
                for (var j = 0; j<data.enemies.length; j++)
                {
                    enemy = data.enemies[j];
                    if (fight.name == enemy.name) break;
                    if (data.enemies[j].type != "Boss") enemy = undefined;
                }
                if (!enemy) continue;
                field = {name: enemy.name, value: '', inline: true}

                for (var j = 0; j<enemy.fights.length; j++)
                {
                    if (field.value.length > 999) break;
                    var fight = data.fights[enemy.fights[j].id-1];
                    var time = convertMilliseconds(fight.kill ? fight.start_time : fight.end_time);
                    field.value += (fight.kill ? "✅" : "❌") + " - ";
                    field.value += "["+time;
                    field.value += "]("+link+"#fight="+fight.id+" 'Click to go to ";
                    field.value += enemy.name+" "+(fight.kill?'kill':'wipe')+" at "+time+"') "+"\n";
                    if (fight.kill) break;
                }

                fields.push(field);
            }
            if (fight.end_time > timer) timer = fight.end_time;
        }
        if (bosses % 3 != 0) fields.push({name:"\u200b ",value:"\u200b ",inline:true})

        fields.push({name:'See the full log:',value:'['+link+']('+link+')'});
        cb.edit({embed: {thumbnail:{ url: 'https://dmszsuqyoe6y6.cloudfront.net/img/warcraft/zones/zone-'+data.zone+'-small.jpg' },fields}});
    }

    switch (message.channel.type) {
        case 'text':
            var id = message.guild.id;
            break;
        case 'dm':
        case 'group':
            var id = message.channel.id;
            break;
    }

    if (!id) return false;

    var msgArr = message.content.split(" ");

    var action = msgArr[1];
    var aIndex = message.content.indexOf(action);

    switch (action) {
        case 'set':
            if (msgArr.length < 5) {
                message.reply(`You sent too few parameters. I must know the gamemode (retail/classic), the region (eu,us,asia,oce), the realm name and the guild name.`)
                return false;
            }
            var zone = msgArr[4] + '/' + msgArr[3] + "|" + msgArr[2];
            var guildName = msgArr[5];
            for (var i = 6; i <= msgArr.length -1; i++) {
                guildName += " " + msgArr[i];
            }
            guildId = guildName + '/' + zone;
            try {
                getLatestLog(guildId);
                db.push('/warcraftlogs/guilds/' + id, guildId);
            } catch (error) {
                message.reply(`Something went wrong. See the **${config.commandPrefix}help** command on how to do it right.`)
            }
            break;
        default:
            try {
                var guildId = db.getData('/warcraftlogs/guilds/' + id);
                var zone = guildId.split('|')[1];
                var guild = guildId.split('|')[0];
                if (msgArr[1])
                {
                    message.channel.send('Getting specified log...')
                    .then((sent) => {getLog(sent, msgArr[1], zone)});
                } else {
                    message.channel.send('Getting latest log...')
                    .then((sent) => {getLatestLog(sent, guildId)});
                }
                message.delete();
            } catch (error) {
                message.reply(`There is no WarcraftLogs Guild related to this discord server. See the **${config.commandPrefix}help** command on how to set it.`);
            }
            break;
    }
}

module.exports = WarcraftLogs;
<commit_msg>Fixed bwl being cut in half<commit_after>var request = require('request'),
    JsonDB = require('node-json-db'),
    config = require('../config.json');

var db = new JsonDB('database', true, true);

var WarcraftLogs = function () {};

var raids = {
    1000: 'Molten Core',
    1001: 'Onyxia\'s Lair',
    1002: 'Blackwing Lair',
    1003: 'Zul\'Gurub'
}

WarcraftLogs.prototype.Message = function(message)
{
    const convertMilliseconds = (miliseconds) =>
    {
        let days, hours, minutes, seconds, total_hours, total_minutes, total_seconds;

        total_seconds = parseInt(Math.floor(miliseconds / 1000));
        total_minutes = parseInt(Math.floor(total_seconds / 60));
        total_hours = parseInt(Math.floor(total_minutes / 60));
        days = parseInt(Math.floor(total_hours / 24));

        seconds = parseInt(total_seconds % 60);
        minutes = parseInt(total_minutes % 60);
        hours = parseInt(total_hours % 24);

        var ret = '';

        if (days) ret += (days > 9 ? days : '0'+days)+':';
        ret += (hours > 9 ? hours : '0'+hours)+':';
        ret += (minutes > 9 ? minutes : '0'+minutes)+':';
        ret += (seconds > 9 ? seconds : '0'+seconds);

        return ret;
    };

    const getLatestLog = (cb, guildId) =>
    {
        var zone = guildId.split('|')[1];
        var guild = guildId.split('|')[0];

        var headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'User-Agent': 'https://github.com/HxxxxxS/DiscordBot'
        }

        var options = {
            url: 'https://' + (zone == 'classic' ? 'classic.' : '') + 'warcraftlogs.com/v1/reports/guild/' + guild + '?api_key=' + config.warcraft_logs.apikey,
            port: 443,
            method: 'GET',
            headers: headers
        }

        request(options, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var data = JSON.parse(body);
                var latest = data[0];
                getLog(cb, latest.id, zone);
            }else{
                console.log((error?error:response));
                message.channel.send(`WarcraftLogs returned an error: ${response.statusCode}`);
            }
        });
    }

    const getLog = (cb, code, zone) =>
    {
        if(code.indexOf("http") > -1){
            if(code.indexOf("#") > -1) code = code.split("#")[0];
            code = code.split("/")[code.split("/").length - 1];
        }
        var headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'User-Agent': 'https://github.com/HxxxxxS/DiscordBot'
        }

        var options = {
            url: 'https://' + (zone == 'classic' ? 'classic.' : '') + 'warcraftlogs.com/v1/report/fights/' + code + '?api_key=' + config.warcraft_logs.apikey,
            port: 443,
            method: 'GET',
            headers: headers
        }

        request(options, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var data = JSON.parse(body);
                sendTheThing(cb, code, zone, data);
            }else{
                console.log((error?error:response));
                message.channel.send(`WarcraftLogs returned an error: ${response.statusCode}`);
            }
        });
    }

    const sendTheThing = (cb, code, zone, data) =>
    {
        var link = 'https://' + (zone == 'classic' ? 'classic.' : '') + 'warcraftlogs.com/reports/' + code;

        var fields = [{
            name: '\u200b',
            value:  'Title: **__'+data.title+"__**\n" +
                    //'Zone: **' + raids[data.zone] + "**\n" +
                    'Date: **' + new Date(data.start).toDateString() + "**\n" +
                    'Duration: **' + convertMilliseconds(data.end - data.start) + "**\n"
        },{name:'\u200b',value:'Bosses:'}];

        var bosses = [];

        var timer = 0;

        for (var i = 0; i<data.fights.length; i++)
        {
            var fight = data.fights[i];
            //if (fight.end_time < timer) break;
            if (fight.boss)
            {
                if (bosses.indexOf(fight.name)>-1) continue;
                bosses.push(fight.name);
                var enemy;
                for (var j = 0; j<data.enemies.length; j++)
                {
                    enemy = data.enemies[j];
                    if (fight.name == enemy.name) break;
                    if (data.enemies[j].type != "Boss") enemy = undefined;
                }
                if (!enemy) continue;
                field = {name: enemy.name, value: '', inline: true}

                for (var j = 0; j<enemy.fights.length; j++)
                {
                    if (field.value.length > 999) break;
                    var fight = data.fights[enemy.fights[j].id-1];
                    var time = convertMilliseconds(fight.kill ? fight.start_time : fight.end_time);
                    field.value += (fight.kill ? "✅" : "❌") + " - ";
                    field.value += "["+time;
                    field.value += "]("+link+"#fight="+fight.id+" 'Click to go to ";
                    field.value += enemy.name+" "+(fight.kill?'kill':'wipe')+" at "+time+"') "+"\n";
                    if (fight.kill) break;
                }

                fields.push(field);
            }
            if (fight.end_time > timer) timer = fight.end_time;
        }
        if (bosses % 3 != 0) fields.push({name:"\u200b ",value:"\u200b ",inline:true})

        fields.push({name:'See the full log:',value:'['+link+']('+link+')'});
        cb.edit({embed: {thumbnail:{ url: 'https://dmszsuqyoe6y6.cloudfront.net/img/warcraft/zones/zone-'+data.zone+'-small.jpg' },fields}});
    }

    switch (message.channel.type) {
        case 'text':
            var id = message.guild.id;
            break;
        case 'dm':
        case 'group':
            var id = message.channel.id;
            break;
    }

    if (!id) return false;

    var msgArr = message.content.split(" ");

    var action = msgArr[1];
    var aIndex = message.content.indexOf(action);

    switch (action) {
        case 'set':
            if (msgArr.length < 5) {
                message.reply(`You sent too few parameters. I must know the gamemode (retail/classic), the region (eu,us,asia,oce), the realm name and the guild name.`)
                return false;
            }
            var zone = msgArr[4] + '/' + msgArr[3] + "|" + msgArr[2];
            var guildName = msgArr[5];
            for (var i = 6; i <= msgArr.length -1; i++) {
                guildName += " " + msgArr[i];
            }
            guildId = guildName + '/' + zone;
            try {
                getLatestLog(guildId);
                db.push('/warcraftlogs/guilds/' + id, guildId);
            } catch (error) {
                message.reply(`Something went wrong. See the **${config.commandPrefix}help** command on how to do it right.`)
            }
            break;
        default:
            try {
                var guildId = db.getData('/warcraftlogs/guilds/' + id);
                var zone = guildId.split('|')[1];
                var guild = guildId.split('|')[0];
                if (msgArr[1])
                {
                    message.channel.send('Getting specified log...')
                    .then((sent) => {getLog(sent, msgArr[1], zone)});
                } else {
                    message.channel.send('Getting latest log...')
                    .then((sent) => {getLatestLog(sent, guildId)});
                }
                message.delete();
            } catch (error) {
                message.reply(`There is no WarcraftLogs Guild related to this discord server. See the **${config.commandPrefix}help** command on how to set it.`);
            }
            break;
    }
}

module.exports = WarcraftLogs;
<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular.module('drsApp', [
    // Angular modules
    'ui.router',

    // Third-party modules
    'firebase',

    // Custom modules
    'drsApp.core',
    'drsApp.home',
    'drsApp.layout',
    'drsApp.pastPres',
    'drsApp.auth',
    'drsApp.reviewerApplication'
  ])
  .config(configFunction)
  // .run(runFunction);

  configFunction.$inject = ['$urlRouterProvider'];

  function configFunction($urlRouterProvider) {
    $urlRouterProvider.otherwise('/');
  }

  runFunction.$inject = ['$rootScope', '$state'];

  function runFunction($rootScope, $state) {
    $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
      if (error === "AUTH_REQUIRED") {
        $state.go('login');
      }
    });
  }
})();
<commit_msg>Add expertise-selector module to main module<commit_after>(function() {
  'use strict';

  angular.module('drsApp', [
    // Angular modules
    'ui.router',

    // Third-party modules
    'firebase',

    // Custom modules
    'drsApp.core',
    'drsApp.home',
    'drsApp.layout',
    'drsApp.pastPres',
    'drsApp.auth',
    'drsApp.reviewerApplication',
    'expertise-choice'
  ])
  .config(configFunction)
  // .run(runFunction);

  configFunction.$inject = ['$urlRouterProvider'];

  function configFunction($urlRouterProvider) {
    $urlRouterProvider.otherwise('/');
  }

  runFunction.$inject = ['$rootScope', '$state'];

  function runFunction($rootScope, $state) {
    $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
      if (error === "AUTH_REQUIRED") {
        $state.go('login');
      }
    });
  }
})();
<|endoftext|>


<commit_before>var map = L.map('map').setView([20, 0], 2);
mapLink =
    'OpenStreetMap';
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors, CC-BY-SA, bike sharing system data from CityBikes',
	minZoom:1,
    maxZoom: 19
}).addTo(map);

// Initialize the SVG layer
map._initPathRoot();

	// svg selection
var svg = d3.select("#map").select("svg"),
	stationAreaGroup = svg.append("g"),
	stationPointGroup = svg.append("g"),
	stationAreas = [],
	stationPoints = [],
	currentStations = [],
	citySelector = d3.select("#cityselector").on("change", onCityChange),
	cityOptions = [];

var cityParam = getURLParameter("city");

map.on("viewreset", onMapUpdate);

d3.json("data?q=networks", function(networks) {
	console.log("networks loaded");

	cityOptions = citySelector.selectAll("option")
	  .data(networks)
	  .enter()
	  .append("option")
	  .attr("value", function(d) {
		  	return "option-" + d.id;
		  })
	  .text(function(d) {
		  	return d.city;
		  });
});

function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}

function onCityChange() {
	var selectedIndex = citySelector.property('selectedIndex');
	if(selectedIndex === "default") {
		return;
	}
    var city = cityOptions[0][selectedIndex].__data__;

	d3.json("data?q=" + city.tag, function(stations) {
		console.log(city.name + " station data loaded");

		stations.forEach(function(d) {
			d.LatLng = new L.LatLng(d.lat / 1000000, d.lng / 1000000);
		});

		// clear the svg
		stationPointGroup.selectAll("circle").remove();
		stationAreaGroup.selectAll("polygon").remove();

		// create station circles
		stationPoints = stationPointGroup.selectAll("circle")
			.data(stations)
			.enter().append("circle")
			.style("stroke", "black")
			.style("opacity", .6)
			.style("fill", function(d) {
				if(d.available_bikes) return "green";
				else return "red";
				})
			.attr("r", 2);

		var colorScale = d3.scale.linear()
								.range(["red", "yellow", "green"])
								.domain([0, 0.5, 1]);

		// create station polygons
		stationAreas = stationAreaGroup.selectAll("path")
			.data(stations)
			.enter().append("svg:polygon")
			.attr("id", function(d) {
					return "station-" + d.idx;
				})
			.attr("stroke-width", "0px")
			.attr("fill-opacity", "0.5")
			.attr("fill", function(d) {
					var slots = d.bikes + d.free;
					var bikeAvailability = d.bikes / slots;
					var slotAvailability = d.free / slots;
					return colorScale(bikeAvailability);
				});

		// apply changes on the map
		currentStations = stations;
	    console.log("zooming on " + city.City);
	    var cityLatLng = new L.LatLng(city.lat / 1000000, city.lng / 1000000);
	    map.setView(cityLatLng, 12); // call onMapUpdate()
	});

}

function onMapUpdate() {
	console.log("onMapUpdate");

	// Data reprojection
	currentStations.forEach(function(d, i) {
			var stationPoint = map.latLngToLayerPoint(d.LatLng);
			d.x = stationPoint.x;
			d.y = stationPoint.y;
		});

	//var pixelBounds = map.getPixelBounds();

	// Voronoi computation, clipped by the new map frame
	var voronoi = d3.geom.voronoi()
	.x(function(d) {
			return d.x;
		})
	.y(function(d) {
			return d.y;
		});
	//.clipExtent([[pixelBounds.min.x, pixelBounds.min.y], [pixelBounds.max.x, pixelBounds.max.y]]);

	voronoi(currentStations).forEach(function(d) {
			d.point.cell = d;
		});

	stationPoints.attr("transform", function(d) {
		return "translate("+ d.x +","+ d.y +")";
		}
	);

	stationAreas.attr("points", function(d) {
		var polygon = "";
		var first = true;
		for(var i = 0; i < d.cell.length; i++) {
			if(isNaN(d.cell[i][0]) || isNaN(d.cell[i][1])) return "";

			if(first) {
				first = false;
			} else {
				polygon += " ";
			}

			polygon += d.cell[i][0] + "," + d.cell[i][1];
		}
		return polygon;
	});

}

<commit_msg>sorting city list<commit_after>var map = L.map('map').setView([20, 0], 2);
mapLink =
    'OpenStreetMap';
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors, CC-BY-SA, bike sharing system data from CityBikes',
	minZoom:1,
    maxZoom: 19
}).addTo(map);

// Initialize the SVG layer
map._initPathRoot();

	// svg selection
var svg = d3.select("#map").select("svg"),
	stationAreaGroup = svg.append("g"),
	stationPointGroup = svg.append("g"),
	stationAreas = [],
	stationPoints = [],
	currentStations = [],
	citySelector = d3.select("#cityselector").on("change", onCityChange),
	cityOptions = [];

var cityParam = getURLParameter("city");

map.on("viewreset", onMapUpdate);

d3.json("data?q=networks", function(networks) {
	console.log("networks loaded");

	networks.sort(function(a,b) {
			if(a.city.toUpperCase() > b.city.toUpperCase()) return 1;
			else if(a.city.toUpperCase() < b.city.toUpperCase()) return -1;
			else return 0;
		});

	cityOptions = citySelector.selectAll("option")
	  .data(networks)
	  .enter()
	  .append("option")
	  .attr("value", function(d) {
		  	return "option-" + d.id;
		  })
	  .text(function(d) {
		  	return d.city;
		  });
});

function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}

function onCityChange() {
	var selectedIndex = citySelector.property('selectedIndex');
	if(selectedIndex === "default") {
		return;
	}
    var city = cityOptions[0][selectedIndex].__data__;

	d3.json("data?q=" + city.tag, function(stations) {
		console.log(city.name + " station data loaded");

		stations.forEach(function(d) {
			d.LatLng = new L.LatLng(d.lat / 1000000, d.lng / 1000000);
		});

		// clear the svg
		stationPointGroup.selectAll("circle").remove();
		stationAreaGroup.selectAll("polygon").remove();

		// create station circles
		stationPoints = stationPointGroup.selectAll("circle")
			.data(stations)
			.enter().append("circle")
			.style("stroke", "black")
			.style("opacity", .6)
			.style("fill", function(d) {
				if(d.available_bikes) return "green";
				else return "red";
				})
			.attr("r", 2);

		var colorScale = d3.scale.linear()
								.range(["red", "yellow", "green"])
								.domain([0, 0.5, 1]);

		// create station polygons
		stationAreas = stationAreaGroup.selectAll("path")
			.data(stations)
			.enter().append("svg:polygon")
			.attr("id", function(d) {
					return "station-" + d.idx;
				})
			.attr("stroke-width", "0px")
			.attr("fill-opacity", "0.5")
			.attr("fill", function(d) {
					var slots = d.bikes + d.free;
					var bikeAvailability = d.bikes / slots;
					var slotAvailability = d.free / slots;
					return colorScale(bikeAvailability);
				});

		// apply changes on the map
		currentStations = stations;
	    console.log("zooming on " + city.City);
	    var cityLatLng = new L.LatLng(city.lat / 1000000, city.lng / 1000000);
	    map.setView(cityLatLng, 12); // call onMapUpdate()
	});

}

function onMapUpdate() {
	console.log("onMapUpdate");

	// Data reprojection
	currentStations.forEach(function(d, i) {
			var stationPoint = map.latLngToLayerPoint(d.LatLng);
			d.x = stationPoint.x;
			d.y = stationPoint.y;
		});

	//var pixelBounds = map.getPixelBounds();

	// Voronoi computation, clipped by the new map frame
	var voronoi = d3.geom.voronoi()
	.x(function(d) {
			return d.x;
		})
	.y(function(d) {
			return d.y;
		});
	//.clipExtent([[pixelBounds.min.x, pixelBounds.min.y], [pixelBounds.max.x, pixelBounds.max.y]]);

	voronoi(currentStations).forEach(function(d) {
			d.point.cell = d;
		});

	stationPoints.attr("transform", function(d) {
		return "translate("+ d.x +","+ d.y +")";
		}
	);

	stationAreas.attr("points", function(d) {
		var polygon = "";
		var first = true;
		for(var i = 0; i < d.cell.length; i++) {
			if(isNaN(d.cell[i][0]) || isNaN(d.cell[i][1])) return "";

			if(first) {
				first = false;
			} else {
				polygon += " ";
			}

			polygon += d.cell[i][0] + "," + d.cell[i][1];
		}
		return polygon;
	});

}

<|endoftext|>


<commit_before>"use strict";

const Call = require("./Call");

/**
* Represents a message
* @prop {String} id The ID of the message
* @prop {Channel} channel The channel the message is in
* @prop {Number} timestamp Timestamp of message creation
* @prop {User} author The message author
* @prop {Member?} member The message author with server-specific data
* @prop {User[]} mentions Array of mentioned users
* @prop {String} content Message content
* @prop {String?} cleanContent Message content with mentions replaced by names, and @everyone/@here escaped
* @prop {String[]} roleMentions Array of mentioned roles' ids
* @prop {String[]?} channelMentions Array of mentions channels' ids, requires client option cleanContent
* @prop {Number?} editedTimestamp Timestamp of latest message edit
* @prop {Boolean} tts Whether to play the message using TTS or not
* @prop {Boolean} mentionEveryone Whether the message mentions everyone/here or not
* @prop {Object[]} attachments Array of attachments
* @prop {Object[]} embeds Array of embeds
*/
class Message {
    constructor(data, client) {
        this.id = data.id;
        this.type = data.type;
        this.timestamp = Date.parse(data.timestamp);
        this.channel = client.getChannel(data.channel_id) || {
            id: data.channel_id
        };
        if(data.author) {
            this.author = client.users.add(data.author);
            if(this.channel.guild) {
                this.member = this.channel.guild.members.get(this.author.id);
            }
        }
        if(this.type === 0 || this.type === undefined);
        else if(this.type === 1) {
            data.content = `${this.author.mention} added <@${data.mentions[0].id}>.`;
        } else if(this.type === 2) {
            if(this.author.id === data.mentions[0].id) {
                data.content = `@${this.author.username} left the group.`;
            } else {
                data.content = `${this.author.mention} removed @${data.mentions[0].username}.`;
            }
        } else if(this.type === 3) { // (╯°□°）╯︵ ┻━┻
            if(data.call.ended_timestamp) {
                if((!this.channel.lastCall || this.channel.lastCall.endedTimestamp < Date.parse(data.call.ended_timestamp))) {
                    data.call.id = this.id;
                    this.channel.lastCall = new Call(data.call, this.channel);
                }
                if(~data.call.participants.indexOf(client.user.id)) {
                    data.content = `You missed a call from ${this.author.mention}.`;
                } else {
                    data.content = `${this.author.mention} started a call.`;
                }
            } else {
                if(!this.channel.call) {
                    data.call.id = this.id;
                    this.channel.call = new Call(data.call, this.channel);
                }
                data.content = `${this.author.mention} started a call. — Join the call.`;
            }
        } else if(this.type === 4) {
            data.content = `${this.author.mention} changed the channel name: ${data.content}`;
        } else if(this.type === 5) {
            data.content = `${this.author.mention} changed the channel icon.`;
        } else {
            throw new Error("Unhandled MESSAGE_CREATE type: " + JSON.stringify(data, null, 2));
        }
        this.update(data, client);
    }

    update(data, client) {
        if(this.type === 3) { // (╯°□°）╯︵ ┻━┻
            (this.channel.call || this.channel.lastCall).update(data.call);
        }
        if(data.content !== undefined) {
            this.content = data.content || "";
            this.mentionEveryone = !!data.mention_everyone;
            this.cleanContent = client.options.cleanContent ? this.content : null;
            this.mentions = data.mentions.map((mention) => {
                if(client.options.cleanContent) {
                    if(this.channel.guild) {
                        var member = this.channel.guild.members.get(mention.id);
                        if(member) {
                            this.cleanContent = this.cleanContent.replace(new RegExp(`<@\!${mention.id}>`, "g"), "@" + member.nick || mention.username);
                        }
                    }
                    this.cleanContent = this.cleanContent.replace(new RegExp(`<@\!?${mention.id}>`, "g"), "@" + mention.username);
                }
                return client.users.add(mention);
            });

            this.roleMentions = data.mention_roles || this.roleMentions;
            if(client.options.cleanContent && this.channel.guild) {
                for(var roleID of this.roleMentions) {
                    this.cleanContent = this.cleanContent.replace(new RegExp(`<@&${roleID}>`, "g"), "@" + this.channel.guild.roles.get(roleID).name);
                }
            }

            if(client.options.cleanContent) {
                this.channelMentions = (this.content.match(/<#[0-9]+>/g) || []).map((mention) => {
                    var id = mention.substring(2, mention.length - 1);
                    var channel = client.getChannel(id);
                    if(channel && channel.name) {
                        this.cleanContent = this.cleanContent.replace(mention, "#" + channel.name);
                    }
                    return id;
                });

                this.cleanContent = this.cleanContent.replace(/@everyone/g, "@\u200beveryone").replace(/@here/g, "@\u200bhere");
            }
        }

        this.pinned = data.pinned !== undefined ? !!data.pinned : this.pinned;
        this.editedTimestamp = data.edited_timestamp !== undefined ? data.edited_timestamp : this.editedTimestamp;
        this.tts = data.tts !== undefined ? data.tts : this.tts;
        this.attachments = data.attachments !== undefined ? data.attachments : this.attachments; // TODO parse attachments
        this.embeds = data.embeds !== undefined ? data.embeds : this.embeds; // TODO parse embeds
    }
}

module.exports = Message;
<commit_msg>Made editedTimestamp also return a number probably (#46)<commit_after>"use strict";

const Call = require("./Call");

/**
* Represents a message
* @prop {String} id The ID of the message
* @prop {Channel} channel The channel the message is in
* @prop {Number} timestamp Timestamp of message creation
* @prop {User} author The message author
* @prop {Member?} member The message author with server-specific data
* @prop {User[]} mentions Array of mentioned users
* @prop {String} content Message content
* @prop {String?} cleanContent Message content with mentions replaced by names, and @everyone/@here escaped
* @prop {String[]} roleMentions Array of mentioned roles' ids
* @prop {String[]?} channelMentions Array of mentions channels' ids, requires client option cleanContent
* @prop {Number?} editedTimestamp Timestamp of latest message edit
* @prop {Boolean} tts Whether to play the message using TTS or not
* @prop {Boolean} mentionEveryone Whether the message mentions everyone/here or not
* @prop {Object[]} attachments Array of attachments
* @prop {Object[]} embeds Array of embeds
*/
class Message {
    constructor(data, client) {
        this.id = data.id;
        this.type = data.type;
        this.timestamp = Date.parse(data.timestamp);
        this.channel = client.getChannel(data.channel_id) || {
            id: data.channel_id
        };
        if(data.author) {
            this.author = client.users.add(data.author);
            if(this.channel.guild) {
                this.member = this.channel.guild.members.get(this.author.id);
            }
        }
        if(this.type === 0 || this.type === undefined);
        else if(this.type === 1) {
            data.content = `${this.author.mention} added <@${data.mentions[0].id}>.`;
        } else if(this.type === 2) {
            if(this.author.id === data.mentions[0].id) {
                data.content = `@${this.author.username} left the group.`;
            } else {
                data.content = `${this.author.mention} removed @${data.mentions[0].username}.`;
            }
        } else if(this.type === 3) { // (╯°□°）╯︵ ┻━┻
            if(data.call.ended_timestamp) {
                if((!this.channel.lastCall || this.channel.lastCall.endedTimestamp < Date.parse(data.call.ended_timestamp))) {
                    data.call.id = this.id;
                    this.channel.lastCall = new Call(data.call, this.channel);
                }
                if(~data.call.participants.indexOf(client.user.id)) {
                    data.content = `You missed a call from ${this.author.mention}.`;
                } else {
                    data.content = `${this.author.mention} started a call.`;
                }
            } else {
                if(!this.channel.call) {
                    data.call.id = this.id;
                    this.channel.call = new Call(data.call, this.channel);
                }
                data.content = `${this.author.mention} started a call. — Join the call.`;
            }
        } else if(this.type === 4) {
            data.content = `${this.author.mention} changed the channel name: ${data.content}`;
        } else if(this.type === 5) {
            data.content = `${this.author.mention} changed the channel icon.`;
        } else {
            throw new Error("Unhandled MESSAGE_CREATE type: " + JSON.stringify(data, null, 2));
        }
        this.update(data, client);
    }

    update(data, client) {
        if(this.type === 3) { // (╯°□°）╯︵ ┻━┻
            (this.channel.call || this.channel.lastCall).update(data.call);
        }
        if(data.content !== undefined) {
            this.content = data.content || "";
            this.mentionEveryone = !!data.mention_everyone;
            this.cleanContent = client.options.cleanContent ? this.content : null;
            this.mentions = data.mentions.map((mention) => {
                if(client.options.cleanContent) {
                    if(this.channel.guild) {
                        var member = this.channel.guild.members.get(mention.id);
                        if(member) {
                            this.cleanContent = this.cleanContent.replace(new RegExp(`<@\!${mention.id}>`, "g"), "@" + member.nick || mention.username);
                        }
                    }
                    this.cleanContent = this.cleanContent.replace(new RegExp(`<@\!?${mention.id}>`, "g"), "@" + mention.username);
                }
                return client.users.add(mention);
            });

            this.roleMentions = data.mention_roles || this.roleMentions;
            if(client.options.cleanContent && this.channel.guild) {
                for(var roleID of this.roleMentions) {
                    this.cleanContent = this.cleanContent.replace(new RegExp(`<@&${roleID}>`, "g"), "@" + this.channel.guild.roles.get(roleID).name);
                }
            }

            if(client.options.cleanContent) {
                this.channelMentions = (this.content.match(/<#[0-9]+>/g) || []).map((mention) => {
                    var id = mention.substring(2, mention.length - 1);
                    var channel = client.getChannel(id);
                    if(channel && channel.name) {
                        this.cleanContent = this.cleanContent.replace(mention, "#" + channel.name);
                    }
                    return id;
                });

                this.cleanContent = this.cleanContent.replace(/@everyone/g, "@\u200beveryone").replace(/@here/g, "@\u200bhere");
            }
        }

        this.pinned = data.pinned !== undefined ? !!data.pinned : this.pinned;
        this.editedTimestamp = data.edited_timestamp !== undefined ? Date.parse(data.edited_timestamp) : this.editedTimestamp;
        this.tts = data.tts !== undefined ? data.tts : this.tts;
        this.attachments = data.attachments !== undefined ? data.attachments : this.attachments; // TODO parse attachments
        this.embeds = data.embeds !== undefined ? data.embeds : this.embeds; // TODO parse embeds
    }
}

module.exports = Message;
<|endoftext|>