<commit_before>var gutil = require('gulp-util');
var through = require('through2');
var semver = require('semver');

//test if a type is a valid semver type
var isValidType = function(type) {
    return semver.inc('0.0.1', type);
};

//test if a version is a valid semver version
var isValidVersion = function(version, type) {
    return semver.valid(version);
};

var setDefaultOptions = function(opts) {
    opts = opts || {};
    //set defaults
    opts.key = opts.key || 'version';
    opts.indent = opts.indent || 2;
    //default type bump is patch
    if (!opts.type || !isValidType(opts.type)) {
        opts.type = 'patch';
    }
    //if passed specific version - validate it
    if (opts.version && !isValidVersion(opts.version, opts.type)) {
        gutil.log('invalid version used as option', opts.version);
        opts.version = null;
    }
    return opts;
};

module.exports = function(opts) {
    //set task options
    opts = setDefaultOptions(opts);
    var key = opts.key;
    var version = opts.version;
    var indent = opts.indent;
    var type = opts.type;

    return through.obj(function(file, enc, cb) {
        //pass through empty file
        if (file.isNull()) {
            this.push(file);
            return cb();
        }

        if (file.isStream()) {
            this.emit('error', new gutil.PluginError('gulp-bump', 'Streaming not supported'));
            return cb();
        }

        var json;
        try {
            json = JSON.parse(file.contents.toString());
        } catch (e) {
            this.emit('error', new gutil.PluginError('gulp-bump', 'Problem parsing JSON file ' + file.path));
            return cb();
        }

        //just set a version to the key
        if (version) {
            if (!json[key]) {
                //log to user that key didn't exist before
                gutil.log('Creating key', gutil.colors.red(key), 'with version:', version);
            }
            //set version to key
            json[key] = version;
        } else if (semver.valid(json[key])) {
            //increment the key with type
            json[key] = semver.inc(json[key], type);
        } else {
            this.emit('error', new gutil.PluginError('gulp-bump', 'Detected invalid semver ' + key + ' in file ' + file.path));
            return cb();
        }

        //rebuild file contents
        file.contents = new Buffer(JSON.stringify(json, null, indent) + '\n');
        //log new version
        gutil.log('Bumped ' + gutil.colors.underline(key) + ' to: ' + gutil.colors.cyan(json[key]));
        this.push(file);
        return cb();
    });
};
<commit_msg>Clean code style<commit_after>var gutil = require('gulp-util');
var through = require('through2');
var semver = require('semver');

var setDefaultOptions = function(opts) {
  opts = opts || {};
  opts.key = opts.key || 'version';
  opts.indent = opts.indent || 2;
  // default type bump is patch
  if (!opts.type || !semver.inc('0.0.1', opts.type)) {
    opts.type = 'patch';
  }
  // if passed specific version - validate it
  if (opts.version && !semver.valid(opts.version, opts.type)) {
    gutil.log('invalid version used as option', gutil.colors.red(opts.version));
    opts.version = null;
  }
  return opts;
};

module.exports = function(opts) {
  // set task options
  opts = setDefaultOptions(opts);
  var key = opts.key;
  var version = opts.version;
  var indent = opts.indent;
  var type = opts.type;

  var json;

  return through.obj(function(file, enc, cb) {
    if (file.isNull()) {
      this.push(file);
      return cb();
    }
    if (file.isStream()) {
      this.emit('error', new gutil.PluginError('gulp-bump', 'Streaming not supported'));
      return cb();
    }

    try {
      json = JSON.parse(file.contents.toString());
    } catch (e) {
      this.emit('error', new gutil.PluginError('gulp-bump', 'Problem parsing JSON file ' + file.path));
      return cb();
    }

    // just set a version to the key
    if (version) {
      if (!json[key]) {
        // log to user that key didn't exist before
        gutil.log('Creating key', gutil.colors.red(key), 'with version:', gutil.colors.cyan(version));
      }
      json[key] = version;
    }
    else if (semver.valid(json[key])) {
    // increment the key with type
      json[key] = semver.inc(json[key], type);
    }
    else {
      this.emit('error', new gutil.PluginError('gulp-bump', 'Detected invalid semver ' + key + ' in file ' + file.path));
      return cb();
    }

    file.contents = new Buffer(JSON.stringify(json, null, indent) + '\n');

    gutil.log('Bumped ' + gutil.colors.magenta(key) + ' to: ' + gutil.colors.cyan(json[key]));
    this.push(file);
    return cb();
  });
};
<|endoftext|>


<commit_before>"use strict";

require("./token");
require("./settings");

const Telegraf = require("telegraf");

const Utils = require("utils");

const ListeEpicerieBot = require("listeEpicerieBot");
const ListeEpicerieBridge = require("listeEpicerieBridge");

const telegraf = new Telegraf(process.env.BOT_TOKEN , {telegram: {agent: null, webhookReply: true}});

telegraf.telegram.getMe().then((botInfo) =>
  {
    telegraf.options.username = botInfo.username;
  });

function initTelegraf (mongoSession)
{
  if (typeof mongoSession !== "undefined")
  {
    telegraf.use(mongoSession.middleware);
  }
  else
  {
    //fake persistency
    telegraf.use(Telegraf.memorySession({ sessionName: "sessionPersistent" }));
  }

  telegraf.use(Telegraf.memorySession());

  telegraf.use((context, next) =>
    {
      if (!context.session.storage)
      {
        Object.assign(context.session, Utils.createSession(context.sessionPersistent));
      }
      return next();
    });

  telegraf.command("/start", ListeEpicerieBridge.commands.start);
  telegraf.command("/commencer", ListeEpicerieBridge.commands.start);
  telegraf.command("/ajouter", ListeEpicerieBridge.commands.add);
  telegraf.command("/ajouter_categorie", ListeEpicerieBridge.commands.addCategories);
  telegraf.command("/liste", ListeEpicerieBridge.commands.list);
  telegraf.command("/message_maitre", ListeEpicerieBridge.commands.masterMessage);
  telegraf.command("/retirer", ListeEpicerieBridge.commands.removeItems);

  telegraf.on("callback_query", (context, next) =>
    {
      try
      {
        context.session.chatId = context.update.callback_query.message.chat.id;
        context.session.list.messageId = context.update.callback_query.message.message_id;
        Object.assign(context.sessionPersistent, context.session);
      }
      catch (exception) {}
      return next();
    });

  telegraf.on("text", (context) =>
    {
      if (ListeEpicerieBot.routeAction(context.session, context.message.text))
      {
        ListeEpicerieBridge.actions.listRefesh(context);
      }
    });

  telegraf.on("edited_message", (context) =>
    {
      var isMasterMessage = false;

      try
      {
        isMasterMessage = context.update.edited_message.message_id === context.session.masterMessage.id
      }
      catch (exception) {}

      if (isMasterMessage)
      {
        if (ListeEpicerieBot.removeItems(context.session, context.session.masterMessage.text))
        {
          ListeEpicerieBot.add(context.session, context.update.edited_message.text);

          context.session.message.callbackButtons = ListeEpicerieBridge.markups.listCallbackButtons;

          context.tg.callApi(
            "editMessageText"
            , Utils.createMessageList(
                context.session
                , ListeEpicerieBot.list(context.session)
                , Markup.inlineKeyboard(context.session.message.callbackButtons).resize().extra()));
        }

        context.session.masterMessage.text = context.update.edited_message.text;

        Object.assign(context.sessionPersistent, context.session);
      }
    });

  telegraf.action(/^\s*\/add_callback/, ListeEpicerieBridge.actions.add);
  telegraf.action(/^\s*\/addCategories_callback/, ListeEpicerieBridge.actions.addCategories);
  telegraf.action(/^\s*\/categorize_callback/, ListeEpicerieBridge.actions.categorize);
  telegraf.action(/^\s*\/categorizeConfirm_callback/, ListeEpicerieBridge.actions.categorizeConfirm);
  telegraf.action(/^\s*\/categorizeDisplayCategories_callback/, ListeEpicerieBridge.actions.categorizeDisplayCategories);
  telegraf.action(/^\s*\/categorizeRefresh_callback/, ListeEpicerieBridge.actions.categorizeRefresh);
  telegraf.action(/^\s*\/categorizeSelect_callback/, ListeEpicerieBridge.actions.categorizeSelect);
  telegraf.action(/^\s*\/categorizeSelectCancel_callback/, ListeEpicerieBridge.actions.categorizeSelectCancel);
  telegraf.action(/^\s*\/cancel_callback/, ListeEpicerieBridge.actions.cancel);
  telegraf.action(/^\s*\/listRefesh_callback/, ListeEpicerieBridge.actions.listRefesh);
  telegraf.action(/^\s*\/removeCategories_callback/, ListeEpicerieBridge.actions.removeCategories);
  telegraf.action(/^\s*\/removeCategoriesConfirm_callback/, ListeEpicerieBridge.actions.removeCategoriesConfirm);
  telegraf.action(/^\s*\/removeCategory_callback/, ListeEpicerieBridge.actions.removeCategory);
  telegraf.action(/^\s*\/removeCategoryCancel_callback/, ListeEpicerieBridge.actions.removeCategoryCancel);
  telegraf.action(/^\s*\/removeItems_callback/, ListeEpicerieBridge.actions.removeItems);
  telegraf.action(/^\s*\/removeItemsConfirm_callback/, ListeEpicerieBridge.actions.removeItemsConfirm);
  telegraf.action(/^\s*\/removeItem_callback/, ListeEpicerieBridge.actions.removeItem);
  telegraf.action(/^\s*\/removeItemCancel_callback/, ListeEpicerieBridge.actions.removeItemCancel);

  telegraf.startPolling();
}

if (process.env.USE_MONGO)
{
  const { MongoClient } = require('mongodb');
  const MongoSession = require('telegraf-session-mongo');

  MongoClient.connect(process.env.MONGO_URL).then((client) =>
    {
      const mongoSession = new MongoSession(
        client
        , {
            property: "sessionPersistent"
            , collection: "sessionsPersistent"
            , "getSessionKey": (context) =>
              {
                return context.from && context.chat && `${context.from.id}:${context.chat.id}`;
              }
          });

      mongoSession.setup().then(() =>
        {
          initTelegraf(mongoSession);
        });
    });
}
else
{
  initTelegraf();
}
<commit_msg>Fix users in group not able to edit the same list<commit_after>"use strict";

require("./token");
require("./settings");

const Telegraf = require("telegraf");

const Utils = require("utils");

const ListeEpicerieBot = require("listeEpicerieBot");
const ListeEpicerieBridge = require("listeEpicerieBridge");

const telegraf = new Telegraf(process.env.BOT_TOKEN , {telegram: {agent: null, webhookReply: true}});

telegraf.telegram.getMe().then((botInfo) =>
  {
    telegraf.options.username = botInfo.username;
  });

function initTelegraf(mongoSession)
{
  if (typeof mongoSession !== "undefined")
  {
    telegraf.use(mongoSession.middleware);
  }
  else
  {
    //fake persistency
    telegraf.use(Telegraf.memorySession(
      {
        sessionName: "sessionPersistent"
        , "getSessionKey": (context) =>
          {
            return context.chat && `${context.from.id}:${context.chat.id}`;
          }
      }));
  }

  telegraf.use(Telegraf.memorySession());

  telegraf.use((context, next) =>
    {
      if (!context.session.storage)
      {
        Object.assign(context.session, Utils.createSession(context.sessionPersistent));
      }
      return next();
    });

  telegraf.command("/start", ListeEpicerieBridge.commands.start);
  telegraf.command("/commencer", ListeEpicerieBridge.commands.start);
  telegraf.command("/ajouter", ListeEpicerieBridge.commands.add);
  telegraf.command("/ajouter_categorie", ListeEpicerieBridge.commands.addCategories);
  telegraf.command("/liste", ListeEpicerieBridge.commands.list);
  telegraf.command("/message_maitre", ListeEpicerieBridge.commands.masterMessage);
  telegraf.command("/retirer", ListeEpicerieBridge.commands.removeItems);

  telegraf.on("callback_query", (context, next) =>
    {
      try
      {
        context.session.chatId = context.update.callback_query.message.chat.id;
        context.session.list.messageId = context.update.callback_query.message.message_id;
        Object.assign(context.sessionPersistent, context.session);
      }
      catch (exception) {}
      return next();
    });

  telegraf.on("text", (context) =>
    {
      if (ListeEpicerieBot.routeAction(context.session, context.message.text))
      {
        ListeEpicerieBridge.actions.listRefesh(context);
      }
    });

  telegraf.on("edited_message", (context) =>
    {
      var isMasterMessage = false;

      try
      {
        isMasterMessage = context.update.edited_message.message_id === context.session.masterMessage.id
      }
      catch (exception) {}

      if (isMasterMessage)
      {
        if (ListeEpicerieBot.removeItems(context.session, context.session.masterMessage.text))
        {
          ListeEpicerieBot.add(context.session, context.update.edited_message.text);

          context.session.message.callbackButtons = ListeEpicerieBridge.markups.listCallbackButtons;

          context.tg.callApi(
            "editMessageText"
            , Utils.createMessageList(
                context.session
                , ListeEpicerieBot.list(context.session)
                , Markup.inlineKeyboard(context.session.message.callbackButtons).resize().extra()));
        }

        context.session.masterMessage.text = context.update.edited_message.text;

        Object.assign(context.sessionPersistent, context.session);
      }
    });

  telegraf.action(/^\s*\/add_callback/, ListeEpicerieBridge.actions.add);
  telegraf.action(/^\s*\/addCategories_callback/, ListeEpicerieBridge.actions.addCategories);
  telegraf.action(/^\s*\/categorize_callback/, ListeEpicerieBridge.actions.categorize);
  telegraf.action(/^\s*\/categorizeConfirm_callback/, ListeEpicerieBridge.actions.categorizeConfirm);
  telegraf.action(/^\s*\/categorizeDisplayCategories_callback/, ListeEpicerieBridge.actions.categorizeDisplayCategories);
  telegraf.action(/^\s*\/categorizeRefresh_callback/, ListeEpicerieBridge.actions.categorizeRefresh);
  telegraf.action(/^\s*\/categorizeSelect_callback/, ListeEpicerieBridge.actions.categorizeSelect);
  telegraf.action(/^\s*\/categorizeSelectCancel_callback/, ListeEpicerieBridge.actions.categorizeSelectCancel);
  telegraf.action(/^\s*\/cancel_callback/, ListeEpicerieBridge.actions.cancel);
  telegraf.action(/^\s*\/listRefesh_callback/, ListeEpicerieBridge.actions.listRefesh);
  telegraf.action(/^\s*\/removeCategories_callback/, ListeEpicerieBridge.actions.removeCategories);
  telegraf.action(/^\s*\/removeCategoriesConfirm_callback/, ListeEpicerieBridge.actions.removeCategoriesConfirm);
  telegraf.action(/^\s*\/removeCategory_callback/, ListeEpicerieBridge.actions.removeCategory);
  telegraf.action(/^\s*\/removeCategoryCancel_callback/, ListeEpicerieBridge.actions.removeCategoryCancel);
  telegraf.action(/^\s*\/removeItems_callback/, ListeEpicerieBridge.actions.removeItems);
  telegraf.action(/^\s*\/removeItemsConfirm_callback/, ListeEpicerieBridge.actions.removeItemsConfirm);
  telegraf.action(/^\s*\/removeItem_callback/, ListeEpicerieBridge.actions.removeItem);
  telegraf.action(/^\s*\/removeItemCancel_callback/, ListeEpicerieBridge.actions.removeItemCancel);

  telegraf.startPolling();
}

if (process.env.USE_MONGO)
{
  const { MongoClient } = require('mongodb');
  const MongoSession = require('telegraf-session-mongo');

  MongoClient.connect(process.env.MONGO_URL).then((client) =>
    {
      const mongoSession = new MongoSession(
        client
        , {
            property: "sessionPersistent"
            , collection: "sessionsPersistent"
            , "getSessionKey": (context) =>
              {
                return context.chat && `${context.from.id}:${context.chat.id}`;
              }
          });

      mongoSession.setup().then(() =>
        {
          initTelegraf(mongoSession);
        });
    });
}
else
{
  initTelegraf();
}
<|endoftext|>


<commit_before>// main module for SenseBase
// meant to be modular but that needs some work.

var fs = require('fs'),
  http = require('http'),
  flash = require('connect-flash'),
  express = require('express'),
  util = require('util');

var utils = require('./lib/utils');

var pubsub, search = require('./lib/search.js'), content = require('./lib/content.js');

var users;

if (fs.existsSync('./local-site.json')) {
  users = require('./local-site.json').logins;
} else {
  users = require('./site.json').logins;
}

// start server with a configuration file
exports.start = function(config, callback) {
  GLOBAL.authed = GLOBAL.authed || {}; //FIXME  use auth scheme that works behind proxies
  config.users = users;
  config.indexer = require('./lib/indexer.js');
  config.pageCache = require('./lib/pageCache.js');
  config.onRequest = require('./lib/auth.js');
  // proxy has requested a content item.
  config.onRetrieve = {
    process: function(uri, referer, is_html, pageBuffer, contentType, saveHeaders, browser_request) {
      var status = browser_request.proxy_received.statusCode;
      if (status != 200) {
        GLOBAL.debug('non-200 status', status, uri);
        return;
      }
      // FIXME don't save binaries
      GLOBAL.config.pageCache.cache(uri, referer, is_html, pageBuffer, contentType, saveHeaders, browser_request);
      var psMember = browser_request.psMember.username;
      var desc = { uri: uri, member: psMember, referer: referer, isHTML: browser_request.is_html, content: pageBuffer, contentType: contentType, headers: saveHeaders}
      content.indexContentItem(desc);
    }
  };
  config.inject = function(content) {
    if (content.toString().match(/<\/body/i)) {
      GLOBAL.debug('injecting iframe');
      // add a div in case there is none, and a div to enable placing the iframe inline
      content = content.toString().replace(/()/im, '
$1')
        .replace(/<\/body/im, '

</body');
    }
    return content;
  };
  config.sitebase = config.sitebase || '';
  // globally shared context
  GLOBAL.config = config;
  pubsub = require('./lib/pubsub.js');
  GLOBAL.config.pubsub = pubsub;

  // Express stuff
  var app = express();
  var actions = require('./lib/app-actions.js');

  app.configure(function() {
    app.set('views', __dirname + '/views');
    app.set('view engine', 'ejs');
    app.use(express.cookieParser());
    app.use(express.bodyParser());
//    app.use(express.logger({stream: GLOBAL.config.logStream}));
    app.use(express.methodOverride());
    app.use(express.session({ secret: 'popsicle-fish' }));
    app.use(flash());
    app.use(actions);
    app.use(app.router);

    app.enable('trust proxy');
  });

  var server = app.listen(GLOBAL.config.HTTP_PORT || 9999);

  pubsub.start(server);

  var filterProxy = require('filter-proxy');

  filterProxy.start(GLOBAL.config);

  // interactive command line

  repl = require('repl');
  r = repl.start({ prompt: GLOBAL.config.project + "> ", useGlobal: true});
  if (callback) {
    callback();
  }
};
<commit_msg>cleanup docs<commit_after>// Main module for SenseBase.

var fs = require('fs'),
  http = require('http'),
  flash = require('connect-flash'),
  express = require('express'),
  util = require('util');

var utils = require('./lib/utils');

var pubsub, search = require('./lib/search.js'), content = require('./lib/content.js');

// Runtime users.
var users;

// Load local configuration is available.
if (fs.existsSync('./local-site.json')) {
  users = require('./local-site.json').logins;
} else {
// Use default included configuration.
  users = require('./site.json').logins;
}

// Start server with configuration.
exports.start = function(config, callback) {
  GLOBAL.authed = GLOBAL.authed || {}; //FIXME  use auth scheme that works behind proxies
  config.users = users;
  config.indexer = require('./lib/indexer.js');
// Proxy operation.
  config.pageCache = require('./lib/pageCache.js');
// Proxy operation.
  config.onRequest = require('./lib/auth.js');
// Proxy operation.
//
// Proxy has requested a content item.
  config.onRetrieve = {
    process: function(uri, referer, is_html, pageBuffer, contentType, saveHeaders, browser_request) {
      var status = browser_request.proxy_received.statusCode;
      if (status != 200) {
        GLOBAL.debug('non-200 status', status, uri);
        return;
      }
      // FIXME don't save binaries
      GLOBAL.config.pageCache.cache(uri, referer, is_html, pageBuffer, contentType, saveHeaders, browser_request);
      var psMember = browser_request.psMember.username;
      var desc = { uri: uri, member: psMember, referer: referer, isHTML: browser_request.is_html, content: pageBuffer, contentType: contentType, headers: saveHeaders}
      content.indexContentItem(desc);
    }
  };
// Proxy operation.
// Inject SenseBase controls.
  config.inject = function(content) {
    if (content.toString().match(/<\/body/i)) {
      GLOBAL.debug('injecting iframe');
      // add a div in case there is none, and a div to enable placing the iframe inline
      content = content.toString().replace(/()/im, '
$1')
        .replace(/<\/body/im, '

</body');
    }
    return content;
  };
  config.sitebase = config.sitebase || '';
// Globally shared config.
  GLOBAL.config = config;
  pubsub = require('./lib/pubsub.js');
  GLOBAL.config.pubsub = pubsub;

// Express stuff.
  var app = express();
  var actions = require('./lib/app-actions.js');

  app.configure(function() {
    app.set('views', __dirname + '/views');
    app.set('view engine', 'ejs');
    app.use(express.cookieParser());
    app.use(express.bodyParser());
//    app.use(express.logger({stream: GLOBAL.config.logStream}));
    app.use(express.methodOverride());
    app.use(express.session({ secret: 'popsicle-fish' }));
    app.use(flash());
    app.use(actions);
    app.use(app.router);

    app.enable('trust proxy');
  });

  var server = app.listen(GLOBAL.config.HTTP_PORT || 9999);

  pubsub.start(server);

  var filterProxy = require('filter-proxy');

  filterProxy.start(GLOBAL.config);

// Interactive command line.

  repl = require('repl');
  r = repl.start({ prompt: GLOBAL.config.project + "> ", useGlobal: true});
  if (callback) {
    callback();
  }
};
<|endoftext|>


<commit_before>var AmpersandModel = require('ampersand-model');
var AmpersandCollection = require('ampersand-rest-collection');
var AmpersandState = require('ampersand-state');
var DatabaseCollection = require('mongodb-database-model').Collection;
var CollectionCollection = require('mongodb-collection-model').Collection;
var hostname = require('os').hostname();

var HostInfo = AmpersandState.extend({
  props: {
    system_time: 'date',
    hostname: 'string',
    os: 'string',
    os_family: 'string',
    kernel_version: 'string',
    kernel_version_string: 'string',
    memory_bits: 'number',
    memory_page_size: 'number',
    arch: 'string',
    cpu_cores: 'number',
    cpu_cores_physical: 'number',
    cpu_scheduler: 'string',
    cpu_frequency: 'number',
    cpu_string: 'string',
    cpu_bits: 'number',
    machine_model: 'string',
    feature_numa: 'boolean',
    feature_always_full_sync: 'number',
    feature_nfs_async: 'number'
  }
});

var BuildInfo = AmpersandState.extend({
  props: {
    version: 'string',
    commit: 'string',
    commit_url: 'string',
    flags_loader: 'string',
    flags_compiler: 'string',
    allocator: 'string',
    javascript_engine: 'string',
    debug: 'boolean',
    for_bits: 'number',
    max_bson_object_size: 'number'
  }
});

var Instance = AmpersandModel.extend({
  modelType: 'Instance',
  idAttribute: '_id',
  props: {
    _id: {
      type: 'string',
      required: true
    },
    name: {
      type: 'string'
    }
  },
  collections: {
    databases: DatabaseCollection,
    collections: CollectionCollection
  },
  children: {
    host: HostInfo,
    build: BuildInfo
  }
});

var InstanceCollection = AmpersandCollection.extend({
  comparator: '_id',
  model: Instance,
  modelType: 'InstanceCollection'
});

module.exports = Instance;
module.exports.Collection = InstanceCollection;
module.exports.BuildInfo = BuildInfo;
module.exports.HostInfo = HostInfo;

module.exports.getId = function(id) {
  if (typeof id === 'number') {
    id = 'localhost:' + id;
  }
  return id.toLowerCase().replace(hostname, 'localhost').replace('mongodb://', '');
};
<commit_msg>added boolean flag for enterprise_module present/absent.<commit_after>var AmpersandModel = require('ampersand-model');
var AmpersandCollection = require('ampersand-rest-collection');
var AmpersandState = require('ampersand-state');
var DatabaseCollection = require('mongodb-database-model').Collection;
var CollectionCollection = require('mongodb-collection-model').Collection;
var hostname = require('os').hostname();

var HostInfo = AmpersandState.extend({
  props: {
    system_time: 'date',
    hostname: 'string',
    os: 'string',
    os_family: 'string',
    kernel_version: 'string',
    kernel_version_string: 'string',
    memory_bits: 'number',
    memory_page_size: 'number',
    arch: 'string',
    cpu_cores: 'number',
    cpu_cores_physical: 'number',
    cpu_scheduler: 'string',
    cpu_frequency: 'number',
    cpu_string: 'string',
    cpu_bits: 'number',
    machine_model: 'string',
    feature_numa: 'boolean',
    feature_always_full_sync: 'number',
    feature_nfs_async: 'number'
  }
});

var BuildInfo = AmpersandState.extend({
  props: {
    version: 'string',
    commit: 'string',
    commit_url: 'string',
    flags_loader: 'string',
    flags_compiler: 'string',
    allocator: 'string',
    javascript_engine: 'string',
    debug: 'boolean',
    for_bits: 'number',
    max_bson_object_size: 'number',
    enterprise_module: 'boolean'
  }
});

var Instance = AmpersandModel.extend({
  modelType: 'Instance',
  idAttribute: '_id',
  props: {
    _id: {
      type: 'string',
      required: true
    },
    name: {
      type: 'string'
    }
  },
  collections: {
    databases: DatabaseCollection,
    collections: CollectionCollection
  },
  children: {
    host: HostInfo,
    build: BuildInfo
  }
});

var InstanceCollection = AmpersandCollection.extend({
  comparator: '_id',
  model: Instance,
  modelType: 'InstanceCollection'
});

module.exports = Instance;
module.exports.Collection = InstanceCollection;
module.exports.BuildInfo = BuildInfo;
module.exports.HostInfo = HostInfo;

module.exports.getId = function(id) {
  if (typeof id === 'number') {
    id = 'localhost:' + id;
  }
  return id.toLowerCase().replace(hostname, 'localhost').replace('mongodb://', '');
};
<|endoftext|>


<commit_before>module.exports = UI;

function UI(store, target) {
  if (!(this instanceof UI)) return new UI(store, target);
  this.store = store;
  this.target = target || document.body;
}

UI.prototype = {
  open: function() {
    var el = this._el;
    if (!el) {
      el = this._el = this.render();
      require.ensure(['./lib/draggable', '!!style-loader!css-loader!./canary.css'], function(require) {
        require('!!style-loader!css-loader!./canary.css');
        (require('./lib/draggable'))(el);
      });
    }
    var target = this.target;
    if (!target.contains(el)) target.appendChild(el);
    el.style.display = '';
    return this;
  },
  close: function() {
    this._el.style.display = 'none';
    return this;
  },
  render: function() {
    var list = this._ul(this.store);

    return DOM('div', {
      id: 'canary-ui'
    }, [
      this._reset(),
      this._close(),
      this._minimize(),
      list
    ]);
  },
  sessionStorage: function() {
    var overrides = {};

    try {
      this._storage = window.sessionStorage;
      overrides = JSON.parse(this._storage.canary || '{}');
    } catch (e) {}

    for (var k in overrides) {
      this.store.override(k, overrides[k]);
    }

    return this;
  },
  hashchange: function() {
    var self = this;
    function onChange() {
      self._onhashchange(location.hash);
    }
    onChange();

    // Set a timeout in case the element gets ripped out of the DOM
    setTimeout(onChange, 1000);

    window.addEventListener('hashchange', onChange);
    return self;
  },
  set: function(feature, variant) {
    this.store.override(feature, variant);
    if (this._storage) this._storage.canary = JSON.stringify(this.store._overrides);
    return this;
  },
  reset: function() {
    this.store.reset();
    if (this._storage) delete this._storage.canary;
  },
  _onhashchange: function(hash) {
    if (hash.indexOf('#canary') !== 0) return;
    var parts = hash.split('=');
    if (parts[0] === '#canary') this.open();
    try {
      var overrides = JSON.parse(decodeURIComponent(parts[1] || '{}'));
      for (var k in overrides) {
        this.set(k, overrides[k]);
      }
    } catch(e) {}
  },
  _reset: function() {
    var self = this;
    return a('reset', 'reset', function() {
      self.reset();
    });
  },
  _close: function() {
    var self = this;
    return a('action close', '×', function() {
      self.close();
    });
  },
  _minimize: function() {
    var self = this;
    var minimize = a('action minimize', '_', function() {
      var el = self._el;
      var minimized = el.className === 'minimized';
      el.className = minimized ? '' : 'minimized';
      minimize.innerText = minimized ? '_' : '+';
    });
    return minimize;
  },
  _ul: function(store) {
    var self = this;
    var ul = DOM('ul');

    function onChange() {
      store.features().forEach(function(feature) {
        ul.appendChild(self._li(feature));
      });
    }

    store.on('change', function() {
      ul.innerHTML = '';
      onChange();
    });

    onChange();

    return ul;
  },
  _li: function(feature) {
    return DOM('li', {}, [
      DOM('label', {}, [
        DOM('span', {innerText: feature.name}),
        this._input(feature)
      ])
    ]);
  },
  _input: function(feature) {
    var variants = feature.variants;
    return variants.length === 2 && typeof variants[0].value === 'boolean' ?
      this._checkbox(feature) :
      this._select(feature);
  },
  _checkbox: function(feature) {
    var self = this;
    var el = DOM('input', {
      type: 'checkbox',
      checked: feature.selected,
      onchange: function() {
        self.set(feature.name, !!el.checked);
      }
    });
    return el;
  },
  _select: function(feature) {
    var self = this;
    var el = DOM('select', {
      onchange: function() {
        self.set(feature.name, el.value);
      }
    }, feature.variants.map(function(variant) {
      return DOM('option', {
        value: variant.value,
        selected: variant.isSelected,
        innerText: variant.value
      })
    }));
    return el;
  }
};

function a(className, text, onclick) {
  return DOM('a', {
    className: className,
    innerText: text,
    href: 'javascript:;',
    onclick: function(evt) {
      onclick(evt)
      return false;
    }
  });
}

function DOM(name, props, children) {
  var el = document.createElement(name);
  props = props || {};
  children = children || [];
  for (var k in props) {
    el[k] = props[k]
  }
  children.forEach(function(child) {
    el.appendChild(child);
  });
  return el;
}
<commit_msg>add toggle method<commit_after>module.exports = UI;

function UI(store, target) {
  if (!(this instanceof UI)) return new UI(store, target);
  this.store = store;
  this.target = target || document.body;
}

UI.prototype = {
  open: function() {
    var el = this._el;
    if (!el) {
      el = this._el = this.render();
      require.ensure(['./lib/draggable', '!!style-loader!css-loader!./canary.css'], function(require) {
        require('!!style-loader!css-loader!./canary.css');
        (require('./lib/draggable'))(el);
      });
    }
    var target = this.target;
    if (!target.contains(el)) target.appendChild(el);
    el.style.display = '';
    return this;
  },
  close: function() {
    this._el.style.display = 'none';
    return this;
  },
  toggle: function() {
    return this._el.style.display === 'none' ?
      this.open() :
      this.close();
  },
  render: function() {
    var list = this._ul(this.store);

    return DOM('div', {
      id: 'canary-ui'
    }, [
      this._reset(),
      this._close(),
      this._minimize(),
      list
    ]);
  },
  sessionStorage: function() {
    var overrides = {};

    try {
      this._storage = window.sessionStorage;
      overrides = JSON.parse(this._storage.canary || '{}');
    } catch (e) {}

    for (var k in overrides) {
      this.store.override(k, overrides[k]);
    }

    return this;
  },
  hashchange: function() {
    var self = this;
    function onChange() {
      self._onhashchange(location.hash);
    }
    onChange();

    // Set a timeout in case the element gets ripped out of the DOM
    setTimeout(onChange, 1000);

    window.addEventListener('hashchange', onChange);
    return self;
  },
  set: function(feature, variant) {
    this.store.override(feature, variant);
    if (this._storage) this._storage.canary = JSON.stringify(this.store._overrides);
    return this;
  },
  reset: function() {
    this.store.reset();
    if (this._storage) delete this._storage.canary;
  },
  _onhashchange: function(hash) {
    if (hash.indexOf('#canary') !== 0) return;
    var parts = hash.split('=');
    if (parts[0] === '#canary') this.open();
    try {
      var overrides = JSON.parse(decodeURIComponent(parts[1] || '{}'));
      for (var k in overrides) {
        this.set(k, overrides[k]);
      }
    } catch(e) {}
  },
  _reset: function() {
    var self = this;
    return a('reset', 'reset', function() {
      self.reset();
    });
  },
  _close: function() {
    var self = this;
    return a('action close', '×', function() {
      self.close();
    });
  },
  _minimize: function() {
    var self = this;
    var minimize = a('action minimize', '_', function() {
      var el = self._el;
      var minimized = el.className === 'minimized';
      el.className = minimized ? '' : 'minimized';
      minimize.innerText = minimized ? '_' : '+';
    });
    return minimize;
  },
  _ul: function(store) {
    var self = this;
    var ul = DOM('ul');

    function onChange() {
      store.features().forEach(function(feature) {
        ul.appendChild(self._li(feature));
      });
    }

    store.on('change', function() {
      ul.innerHTML = '';
      onChange();
    });

    onChange();

    return ul;
  },
  _li: function(feature) {
    return DOM('li', {}, [
      DOM('label', {}, [
        DOM('span', {innerText: feature.name}),
        this._input(feature)
      ])
    ]);
  },
  _input: function(feature) {
    var variants = feature.variants;
    return variants.length === 2 && typeof variants[0].value === 'boolean' ?
      this._checkbox(feature) :
      this._select(feature);
  },
  _checkbox: function(feature) {
    var self = this;
    var el = DOM('input', {
      type: 'checkbox',
      checked: feature.selected,
      onchange: function() {
        self.set(feature.name, !!el.checked);
      }
    });
    return el;
  },
  _select: function(feature) {
    var self = this;
    var el = DOM('select', {
      onchange: function() {
        self.set(feature.name, el.value);
      }
    }, feature.variants.map(function(variant) {
      return DOM('option', {
        value: variant.value,
        selected: variant.isSelected,
        innerText: variant.value
      })
    }));
    return el;
  }
};

function a(className, text, onclick) {
  return DOM('a', {
    className: className,
    innerText: text,
    href: 'javascript:;',
    onclick: function(evt) {
      onclick(evt)
      return false;
    }
  });
}

function DOM(name, props, children) {
  var el = document.createElement(name);
  props = props || {};
  children = children || [];
  for (var k in props) {
    el[k] = props[k]
  }
  children.forEach(function(child) {
    el.appendChild(child);
  });
  return el;
}
<|endoftext|>


<commit_before>'use-strict';

var xml = require('xml');
var Base = require('mocha').reporters.Base;
var fs = require('fs');
var path = require('path');
var debug = require('debug')('mocha-junit-reporter');
var mkdirp = require('mkdirp');
var md5 = require('md5');
var stripAnsi = require('strip-ansi');

var createStatsCollector;
var mocha6plus;

try {
  var json = JSON.parse(
    fs.readFileSync(path.dirname(require.resolve('mocha')) + "/package.json", "utf8")
  );
  var version = json.version;
  if (version >= "6") {
    createStatsCollector = require("mocha/lib/stats-collector");
    mocha6plus = true;
  } else {
    mocha6plus = false;
  }
} catch (e) {
  // eslint-disable-next-line no-console
  console.warn("Couldn't determine Mocha version");
}
module.exports = MochaJUnitReporter;

// A subset of invalid characters as defined in http://www.w3.org/TR/xml/#charsets that can occur in e.g. stacktraces
// regex lifted from https://github.com/MylesBorins/xml-sanitizer/ (licensed MIT)
var INVALID_CHARACTERS_REGEX = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007f-\u0084\u0086-\u009f\uD800-\uDFFF\uFDD0-\uFDFF\uFFFF\uC008]/g; //eslint-disable-line no-control-regex

function configureDefaults(options) {
  debug(options);
  options = options || {};
  options = options.reporterOptions || {};
  options.mochaFile = getSetting(options.mochaFile, 'MOCHA_FILE', 'test-results.xml');
  options.attachments = getSetting(options.attachments, 'ATTACHMENTS', false);
  options.antMode = getSetting(options.antMode, 'ANT_MODE', false);
  options.jenkinsMode = getSetting(options.jenkinsMode, 'JENKINS_MODE', false);
  options.properties = getSetting(options.properties, 'PROPERTIES', null, parsePropertiesFromEnv);
  options.toConsole = !!options.toConsole;
  options.rootSuiteTitle = options.rootSuiteTitle || 'Root Suite';
  options.testsuitesTitle = options.testsuitesTitle || 'Mocha Tests';

  if (options.antMode) {
    updateOptionsForAntMode(options);
  }

  if (options.jenkinsMode) {
    updateOptionsForJenkinsMode(options);
  }

  options.suiteTitleSeparedBy = options.suiteTitleSeparedBy || ' ';
  options.suiteTitleSeparatedBy = options.suiteTitleSeparatedBy || options.suiteTitleSeparedBy;

  return options;
}

function updateOptionsForAntMode(options) {
  options.antHostname = getSetting(options.antHostname, 'ANT_HOSTNAME', process.env.HOSTNAME);

  if (!options.properties) {
    options.properties = {};
  }
}

function updateOptionsForJenkinsMode(options) {
  if (options.useFullSuiteTitle === undefined) {
    options.useFullSuiteTitle = true;
  }
  debug('jenkins mode - testCaseSwitchClassnameAndName', options.testCaseSwitchClassnameAndName);
  if (options.testCaseSwitchClassnameAndName === undefined) {
    options.testCaseSwitchClassnameAndName = true;
  }
  if (options.suiteTitleSeparedBy === undefined) {
    options.suiteTitleSeparedBy = '.';
  }
}

/**
 * Determine an option value.
 * 1. If `key` is present in the environment, then use the environment value
 * 2. If `value` is specified, then use that value
 * 3. Fall back to `defaultVal`
 * @module mocha-junit-reporter
 * @param {Object} value - the value from the reporter options
 * @param {String} key - the environment variable to check
 * @param {Object} defaultVal - the fallback value
 * @param {function} transform - a transformation function to be used when loading values from the environment
 */
function getSetting(value, key, defaultVal, transform) {
  if (process.env[key] !== undefined) {
    var envVal = process.env[key];
    return (typeof transform === 'function') ? transform(envVal) : envVal;
  }
  if (value !== undefined) {
    return value;
  }
  return defaultVal;
}

function defaultSuiteTitle(suite) {
  if (suite.root && suite.title === '') {
      return stripAnsi(this._options.rootSuiteTitle);
  }
  return stripAnsi(suite.title);
}

function fullSuiteTitle(suite) {
  var parent = suite.parent;
  var title = [ suite.title ];

  while (parent) {
    if (parent.root && parent.title === '') {
      title.unshift(this._options.rootSuiteTitle);
    } else {
      title.unshift(parent.title);
    }
    parent = parent.parent;
  }

  return stripAnsi(title.join(this._options.suiteTitleSeparatedBy));
}

function isInvalidSuite(suite) {
  return (!suite.root && suite.title === '') || (suite.tests.length === 0 && suite.suites.length === 0);
}

function parsePropertiesFromEnv(envValue) {
  if (envValue) {
    debug('Parsing from env', envValue);
    return envValue.split(',').reduce(function(properties, prop) {
      var property = prop.split(':');
      properties[property[0]] = property[1];
      return properties;
    }, []);
  }

  return null;
}

function generateProperties(options) {
  var props = options.properties;
  if (!props) {
    return [];
  }
  return Object.keys(props).reduce(function(properties, name) {
    var value = props[name];
    properties.push({ property: { _attr: { name: name, value: value } } });
    return properties;
  }, []);
}

function getJenkinsClassname (test) {
  debug('Building jenkins classname for', test);
  var parent = test.parent;
  var titles = [];
  while (parent) {
    parent.title && titles.unshift(parent.title);
    parent = parent.parent;
  }
  return titles.join('.');
}

/**
 * JUnit reporter for mocha.js.
 * @module mocha-junit-reporter
 * @param {EventEmitter} runner - the test runner
 * @param {Object} options - mocha options
 */
function MochaJUnitReporter(runner, options) {
  if (mocha6plus) {
    createStatsCollector(runner);
  }
  this._options = configureDefaults(options);
  this._runner = runner;
  this._generateSuiteTitle = this._options.useFullSuiteTitle ? fullSuiteTitle : defaultSuiteTitle;
  this._antId = 0;

  var testsuites = [];

  function lastSuite() {
    return testsuites[testsuites.length - 1].testsuite;
  }

  // get functionality from the Base reporter
  Base.call(this, runner);

  // remove old results
  this._runner.on('start', function() {
    if (fs.existsSync(this._options.mochaFile)) {
      debug('removing report file', this._options.mochaFile);
      fs.unlinkSync(this._options.mochaFile);
    }
  }.bind(this));

  this._runner.on('suite', function(suite) {
    if (!isInvalidSuite(suite)) {
      testsuites.push(this.getTestsuiteData(suite));
    }
  }.bind(this));

  this._runner.on('pass', function(test) {
    lastSuite().push(this.getTestcaseData(test));
  }.bind(this));

  this._runner.on('fail', function(test, err) {
    lastSuite().push(this.getTestcaseData(test, err));
  }.bind(this));

  if (this._options.includePending) {
    this._runner.on('pending', function(test) {
      var testcase = this.getTestcaseData(test);

      testcase.testcase.push({ skipped: null });
      lastSuite().push(testcase);
    }.bind(this));
  }

  this._runner.on('end', function(){
    this.flush(testsuites);
  }.bind(this));
}

/**
 * Produces an xml node for a test suite
 * @param  {Object} suite - a test suite
 * @return {Object}       - an object representing the xml node
 */
MochaJUnitReporter.prototype.getTestsuiteData = function(suite) {
  var antMode = this._options.antMode;

  var _attr =  {
    name: this._generateSuiteTitle(suite),
    timestamp: new Date().toISOString().slice(0,-5),
    tests: suite.tests.length
  };
  var testSuite = { testsuite: [ { _attr: _attr } ] };

  if(suite.file) {
    testSuite.testsuite[0]._attr.file =  suite.file;
  }

  var properties = generateProperties(this._options);
  if (properties.length || antMode) {
    testSuite.testsuite.push({
      properties: properties
    });
  }

  if (antMode) {
    _attr.package = _attr.name;
    _attr.hostname = this._options.antHostname;
    _attr.id = this._antId;
    _attr.errors = 0;
    this._antId += 1;
  }

  return testSuite;
};

/**
 * Produces an xml config for a given test case.
 * @param {object} test - test case
 * @param {object} err - if test failed, the failure object
 * @returns {object}
 */
MochaJUnitReporter.prototype.getTestcaseData = function(test, err) {
  var jenkinsMode = this._options.jenkinsMode;
  var flipClassAndName = this._options.testCaseSwitchClassnameAndName;
  var name = stripAnsi(jenkinsMode ? getJenkinsClassname(test) : test.fullTitle());
  var classname = stripAnsi(test.title);
  var testcase = {
    testcase: [{
      _attr: {
        name: flipClassAndName ? classname : name,
        time: (typeof test.duration === 'undefined') ? 0 : test.duration / 1000,
        classname: flipClassAndName ? name : classname
      }
    }]
  };

  // We need to merge console.logs and attachments into one <system-out> -
  //  see JUnit schema (only accepts 1 <system-out> per test).
  var systemOutLines = [];
  if (this._options.outputs && (test.consoleOutputs && test.consoleOutputs.length > 0)) {
    systemOutLines = systemOutLines.concat(test.consoleOutputs);
  }
  if (this._options.attachments && test.attachments && test.attachments.length > 0) {
    systemOutLines = systemOutLines.concat(test.attachments.map(
      function (file) {
        return '[[ATTACHMENT|' + file + ']]';
      }
    ));
  }
  if (systemOutLines.length > 0) {
    testcase.testcase.push({'system-out': this.removeInvalidCharacters(stripAnsi(systemOutLines.join('\n')))});
  }

  if (this._options.outputs && (test.consoleErrors && test.consoleErrors.length > 0)) {
    testcase.testcase.push({'system-err': this.removeInvalidCharacters(stripAnsi(test.consoleErrors.join('\n')))});
  }

  if (err) {
    var message;
    if (err.message && typeof err.message.toString === 'function') {
      message = err.message + '';
    } else if (typeof err.inspect === 'function') {
      message = err.inspect() + '';
    } else {
      message = '';
    }
    var failureMessage = err.stack || message;
    var failureElement = {
      _attr: {
        message: this.removeInvalidCharacters(err.message) || '',
        type: err.name || ''
      },
      _cdata: this.removeInvalidCharacters(failureMessage)
    };

    testcase.testcase.push({failure: failureElement});
  }
  return testcase;
};

/**
 * @param {string} input
 * @returns {string} without invalid characters
 */
MochaJUnitReporter.prototype.removeInvalidCharacters = function(input){
  if (!input) {
    return input;
  }
  return input.replace(INVALID_CHARACTERS_REGEX, '');
};

/**
 * Writes xml to disk and ouputs content if "toConsole" is set to true.
 * @param {Array.<Object>} testsuites - a list of xml configs
 */
MochaJUnitReporter.prototype.flush = function(testsuites){
  var xml = this.getXml(testsuites);

  this.writeXmlToDisk(xml, this._options.mochaFile);

  if (this._options.toConsole === true) {
    console.log(xml); // eslint-disable-line no-console
  }
};

/**
 * Produces an XML string from the given test data.
 * @param {Array.<Object>} testsuites - a list of xml configs
 * @returns {string}
 */
MochaJUnitReporter.prototype.getXml = function(testsuites) {
  var totalSuitesTime = 0;
  var totalTests = 0;
  var stats = this._runner.stats;
  var antMode = this._options.antMode;
  var hasProperties = (!!this._options.properties) || antMode;

  testsuites.forEach(function(suite) {
    var _suiteAttr = suite.testsuite[0]._attr;
    // testsuite is an array: [attrs, properties?, testcase, testcase, …]
    // we want to make sure that we are grabbing test cases at the correct index
    var _casesIndex = hasProperties ? 2 : 1;
    var _cases = suite.testsuite.slice(_casesIndex);
    var missingProps;

    _suiteAttr.failures = 0;
    _suiteAttr.time = 0;
    _suiteAttr.skipped = 0;

    _cases.forEach(function(testcase) {
      var lastNode = testcase.testcase[testcase.testcase.length - 1];

      _suiteAttr.skipped += Number('skipped' in lastNode);
      _suiteAttr.failures += Number('failure' in lastNode);
      _suiteAttr.time += testcase.testcase[0]._attr.time;
    });

    if (antMode) {
      missingProps = ['system-out', 'system-err'];
      suite.testsuite.forEach(function(item) {
        missingProps = missingProps.filter(function(prop) {
          return !item[prop];
        });
      });
      missingProps.forEach(function(prop) {
        var obj = {};
        obj[prop] = [];
        suite.testsuite.push(obj);
      });
    }

    if (!_suiteAttr.skipped) {
      delete _suiteAttr.skipped;
    }

    totalSuitesTime += _suiteAttr.time;
    totalTests += _suiteAttr.tests;
  });

  if (!antMode) {
    var rootSuite = {
      _attr: {
        name: this._options.testsuitesTitle,
        time: totalSuitesTime,
        tests: totalTests,
        failures: stats.failures
      }
    };
    if (stats.pending) {
      rootSuite._attr.skipped = stats.pending;
    }
    testsuites = [ rootSuite ].concat(testsuites);
  }

  return xml({ testsuites: testsuites }, { declaration: true, indent: '  ' });
};

/**
 * Writes a JUnit test report XML document.
 * @param {string} xml - xml string
 * @param {string} filePath - path to output file
 */
MochaJUnitReporter.prototype.writeXmlToDisk = function(xml, filePath){
  if (filePath) {
    if (filePath.indexOf('[hash]') !== -1) {
      filePath = filePath.replace('[hash]', md5(xml));
    }

    debug('writing file to', filePath);
    mkdirp.sync(path.dirname(filePath));

    try {
        fs.writeFileSync(filePath, xml, 'utf-8');
    } catch (exc) {
        debug('problem writing results: ' + exc);
    }
    debug('results written successfully');
  }
};
<commit_msg>Fixed unhandled promise rejection<commit_after>'use-strict';

var xml = require('xml');
var Base = require('mocha').reporters.Base;
var fs = require('fs');
var path = require('path');
var debug = require('debug')('mocha-junit-reporter');
var mkdirp = require('mkdirp');
var md5 = require('md5');
var stripAnsi = require('strip-ansi');

var createStatsCollector;
var mocha6plus;

try {
  var json = JSON.parse(
    fs.readFileSync(path.dirname(require.resolve('mocha')) + "/package.json", "utf8")
  );
  var version = json.version;
  if (version >= "6") {
    createStatsCollector = require("mocha/lib/stats-collector");
    mocha6plus = true;
  } else {
    mocha6plus = false;
  }
} catch (e) {
  // eslint-disable-next-line no-console
  console.warn("Couldn't determine Mocha version");
}
module.exports = MochaJUnitReporter;

// A subset of invalid characters as defined in http://www.w3.org/TR/xml/#charsets that can occur in e.g. stacktraces
// regex lifted from https://github.com/MylesBorins/xml-sanitizer/ (licensed MIT)
var INVALID_CHARACTERS_REGEX = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007f-\u0084\u0086-\u009f\uD800-\uDFFF\uFDD0-\uFDFF\uFFFF\uC008]/g; //eslint-disable-line no-control-regex

function configureDefaults(options) {
  debug(options);
  options = options || {};
  options = options.reporterOptions || {};
  options.mochaFile = getSetting(options.mochaFile, 'MOCHA_FILE', 'test-results.xml');
  options.attachments = getSetting(options.attachments, 'ATTACHMENTS', false);
  options.antMode = getSetting(options.antMode, 'ANT_MODE', false);
  options.jenkinsMode = getSetting(options.jenkinsMode, 'JENKINS_MODE', false);
  options.properties = getSetting(options.properties, 'PROPERTIES', null, parsePropertiesFromEnv);
  options.toConsole = !!options.toConsole;
  options.rootSuiteTitle = options.rootSuiteTitle || 'Root Suite';
  options.testsuitesTitle = options.testsuitesTitle || 'Mocha Tests';

  if (options.antMode) {
    updateOptionsForAntMode(options);
  }

  if (options.jenkinsMode) {
    updateOptionsForJenkinsMode(options);
  }

  options.suiteTitleSeparedBy = options.suiteTitleSeparedBy || ' ';
  options.suiteTitleSeparatedBy = options.suiteTitleSeparatedBy || options.suiteTitleSeparedBy;

  return options;
}

function updateOptionsForAntMode(options) {
  options.antHostname = getSetting(options.antHostname, 'ANT_HOSTNAME', process.env.HOSTNAME);

  if (!options.properties) {
    options.properties = {};
  }
}

function updateOptionsForJenkinsMode(options) {
  if (options.useFullSuiteTitle === undefined) {
    options.useFullSuiteTitle = true;
  }
  debug('jenkins mode - testCaseSwitchClassnameAndName', options.testCaseSwitchClassnameAndName);
  if (options.testCaseSwitchClassnameAndName === undefined) {
    options.testCaseSwitchClassnameAndName = true;
  }
  if (options.suiteTitleSeparedBy === undefined) {
    options.suiteTitleSeparedBy = '.';
  }
}

/**
 * Determine an option value.
 * 1. If `key` is present in the environment, then use the environment value
 * 2. If `value` is specified, then use that value
 * 3. Fall back to `defaultVal`
 * @module mocha-junit-reporter
 * @param {Object} value - the value from the reporter options
 * @param {String} key - the environment variable to check
 * @param {Object} defaultVal - the fallback value
 * @param {function} transform - a transformation function to be used when loading values from the environment
 */
function getSetting(value, key, defaultVal, transform) {
  if (process.env[key] !== undefined) {
    var envVal = process.env[key];
    return (typeof transform === 'function') ? transform(envVal) : envVal;
  }
  if (value !== undefined) {
    return value;
  }
  return defaultVal;
}

function defaultSuiteTitle(suite) {
  if (suite.root && suite.title === '') {
      return stripAnsi(this._options.rootSuiteTitle);
  }
  return stripAnsi(suite.title);
}

function fullSuiteTitle(suite) {
  var parent = suite.parent;
  var title = [ suite.title ];

  while (parent) {
    if (parent.root && parent.title === '') {
      title.unshift(this._options.rootSuiteTitle);
    } else {
      title.unshift(parent.title);
    }
    parent = parent.parent;
  }

  return stripAnsi(title.join(this._options.suiteTitleSeparatedBy));
}

function isInvalidSuite(suite) {
  return (!suite.root && suite.title === '') || (suite.tests.length === 0 && suite.suites.length === 0);
}

function parsePropertiesFromEnv(envValue) {
  if (envValue) {
    debug('Parsing from env', envValue);
    return envValue.split(',').reduce(function(properties, prop) {
      var property = prop.split(':');
      properties[property[0]] = property[1];
      return properties;
    }, []);
  }

  return null;
}

function generateProperties(options) {
  var props = options.properties;
  if (!props) {
    return [];
  }
  return Object.keys(props).reduce(function(properties, name) {
    var value = props[name];
    properties.push({ property: { _attr: { name: name, value: value } } });
    return properties;
  }, []);
}

function getJenkinsClassname (test) {
  debug('Building jenkins classname for', test);
  var parent = test.parent;
  var titles = [];
  while (parent) {
    parent.title && titles.unshift(parent.title);
    parent = parent.parent;
  }
  return titles.join('.');
}

/**
 * JUnit reporter for mocha.js.
 * @module mocha-junit-reporter
 * @param {EventEmitter} runner - the test runner
 * @param {Object} options - mocha options
 */
function MochaJUnitReporter(runner, options) {
  if (mocha6plus) {
    createStatsCollector(runner);
  }
  this._options = configureDefaults(options);
  this._runner = runner;
  this._generateSuiteTitle = this._options.useFullSuiteTitle ? fullSuiteTitle : defaultSuiteTitle;
  this._antId = 0;

  var testsuites = [];

  function lastSuite() {
    return testsuites[testsuites.length - 1].testsuite;
  }

  // get functionality from the Base reporter
  Base.call(this, runner);

  // remove old results
  this._runner.on('start', function() {
    if (fs.existsSync(this._options.mochaFile)) {
      debug('removing report file', this._options.mochaFile);
      fs.unlinkSync(this._options.mochaFile);
    }
  }.bind(this));

  this._runner.on('suite', function(suite) {
    if (!isInvalidSuite(suite)) {
      testsuites.push(this.getTestsuiteData(suite));
    }
  }.bind(this));

  this._runner.on('pass', function(test) {
    lastSuite().push(this.getTestcaseData(test));
  }.bind(this));

  this._runner.on('fail', function(test, err) {
    lastSuite().push(this.getTestcaseData(test, err));
  }.bind(this));

  if (this._options.includePending) {
    this._runner.on('pending', function(test) {
      var testcase = this.getTestcaseData(test);

      testcase.testcase.push({ skipped: null });
      lastSuite().push(testcase);
    }.bind(this));
  }

  this._runner.on('end', function(){
    this.flush(testsuites);
  }.bind(this));
}

/**
 * Produces an xml node for a test suite
 * @param  {Object} suite - a test suite
 * @return {Object}       - an object representing the xml node
 */
MochaJUnitReporter.prototype.getTestsuiteData = function(suite) {
  var antMode = this._options.antMode;

  var _attr =  {
    name: this._generateSuiteTitle(suite),
    timestamp: new Date().toISOString().slice(0,-5),
    tests: suite.tests.length
  };
  var testSuite = { testsuite: [ { _attr: _attr } ] };

  if(suite.file) {
    testSuite.testsuite[0]._attr.file =  suite.file;
  }

  var properties = generateProperties(this._options);
  if (properties.length || antMode) {
    testSuite.testsuite.push({
      properties: properties
    });
  }

  if (antMode) {
    _attr.package = _attr.name;
    _attr.hostname = this._options.antHostname;
    _attr.id = this._antId;
    _attr.errors = 0;
    this._antId += 1;
  }

  return testSuite;
};

/**
 * Produces an xml config for a given test case.
 * @param {object} test - test case
 * @param {object} err - if test failed, the failure object
 * @returns {object}
 */
MochaJUnitReporter.prototype.getTestcaseData = function(test, err) {
  var jenkinsMode = this._options.jenkinsMode;
  var flipClassAndName = this._options.testCaseSwitchClassnameAndName;
  var name = stripAnsi(jenkinsMode ? getJenkinsClassname(test) : test.fullTitle());
  var classname = stripAnsi(test.title);
  var testcase = {
    testcase: [{
      _attr: {
        name: flipClassAndName ? classname : name,
        time: (typeof test.duration === 'undefined') ? 0 : test.duration / 1000,
        classname: flipClassAndName ? name : classname
      }
    }]
  };

  // We need to merge console.logs and attachments into one <system-out> -
  //  see JUnit schema (only accepts 1 <system-out> per test).
  var systemOutLines = [];
  if (this._options.outputs && (test.consoleOutputs && test.consoleOutputs.length > 0)) {
    systemOutLines = systemOutLines.concat(test.consoleOutputs);
  }
  if (this._options.attachments && test.attachments && test.attachments.length > 0) {
    systemOutLines = systemOutLines.concat(test.attachments.map(
      function (file) {
        return '[[ATTACHMENT|' + file + ']]';
      }
    ));
  }
  if (systemOutLines.length > 0) {
    testcase.testcase.push({'system-out': this.removeInvalidCharacters(stripAnsi(systemOutLines.join('\n')))});
  }

  if (this._options.outputs && (test.consoleErrors && test.consoleErrors.length > 0)) {
    testcase.testcase.push({'system-err': this.removeInvalidCharacters(stripAnsi(test.consoleErrors.join('\n')))});
  }

  if (err) {
    var message;
    if (err.message && typeof err.message.toString === 'function') {
      message = err.message + '';
    } else if (typeof err.inspect === 'function') {
      message = err.inspect() + '';
    } else {
      message = '';
    }
    var failureMessage = err.stack || message;
    var failureElement = {
      _attr: {
        message: this.removeInvalidCharacters(message) || '',
        type: err.name || ''
      },
      _cdata: this.removeInvalidCharacters(failureMessage)
    };

    testcase.testcase.push({failure: failureElement});
  }
  return testcase;
};

/**
 * @param {string} input
 * @returns {string} without invalid characters
 */
MochaJUnitReporter.prototype.removeInvalidCharacters = function(input){
  if (!input) {
    return input;
  }
  return input.replace(INVALID_CHARACTERS_REGEX, '');
};

/**
 * Writes xml to disk and ouputs content if "toConsole" is set to true.
 * @param {Array.<Object>} testsuites - a list of xml configs
 */
MochaJUnitReporter.prototype.flush = function(testsuites){
  var xml = this.getXml(testsuites);

  this.writeXmlToDisk(xml, this._options.mochaFile);

  if (this._options.toConsole === true) {
    console.log(xml); // eslint-disable-line no-console
  }
};

/**
 * Produces an XML string from the given test data.
 * @param {Array.<Object>} testsuites - a list of xml configs
 * @returns {string}
 */
MochaJUnitReporter.prototype.getXml = function(testsuites) {
  var totalSuitesTime = 0;
  var totalTests = 0;
  var stats = this._runner.stats;
  var antMode = this._options.antMode;
  var hasProperties = (!!this._options.properties) || antMode;

  testsuites.forEach(function(suite) {
    var _suiteAttr = suite.testsuite[0]._attr;
    // testsuite is an array: [attrs, properties?, testcase, testcase, …]
    // we want to make sure that we are grabbing test cases at the correct index
    var _casesIndex = hasProperties ? 2 : 1;
    var _cases = suite.testsuite.slice(_casesIndex);
    var missingProps;

    _suiteAttr.failures = 0;
    _suiteAttr.time = 0;
    _suiteAttr.skipped = 0;

    _cases.forEach(function(testcase) {
      var lastNode = testcase.testcase[testcase.testcase.length - 1];

      _suiteAttr.skipped += Number('skipped' in lastNode);
      _suiteAttr.failures += Number('failure' in lastNode);
      _suiteAttr.time += testcase.testcase[0]._attr.time;
    });

    if (antMode) {
      missingProps = ['system-out', 'system-err'];
      suite.testsuite.forEach(function(item) {
        missingProps = missingProps.filter(function(prop) {
          return !item[prop];
        });
      });
      missingProps.forEach(function(prop) {
        var obj = {};
        obj[prop] = [];
        suite.testsuite.push(obj);
      });
    }

    if (!_suiteAttr.skipped) {
      delete _suiteAttr.skipped;
    }

    totalSuitesTime += _suiteAttr.time;
    totalTests += _suiteAttr.tests;
  });

  if (!antMode) {
    var rootSuite = {
      _attr: {
        name: this._options.testsuitesTitle,
        time: totalSuitesTime,
        tests: totalTests,
        failures: stats.failures
      }
    };
    if (stats.pending) {
      rootSuite._attr.skipped = stats.pending;
    }
    testsuites = [ rootSuite ].concat(testsuites);
  }

  return xml({ testsuites: testsuites }, { declaration: true, indent: '  ' });
};

/**
 * Writes a JUnit test report XML document.
 * @param {string} xml - xml string
 * @param {string} filePath - path to output file
 */
MochaJUnitReporter.prototype.writeXmlToDisk = function(xml, filePath){
  if (filePath) {
    if (filePath.indexOf('[hash]') !== -1) {
      filePath = filePath.replace('[hash]', md5(xml));
    }

    debug('writing file to', filePath);
    mkdirp.sync(path.dirname(filePath));

    try {
        fs.writeFileSync(filePath, xml, 'utf-8');
    } catch (exc) {
        debug('problem writing results: ' + exc);
    }
    debug('results written successfully');
  }
};
<|endoftext|>


<commit_before>"use strict"
let SMA                        = require('./lib/moving_averages/SMA.js');
let EMA                        = require('./lib/moving_averages/EMA.js');
let WMA                        = require('./lib/moving_averages/WMA.js');
let WEMA                       = require('./lib/moving_averages/WEMA.js');
let MACD                       = require('./lib/moving_averages/MACD.js');
let RSI                        = require('./lib/oscillators/RSI.js');
let BollingerBands             = require('./lib/volatility/BollingerBands.js');
let ADX                        = require('./lib/directionalmovement/ADX.js');
let ATR                        = require('./lib/directionalmovement/ATR.js');
let ROC                        = require('./lib/momentum/ROC.js');
let KST                        = require('./lib/momentum/KST.js');
let Stochastic                 = require('./lib/momentum/Stochastic.js');
let WilliamsR                  = require('./lib/momentum/WilliamsR.js');
let ADL                        = require('./lib/volume/ADL.js');
let OBV                        = require('./lib/volume/OBV.js');
let TRIX                       = require('./lib/momentum/TRIX.js');

let AbandonedBaby              = require('./lib/candlestick/AbandonedBaby.js');
let Doji                       = require('./lib/candlestick/Doji.js');
let BearishEngulfingPattern    = require('./lib/candlestick/BearishEngulfingPattern.js');
let BullishEngulfingPattern    = require('./lib/candlestick/BullishEngulfingPattern.js');
let DarkCloudCover             = require('./lib/candlestick/DarkCloudCover.js');
let DownsideTasukiGap          = require('./lib/candlestick/DownsideTasukiGap.js');
let DragonFlyDoji              = require('./lib/candlestick/DragonFlyDoji');
let GraveStoneDoji             = require('./lib/candlestick/GraveStoneDoji');
let Harami                     = require('./lib/candlestick/Harami');
let HaramiCross                = require('./lib/candlestick/HaramiCross');
let EveningDojiStar            = require('./lib/candlestick/EveningDojiStar');
let EveningStar                = require('./lib/candlestick/EveningStar');
let MorningDojiStar            = require('./lib/candlestick/MorningDojiStar');
let MorningStar                = require('./lib/candlestick/MorningStar');
let Marubozu                   = require('./lib/candlestick/Marubozu');
let PiercingLine               = require('./lib/candlestick/PiercingLine');
let SpinningTop                = require('./lib/candlestick/SpinningTop');
let ThreeBlackCrows            = require('./lib/candlestick/ThreeBlackCrows');
let ThreeWhiteSoldiers         = require('./lib/candlestick/ThreeWhiteSoldiers');

let Indicators;

global.AvailableIndicators = [];

module.exports = Indicators = {
  SMA                          : SMA,
  EMA                          : EMA,
  MACD                         : MACD,
  RSI                          : RSI,
  WMA                          : WMA,
  BollingerBands               : BollingerBands,
  ATR                          : ATR,
  ADX                          : ADX,
  WEMA                         : WEMA,
  ROC                          : ROC,
  KST                          : KST,
  Stochastic                   : Stochastic,
  WilliamsR                    : WilliamsR,
  ADL                          : ADL,
  OBV                          : OBV,
  TRIX                         : TRIX,
  AbandonedBaby                : new AbandonedBaby(),
  Doji                         : new Doji(),
  BearishEngulfingPattern      : new BearishEngulfingPattern(),
  BullishEngulfingPattern      : new BullishEngulfingPattern(),
  DarkCloudCover               : new DarkCloudCover(),
  DownsideTasukiGap            : new DownsideTasukiGap(),
  DragonFlyDoji                : new DragonFlyDoji(),
  GraveStoneDoji               : new GraveStoneDoji(),
  Harami                       : new Harami(),
  HaramiCross                  : new HaramiCross(),
  EveningDojiStars             : new EveningDojiStars(),
  EveningStar                  : new EveningStar(),
  Marubozu                     : new Marubozu(),
  PiercingLine                 : new PiercingLine(),
  SpinningTop                  : new SpinningTop(),
  MorningStar                  : new MorningStar(),
  MorningDojiStar              : new MorningDojiStar(),
  ThreeBlackCrows              : new ThreeBlackCrows(),
  ThreeWhiteSoldiers           : new ThreeWhiteSoldiers(),

};

Object.assign(global, Indicators);

for(let indicator in Indicators){
  var indicatorName = indicator.toLowerCase();
  global.AvailableIndicators.push(indicator);
  let fn            = Indicators[indicator].calculate || Indicators[indicator].hasPattern
  global[indicatorName] = fn;
};
<commit_msg>Fix typo of EveningDojiStar<commit_after>"use strict"
let SMA                        = require('./lib/moving_averages/SMA.js');
let EMA                        = require('./lib/moving_averages/EMA.js');
let WMA                        = require('./lib/moving_averages/WMA.js');
let WEMA                       = require('./lib/moving_averages/WEMA.js');
let MACD                       = require('./lib/moving_averages/MACD.js');
let RSI                        = require('./lib/oscillators/RSI.js');
let BollingerBands             = require('./lib/volatility/BollingerBands.js');
let ADX                        = require('./lib/directionalmovement/ADX.js');
let ATR                        = require('./lib/directionalmovement/ATR.js');
let ROC                        = require('./lib/momentum/ROC.js');
let KST                        = require('./lib/momentum/KST.js');
let Stochastic                 = require('./lib/momentum/Stochastic.js');
let WilliamsR                  = require('./lib/momentum/WilliamsR.js');
let ADL                        = require('./lib/volume/ADL.js');
let OBV                        = require('./lib/volume/OBV.js');
let TRIX                       = require('./lib/momentum/TRIX.js');

let AbandonedBaby              = require('./lib/candlestick/AbandonedBaby.js');
let Doji                       = require('./lib/candlestick/Doji.js');
let BearishEngulfingPattern    = require('./lib/candlestick/BearishEngulfingPattern.js');
let BullishEngulfingPattern    = require('./lib/candlestick/BullishEngulfingPattern.js');
let DarkCloudCover             = require('./lib/candlestick/DarkCloudCover.js');
let DownsideTasukiGap          = require('./lib/candlestick/DownsideTasukiGap.js');
let DragonFlyDoji              = require('./lib/candlestick/DragonFlyDoji');
let GraveStoneDoji             = require('./lib/candlestick/GraveStoneDoji');
let Harami                     = require('./lib/candlestick/Harami');
let HaramiCross                = require('./lib/candlestick/HaramiCross');
let EveningDojiStar            = require('./lib/candlestick/EveningDojiStar');
let EveningStar                = require('./lib/candlestick/EveningStar');
let MorningDojiStar            = require('./lib/candlestick/MorningDojiStar');
let MorningStar                = require('./lib/candlestick/MorningStar');
let Marubozu                   = require('./lib/candlestick/Marubozu');
let PiercingLine               = require('./lib/candlestick/PiercingLine');
let SpinningTop                = require('./lib/candlestick/SpinningTop');
let ThreeBlackCrows            = require('./lib/candlestick/ThreeBlackCrows');
let ThreeWhiteSoldiers         = require('./lib/candlestick/ThreeWhiteSoldiers');

let Indicators;

global.AvailableIndicators = [];

module.exports = Indicators = {
  SMA                          : SMA,
  EMA                          : EMA,
  MACD                         : MACD,
  RSI                          : RSI,
  WMA                          : WMA,
  BollingerBands               : BollingerBands,
  ATR                          : ATR,
  ADX                          : ADX,
  WEMA                         : WEMA,
  ROC                          : ROC,
  KST                          : KST,
  Stochastic                   : Stochastic,
  WilliamsR                    : WilliamsR,
  ADL                          : ADL,
  OBV                          : OBV,
  TRIX                         : TRIX,
  AbandonedBaby                : new AbandonedBaby(),
  Doji                         : new Doji(),
  BearishEngulfingPattern      : new BearishEngulfingPattern(),
  BullishEngulfingPattern      : new BullishEngulfingPattern(),
  DarkCloudCover               : new DarkCloudCover(),
  DownsideTasukiGap            : new DownsideTasukiGap(),
  DragonFlyDoji                : new DragonFlyDoji(),
  GraveStoneDoji               : new GraveStoneDoji(),
  Harami                       : new Harami(),
  HaramiCross                  : new HaramiCross(),
  EveningDojiStar              : new EveningDojiStar(),
  EveningStar                  : new EveningStar(),
  Marubozu                     : new Marubozu(),
  PiercingLine                 : new PiercingLine(),
  SpinningTop                  : new SpinningTop(),
  MorningStar                  : new MorningStar(),
  MorningDojiStar              : new MorningDojiStar(),
  ThreeBlackCrows              : new ThreeBlackCrows(),
  ThreeWhiteSoldiers           : new ThreeWhiteSoldiers(),

};

Object.assign(global, Indicators);

for(let indicator in Indicators){
  var indicatorName = indicator.toLowerCase();
  global.AvailableIndicators.push(indicator);
  let fn            = Indicators[indicator].calculate || Indicators[indicator].hasPattern
  global[indicatorName] = fn;
};
<|endoftext|>


<commit_before>// Setup basic express server
var fs = require('fs');
var express = require('express');
var app = express();
var options = {
    key: fs.readFileSync('/etc/ssl/rtloc.tk/private.key'),
    cert: fs.readFileSync('/etc/ssl/rtloc.tk/public.crt'),
    ca: fs.readFileSync('/etc/ssl/rtloc.tk/ca.pem')
}
var server = require('https').createServer(options,app);
var io = require('socket.io')(server);
var sPort = 443;//process.env.PORT || 443;
var nPort = 80;//process.env.PORT || 80;
var http = require('http');

var allusers = new Array();

server.listen(sPort, function () {
  console.log('Server listening at port %d', sPort);
});

var httpserver = http.createServer(function(req, res) {
  if(req.url == '/track'){
    res.write('
');
    res.write('
Username	Latitude	Longitude
');
    for ( var tuser in allusers ){
      res.write('
');
      res.write('' + alluser[tuser].unm + '	');
      res.write('' + alluser[tuser].lat + '	');
      res.write('' + alluser[tuser].lng + '	');
      res.write('
');
    }
    res.write('
');
  }
  else{
    res.writeHead(302, {'Location': 'https://rtloc.tk' + req.url});
  }
  res.end();
});

httpserver.listen(nPort, function () {
  console.log('Server listening at port %d', nPort);
});

// Routing
app.use(express.static(__dirname + '/public'));

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new location', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new location', {
      uname: data.uname,
      tyLat: data.tyLat,
      tyLng: data.tyLng
    });
    //console.log(data.uname+"@"+data.tyLat+","+data.tyLng);
    if(!( data.uname in allusers )){
      console.log("Creating " + data.uname + "...");
      allusers[data.uname] = new Object();
      allusers[data.uname].lat = data.tyLat;
      allusers[data.uname].lng = data.tyLng;
      allusers[data.uname].unm = data.uname;
      //allusers[data.uname] = node;
    }else{
      allusers[data.uname].lat = data.tyLat;
      allusers[data.uname].lng = data.tyLng;
    }
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });

});
<commit_msg>Automatic commit from server<commit_after>// Setup basic express server
var fs = require('fs');
var express = require('express');
var app = express();
var options = {
    key: fs.readFileSync('/etc/ssl/rtloc.tk/private.key'),
    cert: fs.readFileSync('/etc/ssl/rtloc.tk/public.crt'),
    ca: fs.readFileSync('/etc/ssl/rtloc.tk/ca.pem')
}
var server = require('https').createServer(options,app);
var io = require('socket.io')(server);
var sPort = 443;//process.env.PORT || 443;
var nPort = 80;//process.env.PORT || 80;
var http = require('http');

var allusers = new Array();

server.listen(sPort, function () {
  console.log('Server listening at port %d', sPort);
});

var httpserver = http.createServer(function(req, res) {
  if(req.url == '/track'){
    res.write('
');
    res.write('
Username	Latitude	Longitude
');
    for ( var tuser in allusers ){
      res.write('
');
      res.write('' + allusers[tuser].unm + '	');
      res.write('' + allusers[tuser].lat + '	');
      res.write('' + allusers[tuser].lng + '	');
      res.write('
');
    }
    res.write('
');
  }
  else{
    res.writeHead(302, {'Location': 'https://rtloc.tk' + req.url});
  }
  res.end();
});

httpserver.listen(nPort, function () {
  console.log('Server listening at port %d', nPort);
});

// Routing
app.use(express.static(__dirname + '/public'));

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new location', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new location', {
      uname: data.uname,
      tyLat: data.tyLat,
      tyLng: data.tyLng
    });
    //console.log(data.uname+"@"+data.tyLat+","+data.tyLng);
    if(!( data.uname in allusers )){
      console.log("Creating " + data.uname + "...");
      allusers[data.uname] = new Object();
      allusers[data.uname].lat = data.tyLat;
      allusers[data.uname].lng = data.tyLng;
      allusers[data.uname].unm = data.uname;
      //allusers[data.uname] = node;
    }else{
      allusers[data.uname].lat = data.tyLat;
      allusers[data.uname].lng = data.tyLng;
    }
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });

});
<|endoftext|>


<commit_before>var rc = require('./Ningfile')
var cluster = require('cluster')
var os = require('os')
var numCPUs = os.cpus().length

if (cluster.isMaster) {
    var Monitor = require('./middleware/monitor').Monitor;
    var monitor = new Monitor({
        interval: 6000 * 60,
        pid: process.pid
    });
    monitor.on('os', function(data){

    });
    var pid = process.pid
    var log = function (info){
        console.log( (new Date).toISOString() + ' Master ' + pid + '\t| ' + info )
    }
    var killWorker = function(worker, done){
        // Because long living server connections may block workers from disconnecting,
        // it may be useful to send a message, so application specific actions may be taken to close them.
        // It also may be useful to implement a timeout, killing a worker if the disconnect event
        // has not been emitted after some time.
        worker.send('shutdown');
        worker.disconnect();
        var timeout = setTimeout(function() {
            worker.kill()
        }, 3000);
        worker.on('disconnect', function() {
            clearTimeout(timeout)
            done()
        });
    }
    var killWorkers = function (restart, done){
        var workers = Object.keys(cluster.workers);
        var kill = function(i) {
            if (i == workers.length) {
                return done();
            }
            var workerPid = cluster.workers[workers[i]].process.pid;
            log('Killing worker ' + workerPid);
            killWorker(cluster.workers[workers[i]], function(){
                log('Worker ' + workerPid + ' shutdown complete');
                i++;
                if(restart){
                    var newWorker = cluster.fork();
                    newWorker.on('listening', function() {
                        log('Replacement worker ' + newWorker.process.pid + ' online');
                        kill(i);
                    });
                }else{
                    kill(i)
                }
            });

        }
        kill(0)
    }

    // Put pidfile to logs directory
    var pidfile = require('path').join(__dirname, 'logs/ning.pid')
    require('fs').writeFileSync(pidfile, pid);

    cluster.on('listening', function(worker, address) {
        log('Worker ' + worker.process.pid + ' listening ' + address.address + ':' + address.port)
    })

    // Restart workers without downtime
    process.on('SIGHUP', function() {
        log('Got SIGHUP signal, restarting workers')

        // Delete the cached module, so we can reload the app
        delete require.cache[require.resolve("./index")]

        killWorkers(true, function(){
            log('Workers success restarted')
        })
    });

    process.on('SIGQUIT', function(){
        log('Got SIGQUIT signal, killing master and workers')
        killWorkers(false, function(){
            log('Workers success killed')
            process.exit()
        })

        // Normally below code should no opportunity to execution
        setTimeout(function() {
            log("Could not close connections in time, forcefully shutting down");
            process.exit()
        }, 1000 * 10);

    });

    cluster.on('exit', function(worker, code, signal) {
        if(worker.suicide === true) {
            log('Worker ' + worker.process.pid + ' was just suicide')
        }else if(code !== 0) {
            log('Worker ' + worker.process.pid + ' died with error code: ' + code)
        }else {
            log('Worker ' + worker.process.pid + ' died normally')
        }

        if(signal) {
            log('Worker ' + worker.process.pid + ' was killed by signal: ' + signal)
        }
    })

    if (rc.instances == 'max') {
        rc.instances = numCPUs
    }
    // Fork workers.
    for (var i = 0; i < Number(rc.instances); i++) {
        cluster.fork()
    }
} else {
    // Workers can share any TCP connection
    // In this case its a HTTP server
    var express = require('express')
    var app = express()
    var path = require('path')
    var node_modules = rc.node_modules
    var server
    var pid = process.pid
    var log = function (info){
        console.log( (new Date).toISOString() + ' Worker ' + pid + '\t| ' + info )
    }

    if(node_modules) {
        node_modules = [].concat(node_modules).map(function(p){
            return path.resolve(p)
        })
        module.paths = module.paths.concat(node_modules)
    }

    app.param('mod', function(req, res, next, name){
        try{
            var mod = require(name)
            req.mod = mod
            next()
        }catch(err){
            next(err);
        }
    })

    app.all('/cgi-bin/:mod', function(req, res, next){
        req.mod(req, res, next)
    })

    process.on('message', function(msg) {
        if(msg === 'shutdown') {
            log("Received kill signal, shutting down gracefully");
            server.close(function() {
                log("Closed out remaining connections");
                process.exit(0)
            });
            // Normally below code should no opportunity to execution
            setTimeout(function() {
                log("Could not close connections in time, forcefully shutting down");
                process.exit()
            }, 2000);
        }

    })

    server = app.listen(rc.port)
}
<commit_msg>监控中间件传参修改<commit_after>var rc = require('./Ningfile')
var cluster = require('cluster')
var os = require('os')
var numCPUs = os.cpus().length

if (cluster.isMaster) {
    var Monitor = require('./middleware/monitor').Monitor;

    var monitor = new Monitor({
        interval: 6000 * 60,
        cluster: cluster
    });

    monitor.on('os', function(data){

    });

    monitor.on('process', function(data){

    });

    var pid = process.pid
    var log = function (info){
        console.log( (new Date).toISOString() + ' Master ' + pid + '\t| ' + info )
    }
    var killWorker = function(worker, done){
        // Because long living server connections may block workers from disconnecting,
        // it may be useful to send a message, so application specific actions may be taken to close them.
        // It also may be useful to implement a timeout, killing a worker if the disconnect event
        // has not been emitted after some time.
        worker.send('shutdown');
        worker.disconnect();
        var timeout = setTimeout(function() {
            worker.kill()
        }, 3000);
        worker.on('disconnect', function() {
            clearTimeout(timeout)
            done()
        });
    }
    var killWorkers = function (restart, done){
        var workers = Object.keys(cluster.workers);
        var kill = function(i) {
            if (i == workers.length) {
                return done();
            }
            var workerPid = cluster.workers[workers[i]].process.pid;
            log('Killing worker ' + workerPid);
            killWorker(cluster.workers[workers[i]], function(){
                log('Worker ' + workerPid + ' shutdown complete');
                i++;
                if(restart){
                    var newWorker = cluster.fork();
                    newWorker.on('listening', function() {
                        log('Replacement worker ' + newWorker.process.pid + ' online');
                        kill(i);
                    });
                }else{
                    kill(i)
                }
            });

        }
        kill(0)
    }

    // Put pidfile to logs directory
    var pidfile = require('path').join(__dirname, 'logs/ning.pid')
    require('fs').writeFileSync(pidfile, pid);

    cluster.on('listening', function(worker, address) {
        log('Worker ' + worker.process.pid + ' listening ' + address.address + ':' + address.port)
    })

    // Restart workers without downtime
    process.on('SIGHUP', function() {
        log('Got SIGHUP signal, restarting workers')

        // Delete the cached module, so we can reload the app
        delete require.cache[require.resolve("./index")]

        killWorkers(true, function(){
            log('Workers success restarted')
        })
    });

    process.on('SIGQUIT', function(){
        log('Got SIGQUIT signal, killing master and workers')
        killWorkers(false, function(){
            log('Workers success killed')
            process.exit()
        })

        // Normally below code should no opportunity to execution
        setTimeout(function() {
            log("Could not close connections in time, forcefully shutting down");
            process.exit()
        }, 1000 * 10);

    });

    cluster.on('exit', function(worker, code, signal) {
        if(worker.suicide === true) {
            log('Worker ' + worker.process.pid + ' was just suicide')
        }else if(code !== 0) {
            log('Worker ' + worker.process.pid + ' died with error code: ' + code)
        }else {
            log('Worker ' + worker.process.pid + ' died normally')
        }

        if(signal) {
            log('Worker ' + worker.process.pid + ' was killed by signal: ' + signal)
        }
    })

    if (rc.instances == 'max') {
        rc.instances = numCPUs
    }
    // Fork workers.
    for (var i = 0; i < Number(rc.instances); i++) {
        cluster.fork()
    }
} else {
    // Workers can share any TCP connection
    // In this case its a HTTP server
    var express = require('express')
    var app = express()
    var path = require('path')
    var node_modules = rc.node_modules
    var server
    var pid = process.pid
    var log = function (info){
        console.log( (new Date).toISOString() + ' Worker ' + pid + '\t| ' + info )
    }

    if(node_modules) {
        node_modules = [].concat(node_modules).map(function(p){
            return path.resolve(p)
        })
        module.paths = module.paths.concat(node_modules)
    }

    app.param('mod', function(req, res, next, name){
        try{
            var mod = require(name)
            req.mod = mod
            next()
        }catch(err){
            next(err);
        }
    })

    app.all('/cgi-bin/:mod', function(req, res, next){
        req.mod(req, res, next)
    })

    process.on('message', function(msg) {
        if(msg === 'shutdown') {
            log("Received kill signal, shutting down gracefully");
            server.close(function() {
                log("Closed out remaining connections");
                process.exit(0)
            });
            // Normally below code should no opportunity to execution
            setTimeout(function() {
                log("Could not close connections in time, forcefully shutting down");
                process.exit()
            }, 2000);
        }

    })

    server = app.listen(rc.port)
}
<|endoftext|>


<commit_before>import { computed, action, observable } from 'mobx';
import _ from 'lodash';

import VJF from './validators/VJF'; // Vanilla JavaScript Functions
import SVK from './validators/SVK'; // Json Schema Validation Keywords
import DVR from './validators/DVR'; // Declarative Validation Rules

export default class Validator {

  promises = [];

  options = {};

  schema = {};

  plugins = {
    vjf: true,
    svk: false,
    dvr: false,
  };

  validators = {
    vjf: null,
    svk: null,
    dvr: null,
  };

  @observable $genericErrorMessage = null;

  constructor(obj = {}) {
    this.assignInitData(obj);
    this.initializePlugins();
  }

  assignInitData({ options = {}, plugins = {}, schema = {} }) {
    _.merge(this.plugins, plugins);
    this.options = options;
    this.schema = schema;
  }

  initializePlugins() {
    /**
     Declarative Validation Rules
    */
    if (this.plugins.dvr) {
      this.validators.dvr = new DVR(this.plugins.dvr, {
        promises: this.promises,
        options: this.options,
      });
    }

    /**
      Vanilla JavaScript Functions
    */
    if (this.plugins.vjf) {
      this.validators.vjf = new VJF(this.plugins.vjf, {
        promises: this.promises,
        options: this.options,
      });
    }

    /**
     Schema Validation Keywords
    */
    if (this.plugins.svk) {
      this.validators.svk = new SVK(this.plugins.svk, {
        promises: this.promises,
        options: this.options,
        schema: this.schema,
      });
    }
  }

  @action
  validateAll({ form, showErrors = true, related = false }) {
    // reset generic error message
    this.resetGenericError();
    // validate all fields and nested fields
    this.validateAllDeep(form, form.fields, showErrors, related);
  }

  validateAllDeep(form, fields, showErrors, related) {
    if (!fields.size) return;

    fields.forEach((field) => {
      this.validateField({ form, field, path: field.path, showErrors, related });
      // recursive validation for nested fields
      if (field.fields.size) {
        this.validateAllDeep(form, field.fields, showErrors, related);
      }
    });
  }

  @action
  validateField({ form = null, field = null, path, showErrors = true, related = false }) {
    const $field = field || form.select(path);
    // reset field validation
    $field.resetValidation();
    // get all validators
    const { svk, dvr, vjf } = this.validators;
    // validate with vanilla js functions (vjf)
    if (vjf) vjf.validateField($field, form);
    // validate with json schema validation keywords (dvr)
    if (dvr) dvr.validateField($field, form);
    // validate with json schema validation keywords (svk)
    if (svk) svk.validateField($field);
    // send error to the view
    $field.showErrors(showErrors);
    // related validation
    if (related) this.relatedFieldValidation(form, $field, showErrors);
  }

  relatedFieldValidation(form, field, showErrors) {
    /*
      validate 'related' fields if specified
      and related validation allowed (recursive)
    */
    if (!_.isEmpty(field.related)) {
      _.each(field.related, path =>
        this.validateField({ form, path, showErrors, related: false }));
    }
  }

  @computed get genericErrorMessage() {
    return this.options.get('alwaysShowDefaultError')
      ? (this.$genericErrorMessage || this.options.get('defaultGenericError'))
      : this.$genericErrorMessage;
  }

  getDefaultErrorMessage() {
    // set defaultGenericError message from options
    const $default = this.options.get('defaultGenericError');
    if (_.isString($default)) return $default;
    return 'The form is invalid';
  }

  @action
  resetGenericError() {
    this.$genericErrorMessage = null;
  }

  @action
  invalidate(message = null) {
    // set custom genericErrorMessage if provided
    if (_.isString(message)) {
      this.$genericErrorMessage = message;
      return;
    }
    // if no string provided, show default error.
    this.$genericErrorMessage = this.getDefaultErrorMessage();
  }
}
<commit_msg>refactor:<commit_after>import { computed, action, observable } from 'mobx';
import _ from 'lodash';

import VJF from './validators/VJF'; // Vanilla JavaScript Functions
import SVK from './validators/SVK'; // Json Schema Validation Keywords
import DVR from './validators/DVR'; // Declarative Validation Rules

export default class Validator {

  promises = [];

  options = {};

  schema = {};

  plugins = {
    vjf: true,
    dvr: false,
    svk: false,
  };

  validators = {
    vjf: null,
    dvr: null,
    svk: null,
  };

  @observable $genericErrorMessage = null;

  constructor(obj = {}) {
    this.assignInitData(obj);
    this.initializePlugins();
  }

  assignInitData({ options = {}, plugins = {}, schema = {} }) {
    _.merge(this.plugins, plugins);
    this.options = options;
    this.schema = schema;
  }

  initializePlugins() {
    _.map({
      vjf: VJF,
      dvr: DVR,
      svk: SVK,
    }, (Class, key) => this.plugins[key] &&
      (this.validators[key] = new Class(this.plugins[key], {
        schema: (key === 'svk') ? this.schema : null,
        promises: this.promises,
        options: this.options,
      })));
  }

  @action
  validateAll({ form, showErrors = true, related = false }) {
    // reset generic error message
    this.resetGenericError();
    // validate all fields and nested fields
    form.forEach(field =>
      this.validateField({
        path: field.path,
        form,
        field,
        showErrors,
        related,
      }));
  }

  @action
  validateField({ form = null, field = null, path, showErrors = true, related = false }) {
    const $field = field || form.select(path);
    // reset field validation
    $field.resetValidation();
    // get all validators
    const { svk, dvr, vjf } = this.validators;
    // validate with vanilla js functions (vjf)
    if (vjf) vjf.validateField($field, form);
    // validate with json schema validation keywords (dvr)
    if (dvr) dvr.validateField($field, form);
    // validate with json schema validation keywords (svk)
    if (svk) svk.validateField($field);
    // send error to the view
    $field.showErrors(showErrors);
    // related validation
    if (related) this.relatedFieldValidation(form, $field, showErrors);
  }

  /**
    Validate 'related' fields if specified
    and related validation allowed (recursive)
  */
  relatedFieldValidation(form, field, showErrors) {
    if (!field.related || !field.related.length) return;

    _.each(field.related, path =>
      this.validateField({ form, path, showErrors, related: false }));
  }

  @computed get genericErrorMessage() {
    return this.options.get('alwaysShowDefaultError')
      ? (this.$genericErrorMessage || this.options.get('defaultGenericError'))
      : this.$genericErrorMessage;
  }

  getDefaultErrorMessage() {
    // set defaultGenericError message from options
    const $default = this.options.get('defaultGenericError');
    if (_.isString($default)) return $default;
    return 'The form is invalid';
  }

  @action
  resetGenericError() {
    this.$genericErrorMessage = null;
  }

  @action
  invalidate(message = null) {
    // set custom genericErrorMessage if provided
    if (_.isString(message)) {
      this.$genericErrorMessage = message;
      return;
    }
    // if no string provided, show default error.
    this.$genericErrorMessage = this.getDefaultErrorMessage();
  }
}
<|endoftext|>