<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

var Memcached = require('memcached')
var restify = require('restify')
var config = require('../config')
var log = require('../log')(config.logLevel, 'customs-server')
var packageJson = require('../package.json')

var LIFETIME = config.recordLifetimeSeconds
var BLOCK_INTERVAL_MS = config.blockIntervalSeconds * 1000
var RATE_LIMIT_INTERVAL_MS = config.rateLimitIntervalSeconds * 1000

var IpEmailRecord = require('../ip_email_record')(RATE_LIMIT_INTERVAL_MS, config.maxBadLogins)
var EmailRecord = require('../email_record')(RATE_LIMIT_INTERVAL_MS, BLOCK_INTERVAL_MS, config.maxEmails)
var IpRecord = require('../ip_record')(BLOCK_INTERVAL_MS)

var P = require('bluebird')
P.promisifyAll(Memcached.prototype)

function shutdown() {
  process.nextTick(process.exit)
}

if (process.env.ASS_CODE_COVERAGE) {
  process.on('SIGINT', shutdown)
}

var mc = new Memcached(
  config.memcached,
  {
    timeout: 500,
    retries: 1,
    retry: 1000,
    reconnect: 1000,
    idle: 30000,
    namespace: 'fxa~'
  }
)

var api = restify.createServer()
api.use(restify.bodyParser())

function ignore(err) {
  log.error({ op: 'memcachedError', err: err })
}

function fetchRecords(email, ip) {
  return P.all(
    [
      // get records and ignore errors by returning a new record
      mc.getAsync(email).then(EmailRecord.parse, EmailRecord.parse),
      mc.getAsync(ip).then(IpRecord.parse, IpRecord.parse),
      mc.getAsync(ip + email).then(IpEmailRecord.parse, IpEmailRecord.parse)
    ]
  )
}

function setRecords(email, ip, emailRecord, ipRecord, ipEmailRecord) {
  return P.all(
    [
      // store records ignoring errors
      mc.setAsync(email, emailRecord, LIFETIME).caught(ignore),
      mc.setAsync(ip, ipRecord, LIFETIME).caught(ignore),
      mc.setAsync(ip + email, ipEmailRecord, LIFETIME).caught(ignore)
    ]
  )
}

function max(prev, cur) {
  return Math.max(prev, cur)
}

api.post(
  '/check',
  function (req, res, next) {
    var email = req.body.email
    var ip = req.body.ip
    var action = req.body.action

    if (!email || !ip || !action) {
      var err = {code: 'MissingParameters', message: 'email, ip and action are all required'}
      log.error({ op: 'request.failedLoginAttempt', email: email, ip: ip, action: action, err: err })
      res.send(500, err)
      return next()
    }

    fetchRecords(email, ip)
      .spread(
        function (emailRecord, ipRecord, ipEmailRecord) {
          var blockEmail = emailRecord.update(action)
          var blockIpEmail = ipEmailRecord.update(action)
          var blockIp = ipRecord.update()

          if (blockIpEmail && ipEmailRecord.unblockIfReset(emailRecord.pr)) {
            blockIpEmail = 0
          }
          var retryAfter = [blockEmail, blockIpEmail, blockIp].reduce(max)

          return setRecords(email, ip, emailRecord, ipRecord, ipEmailRecord)
            .then(
              function () {
                return {
                  block: retryAfter > 0,
                  retryAfter: retryAfter
                }
              }
            )
        }
      )
      .then(
        function (result) {
          log.info({ op: 'request.check', email: email, ip: ip, action: action, block: result.block })
          res.send(result)
        },
        function (err) {
          log.error({ op: 'request.check', email: email, ip: ip, action: action, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.post(
  '/failedLoginAttempt',
  function (req, res, next) {
    var email = req.body.email
    var ip = req.body.ip
    if (!email || !ip) {
      var err = {code: 'MissingParameters', message: 'email and ip are both required'}
      log.error({ op: 'request.failedLoginAttempt', email: email, ip: ip, err: err })
      res.send(500, err)
      next()
    }

    mc.getAsync(ip + email)
      .then(IpEmailRecord.parse, IpEmailRecord.parse)
      .then(
        function (ipEmailRecord) {
          ipEmailRecord.addBadLogin()
          return mc.setAsync(ip + email, ipEmailRecord, LIFETIME).caught(ignore)
        }
      )
      .then(
        function () {
          log.info({ op: 'request.failedLoginAttempt', email: email, ip: ip })
          res.send({})
        },
        function (err) {
          log.error({ op: 'request.failedLoginAttempt', email: email, ip: ip, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.post(
  '/passwordReset',
  function (req, res, next) {
    var email = req.body.email
    if (!email) {
      var err = {code: 'MissingParameters', message: 'email is required'}
      log.error({ op: 'request.passwordReset', email: email, err: err })
      res.send(500, err)
      next()
    }

    mc.getAsync(email)
      .then(EmailRecord.parse, EmailRecord.parse)
      .then(
        function (emailRecord) {
          emailRecord.passwordReset()
          return mc.setAsync(email, emailRecord, LIFETIME).caught(ignore)
        }
      )
      .then(
        function () {
          log.info({ op: 'request.passwordReset', email: email })
          res.send({})
        },
        function (err) {
          log.error({ op: 'request.passwordReset', email: email, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.post(
  '/blockEmail',
  function (req, res, next) {
    var email = req.body.email
    if (!email) {
      var err = {code: 'MissingParameters', message: 'email is required'}
      log.error({ op: 'request.blockEmail', email: email, err: err })
      res.send(500, err)
      next()
    }

    mc.getAsync(email)
      .then(EmailRecord.parse, EmailRecord.parse)
      .then(
        function (emailRecord) {
          emailRecord.block()
          return mc.setAsync(email, emailRecord, LIFETIME).caught(ignore)
        }
      )
      .then(
        function () {
          log.info({ op: 'request.blockEmail', email: email })
          res.send({})
        },
        function (err) {
          log.error({ op: 'request.blockEmail', email: email, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.post(
  '/blockIp',
  function (req, res, next) {
    var ip = req.body.ip
    if (!ip) {
      var err = {code: 'MissingParameters', message: 'ip is required'}
      log.error({ op: 'request.blockIp', ip: ip, err: err })
      res.send(500, err)
      next()
    }

    mc.getAsync(ip)
      .then(IpRecord.parse, IpRecord.parse)
      .then(
        function (ipRecord) {
          ipRecord.block()
          return mc.setAsync(ip, ipRecord, LIFETIME).caught(ignore)
        }
      )
      .then(
        function () {
          log.info({ op: 'request.blockIp', ip: ip })
          res.send({})
        },
        function (err) {
          log.error({ op: 'request.blockIp', ip: ip, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.get(
  '/',
  function (req, res, next) {
    res.send({ version: packageJson.version })
    next()
  }
)

api.listen(
  config.port,
  function () {
    log.info({ op: 'listening', port: config.port })
  }
)
<commit_msg>Use catch instead of caught<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

var Memcached = require('memcached')
var restify = require('restify')
var config = require('../config')
var log = require('../log')(config.logLevel, 'customs-server')
var packageJson = require('../package.json')

var LIFETIME = config.recordLifetimeSeconds
var BLOCK_INTERVAL_MS = config.blockIntervalSeconds * 1000
var RATE_LIMIT_INTERVAL_MS = config.rateLimitIntervalSeconds * 1000

var IpEmailRecord = require('../ip_email_record')(RATE_LIMIT_INTERVAL_MS, config.maxBadLogins)
var EmailRecord = require('../email_record')(RATE_LIMIT_INTERVAL_MS, BLOCK_INTERVAL_MS, config.maxEmails)
var IpRecord = require('../ip_record')(BLOCK_INTERVAL_MS)

var P = require('bluebird')
P.promisifyAll(Memcached.prototype)

function shutdown() {
  process.nextTick(process.exit)
}

if (process.env.ASS_CODE_COVERAGE) {
  process.on('SIGINT', shutdown)
}

var mc = new Memcached(
  config.memcached,
  {
    timeout: 500,
    retries: 1,
    retry: 1000,
    reconnect: 1000,
    idle: 30000,
    namespace: 'fxa~'
  }
)

var api = restify.createServer()
api.use(restify.bodyParser())

function ignore(err) {
  log.error({ op: 'memcachedError', err: err })
}

function fetchRecords(email, ip) {
  return P.all(
    [
      // get records and ignore errors by returning a new record
      mc.getAsync(email).then(EmailRecord.parse, EmailRecord.parse),
      mc.getAsync(ip).then(IpRecord.parse, IpRecord.parse),
      mc.getAsync(ip + email).then(IpEmailRecord.parse, IpEmailRecord.parse)
    ]
  )
}

function setRecords(email, ip, emailRecord, ipRecord, ipEmailRecord) {
  return P.all(
    [
      // store records ignoring errors
      mc.setAsync(email, emailRecord, LIFETIME).catch(ignore),
      mc.setAsync(ip, ipRecord, LIFETIME).catch(ignore),
      mc.setAsync(ip + email, ipEmailRecord, LIFETIME).catch(ignore)
    ]
  )
}

function max(prev, cur) {
  return Math.max(prev, cur)
}

api.post(
  '/check',
  function (req, res, next) {
    var email = req.body.email
    var ip = req.body.ip
    var action = req.body.action

    if (!email || !ip || !action) {
      var err = {code: 'MissingParameters', message: 'email, ip and action are all required'}
      log.error({ op: 'request.failedLoginAttempt', email: email, ip: ip, action: action, err: err })
      res.send(500, err)
      return next()
    }

    fetchRecords(email, ip)
      .spread(
        function (emailRecord, ipRecord, ipEmailRecord) {
          var blockEmail = emailRecord.update(action)
          var blockIpEmail = ipEmailRecord.update(action)
          var blockIp = ipRecord.update()

          if (blockIpEmail && ipEmailRecord.unblockIfReset(emailRecord.pr)) {
            blockIpEmail = 0
          }
          var retryAfter = [blockEmail, blockIpEmail, blockIp].reduce(max)

          return setRecords(email, ip, emailRecord, ipRecord, ipEmailRecord)
            .then(
              function () {
                return {
                  block: retryAfter > 0,
                  retryAfter: retryAfter
                }
              }
            )
        }
      )
      .then(
        function (result) {
          log.info({ op: 'request.check', email: email, ip: ip, action: action, block: result.block })
          res.send(result)
        },
        function (err) {
          log.error({ op: 'request.check', email: email, ip: ip, action: action, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.post(
  '/failedLoginAttempt',
  function (req, res, next) {
    var email = req.body.email
    var ip = req.body.ip
    if (!email || !ip) {
      var err = {code: 'MissingParameters', message: 'email and ip are both required'}
      log.error({ op: 'request.failedLoginAttempt', email: email, ip: ip, err: err })
      res.send(500, err)
      next()
    }

    mc.getAsync(ip + email)
      .then(IpEmailRecord.parse, IpEmailRecord.parse)
      .then(
        function (ipEmailRecord) {
          ipEmailRecord.addBadLogin()
          return mc.setAsync(ip + email, ipEmailRecord, LIFETIME).catch(ignore)
        }
      )
      .then(
        function () {
          log.info({ op: 'request.failedLoginAttempt', email: email, ip: ip })
          res.send({})
        },
        function (err) {
          log.error({ op: 'request.failedLoginAttempt', email: email, ip: ip, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.post(
  '/passwordReset',
  function (req, res, next) {
    var email = req.body.email
    if (!email) {
      var err = {code: 'MissingParameters', message: 'email is required'}
      log.error({ op: 'request.passwordReset', email: email, err: err })
      res.send(500, err)
      next()
    }

    mc.getAsync(email)
      .then(EmailRecord.parse, EmailRecord.parse)
      .then(
        function (emailRecord) {
          emailRecord.passwordReset()
          return mc.setAsync(email, emailRecord, LIFETIME).catch(ignore)
        }
      )
      .then(
        function () {
          log.info({ op: 'request.passwordReset', email: email })
          res.send({})
        },
        function (err) {
          log.error({ op: 'request.passwordReset', email: email, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.post(
  '/blockEmail',
  function (req, res, next) {
    var email = req.body.email
    if (!email) {
      var err = {code: 'MissingParameters', message: 'email is required'}
      log.error({ op: 'request.blockEmail', email: email, err: err })
      res.send(500, err)
      next()
    }

    mc.getAsync(email)
      .then(EmailRecord.parse, EmailRecord.parse)
      .then(
        function (emailRecord) {
          emailRecord.block()
          return mc.setAsync(email, emailRecord, LIFETIME).catch(ignore)
        }
      )
      .then(
        function () {
          log.info({ op: 'request.blockEmail', email: email })
          res.send({})
        },
        function (err) {
          log.error({ op: 'request.blockEmail', email: email, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.post(
  '/blockIp',
  function (req, res, next) {
    var ip = req.body.ip
    if (!ip) {
      var err = {code: 'MissingParameters', message: 'ip is required'}
      log.error({ op: 'request.blockIp', ip: ip, err: err })
      res.send(500, err)
      next()
    }

    mc.getAsync(ip)
      .then(IpRecord.parse, IpRecord.parse)
      .then(
        function (ipRecord) {
          ipRecord.block()
          return mc.setAsync(ip, ipRecord, LIFETIME).catch(ignore)
        }
      )
      .then(
        function () {
          log.info({ op: 'request.blockIp', ip: ip })
          res.send({})
        },
        function (err) {
          log.error({ op: 'request.blockIp', ip: ip, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.get(
  '/',
  function (req, res, next) {
    res.send({ version: packageJson.version })
    next()
  }
)

api.listen(
  config.port,
  function () {
    log.info({ op: 'listening', port: config.port })
  }
)
<|endoftext|>


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

const shelljs = require('shelljs');
const replace = require('replace');

const docsDir = './docs/gaiden-css';
const sourceDocsDir = './docs/demo/gaiden-css/scss';
const sourceDir = './src/scss';
const minifiedDocsFile = `${docsDir}/ninja-demo.css`;

const timestamp = new Date().getTime();

const options = {
  sass: ` --include-path ${sourceDocsDir} \
    --include-path ${sourceDir} \
    --output-style expanded \
    --sourceComments true \
    -o ${docsDir} \
    --recursive `
}

shelljs.exec('git checkout -B gh-pages');
shelljs.exec('git pull origin gh-pages');

shelljs.exec(`node-sass ${sourceDocsDir} ${options.sass} ${minifiedDocsFile}`);
shelljs.exec(`documentjs`);

shelljs.cp([
  './dist/gaiden.min.css',
], './');

shelljs.cp('-R', [
  `${docsDir}/static`,
  `${docsDir}/*.html`,
], './');

replace({
  regex: 'docs\/demo',
  replacement: 'demo',
  paths: ['./docs/demo'],
  recursive: false,
  include: '*.html'
});

replace({
  regex: '\/gaiden-css\/gaiden.css',
  replacement: '\/gaiden.css',
  paths: ['./docs/demo/'],
  recursive: true,
  include: '*.html'
});

shelljs.mkdir('./demo');
shelljs.mv('-n', './docs/demo/*', './demo/');

shelljs.exec('$GAIDEN_LAST_TAG=$(git describe)')
shelljs.exec('git add .');
shelljs.exec(`git commit -m '${timestamp}: Updating docs $GAIDEN_LAST_TAG'`);
shelljs.exec('git push origin gh-pages');
shelljs.exec('git checkout -');
<commit_msg>Removing specific files to cp on build:docs task<commit_after>#! /usr/bin/env node

const shelljs = require('shelljs');
const replace = require('replace');

const docsDir = './docs/gaiden-css';
const sourceDocsDir = './docs/demo/gaiden-css/scss';
const sourceDir = './src/scss';
const minifiedDocsFile = `${docsDir}/ninja-demo.css`;

const timestamp = new Date().getTime();

const options = {
  sass: ` --include-path ${sourceDocsDir} \
    --include-path ${sourceDir} \
    --output-style expanded \
    --sourceComments true \
    -o ${docsDir} \
    --recursive `
}

shelljs.exec('git checkout -B gh-pages');
shelljs.exec('git pull origin gh-pages');

shelljs.exec(`node-sass ${sourceDocsDir} ${options.sass} ${minifiedDocsFile}`);
shelljs.exec(`documentjs`);

shelljs.cp([
  './dist/gaiden.min.css',
], './');

shelljs.cp('-R', `${docsDir}/`, './');

replace({
  regex: 'docs\/demo',
  replacement: 'demo',
  paths: ['./docs/demo'],
  recursive: false,
  include: '*.html'
});

replace({
  regex: '\/gaiden-css\/gaiden.css',
  replacement: '\/gaiden.css',
  paths: ['./docs/demo/'],
  recursive: true,
  include: '*.html'
});

shelljs.mkdir('./demo');
shelljs.mv('-n', './docs/demo/*', './demo/');

shelljs.exec('$GAIDEN_LAST_TAG=$(git describe)')
shelljs.exec('git add .');
shelljs.exec(`git commit -m '${timestamp}: Updating docs $GAIDEN_LAST_TAG'`);
shelljs.exec('git push origin gh-pages');
shelljs.exec('git checkout -');
<|endoftext|>


<commit_before>require("sugar");

//
// The base Bugsnag NotificationPlugin class
// Extend this class to create your own Bugsnag notification plugins:
//
//   NotificationPlugin = require "../../notification-plugin.js"
//   class MyPlugin extends NotificationPlugin
//     @receiveEvent = (config, event) ->
//       ...
//   module.exports = MyPlugin
//
// All notification plugins must override the receiveEvent function to perform
// the notification. This method is fired when a new event is triggered.
//
// See https://github.com/bugsnag/bugsnag-notification-plugins/ for full docs
//

var NotificationPlugin = (function () {
  function NotificationPlugin() {}

  // Fired when a new event is triggered for notification
  // Plugins MUST override this method
  NotificationPlugin.receiveEvent = function (config, event, callback) {
    throw new Error("Plugins must override receiveEvent");
  };

  // Utility methods for generating notification content
  NotificationPlugin.stacktraceLineString = function (stacktraceLine) {
    return stacktraceLine.file + ":" + stacktraceLine.lineNumber + " - " + stacktraceLine.method
  };

  NotificationPlugin.firstStacktraceLine = function (stacktrace) {
    for(var i=0; i<stacktrace.length; i++) {
      var line = stacktrace[i];
      if(line.inProject) {
        return this.stacktraceLineString(line);
      }
    }

    return this.stacktraceLineString(stacktrace[0]);
  };

  // Utility methods for http requests
  NotificationPlugin.request = require("superagent");

  // Fire a test event to your notification plugin (do not override)
  NotificationPlugin.fireTestEvent = function (config) {
    var event = {
      error: {
        exceptionClass: "ExampleException",
        message: "Something really bad happened",
        context: "home#example",
        appVersion: "1.0.0",
        releaseStage: "production",
        occurrences: 42,
        firstReceived: new Date(),
        usersAffected: 20,
        url: "http://bugsnag.com/errors/example/events/example",
        stacktrace: [{
          file: "app/controllers/home_controller.rb",
          lineNumber: 123,
          method: "example",
          inProject: true
        }]
      },
      project: {
        name: "Example.com",
        url: "http://bugsnag.com/projects/example"
      },
      trigger: {
        type: "firstException",
        message: "New exception"
      }
    };

    this.receiveEvent(config, event, function (err, data) {
      if(err) return console.error("Error firing notification\n" + err.stack);

      console.log("Fired test event successfully\n", data);
    });
  };

  // Configuration validation methods (do not override)
  NotificationPlugin.validateConfig = function (config, pluginConfigFile) {
    var fs = require("fs");
    var pluginConfig = JSON.parse(fs.readFileSync(pluginConfigFile, "ascii"));
    if(pluginConfig.fields) {
      pluginConfig.fields.each(function (option) {
        var configValue = config[option.name];

        // Validate all non-optional config fields are present
        if (!(configValue !== undefined || option.optional || (option.type == "boolean" && option.defaultValue !== undefined))) {
          throw new Error("ConfigurationError: Required configuration option '" + option.name + "' is missing");
        }

        // Validate fields with allowed values
        if (configValue !== undefined && option.allowedValues && option.allowedValues.none(configValue)) {
          throw new Error("ConfigurationError: Invalid value for '" + option.name + "'");
        }

        // Fill in default values
        if(configValue == undefined && option.defaultValue !== undefined) {
          config[option.name] = option.defaultValue;
        }
      });
    }
  };

  return NotificationPlugin;
})();
module.exports = NotificationPlugin;

// If running plugins from the command line, allow them to fire test events
if (module.parent && module.parent.parent === null) {
  var path = require("path");
  var argv = require("optimist").argv;

  // Parse command line flags
  var flags = Object.keys(argv).exclude("_", "$0");
  var config = {};
  flags.each(function (flag) {
    if(argv[flag] != null && argv[flag] != "") {
      config[flag] = argv[flag];
    }
  });

  // Validate configuration
  try {
    NotificationPlugin.validateConfig(config, path.dirname(module.parent.filename) + "/config.json");
  } catch (err) {
    return console.error(err.message);
  }

  // Fire a test event
  var plugin = require(module.parent.filename);
  plugin.fireTestEvent(config);
}<commit_msg>Move test event callback to the correct place<commit_after>require("sugar");

//
// The base Bugsnag NotificationPlugin class
// Extend this class to create your own Bugsnag notification plugins:
//
//   NotificationPlugin = require "../../notification-plugin.js"
//   class MyPlugin extends NotificationPlugin
//     @receiveEvent = (config, event) ->
//       ...
//   module.exports = MyPlugin
//
// All notification plugins must override the receiveEvent function to perform
// the notification. This method is fired when a new event is triggered.
//
// See https://github.com/bugsnag/bugsnag-notification-plugins/ for full docs
//

var NotificationPlugin = (function () {
  function NotificationPlugin() {}

  // Fired when a new event is triggered for notification
  // Plugins MUST override this method
  NotificationPlugin.receiveEvent = function (config, event, callback) {
    throw new Error("Plugins must override receiveEvent");
  };

  // Utility methods for generating notification content
  NotificationPlugin.stacktraceLineString = function (stacktraceLine) {
    return stacktraceLine.file + ":" + stacktraceLine.lineNumber + " - " + stacktraceLine.method
  };

  NotificationPlugin.firstStacktraceLine = function (stacktrace) {
    for(var i=0; i<stacktrace.length; i++) {
      var line = stacktrace[i];
      if(line.inProject) {
        return this.stacktraceLineString(line);
      }
    }

    return this.stacktraceLineString(stacktrace[0]);
  };

  // Utility methods for http requests
  NotificationPlugin.request = require("superagent");

  // Fire a test event to your notification plugin (do not override)
  NotificationPlugin.fireTestEvent = function (config, callback) {
    var event = {
      error: {
        exceptionClass: "ExampleException",
        message: "Something really bad happened",
        context: "home#example",
        appVersion: "1.0.0",
        releaseStage: "production",
        occurrences: 42,
        firstReceived: new Date(),
        usersAffected: 20,
        url: "http://bugsnag.com/errors/example/events/example",
        stacktrace: [{
          file: "app/controllers/home_controller.rb",
          lineNumber: 123,
          method: "example",
          inProject: true
        }]
      },
      project: {
        name: "Example.com",
        url: "http://bugsnag.com/projects/example"
      },
      trigger: {
        type: "firstException",
        message: "New exception"
      }
    };

    this.receiveEvent(config, event, callback);
  };

  // Configuration validation methods (do not override)
  NotificationPlugin.validateConfig = function (config, pluginConfigFile) {
    var fs = require("fs");
    var pluginConfig = JSON.parse(fs.readFileSync(pluginConfigFile, "ascii"));
    if(pluginConfig.fields) {
      pluginConfig.fields.each(function (option) {
        var configValue = config[option.name];

        // Validate all non-optional config fields are present
        if (!(configValue !== undefined || option.optional || (option.type == "boolean" && option.defaultValue !== undefined))) {
          throw new Error("ConfigurationError: Required configuration option '" + option.name + "' is missing");
        }

        // Validate fields with allowed values
        if (configValue !== undefined && option.allowedValues && option.allowedValues.none(configValue)) {
          throw new Error("ConfigurationError: Invalid value for '" + option.name + "'");
        }

        // Fill in default values
        if(configValue == undefined && option.defaultValue !== undefined) {
          config[option.name] = option.defaultValue;
        }
      });
    }
  };

  return NotificationPlugin;
})();
module.exports = NotificationPlugin;

// If running plugins from the command line, allow them to fire test events
if (module.parent && module.parent.parent === null) {
  var path = require("path");
  var argv = require("optimist").argv;

  // Parse command line flags
  var flags = Object.keys(argv).exclude("_", "$0");
  var config = {};
  flags.each(function (flag) {
    if(argv[flag] != null && argv[flag] != "") {
      config[flag] = argv[flag];
    }
  });

  // Validate configuration
  try {
    NotificationPlugin.validateConfig(config, path.dirname(module.parent.filename) + "/config.json");
  } catch (err) {
    return console.error(err.message);
  }

  // Fire a test event
  var plugin = require(module.parent.filename);
  plugin.fireTestEvent(config, function (err, data) {
    if(err) {
      console.error("Error firing notification\n", err.stack);
    } else {
      console.log("Fired test event successfully\n", data);
    }
  });
}<|endoftext|>


<commit_before>/*global define, console */
(function (definition) {
	if (typeof define === 'function' && define.amd) {
		define([], definition);
	} else {
		var exports = definition();
		window.RangyUtils = exports;
	}
})(function () {
	function nodesAsArray(nodes) {
		var array = [];
		var i;
		for (i = 0; i < nodes.length; ++i) {
			array.push(nodes[i]);
		}
		return array;
	}

	function nodeMatch(nodes, container, common) {
		var i;
		for (i = 0; i < nodes.length; ++i) {
			var element = nodes[i];
			if (compareNodes(element, container, common)) {
				return i;
			}
		}
		return -1;
	}

	function compareNodes(target, container, limit) {
		return _compareNodes(container);
		function _compareNodes(node) {
			if (node === target) {
				return true;
			} else if (node.parentElement === limit || !node.parentElement) {
				return false;
			} else {
				return _compareNodes(node.parentElement);
			}
		}
	}

	function getJsonNodesFromRange(wrappedRange) {
		if (!wrappedRange) {
			return null;
		}

		// handle the case where range wraps only a single node.
		if (wrappedRange.startContainer === wrappedRange.endContainer) {
			if (wrappedRange.startOffset === wrappedRange.endOffset) {
				return null;
			} else {
				var single = nodeAsJson(wrappedRange.startContainer);
				single.text = single.text.substring(wrappedRange.startOffset, wrappedRange.endOffset);
				single.html = single.text;
				return single;
			}
		} else {
			var nodeArray = nodesAsArray(wrappedRange.commonAncestorContainer.childNodes);
			var i = nodeMatch(nodeArray, wrappedRange.startContainer, wrappedRange.commonAncestorContainer);
			var j = nodeMatch(nodeArray, wrappedRange.endContainer, wrappedRange.commonAncestorContainer);
			if (i === -1) { throw { message: 'matching code is busted.' }; }
			if (j === -1) { throw { message: 'matching code is busted.' }; }
			var results = nodeArray.slice(i, j + 1).map(nodeAsJson);
			results[0] = headJsonNode(results[0], wrappedRange.startContainer, wrappedRange.startOffset);
			results[results.length - 1] = tailJsonNode(results[1], wrappedRange.endContainer, wrappedRange.endOffset);
			return results;
		}
	}

	function nodeAsJson(node) {
		var result = {};
		switch (node.nodeType) {
			case 1: // ELEMENT_NODE
				result.type = 'element';
				break;
			case 3: // TEXT_NODE
				result.type = 'text';
				break;
			default:
				console.log('deprecated/not covered nodeType: ' + node.nodeType);
				return null;
		}
		result.node = node;
		result.text = node.textContent;
		result.nodeName = node.nodeName;
		if (result.nodeName !== '#text') {
			result.html = node.outerHTML;
		} else {
			result.html = result.text;
		}
		return result;
	}

	function headJsonNode(jsonNode, startContainer, startOffset) {
		var result = {};
		// type and nodeName are made up.
		result.type = 'fragment';
		result.nodeName = '#start';
		result.text = startContainer.textContent.substring(startOffset);
		var index = jsonNode.html.lastIndexOf(result.text);
		result.html = jsonNode.html.substring(index);

		result.node = jsonNode.node;
		result.jsonNode = jsonNode;

		return result;
	}

	function tailJsonNode(jsonNode, endContainer, endOffset) {
		var result = {};
		// type and nodeName are made up.
		result.type = 'fragment';
		result.nodeName = '#end';
		result.text = endContainer.textContent.substring(0, endOffset);
		var index = jsonNode.html.indexOf(result.text);
		result.html = jsonNode.html.substring(0, index + result.text.length);

		result.node = jsonNode.node;
		result.jsonNode = jsonNode;

		return result;
	}

	function mapTextNode(jsonNode) {
		var textNodes = _mapNode(jsonNode.node);

		function _mapNode(node) {
			if (node.nodeName === '#text') {
				return [ node ];
			} else {
				var array = nodesAsArray(node.childNodes);
				// flatten array
				return [].concat.apply([], array.map(_mapNode));
			}
		}

		return {
			textNodes: textNodes,
			text: jsonNode.text
		}
	}

	function replaceTextNode(textNode, text) {
		var newNode = document.createTextNode(text);
		var parentElement = textNode.parentElement;
		parentElement.replaceChild(newNode, textNode);
		return newNode;
	}

	return {
		getJsonNodesFromRange: getJsonNodesFromRange,
		mapTextNode: mapTextNode,
		replaceTextNode: replaceTextNode
	}
});<commit_msg>Fix index error.<commit_after>/*global define, console */
(function (definition) {
	if (typeof define === 'function' && define.amd) {
		define([], definition);
	} else {
		var exports = definition();
		window.RangyUtils = exports;
	}
})(function () {
	function nodesAsArray(nodes) {
		var array = [];
		var i;
		for (i = 0; i < nodes.length; ++i) {
			array.push(nodes[i]);
		}
		return array;
	}

	function nodeMatch(nodes, container, common) {
		var i;
		for (i = 0; i < nodes.length; ++i) {
			var element = nodes[i];
			if (compareNodes(element, container, common)) {
				return i;
			}
		}
		return -1;
	}

	function compareNodes(target, container, limit) {
		return _compareNodes(container);
		function _compareNodes(node) {
			if (node === target) {
				return true;
			} else if (node.parentElement === limit || !node.parentElement) {
				return false;
			} else {
				return _compareNodes(node.parentElement);
			}
		}
	}

	function getJsonNodesFromRange(wrappedRange) {
		if (!wrappedRange) {
			return null;
		}

		// handle the case where range wraps only a single node.
		if (wrappedRange.startContainer === wrappedRange.endContainer) {
			if (wrappedRange.startOffset === wrappedRange.endOffset) {
				return null;
			} else {
				var single = nodeAsJson(wrappedRange.startContainer);
				single.text = single.text.substring(wrappedRange.startOffset, wrappedRange.endOffset);
				single.html = single.text;
				return single;
			}
		} else {
			var nodeArray = nodesAsArray(wrappedRange.commonAncestorContainer.childNodes);
			var i = nodeMatch(nodeArray, wrappedRange.startContainer, wrappedRange.commonAncestorContainer);
			var j = nodeMatch(nodeArray, wrappedRange.endContainer, wrappedRange.commonAncestorContainer);
			if (i === -1) { throw { message: 'matching code is busted.' }; }
			if (j === -1) { throw { message: 'matching code is busted.' }; }
			var results = nodeArray.slice(i, j + 1).map(nodeAsJson);
			results[0] = headJsonNode(results[0], wrappedRange.startContainer, wrappedRange.startOffset);
			results[results.length - 1] = tailJsonNode(results[results.length - 1], wrappedRange.endContainer, wrappedRange.endOffset);
			return results;
		}
	}

	function nodeAsJson(node) {
		var result = {};
		switch (node.nodeType) {
			case 1: // ELEMENT_NODE
				result.type = 'element';
				break;
			case 3: // TEXT_NODE
				result.type = 'text';
				break;
			default:
				console.log('deprecated/not covered nodeType: ' + node.nodeType);
				return null;
		}
		result.node = node;
		result.text = node.textContent;
		result.nodeName = node.nodeName;
		if (result.nodeName !== '#text') {
			result.html = node.outerHTML;
		} else {
			result.html = result.text;
		}
		return result;
	}

	function headJsonNode(jsonNode, startContainer, startOffset) {
		var result = {};
		// type and nodeName are made up.
		result.type = 'fragment';
		result.nodeName = '#start';
		result.text = startContainer.textContent.substring(startOffset);
		var index = jsonNode.html.lastIndexOf(result.text);
		result.html = jsonNode.html.substring(index);

		result.node = jsonNode.node;
		result.jsonNode = jsonNode;

		return result;
	}

	function tailJsonNode(jsonNode, endContainer, endOffset) {
		var result = {};
		// type and nodeName are made up.
		result.type = 'fragment';
		result.nodeName = '#end';
		result.text = endContainer.textContent.substring(0, endOffset);
		var index = jsonNode.html.indexOf(result.text);
		result.html = jsonNode.html.substring(0, index + result.text.length);

		result.node = jsonNode.node;
		result.jsonNode = jsonNode;

		return result;
	}

	function mapTextNode(jsonNode) {
		var textNodes = _mapNode(jsonNode.node);

		function _mapNode(node) {
			if (node.nodeName === '#text') {
				return [ node ];
			} else {
				var array = nodesAsArray(node.childNodes);
				// flatten array
				return [].concat.apply([], array.map(_mapNode));
			}
		}

		return {
			textNodes: textNodes,
			text: jsonNode.text
		}
	}

	function replaceTextNode(textNode, text) {
		var newNode = document.createTextNode(text);
		var parentElement = textNode.parentElement;
		parentElement.replaceChild(newNode, textNode);
		return newNode;
	}

	return {
		getJsonNodesFromRange: getJsonNodesFromRange,
		mapTextNode: mapTextNode,
		replaceTextNode: replaceTextNode
	}
});<|endoftext|>


<commit_before><commit_msg>API v2.0 - Response<commit_after>/* globals $ javax */
/* eslint-env node, dirigible */

exports.getMethod = function() {
	return $.getRequest().getMethod();
};

exports.getParameter = function(name) {
	return $.getRequest().getParameter(name);
};

exports.getParameterNames = function() {
	var names = [];
	var values = $.getRequest().getParameterNames();
	while (values.hasMoreElements()) {
		names.push(values.nextElement());
	}
	return names;
};

exports.getParameters = function() {
	var parameters = {};
	var values = $.getRequest().getParameterMap().entrySet();
	var iteretor = values.iterator();
	while (iteretor.hasNext()) {
		var parameter = iteretor.next();
		var key = parameter.getKey();
		parameters[key] = [];
		var parameterValues = parameter.getValue();
		for (var i = 0; i < parameterValues.length; i ++) {
			parameters[key].push(parameterValues[i]);
		}
	}
	return parameters;
};

exports.getHeader = function(name) {
	return $.getRequest().getHeader(name);
};

exports.getHeaderNames = function() {
	var names = [];
	var values = $.getRequest().getHeaderNames();
	while (values.hasMoreElements()) {
		names.push(values.nextElement());
	}
	return names;
};

exports.getCookies = function() {
	var cookies = [];
	var values = $.getRequest().getCookies();
	for (var i = 0; i < values.length; i ++) {
		var cookie = values[i];
		cookies.push({
			"name": cookie.getName(),
			"value": cookie.getValue(),
			"maxAge": cookie.getMaxAge(),
			"path": cookie.getPath(),
			"domain": cookie.getDomain(),
			"secure": cookie.getSecure()
		});
	}

	return cookies;
};

exports.isUserInRole = function(role) {
	return $.getRequest().isUserInRole(role);
};

exports.getInfo = function() {
	return {
		"contextPath": $.getRequest().getPathInfo(),
		"pathInfo": $.getRequest().getPathInfo(),
		"protocol": $.getRequest().getProtocol(),
		"queryString": $.getRequest().getQueryString(),
		"scheme": $.getRequest().getScheme(),
		"serverName": $.getRequest().getServerName(),
		"serverPort": $.getRequest().getServerPort()
	};
};
<|endoftext|>


<commit_before>var w = Math.min(screen.height*0.60,500),
h = w,
r = h*0.9,
x = d3.scale.linear().range([0, r]),
y = d3.scale.linear().range([0, r]),
p = 15,
label_rad = 25,
node,
root,
fc1,fc2,fc3,
chart_dyn,
dynamic = false,
chart_type;

if (typeof String.prototype.startsWith != 'function') {
    // see below for better implementation!
    String.prototype.startsWith = function (str){
        return this.indexOf(str) == 0;
    };
}

var colorMap = {"Wet Storage": "#1f77b4",
                "Dry Storage": "#aec7e8",
                "Repository": "#ffbb78",
                "Reprocessed Fuel": "#2ca02c"
               }

function colorPicker(s) {
    var c = "white";
    for (var key in colorMap) {
        if (s.startsWith(key)) {
            c = colorMap[key];
            break;
        };
    };
    return c;
}

function wrap(text, width) {
    text.each(function() {
        var text = d3.select(this),
        lines = text.text().split(/\n/).reverse(),
        line,
        lineNumber = 0,
        lineHeight = 1.1, // ems
        x = text.attr("x"),
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", x)
            .attr("y", y).attr("dy", dy + "em");
        lineNumber = - Math.floor(lines.length / 2);
        while (line = lines.pop()) {
            tspan = text.append("tspan").attr("x", x)
                .attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em")
                .text(line);
        }
    });
}

function scaled_pack(v) {
    var pack = d3.layout.pack()
        .size([r*v, r*v])
        .value(function(d) { return d.size;})
        .padding(p);
    return pack
}

var pack = scaled_pack(1.0);

function load_data(chart_node,json_data,scale_var)
{
    d3.json(json_data, function(data) {
        pack.size([r*data.scale, r*data.scale]);
        node = root = data;
        var nodes = pack.nodes(root);
        chart_node.selectAll("circle")
            .remove();
        chart_node.selectAll("circle")
            .data(nodes)
            .enter().append("svg:circle")
            .attr("class", function(d) { return d.children ? "parent" : "child"; })
            .attr("cx", function(d) { return d.x; })
            .attr("cy", function(d) { return d.y; })
            .attr("r", function(d) { return d.r; })
            .style("stroke-width",function(d) {if (d.children && !chart_dyn && d.children[0].children)
                                               {return 0}; return 1;})
            .style("fill", function(d){return colorPicker(d.name)});

        chart_node.selectAll("text")
            .remove();
        chart_node.selectAll("text")
            .data(nodes)
            .enter().append("svg:text")
            .attr("class", function(d) { return d.children ? "parent" : "child"; })
            .attr("x", function(d) { return d.x; })
            .attr("y", function(d) { if (d.children) {return d.y - d.r - 20;}; if (d.r < 21.5) {return d.y + d.r + 10;}; return d.y; })
            .attr("dy", "-.35em")
            .attr("text-anchor", "middle")
            .text(function(d) { if (d.children) {return d.name;}; return d.name.split('\n').slice(1,3).join('\n'); })
            .call(wrap);
    });
}

function add_info(chart_id)
{
    var new_chart = d3.select(chart_id + " svg")
        .attr("width", w)
        .attr("height", h)
        .append("svg:g")
        .attr("transform", "translate(" + (w - r) / 2 + "," + (h - r) / 2 + ")");

    return new_chart;
}

function load_static(kind)
{
    var cost_ver = "";
    var vary_run = +2;

    if (kind == "cost")
    {
        cost_ver = "-new";
        vary_run = -2;
    }
    load_data(fc1,"info-raw-data-run" + (3+vary_run).toString() +  cost_ver + "-2000_2050_2100-" + kind + ".json");
    load_data(fc2,"info-raw-data-run" + (3+0).toString() +  cost_ver + "-2000_2050_2100-" + kind + ".json");
    load_data(fc3,"info-raw-data-run" + (3-vary_run).toString() +  cost_ver + "-2000_2050_2100-" + kind + ".json");
}

function load_fcs(kind,year) {
    var cost_ver = "";
    var vary_run = +2;

    if (kind == "cost")
    {
        cost_ver = "-new";
        var vary_run = -2;
    }
    load_data(fc1,"years/info-raw-data-run" + (3+vary_run).toString() + cost_ver + "-" + year + "-" + kind + ".json");
    load_data(fc2,"years/info-raw-data-run" + (3+0).toString()  + cost_ver + "-" + year + "-" + kind + ".json");
    load_data(fc3,"years/info-raw-data-run" + (3-vary_run).toString()  + cost_ver + "-" + year + "-" + kind + ".json");
}

function yearUpdate(year) {
    document.querySelector('#yearlabel').value = year;
    load_fcs(chart_type,year);
}

function info(dynamic,kind)
{
    chart_type = kind;
    chart_dyn = dynamic;

    fc1 = add_info("#chart1");
    fc2 = add_info("#chart2");
    fc3 = add_info("#chart3");

    if (dynamic)
    {
        load_fcs(kind,2000);
    }
    else
    {
        load_static(kind);
    }
}

<commit_msg>remove outer circle on waste info graphics; add minimum size<commit_after>var w = Math.min(screen.height*0.60,500),
h = w,
r = h*0.9,
rmin = h * 0.2,
x = d3.scale.linear().range([0, r]),
y = d3.scale.linear().range([0, r]),
p = 15,
label_rad = 25,
node,
root,
fc1,fc2,fc3,
chart_dyn,
dynamic = false,
chart_type;

if (typeof String.prototype.startsWith != 'function') {
    // see below for better implementation!
    String.prototype.startsWith = function (str){
        return this.indexOf(str) == 0;
    };
}

var colorMap = {"Wet Storage": "#1f77b4",
                "Dry Storage": "#aec7e8",
                "Repository": "#ffbb78",
                "Reprocessed Fuel": "#2ca02c"
               }

function colorPicker(s) {
    var c = "white";
    for (var key in colorMap) {
        if (s.startsWith(key)) {
            c = colorMap[key];
            break;
        };
    };
    return c;
}

function wrap(text, width) {
    text.each(function() {
        var text = d3.select(this),
        lines = text.text().split(/\n/).reverse(),
        line,
        lineNumber = 0,
        lineHeight = 1.1, // ems
        x = text.attr("x"),
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", x)
            .attr("y", y).attr("dy", dy + "em");
        lineNumber = - Math.floor(lines.length / 2);
        while (line = lines.pop()) {
            tspan = text.append("tspan").attr("x", x)
                .attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em")
                .text(line);
        }
    });
}

function scaled_pack(v) {
    var pack = d3.layout.pack()
        .size([r*v, r*v])
        .value(function(d) { return d.size;})
        .padding(p);
    return pack
}

var pack = scaled_pack(1.0);

function load_data(chart_node,json_data,scale_var)
{
    d3.json(json_data, function(data) {
        pack.size([(r-rmin)*data.scale+rmin, (r-rmin)*data.scale+rmin]);
        node = root = data;
        var nodes = pack.nodes(root);
        chart_node.selectAll("circle")
            .remove();
        chart_node.selectAll("circle")
            .data(nodes)
            .enter().append("svg:circle")
            .attr("class", function(d) { return d.children ? "parent" : "child"; })
            .attr("cx", function(d) { return d.x; })
            .attr("cy", function(d) { return d.y; })
            .attr("r", function(d) { return d.r; })
            .style("stroke-width",function(d) {if (d.children && (d.children[0].children || d.children[1].children) )
                                               {return 0}; return 1;})
            .style("fill", function(d){return colorPicker(d.name)});

        chart_node.selectAll("text")
            .remove();
        chart_node.selectAll("text")
            .data(nodes)
            .enter().append("svg:text")
            .attr("class", function(d) { return d.children ? "parent" : "child"; })
            .attr("x", function(d) { return d.x; })
            .attr("y", function(d) { if (d.children) {return d.y - d.r - 20;}; if (d.r < 21.5) {return d.y + d.r + 10;}; return d.y; })
            .attr("dy", "-.35em")
            .attr("text-anchor", "middle")
            .text(function(d) { if (d.children) {return d.name;}; return d.name.split('\n').slice(1,3).join('\n'); })
            .call(wrap);
    });
}

function add_info(chart_id)
{
    var new_chart = d3.select(chart_id + " svg")
        .attr("width", w)
        .attr("height", h)
        .append("svg:g")
        .attr("transform", "translate(" + (w - r) / 2 + "," + (h - r) / 2 + ")");

    return new_chart;
}

function load_static(kind)
{
    var cost_ver = "";
    var vary_run = +2;

    if (kind == "cost")
    {
        cost_ver = "-new";
        vary_run = -2;
    }
    load_data(fc1,"info-raw-data-run" + (3+vary_run).toString() +  cost_ver + "-2000_2050_2100-" + kind + ".json");
    load_data(fc2,"info-raw-data-run" + (3+0).toString() +  cost_ver + "-2000_2050_2100-" + kind + ".json");
    load_data(fc3,"info-raw-data-run" + (3-vary_run).toString() +  cost_ver + "-2000_2050_2100-" + kind + ".json");
}

function load_fcs(kind,year) {
    var cost_ver = "";
    var vary_run = +2;

    if (kind == "cost")
    {
        cost_ver = "-new";
        var vary_run = -2;
    }
    load_data(fc1,"years/info-raw-data-run" + (3+vary_run).toString() + cost_ver + "-" + year + "-" + kind + ".json");
    load_data(fc2,"years/info-raw-data-run" + (3+0).toString()  + cost_ver + "-" + year + "-" + kind + ".json");
    load_data(fc3,"years/info-raw-data-run" + (3-vary_run).toString()  + cost_ver + "-" + year + "-" + kind + ".json");
}

function yearUpdate(year) {
    document.querySelector('#yearlabel').value = year;
    load_fcs(chart_type,year);
}

function info(dynamic,kind)
{
    chart_type = kind;
    chart_dyn = dynamic;

    fc1 = add_info("#chart1");
    fc2 = add_info("#chart2");
    fc3 = add_info("#chart3");

    if (dynamic)
    {
        load_fcs(kind,2000);
    }
    else
    {
        load_static(kind);
    }
}

<|endoftext|>


<commit_before>var promise = require('bluebird');

var options = {
  // Initialization Options
  promiseLib: promise
};

var pgp = require('pg-promise')(options);
var ctStr = require("./db_connect.json");

// Connecting to the database:
var db = pgp(ctStr);

// add query functions

module.exports = {
  geopoliticalunits:geopoliticalunits,
  publications:publications,
  dbtables:dbtables,
  chronology:chronology,
  contacts:contacts,
  occurrence:occurrence,
  pollen:pollen,
  taxa:taxa,
  site:site,
  sites:site
};

function site(req, res, next) {

  // Get the query string:
  var query = {};

  console.log(req.query);

  res.status(200)
    .json({
      status: 'success',
      query: query,
      message: 'Retrieved sites'
      })

}

function taxa(req, res, next) {

  // Get the query string:
  var query = {};

  console.log(req.query);

  res.status(200)
    .json({
      status: 'success',
      query: query,
      message: 'Retrieved taxa'
      })

}

function pollen(req, res, next) {

  // Get the query string:
  var query = {};

  console.log(req.query);

  res.status(200)
    .json({
      status: 'success',
      query: query,
      message: 'Retrieved pollen'
      })

}

function occurrence(req, res, next) {

  // Get the query string:
  var query = {};

  console.log(req.query);

  res.status(200)
    .json({
      status: 'success',
      query: query,
      message: 'Retrieved occurrences'
      })

}

function contacts(req, res, next) {

  // Get the query string:
  var query = {};

  console.log(req.query);

  res.status(200)
    .json({
      status: 'success',
      query: query,
      message: 'Retrieved contacts'
      })

}

function chronology(req, res, next) {

  // Get the query string:
  var query = {};

  console.log(query);

  res.status(200)
    .json({
      status: 'success',
      query: query,
      message: 'Retrieved chronology'
      })

}

function publications(req, res, next) {

  // Get the query string:
  var query = {'PublicationID':req.pubid,
               'PublicationID':req.query.pubid,
               'contactid':req.query.contactid,
               'datasetid':req.query.datasetid,
               'author':req.query.author,
               'PubType':req.query.pubtype,
               'Year':req.query.year,
               'search':req.query.search
             };

  query = Object.keys(query).filter(function(key) {
      return !isNaN(query[key]);
      });

  db.any('SELECT * FROM publications WHERE')
    .then(function (data) {
      res.status(200)
        .json({
          status: 'success',
          data: data,
          message: 'Retrieved all tables'
        });
    })
    .catch(function (err) {
      return next(err);
    });

  console.log(query);

  res.status(200)
    .json({
    	status: 'success',
    	query: query,
    	message: 'Retrieved all tables'
    	})

};

function dbtables(req, res, next) {

  var tableID = parseInt(req.params.table);
  if (isNaN(tableID)) {
  	var query = 'SELECT table_name AS table FROM information_schema.tables AS ischeme;';
  } else {
  	var query = 'select * from "' + tableID + '"';
  }

  db.any(query)
    .then(function (data) {
      res.status(200)
        .json({
          status: 'success',
          data: data,
          message: 'Retrieved all tables'
        });
    })
    .catch(function (err) {
      return next(err);
    });
};

function geopoliticalunits(req, res, next) {

  var gpuID = parseInt(req.params.gpid);
  if (isNaN(gpuID)) {
  	var query = 'select * from "GeoPoliticalUnits"';
  } else {
  	var query = 'select * from "GeoPoliticalUnits" where "GeoPoliticalID" = ' + gpuID;
  }

  console.log(gpuID);

  db.any(query)
    .then(function (data) {
      res.status(200)
        .json({
          status: 'success',
          data: data,
          message: 'Retrieved GeoPoliticalUnit ' + gpuID
        });
    })
    .catch(function (err) {
      return next(err);
    });
}<commit_msg>removed the `sites:sites` path and changed it to `sites:site` so that site does it all.<commit_after>var promise = require('bluebird');

var options = {
  // Initialization Options
  promiseLib: promise
};

var pgp = require('pg-promise')(options);
var ctStr = require("./db_connect.json");

// Connecting to the database:
var db = pgp(ctStr);

// add query functions

module.exports = {
  geopoliticalunits:geopoliticalunits,
  publications:publications,
  dbtables:dbtables,
  chronology:chronology,
  contacts:contacts,
  occurrence:occurrence,
  pollen:pollen,
  taxa:taxa,
  site:site,
  sites:site,
  datasets:datasets
};

function site(req, res, next) {

  // Get the query string:
  var query = {};

  console.log(req.query);

  res.status(200)
    .json({
      status: 'success',
      query: query,
      message: 'Retrieved sites'
      })

}

function taxa(req, res, next) {

  // Get the query string:
  var query = {};

  console.log(req.query);

  res.status(200)
    .json({
      status: 'success',
      query: query,
      message: 'Retrieved taxa'
      })

}

function pollen(req, res, next) {

  // Get the query string:
  var query = {};

  console.log(req.query);

  res.status(200)
    .json({
      status: 'success',
      query: query,
      message: 'Retrieved pollen'
      })

}

function occurrence(req, res, next) {

  // Get the query string:
  var query = {};

  console.log(req.query);

  res.status(200)
    .json({
      status: 'success',
      query: query,
      message: 'Retrieved occurrences'
      })

}

function contacts(req, res, next) {

  // Get the query string:
  var query = {};

    db.any('SELECT * FROM "Contacts"')
    .then(function (data) {
      res.status(200)
        .json({
          status: 'success',
          data: data,
          message: 'Retrieved all tables'
        });
    })
    .catch(function (err) {
      return next(err);
    });

  console.log(req.query);

  res.status(200)
    .json({
      status: 'success',
      query: query,
      message: 'Retrieved contacts'
      })

}

function datasets(req, res, next) {

  // Get the query string:
  var query = {};

  console.log(query);

  res.status(200)
    .json({
      status: 'success',
      query: query,
      message: 'Retrieved chronology'
      })

}

function chronology(req, res, next) {

  // Get the query string:
  var query = {};

  console.log(query);

  res.status(200)
    .json({
      status: 'success',
      query: query,
      message: 'Retrieved chronology'
      })

}

function publications(req, res, next) {

  // Get the query string:
  var query = {'PublicationID':req.pubid,
               'PublicationID':req.query.pubid,
               'contactid':req.query.contactid,
               'datasetid':req.query.datasetid,
               'author':req.query.author,
               'PubType':req.query.pubtype,
               'Year':req.query.year,
               'search':req.query.search
             };
  console.log(query);

  query = Object.keys(query).filter(function(key) {
      return !isNaN(query[key]);
      });

  console.log('...');
  console.log(query);

  db.any('SELECT * FROM publications WHERE')
    .then(function (data) {
      res.status(200)
        .json({
          status: 'success',
          data: data,
          message: 'Retrieved all tables'
        });
    })
    .catch(function (err) {
      return next(err);
    });

  console.log(query);

  res.status(200)
    .json({
    	status: 'success',
    	query: query,
    	message: 'Retrieved all tables'
    	})

};

function dbtables(req, res, next) {

  var tableID = parseInt(req.params.table);
  if (isNaN(tableID)) {
  	var query = 'SELECT table_name AS table FROM information_schema.tables AS ischeme;';
  } else {
  	var query = 'select * from "' + tableID + '"';
  }

  db.any(query)
    .then(function (data) {
      res.status(200)
        .json({
          status: 'success',
          data: data,
          message: 'Retrieved all tables'
        });
    })
    .catch(function (err) {
      return next(err);
    });
};

function geopoliticalunits(req, res, next) {

  var gpuID = parseInt(req.params.gpid);
  if (isNaN(gpuID)) {
  	var query = 'select * from "GeoPoliticalUnits"';
  } else {
  	var query = 'select * from "GeoPoliticalUnits" where "GeoPoliticalID" = ' + gpuID;
  }

  console.log(gpuID);

  db.any(query)
    .then(function (data) {
      res.status(200)
        .json({
          status: 'success',
          data: data,
          message: 'Retrieved GeoPoliticalUnit ' + gpuID
        });
    })
    .catch(function (err) {
      return next(err);
    });
}<|endoftext|>


<commit_before>var db = require("./db");

var authQuery = `SELECT * FROM OUWXC.user WHERE username="test"`;
var insertData = `INSERT INTO OUWXC.athlete_data (
			athlete,
			date,
			sleep,
			Illness,
			Injury,
			percent_health,
			cycle_start,
			notes) VALUES (
			"test",
			"test",
			"test",
			"test",
			"test",
			"test",
			"test",
			"test")`;

var insertUser = `INSERT INTO OUWXC.user (
			username,
			email,
			password) VALUES (
			"test",
			"test@gmail.com",
			"testing")`;

function dbObject(input) {
	this.user = input.user

function get_query(query, queryString) {
	var string = "";

	console.log(query);

	if(query == "authenticate")
	{
		string = authQuery;
	}
	else if(query == "insertD")
	{
		string = insertData;
	}
	else if(query == "insertU")
	{
		console.log("In condition");
		string = insertUser;
	}
	else
	{
		console.log("error, could not find query");
	}

	queryString(string);
};

function exec_query(query, input, result) {

	var queryString = "";

	get_query(query, input, function(output){
		queryString = output;
	});

	db.query(queryString, function(err, rows, fields) {
        	if (err) throw err;
		else {
			console.log("executed query" + queryString);
			result(err, rows, fields);
		}
	});
}

module.exports.exec_query = exec_query;

<commit_msg>fixing a debug issue<commit_after>var db = require("./db");

var authQuery = `SELECT * FROM OUWXC.user WHERE username="test"`;
var insertData = `INSERT INTO OUWXC.athlete_data (
			athlete,
			date,
			sleep,
			Illness,
			Injury,
			percent_health,
			cycle_start,
			notes) VALUES (
			"test",
			"test",
			"test",
			"test",
			"test",
			"test",
			"test",
			"test")`;

var insertUser = `INSERT INTO OUWXC.user (
			username,
			email,
			password) VALUES (
			"test",
			"test@gmail.com",
			"testing")`;

function get_query(query, queryString) {
	var string = "";

	console.log(query);

	if(query == "authenticate")
	{
		string = authQuery;
	}
	else if(query == "insertD")
	{
		string = insertData;
	}
	else if(query == "insertU")
	{
		console.log("In condition");
		string = insertUser;
	}
	else
	{
		console.log("error, could not find query");
	}

	queryString(string);
};

function exec_query(query, input, result) {

	var queryString = "";

	get_query(query, input, function(output){
		queryString = output;
	});

	db.query(queryString, function(err, rows, fields) {
        	if (err) throw err;
		else {
			console.log("executed query" + queryString);
			result(err, rows, fields);
		}
	});
}

module.exports.exec_query = exec_query;

<|endoftext|>


<commit_before>/*jshint multistr: true */

'use strict';

var $ = require('jquery'),
    PulsarSortableComponent = require('../../../js/PulsarSortableComponent');

describe('PulsarSortableComponent', function () {
    beforeEach(function () {

        this.$html = $('

').appendTo('html');
        this.$body = $('

').appendTo(this.$html);
        this.$markup = $('\

\

\
        <button data-toggle="dropdown" class="btn dropdown__toggle">\
            Actions \
            \
        </button>\

\

 New Filter
\

 Random Option
\

\

 Delete
\

\

\

\

\

\
                foo	\
                	\
                <input type="checkbox" class="form__control checkbox">	\

\

\
                foo	\
                	\
                <input type="checkbox" class="form__control checkbox">	\

\

\

\

\
').appendTo(this.$body);

        this.$table = this.$html.find('.table');
        this.$rowOne = this.$html.find('.qa-row-one');
        this.$rowTwo = this.$html.find('.qa-row-two');
        this.$moveUp = this.$html.find('[data-move="up"]');
        this.$moveDown = this.$html.find('[data-move="down"]');

        this.pulsarSortable = new PulsarSortableComponent(this.$html);
    });

    describe('The sortable table', function () {
        beforeEach(function () {
            this.pulsarSortable.init();
        });

        it('should have row one at index 0', function () {
            expect(this.$html.find('.qa-row-one').index()).to.equal(0);
        });

        it('should have row two at index 1', function () {
            expect(this.$html.find('.qa-row-two').index()).to.equal(1);
        });
    });

    describe('Clicking a move control in row one', function () {
        beforeEach(function () {
            this.pulsarSortable.init();
            this.$moveUp.click();
        });

        it('should hide the move links', function () {
            expect(this.$html.find('.qa-row-one [data-move="up"]').hasClass('hide')).to.be.true;
        });

        it('should add the success icon', function () {
            expect(this.$html.find('.qa-row-one [data-move="up"]').parent().find('.icon-ok-sign').length).to.equal(1);
        });

        it('should remove the success icon after a delay', function () {
            setTimeout(function (){
                expect(this.$html.find('.qa-row-one [data-move="up"]').parent().find('.js-sortable-moved').length).to.equal(0);
            }, 1000);
        });

        it('should show the move links after a delay', function () {
            setTimeout(function (){
                expect(this.$html.find('.qa-row-one [data-move="up"]').hasClass('hide')).to.be.false;
            }, 2250);
        });
    });

    describe('Clicking the move down control on row one', function () {
        beforeEach(function () {
            this.pulsarSortable.init();
            this.$rowOne.find('[data-move="down"]').click();
        });

        it('should move the row down one position', function () {
            expect(this.$html.find('.qa-row-one').index()).to.equal(1);
        });

        it('should move the other row up one position', function () {
            expect(this.$html.find('.qa-row-two').index()).to.equal(0);
        });
    });

    describe('Clicking the move up control on row one', function () {
        beforeEach(function () {
            this.pulsarSortable.init();
            this.$rowOne.find('[data-move="up"]').click();
        });

        it('should move the row up one position', function () {
            expect(this.$html.find('.qa-row-one').index()).to.equal(0);
        });

        it('should move the other row down one position', function () {
            expect(this.$html.find('.qa-row-two').index()).to.equal(1);
        });
    });

    describe('Selecting a table row', function () {
        beforeEach(function () {
            this.actionsBadgeStub = sinon.stub(this.pulsarSortable, 'actionsBadge');
            this.pulsarSortable.init();
            this.$rowOne.click();
        });

        afterEach(function () {
            this.actionsBadgeStub.restore();
        });

        it('should add class "is-selected"', function () {
            expect(this.$rowOne.hasClass('is-selected')).to.be.true;
        });

        it('should toggle the row\'s checkbox', function () {
            expect(this.$rowOne.find('.checkbox').first().prop('checked')).to.be.true;
        });

        it('should update "Actions" dropdown badge', function () {
            expect(this.actionsBadgeStub).to.have.been.called;
        });

        it('should add a badge to "Actions" dropdown', function () {
            expect($('.has-badges .dropdown__toggle .badge').is(':visible')).to.be.true;
        });

        it('should have the word "item" in the Delete dadge', function () {
            expect($('.has-badges .dropdown__menu li:last-child a').text().indexOf("item") > 1).to.be.true;
        });
    });

    describe('Deselecting a table row', function () {
        beforeEach(function () {
            this.actionsBadgeStub = sinon.stub(this.pulsarSortable, 'actionsBadge');
            this.pulsarSortable.init();
            this.$rowOne.addClass('is-selected');
            this.$rowOne.find('.checkbox').first().prop('checked', true);
            this.$rowOne.click();
        });

        it('should add class "is-selected"', function () {
            expect(this.$rowOne.hasClass('is-selected')).to.be.false;
        });

        it('should toggle the row\'s checkbox', function () {
            expect(this.$rowOne.find('.checkbox').first().prop('checked')).to.be.false;
        });

        it('should update "Actions" dropdown badge', function () {
            expect(this.actionsBadgeStub).to.have.been.called;
        });
    });

    describe('When a row is already selected and another row is selected afterwords,', function () {
        beforeEach(function () {
            this.actionsBadgeStub = sinon.stub(this.pulsarSortable, 'actionsBadge');
            this.pulsarSortable.init();
            this.$rowOne.click();
            this.$rowTwo.click();
        });

        afterEach(function () {
            this.actionsBadgeStub.restore();
        });

        it('should update "Actions" dropdown badge', function () {
            expect(this.actionsBadgeStub).to.have.been.called;
        });

        it('should increase the number of selected items in the "Actions" dropdown badges', function () {
            expect($('.has-badges .dropdown__toggle .badge').text() !== "").to.be.true;
        });

        it('should have the word "items" in the Delete dadge', function () {
            expect($('.has-badges .dropdown__menu li:last-child a').text().indexOf("items") > 1).to.be.true;
        });
    });
});
<commit_msg>Add Two More Test Suits to Improve Test Coverage<commit_after>/*jshint multistr: true */

'use strict';

var $ = require('jquery'),
    PulsarSortableComponent = require('../../../js/PulsarSortableComponent');

describe('PulsarSortableComponent', function () {
    beforeEach(function () {

        this.$html = $('

').appendTo('html');
        this.$body = $('

').appendTo(this.$html);
        this.$markup = $('\

\

\
        <button data-toggle="dropdown" class="btn dropdown__toggle">\
            Actions \
            \
        </button>\

\

 New Filter
\

 Random Option
\

\

 Delete
\

\

\

\

\

\
                foo	\
                	\
                <input type="checkbox" class="form__control checkbox">	\

\

\
                foo	\
                	\
                <input type="checkbox" class="form__control checkbox">	\

\

\

\

\
').appendTo(this.$body);

        this.$table = this.$html.find('.table');
        this.$rowOne = this.$html.find('.qa-row-one');
        this.$rowTwo = this.$html.find('.qa-row-two');
        this.$moveUp = this.$html.find('[data-move="up"]');
        this.$moveDown = this.$html.find('[data-move="down"]');

        this.pulsarSortable = new PulsarSortableComponent(this.$html);
    });

    describe('The sortable table', function () {
        beforeEach(function () {
            this.pulsarSortable.init();
        });

        it('should have row one at index 0', function () {
            expect(this.$html.find('.qa-row-one').index()).to.equal(0);
        });

        it('should have row two at index 1', function () {
            expect(this.$html.find('.qa-row-two').index()).to.equal(1);
        });
    });

    describe('Clicking a move control in row one', function () {
        beforeEach(function () {
            this.pulsarSortable.init();
            this.$moveUp.click();
        });

        it('should hide the move links', function () {
            expect(this.$html.find('.qa-row-one [data-move="up"]').hasClass('hide')).to.be.true;
        });

        it('should add the success icon', function () {
            expect(this.$html.find('.qa-row-one [data-move="up"]').parent().find('.icon-ok-sign').length).to.equal(1);
        });

        it('should remove the success icon after a delay', function () {
            setTimeout(function (){
                expect(this.$html.find('.qa-row-one [data-move="up"]').parent().find('.js-sortable-moved').length).to.equal(0);
            }, 1000);
        });

        it('should show the move links after a delay', function () {
            setTimeout(function (){
                expect(this.$html.find('.qa-row-one [data-move="up"]').hasClass('hide')).to.be.false;
            }, 2250);
        });
    });

    describe('Clicking the move down control on row one', function () {
        beforeEach(function () {
            this.pulsarSortable.init();
            this.$rowOne.find('[data-move="down"]').click();
        });

        it('should move the row down one position', function () {
            expect(this.$html.find('.qa-row-one').index()).to.equal(1);
        });

        it('should move the other row up one position', function () {
            expect(this.$html.find('.qa-row-two').index()).to.equal(0);
        });
    });

    describe('Clicking the move up control on row one', function () {
        beforeEach(function () {
            this.pulsarSortable.init();
            this.$rowOne.find('[data-move="up"]').click();
        });

        it('should move the row up one position', function () {
            expect(this.$html.find('.qa-row-one').index()).to.equal(0);
        });

        it('should move the other row down one position', function () {
            expect(this.$html.find('.qa-row-two').index()).to.equal(1);
        });
    });

    describe('Selecting a table row', function () {
        beforeEach(function () {
            this.actionsBadgeStub = sinon.stub(this.pulsarSortable, 'actionsBadge');
            this.pulsarSortable.init();
            this.$rowOne.click();
        });

        afterEach(function () {
            this.actionsBadgeStub.restore();
        });

        it('should add class "is-selected"', function () {
            expect(this.$rowOne.hasClass('is-selected')).to.be.true;
        });

        it('should toggle the row\'s checkbox', function () {
            expect(this.$rowOne.find('.checkbox').first().prop('checked')).to.be.true;
        });

        it('should update "Actions" dropdown badge', function () {
            expect(this.actionsBadgeStub).to.have.been.called;
        });

        it('should add a badge to "Actions" dropdown', function () {
            expect($('.has-badges .dropdown__toggle .badge').is(':visible')).to.be.true;
        });

        it('should have the word "item" in the Delete dadge', function () {
            expect($('.has-badges .dropdown__menu li:last-child a').text().indexOf("item") > 1).to.be.true;
        });

        it('should display the number of selected items in the "Actions" dropdown Delete badges', function () {
            expect($('.item-wording').is(':visible')).to.be.true;
        });
    });

    describe('Deselecting a table row', function () {
        beforeEach(function () {
            this.actionsBadgeStub = sinon.stub(this.pulsarSortable, 'actionsBadge');
            this.pulsarSortable.init();
            this.$rowOne.addClass('is-selected');
            this.$rowOne.find('.checkbox').first().prop('checked', true);
            this.$rowOne.click();
        });

        it('should add class "is-selected"', function () {
            expect(this.$rowOne.hasClass('is-selected')).to.be.false;
        });

        it('should toggle the row\'s checkbox', function () {
            expect(this.$rowOne.find('.checkbox').first().prop('checked')).to.be.false;
        });

        it('should update "Actions" dropdown badge', function () {
            expect(this.actionsBadgeStub).to.have.been.called;
        });

        it('should decrease the number of selected items in the "Actions" dropdown badges', function () {
            expect(this.$html.find('.item-wording').is(':visible')).to.be.false;
        });
    });

    describe('When a row is already selected and another row is selected afterwords,', function () {
        beforeEach(function () {
            this.actionsBadgeStub = sinon.stub(this.pulsarSortable, 'actionsBadge');
            this.pulsarSortable.init();
            this.$rowOne.click();
            this.$rowTwo.click();
        });

        afterEach(function () {
            this.actionsBadgeStub.restore();
        });

        it('should update "Actions" dropdown badge', function () {
            expect(this.actionsBadgeStub).to.have.been.called;
        });

        it('should increase the number of selected items in the "Actions" dropdown badges', function () {
            expect($('.has-badges .dropdown__toggle .badge').text() !== "").to.be.true;
        });

        it('should have the word "items" in the Delete dadge', function () {
            expect($('.has-badges .dropdown__menu li:last-child a').text().indexOf("items") > 1).to.be.true;
        });
    });
});
<|endoftext|>


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

var fs = require('fs');
var path = require('path');
var glob = require('glob');

var args = require('optimist').argv;

var header = args.h || args.header;

var componentsDir = path.join('src', 'components');

var componentIndex = path.join('src', 'component-index.js');

var packageJson = JSON.parse(fs.readFileSync('./package.json'));

var strm = fs.createWriteStream(componentIndex);

if (header) {
   strm.write(fs.readFileSync(header));
   strm.write('\n');
}

strm.write("/*\n");
strm.write(" * THIS FILE IS AUTO-GENERATED\n");
strm.write(" * You can edit it you like, but your changes will be overwritten,\n");
strm.write(" * so you'd just be trying to swim upstream like a salmon.\n");
strm.write(" * You are not a salmon.\n");
strm.write(" */\n\n");

if (packageJson['matrix-react-parent']) {
    strm.write("module.exports.components = require('"+packageJson['matrix-react-parent']+"/lib/component-index').components;\n\n");
} else {
    strm.write("module.exports.components = {};\n");
}

var files = glob.sync('**/*.js', {cwd: componentsDir});
for (var i = 0; i < files.length; ++i) {
    var file = files[i].replace('.js', '');

    var moduleName = (file.replace(/\//g, '.'));

    strm.write("module.exports.components['"+moduleName+"'] = require('./components/"+file+"');");
    strm.write('\n');
    strm.uncork();
}

// Temporary Vector transition
var vectorViewsPath = path.join('src', 'skins', 'vector', 'views');
if (fs.existsSync(vectorViewsPath)) {
    strm.write('\n');
    strm.write('// Old, unported Vector views:\n');
    var files = glob.sync('**/*.js', {cwd: vectorViewsPath});
    for (var i = 0; i < files.length; ++i) {
        var file = files[i].replace('.js', '');

        var moduleName = (file.replace(/\//g, '.'));

        strm.write("module.exports.components['"+moduleName+"'] = require('./skins/vector/views/"+file+"');");
        strm.write('\n');
        strm.uncork();
    }
}

strm.end();

<commit_msg>Remove temporary vector stuff as the sister PR makes it obsolete.<commit_after>#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var glob = require('glob');

var args = require('optimist').argv;

var header = args.h || args.header;

var componentsDir = path.join('src', 'components');

var componentIndex = path.join('src', 'component-index.js');

var packageJson = JSON.parse(fs.readFileSync('./package.json'));

var strm = fs.createWriteStream(componentIndex);

if (header) {
   strm.write(fs.readFileSync(header));
   strm.write('\n');
}

strm.write("/*\n");
strm.write(" * THIS FILE IS AUTO-GENERATED\n");
strm.write(" * You can edit it you like, but your changes will be overwritten,\n");
strm.write(" * so you'd just be trying to swim upstream like a salmon.\n");
strm.write(" * You are not a salmon.\n");
strm.write(" */\n\n");

if (packageJson['matrix-react-parent']) {
    strm.write("module.exports.components = require('"+packageJson['matrix-react-parent']+"/lib/component-index').components;\n\n");
} else {
    strm.write("module.exports.components = {};\n");
}

var files = glob.sync('**/*.js', {cwd: componentsDir});
for (var i = 0; i < files.length; ++i) {
    var file = files[i].replace('.js', '');

    var moduleName = (file.replace(/\//g, '.'));

    strm.write("module.exports.components['"+moduleName+"'] = require('./components/"+file+"');");
    strm.write('\n');
    strm.uncork();
}

strm.end();
<|endoftext|>